From 0e915c13667ff0e20922d6b916c6e5614614f540 Mon Sep 17 00:00:00 2001 From: jos Date: Thu, 28 May 2015 14:43:30 +0200 Subject: [PATCH 01/11] Removed a broken link --- docs/network/index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/network/index.html b/docs/network/index.html index 0036841a..48f6468e 100644 --- a/docs/network/index.html +++ b/docs/network/index.html @@ -891,7 +891,7 @@ var locales = { - Returns: String + Returns: String Returns a edgeId or undefined. The DOM positions are expected to be in pixels from the top left corner of the canvas.. @@ -1203,7 +1203,7 @@ var options = { oncontext same as click. Fired when the user click on the canvas with the right mouse button. The right mouse button does not - select by default. You can use getNodeAt to select the node if you + select by default. You can use the method getNodeAt to select the node if you want. From 37f93c810b421b2e499c9446f8968e06ced4a827 Mon Sep 17 00:00:00 2001 From: jos Date: Thu, 28 May 2015 15:10:20 +0200 Subject: [PATCH 02/11] Disable `yAxisOrientation` in configurator. (isn't stable) --- lib/timeline/optionsGraph2d.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/timeline/optionsGraph2d.js b/lib/timeline/optionsGraph2d.js index 5ff1eb42..2f73fc99 100644 --- a/lib/timeline/optionsGraph2d.js +++ b/lib/timeline/optionsGraph2d.js @@ -159,7 +159,7 @@ let allOptions = { let configureOptions = { global: { - yAxisOrientation: ['left','right'], + //yAxisOrientation: ['left','right'], // TDOO: enable as soon as Grahp2d doesn't crash when changing this on the fly sort: true, sampling: true, stack:false, From 07c79704f03f16dcd719cb5c14fcb18f51385ea9 Mon Sep 17 00:00:00 2001 From: jos Date: Thu, 28 May 2015 15:32:03 +0200 Subject: [PATCH 03/11] Renamed an example --- .../network/nodeStyles/{HTML_in_Nodes.html => HTMLInNodes.html} | 0 test/timeline.html | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename examples/network/nodeStyles/{HTML_in_Nodes.html => HTMLInNodes.html} (100%) diff --git a/examples/network/nodeStyles/HTML_in_Nodes.html b/examples/network/nodeStyles/HTMLInNodes.html similarity index 100% rename from examples/network/nodeStyles/HTML_in_Nodes.html rename to examples/network/nodeStyles/HTMLInNodes.html diff --git a/test/timeline.html b/test/timeline.html index 7923cb33..ed2e5dbb 100644 --- a/test/timeline.html +++ b/test/timeline.html @@ -136,7 +136,7 @@ end: now.clone().add(1, 'days').add(1, 'minutes').toDate(), title: 'hello title!' }, - {_id: 5, content: 'item 5', start: now.clone().add(9, 'days').toDate(), type:'point', title: 'hello title!'}, + {_id: 5, content: 'item 5', start: now.clone().add(9, 'days').toDate(), type:'point', title: 'hello title!', className: 'special'}, {_id: 6, content: 'item 6', start: now.clone().add(11, 'days').toDate()} ]); From a1b987be77927de8161e806151df524e8a53ceba Mon Sep 17 00:00:00 2001 From: jos Date: Thu, 28 May 2015 15:37:33 +0200 Subject: [PATCH 04/11] Replaced underscores in example names with camel case --- dist/vis.js | 66220 ++++++++-------- ...xis_titles.html => 16_bothAxisTitles.html} | 0 .../{basic_usage.html => basicUsage.html} | 0 ...rom_gephi.html => importingFromGephi.html} | 0 ...scaling_custom.html => scalingCustom.html} | 0 ...odes_edges.html => scalingNodesEdges.html} | 0 ...bels.html => scalingNodesEdgesLabels.html} | 0 ...les_miserables.html => lesMiserables.html} | 0 ...light.html => neighbourhoodHighlight.html} | 0 examples/network/index.html | 57 - ...bel_alignment.html => labelAlignment.html} | 0 ...l_background.html => labelBackground.html} | 0 ...r_and_size.html => labelColorAndSize.html} | 0 .../{label_stroke.html => labelStroke.html} | 0 ...multiline_text.html => multilineText.html} | 0 ...al_layout.html => hierarchicalLayout.html} | 0 ...ds.html => hierarchicalLayoutMethods.html} | 0 ...tml => hierarchicalLayoutUserdefined.html} | 0 ...rcular_images.html => circularImages.html} | 0 19 files changed, 33110 insertions(+), 33167 deletions(-) rename examples/graph2d/{16_bothAxis_titles.html => 16_bothAxisTitles.html} (100%) rename examples/network/{basic_usage.html => basicUsage.html} (100%) rename examples/network/data/{importing_from_gephi.html => importingFromGephi.html} (100%) rename examples/network/data/{scaling_custom.html => scalingCustom.html} (100%) rename examples/network/data/{scaling_nodes_edges.html => scalingNodesEdges.html} (100%) rename examples/network/data/{scaling_nodes_edges_labels.html => scalingNodesEdgesLabels.html} (100%) rename examples/network/exampleApplications/{les_miserables.html => lesMiserables.html} (100%) rename examples/network/exampleApplications/{neighbourhood_highlight.html => neighbourhoodHighlight.html} (100%) delete mode 100644 examples/network/index.html rename examples/network/labels/{label_alignment.html => labelAlignment.html} (100%) rename examples/network/labels/{label_background.html => labelBackground.html} (100%) rename examples/network/labels/{label_color_and_size.html => labelColorAndSize.html} (100%) rename examples/network/labels/{label_stroke.html => labelStroke.html} (100%) rename examples/network/labels/{multiline_text.html => multilineText.html} (100%) rename examples/network/layout/{hierarchical_layout.html => hierarchicalLayout.html} (100%) rename examples/network/layout/{hierarchical_layout_methods.html => hierarchicalLayoutMethods.html} (100%) rename examples/network/layout/{hierarchical_layout_userdefined.html => hierarchicalLayoutUserdefined.html} (100%) rename examples/network/nodeStyles/{circular_images.html => circularImages.html} (100%) diff --git a/dist/vis.js b/dist/vis.js index eb64893b..705e0546 100644 --- a/dist/vis.js +++ b/dist/vis.js @@ -85,63 +85,63 @@ return /******/ (function(modules) { // webpackBootstrap 'use strict'; exports.util = __webpack_require__(2); - exports.DOMutil = __webpack_require__(21); + exports.DOMutil = __webpack_require__(3); // data - exports.DataSet = __webpack_require__(22); - exports.DataView = __webpack_require__(24); - exports.Queue = __webpack_require__(23); + exports.DataSet = __webpack_require__(4); + exports.DataView = __webpack_require__(5); + exports.Queue = __webpack_require__(6); // Graph3d - exports.Graph3d = __webpack_require__(25); + exports.Graph3d = __webpack_require__(7); exports.graph3d = { - Camera: __webpack_require__(29), - Filter: __webpack_require__(30), - Point2d: __webpack_require__(26), - Point3d: __webpack_require__(28), - Slider: __webpack_require__(31), - StepNumber: __webpack_require__(32) + Camera: __webpack_require__(8), + Filter: __webpack_require__(9), + Point2d: __webpack_require__(10), + Point3d: __webpack_require__(11), + Slider: __webpack_require__(12), + StepNumber: __webpack_require__(13) }; // Timeline - exports.Timeline = __webpack_require__(33); - exports.Graph2d = __webpack_require__(56); + exports.Timeline = __webpack_require__(14); + exports.Graph2d = __webpack_require__(15); exports.timeline = { - DateUtil: __webpack_require__(39), - DataStep: __webpack_require__(59), - Range: __webpack_require__(37), - stack: __webpack_require__(42), - TimeStep: __webpack_require__(44), + DateUtil: __webpack_require__(16), + DataStep: __webpack_require__(17), + Range: __webpack_require__(18), + stack: __webpack_require__(19), + TimeStep: __webpack_require__(20), components: { items: { - Item: __webpack_require__(11), - BackgroundItem: __webpack_require__(47), - BoxItem: __webpack_require__(5), - PointItem: __webpack_require__(46), - RangeItem: __webpack_require__(43) + Item: __webpack_require__(21), + BackgroundItem: __webpack_require__(22), + BoxItem: __webpack_require__(57), + PointItem: __webpack_require__(23), + RangeItem: __webpack_require__(24) }, - Component: __webpack_require__(35), - CurrentTime: __webpack_require__(34), - CustomTime: __webpack_require__(51), - DataAxis: __webpack_require__(58), - GraphGroup: __webpack_require__(60), - Group: __webpack_require__(41), - BackgroundGroup: __webpack_require__(45), - ItemSet: __webpack_require__(10), - Legend: __webpack_require__(64), - LineGraph: __webpack_require__(57), - TimeAxis: __webpack_require__(48) + Component: __webpack_require__(25), + CurrentTime: __webpack_require__(26), + CustomTime: __webpack_require__(27), + DataAxis: __webpack_require__(28), + GraphGroup: __webpack_require__(29), + Group: __webpack_require__(30), + BackgroundGroup: __webpack_require__(31), + ItemSet: __webpack_require__(32), + Legend: __webpack_require__(33), + LineGraph: __webpack_require__(34), + TimeAxis: __webpack_require__(35) } }; // Network - exports.Network = __webpack_require__(66); + exports.Network = __webpack_require__(36); exports.network = { - Images: __webpack_require__(112), - dotparser: __webpack_require__(110), - gephiParser: __webpack_require__(111) + Images: __webpack_require__(37), + dotparser: __webpack_require__(38), + gephiParser: __webpack_require__(39) }; exports.network.convertDot = function (input) { return exports.network.dotparser.DOTToGraph(input); @@ -156,565 +156,1175 @@ return /******/ (function(modules) { // webpackBootstrap }; // bundled external libraries - exports.moment = __webpack_require__(17); - exports.hammer = __webpack_require__(13); // TODO: deprecate exports.hammer some day - exports.Hammer = __webpack_require__(13); + exports.moment = __webpack_require__(40); + exports.hammer = __webpack_require__(41); // TODO: deprecate exports.hammer some day + exports.Hammer = __webpack_require__(41); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { - function webpackContext(req) { - throw new Error("Cannot find module '" + req + "'."); - } - webpackContext.keys = function() { return []; }; - webpackContext.resolve = webpackContext; - module.exports = webpackContext; - webpackContext.id = 1; + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); -/***/ }, -/* 2 */ -/***/ function(module, exports, __webpack_require__) { + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // utility functions + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - // first check if moment.js is already loaded in the browser window, if so, - // use this instance. Else, load via commonjs. + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - 'use strict'; + var _componentsPhysicsBarnesHutSolver = __webpack_require__(77); - var moment = __webpack_require__(17); - var uuid = __webpack_require__(20); + var _componentsPhysicsBarnesHutSolver2 = _interopRequireDefault(_componentsPhysicsBarnesHutSolver); - /** - * Test whether given object is a number - * @param {*} object - * @return {Boolean} isNumber - */ - exports.isNumber = function (object) { - return object instanceof Number || typeof object == 'number'; - }; + var _componentsPhysicsRepulsionSolver = __webpack_require__(78); - /** - * Remove everything in the DOM object - * @param DOMobject - */ - exports.recursiveDOMDelete = function (DOMobject) { - if (DOMobject) { - while (DOMobject.hasChildNodes() === true) { - exports.recursiveDOMDelete(DOMobject.firstChild); - DOMobject.removeChild(DOMobject.firstChild); - } - } - }; + var _componentsPhysicsRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsRepulsionSolver); - /** - * 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 min - * @param max - * @param total - * @param 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); - } - }; + var _componentsPhysicsHierarchicalRepulsionSolver = __webpack_require__(79); - /** - * Test whether given object is a string - * @param {*} object - * @return {Boolean} isString - */ - exports.isString = function (object) { - return object instanceof String || typeof object == 'string'; - }; + var _componentsPhysicsHierarchicalRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsHierarchicalRepulsionSolver); - /** - * 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; - } - } + var _componentsPhysicsSpringSolver = __webpack_require__(80); - return false; - }; + var _componentsPhysicsSpringSolver2 = _interopRequireDefault(_componentsPhysicsSpringSolver); - /** - * Create a semi UUID - * source: http://stackoverflow.com/a/105074/1262753 - * @return {String} uuid - */ - exports.randomUUID = function () { - return uuid.v4(); - }; + var _componentsPhysicsHierarchicalSpringSolver = __webpack_require__(81); - /** - * assign all keys of an object that are not nested objects to a certain value (used for color objects). - * @param obj - * @param value - */ - exports.assignAllKeys = function (obj, value) { - for (var prop in obj) { - if (obj.hasOwnProperty(prop)) { - if (typeof obj[prop] !== 'object') { - obj[prop] = value; - } - } - } - }; + var _componentsPhysicsHierarchicalSpringSolver2 = _interopRequireDefault(_componentsPhysicsHierarchicalSpringSolver); - /** - * Fill an object with a possibly partially defined other object. Only copies values if the a object has an object requiring values. - * That means an object is not created on a property if only the b object has it. - * @param obj - * @param value - */ - exports.fillIfDefined = function (a, b) { - var allowDeletion = arguments[2] === undefined ? false : arguments[2]; + var _componentsPhysicsCentralGravitySolver = __webpack_require__(82); - for (var prop in a) { - if (b[prop] !== undefined) { - if (typeof b[prop] !== 'object') { - if ((b[prop] === undefined || b[prop] === null) && a[prop] !== undefined && allowDeletion === true) { - delete a[prop]; - } else { - a[prop] = b[prop]; - } - } else { - if (typeof a[prop] === 'object') { - exports.fillIfDefined(a[prop], b[prop], allowDeletion); - } - } - } - } - }; + var _componentsPhysicsCentralGravitySolver2 = _interopRequireDefault(_componentsPhysicsCentralGravitySolver); - /** - * 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.protoExtend = function (a, b) { - for (var i = 1; i < arguments.length; i++) { - var other = arguments[i]; - for (var prop in other) { - a[prop] = other[prop]; - } - } - return a; - }; + var _componentsPhysicsFA2BasedRepulsionSolver = __webpack_require__(83); - /** - * 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) { - 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; - }; + var _componentsPhysicsFA2BasedRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsFA2BasedRepulsionSolver); - /** - * 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) { - if (!Array.isArray(props)) { - throw new Error('Array with property names expected as first argument'); - } + var _componentsPhysicsFA2BasedCentralGravitySolver = __webpack_require__(84); - for (var i = 2; i < arguments.length; i++) { - var other = arguments[i]; + var _componentsPhysicsFA2BasedCentralGravitySolver2 = _interopRequireDefault(_componentsPhysicsFA2BasedCentralGravitySolver); - for (var p = 0; p < props.length; p++) { - var prop = props[p]; - if (other.hasOwnProperty(prop)) { - a[prop] = other[prop]; - } - } - } - return a; - }; + var util = __webpack_require__(2); - /** - * 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.selectiveDeepExtend = function (props, a, b) { - var allowDeletion = arguments[3] === undefined ? false : arguments[3]; + var PhysicsEngine = (function () { + function PhysicsEngine(body) { + _classCallCheck(this, PhysicsEngine); - // TODO: add support for Arrays to deepExtend - if (Array.isArray(b)) { - throw new TypeError('Arrays are not supported by deepExtend'); - } - 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.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 { - if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) { - delete a[prop]; - } else { - a[prop] = b[prop]; - } - } - } else if (Array.isArray(b[prop])) { - throw new TypeError('Arrays are not supported by deepExtend'); - } else { - a[prop] = b[prop]; - } - } - } - } - return a; - }; + this.body = body; + this.physicsBody = { physicsNodeIndices: [], physicsEdgeIndices: [], forces: {}, velocities: {} }; - /** - * 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.selectiveNotDeepExtend = function (props, a, b) { - var allowDeletion = arguments[3] === undefined ? false : arguments[3]; + this.physicsEnabled = true; + this.simulationInterval = 1000 / 60; + this.requiresTimeout = true; + this.previousStates = {}; + this.freezeCache = {}; + this.renderTimer = undefined; - // TODO: add support for Arrays to deepExtend - if (Array.isArray(b)) { - throw new TypeError('Arrays are not supported by deepExtend'); + this.stabilized = false; + this.startedStabilization = false; + this.stabilizationIterations = 0; + this.ready = false; // will be set to true if the stabilize + + // default options + this.options = {}; + this.defaultOptions = { + barnesHut: { + theta: 0.5, + gravitationalConstant: -2000, + centralGravity: 0.3, + springLength: 95, + springConstant: 0.04, + damping: 0.09, + avoidOverlap: 0 + }, + forceAtlas2Based: { + theta: 0.5, + gravitationalConstant: -50, + centralGravity: 0.01, + springConstant: 0.08, + springLength: 100, + damping: 0.4, + avoidOverlap: 0 + }, + repulsion: { + centralGravity: 0.2, + springLength: 200, + springConstant: 0.05, + nodeDistance: 100, + damping: 0.09, + avoidOverlap: 0 + }, + hierarchicalRepulsion: { + centralGravity: 0, + springLength: 100, + springConstant: 0.01, + nodeDistance: 120, + damping: 0.09 + }, + maxVelocity: 50, + minVelocity: 0.1, // px/s + solver: 'barnesHut', + stabilization: { + enabled: true, + iterations: 1000, // maximum number of iteration to stabilize + updateInterval: 50, + onlyDynamicEdges: false, + fit: true + }, + timestep: 0.5 + }; + util.extend(this.options, this.defaultOptions); + + this.bindEventListeners(); } - for (var prop in b) { - if (b.hasOwnProperty(prop)) { - if (props.indexOf(prop) == -1) { - if (b[prop] && b[prop].constructor === Object) { - if (a[prop] === undefined) { - a[prop] = {}; - } - if (a[prop].constructor === Object) { - exports.deepExtend(a[prop], b[prop]); - } else { - if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) { - delete a[prop]; - } else { - a[prop] = b[prop]; - } - } - } else if (Array.isArray(b[prop])) { - throw new TypeError('Arrays are not supported by deepExtend'); + + _createClass(PhysicsEngine, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this = this; + + this.body.emitter.on('initPhysics', function () { + _this.initPhysics(); + }); + this.body.emitter.on('resetPhysics', function () { + _this.stopSimulation();_this.ready = false; + }); + this.body.emitter.on('disablePhysics', function () { + _this.physicsEnabled = false;_this.stopSimulation(); + }); + this.body.emitter.on('restorePhysics', function () { + _this.setOptions(_this.options); + if (_this.ready === true) { + _this.startSimulation(); + } + }); + this.body.emitter.on('startSimulation', function () { + if (_this.ready === true) { + _this.startSimulation(); + } + }); + this.body.emitter.on('stopSimulation', function () { + _this.stopSimulation(); + }); + this.body.emitter.on('destroy', function () { + _this.stopSimulation(false); + _this.body.emitter.off(); + }); + } + }, { + key: 'setOptions', + value: function setOptions(options) { + if (options !== undefined) { + if (options === false) { + this.physicsEnabled = false; + this.stopSimulation(); } else { - a[prop] = b[prop]; + this.physicsEnabled = true; + util.selectiveNotDeepExtend(['stabilization'], this.options, options); + util.mergeOptions(this.options, options, 'stabilization'); } } + this.init(); } - } - return a; - }; + }, { + key: 'init', + value: function init() { + var options; + if (this.options.solver === 'forceAtlas2Based') { + options = this.options.forceAtlas2Based; + this.nodesSolver = new _componentsPhysicsFA2BasedRepulsionSolver2['default'](this.body, this.physicsBody, options); + this.edgesSolver = new _componentsPhysicsSpringSolver2['default'](this.body, this.physicsBody, options); + this.gravitySolver = new _componentsPhysicsFA2BasedCentralGravitySolver2['default'](this.body, this.physicsBody, options); + } else if (this.options.solver === 'repulsion') { + options = this.options.repulsion; + this.nodesSolver = new _componentsPhysicsRepulsionSolver2['default'](this.body, this.physicsBody, options); + this.edgesSolver = new _componentsPhysicsSpringSolver2['default'](this.body, this.physicsBody, options); + this.gravitySolver = new _componentsPhysicsCentralGravitySolver2['default'](this.body, this.physicsBody, options); + } else if (this.options.solver === 'hierarchicalRepulsion') { + options = this.options.hierarchicalRepulsion; + this.nodesSolver = new _componentsPhysicsHierarchicalRepulsionSolver2['default'](this.body, this.physicsBody, options); + this.edgesSolver = new _componentsPhysicsHierarchicalSpringSolver2['default'](this.body, this.physicsBody, options); + this.gravitySolver = new _componentsPhysicsCentralGravitySolver2['default'](this.body, this.physicsBody, options); + } else { + // barnesHut + options = this.options.barnesHut; + this.nodesSolver = new _componentsPhysicsBarnesHutSolver2['default'](this.body, this.physicsBody, options); + this.edgesSolver = new _componentsPhysicsSpringSolver2['default'](this.body, this.physicsBody, options); + this.gravitySolver = new _componentsPhysicsCentralGravitySolver2['default'](this.body, this.physicsBody, options); + } - /** - * Deep extend an object a with the properties of object b - * @param {Object} a - * @param {Object} b - * @param [Boolean] protoExtend --> optional parameter. 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] global --> optional parameter. If true, the values of fields that are null will not deleted - * @returns {Object} - */ - exports.deepExtend = function (a, b, protoExtend, allowDeletion) { - 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); + this.modelOptions = options; + } + }, { + key: 'initPhysics', + value: function initPhysics() { + if (this.physicsEnabled === true) { + if (this.options.stabilization.enabled === true) { + this.stabilize(); } else { - if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) { - delete a[prop]; - } else { - a[prop] = b[prop]; - } - } - } else if (Array.isArray(b[prop])) { - a[prop] = []; - for (var i = 0; i < b[prop].length; i++) { - a[prop].push(b[prop][i]); + this.stabilized = false; + this.ready = true; + this.body.emitter.emit('fit', {}, true); + this.startSimulation(); } } else { - a[prop] = b[prop]; + this.ready = true; + this.body.emitter.emit('fit'); } } - } - return a; - }; + }, { + key: 'startSimulation', - /** - * 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; + /** + * Start the simulation + */ + value: function startSimulation() { + if (this.physicsEnabled === true) { + this.stabilized = false; - for (var i = 0, len = a.length; i < len; i++) { - if (a[i] != b[i]) return false; - } + // this sets the width of all nodes initially which could be required for the avoidOverlap + this.body.emitter.emit('_resizeNodes'); - return true; - }; + if (this.viewFunction === undefined) { + this.viewFunction = this.simulationStep.bind(this); + this.body.emitter.on('initRedraw', this.viewFunction); + this.body.emitter.emit('_startRendering'); + } + } else { + this.body.emitter.emit('_redraw'); + } + } + }, { + key: 'stopSimulation', - /** - * 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; + /** + * Stop the simulation, force stabilization. + */ + value: function stopSimulation() { + var emit = arguments[0] === undefined ? true : arguments[0]; - 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'); - } + this.stabilized = true; + if (emit === true) { + this._emitStabilized(); + } + if (this.viewFunction !== undefined) { + this.body.emitter.off('initRedraw', this.viewFunction); + this.viewFunction = undefined; + if (emit === true) { + this.body.emitter.emit('_stopRendering'); + } + } + } + }, { + key: 'simulationStep', - //noinspection FallthroughInSwitchStatementJS - switch (type) { - case 'boolean': - case 'Boolean': - return Boolean(object); + /** + * The viewFunction inserts this step into each renderloop. It calls the physics tick and handles the cleanup at stabilized. + * + */ + value: function simulationStep() { + // check if the physics have settled + var startTime = Date.now(); + this.physicsTick(); + var physicsTime = Date.now() - startTime; - case 'number': - case 'Number': - return Number(object.valueOf()); + // run double speed if it is a little graph + if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) { + this.physicsTick(); - case 'string': - case 'String': - return String(object); + // this makes sure there is no jitter. The decision is taken once to run it at double speed. + this.runDoubleSpeed = true; + } - case 'Date': - if (exports.isNumber(object)) { - return new Date(object); + if (this.stabilized === true) { + if (this.stabilizationIterations > 1) { + // trigger the 'stabilized' event. + // The event is triggered on the next tick, to prevent the case that + // it is fired while initializing the Network, in which case you would not + // be able to catch it + this.startedStabilization = false; + //this._emitStabilized(); + } + this.stopSimulation(); } - if (object instanceof Date) { - return new Date(object.valueOf()); - } else if (moment.isMoment(object)) { - return new Date(object.valueOf()); + } + }, { + key: '_emitStabilized', + value: function _emitStabilized() { + var _this2 = this; + + if (this.stabilizationIterations > 1) { + setTimeout(function () { + _this2.body.emitter.emit('stabilized', { iterations: _this2.stabilizationIterations }); + _this2.stabilizationIterations = 0; + }, 0); } - if (exports.isString(object)) { - match = ASPDateRegex.exec(object); - if (match) { - // object is an ASP date - return new Date(Number(match[1])); // parse number + } + }, { + key: 'physicsTick', + + /** + * A single simulation step (or 'tick') in the physics simulation + * + * @private + */ + value: function physicsTick() { + if (this.stabilized === false) { + this.calculateForces(); + this.stabilized = this.moveNodes(); + + // determine if the network has stabilzied + if (this.stabilized === true) { + this.revert(); } else { - return moment(object).toDate(); // parse string + // this is here to ensure that there is no start event when the network is already stable. + if (this.startedStabilization === false) { + this.body.emitter.emit('startStabilizing'); + this.startedStabilization = true; + } } - } else { - throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type Date'); + + this.stabilizationIterations++; } + } + }, { + key: 'updatePhysicsData', - case 'Moment': - if (exports.isNumber(object)) { - return moment(object); + /** + * Nodes and edges can have the physics toggles on or off. A collection of indices is created here so we can skip the check all the time. + * + * @private + */ + value: function updatePhysicsData() { + this.physicsBody.forces = {}; + this.physicsBody.physicsNodeIndices = []; + this.physicsBody.physicsEdgeIndices = []; + var nodes = this.body.nodes; + var edges = this.body.edges; + + // get node indices for physics + for (var nodeId in nodes) { + if (nodes.hasOwnProperty(nodeId)) { + if (nodes[nodeId].options.physics === true) { + this.physicsBody.physicsNodeIndices.push(nodeId); + } + } } - if (object instanceof Date) { - return moment(object.valueOf()); - } else if (moment.isMoment(object)) { - return moment(object); + + // get edge indices for physics + for (var edgeId in edges) { + if (edges.hasOwnProperty(edgeId)) { + if (edges[edgeId].options.physics === true) { + this.physicsBody.physicsEdgeIndices.push(edgeId); + } + } } - 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 + + // get the velocity and the forces vector + for (var i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) { + var nodeId = this.physicsBody.physicsNodeIndices[i]; + this.physicsBody.forces[nodeId] = { x: 0, y: 0 }; + + // forces can be reset because they are recalculated. Velocities have to persist. + if (this.physicsBody.velocities[nodeId] === undefined) { + this.physicsBody.velocities[nodeId] = { x: 0, y: 0 }; } - } 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 + // clean deleted nodes from the velocity vector + for (var nodeId in this.physicsBody.velocities) { + if (nodes[nodeId] === undefined) { + delete this.physicsBody.velocities[nodeId]; + } + } + } + }, { + key: 'revert', + + /** + * Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized. + */ + value: function revert() { + var nodeIds = Object.keys(this.previousStates); + var nodes = this.body.nodes; + var velocities = this.physicsBody.velocities; + + for (var i = 0; i < nodeIds.length; i++) { + var nodeId = nodeIds[i]; + if (nodes[nodeId] !== undefined) { + if (nodes[nodeId].options.physics === true) { + velocities[nodeId].x = this.previousStates[nodeId].vx; + velocities[nodeId].y = this.previousStates[nodeId].vy; + nodes[nodeId].x = this.previousStates[nodeId].x; + nodes[nodeId].y = this.previousStates[nodeId].y; + } } else { - return new Date(object).toISOString(); // parse string + delete this.previousStates[nodeId]; } - } else { - throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type ISODate'); } + } + }, { + key: 'moveNodes', - 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 + /** + * move the nodes one timestap and check if they are stabilized + * @returns {boolean} + */ + value: function moveNodes() { + var nodesPresent = false; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var maxVelocity = this.options.maxVelocity ? this.options.maxVelocity : 1000000000; + var stabilized = true; + var vminCorrected = this.options.minVelocity / Math.max(this.body.view.scale, 0.05); + + for (var i = 0; i < nodeIndices.length; i++) { + var nodeId = nodeIndices[i]; + var nodeVelocity = this._performStep(nodeId, maxVelocity); + // stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized + stabilized = nodeVelocity < vminCorrected && stabilized === true; + nodesPresent = true; + } + + if (nodesPresent === true) { + if (vminCorrected > 0.5 * this.options.maxVelocity) { + return false; } else { - value = new Date(object).valueOf(); // parse string + return stabilized; } - return '/Date(' + value + ')/'; - } else { - throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type ASPDate'); } + return true; + } + }, { + key: '_performStep', - default: - throw new Error('Unknown type "' + type + '"'); - } - }; + /** + * Perform the actual step + * + * @param nodeId + * @param maxVelocity + * @returns {number} + * @private + */ + value: function _performStep(nodeId, maxVelocity) { + var node = this.body.nodes[nodeId]; + var timestep = this.options.timestep; + var forces = this.physicsBody.forces; + var velocities = this.physicsBody.velocities; - // parse ASP.Net Date pattern, - // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/' - // code from http://momentjs.com/ - var ASPDateRegex = /^\/?Date\((\-?\d+)/i; + // store the state so we can revert + this.previousStates[nodeId] = { x: node.x, y: node.y, vx: velocities[nodeId].x, vy: velocities[nodeId].y }; - /** - * 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; + if (node.options.fixed.x === false) { + var dx = this.modelOptions.damping * velocities[nodeId].x; // damping force + var ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration + velocities[nodeId].x += ax * timestep; // velocity + velocities[nodeId].x = Math.abs(velocities[nodeId].x) > maxVelocity ? velocities[nodeId].x > 0 ? maxVelocity : -maxVelocity : velocities[nodeId].x; + node.x += velocities[nodeId].x * timestep; // position + } else { + forces[nodeId].x = 0; + velocities[nodeId].x = 0; + } - if (type == 'object') { - if (object === null) { - return 'null'; + if (node.options.fixed.y === false) { + var dy = this.modelOptions.damping * velocities[nodeId].y; // damping force + var ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration + velocities[nodeId].y += ay * timestep; // velocity + velocities[nodeId].y = Math.abs(velocities[nodeId].y) > maxVelocity ? velocities[nodeId].y > 0 ? maxVelocity : -maxVelocity : velocities[nodeId].y; + node.y += velocities[nodeId].y * timestep; // position + } else { + forces[nodeId].y = 0; + velocities[nodeId].y = 0; + } + + var totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x, 2) + Math.pow(velocities[nodeId].y, 2)); + return totalVelocity; } - if (object instanceof Boolean) { - return 'Boolean'; + }, { + key: 'calculateForces', + + /** + * calculate the forces for one physics iteration. + */ + value: function calculateForces() { + this.gravitySolver.solve(); + this.nodesSolver.solve(); + this.edgesSolver.solve(); } - if (object instanceof Number) { - return 'Number'; + }, { + key: '_freezeNodes', + + /** + * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization + * because only the supportnodes for the smoothCurves have to settle. + * + * @private + */ + value: function _freezeNodes() { + var nodes = this.body.nodes; + for (var id in nodes) { + if (nodes.hasOwnProperty(id)) { + if (nodes[id].x && nodes[id].y) { + this.freezeCache[id] = { x: nodes[id].options.fixed.x, y: nodes[id].options.fixed.y }; + nodes[id].options.fixed.x = true; + nodes[id].options.fixed.y = true; + } + } + } } - if (object instanceof String) { - return 'String'; + }, { + key: '_restoreFrozenNodes', + + /** + * Unfreezes the nodes that have been frozen by _freezeDefinedNodes. + * + * @private + */ + value: function _restoreFrozenNodes() { + var nodes = this.body.nodes; + for (var id in nodes) { + if (nodes.hasOwnProperty(id)) { + if (this.freezeCache[id] !== undefined) { + nodes[id].options.fixed.x = this.freezeCache[id].x; + nodes[id].options.fixed.y = this.freezeCache[id].y; + } + } + } + this.freezeCache = {}; } - if (Array.isArray(object)) { - return 'Array'; + }, { + key: 'stabilize', + + /** + * Find a stable position for all nodes + * @private + */ + value: function stabilize() { + var _this3 = this; + + var iterations = arguments[0] === undefined ? this.options.stabilization.iterations : arguments[0]; + + if (typeof iterations !== 'number') { + console.log('The stabilize method needs a numeric amount of iterations. Switching to default: ', this.options.stabilization.iterations); + iterations = this.options.stabilization.iterations; + } + + // this sets the width of all nodes initially which could be required for the avoidOverlap + this.body.emitter.emit('_resizeNodes'); + + // stop the render loop + this.stopSimulation(); + + // set stabilze to false + this.stabilized = false; + + // block redraw requests + this.body.emitter.emit('_blockRedrawRequests'); + this.targetIterations = iterations; + + // start the stabilization + if (this.options.stabilization.onlyDynamicEdges === true) { + this._freezeNodes(); + } + this.stabilizationIterations = 0; + + setTimeout(function () { + return _this3._stabilizationBatch(); + }, 0); } - if (object instanceof Date) { - return 'Date'; + }, { + key: '_stabilizationBatch', + value: function _stabilizationBatch() { + var count = 0; + while (this.stabilized === false && count < this.options.stabilization.updateInterval && this.stabilizationIterations < this.targetIterations) { + this.physicsTick(); + this.stabilizationIterations++; + count++; + } + + if (this.stabilized === false && this.stabilizationIterations < this.targetIterations) { + this.body.emitter.emit('stabilizationProgress', { iterations: this.stabilizationIterations, total: this.targetIterations }); + setTimeout(this._stabilizationBatch.bind(this), 0); + } else { + this._finalizeStabilization(); + } } - 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'; - } + }, { + key: '_finalizeStabilization', + value: function _finalizeStabilization() { + this.body.emitter.emit('_allowRedrawRequests'); + if (this.options.stabilization.fit === true) { + this.body.emitter.emit('fit'); + } - return type; - }; + if (this.options.stabilization.onlyDynamicEdges === true) { + this._restoreFrozenNodes(); + } + + this.body.emitter.emit('stabilizationIterationsDone'); + this.body.emitter.emit('_requestRedraw'); + + if (this.stabilized === true) { + this._emitStabilized(); + } else { + this.startSimulation(); + } + + this.ready = true; + } + }]); + + return PhysicsEngine; + })(); + + exports['default'] = PhysicsEngine; + module.exports = exports['default']; + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + + // utility functions + + // first check if moment.js is already loaded in the browser window, if so, + // use this instance. Else, load via commonjs. + + 'use strict'; + + var moment = __webpack_require__(40); + var uuid = __webpack_require__(42); /** - * Used to extend an array and copy it. This is used to propagate paths recursively. - * - * @param arr - * @param newValue - * @returns {Array} + * Test whether given object is a number + * @param {*} object + * @return {Boolean} isNumber */ - exports.copyAndExtendArray = function (arr, newValue) { - var newArr = []; - for (var i = 0; i < arr.length; i++) { - newArr.push(arr[i]); - } - newArr.push(newValue); - return newArr; + exports.isNumber = function (object) { + return object instanceof Number || typeof object == 'number'; }; /** - * Used to extend an array and copy it. This is used to propagate paths recursively. - * - * @param arr - * @param newValue - * @returns {Array} + * Remove everything in the DOM object + * @param DOMobject */ - exports.copyArray = function (arr) { - var newArr = []; - for (var i = 0; i < arr.length; i++) { - newArr.push(arr[i]); + exports.recursiveDOMDelete = function (DOMobject) { + if (DOMobject) { + while (DOMobject.hasChildNodes() === true) { + exports.recursiveDOMDelete(DOMobject.firstChild); + DOMobject.removeChild(DOMobject.firstChild); + } } - return newArr; }; /** - * Retrieve the absolute left value of a DOM element - * @param {Element} elem A dom element, for example a div + * 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 min + * @param max + * @param total + * @param 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 obj + * @param value + */ + exports.assignAllKeys = function (obj, value) { + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + if (typeof obj[prop] !== 'object') { + obj[prop] = value; + } + } + } + }; + + /** + * Fill an object with a possibly partially defined other object. Only copies values if the a object has an object requiring values. + * That means an object is not created on a property if only the b object has it. + * @param obj + * @param value + */ + exports.fillIfDefined = function (a, b) { + var allowDeletion = arguments[2] === undefined ? false : arguments[2]; + + for (var prop in a) { + if (b[prop] !== undefined) { + if (typeof b[prop] !== 'object') { + if ((b[prop] === undefined || b[prop] === null) && a[prop] !== undefined && allowDeletion === true) { + delete a[prop]; + } else { + a[prop] = b[prop]; + } + } else { + if (typeof 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.protoExtend = function (a, b) { + for (var i = 1; i < arguments.length; i++) { + var other = arguments[i]; + for (var prop in other) { + a[prop] = other[prop]; + } + } + return a; + }; + + /** + * 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) { + 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) { + 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.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.selectiveDeepExtend = function (props, a, b) { + var allowDeletion = arguments[3] === undefined ? false : arguments[3]; + + // TODO: add support for Arrays to deepExtend + if (Array.isArray(b)) { + throw new TypeError('Arrays are not supported by deepExtend'); + } + 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.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 { + if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) { + delete a[prop]; + } else { + a[prop] = b[prop]; + } + } + } else if (Array.isArray(b[prop])) { + throw new TypeError('Arrays are not supported by deepExtend'); + } else { + a[prop] = b[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.selectiveNotDeepExtend = function (props, a, b) { + var allowDeletion = arguments[3] === undefined ? false : arguments[3]; + + // TODO: add support for Arrays to deepExtend + if (Array.isArray(b)) { + throw new TypeError('Arrays are not supported by deepExtend'); + } + for (var prop in b) { + if (b.hasOwnProperty(prop)) { + if (props.indexOf(prop) == -1) { + if (b[prop] && b[prop].constructor === Object) { + if (a[prop] === undefined) { + a[prop] = {}; + } + if (a[prop].constructor === Object) { + exports.deepExtend(a[prop], b[prop]); + } else { + if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) { + delete a[prop]; + } else { + a[prop] = b[prop]; + } + } + } else if (Array.isArray(b[prop])) { + throw new TypeError('Arrays are not supported by deepExtend'); + } else { + a[prop] = b[prop]; + } + } + } + } + return a; + }; + + /** + * Deep extend an object a with the properties of object b + * @param {Object} a + * @param {Object} b + * @param [Boolean] protoExtend --> optional parameter. 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] global --> optional parameter. If true, the values of fields that are null will not deleted + * @returns {Object} + */ + exports.deepExtend = function (a, b, protoExtend, allowDeletion) { + 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); + } else { + if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) { + delete a[prop]; + } else { + a[prop] = b[prop]; + } + } + } else if (Array.isArray(b[prop])) { + a[prop] = []; + for (var i = 0; i < b[prop].length; i++) { + a[prop].push(b[prop][i]); + } + } else { + a[prop] = b[prop]; + } + } + } + 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': + 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(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 new Date(object).toISOString(); // parse string + } + } 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; + + 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 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 arr + * @param newValue + * @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. */ @@ -1523,23765 +2133,23745 @@ return /******/ (function(modules) { // webpackBootstrap /* 3 */ /***/ function(module, exports, __webpack_require__) { - "use strict"; - - Object.defineProperty(exports, "__esModule", { - value: true - }); + // DOM utility methods - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - var BarnesHutSolver = (function () { - function BarnesHutSolver(body, physicsBody, options) { - _classCallCheck(this, BarnesHutSolver); + /** + * this prepares the JSON container for allocating SVG elements + * @param JSONcontainer + * @private + */ + 'use strict'; - this.body = body; - this.physicsBody = physicsBody; - this.barnesHutTree; - this.setOptions(options); + 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 = []; + } } + }; - _createClass(BarnesHutSolver, [{ - key: "setOptions", - value: function setOptions(options) { - this.options = options; - this.thetaInversed = 1 / this.options.theta; - this.overlapAvoidanceFactor = 1 - Math.max(0, Math.min(1, this.options.avoidOverlap)); // if 1 then min distance = 0.5, if 0.5 then min distance = 0.5 + 0.5*node.shape.radius + /** + * 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 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 = []; + } } - }, { - key: "solve", - - /** - * This function calculates the forces the nodes apply on eachother based on a gravitational model. - * The Barnes Hut method is used to speed up this N-body simulation. - * - * @private - */ - value: function solve() { - if (this.options.gravitationalConstant !== 0 && this.physicsBody.physicsNodeIndices.length > 0) { - var node = undefined; - var nodes = this.body.nodes; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var nodeCount = nodeIndices.length; - - // create the tree - var barnesHutTree = this._formBarnesHutTree(nodes, nodeIndices); + } + }; - // for debugging - this.barnesHutTree = barnesHutTree; + /** + * 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 elementType + * @param JSONcontainer + * @param svgContainer + * @returns {*} + * @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; + }; - // place the nodes one by one recursively - for (var i = 0; i < nodeCount; i++) { - node = nodes[nodeIndices[i]]; - if (node.options.mass > 0) { - // starting with root is irrelevant, it never passes the BarnesHutSolver condition - this._getForceContribution(barnesHutTree.root.children.NW, node); - this._getForceContribution(barnesHutTree.root.children.NE, node); - this._getForceContribution(barnesHutTree.root.children.SW, node); - this._getForceContribution(barnesHutTree.root.children.SE, node); - } - } + /** + * 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 elementType + * @param JSONcontainer + * @param DOMContainer + * @returns {*} + * @private + */ + 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); } } - }, { - key: "_getForceContribution", + } 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; + }; - /** - * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass. - * If a region contains a single node, we check if it is not itself, then we apply the force. - * - * @param parentBranch - * @param node - * @private - */ - value: function _getForceContribution(parentBranch, node) { - // we get no force contribution from an empty region - if (parentBranch.childrenCount > 0) { - var dx = undefined, - dy = undefined, - distance = undefined; + /** + * draw a point object. this is a seperate 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 x + * @param y + * @param group + * @param JSONcontainer + * @param svgContainer + * @param labelObj + * @returns {*} + */ + exports.drawPoint = function (x, y, group, JSONcontainer, svgContainer, labelObj) { + var point; + if (group.options.drawPoints.style == 'circle') { + point = exports.getSVGElement('circle', JSONcontainer, svgContainer); + point.setAttributeNS(null, 'cx', x); + point.setAttributeNS(null, 'cy', y); + point.setAttributeNS(null, 'r', 0.5 * group.options.drawPoints.size); + } else { + point = exports.getSVGElement('rect', JSONcontainer, svgContainer); + point.setAttributeNS(null, 'x', x - 0.5 * group.options.drawPoints.size); + point.setAttributeNS(null, 'y', y - 0.5 * group.options.drawPoints.size); + point.setAttributeNS(null, 'width', group.options.drawPoints.size); + point.setAttributeNS(null, 'height', group.options.drawPoints.size); + } - // get the distance from the center of mass to the node. - dx = parentBranch.centerOfMass.x - node.x; - dy = parentBranch.centerOfMass.y - node.y; - distance = Math.sqrt(dx * dx + dy * dy); + if (group.options.drawPoints.styles !== undefined) { + point.setAttributeNS(null, 'style', group.group.options.drawPoints.styles); + } + point.setAttributeNS(null, 'class', group.className + ' vis-point'); + //handle label - // BarnesHutSolver condition - // original condition : s/d < theta = passed === d/s > 1/theta = passed - // calcSize = 1/s --> d * 1/s > 1/theta = passed - if (distance * parentBranch.calcSize > this.thetaInversed) { - this._calculateForces(distance, dx, dy, node, parentBranch); - } else { - // Did not pass the condition, go into children if available - if (parentBranch.childrenCount === 4) { - this._getForceContribution(parentBranch.children.NW, node); - this._getForceContribution(parentBranch.children.NE, node); - this._getForceContribution(parentBranch.children.SW, node); - this._getForceContribution(parentBranch.children.SE, node); - } else { - // parentBranch must have only one node, if it was empty we wouldnt be here - if (parentBranch.children.data.id != node.id) { - // if it is not self - this._calculateForces(distance, dx, dy, node, parentBranch); - } - } - } - } + if (labelObj) { + var label = exports.getSVGElement('text', JSONcontainer, svgContainer); + if (labelObj.xOffset) { + x = x + labelObj.xOffset; } - }, { - key: "_calculateForces", - /** - * Calculate the forces based on the distance. - * - * @param distance - * @param dx - * @param dy - * @param node - * @param parentBranch - * @private - */ - value: function _calculateForces(distance, dx, dy, node, parentBranch) { - if (distance === 0) { - distance = 0.1; - dx = distance; - } + if (labelObj.yOffset) { + y = y + labelObj.yOffset; + } + if (labelObj.content) { + label.textContent = labelObj.content; + } - if (this.overlapAvoidanceFactor < 1) { - distance = Math.max(0.1 + this.overlapAvoidanceFactor * node.shape.radius, distance - node.shape.radius); - } + if (labelObj.className) { + label.setAttributeNS(null, 'class', labelObj.className + ' vis-label'); + } + label.setAttributeNS(null, 'x', x); + label.setAttributeNS(null, 'y', y); + } - // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines - // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce - var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass / Math.pow(distance, 3); - var fx = dx * gravityForce; - var fy = dy * gravityForce; + return point; + }; - this.physicsBody.forces[node.id].x += fx; - this.physicsBody.forces[node.id].y += fy; + /** + * draw a bar SVG element centered on the X coordinate + * + * @param x + * @param y + * @param className + */ + exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer, style) { + if (height != 0) { + if (height < 0) { + height *= -1; + y -= height; } - }, { - key: "_formBarnesHutTree", + 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); + } + } + }; - /** - * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes. - * - * @param nodes - * @param nodeIndices - * @private - */ - value: function _formBarnesHutTree(nodes, nodeIndices) { - var node = undefined; - var nodeCount = nodeIndices.length; +/***/ }, +/* 4 */ +/***/ function(module, exports, __webpack_require__) { - var minX = nodes[nodeIndices[0]].x; - var minY = nodes[nodeIndices[0]].y; - var maxX = nodes[nodeIndices[0]].x; - var maxY = nodes[nodeIndices[0]].y; + 'use strict'; - // get the range of the nodes - for (var i = 1; i < nodeCount; i++) { - var x = nodes[nodeIndices[i]].x; - var y = nodes[nodeIndices[i]].y; - if (nodes[nodeIndices[i]].options.mass > 0) { - if (x < minX) { - minX = x; - } - if (x > maxX) { - maxX = x; - } - if (y < minY) { - minY = y; - } - if (y > maxY) { - maxY = y; - } - } - } - // make the range a square - var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y - if (sizeDiff > 0) { - minY -= 0.5 * sizeDiff; - maxY += 0.5 * sizeDiff; - } // xSize > ySize - else { - minX += 0.5 * sizeDiff; - maxX -= 0.5 * sizeDiff; - } // xSize < ySize + var util = __webpack_require__(2); + var Queue = __webpack_require__(6); - var minimumTreeSize = 0.00001; - var rootSize = Math.max(minimumTreeSize, Math.abs(maxX - minX)); - var halfRootSize = 0.5 * rootSize; - var centerX = 0.5 * (minX + maxX), - centerY = 0.5 * (minY + maxY); + /** + * DataSet + * + * 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. 0) { - this._placeInTree(barnesHutTree.root, node); + // all variants of a Date are internally stored as Date, so we can convert + // from everything to everything (also from ISODate to Number for example) + if (this._options.type) { + for (var field in this._options.type) { + if (this._options.type.hasOwnProperty(field)) { + var value = this._options.type[field]; + if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') { + this._type[field] = 'Date'; + } else { + this._type[field] = value; } } - - // make global - return barnesHutTree; } - }, { - key: "_updateBranchMass", + } - /** - * this updates the mass of a branch. this is increased by adding a node. - * - * @param parentBranch - * @param node - * @private - */ - value: function _updateBranchMass(parentBranch, node) { - var totalMass = parentBranch.mass + node.options.mass; - var totalMassInv = 1 / totalMass; + // TODO: deprecated since version 1.1.1 (or 2.0.0?) + if (this._options.convert) { + throw new Error('Option "convert" is deprecated. Use "type" instead.'); + } - parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass; - parentBranch.centerOfMass.x *= totalMassInv; + this._subscribers = {}; // event subscribers - parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass; - parentBranch.centerOfMass.y *= totalMassInv; + // add initial data when provided + if (data) { + this.add(data); + } - parentBranch.mass = totalMass; - var biggestSize = Math.max(Math.max(node.height, node.radius), node.width); - parentBranch.maxWidth = parentBranch.maxWidth < biggestSize ? biggestSize : parentBranch.maxWidth; - } - }, { - key: "_placeInTree", + this.setOptions(options); + } - /** - * determine in which branch the node will be placed. - * - * @param parentBranch - * @param node - * @param skipMassUpdate - * @private - */ - value: function _placeInTree(parentBranch, node, skipMassUpdate) { - if (skipMassUpdate != true || skipMassUpdate === undefined) { - // update the mass of the branch. - this._updateBranchMass(parentBranch, node); + /** + * @param {Object} [options] Available options: + * {Object} queue Queue changes to the DataSet, + * flush them all at once. + * Queue options: + * - {number} delay Delay in ms, null by default + * - {number} max Maximum number of entries in the queue, Infinity by default + * @param options + */ + DataSet.prototype.setOptions = function (options) { + if (options && options.queue !== undefined) { + if (options.queue === false) { + // delete queue if loaded + if (this._queue) { + this._queue.destroy(); + delete this._queue; + } + } else { + // create queue and update its options + if (!this._queue) { + this._queue = Queue.extend(this, { + replace: ['add', 'update', 'remove'] + }); } - if (parentBranch.children.NW.range.maxX > node.x) { - // in NW or SW - if (parentBranch.children.NW.range.maxY > node.y) { - // in NW - this._placeInRegion(parentBranch, node, "NW"); - } else { - // in SW - this._placeInRegion(parentBranch, node, "SW"); - } - } else { - // in NE or SE - if (parentBranch.children.NW.range.maxY > node.y) { - // in NE - this._placeInRegion(parentBranch, node, "NE"); - } else { - // in SE - this._placeInRegion(parentBranch, node, "SE"); - } - } - } - }, { - key: "_placeInRegion", - - /** - * actually place the node in a region (or branch) - * - * @param parentBranch - * @param node - * @param region - * @private - */ - value: function _placeInRegion(parentBranch, node, region) { - switch (parentBranch.children[region].childrenCount) { - case 0: - // place node here - parentBranch.children[region].children.data = node; - parentBranch.children[region].childrenCount = 1; - this._updateBranchMass(parentBranch.children[region], node); - break; - case 1: - // convert into children - // if there are two nodes exactly overlapping (on init, on opening of cluster etc.) - // we move one node a pixel and we do not put it in the tree. - if (parentBranch.children[region].children.data.x === node.x && parentBranch.children[region].children.data.y === node.y) { - //node.x += Math.random(); - //node.y += Math.random(); - node.x += 0.1; - node.y += 0.1; - } else { - this._splitBranch(parentBranch.children[region]); - this._placeInTree(parentBranch.children[region], node); - } - break; - case 4: - // place in branch - this._placeInTree(parentBranch.children[region], node); - break; + if (typeof options.queue === 'object') { + this._queue.setOptions(options.queue); } } - }, { - key: "_splitBranch", + } + }; - /** - * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch - * after the split is complete. - * - * @param parentBranch - * @private - */ - value: function _splitBranch(parentBranch) { - // if the branch is shaded with a node, replace the node in the new subset. - var containedNode = null; - if (parentBranch.childrenCount === 1) { - containedNode = parentBranch.children.data; - parentBranch.mass = 0; - parentBranch.centerOfMass.x = 0; - parentBranch.centerOfMass.y = 0; - } - parentBranch.childrenCount = 4; - parentBranch.children.data = null; - this._insertRegion(parentBranch, "NW"); - this._insertRegion(parentBranch, "NE"); - this._insertRegion(parentBranch, "SW"); - this._insertRegion(parentBranch, "SE"); + /** + * Subscribe to an event, add an event listener + * @param {String} event Event name. Available events: 'put', 'update', + * 'remove' + * @param {function} callback Callback method. Called with three parameters: + * {String} event + * {Object | null} params + * {String | Number} senderId + */ + DataSet.prototype.on = function (event, callback) { + var subscribers = this._subscribers[event]; + if (!subscribers) { + subscribers = []; + this._subscribers[event] = subscribers; + } - if (containedNode != null) { - this._placeInTree(parentBranch, containedNode); - } - } - }, { - key: "_insertRegion", + subscribers.push({ + callback: callback + }); + }; - /** - * This function subdivides the region into four new segments. - * Specifically, this inserts a single new segment. - * It fills the children section of the parentBranch - * - * @param parentBranch - * @param region - * @param parentRange - * @private - */ - value: function _insertRegion(parentBranch, region) { - var minX = undefined, - maxX = undefined, - minY = undefined, - maxY = undefined; - var childSize = 0.5 * parentBranch.size; - switch (region) { - case "NW": - minX = parentBranch.range.minX; - maxX = parentBranch.range.minX + childSize; - minY = parentBranch.range.minY; - maxY = parentBranch.range.minY + childSize; - break; - case "NE": - minX = parentBranch.range.minX + childSize; - maxX = parentBranch.range.maxX; - minY = parentBranch.range.minY; - maxY = parentBranch.range.minY + childSize; - break; - case "SW": - minX = parentBranch.range.minX; - maxX = parentBranch.range.minX + childSize; - minY = parentBranch.range.minY + childSize; - maxY = parentBranch.range.maxY; - break; - case "SE": - minX = parentBranch.range.minX + childSize; - maxX = parentBranch.range.maxX; - minY = parentBranch.range.minY + childSize; - maxY = parentBranch.range.maxY; - break; - } + // TODO: remove this deprecated function some day (replaced with `on` since version 0.5, deprecated since v4.0) + DataSet.prototype.subscribe = function () { + throw new Error('DataSet.subscribe is deprecated. Use DataSet.on instead.'); + }; - parentBranch.children[region] = { - centerOfMass: { x: 0, y: 0 }, - mass: 0, - range: { minX: minX, maxX: maxX, minY: minY, maxY: maxY }, - size: 0.5 * parentBranch.size, - calcSize: 2 * parentBranch.calcSize, - children: { data: null }, - maxWidth: 0, - level: parentBranch.level + 1, - childrenCount: 0 - }; - } - }, { - key: "_debug", + /** + * Unsubscribe from an event, remove an event listener + * @param {String} event + * @param {function} callback + */ + DataSet.prototype.off = function (event, callback) { + var subscribers = this._subscribers[event]; + if (subscribers) { + this._subscribers[event] = subscribers.filter(function (listener) { + return listener.callback != callback; + }); + } + }; - //--------------------------- DEBUGGING BELOW ---------------------------// + // TODO: remove this deprecated function some day (replaced with `on` since version 0.5, deprecated since v4.0) + DataSet.prototype.unsubscribe = function () { + throw new Error('DataSet.unsubscribe is deprecated. Use DataSet.off instead.'); + }; - /** - * This function is for debugging purposed, it draws the tree. - * - * @param ctx - * @param color - * @private - */ - value: function _debug(ctx, color) { - if (this.barnesHutTree !== undefined) { + /** + * Trigger an event + * @param {String} event + * @param {Object | null} params + * @param {String} [senderId] Optional id of the sender. + * @private + */ + DataSet.prototype._trigger = function (event, params, senderId) { + if (event == '*') { + throw new Error('Cannot trigger event *'); + } - ctx.lineWidth = 1; + var subscribers = []; + if (event in this._subscribers) { + subscribers = subscribers.concat(this._subscribers[event]); + } + if ('*' in this._subscribers) { + subscribers = subscribers.concat(this._subscribers['*']); + } - this._drawBranch(this.barnesHutTree.root, ctx, color); - } + for (var i = 0; i < subscribers.length; i++) { + var subscriber = subscribers[i]; + if (subscriber.callback) { + subscriber.callback(event, params, senderId || null); } - }, { - key: "_drawBranch", + } + }; - /** - * This function is for debugging purposes. It draws the branches recursively. - * - * @param branch - * @param ctx - * @param color - * @private - */ - value: function _drawBranch(branch, ctx, color) { - if (color === undefined) { - color = "#FF0000"; - } + /** + * Add data. + * Adding an item will fail when there already is an item with the same id. + * @param {Object | Array} data + * @param {String} [senderId] Optional sender id + * @return {Array} addedIds Array with the ids of the added items + */ + DataSet.prototype.add = function (data, senderId) { + var addedIds = [], + id, + me = this; - if (branch.childrenCount === 4) { - this._drawBranch(branch.children.NW, ctx); - this._drawBranch(branch.children.NE, ctx); - this._drawBranch(branch.children.SE, ctx); - this._drawBranch(branch.children.SW, ctx); - } - ctx.strokeStyle = color; - ctx.beginPath(); - ctx.moveTo(branch.range.minX, branch.range.minY); - ctx.lineTo(branch.range.maxX, branch.range.minY); - ctx.stroke(); + 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 instanceof Object) { + // Single item + id = me._addItem(data); + addedIds.push(id); + } else { + throw new Error('Unknown dataType'); + } - ctx.beginPath(); - ctx.moveTo(branch.range.maxX, branch.range.minY); - ctx.lineTo(branch.range.maxX, branch.range.maxY); - ctx.stroke(); + if (addedIds.length) { + this._trigger('add', { items: addedIds }, senderId); + } - ctx.beginPath(); - ctx.moveTo(branch.range.maxX, branch.range.maxY); - ctx.lineTo(branch.range.minX, branch.range.maxY); - ctx.stroke(); + return addedIds; + }; - ctx.beginPath(); - ctx.moveTo(branch.range.minX, branch.range.maxY); - ctx.lineTo(branch.range.minX, branch.range.minY); - ctx.stroke(); + /** + * 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 + */ + DataSet.prototype.update = function (data, senderId) { + var addedIds = []; + var updatedIds = []; + var updatedData = []; + var me = this; + var fieldId = me._fieldId; - /* - if (branch.mass > 0) { - ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass); - ctx.stroke(); - } - */ + var addOrUpdate = function addOrUpdate(item) { + var id = item[fieldId]; + if (me._data[id]) { + // update item + id = me._updateItem(item); + updatedIds.push(id); + updatedData.push(item); + } else { + // add new item + id = me._addItem(item); + addedIds.push(id); } - }]); - - return BarnesHutSolver; - })(); + }; - exports["default"] = BarnesHutSolver; - module.exports = exports["default"]; + if (Array.isArray(data)) { + // Array + for (var i = 0, len = data.length; i < len; i++) { + addOrUpdate(data[i]); + } + } else if (data instanceof Object) { + // Single item + addOrUpdate(data); + } else { + throw new Error('Unknown dataType'); + } -/***/ }, -/* 4 */ -/***/ function(module, exports, __webpack_require__) { + if (addedIds.length) { + this._trigger('add', { items: addedIds }, senderId); + } + if (updatedIds.length) { + this._trigger('update', { items: updatedIds, data: updatedData }, senderId); + } - 'use strict'; + return addedIds.concat(updatedIds); + }; - Object.defineProperty(exports, '__esModule', { - value: true - }); + /** + * 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. + * @throws Error + */ + DataSet.prototype.get = function (args) { + var me = this; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // 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]; + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + // 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'; + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + // build options + var type = options && options.type || this._options.type; + var filter = options && options.filter; + var items = [], + item, + itemId, + i, + len; - var _componentsNode = __webpack_require__(8); + // convert items + if (id != undefined) { + // return a single item + item = me._getItem(id, type); + if (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 + for (itemId in this._data) { + if (this._data.hasOwnProperty(itemId)) { + item = me._getItem(itemId, type); + if (!filter || filter(item)) { + items.push(item); + } + } + } + } - var _componentsNode2 = _interopRequireDefault(_componentsNode); + // order the results + if (options && options.order && id == undefined) { + this._sort(items, options.order); + } - var _componentsSharedLabel = __webpack_require__(68); + // 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); + } + } + } - var _componentsSharedLabel2 = _interopRequireDefault(_componentsSharedLabel); + // return the results + if (returnType == 'Object') { + var result = {}; + for (i = 0; i < items.length; i++) { + result[items[i].id] = items[i]; + } + return result; + } else { + if (id != undefined) { + // a single item + return item; + } else { + // just return our array + return items; + } + } + }; - var util = __webpack_require__(2); - var DataSet = __webpack_require__(22); - var DataView = __webpack_require__(24); + /** + * 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, + i, + len, + id, + item, + items, + ids = []; - var NodesHandler = (function () { - function NodesHandler(body, images, groups, layoutEngine) { - var _this = this; + if (filter) { + // get filtered items + if (order) { + // create ordered list + items = []; + for (id in data) { + if (data.hasOwnProperty(id)) { + item = this._getItem(id, type); + if (filter(item)) { + items.push(item); + } + } + } - _classCallCheck(this, NodesHandler); + this._sort(items, order); - this.body = body; - this.images = images; - this.groups = groups; - this.layoutEngine = layoutEngine; - - // create the node API in the body container - this.body.functions.createNode = this.create.bind(this); - - this.nodesListeners = { - add: function add(event, params) { - _this.add(params.items); - }, - update: function update(event, params) { - _this.update(params.items, params.data); - }, - remove: function remove(event, params) { - _this.remove(params.items); + for (i = 0, len = items.length; i < len; i++) { + ids[i] = items[i][this._fieldId]; } - }; - - this.options = {}; - this.defaultOptions = { - borderWidth: 1, - borderWidthSelected: 2, - brokenImage: undefined, - color: { - border: '#2B7CE9', - background: '#97C2FC', - highlight: { - border: '#2B7CE9', - background: '#D2E5FF' - }, - hover: { - border: '#2B7CE9', - background: '#D2E5FF' - } - }, - fixed: { - x: false, - y: false - }, - font: { - color: '#343434', - size: 14, // px - face: 'arial', - background: 'none', - strokeWidth: 0, // px - strokeColor: '#ffffff', - align: 'horizontal' - }, - group: undefined, - hidden: false, - icon: { - face: 'FontAwesome', //'FontAwesome', - code: undefined, //'\uf007', - size: 50, //50, - color: '#2B7CE9' //'#aa00ff' - }, - image: undefined, // --> URL - label: undefined, - level: undefined, - mass: 1, - physics: true, - scaling: { - min: 10, - max: 30, - label: { - enabled: false, - min: 14, - max: 30, - maxVisible: 30, - drawThreshold: 5 - }, - customScalingFunction: function customScalingFunction(min, max, total, value) { - if (max === min) { - return 0.5; - } else { - var scale = 1 / (max - min); - return Math.max(0, (value - min) * scale); + } else { + // create unordered list + for (id in data) { + if (data.hasOwnProperty(id)) { + item = this._getItem(id, type); + if (filter(item)) { + ids.push(item[this._fieldId]); } } - }, - shadow: { - enabled: false, - size: 10, - x: 5, - y: 5 - }, - shape: 'ellipse', - size: 25, - title: undefined, - value: undefined, - x: undefined, - y: undefined - }; - util.extend(this.options, this.defaultOptions); - - this.bindEventListeners(); - } - - _createClass(NodesHandler, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this2 = this; - - // refresh the nodes. Used when reverting from hierarchical layout - this.body.emitter.on('refreshNodes', this.refresh.bind(this)); - this.body.emitter.on('refresh', this.refresh.bind(this)); - this.body.emitter.on('destroy', function () { - delete _this2.body.functions.createNode; - delete _this2.nodesListeners.add; - delete _this2.nodesListeners.update; - delete _this2.nodesListeners.remove; - delete _this2.nodesListeners; - }); + } } - }, { - key: 'setOptions', - value: function setOptions(options) { - if (options !== undefined) { - _componentsNode2['default'].parseOptions(this.options, options); - - // update the shape in all nodes - if (options.shape !== undefined) { - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - this.body.nodes[nodeId].updateShape(); - } - } - } - - // update the shape size in all nodes - if (options.font !== undefined) { - _componentsSharedLabel2['default'].parseOptions(this.options.font, options); - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - this.body.nodes[nodeId].updateLabelModule(); - this.body.nodes[nodeId]._reset(); - } - } + } else { + // get all items + if (order) { + // create an ordered list + items = []; + for (id in data) { + if (data.hasOwnProperty(id)) { + items.push(data[id]); } + } - // update the shape size in all nodes - if (options.size !== undefined) { - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - this.body.nodes[nodeId]._reset(); - } - } - } + this._sort(items, order); - // update the state of the letiables if needed - if (options.hidden !== undefined || options.physics !== undefined) { - this.body.emitter.emit('_dataChanged'); + for (i = 0, len = items.length; i < len; i++) { + ids[i] = items[i][this._fieldId]; + } + } else { + // create unordered list + for (id in data) { + if (data.hasOwnProperty(id)) { + item = data[id]; + ids.push(item[this._fieldId]); } } } - }, { - key: 'setData', + } - /** - * Set a data set with nodes for the network - * @param {Array | DataSet | DataView} nodes The data containing the nodes. - * @private - */ - value: function setData(nodes) { - var _this3 = this; + return ids; + }; - var doNotEmit = arguments[1] === undefined ? false : arguments[1]; + /** + * Returns the DataSet itself. Is overwritten for example by the DataView, + * which returns the DataSet it is connected to instead. + */ + DataSet.prototype.getDataSet = function () { + return this; + }; - var oldNodesData = this.body.data.nodes; + /** + * 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, + item, + id; - if (nodes instanceof DataSet || nodes instanceof DataView) { - this.body.data.nodes = nodes; - } else if (Array.isArray(nodes)) { - this.body.data.nodes = new DataSet(); - this.body.data.nodes.add(nodes); - } else if (!nodes) { - this.body.data.nodes = new DataSet(); - } else { - throw new TypeError('Array or DataSet expected'); + if (options && options.order) { + // execute forEach on ordered list + var items = this.get(options); + + for (var i = 0, len = items.length; i < len; i++) { + item = items[i]; + id = item[this._fieldId]; + callback(item, id); + } + } else { + // unordered + for (id in data) { + if (data.hasOwnProperty(id)) { + item = this._getItem(id, type); + if (!filter || filter(item)) { + callback(item, id); + } } + } + } + }; - if (oldNodesData) { - // unsubscribe from old dataset - util.forEach(this.nodesListeners, function (callback, event) { - oldNodesData.off(event, callback); - }); + /** + * 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, + item; + + // convert and filter items + for (var id in data) { + if (data.hasOwnProperty(id)) { + item = this._getItem(id, type); + if (!filter || filter(item)) { + mappedItems.push(callback(item, id)); } + } + } - // remove drawn nodes - this.body.nodes = {}; + // order items + if (options && options.order) { + this._sort(mappedItems, options.order); + } - if (this.body.data.nodes) { - (function () { - // subscribe to new dataset - var me = _this3; - util.forEach(_this3.nodesListeners, function (callback, event) { - me.body.data.nodes.on(event, callback); - }); + return mappedItems; + }; - // draw all new nodes - var ids = _this3.body.data.nodes.getIds(); - _this3.add(ids, true); - })(); - } + /** + * 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; + } - if (doNotEmit === false) { - this.body.emitter.emit('_dataChanged'); + var filteredItem = {}; + + if (Array.isArray(fields)) { + for (var field in item) { + if (item.hasOwnProperty(field) && fields.indexOf(field) != -1) { + filteredItem[field] = item[field]; } } - }, { - key: 'add', + } else { + for (var field in item) { + if (item.hasOwnProperty(field) && fields.hasOwnProperty(field)) { + filteredItem[fields[field]] = item[field]; + } + } + } - /** - * Add nodes - * @param {Number[] | String[]} ids - * @private - */ - value: function add(ids) { - var doNotEmit = arguments[1] === undefined ? false : arguments[1]; + return filteredItem; + }; - var id = undefined; - var newNodes = []; - for (var i = 0; i < ids.length; i++) { - id = ids[i]; - var _properties = this.body.data.nodes.get(id); - var node = this.create(_properties); - newNodes.push(node); - this.body.nodes[id] = node; // note: this may replace an existing node - } + /** + * 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'); + } + }; - this.layoutEngine.positionInitially(newNodes); + /** + * 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 = [], + i, + len, + removedId; - if (doNotEmit === false) { - this.body.emitter.emit('_dataChanged'); + if (Array.isArray(id)) { + for (i = 0, len = id.length; i < len; i++) { + removedId = this._remove(id[i]); + if (removedId != null) { + removedIds.push(removedId); } } - }, { - key: 'update', + } else { + removedId = this._remove(id); + if (removedId != null) { + removedIds.push(removedId); + } + } - /** - * Update existing nodes, or create them when not yet existing - * @param {Number[] | String[]} ids - * @private - */ - value: function update(ids, changedData) { - var nodes = this.body.nodes; - var dataChanged = false; - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; - var node = nodes[id]; - var data = changedData[i]; - if (node !== undefined) { - // update node - dataChanged = node.setOptions(data); - } else { - dataChanged = true; - // create node - node = this.create(properties); - nodes[id] = node; - } - } + if (removedIds.length) { + this._trigger('remove', { items: removedIds }, senderId); + } - if (dataChanged === true) { - this.body.emitter.emit('_dataChanged'); - } else { - this.body.emitter.emit('_dataUpdated'); - } + 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) { + if (util.isNumber(id) || util.isString(id)) { + if (this._data[id]) { + delete this._data[id]; + this.length--; + return id; } - }, { - key: 'remove', + } else if (id instanceof Object) { + var itemId = id[this._fieldId]; + if (itemId && this._data[itemId]) { + delete this._data[itemId]; + this.length--; + return itemId; + } + } + return null; + }; - /** - * Remove existing nodes. If nodes do not exist, the method will just ignore it. - * @param {Number[] | String[]} ids - * @private - */ - value: function remove(ids) { - var nodes = this.body.nodes; + /** + * Clear the data + * @param {String} [senderId] Optional sender id + * @return {Array} removedIds The ids of all removed items + */ + DataSet.prototype.clear = function (senderId) { + var ids = Object.keys(this._data); - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; - delete nodes[id]; - } + this._data = {}; + this.length = 0; - this.body.emitter.emit('_dataChanged'); - } - }, { - key: 'create', + this._trigger('remove', { items: ids }, senderId); - /** - * create a node - * @param properties - * @param constructorClass - */ - value: function create(properties) { - var constructorClass = arguments[1] === undefined ? _componentsNode2['default'] : arguments[1]; + return ids; + }; - return new constructorClass(properties, this.body, this.images, this.groups, this.options); - } - }, { - key: 'refresh', - value: function refresh() { - var nodes = this.body.nodes; - for (var nodeId in nodes) { - var node = undefined; - if (nodes.hasOwnProperty(nodeId)) { - node = nodes[nodeId]; - } - var data = this.body.data.nodes._data[nodeId]; - if (node !== undefined && data !== undefined) { - node.setOptions({ fixed: false }); - node.setOptions(data); - } - } - } - }, { - key: 'getPositions', + /** + * 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, + max = null, + maxField = null; - /** - * Returns the positions of the nodes. - * @param ids --> optional, can be array of nodeIds, can be string - * @returns {{}} - */ - value: function getPositions(ids) { - var dataArray = {}; - if (ids !== undefined) { - if (Array.isArray(ids) === true) { - for (var i = 0; i < ids.length; i++) { - if (this.body.nodes[ids[i]] !== undefined) { - var node = this.body.nodes[ids[i]]; - dataArray[ids[i]] = { x: Math.round(node.x), y: Math.round(node.y) }; - } - } - } else { - if (this.body.nodes[ids] !== undefined) { - var node = this.body.nodes[ids]; - dataArray[ids] = { x: Math.round(node.x), y: Math.round(node.y) }; - } - } - } else { - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - var node = this.body.nodes[nodeId]; - dataArray[nodeId] = { x: Math.round(node.x), y: Math.round(node.y) }; - } - } - } - return dataArray; - } - }, { - key: 'storePositions', - - /** - * Load the XY positions of the nodes into the dataset. - */ - value: function storePositions() { - // todo: add support for clusters and hierarchical. - var dataArray = []; - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - var node = this.body.nodes[nodeId]; - if (this.body.data.nodes._data[nodeId].x != Math.round(node.x) || this.body.data.nodes._data[nodeId].y != Math.round(node.y)) { - dataArray.push({ id: nodeId, x: Math.round(node.x), y: Math.round(node.y) }); - } - } + for (var id in data) { + if (data.hasOwnProperty(id)) { + var item = data[id]; + var itemField = item[field]; + if (itemField != null && (!max || itemField > maxField)) { + max = item; + maxField = itemField; } - this.body.data.nodes.update(dataArray); } - }, { - key: 'getBoundingBox', + } - /** - * get the bounding box of a node. - * @param nodeId - * @returns {j|*} - */ - value: function getBoundingBox(nodeId) { - if (this.body.nodes[nodeId] !== undefined) { - return this.body.nodes[nodeId].shape.boundingBox; - } - } - }, { - key: 'getConnectedNodes', + return max; + }; - /** - * Get the Ids of nodes connected to this node. - * @param nodeId - * @returns {Array} - */ - value: function getConnectedNodes(nodeId) { - var nodeList = []; - if (this.body.nodes[nodeId] !== undefined) { - var node = this.body.nodes[nodeId]; - var nodeObj = {}; // used to quickly check if node already exists - for (var i = 0; i < node.edges.length; i++) { - var edge = node.edges[i]; - if (edge.toId == nodeId) { - // these are double equals since ids can be numeric or string - if (nodeObj[edge.fromId] === undefined) { - nodeList.push(edge.fromId); - nodeObj[edge.fromId] = true; - } - } else if (edge.fromId == nodeId) { - // these are double equals since ids can be numeric or string - if (nodeObj[edge.toId] === undefined) { - nodeList.push(edge.toId); - nodeObj[edge.toId] = true; - } - } - } - } - return nodeList; - } - }, { - key: 'getConnectedEdges', + /** + * 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, + min = null, + minField = null; - /** - * Get the ids of the edges connected to this node. - * @param nodeId - * @returns {*} - */ - value: function getConnectedEdges(nodeId) { - var edgeList = []; - if (this.body.nodes[nodeId] !== undefined) { - var node = this.body.nodes[nodeId]; - for (var i = 0; i < node.edges.length; i++) { - edgeList.push(node.edges[i].id); - } - } else { - console.log('NodeId provided for getConnectedEdges does not exist. Provided: ', nodeId); + for (var id in data) { + if (data.hasOwnProperty(id)) { + var item = data[id]; + var itemField = item[field]; + if (itemField != null && (!min || itemField < minField)) { + min = item; + minField = itemField; } - return edgeList; } - }]); - - return NodesHandler; - })(); - - exports['default'] = NodesHandler; - module.exports = exports['default']; - -/***/ }, -/* 5 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; + } - var Item = __webpack_require__(11); - var util = __webpack_require__(2); + return min; + }; /** - * @constructor BoxItem - * @extends Item - * @param {Object} data Object containing parameters start - * content, 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 + * 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. */ - function BoxItem(data, conversion, options) { - this.props = { - dot: { - width: 0, - height: 0 - }, - line: { - width: 0, - height: 0 - } - }; + DataSet.prototype.distinct = function (field) { + var data = this._data; + var values = []; + var fieldType = this._options.type && this._options.type[field] || null; + var count = 0; + var i; - // validate data - if (data) { - if (data.start == undefined) { - throw new Error('Property "start" missing in item ' + data); + for (var prop in data) { + if (data.hasOwnProperty(prop)) { + var item = data[prop]; + var value = item[field]; + var exists = false; + for (i = 0; i < count; i++) { + if (values[i] == value) { + exists = true; + break; + } + } + if (!exists && value !== undefined) { + values[count] = value; + count++; + } } } - Item.call(this, data, conversion, options); - } - - BoxItem.prototype = new Item(null, null, null); + if (fieldType) { + for (i = 0; i < values.length; i++) { + values[i] = util.convert(values[i], fieldType); + } + } - /** - * Check whether this item is visible inside given range - * @returns {{start: Number, end: Number}} range with a timestamp for start and end - * @returns {boolean} True if visible - */ - BoxItem.prototype.isVisible = function (range) { - // determine visibility - // TODO: account for the real width of the item. Right now we just add 1/4 to the window - var interval = (range.end - range.start) / 4; - return this.data.start > range.start - interval && this.data.start < range.end + interval; + return values; }; /** - * Repaint the item + * Add a single item. Will fail when an item with the same id already exists. + * @param {Object} item + * @return {String} id + * @private */ - BoxItem.prototype.redraw = function () { - var dom = this.dom; - if (!dom) { - // create DOM - this.dom = {}; - dom = this.dom; - - // create main box - dom.box = document.createElement('DIV'); - - // contents box (inside the background box). used for making margins - dom.content = document.createElement('DIV'); - dom.content.className = 'vis-item-content'; - dom.box.appendChild(dom.content); - - // line to axis - dom.line = document.createElement('DIV'); - dom.line.className = 'vis-line'; - - // dot on axis - dom.dot = document.createElement('DIV'); - dom.dot.className = 'vis-dot'; - - // attach this item as attribute - dom.box['timeline-item'] = this; - - this.dirty = true; - } + DataSet.prototype._addItem = function (item) { + var id = item[this._fieldId]; - // append DOM to parent DOM - if (!this.parent) { - throw new Error('Cannot redraw item: no parent attached'); - } - if (!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(dom.box); - } - if (!dom.line.parentNode) { - var background = this.parent.dom.background; - if (!background) throw new Error('Cannot redraw item: parent has no background container element'); - background.appendChild(dom.line); - } - if (!dom.dot.parentNode) { - var axis = this.parent.dom.axis; - if (!background) throw new Error('Cannot redraw item: parent has no axis container element'); - axis.appendChild(dom.dot); + 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; } - this.displayed = true; - - // Update DOM when item is marked dirty. 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._updateTitle(this.dom.box); - this._updateDataAttributes(this.dom.box); - this._updateStyle(this.dom.box); - - // update class - var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); - dom.box.className = 'vis-item vis-box' + className; - dom.line.className = 'vis-item vis-line' + className; - dom.dot.className = 'vis-item vis-dot' + className; - - // recalculate size - this.props.dot.height = dom.dot.offsetHeight; - this.props.dot.width = dom.dot.offsetWidth; - this.props.line.width = dom.line.offsetWidth; - this.width = dom.box.offsetWidth; - this.height = dom.box.offsetHeight; - this.dirty = false; + var d = {}; + for (var field in item) { + if (item.hasOwnProperty(field)) { + var fieldType = this._type[field]; // type may be undefined + d[field] = util.convert(item[field], fieldType); + } } + this._data[id] = d; + this.length++; - this._repaintDeleteButton(dom.box); - }; - - /** - * Show the item in the DOM (when not already displayed). The items DOM will - * be created when needed. - */ - BoxItem.prototype.show = function () { - if (!this.displayed) { - this.redraw(); - } + return id; }; /** - * Hide the item from the DOM (when visible) + * 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 */ - BoxItem.prototype.hide = function () { - if (this.displayed) { - var dom = this.dom; - - if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box); - if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line); - if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot); + DataSet.prototype._getItem = function (id, types) { + var field, value; - this.displayed = false; + // get the item from the dataset + var raw = this._data[id]; + if (!raw) { + return null; } - }; - - /** - * Reposition the item horizontally - * @Override - */ - BoxItem.prototype.repositionX = function () { - var start = this.conversion.toScreen(this.data.start); - var align = this.options.align; - var left; - // calculate left position of the box - if (align == 'right') { - this.left = start - this.width; - } else if (align == 'left') { - this.left = start; + // convert the items field types + var converted = {}; + if (types) { + for (field in raw) { + if (raw.hasOwnProperty(field)) { + value = raw[field]; + converted[field] = util.convert(value, types[field]); + } + } } else { - // default or 'center' - this.left = start - this.width / 2; + // no field types specified, no converting needed + for (field in raw) { + if (raw.hasOwnProperty(field)) { + value = raw[field]; + converted[field] = value; + } + } } - - // reposition box - this.dom.box.style.left = this.left + 'px'; - - // reposition line - this.dom.line.style.left = start - this.props.line.width / 2 + 'px'; - - // reposition dot - this.dom.dot.style.left = start - this.props.dot.width / 2 + 'px'; + return converted; }; /** - * Reposition the item vertically - * @Override + * 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 */ - BoxItem.prototype.repositionY = function () { - var orientation = this.options.orientation.item; - var box = this.dom.box; - var line = this.dom.line; - var dot = this.dom.dot; - - if (orientation == 'top') { - box.style.top = (this.top || 0) + 'px'; - - line.style.top = '0'; - line.style.height = this.parent.top + this.top + 1 + 'px'; - line.style.bottom = ''; - } else { - // orientation 'bottom' - var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty - var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top; + DataSet.prototype._updateItem = function (item) { + var id = item[this._fieldId]; + if (id == undefined) { + throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')'); + } + var d = this._data[id]; + if (!d) { + // item doesn't exist + throw new Error('Cannot update item: no item with id ' + id + ' found'); + } - box.style.top = (this.parent.height - this.top - this.height || 0) + 'px'; - line.style.top = itemSetHeight - lineHeight + 'px'; - line.style.bottom = '0'; + // merge with current item + for (var field in item) { + if (item.hasOwnProperty(field)) { + var fieldType = this._type[field]; // type may be undefined + d[field] = util.convert(item[field], fieldType); + } } - dot.style.top = -this.props.dot.height / 2 + 'px'; + return id; }; - module.exports = BoxItem; + module.exports = DataSet; /***/ }, -/* 6 */ +/* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); + var util = __webpack_require__(2); + var DataSet = __webpack_require__(4); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + /** + * 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 - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + var me = this; + this.listener = function () { + me._onEvent.apply(me, arguments); + }; - var util = __webpack_require__(2); + this.setData(data); + } - var LayoutEngine = (function () { - function LayoutEngine(body) { - _classCallCheck(this, LayoutEngine); + // TODO: implement a function .config() to dynamically update things like configured filter + // and trigger changes accordingly - this.body = body; + /** + * Set a data source for the view + * @param {DataSet | DataView} data + */ + DataView.prototype.setData = function (data) { + var ids, i, len; - this.initialRandomSeed = Math.round(Math.random() * 1000000); - this.randomSeed = this.initialRandomSeed; - this.options = {}; - this.optionsBackup = {}; + if (this._data) { + // unsubscribe from current dataset + if (this._data.off) { + this._data.off('*', this.listener); + } - this.defaultOptions = { - randomSeed: undefined, - hierarchical: { - enabled: false, - levelSeparation: 150, - direction: 'UD', // UD, DU, LR, RL - sortMethod: 'hubsize' // hubsize, directed + // trigger a remove of all items in memory + ids = []; + for (var id in this._ids) { + if (this._ids.hasOwnProperty(id)) { + ids.push(id); } - }; - util.extend(this.options, this.defaultOptions); - - this.hierarchicalLevels = {}; - - this.bindEventListeners(); + } + this._ids = {}; + this.length = 0; + this._trigger('remove', { items: ids }); } - _createClass(LayoutEngine, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this = this; + this._data = data; - this.body.emitter.on('_dataChanged', function () { - _this.setupHierarchicalLayout(); - }); - this.body.emitter.on('_resetHierarchicalLayout', function () { - _this.setupHierarchicalLayout(); - }); + 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; } - }, { - key: 'setOptions', - value: function setOptions(options, allOptions) { - if (options !== undefined) { - var prevHierarchicalState = this.options.hierarchical.enabled; + this.length = ids.length; + this._trigger('add', { items: ids }); - util.mergeOptions(this.options, options, 'hierarchical'); - if (options.randomSeed !== undefined) { - this.initialRandomSeed = options.randomSeed; - } + // subscribe to new dataset + if (this._data.on) { + this._data.on('*', this.listener); + } + } + }; - if (this.options.hierarchical.enabled === true) { - // make sure the level seperation is the right way up - if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'DU') { - if (this.options.hierarchical.levelSeparation > 0) { - this.options.hierarchical.levelSeparation *= -1; - } - } else { - if (this.options.hierarchical.levelSeparation < 0) { - this.options.hierarchical.levelSeparation *= -1; - } - } + /** + * Refresh the DataView. Useful when the DataView has a filter function + * containing a variable parameter. + */ + DataView.prototype.refresh = function () { + var id; + var ids = this._data.getIds({ filter: this._options && this._options.filter }); + var newIds = {}; + var added = []; + var removed = []; - this.body.emitter.emit('_resetHierarchicalLayout'); - // because the hierarchical system needs it's own physics and smooth curve settings, we adapt the other options if needed. - return this.adaptAllOptions(allOptions); - } else { - if (prevHierarchicalState === true) { - // refresh the overridden options for nodes and edges. - this.body.emitter.emit('refresh'); - return util.deepExtend(allOptions, this.optionsBackup); - } - } + // check for additions + for (var i = 0; i < ids.length; i++) { + id = ids[i]; + newIds[id] = true; + if (!this._ids[id]) { + added.push(id); + this._ids[id] = true; + this.length++; + } + } + + // check for removals + for (id in this._ids) { + if (this._ids.hasOwnProperty(id)) { + if (!newIds[id]) { + removed.push(id); + delete this._ids[id]; + this.length--; } - return allOptions; } - }, { - key: 'adaptAllOptions', - value: function adaptAllOptions(allOptions) { - if (this.options.hierarchical.enabled === true) { - // set the physics - if (allOptions.physics === undefined || allOptions.physics === true) { - allOptions.physics = { solver: 'hierarchicalRepulsion' }; - this.optionsBackup.physics = { solver: 'barnesHut' }; - } else if (typeof allOptions.physics === 'object') { - this.optionsBackup.physics = { solver: 'barnesHut' }; - if (allOptions.physics.solver !== undefined) { - this.optionsBackup.physics = { solver: allOptions.physics.solver }; - } - allOptions.physics['solver'] = 'hierarchicalRepulsion'; - } else if (allOptions.physics !== false) { - this.optionsBackup.physics = { solver: 'barnesHut' }; - allOptions.physics['solver'] = 'hierarchicalRepulsion'; - } + } - // get the type of static smooth curve in case it is required - var type = 'horizontal'; - if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'LR') { - type = 'vertical'; - } + // trigger events + if (added.length) { + this._trigger('add', { items: added }); + } + if (removed.length) { + this._trigger('remove', { items: removed }); + } + }; - // disable smooth curves if nothing is defined. If smooth curves have been turned on, turn them into static smooth curves. - if (allOptions.edges === undefined) { - this.optionsBackup.edges = { smooth: { enabled: true, type: 'dynamic' } }; - allOptions.edges = { smooth: false }; - } else if (allOptions.edges.smooth === undefined) { - this.optionsBackup.edges = { smooth: { enabled: true, type: 'dynamic' } }; - allOptions.edges.smooth = false; - } else { - if (typeof allOptions.edges.smooth === 'boolean') { - this.optionsBackup.edges = { smooth: allOptions.edges.smooth }; - allOptions.edges.smooth = { enabled: allOptions.edges.smooth, type: type }; - } else { - // allow custom types except for dynamic - if (allOptions.edges.smooth.type !== undefined && allOptions.edges.smooth.type !== 'dynamic') { - type = allOptions.edges.smooth.type; - } + /** + * 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 args + */ + DataView.prototype.get = function (args) { + var me = this; - this.optionsBackup.edges = { - smooth: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled, - type: allOptions.edges.smooth.type === undefined ? 'dynamic' : allOptions.edges.smooth.type, - roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness - }; - allOptions.edges.smooth = { - enabled: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled, - type: type, - roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness - }; - } - } + // 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]; + } - // force all edges into static smooth curves. Only applies to edges that do not use the global options for smooth. - this.body.emitter.emit('_forceDisableDynamicCurves', type); - } - return allOptions; - } - }, { - key: 'seededRandom', - value: function seededRandom() { - var x = Math.sin(this.randomSeed++) * 10000; - return x - Math.floor(x); - } - }, { - key: 'positionInitially', - value: function positionInitially(nodesArray) { - if (this.options.hierarchical.enabled !== true) { - this.randomSeed = this.initialRandomSeed; - for (var i = 0; i < nodesArray.length; i++) { - var node = nodesArray[i]; - if (!node.isFixed() && (node.x === undefined || node.y === undefined)) { - var radius = 10 * 0.1 * nodesArray.length + 10; - var angle = 2 * Math.PI * this.seededRandom(); - if (node.options.fixed.x === false) { - node.x = radius * Math.cos(angle); - } - if (node.options.fixed.x === false) { - node.y = radius * Math.sin(angle); - } - } - } - } - } - }, { - key: 'getSeed', - value: function getSeed() { - return this.initialRandomSeed; - } - }, { - key: 'setupHierarchicalLayout', + // extend the options with the default options and provided options + var viewOptions = util.extend({}, this._options, options); - /** - * This is the main function to layout the nodes in a hierarchical way. - * It checks if the node details are supplied correctly - * - * @private - */ - value: function setupHierarchicalLayout() { - if (this.options.hierarchical.enabled === true && this.body.nodeIndices.length > 0) { - // get the size of the largest hubs and check if the user has defined a level for a node. - var node = undefined, - nodeId = undefined; - var definedLevel = false; - var undefinedLevel = false; - this.hierarchicalLevels = {}; - this.nodeSpacing = 100; + // 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); + }; + } - for (nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - node = this.body.nodes[nodeId]; - if (node.options.level !== undefined) { - definedLevel = true; - this.hierarchicalLevels[nodeId] = node.options.level; - } else { - undefinedLevel = true; - } - } - } + // build up the call to the linked data set + var getArguments = []; + if (ids != undefined) { + getArguments.push(ids); + } + getArguments.push(viewOptions); + getArguments.push(data); - // if the user defined some levels but not all, alert and run without hierarchical layout - if (undefinedLevel === true && definedLevel === true) { - throw new Error('To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.'); - return; - } else { - // setup the system to use hierarchical method. - //this._changeConstants(); + return this._data && this._data.get.apply(this._data, getArguments); + }; - // define levels if undefined by the users. Based on hubsize - if (undefinedLevel === true) { - if (this.options.hierarchical.sortMethod === 'hubsize') { - this._determineLevelsByHubsize(); - } else if (this.options.hierarchical.sortMethod === 'directed' || 'direction') { - this._determineLevelsDirected(); - } - } + /** + * 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; - // check the distribution of the nodes per level. - var distribution = this._getDistribution(); + if (this._data) { + var defaultFilter = this._options.filter; + var filter; - // place the nodes on the canvas. - this._placeNodesByHierarchy(distribution); - } + if (options && options.filter) { + if (defaultFilter) { + filter = function (item) { + return defaultFilter(item) && options.filter(item); + }; + } else { + filter = options.filter; } + } else { + filter = defaultFilter; } - }, { - key: '_placeNodesByHierarchy', - /** - * This function places the nodes on the canvas based on the hierarchial distribution. - * - * @param {Object} distribution | obtained by the function this._getDistribution() - * @private - */ - value: function _placeNodesByHierarchy(distribution) { - var nodeId = undefined, - node = undefined; - this.positionedNodes = {}; - // start placing all the level 0 nodes first. Then recursively position their branches. - for (var level in distribution) { - if (distribution.hasOwnProperty(level)) { - for (nodeId in distribution[level].nodes) { - if (distribution[level].nodes.hasOwnProperty(nodeId)) { + ids = this._data.getIds({ + filter: filter, + order: options && options.order + }); + } else { + ids = []; + } - node = distribution[level].nodes[nodeId]; + return ids; + }; - if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') { - if (node.x === undefined) { - node.x = distribution[level].distance; - } - distribution[level].distance = node.x + this.nodeSpacing; - } else { - if (node.y === undefined) { - node.y = distribution[level].distance; - } - distribution[level].distance = node.y + this.nodeSpacing; - } + /** + * 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; + }; - this.positionedNodes[nodeId] = true; - this._placeBranchNodes(node.edges, node.id, distribution, level); - } + /** + * 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 data = this._data; + var updatedData = []; + var added = []; + var updated = []; + var removed = []; + + if (ids && 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; + added.push(id); } } - } - } - }, { - key: '_getDistribution', - /** - * This function get the distribution of levels based on hubsize - * - * @returns {Object} - * @private - */ - value: function _getDistribution() { - var distribution = {}; - var nodeId = undefined, - node = undefined; + break; - // we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time. - // the fix of X is removed after the x value has been set. - for (nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - node = this.body.nodes[nodeId]; - var level = this.hierarchicalLevels[nodeId] === undefined ? 0 : this.hierarchicalLevels[nodeId]; - if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') { - node.y = this.options.hierarchical.levelSeparation * level; - node.options.fixed.y = true; + 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]) { + updated.push(id); + updatedData.push(params.data[i]); + } else { + this._ids[id] = true; + added.push(id); + } } else { - node.x = this.options.hierarchical.levelSeparation * level; - node.options.fixed.x = true; - } - if (distribution[level] === undefined) { - distribution[level] = { amount: 0, nodes: {}, distance: 0 }; + if (this._ids[id]) { + delete this._ids[id]; + removed.push(id); + } else {} } - distribution[level].amount += 1; - distribution[level].nodes[nodeId] = node; } - } - return distribution; - } - }, { - key: '_getHubSize', - /** - * Get the hubsize from all remaining unlevelled nodes. - * - * @returns {number} - * @private - */ - value: function _getHubSize() { - var hubSize = 0; - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - var node = this.body.nodes[nodeId]; - if (this.hierarchicalLevels[nodeId] === undefined) { - hubSize = node.edges.length < hubSize ? hubSize : node.edges.length; + 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]; + removed.push(id); } } - } - return hubSize; - } - }, { - key: '_determineLevelsByHubsize', - /** - * this function allocates nodes in levels based on the recursive branching from the largest hubs. - * - * @param hubsize - * @private - */ - value: function _determineLevelsByHubsize() { - var nodeId = undefined, - node = undefined; - var hubSize = 1; + break; + } - while (hubSize > 0) { - // determine hubs - hubSize = this._getHubSize(); - if (hubSize === 0) break; + this.length += added.length - removed.length; - for (nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - node = this.body.nodes[nodeId]; - if (node.edges.length === hubSize) { - this._setLevelByHubsize(0, node); - } - } - } - } + if (added.length) { + this._trigger('add', { items: added }, senderId); } - }, { - key: '_setLevelByHubsize', - - /** - * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level. - * - * @param level - * @param edges - * @param parentId - * @private - */ - value: function _setLevelByHubsize(level, node) { - if (this.hierarchicalLevels[node.id] !== undefined) return; - - var childNode = undefined; - this.hierarchicalLevels[node.id] = level; - for (var i = 0; i < node.edges.length; i++) { - if (node.edges[i].toId === node.id) { - childNode = node.edges[i].from; - } else { - childNode = node.edges[i].to; - } - this._setLevelByHubsize(level + 1, childNode); - } - } - }, { - key: '_determineLevelsDirected', - - /** - * this function allocates nodes in levels based on the direction of the edges - * - * @param hubsize - * @private - */ - value: function _determineLevelsDirected() { - var nodeId = undefined, - node = undefined; - var minLevel = 10000; - - // set first node to source - for (nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - node = this.body.nodes[nodeId]; - this._setLevelDirected(minLevel, node); - } - } - - // get the minimum level - for (nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - minLevel = this.hierarchicalLevels[nodeId] < minLevel ? this.hierarchicalLevels[nodeId] : minLevel; - } - } - - // subtract the minimum from the set so we have a range starting from 0 - for (nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - this.hierarchicalLevels[nodeId] -= minLevel; - } - } + if (updated.length) { + this._trigger('update', { items: updated, data: updatedData }, senderId); } - }, { - key: '_setLevelDirected', - - /** - * this function is called recursively to enumerate the branched of the first node and give each node a level based on edge direction - * - * @param level - * @param edges - * @param parentId - * @private - */ - value: function _setLevelDirected(level, node) { - if (this.hierarchicalLevels[node.id] !== undefined) return; - - var childNode = undefined; - this.hierarchicalLevels[node.id] = level; - - for (var i = 0; i < node.edges.length; i++) { - if (node.edges[i].toId === node.id) { - childNode = node.edges[i].from; - this._setLevelDirected(level - 1, childNode); - } else { - childNode = node.edges[i].to; - this._setLevelDirected(level + 1, childNode); - } - } + if (removed.length) { + this._trigger('remove', { items: removed }, senderId); } - }, { - key: '_placeBranchNodes', - - /** - * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes - * on a X position that ensures there will be no overlap. - * - * @param edges - * @param parentId - * @param distribution - * @param parentLevel - * @private - */ - value: function _placeBranchNodes(edges, parentId, distribution, parentLevel) { - for (var i = 0; i < edges.length; i++) { - var childNode = undefined; - var parentNode = undefined; - if (edges[i].toId === parentId) { - childNode = edges[i].from; - parentNode = edges[i].to; - } else { - childNode = edges[i].to; - parentNode = edges[i].from; - } - var childNodeLevel = this.hierarchicalLevels[childNode.id]; + } + }; - if (this.positionedNodes[childNode.id] === undefined) { - // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here. - if (childNodeLevel > parentLevel) { - if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') { - if (childNode.x === undefined) { - childNode.x = Math.max(distribution[childNodeLevel].distance, parentNode.x); - } - distribution[childNodeLevel].distance = childNode.x + this.nodeSpacing; - this.positionedNodes[childNode.id] = true; - } else { - if (childNode.y === undefined) { - childNode.y = Math.max(distribution[childNodeLevel].distance, parentNode.y); - } - distribution[childNodeLevel].distance = childNode.y + this.nodeSpacing; - } - this.positionedNodes[childNode.id] = true; + // copy subscription functionality from DataSet + DataView.prototype.on = DataSet.prototype.on; + DataView.prototype.off = DataSet.prototype.off; + DataView.prototype._trigger = DataSet.prototype._trigger; - if (childNode.edges.length > 1) { - this._placeBranchNodes(childNode.edges, childNode.id, distribution, childNodeLevel); - } - } - } - } - } - }]); + // 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; - return LayoutEngine; - })(); + module.exports = DataView; - exports['default'] = LayoutEngine; - module.exports = exports['default']; + // nothing interesting for me :-( /***/ }, -/* 7 */ +/* 6 */ /***/ function(module, exports, __webpack_require__) { + /** + * 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 + */ 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); + function Queue(options) { + // options + this.delay = null; + this.max = Infinity; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // properties + this._queue = []; + this._timeout = null; + this._extended = null; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + this.setOptions(options); + } - var util = __webpack_require__(2); - var Hammer = __webpack_require__(13); - var hammerUtil = __webpack_require__(38); + /** + * 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. + * @param options + */ + 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(); + }; /** - * clears the toolbar div element of children - * - * @private + * 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); - var ManipulationSystem = (function () { - function ManipulationSystem(body, canvas, selectionHandler) { - var _this = this; + if (object.flush !== undefined) { + throw new Error('Target object already has a property flush'); + } + object.flush = function () { + queue.flush(); + }; - _classCallCheck(this, ManipulationSystem); + var methods = [{ + name: 'flush', + original: undefined + }]; - this.body = body; - this.canvas = canvas; - this.selectionHandler = selectionHandler; + 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); + } + } - this.editMode = false; - this.manipulationDiv = undefined; - this.editModeDiv = undefined; - this.closeDiv = undefined; + queue._extended = { + object: object, + methods: methods + }; - this.manipulationHammers = []; - this.temporaryUIFunctions = {}; - this.temporaryEventFunctions = []; + return queue; + }; - this.touchTime = 0; - this.temporaryIds = { nodes: [], edges: [] }; - this.guiEnabled = false; - this.inMode = false; - this.selectedControlNode = undefined; + /** + * 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(); - this.options = {}; - this.defaultOptions = { - enabled: false, - initiallyActive: false, - addNode: true, - addEdge: true, - editNode: undefined, - editEdge: true, - deleteNode: true, - deleteEdge: true, - controlNodeStyle: { - shape: 'dot', - size: 6, - color: { background: '#ff0000', border: '#3c3c3c', highlight: { background: '#07f968', border: '#3c3c3c' } }, - borderWidth: 2, - borderWidthSelected: 2 + 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]; } - }; - util.extend(this.options, this.defaultOptions); - - this.body.emitter.on('destroy', function () { - _this._clean(); - }); - this.body.emitter.on('_dataChanged', this._restore.bind(this)); - this.body.emitter.on('_resetData', this._restore.bind(this)); + } + this._extended = null; } + }; - _createClass(ManipulationSystem, [{ - key: '_restore', + /** + * 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'); + } - /** - * If something changes in the data during editing, switch back to the initial datamanipulation state and close all edit modes. - * @private - */ - value: function _restore() { - if (this.inMode !== false) { - if (this.options.initiallyActive === true) { - this.enableEditMode(); - } else { - this.disableEditMode(); - } - } + object[method] = function () { + // create an Array with the arguments + var args = []; + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; } - }, { - key: 'setOptions', - /** - * Set the Options - * @param options - */ - value: function setOptions(options, allOptions, globalOptions) { - if (allOptions !== undefined) { - if (allOptions.locale !== undefined) { - this.options.locale = allOptions.locale; - } else { - this.options.locale = globalOptions.locale; - } - if (allOptions.locales !== undefined) { - this.options.locales = allOptions.locales; - } else { - this.options.locales = globalOptions.locales; - } - } + // add this call to the queue + me.queue({ + args: args, + fn: original, + context: this + }); + }; + }; - if (options !== undefined) { - if (typeof options === 'boolean') { - this.options.enabled = options; - } else { - this.options.enabled = true; - util.deepExtend(this.options, options); - } - if (this.options.initiallyActive === true) { - this.editMode = true; - } - this._setup(); - } - } - }, { - key: 'toggleEditMode', + /** + * 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); + } - /** - * Enable or disable edit-mode. Draws the DOM required and cleans up after itself. - * - * @private - */ - value: function toggleEditMode() { - if (this.editMode === true) { - this.disableEditMode(); - } else { - this.enableEditMode(); - } - } - }, { - key: 'enableEditMode', - value: function enableEditMode() { - this.editMode = true; + this._flushIfNeeded(); + }; - this._clean(); - if (this.guiEnabled === true) { - this.manipulationDiv.style.display = 'block'; - this.closeDiv.style.display = 'block'; - this.editModeDiv.style.display = 'none'; - this.showManipulatorToolbar(); - } - } - }, { - key: 'disableEditMode', - value: function disableEditMode() { - this.editMode = false; + /** + * 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(); + } - this._clean(); - if (this.guiEnabled === true) { - this.manipulationDiv.style.display = 'none'; - this.closeDiv.style.display = 'none'; - this.editModeDiv.style.display = 'block'; - this._createEditButton(); - } - } - }, { - key: 'showManipulatorToolbar', + // 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); + } + }; - /** - * Creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar. - * - * @private - */ - value: function showManipulatorToolbar() { - // restore the state of any bound functions or events, remove control nodes, restore physics - this._clean(); + /** + * 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 || []); + } + }; - // reset global letiables - this.manipulationDOM = {}; + module.exports = Queue; - // if the gui is enabled, draw all elements. - if (this.guiEnabled === true) { - // a _restore will hide these menus - this.editMode = true; - this.manipulationDiv.style.display = 'block'; - this.closeDiv.style.display = 'block'; +/***/ }, +/* 7 */ +/***/ function(module, exports, __webpack_require__) { - var selectedNodeCount = this.selectionHandler._getSelectedNodeCount(); - var selectedEdgeCount = this.selectionHandler._getSelectedEdgeCount(); - var selectedTotalCount = selectedNodeCount + selectedEdgeCount; - var locale = this.options.locales[this.options.locale]; - var needSeperator = false; + 'use strict'; - if (this.options.addNode !== false) { - this._createAddNodeButton(locale); - needSeperator = true; - } - if (this.options.addEdge !== false) { - if (needSeperator === true) { - this._createSeperator(1); - } else { - needSeperator = true; - } - this._createAddEdgeButton(locale); - } + var Emitter = __webpack_require__(43); + var DataSet = __webpack_require__(4); + var DataView = __webpack_require__(5); + var util = __webpack_require__(2); + var Point3d = __webpack_require__(11); + var Point2d = __webpack_require__(10); + var Camera = __webpack_require__(8); + var Filter = __webpack_require__(9); + var Slider = __webpack_require__(12); + var StepNumber = __webpack_require__(13); - if (selectedNodeCount === 1 && typeof this.options.editNode === 'function') { - if (needSeperator === true) { - this._createSeperator(2); - } else { - needSeperator = true; - } - this._createEditNodeButton(locale); - } else if (selectedEdgeCount === 1 && selectedNodeCount === 0 && this.options.editEdge !== false) { - if (needSeperator === true) { - this._createSeperator(3); - } else { - needSeperator = true; - } - this._createEditEdgeButton(locale); - } - - // remove buttons - if (selectedTotalCount !== 0) { - if (selectedNodeCount === 1 && this.options.deleteNode !== false) { - if (needSeperator === true) { - this._createSeperator(4); - } - this._createDeleteButton(locale); - } else if (selectedNodeCount === 0 && this.options.deleteEdge !== false) { - if (needSeperator === true) { - this._createSeperator(4); - } - this._createDeleteButton(locale); - } - } + /** + * @constructor Graph3d + * Graph3d displays data in 3d. + * + * Graph3d is developed in javascript as a Google Visualization Chart. + * + * @param {Element} container The DOM element in which the Graph3d will + * be created. Normally a div element. + * @param {DataSet | DataView | Array} [data] + * @param {Object} [options] + */ + function Graph3d(container, data, options) { + if (!(this instanceof Graph3d)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } - // bind the close button - this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); + // create variables and set default values + this.containerElement = container; + this.width = '400px'; + this.height = '400px'; + this.margin = 10; // px + this.defaultXCenter = '55%'; + this.defaultYCenter = '50%'; - // refresh this bar based on what has been selected - this._temporaryBindEvent('select', this.showManipulatorToolbar.bind(this)); - } + this.xLabel = 'x'; + this.yLabel = 'y'; + this.zLabel = 'z'; - // redraw to show any possible changes - this.body.emitter.emit('_redraw'); - } - }, { - key: 'addNodeMode', + var passValueFn = function passValueFn(v) { + return v; + }; + this.xValueLabel = passValueFn; + this.yValueLabel = passValueFn; + this.zValueLabel = passValueFn; - /** - * Create the toolbar for adding Nodes - * - * @private - */ - value: function addNodeMode() { - // when using the gui, enable edit mode if it wasnt already. - if (this.editMode !== true) { - this.enableEditMode(); - } + this.filterLabel = 'time'; + this.legendLabel = 'value'; - // restore the state of any bound functions or events, remove control nodes, restore physics - this._clean(); + this.style = Graph3d.STYLE.DOT; + this.showPerspective = true; + this.showGrid = true; + this.keepAspectRatio = true; + this.showShadow = false; + this.showGrayBottom = false; // TODO: this does not work correctly + this.showTooltip = false; + this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube' - this.inMode = 'addNode'; - if (this.guiEnabled === true) { - var locale = this.options.locales[this.options.locale]; - this.manipulationDOM = {}; - this._createBackButton(locale); - this._createSeperator(); - this._createDescription(locale['addDescription'] || this.options.locales['en']['addDescription']); + this.animationInterval = 1000; // milliseconds + this.animationPreload = false; - // bind the close button - this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); - } + this.camera = new Camera(); + this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window? - this._temporaryBindEvent('click', this._performAddNode.bind(this)); - } - }, { - key: 'editNode', + this.dataTable = null; // The original data table + this.dataPoints = null; // The table with point objects - /** - * call the bound function to handle the editing of the node. The node has to be selected. - * - * @private - */ - value: function editNode() { - var _this2 = this; + // the column indexes + this.colX = undefined; + this.colY = undefined; + this.colZ = undefined; + this.colValue = undefined; + this.colFilter = undefined; - // when using the gui, enable edit mode if it wasnt already. - if (this.editMode !== true) { - this.enableEditMode(); - } + this.xMin = 0; + this.xStep = undefined; // auto by default + this.xMax = 1; + this.yMin = 0; + this.yStep = undefined; // auto by default + this.yMax = 1; + this.zMin = 0; + this.zStep = undefined; // auto by default + this.zMax = 1; + this.valueMin = 0; + this.valueMax = 1; + this.xBarWidth = 1; + this.yBarWidth = 1; + // TODO: customize axis range - // restore the state of any bound functions or events, remove control nodes, restore physics - this._clean(); + // constants + this.colorAxis = '#4D4D4D'; + this.colorGrid = '#D3D3D3'; + this.colorDot = '#7DC1FF'; + this.colorDotBorder = '#3267D2'; - this.inMode = 'editNode'; - if (typeof this.options.editNode === 'function') { - var node = this.selectionHandler._getSelectedNode(); - if (node.isCluster !== true) { - var data = util.deepExtend({}, node.options, true); - data.x = node.x; - data.y = node.y; + // create a frame and canvas + this.create(); - if (this.options.editNode.length === 2) { - this.options.editNode(data, function (finalizedData) { - if (finalizedData !== null && finalizedData !== undefined && _this2.inMode === 'editNode') { - // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { - _this2.body.data.nodes.update(finalizedData); - } - _this2.showManipulatorToolbar(); - }); - } else { - throw new Error('The function for edit does not support two arguments (data, callback)'); - } - } else { - alert(this.options.locales[this.options.locale]['editClusterError'] || this.options.locales['en']['editClusterError']); - } - } else { - throw new Error('No function has been configured to handle the editing of nodes.'); - } - } - }, { - key: 'addEdgeMode', + // apply options (also when undefined) + this.setOptions(options); - /** - * create the toolbar to connect nodes - * - * @private - */ - value: function addEdgeMode() { - // when using the gui, enable edit mode if it wasnt already. - if (this.editMode !== true) { - this.enableEditMode(); - } + // apply data + if (data) { + this.setData(data); + } + } - // restore the state of any bound functions or events, remove control nodes, restore physics - this._clean(); + // Extend Graph3d with an Emitter mixin + Emitter(Graph3d.prototype); - this.inMode = 'addEdge'; - if (this.guiEnabled === true) { - var locale = this.options.locales[this.options.locale]; - this.manipulationDOM = {}; - this._createBackButton(locale); - this._createSeperator(); - this._createDescription(locale['edgeDescription'] || this.options.locales['en']['edgeDescription']); + /** + * Calculate the scaling values, dependent on the range in x, y, and z direction + */ + Graph3d.prototype._setScale = function () { + this.scale = new Point3d(1 / (this.xMax - this.xMin), 1 / (this.yMax - this.yMin), 1 / (this.zMax - this.zMin)); - // bind the close button - this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); - } + // keep aspect ration between x and y scale if desired + if (this.keepAspectRatio) { + if (this.scale.x < this.scale.y) { + //noinspection JSSuspiciousNameCombination + this.scale.y = this.scale.x; + } else { + //noinspection JSSuspiciousNameCombination + this.scale.x = this.scale.y; + } + } - // temporarily overload functions - this._temporaryBindUI('onTouch', this._handleConnect.bind(this)); - this._temporaryBindUI('onDragEnd', this._finishConnect.bind(this)); - this._temporaryBindUI('onDrag', this._dragControlNode.bind(this)); - this._temporaryBindUI('onRelease', this._finishConnect.bind(this)); + // scale the vertical axis + this.scale.z *= this.verticalRatio; + // TODO: can this be automated? verticalRatio? - this._temporaryBindUI('onDragStart', function () {}); - this._temporaryBindUI('onHold', function () {}); - } - }, { - key: 'editEdgeMode', + // determine scale for (optional) value + this.scale.value = 1 / (this.valueMax - this.valueMin); - /** - * create the toolbar to edit edges - * - * @private - */ - value: function editEdgeMode() { - // when using the gui, enable edit mode if it wasnt already. - if (this.editMode !== true) { - this.enableEditMode(); - } + // position the camera arm + var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x; + var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y; + var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z; + this.camera.setArmLocation(xCenter, yCenter, zCenter); + }; - // restore the state of any bound functions or events, remove control nodes, restore physics - this._clean(); + /** + * Convert a 3D location to a 2D location on screen + * http://en.wikipedia.org/wiki/3D_projection + * @param {Point3d} point3d A 3D point with parameters x, y, z + * @return {Point2d} point2d A 2D point with parameters x, y + */ + Graph3d.prototype._convert3Dto2D = function (point3d) { + var translation = this._convertPointToTranslation(point3d); + return this._convertTranslationToScreen(translation); + }; - this.inMode = 'editEdge'; - if (this.guiEnabled === true) { - var locale = this.options.locales[this.options.locale]; - this.manipulationDOM = {}; - this._createBackButton(locale); - this._createSeperator(); - this._createDescription(locale['editEdgeDescription'] || this.options.locales['en']['editEdgeDescription']); + /** + * Convert a 3D location its translation seen from the camera + * http://en.wikipedia.org/wiki/3D_projection + * @param {Point3d} point3d A 3D point with parameters x, y, z + * @return {Point3d} translation A 3D point with parameters x, y, z This is + * the translation of the point, seen from the + * camera + */ + Graph3d.prototype._convertPointToTranslation = function (point3d) { + var ax = point3d.x * this.scale.x, + ay = point3d.y * this.scale.y, + az = point3d.z * this.scale.z, + cx = this.camera.getCameraLocation().x, + cy = this.camera.getCameraLocation().y, + cz = this.camera.getCameraLocation().z, - // bind the close button - this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); - } + // calculate angles + sinTx = Math.sin(this.camera.getCameraRotation().x), + cosTx = Math.cos(this.camera.getCameraRotation().x), + sinTy = Math.sin(this.camera.getCameraRotation().y), + cosTy = Math.cos(this.camera.getCameraRotation().y), + sinTz = Math.sin(this.camera.getCameraRotation().z), + cosTz = Math.cos(this.camera.getCameraRotation().z), - this.edgeBeingEditedId = this.selectionHandler.getSelectedEdges()[0]; - var edge = this.body.edges[this.edgeBeingEditedId]; + // calculate translation + dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz), + dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax - cx)), + dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax - cx)); - // create control nodes - var controlNodeFrom = this._getNewTargetNode(edge.from.x, edge.from.y); - var controlNodeTo = this._getNewTargetNode(edge.to.x, edge.to.y); + return new Point3d(dx, dy, dz); + }; - this.temporaryIds.nodes.push(controlNodeFrom.id); - this.temporaryIds.nodes.push(controlNodeTo.id); + /** + * Convert a translation point to a point on the screen + * @param {Point3d} translation A 3D point with parameters x, y, z This is + * the translation of the point, seen from the + * camera + * @return {Point2d} point2d A 2D point with parameters x, y + */ + Graph3d.prototype._convertTranslationToScreen = function (translation) { + var ex = this.eye.x, + ey = this.eye.y, + ez = this.eye.z, + dx = translation.x, + dy = translation.y, + dz = translation.z; - this.body.nodes[controlNodeFrom.id] = controlNodeFrom; - this.body.nodeIndices.push(controlNodeFrom.id); - this.body.nodes[controlNodeTo.id] = controlNodeTo; - this.body.nodeIndices.push(controlNodeTo.id); + // calculate position on screen from translation + var bx; + var by; + if (this.showPerspective) { + bx = (dx - ex) * (ez / dz); + by = (dy - ey) * (ez / dz); + } else { + bx = dx * -(ez / this.camera.getArmLength()); + by = dy * -(ez / this.camera.getArmLength()); + } - // temporarily overload UI functions, cleaned up automatically because of _temporaryBindUI - this._temporaryBindUI('onTouch', this._controlNodeTouch.bind(this)); // used to get the position - this._temporaryBindUI('onTap', function () {}); // disabled - this._temporaryBindUI('onHold', function () {}); // disabled - this._temporaryBindUI('onDragStart', this._controlNodeDragStart.bind(this)); // used to select control node - this._temporaryBindUI('onDrag', this._controlNodeDrag.bind(this)); // used to drag control node - this._temporaryBindUI('onDragEnd', this._controlNodeDragEnd.bind(this)); // used to connect or revert control nodes - this._temporaryBindUI('onMouseMove', function () {}); // disabled + // shift and scale the point to the center of the screen + // use the width of the graph to scale both horizontally and vertically. + return new Point2d(this.xcenter + bx * this.frame.canvas.clientWidth, this.ycenter - by * this.frame.canvas.clientWidth); + }; - // create function to position control nodes correctly on movement - // automatically cleaned up because we use the temporary bind - this._temporaryBindEvent('beforeDrawing', function (ctx) { - var positions = edge.edgeType.findBorderPositions(ctx); - if (controlNodeFrom.selected === false) { - controlNodeFrom.x = positions.from.x; - controlNodeFrom.y = positions.from.y; - } - if (controlNodeTo.selected === false) { - controlNodeTo.x = positions.to.x; - controlNodeTo.y = positions.to.y; - } - }); + /** + * Set the background styling for the graph + * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor + */ + Graph3d.prototype._setBackgroundColor = function (backgroundColor) { + var fill = 'white'; + var stroke = 'gray'; + var strokeWidth = 1; - this.body.emitter.emit('_redraw'); - } - }, { - key: 'deleteSelected', + if (typeof backgroundColor === 'string') { + fill = backgroundColor; + stroke = 'none'; + strokeWidth = 0; + } else if (typeof backgroundColor === 'object') { + if (backgroundColor.fill !== undefined) fill = backgroundColor.fill; + if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke; + if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth; + } else if (backgroundColor === undefined) {} else { + throw 'Unsupported type of backgroundColor'; + } - /** - * delete everything in the selection - * - * @private - */ - value: function deleteSelected() { - var _this3 = this; + this.frame.style.backgroundColor = fill; + this.frame.style.borderColor = stroke; + this.frame.style.borderWidth = strokeWidth + 'px'; + this.frame.style.borderStyle = 'solid'; + }; - // when using the gui, enable edit mode if it wasnt already. - if (this.editMode !== true) { - this.enableEditMode(); - } + /// enumerate the available styles + Graph3d.STYLE = { + BAR: 0, + BARCOLOR: 1, + BARSIZE: 2, + DOT: 3, + DOTLINE: 4, + DOTCOLOR: 5, + DOTSIZE: 6, + GRID: 7, + LINE: 8, + SURFACE: 9 + }; - // restore the state of any bound functions or events, remove control nodes, restore physics - this._clean(); + /** + * 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 + */ + Graph3d.prototype._getStyleNumber = function (styleName) { + switch (styleName) { + case 'dot': + return Graph3d.STYLE.DOT; + case 'dot-line': + return Graph3d.STYLE.DOTLINE; + case 'dot-color': + return Graph3d.STYLE.DOTCOLOR; + case 'dot-size': + return Graph3d.STYLE.DOTSIZE; + case 'line': + return Graph3d.STYLE.LINE; + case 'grid': + return Graph3d.STYLE.GRID; + case 'surface': + return Graph3d.STYLE.SURFACE; + case 'bar': + return Graph3d.STYLE.BAR; + case 'bar-color': + return Graph3d.STYLE.BARCOLOR; + case 'bar-size': + return Graph3d.STYLE.BARSIZE; + } - this.inMode = 'delete'; - var selectedNodes = this.selectionHandler.getSelectedNodes(); - var selectedEdges = this.selectionHandler.getSelectedEdges(); - var deleteFunction = undefined; - if (selectedNodes.length > 0) { - for (var i = 0; i < selectedNodes.length; i++) { - if (this.body.nodes[selectedNodes[i]].isCluster === true) { - alert(this.options.locales[this.options.locale]['deleteClusterError'] || this.options.locales['en']['deleteClusterError']); - return; - } - } + return -1; + }; - if (typeof this.options.deleteNode === 'function') { - deleteFunction = this.options.deleteNode; - } - } else if (selectedEdges.length > 0) { - if (typeof this.options.deleteEdge === 'function') { - deleteFunction = this.options.deleteEdge; - } - } + /** + * Determine the indexes of the data columns, based on the given style and data + * @param {DataSet} data + * @param {Number} style + */ + Graph3d.prototype._determineColumnIndexes = function (data, style) { + if (this.style === Graph3d.STYLE.DOT || this.style === Graph3d.STYLE.DOTLINE || this.style === Graph3d.STYLE.LINE || this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE || this.style === Graph3d.STYLE.BAR) { + // 3 columns expected, and optionally a 4th with filter values + this.colX = 0; + this.colY = 1; + this.colZ = 2; + this.colValue = undefined; - if (typeof deleteFunction === 'function') { - var data = { nodes: selectedNodes, edges: selectedEdges }; - if (deleteFunction.length === 2) { - deleteFunction(data, function (finalizedData) { - if (finalizedData !== null && finalizedData !== undefined && _this3.inMode === 'delete') { - // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { - _this3.body.data.edges.remove(finalizedData.edges); - _this3.body.data.nodes.remove(finalizedData.nodes); - _this3.body.emitter.emit('startSimulation'); - _this3.showManipulatorToolbar(); - } - }); - } else { - throw new Error('The function for delete does not support two arguments (data, callback)'); - } - } else { - this.body.data.edges.remove(selectedEdges); - this.body.data.nodes.remove(selectedNodes); - this.body.emitter.emit('startSimulation'); - this.showManipulatorToolbar(); - } + if (data.getNumberOfColumns() > 3) { + this.colFilter = 3; } - }, { - key: '_setup', + } else if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { + // 4 columns expected, and optionally a 5th with filter values + this.colX = 0; + this.colY = 1; + this.colZ = 2; + this.colValue = 3; - //********************************************** PRIVATE ***************************************// + if (data.getNumberOfColumns() > 4) { + this.colFilter = 4; + } + } else { + throw 'Unknown style "' + this.style + '"'; + } + }; - /** - * draw or remove the DOM - * @private - */ - value: function _setup() { - if (this.options.enabled === true) { - // Enable the GUI - this.guiEnabled = true; + Graph3d.prototype.getNumberOfRows = function (data) { + return data.length; + }; - this._createWrappers(); - if (this.editMode === false) { - this._createEditButton(); - } else { - this.showManipulatorToolbar(); - } - } else { - this._removeManipulationDOM(); + Graph3d.prototype.getNumberOfColumns = function (data) { + var counter = 0; + for (var column in data[0]) { + if (data[0].hasOwnProperty(column)) { + counter++; + } + } + return counter; + }; - // disable the gui - this.guiEnabled = false; - } + Graph3d.prototype.getDistinctValues = function (data, column) { + var distinctValues = []; + for (var i = 0; i < data.length; i++) { + if (distinctValues.indexOf(data[i][column]) == -1) { + distinctValues.push(data[i][column]); } - }, { - key: '_createWrappers', + } + return distinctValues; + }; - /** - * create the div overlays that contain the DOM - * @private - */ - value: function _createWrappers() { - // load the manipulator HTML elements. All styling done in css. - if (this.manipulationDiv === undefined) { - this.manipulationDiv = document.createElement('div'); - this.manipulationDiv.className = 'vis-manipulation'; - if (this.editMode === true) { - this.manipulationDiv.style.display = 'block'; - } else { - this.manipulationDiv.style.display = 'none'; - } - this.canvas.frame.appendChild(this.manipulationDiv); - } + Graph3d.prototype.getColumnRange = function (data, column) { + var minMax = { min: data[0][column], max: data[0][column] }; + for (var i = 0; i < data.length; i++) { + if (minMax.min > data[i][column]) { + minMax.min = data[i][column]; + } + if (minMax.max < data[i][column]) { + minMax.max = data[i][column]; + } + } + return minMax; + }; - // container for the edit button. - if (this.editModeDiv === undefined) { - this.editModeDiv = document.createElement('div'); - this.editModeDiv.className = 'vis-edit-mode'; - if (this.editMode === true) { - this.editModeDiv.style.display = 'none'; - } else { - this.editModeDiv.style.display = 'block'; - } - this.canvas.frame.appendChild(this.editModeDiv); - } + /** + * Initialize the data from the data table. Calculate minimum and maximum values + * and column index values + * @param {Array | DataSet | DataView} rawData The data containing the items for the Graph. + * @param {Number} style Style Number + */ + Graph3d.prototype._dataInitialize = function (rawData, style) { + var me = this; - // container for the close div button - if (this.closeDiv === undefined) { - this.closeDiv = document.createElement('div'); - this.closeDiv.className = 'vis-close'; - this.closeDiv.style.display = this.manipulationDiv.style.display; - this.canvas.frame.appendChild(this.closeDiv); - } - } - }, { - key: '_getNewTargetNode', + // unsubscribe from the dataTable + if (this.dataSet) { + this.dataSet.off('*', this._onChange); + } - /** - * generate a new target node. Used for creating new edges and editing edges - * @param x - * @param y - * @returns {*} - * @private - */ - value: function _getNewTargetNode(x, y) { - var controlNodeStyle = util.deepExtend({}, this.options.controlNodeStyle); + if (rawData === undefined) return; - controlNodeStyle.id = 'targetNode' + util.randomUUID(); - controlNodeStyle.hidden = false; - controlNodeStyle.physics = false; - controlNodeStyle.x = x; - controlNodeStyle.y = y; + if (Array.isArray(rawData)) { + rawData = new DataSet(rawData); + } - return this.body.functions.createNode(controlNodeStyle); - } - }, { - key: '_createEditButton', + var data; + if (rawData instanceof DataSet || rawData instanceof DataView) { + data = rawData.get(); + } else { + throw new Error('Array, DataSet, or DataView expected'); + } - /** - * Create the edit button - */ - value: function _createEditButton() { - // restore everything to it's original state (if applicable) - this._clean(); + if (data.length == 0) return; - // reset the manipulationDOM - this.manipulationDOM = {}; + this.dataSet = rawData; + this.dataTable = data; - // empty the editModeDiv - util.recursiveDOMDelete(this.editModeDiv); + // subscribe to changes in the dataset + this._onChange = function () { + me.setData(me.dataSet); + }; + this.dataSet.on('*', this._onChange); - // create the contents for the editMode button - var locale = this.options.locales[this.options.locale]; - var button = this._createButton('editMode', 'vis-button vis-edit vis-edit-mode', locale['edit'] || this.options.locales['en']['edit']); - this.editModeDiv.appendChild(button); + // _determineColumnIndexes + // getNumberOfRows (points) + // getNumberOfColumns (x,y,z,v,t,t1,t2...) + // getDistinctValues (unique values?) + // getColumnRange - // bind a hammer listener to the button, calling the function toggleEditMode. - this._bindHammerToDiv(button, this.toggleEditMode.bind(this)); + // determine the location of x,y,z,value,filter columns + this.colX = 'x'; + this.colY = 'y'; + this.colZ = 'z'; + this.colValue = 'style'; + this.colFilter = 'filter'; + + // check if a filter column is provided + if (data[0].hasOwnProperty('filter')) { + if (this.dataFilter === undefined) { + this.dataFilter = new Filter(rawData, this.colFilter, this); + this.dataFilter.setOnLoadCallback(function () { + me.redraw(); + }); } - }, { - key: '_clean', + } - /** - * this function cleans up after everything this module does. Temporary elements, functions and events are removed, physics restored, hammers removed. - * @private - */ - value: function _clean() { - // not in mode - this.inMode = false; + var withBars = this.style == Graph3d.STYLE.BAR || this.style == Graph3d.STYLE.BARCOLOR || this.style == Graph3d.STYLE.BARSIZE; - // _clean the divs - if (this.guiEnabled === true) { - util.recursiveDOMDelete(this.editModeDiv); - util.recursiveDOMDelete(this.manipulationDiv); + // determine barWidth from data + if (withBars) { + if (this.defaultXBarWidth !== undefined) { + this.xBarWidth = this.defaultXBarWidth; + } else { + var dataX = this.getDistinctValues(data, this.colX); + this.xBarWidth = dataX[1] - dataX[0] || 1; + } - // removes all the bindings and overloads - this._cleanManipulatorHammers(); - } + if (this.defaultYBarWidth !== undefined) { + this.yBarWidth = this.defaultYBarWidth; + } else { + var dataY = this.getDistinctValues(data, this.colY); + this.yBarWidth = dataY[1] - dataY[0] || 1; + } + } - // remove temporary nodes and edges - this._cleanupTemporaryNodesAndEdges(); + // calculate minimums and maximums + var xRange = this.getColumnRange(data, this.colX); + if (withBars) { + xRange.min -= this.xBarWidth / 2; + xRange.max += this.xBarWidth / 2; + } + this.xMin = this.defaultXMin !== undefined ? this.defaultXMin : xRange.min; + this.xMax = this.defaultXMax !== undefined ? this.defaultXMax : xRange.max; + if (this.xMax <= this.xMin) this.xMax = this.xMin + 1; + this.xStep = this.defaultXStep !== undefined ? this.defaultXStep : (this.xMax - this.xMin) / 5; - // restore overloaded UI functions - this._unbindTemporaryUIs(); + var yRange = this.getColumnRange(data, this.colY); + if (withBars) { + yRange.min -= this.yBarWidth / 2; + yRange.max += this.yBarWidth / 2; + } + this.yMin = this.defaultYMin !== undefined ? this.defaultYMin : yRange.min; + this.yMax = this.defaultYMax !== undefined ? this.defaultYMax : yRange.max; + if (this.yMax <= this.yMin) this.yMax = this.yMin + 1; + this.yStep = this.defaultYStep !== undefined ? this.defaultYStep : (this.yMax - this.yMin) / 5; - // remove the temporaryEventFunctions - this._unbindTemporaryEvents(); + var zRange = this.getColumnRange(data, this.colZ); + this.zMin = this.defaultZMin !== undefined ? this.defaultZMin : zRange.min; + this.zMax = this.defaultZMax !== undefined ? this.defaultZMax : zRange.max; + if (this.zMax <= this.zMin) this.zMax = this.zMin + 1; + this.zStep = this.defaultZStep !== undefined ? this.defaultZStep : (this.zMax - this.zMin) / 5; - // restore the physics if required - this.body.emitter.emit('restorePhysics'); - } - }, { - key: '_cleanManipulatorHammers', + if (this.colValue !== undefined) { + var valueRange = this.getColumnRange(data, this.colValue); + this.valueMin = this.defaultValueMin !== undefined ? this.defaultValueMin : valueRange.min; + this.valueMax = this.defaultValueMax !== undefined ? this.defaultValueMax : valueRange.max; + if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1; + } - /** - * Each dom element has it's own hammer. They are stored in this.manipulationHammers. This cleans them up. - * @private - */ - value: function _cleanManipulatorHammers() { - // _clean hammer bindings - if (this.manipulationHammers.length != 0) { - for (var i = 0; i < this.manipulationHammers.length; i++) { - this.manipulationHammers[i].destroy(); - } - this.manipulationHammers = []; - } - } - }, { - key: '_removeManipulationDOM', + // set the scale dependent on the ranges. + this._setScale(); + }; - /** - * Remove all DOM elements created by this module. - * @private - */ - value: function _removeManipulationDOM() { - // removes all the bindings and overloads - this._clean(); + /** + * Filter the data based on the current filter + * @param {Array} data + * @return {Array} dataPoints Array with point objects which can be drawn on screen + */ + Graph3d.prototype._getDataPoints = function (data) { + // TODO: store the created matrix dataPoints in the filters instead of reloading each time + var x, y, i, z, obj, point; - // empty the manipulation divs - util.recursiveDOMDelete(this.manipulationDiv); - util.recursiveDOMDelete(this.editModeDiv); - util.recursiveDOMDelete(this.closeDiv); + var dataPoints = []; - // remove the manipulation divs - if (this.manipulationDiv) { - this.canvas.frame.removeChild(this.manipulationDiv); - } - if (this.editModeDiv) { - this.canvas.frame.removeChild(this.editModeDiv); + if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { + // copy all values from the google data table to a matrix + // the provided values are supposed to form a grid of (x,y) positions + + // create two lists with all present x and y values + var dataX = []; + var dataY = []; + for (i = 0; i < this.getNumberOfRows(data); i++) { + x = data[i][this.colX] || 0; + y = data[i][this.colY] || 0; + + if (dataX.indexOf(x) === -1) { + dataX.push(x); } - if (this.closeDiv) { - this.canvas.frame.removeChild(this.manipulationDiv); + if (dataY.indexOf(y) === -1) { + dataY.push(y); } - - // set the references to undefined - this.manipulationDiv = undefined; - this.editModeDiv = undefined; - this.closeDiv = undefined; } - }, { - key: '_createSeperator', - /** - * create a seperator line. the index is to differentiate in the manipulation dom - * @param index - * @private - */ - value: function _createSeperator() { - var index = arguments[0] === undefined ? 1 : arguments[0]; + var sortNumber = function sortNumber(a, b) { + return a - b; + }; + dataX.sort(sortNumber); + dataY.sort(sortNumber); - this.manipulationDOM['seperatorLineDiv' + index] = document.createElement('div'); - this.manipulationDOM['seperatorLineDiv' + index].className = 'vis-separator-line'; - this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv' + index]); - } - }, { - key: '_createAddNodeButton', + // create a grid, a 2d matrix, with all values. + var dataMatrix = []; // temporary data matrix + for (i = 0; i < data.length; i++) { + x = data[i][this.colX] || 0; + y = data[i][this.colY] || 0; + z = data[i][this.colZ] || 0; - // ---------------------- DOM functions for buttons --------------------------// + var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer + var yIndex = dataY.indexOf(y); - value: function _createAddNodeButton(locale) { - var button = this._createButton('addNode', 'vis-button vis-add', locale['addNode'] || this.options.locales['en']['addNode']); - this.manipulationDiv.appendChild(button); - this._bindHammerToDiv(button, this.addNodeMode.bind(this)); - } - }, { - key: '_createAddEdgeButton', - value: function _createAddEdgeButton(locale) { - var button = this._createButton('addEdge', 'vis-button vis-connect', locale['addEdge'] || this.options.locales['en']['addEdge']); - this.manipulationDiv.appendChild(button); - this._bindHammerToDiv(button, this.addEdgeMode.bind(this)); - } - }, { - key: '_createEditNodeButton', - value: function _createEditNodeButton(locale) { - var button = this._createButton('editNode', 'vis-button vis-edit', locale['editNode'] || this.options.locales['en']['editNode']); - this.manipulationDiv.appendChild(button); - this._bindHammerToDiv(button, this.editNode.bind(this)); - } - }, { - key: '_createEditEdgeButton', - value: function _createEditEdgeButton(locale) { - var button = this._createButton('editEdge', 'vis-button vis-edit', locale['editEdge'] || this.options.locales['en']['editEdge']); - this.manipulationDiv.appendChild(button); - this._bindHammerToDiv(button, this.editEdgeMode.bind(this)); - } - }, { - key: '_createDeleteButton', - value: function _createDeleteButton(locale) { - var button = this._createButton('delete', 'vis-button vis-delete', locale['del'] || this.options.locales['en']['del']); - this.manipulationDiv.appendChild(button); - this._bindHammerToDiv(button, this.deleteSelected.bind(this)); - } - }, { - key: '_createBackButton', - value: function _createBackButton(locale) { - var button = this._createButton('back', 'vis-button vis-back', locale['back'] || this.options.locales['en']['back']); - this.manipulationDiv.appendChild(button); - this._bindHammerToDiv(button, this.showManipulatorToolbar.bind(this)); - } - }, { - key: '_createButton', - value: function _createButton(id, className, label) { - var labelClassName = arguments[3] === undefined ? 'vis-label' : arguments[3]; + if (dataMatrix[xIndex] === undefined) { + dataMatrix[xIndex] = []; + } - this.manipulationDOM[id + 'Div'] = document.createElement('div'); - this.manipulationDOM[id + 'Div'].className = className; - this.manipulationDOM[id + 'Label'] = document.createElement('div'); - this.manipulationDOM[id + 'Label'].className = labelClassName; - this.manipulationDOM[id + 'Label'].innerHTML = label; - this.manipulationDOM[id + 'Div'].appendChild(this.manipulationDOM[id + 'Label']); - return this.manipulationDOM[id + 'Div']; - } - }, { - key: '_createDescription', - value: function _createDescription(label) { - this.manipulationDiv.appendChild(this._createButton('description', 'vis-button vis-none', label)); - } - }, { - key: '_temporaryBindEvent', + var point3d = new Point3d(); + point3d.x = x; + point3d.y = y; + point3d.z = z; - // -------------------------- End of DOM functions for buttons ------------------------------// + obj = {}; + obj.point = point3d; + obj.trans = undefined; + obj.screen = undefined; + obj.bottom = new Point3d(x, y, this.zMin); - /** - * this binds an event until cleanup by the clean functions. - * @param event - * @param newFunction - * @private - */ - value: function _temporaryBindEvent(event, newFunction) { - this.temporaryEventFunctions.push({ event: event, boundFunction: newFunction }); - this.body.emitter.on(event, newFunction); - } - }, { - key: '_temporaryBindUI', + dataMatrix[xIndex][yIndex] = obj; - /** - * this overrides an UI function until cleanup by the clean function - * @param UIfunctionName - * @param newFunction - * @private - */ - value: function _temporaryBindUI(UIfunctionName, newFunction) { - if (this.body.eventListeners[UIfunctionName] !== undefined) { - this.temporaryUIFunctions[UIfunctionName] = this.body.eventListeners[UIfunctionName]; - this.body.eventListeners[UIfunctionName] = newFunction; - } else { - throw new Error('This UI function does not exist. Typo? You tried: ' + UIfunctionName + ' possible are: ' + JSON.stringify(Object.keys(this.body.eventListeners))); - } + dataPoints.push(obj); } - }, { - key: '_unbindTemporaryUIs', - /** - * Restore the overridden UI functions to their original state. - * - * @private - */ - value: function _unbindTemporaryUIs() { - for (var functionName in this.temporaryUIFunctions) { - if (this.temporaryUIFunctions.hasOwnProperty(functionName)) { - this.body.eventListeners[functionName] = this.temporaryUIFunctions[functionName]; - delete this.temporaryUIFunctions[functionName]; + // fill in the pointers to the neighbors. + for (x = 0; x < dataMatrix.length; x++) { + for (y = 0; y < dataMatrix[x].length; y++) { + if (dataMatrix[x][y]) { + dataMatrix[x][y].pointRight = x < dataMatrix.length - 1 ? dataMatrix[x + 1][y] : undefined; + dataMatrix[x][y].pointTop = y < dataMatrix[x].length - 1 ? dataMatrix[x][y + 1] : undefined; + dataMatrix[x][y].pointCross = x < dataMatrix.length - 1 && y < dataMatrix[x].length - 1 ? dataMatrix[x + 1][y + 1] : undefined; } } - this.temporaryUIFunctions = {}; } - }, { - key: '_unbindTemporaryEvents', + } else { + // 'dot', 'dot-line', etc. + // copy all values from the google data table to a list with Point3d objects + for (i = 0; i < data.length; i++) { + point = new Point3d(); + point.x = data[i][this.colX] || 0; + point.y = data[i][this.colY] || 0; + point.z = data[i][this.colZ] || 0; - /** - * Unbind the events created by _temporaryBindEvent - * @private - */ - value: function _unbindTemporaryEvents() { - for (var i = 0; i < this.temporaryEventFunctions.length; i++) { - var eventName = this.temporaryEventFunctions[i].event; - var boundFunction = this.temporaryEventFunctions[i].boundFunction; - this.body.emitter.off(eventName, boundFunction); + if (this.colValue !== undefined) { + point.value = data[i][this.colValue] || 0; } - this.temporaryEventFunctions = []; - } - }, { - key: '_bindHammerToDiv', - /** - * Bind an hammer instance to a DOM element. - * @param domElement - * @param funct - */ - value: function _bindHammerToDiv(domElement, boundFunction) { - var hammer = new Hammer(domElement, {}); - hammerUtil.onTouch(hammer, boundFunction); - this.manipulationHammers.push(hammer); + obj = {}; + obj.point = point; + obj.bottom = new Point3d(point.x, point.y, this.zMin); + obj.trans = undefined; + obj.screen = undefined; + + dataPoints.push(obj); } - }, { - key: '_cleanupTemporaryNodesAndEdges', + } - /** - * Neatly clean up temporary edges and nodes - * @private - */ - value: function _cleanupTemporaryNodesAndEdges() { - // _clean temporary edges - for (var i = 0; i < this.temporaryIds.edges.length; i++) { - this.body.edges[this.temporaryIds.edges[i]].disconnect(); - delete this.body.edges[this.temporaryIds.edges[i]]; - var indexTempEdge = this.body.edgeIndices.indexOf(this.temporaryIds.edges[i]); - if (indexTempEdge !== -1) { - this.body.edgeIndices.splice(indexTempEdge, 1); - } - } + return dataPoints; + }; - // _clean temporary nodes - for (var i = 0; i < this.temporaryIds.nodes.length; i++) { - delete this.body.nodes[this.temporaryIds.nodes[i]]; - var indexTempNode = this.body.nodeIndices.indexOf(this.temporaryIds.nodes[i]); - if (indexTempNode !== -1) { - this.body.nodeIndices.splice(indexTempNode, 1); - } - } + /** + * Create the main frame for the Graph3d. + * This function is executed once when a Graph3d object is created. The frame + * contains a canvas, and this canvas contains all objects like the axis and + * nodes. + */ + Graph3d.prototype.create = function () { + // remove all elements from the container element. + while (this.containerElement.hasChildNodes()) { + this.containerElement.removeChild(this.containerElement.firstChild); + } - this.temporaryIds = { nodes: [], edges: [] }; - } - }, { - key: '_controlNodeTouch', + this.frame = document.createElement('div'); + this.frame.style.position = 'relative'; + this.frame.style.overflow = 'hidden'; - // ------------------------------------------ EDIT EDGE FUNCTIONS -----------------------------------------// + // create the graph canvas (HTML canvas element) + this.frame.canvas = document.createElement('canvas'); + this.frame.canvas.style.position = 'relative'; + this.frame.appendChild(this.frame.canvas); + //if (!this.frame.canvas.getContext) { + { + var noCanvas = document.createElement('DIV'); + noCanvas.style.color = 'red'; + noCanvas.style.fontWeight = 'bold'; + noCanvas.style.padding = '10px'; + noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; + this.frame.canvas.appendChild(noCanvas); + } - /** - * the touch is used to get the position of the initial click - * @param event - * @private - */ - value: function _controlNodeTouch(event) { - this.selectionHandler.unselectAll(); - this.lastTouch = this.body.functions.getPointer(event.center); - this.lastTouch.translation = util.extend({}, this.body.view.translation); // copy the object - } - }, { - key: '_controlNodeDragStart', + this.frame.filter = document.createElement('div'); + this.frame.filter.style.position = 'absolute'; + this.frame.filter.style.bottom = '0px'; + this.frame.filter.style.left = '0px'; + this.frame.filter.style.width = '100%'; + this.frame.appendChild(this.frame.filter); - /** - * the drag start is used to mark one of the control nodes as selected. - * @param event - * @private - */ - value: function _controlNodeDragStart(event) { - var pointer = this.lastTouch; - var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); - var from = this.body.nodes[this.temporaryIds.nodes[0]]; - var to = this.body.nodes[this.temporaryIds.nodes[1]]; - var edge = this.body.edges[this.edgeBeingEditedId]; - this.selectedControlNode = undefined; + // add event listeners to handle moving and zooming the contents + var me = this; + var onmousedown = function onmousedown(event) { + me._onMouseDown(event); + }; + var ontouchstart = function ontouchstart(event) { + me._onTouchStart(event); + }; + var onmousewheel = function onmousewheel(event) { + me._onWheel(event); + }; + var ontooltip = function ontooltip(event) { + me._onTooltip(event); + }; + // TODO: these events are never cleaned up... can give a 'memory leakage' - var fromSelect = from.isOverlappingWith(pointerObj); - var toSelect = to.isOverlappingWith(pointerObj); + util.addEventListener(this.frame.canvas, 'keydown', onkeydown); + util.addEventListener(this.frame.canvas, 'mousedown', onmousedown); + util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart); + util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel); + util.addEventListener(this.frame.canvas, 'mousemove', ontooltip); - if (fromSelect === true) { - this.selectedControlNode = from; - edge.edgeType.from = from; - } else if (toSelect === true) { - this.selectedControlNode = to; - edge.edgeType.to = to; - } + // add the new graph to the container element + this.containerElement.appendChild(this.frame); + }; - this.body.emitter.emit('_redraw'); - } - }, { - key: '_controlNodeDrag', + /** + * Set a new size for the graph + * @param {string} width Width in pixels or percentage (for example '800px' + * or '50%') + * @param {string} height Height in pixels or percentage (for example '400px' + * or '30%') + */ + Graph3d.prototype.setSize = function (width, height) { + this.frame.style.width = width; + this.frame.style.height = height; - /** - * dragging the control nodes or the canvas - * @param event - * @private - */ - value: function _controlNodeDrag(event) { - this.body.emitter.emit('disablePhysics'); - var pointer = this.body.functions.getPointer(event.center); - var pos = this.canvas.DOMtoCanvas(pointer); + this._resizeCanvas(); + }; - if (this.selectedControlNode !== undefined) { - this.selectedControlNode.x = pos.x; - this.selectedControlNode.y = pos.y; - } else { - // if the drag was not started properly because the click started outside the network div, start it now. - var diffX = pointer.x - this.lastTouch.x; - var diffY = pointer.y - this.lastTouch.y; - this.body.view.translation = { x: this.lastTouch.translation.x + diffX, y: this.lastTouch.translation.y + diffY }; - } - this.body.emitter.emit('_redraw'); - } - }, { - key: '_controlNodeDragEnd', + /** + * Resize the canvas to the current size of the frame + */ + Graph3d.prototype._resizeCanvas = function () { + this.frame.canvas.style.width = '100%'; + this.frame.canvas.style.height = '100%'; - /** - * connecting or restoring the control nodes. - * @param event - * @private - */ - value: function _controlNodeDragEnd(event) { - var pointer = this.body.functions.getPointer(event.center); - var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); - var edge = this.body.edges[this.edgeBeingEditedId]; + this.frame.canvas.width = this.frame.canvas.clientWidth; + this.frame.canvas.height = this.frame.canvas.clientHeight; - var overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj); - var node = undefined; - for (var i = overlappingNodeIds.length - 1; i >= 0; i--) { - if (overlappingNodeIds[i] !== this.selectedControlNode.id) { - node = this.body.nodes[overlappingNodeIds[i]]; - break; - } - } + // adjust with for margin + this.frame.filter.style.width = this.frame.canvas.clientWidth - 2 * 10 + 'px'; + }; - // perform the connection - if (node !== undefined && this.selectedControlNode !== undefined) { - if (node.isCluster === true) { - alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']); - } else { - var from = this.body.nodes[this.temporaryIds.nodes[0]]; - if (this.selectedControlNode.id === from.id) { - this._performEditEdge(node.id, edge.to.id); - } else { - this._performEditEdge(edge.from.id, node.id); - } - } - } else { - edge.updateEdgeType(); - this.body.emitter.emit('restorePhysics'); - } - this.body.emitter.emit('_redraw'); - } - }, { - key: '_handleConnect', + /** + * Start animation + */ + Graph3d.prototype.animationStart = function () { + if (!this.frame.filter || !this.frame.filter.slider) throw 'No animation available'; - // ------------------------------------ END OF EDIT EDGE FUNCTIONS -----------------------------------------// + this.frame.filter.slider.play(); + }; - // ------------------------------------------- ADD EDGE FUNCTIONS -----------------------------------------// - /** - * the function bound to the selection event. It checks if you want to connect a cluster and changes the description - * to walk the user through the process. - * - * @private - */ - value: function _handleConnect(event) { - // check to avoid double fireing of this function. - if (new Date().valueOf() - this.touchTime > 100) { - this.lastTouch = this.body.functions.getPointer(event.center); - this.lastTouch.translation = util.extend({}, this.body.view.translation); // copy the object + /** + * Stop animation + */ + Graph3d.prototype.animationStop = function () { + if (!this.frame.filter || !this.frame.filter.slider) return; - var pointer = this.lastTouch; - var node = this.selectionHandler.getNodeAt(pointer); + this.frame.filter.slider.stop(); + }; - if (node !== undefined) { - if (node.isCluster === true) { - alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']); - } else { - // create a node the temporary line can look at - var targetNode = this._getNewTargetNode(node.x, node.y); - this.body.nodes[targetNode.id] = targetNode; - this.body.nodeIndices.push(targetNode.id); + /** + * Resize the center position based on the current values in this.defaultXCenter + * and this.defaultYCenter (which are strings with a percentage or a value + * in pixels). The center positions are the variables this.xCenter + * and this.yCenter + */ + Graph3d.prototype._resizeCenter = function () { + // calculate the horizontal center position + if (this.defaultXCenter.charAt(this.defaultXCenter.length - 1) === '%') { + this.xcenter = parseFloat(this.defaultXCenter) / 100 * this.frame.canvas.clientWidth; + } else { + this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px + } - // create a temporary edge - var connectionEdge = this.body.functions.createEdge({ - id: 'connectionEdge' + util.randomUUID(), - from: node.id, - to: targetNode.id, - physics: false, - smooth: { - enabled: true, - type: 'continuous', - roundness: 0.5 - } - }); - this.body.edges[connectionEdge.id] = connectionEdge; - this.body.edgeIndices.push(connectionEdge.id); + // calculate the vertical center position + if (this.defaultYCenter.charAt(this.defaultYCenter.length - 1) === '%') { + this.ycenter = parseFloat(this.defaultYCenter) / 100 * (this.frame.canvas.clientHeight - this.frame.filter.clientHeight); + } else { + this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px + } + }; - this.temporaryIds.nodes.push(targetNode.id); - this.temporaryIds.edges.push(connectionEdge.id); - } - } - this.touchTime = new Date().valueOf(); - } - } - }, { - key: '_dragControlNode', - value: function _dragControlNode(event) { - var pointer = this.body.functions.getPointer(event.center); - if (this.temporaryIds.nodes[0] !== undefined) { - var targetNode = this.body.nodes[this.temporaryIds.nodes[0]]; // there is only one temp node in the add edge mode. - targetNode.x = this.canvas._XconvertDOMtoCanvas(pointer.x); - targetNode.y = this.canvas._YconvertDOMtoCanvas(pointer.y); - this.body.emitter.emit('_redraw'); - } else { - var diffX = pointer.x - this.lastTouch.x; - var diffY = pointer.y - this.lastTouch.y; - this.body.view.translation = { x: this.lastTouch.translation.x + diffX, y: this.lastTouch.translation.y + diffY }; - } - } - }, { - key: '_finishConnect', + /** + * Set the rotation and distance of the camera + * @param {Object} pos An object with the camera position. The object + * contains three parameters: + * - horizontal {Number} + * The horizontal rotation, between 0 and 2*PI. + * Optional, can be left undefined. + * - vertical {Number} + * 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. + * - distance {Number} + * The (normalized) distance of the camera to the + * center of the graph, a value between 0.71 and 5.0. + * Optional, can be left undefined. + */ + Graph3d.prototype.setCameraPosition = function (pos) { + if (pos === undefined) { + return; + } - /** - * Connect the new edge to the target if one exists, otherwise remove temp line - * @param event - * @private - */ - value: function _finishConnect(event) { - var pointer = this.body.functions.getPointer(event.center); - var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); + if (pos.horizontal !== undefined && pos.vertical !== undefined) { + this.camera.setArmRotation(pos.horizontal, pos.vertical); + } - // remember the edge id - var connectFromId = undefined; - if (this.temporaryIds.edges[0] !== undefined) { - connectFromId = this.body.edges[this.temporaryIds.edges[0]].fromId; - } + if (pos.distance !== undefined) { + this.camera.setArmLength(pos.distance); + } - // get the overlapping node but NOT the temporary node; - var overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj); - var node = undefined; - for (var i = overlappingNodeIds.length - 1; i >= 0; i--) { - // if the node id is NOT a temporary node, accept the node. - if (this.temporaryIds.nodes.indexOf(overlappingNodeIds[i]) === -1) { - node = this.body.nodes[overlappingNodeIds[i]]; - break; - } - } + this.redraw(); + }; - // clean temporary nodes and edges. - this._cleanupTemporaryNodesAndEdges(); + /** + * Retrieve the current camera rotation + * @return {object} An object with parameters horizontal, vertical, and + * distance + */ + Graph3d.prototype.getCameraPosition = function () { + var pos = this.camera.getArmRotation(); + pos.distance = this.camera.getArmLength(); + return pos; + }; - // perform the connection - if (node !== undefined) { - if (node.isCluster === true) { - alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']); - } else { - if (this.body.nodes[connectFromId] !== undefined && this.body.nodes[node.id] !== undefined) { - this._performAddEdge(connectFromId, node.id); - } - } - } - this.body.emitter.emit('_redraw'); - } - }, { - key: '_performAddNode', + /** + * Load data into the 3D Graph + */ + Graph3d.prototype._readData = function (data) { + // read the data + this._dataInitialize(data, this.style); - // --------------------------------------- END OF ADD EDGE FUNCTIONS -------------------------------------// + if (this.dataFilter) { + // apply filtering + this.dataPoints = this.dataFilter._getDataPoints(); + } else { + // no filtering. load all data + this.dataPoints = this._getDataPoints(this.dataTable); + } - // ------------------------------ Performing all the actual data manipulation ------------------------// + // draw the filter + this._redrawFilter(); + }; - /** - * Adds a node on the specified location - */ - value: function _performAddNode(clickData) { - var _this4 = this; + /** + * Replace the dataset of the Graph3d + * @param {Array | DataSet | DataView} data + */ + Graph3d.prototype.setData = function (data) { + this._readData(data); + this.redraw(); - var defaultData = { - id: util.randomUUID(), - x: clickData.pointer.canvas.x, - y: clickData.pointer.canvas.y, - label: 'new' - }; + // start animation when option is true + if (this.animationAutoStart && this.dataFilter) { + this.animationStart(); + } + }; - if (typeof this.options.addNode === 'function') { - if (this.options.addNode.length === 2) { - this.options.addNode(defaultData, function (finalizedData) { - if (finalizedData !== null && finalizedData !== undefined && _this4.inMode === 'addNode') { - // if for whatever reason the mode has changes (due to dataset change) disregard the callback - _this4.body.data.nodes.add(finalizedData); - _this4.showManipulatorToolbar(); - } - }); - } else { - throw new Error('The function for add does not support two arguments (data,callback)'); - this.showManipulatorToolbar(); - } - } else { - this.body.data.nodes.add(defaultData); - this.showManipulatorToolbar(); - } - } - }, { - key: '_performAddEdge', + /** + * Update the options. Options will be merged with current options + * @param {Object} options + */ + Graph3d.prototype.setOptions = function (options) { + var cameraPosition = undefined; - /** - * connect two nodes with a new edge. - * - * @private - */ - value: function _performAddEdge(sourceNodeId, targetNodeId) { - var _this5 = this; + this.animationStop(); - var defaultData = { from: sourceNodeId, to: targetNodeId }; - if (typeof this.options.addEdge === 'function') { - if (this.options.addEdge.length === 2) { - this.options.addEdge(defaultData, function (finalizedData) { - if (finalizedData !== null && finalizedData !== undefined && _this5.inMode === 'addEdge') { - // if for whatever reason the mode has changes (due to dataset change) disregard the callback - _this5.body.data.edges.add(finalizedData); - _this5.selectionHandler.unselectAll(); - _this5.showManipulatorToolbar(); - } - }); - } else { - throw new Error('The function for connect does not support two arguments (data,callback)'); - } - } else { - this.body.data.edges.add(defaultData); - this.selectionHandler.unselectAll(); - this.showManipulatorToolbar(); - } - } - }, { - key: '_performEditEdge', + if (options !== undefined) { + // retrieve parameter values + if (options.width !== undefined) this.width = options.width; + if (options.height !== undefined) this.height = options.height; - /** - * connect two nodes with a new edge. - * - * @private - */ - value: function _performEditEdge(sourceNodeId, targetNodeId) { - var _this6 = this; + if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter; + if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter; - var defaultData = { id: this.edgeBeingEditedId, from: sourceNodeId, to: targetNodeId }; - if (typeof this.options.editEdge === 'function') { - if (this.options.editEdge.length === 2) { - this.options.editEdge(defaultData, function (finalizedData) { - if (finalizedData === null || finalizedData === undefined || _this6.inMode !== 'editEdge') { - // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { - _this6.body.edges[defaultData.id].updateEdgeType(); - _this6.body.emitter.emit('_redraw'); - } else { - _this6.body.data.edges.update(finalizedData); - _this6.selectionHandler.unselectAll(); - _this6.showManipulatorToolbar(); - } - }); - } else { - throw new Error('The function for edit does not support two arguments (data, callback)'); - } - } else { - this.body.data.edges.update(defaultData); - this.selectionHandler.unselectAll(); - this.showManipulatorToolbar(); - } - } - }]); + if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel; + if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel; + if (options.xLabel !== undefined) this.xLabel = options.xLabel; + if (options.yLabel !== undefined) this.yLabel = options.yLabel; + if (options.zLabel !== undefined) this.zLabel = options.zLabel; - return ManipulationSystem; - })(); + if (options.xValueLabel !== undefined) this.xValueLabel = options.xValueLabel; + if (options.yValueLabel !== undefined) this.yValueLabel = options.yValueLabel; + if (options.zValueLabel !== undefined) this.zValueLabel = options.zValueLabel; - exports['default'] = ManipulationSystem; - module.exports = exports['default']; + if (options.style !== undefined) { + var styleNumber = this._getStyleNumber(options.style); + if (styleNumber !== -1) { + this.style = styleNumber; + } + } + if (options.showGrid !== undefined) this.showGrid = options.showGrid; + if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective; + if (options.showShadow !== undefined) this.showShadow = options.showShadow; + if (options.tooltip !== undefined) this.showTooltip = options.tooltip; + if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls; + if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio; + if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio; -/***/ }, -/* 8 */ -/***/ function(module, exports, __webpack_require__) { + if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval; + if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload; + if (options.animationAutoStart !== undefined) this.animationAutoStart = options.animationAutoStart; - 'use strict'; + if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth; + if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth; - Object.defineProperty(exports, '__esModule', { - value: true - }); + if (options.xMin !== undefined) this.defaultXMin = options.xMin; + if (options.xStep !== undefined) this.defaultXStep = options.xStep; + if (options.xMax !== undefined) this.defaultXMax = options.xMax; + if (options.yMin !== undefined) this.defaultYMin = options.yMin; + if (options.yStep !== undefined) this.defaultYStep = options.yStep; + if (options.yMax !== undefined) this.defaultYMax = options.yMax; + if (options.zMin !== undefined) this.defaultZMin = options.zMin; + if (options.zStep !== undefined) this.defaultZStep = options.zStep; + if (options.zMax !== undefined) this.defaultZMax = options.zMax; + if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin; + if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + if (cameraPosition !== undefined) { + this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical); + this.camera.setArmLength(cameraPosition.distance); + } else { + this.camera.setArmRotation(1, 0.5); + this.camera.setArmLength(1.7); + } + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + this._setBackgroundColor(options && options.backgroundColor); - var _sharedLabel = __webpack_require__(68); + this.setSize(this.width, this.height); - var _sharedLabel2 = _interopRequireDefault(_sharedLabel); + // re-load the data + if (this.dataTable) { + this.setData(this.dataTable); + } - var _nodesShapesBox = __webpack_require__(69); + // start animation when option is true + if (this.animationAutoStart && this.dataFilter) { + this.animationStart(); + } + }; - var _nodesShapesBox2 = _interopRequireDefault(_nodesShapesBox); + /** + * Redraw the Graph. + */ + Graph3d.prototype.redraw = function () { + if (this.dataPoints === undefined) { + throw 'Error: graph data not initialized'; + } - var _nodesShapesCircle = __webpack_require__(71); + this._resizeCanvas(); + this._resizeCenter(); + this._redrawSlider(); + this._redrawClear(); + this._redrawAxis(); - var _nodesShapesCircle2 = _interopRequireDefault(_nodesShapesCircle); + if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { + this._redrawDataGrid(); + } else if (this.style === Graph3d.STYLE.LINE) { + this._redrawDataLine(); + } else if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { + this._redrawDataBar(); + } else { + // style is DOT, DOTLINE, DOTCOLOR, DOTSIZE + this._redrawDataDot(); + } - var _nodesShapesCircularImage = __webpack_require__(73); + this._redrawInfo(); + this._redrawLegend(); + }; - var _nodesShapesCircularImage2 = _interopRequireDefault(_nodesShapesCircularImage); + /** + * Clear the canvas before redrawing + */ + Graph3d.prototype._redrawClear = function () { + var canvas = this.frame.canvas; + var ctx = canvas.getContext('2d'); - var _nodesShapesDatabase = __webpack_require__(74); + ctx.clearRect(0, 0, canvas.width, canvas.height); + }; - var _nodesShapesDatabase2 = _interopRequireDefault(_nodesShapesDatabase); + /** + * Redraw the legend showing the colors + */ + Graph3d.prototype._redrawLegend = function () { + var y; - var _nodesShapesDiamond = __webpack_require__(75); + if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { - var _nodesShapesDiamond2 = _interopRequireDefault(_nodesShapesDiamond); + var dotSize = this.frame.clientWidth * 0.02; - var _nodesShapesDot = __webpack_require__(77); + var widthMin, widthMax; + if (this.style === Graph3d.STYLE.DOTSIZE) { + widthMin = dotSize / 2; // px + widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function + } else { + widthMin = 20; // px + widthMax = 20; // px + } - var _nodesShapesDot2 = _interopRequireDefault(_nodesShapesDot); + var height = Math.max(this.frame.clientHeight * 0.25, 100); + var top = this.margin; + var right = this.frame.clientWidth - this.margin; + var left = right - widthMax; + var bottom = top + height; + } - var _nodesShapesEllipse = __webpack_require__(78); + var canvas = this.frame.canvas; + var ctx = canvas.getContext('2d'); + ctx.lineWidth = 1; + ctx.font = '14px arial'; // TODO: put in options - var _nodesShapesEllipse2 = _interopRequireDefault(_nodesShapesEllipse); + if (this.style === Graph3d.STYLE.DOTCOLOR) { + // draw the color bar + var ymin = 0; + var ymax = height; // Todo: make height customizable + for (y = ymin; y < ymax; y++) { + var f = (y - ymin) / (ymax - ymin); - var _nodesShapesIcon = __webpack_require__(79); + //var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function + var hue = f * 240; + var color = this._hsv2rgb(hue, 1, 1); - var _nodesShapesIcon2 = _interopRequireDefault(_nodesShapesIcon); + ctx.strokeStyle = color; + ctx.beginPath(); + ctx.moveTo(left, top + y); + ctx.lineTo(right, top + y); + ctx.stroke(); + } - var _nodesShapesImage = __webpack_require__(80); + ctx.strokeStyle = this.colorAxis; + ctx.strokeRect(left, top, widthMax, height); + } - var _nodesShapesImage2 = _interopRequireDefault(_nodesShapesImage); + if (this.style === Graph3d.STYLE.DOTSIZE) { + // draw border around color bar + ctx.strokeStyle = this.colorAxis; + ctx.fillStyle = this.colorDot; + ctx.beginPath(); + ctx.moveTo(left, top); + ctx.lineTo(right, top); + ctx.lineTo(right - widthMax + widthMin, bottom); + ctx.lineTo(left, bottom); + ctx.closePath(); + ctx.fill(); + ctx.stroke(); + } - var _nodesShapesSquare = __webpack_require__(81); + if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { + // print values along the color bar + var gridLineLen = 5; // px + var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax - this.valueMin) / 5, true); + step.start(); + if (step.getCurrent() < this.valueMin) { + step.next(); + } + while (!step.end()) { + y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height; - var _nodesShapesSquare2 = _interopRequireDefault(_nodesShapesSquare); + ctx.beginPath(); + ctx.moveTo(left - gridLineLen, y); + ctx.lineTo(left, y); + ctx.stroke(); - var _nodesShapesStar = __webpack_require__(82); + ctx.textAlign = 'right'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = this.colorAxis; + ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y); - var _nodesShapesStar2 = _interopRequireDefault(_nodesShapesStar); + step.next(); + } - var _nodesShapesText = __webpack_require__(83); + ctx.textAlign = 'right'; + ctx.textBaseline = 'top'; + var label = this.legendLabel; + ctx.fillText(label, right, bottom + this.margin); + } + }; - var _nodesShapesText2 = _interopRequireDefault(_nodesShapesText); + /** + * Redraw the filter + */ + Graph3d.prototype._redrawFilter = function () { + this.frame.filter.innerHTML = ''; - var _nodesShapesTriangle = __webpack_require__(84); + if (this.dataFilter) { + var options = { + 'visible': this.showAnimationControls + }; + var slider = new Slider(this.frame.filter, options); + this.frame.filter.slider = slider; - var _nodesShapesTriangle2 = _interopRequireDefault(_nodesShapesTriangle); + // TODO: css here is not nice here... + this.frame.filter.style.padding = '10px'; + //this.frame.filter.style.backgroundColor = '#EFEFEF'; - var _nodesShapesTriangleDown = __webpack_require__(85); + slider.setValues(this.dataFilter.values); + slider.setPlayInterval(this.animationInterval); - var _nodesShapesTriangleDown2 = _interopRequireDefault(_nodesShapesTriangleDown); + // create an event handler + var me = this; + var onchange = function onchange() { + var index = slider.getIndex(); - var _sharedValidator = __webpack_require__(54); + me.dataFilter.selectValue(index); + me.dataPoints = me.dataFilter._getDataPoints(); - var _sharedValidator2 = _interopRequireDefault(_sharedValidator); + me.redraw(); + }; + slider.setOnChangeCallback(onchange); + } else { + this.frame.filter.slider = undefined; + } + }; - var util = __webpack_require__(2); + /** + * Redraw the slider + */ + Graph3d.prototype._redrawSlider = function () { + if (this.frame.filter.slider !== undefined) { + this.frame.filter.slider.redraw(); + } + }; /** - * @class Node - * A node. A node can be connected to other nodes via one or multiple edges. - * @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, available: - * "database", "circle", "ellipse", - * "box", "image", "text", "dot", - * "star", "triangle", "triangleDown", - * "square", "icon" - * {string} image An image url - * {string} title An title text, can be HTML - * {anytype} group A group name or number - * @param {Network.Images} imagelist A list with images. Only needed - * when the node has an image - * @param {Network.Groups} grouplist A list with groups. Needed for - * retrieving group options - * @param {Object} constants An object with default values for - * example for the color - * + * Redraw common information */ + Graph3d.prototype._redrawInfo = function () { + if (this.dataFilter) { + var canvas = this.frame.canvas; + var ctx = canvas.getContext('2d'); - var Node = (function () { - function Node(options, body, imagelist, grouplist, globalOptions) { - _classCallCheck(this, Node); + ctx.font = '14px arial'; // TODO: put in options + ctx.lineStyle = 'gray'; + ctx.fillStyle = 'gray'; + ctx.textAlign = 'left'; + ctx.textBaseline = 'top'; - this.options = util.bridgeObject(globalOptions); - this.body = body; + var x = this.margin; + var y = this.margin; + ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y); + } + }; - this.edges = []; // all edges connected to this node + /** + * Redraw the axis + */ + Graph3d.prototype._redrawAxis = function () { + var canvas = this.frame.canvas, + ctx = canvas.getContext('2d'), + from, + to, + step, + prettyStep, + text, + xText, + yText, + zText, + offset, + xOffset, + yOffset, + xMin2d, + xMax2d; - // set defaults for the options - this.id = undefined; - this.imagelist = imagelist; - this.grouplist = grouplist; + // TODO: get the actual rendered style of the containerElement + //ctx.font = this.containerElement.style.font; + ctx.font = 24 / this.camera.getArmLength() + 'px arial'; - // 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; + // calculate the length for the short grid lines + var gridLenX = 0.025 / this.scale.x; + var gridLenY = 0.025 / this.scale.y; + var textMargin = 5 / this.camera.getArmLength(); // px + var armAngle = this.camera.getArmRotation().horizontal; - this.labelModule = new _sharedLabel2['default'](this.body, this.options); - this.setOptions(options); + // draw x-grid lines + ctx.lineWidth = 1; + prettyStep = this.defaultXStep === undefined; + step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep); + step.start(); + if (step.getCurrent() < this.xMin) { + step.next(); } + while (!step.end()) { + var x = step.getCurrent(); - _createClass(Node, [{ - key: 'attachEdge', - - /** - * Attach a edge to the node - * @param {Edge} edge - */ - value: function attachEdge(edge) { - if (this.edges.indexOf(edge) === -1) { - this.edges.push(edge); - } - } - }, { - key: 'detachEdge', + if (this.showGrid) { + from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); + to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); + ctx.strokeStyle = this.colorGrid; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); + } else { + from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); + to = this._convert3Dto2D(new Point3d(x, this.yMin + gridLenX, this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); - /** - * Detach a edge from the node - * @param {Edge} edge - */ - value: function detachEdge(edge) { - var index = this.edges.indexOf(edge); - if (index != -1) { - this.edges.splice(index, 1); - } + from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); + to = this._convert3Dto2D(new Point3d(x, this.yMax - gridLenX, this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); } - }, { - key: 'togglePhysics', - /** - * Enable or disable the physics. - * @param status - */ - value: function togglePhysics(status) { - this.options.physics = status; + yText = Math.cos(armAngle) > 0 ? this.yMin : this.yMax; + text = this._convert3Dto2D(new Point3d(x, yText, this.zMin)); + if (Math.cos(armAngle * 2) > 0) { + ctx.textAlign = 'center'; + ctx.textBaseline = 'top'; + text.y += textMargin; + } else if (Math.sin(armAngle * 2) < 0) { + ctx.textAlign = 'right'; + ctx.textBaseline = 'middle'; + } else { + ctx.textAlign = 'left'; + ctx.textBaseline = 'middle'; } - }, { - key: 'setOptions', + ctx.fillStyle = this.colorAxis; + ctx.fillText(' ' + this.xValueLabel(step.getCurrent()) + ' ', text.x, text.y); - /** - * Set or overwrite options for the node - * @param {Object} options an object with options - * @param {Object} constants and object with default, global options - */ - value: function setOptions(options) { - if (!options) { - return; - } - // basic options - if (options.id !== undefined) { - this.id = options.id; - } + step.next(); + } - if (this.id === undefined) { - throw 'Node must have an id'; - } + // draw y-grid lines + ctx.lineWidth = 1; + prettyStep = this.defaultYStep === undefined; + step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep); + step.start(); + if (step.getCurrent() < this.yMin) { + step.next(); + } + while (!step.end()) { + if (this.showGrid) { + from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); + to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); + ctx.strokeStyle = this.colorGrid; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); + } else { + from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); + to = this._convert3Dto2D(new Point3d(this.xMin + gridLenY, step.getCurrent(), this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); - // set these options locally - if (options.x !== undefined) { - this.x = parseInt(options.x);this.predefinedPosition = true; - } - if (options.y !== undefined) { - this.y = parseInt(options.y);this.predefinedPosition = true; - } - if (options.size !== undefined) { - this.baseSize = options.size; - } - if (options.value !== undefined) { - options.value = parseInt(options.value); - } + from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); + to = this._convert3Dto2D(new Point3d(this.xMax - gridLenY, step.getCurrent(), this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); + } - // copy group options - if (typeof options.group === 'number' || typeof options.group === 'string' && options.group != '') { - var groupObj = this.grouplist.get(options.group); - util.deepExtend(this.options, groupObj); - // the color object needs to be completely defined. Since groups can partially overwrite the colors, we parse it again, just in case. - this.options.color = util.parseColor(this.options.color); - } + xText = Math.sin(armAngle) > 0 ? this.xMin : this.xMax; + text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin)); + if (Math.cos(armAngle * 2) < 0) { + ctx.textAlign = 'center'; + ctx.textBaseline = 'top'; + text.y += textMargin; + } else if (Math.sin(armAngle * 2) > 0) { + ctx.textAlign = 'right'; + ctx.textBaseline = 'middle'; + } else { + ctx.textAlign = 'left'; + ctx.textBaseline = 'middle'; + } + ctx.fillStyle = this.colorAxis; + ctx.fillText(' ' + this.yValueLabel(step.getCurrent()) + ' ', text.x, text.y); - // this transforms all shorthands into fully defined options - Node.parseOptions(this.options, options, true); + step.next(); + } - // load the images - if (this.options.image !== undefined && this.options.image != '') { - if (this.imagelist) { - this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage, this.id); - } else { - throw 'No imagelist provided'; - } - } + // draw z-grid lines and axis + ctx.lineWidth = 1; + prettyStep = this.defaultZStep === undefined; + step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep); + step.start(); + if (step.getCurrent() < this.zMin) { + step.next(); + } + xText = Math.cos(armAngle) > 0 ? this.xMin : this.xMax; + yText = Math.sin(armAngle) < 0 ? this.yMin : this.yMax; + while (!step.end()) { + // TODO: make z-grid lines really 3d? + from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent())); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(from.x - textMargin, from.y); + ctx.stroke(); - this.updateShape(); - this.updateLabelModule(); + ctx.textAlign = 'right'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = this.colorAxis; + ctx.fillText(this.zValueLabel(step.getCurrent()) + ' ', from.x - 5, from.y); - // reset the size of the node, this can be changed - this._reset(); + step.next(); + } + ctx.lineWidth = 1; + from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); + to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); - if (options.hidden !== undefined || options.physics !== undefined) { - return true; - } - return false; - } - }, { - key: 'updateLabelModule', - value: function updateLabelModule() { - if (this.options.label === undefined || this.options.label === null) { - this.options.label = ''; - } - this.labelModule.setOptions(this.options, true); - if (this.labelModule.baseSize !== undefined) { - this.baseFontSize = this.labelModule.baseSize; - } - } - }, { - key: 'updateShape', - value: function updateShape() { - // choose draw method depending on the shape - switch (this.options.shape) { - case 'box': - this.shape = new _nodesShapesBox2['default'](this.options, this.body, this.labelModule); - break; - case 'circle': - this.shape = new _nodesShapesCircle2['default'](this.options, this.body, this.labelModule); - break; - case 'circularImage': - this.shape = new _nodesShapesCircularImage2['default'](this.options, this.body, this.labelModule, this.imageObj); - break; - case 'database': - this.shape = new _nodesShapesDatabase2['default'](this.options, this.body, this.labelModule); - break; - case 'diamond': - this.shape = new _nodesShapesDiamond2['default'](this.options, this.body, this.labelModule); - break; - case 'dot': - this.shape = new _nodesShapesDot2['default'](this.options, this.body, this.labelModule); - break; - case 'ellipse': - this.shape = new _nodesShapesEllipse2['default'](this.options, this.body, this.labelModule); - break; - case 'icon': - this.shape = new _nodesShapesIcon2['default'](this.options, this.body, this.labelModule); - break; - case 'image': - this.shape = new _nodesShapesImage2['default'](this.options, this.body, this.labelModule, this.imageObj); - break; - case 'square': - this.shape = new _nodesShapesSquare2['default'](this.options, this.body, this.labelModule); - break; - case 'star': - this.shape = new _nodesShapesStar2['default'](this.options, this.body, this.labelModule); - break; - case 'text': - this.shape = new _nodesShapesText2['default'](this.options, this.body, this.labelModule); - break; - case 'triangle': - this.shape = new _nodesShapesTriangle2['default'](this.options, this.body, this.labelModule); - break; - case 'triangleDown': - this.shape = new _nodesShapesTriangleDown2['default'](this.options, this.body, this.labelModule); - break; - default: - this.shape = new _nodesShapesEllipse2['default'](this.options, this.body, this.labelModule); - break; - } - this._reset(); - } - }, { - key: 'select', + // draw x-axis + ctx.lineWidth = 1; + // line at yMin + xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); + xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(xMin2d.x, xMin2d.y); + ctx.lineTo(xMax2d.x, xMax2d.y); + ctx.stroke(); + // line at ymax + xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); + xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(xMin2d.x, xMin2d.y); + ctx.lineTo(xMax2d.x, xMax2d.y); + ctx.stroke(); - /** - * select this node - */ - value: function select() { - this.selected = true; - this._reset(); - } - }, { - key: 'unselect', + // draw y-axis + ctx.lineWidth = 1; + // line at xMin + from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); + to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); + // line at xMax + from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); + to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); - /** - * unselect this node - */ - value: function unselect() { - this.selected = false; - this._reset(); + // draw x-label + var xLabel = this.xLabel; + if (xLabel.length > 0) { + yOffset = 0.1 / this.scale.y; + xText = (this.xMin + this.xMax) / 2; + yText = Math.cos(armAngle) > 0 ? this.yMin - yOffset : this.yMax + yOffset; + text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); + if (Math.cos(armAngle * 2) > 0) { + ctx.textAlign = 'center'; + ctx.textBaseline = 'top'; + } else if (Math.sin(armAngle * 2) < 0) { + ctx.textAlign = 'right'; + ctx.textBaseline = 'middle'; + } else { + ctx.textAlign = 'left'; + ctx.textBaseline = 'middle'; } - }, { - key: '_reset', + ctx.fillStyle = this.colorAxis; + ctx.fillText(xLabel, text.x, text.y); + } - /** - * Reset the calculated size of the node, forces it to recalculate its size - * @private - */ - value: function _reset() { - this.shape.width = undefined; - this.shape.height = undefined; + // draw y-label + var yLabel = this.yLabel; + if (yLabel.length > 0) { + xOffset = 0.1 / this.scale.x; + xText = Math.sin(armAngle) > 0 ? this.xMin - xOffset : this.xMax + xOffset; + yText = (this.yMin + this.yMax) / 2; + text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); + if (Math.cos(armAngle * 2) < 0) { + ctx.textAlign = 'center'; + ctx.textBaseline = 'top'; + } else if (Math.sin(armAngle * 2) > 0) { + ctx.textAlign = 'right'; + ctx.textBaseline = 'middle'; + } else { + ctx.textAlign = 'left'; + ctx.textBaseline = 'middle'; } - }, { - key: 'getTitle', + ctx.fillStyle = this.colorAxis; + ctx.fillText(yLabel, text.x, text.y); + } - /** - * get the title of this node. - * @return {string} title The title of the node, or undefined when no title - * has been set. - */ - value: function getTitle() { - return this.options.title; - } - }, { - key: 'distanceToBorder', + // draw z-label + var zLabel = this.zLabel; + if (zLabel.length > 0) { + offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis? + xText = Math.cos(armAngle) > 0 ? this.xMin : this.xMax; + yText = Math.sin(armAngle) < 0 ? this.yMin : this.yMax; + zText = (this.zMin + this.zMax) / 2; + text = this._convert3Dto2D(new Point3d(xText, yText, zText)); + ctx.textAlign = 'right'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = this.colorAxis; + ctx.fillText(zLabel, text.x - offset, text.y); + } + }; - /** - * 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 - */ - value: function distanceToBorder(ctx, angle) { - return this.shape.distanceToBorder(ctx, angle); - } - }, { - key: 'isFixed', + /** + * Calculate the color based on the given value. + * @param {Number} H Hue, a value be between 0 and 360 + * @param {Number} S Saturation, a value between 0 and 1 + * @param {Number} V Value, a value between 0 and 1 + */ + Graph3d.prototype._hsv2rgb = function (H, S, V) { + var R, G, B, C, Hi, X; - /** - * Check if this node has a fixed x and y position - * @return {boolean} true if fixed, false if not - */ - value: function isFixed() { - return this.options.fixed.x && this.options.fixed.y; - } - }, { - key: 'isSelected', + C = V * S; + Hi = Math.floor(H / 60); // hi = 0,1,2,3,4,5 + X = C * (1 - Math.abs(H / 60 % 2 - 1)); - /** - * check if this node is selecte - * @return {boolean} selected True if node is selected, else false - */ - value: function isSelected() { - return this.selected; - } - }, { - key: 'getValue', + switch (Hi) { + case 0: + R = C;G = X;B = 0;break; + case 1: + R = X;G = C;B = 0;break; + case 2: + R = 0;G = C;B = X;break; + case 3: + R = 0;G = X;B = C;break; + case 4: + R = X;G = 0;B = C;break; + case 5: + R = C;G = 0;B = X;break; - /** - * Retrieve the value of the node. Can be undefined - * @return {Number} value - */ - value: function getValue() { - return this.options.value; - } - }, { - key: 'setValueRange', + default: + R = 0;G = 0;B = 0;break; + } - /** - * Adjust the value range of the node. The node will adjust it's size - * based on its value. - * @param {Number} min - * @param {Number} max - */ - 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; - } - } - }, { - key: 'draw', + return 'RGB(' + parseInt(R * 255) + ',' + parseInt(G * 255) + ',' + parseInt(B * 255) + ')'; + }; - /** - * Draw this node in the given canvas - * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); - * @param {CanvasRenderingContext2D} ctx - */ - value: function draw(ctx) { - this.shape.draw(ctx, this.x, this.y, this.selected, this.hover); - } - }, { - key: 'updateBoundingBox', + /** + * Draw all datapoints as a grid + * This function can be used when the style is 'grid' + */ + Graph3d.prototype._redrawDataGrid = function () { + var canvas = this.frame.canvas, + ctx = canvas.getContext('2d'), + point, + right, + top, + cross, + i, + topSideVisible, + fillStyle, + strokeStyle, + lineWidth, + h, + s, + v, + zAvg; - /** - * Update the bounding box of the shape - */ - value: function updateBoundingBox() { - this.shape.updateBoundingBox(this.x, this.y); - } - }, { - key: 'resize', + if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? - /** - * 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 - */ - value: function resize(ctx) { - this.shape.resize(ctx); - } - }, { - key: 'isOverlappingWith', + // calculate the translations and screen position of all points + for (i = 0; i < this.dataPoints.length; i++) { + var trans = this._convertPointToTranslation(this.dataPoints[i].point); + var screen = this._convertTranslationToScreen(trans); - /** - * 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 - */ - 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; - } - }, { - key: 'isBoundingBoxOverlappingWith', + this.dataPoints[i].trans = trans; + this.dataPoints[i].screen = screen; - /** - * 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 - */ - 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; - } - }], [{ - key: 'parseOptions', + // calculate the translation of the point at the bottom (needed for sorting) + var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); + this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; + } - /** - * 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 parentOptions - * @param newOptions - */ - value: function parseOptions(parentOptions, newOptions) { - var allowDeletion = arguments[2] === undefined ? false : arguments[2]; + // sort the points on depth of their (x,y) position (not on z) + var sortDepth = function sortDepth(a, b) { + return b.dist - a.dist; + }; + this.dataPoints.sort(sortDepth); - var fields = ['color', 'font', 'fixed', 'shadow']; - util.selectiveNotDeepExtend(fields, parentOptions, newOptions, allowDeletion); + if (this.style === Graph3d.STYLE.SURFACE) { + for (i = 0; i < this.dataPoints.length; i++) { + point = this.dataPoints[i]; + right = this.dataPoints[i].pointRight; + top = this.dataPoints[i].pointTop; + cross = this.dataPoints[i].pointCross; - // merge the shadow options into the parent. - util.mergeOptions(parentOptions, newOptions, 'shadow'); + if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) { - // 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 = undefined; - delete parentOptions.color; - } + if (this.showGrayBottom || this.showShadow) { + // calculate the cross product of the two vectors from center + // to left and right, in order to know whether we are looking at the + // bottom or at the top side. We can also use the cross product + // for calculating light intensity + var aDiff = Point3d.subtract(cross.trans, point.trans); + var bDiff = Point3d.subtract(top.trans, right.trans); + var crossproduct = Point3d.crossProduct(aDiff, bDiff); + var len = crossproduct.length(); + // FIXME: there is a bug with determining the surface side (shadow or colored) - // 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; + topSideVisible = crossproduct.z > 0; } 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; - } + topSideVisible = true; } - } - // handle the font options - if (newOptions.font !== undefined) { - _sharedLabel2['default'].parseOptions(parentOptions.font, newOptions); - } + if (topSideVisible) { + // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 + zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4; + h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; + s = 1; // saturation - // handle the scaling options, specifically the label part - if (newOptions.scaling !== undefined) { - util.mergeOptions(parentOptions.scaling, newOptions.scaling, 'label'); + if (this.showShadow) { + v = Math.min(1 + crossproduct.x / len / 2, 1); // value. TODO: scale + fillStyle = this._hsv2rgb(h, s, v); + strokeStyle = fillStyle; + } else { + v = 1; + fillStyle = this._hsv2rgb(h, s, v); + strokeStyle = this.colorAxis; + } + } else { + fillStyle = 'gray'; + strokeStyle = this.colorAxis; + } + lineWidth = 0.5; + + ctx.lineWidth = lineWidth; + ctx.fillStyle = fillStyle; + ctx.strokeStyle = strokeStyle; + ctx.beginPath(); + ctx.moveTo(point.screen.x, point.screen.y); + ctx.lineTo(right.screen.x, right.screen.y); + ctx.lineTo(cross.screen.x, cross.screen.y); + ctx.lineTo(top.screen.x, top.screen.y); + ctx.closePath(); + ctx.fill(); + ctx.stroke(); } } - }]); + } else { + // grid style + for (i = 0; i < this.dataPoints.length; i++) { + point = this.dataPoints[i]; + right = this.dataPoints[i].pointRight; + top = this.dataPoints[i].pointTop; - return Node; - })(); + if (point !== undefined) { + if (this.showPerspective) { + lineWidth = 2 / -point.trans.z; + } else { + lineWidth = 2 * -(this.eye.z / this.camera.getArmLength()); + } + } - exports['default'] = Node; - module.exports = exports['default']; + if (point !== undefined && right !== undefined) { + // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 + zAvg = (point.point.z + right.point.z) / 2; + h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; -/***/ }, -/* 9 */ -/***/ function(module, exports, __webpack_require__) { + ctx.lineWidth = lineWidth; + ctx.strokeStyle = this._hsv2rgb(h, 1, 1); + ctx.beginPath(); + ctx.moveTo(point.screen.x, point.screen.y); + ctx.lineTo(right.screen.x, right.screen.y); + ctx.stroke(); + } - 'use strict'; + if (point !== undefined && top !== undefined) { + // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 + zAvg = (point.point.z + top.point.z) / 2; + h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + ctx.lineWidth = lineWidth; + ctx.strokeStyle = this._hsv2rgb(h, 1, 1); + ctx.beginPath(); + ctx.moveTo(point.screen.x, point.screen.y); + ctx.lineTo(top.screen.x, top.screen.y); + ctx.stroke(); + } + } + } + }; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + /** + * Draw all datapoints as dots. + * This function can be used when the style is 'dot' or 'dot-line' + */ + Graph3d.prototype._redrawDataDot = function () { + var canvas = this.frame.canvas; + var ctx = canvas.getContext('2d'); + var i; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? - var _sharedLabel = __webpack_require__(68); + // calculate the translations of all points + for (i = 0; i < this.dataPoints.length; i++) { + var trans = this._convertPointToTranslation(this.dataPoints[i].point); + var screen = this._convertTranslationToScreen(trans); + this.dataPoints[i].trans = trans; + this.dataPoints[i].screen = screen; - var _sharedLabel2 = _interopRequireDefault(_sharedLabel); + // calculate the distance from the point at the bottom to the camera + var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); + this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; + } - var _edgesBezierEdgeDynamic = __webpack_require__(87); + // order the translated points by depth + var sortDepth = function sortDepth(a, b) { + return b.dist - a.dist; + }; + this.dataPoints.sort(sortDepth); - var _edgesBezierEdgeDynamic2 = _interopRequireDefault(_edgesBezierEdgeDynamic); + // draw the datapoints as colored circles + var dotSize = this.frame.clientWidth * 0.02; // px + for (i = 0; i < this.dataPoints.length; i++) { + var point = this.dataPoints[i]; - var _edgesBezierEdgeStatic = __webpack_require__(90); + if (this.style === Graph3d.STYLE.DOTLINE) { + // draw a vertical line from the bottom to the graph value + //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin)); + var from = this._convert3Dto2D(point.bottom); + ctx.lineWidth = 1; + ctx.strokeStyle = this.colorGrid; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(point.screen.x, point.screen.y); + ctx.stroke(); + } - var _edgesBezierEdgeStatic2 = _interopRequireDefault(_edgesBezierEdgeStatic); + // calculate radius for the circle + var size; + if (this.style === Graph3d.STYLE.DOTSIZE) { + size = dotSize / 2 + 2 * dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin); + } else { + size = dotSize; + } - var _edgesStraightEdge = __webpack_require__(91); + var radius; + if (this.showPerspective) { + radius = size / -point.trans.z; + } else { + radius = size * -(this.eye.z / this.camera.getArmLength()); + } + if (radius < 0) { + radius = 0; + } - var _edgesStraightEdge2 = _interopRequireDefault(_edgesStraightEdge); + var hue, color, borderColor; + if (this.style === Graph3d.STYLE.DOTCOLOR) { + // calculate the color based on the value + hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; + color = this._hsv2rgb(hue, 1, 1); + borderColor = this._hsv2rgb(hue, 1, 0.8); + } else if (this.style === Graph3d.STYLE.DOTSIZE) { + color = this.colorDot; + borderColor = this.colorDotBorder; + } else { + // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 + hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; + color = this._hsv2rgb(hue, 1, 1); + borderColor = this._hsv2rgb(hue, 1, 0.8); + } - var util = __webpack_require__(2); + // draw the circle + ctx.lineWidth = 1; + ctx.strokeStyle = borderColor; + ctx.fillStyle = color; + ctx.beginPath(); + ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI * 2, true); + ctx.fill(); + ctx.stroke(); + } + }; /** - * @class Edge - * - * A edge connects two nodes - * @param {Object} properties Object with options. Must contain - * At least options from and to. - * Available options: from (number), - * to (number), label (string, color (string), - * width (number), style (string), - * length (number), title (string) - * @param {Network} network A Network object, used to find and edge to - * nodes. - * @param {Object} constants An object with default values for - * example for the color + * Draw all datapoints as bars. + * This function can be used when the style is 'bar', 'bar-color', or 'bar-size' */ + Graph3d.prototype._redrawDataBar = function () { + var canvas = this.frame.canvas; + var ctx = canvas.getContext('2d'); + var i, j, surface, corners; - var Edge = (function () { - function Edge(options, body, globalOptions) { - _classCallCheck(this, Edge); + if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? - if (body === undefined) { - throw 'No body provided'; + // calculate the translations of all points + for (i = 0; i < this.dataPoints.length; i++) { + var trans = this._convertPointToTranslation(this.dataPoints[i].point); + var screen = this._convertTranslationToScreen(trans); + this.dataPoints[i].trans = trans; + this.dataPoints[i].screen = screen; + + // calculate the distance from the point at the bottom to the camera + var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); + this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; + } + + // order the translated points by depth + var sortDepth = function sortDepth(a, b) { + return b.dist - a.dist; + }; + this.dataPoints.sort(sortDepth); + + // draw the datapoints as bars + var xWidth = this.xBarWidth / 2; + var yWidth = this.yBarWidth / 2; + for (i = 0; i < this.dataPoints.length; i++) { + var point = this.dataPoints[i]; + + // determine color + var hue, color, borderColor; + if (this.style === Graph3d.STYLE.BARCOLOR) { + // calculate the color based on the value + hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; + color = this._hsv2rgb(hue, 1, 1); + borderColor = this._hsv2rgb(hue, 1, 0.8); + } else if (this.style === Graph3d.STYLE.BARSIZE) { + color = this.colorDot; + borderColor = this.colorDotBorder; + } else { + // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 + hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; + color = this._hsv2rgb(hue, 1, 1); + borderColor = this._hsv2rgb(hue, 1, 0.8); } - this.options = util.bridgeObject(globalOptions); - this.body = body; - // initialize variables - this.id = undefined; - this.fromId = undefined; - this.toId = undefined; - this.selected = false; - this.hover = false; - this.labelDirty = true; - this.colorDirty = true; + // calculate size for the bar + if (this.style === Graph3d.STYLE.BARSIZE) { + xWidth = this.xBarWidth / 2 * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); + yWidth = this.yBarWidth / 2 * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); + } - this.baseWidth = this.options.width; - this.baseFontSize = this.options.font.size; + // calculate all corner points + var me = this; + var point3d = point.point; + var top = [{ point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z) }, { point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z) }, { point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z) }, { point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z) }]; + var bottom = [{ point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin) }, { point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin) }, { point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin) }, { point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin) }]; - this.from = undefined; // a node - this.to = undefined; // a node + // calculate screen location of the points + top.forEach(function (obj) { + obj.screen = me._convert3Dto2D(obj.point); + }); + bottom.forEach(function (obj) { + obj.screen = me._convert3Dto2D(obj.point); + }); - this.edgeType = undefined; + // create five sides, calculate both corner points and center points + var surfaces = [{ corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point) }, { corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point) }, { corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point) }, { corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point) }, { corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point) }]; + point.surfaces = surfaces; - this.connected = false; + // calculate the distance of each of the surface centers to the camera + for (j = 0; j < surfaces.length; j++) { + surface = surfaces[j]; + var transCenter = this._convertPointToTranslation(surface.center); + surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z; + // TODO: this dept calculation doesn't work 100% of the cases due to perspective, + // but the current solution is fast/simple and works in 99.9% of all cases + // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9}) + } - this.labelModule = new _sharedLabel2['default'](this.body, this.options); + // order the surfaces by their (translated) depth + surfaces.sort(function (a, b) { + var diff = b.dist - a.dist; + if (diff) return diff; - this.setOptions(options); + // if equal depth, sort the top surface last + if (a.corners === top) return 1; + if (b.corners === top) return -1; + + // both are equal + return 0; + }); + + // draw the ordered surfaces + ctx.lineWidth = 1; + ctx.strokeStyle = borderColor; + ctx.fillStyle = color; + // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside + for (j = 2; j < surfaces.length; j++) { + surface = surfaces[j]; + corners = surface.corners; + ctx.beginPath(); + ctx.moveTo(corners[3].screen.x, corners[3].screen.y); + ctx.lineTo(corners[0].screen.x, corners[0].screen.y); + ctx.lineTo(corners[1].screen.x, corners[1].screen.y); + ctx.lineTo(corners[2].screen.x, corners[2].screen.y); + ctx.lineTo(corners[3].screen.x, corners[3].screen.y); + ctx.fill(); + ctx.stroke(); + } } + }; - _createClass(Edge, [{ - key: 'setOptions', + /** + * Draw a line through all datapoints. + * This function can be used when the style is 'line' + */ + Graph3d.prototype._redrawDataLine = function () { + var canvas = this.frame.canvas, + ctx = canvas.getContext('2d'), + point, + i; - /** - * Set or overwrite options for the edge - * @param {Object} options an object with options - * @param doNotEmit - */ - value: function setOptions(options) { - if (!options) { - return; - } - this.colorDirty = true; + if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? - Edge.parseOptions(this.options, options, true); + // calculate the translations of all points + for (i = 0; i < this.dataPoints.length; i++) { + var trans = this._convertPointToTranslation(this.dataPoints[i].point); + var screen = this._convertTranslationToScreen(trans); - 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 = parseInt(options.value); - } + this.dataPoints[i].trans = trans; + this.dataPoints[i].screen = screen; + } - // update label Module - this.updateLabelModule(); + // start the line + if (this.dataPoints.length > 0) { + point = this.dataPoints[0]; - var dataChanged = this.updateEdgeType(); + ctx.lineWidth = 1; // TODO: make customizable + ctx.strokeStyle = 'blue'; // TODO: make customizable + ctx.beginPath(); + ctx.moveTo(point.screen.x, point.screen.y); + } - // if anything has been updates, reset the selection width and the hover width - this._setInteractionWidths(); + // draw the datapoints as colored circles + for (i = 1; i < this.dataPoints.length; i++) { + point = this.dataPoints[i]; + ctx.lineTo(point.screen.x, point.screen.y); + } - // A node is connected when it has a from and to node that both exist in the network.body.nodes. - this.connect(); + // finish the line + if (this.dataPoints.length > 0) { + ctx.stroke(); + } + }; - if (options.hidden !== undefined || options.physics !== undefined) { - dataChanged = true; - } + /** + * Start a moving operation inside the provided parent element + * @param {Event} event The event that occurred (required for + * retrieving the mouse position) + */ + Graph3d.prototype._onMouseDown = function (event) { + event = event || window.event; - return dataChanged; - } - }, { - key: 'updateLabelModule', + // check if mouse is still down (may be up when focus is lost for example + // in an iframe) + if (this.leftButtonDown) { + this._onMouseUp(event); + } - /** - * update the options in the label module - */ - value: function updateLabelModule() { - this.labelModule.setOptions(this.options, true); - if (this.labelModule.baseSize !== undefined) { - this.baseFontSize = this.labelModule.baseSize; - } - } - }, { - key: 'updateEdgeType', + // only react on left mouse button down + this.leftButtonDown = event.which ? event.which === 1 : event.button === 1; + if (!this.leftButtonDown && !this.touchDown) return; - /** - * update the edge type, set the options - * @returns {boolean} - */ - value: function updateEdgeType() { - var dataChanged = false; - var changeInType = true; - if (this.edgeType !== undefined) { - if (this.edgeType instanceof _edgesBezierEdgeDynamic2['default'] && this.options.smooth.enabled === true && this.options.smooth.type === 'dynamic') { - changeInType = false; - } - if (this.edgeType instanceof _edgesBezierEdgeStatic2['default'] && this.options.smooth.enabled === true && this.options.smooth.type !== 'dynamic') { - changeInType = false; - } - if (this.edgeType instanceof _edgesStraightEdge2['default'] && this.options.smooth.enabled === false) { - changeInType = false; - } + // get mouse position (different code for IE and all other browsers) + this.startMouseX = getMouseX(event); + this.startMouseY = getMouseY(event); - if (changeInType === true) { - dataChanged = this.edgeType.cleanup(); - } - } + this.startStart = new Date(this.start); + this.startEnd = new Date(this.end); + this.startArmRotation = this.camera.getArmRotation(); - if (changeInType === true) { - if (this.options.smooth.enabled === true) { - if (this.options.smooth.type === 'dynamic') { - dataChanged = true; - this.edgeType = new _edgesBezierEdgeDynamic2['default'](this.options, this.body, this.labelModule); - } else { - this.edgeType = new _edgesBezierEdgeStatic2['default'](this.options, this.body, this.labelModule); - } - } else { - this.edgeType = new _edgesStraightEdge2['default'](this.options, this.body, this.labelModule); - } - } else { - // if nothing changes, we just set the options. - this.edgeType.setOptions(this.options); - } + this.frame.style.cursor = 'move'; - return dataChanged; - } - }, { - key: 'togglePhysics', + // 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', me.onmousemove); + util.addEventListener(document, 'mouseup', me.onmouseup); + util.preventDefault(event); + }; - /** - * Enable or disable the physics. - * @param status - */ - value: function togglePhysics(status) { - this.options.physics = status; - this.edgeType.togglePhysics(status); - } - }, { - key: 'connect', + /** + * Perform moving operating. + * This function activated from within the funcion Graph.mouseDown(). + * @param {Event} event Well, eehh, the event + */ + Graph3d.prototype._onMouseMove = function (event) { + event = event || window.event; - /** - * Connect an edge to its nodes - */ - value: function connect() { - this.disconnect(); + // calculate change in mouse position + var diffX = parseFloat(getMouseX(event)) - this.startMouseX; + var diffY = parseFloat(getMouseY(event)) - this.startMouseY; - this.from = this.body.nodes[this.fromId] || undefined; - this.to = this.body.nodes[this.toId] || undefined; - this.connected = this.from !== undefined && this.to !== undefined; + var horizontalNew = this.startArmRotation.horizontal + diffX / 200; + var verticalNew = this.startArmRotation.vertical + diffY / 200; - 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); - } - } + var snapAngle = 4; // degrees + var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI); - this.edgeType.connect(); - } - }, { - key: 'disconnect', + // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc... + // the -0.001 is to take care that the vertical axis is always drawn at the left front corner + if (Math.abs(Math.sin(horizontalNew)) < snapValue) { + horizontalNew = Math.round(horizontalNew / Math.PI) * Math.PI - 0.001; + } + if (Math.abs(Math.cos(horizontalNew)) < snapValue) { + horizontalNew = (Math.round(horizontalNew / Math.PI - 0.5) + 0.5) * Math.PI - 0.001; + } - /** - * Disconnect an edge from its nodes - */ - value: function disconnect() { - if (this.from) { - this.from.detachEdge(this); - this.from = undefined; - } - if (this.to) { - this.to.detachEdge(this); - this.to = undefined; - } + // snap vertically to nice angles + if (Math.abs(Math.sin(verticalNew)) < snapValue) { + verticalNew = Math.round(verticalNew / Math.PI) * Math.PI; + } + if (Math.abs(Math.cos(verticalNew)) < snapValue) { + verticalNew = (Math.round(verticalNew / Math.PI - 0.5) + 0.5) * Math.PI; + } - this.connected = false; - } - }, { - key: 'getTitle', + this.camera.setArmRotation(horizontalNew, verticalNew); + this.redraw(); - /** - * get the title of this edge. - * @return {string} title The title of the edge, or undefined when no title - * has been set. - */ - value: function getTitle() { - return this.title; - } - }, { - key: 'isSelected', + // fire a cameraPositionChange event + var parameters = this.getCameraPosition(); + this.emit('cameraPositionChange', parameters); - /** - * check if this node is selecte - * @return {boolean} selected True if node is selected, else false - */ - value: function isSelected() { - return this.selected; - } - }, { - key: 'getValue', + util.preventDefault(event); + }; - /** - * Retrieve the value of the edge. Can be undefined - * @return {Number} value - */ - value: function getValue() { - return this.options.value; - } - }, { - key: 'setValueRange', + /** + * Stop moving operating. + * This function activated from within the funcion Graph.mouseDown(). + * @param {event} event The event + */ + Graph3d.prototype._onMouseUp = function (event) { + this.frame.style.cursor = 'auto'; + this.leftButtonDown = false; - /** - * 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 total - */ - 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; - } + // remove event listeners here + util.removeEventListener(document, 'mousemove', this.onmousemove); + util.removeEventListener(document, 'mouseup', this.onmouseup); + util.preventDefault(event); + }; - this._setInteractionWidths(); - } - }, { - 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; - } + /** + * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point + * @param {Event} event A mouse move event + */ + Graph3d.prototype._onTooltip = function (event) { + var delay = 300; // ms + var boundingRect = this.frame.getBoundingClientRect(); + var mouseX = getMouseX(event) - boundingRect.left; + var mouseY = getMouseY(event) - boundingRect.top; - if (typeof this.options.selectionWidth === 'function') { - this.edgeType.selectionWidth = this.options.selectionWidth(this.options.width); + if (!this.showTooltip) { + return; + } + + if (this.tooltipTimeout) { + clearTimeout(this.tooltipTimeout); + } + + // (delayed) display of a tooltip only if no mouse button is down + if (this.leftButtonDown) { + this._hideTooltip(); + return; + } + + if (this.tooltip && this.tooltip.dataPoint) { + // tooltip is currently visible + var dataPoint = this._dataPointFromXY(mouseX, mouseY); + if (dataPoint !== this.tooltip.dataPoint) { + // datapoint changed + if (dataPoint) { + this._showTooltip(dataPoint); } else { - this.edgeType.selectionWidth = this.options.selectionWidth + this.options.width; + this._hideTooltip(); } } - }, { - key: 'draw', + } else { + // tooltip is currently not visible + var me = this; + this.tooltipTimeout = setTimeout(function () { + me.tooltipTimeout = null; - /** - * 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 - */ - value: function draw(ctx) { - var via = this.edgeType.drawLine(ctx, this.selected, this.hover); - this.drawArrows(ctx, via); - this.drawLabel(ctx, via); - } - }, { - key: 'drawArrows', - value: function drawArrows(ctx, viaNode) { - if (this.options.arrows.from.enabled === true) { - this.edgeType.drawArrowHead(ctx, 'from', viaNode, this.selected, this.hover); - } - if (this.options.arrows.middle.enabled === true) { - this.edgeType.drawArrowHead(ctx, 'middle', viaNode, this.selected, this.hover); - } - if (this.options.arrows.to.enabled === true) { - this.edgeType.drawArrowHead(ctx, 'to', viaNode, this.selected, this.hover); + // show a tooltip if we have a data point + var dataPoint = me._dataPointFromXY(mouseX, mouseY); + if (dataPoint) { + me._showTooltip(dataPoint); } - } - }, { - key: 'drawLabel', - value: function drawLabel(ctx, viaNode) { - if (this.options.label !== undefined) { - // set style - var node1 = this.from; - var node2 = this.to; - var selected = this.from.selected || this.to.selected || this.selected; - if (node1.id != node2.id) { - var point = this.edgeType.getPoint(0.5, viaNode); - ctx.save(); + }, delay); + } + }; - // if the label has to be rotated: - if (this.options.font.align !== 'horizontal') { - this.labelModule.calculateLabelSize(ctx, selected, point.x, point.y); - ctx.translate(point.x, this.labelModule.size.yLine); - this._rotateForLabelAlignment(ctx); - } + /** + * Event handler for touchstart event on mobile devices + */ + Graph3d.prototype._onTouchStart = function (event) { + this.touchDown = true; - // draw the label - this.labelModule.draw(ctx, point.x, point.y, selected); - ctx.restore(); - } else { - 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, selected); - } - } - } - }, { - key: 'isOverlappingWith', + var me = this; + this.ontouchmove = function (event) { + me._onTouchMove(event); + }; + this.ontouchend = function (event) { + me._onTouchEnd(event); + }; + util.addEventListener(document, 'touchmove', me.ontouchmove); + util.addEventListener(document, 'touchend', me.ontouchend); - /** - * 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 - */ - 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; + this._onMouseDown(event); + }; - var dist = this.edgeType.getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj); + /** + * Event handler for touchmove event on mobile devices + */ + Graph3d.prototype._onTouchMove = function (event) { + this._onMouseMove(event); + }; - return dist < distMax; - } else { - return false; - } - } - }, { - key: '_rotateForLabelAlignment', + /** + * Event handler for touchend event on mobile devices + */ + Graph3d.prototype._onTouchEnd = function (event) { + this.touchDown = false; - /** - * Rotates the canvas so the text is most readable - * @param {CanvasRenderingContext2D} ctx - * @private - */ - value: function _rotateForLabelAlignment(ctx) { - var dy = this.from.y - this.to.y; - var dx = this.from.x - this.to.x; - var angleInDegrees = Math.atan2(dy, dx); + util.removeEventListener(document, 'touchmove', this.ontouchmove); + util.removeEventListener(document, 'touchend', this.ontouchend); - // rotate so label it is readable - if (angleInDegrees < -1 && dx < 0 || angleInDegrees > 0 && dx < 0) { - angleInDegrees = angleInDegrees + Math.PI; - } + this._onMouseUp(event); + }; - ctx.rotate(angleInDegrees); - } - }, { - key: '_pointOnCircle', + /** + * Event handler for mouse wheel event, used to zoom the graph + * Code from http://adomas.org/javascript-mouse-wheel/ + * @param {event} event The event + */ + Graph3d.prototype._onWheel = function (event) { + if (!event) /* For IE. */ + event = window.event; - /** - * 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 - */ - 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) - }; - } - }, { - key: 'select', - value: function select() { - this.selected = true; - } - }, { - key: 'unselect', - value: function unselect() { - this.selected = false; - } - }], [{ - key: 'parseOptions', - value: function parseOptions(parentOptions, newOptions) { - var allowDeletion = arguments[2] === undefined ? false : arguments[2]; + // 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; + } - var fields = ['id', 'from', 'hidden', 'hoverWidth', 'label', 'length', 'line', 'opacity', 'physics', 'selectionWidth', 'selfReferenceSize', 'to', 'title', 'value', 'width']; + // 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) { + var oldLength = this.camera.getArmLength(); + var newLength = oldLength * (1 - delta / 10); - // only deep extend the items in the field array. These do not have shorthand. - util.selectiveDeepExtend(fields, parentOptions, newOptions, allowDeletion); + this.camera.setArmLength(newLength); + this.redraw(); - util.mergeOptions(parentOptions, newOptions, 'smooth'); - util.mergeOptions(parentOptions, newOptions, 'shadow'); + this._hideTooltip(); + } - if (newOptions.dashes !== undefined && newOptions.dashes !== null) { - parentOptions.dashes = newOptions.dashes; - } else if (allowDeletion === true && newOptions.dashes === null) { - parentOptions.dashes = undefined; - delete parentOptions.dashes; - } + // fire a cameraPositionChange event + var parameters = this.getCameraPosition(); + this.emit('cameraPositionChange', parameters); - // 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'); - } else if (allowDeletion === true && newOptions.scaling === null) { - parentOptions.scaling = undefined; - delete parentOptions.scaling; - } + // Prevent default actions caused by mouse wheel. + // That might be ugly, but we handle scrolls somehow + // anyway, so don't bother here.. + util.preventDefault(event); + }; - // hanlde multiple input cases for arrows - if (newOptions.arrows !== undefined && newOptions.arrows !== null) { - if (typeof newOptions.arrows === 'string') { - var arrows = newOptions.arrows.toLowerCase(); - if (arrows.indexOf('to') != -1) { - parentOptions.arrows.to.enabled = true; - } - if (arrows.indexOf('middle') != -1) { - parentOptions.arrows.middle.enabled = true; - } - if (arrows.indexOf('from') != -1) { - parentOptions.arrows.from.enabled = true; - } - } else if (typeof newOptions.arrows === 'object') { - util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'to'); - util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'middle'); - util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'from'); - } else { - throw new Error('The arrow newOptions can only be an object or a string. Refer to the documentation. You used:' + JSON.stringify(newOptions.arrows)); - } - } else if (allowDeletion === true && newOptions.arrows === null) { - parentOptions.arrows = undefined; - delete parentOptions.arrows; - } + /** + * Test whether a point lies inside given 2D triangle + * @param {Point2d} point + * @param {Point2d[]} triangle + * @return {boolean} Returns true if given point lies inside or on the edge of the triangle + * @private + */ + Graph3d.prototype._insideTriangle = function (point, triangle) { + var a = triangle[0], + b = triangle[1], + c = triangle[2]; - // hanlde multiple input cases for color - if (newOptions.color !== undefined && newOptions.color !== null) { - if (util.isString(newOptions.color)) { - parentOptions.color.color = newOptions.color; - parentOptions.color.highlight = newOptions.color; - parentOptions.color.hover = newOptions.color; - parentOptions.color.inherit = false; - } else { - var colorsDefined = false; - if (newOptions.color.color !== undefined) { - parentOptions.color.color = newOptions.color.color;colorsDefined = true; - } - if (newOptions.color.highlight !== undefined) { - parentOptions.color.highlight = newOptions.color.highlight;colorsDefined = true; - } - if (newOptions.color.hover !== undefined) { - parentOptions.color.hover = newOptions.color.hover;colorsDefined = true; - } - if (newOptions.color.inherit !== undefined) { - parentOptions.color.inherit = newOptions.color.inherit; - } - if (newOptions.color.opacity !== undefined) { - parentOptions.color.opacity = Math.min(1, Math.max(0, newOptions.color.opacity)); - } + function sign(x) { + return x > 0 ? 1 : x < 0 ? -1 : 0; + } - if (newOptions.color.inherit === undefined && colorsDefined === true) { - parentOptions.color.inherit = false; + var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x)); + var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x)); + var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x)); + + // each of the three signs must be either equal to each other or zero + return (as == 0 || bs == 0 || as == bs) && (bs == 0 || cs == 0 || bs == cs) && (as == 0 || cs == 0 || as == cs); + }; + + /** + * Find a data point close to given screen position (x, y) + * @param {Number} x + * @param {Number} y + * @return {Object | null} The closest data point or null if not close to any data point + * @private + */ + Graph3d.prototype._dataPointFromXY = function (x, y) { + var i, + distMax = 100, + // px + dataPoint = null, + closestDataPoint = null, + closestDist = null, + center = new Point2d(x, y); + + if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { + // the data points are ordered from far away to closest + for (i = this.dataPoints.length - 1; i >= 0; i--) { + dataPoint = this.dataPoints[i]; + var surfaces = dataPoint.surfaces; + if (surfaces) { + for (var s = surfaces.length - 1; s >= 0; s--) { + // split each surface in two triangles, and see if the center point is inside one of these + var surface = surfaces[s]; + var corners = surface.corners; + var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen]; + var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen]; + if (this._insideTriangle(center, triangle1) || this._insideTriangle(center, triangle2)) { + // return immediately at the first hit + return dataPoint; } } - } else if (allowDeletion === true && newOptions.color === null) { - parentOptions.color = undefined; - delete parentOptions.color; } + } + } else { + // find the closest data point, using distance to the center of the point on 2d screen + for (i = 0; i < this.dataPoints.length; i++) { + dataPoint = this.dataPoints[i]; + var point = dataPoint.screen; + if (point) { + var distX = Math.abs(x - point.x); + var distY = Math.abs(y - point.y); + var dist = Math.sqrt(distX * distX + distY * distY); - // handle the font settings - if (newOptions.font !== undefined) { - _sharedLabel2['default'].parseOptions(parentOptions.font, newOptions); + if ((closestDist === null || dist < closestDist) && dist < distMax) { + closestDist = dist; + closestDataPoint = dataPoint; + } } } - }]); - - return Edge; - })(); - - exports['default'] = Edge; - module.exports = exports['default']; - -/***/ }, -/* 10 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var Hammer = __webpack_require__(13); - var util = __webpack_require__(2); - var DataSet = __webpack_require__(22); - var DataView = __webpack_require__(24); - var TimeStep = __webpack_require__(44); - var Component = __webpack_require__(35); - var Group = __webpack_require__(41); - var BackgroundGroup = __webpack_require__(45); - var BoxItem = __webpack_require__(5); - var PointItem = __webpack_require__(46); - var RangeItem = __webpack_require__(43); - var BackgroundItem = __webpack_require__(47); + } - var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items - var BACKGROUND = '__background__'; // reserved group id for background items without group + return closestDataPoint; + }; /** - * 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 + * Display a tooltip for given data point + * @param {Object} dataPoint + * @private */ - function ItemSet(body, options) { - this.body = body; + Graph3d.prototype._showTooltip = function (dataPoint) { + var content, line, dot; - this.defaultOptions = { - type: null, // 'box', 'point', 'range', 'background' - orientation: { - item: 'bottom' // item orientation: 'top' or 'bottom' - }, - align: 'auto', // alignment of box items - stack: true, - groupOrder: null, + if (!this.tooltip) { + content = document.createElement('div'); + content.style.position = 'absolute'; + content.style.padding = '10px'; + content.style.border = '1px solid #4d4d4d'; + content.style.color = '#1a1a1a'; + content.style.background = 'rgba(255,255,255,0.7)'; + content.style.borderRadius = '2px'; + content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)'; - selectable: true, - multiselect: false, + line = document.createElement('div'); + line.style.position = 'absolute'; + line.style.height = '40px'; + line.style.width = '0'; + line.style.borderLeft = '1px solid #4d4d4d'; - editable: { - updateTime: false, - updateGroup: false, - add: false, - remove: false - }, + dot = document.createElement('div'); + dot.style.position = 'absolute'; + dot.style.height = '0'; + dot.style.width = '0'; + dot.style.border = '5px solid #4d4d4d'; + dot.style.borderRadius = '5px'; - snap: TimeStep.snap, - - 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); - }, - - margin: { - item: { - horizontal: 10, - vertical: 10 - }, - axis: 20 - } - }; - - // options is shared by this ItemSet and all its items - this.options = util.extend({}, this.defaultOptions); - - // 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) { - me._onAdd(params.items); - }, - 'update': function update(event, params, senderId) { - me._onUpdate(params.items); - }, - 'remove': function remove(event, params, senderId) { - me._onRemove(params.items); - } - }; - - // listeners for the DataSet of the groups - this.groupListeners = { - 'add': function add(event, params, senderId) { - me._onAddGroups(params.items); - }, - 'update': function update(event, params, senderId) { - me._onUpdateGroups(params.items); - }, - 'remove': function remove(event, params, senderId) { - me._onRemoveGroups(params.items); - } - }; - - this.items = {}; // object with an Item for every data item - this.groups = {}; // Group object for every group - this.groupIds = []; + this.tooltip = { + dataPoint: null, + dom: { + content: content, + line: line, + dot: dot + } + }; + } else { + content = this.tooltip.dom.content; + line = this.tooltip.dom.line; + dot = this.tooltip.dom.dot; + } - this.selection = []; // list with the ids of all selected nodes - this.stackDirty = true; // if true, all items will be restacked on next redraw + this._hideTooltip(); - this.touchParams = {}; // stores properties while dragging - // create the HTML DOM + this.tooltip.dataPoint = dataPoint; + if (typeof this.showTooltip === 'function') { + content.innerHTML = this.showTooltip(dataPoint.point); + } else { + content.innerHTML = '' + '' + '' + '' + '
x:' + dataPoint.point.x + '
y:' + dataPoint.point.y + '
z:' + dataPoint.point.z + '
'; + } - this._create(); + content.style.left = '0'; + content.style.top = '0'; + this.frame.appendChild(content); + this.frame.appendChild(line); + this.frame.appendChild(dot); - this.setOptions(options); - } + // calculate sizes + var contentWidth = content.offsetWidth; + var contentHeight = content.offsetHeight; + var lineHeight = line.offsetHeight; + var dotWidth = dot.offsetWidth; + var dotHeight = dot.offsetHeight; - ItemSet.prototype = new Component(); + var left = dataPoint.screen.x - contentWidth / 2; + left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth); - // available item types will be registered here - ItemSet.types = { - background: BackgroundItem, - box: BoxItem, - range: RangeItem, - point: PointItem + line.style.left = dataPoint.screen.x + 'px'; + line.style.top = dataPoint.screen.y - lineHeight + 'px'; + content.style.left = left + 'px'; + content.style.top = dataPoint.screen.y - lineHeight - contentHeight + 'px'; + dot.style.left = dataPoint.screen.x - dotWidth / 2 + 'px'; + dot.style.top = dataPoint.screen.y - dotHeight / 2 + 'px'; }; /** - * Create the HTML DOM for the ItemSet + * Hide the tooltip when displayed + * @private */ - 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); + Graph3d.prototype._hideTooltip = function () { + if (this.tooltip) { + this.tooltip.dataPoint = null; - // drag items when selected - this.hammer.on('hammer.input', (function (event) { - if (event.isFirst) { - this._onTouch(event); + for (var prop in this.tooltip.dom) { + if (this.tooltip.dom.hasOwnProperty(prop)) { + var elem = this.tooltip.dom[prop]; + if (elem && elem.parentNode) { + elem.parentNode.removeChild(elem); + } + } } - }).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)); - - // 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)); + /**--------------------------------------------------------------------------**/ - // attach to the DOM - this.show(); - }; + /** + * Get the horizontal mouse position from a mouse event + * @param {Event} event + * @return {Number} mouse x + */ + function getMouseX(event) { + if ('clientX' in event) return event.clientX; + return event.targetTouches[0] && event.targetTouches[0].clientX || 0; + } /** - * 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. + * Get the vertical mouse position from a mouse event + * @param {Event} event + * @return {Number} mouse y */ - ItemSet.prototype.setOptions = function (options) { - if (options) { - // copy all options that we know - var fields = ['type', 'align', 'order', 'stack', 'selectable', 'multiselect', 'groupOrder', 'dataAttributes', 'template', 'hide', 'snap']; - util.selectiveExtend(fields, this.options, options); + function getMouseY(event) { + if ('clientY' in event) return event.clientY; + return event.targetTouches[0] && event.targetTouches[0].clientY || 0; + } - if ('orientation' in options) { - if (typeof options.orientation === 'string') { - this.options.orientation.item = options.orientation === 'top' ? 'top' : 'bottom'; - } else if (typeof options.orientation === 'object' && 'item' in options.orientation) { - this.options.orientation.item = options.orientation.item; - } - } + module.exports = Graph3d; - 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 (typeof 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 (typeof options.margin.item === 'object') { - util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item); - } - } - } - } + // use use defaults - 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; - } else if (typeof options.editable === 'object') { - util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable); - } - } +/***/ }, +/* 8 */ +/***/ function(module, exports, __webpack_require__) { - // 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); - ['onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving'].forEach(addCallback); + 'use strict'; - // force the itemSet to refresh: options like orientation and margins may be changed - this.markDirty(); - } - }; + var Point3d = __webpack_require__(11); /** - * 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] + * @class Camera + * 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 */ - ItemSet.prototype.markDirty = function (options) { - this.groupIds = []; - this.stackDirty = true; + function Camera() { + this.armLocation = new Point3d(); + this.armRotation = {}; + this.armRotation.horizontal = 0; + this.armRotation.vertical = 0; + this.armLength = 1.7; - if (options && options.refreshItems) { - util.forEach(this.items, function (item) { - item.dirty = true; - if (item.displayed) item.redraw(); - }); - } - }; + this.cameraLocation = new Point3d(); + this.cameraRotation = new Point3d(0.5 * Math.PI, 0, 0); + + this.calculateCameraOrientation(); + } /** - * Destroy the ItemSet + * 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 */ - ItemSet.prototype.destroy = function () { - this.hide(); - this.setItems(null); - this.setGroups(null); - - this.hammer = null; + Camera.prototype.setArmLocation = function (x, y, z) { + this.armLocation.x = x; + this.armLocation.y = y; + this.armLocation.z = z; - this.body = null; - this.conversion = null; + this.calculateCameraOrientation(); }; /** - * Hide the component from the DOM + * 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. */ - ItemSet.prototype.hide = function () { - // remove the frame containing the items - if (this.dom.frame.parentNode) { - this.dom.frame.parentNode.removeChild(this.dom.frame); + Camera.prototype.setArmRotation = function (horizontal, vertical) { + if (horizontal !== undefined) { + this.armRotation.horizontal = horizontal; } - // remove the axis with dots - if (this.dom.axis.parentNode) { - this.dom.axis.parentNode.removeChild(this.dom.axis); + 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; } - // remove the labelset containing all group labels - if (this.dom.labelSet.parentNode) { - this.dom.labelSet.parentNode.removeChild(this.dom.labelSet); + if (horizontal !== undefined || vertical !== undefined) { + this.calculateCameraOrientation(); } }; /** - * Show the component in the DOM (when not already visible). - * @return {Boolean} changed + * Retrieve the current arm rotation + * @return {object} An object with parameters horizontal and vertical */ - 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); - } + Camera.prototype.getArmRotation = function () { + var rot = {}; + rot.horizontal = this.armRotation.horizontal; + rot.vertical = this.armRotation.vertical; - // show labelset containing labels - if (!this.dom.labelSet.parentNode) { - this.body.dom.left.appendChild(this.dom.labelSet); - } + return rot; }; /** - * 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. + * Set the (normalized) length of the camera arm. + * @param {Number} length A length between 0.71 and 5.0 */ - ItemSet.prototype.setSelection = function (ids) { - var i, ii, id, item; + Camera.prototype.setArmLength = function (length) { + if (length === undefined) return; - if (ids == undefined) ids = []; - if (!Array.isArray(ids)) ids = [ids]; + this.armLength = length; - // 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(); - } + // 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) this.armLength = 5; - // 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(); - } - } + this.calculateCameraOrientation(); }; /** - * Get the selected items by their id - * @return {Array} ids The ids of the selected items + * Retrieve the arm length + * @return {Number} length */ - ItemSet.prototype.getSelection = function () { - return this.selection.concat([]); + Camera.prototype.getArmLength = function () { + return this.armLength; }; /** - * Get the id's of the currently visible items. - * @returns {Array} The ids of the visible items + * Retrieve the camera location + * @return {Point3d} cameraLocation */ - ItemSet.prototype.getVisibleItems = function () { - var range = this.body.range.getRange(); - var left = this.body.util.toScreen(range.start); - var right = this.body.util.toScreen(range.end); + Camera.prototype.getCameraLocation = function () { + return this.cameraLocation; + }; - var ids = []; - for (var groupId in this.groups) { - if (this.groups.hasOwnProperty(groupId)) { - var group = this.groups[groupId]; - var rawVisibleItems = 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 (item.left < right && item.left + item.width > left) { - ids.push(item.id); - } - } - } - } - - return ids; - }; + /** + * Retrieve the camera rotation + * @return {Point3d} cameraRotation + */ + Camera.prototype.getCameraRotation = function () { + return this.cameraRotation; + }; /** - * Deselect a selected item - * @param {String | Number} id - * @private + * Calculate the location and rotation of the camera based on the + * position and orientation of the camera arm */ - 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; - } - } + 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; }; - /** - * 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, - editable = options.editable.updateTime || options.editable.updateGroup; + module.exports = Camera; - // recalculate absolute position (before redrawing groups) - this.props.top = this.body.domProps.top.height + this.body.domProps.border.top; - this.props.left = this.body.domProps.left.width + this.body.domProps.border.left; +/***/ }, +/* 9 */ +/***/ function(module, exports, __webpack_require__) { - // update class name - frame.className = 'vis-itemset' + (editable ? ' vis-editable' : ''); + 'use strict'; - // reorder the groups (if needed) - resized = this._orderGroups() || resized; + var DataView = __webpack_require__(5); - // 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; - if (zoomed) this.stackDirty = true; - this.lastVisibleInterval = visibleInterval; - this.props.lastWidth = this.props.width; + /** + * @class Filter + * + * @param {DataSet} data The google data table + * @param {Number} column The index of the column to be filtered + * @param {Graph} graph The graph + */ + function Filter(data, column, graph) { + this.data = data; + this.column = column; + this.graph = graph; // the parent graph - var restack = this.stackDirty; - 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; + this.index = undefined; + this.value = undefined; - // redraw the background group - this.groups[BACKGROUND].redraw(range, nonFirstMargin, restack); + // read all distinct values and select the first one + this.values = graph.getDistinctValues(data.get(), this.column); - // redraw all regular groups - util.forEach(this.groups, function (group) { - var groupMargin = group == firstGroup ? firstMargin : nonFirstMargin; - var groupResized = group.redraw(range, groupMargin, restack); - resized = groupResized || resized; - height += group.height; + // sort both numeric and string values correctly + this.values.sort(function (a, b) { + return a > b ? 1 : a < b ? -1 : 0; }); - height = Math.max(height, minHeight); - this.stackDirty = false; - // update frame height - frame.style.height = asSize(height); + if (this.values.length > 0) { + this.selectValue(0); + } - // calculate actual size - this.props.width = frame.offsetWidth; - this.props.height = height; + // create an array with the filtered datapoints. this will be loaded afterwards + this.dataPoints = []; - // 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); - this.dom.axis.style.left = '0'; + this.loaded = false; + this.onLoadCallback = undefined; - // check if this component is resized - resized = this._isResized() || resized; + if (graph.animationPreload) { + this.loaded = false; + this.loadInBackground(); + } else { + this.loaded = true; + } + }; - return resized; + /** + * Return the label + * @return {string} label + */ + Filter.prototype.isLoaded = function () { + return this.loaded; }; /** - * Get the first group, aligned with the axis - * @return {Group | null} firstGroup - * @private + * Return the loaded progress + * @return {Number} percentage between 0 and 100 */ - 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]; + Filter.prototype.getLoadedProgress = function () { + var len = this.values.length; - return firstGroup || null; + var i = 0; + while (this.dataPoints[i]) { + i++; + } + + return Math.round(i / len * 100); }; /** - * Create or delete the group holding all ungrouped items. This group is used when - * there are no groups specified. - * @protected + * Return the label + * @return {string} label */ - ItemSet.prototype._updateUngrouped = function () { - var ungrouped = this.groups[UNGROUPED]; - var background = this.groups[BACKGROUND]; - var item, itemId; + Filter.prototype.getLabel = function () { + return this.graph.filterLabel; + }; - if (this.groupsData) { - // remove the group holding all ungrouped items - if (ungrouped) { - ungrouped.hide(); - delete this.groups[UNGROUPED]; + /** + * Return the columnIndex of the filter + * @return {Number} columnIndex + */ + Filter.prototype.getColumn = function () { + return this.column; + }; - 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; + /** + * Return the currently selected value. Returns undefined if there is no selection + * @return {*} value + */ + Filter.prototype.getSelectedValue = function () { + if (this.index === undefined) return undefined; - for (itemId in this.items) { - if (this.items.hasOwnProperty(itemId)) { - item = this.items[itemId]; - ungrouped.add(item); - } - } + return this.values[this.index]; + }; - ungrouped.show(); - } - } + /** + * Retrieve all values of the filter + * @return {Array} values + */ + Filter.prototype.getValues = function () { + return this.values; }; /** - * Get the element for the labelset - * @return {HTMLElement} labelSet + * Retrieve one value of the filter + * @param {Number} index + * @return {*} value */ - ItemSet.prototype.getLabelSet = function () { - return this.dom.labelSet; + Filter.prototype.getValue = function (index) { + if (index >= this.values.length) throw 'Error: index out of range'; + + return this.values[index]; }; /** - * Set items - * @param {vis.DataSet | null} items + * Retrieve the (filtered) dataPoints for the currently selected filter index + * @param {Number} [index] (optional) + * @return {Array} dataPoints */ - ItemSet.prototype.setItems = function (items) { - var me = this, - ids, - oldItemsData = this.itemsData; + Filter.prototype._getDataPoints = function (index) { + if (index === undefined) index = this.index; - // replace the dataset - if (!items) { - this.itemsData = null; - } else if (items instanceof DataSet || items instanceof DataView) { - this.itemsData = items; + if (index === undefined) return []; + + var dataPoints; + if (this.dataPoints[index]) { + dataPoints = this.dataPoints[index]; } else { - throw new TypeError('Data must be an instance of DataSet or DataView'); - } + var f = {}; + f.column = this.column; + f.value = this.values[index]; - if (oldItemsData) { - // unsubscribe from old dataset - util.forEach(this.itemListeners, function (callback, event) { - oldItemsData.off(event, callback); - }); + var dataView = new DataView(this.data, { filter: function filter(item) { + return item[f.column] == f.value; + } }).get(); + dataPoints = this.graph._getDataPoints(dataView); - // remove all drawn items - ids = oldItemsData.getIds(); - this._onRemove(ids); + this.dataPoints[index] = dataPoints; } - 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); + return dataPoints; + }; - // update the group holding all ungrouped items - this._updateUngrouped(); - } + /** + * Set a callback function when the filter is fully loaded. + */ + Filter.prototype.setOnLoadCallback = function (callback) { + this.onLoadCallback = callback; }; /** - * Get the current items - * @returns {vis.DataSet | null} + * Add a value to the list with available values for this filter + * No double entries will be created. + * @param {Number} index */ - ItemSet.prototype.getItems = function () { - return this.itemsData; + Filter.prototype.selectValue = function (index) { + if (index >= this.values.length) throw 'Error: index out of range'; + + this.index = index; + this.value = this.values[index]; }; /** - * Set groups - * @param {vis.DataSet} groups + * Load all filtered rows in the background one by one + * Start this method without providing an index! */ - ItemSet.prototype.setGroups = function (groups) { - var me = this, - ids; + Filter.prototype.loadInBackground = function (index) { + if (index === undefined) index = 0; - // unsubscribe from current dataset - if (this.groupsData) { - util.forEach(this.groupListeners, function (callback, event) { - me.groupsData.off(event, callback); - }); + var frame = this.graph.frame; - // remove all drawn groups - ids = this.groupsData.getIds(); - this.groupsData = null; - this._onRemoveGroups(ids); // note: this will cause a redraw - } + if (index < this.values.length) { + var dataPointsTemp = this._getDataPoints(index); + //this.graph.redrawInfo(); // TODO: not neat - // replace the dataset - if (!groups) { - this.groupsData = null; - } else if (groups instanceof DataSet || groups instanceof DataView) { - this.groupsData = groups; + // 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 { - throw new TypeError('Data must be an instance of DataSet or DataView'); - } + this.loaded = true; - if (this.groupsData) { - // subscribe to new dataset - var id = this.id; - util.forEach(this.groupListeners, function (callback, event) { - me.groupsData.on(event, callback, id); - }); + // remove the progress box + if (frame.progress !== undefined) { + frame.removeChild(frame.progress); + frame.progress = undefined; + } - // draw all ms - ids = this.groupsData.getIds(); - this._onAddGroups(ids); + if (this.onLoadCallback) this.onLoadCallback(); } + }; - // update the group holding all ungrouped items - this._updateUngrouped(); + module.exports = Filter; - // update the order of all items in each group - this._order(); +/***/ }, +/* 10 */ +/***/ function(module, exports, __webpack_require__) { - this.body.emitter.emit('change', { queue: true }); - }; + /** + * @prototype Point2d + * @param {Number} [x] + * @param {Number} [y] + */ + "use strict"; + + function Point2d(x, y) { + this.x = x !== undefined ? x : 0; + this.y = y !== undefined ? y : 0; + } + + module.exports = Point2d; + +/***/ }, +/* 11 */ +/***/ function(module, exports, __webpack_require__) { /** - * Get the current groups - * @returns {vis.DataSet | null} groups + * @prototype Point3d + * @param {Number} [x] + * @param {Number} [y] + * @param {Number} [z] */ - ItemSet.prototype.getGroups = function () { - return this.groupsData; + "use strict"; + + function Point3d(x, y, z) { + this.x = x !== undefined ? x : 0; + this.y = y !== undefined ? y : 0; + this.z = z !== undefined ? z : 0; }; /** - * Remove an item by its id - * @param {String | Number} id + * Subtract the two provided points, returns a-b + * @param {Point3d} a + * @param {Point3d} b + * @return {Point3d} a-b */ - 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); - } - }); - } + 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; }; /** - * Get the time of an item based on it's data and options.type - * @param {Object} itemData - * @returns {string} Returns the type - * @private + * Add the two provided points, returns a+b + * @param {Point3d} a + * @param {Point3d} b + * @return {Point3d} a+b */ - ItemSet.prototype._getType = function (itemData) { - return itemData.type || this.options.type || (itemData.end ? 'range' : 'box'); + 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; }; /** - * Get the group id for an item - * @param {Object} itemData - * @returns {string} Returns the groupId - * @private + * Calculate the average of two 3d points + * @param {Point3d} a + * @param {Point3d} b + * @return {Point3d} The average, (a+b)/2 */ - 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; - } + Point3d.avg = function (a, b) { + return new Point3d((a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2); }; /** - * Handle updated items - * @param {Number[]} ids - * @protected + * 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 */ - ItemSet.prototype._onUpdate = function (ids) { - var me = this; + Point3d.crossProduct = function (a, b) { + var crossproduct = new Point3d(); - ids.forEach((function (id) { - var itemData = me.itemsData.get(id, me.itemOptions); - var item = me.items[id]; - var type = me._getType(itemData); + 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; - var constructor = ItemSet.types[type]; - var selected; + return crossproduct; + }; - 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); - } - } + /** + * 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); + }; - if (!item) { - // 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)); + module.exports = Point3d; - this._order(); - this.stackDirty = true; // force re-stacking of all items next redraw - this.body.emitter.emit('change', { queue: true }); - }; +/***/ }, +/* 12 */ +/***/ function(module, exports, __webpack_require__) { - /** - * Handle added items - * @param {Number[]} ids - * @protected - */ - ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate; + 'use strict'; + + var util = __webpack_require__(2); /** - * Handle removed items - * @param {Number[]} ids - * @protected + * @constructor Slider + * + * An html slider control with start/stop/prev/next buttons + * @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. */ - 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); - } - }); + function Slider(container, options) { + if (container === undefined) { + throw 'Error: No container element defined'; + } + this.container = container; + this.visible = options && options.visible != undefined ? options.visible : true; - if (count) { - // update order - this._order(); - this.stackDirty = true; // force re-stacking of all items next redraw - this.body.emitter.emit('change', { queue: 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; + } /** - * Update the order of item in all groups - * @private + * Select the previous index */ - 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(); - }); + Slider.prototype.prev = function () { + var index = this.getIndex(); + if (index > 0) { + index--; + this.setIndex(index); + } }; /** - * Handle updated groups - * @param {Number[]} ids - * @private + * Select the next index */ - ItemSet.prototype._onUpdateGroups = function (ids) { - this._onAddGroups(ids); + Slider.prototype.next = function () { + var index = this.getIndex(); + if (index < this.values.length - 1) { + index++; + this.setIndex(index); + } }; /** - * Handle changed groups (added or updated) - * @param {Number[]} ids - * @private + * Select the next index */ - 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 = Object.create(me.options); - util.extend(groupOptions, { - height: null - }); + Slider.prototype.playNext = function () { + var start = new Date(); - group = new Group(id, groupData, me); - me.groups[id] = group; + 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); + } - // 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); - } - } - } + var end = new Date(); + var diff = end - start; - group.order(); - group.show(); - } else { - // update group - group.setData(groupData); - } - }); + // 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 - this.body.emitter.emit('change', { queue: true }); + var me = this; + this.playTimeout = setTimeout(function () { + me.playNext(); + }, interval); }; /** - * Handle removed groups - * @param {Number[]} ids - * @private + * Toggle start or stop playing */ - 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 }); + Slider.prototype.togglePlay = function () { + if (this.playTimeout === undefined) { + this.play(); + } else { + this.stop(); + } }; /** - * Reorder the groups if needed - * @return {boolean} changed - * @private + * Start playing */ - ItemSet.prototype._orderGroups = function () { - if (this.groupsData) { - // reorder the groups - var groupIds = this.groupsData.getIds({ - order: this.options.groupOrder - }); + Slider.prototype.play = function () { + // Test whether already playing + if (this.playTimeout) return; - 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(); - }); + this.playNext(); - // show the groups again, attach them to the DOM in correct order - groupIds.forEach(function (groupId) { - groups[groupId].show(); - }); + if (this.frame) { + this.frame.play.value = 'Stop'; + } + }; - this.groupIds = groupIds; - } + /** + * Stop playing + */ + Slider.prototype.stop = function () { + clearInterval(this.playTimeout); + this.playTimeout = undefined; - return changed; - } else { - return false; + if (this.frame) { + this.frame.play.value = 'Play'; } }; /** - * Add a new item - * @param {Item} item - * @private + * Set a callback function which will be triggered when the value of the + * slider bar has changed. */ - 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) group.add(item); + Slider.prototype.setOnChangeCallback = function (callback) { + this.onChangeCallback = callback; }; /** - * Update an existing item - * @param {Item} item - * @param {Object} itemData - * @private + * Set the interval for playing the list + * @param {Number} interval The interval in milliseconds */ - ItemSet.prototype._updateItem = function (item, itemData) { - var oldGroupId = item.data.group; - var oldSubGroupId = item.data.subgroup; + Slider.prototype.setPlayInterval = function (interval) { + this.playInterval = interval; + }; - // update the items data (will redraw the item when displayed) - item.setData(itemData); + /** + * Retrieve the current play interval + * @return {Number} interval The interval in milliseconds + */ + Slider.prototype.getPlayInterval = function (interval) { + return this.playInterval; + }; - // update group - if (oldGroupId != item.data.group || oldSubGroupId != item.data.subgroup) { - var oldGroup = this.groups[oldGroupId]; - if (oldGroup) oldGroup.remove(item); + /** + * Set looping on or off + * @pararm {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; + }; - var groupId = this._getGroupId(item.data); - var group = this.groups[groupId]; - if (group) group.add(item); + /** + * Execute the onchange callback function + */ + Slider.prototype.onChange = function () { + if (this.onChangeCallback !== undefined) { + this.onChangeCallback(); } }; /** - * 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 + * redraw the slider on the correct place */ - ItemSet.prototype._removeItem = function (item) { - // remove from DOM - item.hide(); + 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'; - // remove from items - delete this.items[item.id]; + // position the slider button + var left = this.indexToLeft(this.index); + this.frame.slide.style.left = left + 'px'; + } + }; - // remove from selection - var index = this.selection.indexOf(item.id); - if (index != -1) this.selection.splice(index, 1); + /** + * 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; - // remove from group - item.parent && item.parent.remove(item); + if (this.values.length > 0) this.setIndex(0);else this.index = undefined; }; /** - * Create an array containing all items being a range (having an end date) - * @param array - * @returns {Array} - * @private + * Select a value by its index + * @param {Number} index */ - ItemSet.prototype._constructByEndArray = function (array) { - var endArray = []; + Slider.prototype.setIndex = function (index) { + if (index < this.values.length) { + this.index = index; - for (var i = 0; i < array.length; i++) { - if (array[i] instanceof RangeItem) { - endArray.push(array[i]); - } + this.redraw(); + this.onChange(); + } else { + throw 'Error: index out of range'; } - return endArray; }; /** - * Register the clicked item on touch, before dragStart is initiated. - * - * dragStart is initiated from a mousemove event, AFTER the mouse/touch is - * already moving. Therefore, the mouse/touch can sometimes be above an other - * DOM element than the item itself. - * - * @param {Event} event - * @private + * retrieve the index of the currently selected vaue + * @return {Number} index */ - ItemSet.prototype._onTouch = function (event) { - // store the touched item, used in _onDragStart - this.touchParams.item = this.itemFromTarget(event); - this.touchParams.dragLeftItem = event.target.dragLeftItem || false; - this.touchParams.dragRightItem = event.target.dragRightItem || false; - this.touchParams.itemProps = null; + Slider.prototype.getIndex = function () { + return this.index; }; /** - * Start dragging the selected events - * @param {Event} event - * @private + * retrieve the currently selected value + * @return {*} value */ - ItemSet.prototype._onDragStart = function (event) { - if (!this.options.editable.updateTime && !this.options.editable.updateGroup) { - return; - } + Slider.prototype.get = function () { + return this.values[this.index]; + }; - var item = this.touchParams.item || null; - var me = this; - var props; + 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; - if (item && item.selected) { - var dragLeftItem = this.touchParams.dragLeftItem; - var dragRightItem = this.touchParams.dragRightItem; + this.startClientX = event.clientX; + this.startSlideX = parseFloat(this.frame.slide.style.left); - if (dragLeftItem) { - props = { - item: dragLeftItem, - initialX: event.center.x, - dragLeft: true, - data: util.extend({}, item.data) // clone the items data - }; + this.frame.style.cursor = 'move'; - this.touchParams.itemProps = [props]; - } else if (dragRightItem) { - props = { - item: dragRightItem, - initialX: event.center.x, - dragRight: true, - data: util.extend({}, item.data) // clone the items data - }; + // 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); + }; - this.touchParams.itemProps = [props]; - } else { - this.touchParams.itemProps = this.getSelection().map(function (id) { - var item = me.items[id]; - var props = { - item: item, - initialX: event.center.x, - data: util.extend({}, item.data) // clone the items data - }; + Slider.prototype.leftToIndex = function (left) { + var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10; + var x = left - 3; - return props; - }); - } + 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; - event.stopPropagation(); - } else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) { - // create a new range item when dragging with ctrl key down - this._onDragStartAddItem(event); - } + return index; }; - /** - * Start creating a new range item by dragging. - * @param {Event} event - * @private - */ - ItemSet.prototype._onDragStartAddItem = function (event) { - var snap = this.options.snap || null; - var xAbs = util.getAbsoluteLeft(this.dom.frame); - var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px - var time = this.body.util.toTime(x); - var scale = this.body.util.getScale(); - var step = this.body.util.getStep(); - var start = snap ? snap(time, scale, step) : start; - var end = start; + Slider.prototype.indexToLeft = function (index) { + var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10; - var itemData = { - type: 'range', - start: start, - end: end, - content: 'new item' - }; + var x = index / (this.values.length - 1) * width; + var left = x + 3; - var id = util.randomUUID(); - itemData[this.itemsData._fieldId] = id; - - var group = this.groupFromTarget(event); - if (group) { - itemData.group = group.groupId; - } - - var newItem = new RangeItem(itemData, this.conversion, this.options); - newItem.id = id; // TODO: not so nice setting id afterwards - newItem.data = itemData; - this._addItem(newItem); - - var props = { - item: newItem, - dragRight: true, - initialX: event.center.x, - data: util.extend({}, itemData) - }; - this.touchParams.itemProps = [props]; - - event.stopPropagation(); + return left; }; - /** - * Drag selected items - * @param {Event} event - * @private - */ - ItemSet.prototype._onDrag = function (event) { - if (this.touchParams.itemProps) { - event.stopPropagation(); - - var me = this; - var snap = this.options.snap || null; - var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width; - var scale = this.body.util.getScale(); - var step = this.body.util.getStep(); + Slider.prototype._onMouseMove = function (event) { + var diff = event.clientX - this.startClientX; + var x = this.startSlideX + diff; - // move - this.touchParams.itemProps.forEach(function (props) { - var newProps = {}; - var current = me.body.util.toTime(event.center.x - xOffset); - var initial = me.body.util.toTime(props.initialX - xOffset); - var offset = current - initial; + var index = this.leftToIndex(x); - var itemData = util.extend({}, props.item.data); // clone the data + this.setIndex(index); - if (me.options.editable.updateTime) { - if (props.dragLeft) { - // drag left side of a range item - if (itemData.start != undefined) { - var initialStart = util.convert(props.data.start, 'Date'); - var start = new Date(initialStart.valueOf() + offset); - itemData.start = snap ? snap(start, scale, step) : start; - } - } else if (props.dragRight) { - // drag right side of a range item - if (itemData.end != undefined) { - var initialEnd = util.convert(props.data.end, 'Date'); - var end = new Date(initialEnd.valueOf() + offset); - itemData.end = snap ? snap(end, scale, step) : end; - } - } else { - // drag both start and end - if (itemData.start != undefined) { - var initialStart = util.convert(props.data.start, 'Date').valueOf(); - var start = new Date(initialStart + offset); + util.preventDefault(); + }; - if (itemData.end != undefined) { - var initialEnd = util.convert(props.data.end, 'Date'); - var duration = initialEnd.valueOf() - initialStart.valueOf(); + Slider.prototype._onMouseUp = function (event) { + this.frame.style.cursor = 'auto'; - itemData.start = snap ? snap(start, scale, step) : start; - itemData.end = new Date(itemData.start.valueOf() + duration); - } else { - itemData.start = snap ? snap(start, scale, step) : start; - } - } - } - } + // remove event listeners + util.removeEventListener(document, 'mousemove', this.onmousemove); + util.removeEventListener(document, 'mouseup', this.onmouseup); - if (me.options.editable.updateGroup && (!props.dragLeft && !props.dragRight)) { - if (itemData.group != undefined) { - // drag from one group to another - var group = me.groupFromTarget(event); - if (group) { - itemData.group = group.groupId; - } - } - } + util.preventDefault(); + }; - // confirm moving the item - me.options.onMoving(itemData, function (itemData) { - if (itemData) { - props.item.setData(itemData); - } - }); - }); + module.exports = Slider; - this.stackDirty = true; // force re-stacking of all items next redraw - this.body.emitter.emit('change'); - } - }; +/***/ }, +/* 13 */ +/***/ function(module, exports, __webpack_require__) { /** - * Move an item to another group - * @param {Item} item - * @param {String | Number} groupId - * @private + * @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, ...) */ - ItemSet.prototype._moveToGroup = function (item, groupId) { - var group = this.groups[groupId]; - if (group && group.groupId != item.data.group) { - var oldGroup = item.parent; - oldGroup.remove(item); - oldGroup.order(); - group.add(item); - group.order(); + "use strict"; - item.data.group = group.groupId; - } + 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); }; /** - * End of dragging selected items - * @param {Event} event - * @private + * 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, ...) */ - ItemSet.prototype._onDragEnd = function (event) { - if (this.touchParams.itemProps) { - event.stopPropagation(); - - // prepare a change set for the changed items - var changes = []; - var me = this; - var dataset = this.itemsData.getDataSet(); - - var itemProps = this.touchParams.itemProps; - this.touchParams.itemProps = null; - itemProps.forEach(function (props) { - var id = props.item.id; - var exists = me.itemsData.get(id, me.itemOptions) != null; - - if (!exists) { - // add a new item - me.options.onAdd(props.item.data, function (itemData) { - me._removeItem(props.item); // remove temporary item - if (itemData) { - me.itemsData.getDataSet().add(itemData); - } - - // force re-stacking of all items next redraw - me.stackDirty = true; - me.body.emitter.emit('change'); - }); - } else { - // update existing item - var itemData = util.extend({}, props.item.data); // clone the data - me.options.onMove(itemData, function (itemData) { - if (itemData) { - // apply changes - itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined) - changes.push(itemData); - } else { - // restore original values - props.item.setData(props.data); - - me.stackDirty = true; // force re-stacking of all items next redraw - me.body.emitter.emit('change'); - } - }); - } - }); + StepNumber.prototype.setRange = function (start, end, step, prettyStep) { + this._start = start ? start : 0; + this._end = end ? end : 0; - // apply the changes to the data (if there are changes) - if (changes.length) { - dataset.update(changes); - } - } + this.setStep(step, prettyStep); }; /** - * Handle selecting/deselecting an item when tapping it - * @param {Event} event - * @private + * 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, ...) */ - ItemSet.prototype._onSelectItem = function (event) { - if (!this.options.selectable) return; - - var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey); - var shiftKey = event.srcEvent && event.srcEvent.shiftKey; - if (ctrlKey || shiftKey) { - this._onMultiSelectItem(event); - return; - } - - var oldSelection = this.getSelection(); - - var item = this.itemFromTarget(event); - var selection = item ? [item.id] : []; - this.setSelection(selection); + StepNumber.prototype.setStep = function (step, prettyStep) { + if (step === undefined || step <= 0) return; - var newSelection = this.getSelection(); + if (prettyStep !== undefined) this.prettyStep = prettyStep; - // emit a select event, - // except when old selection is empty and new selection is still empty - if (newSelection.length > 0 || oldSelection.length > 0) { - this.body.emitter.emit('select', { - items: newSelection - }); - } + if (this.prettyStep === true) this._step = StepNumber.calculatePrettyStep(step);else this._step = step; }; /** - * Handle creation and updates of an item on double tap - * @param event - * @private + * 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 */ - ItemSet.prototype._onAddItem = function (event) { - if (!this.options.selectable) return; - if (!this.options.editable.add) return; - - var me = this; - var snap = this.options.snap || null; - var item = this.itemFromTarget(event); - - event.stopPropagation(); - - if (item) { - // update item - - // execute async handler to update the item (or cancel it) - var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset - this.options.onUpdate(itemData, function (itemData) { - if (itemData) { - me.itemsData.getDataSet().update(itemData); - } - }); - } else { - // add item - var xAbs = util.getAbsoluteLeft(this.dom.frame); - var x = event.center.x - xAbs; - var start = this.body.util.toTime(x); - var scale = this.body.util.getScale(); - var step = this.body.util.getStep(); - - var newItem = { - start: snap ? snap(start, scale, step) : start, - content: 'new item' - }; - - // when default type is a range, add a default end date to the new item - if (this.options.type === 'range') { - var end = this.body.util.toTime(x + this.props.width / 5); - newItem.end = snap ? snap(end, scale, step) : end; - } + StepNumber.calculatePrettyStep = function (step) { + var log10 = function log10(x) { + return Math.log(x) / Math.LN10; + }; - newItem[this.itemsData._fieldId] = util.randomUUID(); + // 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))); - var group = this.groupFromTarget(event); - if (group) { - newItem.group = group.groupId; - } + // 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; - // execute async handler to customize (or cancel) adding an item - this.options.onAdd(newItem, function (item) { - if (item) { - me.itemsData.getDataSet().add(item); - // TODO: need to trigger a redraw? - } - }); + // for safety + if (prettyStep <= 0) { + prettyStep = 1; } + + return prettyStep; }; /** - * Handle selecting/deselecting multiple items when holding an item - * @param {Event} event - * @private + * returns the current value of the step + * @return {Number} current value */ - ItemSet.prototype._onMultiSelectItem = function (event) { - if (!this.options.selectable) return; - - var item = this.itemFromTarget(event); - - if (item) { - // multi select items (if allowed) - - var selection = this.options.multiselect ? this.getSelection() // take current selection - : []; // deselect current selection - - var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false; - - if (shiftKey && this.options.multiselect) { - // select all items between the old selection and the tapped item - - // determine the selection range - selection.push(item.id); - var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions)); - - // select all items within the selection range - selection = []; - for (var id in this.items) { - if (this.items.hasOwnProperty(id)) { - var _item = this.items[id]; - var start = _item.data.start; - var end = _item.data.end !== undefined ? _item.data.end : start; - - if (start >= range.min && end <= range.max && !(_item instanceof BackgroundItem)) { - selection.push(_item.id); // do not use id but item.id, id itself is stringified - } - } - } - } else { - // add/remove this item from the current selection - var index = selection.indexOf(item.id); - if (index == -1) { - // item is not yet selected -> select it - selection.push(item.id); - } else { - // item is already selected -> deselect it - selection.splice(index, 1); - } - } - - this.setSelection(selection); - - this.body.emitter.emit('select', { - items: this.getSelection() - }); - } + StepNumber.prototype.getCurrent = function () { + return parseFloat(this._current.toPrecision(this.precision)); }; /** - * Calculate the time range of a list of items - * @param {Array.} itemsData - * @return {{min: Date, max: Date}} Returns the range of the provided items - * @private + * returns the current step size + * @return {Number} current step size */ - ItemSet._getItemRange = function (itemsData) { - var max = null; - var min = null; - - itemsData.forEach(function (data) { - if (min == null || data.start < min) { - min = data.start; - } - - if (data.end != undefined) { - if (max == null || data.end > max) { - max = data.end; - } - } else { - if (max == null || data.start > max) { - max = data.start; - } - } - }); - - return { - min: min, - max: max - }; + StepNumber.prototype.getStep = function () { + return this._step; }; /** - * Find an item from an event target: - * searches for the attribute 'timeline-item' in the event target's element tree - * @param {Event} event - * @return {Item | null} item + * Set the current value to the largest value smaller than start, which + * is a multiple of the step size */ - ItemSet.prototype.itemFromTarget = function (event) { - var target = event.target; - while (target) { - if (target.hasOwnProperty('timeline-item')) { - return target['timeline-item']; - } - target = target.parentNode; - } - - return null; + StepNumber.prototype.start = function () { + this._current = this._start - this._start % this._step; }; /** - * Find the Group from an event target: - * searches for the attribute 'timeline-group' in the event target's element tree - * @param {Event} event - * @return {Group | null} group + * Do a step, add the step size to the current value */ - ItemSet.prototype.groupFromTarget = function (event) { - var clientY = event.center ? event.center.y : event.clientY; - for (var i = 0; i < this.groupIds.length; i++) { - var groupId = this.groupIds[i]; - var group = this.groups[groupId]; - var foreground = group.dom.foreground; - var top = util.getAbsoluteTop(foreground); - if (clientY > top && clientY < top + foreground.offsetHeight) { - return group; - } - - if (this.options.orientation.item === 'top') { - if (i === this.groupIds.length - 1 && clientY > top) { - return group; - } - } else { - if (i === 0 && clientY < top + foreground.offset) { - return group; - } - } - } - - return null; + StepNumber.prototype.next = function () { + this._current += this._step; }; /** - * Find the ItemSet from an event target: - * searches for the attribute 'timeline-itemset' in the event target's element tree - * @param {Event} event - * @return {ItemSet | null} item + * Returns true whether the end is reached + * @return {boolean} True if the current value has passed the end value. */ - ItemSet.itemSetFromTarget = function (event) { - var target = event.target; - while (target) { - if (target.hasOwnProperty('timeline-itemset')) { - return target['timeline-itemset']; - } - target = target.parentNode; - } - - return null; + StepNumber.prototype.end = function () { + return this._current > this._end; }; - module.exports = ItemSet; + module.exports = StepNumber; /***/ }, -/* 11 */ +/* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Hammer = __webpack_require__(13); + var Emitter = __webpack_require__(43); + var Hammer = __webpack_require__(41); var util = __webpack_require__(2); + var DataSet = __webpack_require__(4); + var DataView = __webpack_require__(5); + var Range = __webpack_require__(18); + var Core = __webpack_require__(44); + var TimeAxis = __webpack_require__(35); + var CurrentTime = __webpack_require__(26); + var CustomTime = __webpack_require__(27); + var ItemSet = __webpack_require__(32); + + var Configurator = __webpack_require__(45); + var Validator = __webpack_require__(46)['default']; + var printStyle = __webpack_require__(46).printStyle; + var allOptions = __webpack_require__(47).allOptions; + var configureOptions = __webpack_require__(47).configureOptions; /** - * @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 + * Create a timeline visualization + * @param {HTMLElement} container + * @param {vis.DataSet | vis.DataView | Array} [items] + * @param {vis.DataSet | vis.DataView | Array} [groups] + * @param {Object} [options] See Timeline.setOptions for the available options. + * @constructor + * @extends Core */ - function Item(data, conversion, options) { - this.id = null; - this.parent = null; - this.data = data; - this.dom = null; - this.conversion = conversion || {}; - this.options = options || {}; + function Timeline(container, items, groups, options) { + if (!(this instanceof Timeline)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } - this.selected = false; - this.displayed = false; - this.dirty = true; + // if the third element is options, the forth is groups (optionally); + if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) { + var forthArgument = options; + options = groups; + groups = forthArgument; + } - this.top = null; - this.left = null; - this.width = null; - this.height = null; - } + var me = this; + this.defaultOptions = { + start: null, + end: null, - Item.prototype.stack = true; + autoResize: true, - /** - * Select current item - */ - Item.prototype.select = function () { - this.selected = true; - this.dirty = true; - if (this.displayed) this.redraw(); - }; + orientation: { + axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both' + item: 'bottom' // not relevant + }, - /** - * Unselect current item - */ - Item.prototype.unselect = function () { - this.selected = false; - this.dirty = true; - if (this.displayed) this.redraw(); - }; + width: null, + height: null, + maxHeight: null, + minHeight: null + }; + this.options = util.deepExtend({}, this.defaultOptions); - /** - * 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.itemSet._moveToGroup(this, data.group); - } + // Create the DOM, props, and emitter + this._create(container); - this.data = data; - this.dirty = true; - if (this.displayed) this.redraw(); - }; + // all components listed here will be repainted automatically + this.components = []; - /** - * Set a parent for the item - * @param {ItemSet | Group} parent - */ - Item.prototype.setParent = function (parent) { - if (this.displayed) { - this.hide(); - this.parent = parent; - if (this.parent) { - this.show(); + this.body = { + dom: this.dom, + domProps: this.props, + emitter: { + on: this.on.bind(this), + off: this.off.bind(this), + emit: this.emit.bind(this) + }, + hiddenDates: [], + util: { + getScale: function getScale() { + return me.timeAxis.step.scale; + }, + getStep: function getStep() { + return me.timeAxis.step.step; + }, + + toScreen: me._toScreen.bind(me), + toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width + toTime: me._toTime.bind(me), + toGlobalTime: me._toGlobalTime.bind(me) } - } else { - this.parent = parent; - } - }; + }; - /** - * Check whether this item is visible inside given range - * @returns {{start: Number, end: Number}} range with a timestamp for start and end - * @returns {boolean} True if visible - */ - Item.prototype.isVisible = function (range) { - // Should be implemented by Item implementations - return false; - }; + // range + this.range = new Range(this.body); + this.components.push(this.range); + this.body.range = this.range; - /** - * Show the Item in the DOM (when not already visible) - * @return {Boolean} changed - */ - Item.prototype.show = function () { - return false; - }; + // time axis + this.timeAxis = new TimeAxis(this.body); + this.timeAxis2 = null; // used in case of orientation option 'both' + this.components.push(this.timeAxis); - /** - * Hide the Item from the DOM (when visible) - * @return {Boolean} changed - */ - Item.prototype.hide = function () { - return false; - }; + // current time bar + this.currentTime = new CurrentTime(this.body); + this.components.push(this.currentTime); - /** - * Repaint the item - */ - Item.prototype.redraw = function () {}; + // item set + this.itemSet = new ItemSet(this.body); + this.components.push(this.itemSet); - /** - * Reposition the Item horizontally - */ - Item.prototype.repositionX = function () {}; + this.itemsData = null; // DataSet + this.groupsData = null; // DataSet - /** - * Reposition the Item vertically - */ - Item.prototype.repositionY = function () {}; + this.on('tap', function (event) { + me.emit('click', me.getEventProperties(event)); + }); + this.on('doubletap', function (event) { + me.emit('doubleClick', me.getEventProperties(event)); + }); + this.dom.root.oncontextmenu = function (event) { + me.emit('contextmenu', me.getEventProperties(event)); + }; + + // setup configuration system + this.configurator = new Configurator(this, container, configureOptions); + + // apply options + if (options) { + this.setOptions(options); + } + + // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! + if (groups) { + this.setGroups(groups); + } + + // create itemset + if (items) { + this.setItems(items); + } else { + this._redraw(); + } + } + + // Extend the functionality from Core + Timeline.prototype = new Core(); /** - * Repaint a delete button on the top right of the item when the item is selected - * @param {HTMLElement} anchor - * @protected + * Force a redraw. The size of all items will be recalculated. + * Can be useful to manually redraw when option autoResize=false and the window + * has been resized, or when the items CSS has been changed. */ - Item.prototype._repaintDeleteButton = function (anchor) { - if (this.selected && this.options.editable.remove && !this.dom.deleteButton) { - // create and show button - var me = this; + Timeline.prototype.redraw = function () { + this.itemSet && this.itemSet.markDirty({ refreshItems: true }); + this._redraw(); + }; - var deleteButton = document.createElement('div'); - deleteButton.className = 'vis-delete'; - deleteButton.title = 'Delete this item'; + Timeline.prototype.setOptions = function (options) { + // validate options + var errorFound = Validator.validate(options, allOptions); + if (errorFound === true) { + console.log('%cErrors have been found in the supplied options object.', printStyle); + } - // TODO: be able to destroy the delete button - new Hammer(deleteButton).on('tap', function (event) { - event.stopPropagation(); - me.parent.removeFromDataSet(me); - }); + Core.prototype.setOptions.call(this, options); - 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); + if ('type' in options) { + if (options.type !== this.options.type) { + this.options.type = options.type; + + // force recreation of all items + var itemsData = this.itemsData; + if (itemsData) { + var selection = this.getSelection(); + this.setItems(null); // remove all + this.setItems(itemsData); // add all + this.setSelection(selection); // restore selection + } } - this.dom.deleteButton = null; } }; /** - * Set HTML contents for the item - * @param {Element} element HTML element to fill with the contents - * @private + * Set items + * @param {vis.DataSet | Array | null} items */ - Item.prototype._updateContents = function (element) { - var content; - if (this.options.template) { - var itemData = this.parent.itemSet.itemsData.get(this.id); // get a clone of the data from the dataset - content = this.options.template(itemData); + Timeline.prototype.setItems = function (items) { + var initialLoad = this.itemsData == null; + + // convert to type DataSet when needed + var newDataSet; + if (!items) { + newDataSet = null; + } else if (items instanceof DataSet || items instanceof DataView) { + newDataSet = items; } else { - content = this.data.content; + // turn an array into a dataset + newDataSet = new DataSet(items, { + type: { + start: 'Date', + end: 'Date' + } + }); } - var 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); + // set items + this.itemsData = newDataSet; + this.itemSet && this.itemSet.setItems(newDataSet); + + if (initialLoad) { + if (this.options.start != undefined || this.options.end != undefined) { + if (this.options.start == undefined || this.options.end == undefined) { + var dataRange = this._getDataRange(); } - } - this.content = content; + var start = this.options.start != undefined ? this.options.start : dataRange.start; + var end = this.options.end != undefined ? this.options.end : dataRange.end; + + this.setWindow(start, end, { animation: false }); + } else { + this.fit({ animation: false }); + } } }; /** - * Set HTML contents for the item - * @param {Element} element HTML element to fill with the contents - * @private + * Set groups + * @param {vis.DataSet | Array} groups */ - Item.prototype._updateTitle = function (element) { - if (this.data.title != null) { - element.title = this.data.title || ''; + Timeline.prototype.setGroups = function (groups) { + // convert to type DataSet when needed + var newDataSet; + if (!groups) { + newDataSet = null; + } else if (groups instanceof DataSet || groups instanceof DataView) { + newDataSet = groups; } else { - element.removeAttribute('vis-title'); + // turn an array into a dataset + newDataSet = new DataSet(groups); } + + this.groupsData = newDataSet; + this.itemSet.setGroups(newDataSet); }; /** - * 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 + * Set both items and groups in one go + * @param {{items: Array | vis.DataSet, groups: Array | vis.DataSet}} data */ - 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 = Object.keys(this.data); - } else { - return; - } - - for (var i = 0; i < attributes.length; i++) { - var name = attributes[i]; - var value = this.data[name]; + Timeline.prototype.setData = function (data) { + if (data && data.groups) { + this.setGroups(data.groups); + } - if (value != null) { - element.setAttribute('data-' + name, value); - } else { - element.removeAttribute('data-' + name); - } - } + if (data && data.items) { + this.setItems(data.items); } }; /** - * Update custom styles of the element - * @param element - * @private + * 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. If ids is an empty array, all items will be + * unselected. + * @param {Object} [options] Available options: + * `focus: boolean` + * If true, focus will be set to the selected item(s) + * `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'. + * Only applicable when option focus is true. */ - Item.prototype._updateStyle = function (element) { - // remove old styles - if (this.style) { - util.removeCssText(element, this.style); - this.style = null; - } + Timeline.prototype.setSelection = function (ids, options) { + this.itemSet && this.itemSet.setSelection(ids); - // append new styles - if (this.data.style) { - util.addCssText(element, this.data.style); - this.style = this.data.style; + if (options && options.focus) { + this.focus(ids, options); } }; /** - * Stringify the items contents - * @param {string | Element | undefined} content - * @returns {string | undefined} - * @private + * Get the selected items by their id + * @return {Array} ids The ids of the selected items */ - Item.prototype._contentToString = function (content) { - if (typeof content === 'string') return content; - if (content && 'outerHTML' in content) return content.outerHTML; - return content; + Timeline.prototype.getSelection = function () { + return this.itemSet && this.itemSet.getSelection() || []; }; - module.exports = Item; - - // should be implemented by the item + /** + * Adjust the visible window such that the selected item (or multiple items) + * are centered on screen. + * @param {String | String[]} id An item id or array with item ids + * @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'. + */ + Timeline.prototype.focus = function (id, options) { + if (!this.itemsData || id == undefined) return; - // should be implemented by the item + var ids = Array.isArray(id) ? id : [id]; - // should be implemented by the item + // get the specified item(s) + var itemsData = this.itemsData.getDataSet().get(ids, { + type: { + start: 'Date', + end: 'Date' + } + }); -/***/ }, -/* 12 */ -/***/ function(module, exports, __webpack_require__) { + // calculate minimum start and maximum end of specified items + var start = null; + var end = null; + itemsData.forEach(function (itemData) { + var s = itemData.start.valueOf(); + var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf(); - 'use strict'; + if (start === null || s < start) { + start = s; + } - Object.defineProperty(exports, '__esModule', { - value: true - }); + if (end === null || e > end) { + end = e; + } + }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + if (start !== null && end !== null) { + // calculate the new middle and interval for the window + var middle = (start + end) / 2; + var interval = Math.max(this.range.end - this.range.start, (end - start) * 1.1); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var animation = options && options.animation !== undefined ? options.animation : true; + this.range.setRange(middle - interval / 2, middle + interval / 2, animation); + } + }; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * Get the data range of the item set. + * @returns {{min: Date, max: Date}} range A range with a start and end Date. + * When no minimum is found, min==null + * When no maximum is found, max==null + */ + Timeline.prototype.getItemRange = function () { + // calculate min from start filed + var dataset = this.itemsData && this.itemsData.getDataSet(); + var min = null; + var max = null; - var _componentsNavigationHandler = __webpack_require__(105); + if (dataset) { + // calculate the minimum value of the field 'start' + var minItem = dataset.min('start'); + min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null; + // Note: we convert first to Date and then to number because else + // a conversion from ISODate to Number will fail - var _componentsNavigationHandler2 = _interopRequireDefault(_componentsNavigationHandler); + // calculate maximum value of fields 'start' and 'end' + var maxStartItem = dataset.max('start'); + if (maxStartItem) { + max = util.convert(maxStartItem.start, 'Date').valueOf(); + } + var maxEndItem = dataset.max('end'); + if (maxEndItem) { + if (max == null) { + max = util.convert(maxEndItem.end, 'Date').valueOf(); + } else { + max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf()); + } + } + } - var _componentsPopup = __webpack_require__(106); + return { + min: min != null ? new Date(min) : null, + max: max != null ? new Date(max) : null + }; + }; - var _componentsPopup2 = _interopRequireDefault(_componentsPopup); + /** + * Generate Timeline related information from an event + * @param {Event} event + * @return {Object} An object with related information, like on which area + * The event happened, whether clicked on an item, etc. + */ + Timeline.prototype.getEventProperties = function (event) { + var clientX = event.center ? event.center.x : event.clientX; + var clientY = event.center ? event.center.y : event.clientY; + var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer); + var y = clientY - util.getAbsoluteTop(this.dom.centerContainer); - var util = __webpack_require__(2); + var item = this.itemSet.itemFromTarget(event); + var group = this.itemSet.groupFromTarget(event); + var customTime = CustomTime.customTimeFromTarget(event); - var InteractionHandler = (function () { - function InteractionHandler(body, canvas, selectionHandler) { - _classCallCheck(this, InteractionHandler); + var snap = this.itemSet.options.snap || null; + var scale = this.body.util.getScale(); + var step = this.body.util.getStep(); + var time = this._toTime(x); + var snappedTime = snap ? snap(time, scale, step) : time; - this.body = body; - this.canvas = canvas; - this.selectionHandler = selectionHandler; - this.navigationHandler = new _componentsNavigationHandler2['default'](body, canvas); + var element = util.getTarget(event); + var what = null; + if (item != null) { + what = 'item'; + } else if (customTime != null) { + what = 'custom-time'; + } else if (util.hasParent(element, this.timeAxis.dom.foreground)) { + what = 'axis'; + } else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) { + what = 'axis'; + } else if (util.hasParent(element, this.itemSet.dom.labelSet)) { + what = 'group-label'; + } else if (util.hasParent(element, this.currentTime.bar)) { + what = 'current-time'; + } else if (util.hasParent(element, this.dom.center)) { + what = 'background'; + } - // bind the events from hammer to functions in this object - this.body.eventListeners.onTap = this.onTap.bind(this); - this.body.eventListeners.onTouch = this.onTouch.bind(this); - this.body.eventListeners.onDoubleTap = this.onDoubleTap.bind(this); - this.body.eventListeners.onHold = this.onHold.bind(this); - this.body.eventListeners.onDragStart = this.onDragStart.bind(this); - this.body.eventListeners.onDrag = this.onDrag.bind(this); - this.body.eventListeners.onDragEnd = this.onDragEnd.bind(this); - this.body.eventListeners.onMouseWheel = this.onMouseWheel.bind(this); - this.body.eventListeners.onPinch = this.onPinch.bind(this); - this.body.eventListeners.onMouseMove = this.onMouseMove.bind(this); - this.body.eventListeners.onRelease = this.onRelease.bind(this); - this.body.eventListeners.onContext = this.onContext.bind(this); + return { + event: event, + item: item ? item.id : null, + group: group ? group.groupId : null, + what: what, + pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX, + pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY, + x: x, + y: y, + time: time, + snappedTime: snappedTime + }; + }; - this.touchTime = 0; - this.drag = {}; - this.pinch = {}; - this.popup = undefined; - this.popupObj = undefined; - this.popupTimer = undefined; + module.exports = Timeline; - this.body.functions.getPointer = this.getPointer.bind(this); +/***/ }, +/* 15 */ +/***/ function(module, exports, __webpack_require__) { - this.options = {}; - this.defaultOptions = { - dragNodes: true, - dragView: true, - hover: false, - keyboard: { - enabled: false, - speed: { x: 10, y: 10, zoom: 0.02 }, - bindToWindow: true - }, - navigationButtons: false, - tooltipDelay: 300, - zoomView: true - }; - util.extend(this.options, this.defaultOptions); + 'use strict'; - this.bindEventListeners(); + var Emitter = __webpack_require__(43); + var Hammer = __webpack_require__(41); + var util = __webpack_require__(2); + var DataSet = __webpack_require__(4); + var DataView = __webpack_require__(5); + var Range = __webpack_require__(18); + var Core = __webpack_require__(44); + var TimeAxis = __webpack_require__(35); + var CurrentTime = __webpack_require__(26); + var CustomTime = __webpack_require__(27); + var LineGraph = __webpack_require__(34); + + var Configurator = __webpack_require__(45); + var Validator = __webpack_require__(46)['default']; + var printStyle = __webpack_require__(46).printStyle; + var allOptions = __webpack_require__(48).allOptions; + var configureOptions = __webpack_require__(48).configureOptions; + + /** + * Create a timeline visualization + * @param {HTMLElement} container + * @param {vis.DataSet | Array} [items] + * @param {Object} [options] See Graph2d.setOptions for the available options. + * @constructor + * @extends Core + */ + function Graph2d(container, items, groups, options) { + // if the third element is options, the forth is groups (optionally); + if (!(Array.isArray(groups) || groups instanceof DataSet) && groups instanceof Object) { + var forthArgument = options; + options = groups; + groups = forthArgument; } - _createClass(InteractionHandler, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this = this; + var me = this; + this.defaultOptions = { + start: null, + end: null, - this.body.emitter.on('destroy', function () { - clearTimeout(_this.popupTimer); - delete _this.body.functions.getPointer; - }); - } - }, { - key: 'setOptions', - value: function setOptions(options) { - if (options !== undefined) { - // extend all but the values in fields - var fields = ['hideEdgesOnDrag', 'hideNodesOnDrag', 'keyboard', 'multiselect', 'selectable', 'selectConnectedEdges']; - util.selectiveNotDeepExtend(fields, this.options, options); + autoResize: true, - // merge the keyboard options in. - util.mergeOptions(this.options, options, 'keyboard'); + orientation: { + axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both' + item: 'bottom' // not relevant for Graph2d + }, - if (options.tooltip) { - util.extend(this.options.tooltip, options.tooltip); - if (options.tooltip.color) { - this.options.tooltip.color = util.parseColor(options.tooltip.color); - } - } - } + width: null, + height: null, + maxHeight: null, + minHeight: null + }; + this.options = util.deepExtend({}, this.defaultOptions); - this.navigationHandler.setOptions(this.options); - } - }, { - key: 'getPointer', + // Create the DOM, props, and emitter + this._create(container); - /** - * Get the pointer location from a touch location - * @param {{x: Number, y: Number}} touch - * @return {{x: Number, y: Number}} pointer - * @private - */ - value: function getPointer(touch) { - return { - x: touch.x - util.getAbsoluteLeft(this.canvas.frame.canvas), - y: touch.y - util.getAbsoluteTop(this.canvas.frame.canvas) - }; - } - }, { - key: 'onTouch', + // all components listed here will be repainted automatically + this.components = []; - /** - * On start of a touch gesture, store the pointer - * @param event - * @private - */ - value: function onTouch(event) { - if (new Date().valueOf() - this.touchTime > 50) { - this.drag.pointer = this.getPointer(event.center); - this.drag.pinched = false; - this.pinch.scale = this.body.view.scale; - // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame) - this.touchTime = new Date().valueOf(); - } + this.body = { + dom: this.dom, + domProps: this.props, + emitter: { + on: this.on.bind(this), + off: this.off.bind(this), + emit: this.emit.bind(this) + }, + hiddenDates: [], + util: { + toScreen: me._toScreen.bind(me), + toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width + toTime: me._toTime.bind(me), + toGlobalTime: me._toGlobalTime.bind(me) } - }, { - key: 'onTap', + }; - /** - * handle tap/click event: select/unselect a node - * @private - */ - value: function onTap(event) { - var pointer = this.getPointer(event.center); - var multiselect = this.selectionHandler.options.multiselect && (event.changedPointers[0].ctrlKey || event.changedPointers[0].metaKey); + // range + this.range = new Range(this.body); + this.components.push(this.range); + this.body.range = this.range; - this.checkSelectionChanges(pointer, event, multiselect); - this.selectionHandler._generateClickEvent('click', event, pointer); - } - }, { - key: 'onDoubleTap', + // time axis + this.timeAxis = new TimeAxis(this.body); + this.components.push(this.timeAxis); + //this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); - /** - * handle doubletap event - * @private - */ - value: function onDoubleTap(event) { - var pointer = this.getPointer(event.center); - this.selectionHandler._generateClickEvent('doubleClick', event, pointer); - } - }, { - key: 'onHold', + // current time bar + this.currentTime = new CurrentTime(this.body); + this.components.push(this.currentTime); - /** - * handle long tap event: multi select nodes - * @private - */ - value: function onHold(event) { - var pointer = this.getPointer(event.center); - var multiselect = this.selectionHandler.options.multiselect; + // item set + this.linegraph = new LineGraph(this.body); + this.components.push(this.linegraph); - this.checkSelectionChanges(pointer, event, multiselect); + this.itemsData = null; // DataSet + this.groupsData = null; // DataSet - this.selectionHandler._generateClickEvent('click', event, pointer); - this.selectionHandler._generateClickEvent('hold', event, pointer); - } - }, { - key: 'onRelease', + this.on('tap', function (event) { + me.emit('click', me.getEventProperties(event)); + }); + this.on('doubletap', function (event) { + me.emit('doubleClick', me.getEventProperties(event)); + }); + this.dom.root.oncontextmenu = function (event) { + me.emit('contextmenu', me.getEventProperties(event)); + }; - /** - * handle the release of the screen - * - * @private - */ - value: function onRelease(event) { - if (new Date().valueOf() - this.touchTime > 10) { - var pointer = this.getPointer(event.center); - this.selectionHandler._generateClickEvent('release', event, pointer); - // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame) - this.touchTime = new Date().valueOf(); - } - } - }, { - key: 'onContext', - value: function onContext(event) { - var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); - this.selectionHandler._generateClickEvent('oncontext', event, pointer); - } - }, { - key: 'checkSelectionChanges', + // setup configuration system + this.configurator = new Configurator(this, container, configureOptions); - /** - * - * @param pointer - * @param add - */ - value: function checkSelectionChanges(pointer, event) { - var add = arguments[2] === undefined ? false : arguments[2]; + // apply options + if (options) { + this.setOptions(options); + } - var previouslySelectedEdgeCount = this.selectionHandler._getSelectedEdgeCount(); - var previouslySelectedNodeCount = this.selectionHandler._getSelectedNodeCount(); - var previousSelection = this.selectionHandler.getSelection(); - var selected = undefined; - if (add === true) { - selected = this.selectionHandler.selectAdditionalOnPoint(pointer); - } else { - selected = this.selectionHandler.selectOnPoint(pointer); - } - var selectedEdgesCount = this.selectionHandler._getSelectedEdgeCount(); - var selectedNodesCount = this.selectionHandler._getSelectedNodeCount(); - var currentSelection = this.selectionHandler.getSelection(); + // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! + if (groups) { + this.setGroups(groups); + } - var _determineIfDifferent = this._determineIfDifferent(previousSelection, currentSelection); + // create itemset + if (items) { + this.setItems(items); + } else { + this._redraw(); + } + } - var nodesChanges = _determineIfDifferent.nodesChanges; - var edgesChanges = _determineIfDifferent.edgesChanges; + // Extend the functionality from Core + Graph2d.prototype = new Core(); - if (selectedNodesCount - previouslySelectedNodeCount > 0) { - // node was selected - this.selectionHandler._generateClickEvent('selectNode', event, pointer); - selected = true; - } else if (selectedNodesCount - previouslySelectedNodeCount < 0) { - // node was deselected - this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection); - selected = true; - } else if (selectedNodesCount === previouslySelectedNodeCount && nodesChanges === true) { - this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection); - this.selectionHandler._generateClickEvent('selectNode', event, pointer); - selected = true; - } + Graph2d.prototype.setOptions = function (options) { + // validate options + var errorFound = Validator.validate(options, allOptions); + if (errorFound === true) { + console.log('%cErrors have been found in the supplied options object.', printStyle); + } - if (selectedEdgesCount - previouslySelectedEdgeCount > 0) { - // edge was selected - this.selectionHandler._generateClickEvent('selectEdge', event, pointer); - selected = true; - } else if (selectedEdgesCount - previouslySelectedEdgeCount < 0) { - // edge was deselected - this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection); - selected = true; - } else if (selectedEdgesCount === previouslySelectedEdgeCount && edgesChanges === true) { - this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection); - this.selectionHandler._generateClickEvent('selectEdge', event, pointer); - selected = true; - } + Core.prototype.setOptions.call(this, options); + }; - if (selected === true) { - // select or unselect - this.selectionHandler._generateClickEvent('select', event, pointer); + /** + * Set items + * @param {vis.DataSet | Array | null} items + */ + Graph2d.prototype.setItems = function (items) { + var initialLoad = this.itemsData == null; + + // convert to type DataSet when needed + var newDataSet; + if (!items) { + newDataSet = null; + } else if (items instanceof DataSet || items instanceof DataView) { + newDataSet = items; + } else { + // turn an array into a dataset + newDataSet = new DataSet(items, { + type: { + start: 'Date', + end: 'Date' } - } - }, { - key: '_determineIfDifferent', + }); + } - /** - * This function checks if the nodes and edges previously selected have changed. - * @param previousSelection - * @param currentSelection - * @returns {{nodesChanges: boolean, edgesChanges: boolean}} - * @private - */ - value: function _determineIfDifferent(previousSelection, currentSelection) { - var nodesChanges = false; - var edgesChanges = false; + // set items + this.itemsData = newDataSet; + this.linegraph && this.linegraph.setItems(newDataSet); - for (var i = 0; i < previousSelection.nodes.length; i++) { - if (currentSelection.nodes.indexOf(previousSelection.nodes[i]) === -1) { - nodesChanges = true; - } - } - for (var i = 0; i < currentSelection.nodes.length; i++) { - if (previousSelection.nodes.indexOf(previousSelection.nodes[i]) === -1) { - nodesChanges = true; - } - } - for (var i = 0; i < previousSelection.edges.length; i++) { - if (currentSelection.edges.indexOf(previousSelection.edges[i]) === -1) { - edgesChanges = true; - } - } - for (var i = 0; i < currentSelection.edges.length; i++) { - if (previousSelection.edges.indexOf(previousSelection.edges[i]) === -1) { - edgesChanges = true; - } - } + if (initialLoad) { + if (this.options.start != undefined || this.options.end != undefined) { + var start = this.options.start != undefined ? this.options.start : null; + var end = this.options.end != undefined ? this.options.end : null; - return { nodesChanges: nodesChanges, edgesChanges: edgesChanges }; + this.setWindow(start, end, { animation: false }); + } else { + this.fit({ animation: false }); } - }, { - key: 'onDragStart', + } + }; - /** - * This function is called by onDragStart. - * It is separated out because we can then overload it for the datamanipulation system. - * - * @private - */ - value: function onDragStart(event) { - //in case the touch event was triggered on an external div, do the initial touch now. - if (this.drag.pointer === undefined) { - this.onTouch(event); - } + /** + * Set groups + * @param {vis.DataSet | Array} groups + */ + Graph2d.prototype.setGroups = function (groups) { + // convert to type DataSet when needed + var newDataSet; + if (!groups) { + newDataSet = null; + } else if (groups instanceof DataSet || groups instanceof DataView) { + newDataSet = groups; + } else { + // turn an array into a dataset + newDataSet = new DataSet(groups); + } - // note: drag.pointer is set in onTouch to get the initial touch location - var node = this.selectionHandler.getNodeAt(this.drag.pointer); + this.groupsData = newDataSet; + this.linegraph.setGroups(newDataSet); + }; - this.drag.dragging = true; - this.drag.selection = []; - this.drag.translation = util.extend({}, this.body.view.translation); // copy the object - this.drag.nodeId = undefined; + /** + * Returns an object containing an SVG element with the icon of the group (size determined by iconWidth and iconHeight), the label of the group (content) and the yAxisOrientation of the group (left or right). + * @param groupId + * @param width + * @param height + */ + Graph2d.prototype.getLegend = function (groupId, width, height) { + if (width === undefined) { + width = 15; + } + if (height === undefined) { + height = 15; + } + if (this.linegraph.groups[groupId] !== undefined) { + return this.linegraph.groups[groupId].getLegend(width, height); + } else { + return 'cannot find group:' + groupId; + } + }; - this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer); + /** + * This checks if the visible option of the supplied group (by ID) is true or false. + * @param groupId + * @returns {*} + */ + Graph2d.prototype.isGroupVisible = function (groupId) { + if (this.linegraph.groups[groupId] !== undefined) { + return this.linegraph.groups[groupId].visible && (this.linegraph.options.groups.visibility[groupId] === undefined || this.linegraph.options.groups.visibility[groupId] == true); + } else { + return false; + } + }; - if (node !== undefined && this.options.dragNodes === true) { - this.drag.nodeId = node.id; - // select the clicked node if not yet selected - if (node.isSelected() === false) { - this.selectionHandler.unselectAll(); - this.selectionHandler.selectObject(node); + /** + * Get the data range of the item set. + * @returns {{min: Date, max: Date}} range A range with a start and end Date. + * When no minimum is found, min==null + * When no maximum is found, max==null + */ + Graph2d.prototype.getItemRange = function () { + var min = null; + var max = null; + + // calculate min from start filed + for (var groupId in this.linegraph.groups) { + if (this.linegraph.groups.hasOwnProperty(groupId)) { + if (this.linegraph.groups[groupId].visible == true) { + for (var i = 0; i < this.linegraph.groups[groupId].itemsData.length; i++) { + var item = this.linegraph.groups[groupId].itemsData[i]; + var value = util.convert(item.x, 'Date').valueOf(); + min = min == null ? value : min > value ? value : min; + max = max == null ? value : max < value ? value : max; } + } + } + } - var selection = this.selectionHandler.selectionObj.nodes; - // create an array with the selected nodes and their original location and status - for (var nodeId in selection) { - if (selection.hasOwnProperty(nodeId)) { - var object = selection[nodeId]; - var s = { - id: object.id, - node: object, - - // store original x, y, xFixed and yFixed, make the node temporarily Fixed - x: object.x, - y: object.y, - xFixed: object.options.fixed.x, - yFixed: object.options.fixed.y - }; - - object.options.fixed.x = true; - object.options.fixed.y = true; + return { + min: min != null ? new Date(min) : null, + max: max != null ? new Date(max) : null + }; + }; - this.drag.selection.push(s); - } - } - } - } - }, { - key: 'onDrag', + /** + * Generate Timeline related information from an event + * @param {Event} event + * @return {Object} An object with related information, like on which area + * The event happened, whether clicked on an item, etc. + */ + Graph2d.prototype.getEventProperties = function (event) { + var clientX = event.center ? event.center.x : event.clientX; + var clientY = event.center ? event.center.y : event.clientY; + var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer); + var y = clientY - util.getAbsoluteTop(this.dom.centerContainer); + var time = this._toTime(x); - /** - * handle drag event - * @private - */ - value: function onDrag(event) { - var _this2 = this; + var customTime = CustomTime.customTimeFromTarget(event); - if (this.drag.pinched === true) { - return; - } + var element = util.getTarget(event); + var what = null; + if (util.hasParent(element, this.timeAxis.dom.foreground)) { + what = 'axis'; + } else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) { + what = 'axis'; + } else if (util.hasParent(element, this.linegraph.yAxisLeft.dom.frame)) { + what = 'data-axis'; + } else if (util.hasParent(element, this.linegraph.yAxisRight.dom.frame)) { + what = 'data-axis'; + } else if (util.hasParent(element, this.linegraph.legendLeft.dom.frame)) { + what = 'legend'; + } else if (util.hasParent(element, this.linegraph.legendRight.dom.frame)) { + what = 'legend'; + } else if (customTime != null) { + what = 'custom-time'; + } else if (util.hasParent(element, this.currentTime.bar)) { + what = 'current-time'; + } else if (util.hasParent(element, this.dom.center)) { + what = 'background'; + } - // remove the focus on node if it is focussed on by the focusOnNode - this.body.emitter.emit('unlockNode'); + var value = []; + var yAxisLeft = this.linegraph.yAxisLeft; + var yAxisRight = this.linegraph.yAxisRight; + if (!yAxisLeft.hidden) { + value.push(yAxisLeft.screenToValue(y)); + } + if (!yAxisRight.hidden) { + value.push(yAxisRight.screenToValue(y)); + } - var pointer = this.getPointer(event.center); + return { + event: event, + what: what, + pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX, + pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY, + x: x, + y: y, + time: time, + value: value + }; + }; - this.selectionHandler._generateClickEvent('dragging', event, pointer); + module.exports = Graph2d; - var selection = this.drag.selection; - if (selection && selection.length && this.options.dragNodes === true) { - (function () { - // calculate delta's and new location - var deltaX = pointer.x - _this2.drag.pointer.x; - var deltaY = pointer.y - _this2.drag.pointer.y; +/***/ }, +/* 16 */ +/***/ function(module, exports, __webpack_require__) { - // update position of all selected nodes - selection.forEach(function (selection) { - var node = selection.node; - // only move the node if it was not fixed initially - if (selection.xFixed === false) { - node.x = _this2.canvas._XconvertDOMtoCanvas(_this2.canvas._XconvertCanvasToDOM(selection.x) + deltaX); - } - // only move the node if it was not fixed initially - if (selection.yFixed === false) { - node.y = _this2.canvas._YconvertDOMtoCanvas(_this2.canvas._YconvertCanvasToDOM(selection.y) + deltaY); - } - }); + "use strict"; - // start the simulation of the physics - _this2.body.emitter.emit('startSimulation'); - })(); - } else { - // move the network - if (this.options.dragView === true) { - // if the drag was not started properly because the click started outside the network div, start it now. - if (this.drag.pointer === undefined) { - this._handleDragStart(event); - return; - } - var diffX = pointer.x - this.drag.pointer.x; - var diffY = pointer.y - this.drag.pointer.y; + var moment = __webpack_require__(40); - this.body.view.translation = { x: this.drag.translation.x + diffX, y: this.drag.translation.y + diffY }; - this.body.emitter.emit('_redraw'); + /** + * used in Core to convert the options into a volatile variable + * + * @param Core + */ + exports.convertHiddenOptions = function (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 } - }, { - key: 'onDragEnd', + } + }; - /** - * handle drag start event - * @private - */ - value: function onDragEnd(event) { - this.drag.dragging = false; - var selection = this.drag.selection; - if (selection && selection.length) { - selection.forEach(function (s) { - // restore original xFixed and yFixed - s.node.options.fixed.x = s.xFixed; - s.node.options.fixed.y = s.yFixed; - }); - this.body.emitter.emit('startSimulation'); - } else { - this.body.emitter.emit('_requestRedraw'); - } - this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center)); - } - }, { - key: 'onPinch', + /** + * create new entrees for the repeating hidden dates + * @param body + * @param hiddenDates + */ + exports.updateHiddenDates = function (body, hiddenDates) { + if (hiddenDates && body.domProps.centerContainer.width !== undefined) { + exports.convertHiddenOptions(body, hiddenDates); - /** - * Handle pinch event - * @param event - * @private - */ - value: function onPinch(event) { - var pointer = this.getPointer(event.center); + var start = moment(body.range.start); + var end = moment(body.range.end); - this.drag.pinched = true; - if (this.pinch['scale'] === undefined) { - this.pinch.scale = 1; - } + var totalRange = body.range.end - body.range.start; + var pixelTime = totalRange / body.domProps.centerContainer.width; - // TODO: enabled moving while pinching? - var scale = this.pinch.scale * event.scale; - this.zoom(scale, pointer); - } - }, { - key: 'zoom', + 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); - /** - * Zoom the network in or out - * @param {Number} scale a number around 1, and between 0.01 and 10 - * @param {{x: Number, y: Number}} pointer Position on screen - * @return {Number} appliedScale scale is limited within the boundaries - * @private - */ - value: function zoom(scale, pointer) { - if (this.options.zoomView === true) { - var scaleOld = this.body.view.scale; - if (scale < 0.00001) { - scale = 0.00001; + if (startDate._d == "Invalid Date") { + throw new Error("Supplied start date is not valid: " + hiddenDates[i].start); } - if (scale > 10) { - scale = 10; + if (endDate._d == "Invalid Date") { + throw new Error("Supplied end date is not valid: " + hiddenDates[i].end); } - var preScaleDragPointer = undefined; - if (this.drag !== undefined) { - if (this.drag.dragging === true) { - preScaleDragPointer = this.canvas.DOMtoCanvas(this.drag.pointer); - } - } - // + this.canvas.frame.canvas.clientHeight / 2 - var translation = this.body.view.translation; + var duration = endDate - startDate; + if (duration >= 4 * pixelTime) { - var scaleFrac = scale / scaleOld; - var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac; - var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac; + 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"); - this.body.view.scale = scale; - this.body.view.translation = { x: tx, y: ty }; + endDate.dayOfYear(start.dayOfYear()); + endDate.year(start.year()); + endDate.subtract(7 - offset, "days"); - if (preScaleDragPointer != undefined) { - var postScaleDragPointer = this.canvas.canvasToDOM(preScaleDragPointer); - this.drag.pointer.x = postScaleDragPointer.x; - this.drag.pointer.y = postScaleDragPointer.y; - } + runUntil.add(1, "weeks"); + break; + case "weekly": + var dayOffset = endDate.diff(startDate, "days"); + var day = startDate.day(); - this.body.emitter.emit('_requestRedraw'); + // set the start date to the range.start + startDate.date(start.date()); + startDate.month(start.month()); + startDate.year(start.year()); + endDate = startDate.clone(); - if (scaleOld < scale) { - this.body.emitter.emit('zoom', { direction: '+', scale: this.body.view.scale }); - } else { - this.body.emitter.emit('zoom', { direction: '-', scale: this.body.view.scale }); - } - } - } - }, { - key: 'onMouseWheel', + // force + startDate.day(day); + endDate.day(day); + endDate.add(dayOffset, "days"); - /** - * Event handler for mouse wheel event, used to zoom the timeline - * See http://adomas.org/javascript-mouse-wheel/ - * https://github.com/EightMedia/hammer.js/issues/256 - * @param {MouseEvent} event - * @private - */ - value: function onMouseWheel(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; - } + startDate.subtract(1, "weeks"); + endDate.subtract(1, "weeks"); - // 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 !== 0) { + 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"); - // calculate the new scale - var scale = this.body.view.scale; - var zoom = delta / 10; - if (delta < 0) { - zoom = zoom / (1 - zoom); - } - scale *= 1 + zoom; + endDate.month(start.month()); + endDate.year(start.year()); + endDate.subtract(1, "months"); + endDate.add(offset, "months"); - // calculate the pointer location - var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); + 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"); - // apply the new scale - this.zoom(scale, pointer); + 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() }); + } } - - // Prevent default actions caused by mouse wheel. - event.preventDefault(); } - }, { - key: 'onMouseMove', - - /** - * Mouse move handler for checking whether the title moves over a node with a title. - * @param {Event} event - * @private - */ - value: function onMouseMove(event) { - var _this3 = this; - - var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); - var popupVisible = false; - - // check if the previously selected node is still selected - if (this.popup !== undefined) { - if (this.popup.hidden === false) { - this._checkHidePopup(pointer); - } + // 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); + } + } + }; - // if the popup was not hidden above - if (this.popup.hidden === false) { - popupVisible = true; - this.popup.setPosition(pointer.x + 3, pointer.y - 5); - this.popup.show(); + /** + * remove duplicates from the hidden dates list. Duplicates are evil. They mess everything up. + * Scales with N^2 + * @param 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; } - } - - // if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over. - if (this.options.keyboard.bindToWindow === false && this.options.keyboard.enabled === true) { - this.canvas.frame.focus(); - } - - // start a timeout that will check if the mouse is positioned above an element - if (popupVisible === false) { - if (this.popupTimer !== undefined) { - clearInterval(this.popupTimer); // stop any running calculationTimer - this.popupTimer = undefined; + // 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; } - if (!this.drag.dragging) { - this.popupTimer = setTimeout(function () { - return _this3._checkShowPopup(pointer); - }, this.options.tooltipDelay); + // 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; } } + } + } - /** - * Adding hover highlights - */ - if (this.options.hover === true) { - // adding hover highlights - var obj = this.selectionHandler.getNodeAt(pointer); - if (obj === undefined) { - obj = this.selectionHandler.getEdgeAt(pointer); - } - this.selectionHandler.hoverObject(obj); - } + for (var i = 0; i < hiddenDates.length; i++) { + if (hiddenDates[i].remove !== true) { + safeDates.push(hiddenDates[i]); } - }, { - key: '_checkShowPopup', + } - /** - * Check if there is an element on the given position in the network - * (a node or edge). If so, and if this element has a title, - * show a popup window with its title. - * - * @param {{x:Number, y:Number}} pointer - * @private - */ - value: function _checkShowPopup(pointer) { - var x = this.canvas._XconvertDOMtoCanvas(pointer.x); - var y = this.canvas._YconvertDOMtoCanvas(pointer.y); - var pointerObj = { - left: x, - top: y, - right: x, - bottom: y - }; + body.hiddenDates = safeDates; + body.hiddenDates.sort(function (a, b) { + return a.start - b.start; + }); // sort by start time + }; - var previousPopupObjId = this.popupObj === undefined ? undefined : this.popupObj.id; - var nodeUnderCursor = false; - var popupType = 'node'; + 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); + } + }; - // check if a node is under the cursor. - if (this.popupObj === undefined) { - // search the nodes for overlap, select the top one in case of multiple nodes - var nodeIndices = this.body.nodeIndices; - var nodes = this.body.nodes; - var node = undefined; - var overlappingNodes = []; - for (var i = 0; i < nodeIndices.length; i++) { - node = nodes[nodeIndices[i]]; - if (node.isOverlappingWith(pointerObj) === true) { - if (node.getTitle() !== undefined) { - overlappingNodes.push(nodeIndices[i]); - } - } - } + /** + * Used in TimeStep to avoid the hidden times. + * @param timeStep + * @param previousTime + */ + exports.stepOverHiddenDates = function (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 (overlappingNodes.length > 0) { - // if there are overlapping nodes, select the last one, this is the one which is drawn on top of the others - this.popupObj = nodes[overlappingNodes[overlappingNodes.length - 1]]; - // if you hover over a node, the title of the edge is not supposed to be shown. - nodeUnderCursor = true; - } - } + 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; + } - if (this.popupObj === undefined && nodeUnderCursor === false) { - // search the edges for overlap - var edgeIndices = this.body.edgeIndices; - var edges = this.body.edges; - var edge = undefined; - var overlappingEdges = []; - for (var i = 0; i < edgeIndices.length; i++) { - edge = edges[edgeIndices[i]]; - if (edge.isOverlappingWith(pointerObj) === true) { - if (edge.connected === true && edge.getTitle() !== undefined) { - overlappingEdges.push(edgeIndices[i]); - } - } - } + timeStep.current = newValue.toDate(); + } + }; - if (overlappingEdges.length > 0) { - this.popupObj = edges[overlappingEdges[overlappingEdges.length - 1]]; - popupType = 'edge'; - } - } + ///** + // * 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(); + // } + //}; - if (this.popupObj !== undefined) { - // show popup message window - if (this.popupObj.id !== previousPopupObjId) { - if (this.popup === undefined) { - this.popup = new _componentsPopup2['default'](this.canvas.frame); - } + /** + * replaces the Core toScreen methods + * @param Core + * @param time + * @param width + * @returns {number} + */ + exports.toScreen = function (Core, time, width) { + if (Core.body.hiddenDates.length == 0) { + var 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; + } - this.popup.popupTargetType = popupType; - this.popup.popupTargetId = this.popupObj.id; + var duration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end); + time = exports.correctTimeForHidden(Core.body.hiddenDates, Core.range, time); - // adjust a small offset such that the mouse cursor is located in the - // bottom left location of the popup, and you can easily move over the - // popup area - this.popup.setPosition(pointer.x + 3, pointer.y - 5); - this.popup.setText(this.popupObj.getTitle()); - this.popup.show(); - this.body.emitter.emit('showPopup', this.popupObj.id); - } - } else { - if (this.popup !== undefined) { - this.popup.hide(); - this.body.emitter.emit('hidePopup'); - } - } + var conversion = Core.range.conversion(width, duration); + return (time.valueOf() - conversion.offset) * conversion.scale; + } + }; + + /** + * Replaces the core toTime methods + * @param body + * @param range + * @param x + * @param 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); + + var newTime = new Date(accumulatedHiddenDuration + partialDuration + Core.range.start); + return newTime; + } + }; + + /** + * Support function + * + * @param hiddenDates + * @param range + * @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; } - }, { - key: '_checkHidePopup', + } + return duration; + }; - /** - * Check if the popup must be hidden, which is the case when the mouse is no - * longer hovering on the object - * @param {{x:Number, y:Number}} pointer - * @private - */ - value: function _checkHidePopup(pointer) { - var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); + /** + * Support function + * @param hiddenDates + * @param range + * @param time + * @returns {{duration: number, time: *, offset: number}} + */ + exports.correctTimeForHidden = function (hiddenDates, range, time) { + time = moment(time).toDate().valueOf(); + time -= exports.getHiddenDurationBefore(hiddenDates, range, time); + return time; + }; - var stillOnObj = false; - if (this.popup.popupTargetType === 'node') { - if (this.body.nodes[this.popup.popupTargetId] !== undefined) { - stillOnObj = this.body.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj); + exports.getHiddenDurationBefore = function (hiddenDates, range, time) { + var timeOffset = 0; + time = moment(time).toDate().valueOf(); - // if the mouse is still one the node, we have to check if it is not also on one that is drawn on top of it. - // we initially only check stillOnObj because this is much faster. - if (stillOnObj === true) { - var overNode = this.selectionHandler.getNodeAt(pointer); - stillOnObj = overNode.id === this.popup.popupTargetId; - } - } + 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 hiddenDates + * @param range + * @param time + * @returns {{duration: number, time: *, offset: 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 { - if (this.selectionHandler.getNodeAt(pointer) === undefined) { - if (this.body.edges[this.popup.popupTargetId] !== undefined) { - stillOnObj = this.body.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj); - } - } + hiddenDuration += endDate - startDate; } + } + } - if (stillOnObj === false) { - this.popupObj = undefined; - this.popup.hide(); - this.body.emitter.emit('hidePopup'); + return hiddenDuration; + }; + + /** + * used to step over to either side of a hidden block. Correction is disabled on tablets, might be set to true + * @param hiddenDates + * @param time + * @param direction + * @param correctionEnabled + * @returns {*} + */ + 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; + } + }; - return InteractionHandler; - })(); + /** + * Check if a time is hidden + * + * @param time + * @param 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; - exports['default'] = InteractionHandler; - module.exports = exports['default']; + if (time >= startDate && time < endDate) { + // if the start is entering a hidden zone + return { hidden: true, startDate: startDate, endDate: endDate }; + break; + } + } + return { hidden: false, startDate: startDate, endDate: endDate }; + }; /***/ }, -/* 13 */ +/* 17 */ /***/ function(module, exports, __webpack_require__) { - // Only load hammer.js when in a browser environment - // (loading hammer.js in a node.js environment gives errors) + /** + * @constructor DataStep + * The class DataStep is an iterator for data for the lineGraph. You provide a start data point and an + * end data point. 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 DataStep 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 + */ 'use strict'; - if (typeof window !== 'undefined') { - var propagating = __webpack_require__(14); - var Hammer = window['Hammer'] || __webpack_require__(15); - module.exports = propagating(Hammer, { - preventDefault: 'mouse' - }); - } else { - module.exports = function () { - throw Error('hammer.js is only available in a browser, not in node.js.'); - }; + function DataStep(start, end, minimumStep, containerHeight, customRange, formattingFunction, alignZeros) { + // variables + this.current = 0; + + this.autoScale = true; + this.stepIndex = 0; + this.step = 1; + this.scale = 1; + this.formattingFunction = formattingFunction; + + this.marginStart; + this.marginEnd; + this.deadSpace = 0; + + this.majorSteps = [1, 2, 5, 10]; + this.minorSteps = [0.25, 0.5, 1, 2]; + + this.alignZeros = alignZeros; + + this.setRange(start, end, minimumStep, containerHeight, customRange); } -/***/ }, -/* 14 */ -/***/ function(module, exports, __webpack_require__) { + /** + * 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 {Number} [start] The start date and time. + * @param {Number} [end] The end date and time. + * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds + */ + DataStep.prototype.setRange = function (start, end, minimumStep, containerHeight, customRange) { + this._start = customRange.min === undefined ? start : customRange.min; + this._end = customRange.max === undefined ? end : customRange.max; + if (this._start === this._end) { + this._start = customRange.min === undefined ? this._start - 0.75 : this._start; + this._end = customRange.max === undefined ? this._end + 1 : this._end;; + } - var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; + if (this.autoScale === true) { + this.setMinimumStep(minimumStep, containerHeight); + } - (function (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) - window.propagating = factory(); + this.setFirst(customRange); + }; + + /** + * Automatically determine the scale that bests fits the provided minimum step + * @param {Number} [minimumStep] The minimum step size in pixels + */ + DataStep.prototype.setMinimumStep = function (minimumStep, containerHeight) { + // round to floor + var range = this._end - this._start; + var safeRange = range * 1.2; + var minimumStepValue = minimumStep * (safeRange / containerHeight); + var orderOfMagnitude = Math.round(Math.log(safeRange) / Math.LN10); + + var minorStepIdx = -1; + var magnitudefactor = Math.pow(10, orderOfMagnitude); + + var start = 0; + if (orderOfMagnitude < 0) { + start = orderOfMagnitude; } - }(function () { - var _firstTarget = null; // singleton, will contain the target element where the touch event started - var _processing = false; // singleton, true when a touch event is being handled - /** - * Extend an Hammer.js instance with event propagation. - * - * Features: - * - Events emitted by hammer will propagate in order from child to parent - * elements. - * - Events are extended with a function `event.stopPropagation()` to stop - * propagation to parent elements. - * - An option `preventDefault` to stop all default browser behavior. - * - * Usage: - * var hammer = propagatingHammer(new Hammer(element)); - * var hammer = propagatingHammer(new Hammer(element), {preventDefault: true}); - * - * @param {Hammer.Manager} hammer An hammer instance. - * @param {Object} [options] Available options: - * - `preventDefault: true | 'mouse' | 'touch' | 'pen'`. - * Enforce preventing the default browser behavior. - * Cannot be set to `false`. - * @return {Hammer.Manager} Returns the same hammer instance with extended - * functionality - */ - return function propagating(hammer, options) { - if (options && options.preventDefault === false) { - throw new Error('Only supports preventDefault == true'); + var solutionFound = false; + for (var i = start; Math.abs(i) <= Math.abs(orderOfMagnitude); i++) { + magnitudefactor = Math.pow(10, i); + for (var j = 0; j < this.minorSteps.length; j++) { + var stepSize = magnitudefactor * this.minorSteps[j]; + if (stepSize >= minimumStepValue) { + solutionFound = true; + minorStepIdx = j; + break; + } } - var _options = options || { - preventDefault: false - }; + if (solutionFound === true) { + break; + } + } + this.stepIndex = minorStepIdx; + this.scale = magnitudefactor; + this.step = magnitudefactor * this.minorSteps[minorStepIdx]; + }; - if (hammer.Manager) { - // This looks like the Hammer constructor. - // Overload the constructors with our own. - var Hammer = hammer; + /** + * Round the current date to the first minor date value + * This must be executed once when the current date is set to start Date + */ + DataStep.prototype.setFirst = function (customRange) { + if (customRange === undefined) { + customRange = {}; + } - var PropagatingHammer = function(element, options) { - return propagating(new Hammer(element, options), _options); - }; - Hammer.extend(PropagatingHammer, Hammer); - PropagatingHammer.Manager = function (element, options) { - return propagating(new Hammer.Manager(element, options), _options); - }; + var niceStart = customRange.min === undefined ? this._start - this.scale * 2 * this.minorSteps[this.stepIndex] : customRange.min; + var niceEnd = customRange.max === undefined ? this._end + this.scale * this.minorSteps[this.stepIndex] : customRange.max; - return PropagatingHammer; - } + this.marginEnd = customRange.max === undefined ? this.roundToMinor(niceEnd) : customRange.max; + this.marginStart = customRange.min === undefined ? this.roundToMinor(niceStart) : customRange.min; - // attach to DOM element - var element = hammer.element; - element.hammer = hammer; + // if we need to align the zero's we need to make sure that there is a zero to use. + if (this.alignZeros === true && (this.marginEnd - this.marginStart) % this.step != 0) { + this.marginEnd += this.marginEnd % this.step; + } - // move the original functions that we will wrap - hammer._on = hammer.on; - hammer._off = hammer.off; - hammer._emit = hammer.emit; - hammer._destroy = hammer.destroy; + this.deadSpace = this.roundToMinor(niceEnd) - niceEnd + this.roundToMinor(niceStart) - niceStart; + this.marginRange = this.marginEnd - this.marginStart; - /** @type {Object.>} */ - hammer._handlers = {}; + this.current = this.marginEnd; + }; - // register an event to catch the start of a gesture and store the - // target in a singleton - hammer._on('hammer.input', function (event) { - if (_options.preventDefault === true || (_options.preventDefault === event.pointerType)) { - event.preventDefault(); - } - if (event.isFirst) { - _firstTarget = event.target; - _processing = true; - } - if (event.isFinal) { - _processing = false; - } - }); - - /** - * Register a handler for one or multiple events - * @param {String} events A space separated string with events - * @param {function} handler A callback function, called as handler(event) - * @returns {Hammer.Manager} Returns the hammer instance - */ - hammer.on = function (events, handler) { - // register the handler - split(events).forEach(function (event) { - var _handlers = hammer._handlers[event]; - if (!_handlers) { - hammer._handlers[event] = _handlers = []; - - // register the static, propagated handler - hammer._on(event, propagatedHandler); - } - _handlers.push(handler); - }); - - return hammer; - }; + DataStep.prototype.roundToMinor = function (value) { + var rounded = value - value % (this.scale * this.minorSteps[this.stepIndex]); + if (value % (this.scale * this.minorSteps[this.stepIndex]) > 0.5 * (this.scale * this.minorSteps[this.stepIndex])) { + return rounded + this.scale * this.minorSteps[this.stepIndex]; + } else { + return rounded; + } + }; - /** - * Unregister a handler for one or multiple events - * @param {String} events A space separated string with events - * @param {function} [handler] Optional. The registered handler. If not - * provided, all handlers for given events - * are removed. - * @returns {Hammer.Manager} Returns the hammer instance - */ - hammer.off = function (events, handler) { - // unregister the handler - split(events).forEach(function (event) { - var _handlers = hammer._handlers[event]; - if (_handlers) { - _handlers = handler ? _handlers.filter(function (h) { - return h !== handler; - }) : []; + /** + * Check if the there is a next step + * @return {boolean} true if the current date has not passed the end date + */ + DataStep.prototype.hasNext = function () { + return this.current >= this.marginStart; + }; - if (_handlers.length > 0) { - hammer._handlers[event] = _handlers; - } - else { - // remove static, propagated handler - hammer._off(event, propagatedHandler); - delete hammer._handlers[event]; - } - } - }); + /** + * Do the next step + */ + DataStep.prototype.next = function () { + var prev = this.current; + this.current -= this.step; - return hammer; - }; + // safety mechanism: if current time is still unchanged, move to the end + if (this.current === prev) { + this.current = this._end; + } + }; - /** - * Emit to the event listeners - * @param {string} eventType - * @param {Event} event - */ - hammer.emit = function(eventType, event) { - if (!_processing) { - _firstTarget = event.target; - } - hammer._emit(eventType, event); - }; + /** + * Do the next step + */ + DataStep.prototype.previous = function () { + this.current += this.step; + this.marginEnd += this.step; + this.marginRange = this.marginEnd - this.marginStart; + }; - hammer.destroy = function () { - // Detach from DOM element - var element = hammer.element; - delete element.hammer; + /** + * Get the current datetime + * @return {String} current The current date + */ + DataStep.prototype.getCurrent = function () { + // prevent round-off errors when close to zero + var current = Math.abs(this.current) < this.step / 2 ? 0 : this.current; + var returnValue = current.toPrecision(5); + if (typeof this.formattingFunction === 'function') { + returnValue = this.formattingFunction(current); + } - // clear all handlers - hammer._handlers = {}; + if (typeof returnValue === 'number') { + return '' + returnValue; + } else if (typeof returnValue === 'string') { + return returnValue; + } else { + return current.toPrecision(5); + } + }; - // call original hammer destroy - hammer._destroy(); - }; + /** + * 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. + */ + DataStep.prototype.isMajor = function () { + return this.current % (this.scale * this.majorSteps[this.stepIndex]) === 0; + }; - // split a string with space separated words - function split(events) { - return events.match(/[^ ]+/g); + DataStep.prototype.shift = function (steps) { + if (steps < 0) { + for (var i = 0; i < -steps; i++) { + this.previous(); } + } else if (steps > 0) { + for (var i = 0; i < steps; i++) { + this.next(); + } + } + }; - /** - * A static event handler, applying event propagation. - * @param {Object} event - */ - function propagatedHandler(event) { - // let only a single hammer instance handle this event - if (event.type !== 'hammer.input') { - // it is possible that the same srcEvent is used with multiple hammer events, - // we keep track on which events are handled in an object _handled - if (!event.srcEvent._handled) { - event.srcEvent._handled = {}; - } + module.exports = DataStep; - if (event.srcEvent._handled[event.type]) { - return; - } - else { - event.srcEvent._handled[event.type] = true; - } - } +/***/ }, +/* 18 */ +/***/ function(module, exports, __webpack_require__) { - // attach a stopPropagation function to the event - var stopped = false; - event.stopPropagation = function () { - stopped = true; - }; + 'use strict'; - // attach firstTarget property to the event - event.firstTarget = _firstTarget; + var util = __webpack_require__(2); + var hammerUtil = __webpack_require__(49); + var moment = __webpack_require__(40); + var Component = __webpack_require__(25); + var DateUtil = __webpack_require__(16); - // propagate over all elements (until stopped) - var elem = _firstTarget; - while (elem && !stopped) { - var _handlers = elem.hammer && elem.hammer._handlers[event.type]; - if (_handlers) { - for (var i = 0; i < _handlers.length && !stopped; i++) { - _handlers[i](event); - } - } + /** + * @constructor Range + * 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 + */ + function Range(body, options) { + var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0); + this.start = now.clone().add(-3, 'days').valueOf(); // Number + this.end = now.clone().add(4, 'days').valueOf(); // Number - elem = elem.parentNode; - } - } + this.body = body; + this.deltaDifference = 0; + this.scaleOffset = 0; + this.startToFront = false; + this.endToFront = true; - return hammer; + // default options + this.defaultOptions = { + start: null, + end: null, + direction: 'horizontal', // 'horizontal' or 'vertical' + moveable: true, + zoomable: true, + min: null, + max: null, + zoomMin: 10, // milliseconds + zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds }; - })); + this.options = util.extend({}, this.defaultOptions); + this.props = { + touch: {} + }; + this.animationTimer = null; -/***/ }, -/* 15 */ -/***/ function(module, exports, __webpack_require__) { + // 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)); - var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v2.0.4 - 2014-09-28 - * http://hammerjs.github.io/ - * - * Copyright (c) 2014 Jorik Tangelder; - * Licensed under the MIT license */ - (function(window, document, exportName, undefined) { - 'use strict'; + // mouse wheel for zooming + this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this)); - var VENDOR_PREFIXES = ['', 'webkit', 'moz', 'MS', 'ms', 'o']; - var TEST_ELEMENT = document.createElement('div'); + // pinch to zoom + this.body.emitter.on('touch', this._onTouch.bind(this)); + this.body.emitter.on('pinch', this._onPinch.bind(this)); - var TYPE_FUNCTION = 'function'; + this.setOptions(options); + } - var round = Math.round; - var abs = Math.abs; - var now = Date.now; + Range.prototype = new Component(); /** - * set a timeout with a given scope - * @param {Function} fn - * @param {Number} timeout - * @param {Object} context - * @returns {number} + * 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 */ - function setTimeoutContext(fn, timeout, context) { - return setTimeout(bindFn(fn, context), timeout); - } + Range.prototype.setOptions = function (options) { + if (options) { + // copy the options that we know + var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable', 'activate', 'hiddenDates']; + util.selectiveExtend(fields, this.options, options); + + if ('start' in options || 'end' in options) { + // apply a new range. both start and end are optional + this.setRange(options.start, options.end); + } + } + }; /** - * if the argument is an array, we want to execute the fn on each entry - * if it aint an array we don't want to do a thing. - * this is used by all the methods that accept a single and array argument. - * @param {*|Array} arg - * @param {String} fn - * @param {Object} [context] - * @returns {Boolean} + * Test whether direction has a valid value + * @param {String} direction 'horizontal' or 'vertical' */ - function invokeArrayArg(arg, fn, context) { - if (Array.isArray(arg)) { - each(arg, context[fn], context); - return true; - } - return false; + function validateDirection(direction) { + if (direction != 'horizontal' && direction != 'vertical') { + throw new TypeError('Unknown direction "' + direction + '". ' + 'Choose "horizontal" or "vertical".'); + } } /** - * walk objects and arrays - * @param {Object} obj - * @param {Function} iterator - * @param {Object} context + * Set a new start and end range + * @param {Date | Number | String} [start] + * @param {Date | Number | String} [end] + * @param {boolean | {duration: number, easingFunction: string}} [animation=false] + * 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 {Boolean} [byUser=false] + * */ - function each(obj, iterator, context) { - var i; + Range.prototype.setRange = function (start, end, animation, byUser) { + if (byUser !== true) { + byUser = false; + } + var finalStart = start != undefined ? util.convert(start, 'Date').valueOf() : null; + var finalEnd = end != undefined ? util.convert(end, 'Date').valueOf() : null; + this._cancelAnimation(); - if (!obj) { - return; + if (animation) { + // true or an Object + var me = this; + var initStart = this.start; + var initEnd = this.end; + var duration = typeof animation === 'object' && 'duration' in animation ? animation.duration : 500; + var easingName = typeof animation === 'object' && 'easingFunction' in animation ? animation.easingFunction : 'easeInOutQuad'; + var easingFunction = util.easingFunctions[easingName]; + if (!easingFunction) { + throw new Error('Unknown easing function ' + JSON.stringify(easingName) + '. ' + 'Choose from: ' + Object.keys(util.easingFunctions).join(', ')); } - if (obj.forEach) { - obj.forEach(iterator, context); - } else if (obj.length !== undefined) { - i = 0; - while (i < obj.length) { - iterator.call(context, obj[i], i, obj); - i++; - } - } else { - for (i in obj) { - obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj); + 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.body, me.options.hiddenDates); + anyChanged = anyChanged || changed; + if (changed) { + me.body.emitter.emit('rangechange', { start: new Date(me.start), end: new Date(me.end), byUser: byUser }); } - } - } - /** - * extend object. - * means that properties in dest will be overwritten by the ones in src. - * @param {Object} dest - * @param {Object} src - * @param {Boolean} [merge] - * @returns {Object} dest - */ - function extend(dest, src, merge) { - var keys = Object.keys(src); - var i = 0; - while (i < keys.length) { - if (!merge || (merge && dest[keys[i]] === undefined)) { - dest[keys[i]] = src[keys[i]]; + if (done) { + if (anyChanged) { + me.body.emitter.emit('rangechanged', { start: new Date(me.start), end: new Date(me.end), byUser: byUser }); + } + } 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); } - i++; + } + }; + + return next(); + } else { + var changed = this._applyRange(finalStart, finalEnd); + DateUtil.updateHiddenDates(this.body, this.options.hiddenDates); + if (changed) { + var params = { start: new Date(this.start), end: new Date(this.end), byUser: byUser }; + this.body.emitter.emit('rangechange', params); + this.body.emitter.emit('rangechanged', params); } - return dest; - } + } + }; /** - * merge the values from src in the dest. - * means that properties that exist in dest will not be overwritten by src - * @param {Object} dest - * @param {Object} src - * @returns {Object} dest + * Stop an animation + * @private */ - function merge(dest, src) { - return extend(dest, src, true); - } + Range.prototype._cancelAnimation = function () { + if (this.animationTimer) { + clearTimeout(this.animationTimer); + this.animationTimer = null; + } + }; /** - * simple class inheritance - * @param {Function} child - * @param {Function} base - * @param {Object} [properties] + * 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 */ - function inherit(child, base, properties) { - var baseP = base.prototype, - childP; + 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; - childP = child.prototype = Object.create(baseP); - childP.constructor = child; - childP._super = baseP; + // 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 + '"'); + } - if (properties) { - extend(childP, properties); - } - } + // prevent start < end + if (newEnd < newStart) { + newEnd = newStart; + } - /** - * simple function bind - * @param {Function} fn - * @param {Object} context - * @returns {Function} - */ - function bindFn(fn, context) { - return function boundFn() { - return fn.apply(context, arguments); - }; - } + // prevent start < min + if (min !== null) { + if (newStart < min) { + diff = min - newStart; + newStart += diff; + newEnd += diff; - /** - * let a boolean value also be a function that must return a boolean - * this first item in args will be used as the context - * @param {Boolean|Function} val - * @param {Array} [args] - * @returns {Boolean} - */ - function boolOrFn(val, args) { - if (typeof val == TYPE_FUNCTION) { - return val.apply(args ? args[0] || undefined : undefined, args); + // prevent end > max + if (max != null) { + if (newEnd > max) { + newEnd = max; + } + } } - return val; - } + } - /** - * use the val2 when val1 is undefined - * @param {*} val1 - * @param {*} val2 - * @returns {*} - */ - function ifUndefined(val1, val2) { - return (val1 === undefined) ? val2 : val1; - } + // prevent end > max + if (max !== null) { + if (newEnd > max) { + diff = newEnd - max; + newStart -= diff; + newEnd -= diff; - /** - * addEventListener with multiple events at once - * @param {EventTarget} target - * @param {String} types - * @param {Function} handler - */ - function addEventListeners(target, types, handler) { - each(splitStr(types), function(type) { - target.addEventListener(type, handler, false); - }); - } + // prevent start < min + if (min != null) { + if (newStart < min) { + newStart = min; + } + } + } + } - /** - * removeEventListener with multiple events at once - * @param {EventTarget} target - * @param {String} types - * @param {Function} handler - */ - function removeEventListeners(target, types, handler) { - each(splitStr(types), function(type) { - target.removeEventListener(type, handler, false); - }); - } + // prevent (end-start) < zoomMin + if (this.options.zoomMin !== null) { + var zoomMin = parseFloat(this.options.zoomMin); + if (zoomMin < 0) { + zoomMin = 0; + } + if (newEnd - newStart < zoomMin) { + if (this.end - this.start === zoomMin && newStart > this.start && 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; + } + } + } - /** - * find if a node is in the given parent - * @method hasParent - * @param {HTMLElement} node - * @param {HTMLElement} parent - * @return {Boolean} found - */ - function hasParent(node, parent) { - while (node) { - if (node == parent) { - return true; - } - node = node.parentNode; + // prevent (end-start) > zoomMax + if (this.options.zoomMax !== null) { + var zoomMax = parseFloat(this.options.zoomMax); + if (zoomMax < 0) { + zoomMax = 0; } - return false; - } - /** - * small indexOf wrapper - * @param {String} str - * @param {String} find - * @returns {Boolean} found - */ - function inStr(str, find) { - return str.indexOf(find) > -1; - } + 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; + }; /** - * split string on whitespace - * @param {String} str - * @returns {Array} words + * Retrieve the current range. + * @return {Object} An object with start and end properties */ - function splitStr(str) { - return str.trim().split(/\s+/g); - } + Range.prototype.getRange = function () { + return { + start: this.start, + end: this.end + }; + }; /** - * find if a array contains the object using indexOf or a simple polyFill - * @param {Array} src - * @param {String} find - * @param {String} [findByKey] - * @return {Boolean|Number} false when not found, or the index + * Calculate the conversion offset and scale for current range, based on + * the provided width + * @param {Number} width + * @returns {{offset: number, scale: number}} conversion */ - function inArray(src, find, findByKey) { - if (src.indexOf && !findByKey) { - return src.indexOf(find); - } else { - var i = 0; - while (i < src.length) { - if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) { - return i; - } - i++; - } - return -1; - } - } + Range.prototype.conversion = function (width, totalHidden) { + return Range.conversion(this.start, this.end, width, totalHidden); + }; /** - * convert array-like objects to real arrays - * @param {Object} obj - * @returns {Array} + * 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 + * @returns {{offset: number, scale: number}} conversion */ - function toArray(obj) { - return Array.prototype.slice.call(obj, 0); - } + 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 + }; + } + }; /** - * unique array with objects based on a key (like 'id') or just by the array's value - * @param {Array} src [{id:1},{id:2},{id:1}] - * @param {String} [key] - * @param {Boolean} [sort=False] - * @returns {Array} [{id:1},{id:2}] + * Start dragging horizontally or vertically + * @param {Event} event + * @private */ - function uniqueArray(src, key, sort) { - var results = []; - var values = []; - var i = 0; + Range.prototype._onDragStart = function (event) { + this.deltaDifference = 0; + this.previousDelta = 0; + // only allow dragging when configured as movable + if (!this.options.moveable) return; - while (i < src.length) { - var val = key ? src[i][key] : src[i]; - if (inArray(values, val) < 0) { - results.push(src[i]); - } - values[i] = val; - i++; - } + // 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; - if (sort) { - if (!key) { - results = results.sort(); - } else { - results = results.sort(function sortUniqueArray(a, b) { - return a[key] > b[key]; - }); - } - } + this.props.touch.start = this.start; + this.props.touch.end = this.end; + this.props.touch.dragging = true; - return results; - } + if (this.body.dom.root) { + this.body.dom.root.style.cursor = 'move'; + } + }; /** - * get the prefixed property - * @param {Object} obj - * @param {String} property - * @returns {String|Undefined} prefixed + * Perform dragging operation + * @param {Event} event + * @private */ - function prefixed(obj, property) { - var prefix, prop; - var camelProp = property[0].toUpperCase() + property.slice(1); - - var i = 0; - while (i < VENDOR_PREFIXES.length) { - prefix = VENDOR_PREFIXES[i]; - prop = (prefix) ? prefix + camelProp : property; + Range.prototype._onDrag = function (event) { + // only allow dragging when configured as movable + if (!this.options.moveable) return; - if (prop in obj) { - return prop; - } - i++; - } - return undefined; - } + // 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; - /** - * get a unique id - * @returns {number} uniqueId - */ - var _uniqueId = 1; - function uniqueId() { - return _uniqueId++; - } + 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; - /** - * get the window object of an element - * @param {HTMLElement} element - * @returns {DocumentView|Window} - */ - function getWindowForElement(element) { - var doc = element.ownerDocument; - return (doc.defaultView || doc.parentWindow); - } + // normalize dragging speed if cutout is in between. + var duration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end); + interval -= duration; - var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i; + var width = direction == 'horizontal' ? this.body.domProps.center.width : this.body.domProps.center.height; + var diffRange = -delta / width * interval; + var newStart = this.props.touch.start + diffRange; + var newEnd = this.props.touch.end + diffRange; - var SUPPORT_TOUCH = ('ontouchstart' in window); - var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined; - var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent); + // 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; + } - var INPUT_TYPE_TOUCH = 'touch'; - var INPUT_TYPE_PEN = 'pen'; - var INPUT_TYPE_MOUSE = 'mouse'; - var INPUT_TYPE_KINECT = 'kinect'; + this.previousDelta = delta; + this._applyRange(newStart, newEnd); - var COMPUTE_INTERVAL = 25; + // fire a rangechange event + this.body.emitter.emit('rangechange', { + start: new Date(this.start), + end: new Date(this.end), + byUser: true + }); + }; - var INPUT_START = 1; - var INPUT_MOVE = 2; - var INPUT_END = 4; - var INPUT_CANCEL = 8; + /** + * Stop dragging operation + * @param {event} event + * @private + */ + Range.prototype._onDragEnd = function (event) { + // only allow dragging when configured as movable + if (!this.options.moveable) return; - var DIRECTION_NONE = 1; - var DIRECTION_LEFT = 2; - var DIRECTION_RIGHT = 4; - var DIRECTION_UP = 8; - var DIRECTION_DOWN = 16; + // 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_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT; - var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN; - var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL; + this.props.touch.dragging = false; + if (this.body.dom.root) { + this.body.dom.root.style.cursor = 'auto'; + } - var PROPS_XY = ['x', 'y']; - var PROPS_CLIENT_XY = ['clientX', 'clientY']; + // fire a rangechanged event + this.body.emitter.emit('rangechanged', { + start: new Date(this.start), + end: new Date(this.end), + byUser: true + }); + }; /** - * create new input type manager - * @param {Manager} manager - * @param {Function} callback - * @returns {Input} - * @constructor + * Event handler for mouse wheel event, used to zoom + * Code from http://adomas.org/javascript-mouse-wheel/ + * @param {Event} event + * @private */ - function Input(manager, callback) { - var self = this; - this.manager = manager; - this.callback = callback; - this.element = manager.element; - this.target = manager.options.inputTarget; + Range.prototype._onMouseWheel = function (event) { + // only allow zooming when configured as zoomable and moveable + if (!(this.options.zoomable && this.options.moveable)) return; - // smaller wrapper around the handler, for the scope and the enabled state of the manager, - // so when disabled the input events are completely bypassed. - this.domHandler = function(ev) { - if (boolOrFn(manager.options.enable, [manager])) { - self.handler(ev); - } - }; + // 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; + } - this.init(); + // 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); + } - Input.prototype = { - /** - * should handle the inputEvent data and trigger the callback - * @virtual - */ - handler: function() { }, + // calculate center, the date to zoom around + var pointer = getPointer({ x: event.clientX, y: event.clientY }, this.body.dom.center); + var pointerDate = this._pointerToDate(pointer); - /** - * bind the events - */ - init: function() { - this.evEl && addEventListeners(this.element, this.evEl, this.domHandler); - this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler); - this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); - }, + this.zoom(scale, pointerDate, delta); + } - /** - * unbind the events - */ - destroy: function() { - this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler); - this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler); - this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); - } + // Prevent default actions caused by mouse wheel + // (else the page and timeline both zoom and scroll) + event.preventDefault(); }; /** - * create new input type manager - * called by the Manager constructor - * @param {Hammer} manager - * @returns {Input} + * Start of a touch gesture + * @private */ - function createInputInstance(manager) { - var Type; - var inputClass = manager.options.inputClass; - - if (inputClass) { - Type = inputClass; - } else if (SUPPORT_POINTER_EVENTS) { - Type = PointerEventInput; - } else if (SUPPORT_ONLY_TOUCH) { - Type = TouchInput; - } else if (!SUPPORT_TOUCH) { - Type = MouseInput; - } else { - Type = TouchMouseInput; - } - return new (Type)(manager, inputHandler); - } + Range.prototype._onTouch = function (event) { + 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; + }; /** - * handle input events - * @param {Manager} manager - * @param {String} eventType - * @param {Object} input + * Handle pinch event + * @param {Event} event + * @private */ - function inputHandler(manager, eventType, input) { - var pointersLen = input.pointers.length; - var changedPointersLen = input.changedPointers.length; - var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0)); - var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0)); + Range.prototype._onPinch = function (event) { + // only allow zooming when configured as zoomable and moveable + if (!(this.options.zoomable && this.options.moveable)) return; - input.isFirst = !!isFirst; - input.isFinal = !!isFinal; + this.props.touch.allowDragging = false; - if (isFirst) { - manager.session = {}; - } + if (!this.props.touch.center) { + this.props.touch.center = getPointer(event.center, this.body.dom.center); + } - // source event is the normalized value of the domEvents - // like 'touchstart, mouseup, pointerdown' - input.eventType = eventType; + var scale = 1 / (event.scale + this.scaleOffset); + var centerDate = this._pointerToDate(this.props.touch.center); - // compute scale, rotation etc - computeInputData(manager, input); + var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end); + var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, centerDate); + var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore; - // emit secret event - manager.emit('hammer.input', input); + // 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; - manager.recognize(input); - manager.session.prevInput = input; - } + // 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 - /** - * extend the data with some usable properties like scale, rotate, velocity etc - * @param {Object} manager - * @param {Object} input - */ - function computeInputData(manager, input) { - var session = manager.session; - var pointers = input.pointers; - var pointersLength = pointers.length; - - // store the first input to calculate the distance and direction - if (!session.firstInput) { - session.firstInput = simpleCloneInputData(input); - } - - // to compute scale and rotation we need to store the multiple touches - if (pointersLength > 1 && !session.firstMultiple) { - session.firstMultiple = simpleCloneInputData(input); - } else if (pointersLength === 1) { - session.firstMultiple = false; - } - - var firstInput = session.firstInput; - var firstMultiple = session.firstMultiple; - var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center; - - var center = input.center = getCenter(pointers); - input.timeStamp = now(); - input.deltaTime = input.timeStamp - firstInput.timeStamp; - - input.angle = getAngle(offsetCenter, center); - input.distance = getDistance(offsetCenter, center); - - computeDeltaXY(session, input); - input.offsetDirection = getDirection(input.deltaX, input.deltaY); - - input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1; - input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0; + 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; + } - computeIntervalInputData(session, input); + this.setRange(newStart, newEnd, false, true); - // find the correct target - var target = manager.element; - if (hasParent(input.srcEvent.target, target)) { - target = input.srcEvent.target; - } - input.target = target; - } + this.startToFront = false; // revert to default + this.endToFront = true; // revert to default + }; - function computeDeltaXY(session, input) { - var center = input.center; - var offset = session.offsetDelta || {}; - var prevDelta = session.prevDelta || {}; - var prevInput = session.prevInput || {}; + /** + * 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; - if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) { - prevDelta = session.prevDelta = { - x: prevInput.deltaX || 0, - y: prevInput.deltaY || 0 - }; + validateDirection(direction); - offset = session.offsetDelta = { - x: center.x, - y: center.y - }; - } + 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; + } + }; - input.deltaX = prevDelta.x + (center.x - offset.x); - input.deltaY = prevDelta.y + (center.y - offset.y); + /** + * 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 + */ + function getPointer(touch, element) { + return { + x: touch.x - util.getAbsoluteLeft(element), + y: touch.y - util.getAbsoluteTop(element) + }; } /** - * velocity is calculated every x ms - * @param {Object} session - * @param {Object} input + * 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. */ - function computeIntervalInputData(session, input) { - var last = session.lastInterval || input, - deltaTime = input.timeStamp - last.timeStamp, - velocity, velocityX, velocityY, direction; - - if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) { - var deltaX = last.deltaX - input.deltaX; - var deltaY = last.deltaY - input.deltaY; + Range.prototype.zoom = function (scale, center, delta) { + // if centerDate is not provided, take it half between start Date and end Date + if (center == null) { + center = (this.start + this.end) / 2; + } - var v = getVelocity(deltaTime, deltaX, deltaY); - velocityX = v.x; - velocityY = v.y; - velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y; - direction = getDirection(deltaX, deltaY); + var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end); + var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, center); + var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore; - session.lastInterval = input; - } else { - // use latest velocity info if it doesn't overtake a minimum period - velocity = last.velocity; - velocityX = last.velocityX; - velocityY = last.velocityY; - direction = last.direction; - } + // calculate new start and end + var newStart = center - hiddenDurationBefore + (this.start - (center - hiddenDurationBefore)) * scale; + var newEnd = center + hiddenDurationAfter + (this.end - (center + hiddenDurationAfter)) * scale; - input.velocity = velocity; - input.velocityX = velocityX; - input.velocityY = velocityY; - input.direction = direction; - } + // 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; + } - /** - * create a simple clone from the input used for storage of firstInput and firstMultiple - * @param {Object} input - * @returns {Object} clonedInputData - */ - function simpleCloneInputData(input) { - // make a simple copy of the pointers because we will get a reference if we don't - // we only need clientXY for the calculations - var pointers = []; - var i = 0; - while (i < input.pointers.length) { - pointers[i] = { - clientX: round(input.pointers[i].clientX), - clientY: round(input.pointers[i].clientY) - }; - i++; - } + this.setRange(newStart, newEnd, false, true); - return { - timeStamp: now(), - pointers: pointers, - center: getCenter(pointers), - deltaX: input.deltaX, - deltaY: input.deltaY - }; - } + this.startToFront = false; // revert to default + this.endToFront = true; // revert to default + }; /** - * get the center of all the pointers - * @param {Array} pointers - * @return {Object} center contains `x` and `y` properties + * 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 */ - function getCenter(pointers) { - var pointersLength = pointers.length; + Range.prototype.move = function (delta) { + // zoom start Date and end Date relative to the centerDate + var diff = this.end - this.start; - // no need to loop when only one touch - if (pointersLength === 1) { - return { - x: round(pointers[0].clientX), - y: round(pointers[0].clientY) - }; - } + // apply new values + var newStart = this.start + diff * delta; + var newEnd = this.end + diff * delta; - var x = 0, y = 0, i = 0; - while (i < pointersLength) { - x += pointers[i].clientX; - y += pointers[i].clientY; - i++; - } + // TODO: reckon with min and max range - return { - x: round(x / pointersLength), - y: round(y / pointersLength) - }; - } + this.start = newStart; + this.end = newEnd; + }; /** - * calculate the velocity between two points. unit is in px per ms. - * @param {Number} deltaTime - * @param {Number} x - * @param {Number} y - * @return {Object} velocity `x` and `y` + * Move the range to a new center point + * @param {Number} moveTo New center point of the range */ - function getVelocity(deltaTime, x, y) { - return { - x: x / deltaTime || 0, - y: y / deltaTime || 0 - }; - } + Range.prototype.moveTo = function (moveTo) { + var center = (this.start + this.end) / 2; - /** - * get the direction between two points - * @param {Number} x - * @param {Number} y - * @return {Number} direction - */ - function getDirection(x, y) { - if (x === y) { - return DIRECTION_NONE; - } + var diff = center - moveTo; - if (abs(x) >= abs(y)) { - return x > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; - } - return y > 0 ? DIRECTION_UP : DIRECTION_DOWN; - } + // calculate new start and end + var newStart = this.start - diff; + var newEnd = this.end - diff; - /** - * calculate the absolute distance between two points - * @param {Object} p1 {x, y} - * @param {Object} p2 {x, y} - * @param {Array} [props] containing x and y keys - * @return {Number} distance - */ - function getDistance(p1, p2, props) { - if (!props) { - props = PROPS_XY; - } - var x = p2[props[0]] - p1[props[0]], - y = p2[props[1]] - p1[props[1]]; + this.setRange(newStart, newEnd); + }; - return Math.sqrt((x * x) + (y * y)); - } + module.exports = Range; - /** - * calculate the angle between two coordinates - * @param {Object} p1 - * @param {Object} p2 - * @param {Array} [props] containing x and y keys - * @return {Number} angle - */ - function getAngle(p1, p2, props) { - if (!props) { - props = PROPS_XY; - } - var x = p2[props[0]] - p1[props[0]], - y = p2[props[1]] - p1[props[1]]; - return Math.atan2(y, x) * 180 / Math.PI; - } +/***/ }, +/* 19 */ +/***/ function(module, exports, __webpack_require__) { + + // Utility functions for ordering and stacking of items + 'use strict'; + + var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors /** - * calculate the rotation degrees between two pointersets - * @param {Array} start array of pointers - * @param {Array} end array of pointers - * @return {Number} rotation + * Order items by their start data + * @param {Item[]} items */ - function getRotation(start, end) { - return getAngle(end[1], end[0], PROPS_CLIENT_XY) - getAngle(start[1], start[0], PROPS_CLIENT_XY); - } + exports.orderByStart = function (items) { + items.sort(function (a, b) { + return a.data.start - b.data.start; + }); + }; /** - * calculate the scale factor between two pointersets - * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out - * @param {Array} start array of pointers - * @param {Array} end array of pointers - * @return {Number} scale + * Order items by their end date. If they have no end date, their start date + * is used. + * @param {Item[]} items */ - function getScale(start, end) { - return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY); - } + exports.orderByEnd = function (items) { + items.sort(function (a, b) { + var aTime = 'end' in a.data ? a.data.end : a.data.start, + bTime = 'end' in b.data ? b.data.end : b.data.start; - var MOUSE_INPUT_MAP = { - mousedown: INPUT_START, - mousemove: INPUT_MOVE, - mouseup: INPUT_END + return aTime - bTime; + }); }; - var MOUSE_ELEMENT_EVENTS = 'mousedown'; - var MOUSE_WINDOW_EVENTS = 'mousemove mouseup'; - /** - * Mouse events input - * @constructor - * @extends Input + * Adjust vertical positions of the items such that they don't overlap each + * other. + * @param {Item[]} items + * All visible items + * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin + * Margins between items and between items and the axis. + * @param {boolean} [force=false] + * If true, all items will be repositioned. If false (default), only + * items having a top===null will be re-stacked */ - function MouseInput() { - this.evEl = MOUSE_ELEMENT_EVENTS; - this.evWin = MOUSE_WINDOW_EVENTS; - - this.allow = true; // used by Input.TouchMouse to disable mouse events - this.pressed = false; // mousedown state + exports.stack = function (items, margin, force) { + var i, iMax; - Input.apply(this, arguments); - } + if (force) { + // reset top position of all items + for (i = 0, iMax = items.length; i < iMax; i++) { + items[i].top = null; + } + } - inherit(MouseInput, Input, { - /** - * handle mouse events - * @param {Object} ev - */ - handler: function MEhandler(ev) { - var eventType = MOUSE_INPUT_MAP[ev.type]; + // calculate new, non-overlapping positions + for (i = 0, iMax = items.length; i < iMax; i++) { + var item = items[i]; + if (item.stack && item.top === null) { + // initialize top position + item.top = margin.axis; - // on start we want to have the left mouse button down - if (eventType & INPUT_START && ev.button === 0) { - this.pressed = true; + do { + // TODO: optimize checking for overlap. when there is a gap without items, + // you only need to check for items from the next item on, not from zero + var collidingItem = null; + for (var j = 0, jj = items.length; j < jj; j++) { + var other = items[j]; + if (other.top !== null && other !== item && other.stack && exports.collision(item, other, margin.item)) { + collidingItem = other; + break; + } } - if (eventType & INPUT_MOVE && ev.which !== 1) { - eventType = INPUT_END; + if (collidingItem != null) { + // There is a collision. Reposition the items above the colliding element + item.top = collidingItem.top + collidingItem.height + margin.item.vertical; } + } while (collidingItem); + } + } + }; - // mouse must be down, and mouse events are allowed (see the TouchMouse input) - if (!this.pressed || !this.allow) { - return; - } + /** + * Adjust vertical positions of the items without stacking them + * @param {Item[]} items + * All visible items + * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin + * Margins between items and between items and the axis. + */ + exports.nostack = function (items, margin, subgroups) { + var i, iMax, newTop; - if (eventType & INPUT_END) { - this.pressed = false; + // reset top position of all items + for (i = 0, iMax = items.length; i < iMax; i++) { + if (items[i].data.subgroup !== undefined) { + newTop = margin.axis; + for (var subgroup in subgroups) { + if (subgroups.hasOwnProperty(subgroup)) { + if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroups[items[i].data.subgroup].index) { + newTop += subgroups[subgroup].height + margin.item.vertical; + } } - - this.callback(this.manager, eventType, { - pointers: [ev], - changedPointers: [ev], - pointerType: INPUT_TYPE_MOUSE, - srcEvent: ev - }); + } + items[i].top = newTop; + } else { + items[i].top = margin.axis; } - }); - - var POINTER_INPUT_MAP = { - pointerdown: INPUT_START, - pointermove: INPUT_MOVE, - pointerup: INPUT_END, - pointercancel: INPUT_CANCEL, - pointerout: INPUT_CANCEL - }; - - // in IE10 the pointer types is defined as an enum - var IE10_POINTER_TYPE_ENUM = { - 2: INPUT_TYPE_TOUCH, - 3: INPUT_TYPE_PEN, - 4: INPUT_TYPE_MOUSE, - 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816 + } }; - var POINTER_ELEMENT_EVENTS = 'pointerdown'; - var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel'; - - // IE10 has prefixed support, and case-sensitive - if (window.MSPointerEvent) { - POINTER_ELEMENT_EVENTS = 'MSPointerDown'; - POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel'; - } - /** - * Pointer events input - * @constructor - * @extends Input + * Test if the two provided items collide + * The items must have parameters left, width, top, and height. + * @param {Item} a The first item + * @param {Item} b The second item + * @param {{horizontal: number, vertical: number}} margin + * An object containing a horizontal and vertical + * minimum required margin. + * @return {boolean} true if a and b collide, else false */ - function PointerEventInput() { - this.evEl = POINTER_ELEMENT_EVENTS; - this.evWin = POINTER_WINDOW_EVENTS; - - Input.apply(this, arguments); - - this.store = (this.manager.session.pointerEvents = []); - } - - inherit(PointerEventInput, Input, { - /** - * handle mouse events - * @param {Object} ev - */ - handler: function PEhandler(ev) { - var store = this.store; - var removePointer = false; + exports.collision = function (a, b, margin) { + return a.left - margin.horizontal + EPSILON < b.left + b.width && a.left + a.width + margin.horizontal - EPSILON > b.left && a.top - margin.vertical + EPSILON < b.top + b.height && a.top + a.height + margin.vertical - EPSILON > b.top; + }; - var eventTypeNormalized = ev.type.toLowerCase().replace('ms', ''); - var eventType = POINTER_INPUT_MAP[eventTypeNormalized]; - var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType; +/***/ }, +/* 20 */ +/***/ function(module, exports, __webpack_require__) { - var isTouch = (pointerType == INPUT_TYPE_TOUCH); + 'use strict'; - // get index of the event in the store - var storeIndex = inArray(store, ev.pointerId, 'pointerId'); + var moment = __webpack_require__(40); + var DateUtil = __webpack_require__(16); + var util = __webpack_require__(2); - // start and mouse must be down - if (eventType & INPUT_START && (ev.button === 0 || isTouch)) { - if (storeIndex < 0) { - store.push(ev); - storeIndex = store.length - 1; - } - } else if (eventType & (INPUT_END | INPUT_CANCEL)) { - removePointer = true; - } + /** + * @constructor TimeStep + * 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 + */ + function TimeStep(start, end, minimumStep, hiddenDates) { + // variables + this.current = new Date(); + this._start = new Date(); + this._end = new Date(); - // it not found, so the pointer hasn't been down (so it's probably a hover) - if (storeIndex < 0) { - return; - } + this.autoScale = true; + this.scale = 'day'; + this.step = 1; - // update the event in the store - store[storeIndex] = ev; + // initialize the range + this.setRange(start, end, minimumStep); - this.callback(this.manager, eventType, { - pointers: store, - changedPointers: [ev], - pointerType: pointerType, - srcEvent: ev - }); + // hidden Dates options + this.switchedDay = false; + this.switchedMonth = false; + this.switchedYear = false; + this.hiddenDates = hiddenDates; + if (hiddenDates === undefined) { + this.hiddenDates = []; + } - if (removePointer) { - // remove from the store - store.splice(storeIndex, 1); - } - } - }); + this.format = TimeStep.FORMAT; // default formatting + } - var SINGLE_TOUCH_INPUT_MAP = { - touchstart: INPUT_START, - touchmove: INPUT_MOVE, - touchend: INPUT_END, - touchcancel: INPUT_CANCEL + // Time formatting + TimeStep.FORMAT = { + minorLabels: { + millisecond: 'SSS', + second: 's', + minute: 'HH:mm', + hour: 'HH:mm', + weekday: 'ddd D', + day: 'D', + 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', + month: 'YYYY', + year: '' + } }; - var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart'; - var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel'; - /** - * Touch events input - * @constructor - * @extends Input + * 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', 'month', 'year'. + * @param {{minorLabels: Object, majorLabels: Object}} format */ - function SingleTouchInput() { - this.evTarget = SINGLE_TOUCH_TARGET_EVENTS; - this.evWin = SINGLE_TOUCH_WINDOW_EVENTS; - this.started = false; - - Input.apply(this, arguments); - } - - inherit(SingleTouchInput, Input, { - handler: function TEhandler(ev) { - var type = SINGLE_TOUCH_INPUT_MAP[ev.type]; - - // should we handle the touch events? - if (type === INPUT_START) { - this.started = true; - } - - if (!this.started) { - return; - } - - var touches = normalizeSingleTouches.call(this, ev, type); - - // when done, reset the started state - if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) { - this.started = false; - } - - this.callback(this.manager, type, { - pointers: touches[0], - changedPointers: touches[1], - pointerType: INPUT_TYPE_TOUCH, - srcEvent: ev - }); - } - }); + TimeStep.prototype.setFormat = function (format) { + var defaultFormat = util.deepExtend({}, TimeStep.FORMAT); + this.format = util.deepExtend(defaultFormat, format); + }; /** - * @this {TouchInput} - * @param {Object} ev - * @param {Number} type flag - * @returns {undefined|Array} [all, changed] + * 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 */ - function normalizeSingleTouches(ev, type) { - var all = toArray(ev.touches); - var changed = toArray(ev.changedTouches); - - if (type & (INPUT_END | INPUT_CANCEL)) { - all = uniqueArray(all.concat(changed), 'identifier', true); - } + TimeStep.prototype.setRange = function (start, end, minimumStep) { + if (!(start instanceof Date) || !(end instanceof Date)) { + throw 'No legal start or end date in method setRange'; + } - return [all, changed]; - } + this._start = start != undefined ? new Date(start.valueOf()) : new Date(); + this._end = end != undefined ? new Date(end.valueOf()) : new Date(); - var TOUCH_INPUT_MAP = { - touchstart: INPUT_START, - touchmove: INPUT_MOVE, - touchend: INPUT_END, - touchcancel: INPUT_CANCEL + if (this.autoScale) { + this.setMinimumStep(minimumStep); + } }; - var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel'; - /** - * Multi-user touch events input - * @constructor - * @extends Input + * Set the range iterator to the start date. */ - function TouchInput() { - this.evTarget = TOUCH_TARGET_EVENTS; - this.targetIds = {}; - - Input.apply(this, arguments); - } + TimeStep.prototype.first = function () { + this.current = new Date(this._start.valueOf()); + this.roundToMinor(); + }; - inherit(TouchInput, Input, { - handler: function MTEhandler(ev) { - var type = TOUCH_INPUT_MAP[ev.type]; - var touches = getTouches.call(this, ev, type); - if (!touches) { - return; - } + /** + * 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 + // IMPORTANT: we have no breaks in this switch! (this is no bug) + // noinspection FallThroughInSwitchStatementJS + switch (this.scale) { + case 'year': + this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step)); + this.current.setMonth(0); + case 'month': + this.current.setDate(1); + case 'day': // intentional fall through + case 'weekday': + this.current.setHours(0); + case 'hour': + this.current.setMinutes(0); + case 'minute': + this.current.setSeconds(0); + case 'second': + this.current.setMilliseconds(0); + //case 'millisecond': // nothing to do for milliseconds + } - this.callback(this.manager, type, { - pointers: touches[0], - changedPointers: touches[1], - pointerType: INPUT_TYPE_TOUCH, - srcEvent: ev - }); + 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.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step);break; + case 'second': + this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step);break; + case 'minute': + this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step);break; + case 'hour': + this.current.setHours(this.current.getHours() - this.current.getHours() % this.step);break; + case 'weekday': // intentional fall through + case 'day': + this.current.setDate(this.current.getDate() - 1 - (this.current.getDate() - 1) % this.step + 1);break; + case 'month': + this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step);break; + case 'year': + this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step);break; + default: + break; } - }); + } + }; /** - * @this {TouchInput} - * @param {Object} ev - * @param {Number} type flag - * @returns {undefined|Array} [all, changed] + * Check if the there is a next step + * @return {boolean} true if the current date has not passed the end date */ - function getTouches(ev, type) { - var allTouches = toArray(ev.touches); - var targetIds = this.targetIds; - - // when there is only one touch, the process can be simplified - if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) { - targetIds[allTouches[0].identifier] = true; - return [allTouches, allTouches]; - } + TimeStep.prototype.hasNext = function () { + return this.current.valueOf() <= this._end.valueOf(); + }; - var i, - targetTouches, - changedTouches = toArray(ev.changedTouches), - changedTargetTouches = [], - target = this.target; + /** + * Do the next step + */ + TimeStep.prototype.next = function () { + var prev = this.current.valueOf(); - // get target touches from touches - targetTouches = allTouches.filter(function(touch) { - return hasParent(touch.target, target); - }); + // Two cases, needed to prevent issues with switching daylight savings + // (end of March and end of October) + if (this.current.getMonth() < 6) { + switch (this.scale) { + case 'millisecond': - // collect touches - if (type === INPUT_START) { - i = 0; - while (i < targetTouches.length) { - targetIds[targetTouches[i].identifier] = true; - i++; - } + this.current = new Date(this.current.valueOf() + this.step);break; + case 'second': + this.current = new Date(this.current.valueOf() + this.step * 1000);break; + case 'minute': + this.current = new Date(this.current.valueOf() + this.step * 1000 * 60);break; + case 'hour': + this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60); + // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...) + var h = this.current.getHours(); + this.current.setHours(h - h % this.step); + break; + case 'weekday': // intentional fall through + case 'day': + this.current.setDate(this.current.getDate() + this.step);break; + case 'month': + this.current.setMonth(this.current.getMonth() + this.step);break; + case 'year': + this.current.setFullYear(this.current.getFullYear() + this.step);break; + default: + break; } - - // filter changed touches to only contain touches that exist in the collected target ids - i = 0; - while (i < changedTouches.length) { - if (targetIds[changedTouches[i].identifier]) { - changedTargetTouches.push(changedTouches[i]); - } - - // cleanup removed touches - if (type & (INPUT_END | INPUT_CANCEL)) { - delete targetIds[changedTouches[i].identifier]; - } - i++; + } else { + switch (this.scale) { + case 'millisecond': + this.current = new Date(this.current.valueOf() + this.step);break; + case 'second': + this.current.setSeconds(this.current.getSeconds() + this.step);break; + case 'minute': + this.current.setMinutes(this.current.getMinutes() + this.step);break; + case 'hour': + this.current.setHours(this.current.getHours() + this.step);break; + case 'weekday': // intentional fall through + case 'day': + this.current.setDate(this.current.getDate() + this.step);break; + case 'month': + this.current.setMonth(this.current.getMonth() + this.step);break; + case 'year': + this.current.setFullYear(this.current.getFullYear() + this.step);break; + default: + break; } + } - if (!changedTargetTouches.length) { - return; + if (this.step != 1) { + // round down to the correct major value + switch (this.scale) { + case 'millisecond': + if (this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0);break; + case 'second': + if (this.current.getSeconds() < this.step) this.current.setSeconds(0);break; + case 'minute': + if (this.current.getMinutes() < this.step) this.current.setMinutes(0);break; + case 'hour': + if (this.current.getHours() < this.step) this.current.setHours(0);break; + case 'weekday': // intentional fall through + case 'day': + if (this.current.getDate() < this.step + 1) this.current.setDate(1);break; + case 'month': + if (this.current.getMonth() < this.step) this.current.setMonth(0);break; + case 'year': + break; // nothing to do for year + default: + break; } + } - return [ - // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel' - uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true), - changedTargetTouches - ]; - } + // safety mechanism: if current time is still unchanged, move to the end + if (this.current.valueOf() == prev) { + this.current = new Date(this._end.valueOf()); + } + + DateUtil.stepOverHiddenDates(this, prev); + }; /** - * Combined touch and mouse input - * - * Touch has a higher priority then mouse, and while touching no mouse events are allowed. - * This because touch devices also emit mouse events while doing a touch. - * - * @constructor - * @extends Input + * Get the current datetime + * @return {Date} current The current date */ - function TouchMouseInput() { - Input.apply(this, arguments); - - var handler = bindFn(this.handler, this); - this.touch = new TouchInput(this.manager, handler); - this.mouse = new MouseInput(this.manager, handler); - } - - inherit(TouchMouseInput, Input, { - /** - * handle mouse and touch events - * @param {Hammer} manager - * @param {String} inputEvent - * @param {Object} inputData - */ - handler: function TMEhandler(manager, inputEvent, inputData) { - var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH), - isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE); - - // when we're in a touch event, so block all upcoming mouse events - // most mobile browser also emit mouseevents, right after touchstart - if (isTouch) { - this.mouse.allow = false; - } else if (isMouse && !this.mouse.allow) { - return; - } - - // reset the allowMouse when we're done - if (inputEvent & (INPUT_END | INPUT_CANCEL)) { - this.mouse.allow = true; - } - - this.callback(manager, inputEvent, inputData); - }, - - /** - * remove the event listeners - */ - destroy: function destroy() { - this.touch.destroy(); - this.mouse.destroy(); - } - }); + TimeStep.prototype.getCurrent = function () { + return this.current; + }; - var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction'); - var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined; + /** + * 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', '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; + } + }; - // magical touchAction value - var TOUCH_ACTION_COMPUTE = 'compute'; - var TOUCH_ACTION_AUTO = 'auto'; - var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented - var TOUCH_ACTION_NONE = 'none'; - var TOUCH_ACTION_PAN_X = 'pan-x'; - var TOUCH_ACTION_PAN_Y = 'pan-y'; + /** + * Enable or disable autoscaling + * @param {boolean} enable If true, autoascaling is set true + */ + TimeStep.prototype.setAutoScale = function (enable) { + this.autoScale = enable; + }; /** - * Touch Action - * sets the touchAction property or uses the js alternative - * @param {Manager} manager - * @param {String} value - * @constructor + * Automatically determine the scale that bests fits the provided minimum step + * @param {Number} [minimumStep] The minimum step size in milliseconds */ - function TouchAction(manager, value) { - this.manager = manager; - this.set(value); - } + TimeStep.prototype.setMinimumStep = function (minimumStep) { + if (minimumStep == undefined) { + return; + } - TouchAction.prototype = { - /** - * set the touchAction value on the element or enable the polyfill - * @param {String} value - */ - set: function(value) { - // find out the touch-action by the event handlers - if (value == TOUCH_ACTION_COMPUTE) { - value = this.compute(); - } + //var b = asc + ds; - if (NATIVE_TOUCH_ACTION) { - this.manager.element.style[PREFIXED_TOUCH_ACTION] = value; - } - this.actions = value.toLowerCase().trim(); - }, - - /** - * just re-set the touchAction value - */ - update: function() { - this.set(this.manager.options.touchAction); - }, - - /** - * compute the value for the touchAction property based on the recognizer's settings - * @returns {String} value - */ - compute: function() { - var actions = []; - each(this.manager.recognizers, function(recognizer) { - if (boolOrFn(recognizer.options.enable, [recognizer])) { - actions = actions.concat(recognizer.getTouchAction()); - } - }); - return cleanTouchActions(actions.join(' ')); - }, - - /** - * this method is called on each input cycle and provides the preventing of the browser behavior - * @param {Object} input - */ - preventDefaults: function(input) { - // not needed with native support for the touchAction property - if (NATIVE_TOUCH_ACTION) { - return; - } - - var srcEvent = input.srcEvent; - var direction = input.offsetDirection; + 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; - // if the touch action did prevented once this session - if (this.manager.session.prevented) { - srcEvent.preventDefault(); - return; - } + // 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; + } + }; - var actions = this.actions; - var hasNone = inStr(actions, TOUCH_ACTION_NONE); - var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); - var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); + /** + * 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', 'month', 'year'. + * @param {number} step Current step (1, 2, 4, 5, ... + * @return {Date} snappedDate + */ + TimeStep.snap = function (date, scale, step) { + var clone = new Date(date.valueOf()); - if (hasNone || - (hasPanY && direction & DIRECTION_HORIZONTAL) || - (hasPanX && direction & DIRECTION_VERTICAL)) { - return this.preventSrc(srcEvent); - } - }, + if (scale == 'year') { + var year = clone.getFullYear() + Math.round(clone.getMonth() / 12); + clone.setFullYear(Math.round(year / step) * step); + clone.setMonth(0); + clone.setDate(0); + clone.setHours(0); + clone.setMinutes(0); + clone.setSeconds(0); + clone.setMilliseconds(0); + } else if (scale == 'month') { + if (clone.getDate() > 15) { + clone.setDate(1); + clone.setMonth(clone.getMonth() + 1); + // important: first set Date to 1, after that change the month. + } else { + clone.setDate(1); + } - /** - * call preventDefault to prevent the browser's default behavior (scrolling in most cases) - * @param {Object} srcEvent - */ - preventSrc: function(srcEvent) { - this.manager.session.prevented = true; - srcEvent.preventDefault(); + clone.setHours(0); + clone.setMinutes(0); + clone.setSeconds(0); + clone.setMilliseconds(0); + } else if (scale == 'day') { + //noinspection FallthroughInSwitchStatementJS + switch (step) { + case 5: + case 2: + clone.setHours(Math.round(clone.getHours() / 24) * 24);break; + default: + clone.setHours(Math.round(clone.getHours() / 12) * 12);break; + } + clone.setMinutes(0); + clone.setSeconds(0); + clone.setMilliseconds(0); + } else if (scale == 'weekday') { + //noinspection FallthroughInSwitchStatementJS + switch (step) { + case 5: + case 2: + clone.setHours(Math.round(clone.getHours() / 12) * 12);break; + default: + clone.setHours(Math.round(clone.getHours() / 6) * 6);break; + } + clone.setMinutes(0); + clone.setSeconds(0); + clone.setMilliseconds(0); + } else if (scale == 'hour') { + switch (step) { + case 4: + clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60);break; + default: + clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30);break; + } + clone.setSeconds(0); + clone.setMilliseconds(0); + } else if (scale == 'minute') { + //noinspection FallthroughInSwitchStatementJS + switch (step) { + case 15: + case 10: + clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5); + clone.setSeconds(0); + break; + case 5: + clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60);break; + default: + clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30);break; + } + clone.setMilliseconds(0); + } else if (scale == 'second') { + //noinspection FallthroughInSwitchStatementJS + switch (step) { + case 15: + case 10: + clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5); + clone.setMilliseconds(0); + break; + case 5: + clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000);break; + default: + clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500);break; } + } else if (scale == 'millisecond') { + var _step = step > 5 ? step / 2 : 1; + clone.setMilliseconds(Math.round(clone.getMilliseconds() / _step) * _step); + } + + return clone; }; /** - * when the touchActions are collected they are not a valid value, so we need to clean things up. * - * @param {String} actions - * @returns {*} + * 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. */ - function cleanTouchActions(actions) { - // none - if (inStr(actions, TOUCH_ACTION_NONE)) { - return TOUCH_ACTION_NONE; - } - - var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); - var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); - - // pan-x and pan-y can be combined - if (hasPanX && hasPanY) { - return TOUCH_ACTION_PAN_X + ' ' + TOUCH_ACTION_PAN_Y; + TimeStep.prototype.isMajor = function () { + if (this.switchedYear == true) { + this.switchedYear = false; + switch (this.scale) { + case 'year': + case 'month': + case 'weekday': + case 'day': + case 'hour': + case 'minute': + case 'second': + case 'millisecond': + return true; + default: + return false; } - - // pan-x OR pan-y - if (hasPanX || hasPanY) { - return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y; + } else if (this.switchedMonth == true) { + this.switchedMonth = false; + switch (this.scale) { + case 'weekday': + case 'day': + case 'hour': + case 'minute': + case 'second': + case 'millisecond': + return true; + default: + return false; } - - // manipulation - if (inStr(actions, TOUCH_ACTION_MANIPULATION)) { - return TOUCH_ACTION_MANIPULATION; + } else if (this.switchedDay == true) { + this.switchedDay = false; + switch (this.scale) { + case 'millisecond': + case 'second': + case 'minute': + case 'hour': + return true; + default: + return false; } + } - return TOUCH_ACTION_AUTO; - } + switch (this.scale) { + case 'millisecond': + return this.current.getMilliseconds() == 0; + case 'second': + return this.current.getSeconds() == 0; + case 'minute': + return this.current.getHours() == 0 && this.current.getMinutes() == 0; + case 'hour': + return this.current.getHours() == 0; + case 'weekday': // intentional fall through + case 'day': + return this.current.getDate() == 1; + case 'month': + return this.current.getMonth() == 0; + case 'year': + return false; + default: + return false; + } + }; /** - * Recognizer flow explained; * - * All recognizers have the initial state of POSSIBLE when a input session starts. - * The definition of a input session is from the first input until the last input, with all it's movement in it. * - * Example session for mouse-input: mousedown -> mousemove -> mouseup - * - * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed - * which determines with state it should be. - * - * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to - * POSSIBLE to give it another change on the next cycle. - * - * Possible - * | - * +-----+---------------+ - * | | - * +-----+-----+ | - * | | | - * Failed Cancelled | - * +-------+------+ - * | | - * Recognized Began - * | - * Changed - * | - * Ended/Recognized + * 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] custom date. if not provided, current date is taken */ - var STATE_POSSIBLE = 1; - var STATE_BEGAN = 2; - var STATE_CHANGED = 4; - var STATE_ENDED = 8; - var STATE_RECOGNIZED = STATE_ENDED; - var STATE_CANCELLED = 16; - var STATE_FAILED = 32; + TimeStep.prototype.getLabelMinor = function (date) { + if (date == undefined) { + date = this.current; + } + + var format = this.format.minorLabels[this.scale]; + return format && format.length > 0 ? moment(date).format(format) : ''; + }; /** - * Recognizer - * Every recognizer needs to extend from this class. - * @constructor - * @param {Object} options + * 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] custom date. if not provided, current date is taken */ - function Recognizer(options) { - this.id = uniqueId(); + TimeStep.prototype.getLabelMajor = function (date) { + if (date == undefined) { + date = this.current; + } - this.manager = null; - this.options = merge(options || {}, this.defaults); + var format = this.format.majorLabels[this.scale]; + return format && format.length > 0 ? moment(date).format(format) : ''; + }; - // default is enable true - this.options.enable = ifUndefined(this.options.enable, true); + TimeStep.prototype.getClassName = function () { + var m = moment(this.current); + var date = m.locale ? m.locale('en') : m.lang('en'); // old versions of moment have .lang() function + var step = this.step; - this.state = STATE_POSSIBLE; + function even(value) { + return value / step % 2 == 0 ? ' vis-even' : ' vis-odd'; + } - this.simultaneous = {}; - this.requireFail = []; - } + 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 ''; + } - Recognizer.prototype = { - /** - * @virtual - * @type {Object} - */ - defaults: {}, + function currentWeek(date) { + return date.isSame(new Date(), 'week') ? ' vis-current-week' : ''; + } - /** - * set options - * @param {Object} options - * @return {Recognizer} - */ - set: function(options) { - extend(this.options, options); + function currentMonth(date) { + return date.isSame(new Date(), 'month') ? ' vis-current-month' : ''; + } - // also update the touchAction, in case something changed about the directions/enabled state - this.manager && this.manager.touchAction.update(); - return this; - }, + function currentYear(date) { + return date.isSame(new Date(), 'year') ? ' vis-current-year' : ''; + } - /** - * recognize simultaneous with an other recognizer. - * @param {Recognizer} otherRecognizer - * @returns {Recognizer} this - */ - recognizeWith: function(otherRecognizer) { - if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) { - return this; - } + switch (this.scale) { + case 'millisecond': + return even(date.milliseconds()).trim(); - var simultaneous = this.simultaneous; - otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); - if (!simultaneous[otherRecognizer.id]) { - simultaneous[otherRecognizer.id] = otherRecognizer; - otherRecognizer.recognizeWith(this); - } - return this; - }, + case 'second': + return even(date.seconds()).trim(); - /** - * drop the simultaneous link. it doesnt remove the link on the other recognizer. - * @param {Recognizer} otherRecognizer - * @returns {Recognizer} this - */ - dropRecognizeWith: function(otherRecognizer) { - if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) { - return this; - } + case 'minute': + return even(date.minutes()).trim(); - otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); - delete this.simultaneous[otherRecognizer.id]; - return this; - }, + case 'hour': + var hours = date.hours(); + if (this.step == 4) { + hours = hours + '-h' + (hours + 4); + } + return 'vis-h' + hours + today(date) + even(date.hours()); - /** - * recognizer can only run when an other is failing - * @param {Recognizer} otherRecognizer - * @returns {Recognizer} this - */ - requireFailure: function(otherRecognizer) { - if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) { - return this; - } + case 'weekday': + return 'vis-' + date.format('dddd').toLowerCase() + today(date) + currentWeek(date) + even(date.date()); - var requireFail = this.requireFail; - otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); - if (inArray(requireFail, otherRecognizer) === -1) { - requireFail.push(otherRecognizer); - otherRecognizer.requireFailure(this); - } - return this; - }, - - /** - * drop the requireFailure link. it does not remove the link on the other recognizer. - * @param {Recognizer} otherRecognizer - * @returns {Recognizer} this - */ - dropRequireFailure: function(otherRecognizer) { - if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) { - return this; - } - - otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); - var index = inArray(this.requireFail, otherRecognizer); - if (index > -1) { - this.requireFail.splice(index, 1); - } - return this; - }, + case 'day': + var day = date.date(); + var month = date.format('MMMM').toLowerCase(); + return 'vis-day' + day + ' vis-' + month + currentMonth(date) + even(day - 1); - /** - * has require failures boolean - * @returns {boolean} - */ - hasRequireFailures: function() { - return this.requireFail.length > 0; - }, + case 'month': + return 'vis-' + date.format('MMMM').toLowerCase() + currentMonth(date) + even(date.month()); - /** - * if the recognizer can recognize simultaneous with an other recognizer - * @param {Recognizer} otherRecognizer - * @returns {Boolean} - */ - canRecognizeWith: function(otherRecognizer) { - return !!this.simultaneous[otherRecognizer.id]; - }, + case 'year': + var year = date.year(); + return 'vis-year' + year + currentYear(date) + even(year); - /** - * You should use `tryEmit` instead of `emit` directly to check - * that all the needed recognizers has failed before emitting. - * @param {Object} input - */ - emit: function(input) { - var self = this; - var state = this.state; + default: + return ''; + } + }; - function emit(withState) { - self.manager.emit(self.options.event + (withState ? stateStr(state) : ''), input); - } + module.exports = TimeStep; - // 'panstart' and 'panmove' - if (state < STATE_ENDED) { - emit(true); - } +/***/ }, +/* 21 */ +/***/ function(module, exports, __webpack_require__) { - emit(); // simple 'eventName' events + 'use strict'; - // panend and pancancel - if (state >= STATE_ENDED) { - emit(true); - } - }, + var Hammer = __webpack_require__(41); + var util = __webpack_require__(2); - /** - * Check that all the require failure recognizers has failed, - * if true, it emits a gesture event, - * otherwise, setup the state to FAILED. - * @param {Object} input - */ - tryEmit: function(input) { - if (this.canEmit()) { - return this.emit(input); - } - // it's failing anyway - this.state = STATE_FAILED; - }, + /** + * @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 || {}; - /** - * can we emit? - * @returns {boolean} - */ - canEmit: function() { - var i = 0; - while (i < this.requireFail.length) { - if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) { - return false; - } - i++; - } - return true; - }, + this.selected = false; + this.displayed = false; + this.dirty = true; - /** - * update the recognizer - * @param {Object} inputData - */ - recognize: function(inputData) { - // make a new copy of the inputData - // so we can change the inputData without messing up the other recognizers - var inputDataClone = extend({}, inputData); + this.top = null; + this.left = null; + this.width = null; + this.height = null; + } - // is is enabled and allow recognizing? - if (!boolOrFn(this.options.enable, [this, inputDataClone])) { - this.reset(); - this.state = STATE_FAILED; - return; - } + Item.prototype.stack = true; - // reset when we've reached the end - if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) { - this.state = STATE_POSSIBLE; - } + /** + * Select current item + */ + Item.prototype.select = function () { + this.selected = true; + this.dirty = true; + if (this.displayed) this.redraw(); + }; - this.state = this.process(inputDataClone); + /** + * Unselect current item + */ + Item.prototype.unselect = function () { + this.selected = false; + this.dirty = true; + if (this.displayed) this.redraw(); + }; - // the recognizer has recognized a gesture - // so trigger an event - if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) { - this.tryEmit(inputDataClone); - } - }, + /** + * 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.itemSet._moveToGroup(this, data.group); + } - /** - * return the state of the recognizer - * the actual recognizing happens in this method - * @virtual - * @param {Object} inputData - * @returns {Const} STATE - */ - process: function(inputData) { }, // jshint ignore:line + this.data = data; + this.dirty = true; + if (this.displayed) this.redraw(); + }; - /** - * return the preferred touch-action - * @virtual - * @returns {Array} - */ - getTouchAction: function() { }, + /** + * Set a parent for the item + * @param {ItemSet | Group} parent + */ + Item.prototype.setParent = function (parent) { + if (this.displayed) { + this.hide(); + this.parent = parent; + if (this.parent) { + this.show(); + } + } else { + this.parent = parent; + } + }; - /** - * called when the gesture isn't allowed to recognize - * like when another is being recognized or it is disabled - * @virtual - */ - reset: function() { } + /** + * Check whether this item is visible inside given range + * @returns {{start: Number, end: Number}} range with a timestamp for start and end + * @returns {boolean} True if visible + */ + Item.prototype.isVisible = function (range) { + // Should be implemented by Item implementations + return false; }; /** - * get a usable string, used as event postfix - * @param {Const} state - * @returns {String} state + * Show the Item in the DOM (when not already visible) + * @return {Boolean} changed */ - function stateStr(state) { - if (state & STATE_CANCELLED) { - return 'cancel'; - } else if (state & STATE_ENDED) { - return 'end'; - } else if (state & STATE_CHANGED) { - return 'move'; - } else if (state & STATE_BEGAN) { - return 'start'; - } - return ''; - } + Item.prototype.show = function () { + return false; + }; /** - * direction cons to string - * @param {Const} direction - * @returns {String} + * Hide the Item from the DOM (when visible) + * @return {Boolean} changed */ - function directionStr(direction) { - if (direction == DIRECTION_DOWN) { - return 'down'; - } else if (direction == DIRECTION_UP) { - return 'up'; - } else if (direction == DIRECTION_LEFT) { - return 'left'; - } else if (direction == DIRECTION_RIGHT) { - return 'right'; - } - return ''; - } + Item.prototype.hide = function () { + return false; + }; /** - * get a recognizer by name if it is bound to a manager - * @param {Recognizer|String} otherRecognizer - * @param {Recognizer} recognizer - * @returns {Recognizer} + * Repaint the item */ - function getRecognizerByNameIfManager(otherRecognizer, recognizer) { - var manager = recognizer.manager; - if (manager) { - return manager.get(otherRecognizer); - } - return otherRecognizer; - } + Item.prototype.redraw = function () {}; /** - * This recognizer is just used as a base for the simple attribute recognizers. - * @constructor - * @extends Recognizer + * Reposition the Item horizontally */ - function AttrRecognizer() { - Recognizer.apply(this, arguments); - } + Item.prototype.repositionX = function () {}; - inherit(AttrRecognizer, Recognizer, { - /** - * @namespace - * @memberof AttrRecognizer - */ - defaults: { - /** - * @type {Number} - * @default 1 - */ - pointers: 1 - }, + /** + * Reposition the Item vertically + */ + Item.prototype.repositionY = function () {}; - /** - * Used to check if it the recognizer receives valid input, like input.distance > 10. - * @memberof AttrRecognizer - * @param {Object} input - * @returns {Boolean} recognized - */ - attrTest: function(input) { - var optionPointers = this.options.pointers; - return optionPointers === 0 || input.pointers.length === optionPointers; - }, + /** + * 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) { + if (this.selected && this.options.editable.remove && !this.dom.deleteButton) { + // create and show button + var me = this; - /** - * Process the input and return the state for the recognizer - * @memberof AttrRecognizer - * @param {Object} input - * @returns {*} State - */ - process: function(input) { - var state = this.state; - var eventType = input.eventType; + var deleteButton = document.createElement('div'); + deleteButton.className = 'vis-delete'; + deleteButton.title = 'Delete this item'; - var isRecognized = state & (STATE_BEGAN | STATE_CHANGED); - var isValid = this.attrTest(input); + // TODO: be able to destroy the delete button + new Hammer(deleteButton).on('tap', function (event) { + event.stopPropagation(); + me.parent.removeFromDataSet(me); + }); - // on cancel input and we've recognized before, return STATE_CANCELLED - if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) { - return state | STATE_CANCELLED; - } else if (isRecognized || isValid) { - if (eventType & INPUT_END) { - return state | STATE_ENDED; - } else if (!(state & STATE_BEGAN)) { - return STATE_BEGAN; - } - return state | STATE_CHANGED; - } - return STATE_FAILED; + 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; + } + }; /** - * Pan - * Recognized when the pointer is down and moved in the allowed direction. - * @constructor - * @extends AttrRecognizer + * Set HTML contents for the item + * @param {Element} element HTML element to fill with the contents + * @private */ - function PanRecognizer() { - AttrRecognizer.apply(this, arguments); - - this.pX = null; - this.pY = null; - } - - inherit(PanRecognizer, AttrRecognizer, { - /** - * @namespace - * @memberof PanRecognizer - */ - defaults: { - event: 'pan', - threshold: 10, - pointers: 1, - direction: DIRECTION_ALL - }, + Item.prototype._updateContents = function (element) { + var content; + if (this.options.template) { + var itemData = this.parent.itemSet.itemsData.get(this.id); // get a clone of the data from the dataset + content = this.options.template(itemData); + } else { + content = this.data.content; + } - getTouchAction: function() { - var direction = this.options.direction; - var actions = []; - if (direction & DIRECTION_HORIZONTAL) { - actions.push(TOUCH_ACTION_PAN_Y); - } - if (direction & DIRECTION_VERTICAL) { - actions.push(TOUCH_ACTION_PAN_X); - } - return actions; - }, + var 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); + } + } - directionTest: function(input) { - var options = this.options; - var hasMoved = true; - var distance = input.distance; - var direction = input.direction; - var x = input.deltaX; - var y = input.deltaY; + this.content = content; + } + }; - // lock to axis? - if (!(direction & options.direction)) { - if (options.direction & DIRECTION_HORIZONTAL) { - direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; - hasMoved = x != this.pX; - distance = Math.abs(input.deltaX); - } else { - direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN; - hasMoved = y != this.pY; - distance = Math.abs(input.deltaY); - } - } - input.direction = direction; - return hasMoved && distance > options.threshold && direction & options.direction; - }, + /** + * Set HTML contents for the item + * @param {Element} element HTML element to fill with the contents + * @private + */ + Item.prototype._updateTitle = function (element) { + if (this.data.title != null) { + element.title = this.data.title || ''; + } else { + element.removeAttribute('vis-title'); + } + }; - attrTest: function(input) { - return AttrRecognizer.prototype.attrTest.call(this, input) && - (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input))); - }, + /** + * 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 = []; - emit: function(input) { - this.pX = input.deltaX; - this.pY = input.deltaY; + if (Array.isArray(this.options.dataAttributes)) { + attributes = this.options.dataAttributes; + } else if (this.options.dataAttributes == 'all') { + attributes = Object.keys(this.data); + } else { + return; + } - var direction = directionStr(input.direction); - if (direction) { - this.manager.emit(this.options.event + direction, input); - } + for (var i = 0; i < attributes.length; i++) { + var name = attributes[i]; + var value = this.data[name]; - this._super.emit.call(this, input); + if (value != null) { + element.setAttribute('data-' + name, value); + } else { + element.removeAttribute('data-' + name); + } } - }); + } + }; /** - * Pinch - * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out). - * @constructor - * @extends AttrRecognizer + * Update custom styles of the element + * @param element + * @private */ - function PinchRecognizer() { - AttrRecognizer.apply(this, arguments); - } + Item.prototype._updateStyle = function (element) { + // remove old styles + if (this.style) { + util.removeCssText(element, this.style); + this.style = null; + } - inherit(PinchRecognizer, AttrRecognizer, { - /** - * @namespace - * @memberof PinchRecognizer - */ - defaults: { - event: 'pinch', - threshold: 0, - pointers: 2 - }, - - getTouchAction: function() { - return [TOUCH_ACTION_NONE]; - }, - - attrTest: function(input) { - return this._super.attrTest.call(this, input) && - (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN); - }, - - emit: function(input) { - this._super.emit.call(this, input); - if (input.scale !== 1) { - var inOut = input.scale < 1 ? 'in' : 'out'; - this.manager.emit(this.options.event + inOut, input); - } - } - }); + // append new styles + if (this.data.style) { + util.addCssText(element, this.data.style); + this.style = this.data.style; + } + }; /** - * Press - * Recognized when the pointer is down for x ms without any movement. - * @constructor - * @extends Recognizer + * Stringify the items contents + * @param {string | Element | undefined} content + * @returns {string | undefined} + * @private */ - function PressRecognizer() { - Recognizer.apply(this, arguments); + Item.prototype._contentToString = function (content) { + if (typeof content === 'string') return content; + if (content && 'outerHTML' in content) return content.outerHTML; + return content; + }; - this._timer = null; - this._input = null; - } + module.exports = Item; - inherit(PressRecognizer, Recognizer, { - /** - * @namespace - * @memberof PressRecognizer - */ - defaults: { - event: 'press', - pointers: 1, - time: 500, // minimal time of the pointer to be pressed - threshold: 5 // a minimal movement is ok, but keep it low - }, + // should be implemented by the item - getTouchAction: function() { - return [TOUCH_ACTION_AUTO]; - }, + // should be implemented by the item - process: function(input) { - var options = this.options; - var validPointers = input.pointers.length === options.pointers; - var validMovement = input.distance < options.threshold; - var validTime = input.deltaTime > options.time; + // should be implemented by the item - this._input = input; +/***/ }, +/* 22 */ +/***/ function(module, exports, __webpack_require__) { - // we only allow little movement - // and we've reached an end event, so a tap is possible - if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) { - this.reset(); - } else if (input.eventType & INPUT_START) { - this.reset(); - this._timer = setTimeoutContext(function() { - this.state = STATE_RECOGNIZED; - this.tryEmit(); - }, options.time, this); - } else if (input.eventType & INPUT_END) { - return STATE_RECOGNIZED; - } - return STATE_FAILED; - }, + 'use strict'; - reset: function() { - clearTimeout(this._timer); - }, + var Hammer = __webpack_require__(41); + var Item = __webpack_require__(21); + var BackgroundGroup = __webpack_require__(31); + var RangeItem = __webpack_require__(24); - emit: function(input) { - if (this.state !== STATE_RECOGNIZED) { - return; - } + /** + * @constructor BackgroundItem + * @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 + */ + // TODO: implement support for the BackgroundItem just having a start, then being displayed as a sort of an annotation + function BackgroundItem(data, conversion, options) { + this.props = { + content: { + width: 0 + } + }; + this.overflow = false; // if contents can overflow (css styling), this flag is set to true - if (input && (input.eventType & INPUT_END)) { - this.manager.emit(this.options.event + 'up', input); - } else { - this._input.timeStamp = now(); - this.manager.emit(this.options.event, this._input); - } + // 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); + } + } - /** - * Rotate - * Recognized when two or more pointer are moving in a circular motion. - * @constructor - * @extends AttrRecognizer - */ - function RotateRecognizer() { - AttrRecognizer.apply(this, arguments); + Item.call(this, data, conversion, options); } - inherit(RotateRecognizer, AttrRecognizer, { - /** - * @namespace - * @memberof RotateRecognizer - */ - defaults: { - event: 'rotate', - threshold: 0, - pointers: 2 - }, - - getTouchAction: function() { - return [TOUCH_ACTION_NONE]; - }, + BackgroundItem.prototype = new Item(null, null, null); - attrTest: function(input) { - return this._super.attrTest.call(this, input) && - (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN); - } - }); + BackgroundItem.prototype.baseClassName = 'vis-item vis-background'; + BackgroundItem.prototype.stack = false; /** - * Swipe - * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction. - * @constructor - * @extends AttrRecognizer + * Check whether this item is visible inside given range + * @returns {{start: Number, end: Number}} range with a timestamp for start and end + * @returns {boolean} True if visible */ - function SwipeRecognizer() { - AttrRecognizer.apply(this, arguments); - } + BackgroundItem.prototype.isVisible = function (range) { + // determine visibility + return this.data.start < range.end && this.data.end > range.start; + }; - inherit(SwipeRecognizer, AttrRecognizer, { - /** - * @namespace - * @memberof SwipeRecognizer - */ - defaults: { - event: 'swipe', - threshold: 10, - velocity: 0.65, - direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL, - pointers: 1 - }, + /** + * Repaint the item + */ + BackgroundItem.prototype.redraw = function () { + var dom = this.dom; + if (!dom) { + // create DOM + this.dom = {}; + dom = this.dom; - getTouchAction: function() { - return PanRecognizer.prototype.getTouchAction.call(this); - }, + // background box + dom.box = document.createElement('div'); + // className is updated in redraw() - attrTest: function(input) { - var direction = this.options.direction; - var velocity; + // frame box (to prevent the item contents from overflowing + dom.frame = document.createElement('div'); + dom.frame.className = 'vis-item-overflow'; + dom.box.appendChild(dom.frame); - if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) { - velocity = input.velocity; - } else if (direction & DIRECTION_HORIZONTAL) { - velocity = input.velocityX; - } else if (direction & DIRECTION_VERTICAL) { - velocity = input.velocityY; - } + // contents box + dom.content = document.createElement('div'); + dom.content.className = 'vis-item-content'; + dom.frame.appendChild(dom.content); - return this._super.attrTest.call(this, input) && - direction & input.direction && - input.distance > this.options.threshold && - abs(velocity) > this.options.velocity && input.eventType & INPUT_END; - }, + // Note: we do NOT attach this item as attribute to the DOM, + // such that background items cannot be selected + //dom.box['timeline-item'] = this; - emit: function(input) { - var direction = directionStr(input.direction); - if (direction) { - this.manager.emit(this.options.event + direction, input); - } + this.dirty = true; + } - this.manager.emit(this.options.event, input); + // append DOM to parent DOM + if (!this.parent) { + throw new Error('Cannot redraw item: no parent attached'); + } + if (!dom.box.parentNode) { + var background = this.parent.dom.background; + if (!background) { + throw new Error('Cannot redraw item: parent has no background container element'); } - }); - - /** - * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur - * between the given interval and position. The delay option can be used to recognize multi-taps without firing - * a single tap. - * - * The eventData from the emitted event contains the property `tapCount`, which contains the amount of - * multi-taps being recognized. - * @constructor - * @extends Recognizer - */ - function TapRecognizer() { - Recognizer.apply(this, arguments); + background.appendChild(dom.box); + } + this.displayed = true; - // previous time and center, - // used for tap counting - this.pTime = false; - this.pCenter = false; + // Update DOM when item is marked dirty. 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._updateTitle(this.dom.content); + this._updateDataAttributes(this.dom.content); + this._updateStyle(this.dom.box); - this._timer = null; - this._input = null; - this.count = 0; - } + // update class + var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); + dom.box.className = this.baseClassName + className; - inherit(TapRecognizer, Recognizer, { - /** - * @namespace - * @memberof PinchRecognizer - */ - defaults: { - event: 'tap', - pointers: 1, - taps: 1, - interval: 300, // max time between the multi-tap taps - time: 250, // max time of the pointer to be down (like finger on the screen) - threshold: 2, // a minimal movement is ok, but keep it low - posThreshold: 10 // a multi-tap can be a bit off the initial position - }, + // determine from css whether this box has overflow + this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden'; - getTouchAction: function() { - return [TOUCH_ACTION_MANIPULATION]; - }, + // recalculate size + this.props.content.width = this.dom.content.offsetWidth; + this.height = 0; // set height zero, so this item will be ignored when stacking items - process: function(input) { - var options = this.options; + this.dirty = false; + } + }; - var validPointers = input.pointers.length === options.pointers; - var validMovement = input.distance < options.threshold; - var validTouchTime = input.deltaTime < options.time; + /** + * Show the item in the DOM (when not already visible). The items DOM will + * be created when needed. + */ + BackgroundItem.prototype.show = RangeItem.prototype.show; - this.reset(); + /** + * Hide the item from the DOM (when visible) + * @return {Boolean} changed + */ + BackgroundItem.prototype.hide = RangeItem.prototype.hide; - if ((input.eventType & INPUT_START) && (this.count === 0)) { - return this.failTimeout(); - } + /** + * Reposition the item horizontally + * @Override + */ + BackgroundItem.prototype.repositionX = RangeItem.prototype.repositionX; - // we only allow little movement - // and we've reached an end event, so a tap is possible - if (validMovement && validTouchTime && validPointers) { - if (input.eventType != INPUT_END) { - return this.failTimeout(); - } + /** + * Reposition the item vertically + * @Override + */ + BackgroundItem.prototype.repositionY = function (margin) { + var onTop = this.options.orientation.item === 'top'; + this.dom.content.style.top = onTop ? '' : '0'; + this.dom.content.style.bottom = onTop ? '0' : ''; + var height; - var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true; - var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold; + // special positioning for subgroups + if (this.data.subgroup !== undefined) { + // TODO: instead of calculating the top position of the subgroups here for every BackgroundItem, calculate the top of the subgroup once in Itemset - this.pTime = input.timeStamp; - this.pCenter = input.center; + var itemSubgroup = this.data.subgroup; + var subgroups = this.parent.subgroups; + var subgroupIndex = subgroups[itemSubgroup].index; + // if the orientation is top, we need to take the difference in height into account. + if (onTop == true) { + // the first subgroup will have to account for the distance from the top to the first item. + height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical; + height += subgroupIndex == 0 ? margin.axis - 0.5 * margin.item.vertical : 0; + var newTop = this.parent.top; + for (var subgroup in subgroups) { + if (subgroups.hasOwnProperty(subgroup)) { + if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroupIndex) { + newTop += subgroups[subgroup].height + margin.item.vertical; + } + } + } - if (!validMultiTap || !validInterval) { - this.count = 1; - } else { - this.count += 1; + // the others will have to be offset downwards with this same distance. + newTop += subgroupIndex != 0 ? margin.axis - 0.5 * margin.item.vertical : 0; + this.dom.box.style.top = newTop + 'px'; + this.dom.box.style.bottom = ''; + } + // and when the orientation is bottom: + else { + var newTop = this.parent.top; + var totalHeight = 0; + for (var subgroup in subgroups) { + if (subgroups.hasOwnProperty(subgroup)) { + if (subgroups[subgroup].visible == true) { + var newHeight = subgroups[subgroup].height + margin.item.vertical; + totalHeight += newHeight; + if (subgroups[subgroup].index > subgroupIndex) { + newTop += newHeight; } + } + } + } + height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical; + this.dom.box.style.top = this.parent.height - totalHeight + newTop + 'px'; + this.dom.box.style.bottom = ''; + } + } + // and in the case of no subgroups: + else { + // we want backgrounds with groups to only show in groups. + if (this.parent instanceof BackgroundGroup) { + // if the item is not in a group: + height = Math.max(this.parent.height, this.parent.itemSet.body.domProps.center.height, this.parent.itemSet.body.domProps.centerContainer.height); + this.dom.box.style.top = onTop ? '0' : ''; + this.dom.box.style.bottom = onTop ? '' : '0'; + } else { + height = this.parent.height; + // same alignment for items when orientation is top or bottom + this.dom.box.style.top = this.parent.top + 'px'; + this.dom.box.style.bottom = ''; + } + } + this.dom.box.style.height = height + 'px'; + }; - this._input = input; + module.exports = BackgroundItem; - // if tap count matches we have recognized it, - // else it has began recognizing... - var tapCount = this.count % options.taps; - if (tapCount === 0) { - // no failing requirements, immediately trigger the tap event - // or wait as long as the multitap interval to trigger - if (!this.hasRequireFailures()) { - return STATE_RECOGNIZED; - } else { - this._timer = setTimeoutContext(function() { - this.state = STATE_RECOGNIZED; - this.tryEmit(); - }, options.interval, this); - return STATE_BEGAN; - } - } - } - return STATE_FAILED; - }, +/***/ }, +/* 23 */ +/***/ function(module, exports, __webpack_require__) { - failTimeout: function() { - this._timer = setTimeoutContext(function() { - this.state = STATE_FAILED; - }, this.options.interval, this); - return STATE_FAILED; - }, + 'use strict'; - reset: function() { - clearTimeout(this._timer); + var Item = __webpack_require__(21); + + /** + * @constructor PointItem + * @extends Item + * @param {Object} data Object containing parameters start + * content, 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 PointItem(data, conversion, options) { + this.props = { + dot: { + top: 0, + width: 0, + height: 0 }, + content: { + height: 0, + marginLeft: 0 + } + }; - emit: function() { - if (this.state == STATE_RECOGNIZED ) { - this._input.tapCount = this.count; - this.manager.emit(this.options.event, this._input); - } + // validate data + if (data) { + if (data.start == undefined) { + throw new Error('Property "start" missing in item ' + data); } - }); + } - /** - * Simple way to create an manager with a default set of recognizers. - * @param {HTMLElement} element - * @param {Object} [options] - * @constructor - */ - function Hammer(element, options) { - options = options || {}; - options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset); - return new Manager(element, options); + Item.call(this, data, conversion, options); } + PointItem.prototype = new Item(null, null, null); + /** - * @const {string} + * Check whether this item is visible inside given range + * @returns {{start: Number, end: Number}} range with a timestamp for start and end + * @returns {boolean} True if visible */ - Hammer.VERSION = '2.0.4'; + PointItem.prototype.isVisible = function (range) { + // determine visibility + // TODO: account for the real width of the item. Right now we just add 1/4 to the window + var interval = (range.end - range.start) / 4; + return this.data.start > range.start - interval && this.data.start < range.end + interval; + }; /** - * default settings - * @namespace + * Repaint the item */ - Hammer.defaults = { - /** - * set if DOM events are being triggered. - * But this is slower and unused by simple implementations, so disabled by default. - * @type {Boolean} - * @default false - */ - domEvents: false, + PointItem.prototype.redraw = function () { + var dom = this.dom; + if (!dom) { + // create DOM + this.dom = {}; + dom = this.dom; - /** - * The value for the touchAction property/fallback. - * When set to `compute` it will magically set the correct value based on the added recognizers. - * @type {String} - * @default compute - */ - touchAction: TOUCH_ACTION_COMPUTE, + // background box + dom.point = document.createElement('div'); + // className is updated in redraw() - /** - * @type {Boolean} - * @default true - */ - enable: true, + // contents box, right from the dot + dom.content = document.createElement('div'); + dom.content.className = 'vis-item-content'; + dom.point.appendChild(dom.content); - /** - * EXPERIMENTAL FEATURE -- can be removed/changed - * Change the parent input target element. - * If Null, then it is being set the to main element. - * @type {Null|EventTarget} - * @default null - */ - inputTarget: null, + // dot at start + dom.dot = document.createElement('div'); + dom.point.appendChild(dom.dot); - /** - * force an input class - * @type {Null|Function} - * @default null - */ - inputClass: null, + // attach this item as attribute + dom.point['timeline-item'] = this; - /** - * Default recognizer setup when calling `Hammer()` - * When creating a new Manager these will be skipped. - * @type {Array} - */ - preset: [ - // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...] - [RotateRecognizer, { enable: false }], - [PinchRecognizer, { enable: false }, ['rotate']], - [SwipeRecognizer,{ direction: DIRECTION_HORIZONTAL }], - [PanRecognizer, { direction: DIRECTION_HORIZONTAL }, ['swipe']], - [TapRecognizer], - [TapRecognizer, { event: 'doubletap', taps: 2 }, ['tap']], - [PressRecognizer] - ], + this.dirty = true; + } - /** - * Some CSS properties can be used to improve the working of Hammer. - * Add them to this method and they will be set when creating a new Manager. - * @namespace - */ - cssProps: { - /** - * Disables text selection to improve the dragging gesture. Mainly for desktop browsers. - * @type {String} - * @default 'none' - */ - userSelect: 'none', + // append DOM to parent DOM + if (!this.parent) { + throw new Error('Cannot redraw item: no parent attached'); + } + if (!dom.point.parentNode) { + var foreground = this.parent.dom.foreground; + if (!foreground) { + throw new Error('Cannot redraw item: parent has no foreground container element'); + } + foreground.appendChild(dom.point); + } + this.displayed = true; - /** - * Disable the Windows Phone grippers when pressing an element. - * @type {String} - * @default 'none' - */ - touchSelect: 'none', + // Update DOM when item is marked dirty. 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._updateTitle(this.dom.point); + this._updateDataAttributes(this.dom.point); + this._updateStyle(this.dom.point); - /** - * Disables the default callout shown when you touch and hold a touch target. - * On iOS, when you touch and hold a touch target such as a link, Safari displays - * a callout containing information about the link. This property allows you to disable that callout. - * @type {String} - * @default 'none' - */ - touchCallout: 'none', + // update class + var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); + dom.point.className = 'vis-item vis-point' + className; + dom.dot.className = 'vis-item vis-dot' + className; - /** - * Specifies whether zooming is enabled. Used by IE10> - * @type {String} - * @default 'none' - */ - contentZooming: 'none', + // recalculate size + this.width = dom.point.offsetWidth; + this.height = dom.point.offsetHeight; + this.props.dot.width = dom.dot.offsetWidth; + this.props.dot.height = dom.dot.offsetHeight; + this.props.content.height = dom.content.offsetHeight; - /** - * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers. - * @type {String} - * @default 'none' - */ - userDrag: 'none', + // resize contents + dom.content.style.marginLeft = 2 * this.props.dot.width + 'px'; + //dom.content.style.marginRight = ... + 'px'; // TODO: margin right - /** - * Overrides the highlight color shown when the user taps a link or a JavaScript - * clickable element in iOS. This property obeys the alpha value, if specified. - * @type {String} - * @default 'rgba(0,0,0,0)' - */ - tapHighlightColor: 'rgba(0,0,0,0)' - } + dom.dot.style.top = (this.height - this.props.dot.height) / 2 + 'px'; + dom.dot.style.left = this.props.dot.width / 2 + 'px'; + + this.dirty = false; + } + + this._repaintDeleteButton(dom.point); }; - var STOP = 1; - var FORCED_STOP = 2; + /** + * Show the item in the DOM (when not already visible). The items DOM will + * be created when needed. + */ + PointItem.prototype.show = function () { + if (!this.displayed) { + this.redraw(); + } + }; /** - * Manager - * @param {HTMLElement} element - * @param {Object} [options] - * @constructor + * Hide the item from the DOM (when visible) */ - function Manager(element, options) { - options = options || {}; + PointItem.prototype.hide = function () { + if (this.displayed) { + if (this.dom.point.parentNode) { + this.dom.point.parentNode.removeChild(this.dom.point); + } - this.options = merge(options, Hammer.defaults); - this.options.inputTarget = this.options.inputTarget || element; + this.displayed = false; + } + }; - this.handlers = {}; - this.session = {}; - this.recognizers = []; + /** + * Reposition the item horizontally + * @Override + */ + PointItem.prototype.repositionX = function () { + var start = this.conversion.toScreen(this.data.start); - this.element = element; - this.input = createInputInstance(this); - this.touchAction = new TouchAction(this, this.options.touchAction); + this.left = start - this.props.dot.width; - toggleCssProps(this, true); + // reposition point + this.dom.point.style.left = this.left + 'px'; + }; - each(options.recognizers, function(item) { - var recognizer = this.add(new (item[0])(item[1])); - item[2] && recognizer.recognizeWith(item[2]); - item[3] && recognizer.requireFailure(item[3]); - }, this); - } + /** + * Reposition the item vertically + * @Override + */ + PointItem.prototype.repositionY = function () { + var orientation = this.options.orientation.item; + var point = this.dom.point; - Manager.prototype = { - /** - * set options - * @param {Object} options - * @returns {Manager} - */ - set: function(options) { - extend(this.options, options); + if (orientation == 'top') { + point.style.top = this.top + 'px'; + } else { + point.style.top = this.parent.height - this.top - this.height + 'px'; + } + }; - // Options that need a little more setup - if (options.touchAction) { - this.touchAction.update(); - } - if (options.inputTarget) { - // Clean up existing event listeners and reinitialize - this.input.destroy(); - this.input.target = options.inputTarget; - this.input.init(); - } - return this; - }, + module.exports = PointItem; - /** - * stop recognizing for this session. - * This session will be discarded, when a new [input]start event is fired. - * When forced, the recognizer cycle is stopped immediately. - * @param {Boolean} [force] - */ - stop: function(force) { - this.session.stopped = force ? FORCED_STOP : STOP; - }, +/***/ }, +/* 24 */ +/***/ function(module, exports, __webpack_require__) { - /** - * run the recognizers! - * called by the inputHandler function on every movement of the pointers (touches) - * it walks through all the recognizers and tries to detect the gesture that is being made - * @param {Object} inputData - */ - recognize: function(inputData) { - var session = this.session; - if (session.stopped) { - return; - } + 'use strict'; - // run the touch-action polyfill - this.touchAction.preventDefaults(inputData); + var Hammer = __webpack_require__(41); + var Item = __webpack_require__(21); - var recognizer; - var recognizers = this.recognizers; + /** + * @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 holds the recognizer that is being recognized. - // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED - // if no recognizer is detecting a thing, it is set to `null` - var curRecognizer = session.curRecognizer; + // 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); + } + } - // reset when the last recognizer is recognized - // or when we're in a new session - if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) { - curRecognizer = session.curRecognizer = null; - } + Item.call(this, data, conversion, options); + } - var i = 0; - while (i < recognizers.length) { - recognizer = recognizers[i]; + RangeItem.prototype = new Item(null, null, null); - // find out if we are allowed try to recognize the input for this one. - // 1. allow if the session is NOT forced stopped (see the .stop() method) - // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one - // that is being recognized. - // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer. - // this can be setup with the `recognizeWith()` method on the recognizer. - if (session.stopped !== FORCED_STOP && ( // 1 - !curRecognizer || recognizer == curRecognizer || // 2 - recognizer.canRecognizeWith(curRecognizer))) { // 3 - recognizer.recognize(inputData); - } else { - recognizer.reset(); - } + RangeItem.prototype.baseClassName = 'vis-item vis-range'; - // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the - // current active recognizer. but only if we don't already have an active recognizer - if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) { - curRecognizer = session.curRecognizer = recognizer; - } - i++; - } - }, + /** + * Check whether this item is visible inside given range + * @returns {{start: Number, end: Number}} 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; + }; - /** - * get a recognizer by its event name. - * @param {Recognizer|String} recognizer - * @returns {Recognizer|Null} - */ - get: function(recognizer) { - if (recognizer instanceof Recognizer) { - return recognizer; - } + /** + * Repaint the item + */ + RangeItem.prototype.redraw = function () { + var dom = this.dom; + if (!dom) { + // create DOM + this.dom = {}; + dom = this.dom; - var recognizers = this.recognizers; - for (var i = 0; i < recognizers.length; i++) { - if (recognizers[i].options.event == recognizer) { - return recognizers[i]; - } - } - return null; - }, + // background box + dom.box = document.createElement('div'); + // className is updated in redraw() - /** - * add a recognizer to the manager - * existing recognizers with the same event name will be removed - * @param {Recognizer} recognizer - * @returns {Recognizer|Manager} - */ - add: function(recognizer) { - if (invokeArrayArg(recognizer, 'add', this)) { - return this; - } + // frame box (to prevent the item contents from overflowing + dom.frame = document.createElement('div'); + dom.frame.className = 'vis-item-overflow'; + dom.box.appendChild(dom.frame); - // remove existing - var existing = this.get(recognizer.options.event); - if (existing) { - this.remove(existing); - } + // contents box + dom.content = document.createElement('div'); + dom.content.className = 'vis-item-content'; + dom.frame.appendChild(dom.content); - this.recognizers.push(recognizer); - recognizer.manager = this; + // attach this item as attribute + dom.box['timeline-item'] = this; - this.touchAction.update(); - return recognizer; - }, + this.dirty = true; + } - /** - * remove a recognizer by name or instance - * @param {Recognizer|String} recognizer - * @returns {Manager} - */ - remove: function(recognizer) { - if (invokeArrayArg(recognizer, 'remove', this)) { - return this; - } + // append DOM to parent DOM + if (!this.parent) { + throw new Error('Cannot redraw item: no parent attached'); + } + if (!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(dom.box); + } + this.displayed = true; - var recognizers = this.recognizers; - recognizer = this.get(recognizer); - recognizers.splice(inArray(recognizers, recognizer), 1); + // Update DOM when item is marked dirty. 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._updateTitle(this.dom.box); + this._updateDataAttributes(this.dom.box); + this._updateStyle(this.dom.box); - this.touchAction.update(); - return this; - }, + // update class + var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); + dom.box.className = this.baseClassName + className; - /** - * bind event - * @param {String} events - * @param {Function} handler - * @returns {EventEmitter} this - */ - on: function(events, handler) { - var handlers = this.handlers; - each(splitStr(events), function(event) { - handlers[event] = handlers[event] || []; - handlers[event].push(handler); - }); - return this; - }, + // determine from css whether this box has overflow + this.overflow = window.getComputedStyle(dom.frame).overflow !== 'hidden'; - /** - * unbind event, leave emit blank to remove all handlers - * @param {String} events - * @param {Function} [handler] - * @returns {EventEmitter} this - */ - off: function(events, handler) { - var handlers = this.handlers; - each(splitStr(events), function(event) { - if (!handler) { - delete handlers[event]; - } else { - handlers[event].splice(inArray(handlers[event], handler), 1); - } - }); - return this; - }, + // recalculate size + // 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'; + this.props.content.width = this.dom.content.offsetWidth; + this.height = this.dom.box.offsetHeight; + this.dom.content.style.maxWidth = ''; - /** - * emit event to the listeners - * @param {String} event - * @param {Object} data - */ - emit: function(event, data) { - // we also want to trigger dom events - if (this.options.domEvents) { - triggerDomEvent(event, data); - } + this.dirty = false; + } - // no handlers, so skip it all - var handlers = this.handlers[event] && this.handlers[event].slice(); - if (!handlers || !handlers.length) { - return; - } + this._repaintDeleteButton(dom.box); + this._repaintDragLeft(); + this._repaintDragRight(); + }; - data.type = event; - data.preventDefault = function() { - data.srcEvent.preventDefault(); - }; + /** + * 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(); + } + }; - var i = 0; - while (i < handlers.length) { - handlers[i](data); - i++; - } - }, - - /** - * destroy the manager and unbinds all events - * it doesn't unbind dom events, that is the user own responsibility - */ - destroy: function() { - this.element && toggleCssProps(this, false); + /** + * Hide the item from the DOM (when visible) + * @return {Boolean} changed + */ + RangeItem.prototype.hide = function () { + if (this.displayed) { + var box = this.dom.box; - this.handlers = {}; - this.session = {}; - this.input.destroy(); - this.element = null; + if (box.parentNode) { + box.parentNode.removeChild(box); } + + this.displayed = false; + } }; /** - * add/remove the css properties as defined in manager.options.cssProps - * @param {Manager} manager - * @param {Boolean} add + * 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 */ - function toggleCssProps(manager, add) { - var element = manager.element; - each(manager.options.cssProps, function(value, name) { - element.style[prefixed(element.style, name)] = add ? value : ''; - }); - } + 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 contentLeft; + var contentWidth; + + // limit the width of the range, as browsers cannot draw very wide divs + if (limitSize === undefined || limitSize === true) { + if (start < -parentWidth) { + start = -parentWidth; + } + if (end > 2 * parentWidth) { + end = 2 * parentWidth; + } + } + var boxWidth = Math.max(end - start, 1); + + if (this.overflow) { + 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 { + this.left = start; + this.width = boxWidth; + contentWidth = Math.min(end - start, this.props.content.width); + } + + this.dom.box.style.left = this.left + 'px'; + this.dom.box.style.width = boxWidth + 'px'; + + switch (this.options.align) { + case 'left': + this.dom.content.style.left = '0'; + break; + + case 'right': + this.dom.content.style.left = Math.max(boxWidth - contentWidth, 0) + 'px'; + break; + + case 'center': + 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) { + contentLeft = Math.max(-start, 0); + } else { + contentLeft = -contentWidth; // ensure it's not visible anymore + } + } else { + if (start < 0) { + contentLeft = -start; + } else { + contentLeft = 0; + } + } + this.dom.content.style.left = contentLeft + 'px'; + } + }; /** - * trigger dom event - * @param {String} event - * @param {Object} data + * Reposition the item vertically + * @Override */ - function triggerDomEvent(event, data) { - var gestureEvent = document.createEvent('Event'); - gestureEvent.initEvent(event, true, true); - gestureEvent.gesture = data; - data.target.dispatchEvent(gestureEvent); - } + RangeItem.prototype.repositionY = function () { + var orientation = this.options.orientation.item; + var box = this.dom.box; - extend(Hammer, { - INPUT_START: INPUT_START, - INPUT_MOVE: INPUT_MOVE, - INPUT_END: INPUT_END, - INPUT_CANCEL: INPUT_CANCEL, + if (orientation == 'top') { + box.style.top = this.top + 'px'; + } else { + box.style.top = this.parent.height - this.top - this.height + 'px'; + } + }; - STATE_POSSIBLE: STATE_POSSIBLE, - STATE_BEGAN: STATE_BEGAN, - STATE_CHANGED: STATE_CHANGED, - STATE_ENDED: STATE_ENDED, - STATE_RECOGNIZED: STATE_RECOGNIZED, - STATE_CANCELLED: STATE_CANCELLED, - STATE_FAILED: STATE_FAILED, + /** + * 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.editable.updateTime && !this.dom.dragLeft) { + // create and show drag area + var dragLeft = document.createElement('div'); + dragLeft.className = 'vis-drag-left'; + dragLeft.dragLeftItem = this; - DIRECTION_NONE: DIRECTION_NONE, - DIRECTION_LEFT: DIRECTION_LEFT, - DIRECTION_RIGHT: DIRECTION_RIGHT, - DIRECTION_UP: DIRECTION_UP, - DIRECTION_DOWN: DIRECTION_DOWN, - DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL, - DIRECTION_VERTICAL: DIRECTION_VERTICAL, - DIRECTION_ALL: DIRECTION_ALL, + this.dom.box.appendChild(dragLeft); + this.dom.dragLeft = dragLeft; + } else if (!this.selected && this.dom.dragLeft) { + // delete drag area + if (this.dom.dragLeft.parentNode) { + this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft); + } + this.dom.dragLeft = null; + } + }; - Manager: Manager, - Input: Input, - TouchAction: TouchAction, + /** + * 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.editable.updateTime && !this.dom.dragRight) { + // create and show drag area + var dragRight = document.createElement('div'); + dragRight.className = 'vis-drag-right'; + dragRight.dragRightItem = this; - TouchInput: TouchInput, - MouseInput: MouseInput, - PointerEventInput: PointerEventInput, - TouchMouseInput: TouchMouseInput, - SingleTouchInput: SingleTouchInput, + this.dom.box.appendChild(dragRight); + this.dom.dragRight = dragRight; + } else if (!this.selected && this.dom.dragRight) { + // delete drag area + if (this.dom.dragRight.parentNode) { + this.dom.dragRight.parentNode.removeChild(this.dom.dragRight); + } + this.dom.dragRight = null; + } + }; - Recognizer: Recognizer, - AttrRecognizer: AttrRecognizer, - Tap: TapRecognizer, - Pan: PanRecognizer, - Swipe: SwipeRecognizer, - Pinch: PinchRecognizer, - Rotate: RotateRecognizer, - Press: PressRecognizer, + module.exports = RangeItem; - on: addEventListeners, - off: removeEventListeners, - each: each, - merge: merge, - extend: extend, - inherit: inherit, - bindFn: bindFn, - prefixed: prefixed - }); +/***/ }, +/* 25 */ +/***/ function(module, exports, __webpack_require__) { - if ("function" == TYPE_FUNCTION && __webpack_require__(16)) { - !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { - return Hammer; - }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else if (typeof module != 'undefined' && module.exports) { - module.exports = Hammer; - } else { - window[exportName] = Hammer; + /** + * Prototype for visual components + * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body] + * @param {Object} [options] + */ + "use strict"; + + function Component(body, options) { + this.options = null; + this.props = null; } - })(window, document, 'Hammer'); + /** + * 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; + }; -/***/ }, -/* 16 */ -/***/ function(module, exports, __webpack_require__) { + /** + * Destroy the component. Cleanup DOM and event listeners + */ + Component.prototype.destroy = function () {}; - /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__; + /** + * 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; - /* WEBPACK VAR INJECTION */}.call(exports, {})) + this.props._previousWidth = this.props.width; + this.props._previousHeight = this.props.height; -/***/ }, -/* 17 */ -/***/ function(module, exports, __webpack_require__) { + return resized; + }; - // first check if moment.js is already loaded in the browser window, if so, - // use this instance. Else, load via commonjs. - 'use strict'; + module.exports = Component; - module.exports = typeof window !== 'undefined' && window['moment'] || __webpack_require__(18); + // should be implemented by the component /***/ }, -/* 18 */ +/* 26 */ /***/ function(module, exports, __webpack_require__) { - /* WEBPACK VAR INJECTION */(function(module) {//! moment.js - //! version : 2.10.3 - //! authors : Tim Wood, Iskren Chernev, Moment.js contributors - //! license : MIT - //! momentjs.com + 'use strict'; - (function (global, factory) { - true ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - global.moment = factory() - }(this, function () { 'use strict'; + var util = __webpack_require__(2); + var Component = __webpack_require__(25); + var moment = __webpack_require__(40); + var locales = __webpack_require__(50); - var hookCallback; + /** + * 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; - function utils_hooks__hooks () { - return hookCallback.apply(null, arguments); - } + // default options + this.defaultOptions = { + showCurrentTime: true, - // This is done to register the method called with moment() - // without creating circular dependencies. - function setHookCallback (callback) { - hookCallback = callback; - } + locales: locales, + locale: 'en' + }; + this.options = util.extend({}, this.defaultOptions); + this.offset = 0; - function isArray(input) { - return Object.prototype.toString.call(input) === '[object Array]'; - } + this._create(); - function isDate(input) { - return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; - } + this.setOptions(options); + } - function map(arr, fn) { - var res = [], i; - for (i = 0; i < arr.length; ++i) { - res.push(fn(arr[i], i)); - } - return res; - } + CurrentTime.prototype = new Component(); - function hasOwnProp(a, b) { - return Object.prototype.hasOwnProperty.call(a, b); - } + /** + * 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%'; - function extend(a, b) { - for (var i in b) { - if (hasOwnProp(b, i)) { - a[i] = b[i]; - } - } + this.bar = bar; + }; - if (hasOwnProp(b, 'toString')) { - a.toString = b.toString; - } + /** + * Destroy the CurrentTime bar + */ + CurrentTime.prototype.destroy = function () { + this.options.showCurrentTime = false; + this.redraw(); // will remove the bar from the DOM and stop refreshing - if (hasOwnProp(b, 'valueOf')) { - a.valueOf = b.valueOf; - } + this.body = null; + }; - return a; - } + /** + * 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(['showCurrentTime', 'locale', 'locales'], this.options, options); + } + }; - function create_utc__createUTC (input, format, locale, strict) { - return createLocalOrUTC(input, format, locale, strict, true).utc(); + /** + * 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(); } - function defaultParsingFlags() { - // We need to deep clone this object. - return { - empty : false, - unusedTokens : [], - unusedInput : [], - overflow : -2, - charsLeftOver : 0, - nullInput : false, - invalidMonth : null, - invalidFormat : false, - userInvalidated : false, - iso : false - }; + var now = new Date(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.html#Localization'); + this.warned = true; + } + locale = this.options.locales['en']; // fall back on english when not available } + var title = locale.current + ' ' + locale.time + ': ' + moment(now).format('dddd, MMMM Do YYYY, H:mm:ss'); + title = title.charAt(0).toUpperCase() + title.substring(1); - function getParsingFlags(m) { - if (m._pf == null) { - m._pf = defaultParsingFlags(); - } - return m._pf; + 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(); + } - function valid__isValid(m) { - if (m._isValid == null) { - var flags = getParsingFlags(m); - m._isValid = !isNaN(m._d.getTime()) && - flags.overflow < 0 && - !flags.empty && - !flags.invalidMonth && - !flags.nullInput && - !flags.invalidFormat && - !flags.userInvalidated; + return false; + }; - if (m._strict) { - m._isValid = m._isValid && - flags.charsLeftOver === 0 && - flags.unusedTokens.length === 0 && - flags.bigHour === undefined; - } - } - return m._isValid; - } + /** + * Start auto refreshing the current time bar + */ + CurrentTime.prototype.start = function () { + var me = this; - function valid__createInvalid (flags) { - var m = create_utc__createUTC(NaN); - if (flags != null) { - extend(getParsingFlags(m), flags); - } - else { - getParsingFlags(m).userInvalidated = true; - } + function update() { + me.stop(); - return m; - } + // 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; - var momentProperties = utils_hooks__hooks.momentProperties = []; + me.redraw(); - function copyConfig(to, from) { - var i, prop, val; + // start a renderTimer to adjust for the new time + me.currentTimeTimer = setTimeout(update, interval); + } - if (typeof from._isAMomentObject !== 'undefined') { - to._isAMomentObject = from._isAMomentObject; - } - if (typeof from._i !== 'undefined') { - to._i = from._i; - } - if (typeof from._f !== 'undefined') { - to._f = from._f; - } - if (typeof from._l !== 'undefined') { - to._l = from._l; - } - if (typeof from._strict !== 'undefined') { - to._strict = from._strict; - } - if (typeof from._tzm !== 'undefined') { - to._tzm = from._tzm; - } - if (typeof from._isUTC !== 'undefined') { - to._isUTC = from._isUTC; - } - if (typeof from._offset !== 'undefined') { - to._offset = from._offset; - } - if (typeof from._pf !== 'undefined') { - to._pf = getParsingFlags(from); - } - if (typeof from._locale !== 'undefined') { - to._locale = from._locale; - } - - if (momentProperties.length > 0) { - for (i in momentProperties) { - prop = momentProperties[i]; - val = from[prop]; - if (typeof val !== 'undefined') { - to[prop] = val; - } - } - } - - return to; - } - - var updateInProgress = false; + update(); + }; - // Moment prototype object - function Moment(config) { - copyConfig(this, config); - this._d = new Date(+config._d); - // Prevent infinite loop in case updateOffset creates new moment - // objects. - if (updateInProgress === false) { - updateInProgress = true; - utils_hooks__hooks.updateOffset(this); - updateInProgress = false; - } - } + /** + * Stop auto refreshing the current time bar + */ + CurrentTime.prototype.stop = function () { + if (this.currentTimeTimer !== undefined) { + clearTimeout(this.currentTimeTimer); + delete this.currentTimeTimer; + } + }; - function isMoment (obj) { - return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); - } + /** + * 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(); + }; - function toInt(argumentForCoercion) { - var coercedNumber = +argumentForCoercion, - value = 0; + /** + * Get the current time. + * @return {Date} Returns the current time. + */ + CurrentTime.prototype.getCurrentTime = function () { + return new Date(new Date().valueOf() + this.offset); + }; - if (coercedNumber !== 0 && isFinite(coercedNumber)) { - if (coercedNumber >= 0) { - value = Math.floor(coercedNumber); - } else { - value = Math.ceil(coercedNumber); - } - } + module.exports = CurrentTime; - return value; - } +/***/ }, +/* 27 */ +/***/ function(module, exports, __webpack_require__) { - function compareArrays(array1, array2, dontConvert) { - var len = Math.min(array1.length, array2.length), - lengthDiff = Math.abs(array1.length - array2.length), - diffs = 0, - i; - for (i = 0; i < len; i++) { - if ((dontConvert && array1[i] !== array2[i]) || - (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { - diffs++; - } - } - return diffs + lengthDiff; - } + 'use strict'; - function Locale() { - } + var Hammer = __webpack_require__(41); + var util = __webpack_require__(2); + var Component = __webpack_require__(25); + var moment = __webpack_require__(40); + var locales = __webpack_require__(50); - var locales = {}; - var globalLocale; + /** + * 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 normalizeLocale(key) { - return key ? key.toLowerCase().replace('_', '-') : key; - } + function CustomTime(body, options) { + this.body = body; - // pick the locale from the array - // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each - // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root - function chooseLocale(names) { - var i = 0, j, next, locale, split; + // default options + this.defaultOptions = { + locales: locales, + locale: 'en', + id: undefined + }; + this.options = util.extend({}, this.defaultOptions); - while (i < names.length) { - split = normalizeLocale(names[i]).split('-'); - j = split.length; - next = normalizeLocale(names[i + 1]); - next = next ? next.split('-') : null; - while (j > 0) { - locale = loadLocale(split.slice(0, j).join('-')); - if (locale) { - return locale; - } - if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { - //the next array item is better than a shallower substring of this one - break; - } - j--; - } - i++; - } - return null; - } + if (options && options.time) { + this.customTime = options.time; + } else { + this.customTime = new Date(); + } - function loadLocale(name) { - var oldLocale = null; - // TODO: Find a better way to register and load all the locales in Node - if (!locales[name] && typeof module !== 'undefined' && - module && module.exports) { - try { - oldLocale = globalLocale._abbr; - !(function webpackMissingModule() { var e = new Error("Cannot find module \"./locale\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()); - // because defineLocale currently also sets the global locale, we - // want to undo that for lazy loaded locales - locale_locales__getSetGlobalLocale(oldLocale); - } catch (e) { } - } - return locales[name]; - } + this.eventParams = {}; // stores state parameters while dragging the bar - // This function will load locale and then set the global locale. If - // no arguments are passed in, it will simply return the current global - // locale key. - function locale_locales__getSetGlobalLocale (key, values) { - var data; - if (key) { - if (typeof values === 'undefined') { - data = locale_locales__getLocale(key); - } - else { - data = defineLocale(key, values); - } + this.setOptions(options); - if (data) { - // moment.duration._locale = moment._locale = data; - globalLocale = data; - } - } + // create the DOM + this._create(); + } - return globalLocale._abbr; - } + CustomTime.prototype = new Component(); - function defineLocale (name, values) { - if (values !== null) { - values.abbr = name; - if (!locales[name]) { - locales[name] = new Locale(); - } - locales[name].set(values); + /** + * 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(['locale', 'locales', 'id'], this.options, options); + } + }; - // backwards compat for now: also set the locale - locale_locales__getSetGlobalLocale(name); + /** + * 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; - return locales[name]; - } else { - // useful for testing - delete locales[name]; - return null; - } - } + 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'; + bar.appendChild(drag); - // returns locale data - function locale_locales__getLocale (key) { - var locale; + // 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)); + // TODO: cleanup + //this.hammer.on('pan', function (event) { + // event.preventDefault(); + //}); + }; - if (key && key._locale && key._locale._abbr) { - key = key._locale._abbr; - } + /** + * Destroy the CustomTime bar + */ + CustomTime.prototype.destroy = function () { + this.hide(); - if (!key) { - return globalLocale; - } + this.hammer.destroy(); + this.hammer = null; - if (!isArray(key)) { - //short-circuit everything else - locale = loadLocale(key); - if (locale) { - return locale; - } - key = [key]; - } + this.body = null; + }; - return chooseLocale(key); + /** + * 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 aliases = {}; + var x = this.body.util.toScreen(this.customTime); - function addUnitAlias (unit, shorthand) { - var lowerCase = unit.toLowerCase(); - aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; + 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.html#Localization'); + this.warned = true; } + locale = this.options.locales['en']; // fall back on english when not available + } + var title = locale.time + ': ' + moment(this.customTime).format('dddd, MMMM Do YYYY, H:mm:ss'); + title = title.charAt(0).toUpperCase() + title.substring(1); - function normalizeUnits(units) { - return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; - } + this.bar.style.left = x + 'px'; + this.bar.title = title; - function normalizeObjectUnits(inputObject) { - var normalizedInput = {}, - normalizedProp, - prop; + return false; + }; - for (prop in inputObject) { - if (hasOwnProp(inputObject, prop)) { - normalizedProp = normalizeUnits(prop); - if (normalizedProp) { - normalizedInput[normalizedProp] = inputObject[prop]; - } - } - } + /** + * 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); + } + }; - return normalizedInput; - } + /** + * Set custom time. + * @param {Date | number | string} time + */ + CustomTime.prototype.setCustomTime = function (time) { + this.customTime = util.convert(time, 'Date'); + this.redraw(); + }; - function makeGetSet (unit, keepTime) { - return function (value) { - if (value != null) { - get_set__set(this, unit, value); - utils_hooks__hooks.updateOffset(this, keepTime); - return this; - } else { - return get_set__get(this, unit); - } - }; - } + /** + * Retrieve the current custom time. + * @return {Date} customTime + */ + CustomTime.prototype.getCustomTime = function () { + return new Date(this.customTime.valueOf()); + }; - function get_set__get (mom, unit) { - return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); - } + /** + * Start moving horizontally + * @param {Event} event + * @private + */ + CustomTime.prototype._onDragStart = function (event) { + this.eventParams.dragging = true; + this.eventParams.customTime = this.customTime; - function get_set__set (mom, unit, value) { - return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); - } + event.stopPropagation(); + }; - // MOMENTS + /** + * Perform moving operating. + * @param {Event} event + * @private + */ + CustomTime.prototype._onDrag = function (event) { + if (!this.eventParams.dragging) return; - function getSet (units, value) { - var unit; - if (typeof units === 'object') { - for (unit in units) { - this.set(unit, units[unit]); - } - } else { - units = normalizeUnits(units); - if (typeof this[units] === 'function') { - return this[units](value); - } - } - return this; - } + var x = this.body.util.toScreen(this.eventParams.customTime) + event.deltaX; + var time = this.body.util.toTime(x); - function zeroFill(number, targetLength, forceSign) { - var output = '' + Math.abs(number), - sign = number >= 0; + this.setCustomTime(time); - while (output.length < targetLength) { - output = '0' + output; - } - return (sign ? (forceSign ? '+' : '') : '-') + output; - } + // fire a timechange event + this.body.emitter.emit('timechange', { + id: this.options.id, + time: new Date(this.customTime.valueOf()) + }); - var formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g; + event.stopPropagation(); + }; - var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; + /** + * Stop moving operating. + * @param {Event} event + * @private + */ + CustomTime.prototype._onDragEnd = function (event) { + if (!this.eventParams.dragging) return; - var formatFunctions = {}; + // fire a timechanged event + this.body.emitter.emit('timechanged', { + id: this.options.id, + time: new Date(this.customTime.valueOf()) + }); - var formatTokenFunctions = {}; + event.stopPropagation(); + }; - // token: 'M' - // padded: ['MM', 2] - // ordinal: 'Mo' - // callback: function () { this.month() + 1 } - function addFormatToken (token, padded, ordinal, callback) { - var func = callback; - if (typeof callback === 'string') { - func = function () { - return this[callback](); - }; - } - if (token) { - formatTokenFunctions[token] = func; - } - if (padded) { - formatTokenFunctions[padded[0]] = function () { - return zeroFill(func.apply(this, arguments), padded[1], padded[2]); - }; - } - if (ordinal) { - formatTokenFunctions[ordinal] = function () { - return this.localeData().ordinal(func.apply(this, arguments), token); - }; - } + /** + * 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; + } - function removeFormattingTokens(input) { - if (input.match(/\[[\s\S]/)) { - return input.replace(/^\[|\]$/g, ''); - } - return input.replace(/\\/g, ''); - } + return null; + }; - function makeFormatFunction(format) { - var array = format.match(formattingTokens), i, length; + module.exports = CustomTime; - for (i = 0, length = array.length; i < length; i++) { - if (formatTokenFunctions[array[i]]) { - array[i] = formatTokenFunctions[array[i]]; - } else { - array[i] = removeFormattingTokens(array[i]); - } - } +/***/ }, +/* 28 */ +/***/ function(module, exports, __webpack_require__) { - return function (mom) { - var output = ''; - for (i = 0; i < length; i++) { - output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; - } - return output; - }; - } + 'use strict'; - // format date using native date object - function formatMoment(m, format) { - if (!m.isValid()) { - return m.localeData().invalidDate(); - } - - format = expandFormat(format, m.localeData()); + var util = __webpack_require__(2); + var DOMutil = __webpack_require__(3); + var Component = __webpack_require__(25); + var DataStep = __webpack_require__(17); - if (!formatFunctions[format]) { - formatFunctions[format] = makeFormatFunction(format); - } + /** + * A horizontal time axis + * @param {Object} [options] See DataAxis.setOptions for the available + * options. + * @constructor DataAxis + * @extends Component + * @param body + */ + function DataAxis(body, options, svg, linegraphOptions) { + this.id = util.randomUUID(); + this.body = body; - return formatFunctions[format](m); + this.defaultOptions = { + orientation: 'left', // supported: 'left', 'right' + showMinorLabels: true, + showMajorLabels: true, + icons: true, + majorLinesOffset: 7, + minorLinesOffset: 4, + labelOffsetX: 10, + labelOffsetY: 2, + iconWidth: 20, + width: '40px', + visible: true, + alignZeros: true, + left: { + range: { min: undefined, max: undefined }, + format: function format(value) { + return value; + }, + title: { text: undefined, style: undefined } + }, + right: { + range: { min: undefined, max: undefined }, + format: function format(value) { + return value; + }, + title: { text: undefined, style: undefined } } + }; - function expandFormat(format, locale) { - var i = 5; - - function replaceLongDateFormatTokens(input) { - return locale.longDateFormat(input) || input; - } - - localFormattingTokens.lastIndex = 0; - while (i >= 0 && localFormattingTokens.test(format)) { - format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); - localFormattingTokens.lastIndex = 0; - i -= 1; - } - - return format; - } + this.linegraphOptions = linegraphOptions; + this.linegraphSVG = svg; + this.props = {}; + this.DOMelements = { // dynamic elements + lines: {}, + labels: {}, + title: {} + }; - var match1 = /\d/; // 0 - 9 - var match2 = /\d\d/; // 00 - 99 - var match3 = /\d{3}/; // 000 - 999 - var match4 = /\d{4}/; // 0000 - 9999 - var match6 = /[+-]?\d{6}/; // -999999 - 999999 - var match1to2 = /\d\d?/; // 0 - 99 - var match1to3 = /\d{1,3}/; // 0 - 999 - var match1to4 = /\d{1,4}/; // 0 - 9999 - var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 + this.dom = {}; - var matchUnsigned = /\d+/; // 0 - inf - var matchSigned = /[+-]?\d+/; // -inf - inf + this.range = { start: 0, end: 0 }; - var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z + this.options = util.extend({}, this.defaultOptions); + this.conversionFactor = 1; - var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 + this.setOptions(options); + this.width = Number(('' + this.options.width).replace('px', '')); + this.minWidth = this.width; + this.height = this.linegraphSVG.offsetHeight; + this.hidden = false; - // any word (or two) characters or numbers including two/three word month in arabic. - var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i; + this.stepPixels = 25; + this.zeroCrossing = -1; + this.amountOfSteps = -1; - var regexes = {}; + this.lineOffset = 0; + this.master = true; + this.svgElements = {}; + this.iconsRemoved = false; - function addRegexToken (token, regex, strictRegex) { - regexes[token] = typeof regex === 'function' ? regex : function (isStrict) { - return (isStrict && strictRegex) ? strictRegex : regex; - }; - } + this.groups = {}; + this.amountOfGroups = 0; - function getParseRegexForToken (token, config) { - if (!hasOwnProp(regexes, token)) { - return new RegExp(unescapeFormat(token)); - } + // create the HTML DOM + this._create(); - return regexes[token](config._strict, config._locale); - } + var me = this; + this.body.emitter.on('verticalDrag', function () { + me.dom.lineContainer.style.top = me.body.domProps.scrollTop + 'px'; + }); + } - // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript - function unescapeFormat(s) { - return s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { - return p1 || p2 || p3 || p4; - }).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); - } + DataAxis.prototype = new Component(); - var tokens = {}; + DataAxis.prototype.addGroup = function (label, graphOptions) { + if (!this.groups.hasOwnProperty(label)) { + this.groups[label] = graphOptions; + } + this.amountOfGroups += 1; + }; - function addParseToken (token, callback) { - var i, func = callback; - if (typeof token === 'string') { - token = [token]; - } - if (typeof callback === 'number') { - func = function (input, array) { - array[callback] = toInt(input); - }; - } - for (i = 0; i < token.length; i++) { - tokens[token[i]] = func; - } - } + DataAxis.prototype.updateGroup = function (label, graphOptions) { + this.groups[label] = graphOptions; + }; - function addWeekParseToken (token, callback) { - addParseToken(token, function (input, array, config, token) { - config._w = config._w || {}; - callback(input, config._w, config, token); - }); - } + DataAxis.prototype.removeGroup = function (label) { + if (this.groups.hasOwnProperty(label)) { + delete this.groups[label]; + this.amountOfGroups -= 1; + } + }; - function addTimeToArrayFromToken(token, input, config) { - if (input != null && hasOwnProp(tokens, token)) { - tokens[token](input, config._a, config, token); - } + DataAxis.prototype.setOptions = function (options) { + if (options) { + var redraw = false; + if (this.options.orientation != options.orientation && options.orientation !== undefined) { + redraw = true; } + var fields = ['orientation', 'showMinorLabels', 'showMajorLabels', 'icons', 'majorLinesOffset', 'minorLinesOffset', 'labelOffsetX', 'labelOffsetY', 'iconWidth', 'width', 'visible', 'left', 'right', 'alignZeros']; + util.selectiveExtend(fields, this.options, options); - var YEAR = 0; - var MONTH = 1; - var DATE = 2; - var HOUR = 3; - var MINUTE = 4; - var SECOND = 5; - var MILLISECOND = 6; + this.minWidth = Number(('' + this.options.width).replace('px', '')); - function daysInMonth(year, month) { - return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); + if (redraw === true && this.dom.frame) { + this.hide(); + this.show(); } + } + }; - // FORMATTING - - addFormatToken('M', ['MM', 2], 'Mo', function () { - return this.month() + 1; - }); - - addFormatToken('MMM', 0, 0, function (format) { - return this.localeData().monthsShort(this, format); - }); - - addFormatToken('MMMM', 0, 0, function (format) { - return this.localeData().months(this, format); - }); - - // ALIASES - - addUnitAlias('month', 'M'); + /** + * Create the HTML DOM for the DataAxis + */ + DataAxis.prototype._create = function () { + this.dom.frame = document.createElement('div'); + this.dom.frame.style.width = this.options.width; + this.dom.frame.style.height = this.height; - // PARSING + this.dom.lineContainer = document.createElement('div'); + this.dom.lineContainer.style.width = '100%'; + this.dom.lineContainer.style.height = this.height; + this.dom.lineContainer.style.position = 'relative'; - addRegexToken('M', match1to2); - addRegexToken('MM', match1to2, match2); - addRegexToken('MMM', matchWord); - addRegexToken('MMMM', matchWord); + // create svg element for graph drawing. + this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + this.svg.style.position = 'absolute'; + this.svg.style.top = '0px'; + this.svg.style.height = '100%'; + this.svg.style.width = '100%'; + this.svg.style.display = 'block'; + this.dom.frame.appendChild(this.svg); + }; - addParseToken(['M', 'MM'], function (input, array) { - array[MONTH] = toInt(input) - 1; - }); + DataAxis.prototype._redrawGroupIcons = function () { + DOMutil.prepareElements(this.svgElements); - addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { - var month = config._locale.monthsParse(input, token, config._strict); - // if we didn't find a month name, mark the date as invalid. - if (month != null) { - array[MONTH] = month; - } else { - getParsingFlags(config).invalidMonth = input; - } - }); + var x; + var iconWidth = this.options.iconWidth; + var iconHeight = 15; + var iconOffset = 4; + var y = iconOffset + 0.5 * iconHeight; - // LOCALES + if (this.options.orientation === 'left') { + x = iconOffset; + } else { + x = this.width - iconWidth - iconOffset; + } - var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); - function localeMonths (m) { - return this._months[m.month()]; - } + var groupArray = Object.keys(this.groups); + groupArray.sort(function (a, b) { + return a < b ? -1 : 1; + }); - var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); - function localeMonthsShort (m) { - return this._monthsShort[m.month()]; + for (var i = 0; i < groupArray.length; i++) { + var groupId = groupArray[i]; + if (this.groups[groupId].visible === true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] === true)) { + this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight); + y += iconHeight + iconOffset; } + } - function localeMonthsParse (monthName, format, strict) { - var i, mom, regex; + DOMutil.cleanupElements(this.svgElements); + this.iconsRemoved = false; + }; - if (!this._monthsParse) { - this._monthsParse = []; - this._longMonthsParse = []; - this._shortMonthsParse = []; - } + DataAxis.prototype._cleanupIcons = function () { + if (this.iconsRemoved === false) { + DOMutil.prepareElements(this.svgElements); + DOMutil.cleanupElements(this.svgElements); + this.iconsRemoved = true; + } + }; - for (i = 0; i < 12; i++) { - // make the regex if we don't have it already - mom = create_utc__createUTC([2000, i]); - if (strict && !this._longMonthsParse[i]) { - this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); - this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); - } - if (!strict && !this._monthsParse[i]) { - regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); - this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); - } - // test the regex - if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { - return i; - } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { - return i; - } else if (!strict && this._monthsParse[i].test(monthName)) { - return i; - } - } + /** + * Create the HTML DOM for the DataAxis + */ + DataAxis.prototype.show = function () { + this.hidden = false; + if (!this.dom.frame.parentNode) { + if (this.options.orientation === 'left') { + this.body.dom.left.appendChild(this.dom.frame); + } else { + this.body.dom.right.appendChild(this.dom.frame); } + } - // MOMENTS + if (!this.dom.lineContainer.parentNode) { + this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer); + } + }; - function setMonth (mom, value) { - var dayOfMonth; + /** + * Create the HTML DOM for the DataAxis + */ + DataAxis.prototype.hide = function () { + this.hidden = true; + if (this.dom.frame.parentNode) { + this.dom.frame.parentNode.removeChild(this.dom.frame); + } - // TODO: Move this out of here! - if (typeof value === 'string') { - value = mom.localeData().monthsParse(value); - // TODO: Another silent failure? - if (typeof value !== 'number') { - return mom; - } - } + if (this.dom.lineContainer.parentNode) { + this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer); + } + }; - dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); - mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); - return mom; + /** + * Set a range (start and end) + * @param end + * @param start + * @param end + */ + DataAxis.prototype.setRange = function (start, end) { + if (this.master === false && this.options.alignZeros === true && this.zeroCrossing != -1) { + if (start > 0) { + start = 0; } + } + this.range.start = start; + this.range.end = end; + }; - function getSetMonth (value) { - if (value != null) { - setMonth(this, value); - utils_hooks__hooks.updateOffset(this, true); - return this; - } else { - return get_set__get(this, 'Month'); - } - } + /** + * Repaint the component + * @return {boolean} Returns true if the component is resized + */ + DataAxis.prototype.redraw = function () { + var resized = false; + var activeGroups = 0; - function getDaysInMonth () { - return daysInMonth(this.year(), this.month()); + // Make sure the line container adheres to the vertical scrolling. + this.dom.lineContainer.style.top = this.body.domProps.scrollTop + 'px'; + + for (var groupId in this.groups) { + if (this.groups.hasOwnProperty(groupId)) { + if (this.groups[groupId].visible === true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] === true)) { + activeGroups++; + } } + } + if (this.amountOfGroups === 0 || activeGroups === 0) { + this.hide(); + } else { + this.show(); + this.height = Number(this.linegraphSVG.style.height.replace('px', '')); - function checkOverflow (m) { - var overflow; - var a = m._a; + // svg offsetheight did not work in firefox and explorer... + this.dom.lineContainer.style.height = this.height + 'px'; + this.width = this.options.visible === true ? Number(('' + this.options.width).replace('px', '')) : 0; - if (a && getParsingFlags(m).overflow === -2) { - overflow = - a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : - a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : - a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : - a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : - a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : - a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : - -1; + var props = this.props; + var frame = this.dom.frame; - if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { - overflow = DATE; - } + // update classname + frame.className = 'vis-data-axis'; - getParsingFlags(m).overflow = overflow; - } + // calculate character width and height + this._calculateCharSize(); - return m; - } + var orientation = this.options.orientation; + var showMinorLabels = this.options.showMinorLabels; + var showMajorLabels = this.options.showMajorLabels; - function warn(msg) { - if (utils_hooks__hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { - console.warn('Deprecation warning: ' + msg); - } - } + // determine the width and height of the elements for the axis + props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0; + props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0; - function deprecate(msg, fn) { - var firstTime = true, - msgWithStack = msg + '\n' + (new Error()).stack; + props.minorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.minorLinesOffset; + props.minorLineHeight = 1; + props.majorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.majorLinesOffset; + props.majorLineHeight = 1; - return extend(function () { - if (firstTime) { - warn(msgWithStack); - firstTime = false; - } - return fn.apply(this, arguments); - }, fn); + // take frame offline while updating (is almost twice as fast) + if (orientation === 'left') { + frame.style.top = '0'; + frame.style.left = '0'; + frame.style.bottom = ''; + frame.style.width = this.width + 'px'; + frame.style.height = this.height + 'px'; + this.props.width = this.body.domProps.left.width; + this.props.height = this.body.domProps.left.height; + } else { + // right + frame.style.top = ''; + frame.style.bottom = '0'; + frame.style.left = '0'; + frame.style.width = this.width + 'px'; + frame.style.height = this.height + 'px'; + this.props.width = this.body.domProps.right.width; + this.props.height = this.body.domProps.right.height; } - var deprecations = {}; + resized = this._redrawLabels(); + resized = this._isResized() || resized; - function deprecateSimple(name, msg) { - if (!deprecations[name]) { - warn(msg); - deprecations[name] = true; - } + if (this.options.icons === true) { + this._redrawGroupIcons(); + } else { + this._cleanupIcons(); } - utils_hooks__hooks.suppressDeprecationWarnings = false; - - var from_string__isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; + this._redrawTitle(orientation); + } + return resized; + }; - var isoDates = [ - ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], - ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], - ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], - ['GGGG-[W]WW', /\d{4}-W\d{2}/], - ['YYYY-DDD', /\d{4}-\d{3}/] - ]; + /** + * Repaint major and minor text labels and vertical grid lines + * @private + */ + DataAxis.prototype._redrawLabels = function () { + var resized = false; + DOMutil.prepareElements(this.DOMelements.lines); + DOMutil.prepareElements(this.DOMelements.labels); + var orientation = this.options['orientation']; - // iso time formats and regexes - var isoTimes = [ - ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], - ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], - ['HH:mm', /(T| )\d\d:\d\d/], - ['HH', /(T| )\d\d/] - ]; - - var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; - - // date from iso format - function configFromISO(config) { - var i, l, - string = config._i, - match = from_string__isoRegex.exec(string); - - if (match) { - getParsingFlags(config).iso = true; - for (i = 0, l = isoDates.length; i < l; i++) { - if (isoDates[i][1].exec(string)) { - // match[5] should be 'T' or undefined - config._f = isoDates[i][0] + (match[6] || ' '); - break; - } - } - for (i = 0, l = isoTimes.length; i < l; i++) { - if (isoTimes[i][1].exec(string)) { - config._f += isoTimes[i][0]; - break; - } - } - if (string.match(matchOffset)) { - config._f += 'Z'; - } - configFromStringAndFormat(config); - } else { - config._isValid = false; - } + // get the range for the slaved axis + var step; + if (this.master === false) { + var stepSize, rangeStart, rangeEnd, minimumStep; + if (this.zeroCrossing !== -1 && this.options.alignZeros === true) { + if (this.range.end > 0) { + stepSize = this.range.end / this.zeroCrossing; // size of one step + rangeStart = this.range.end - this.amountOfSteps * stepSize; + rangeEnd = this.range.end; + } else { + // all of the range (including start) has to be done before the zero crossing. + stepSize = -1 * this.range.start / (this.amountOfSteps - this.zeroCrossing); // absolute size of a step + rangeStart = this.range.start; + rangeEnd = this.range.start + stepSize * this.amountOfSteps; + } + } else { + rangeStart = this.range.start; + rangeEnd = this.range.end; } + minimumStep = this.stepPixels; + } else { + // calculate range and step (step such that we have space for 7 characters per label) + minimumStep = this.props.majorCharHeight; + rangeStart = this.range.start; + rangeEnd = this.range.end; + } - // date from iso format or fallback - function configFromString(config) { - var matched = aspNetJsonRegex.exec(config._i); - - if (matched !== null) { - config._d = new Date(+matched[1]); - return; - } + this.step = step = new DataStep(rangeStart, rangeEnd, minimumStep, this.dom.frame.offsetHeight, this.options[this.options.orientation].range, this.options[this.options.orientation].format, this.master === false && this.options.alignZeros // does the step have to align zeros? only if not master and the options is on + ); - configFromISO(config); - if (config._isValid === false) { - delete config._isValid; - utils_hooks__hooks.createFromInputFallback(config); - } + // the slave axis needs to use the same horizontal lines as the master axis. + if (this.master === true) { + this.stepPixels = this.dom.frame.offsetHeight / step.marginRange * step.step; + this.amountOfSteps = Math.ceil(this.dom.frame.offsetHeight / this.stepPixels); + } else { + // align with zero + if (this.options.alignZeros === true && this.zeroCrossing !== -1) { + // distance is the amount of steps away from the zero crossing we are. + var distance = (step.current - this.zeroCrossing * step.step) / step.step; + this.step.shift(distance); } + } - utils_hooks__hooks.createFromInputFallback = deprecate( - 'moment construction falls back to js Date. This is ' + - 'discouraged and will be removed in upcoming major ' + - 'release. Please refer to ' + - 'https://github.com/moment/moment/issues/1407 for more info.', - function (config) { - config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); - } - ); + // value at the bottom of the SVG + this.valueAtBottom = step.marginEnd; - function createDate (y, m, d, h, M, s, ms) { - //can't just apply() to create a date: - //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply - var date = new Date(y, m, d, h, M, s, ms); + this.maxLabelSize = 0; + var y = 0; // init value + var stepIndex = 0; // init value + var isMajor = false; // init value + while (stepIndex < this.amountOfSteps) { + y = Math.round(stepIndex * this.stepPixels); + isMajor = step.isMajor(); - //the date constructor doesn't accept years < 1970 - if (y < 1970) { - date.setFullYear(y); - } - return date; - } + if (stepIndex > 0 && stepIndex !== this.amountOfSteps) { + if (this.options['showMinorLabels'] && isMajor === false || this.master === false && this.options['showMinorLabels'] === true) { + this._redrawLabel(y - 2, step.getCurrent(), orientation, 'vis-y-axis vis-minor', this.props.minorCharHeight); + } - function createUTCDate (y) { - var date = new Date(Date.UTC.apply(null, arguments)); - if (y < 1970) { - date.setUTCFullYear(y); + if (isMajor && this.options['showMajorLabels'] && this.master === true || this.options['showMinorLabels'] === false && this.master === false && isMajor === true) { + if (y >= 0) { + this._redrawLabel(y - 2, step.getCurrent(), orientation, 'vis-y-axis vis-major', this.props.majorCharHeight); } - return date; + this._redrawLine(y, orientation, 'vis-grid vis-horizontal vis-major', this.options.majorLinesOffset, this.props.majorLineWidth); + } else { + this._redrawLine(y, orientation, 'vis-grid vis-horizontal vis-minor', this.options.minorLinesOffset, this.props.minorLineWidth); + } } - addFormatToken(0, ['YY', 2], 0, function () { - return this.year() % 100; - }); + // get zero crossing + if (this.master === true && step.current === 0) { + this.zeroCrossing = stepIndex; + } - addFormatToken(0, ['YYYY', 4], 0, 'year'); - addFormatToken(0, ['YYYYY', 5], 0, 'year'); - addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); + step.next(); + stepIndex += 1; + } - // ALIASES + // get zero crossing if it's the last step + if (this.master === true && step.current === 0) { + this.zeroCrossing = stepIndex; + } - addUnitAlias('year', 'y'); + this.conversionFactor = this.stepPixels / step.step; - // PARSING + // Note that title is rotated, so we're using the height, not width! + var titleWidth = 0; + if (this.options[orientation].title !== undefined && this.options[orientation].title.text !== undefined) { + titleWidth = this.props.titleCharHeight; + } + var offset = this.options.icons === true ? Math.max(this.options.iconWidth, titleWidth) + this.options.labelOffsetX + 15 : titleWidth + this.options.labelOffsetX + 15; - addRegexToken('Y', matchSigned); - addRegexToken('YY', match1to2, match2); - addRegexToken('YYYY', match1to4, match4); - addRegexToken('YYYYY', match1to6, match6); - addRegexToken('YYYYYY', match1to6, match6); + // this will resize the yAxis to accommodate the labels. + if (this.maxLabelSize > this.width - offset && this.options.visible === true) { + this.width = this.maxLabelSize + offset; + this.options.width = this.width + 'px'; + DOMutil.cleanupElements(this.DOMelements.lines); + DOMutil.cleanupElements(this.DOMelements.labels); + this.redraw(); + resized = true; + } + // this will resize the yAxis if it is too big for the labels. + else if (this.maxLabelSize < this.width - offset && this.options.visible === true && this.width > this.minWidth) { + this.width = Math.max(this.minWidth, this.maxLabelSize + offset); + this.options.width = this.width + 'px'; + DOMutil.cleanupElements(this.DOMelements.lines); + DOMutil.cleanupElements(this.DOMelements.labels); + this.redraw(); + resized = true; + } else { + DOMutil.cleanupElements(this.DOMelements.lines); + DOMutil.cleanupElements(this.DOMelements.labels); + resized = false; + } - addParseToken(['YYYY', 'YYYYY', 'YYYYYY'], YEAR); - addParseToken('YY', function (input, array) { - array[YEAR] = utils_hooks__hooks.parseTwoDigitYear(input); - }); + return resized; + }; - // HELPERS + DataAxis.prototype.convertValue = function (value) { + var invertedValue = this.valueAtBottom - value; + var convertedValue = invertedValue * this.conversionFactor; + return convertedValue; + }; - function daysInYear(year) { - return isLeapYear(year) ? 366 : 365; - } + DataAxis.prototype.screenToValue = function (x) { + return this.valueAtBottom - x / this.conversionFactor; + }; - function isLeapYear(year) { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; - } + /** + * Create a label for the axis at position x + * @private + * @param y + * @param text + * @param orientation + * @param className + * @param characterHeight + */ + DataAxis.prototype._redrawLabel = function (y, text, orientation, className, characterHeight) { + // reuse redundant label + var label = DOMutil.getDOMElement('div', this.DOMelements.labels, this.dom.frame); //this.dom.redundant.labels.shift(); + label.className = className; + label.innerHTML = text; + if (orientation === 'left') { + label.style.left = '-' + this.options.labelOffsetX + 'px'; + label.style.textAlign = 'right'; + } else { + label.style.right = '-' + this.options.labelOffsetX + 'px'; + label.style.textAlign = 'left'; + } - // HOOKS + label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px'; - utils_hooks__hooks.parseTwoDigitYear = function (input) { - return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); - }; + text += ''; - // MOMENTS + var largestWidth = Math.max(this.props.majorCharWidth, this.props.minorCharWidth); + if (this.maxLabelSize < text.length * largestWidth) { + this.maxLabelSize = text.length * largestWidth; + } + }; - var getSetYear = makeGetSet('FullYear', false); + /** + * Create a minor line for the axis at position y + * @param y + * @param orientation + * @param className + * @param offset + * @param width + */ + DataAxis.prototype._redrawLine = function (y, orientation, className, offset, width) { + if (this.master === true) { + var line = DOMutil.getDOMElement('div', this.DOMelements.lines, this.dom.lineContainer); //this.dom.redundant.lines.shift(); + line.className = className; + line.innerHTML = ''; - function getIsLeapYear () { - return isLeapYear(this.year()); + if (orientation === 'left') { + line.style.left = this.width - offset + 'px'; + } else { + line.style.right = this.width - offset + 'px'; } - addFormatToken('w', ['ww', 2], 'wo', 'week'); - addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); - - // ALIASES - - addUnitAlias('week', 'w'); - addUnitAlias('isoWeek', 'W'); - - // PARSING - - addRegexToken('w', match1to2); - addRegexToken('ww', match1to2, match2); - addRegexToken('W', match1to2); - addRegexToken('WW', match1to2, match2); - - addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { - week[token.substr(0, 1)] = toInt(input); - }); - - // HELPERS - - // firstDayOfWeek 0 = sun, 6 = sat - // the day of the week that starts the week - // (usually sunday or monday) - // firstDayOfWeekOfYear 0 = sun, 6 = sat - // the first week is the week that contains the first - // of this day of the week - // (eg. ISO weeks use thursday (4)) - function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { - var end = firstDayOfWeekOfYear - firstDayOfWeek, - daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), - adjustedMoment; + line.style.width = width + 'px'; + line.style.top = y + 'px'; + } + }; + /** + * Create a title for the axis + * @private + * @param orientation + */ + DataAxis.prototype._redrawTitle = function (orientation) { + DOMutil.prepareElements(this.DOMelements.title); - if (daysToDayOfWeek > end) { - daysToDayOfWeek -= 7; - } + // Check if the title is defined for this axes + if (this.options[orientation].title !== undefined && this.options[orientation].title.text !== undefined) { + var title = DOMutil.getDOMElement('div', this.DOMelements.title, this.dom.frame); + title.className = 'vis-y-axis vis-title vis-' + orientation; + title.innerHTML = this.options[orientation].title.text; - if (daysToDayOfWeek < end - 7) { - daysToDayOfWeek += 7; - } + // Add style - if provided + if (this.options[orientation].title.style !== undefined) { + util.addCssText(title, this.options[orientation].title.style); + } - adjustedMoment = local__createLocal(mom).add(daysToDayOfWeek, 'd'); - return { - week: Math.ceil(adjustedMoment.dayOfYear() / 7), - year: adjustedMoment.year() - }; + if (orientation === 'left') { + title.style.left = this.props.titleCharHeight + 'px'; + } else { + title.style.right = this.props.titleCharHeight + 'px'; } - // LOCALES + title.style.width = this.height + 'px'; + } - function localeWeek (mom) { - return weekOfYear(mom, this._week.dow, this._week.doy).week; - } + // we need to clean up in case we did not use all elements. + DOMutil.cleanupElements(this.DOMelements.title); + }; - var defaultLocaleWeek = { - dow : 0, // Sunday is the first day of the week. - doy : 6 // The week that contains Jan 1st is the first week of the year. - }; + /** + * 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 + */ + DataAxis.prototype._calculateCharSize = function () { + // determine the char width and height on the minor axis + if (!('minorCharHeight' in this.props)) { + var textMinor = document.createTextNode('0'); + var measureCharMinor = document.createElement('div'); + measureCharMinor.className = 'vis-y-axis vis-minor vis-measure'; + measureCharMinor.appendChild(textMinor); + this.dom.frame.appendChild(measureCharMinor); - function localeFirstDayOfWeek () { - return this._week.dow; - } + this.props.minorCharHeight = measureCharMinor.clientHeight; + this.props.minorCharWidth = measureCharMinor.clientWidth; - function localeFirstDayOfYear () { - return this._week.doy; - } + this.dom.frame.removeChild(measureCharMinor); + } - // MOMENTS + if (!('majorCharHeight' in this.props)) { + var textMajor = document.createTextNode('0'); + var measureCharMajor = document.createElement('div'); + measureCharMajor.className = 'vis-y-axis vis-major vis-measure'; + measureCharMajor.appendChild(textMajor); + this.dom.frame.appendChild(measureCharMajor); - function getSetWeek (input) { - var week = this.localeData().week(this); - return input == null ? week : this.add((input - week) * 7, 'd'); - } + this.props.majorCharHeight = measureCharMajor.clientHeight; + this.props.majorCharWidth = measureCharMajor.clientWidth; - function getSetISOWeek (input) { - var week = weekOfYear(this, 1, 4).week; - return input == null ? week : this.add((input - week) * 7, 'd'); - } + this.dom.frame.removeChild(measureCharMajor); + } - addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); + if (!('titleCharHeight' in this.props)) { + var textTitle = document.createTextNode('0'); + var measureCharTitle = document.createElement('div'); + measureCharTitle.className = 'vis-y-axis vis-title vis-measure'; + measureCharTitle.appendChild(textTitle); + this.dom.frame.appendChild(measureCharTitle); - // ALIASES + this.props.titleCharHeight = measureCharTitle.clientHeight; + this.props.titleCharWidth = measureCharTitle.clientWidth; - addUnitAlias('dayOfYear', 'DDD'); + this.dom.frame.removeChild(measureCharTitle); + } + }; - // PARSING + module.exports = DataAxis; - addRegexToken('DDD', match1to3); - addRegexToken('DDDD', match3); - addParseToken(['DDD', 'DDDD'], function (input, array, config) { - config._dayOfYear = toInt(input); - }); +/***/ }, +/* 29 */ +/***/ function(module, exports, __webpack_require__) { - // HELPERS + 'use strict'; - //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday - function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { - var d = createUTCDate(year, 0, 1).getUTCDay(); - var daysToAdd; - var dayOfYear; + var util = __webpack_require__(2); + var DOMutil = __webpack_require__(3); + var Line = __webpack_require__(51); + var Bar = __webpack_require__(52); + var Points = __webpack_require__(53); - d = d === 0 ? 7 : d; - weekday = weekday != null ? weekday : firstDayOfWeek; - daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); - dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; + /** + * /** + * @param {object} group | the object of the group from the dataset + * @param {string} groupId | ID of the group + * @param {object} options | the default options + * @param {array} groupsUsingDefaultStyles | this array has one entree. + * It is passed as an array so it is passed by reference. + * It enumerates through the default styles + * @constructor + */ + function GraphGroup(group, groupId, options, groupsUsingDefaultStyles) { + this.id = groupId; + var fields = ['sampling', 'style', 'sort', 'yAxisOrientation', 'barChart', 'drawPoints', 'shaded', 'interpolation']; + this.options = util.selectiveBridgeObject(fields, options); + this.usingDefaultStyle = group.className === undefined; + this.groupsUsingDefaultStyles = groupsUsingDefaultStyles; + this.zeroPosition = 0; + this.update(group); + if (this.usingDefaultStyle == true) { + this.groupsUsingDefaultStyles[0] += 1; + } + this.itemsData = []; + this.visible = group.visible === undefined ? true : group.visible; + } - return { - year : dayOfYear > 0 ? year : year - 1, - dayOfYear : dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear - }; + /** + * this loads a reference to all items in this group into this group. + * @param {array} items + */ + GraphGroup.prototype.setItems = function (items) { + if (items != null) { + this.itemsData = items; + if (this.options.sort == true) { + this.itemsData.sort(function (a, b) { + return a.x - b.x; + }); } + } else { + this.itemsData = []; + } + }; - // MOMENTS + /** + * this is used for plotting barcharts, this way, we only have to calculate it once. + * @param pos + */ + GraphGroup.prototype.setZeroPosition = function (pos) { + this.zeroPosition = pos; + }; - function getSetDayOfYear (input) { - var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; - return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); - } + /** + * set the options of the graph group over the default options. + * @param options + */ + GraphGroup.prototype.setOptions = function (options) { + if (options !== undefined) { + var fields = ['sampling', 'style', 'sort', 'yAxisOrientation', 'barChart']; + util.selectiveDeepExtend(fields, this.options, options); - // Pick the first defined of two or three arguments. - function defaults(a, b, c) { - if (a != null) { - return a; - } - if (b != null) { - return b; - } - return c; - } + util.mergeOptions(this.options, options, 'interpolation'); + util.mergeOptions(this.options, options, 'drawPoints'); + util.mergeOptions(this.options, options, 'shaded'); - function currentDateArray(config) { - var now = new Date(); - if (config._useUTC) { - return [now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()]; + if (options.interpolation) { + if (typeof options.interpolation == 'object') { + if (options.interpolation.parametrization) { + if (options.interpolation.parametrization == 'uniform') { + this.options.interpolation.alpha = 0; + } else if (options.interpolation.parametrization == 'chordal') { + this.options.interpolation.alpha = 1; + } else { + this.options.interpolation.parametrization = 'centripetal'; + this.options.interpolation.alpha = 0.5; + } } - return [now.getFullYear(), now.getMonth(), now.getDate()]; + } } + } - // convert an array to a date. - // the array should mirror the parameters below - // note: all values past the year are optional and will default to the lowest possible value. - // [year, month, day , hour, minute, second, millisecond] - function configFromArray (config) { - var i, date, input = [], currentDate, yearToUse; + if (this.options.style == 'line') { + this.type = new Line(this.id, this.options); + } else if (this.options.style == 'bar') { + this.type = new Bar(this.id, this.options); + } else if (this.options.style == 'points') { + this.type = new Points(this.id, this.options); + } + }; - if (config._d) { - return; - } + /** + * this updates the current group class with the latest group dataset entree, used in _updateGroup in linegraph + * @param group + */ + GraphGroup.prototype.update = function (group) { + this.group = group; + this.content = group.content || 'graph'; + this.className = group.className || this.className || 'vis-graph-group' + this.groupsUsingDefaultStyles[0] % 10; + this.visible = group.visible === undefined ? true : group.visible; + this.style = group.style; + this.setOptions(group.options); + }; - currentDate = currentDateArray(config); + /** + * draw the icon for the legend. + * + * @param x + * @param y + * @param JSONcontainer + * @param SVGcontainer + * @param iconWidth + * @param iconHeight + */ + GraphGroup.prototype.drawIcon = function (x, y, JSONcontainer, SVGcontainer, iconWidth, iconHeight) { + var fillHeight = iconHeight * 0.5; + var path, fillPath; - //compute day of the year from weeks and weekdays - if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { - dayOfYearFromWeekInfo(config); - } + var outline = DOMutil.getSVGElement('rect', JSONcontainer, SVGcontainer); + 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'); - //if the day of the year is set, figure out what it is - if (config._dayOfYear) { - yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); + if (this.options.style == 'line') { + path = DOMutil.getSVGElement('path', JSONcontainer, SVGcontainer); + path.setAttributeNS(null, 'class', this.className); + if (this.style !== undefined) { + path.setAttributeNS(null, 'style', this.style); + } - if (config._dayOfYear > daysInYear(yearToUse)) { - getParsingFlags(config)._overflowDayOfYear = true; - } + path.setAttributeNS(null, 'd', 'M' + x + ',' + y + ' L' + (x + iconWidth) + ',' + y + ''); + if (this.options.shaded.enabled == true) { + fillPath = DOMutil.getSVGElement('path', JSONcontainer, SVGcontainer); + if (this.options.shaded.orientation == 'top') { + fillPath.setAttributeNS(null, 'd', 'M' + x + ', ' + (y - fillHeight) + 'L' + x + ',' + y + ' L' + (x + iconWidth) + ',' + y + ' L' + (x + iconWidth) + ',' + (y - fillHeight)); + } else { + fillPath.setAttributeNS(null, 'd', 'M' + x + ',' + y + ' ' + 'L' + x + ',' + (y + fillHeight) + ' ' + 'L' + (x + iconWidth) + ',' + (y + fillHeight) + 'L' + (x + iconWidth) + ',' + y); + } + fillPath.setAttributeNS(null, 'class', this.className + ' vis-icon-fill'); + } - date = createUTCDate(yearToUse, 0, config._dayOfYear); - config._a[MONTH] = date.getUTCMonth(); - config._a[DATE] = date.getUTCDate(); - } + if (this.options.drawPoints.enabled == true) { + DOMutil.drawPoint(x + 0.5 * iconWidth, y, this, JSONcontainer, SVGcontainer); + } + } else { + var barWidth = Math.round(0.3 * iconWidth); + var bar1Height = Math.round(0.4 * iconHeight); + var bar2Height = Math.round(0.75 * iconHeight); - // Default to current date. - // * if no year, month, day of month are given, default to today - // * if day of month is given, default month and year - // * if month is given, default only year - // * if year is given, don't default anything - for (i = 0; i < 3 && config._a[i] == null; ++i) { - config._a[i] = input[i] = currentDate[i]; - } + var offset = Math.round((iconWidth - 2 * barWidth) / 3); - // Zero out whatever was not defaulted, including time - for (; i < 7; i++) { - config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; - } + DOMutil.drawBar(x + 0.5 * barWidth + offset, y + fillHeight - bar1Height - 1, barWidth, bar1Height, this.className + ' vis-bar', JSONcontainer, SVGcontainer, this.style); + DOMutil.drawBar(x + 1.5 * barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, this.className + ' vis-bar', JSONcontainer, SVGcontainer, this.style); + } + }; - // Check for 24:00:00.000 - if (config._a[HOUR] === 24 && - config._a[MINUTE] === 0 && - config._a[SECOND] === 0 && - config._a[MILLISECOND] === 0) { - config._nextDay = true; - config._a[HOUR] = 0; - } + /** + * return the legend entree for this group. + * + * @param iconWidth + * @param iconHeight + * @returns {{icon: HTMLElement, label: (group.content|*|string), orientation: (.options.yAxisOrientation|*)}} + */ + GraphGroup.prototype.getLegend = function (iconWidth, iconHeight) { + var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + this.drawIcon(0, 0.5 * iconHeight, [], svg, iconWidth, iconHeight); + return { icon: svg, label: this.content, orientation: this.options.yAxisOrientation }; + }; - config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); - // Apply timezone offset from input. The actual utcOffset can be changed - // with parseZone. - if (config._tzm != null) { - config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); - } + GraphGroup.prototype.getYRange = function (groupData) { + return this.type.getYRange(groupData); + }; - if (config._nextDay) { - config._a[HOUR] = 24; - } - } + GraphGroup.prototype.getData = function (groupData) { + return this.type.getData(groupData); + }; - function dayOfYearFromWeekInfo(config) { - var w, weekYear, week, weekday, dow, doy, temp; + GraphGroup.prototype.draw = function (dataset, group, framework) { + this.type.draw(dataset, group, framework); + }; - w = config._w; - if (w.GG != null || w.W != null || w.E != null) { - dow = 1; - doy = 4; + module.exports = GraphGroup; - // TODO: We need to take the current isoWeekYear, but that depends on - // how we interpret now (local, utc, fixed offset). So create - // a now version of current config (take local/utc/offset flags, and - // create now). - weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(local__createLocal(), 1, 4).year); - week = defaults(w.W, 1); - weekday = defaults(w.E, 1); - } else { - dow = config._locale._week.dow; - doy = config._locale._week.doy; +/***/ }, +/* 30 */ +/***/ function(module, exports, __webpack_require__) { - weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(local__createLocal(), dow, doy).year); - week = defaults(w.w, 1); + 'use strict'; - if (w.d != null) { - // weekday -- low day numbers are considered next week - weekday = w.d; - if (weekday < dow) { - ++week; - } - } else if (w.e != null) { - // local weekday -- counting starts from begining of week - weekday = w.e + dow; - } else { - // default to begining of week - weekday = dow; - } - } - temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); + var util = __webpack_require__(2); + var stack = __webpack_require__(19); + var RangeItem = __webpack_require__(24); - config._a[YEAR] = temp.year; - config._dayOfYear = temp.dayOfYear; + /** + * @constructor Group + * @param {Number | String} groupId + * @param {Object} data + * @param {ItemSet} itemSet + */ + function Group(groupId, data, itemSet) { + this.groupId = groupId; + this.subgroups = {}; + this.subgroupIndex = 0; + this.subgroupOrderer = data && data.subgroupOrder; + this.itemSet = itemSet; + + this.dom = {}; + this.props = { + label: { + width: 0, + height: 0 } + }; + this.className = null; - utils_hooks__hooks.ISO_8601 = function () {}; + this.items = {}; // items filtered by groupId of this group + this.visibleItems = []; // items currently visible in window + 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; + }); - // date from string and format string - function configFromStringAndFormat(config) { - // TODO: Move this to another part of the creation flow to prevent circular deps - if (config._f === utils_hooks__hooks.ISO_8601) { - configFromISO(config); - return; - } + this._create(); - config._a = []; - getParsingFlags(config).empty = true; + this.setData(data); + } - // This array is used to make a Date, either with `new Date` or `Date.UTC` - var string = '' + config._i, - i, parsedInput, tokens, token, skipped, - stringLength = string.length, - totalParsedInputLength = 0; + /** + * Create DOM elements for the group + * @private + */ + Group.prototype._create = function () { + var label = document.createElement('div'); + label.className = 'vis-label'; + this.dom.label = label; - tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; + var inner = document.createElement('div'); + inner.className = 'vis-inner'; + label.appendChild(inner); + this.dom.inner = inner; - for (i = 0; i < tokens.length; i++) { - token = tokens[i]; - parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; - if (parsedInput) { - skipped = string.substr(0, string.indexOf(parsedInput)); - if (skipped.length > 0) { - getParsingFlags(config).unusedInput.push(skipped); - } - string = string.slice(string.indexOf(parsedInput) + parsedInput.length); - totalParsedInputLength += parsedInput.length; - } - // don't parse if it's not a known token - if (formatTokenFunctions[token]) { - if (parsedInput) { - getParsingFlags(config).empty = false; - } - else { - getParsingFlags(config).unusedTokens.push(token); - } - addTimeToArrayFromToken(token, parsedInput, config); - } - else if (config._strict && !parsedInput) { - getParsingFlags(config).unusedTokens.push(token); - } - } + var foreground = document.createElement('div'); + foreground.className = 'vis-group'; + foreground['timeline-group'] = this; + this.dom.foreground = foreground; - // add remaining unparsed input length to the string - getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; - if (string.length > 0) { - getParsingFlags(config).unusedInput.push(string); - } + this.dom.background = document.createElement('div'); + this.dom.background.className = 'vis-group'; - // clear _12h flag if hour is <= 12 - if (getParsingFlags(config).bigHour === true && - config._a[HOUR] <= 12 && - config._a[HOUR] > 0) { - getParsingFlags(config).bigHour = undefined; - } - // handle meridiem - config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); + this.dom.axis = document.createElement('div'); + this.dom.axis.className = 'vis-group'; - configFromArray(config); - checkOverflow(config); - } + // 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.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 = data && data.content; + if (content instanceof Element) { + this.dom.inner.appendChild(content); + } else if (content !== undefined && content !== null) { + this.dom.inner.innerHTML = content; + } else { + this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null + } - function meridiemFixWrap (locale, hour, meridiem) { - var isPm; + // update title + this.dom.label.title = data && data.title || ''; - if (meridiem == null) { - // nothing to do - return hour; - } - if (locale.meridiemHour != null) { - return locale.meridiemHour(hour, meridiem); - } else if (locale.isPM != null) { - // Fallback - isPm = locale.isPM(meridiem); - if (isPm && hour < 12) { - hour += 12; - } - if (!isPm && hour === 12) { - hour = 0; - } - return hour; - } else { - // this is not supposed to happen - return hour; - } + if (!this.dom.inner.firstChild) { + util.addClassName(this.dom.inner, 'vis-hidden'); + } else { + util.removeClassName(this.dom.inner, 'vis-hidden'); + } + + // 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; + } - function configFromStringAndArray(config) { - var tempConfig, - bestMoment, + // update style + if (this.style) { + util.removeCssText(this.dom.label, 'vis-' + this.style); + this.style = null; + } + if (data && data.style) { + util.addCssText(this.dom.label, 'vis-' + data.style); + this.style = data.style; + } + }; - scoreToBeat, - i, - currentScore; + /** + * Get the width of the group label + * @return {number} width + */ + Group.prototype.getLabelWidth = function () { + return this.props.label.width; + }; - if (config._f.length === 0) { - getParsingFlags(config).invalidFormat = true; - config._d = new Date(NaN); - return; - } + /** + * Repaint this group + * @param {{start: number, end: number}} range + * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin + * @param {boolean} [restack=false] Force restacking of all items + * @return {boolean} Returns true if the group is resized + */ + Group.prototype.redraw = function (range, margin, restack) { + var resized = false; - for (i = 0; i < config._f.length; i++) { - currentScore = 0; - tempConfig = copyConfig({}, config); - if (config._useUTC != null) { - tempConfig._useUTC = config._useUTC; - } - tempConfig._f = config._f[i]; - configFromStringAndFormat(tempConfig); + // 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) + var markerHeight = this.dom.marker.clientHeight; + if (markerHeight != this.lastMarkerHeight) { + this.lastMarkerHeight = markerHeight; - if (!valid__isValid(tempConfig)) { - continue; - } + util.forEach(this.items, function (item) { + item.dirty = true; + if (item.displayed) item.redraw(); + }); - // if there is any input that was not parsed add a penalty for that format - currentScore += getParsingFlags(tempConfig).charsLeftOver; + restack = true; + } - //or tokens - currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; + // reposition visible items vertically + if (typeof this.itemSet.options.order === 'function') { + // a custom order function - getParsingFlags(tempConfig).score = currentScore; + if (restack) { + // brute force restack of all items - if (scoreToBeat == null || currentScore < scoreToBeat) { - scoreToBeat = currentScore; - bestMoment = tempConfig; - } + // show all items + var me = this; + var limitSize = false; + util.forEach(this.items, function (item) { + if (!item.displayed) { + item.redraw(); + me.visibleItems.push(item); } + item.repositionX(limitSize); + }); - extend(config, bestMoment || tempConfig); + // 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 */); } - function configFromObject(config) { - if (config._d) { - return; - } - - var i = normalizeObjectUnits(config._i); - config._a = [i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond]; + this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); + } else { + // no custom order function, lazy stacking + this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); - configFromArray(config); + if (this.itemSet.options.stack) { + // TODO: ugly way to access options... + stack.stack(this.visibleItems, margin, restack); + } else { + // no stacking + stack.nostack(this.visibleItems, margin, this.subgroups); } + } - function createFromConfig (config) { - var input = config._i, - format = config._f, - res; + // recalculate the height of the group + var height = this._calculateHeight(margin); - config._locale = config._locale || locale_locales__getLocale(config._l); + // calculate actual size and position + var foreground = this.dom.foreground; + this.top = foreground.offsetTop; + this.left = foreground.offsetLeft; + this.width = foreground.offsetWidth; + resized = util.updateProperty(this, 'height', height) || resized; - if (input === null || (format === undefined && input === '')) { - return valid__createInvalid({nullInput: true}); - } + // recalculate size of label + resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized; + resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized; - if (typeof input === 'string') { - config._i = input = config._locale.preparse(input); - } + // apply new height + this.dom.background.style.height = height + 'px'; + this.dom.foreground.style.height = height + 'px'; + this.dom.label.style.height = height + 'px'; - if (isMoment(input)) { - return new Moment(checkOverflow(input)); - } else if (isArray(format)) { - configFromStringAndArray(config); - } else if (format) { - configFromStringAndFormat(config); - } else if (isDate(input)) { - config._d = input; - } else { - configFromInput(config); - } + // 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); + } - res = new Moment(checkOverflow(config)); - if (res._nextDay) { - // Adding is smart enough around DST - res.add(1, 'd'); - res._nextDay = undefined; - } + return resized; + }; - return res; - } - - function configFromInput(config) { - var input = config._i; - if (input === undefined) { - config._d = new Date(); - } else if (isDate(input)) { - config._d = new Date(+input); - } else if (typeof input === 'string') { - configFromString(config); - } else if (isArray(input)) { - config._a = map(input.slice(0), function (obj) { - return parseInt(obj, 10); - }); - configFromArray(config); - } else if (typeof(input) === 'object') { - configFromObject(config); - } else if (typeof(input) === 'number') { - // from milliseconds - config._d = new Date(input); - } else { - utils_hooks__hooks.createFromInputFallback(config); - } + /** + * 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 visibleItems = this.visibleItems; + //var visibleSubgroups = []; + //this.visibleSubgroups = 0; + this.resetSubgroups(); + var me = this; + if (visibleItems.length > 0) { + var min = visibleItems[0].top; + var max = visibleItems[0].top + visibleItems[0].height; + util.forEach(visibleItems, function (item) { + min = Math.min(min, item.top); + max = Math.max(max, item.top + item.height); + if (item.data.subgroup !== undefined) { + me.subgroups[item.data.subgroup].height = Math.max(me.subgroups[item.data.subgroup].height, item.height); + me.subgroups[item.data.subgroup].visible = true; + } + }); + 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(visibleItems, function (item) { + item.top -= offset; + }); } + height = max + margin.item.vertical / 2; + } else { + height = 0; + } + height = Math.max(height, this.props.label.height); - function createLocalOrUTC (input, format, locale, strict, isUTC) { - var c = {}; + return height; + }; - if (typeof(locale) === 'boolean') { - strict = locale; - locale = undefined; - } - // object construction must be done this way. - // https://github.com/moment/moment/issues/1423 - c._isAMomentObject = true; - c._useUTC = c._isUTC = isUTC; - c._l = locale; - c._i = input; - c._f = format; - c._strict = strict; + /** + * Show this group: attach to the DOM + */ + Group.prototype.show = function () { + if (!this.dom.label.parentNode) { + this.itemSet.dom.labelSet.appendChild(this.dom.label); + } - return createFromConfig(c); - } + if (!this.dom.foreground.parentNode) { + this.itemSet.dom.foreground.appendChild(this.dom.foreground); + } - function local__createLocal (input, format, locale, strict) { - return createLocalOrUTC(input, format, locale, strict, false); - } + if (!this.dom.background.parentNode) { + this.itemSet.dom.background.appendChild(this.dom.background); + } - var prototypeMin = deprecate( - 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548', - function () { - var other = local__createLocal.apply(null, arguments); - return other < this ? this : other; - } - ); + if (!this.dom.axis.parentNode) { + this.itemSet.dom.axis.appendChild(this.dom.axis); + } + }; - var prototypeMax = deprecate( - 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548', - function () { - var other = local__createLocal.apply(null, arguments); - return other > this ? this : other; - } - ); + /** + * Hide this group: remove from the DOM + */ + Group.prototype.hide = function () { + var label = this.dom.label; + if (label.parentNode) { + label.parentNode.removeChild(label); + } - // Pick a moment m from moments so that m[fn](other) is true for all - // other. This relies on the function fn to be transitive. - // - // moments should either be an array of moment objects or an array, whose - // first element is an array of moment objects. - function pickBy(fn, moments) { - var res, i; - if (moments.length === 1 && isArray(moments[0])) { - moments = moments[0]; - } - if (!moments.length) { - return local__createLocal(); - } - res = moments[0]; - for (i = 1; i < moments.length; ++i) { - if (moments[i][fn](res)) { - res = moments[i]; - } - } - return res; - } + var foreground = this.dom.foreground; + if (foreground.parentNode) { + foreground.parentNode.removeChild(foreground); + } - // TODO: Use [].sort instead? - function min () { - var args = [].slice.call(arguments, 0); + var background = this.dom.background; + if (background.parentNode) { + background.parentNode.removeChild(background); + } - return pickBy('isBefore', args); - } + var axis = this.dom.axis; + if (axis.parentNode) { + axis.parentNode.removeChild(axis); + } + }; - function max () { - var args = [].slice.call(arguments, 0); + /** + * Add an item to the group + * @param {Item} item + */ + Group.prototype.add = function (item) { + this.items[item.id] = item; + item.setParent(this); - return pickBy('isAfter', args); + // add to + if (item.data.subgroup !== undefined) { + if (this.subgroups[item.data.subgroup] === undefined) { + this.subgroups[item.data.subgroup] = { height: 0, visible: false, index: this.subgroupIndex, items: [] }; + this.subgroupIndex++; } + this.subgroups[item.data.subgroup].items.push(item); + } + this.orderSubgroups(); - function Duration (duration) { - var normalizedInput = normalizeObjectUnits(duration), - years = normalizedInput.year || 0, - quarters = normalizedInput.quarter || 0, - months = normalizedInput.month || 0, - weeks = normalizedInput.week || 0, - days = normalizedInput.day || 0, - hours = normalizedInput.hour || 0, - minutes = normalizedInput.minute || 0, - seconds = normalizedInput.second || 0, - milliseconds = normalizedInput.millisecond || 0; - - // representation for dateAddRemove - this._milliseconds = +milliseconds + - seconds * 1e3 + // 1000 - minutes * 6e4 + // 1000 * 60 - hours * 36e5; // 1000 * 60 * 60 - // Because of dateAddRemove treats 24 hours as different from a - // day when working around DST, we need to store them separately - this._days = +days + - weeks * 7; - // It is impossible translate months into days without knowing - // which months you are are talking about, so we have to store - // it separately. - this._months = +months + - quarters * 3 + - years * 12; - - this._data = {}; - - this._locale = locale_locales__getLocale(); + 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); + } + }; - this._bubble(); + Group.prototype.orderSubgroups = function () { + if (this.subgroupOrderer !== undefined) { + var sortArray = []; + if (typeof this.subgroupOrderer == 'string') { + for (var 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 (var subgroup in this.subgroups) { + sortArray.push(this.subgroups[subgroup].items[0].data); + } + sortArray.sort(this.subgroupOrderer); } - function isDuration (obj) { - return obj instanceof Duration; + if (sortArray.length > 0) { + for (var i = 0; i < sortArray.length; i++) { + this.subgroups[sortArray[i].subgroup].index = i; + } } + } + }; - function offset (token, separator) { - addFormatToken(token, 0, 0, function () { - var offset = this.utcOffset(); - var sign = '+'; - if (offset < 0) { - offset = -offset; - sign = '-'; - } - return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); - }); + Group.prototype.resetSubgroups = function () { + for (var subgroup in this.subgroups) { + if (this.subgroups.hasOwnProperty(subgroup)) { + this.subgroups[subgroup].visible = false; } + } + }; - offset('Z', ':'); - offset('ZZ', ''); - - // PARSING + /** + * Remove an item from the group + * @param {Item} item + */ + Group.prototype.remove = function (item) { + delete this.items[item.id]; + item.setParent(null); - addRegexToken('Z', matchOffset); - addRegexToken('ZZ', matchOffset); - addParseToken(['Z', 'ZZ'], function (input, array, config) { - config._useUTC = true; - config._tzm = offsetFromString(input); - }); + // remove from visible items + var index = this.visibleItems.indexOf(item); + if (index != -1) this.visibleItems.splice(index, 1); - // HELPERS + // TODO: also remove from ordered items? + }; - // timezone chunker - // '+10:00' > ['10', '00'] - // '-1530' > ['-15', '30'] - var chunkOffset = /([\+\-]|\d\d)/gi; + /** + * Remove an item from the corresponding DataSet + * @param {Item} item + */ + Group.prototype.removeFromDataSet = function (item) { + this.itemSet.removeItem(item.id); + }; - function offsetFromString(string) { - var matches = ((string || '').match(matchOffset) || []); - var chunk = matches[matches.length - 1] || []; - var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; - var minutes = +(parts[1] * 60) + toInt(parts[2]); + /** + * Reorder the items + */ + Group.prototype.order = function () { + var array = util.toArray(this.items); + var startArray = []; + var endArray = []; - return parts[0] === '+' ? minutes : -minutes; + 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 + }; - // Return a moment from input, that is local/utc/zone equivalent to model. - function cloneWithOffset(input, model) { - var res, diff; - if (model._isUTC) { - res = model.clone(); - diff = (isMoment(input) || isDate(input) ? +input : +local__createLocal(input)) - (+res); - // Use low-level api, because this fn is low-level api. - res._d.setTime(+res._d + diff); - utils_hooks__hooks.updateOffset(res, false); - return res; - } else { - return local__createLocal(input).local(); - } - return model._isUTC ? local__createLocal(input).zone(model._offset || 0) : local__createLocal(input).local(); - } + stack.orderByStart(this.orderedItems.byStart); + stack.orderByEnd(this.orderedItems.byEnd); + }; - function getDateOffset (m) { - // On Firefox.24 Date#getTimezoneOffset returns a floating point. - // https://github.com/moment/moment/pull/1871 - return -Math.round(m._d.getTimezoneOffset() / 15) * 15; + /** + * Update the visible items + * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date + * @param {Item[]} visibleItems The previously visible items. + * @param {{start: number, end: number}} range Visible range + * @return {Item[]} visibleItems The new visible items. + * @private + */ + Group.prototype._updateVisibleItems = 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; + var item, i; + + // 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; } + }; - // HOOKS + // 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 (i = 0; i < oldVisibleItems.length; i++) { + this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range); + } + } - // This function will be called whenever a moment is mutated. - // It is intended to keep the offset in sync with the timezone. - utils_hooks__hooks.updateOffset = function () {}; + // we do a binary search for the items that have only start values. + var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data', 'start'); - // MOMENTS + // 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; + }); - // keepLocalTime = true means only change the timezone, without - // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> - // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset - // +0200, so we adjust the time as needed, to be valid. - // - // Keeping the time actually adds/subtracts (one hour) - // from the actual represented time. That is why we call updateOffset - // a second time. In case it wants us to change the offset again - // _changeInProgress == true case, then we have to adjust, because - // there is no such time in the given timezone. - function getSetOffset (input, keepLocalTime) { - var offset = this._offset || 0, - localAdjust; - if (input != null) { - if (typeof input === 'string') { - input = offsetFromString(input); - } - if (Math.abs(input) < 16) { - input = input * 60; - } - if (!this._isUTC && keepLocalTime) { - localAdjust = getDateOffset(this); - } - this._offset = input; - this._isUTC = true; - if (localAdjust != null) { - this.add(localAdjust, 'm'); - } - if (offset !== input) { - if (!keepLocalTime || this._changeInProgress) { - add_subtract__addSubtract(this, create__createDuration(input - offset, 'm'), 1, false); - } else if (!this._changeInProgress) { - this._changeInProgress = true; - utils_hooks__hooks.updateOffset(this, true); - this._changeInProgress = null; - } - } - return this; - } else { - return this._isUTC ? offset : getDateOffset(this); - } + // 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'); - function getSetZone (input, keepLocalTime) { - if (input != null) { - if (typeof input !== 'string') { - input = -input; - } + // 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; + }); + } - this.utcOffset(input, keepLocalTime); + // finally, we reposition all the visible items. + for (i = 0; i < visibleItems.length; i++) { + item = visibleItems[i]; + if (!item.displayed) item.show(); + // reposition item horizontally + item.repositionX(); + } - return this; - } else { - return -this.utcOffset(); - } - } + // debug + //console.log("new line") + //if (this.groupId == null) { + // for (i = 0; i < orderedItems.byStart.length; i++) { + // item = orderedItems.byStart[i].data; + // console.log('start',i,initialPosByStart, item.start.valueOf(), item.content, item.start >= lowerBound && item.start <= upperBound,i == initialPosByStart ? "<------------------- HEREEEE" : "") + // } + // for (i = 0; i < orderedItems.byEnd.length; i++) { + // item = orderedItems.byEnd[i].data; + // console.log('rangeEnd',i,initialPosByEnd, item.end.valueOf(), item.content, item.end >= range.start && item.end <= range.end,i == initialPosByEnd ? "<------------------- HEREEEE" : "") + // } + //} - function setOffsetToUTC (keepLocalTime) { - return this.utcOffset(0, keepLocalTime); - } + return visibleItems; + }; - function setOffsetToLocal (keepLocalTime) { - if (this._isUTC) { - this.utcOffset(0, keepLocalTime); - this._isUTC = false; + Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) { + var item; + var i; - if (keepLocalTime) { - this.subtract(getDateOffset(this), 'm'); - } + if (initialPos != -1) { + 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); } - return this; + } } - function setOffsetToParsedOffset () { - if (this._tzm) { - this.utcOffset(this._tzm); - } else if (typeof this._i === 'string') { - this.utcOffset(offsetFromString(this._i)); + 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); } - return this; + } } + } + }; - function hasAlignedHourOffset (input) { - if (!input) { - input = 0; - } - else { - input = local__createLocal(input).utcOffset(); - } - - return (this.utcOffset() - input) % 60 === 0; - } + /** + * 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(); + } + }; - function isDaylightSavingTime () { - return ( - this.utcOffset() > this.clone().month(0).utcOffset() || - this.utcOffset() > this.clone().month(5).utcOffset() - ); + /** + * 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._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(); + } + }; - function isDaylightSavingTimeShifted () { - if (this._a) { - var other = this._isUTC ? create_utc__createUTC(this._a) : local__createLocal(this._a); - return this.isValid() && compareArrays(this._a, other.toArray()) > 0; - } + module.exports = Group; - return false; - } +/***/ }, +/* 31 */ +/***/ function(module, exports, __webpack_require__) { - function isLocal () { - return !this._isUTC; - } + 'use strict'; - function isUtcOffset () { - return this._isUTC; - } + var util = __webpack_require__(2); + var Group = __webpack_require__(30); - function isUtc () { - return this._isUTC && this._offset === 0; - } + /** + * @constructor BackgroundGroup + * @param {Number | String} groupId + * @param {Object} data + * @param {ItemSet} itemSet + */ + function BackgroundGroup(groupId, data, itemSet) { + Group.call(this, groupId, data, itemSet); - var aspNetRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/; + this.width = 0; + this.height = 0; + this.top = 0; + this.left = 0; + } - // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html - // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere - var create__isoRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/; + BackgroundGroup.prototype = Object.create(Group.prototype); - function create__createDuration (input, key) { - var duration = input, - // matching against regexp is expensive, do it on demand - match = null, - sign, - ret, - diffRes; + /** + * Repaint this group + * @param {{start: number, end: number}} range + * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin + * @param {boolean} [restack=false] Force restacking of all items + * @return {boolean} Returns true if the group is resized + */ + BackgroundGroup.prototype.redraw = function (range, margin, restack) { + var resized = false; - if (isDuration(input)) { - duration = { - ms : input._milliseconds, - d : input._days, - M : input._months - }; - } else if (typeof input === 'number') { - duration = {}; - if (key) { - duration[key] = input; - } else { - duration.milliseconds = input; - } - } else if (!!(match = aspNetRegex.exec(input))) { - sign = (match[1] === '-') ? -1 : 1; - duration = { - y : 0, - d : toInt(match[DATE]) * sign, - h : toInt(match[HOUR]) * sign, - m : toInt(match[MINUTE]) * sign, - s : toInt(match[SECOND]) * sign, - ms : toInt(match[MILLISECOND]) * sign - }; - } else if (!!(match = create__isoRegex.exec(input))) { - sign = (match[1] === '-') ? -1 : 1; - duration = { - y : parseIso(match[2], sign), - M : parseIso(match[3], sign), - d : parseIso(match[4], sign), - h : parseIso(match[5], sign), - m : parseIso(match[6], sign), - s : parseIso(match[7], sign), - w : parseIso(match[8], sign) - }; - } else if (duration == null) {// checks for null or undefined - duration = {}; - } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { - diffRes = momentsDifference(local__createLocal(duration.from), local__createLocal(duration.to)); + this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); - duration = {}; - duration.ms = diffRes.milliseconds; - duration.M = diffRes.months; - } + // calculate actual size + this.width = this.dom.background.offsetWidth; - ret = new Duration(duration); + // apply new height (just always zero for BackgroundGroup + this.dom.background.style.height = '0'; - if (isDuration(input) && hasOwnProp(input, '_locale')) { - ret._locale = input._locale; - } + // 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 ret; - } + return resized; + }; - create__createDuration.fn = Duration.prototype; + /** + * Show this group: attach to the DOM + */ + BackgroundGroup.prototype.show = function () { + if (!this.dom.background.parentNode) { + this.itemSet.dom.background.appendChild(this.dom.background); + } + }; - function parseIso (inp, sign) { - // We'd normally use ~~inp for this, but unfortunately it also - // converts floats to ints. - // inp may be undefined, so careful calling replace on it. - var res = inp && parseFloat(inp.replace(',', '.')); - // apply sign while we're at it - return (isNaN(res) ? 0 : res) * sign; - } + module.exports = BackgroundGroup; - function positiveMomentsDifference(base, other) { - var res = {milliseconds: 0, months: 0}; +/***/ }, +/* 32 */ +/***/ function(module, exports, __webpack_require__) { - res.months = other.month() - base.month() + - (other.year() - base.year()) * 12; - if (base.clone().add(res.months, 'M').isAfter(other)) { - --res.months; - } + 'use strict'; - res.milliseconds = +other - +(base.clone().add(res.months, 'M')); + var Hammer = __webpack_require__(41); + var util = __webpack_require__(2); + var DataSet = __webpack_require__(4); + var DataView = __webpack_require__(5); + var TimeStep = __webpack_require__(20); + var Component = __webpack_require__(25); + var Group = __webpack_require__(30); + var BackgroundGroup = __webpack_require__(31); + var BoxItem = __webpack_require__(57); + var PointItem = __webpack_require__(23); + var RangeItem = __webpack_require__(24); + var BackgroundItem = __webpack_require__(22); - return res; - } + var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items + var BACKGROUND = '__background__'; // reserved group id for background items without group - function momentsDifference(base, other) { - var res; - other = cloneWithOffset(other, base); - if (base.isBefore(other)) { - res = positiveMomentsDifference(base, other); - } else { - res = positiveMomentsDifference(other, base); - res.milliseconds = -res.milliseconds; - res.months = -res.months; - } + /** + * 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; - return res; - } + this.defaultOptions = { + type: null, // 'box', 'point', 'range', 'background' + orientation: { + item: 'bottom' // item orientation: 'top' or 'bottom' + }, + align: 'auto', // alignment of box items + stack: true, + groupOrder: null, - function createAdder(direction, name) { - return function (val, period) { - var dur, tmp; - //invert the arguments, but complain about it - if (period !== null && !isNaN(+period)) { - deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).'); - tmp = val; val = period; period = tmp; - } + selectable: true, + multiselect: false, - val = typeof val === 'string' ? +val : val; - dur = create__createDuration(val, period); - add_subtract__addSubtract(this, dur, direction); - return this; - }; - } + editable: { + updateTime: false, + updateGroup: false, + add: false, + remove: false + }, - function add_subtract__addSubtract (mom, duration, isAdding, updateOffset) { - var milliseconds = duration._milliseconds, - days = duration._days, - months = duration._months; - updateOffset = updateOffset == null ? true : updateOffset; + snap: TimeStep.snap, - if (milliseconds) { - mom._d.setTime(+mom._d + milliseconds * isAdding); - } - if (days) { - get_set__set(mom, 'Date', get_set__get(mom, 'Date') + days * isAdding); - } - if (months) { - setMonth(mom, get_set__get(mom, 'Month') + months * isAdding); - } - if (updateOffset) { - utils_hooks__hooks.updateOffset(mom, days || months); - } + 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); + }, + + margin: { + item: { + horizontal: 10, + vertical: 10 + }, + axis: 20 } + }; - var add_subtract__add = createAdder(1, 'add'); - var add_subtract__subtract = createAdder(-1, 'subtract'); + // options is shared by this ItemSet and all its items + this.options = util.extend({}, this.defaultOptions); - function moment_calendar__calendar (time) { - // We want to compare the start of today, vs this. - // Getting start-of-today depends on whether we're local/utc/offset or not. - var now = time || local__createLocal(), - sod = cloneWithOffset(now, this).startOf('day'), - diff = this.diff(sod, 'days', true), - format = diff < -6 ? 'sameElse' : - diff < -1 ? 'lastWeek' : - diff < 0 ? 'lastDay' : - diff < 1 ? 'sameDay' : - diff < 2 ? 'nextDay' : - diff < 7 ? 'nextWeek' : 'sameElse'; - return this.format(this.localeData().calendar(format, this, local__createLocal(now))); - } + // options for getting items from the DataSet with the correct type + this.itemOptions = { + type: { start: 'Date', end: 'Date' } + }; - function clone () { - return new Moment(this); - } + this.conversion = { + toScreen: body.util.toScreen, + toTime: body.util.toTime + }; + this.dom = {}; + this.props = {}; + this.hammer = null; - function isAfter (input, units) { - var inputMs; - units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); - if (units === 'millisecond') { - input = isMoment(input) ? input : local__createLocal(input); - return +this > +input; - } else { - inputMs = isMoment(input) ? +input : +local__createLocal(input); - return inputMs < +this.clone().startOf(units); - } - } + var me = this; + this.itemsData = null; // DataSet + this.groupsData = null; // DataSet - function isBefore (input, units) { - var inputMs; - units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); - if (units === 'millisecond') { - input = isMoment(input) ? input : local__createLocal(input); - return +this < +input; - } else { - inputMs = isMoment(input) ? +input : +local__createLocal(input); - return +this.clone().endOf(units) < inputMs; - } + // listeners for the DataSet of the items + this.itemListeners = { + 'add': function add(event, params, senderId) { + me._onAdd(params.items); + }, + 'update': function update(event, params, senderId) { + me._onUpdate(params.items); + }, + 'remove': function remove(event, params, senderId) { + me._onRemove(params.items); } + }; - function isBetween (from, to, units) { - return this.isAfter(from, units) && this.isBefore(to, units); + // listeners for the DataSet of the groups + this.groupListeners = { + 'add': function add(event, params, senderId) { + me._onAddGroups(params.items); + }, + 'update': function update(event, params, senderId) { + me._onUpdateGroups(params.items); + }, + 'remove': function remove(event, params, senderId) { + me._onRemoveGroups(params.items); } + }; - function isSame (input, units) { - var inputMs; - units = normalizeUnits(units || 'millisecond'); - if (units === 'millisecond') { - input = isMoment(input) ? input : local__createLocal(input); - return +this === +input; - } else { - inputMs = +local__createLocal(input); - return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units)); - } - } + this.items = {}; // object with an Item for every data item + this.groups = {}; // Group object for every group + this.groupIds = []; - function absFloor (number) { - if (number < 0) { - return Math.ceil(number); - } else { - return Math.floor(number); - } - } + this.selection = []; // list with the ids of all selected nodes + this.stackDirty = true; // if true, all items will be restacked on next redraw - function diff (input, units, asFloat) { - var that = cloneWithOffset(input, this), - zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4, - delta, output; + this.touchParams = {}; // stores properties while dragging + // create the HTML DOM - units = normalizeUnits(units); + this._create(); - if (units === 'year' || units === 'month' || units === 'quarter') { - output = monthDiff(this, that); - if (units === 'quarter') { - output = output / 3; - } else if (units === 'year') { - output = output / 12; - } - } else { - delta = this - that; - output = units === 'second' ? delta / 1e3 : // 1000 - units === 'minute' ? delta / 6e4 : // 1000 * 60 - units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60 - units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst - units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst - delta; - } - return asFloat ? output : absFloor(output); - } + this.setOptions(options); + } - function monthDiff (a, b) { - // difference in months - var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), - // b is in (anchor - 1 month, anchor + 1 month) - anchor = a.clone().add(wholeMonthDiff, 'months'), - anchor2, adjust; + ItemSet.prototype = new Component(); - if (b - anchor < 0) { - anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); - // linear across the month - adjust = (b - anchor) / (anchor - anchor2); - } else { - anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); - // linear across the month - adjust = (b - anchor) / (anchor2 - anchor); - } + // available item types will be registered here + ItemSet.types = { + background: BackgroundItem, + box: BoxItem, + range: RangeItem, + point: PointItem + }; - return -(wholeMonthDiff + adjust); - } + /** + * 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; - utils_hooks__hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; + // create background panel + var background = document.createElement('div'); + background.className = 'vis-background'; + frame.appendChild(background); + this.dom.background = background; - function toString () { - return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); - } + // create foreground panel + var foreground = document.createElement('div'); + foreground.className = 'vis-foreground'; + frame.appendChild(foreground); + this.dom.foreground = foreground; - function moment_format__toISOString () { - var m = this.clone().utc(); - if (0 < m.year() && m.year() <= 9999) { - if ('function' === typeof Date.prototype.toISOString) { - // native implementation is ~50x faster, use it when we can - return this.toDate().toISOString(); - } else { - return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); - } - } else { - return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); - } - } + // create axis panel + var axis = document.createElement('div'); + axis.className = 'vis-axis'; + this.dom.axis = axis; - function format (inputString) { - var output = formatMoment(this, inputString || utils_hooks__hooks.defaultFormat); - return this.localeData().postformat(output); - } + // create labelset + var labelSet = document.createElement('div'); + labelSet.className = 'vis-labelset'; + this.dom.labelSet = labelSet; - function from (time, withoutSuffix) { - if (!this.isValid()) { - return this.localeData().invalidDate(); - } - return create__createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); - } + // create ungrouped Group + this._updateUngrouped(); - function fromNow (withoutSuffix) { - return this.from(local__createLocal(), withoutSuffix); - } + // create background Group + var backgroundGroup = new BackgroundGroup(BACKGROUND, null, this); + backgroundGroup.show(); + this.groups[BACKGROUND] = backgroundGroup; - function to (time, withoutSuffix) { - if (!this.isValid()) { - return this.localeData().invalidDate(); - } - return create__createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix); - } - - function toNow (withoutSuffix) { - return this.to(local__createLocal(), withoutSuffix); - } - - function locale (key) { - var newLocaleData; + // 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); - if (key === undefined) { - return this._locale._abbr; - } else { - newLocaleData = locale_locales__getLocale(key); - if (newLocaleData != null) { - this._locale = newLocaleData; - } - return this; - } + // 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)); - var lang = deprecate( - 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', - function (key) { - if (key === undefined) { - return this.localeData(); - } else { - return this.locale(key); - } - } - ); + // single select (or unselect) when tapping an item + this.hammer.on('tap', this._onSelectItem.bind(this)); - function localeData () { - return this._locale; - } + // multi select when holding mouse/touch, or on ctrl+click + this.hammer.on('press', this._onMultiSelectItem.bind(this)); - function startOf (units) { - units = normalizeUnits(units); - // the following switch intentionally omits break keywords - // to utilize falling through the cases. - switch (units) { - case 'year': - this.month(0); - /* falls through */ - case 'quarter': - case 'month': - this.date(1); - /* falls through */ - case 'week': - case 'isoWeek': - case 'day': - this.hours(0); - /* falls through */ - case 'hour': - this.minutes(0); - /* falls through */ - case 'minute': - this.seconds(0); - /* falls through */ - case 'second': - this.milliseconds(0); - } + // add item on doubletap + this.hammer.on('doubletap', this._onAddItem.bind(this)); - // weeks are a special case - if (units === 'week') { - this.weekday(0); - } - if (units === 'isoWeek') { - this.isoWeekday(1); - } + // attach to the DOM + this.show(); + }; - // quarters are also special - if (units === 'quarter') { - this.month(Math.floor(this.month() / 3) * 3); - } + /** + * 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', 'align', 'order', 'stack', 'selectable', 'multiselect', 'groupOrder', 'dataAttributes', 'template', 'hide', 'snap']; + util.selectiveExtend(fields, this.options, options); - return this; + if ('orientation' in options) { + if (typeof options.orientation === 'string') { + this.options.orientation.item = options.orientation === 'top' ? 'top' : 'bottom'; + } else if (typeof options.orientation === 'object' && 'item' in options.orientation) { + this.options.orientation.item = options.orientation.item; + } } - function endOf (units) { - units = normalizeUnits(units); - if (units === undefined || units === 'millisecond') { - return this; + 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 (typeof 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 (typeof options.margin.item === 'object') { + util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item); + } } - return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); - } - - function to_type__valueOf () { - return +this._d - ((this._offset || 0) * 60000); - } - - function unix () { - return Math.floor(+this / 1000); - } - - function toDate () { - return this._offset ? new Date(+this) : this._d; + } } - function toArray () { - var m = this; - return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; + 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; + } else if (typeof options.editable === 'object') { + util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable); + } } - function moment_valid__isValid () { - return valid__isValid(this); - } + // 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); + ['onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving'].forEach(addCallback); - function parsingFlags () { - return extend({}, getParsingFlags(this)); - } + // force the itemSet to refresh: options like orientation and margins may be changed + this.markDirty(); + } + }; - function invalidAt () { - return getParsingFlags(this).overflow; - } + /** + * 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 = []; + this.stackDirty = true; - addFormatToken(0, ['gg', 2], 0, function () { - return this.weekYear() % 100; + if (options && options.refreshItems) { + util.forEach(this.items, function (item) { + item.dirty = true; + if (item.displayed) item.redraw(); }); + } + }; - addFormatToken(0, ['GG', 2], 0, function () { - return this.isoWeekYear() % 100; - }); + /** + * Destroy the ItemSet + */ + ItemSet.prototype.destroy = function () { + this.hide(); + this.setItems(null); + this.setGroups(null); - function addWeekYearFormatToken (token, getter) { - addFormatToken(0, [token, token.length], 0, getter); - } + this.hammer = null; - addWeekYearFormatToken('gggg', 'weekYear'); - addWeekYearFormatToken('ggggg', 'weekYear'); - addWeekYearFormatToken('GGGG', 'isoWeekYear'); - addWeekYearFormatToken('GGGGG', 'isoWeekYear'); + this.body = null; + this.conversion = null; + }; - // ALIASES + /** + * 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); + } - addUnitAlias('weekYear', 'gg'); - addUnitAlias('isoWeekYear', 'GG'); + // remove the axis with dots + if (this.dom.axis.parentNode) { + this.dom.axis.parentNode.removeChild(this.dom.axis); + } - // PARSING + // remove the labelset containing all group labels + if (this.dom.labelSet.parentNode) { + this.dom.labelSet.parentNode.removeChild(this.dom.labelSet); + } + }; - addRegexToken('G', matchSigned); - addRegexToken('g', matchSigned); - addRegexToken('GG', match1to2, match2); - addRegexToken('gg', match1to2, match2); - addRegexToken('GGGG', match1to4, match4); - addRegexToken('gggg', match1to4, match4); - addRegexToken('GGGGG', match1to6, match6); - addRegexToken('ggggg', match1to6, match6); + /** + * Show the component in the DOM (when not already visible). + * @return {Boolean} changed + */ + ItemSet.prototype.show = function () { + // show frame containing the items + if (!this.dom.frame.parentNode) { + this.body.dom.center.appendChild(this.dom.frame); + } - addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { - week[token.substr(0, 2)] = toInt(input); - }); + // show axis with dots + if (!this.dom.axis.parentNode) { + this.body.dom.backgroundVertical.appendChild(this.dom.axis); + } - addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { - week[token] = utils_hooks__hooks.parseTwoDigitYear(input); - }); + // show labelset containing labels + if (!this.dom.labelSet.parentNode) { + this.body.dom.left.appendChild(this.dom.labelSet); + } + }; - // HELPERS + /** + * 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; - function weeksInYear(year, dow, doy) { - return weekOfYear(local__createLocal([year, 11, 31 + dow - doy]), dow, doy).week; - } + if (ids == undefined) ids = []; + if (!Array.isArray(ids)) ids = [ids]; - // MOMENTS + // 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(); + } - function getSetWeekYear (input) { - var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year; - return input == null ? year : this.add((input - year), 'y'); + // 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(); } + } + }; - function getSetISOWeekYear (input) { - var year = weekOfYear(this, 1, 4).year; - return input == null ? year : this.add((input - year), 'y'); - } + /** + * Get the selected items by their id + * @return {Array} ids The ids of the selected items + */ + ItemSet.prototype.getSelection = function () { + return this.selection.concat([]); + }; - function getISOWeeksInYear () { - return weeksInYear(this.year(), 1, 4); - } + /** + * 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 left = this.body.util.toScreen(range.start); + var right = this.body.util.toScreen(range.end); - function getWeeksInYear () { - var weekInfo = this.localeData()._week; - return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); - } + var ids = []; + for (var groupId in this.groups) { + if (this.groups.hasOwnProperty(groupId)) { + var group = this.groups[groupId]; + var rawVisibleItems = group.visibleItems; - addFormatToken('Q', 0, 0, 'quarter'); + // 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 (item.left < right && item.left + item.width > left) { + ids.push(item.id); + } + } + } + } - // ALIASES + return ids; + }; - addUnitAlias('quarter', 'Q'); + /** + * 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; + } + } + }; - // PARSING + /** + * 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, + editable = options.editable.updateTime || options.editable.updateGroup; - addRegexToken('Q', match1); - addParseToken('Q', function (input, array) { - array[MONTH] = (toInt(input) - 1) * 3; - }); + // recalculate absolute position (before redrawing groups) + this.props.top = this.body.domProps.top.height + this.body.domProps.border.top; + this.props.left = this.body.domProps.left.width + this.body.domProps.border.left; - // MOMENTS + // update class name + frame.className = 'vis-itemset' + (editable ? ' vis-editable' : ''); - function getSetQuarter (input) { - return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); - } + // reorder the groups (if needed) + resized = this._orderGroups() || resized; - addFormatToken('D', ['DD', 2], 'Do', 'date'); + // 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; + if (zoomed) this.stackDirty = true; + this.lastVisibleInterval = visibleInterval; + this.props.lastWidth = this.props.width; - // ALIASES + var restack = this.stackDirty; + 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; - addUnitAlias('date', 'D'); + // redraw the background group + this.groups[BACKGROUND].redraw(range, nonFirstMargin, restack); - // PARSING + // redraw all regular groups + util.forEach(this.groups, function (group) { + var groupMargin = group == firstGroup ? firstMargin : nonFirstMargin; + var groupResized = group.redraw(range, groupMargin, restack); + resized = groupResized || resized; + height += group.height; + }); + height = Math.max(height, minHeight); + this.stackDirty = false; - addRegexToken('D', match1to2); - addRegexToken('DD', match1to2, match2); - addRegexToken('Do', function (isStrict, locale) { - return isStrict ? locale._ordinalParse : locale._ordinalParseLenient; - }); + // update frame height + frame.style.height = asSize(height); - addParseToken(['D', 'DD'], DATE); - addParseToken('Do', function (input, array) { - array[DATE] = toInt(input.match(match1to2)[0], 10); - }); + // calculate actual size + this.props.width = frame.offsetWidth; + this.props.height = height; - // MOMENTS + // 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); + this.dom.axis.style.left = '0'; - var getSetDayOfMonth = makeGetSet('Date', true); + // check if this component is resized + resized = this._isResized() || resized; - addFormatToken('d', 0, 'do', 'day'); + return resized; + }; - addFormatToken('dd', 0, 0, function (format) { - return this.localeData().weekdaysMin(this, format); - }); + /** + * 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]; - addFormatToken('ddd', 0, 0, function (format) { - return this.localeData().weekdaysShort(this, format); - }); + return firstGroup || null; + }; - addFormatToken('dddd', 0, 0, function (format) { - return this.localeData().weekdays(this, format); - }); + /** + * 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 background = this.groups[BACKGROUND]; + var item, itemId; - addFormatToken('e', 0, 0, 'weekday'); - addFormatToken('E', 0, 0, 'isoWeekday'); + if (this.groupsData) { + // remove the group holding all ungrouped items + if (ungrouped) { + ungrouped.hide(); + delete this.groups[UNGROUPED]; - // ALIASES + 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; - addUnitAlias('day', 'd'); - addUnitAlias('weekday', 'e'); - addUnitAlias('isoWeekday', 'E'); + for (itemId in this.items) { + if (this.items.hasOwnProperty(itemId)) { + item = this.items[itemId]; + ungrouped.add(item); + } + } - // PARSING + ungrouped.show(); + } + } + }; - addRegexToken('d', match1to2); - addRegexToken('e', match1to2); - addRegexToken('E', match1to2); - addRegexToken('dd', matchWord); - addRegexToken('ddd', matchWord); - addRegexToken('dddd', matchWord); + /** + * Get the element for the labelset + * @return {HTMLElement} labelSet + */ + ItemSet.prototype.getLabelSet = function () { + return this.dom.labelSet; + }; - addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config) { - var weekday = config._locale.weekdaysParse(input); - // if we didn't get a weekday name, mark the date as invalid - if (weekday != null) { - week.d = weekday; - } else { - getParsingFlags(config).invalidWeekday = input; - } - }); + /** + * Set items + * @param {vis.DataSet | null} items + */ + ItemSet.prototype.setItems = function (items) { + var me = this, + ids, + oldItemsData = this.itemsData; - addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { - week[token] = toInt(input); - }); + // 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'); + } - // HELPERS + if (oldItemsData) { + // unsubscribe from old dataset + util.forEach(this.itemListeners, function (callback, event) { + oldItemsData.off(event, callback); + }); - function parseWeekday(input, locale) { - if (typeof input === 'string') { - if (!isNaN(input)) { - input = parseInt(input, 10); - } - else { - input = locale.weekdaysParse(input); - if (typeof input !== 'number') { - return null; - } - } - } - return input; - } + // remove all drawn items + ids = oldItemsData.getIds(); + this._onRemove(ids); + } - // LOCALES + if (this.itemsData) { + // subscribe to new dataset + var id = this.id; + util.forEach(this.itemListeners, function (callback, event) { + me.itemsData.on(event, callback, id); + }); - var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); - function localeWeekdays (m) { - return this._weekdays[m.day()]; - } + // add all new items + ids = this.itemsData.getIds(); + this._onAdd(ids); - var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); - function localeWeekdaysShort (m) { - return this._weekdaysShort[m.day()]; - } + // update the group holding all ungrouped items + this._updateUngrouped(); + } + }; - var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); - function localeWeekdaysMin (m) { - return this._weekdaysMin[m.day()]; - } + /** + * Get the current items + * @returns {vis.DataSet | null} + */ + ItemSet.prototype.getItems = function () { + return this.itemsData; + }; - function localeWeekdaysParse (weekdayName) { - var i, mom, regex; + /** + * Set groups + * @param {vis.DataSet} groups + */ + ItemSet.prototype.setGroups = function (groups) { + var me = this, + ids; - if (!this._weekdaysParse) { - this._weekdaysParse = []; - } + // unsubscribe from current dataset + if (this.groupsData) { + util.forEach(this.groupListeners, function (callback, event) { + me.groupsData.off(event, callback); + }); - for (i = 0; i < 7; i++) { - // make the regex if we don't have it already - if (!this._weekdaysParse[i]) { - mom = local__createLocal([2000, 1]).day(i); - regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); - this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); - } - // test the regex - if (this._weekdaysParse[i].test(weekdayName)) { - return i; - } - } - } + // remove all drawn groups + ids = this.groupsData.getIds(); + this.groupsData = null; + this._onRemoveGroups(ids); // note: this will cause a redraw + } - // MOMENTS + // 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'); + } - function getSetDayOfWeek (input) { - var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); - if (input != null) { - input = parseWeekday(input, this.localeData()); - return this.add(input - day, 'd'); - } else { - return day; - } - } + if (this.groupsData) { + // subscribe to new dataset + var id = this.id; + util.forEach(this.groupListeners, function (callback, event) { + me.groupsData.on(event, callback, id); + }); - function getSetLocaleDayOfWeek (input) { - var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; - return input == null ? weekday : this.add(input - weekday, 'd'); - } + // draw all ms + ids = this.groupsData.getIds(); + this._onAddGroups(ids); + } - function getSetISODayOfWeek (input) { - // behaves the same as moment#day except - // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) - // as a setter, sunday should belong to the previous week. - return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); - } + // update the group holding all ungrouped items + this._updateUngrouped(); - addFormatToken('H', ['HH', 2], 0, 'hour'); - addFormatToken('h', ['hh', 2], 0, function () { - return this.hours() % 12 || 12; - }); + // update the order of all items in each group + this._order(); - function meridiem (token, lowercase) { - addFormatToken(token, 0, 0, function () { - return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); - }); - } + this.body.emitter.emit('change', { queue: true }); + }; - meridiem('a', true); - meridiem('A', false); + /** + * Get the current groups + * @returns {vis.DataSet | null} groups + */ + ItemSet.prototype.getGroups = function () { + return this.groupsData; + }; - // ALIASES + /** + * 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(); - addUnitAlias('hour', 'h'); + 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); + } + }); + } + }; - // PARSING + /** + * 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'); + }; - function matchMeridiem (isStrict, locale) { - return locale._meridiemParse; - } + /** + * 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; + } + }; - addRegexToken('a', matchMeridiem); - addRegexToken('A', matchMeridiem); - addRegexToken('H', match1to2); - addRegexToken('h', match1to2); - addRegexToken('HH', match1to2, match2); - addRegexToken('hh', match1to2, match2); + /** + * Handle updated items + * @param {Number[]} ids + * @protected + */ + ItemSet.prototype._onUpdate = function (ids) { + var me = this; - addParseToken(['H', 'HH'], HOUR); - addParseToken(['a', 'A'], function (input, array, config) { - config._isPm = config._locale.isPM(input); - config._meridiem = input; - }); - addParseToken(['h', 'hh'], function (input, array, config) { - array[HOUR] = toInt(input); - getParsingFlags(config).bigHour = true; - }); + ids.forEach((function (id) { + var itemData = me.itemsData.get(id, me.itemOptions); + var item = me.items[id]; + var type = me._getType(itemData); - // LOCALES + var constructor = ItemSet.types[type]; + var selected; - function localeIsPM (input) { - // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays - // Using charAt should be more compatible. - return ((input + '').toLowerCase().charAt(0) === 'p'); + 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); + } } - var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; - function localeMeridiem (hours, minutes, isLower) { - if (hours > 11) { - return isLower ? 'pm' : 'PM'; - } else { - return isLower ? 'am' : 'AM'; + if (!item) { + // 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.stackDirty = true; // force re-stacking of all items next redraw + this.body.emitter.emit('change', { queue: true }); + }; - // MOMENTS - - // Setting the hour should keep the time, because the user explicitly - // specified which hour he wants. So trying to maintain the same hour (in - // a new timezone) makes sense. Adding/subtracting hours does not follow - // this rule. - var getSetHour = makeGetSet('Hours', true); + /** + * Handle added items + * @param {Number[]} ids + * @protected + */ + ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate; - addFormatToken('m', ['mm', 2], 0, 'minute'); + /** + * 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); + } + }); - // ALIASES + if (count) { + // update order + this._order(); + this.stackDirty = true; // force re-stacking of all items next redraw + this.body.emitter.emit('change', { queue: true }); + } + }; - addUnitAlias('minute', 'm'); + /** + * 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(); + }); + }; - // PARSING + /** + * Handle updated groups + * @param {Number[]} ids + * @private + */ + ItemSet.prototype._onUpdateGroups = function (ids) { + this._onAddGroups(ids); + }; - addRegexToken('m', match1to2); - addRegexToken('mm', match1to2, match2); - addParseToken(['m', 'mm'], MINUTE); + /** + * Handle changed groups (added or updated) + * @param {Number[]} ids + * @private + */ + ItemSet.prototype._onAddGroups = function (ids) { + var me = this; - // MOMENTS + ids.forEach(function (id) { + var groupData = me.groupsData.get(id); + var group = me.groups[id]; - var getSetMinute = makeGetSet('Minutes', false); + if (!group) { + // check for reserved ids + if (id == UNGROUPED || id == BACKGROUND) { + throw new Error('Illegal group id. ' + id + ' is a reserved id.'); + } - addFormatToken('s', ['ss', 2], 0, 'second'); + var groupOptions = Object.create(me.options); + util.extend(groupOptions, { + height: null + }); - // ALIASES + group = new Group(id, groupData, me); + me.groups[id] = group; - addUnitAlias('second', 's'); + // 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); + } + } + } - // PARSING + group.order(); + group.show(); + } else { + // update group + group.setData(groupData); + } + }); - addRegexToken('s', match1to2); - addRegexToken('ss', match1to2, match2); - addParseToken(['s', 'ss'], SECOND); + this.body.emitter.emit('change', { queue: true }); + }; - // MOMENTS + /** + * Handle removed groups + * @param {Number[]} ids + * @private + */ + ItemSet.prototype._onRemoveGroups = function (ids) { + var groups = this.groups; + ids.forEach(function (id) { + var group = groups[id]; - var getSetSecond = makeGetSet('Seconds', false); + if (group) { + group.hide(); + delete groups[id]; + } + }); - addFormatToken('S', 0, 0, function () { - return ~~(this.millisecond() / 100); - }); + this.markDirty(); - addFormatToken(0, ['SS', 2], 0, function () { - return ~~(this.millisecond() / 10); - }); + this.body.emitter.emit('change', { queue: true }); + }; - function millisecond__milliseconds (token) { - addFormatToken(0, [token, 3], 0, 'millisecond'); - } - - millisecond__milliseconds('SSS'); - millisecond__milliseconds('SSSS'); - - // ALIASES - - addUnitAlias('millisecond', 'ms'); - - // PARSING - - addRegexToken('S', match1to3, match1); - addRegexToken('SS', match1to3, match2); - addRegexToken('SSS', match1to3, match3); - addRegexToken('SSSS', matchUnsigned); - addParseToken(['S', 'SS', 'SSS', 'SSSS'], function (input, array) { - array[MILLISECOND] = toInt(('0.' + input) * 1000); + /** + * 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 }); - // MOMENTS + 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(); + }); - var getSetMillisecond = makeGetSet('Milliseconds', false); + // show the groups again, attach them to the DOM in correct order + groupIds.forEach(function (groupId) { + groups[groupId].show(); + }); - addFormatToken('z', 0, 0, 'zoneAbbr'); - addFormatToken('zz', 0, 0, 'zoneName'); + this.groupIds = groupIds; + } - // MOMENTS + return changed; + } else { + return false; + } + }; - function getZoneAbbr () { - return this._isUTC ? 'UTC' : ''; - } + /** + * Add a new item + * @param {Item} item + * @private + */ + ItemSet.prototype._addItem = function (item) { + this.items[item.id] = item; - function getZoneName () { - return this._isUTC ? 'Coordinated Universal Time' : ''; - } + // add to group + var groupId = this._getGroupId(item.data); + var group = this.groups[groupId]; + if (group) group.add(item); + }; - var momentPrototype__proto = Moment.prototype; + /** + * Update an existing item + * @param {Item} item + * @param {Object} itemData + * @private + */ + ItemSet.prototype._updateItem = function (item, itemData) { + var oldGroupId = item.data.group; + var oldSubGroupId = item.data.subgroup; - momentPrototype__proto.add = add_subtract__add; - momentPrototype__proto.calendar = moment_calendar__calendar; - momentPrototype__proto.clone = clone; - momentPrototype__proto.diff = diff; - momentPrototype__proto.endOf = endOf; - momentPrototype__proto.format = format; - momentPrototype__proto.from = from; - momentPrototype__proto.fromNow = fromNow; - momentPrototype__proto.to = to; - momentPrototype__proto.toNow = toNow; - momentPrototype__proto.get = getSet; - momentPrototype__proto.invalidAt = invalidAt; - momentPrototype__proto.isAfter = isAfter; - momentPrototype__proto.isBefore = isBefore; - momentPrototype__proto.isBetween = isBetween; - momentPrototype__proto.isSame = isSame; - momentPrototype__proto.isValid = moment_valid__isValid; - momentPrototype__proto.lang = lang; - momentPrototype__proto.locale = locale; - momentPrototype__proto.localeData = localeData; - momentPrototype__proto.max = prototypeMax; - momentPrototype__proto.min = prototypeMin; - momentPrototype__proto.parsingFlags = parsingFlags; - momentPrototype__proto.set = getSet; - momentPrototype__proto.startOf = startOf; - momentPrototype__proto.subtract = add_subtract__subtract; - momentPrototype__proto.toArray = toArray; - momentPrototype__proto.toDate = toDate; - momentPrototype__proto.toISOString = moment_format__toISOString; - momentPrototype__proto.toJSON = moment_format__toISOString; - momentPrototype__proto.toString = toString; - momentPrototype__proto.unix = unix; - momentPrototype__proto.valueOf = to_type__valueOf; + // update the items data (will redraw the item when displayed) + item.setData(itemData); - // Year - momentPrototype__proto.year = getSetYear; - momentPrototype__proto.isLeapYear = getIsLeapYear; + // update group + if (oldGroupId != item.data.group || oldSubGroupId != item.data.subgroup) { + var oldGroup = this.groups[oldGroupId]; + if (oldGroup) oldGroup.remove(item); - // Week Year - momentPrototype__proto.weekYear = getSetWeekYear; - momentPrototype__proto.isoWeekYear = getSetISOWeekYear; + var groupId = this._getGroupId(item.data); + var group = this.groups[groupId]; + if (group) group.add(item); + } + }; - // Quarter - momentPrototype__proto.quarter = momentPrototype__proto.quarters = getSetQuarter; + /** + * 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(); - // Month - momentPrototype__proto.month = getSetMonth; - momentPrototype__proto.daysInMonth = getDaysInMonth; + // remove from items + delete this.items[item.id]; - // Week - momentPrototype__proto.week = momentPrototype__proto.weeks = getSetWeek; - momentPrototype__proto.isoWeek = momentPrototype__proto.isoWeeks = getSetISOWeek; - momentPrototype__proto.weeksInYear = getWeeksInYear; - momentPrototype__proto.isoWeeksInYear = getISOWeeksInYear; + // remove from selection + var index = this.selection.indexOf(item.id); + if (index != -1) this.selection.splice(index, 1); - // Day - momentPrototype__proto.date = getSetDayOfMonth; - momentPrototype__proto.day = momentPrototype__proto.days = getSetDayOfWeek; - momentPrototype__proto.weekday = getSetLocaleDayOfWeek; - momentPrototype__proto.isoWeekday = getSetISODayOfWeek; - momentPrototype__proto.dayOfYear = getSetDayOfYear; + // remove from group + item.parent && item.parent.remove(item); + }; - // Hour - momentPrototype__proto.hour = momentPrototype__proto.hours = getSetHour; + /** + * Create an array containing all items being a range (having an end date) + * @param array + * @returns {Array} + * @private + */ + ItemSet.prototype._constructByEndArray = function (array) { + var endArray = []; - // Minute - momentPrototype__proto.minute = momentPrototype__proto.minutes = getSetMinute; + for (var i = 0; i < array.length; i++) { + if (array[i] instanceof RangeItem) { + endArray.push(array[i]); + } + } + return endArray; + }; - // Second - momentPrototype__proto.second = momentPrototype__proto.seconds = getSetSecond; + /** + * Register the clicked item on touch, before dragStart is initiated. + * + * dragStart is initiated from a mousemove event, AFTER the mouse/touch is + * already moving. Therefore, the mouse/touch can sometimes be above an other + * DOM element than the item itself. + * + * @param {Event} event + * @private + */ + ItemSet.prototype._onTouch = function (event) { + // store the touched item, used in _onDragStart + this.touchParams.item = this.itemFromTarget(event); + this.touchParams.dragLeftItem = event.target.dragLeftItem || false; + this.touchParams.dragRightItem = event.target.dragRightItem || false; + this.touchParams.itemProps = null; + }; - // Millisecond - momentPrototype__proto.millisecond = momentPrototype__proto.milliseconds = getSetMillisecond; + /** + * Start dragging the selected events + * @param {Event} event + * @private + */ + ItemSet.prototype._onDragStart = function (event) { + if (!this.options.editable.updateTime && !this.options.editable.updateGroup) { + return; + } - // Offset - momentPrototype__proto.utcOffset = getSetOffset; - momentPrototype__proto.utc = setOffsetToUTC; - momentPrototype__proto.local = setOffsetToLocal; - momentPrototype__proto.parseZone = setOffsetToParsedOffset; - momentPrototype__proto.hasAlignedHourOffset = hasAlignedHourOffset; - momentPrototype__proto.isDST = isDaylightSavingTime; - momentPrototype__proto.isDSTShifted = isDaylightSavingTimeShifted; - momentPrototype__proto.isLocal = isLocal; - momentPrototype__proto.isUtcOffset = isUtcOffset; - momentPrototype__proto.isUtc = isUtc; - momentPrototype__proto.isUTC = isUtc; + var item = this.touchParams.item || null; + var me = this; + var props; - // Timezone - momentPrototype__proto.zoneAbbr = getZoneAbbr; - momentPrototype__proto.zoneName = getZoneName; + if (item && item.selected) { + var dragLeftItem = this.touchParams.dragLeftItem; + var dragRightItem = this.touchParams.dragRightItem; - // Deprecations - momentPrototype__proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); - momentPrototype__proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); - momentPrototype__proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); - momentPrototype__proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779', getSetZone); + if (dragLeftItem) { + props = { + item: dragLeftItem, + initialX: event.center.x, + dragLeft: true, + data: util.extend({}, item.data) // clone the items data + }; - var momentPrototype = momentPrototype__proto; + this.touchParams.itemProps = [props]; + } else if (dragRightItem) { + props = { + item: dragRightItem, + initialX: event.center.x, + dragRight: true, + data: util.extend({}, item.data) // clone the items data + }; - function moment__createUnix (input) { - return local__createLocal(input * 1000); - } + this.touchParams.itemProps = [props]; + } else { + this.touchParams.itemProps = this.getSelection().map(function (id) { + var item = me.items[id]; + var props = { + item: item, + initialX: event.center.x, + data: util.extend({}, item.data) // clone the items data + }; - function moment__createInZone () { - return local__createLocal.apply(null, arguments).parseZone(); + return props; + }); } - var defaultCalendar = { - sameDay : '[Today at] LT', - nextDay : '[Tomorrow at] LT', - nextWeek : 'dddd [at] LT', - lastDay : '[Yesterday at] LT', - lastWeek : '[Last] dddd [at] LT', - sameElse : 'L' - }; + event.stopPropagation(); + } else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) { + // create a new range item when dragging with ctrl key down + this._onDragStartAddItem(event); + } + }; - function locale_calendar__calendar (key, mom, now) { - var output = this._calendar[key]; - return typeof output === 'function' ? output.call(mom, now) : output; - } + /** + * Start creating a new range item by dragging. + * @param {Event} event + * @private + */ + ItemSet.prototype._onDragStartAddItem = function (event) { + var snap = this.options.snap || null; + var xAbs = util.getAbsoluteLeft(this.dom.frame); + var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px + var time = this.body.util.toTime(x); + var scale = this.body.util.getScale(); + var step = this.body.util.getStep(); + var start = snap ? snap(time, scale, step) : start; + var end = start; - var defaultLongDateFormat = { - LTS : 'h:mm:ss A', - LT : 'h:mm A', - L : 'MM/DD/YYYY', - LL : 'MMMM D, YYYY', - LLL : 'MMMM D, YYYY LT', - LLLL : 'dddd, MMMM D, YYYY LT' - }; + var itemData = { + type: 'range', + start: start, + end: end, + content: 'new item' + }; - function longDateFormat (key) { - var output = this._longDateFormat[key]; - if (!output && this._longDateFormat[key.toUpperCase()]) { - output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { - return val.slice(1); - }); - this._longDateFormat[key] = output; - } - return output; - } + var id = util.randomUUID(); + itemData[this.itemsData._fieldId] = id; - var defaultInvalidDate = 'Invalid date'; + var group = this.groupFromTarget(event); + if (group) { + itemData.group = group.groupId; + } - function invalidDate () { - return this._invalidDate; - } + var newItem = new RangeItem(itemData, this.conversion, this.options); + newItem.id = id; // TODO: not so nice setting id afterwards + newItem.data = itemData; + this._addItem(newItem); - var defaultOrdinal = '%d'; - var defaultOrdinalParse = /\d{1,2}/; + var props = { + item: newItem, + dragRight: true, + initialX: event.center.x, + data: util.extend({}, itemData) + }; + this.touchParams.itemProps = [props]; - function ordinal (number) { - return this._ordinal.replace('%d', number); - } + event.stopPropagation(); + }; - function preParsePostFormat (string) { - return string; - } + /** + * Drag selected items + * @param {Event} event + * @private + */ + ItemSet.prototype._onDrag = function (event) { + if (this.touchParams.itemProps) { + event.stopPropagation(); - var defaultRelativeTime = { - future : 'in %s', - past : '%s ago', - s : 'a few seconds', - m : 'a minute', - mm : '%d minutes', - h : 'an hour', - hh : '%d hours', - d : 'a day', - dd : '%d days', - M : 'a month', - MM : '%d months', - y : 'a year', - yy : '%d years' - }; + var me = this; + var snap = this.options.snap || null; + var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width; + var scale = this.body.util.getScale(); + var step = this.body.util.getStep(); - function relative__relativeTime (number, withoutSuffix, string, isFuture) { - var output = this._relativeTime[string]; - return (typeof output === 'function') ? - output(number, withoutSuffix, string, isFuture) : - output.replace(/%d/i, number); - } + // move + this.touchParams.itemProps.forEach(function (props) { + var newProps = {}; + var current = me.body.util.toTime(event.center.x - xOffset); + var initial = me.body.util.toTime(props.initialX - xOffset); + var offset = current - initial; - function pastFuture (diff, output) { - var format = this._relativeTime[diff > 0 ? 'future' : 'past']; - return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); - } + var itemData = util.extend({}, props.item.data); // clone the data - function locale_set__set (config) { - var prop, i; - for (i in config) { - prop = config[i]; - if (typeof prop === 'function') { - this[i] = prop; + if (me.options.editable.updateTime) { + if (props.dragLeft) { + // drag left side of a range item + if (itemData.start != undefined) { + var initialStart = util.convert(props.data.start, 'Date'); + var start = new Date(initialStart.valueOf() + offset); + itemData.start = snap ? snap(start, scale, step) : start; + } + } else if (props.dragRight) { + // drag right side of a range item + if (itemData.end != undefined) { + var initialEnd = util.convert(props.data.end, 'Date'); + var end = new Date(initialEnd.valueOf() + offset); + itemData.end = snap ? snap(end, scale, step) : end; + } + } else { + // drag both start and end + if (itemData.start != undefined) { + var initialStart = util.convert(props.data.start, 'Date').valueOf(); + var start = new Date(initialStart + offset); + + if (itemData.end != undefined) { + var initialEnd = util.convert(props.data.end, 'Date'); + var duration = initialEnd.valueOf() - initialStart.valueOf(); + + itemData.start = snap ? snap(start, scale, step) : start; + itemData.end = new Date(itemData.start.valueOf() + duration); } else { - this['_' + i] = prop; + itemData.start = snap ? snap(start, scale, step) : start; } + } } - // Lenient ordinal parsing accepts just a number in addition to - // number + (possibly) stuff coming from _ordinalParseLenient. - this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + (/\d{1,2}/).source); - } + } - var prototype__proto = Locale.prototype; + if (me.options.editable.updateGroup && (!props.dragLeft && !props.dragRight)) { + if (itemData.group != undefined) { + // drag from one group to another + var group = me.groupFromTarget(event); + if (group) { + itemData.group = group.groupId; + } + } + } - prototype__proto._calendar = defaultCalendar; - prototype__proto.calendar = locale_calendar__calendar; - prototype__proto._longDateFormat = defaultLongDateFormat; - prototype__proto.longDateFormat = longDateFormat; - prototype__proto._invalidDate = defaultInvalidDate; - prototype__proto.invalidDate = invalidDate; - prototype__proto._ordinal = defaultOrdinal; - prototype__proto.ordinal = ordinal; - prototype__proto._ordinalParse = defaultOrdinalParse; - prototype__proto.preparse = preParsePostFormat; - prototype__proto.postformat = preParsePostFormat; - prototype__proto._relativeTime = defaultRelativeTime; - prototype__proto.relativeTime = relative__relativeTime; - prototype__proto.pastFuture = pastFuture; - prototype__proto.set = locale_set__set; + // confirm moving the item + me.options.onMoving(itemData, function (itemData) { + if (itemData) { + props.item.setData(itemData); + } + }); + }); - // Month - prototype__proto.months = localeMonths; - prototype__proto._months = defaultLocaleMonths; - prototype__proto.monthsShort = localeMonthsShort; - prototype__proto._monthsShort = defaultLocaleMonthsShort; - prototype__proto.monthsParse = localeMonthsParse; + this.stackDirty = true; // force re-stacking of all items next redraw + this.body.emitter.emit('change'); + } + }; - // Week - prototype__proto.week = localeWeek; - prototype__proto._week = defaultLocaleWeek; - prototype__proto.firstDayOfYear = localeFirstDayOfYear; - prototype__proto.firstDayOfWeek = localeFirstDayOfWeek; + /** + * Move an item to another group + * @param {Item} item + * @param {String | Number} groupId + * @private + */ + ItemSet.prototype._moveToGroup = function (item, groupId) { + var group = this.groups[groupId]; + if (group && group.groupId != item.data.group) { + var oldGroup = item.parent; + oldGroup.remove(item); + oldGroup.order(); + group.add(item); + group.order(); - // Day of Week - prototype__proto.weekdays = localeWeekdays; - prototype__proto._weekdays = defaultLocaleWeekdays; - prototype__proto.weekdaysMin = localeWeekdaysMin; - prototype__proto._weekdaysMin = defaultLocaleWeekdaysMin; - prototype__proto.weekdaysShort = localeWeekdaysShort; - prototype__proto._weekdaysShort = defaultLocaleWeekdaysShort; - prototype__proto.weekdaysParse = localeWeekdaysParse; - - // Hours - prototype__proto.isPM = localeIsPM; - prototype__proto._meridiemParse = defaultLocaleMeridiemParse; - prototype__proto.meridiem = localeMeridiem; + item.data.group = group.groupId; + } + }; - function lists__get (format, index, field, setter) { - var locale = locale_locales__getLocale(); - var utc = create_utc__createUTC().set(setter, index); - return locale[field](utc, format); - } + /** + * End of dragging selected items + * @param {Event} event + * @private + */ + ItemSet.prototype._onDragEnd = function (event) { + if (this.touchParams.itemProps) { + event.stopPropagation(); - function list (format, index, field, count, setter) { - if (typeof format === 'number') { - index = format; - format = undefined; - } + // prepare a change set for the changed items + var changes = []; + var me = this; + var dataset = this.itemsData.getDataSet(); - format = format || ''; + var itemProps = this.touchParams.itemProps; + this.touchParams.itemProps = null; + itemProps.forEach(function (props) { + var id = props.item.id; + var exists = me.itemsData.get(id, me.itemOptions) != null; - if (index != null) { - return lists__get(format, index, field, setter); - } + if (!exists) { + // add a new item + me.options.onAdd(props.item.data, function (itemData) { + me._removeItem(props.item); // remove temporary item + if (itemData) { + me.itemsData.getDataSet().add(itemData); + } - var i; - var out = []; - for (i = 0; i < count; i++) { - out[i] = lists__get(format, i, field, setter); - } - return out; - } + // force re-stacking of all items next redraw + me.stackDirty = true; + me.body.emitter.emit('change'); + }); + } else { + // update existing item + var itemData = util.extend({}, props.item.data); // clone the data + me.options.onMove(itemData, function (itemData) { + if (itemData) { + // apply changes + itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined) + changes.push(itemData); + } else { + // restore original values + props.item.setData(props.data); - function lists__listMonths (format, index) { - return list(format, index, 'months', 12, 'month'); - } + me.stackDirty = true; // force re-stacking of all items next redraw + me.body.emitter.emit('change'); + } + }); + } + }); - function lists__listMonthsShort (format, index) { - return list(format, index, 'monthsShort', 12, 'month'); + // apply the changes to the data (if there are changes) + if (changes.length) { + dataset.update(changes); } + } + }; - function lists__listWeekdays (format, index) { - return list(format, index, 'weekdays', 7, 'day'); - } + /** + * Handle selecting/deselecting an item when tapping it + * @param {Event} event + * @private + */ + ItemSet.prototype._onSelectItem = function (event) { + if (!this.options.selectable) return; - function lists__listWeekdaysShort (format, index) { - return list(format, index, 'weekdaysShort', 7, 'day'); - } + var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey); + var shiftKey = event.srcEvent && event.srcEvent.shiftKey; + if (ctrlKey || shiftKey) { + this._onMultiSelectItem(event); + return; + } - function lists__listWeekdaysMin (format, index) { - return list(format, index, 'weekdaysMin', 7, 'day'); - } + var oldSelection = this.getSelection(); - locale_locales__getSetGlobalLocale('en', { - ordinalParse: /\d{1,2}(th|st|nd|rd)/, - ordinal : function (number) { - var b = number % 10, - output = (toInt(number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - return number + output; - } - }); + var item = this.itemFromTarget(event); + var selection = item ? [item.id] : []; + this.setSelection(selection); - // Side effect imports - utils_hooks__hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', locale_locales__getSetGlobalLocale); - utils_hooks__hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', locale_locales__getLocale); + var newSelection = this.getSelection(); - var mathAbs = Math.abs; + // emit a select event, + // except when old selection is empty and new selection is still empty + if (newSelection.length > 0 || oldSelection.length > 0) { + this.body.emitter.emit('select', { + items: newSelection + }); + } + }; - function duration_abs__abs () { - var data = this._data; + /** + * Handle creation and updates of an item on double tap + * @param event + * @private + */ + ItemSet.prototype._onAddItem = function (event) { + if (!this.options.selectable) return; + if (!this.options.editable.add) return; - this._milliseconds = mathAbs(this._milliseconds); - this._days = mathAbs(this._days); - this._months = mathAbs(this._months); + var me = this; + var snap = this.options.snap || null; + var item = this.itemFromTarget(event); - data.milliseconds = mathAbs(data.milliseconds); - data.seconds = mathAbs(data.seconds); - data.minutes = mathAbs(data.minutes); - data.hours = mathAbs(data.hours); - data.months = mathAbs(data.months); - data.years = mathAbs(data.years); + event.stopPropagation(); - return this; - } + if (item) { + // update item - function duration_add_subtract__addSubtract (duration, input, value, direction) { - var other = create__createDuration(input, value); + // execute async handler to update the item (or cancel it) + var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset + this.options.onUpdate(itemData, function (itemData) { + if (itemData) { + me.itemsData.getDataSet().update(itemData); + } + }); + } else { + // add item + var xAbs = util.getAbsoluteLeft(this.dom.frame); + var x = event.center.x - xAbs; + var start = this.body.util.toTime(x); + var scale = this.body.util.getScale(); + var step = this.body.util.getStep(); - duration._milliseconds += direction * other._milliseconds; - duration._days += direction * other._days; - duration._months += direction * other._months; + var newItem = { + start: snap ? snap(start, scale, step) : start, + content: 'new item' + }; - return duration._bubble(); + // when default type is a range, add a default end date to the new item + if (this.options.type === 'range') { + var end = this.body.util.toTime(x + this.props.width / 5); + newItem.end = snap ? snap(end, scale, step) : end; } - // supports only 2.0-style add(1, 's') or add(duration) - function duration_add_subtract__add (input, value) { - return duration_add_subtract__addSubtract(this, input, value, 1); - } + newItem[this.itemsData._fieldId] = util.randomUUID(); - // supports only 2.0-style subtract(1, 's') or subtract(duration) - function duration_add_subtract__subtract (input, value) { - return duration_add_subtract__addSubtract(this, input, value, -1); + var group = this.groupFromTarget(event); + if (group) { + newItem.group = group.groupId; } - function bubble () { - var milliseconds = this._milliseconds; - var days = this._days; - var months = this._months; - var data = this._data; - var seconds, minutes, hours, years = 0; - - // The following code bubbles up values, see the tests for - // examples of what that means. - data.milliseconds = milliseconds % 1000; - - seconds = absFloor(milliseconds / 1000); - data.seconds = seconds % 60; + // execute async handler to customize (or cancel) adding an item + this.options.onAdd(newItem, function (item) { + if (item) { + me.itemsData.getDataSet().add(item); + // TODO: need to trigger a redraw? + } + }); + } + }; - minutes = absFloor(seconds / 60); - data.minutes = minutes % 60; + /** + * Handle selecting/deselecting multiple items when holding an item + * @param {Event} event + * @private + */ + ItemSet.prototype._onMultiSelectItem = function (event) { + if (!this.options.selectable) return; - hours = absFloor(minutes / 60); - data.hours = hours % 24; + var item = this.itemFromTarget(event); - days += absFloor(hours / 24); + if (item) { + // multi select items (if allowed) - // Accurately convert days to years, assume start from year 0. - years = absFloor(daysToYears(days)); - days -= absFloor(yearsToDays(years)); + var selection = this.options.multiselect ? this.getSelection() // take current selection + : []; // deselect current selection - // 30 days to a month - // TODO (iskren): Use anchor date (like 1st Jan) to compute this. - months += absFloor(days / 30); - days %= 30; + var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false; - // 12 months -> 1 year - years += absFloor(months / 12); - months %= 12; + if (shiftKey && this.options.multiselect) { + // select all items between the old selection and the tapped item - data.days = days; - data.months = months; - data.years = years; + // determine the selection range + selection.push(item.id); + var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions)); - return this; - } + // select all items within the selection range + selection = []; + for (var id in this.items) { + if (this.items.hasOwnProperty(id)) { + var _item = this.items[id]; + var start = _item.data.start; + var end = _item.data.end !== undefined ? _item.data.end : start; - function daysToYears (days) { - // 400 years have 146097 days (taking into account leap year rules) - return days * 400 / 146097; + if (start >= range.min && end <= range.max && !(_item instanceof BackgroundItem)) { + selection.push(_item.id); // do not use id but item.id, id itself is stringified + } + } + } + } else { + // add/remove this item from the current selection + var index = selection.indexOf(item.id); + if (index == -1) { + // item is not yet selected -> select it + selection.push(item.id); + } else { + // item is already selected -> deselect it + selection.splice(index, 1); + } } - function yearsToDays (years) { - // years * 365 + absFloor(years / 4) - - // absFloor(years / 100) + absFloor(years / 400); - return years * 146097 / 400; - } + this.setSelection(selection); - function as (units) { - var days; - var months; - var milliseconds = this._milliseconds; + this.body.emitter.emit('select', { + items: this.getSelection() + }); + } + }; - units = normalizeUnits(units); + /** + * Calculate the time range of a list of items + * @param {Array.} itemsData + * @return {{min: Date, max: Date}} Returns the range of the provided items + * @private + */ + ItemSet._getItemRange = function (itemsData) { + var max = null; + var min = null; - if (units === 'month' || units === 'year') { - days = this._days + milliseconds / 864e5; - months = this._months + daysToYears(days) * 12; - return units === 'month' ? months : months / 12; - } else { - // handle milliseconds separately because of floating point math errors (issue #1867) - days = this._days + Math.round(yearsToDays(this._months / 12)); - switch (units) { - case 'week' : return days / 7 + milliseconds / 6048e5; - case 'day' : return days + milliseconds / 864e5; - case 'hour' : return days * 24 + milliseconds / 36e5; - case 'minute' : return days * 1440 + milliseconds / 6e4; - case 'second' : return days * 86400 + milliseconds / 1000; - // Math.floor prevents floating point math errors here - case 'millisecond': return Math.floor(days * 864e5) + milliseconds; - default: throw new Error('Unknown unit ' + units); - } - } + itemsData.forEach(function (data) { + if (min == null || data.start < min) { + min = data.start; } - // TODO: Use this.as('ms')? - function duration_as__valueOf () { - return ( - this._milliseconds + - this._days * 864e5 + - (this._months % 12) * 2592e6 + - toInt(this._months / 12) * 31536e6 - ); + if (data.end != undefined) { + if (max == null || data.end > max) { + max = data.end; + } + } else { + if (max == null || data.start > max) { + max = data.start; + } } + }); - function makeAs (alias) { - return function () { - return this.as(alias); - }; + return { + min: min, + max: max + }; + }; + + /** + * Find an item from an event target: + * searches for the attribute 'timeline-item' in the event target's element tree + * @param {Event} event + * @return {Item | null} item + */ + ItemSet.prototype.itemFromTarget = function (event) { + var target = event.target; + while (target) { + if (target.hasOwnProperty('timeline-item')) { + return target['timeline-item']; } + target = target.parentNode; + } - var asMilliseconds = makeAs('ms'); - var asSeconds = makeAs('s'); - var asMinutes = makeAs('m'); - var asHours = makeAs('h'); - var asDays = makeAs('d'); - var asWeeks = makeAs('w'); - var asMonths = makeAs('M'); - var asYears = makeAs('y'); + return null; + }; - function duration_get__get (units) { - units = normalizeUnits(units); - return this[units + 's'](); + /** + * Find the Group from an event target: + * searches for the attribute 'timeline-group' in the event target's element tree + * @param {Event} event + * @return {Group | null} group + */ + ItemSet.prototype.groupFromTarget = function (event) { + var clientY = event.center ? event.center.y : event.clientY; + for (var i = 0; i < this.groupIds.length; i++) { + var groupId = this.groupIds[i]; + var group = this.groups[groupId]; + var foreground = group.dom.foreground; + var top = util.getAbsoluteTop(foreground); + if (clientY > top && clientY < top + foreground.offsetHeight) { + return group; } - function makeGetter(name) { - return function () { - return this._data[name]; - }; + if (this.options.orientation.item === 'top') { + if (i === this.groupIds.length - 1 && clientY > top) { + return group; + } + } else { + if (i === 0 && clientY < top + foreground.offset) { + return group; + } } + } - var duration_get__milliseconds = makeGetter('milliseconds'); - var seconds = makeGetter('seconds'); - var minutes = makeGetter('minutes'); - var hours = makeGetter('hours'); - var days = makeGetter('days'); - var months = makeGetter('months'); - var years = makeGetter('years'); + return null; + }; - function weeks () { - return absFloor(this.days() / 7); + /** + * Find the ItemSet from an event target: + * searches for the attribute 'timeline-itemset' in the event target's element tree + * @param {Event} event + * @return {ItemSet | null} item + */ + ItemSet.itemSetFromTarget = function (event) { + var target = event.target; + while (target) { + if (target.hasOwnProperty('timeline-itemset')) { + return target['timeline-itemset']; } + target = target.parentNode; + } - var round = Math.round; - var thresholds = { - s: 45, // seconds to minute - m: 45, // minutes to hour - h: 22, // hours to day - d: 26, // days to month - M: 11 // months to year - }; + return null; + }; - // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize - function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { - return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); - } + module.exports = ItemSet; - function duration_humanize__relativeTime (posNegDuration, withoutSuffix, locale) { - var duration = create__createDuration(posNegDuration).abs(); - var seconds = round(duration.as('s')); - var minutes = round(duration.as('m')); - var hours = round(duration.as('h')); - var days = round(duration.as('d')); - var months = round(duration.as('M')); - var years = round(duration.as('y')); +/***/ }, +/* 33 */ +/***/ function(module, exports, __webpack_require__) { - var a = seconds < thresholds.s && ['s', seconds] || - minutes === 1 && ['m'] || - minutes < thresholds.m && ['mm', minutes] || - hours === 1 && ['h'] || - hours < thresholds.h && ['hh', hours] || - days === 1 && ['d'] || - days < thresholds.d && ['dd', days] || - months === 1 && ['M'] || - months < thresholds.M && ['MM', months] || - years === 1 && ['y'] || ['yy', years]; + 'use strict'; - a[2] = withoutSuffix; - a[3] = +posNegDuration > 0; - a[4] = locale; - return substituteTimeAgo.apply(null, a); - } + var util = __webpack_require__(2); + var DOMutil = __webpack_require__(3); + var Component = __webpack_require__(25); - // This function allows you to set a threshold for relative time strings - function duration_humanize__getSetRelativeTimeThreshold (threshold, limit) { - if (thresholds[threshold] === undefined) { - return false; - } - if (limit === undefined) { - return thresholds[threshold]; - } - thresholds[threshold] = limit; - return true; + /** + * Legend for Graph2d + */ + function Legend(body, options, side, linegraphOptions) { + this.body = body; + this.defaultOptions = { + enabled: true, + icons: true, + iconSize: 20, + iconSpacing: 6, + left: { + visible: true, + position: 'top-left' // top/bottom - left,center,right + }, + right: { + visible: true, + position: 'top-left' // top/bottom - left,center,right } + }; + this.side = side; + this.options = util.extend({}, this.defaultOptions); + this.linegraphOptions = linegraphOptions; - function humanize (withSuffix) { - var locale = this.localeData(); - var output = duration_humanize__relativeTime(this, !withSuffix, locale); + this.svgElements = {}; + this.dom = {}; + this.groups = {}; + this.amountOfGroups = 0; + this._create(); - if (withSuffix) { - output = locale.pastFuture(+this, output); - } + this.setOptions(options); + } - return locale.postformat(output); - } + Legend.prototype = new Component(); - var iso_string__abs = Math.abs; + Legend.prototype.clear = function () { + this.groups = {}; + this.amountOfGroups = 0; + }; - function iso_string__toISOString() { - // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js - var Y = iso_string__abs(this.years()); - var M = iso_string__abs(this.months()); - var D = iso_string__abs(this.days()); - var h = iso_string__abs(this.hours()); - var m = iso_string__abs(this.minutes()); - var s = iso_string__abs(this.seconds() + this.milliseconds() / 1000); - var total = this.asSeconds(); + Legend.prototype.addGroup = function (label, graphOptions) { - if (!total) { - // this is the same as C#'s (Noda) and python (isodate)... - // but not other JS (goog.date) - return 'P0D'; - } + if (!this.groups.hasOwnProperty(label)) { + this.groups[label] = graphOptions; + } + this.amountOfGroups += 1; + }; - return (total < 0 ? '-' : '') + - 'P' + - (Y ? Y + 'Y' : '') + - (M ? M + 'M' : '') + - (D ? D + 'D' : '') + - ((h || m || s) ? 'T' : '') + - (h ? h + 'H' : '') + - (m ? m + 'M' : '') + - (s ? s + 'S' : ''); - } + Legend.prototype.updateGroup = function (label, graphOptions) { + this.groups[label] = graphOptions; + }; - var duration_prototype__proto = Duration.prototype; + Legend.prototype.removeGroup = function (label) { + if (this.groups.hasOwnProperty(label)) { + delete this.groups[label]; + this.amountOfGroups -= 1; + } + }; - duration_prototype__proto.abs = duration_abs__abs; - duration_prototype__proto.add = duration_add_subtract__add; - duration_prototype__proto.subtract = duration_add_subtract__subtract; - duration_prototype__proto.as = as; - duration_prototype__proto.asMilliseconds = asMilliseconds; - duration_prototype__proto.asSeconds = asSeconds; - duration_prototype__proto.asMinutes = asMinutes; - duration_prototype__proto.asHours = asHours; - duration_prototype__proto.asDays = asDays; - duration_prototype__proto.asWeeks = asWeeks; - duration_prototype__proto.asMonths = asMonths; - duration_prototype__proto.asYears = asYears; - duration_prototype__proto.valueOf = duration_as__valueOf; - duration_prototype__proto._bubble = bubble; - duration_prototype__proto.get = duration_get__get; - duration_prototype__proto.milliseconds = duration_get__milliseconds; - duration_prototype__proto.seconds = seconds; - duration_prototype__proto.minutes = minutes; - duration_prototype__proto.hours = hours; - duration_prototype__proto.days = days; - duration_prototype__proto.weeks = weeks; - duration_prototype__proto.months = months; - duration_prototype__proto.years = years; - duration_prototype__proto.humanize = humanize; - duration_prototype__proto.toISOString = iso_string__toISOString; - duration_prototype__proto.toString = iso_string__toISOString; - duration_prototype__proto.toJSON = iso_string__toISOString; - duration_prototype__proto.locale = locale; - duration_prototype__proto.localeData = localeData; + Legend.prototype._create = function () { + this.dom.frame = document.createElement('div'); + this.dom.frame.className = 'vis-legend'; + this.dom.frame.style.position = 'absolute'; + this.dom.frame.style.top = '10px'; + this.dom.frame.style.display = 'block'; - // Deprecations - duration_prototype__proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', iso_string__toISOString); - duration_prototype__proto.lang = lang; + this.dom.textArea = document.createElement('div'); + this.dom.textArea.className = 'vis-legend-text'; + this.dom.textArea.style.position = 'relative'; + this.dom.textArea.style.top = '0px'; - // Side effect imports + this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + this.svg.style.position = 'absolute'; + this.svg.style.top = 0 + 'px'; + this.svg.style.width = this.options.iconSize + 5 + 'px'; + this.svg.style.height = '100%'; - addFormatToken('X', 0, 0, 'unix'); - addFormatToken('x', 0, 0, 'valueOf'); + this.dom.frame.appendChild(this.svg); + this.dom.frame.appendChild(this.dom.textArea); + }; - // PARSING + /** + * Hide the component from the DOM + */ + Legend.prototype.hide = function () { + // remove the frame containing the items + if (this.dom.frame.parentNode) { + this.dom.frame.parentNode.removeChild(this.dom.frame); + } + }; - addRegexToken('x', matchSigned); - addRegexToken('X', matchTimestamp); - addParseToken('X', function (input, array, config) { - config._d = new Date(parseFloat(input, 10) * 1000); - }); - addParseToken('x', function (input, array, config) { - config._d = new Date(toInt(input)); - }); + /** + * Show the component in the DOM (when not already visible). + * @return {Boolean} changed + */ + Legend.prototype.show = function () { + // show frame containing the items + if (!this.dom.frame.parentNode) { + this.body.dom.center.appendChild(this.dom.frame); + } + }; - // Side effect imports + Legend.prototype.setOptions = function (options) { + var fields = ['enabled', 'orientation', 'icons', 'left', 'right']; + util.selectiveDeepExtend(fields, this.options, options); + }; + Legend.prototype.redraw = function () { + var activeGroups = 0; + var groupArray = Object.keys(this.groups); + groupArray.sort(function (a, b) { + return a < b ? -1 : 1; + }); - utils_hooks__hooks.version = '2.10.3'; + for (var i = 0; i < groupArray.length; i++) { + var groupId = groupArray[i]; + if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { + activeGroups++; + } + } - setHookCallback(local__createLocal); + if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false || activeGroups == 0) { + this.hide(); + } else { + this.show(); + if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'bottom-left') { + this.dom.frame.style.left = '4px'; + this.dom.frame.style.textAlign = 'left'; + this.dom.textArea.style.textAlign = 'left'; + this.dom.textArea.style.left = this.options.iconSize + 15 + 'px'; + this.dom.textArea.style.right = ''; + this.svg.style.left = 0 + 'px'; + this.svg.style.right = ''; + } else { + this.dom.frame.style.right = '4px'; + this.dom.frame.style.textAlign = 'right'; + this.dom.textArea.style.textAlign = 'right'; + this.dom.textArea.style.right = this.options.iconSize + 15 + 'px'; + this.dom.textArea.style.left = ''; + this.svg.style.right = 0 + 'px'; + this.svg.style.left = ''; + } - utils_hooks__hooks.fn = momentPrototype; - utils_hooks__hooks.min = min; - utils_hooks__hooks.max = max; - utils_hooks__hooks.utc = create_utc__createUTC; - utils_hooks__hooks.unix = moment__createUnix; - utils_hooks__hooks.months = lists__listMonths; - utils_hooks__hooks.isDate = isDate; - utils_hooks__hooks.locale = locale_locales__getSetGlobalLocale; - utils_hooks__hooks.invalid = valid__createInvalid; - utils_hooks__hooks.duration = create__createDuration; - utils_hooks__hooks.isMoment = isMoment; - utils_hooks__hooks.weekdays = lists__listWeekdays; - utils_hooks__hooks.parseZone = moment__createInZone; - utils_hooks__hooks.localeData = locale_locales__getLocale; - utils_hooks__hooks.isDuration = isDuration; - utils_hooks__hooks.monthsShort = lists__listMonthsShort; - utils_hooks__hooks.weekdaysMin = lists__listWeekdaysMin; - utils_hooks__hooks.defineLocale = defineLocale; - utils_hooks__hooks.weekdaysShort = lists__listWeekdaysShort; - utils_hooks__hooks.normalizeUnits = normalizeUnits; - utils_hooks__hooks.relativeTimeThreshold = duration_humanize__getSetRelativeTimeThreshold; + if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'top-right') { + this.dom.frame.style.top = 4 - Number(this.body.dom.center.style.top.replace('px', '')) + 'px'; + this.dom.frame.style.bottom = ''; + } else { + var scrollableHeight = this.body.domProps.center.height - this.body.domProps.centerContainer.height; + this.dom.frame.style.bottom = 4 + scrollableHeight + Number(this.body.dom.center.style.top.replace('px', '')) + 'px'; + this.dom.frame.style.top = ''; + } - var _moment = utils_hooks__hooks; + if (this.options.icons == false) { + this.dom.frame.style.width = this.dom.textArea.offsetWidth + 10 + 'px'; + this.dom.textArea.style.right = ''; + this.dom.textArea.style.left = ''; + this.svg.style.width = '0px'; + } else { + this.dom.frame.style.width = this.options.iconSize + 15 + this.dom.textArea.offsetWidth + 10 + 'px'; + this.drawLegendIcons(); + } - return _moment; + var content = ''; + for (var i = 0; i < groupArray.length; i++) { + var groupId = groupArray[i]; + if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { + content += this.groups[groupId].content + '
'; + } + } + this.dom.textArea.innerHTML = content; + this.dom.textArea.style.lineHeight = 0.75 * this.options.iconSize + this.options.iconSpacing + 'px'; + } + }; - })); - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) + Legend.prototype.drawLegendIcons = function () { + if (this.dom.frame.parentNode) { + var groupArray = Object.keys(this.groups); + groupArray.sort(function (a, b) { + return a < b ? -1 : 1; + }); -/***/ }, -/* 19 */ -/***/ function(module, exports, __webpack_require__) { + DOMutil.prepareElements(this.svgElements); + var padding = window.getComputedStyle(this.dom.frame).paddingTop; + var iconOffset = Number(padding.replace('px', '')); + var x = iconOffset; + var iconWidth = this.options.iconSize; + var iconHeight = 0.75 * this.options.iconSize; + var y = iconOffset + 0.5 * iconHeight + 3; - module.exports = function(module) { - if(!module.webpackPolyfill) { - module.deprecate = function() {}; - module.paths = []; - // module.parent = undefined by default - module.children = []; - module.webpackPolyfill = 1; - } - return module; - } + this.svg.style.width = iconWidth + 5 + iconOffset + 'px'; + + for (var i = 0; i < groupArray.length; i++) { + var groupId = groupArray[i]; + if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { + this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight); + y += iconHeight + this.options.iconSpacing; + } + } + + DOMutil.cleanupElements(this.svgElements); + } + }; + module.exports = Legend; /***/ }, -/* 20 */ +/* 34 */ /***/ function(module, exports, __webpack_require__) { - /* WEBPACK VAR INJECTION */(function(global) {'use strict'; + 'use strict'; - var _rng; + var util = __webpack_require__(2); + var DOMutil = __webpack_require__(3); + var DataSet = __webpack_require__(4); + var DataView = __webpack_require__(5); + var Component = __webpack_require__(25); + var DataAxis = __webpack_require__(28); + var GraphGroup = __webpack_require__(29); + var Legend = __webpack_require__(33); + var BarFunctions = __webpack_require__(52); + var LineFunctions = __webpack_require__(51); - var globalVar = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : null; + var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items - if (globalVar && globalVar.crypto && crypto.getRandomValues) { - // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto - // Moderately fast, high quality - var _rnds8 = new Uint8Array(16); - _rng = function whatwgRNG() { - crypto.getRandomValues(_rnds8); - return _rnds8; - }; - } + /** + * This is the constructor of the LineGraph. It requires a Timeline body and options. + * + * @param body + * @param options + * @constructor + */ + function LineGraph(body, options) { + this.id = util.randomUUID(); + this.body = body; - if (!_rng) { - // Math.random()-based (RNG) - // - // If all else fails, use Math.random(). It's fast, but is of unspecified - // quality. - var _rnds = new Array(16); - _rng = function () { - for (var i = 0, r; i < 16; i++) { - if ((i & 3) === 0) r = Math.random() * 4294967296; - _rnds[i] = r >>> ((i & 3) << 3) & 255; + this.defaultOptions = { + yAxisOrientation: 'left', + defaultGroup: 'default', + sort: true, + sampling: true, + stack: false, + graphHeight: '400px', + shaded: { + enabled: false, + orientation: 'bottom' // top, bottom + }, + style: 'line', // line, bar + barChart: { + width: 50, + sideBySide: false, + align: 'center' // left, center, right + }, + interpolation: { + enabled: true, + parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) + alpha: 0.5 + }, + drawPoints: { + enabled: true, + size: 6, + style: 'square' // square, circle + }, + dataAxis: { + showMinorLabels: true, + showMajorLabels: true, + icons: false, + width: '40px', + visible: true, + alignZeros: true, + left: { + range: { min: undefined, max: undefined }, + format: function format(value) { + return value; + }, + title: { text: undefined, style: undefined } + }, + right: { + range: { min: undefined, max: undefined }, + format: function format(value) { + return value; + }, + title: { text: undefined, style: undefined } + } + }, + legend: { + enabled: false, + icons: true, + left: { + visible: true, + position: 'top-left' // top/bottom - left,right + }, + right: { + visible: true, + position: 'top-right' // top/bottom - left,right + } + }, + groups: { + visibility: {} } - - return _rnds; }; - } - - // uuid.js - // - // Copyright (c) 2010-2012 Robert Kieffer - // MIT License - http://opensource.org/licenses/mit-license.php - - // Unique ID creation requires a high quality random # generator. We feature - // detect to determine the best RNG source, normalizing to a function that - // returns 128-bits of randomness, since that's what's usually required - //var _rng = require('./rng'); + // options is shared by this ItemSet and all its items + this.options = util.extend({}, this.defaultOptions); + this.dom = {}; + this.props = {}; + this.hammer = null; + this.groups = {}; + this.abortedGraphUpdate = false; + this.updateSVGheight = false; + this.updateSVGheightOnResize = false; - // Maps for number <-> hex string conversion - var _byteToHex = []; - var _hexToByte = {}; - for (var i = 0; i < 256; i++) { - _byteToHex[i] = (i + 256).toString(16).substr(1); - _hexToByte[_byteToHex[i]] = i; - } + var me = this; + this.itemsData = null; // DataSet + this.groupsData = null; // DataSet - // **`parse()` - Parse a UUID into it's component bytes** - function parse(s, buf, offset) { - var i = buf && offset || 0, - ii = 0; + // listeners for the DataSet of the items + this.itemListeners = { + 'add': function add(event, params, senderId) { + me._onAdd(params.items); + }, + 'update': function update(event, params, senderId) { + me._onUpdate(params.items); + }, + 'remove': function remove(event, params, senderId) { + me._onRemove(params.items); + } + }; - buf = buf || []; - s.toLowerCase().replace(/[0-9a-f]{2}/g, function (oct) { - if (ii < 16) { - // Don't overflow! - buf[i + ii++] = _hexToByte[oct]; + // listeners for the DataSet of the groups + this.groupListeners = { + 'add': function add(event, params, senderId) { + me._onAddGroups(params.items); + }, + 'update': function update(event, params, senderId) { + me._onUpdateGroups(params.items); + }, + 'remove': function remove(event, params, senderId) { + me._onRemoveGroups(params.items); } - }); + }; - // Zero out remaining bytes if string was short - while (ii < 16) { - buf[i + ii++] = 0; - } + this.items = {}; // object with an Item for every data item + this.selection = []; // list with the ids of all selected nodes + this.lastStart = this.body.range.start; + this.touchParams = {}; // stores properties while dragging - return buf; - } + this.svgElements = {}; + this.setOptions(options); + this.groupsUsingDefaultStyles = [0]; + this.COUNTER = 0; + this.body.emitter.on('rangechanged', function () { + me.lastStart = me.body.range.start; + me.svg.style.left = util.option.asSize(-me.props.width); + me.redraw.call(me, true); + }); - // **`unparse()` - Convert UUID byte array (ala parse()) into a string** - function unparse(buf, offset) { - var i = offset || 0, - bth = _byteToHex; - return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]]; + // create the HTML DOM + this._create(); + this.framework = { svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups }; + this.body.emitter.emit('change'); } - // **`v1()` - Generate time-based UUID** - // - // Inspired by https://github.com/LiosK/UUID.js - // and http://docs.python.org/library/uuid.html - - // random #'s we need to init node and clockseq - var _seedBytes = _rng(); + LineGraph.prototype = new Component(); - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - var _nodeId = [_seedBytes[0] | 1, _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]]; + /** + * Create the HTML DOM for the ItemSet + */ + LineGraph.prototype._create = function () { + var frame = document.createElement('div'); + frame.className = 'vis-line-graph'; + this.dom.frame = frame; - // Per 4.2.2, randomize (14 bit) clockseq - var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 16383; + // create svg element for graph drawing. + this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + this.svg.style.position = 'relative'; + this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px'; + this.svg.style.display = 'block'; + frame.appendChild(this.svg); - // Previous uuid creation time - var _lastMSecs = 0, - _lastNSecs = 0; + // data axis + this.options.dataAxis.orientation = 'left'; + this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups); - // See https://github.com/broofa/node-uuid for API details - function v1(options, buf, offset) { - var i = buf && offset || 0; - var b = buf || []; + this.options.dataAxis.orientation = 'right'; + this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups); + delete this.options.dataAxis.orientation; - options = options || {}; + // legends + this.legendLeft = new Legend(this.body, this.options.legend, 'left', this.options.groups); + this.legendRight = new Legend(this.body, this.options.legend, 'right', this.options.groups); - var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; + this.show(); + }; - // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); + /** + * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element. + * @param {object} options + */ + LineGraph.prototype.setOptions = function (options) { + if (options) { + var fields = ['sampling', 'defaultGroup', 'stack', 'height', 'graphHeight', 'yAxisOrientation', 'style', 'barChart', 'dataAxis', 'sort', 'groups']; + if (options.graphHeight === undefined && options.height !== undefined && this.body.domProps.centerContainer.height !== undefined) { + this.updateSVGheight = true; + this.updateSVGheightOnResize = true; + } else if (this.body.domProps.centerContainer.height !== undefined && options.graphHeight !== undefined) { + if (parseInt((options.graphHeight + '').replace('px', '')) < this.body.domProps.centerContainer.height) { + this.updateSVGheight = true; + } + } + util.selectiveDeepExtend(fields, this.options, options); + util.mergeOptions(this.options, options, 'interpolation'); + util.mergeOptions(this.options, options, 'drawPoints'); + util.mergeOptions(this.options, options, 'shaded'); + util.mergeOptions(this.options, options, 'legend'); - // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; + if (options.interpolation) { + if (typeof options.interpolation == 'object') { + if (options.interpolation.parametrization) { + if (options.interpolation.parametrization == 'uniform') { + this.options.interpolation.alpha = 0; + } else if (options.interpolation.parametrization == 'chordal') { + this.options.interpolation.alpha = 1; + } else { + this.options.interpolation.parametrization = 'centripetal'; + this.options.interpolation.alpha = 0.5; + } + } + } + } - // Time since last uuid creation (in msecs) - var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; + if (this.yAxisLeft) { + if (options.dataAxis !== undefined) { + this.yAxisLeft.setOptions(this.options.dataAxis); + this.yAxisRight.setOptions(this.options.dataAxis); + } + } - // Per 4.2.1.2, Bump clockseq on clock regression - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 16383; - } + if (this.legendLeft) { + if (options.legend !== undefined) { + this.legendLeft.setOptions(this.options.legend); + this.legendRight.setOptions(this.options.legend); + } + } - // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; + if (this.groups.hasOwnProperty(UNGROUPED)) { + this.groups[UNGROUPED].setOptions(options); + } } - // Per 4.2.1.2 Throw error if too many uuids are requested - if (nsecs >= 10000) { - throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + // this is used to redraw the graph if the visibility of the groups is changed. + if (this.dom.frame) { + this.redraw(true); } + }; - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; - - // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000; - - // `time_low` - var tl = ((msecs & 268435455) * 10000 + nsecs) % 4294967296; - b[i++] = tl >>> 24 & 255; - b[i++] = tl >>> 16 & 255; - b[i++] = tl >>> 8 & 255; - b[i++] = tl & 255; - - // `time_mid` - var tmh = msecs / 4294967296 * 10000 & 268435455; - b[i++] = tmh >>> 8 & 255; - b[i++] = tmh & 255; - - // `time_high_and_version` - b[i++] = tmh >>> 24 & 15 | 16; // include version - b[i++] = tmh >>> 16 & 255; + /** + * Hide the component from the DOM + */ + LineGraph.prototype.hide = function () { + // remove the frame containing the items + if (this.dom.frame.parentNode) { + this.dom.frame.parentNode.removeChild(this.dom.frame); + } + }; - // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - b[i++] = clockseq >>> 8 | 128; + /** + * Show the component in the DOM (when not already visible). + * @return {Boolean} changed + */ + LineGraph.prototype.show = function () { + // show frame containing the items + if (!this.dom.frame.parentNode) { + this.body.dom.center.appendChild(this.dom.frame); + } + }; - // `clock_seq_low` - b[i++] = clockseq & 255; + /** + * Set items + * @param {vis.DataSet | null} items + */ + LineGraph.prototype.setItems = function (items) { + var me = this, + ids, + oldItemsData = this.itemsData; - // `node` - var node = options.node || _nodeId; - for (var n = 0; n < 6; n++) { - b[i + n] = node[n]; + // 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'); } - return buf ? buf : unparse(b); - } + if (oldItemsData) { + // unsubscribe from old dataset + util.forEach(this.itemListeners, function (callback, event) { + oldItemsData.off(event, callback); + }); - // **`v4()` - Generate random UUID** + // remove all drawn items + ids = oldItemsData.getIds(); + this._onRemove(ids); + } - // See https://github.com/broofa/node-uuid for API details - function v4(options, buf, offset) { - // Deprecated - 'format' argument, as supported in v1.2 - var i = buf && offset || 0; + if (this.itemsData) { + // subscribe to new dataset + var id = this.id; + util.forEach(this.itemListeners, function (callback, event) { + me.itemsData.on(event, callback, id); + }); - if (typeof options == 'string') { - buf = options == 'binary' ? new Array(16) : null; - options = null; + // add all new items + ids = this.itemsData.getIds(); + this._onAdd(ids); } - options = options || {}; + this._updateUngrouped(); + //this._updateGraph(); + this.redraw(true); + }; - var rnds = options.random || (options.rng || _rng)(); + /** + * Set groups + * @param {vis.DataSet} groups + */ + LineGraph.prototype.setGroups = function (groups) { + var me = this; + var ids; - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = rnds[6] & 15 | 64; - rnds[8] = rnds[8] & 63 | 128; + // unsubscribe from current dataset + if (this.groupsData) { + util.forEach(this.groupListeners, function (callback, event) { + me.groupsData.off(event, callback); + }); - // Copy bytes to buffer, if provided - if (buf) { - for (var ii = 0; ii < 16; ii++) { - buf[i + ii] = rnds[ii]; - } + // remove all drawn groups + ids = this.groupsData.getIds(); + this.groupsData = null; + this._onRemoveGroups(ids); // note: this will cause a redraw } - return buf || unparse(rnds); - } - - // Export public API - var uuid = v4; - uuid.v1 = v1; - uuid.v4 = v4; - uuid.parse = parse; - uuid.unparse = unparse; - - module.exports = uuid; - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + // 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'); + } -/***/ }, -/* 21 */ -/***/ function(module, exports, __webpack_require__) { + if (this.groupsData) { + // subscribe to new dataset + var id = this.id; + util.forEach(this.groupListeners, function (callback, event) { + me.groupsData.on(event, callback, id); + }); - // DOM utility methods + // draw all ms + ids = this.groupsData.getIds(); + this._onAddGroups(ids); + } + this._onUpdate(); + }; /** - * this prepares the JSON container for allocating SVG elements - * @param JSONcontainer + * Update the data + * @param [ids] * @private */ - 'use strict'; - - 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 = []; - } + LineGraph.prototype._onUpdate = function (ids) { + this._updateUngrouped(); + this._updateAllGroupData(); + //this._updateGraph(); + this.redraw(true); + }; + LineGraph.prototype._onAdd = function (ids) { + this._onUpdate(ids); + }; + LineGraph.prototype._onRemove = function (ids) { + this._onUpdate(ids); + }; + LineGraph.prototype._onUpdateGroups = function (groupIds) { + for (var i = 0; i < groupIds.length; i++) { + var group = this.groupsData.get(groupIds[i]); + this._updateGroup(group, groupIds[i]); } + + //this._updateGraph(); + this.redraw(true); + }; + LineGraph.prototype._onAddGroups = function (groupIds) { + this._onUpdateGroups(groupIds); }; /** - * 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 JSONcontainer + * this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph + * @param {Array} groupIds * @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 = []; + LineGraph.prototype._onRemoveGroups = function (groupIds) { + for (var i = 0; i < groupIds.length; i++) { + if (this.groups.hasOwnProperty(groupIds[i])) { + if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') { + this.yAxisRight.removeGroup(groupIds[i]); + this.legendRight.removeGroup(groupIds[i]); + this.legendRight.redraw(); + } else { + this.yAxisLeft.removeGroup(groupIds[i]); + this.legendLeft.removeGroup(groupIds[i]); + this.legendLeft.redraw(); } + delete this.groups[groupIds[i]]; } } + this._updateUngrouped(); + //this._updateGraph(); + this.redraw(true); }; /** - * 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. + * update a group object with the group dataset entree * - * @param elementType - * @param JSONcontainer - * @param svgContainer - * @returns {*} + * @param group + * @param groupId * @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(); + LineGraph.prototype._updateGroup = function (group, groupId) { + if (!this.groups.hasOwnProperty(groupId)) { + this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles); + if (this.groups[groupId].options.yAxisOrientation == 'right') { + this.yAxisRight.addGroup(groupId, this.groups[groupId]); + this.legendRight.addGroup(groupId, this.groups[groupId]); } else { - // create a new element and add it to the SVG - element = document.createElementNS('http://www.w3.org/2000/svg', elementType); - svgContainer.appendChild(element); + this.yAxisLeft.addGroup(groupId, this.groups[groupId]); + this.legendLeft.addGroup(groupId, this.groups[groupId]); } } 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); + this.groups[groupId].update(group); + if (this.groups[groupId].options.yAxisOrientation == 'right') { + this.yAxisRight.updateGroup(groupId, this.groups[groupId]); + this.legendRight.updateGroup(groupId, this.groups[groupId]); + } else { + this.yAxisLeft.updateGroup(groupId, this.groups[groupId]); + this.legendLeft.updateGroup(groupId, this.groups[groupId]); + } } - JSONcontainer[elementType].used.push(element); - return element; + this.legendLeft.redraw(); + this.legendRight.redraw(); }; /** - * 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. + * this updates all groups, it is used when there is an update the the itemset. * - * @param elementType - * @param JSONcontainer - * @param DOMContainer - * @returns {*} * @private */ - 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); + LineGraph.prototype._updateAllGroupData = function () { + if (this.itemsData != null) { + var groupsContent = {}; + var groupId; + for (groupId in this.groups) { + if (this.groups.hasOwnProperty(groupId)) { + groupsContent[groupId] = []; } } - } 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); + for (var itemId in this.itemsData._data) { + if (this.itemsData._data.hasOwnProperty(itemId)) { + var item = this.itemsData._data[itemId]; + if (groupsContent[item.group] === undefined) { + throw new Error('Cannot find referenced group. Possible reason: items added before groups? Groups need to be added before items, as items refer to groups.'); + } + item.x = util.convert(item.x, 'Date'); + groupsContent[item.group].push(item); + } + } + for (groupId in this.groups) { + if (this.groups.hasOwnProperty(groupId)) { + this.groups[groupId].setItems(groupsContent[groupId]); + } } } - JSONcontainer[elementType].used.push(element); - return element; }; /** - * draw a point object. this is a seperate 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 x - * @param y - * @param group - * @param JSONcontainer - * @param svgContainer - * @param labelObj - * @returns {*} + * Create or delete the group holding all ungrouped items. This group is used when + * there are no groups specified. This anonymous group is called 'graph'. + * @protected */ - exports.drawPoint = function (x, y, group, JSONcontainer, svgContainer, labelObj) { - var point; - if (group.options.drawPoints.style == 'circle') { - point = exports.getSVGElement('circle', JSONcontainer, svgContainer); - point.setAttributeNS(null, 'cx', x); - point.setAttributeNS(null, 'cy', y); - point.setAttributeNS(null, 'r', 0.5 * group.options.drawPoints.size); - } else { - point = exports.getSVGElement('rect', JSONcontainer, svgContainer); - point.setAttributeNS(null, 'x', x - 0.5 * group.options.drawPoints.size); - point.setAttributeNS(null, 'y', y - 0.5 * group.options.drawPoints.size); - point.setAttributeNS(null, 'width', group.options.drawPoints.size); - point.setAttributeNS(null, 'height', group.options.drawPoints.size); - } - - if (group.options.drawPoints.styles !== undefined) { - point.setAttributeNS(null, 'style', group.group.options.drawPoints.styles); - } - point.setAttributeNS(null, 'class', group.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; + LineGraph.prototype._updateUngrouped = function () { + if (this.itemsData && this.itemsData != null) { + var ungroupedCounter = 0; + for (var itemId in this.itemsData._data) { + if (this.itemsData._data.hasOwnProperty(itemId)) { + var item = this.itemsData._data[itemId]; + if (item != undefined) { + if (item.hasOwnProperty('group')) { + if (item.group === undefined) { + item.group = UNGROUPED; + } + } else { + item.group = UNGROUPED; + } + ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter; + } + } } - if (labelObj.className) { - label.setAttributeNS(null, 'class', labelObj.className + ' vis-label'); + if (ungroupedCounter == 0) { + delete this.groups[UNGROUPED]; + this.legendLeft.removeGroup(UNGROUPED); + this.legendRight.removeGroup(UNGROUPED); + this.yAxisLeft.removeGroup(UNGROUPED); + this.yAxisRight.removeGroup(UNGROUPED); + } else { + var group = { id: UNGROUPED, content: this.options.defaultGroup }; + this._updateGroup(group, UNGROUPED); } - label.setAttributeNS(null, 'x', x); - label.setAttributeNS(null, 'y', y); + } else { + delete this.groups[UNGROUPED]; + this.legendLeft.removeGroup(UNGROUPED); + this.legendRight.removeGroup(UNGROUPED); + this.yAxisLeft.removeGroup(UNGROUPED); + this.yAxisRight.removeGroup(UNGROUPED); } - return point; + this.legendLeft.redraw(); + this.legendRight.redraw(); }; /** - * draw a bar SVG element centered on the X coordinate - * - * @param x - * @param y - * @param className + * Redraw the component, mandatory function + * @return {boolean} Returns true if the component is resized */ - 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); - } - } - }; + LineGraph.prototype.redraw = function (forceGraphUpdate) { + var resized = false; -/***/ }, -/* 22 */ -/***/ function(module, exports, __webpack_require__) { + // calculate actual size and position + this.props.width = this.dom.frame.offsetWidth; + this.props.height = this.body.domProps.centerContainer.height - this.body.domProps.border.top - this.body.domProps.border.bottom; - 'use strict'; + // update the graph if there is no lastWidth or with, used for the initial draw + if (this.lastWidth === undefined && this.props.width) { + forceGraphUpdate = true; + } - var util = __webpack_require__(2); - var Queue = __webpack_require__(23); + // check if this component is resized + resized = this._isResized() || resized; - /** - * DataSet - * - * 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. 0) { + // this is the range of the SVG canvas + var minDate = this.body.util.toGlobalTime(-this.body.domProps.root.width); + var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width); + var groupsData = {}; + // fill groups data, this only loads the data we require based on the timewindow + this._getRelevantData(groupIds, groupsData, minDate, maxDate); + + // apply sampling, if disabled, it will pass through this function. + this._applySampling(groupIds, groupsData); + + // we transform the X coordinates to detect collisions + for (i = 0; i < groupIds.length; i++) { + preprocessedGroupData[groupIds[i]] = this._convertXcoordinates(groupsData[groupIds[i]]); } - if (typeof options.queue === 'object') { - this._queue.setOptions(options.queue); + // now all needed data has been collected we start the processing. + this._getYRanges(groupIds, preprocessedGroupData, groupRanges); + + // update the Y axis first, we use this data to draw at the correct Y points + // changeCalled is required to clean the SVG on a change emit. + changeCalled = this._updateYAxis(groupIds, groupRanges); + var MAX_CYCLES = 5; + if (changeCalled == true && this.COUNTER < MAX_CYCLES) { + DOMutil.cleanupElements(this.svgElements); + this.abortedGraphUpdate = true; + this.COUNTER++; + this.body.emitter.emit('change'); + return true; + } else { + if (this.COUNTER > MAX_CYCLES) { + console.log('WARNING: there may be an infinite loop in the _updateGraph emitter cycle.'); + } + this.COUNTER = 0; + this.abortedGraphUpdate = false; + + // With the yAxis scaled correctly, use this to get the Y values of the points. + for (i = 0; i < groupIds.length; i++) { + group = this.groups[groupIds[i]]; + processedGroupData[groupIds[i]] = this._convertYcoordinates(groupsData[groupIds[i]], group); + } + + // draw the groups + for (i = 0; i < groupIds.length; i++) { + group = this.groups[groupIds[i]]; + if (group.options.style != 'bar') { + // bar needs to be drawn enmasse + group.draw(processedGroupData[groupIds[i]], group, this.framework); + } + } + BarFunctions.draw(groupIds, processedGroupData, this.framework); } } } - }; - - /** - * Subscribe to an event, add an event listener - * @param {String} event Event name. Available events: 'put', 'update', - * 'remove' - * @param {function} callback Callback method. Called with three parameters: - * {String} event - * {Object | null} params - * {String | Number} senderId - */ - DataSet.prototype.on = function (event, callback) { - var subscribers = this._subscribers[event]; - if (!subscribers) { - subscribers = []; - this._subscribers[event] = subscribers; - } - - subscribers.push({ - callback: callback - }); - }; - // TODO: remove this deprecated function some day (replaced with `on` since version 0.5, deprecated since v4.0) - DataSet.prototype.subscribe = function () { - throw new Error('DataSet.subscribe is deprecated. Use DataSet.on instead.'); + // cleanup unused svg elements + DOMutil.cleanupElements(this.svgElements); + return false; }; /** - * Unsubscribe from an event, remove an event listener - * @param {String} event - * @param {function} callback + * first select and preprocess the data from the datasets. + * the groups have their preselection of data, we now loop over this data to see + * what data we need to draw. Sorted data is much faster. + * more optimization is possible by doing the sampling before and using the binary search + * to find the end date to determine the increment. + * + * @param {array} groupIds + * @param {object} groupsData + * @param {date} minDate + * @param {date} maxDate + * @private */ - DataSet.prototype.off = function (event, callback) { - var subscribers = this._subscribers[event]; - if (subscribers) { - this._subscribers[event] = subscribers.filter(function (listener) { - return listener.callback != callback; - }); + LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) { + var group, i, j, item; + if (groupIds.length > 0) { + for (i = 0; i < groupIds.length; i++) { + group = this.groups[groupIds[i]]; + groupsData[groupIds[i]] = []; + var dataContainer = groupsData[groupIds[i]]; + // optimization for sorted data + if (group.options.sort == true) { + var guess = Math.max(0, util.binarySearchValue(group.itemsData, minDate, 'x', 'before')); + for (j = guess; j < group.itemsData.length; j++) { + item = group.itemsData[j]; + if (item !== undefined) { + if (item.x > maxDate) { + dataContainer.push(item); + break; + } else { + dataContainer.push(item); + } + } + } + } else { + for (j = 0; j < group.itemsData.length; j++) { + item = group.itemsData[j]; + if (item !== undefined) { + if (item.x > minDate && item.x < maxDate) { + dataContainer.push(item); + } + } + } + } + } } }; - // TODO: remove this deprecated function some day (replaced with `on` since version 0.5, deprecated since v4.0) - DataSet.prototype.unsubscribe = function () { - throw new Error('DataSet.unsubscribe is deprecated. Use DataSet.off instead.'); - }; - /** - * Trigger an event - * @param {String} event - * @param {Object | null} params - * @param {String} [senderId] Optional id of the sender. + * + * @param groupIds + * @param groupsData * @private */ - DataSet.prototype._trigger = function (event, params, senderId) { - if (event == '*') { - throw new Error('Cannot trigger event *'); - } + LineGraph.prototype._applySampling = function (groupIds, groupsData) { + var group; + if (groupIds.length > 0) { + for (var i = 0; i < groupIds.length; i++) { + group = this.groups[groupIds[i]]; + if (group.options.sampling == true) { + var dataContainer = groupsData[groupIds[i]]; + if (dataContainer.length > 0) { + var increment = 1; + var amountOfPoints = dataContainer.length; - var subscribers = []; - if (event in this._subscribers) { - subscribers = subscribers.concat(this._subscribers[event]); - } - if ('*' in this._subscribers) { - subscribers = subscribers.concat(this._subscribers['*']); - } + // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop + // of width changing of the yAxis. + var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x); + var pointsPerPixel = amountOfPoints / xDistance; + increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel))); - for (var i = 0; i < subscribers.length; i++) { - var subscriber = subscribers[i]; - if (subscriber.callback) { - subscriber.callback(event, params, senderId || null); + var sampledData = []; + for (var j = 0; j < amountOfPoints; j += increment) { + sampledData.push(dataContainer[j]); + } + groupsData[groupIds[i]] = sampledData; + } + } } } }; /** - * Add data. - * Adding an item will fail when there already is an item with the same id. - * @param {Object | Array} data - * @param {String} [senderId] Optional sender id - * @return {Array} addedIds Array with the ids of the added items + * + * + * @param {array} groupIds + * @param {object} groupsData + * @param {object} groupRanges | this is being filled here + * @private */ - 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); + LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) { + var groupData, group, i; + var combinedDataLeft = []; + var combinedDataRight = []; + var options; + if (groupIds.length > 0) { + for (i = 0; i < groupIds.length; i++) { + groupData = groupsData[groupIds[i]]; + options = this.groups[groupIds[i]].options; + if (groupData.length > 0) { + group = this.groups[groupIds[i]]; + // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups. + if (options.stack === true) { + if (options.yAxisOrientation == 'left') { + combinedDataLeft = combinedDataLeft.concat(group.getData(groupData)); + } else { + combinedDataRight = combinedDataRight.concat(group.getData(groupData)); + } + } else { + groupRanges[groupIds[i]] = group.getYRange(groupData, groupIds[i]); + } + } } - } else if (data instanceof 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); + // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups. + BarFunctions.getStackedYRange(combinedDataLeft, groupRanges, groupIds, '__barStackLeft', 'left'); + BarFunctions.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__barStackRight', 'right'); + // if line graphs are stacked, their range need to be handled differently and accumulated over all groups. + LineFunctions.getStackedYRange(combinedDataLeft, groupRanges, groupIds, '__lineStackLeft', 'left'); + LineFunctions.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__lineStackRight', 'right'); } - - 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 + * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden. + * @param {Array} groupIds + * @param {Object} groupRanges + * @private */ - DataSet.prototype.update = function (data, senderId) { - var addedIds = []; - var updatedIds = []; - var updatedData = []; - var me = this; - var fieldId = me._fieldId; + LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) { + var resized = false; + var yAxisLeftUsed = false; + var yAxisRightUsed = false; + var minLeft = 1000000000, + minRight = 1000000000, + maxLeft = -1000000000, + maxRight = -1000000000, + minVal, + maxVal; + // if groups are present + if (groupIds.length > 0) { + // this is here to make sure that if there are no items in the axis but there are groups, that there is no infinite draw/redraw loop. + for (var i = 0; i < groupIds.length; i++) { + var group = this.groups[groupIds[i]]; + if (group && group.options.yAxisOrientation != 'right') { + yAxisLeftUsed = true; + minLeft = 0; + maxLeft = 0; + } else if (group && group.options.yAxisOrientation) { + yAxisRightUsed = true; + minRight = 0; + maxRight = 0; + } + } - var addOrUpdate = function addOrUpdate(item) { - var id = item[fieldId]; - if (me._data[id]) { - // update item - id = me._updateItem(item); - updatedIds.push(id); - updatedData.push(item); - } else { - // add new item - id = me._addItem(item); - addedIds.push(id); + // if there are items: + for (var i = 0; i < groupIds.length; i++) { + if (groupRanges.hasOwnProperty(groupIds[i])) { + if (groupRanges[groupIds[i]].ignore !== true) { + minVal = groupRanges[groupIds[i]].min; + maxVal = groupRanges[groupIds[i]].max; + + if (groupRanges[groupIds[i]].yAxisOrientation != 'right') { + yAxisLeftUsed = true; + minLeft = minLeft > minVal ? minVal : minLeft; + maxLeft = maxLeft < maxVal ? maxVal : maxLeft; + } else { + yAxisRightUsed = true; + minRight = minRight > minVal ? minVal : minRight; + maxRight = maxRight < maxVal ? maxVal : maxRight; + } + } + } } - }; - if (Array.isArray(data)) { - // Array - for (var i = 0, len = data.length; i < len; i++) { - addOrUpdate(data[i]); + if (yAxisLeftUsed == true) { + this.yAxisLeft.setRange(minLeft, maxLeft); + } + if (yAxisRightUsed == true) { + this.yAxisRight.setRange(minRight, maxRight); } - } else if (data instanceof Object) { - // Single item - addOrUpdate(data); - } else { - throw new Error('Unknown dataType'); } + resized = this._toggleAxisVisiblity(yAxisLeftUsed, this.yAxisLeft) || resized; + resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized; - if (addedIds.length) { - this._trigger('add', { items: addedIds }, senderId); - } - if (updatedIds.length) { - this._trigger('update', { items: updatedIds, data: updatedData }, senderId); + if (yAxisRightUsed == true && yAxisLeftUsed == true) { + this.yAxisLeft.drawIcons = true; + this.yAxisRight.drawIcons = true; + } else { + this.yAxisLeft.drawIcons = false; + this.yAxisRight.drawIcons = false; } + this.yAxisRight.master = !yAxisLeftUsed; + if (this.yAxisRight.master == false) { + if (yAxisRightUsed == true) { + this.yAxisLeft.lineOffset = this.yAxisRight.width; + } else { + this.yAxisLeft.lineOffset = 0; + } - 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. - * @throws Error - */ - DataSet.prototype.get = function (args) { - 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]; + resized = this.yAxisLeft.redraw() || resized; + this.yAxisRight.stepPixels = this.yAxisLeft.stepPixels; + this.yAxisRight.zeroCrossing = this.yAxisLeft.zeroCrossing; + this.yAxisRight.amountOfSteps = this.yAxisLeft.amountOfSteps; + resized = this.yAxisRight.redraw() || resized; } else { - // get([, options]) - options = arguments[0]; + resized = this.yAxisRight.redraw() || resized; } - // 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'; + // clean the accumulated lists + var tempGroups = ['__barStackLeft', '__barStackRight', '__lineStackLeft', '__lineStackRight']; + for (var i = 0; i < tempGroups.length; i++) { + if (groupIds.indexOf(tempGroups[i]) != -1) { + groupIds.splice(groupIds.indexOf(tempGroups[i]), 1); + } } - // build options - var type = options && options.type || this._options.type; - var filter = options && options.filter; - var items = [], - item, - itemId, - i, - len; + return resized; + }; - // convert items - if (id != undefined) { - // return a single item - item = me._getItem(id, type); - if (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); - } + /** + * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function + * + * @param {boolean} axisUsed + * @returns {boolean} + * @private + * @param axis + */ + LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) { + var changed = false; + if (axisUsed == false) { + if (axis.dom.frame.parentNode && axis.hidden == false) { + axis.hide(); + changed = true; } } else { - // return all items - for (itemId in this._data) { - if (this._data.hasOwnProperty(itemId)) { - item = me._getItem(itemId, type); - if (!filter || filter(item)) { - items.push(item); - } - } + if (!axis.dom.frame.parentNode && axis.hidden == true) { + axis.show(); + changed = true; } } + return changed; + }; - // order the results - if (options && options.order && id == undefined) { - this._sort(items, options.order); - } + /** + * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the + * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for + * the yAxis. + * + * @param datapoints + * @returns {Array} + * @private + */ + LineGraph.prototype._convertXcoordinates = function (datapoints) { + var extractedData = []; + var xValue, yValue; + var toScreen = this.body.util.toScreen; - // 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); - } - } + for (var i = 0; i < datapoints.length; i++) { + xValue = toScreen(datapoints[i].x) + this.props.width; + yValue = datapoints[i].y; + extractedData.push({ x: xValue, y: yValue }); } - // return the results - if (returnType == 'Object') { - var result = {}; - for (i = 0; i < items.length; i++) { - result[items[i].id] = items[i]; - } - return result; - } else { - if (id != undefined) { - // a single item - return item; - } else { - // just return our array - return items; - } - } + return extractedData; }; /** - * 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 + * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the + * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for + * the yAxis. + * + * @param datapoints + * @param group + * @returns {Array} + * @private */ - DataSet.prototype.getIds = function (options) { - var data = this._data, - filter = options && options.filter, - order = options && options.order, - type = options && options.type || this._options.type, - i, - len, - id, - item, - items, - ids = []; + LineGraph.prototype._convertYcoordinates = function (datapoints, group) { + var extractedData = []; + var xValue, yValue; + var toScreen = this.body.util.toScreen; + var axis = this.yAxisLeft; + var svgHeight = Number(this.svg.style.height.replace('px', '')); + if (group.options.yAxisOrientation == 'right') { + axis = this.yAxisRight; + } - if (filter) { - // get filtered items - if (order) { - // create ordered list - items = []; - for (id in data) { - if (data.hasOwnProperty(id)) { - item = this._getItem(id, type); - if (filter(item)) { - items.push(item); - } - } - } + for (var i = 0; i < datapoints.length; i++) { + var labelValue = datapoints[i].label ? datapoints[i].label : null; + xValue = toScreen(datapoints[i].x) + this.props.width; + yValue = Math.round(axis.convertValue(datapoints[i].y)); + extractedData.push({ x: xValue, y: yValue, label: labelValue }); + } - this._sort(items, order); + group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0))); - for (i = 0, len = items.length; i < len; i++) { - ids[i] = items[i][this._fieldId]; - } - } else { - // create unordered list - for (id in data) { - if (data.hasOwnProperty(id)) { - 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 (id in data) { - if (data.hasOwnProperty(id)) { - items.push(data[id]); - } - } + return extractedData; + }; - this._sort(items, order); + module.exports = LineGraph; - for (i = 0, len = items.length; i < len; i++) { - ids[i] = items[i][this._fieldId]; - } - } else { - // create unordered list - for (id in data) { - if (data.hasOwnProperty(id)) { - item = data[id]; - ids.push(item[this._fieldId]); - } - } - } - } +/***/ }, +/* 35 */ +/***/ function(module, exports, __webpack_require__) { - return ids; - }; + 'use strict'; + + var util = __webpack_require__(2); + var Component = __webpack_require__(25); + var TimeStep = __webpack_require__(20); + var DateUtil = __webpack_require__(16); + var moment = __webpack_require__(40); /** - * Returns the DataSet itself. Is overwritten for example by the DataView, - * which returns the DataSet it is connected to instead. + * 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 */ - DataSet.prototype.getDataSet = function () { - return this; - }; + 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, + format: TimeStep.FORMAT, + timeAxis: null + }; + this.options = util.extend({}, this.defaultOptions); + + this.body = body; + + // create the HTML DOM + this._create(); + + this.setOptions(options); + } + + TimeAxis.prototype = new Component(); /** - * 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. + * Set options for the TimeAxis. + * Parameters will be merged in current options. + * @param {Object} options Available options: + * {string} [orientation.axis] + * {boolean} [showMinorLabels] + * {boolean} [showMajorLabels] */ - DataSet.prototype.forEach = function (callback, options) { - var filter = options && options.filter, - type = options && options.type || this._options.type, - data = this._data, - item, - id; + TimeAxis.prototype.setOptions = function (options) { + if (options) { + // copy all options that we know + util.selectiveExtend(['showMinorLabels', 'showMajorLabels', 'hiddenDates', 'timeAxis'], this.options, options); - if (options && options.order) { - // execute forEach on ordered list - var items = this.get(options); + // deep copy the format options + util.selectiveDeepExtend(['format'], this.options, options); - for (var i = 0, len = items.length; i < len; i++) { - item = items[i]; - id = item[this._fieldId]; - callback(item, id); + if ('orientation' in options) { + if (typeof options.orientation === 'string') { + this.options.orientation.axis = options.orientation; + } else if (typeof options.orientation === 'object' && 'axis' in options.orientation) { + this.options.orientation.axis = options.orientation.axis; + } } - } else { - // unordered - for (id in data) { - if (data.hasOwnProperty(id)) { - item = this._getItem(id, type); - if (!filter || filter(item)) { - callback(item, id); - } + + // 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); } } } }; /** - * 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 + * Create the HTML DOM for the TimeAxis */ - DataSet.prototype.map = function (callback, options) { - var filter = options && options.filter, - type = options && options.type || this._options.type, - mappedItems = [], - data = this._data, - item; + TimeAxis.prototype._create = function () { + this.dom.foreground = document.createElement('div'); + this.dom.background = document.createElement('div'); - // convert and filter items - for (var id in data) { - if (data.hasOwnProperty(id)) { - item = this._getItem(id, type); - if (!filter || filter(item)) { - mappedItems.push(callback(item, id)); - } - } - } + this.dom.foreground.className = 'vis-time-axis vis-foreground'; + this.dom.background.className = 'vis-time-axis vis-background'; + }; - // order items - if (options && options.order) { - this._sort(mappedItems, options.order); + /** + * 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); } - return mappedItems; + this.body = null; }; /** - * 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 + * Repaint the component + * @return {boolean} Returns true if the component is resized */ - DataSet.prototype._filterFields = function (item, fields) { - if (!item) { - // item is null - return item; - } + TimeAxis.prototype.redraw = function () { + var options = this.options; + var props = this.props; + var foreground = this.dom.foreground; + var background = this.dom.background; - var filteredItem = {}; + // determine the correct parent DOM element (depending on option orientation) + var parent = options.orientation.axis == 'top' ? this.body.dom.top : this.body.dom.bottom; + var parentChanged = foreground.parentNode !== parent; - if (Array.isArray(fields)) { - for (var field in item) { - if (item.hasOwnProperty(field) && fields.indexOf(field) != -1) { - filteredItem[field] = item[field]; - } - } + // 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; + var showMajorLabels = this.options.showMajorLabels; + + // 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 - (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 { - for (var field in item) { - if (item.hasOwnProperty(field) && fields.hasOwnProperty(field)) { - filteredItem[fields[field]] = item[field]; - } - } + parent.appendChild(foreground); + } + if (backgroundNextSibling) { + this.body.dom.backgroundVertical.insertBefore(background, backgroundNextSibling); + } else { + this.body.dom.backgroundVertical.appendChild(background); } - return filteredItem; + return this._isResized() || parentChanged; }; /** - * Sort the provided array with items - * @param {Object[]} items - * @param {String | function} order A field name or custom sort function. + * Repaint major and minor text labels and vertical grid lines * @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'); - } - }; + TimeAxis.prototype._repaintLabels = function () { + var orientation = this.options.orientation.axis; - /** - * 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 = [], - i, - len, - removedId; + // 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) * 7).valueOf(); + var minimumStep = timeLabelsize - DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this.body.range, timeLabelsize); + minimumStep -= this.body.util.toTime(0).valueOf(); - if (Array.isArray(id)) { - for (i = 0, len = id.length; i < len; i++) { - removedId = this._remove(id[i]); - if (removedId != null) { - removedIds.push(removedId); - } - } - } else { - removedId = this._remove(id); - if (removedId != null) { - removedIds.push(removedId); - } + var step = new TimeStep(new Date(start), new Date(end), minimumStep, this.body.hiddenDates); + if (this.options.format) { + step.setFormat(this.options.format); } - - if (removedIds.length) { - this._trigger('remove', { items: removedIds }, senderId); + if (this.options.timeAxis) { + step.setScale(this.options.timeAxis); } + this.step = step; - 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) { - if (util.isNumber(id) || util.isString(id)) { - if (this._data[id]) { - delete this._data[id]; - this.length--; - return id; - } - } else if (id instanceof Object) { - var itemId = id[this._fieldId]; - if (itemId && this._data[itemId]) { - delete this._data[itemId]; - this.length--; - return itemId; - } - } - return null; - }; + // 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 = []; - /** - * Clear the data - * @param {String} [senderId] Optional sender id - * @return {Array} removedIds The ids of all removed items - */ - DataSet.prototype.clear = function (senderId) { - var ids = Object.keys(this._data); + var cur; + var x = 0; + var isMajor; + var xPrev = 0; + var width = 0; + var prevLine; + var xFirstMajorLabel = undefined; + var max = 0; + var className; - this._data = {}; - this.length = 0; + step.first(); + while (step.hasNext() && max < 1000) { + max++; - this._trigger('remove', { items: ids }, senderId); + cur = step.getCurrent(); + isMajor = step.isMajor(); + className = step.getClassName(); - return ids; - }; + xPrev = x; + x = this.body.util.toScreen(cur); + width = x - xPrev; + if (prevLine) { + prevLine.style.width = width + 'px'; + } - /** - * 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, - max = null, - maxField = null; + if (this.options.showMinorLabels) { + this._repaintMinorText(x, step.getLabelMinor(), orientation, className); + } - for (var id in data) { - if (data.hasOwnProperty(id)) { - var item = data[id]; - var itemField = item[field]; - if (itemField != null && (!max || itemField > maxField)) { - max = item; - maxField = itemField; + if (isMajor && this.options.showMajorLabels) { + if (x > 0) { + if (xFirstMajorLabel == undefined) { + xFirstMajorLabel = x; + } + this._repaintMajorText(x, step.getLabelMajor(), orientation, className); } + prevLine = this._repaintMajorLine(x, orientation, className); + } else { + prevLine = this._repaintMinorLine(x, orientation, className); } + + step.next(); } - return max; + // 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); + } + } + }); }; /** - * 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 + * 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 + * @private */ - DataSet.prototype.min = function (field) { - var data = this._data, - min = null, - minField = null; + TimeAxis.prototype._repaintMinorText = function (x, text, orientation, className) { + // reuse redundant label + var label = this.dom.redundant.minorTexts.shift(); - for (var id in data) { - if (data.hasOwnProperty(id)) { - var item = data[id]; - var itemField = item[field]; - if (itemField != null && (!min || itemField < minField)) { - min = item; - minField = itemField; - } - } + 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); - return min; + label.childNodes[0].nodeValue = text; + + label.style.top = orientation == 'top' ? this.props.majorLabelHeight + 'px' : '0'; + label.style.left = x + 'px'; + label.className = 'vis-text vis-minor ' + className; + //label.title = title; // TODO: this is a heavy operation }; /** - * 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. + * 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 + * @private */ - DataSet.prototype.distinct = function (field) { - var data = this._data; - var values = []; - var fieldType = this._options.type && this._options.type[field] || null; - var count = 0; - var i; + TimeAxis.prototype._repaintMajorText = function (x, text, orientation, className) { + // reuse redundant label + var label = this.dom.redundant.majorTexts.shift(); - for (var prop in data) { - if (data.hasOwnProperty(prop)) { - var item = data[prop]; - var value = item[field]; - var exists = false; - for (i = 0; i < count; i++) { - if (values[i] == value) { - exists = true; - break; - } - } - if (!exists && value !== undefined) { - values[count] = value; - count++; - } - } + if (!label) { + // create label + var content = document.createTextNode(text); + label = document.createElement('div'); + label.appendChild(content); + this.dom.foreground.appendChild(label); } + this.dom.majorTexts.push(label); - if (fieldType) { - for (i = 0; i < values.length; i++) { - values[i] = util.convert(values[i], fieldType); - } - } + label.childNodes[0].nodeValue = text; + label.className = 'vis-text vis-major ' + className; + //label.title = title; // TODO: this is a heavy operation - return values; + label.style.top = orientation == 'top' ? '0' : this.props.minorLabelHeight + 'px'; + label.style.left = x + 'px'; }; /** - * Add a single item. Will fail when an item with the same id already exists. - * @param {Object} item - * @return {String} id + * Create a minor line for the axis at position x + * @param {Number} x + * @param {String} orientation "top" or "bottom" (default) + * @param {String} className + * @return {Element} Returns the created line * @private */ - DataSet.prototype._addItem = function (item) { - var id = item[this._fieldId]; + TimeAxis.prototype._repaintMinorLine = function (x, 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); - 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'); - } + var props = this.props; + if (orientation == 'top') { + line.style.top = props.majorLabelHeight + 'px'; } else { - // generate an id - id = util.randomUUID(); - item[this._fieldId] = id; + line.style.top = this.body.domProps.top.height + 'px'; } + line.style.height = props.minorLineHeight + 'px'; + line.style.left = x - props.minorLineWidth / 2 + 'px'; - var d = {}; - for (var field in item) { - if (item.hasOwnProperty(field)) { - var fieldType = this._type[field]; // type may be undefined - d[field] = util.convert(item[field], fieldType); - } - } - this._data[id] = d; - this.length++; + line.className = 'vis-grid vis-vertical vis-minor ' + className; - return id; + return line; }; /** - * 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 + * Create a Major line for the axis at position x + * @param {Number} x + * @param {String} orientation "top" or "bottom" (default) + * @param {String} className + * @return {Element} Returns the created line * @private */ - DataSet.prototype._getItem = function (id, types) { - var field, value; - - // get the item from the dataset - var raw = this._data[id]; - if (!raw) { - return null; + TimeAxis.prototype._repaintMajorLine = function (x, 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); - // convert the items field types - var converted = {}; - if (types) { - for (field in raw) { - if (raw.hasOwnProperty(field)) { - value = raw[field]; - converted[field] = util.convert(value, types[field]); - } - } + var props = this.props; + if (orientation == 'top') { + line.style.top = '0'; } else { - // no field types specified, no converting needed - for (field in raw) { - if (raw.hasOwnProperty(field)) { - value = raw[field]; - converted[field] = value; - } - } + line.style.top = this.body.domProps.top.height + 'px'; } - return converted; + line.style.left = x - props.majorLineWidth / 2 + 'px'; + line.style.height = props.majorLineHeight + 'px'; + + line.className = 'vis-grid vis-vertical vis-major ' + className; + + return line; }; /** - * 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 + * 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 */ - DataSet.prototype._updateItem = function (item) { - var id = item[this._fieldId]; - if (id == undefined) { - throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')'); - } - var d = this._data[id]; - if (!d) { - // item doesn't exist - throw new Error('Cannot update item: no item with id ' + id + ' found'); - } + 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. - // merge with current item - for (var field in item) { - if (item.hasOwnProperty(field)) { - var fieldType = this._type[field]; // type may be undefined - d[field] = util.convert(item[field], fieldType); - } + // 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; - return id; + // 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; }; - module.exports = DataSet; + module.exports = TimeAxis; /***/ }, -/* 23 */ +/* 36 */ /***/ function(module, exports, __webpack_require__) { - /** - * 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 - */ + // Load custom shapes into CanvasRenderingContext2D 'use strict'; - function Queue(options) { - // options - this.delay = null; - this.max = Infinity; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - // properties - this._queue = []; - this._timeout = null; - this._extended = null; + var _modulesGroups = __webpack_require__(54); - this.setOptions(options); - } + var _modulesGroups2 = _interopRequireDefault(_modulesGroups); - /** - * 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. - * @param options - */ - 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; - } + var _modulesNodesHandler = __webpack_require__(55); - this._flushIfNeeded(); - }; + var _modulesNodesHandler2 = _interopRequireDefault(_modulesNodesHandler); - /** - * 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); + var _modulesEdgesHandler = __webpack_require__(56); - if (object.flush !== undefined) { - throw new Error('Target object already has a property flush'); - } - object.flush = function () { - queue.flush(); - }; + var _modulesEdgesHandler2 = _interopRequireDefault(_modulesEdgesHandler); - var methods = [{ - name: 'flush', - original: undefined - }]; + var _modulesPhysicsEngine = __webpack_require__(1); - 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); - } - } + var _modulesPhysicsEngine2 = _interopRequireDefault(_modulesPhysicsEngine); - queue._extended = { - object: object, - methods: methods - }; + var _modulesClustering = __webpack_require__(58); - return queue; - }; + var _modulesClustering2 = _interopRequireDefault(_modulesClustering); - /** - * 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(); + var _modulesCanvasRenderer = __webpack_require__(59); - 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; - } - }; + var _modulesCanvasRenderer2 = _interopRequireDefault(_modulesCanvasRenderer); - /** - * 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'); - } + var _modulesCanvas = __webpack_require__(60); - object[method] = function () { - // create an Array with the arguments - var args = []; - for (var i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } + var _modulesCanvas2 = _interopRequireDefault(_modulesCanvas); - // add this call to the queue - me.queue({ - args: args, - fn: original, - context: this - }); - }; - }; + var _modulesView = __webpack_require__(61); - /** - * 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); - } + var _modulesView2 = _interopRequireDefault(_modulesView); - this._flushIfNeeded(); - }; + var _modulesInteractionHandler = __webpack_require__(62); - /** - * 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(); - } + var _modulesInteractionHandler2 = _interopRequireDefault(_modulesInteractionHandler); - // 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); - } - }; + var _modulesSelectionHandler = __webpack_require__(63); - /** - * 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 || []); - } - }; + var _modulesSelectionHandler2 = _interopRequireDefault(_modulesSelectionHandler); - module.exports = Queue; + var _modulesLayoutEngine = __webpack_require__(64); -/***/ }, -/* 24 */ -/***/ function(module, exports, __webpack_require__) { + var _modulesLayoutEngine2 = _interopRequireDefault(_modulesLayoutEngine); - 'use strict'; + var _modulesManipulationSystem = __webpack_require__(65); + + var _modulesManipulationSystem2 = _interopRequireDefault(_modulesManipulationSystem); + + var _sharedConfigurator = __webpack_require__(45); + + var _sharedConfigurator2 = _interopRequireDefault(_sharedConfigurator); + var _sharedValidator = __webpack_require__(46); + + var _sharedValidator2 = _interopRequireDefault(_sharedValidator); + + var _optionsJs = __webpack_require__(66); + + __webpack_require__(67); + + var Emitter = __webpack_require__(43); + var Hammer = __webpack_require__(41); var util = __webpack_require__(2); - var DataSet = __webpack_require__(22); + var DataSet = __webpack_require__(4); + var DataView = __webpack_require__(5); + var dotparser = __webpack_require__(38); + var gephiParser = __webpack_require__(39); + var Images = __webpack_require__(37); + var Activator = __webpack_require__(68); + var locales = __webpack_require__(69); /** - * 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 Network + * Create a network visualization, displaying nodes and edges. * - * @constructor DataView + * @param {Element} container The DOM element in which the Network will + * be created. Normally a div element. + * @param {Object} data An object containing parameters + * {Array} nodes + * {Array} edges + * @param {Object} options Options */ - 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 + function Network(container, data, options) { + var _this = this; - var me = this; - this.listener = function () { - me._onEvent.apply(me, arguments); + if (!(this instanceof Network)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + // set constant values + this.options = {}; + this.defaultOptions = { + locale: 'en', + locales: locales, + clickToUse: false + }; + util.extend(this.options, this.defaultOptions); + + // containers for nodes and edges + this.body = { + nodes: {}, + nodeIndices: [], + edges: {}, + edgeIndices: [], + data: { + nodes: null, // A DataSet or DataView + edges: null // A DataSet or DataView + }, + functions: { + createNode: function createNode() {}, + createEdge: function createEdge() {}, + getPointer: function getPointer() {} + }, + emitter: { + on: this.on.bind(this), + off: this.off.bind(this), + emit: this.emit.bind(this), + once: this.once.bind(this) + }, + eventListeners: { + onTap: function onTap() {}, + onTouch: function onTouch() {}, + onDoubleTap: function onDoubleTap() {}, + onHold: function onHold() {}, + onDragStart: function onDragStart() {}, + onDrag: function onDrag() {}, + onDragEnd: function onDragEnd() {}, + onMouseWheel: function onMouseWheel() {}, + onPinch: function onPinch() {}, + onMouseMove: function onMouseMove() {}, + onRelease: function onRelease() {}, + onContext: function onContext() {} + }, + container: container, + view: { + scale: 1, + translation: { x: 0, y: 0 } + } }; + // bind the event listeners + this.bindEventListeners(); + + // setting up all modules + this.images = new Images(function () { + return _this.body.emitter.emit('_requestRedraw'); + }); // object with images + this.groups = new _modulesGroups2['default'](); // object with groups + this.canvas = new _modulesCanvas2['default'](this.body); // DOM handler + this.selectionHandler = new _modulesSelectionHandler2['default'](this.body, this.canvas); // Selection handler + this.interactionHandler = new _modulesInteractionHandler2['default'](this.body, this.canvas, this.selectionHandler); // Interaction handler handles all the hammer bindings (that are bound by canvas), key + this.view = new _modulesView2['default'](this.body, this.canvas); // camera handler, does animations and zooms + this.renderer = new _modulesCanvasRenderer2['default'](this.body, this.canvas); // renderer, starts renderloop, has events that modules can hook into + this.physics = new _modulesPhysicsEngine2['default'](this.body); // physics engine, does all the simulations + this.layoutEngine = new _modulesLayoutEngine2['default'](this.body); // layout engine for inital layout and hierarchical layout + this.clustering = new _modulesClustering2['default'](this.body); // clustering api + this.manipulation = new _modulesManipulationSystem2['default'](this.body, this.canvas, this.selectionHandler); // data manipulation system + + this.nodesHandler = new _modulesNodesHandler2['default'](this.body, this.images, this.groups, this.layoutEngine); // Handle adding, deleting and updating of nodes as well as global options + this.edgesHandler = new _modulesEdgesHandler2['default'](this.body, this.images, this.groups); // Handle adding, deleting and updating of edges as well as global options + + // create the DOM elements + this.canvas._create(); + + // setup configuration system + this.configurator = new _sharedConfigurator2['default'](this, this.body.container, _optionsJs.configureOptions, this.canvas.pixelRatio); + + // apply options + this.setOptions(options); + + // load data (the disable start variable will be the same as the enabled clustering) this.setData(data); } - // TODO: implement a function .config() to dynamically update things like configured filter - // and trigger changes accordingly + // Extend Network with an Emitter mixin + Emitter(Network.prototype); /** - * Set a data source for the view - * @param {DataSet | DataView} data + * Set options + * @param {Object} options */ - DataView.prototype.setData = function (data) { - var ids, i, len; + Network.prototype.setOptions = function (options) { + var _this2 = this; - if (this._data) { - // unsubscribe from current dataset - if (this._data.off) { - this._data.off('*', this.listener); + if (options !== undefined) { + + var errorFound = _sharedValidator2['default'].validate(options, _optionsJs.allOptions); + if (errorFound === true) { + console.log('%cErrors have been found in the supplied options object.', _sharedValidator.printStyle); } - // trigger a remove of all items in memory - ids = []; - for (var id in this._ids) { - if (this._ids.hasOwnProperty(id)) { - ids.push(id); - } + // copy the global fields over + var fields = ['locale', 'locales', 'clickToUse']; + util.selectiveDeepExtend(fields, this.options, options); + + // the hierarchical system can adapt the edges and the physics to it's own options because not all combinations work with the hierarichical system. + options = this.layoutEngine.setOptions(options.layout, options); + + this.canvas.setOptions(options); // options for canvas are in globals + + // pass the options to the modules + this.groups.setOptions(options.groups); + this.nodesHandler.setOptions(options.nodes); + this.edgesHandler.setOptions(options.edges); + this.physics.setOptions(options.physics); + this.manipulation.setOptions(options.manipulation, options, this.options); // manipulation uses the locales in the globals + + this.interactionHandler.setOptions(options.interaction); + this.renderer.setOptions(options.interaction); // options for rendering are in interaction + this.selectionHandler.setOptions(options.interaction); // options for selection are in interaction + + // reload the settings of the nodes to apply changes in groups that are not referenced by pointer. + if (options.groups !== undefined) { + this.body.emitter.emit('refreshNodes'); } - this._ids = {}; - this.length = 0; - this._trigger('remove', { items: ids }); - } + // these two do not have options at the moment, here for completeness + //this.view.setOptions(options.view); + //this.clustering.setOptions(options.clustering); - this._data = data; + this.configurator.setOptions(options.configure); - if (this._data) { - // update fieldId - this._fieldId = this._options.fieldId || this._data && this._data.options && this._data.options.fieldId || 'id'; + // if the configuration system is enabled, copy all options and put them into the config system + if (this.configurator.options.enabled === true) { + var networkOptions = { nodes: {}, edges: {}, layout: {}, interaction: {}, manipulation: {}, physics: {}, global: {} }; + util.deepExtend(networkOptions.nodes, this.nodesHandler.options); + util.deepExtend(networkOptions.edges, this.edgesHandler.options); + util.deepExtend(networkOptions.layout, this.layoutEngine.options); + // load the selectionHandler and rendere default options in to the interaction group + util.deepExtend(networkOptions.interaction, this.selectionHandler.options); + util.deepExtend(networkOptions.interaction, this.renderer.options); - // 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; + util.deepExtend(networkOptions.interaction, this.interactionHandler.options); + util.deepExtend(networkOptions.manipulation, this.manipulation.options); + util.deepExtend(networkOptions.physics, this.physics.options); + + // load globals into the global object + util.deepExtend(networkOptions.global, this.canvas.options); + util.deepExtend(networkOptions.global, this.options); + + this.configurator.setModuleOptions(networkOptions); } - this.length = ids.length; - this._trigger('add', { items: ids }); - // subscribe to new dataset - if (this._data.on) { - this._data.on('*', this.listener); + // handle network global options + if (options.clickToUse !== undefined) { + if (options.clickToUse === true) { + if (this.activator === undefined) { + this.activator = new Activator(this.canvas.frame); + this.activator.on('change', function () { + _this2.body.emitter.emit('activate'); + }); + } + } else { + if (this.activator !== undefined) { + this.activator.destroy(); + delete this.activator; + } + this.body.emitter.emit('activate'); + } + } else { + this.body.emitter.emit('activate'); } + + this.canvas.setSize(); + + // start the physics simulation. Can be safely called multiple times. + this.body.emitter.emit('startSimulation'); } }; /** - * Refresh the DataView. Useful when the DataView has a filter function - * containing a variable parameter. + * Update the this.body.nodeIndices with the most recent node index list + * @private */ - DataView.prototype.refresh = function () { - var id; - var ids = this._data.getIds({ filter: this._options && this._options.filter }); - var newIds = {}; - var added = []; - var removed = []; + Network.prototype._updateVisibleIndices = function () { + var nodes = this.body.nodes; + var edges = this.body.edges; + this.body.nodeIndices = []; + this.body.edgeIndices = []; - // check for additions - for (var i = 0; i < ids.length; i++) { - id = ids[i]; - newIds[id] = true; - if (!this._ids[id]) { - added.push(id); - this._ids[id] = true; - this.length++; + for (var nodeId in nodes) { + if (nodes.hasOwnProperty(nodeId)) { + if (nodes[nodeId].options.hidden === false) { + this.body.nodeIndices.push(nodeId); + } } } - // check for removals - for (id in this._ids) { - if (this._ids.hasOwnProperty(id)) { - if (!newIds[id]) { - removed.push(id); - delete this._ids[id]; - this.length--; + for (var edgeId in edges) { + if (edges.hasOwnProperty(edgeId)) { + if (edges[edgeId].options.hidden === false) { + this.body.edgeIndices.push(edgeId); } } } - - // trigger events - if (added.length) { - this._trigger('add', { items: added }); - } - if (removed.length) { - this._trigger('remove', { items: removed }); - } }; /** - * 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 args + * Bind all events */ - DataView.prototype.get = function (args) { - 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); + Network.prototype.bindEventListeners = function () { + var _this3 = this; - // 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); - }; - } + // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed. + this.body.emitter.on('_dataChanged', function () { + // update shortcut lists + _this3._updateVisibleIndices(); + _this3.physics.updatePhysicsData(); - // build up the call to the linked data set - var getArguments = []; - if (ids != undefined) { - getArguments.push(ids); - } - getArguments.push(viewOptions); - getArguments.push(data); + // call the dataUpdated event because the only difference between the two is the updating of the indices + _this3.body.emitter.emit('_dataUpdated'); + }); - return this._data && this._data.get.apply(this._data, getArguments); + // this is called when options of EXISTING nodes or edges have changed. + this.body.emitter.on('_dataUpdated', function () { + // update values + _this3._updateValueRange(_this3.body.nodes); + _this3._updateValueRange(_this3.body.edges); + // start simulation (can be called safely, even if already running) + _this3.body.emitter.emit('startSimulation'); + }); }; /** - * 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 + * Set nodes and edges, and optionally options as well. + * + * @param {Object} data Object containing parameters: + * {Array | DataSet | DataView} [nodes] Array with nodes + * {Array | DataSet | DataView} [edges] Array with edges + * {String} [dot] String containing data in DOT format + * {String} [gephi] String containing data in gephi JSON format + * {Options} [options] Object with options */ - DataView.prototype.getIds = function (options) { - var ids; + Network.prototype.setData = function (data) { + // reset the physics engine. + this.body.emitter.emit('resetPhysics'); + this.body.emitter.emit('_resetData'); - if (this._data) { - var defaultFilter = this._options.filter; - var filter; + // unselect all to ensure no selections from old data are carried over. + this.selectionHandler.unselectAll(); - if (options && options.filter) { - if (defaultFilter) { - filter = function (item) { - return defaultFilter(item) && options.filter(item); - }; - } else { - filter = options.filter; - } - } else { - filter = defaultFilter; - } + if (data && data.dot && (data.nodes || data.edges)) { + throw new SyntaxError('Data must contain either parameter "dot" or ' + ' parameter pair "nodes" and "edges", but not both.'); + } - ids = this._data.getIds({ - filter: filter, - order: options && options.order - }); + // set options + this.setOptions(data && data.options); + // set all data + if (data && data.dot) { + console.log('The dot property has been depricated. Please use the static convertDot method to convert DOT into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertDot(dotString);'); + // parse DOT file + var dotData = dotparser.DOTToGraph(data.dot); + this.setData(dotData); + return; + } else if (data && data.gephi) { + // parse DOT file + console.log('The gephi property has been depricated. Please use the static convertGephi method to convert gephi into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertGephi(gephiJson);'); + var gephiData = gephiParser.parseGephi(data.gephi); + this.setData(gephiData); + return; } else { - ids = []; + this.nodesHandler.setData(data && data.nodes, true); + this.edgesHandler.setData(data && data.edges, true); } - return ids; - }; - - /** - * 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; + // emit change in data + this.body.emitter.emit('_dataChanged'); + + // find a stable position or start animating to a stable position + this.body.emitter.emit('initPhysics'); }; /** - * 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 + * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function. + * var network = new vis.Network(..); + * network.destroy(); + * network = null; */ - DataView.prototype._onEvent = function (event, params, senderId) { - var i, len, id, item; - var ids = params && params.items; - var data = this._data; - var updatedData = []; - var added = []; - var updated = []; - var removed = []; - - if (ids && 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; - added.push(id); - } - } + Network.prototype.destroy = function () { + this.body.emitter.emit('destroy'); + // clear events + this.body.emitter.off(); + this.off(); - break; + // delete modules + delete this.groups; + delete this.canvas; + delete this.selectionHandler; + delete this.interactionHandler; + delete this.view; + delete this.renderer; + delete this.physics; + delete this.layoutEngine; + delete this.clustering; + delete this.manipulation; + delete this.nodesHandler; + delete this.edgesHandler; + delete this.configurator; + delete this.images; - 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); + // delete emitter bindings + delete this.body.emitter.emit; + delete this.body.emitter.on; + delete this.body.emitter.off; + delete this.body.emitter.once; + delete this.body.emitter; - if (item) { - if (this._ids[id]) { - updated.push(id); - updatedData.push(params.data[i]); - } else { - this._ids[id] = true; - added.push(id); - } - } else { - if (this._ids[id]) { - delete this._ids[id]; - removed.push(id); - } else {} - } - } + for (var nodeId in this.body.nodes) { + delete this.body.nodes[nodeId]; + } + for (var edgeId in this.body.edges) { + delete this.body.edges[edgeId]; + } - break; + // remove the container and everything inside it recursively + util.recursiveDOMDelete(this.body.container); + }; - 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]; - removed.push(id); - } - } + /** + * Update the values of all object in the given array according to the current + * value range of the objects in the array. + * @param {Object} obj An object containing a set of Edges or Nodes + * The objects must have a method getValue() and + * setValueRange(min, max). + * @private + */ + Network.prototype._updateValueRange = function (obj) { + var id; - break; + // determine the range of the objects + var valueMin = undefined; + var valueMax = undefined; + var valueTotal = 0; + for (id in obj) { + if (obj.hasOwnProperty(id)) { + var value = obj[id].getValue(); + if (value !== undefined) { + valueMin = valueMin === undefined ? value : Math.min(value, valueMin); + valueMax = valueMax === undefined ? value : Math.max(value, valueMax); + valueTotal += value; + } } + } - this.length += added.length - removed.length; - - if (added.length) { - this._trigger('add', { items: added }, senderId); - } - if (updated.length) { - this._trigger('update', { items: updated, data: updatedData }, senderId); - } - if (removed.length) { - this._trigger('remove', { items: removed }, senderId); + // adjust the range of all objects + if (valueMin !== undefined && valueMax !== undefined) { + for (id in obj) { + if (obj.hasOwnProperty(id)) { + obj[id].setValueRange(valueMin, valueMax, valueTotal); + } } } }; - // 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; + /** + * Returns true when the Network is active. + * @returns {boolean} + */ + Network.prototype.isActive = function () { + return !this.activator || this.activator.active; + }; - module.exports = DataView; + Network.prototype.setSize = function () { + return this.canvas.setSize.apply(this.canvas, arguments); + }; + Network.prototype.canvasToDOM = function () { + return this.canvas.canvasToDOM.apply(this.canvas, arguments); + }; + Network.prototype.DOMtoCanvas = function () { + return this.canvas.setSize.DOMtoCanvas(this.canvas, arguments); + }; + Network.prototype.findNode = function () { + return this.clustering.findNode.apply(this.clustering, arguments); + }; + Network.prototype.isCluster = function () { + return this.clustering.isCluster.apply(this.clustering, arguments); + }; + Network.prototype.openCluster = function () { + return this.clustering.openCluster.apply(this.clustering, arguments); + }; + Network.prototype.cluster = function () { + return this.clustering.cluster.apply(this.clustering, arguments); + }; + Network.prototype.getNodesInCluster = function () { + return this.clustering.getNodesInCluster.apply(this.clustering, arguments); + }; + Network.prototype.clusterByConnection = function () { + return this.clustering.clusterByConnection.apply(this.clustering, arguments); + }; + Network.prototype.clusterByHubsize = function () { + return this.clustering.clusterByHubsize.apply(this.clustering, arguments); + }; + Network.prototype.clusterOutliers = function () { + return this.clustering.clusterOutliers.apply(this.clustering, arguments); + }; + Network.prototype.getSeed = function () { + return this.layoutEngine.getSeed.apply(this.layoutEngine, arguments); + }; + Network.prototype.enableEditMode = function () { + return this.manipulation.enableEditMode.apply(this.manipulation, arguments); + }; + Network.prototype.disableEditMode = function () { + return this.manipulation.disableEditMode.apply(this.manipulation, arguments); + }; + Network.prototype.addNodeMode = function () { + return this.manipulation.addNodeMode.apply(this.manipulation, arguments); + }; + Network.prototype.editNode = function () { + return this.manipulation.editNode.apply(this.manipulation, arguments); + }; + Network.prototype.editNodeMode = function () { + console.log('Depricated: Please use editNode instead of editNodeMode.');return this.manipulation.editNode.apply(this.manipulation, arguments); + }; + Network.prototype.addEdgeMode = function () { + return this.manipulation.addEdgeMode.apply(this.manipulation, arguments); + }; + Network.prototype.editEdgeMode = function () { + return this.manipulation.editEdgeMode.apply(this.manipulation, arguments); + }; + Network.prototype.deleteSelected = function () { + return this.manipulation.deleteSelected.apply(this.manipulation, arguments); + }; + Network.prototype.getPositions = function () { + return this.nodesHandler.getPositions.apply(this.nodesHandler, arguments); + }; + Network.prototype.storePositions = function () { + return this.nodesHandler.storePositions.apply(this.nodesHandler, arguments); + }; + Network.prototype.getBoundingBox = function () { + return this.nodesHandler.getBoundingBox.apply(this.nodesHandler, arguments); + }; + Network.prototype.getConnectedNodes = function (objectId) { + if (this.body.nodes[objectId] !== undefined) { + return this.nodesHandler.getConnectedNodes.apply(this.nodesHandler, arguments); + } else { + return this.edgesHandler.getConnectedNodes.apply(this.edgesHandler, arguments); + } + }; + Network.prototype.getConnectedEdges = function () { + return this.nodesHandler.getConnectedEdges.apply(this.nodesHandler, arguments); + }; + Network.prototype.startSimulation = function () { + return this.physics.startSimulation.apply(this.physics, arguments); + }; + Network.prototype.stopSimulation = function () { + return this.physics.stopSimulation.apply(this.physics, arguments); + }; + Network.prototype.stabilize = function () { + return this.physics.stabilize.apply(this.physics, arguments); + }; + Network.prototype.getSelection = function () { + return this.selectionHandler.getSelection.apply(this.selectionHandler, arguments); + }; + Network.prototype.getSelectedNodes = function () { + return this.selectionHandler.getSelectedNodes.apply(this.selectionHandler, arguments); + }; + Network.prototype.getSelectedEdges = function () { + return this.selectionHandler.getSelectedEdges.apply(this.selectionHandler, arguments); + }; + Network.prototype.getNodeAt = function () { + var node = this.selectionHandler.getNodeAt.apply(this.selectionHandler, arguments); + if (node !== undefined && node.id !== undefined) { + return node.id; + } + return node; + }; + Network.prototype.getEdgeAt = function () { + var edge = this.selectionHandler.getEdgeAt.apply(this.selectionHandler, arguments); + if (edge !== undefined && edge.id !== undefined) { + return edge.id; + } + return edge; + }; + Network.prototype.selectNodes = function () { + return this.selectionHandler.selectNodes.apply(this.selectionHandler, arguments); + }; + Network.prototype.selectEdges = function () { + return this.selectionHandler.selectEdges.apply(this.selectionHandler, arguments); + }; + Network.prototype.unselectAll = function () { + return this.selectionHandler.unselectAll.apply(this.selectionHandler, arguments); + }; + Network.prototype.redraw = function () { + return this.renderer.redraw.apply(this.renderer, arguments); + }; + Network.prototype.getScale = function () { + return this.view.getScale.apply(this.view, arguments); + }; + Network.prototype.getViewPosition = function () { + return this.view.getViewPosition.apply(this.view, arguments); + }; + Network.prototype.fit = function () { + return this.view.fit.apply(this.view, arguments); + }; + Network.prototype.moveTo = function () { + return this.view.moveTo.apply(this.view, arguments); + }; + Network.prototype.focus = function () { + return this.view.focus.apply(this.view, arguments); + }; + Network.prototype.releaseNode = function () { + return this.view.releaseNode.apply(this.view, arguments); + }; - // nothing interesting for me :-( + module.exports = Network; /***/ }, -/* 25 */ +/* 37 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; + /** + * @class Images + * This class loads images and keeps them stored. + */ + "use strict"; - var Emitter = __webpack_require__(27); - var DataSet = __webpack_require__(22); - var DataView = __webpack_require__(24); - var util = __webpack_require__(2); - var Point3d = __webpack_require__(28); - var Point2d = __webpack_require__(26); - var Camera = __webpack_require__(29); - var Filter = __webpack_require__(30); - var Slider = __webpack_require__(31); - var StepNumber = __webpack_require__(32); + function Images(callback) { + this.images = {}; + this.imageBroken = {}; + this.callback = callback; + } /** - * @constructor Graph3d - * Graph3d displays data in 3d. - * - * Graph3d is developed in javascript as a Google Visualization Chart. * - * @param {Element} container The DOM element in which the Graph3d will - * be created. Normally a div element. - * @param {DataSet | DataView | Array} [data] - * @param {Object} [options] + * @param {string} url Url of the image + * @param {string} url Url of an image to use if the url image is not found + * @return {Image} img The image object */ - function Graph3d(container, data, options) { - if (!(this instanceof Graph3d)) { - throw new SyntaxError('Constructor must be called with the new operator'); - } + Images.prototype.load = function (url, brokenUrl, id) { + var img = this.images[url]; // make a pointer + if (img === undefined) { + // create the image + var me = this; + img = new Image(); + img.onload = function () { + // IE11 fix -- thanks dponch! + if (this.width === 0) { + document.body.appendChild(this); + this.width = this.offsetWidth; + this.height = this.offsetHeight; + document.body.removeChild(this); + } - // create variables and set default values - this.containerElement = container; - this.width = '400px'; - this.height = '400px'; - this.margin = 10; // px - this.defaultXCenter = '55%'; - this.defaultYCenter = '50%'; + if (me.callback) { + me.images[url] = img; + me.callback(this); + } + }; - this.xLabel = 'x'; - this.yLabel = 'y'; - this.zLabel = 'z'; + img.onerror = function () { + if (brokenUrl === undefined) { + console.error("Could not load image:", url); + delete this.src; + if (me.callback) { + me.callback(this); + } + } else { + if (me.imageBroken[id] && me.imageBroken[id][url] === true) { + console.error("Could not load brokenImage:", brokenUrl); + delete this.src; + if (me.callback) { + me.callback(this); + } + } else { + console.error("Could not load image:", url); + this.src = brokenUrl; + if (me.imageBroken[id] === undefined) { + me.imageBroken[id] = {}; + } + me.imageBroken[id][url] = true; + } + } + }; - var passValueFn = function passValueFn(v) { - return v; - }; - this.xValueLabel = passValueFn; - this.yValueLabel = passValueFn; - this.zValueLabel = passValueFn; + img.src = url; + } - this.filterLabel = 'time'; - this.legendLabel = 'value'; + return img; + }; - this.style = Graph3d.STYLE.DOT; - this.showPerspective = true; - this.showGrid = true; - this.keepAspectRatio = true; - this.showShadow = false; - this.showGrayBottom = false; // TODO: this does not work correctly - this.showTooltip = false; - this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube' + module.exports = Images; - this.animationInterval = 1000; // milliseconds - this.animationPreload = false; +/***/ }, +/* 38 */ +/***/ function(module, exports, __webpack_require__) { - this.camera = new Camera(); - this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window? + /** + * Parse a text source containing data in DOT language into a JSON object. + * The object contains two lists: one with nodes and one with edges. + * + * DOT language reference: http://www.graphviz.org/doc/info/lang.html + * + * DOT language attributes: http://graphviz.org/content/attrs + * + * @param {String} data Text containing a graph in DOT-notation + * @return {Object} graph An object containing two parameters: + * {Object[]} nodes + * {Object[]} edges + */ + 'use strict'; - this.dataTable = null; // The original data table - this.dataPoints = null; // The table with point objects + function parseDOT(data) { + dot = data; + return parseGraph(); + } - // the column indexes - this.colX = undefined; - this.colY = undefined; - this.colZ = undefined; - this.colValue = undefined; - this.colFilter = undefined; + // mapping of attributes from DOT (the keys) to vis.js (the values) + var NODE_ATTR_MAPPING = { + 'fontsize': 'font.size', + 'fontcolor': 'font.color', + 'labelfontcolor': 'font.color', + 'fontname': 'font.face', + 'color': ['color.border', 'color.background'], + 'fillcolor': 'color.background', + 'tooltip': 'title', + 'labeltooltip': 'title' + }; + var EDGE_ATTR_MAPPING = Object.create(NODE_ATTR_MAPPING); + EDGE_ATTR_MAPPING.color = 'color.color'; - this.xMin = 0; - this.xStep = undefined; // auto by default - this.xMax = 1; - this.yMin = 0; - this.yStep = undefined; // auto by default - this.yMax = 1; - this.zMin = 0; - this.zStep = undefined; // auto by default - this.zMax = 1; - this.valueMin = 0; - this.valueMax = 1; - this.xBarWidth = 1; - this.yBarWidth = 1; - // TODO: customize axis range + // token types enumeration + var TOKENTYPE = { + NULL: 0, + DELIMITER: 1, + IDENTIFIER: 2, + UNKNOWN: 3 + }; - // constants - this.colorAxis = '#4D4D4D'; - this.colorGrid = '#D3D3D3'; - this.colorDot = '#7DC1FF'; - this.colorDotBorder = '#3267D2'; + // map with all delimiters + var DELIMITERS = { + '{': true, + '}': true, + '[': true, + ']': true, + ';': true, + '=': true, + ',': true, - // create a frame and canvas - this.create(); + '->': true, + '--': true + }; - // apply options (also when undefined) - this.setOptions(options); - - // apply data - if (data) { - this.setData(data); - } - } - - // Extend Graph3d with an Emitter mixin - Emitter(Graph3d.prototype); + var dot = ''; // current dot file + var index = 0; // current index in dot file + var c = ''; // current token character in expr + var token = ''; // current token + var tokenType = TOKENTYPE.NULL; // type of the token /** - * Calculate the scaling values, dependent on the range in x, y, and z direction + * Get the first character from the dot file. + * The character is stored into the char c. If the end of the dot file is + * reached, the function puts an empty string in c. */ - Graph3d.prototype._setScale = function () { - this.scale = new Point3d(1 / (this.xMax - this.xMin), 1 / (this.yMax - this.yMin), 1 / (this.zMax - this.zMin)); - - // keep aspect ration between x and y scale if desired - if (this.keepAspectRatio) { - if (this.scale.x < this.scale.y) { - //noinspection JSSuspiciousNameCombination - this.scale.y = this.scale.x; - } else { - //noinspection JSSuspiciousNameCombination - this.scale.x = this.scale.y; - } - } - - // scale the vertical axis - this.scale.z *= this.verticalRatio; - // TODO: can this be automated? verticalRatio? - - // determine scale for (optional) value - this.scale.value = 1 / (this.valueMax - this.valueMin); - - // position the camera arm - var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x; - var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y; - var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z; - this.camera.setArmLocation(xCenter, yCenter, zCenter); - }; + function first() { + index = 0; + c = dot.charAt(0); + } /** - * Convert a 3D location to a 2D location on screen - * http://en.wikipedia.org/wiki/3D_projection - * @param {Point3d} point3d A 3D point with parameters x, y, z - * @return {Point2d} point2d A 2D point with parameters x, y + * Get the next character from the dot file. + * The character is stored into the char c. If the end of the dot file is + * reached, the function puts an empty string in c. */ - Graph3d.prototype._convert3Dto2D = function (point3d) { - var translation = this._convertPointToTranslation(point3d); - return this._convertTranslationToScreen(translation); - }; + function next() { + index++; + c = dot.charAt(index); + } /** - * Convert a 3D location its translation seen from the camera - * http://en.wikipedia.org/wiki/3D_projection - * @param {Point3d} point3d A 3D point with parameters x, y, z - * @return {Point3d} translation A 3D point with parameters x, y, z This is - * the translation of the point, seen from the - * camera + * Preview the next character from the dot file. + * @return {String} cNext */ - Graph3d.prototype._convertPointToTranslation = function (point3d) { - var ax = point3d.x * this.scale.x, - ay = point3d.y * this.scale.y, - az = point3d.z * this.scale.z, - cx = this.camera.getCameraLocation().x, - cy = this.camera.getCameraLocation().y, - cz = this.camera.getCameraLocation().z, - - // calculate angles - sinTx = Math.sin(this.camera.getCameraRotation().x), - cosTx = Math.cos(this.camera.getCameraRotation().x), - sinTy = Math.sin(this.camera.getCameraRotation().y), - cosTy = Math.cos(this.camera.getCameraRotation().y), - sinTz = Math.sin(this.camera.getCameraRotation().z), - cosTz = Math.cos(this.camera.getCameraRotation().z), - - // calculate translation - dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz), - dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax - cx)), - dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax - cx)); - - return new Point3d(dx, dy, dz); - }; + function nextPreview() { + return dot.charAt(index + 1); + } /** - * Convert a translation point to a point on the screen - * @param {Point3d} translation A 3D point with parameters x, y, z This is - * the translation of the point, seen from the - * camera - * @return {Point2d} point2d A 2D point with parameters x, y + * Test whether given character is alphabetic or numeric + * @param {String} c + * @return {Boolean} isAlphaNumeric */ - Graph3d.prototype._convertTranslationToScreen = function (translation) { - var ex = this.eye.x, - ey = this.eye.y, - ez = this.eye.z, - dx = translation.x, - dy = translation.y, - dz = translation.z; - - // calculate position on screen from translation - var bx; - var by; - if (this.showPerspective) { - bx = (dx - ex) * (ez / dz); - by = (dy - ey) * (ez / dz); - } else { - bx = dx * -(ez / this.camera.getArmLength()); - by = dy * -(ez / this.camera.getArmLength()); - } - - // shift and scale the point to the center of the screen - // use the width of the graph to scale both horizontally and vertically. - return new Point2d(this.xcenter + bx * this.frame.canvas.clientWidth, this.ycenter - by * this.frame.canvas.clientWidth); - }; + var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/; + function isAlphaNumeric(c) { + return regexAlphaNumeric.test(c); + } /** - * Set the background styling for the graph - * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor + * Merge all options of object b into object b + * @param {Object} a + * @param {Object} b + * @return {Object} a */ - Graph3d.prototype._setBackgroundColor = function (backgroundColor) { - var fill = 'white'; - var stroke = 'gray'; - var strokeWidth = 1; - - if (typeof backgroundColor === 'string') { - fill = backgroundColor; - stroke = 'none'; - strokeWidth = 0; - } else if (typeof backgroundColor === 'object') { - if (backgroundColor.fill !== undefined) fill = backgroundColor.fill; - if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke; - if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth; - } else if (backgroundColor === undefined) {} else { - throw 'Unsupported type of backgroundColor'; + function merge(a, b) { + if (!a) { + a = {}; } - this.frame.style.backgroundColor = fill; - this.frame.style.borderColor = stroke; - this.frame.style.borderWidth = strokeWidth + 'px'; - this.frame.style.borderStyle = 'solid'; - }; - - /// enumerate the available styles - Graph3d.STYLE = { - BAR: 0, - BARCOLOR: 1, - BARSIZE: 2, - DOT: 3, - DOTLINE: 4, - DOTCOLOR: 5, - DOTSIZE: 6, - GRID: 7, - LINE: 8, - SURFACE: 9 - }; + if (b) { + for (var name in b) { + if (b.hasOwnProperty(name)) { + a[name] = b[name]; + } + } + } + return a; + } /** - * 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 + * Set a value in an object, where the provided parameter name can be a + * path with nested parameters. For example: + * + * var obj = {a: 2}; + * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}} + * + * @param {Object} obj + * @param {String} path A parameter name or dot-separated parameter path, + * like "color.highlight.border". + * @param {*} value */ - Graph3d.prototype._getStyleNumber = function (styleName) { - switch (styleName) { - case 'dot': - return Graph3d.STYLE.DOT; - case 'dot-line': - return Graph3d.STYLE.DOTLINE; - case 'dot-color': - return Graph3d.STYLE.DOTCOLOR; - case 'dot-size': - return Graph3d.STYLE.DOTSIZE; - case 'line': - return Graph3d.STYLE.LINE; - case 'grid': - return Graph3d.STYLE.GRID; - case 'surface': - return Graph3d.STYLE.SURFACE; - case 'bar': - return Graph3d.STYLE.BAR; - case 'bar-color': - return Graph3d.STYLE.BARCOLOR; - case 'bar-size': - return Graph3d.STYLE.BARSIZE; + function setValue(obj, path, value) { + var keys = path.split('.'); + var o = obj; + while (keys.length) { + var key = keys.shift(); + if (keys.length) { + // this isn't the end point + if (!o[key]) { + o[key] = {}; + } + o = o[key]; + } else { + // this is the end point + o[key] = value; + } } - - return -1; - }; + } /** - * Determine the indexes of the data columns, based on the given style and data - * @param {DataSet} data - * @param {Number} style + * Add a node to a graph object. If there is already a node with + * the same id, their attributes will be merged. + * @param {Object} graph + * @param {Object} node */ - Graph3d.prototype._determineColumnIndexes = function (data, style) { - if (this.style === Graph3d.STYLE.DOT || this.style === Graph3d.STYLE.DOTLINE || this.style === Graph3d.STYLE.LINE || this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE || this.style === Graph3d.STYLE.BAR) { - // 3 columns expected, and optionally a 4th with filter values - this.colX = 0; - this.colY = 1; - this.colZ = 2; - this.colValue = undefined; + function addNode(graph, node) { + var i, len; + var current = null; - if (data.getNumberOfColumns() > 3) { - this.colFilter = 3; + // find root graph (in case of subgraph) + var graphs = [graph]; // list with all graphs from current graph to root graph + var root = graph; + while (root.parent) { + graphs.push(root.parent); + root = root.parent; + } + + // find existing node (at root level) by its id + if (root.nodes) { + for (i = 0, len = root.nodes.length; i < len; i++) { + if (node.id === root.nodes[i].id) { + current = root.nodes[i]; + break; + } } - } else if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { - // 4 columns expected, and optionally a 5th with filter values - this.colX = 0; - this.colY = 1; - this.colZ = 2; - this.colValue = 3; + } - if (data.getNumberOfColumns() > 4) { - this.colFilter = 4; + if (!current) { + // this is a new node + current = { + id: node.id + }; + if (graph.node) { + // clone default attributes + current.attr = merge(current.attr, graph.node); } - } else { - throw 'Unknown style "' + this.style + '"'; } - }; - Graph3d.prototype.getNumberOfRows = function (data) { - return data.length; - }; + // add node to this (sub)graph and all its parent graphs + for (i = graphs.length - 1; i >= 0; i--) { + var g = graphs[i]; - Graph3d.prototype.getNumberOfColumns = function (data) { - var counter = 0; - for (var column in data[0]) { - if (data[0].hasOwnProperty(column)) { - counter++; + if (!g.nodes) { + g.nodes = []; + } + if (g.nodes.indexOf(current) === -1) { + g.nodes.push(current); } } - return counter; - }; - Graph3d.prototype.getDistinctValues = function (data, column) { - var distinctValues = []; - for (var i = 0; i < data.length; i++) { - if (distinctValues.indexOf(data[i][column]) == -1) { - distinctValues.push(data[i][column]); - } + // merge attributes + if (node.attr) { + current.attr = merge(current.attr, node.attr); } - return distinctValues; - }; + } - Graph3d.prototype.getColumnRange = function (data, column) { - var minMax = { min: data[0][column], max: data[0][column] }; - for (var i = 0; i < data.length; i++) { - if (minMax.min > data[i][column]) { - minMax.min = data[i][column]; - } - if (minMax.max < data[i][column]) { - minMax.max = data[i][column]; - } + /** + * Add an edge to a graph object + * @param {Object} graph + * @param {Object} edge + */ + function addEdge(graph, edge) { + if (!graph.edges) { + graph.edges = []; } - return minMax; - }; + graph.edges.push(edge); + if (graph.edge) { + var attr = merge({}, graph.edge); // clone default attributes + edge.attr = merge(attr, edge.attr); // merge attributes + } + } /** - * Initialize the data from the data table. Calculate minimum and maximum values - * and column index values - * @param {Array | DataSet | DataView} rawData The data containing the items for the Graph. - * @param {Number} style Style Number + * Create an edge to a graph object + * @param {Object} graph + * @param {String | Number | Object} from + * @param {String | Number | Object} to + * @param {String} type + * @param {Object | null} attr + * @return {Object} edge */ - Graph3d.prototype._dataInitialize = function (rawData, style) { - var me = this; + function createEdge(graph, from, to, type, attr) { + var edge = { + from: from, + to: to, + type: type + }; - // unsubscribe from the dataTable - if (this.dataSet) { - this.dataSet.off('*', this._onChange); + if (graph.edge) { + edge.attr = merge({}, graph.edge); // clone default attributes } + edge.attr = merge(edge.attr || {}, attr); // merge attributes - if (rawData === undefined) return; + return edge; + } - if (Array.isArray(rawData)) { - rawData = new DataSet(rawData); - } + /** + * Get next token in the current dot file. + * The token and token type are available as token and tokenType + */ + function getToken() { + tokenType = TOKENTYPE.NULL; + token = ''; - var data; - if (rawData instanceof DataSet || rawData instanceof DataView) { - data = rawData.get(); - } else { - throw new Error('Array, DataSet, or DataView expected'); + // skip over whitespaces + while (c === ' ' || c === '\t' || c === '\n' || c === '\r') { + // space, tab, enter + next(); } - if (data.length == 0) return; + do { + var isComment = false; - this.dataSet = rawData; - this.dataTable = data; + // skip comment + if (c === '#') { + // find the previous non-space character + var i = index - 1; + while (dot.charAt(i) === ' ' || dot.charAt(i) === '\t') { + i--; + } + if (dot.charAt(i) === '\n' || dot.charAt(i) === '') { + // the # is at the start of a line, this is indeed a line comment + while (c != '' && c != '\n') { + next(); + } + isComment = true; + } + } + if (c === '/' && nextPreview() === '/') { + // skip line comment + while (c != '' && c != '\n') { + next(); + } + isComment = true; + } + if (c === '/' && nextPreview() === '*') { + // skip block comment + while (c != '') { + if (c === '*' && nextPreview() === '/') { + // end of block comment found. skip these last two characters + next(); + next(); + break; + } else { + next(); + } + } + isComment = true; + } - // subscribe to changes in the dataset - this._onChange = function () { - me.setData(me.dataSet); - }; - this.dataSet.on('*', this._onChange); + // skip over whitespaces + while (c === ' ' || c === '\t' || c === '\n' || c === '\r') { + // space, tab, enter + next(); + } + } while (isComment); - // _determineColumnIndexes - // getNumberOfRows (points) - // getNumberOfColumns (x,y,z,v,t,t1,t2...) - // getDistinctValues (unique values?) - // getColumnRange + // check for end of dot file + if (c === '') { + // token is still empty + tokenType = TOKENTYPE.DELIMITER; + return; + } - // determine the location of x,y,z,value,filter columns - this.colX = 'x'; - this.colY = 'y'; - this.colZ = 'z'; - this.colValue = 'style'; - this.colFilter = 'filter'; + // check for delimiters consisting of 2 characters + var c2 = c + nextPreview(); + if (DELIMITERS[c2]) { + tokenType = TOKENTYPE.DELIMITER; + token = c2; + next(); + next(); + return; + } - // check if a filter column is provided - if (data[0].hasOwnProperty('filter')) { - if (this.dataFilter === undefined) { - this.dataFilter = new Filter(rawData, this.colFilter, this); - this.dataFilter.setOnLoadCallback(function () { - me.redraw(); - }); - } + // check for delimiters consisting of 1 character + if (DELIMITERS[c]) { + tokenType = TOKENTYPE.DELIMITER; + token = c; + next(); + return; } - var withBars = this.style == Graph3d.STYLE.BAR || this.style == Graph3d.STYLE.BARCOLOR || this.style == Graph3d.STYLE.BARSIZE; + // check for an identifier (number or string) + // TODO: more precise parsing of numbers/strings (and the port separator ':') + if (isAlphaNumeric(c) || c === '-') { + token += c; + next(); - // determine barWidth from data - if (withBars) { - if (this.defaultXBarWidth !== undefined) { - this.xBarWidth = this.defaultXBarWidth; - } else { - var dataX = this.getDistinctValues(data, this.colX); - this.xBarWidth = dataX[1] - dataX[0] || 1; + while (isAlphaNumeric(c)) { + token += c; + next(); } - - if (this.defaultYBarWidth !== undefined) { - this.yBarWidth = this.defaultYBarWidth; - } else { - var dataY = this.getDistinctValues(data, this.colY); - this.yBarWidth = dataY[1] - dataY[0] || 1; + if (token === 'false') { + token = false; // convert to boolean + } else if (token === 'true') { + token = true; // convert to boolean + } else if (!isNaN(Number(token))) { + token = Number(token); // convert to number } + tokenType = TOKENTYPE.IDENTIFIER; + return; } - // calculate minimums and maximums - var xRange = this.getColumnRange(data, this.colX); - if (withBars) { - xRange.min -= this.xBarWidth / 2; - xRange.max += this.xBarWidth / 2; - } - this.xMin = this.defaultXMin !== undefined ? this.defaultXMin : xRange.min; - this.xMax = this.defaultXMax !== undefined ? this.defaultXMax : xRange.max; - if (this.xMax <= this.xMin) this.xMax = this.xMin + 1; - this.xStep = this.defaultXStep !== undefined ? this.defaultXStep : (this.xMax - this.xMin) / 5; - - var yRange = this.getColumnRange(data, this.colY); - if (withBars) { - yRange.min -= this.yBarWidth / 2; - yRange.max += this.yBarWidth / 2; + // check for a string enclosed by double quotes + if (c === '"') { + next(); + while (c != '' && (c != '"' || c === '"' && nextPreview() === '"')) { + token += c; + if (c === '"') { + // skip the escape character + next(); + } + next(); + } + if (c != '"') { + throw newSyntaxError('End of string " expected'); + } + next(); + tokenType = TOKENTYPE.IDENTIFIER; + return; } - this.yMin = this.defaultYMin !== undefined ? this.defaultYMin : yRange.min; - this.yMax = this.defaultYMax !== undefined ? this.defaultYMax : yRange.max; - if (this.yMax <= this.yMin) this.yMax = this.yMin + 1; - this.yStep = this.defaultYStep !== undefined ? this.defaultYStep : (this.yMax - this.yMin) / 5; - - var zRange = this.getColumnRange(data, this.colZ); - this.zMin = this.defaultZMin !== undefined ? this.defaultZMin : zRange.min; - this.zMax = this.defaultZMax !== undefined ? this.defaultZMax : zRange.max; - if (this.zMax <= this.zMin) this.zMax = this.zMin + 1; - this.zStep = this.defaultZStep !== undefined ? this.defaultZStep : (this.zMax - this.zMin) / 5; - if (this.colValue !== undefined) { - var valueRange = this.getColumnRange(data, this.colValue); - this.valueMin = this.defaultValueMin !== undefined ? this.defaultValueMin : valueRange.min; - this.valueMax = this.defaultValueMax !== undefined ? this.defaultValueMax : valueRange.max; - if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1; + // something unknown is found, wrong characters, a syntax error + tokenType = TOKENTYPE.UNKNOWN; + while (c != '') { + token += c; + next(); } - - // set the scale dependent on the ranges. - this._setScale(); - }; + throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"'); + } /** - * Filter the data based on the current filter - * @param {Array} data - * @return {Array} dataPoints Array with point objects which can be drawn on screen + * Parse a graph. + * @returns {Object} graph */ - Graph3d.prototype._getDataPoints = function (data) { - // TODO: store the created matrix dataPoints in the filters instead of reloading each time - var x, y, i, z, obj, point; - - var dataPoints = []; + function parseGraph() { + var graph = {}; - if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { - // copy all values from the google data table to a matrix - // the provided values are supposed to form a grid of (x,y) positions + first(); + getToken(); - // create two lists with all present x and y values - var dataX = []; - var dataY = []; - for (i = 0; i < this.getNumberOfRows(data); i++) { - x = data[i][this.colX] || 0; - y = data[i][this.colY] || 0; + // optional strict keyword + if (token === 'strict') { + graph.strict = true; + getToken(); + } - if (dataX.indexOf(x) === -1) { - dataX.push(x); - } - if (dataY.indexOf(y) === -1) { - dataY.push(y); - } - } + // graph or digraph keyword + if (token === 'graph' || token === 'digraph') { + graph.type = token; + getToken(); + } - var sortNumber = function sortNumber(a, b) { - return a - b; - }; - dataX.sort(sortNumber); - dataY.sort(sortNumber); + // optional graph id + if (tokenType === TOKENTYPE.IDENTIFIER) { + graph.id = token; + getToken(); + } - // create a grid, a 2d matrix, with all values. - var dataMatrix = []; // temporary data matrix - for (i = 0; i < data.length; i++) { - x = data[i][this.colX] || 0; - y = data[i][this.colY] || 0; - z = data[i][this.colZ] || 0; + // open angle bracket + if (token != '{') { + throw newSyntaxError('Angle bracket { expected'); + } + getToken(); - var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer - var yIndex = dataY.indexOf(y); + // statements + parseStatements(graph); - if (dataMatrix[xIndex] === undefined) { - dataMatrix[xIndex] = []; - } + // close angle bracket + if (token != '}') { + throw newSyntaxError('Angle bracket } expected'); + } + getToken(); - var point3d = new Point3d(); - point3d.x = x; - point3d.y = y; - point3d.z = z; + // end of file + if (token !== '') { + throw newSyntaxError('End of file expected'); + } + getToken(); - obj = {}; - obj.point = point3d; - obj.trans = undefined; - obj.screen = undefined; - obj.bottom = new Point3d(x, y, this.zMin); + // remove temporary default options + delete graph.node; + delete graph.edge; + delete graph.graph; - dataMatrix[xIndex][yIndex] = obj; + return graph; + } - dataPoints.push(obj); + /** + * Parse a list with statements. + * @param {Object} graph + */ + function parseStatements(graph) { + while (token !== '' && token != '}') { + parseStatement(graph); + if (token === ';') { + getToken(); } + } + } - // fill in the pointers to the neighbors. - for (x = 0; x < dataMatrix.length; x++) { - for (y = 0; y < dataMatrix[x].length; y++) { - if (dataMatrix[x][y]) { - dataMatrix[x][y].pointRight = x < dataMatrix.length - 1 ? dataMatrix[x + 1][y] : undefined; - dataMatrix[x][y].pointTop = y < dataMatrix[x].length - 1 ? dataMatrix[x][y + 1] : undefined; - dataMatrix[x][y].pointCross = x < dataMatrix.length - 1 && y < dataMatrix[x].length - 1 ? dataMatrix[x + 1][y + 1] : undefined; - } - } - } - } else { - // 'dot', 'dot-line', etc. - // copy all values from the google data table to a list with Point3d objects - for (i = 0; i < data.length; i++) { - point = new Point3d(); - point.x = data[i][this.colX] || 0; - point.y = data[i][this.colY] || 0; - point.z = data[i][this.colZ] || 0; + /** + * Parse a single statement. Can be a an attribute statement, node + * statement, a series of node statements and edge statements, or a + * parameter. + * @param {Object} graph + */ + function parseStatement(graph) { + // parse subgraph + var subgraph = parseSubgraph(graph); + if (subgraph) { + // edge statements + parseEdge(graph, subgraph); - if (this.colValue !== undefined) { - point.value = data[i][this.colValue] || 0; - } + return; + } - obj = {}; - obj.point = point; - obj.bottom = new Point3d(point.x, point.y, this.zMin); - obj.trans = undefined; - obj.screen = undefined; + // parse an attribute statement + var attr = parseAttributeStatement(graph); + if (attr) { + return; + } - dataPoints.push(obj); - } + // parse node + if (tokenType != TOKENTYPE.IDENTIFIER) { + throw newSyntaxError('Identifier expected'); } + var id = token; // id can be a string or a number + getToken(); - return dataPoints; - }; + if (token === '=') { + // id statement + getToken(); + if (tokenType != TOKENTYPE.IDENTIFIER) { + throw newSyntaxError('Identifier expected'); + } + graph[id] = token; + getToken(); + // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] " + } else { + parseNodeStatement(graph, id); + } + } /** - * Create the main frame for the Graph3d. - * This function is executed once when a Graph3d object is created. The frame - * contains a canvas, and this canvas contains all objects like the axis and - * nodes. + * Parse a subgraph + * @param {Object} graph parent graph object + * @return {Object | null} subgraph */ - Graph3d.prototype.create = function () { - // remove all elements from the container element. - while (this.containerElement.hasChildNodes()) { - this.containerElement.removeChild(this.containerElement.firstChild); - } + function parseSubgraph(graph) { + var subgraph = null; - this.frame = document.createElement('div'); - this.frame.style.position = 'relative'; - this.frame.style.overflow = 'hidden'; + // optional subgraph keyword + if (token === 'subgraph') { + subgraph = {}; + subgraph.type = 'subgraph'; + getToken(); - // create the graph canvas (HTML canvas element) - this.frame.canvas = document.createElement('canvas'); - this.frame.canvas.style.position = 'relative'; - this.frame.appendChild(this.frame.canvas); - //if (!this.frame.canvas.getContext) { - { - var noCanvas = document.createElement('DIV'); - noCanvas.style.color = 'red'; - noCanvas.style.fontWeight = 'bold'; - noCanvas.style.padding = '10px'; - noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; - this.frame.canvas.appendChild(noCanvas); + // optional graph id + if (tokenType === TOKENTYPE.IDENTIFIER) { + subgraph.id = token; + getToken(); + } } - this.frame.filter = document.createElement('div'); - this.frame.filter.style.position = 'absolute'; - this.frame.filter.style.bottom = '0px'; - this.frame.filter.style.left = '0px'; - this.frame.filter.style.width = '100%'; - this.frame.appendChild(this.frame.filter); + // open angle bracket + if (token === '{') { + getToken(); - // add event listeners to handle moving and zooming the contents - var me = this; - var onmousedown = function onmousedown(event) { - me._onMouseDown(event); - }; - var ontouchstart = function ontouchstart(event) { - me._onTouchStart(event); - }; - var onmousewheel = function onmousewheel(event) { - me._onWheel(event); - }; - var ontooltip = function ontooltip(event) { - me._onTooltip(event); - }; - // TODO: these events are never cleaned up... can give a 'memory leakage' + if (!subgraph) { + subgraph = {}; + } + subgraph.parent = graph; + subgraph.node = graph.node; + subgraph.edge = graph.edge; + subgraph.graph = graph.graph; - util.addEventListener(this.frame.canvas, 'keydown', onkeydown); - util.addEventListener(this.frame.canvas, 'mousedown', onmousedown); - util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart); - util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel); - util.addEventListener(this.frame.canvas, 'mousemove', ontooltip); + // statements + parseStatements(subgraph); - // add the new graph to the container element - this.containerElement.appendChild(this.frame); - }; + // close angle bracket + if (token != '}') { + throw newSyntaxError('Angle bracket } expected'); + } + getToken(); - /** - * Set a new size for the graph - * @param {string} width Width in pixels or percentage (for example '800px' - * or '50%') - * @param {string} height Height in pixels or percentage (for example '400px' - * or '30%') - */ - Graph3d.prototype.setSize = function (width, height) { - this.frame.style.width = width; - this.frame.style.height = height; + // remove temporary default options + delete subgraph.node; + delete subgraph.edge; + delete subgraph.graph; + delete subgraph.parent; - this._resizeCanvas(); - }; + // register at the parent graph + if (!graph.subgraphs) { + graph.subgraphs = []; + } + graph.subgraphs.push(subgraph); + } + + return subgraph; + } /** - * Resize the canvas to the current size of the frame + * parse an attribute statement like "node [shape=circle fontSize=16]". + * Available keywords are 'node', 'edge', 'graph'. + * The previous list with default attributes will be replaced + * @param {Object} graph + * @returns {String | null} keyword Returns the name of the parsed attribute + * (node, edge, graph), or null if nothing + * is parsed. */ - Graph3d.prototype._resizeCanvas = function () { - this.frame.canvas.style.width = '100%'; - this.frame.canvas.style.height = '100%'; + function parseAttributeStatement(graph) { + // attribute statements + if (token === 'node') { + getToken(); - this.frame.canvas.width = this.frame.canvas.clientWidth; - this.frame.canvas.height = this.frame.canvas.clientHeight; + // node attributes + graph.node = parseAttributeList(); + return 'node'; + } else if (token === 'edge') { + getToken(); - // adjust with for margin - this.frame.filter.style.width = this.frame.canvas.clientWidth - 2 * 10 + 'px'; - }; + // edge attributes + graph.edge = parseAttributeList(); + return 'edge'; + } else if (token === 'graph') { + getToken(); - /** - * Start animation - */ - Graph3d.prototype.animationStart = function () { - if (!this.frame.filter || !this.frame.filter.slider) throw 'No animation available'; + // graph attributes + graph.graph = parseAttributeList(); + return 'graph'; + } - this.frame.filter.slider.play(); - }; + return null; + } /** - * Stop animation + * parse a node statement + * @param {Object} graph + * @param {String | Number} id */ - Graph3d.prototype.animationStop = function () { - if (!this.frame.filter || !this.frame.filter.slider) return; + function parseNodeStatement(graph, id) { + // node statement + var node = { + id: id + }; + var attr = parseAttributeList(); + if (attr) { + node.attr = attr; + } + addNode(graph, node); - this.frame.filter.slider.stop(); - }; + // edge statements + parseEdge(graph, id); + } /** - * Resize the center position based on the current values in this.defaultXCenter - * and this.defaultYCenter (which are strings with a percentage or a value - * in pixels). The center positions are the variables this.xCenter - * and this.yCenter + * Parse an edge or a series of edges + * @param {Object} graph + * @param {String | Number} from Id of the from node */ - Graph3d.prototype._resizeCenter = function () { - // calculate the horizontal center position - if (this.defaultXCenter.charAt(this.defaultXCenter.length - 1) === '%') { - this.xcenter = parseFloat(this.defaultXCenter) / 100 * this.frame.canvas.clientWidth; - } else { - this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px - } + function parseEdge(graph, from) { + while (token === '->' || token === '--') { + var to; + var type = token; + getToken(); - // calculate the vertical center position - if (this.defaultYCenter.charAt(this.defaultYCenter.length - 1) === '%') { - this.ycenter = parseFloat(this.defaultYCenter) / 100 * (this.frame.canvas.clientHeight - this.frame.filter.clientHeight); - } else { - this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px - } - }; + var subgraph = parseSubgraph(graph); + if (subgraph) { + to = subgraph; + } else { + if (tokenType != TOKENTYPE.IDENTIFIER) { + throw newSyntaxError('Identifier or subgraph expected'); + } + to = token; + addNode(graph, { + id: to + }); + getToken(); + } - /** - * Set the rotation and distance of the camera - * @param {Object} pos An object with the camera position. The object - * contains three parameters: - * - horizontal {Number} - * The horizontal rotation, between 0 and 2*PI. - * Optional, can be left undefined. - * - vertical {Number} - * 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. - * - distance {Number} - * The (normalized) distance of the camera to the - * center of the graph, a value between 0.71 and 5.0. - * Optional, can be left undefined. - */ - Graph3d.prototype.setCameraPosition = function (pos) { - if (pos === undefined) { - return; - } + // parse edge attributes + var attr = parseAttributeList(); - if (pos.horizontal !== undefined && pos.vertical !== undefined) { - this.camera.setArmRotation(pos.horizontal, pos.vertical); - } + // create edge + var edge = createEdge(graph, from, to, type, attr); + addEdge(graph, edge); - if (pos.distance !== undefined) { - this.camera.setArmLength(pos.distance); + from = to; } - - this.redraw(); - }; + } /** - * Retrieve the current camera rotation - * @return {object} An object with parameters horizontal, vertical, and - * distance + * Parse a set with attributes, + * for example [label="1.000", shape=solid] + * @return {Object | null} attr */ - Graph3d.prototype.getCameraPosition = function () { - var pos = this.camera.getArmRotation(); - pos.distance = this.camera.getArmLength(); - return pos; - }; + function parseAttributeList() { + var attr = null; - /** - * Load data into the 3D Graph - */ - Graph3d.prototype._readData = function (data) { - // read the data - this._dataInitialize(data, this.style); + while (token === '[') { + getToken(); + attr = {}; + while (token !== '' && token != ']') { + if (tokenType != TOKENTYPE.IDENTIFIER) { + throw newSyntaxError('Attribute name expected'); + } + var name = token; - if (this.dataFilter) { - // apply filtering - this.dataPoints = this.dataFilter._getDataPoints(); - } else { - // no filtering. load all data - this.dataPoints = this._getDataPoints(this.dataTable); - } + getToken(); + if (token != '=') { + throw newSyntaxError('Equal sign = expected'); + } + getToken(); - // draw the filter - this._redrawFilter(); - }; + if (tokenType != TOKENTYPE.IDENTIFIER) { + throw newSyntaxError('Attribute value expected'); + } + var value = token; + setValue(attr, name, value); // name can be a path - /** - * Replace the dataset of the Graph3d - * @param {Array | DataSet | DataView} data - */ - Graph3d.prototype.setData = function (data) { - this._readData(data); - this.redraw(); + getToken(); + if (token == ',') { + getToken(); + } + } - // start animation when option is true - if (this.animationAutoStart && this.dataFilter) { - this.animationStart(); + if (token != ']') { + throw newSyntaxError('Bracket ] expected'); + } + getToken(); } - }; + + return attr; + } /** - * Update the options. Options will be merged with current options - * @param {Object} options + * Create a syntax error with extra information on current token and index. + * @param {String} message + * @returns {SyntaxError} err */ - Graph3d.prototype.setOptions = function (options) { - var cameraPosition = undefined; - - this.animationStop(); - - if (options !== undefined) { - // retrieve parameter values - if (options.width !== undefined) this.width = options.width; - if (options.height !== undefined) this.height = options.height; - - if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter; - if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter; - - if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel; - if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel; - if (options.xLabel !== undefined) this.xLabel = options.xLabel; - if (options.yLabel !== undefined) this.yLabel = options.yLabel; - if (options.zLabel !== undefined) this.zLabel = options.zLabel; + function newSyntaxError(message) { + return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')'); + } - if (options.xValueLabel !== undefined) this.xValueLabel = options.xValueLabel; - if (options.yValueLabel !== undefined) this.yValueLabel = options.yValueLabel; - if (options.zValueLabel !== undefined) this.zValueLabel = options.zValueLabel; + /** + * Chop off text after a maximum length + * @param {String} text + * @param {Number} maxLength + * @returns {String} + */ + function chop(text, maxLength) { + return text.length <= maxLength ? text : text.substr(0, 27) + '...'; + } - if (options.style !== undefined) { - var styleNumber = this._getStyleNumber(options.style); - if (styleNumber !== -1) { - this.style = styleNumber; + /** + * Execute a function fn for each pair of elements in two arrays + * @param {Array | *} array1 + * @param {Array | *} array2 + * @param {function} fn + */ + function forEach2(array1, array2, fn) { + if (Array.isArray(array1)) { + array1.forEach(function (elem1) { + if (Array.isArray(array2)) { + array2.forEach(function (elem2) { + fn(elem1, elem2); + }); + } else { + fn(elem1, array2); } + }); + } else { + if (Array.isArray(array2)) { + array2.forEach(function (elem2) { + fn(array1, elem2); + }); + } else { + fn(array1, array2); } - if (options.showGrid !== undefined) this.showGrid = options.showGrid; - if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective; - if (options.showShadow !== undefined) this.showShadow = options.showShadow; - if (options.tooltip !== undefined) this.showTooltip = options.tooltip; - if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls; - if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio; - if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio; - - if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval; - if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload; - if (options.animationAutoStart !== undefined) this.animationAutoStart = options.animationAutoStart; - - if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth; - if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth; - - if (options.xMin !== undefined) this.defaultXMin = options.xMin; - if (options.xStep !== undefined) this.defaultXStep = options.xStep; - if (options.xMax !== undefined) this.defaultXMax = options.xMax; - if (options.yMin !== undefined) this.defaultYMin = options.yMin; - if (options.yStep !== undefined) this.defaultYStep = options.yStep; - if (options.yMax !== undefined) this.defaultYMax = options.yMax; - if (options.zMin !== undefined) this.defaultZMin = options.zMin; - if (options.zStep !== undefined) this.defaultZStep = options.zStep; - if (options.zMax !== undefined) this.defaultZMax = options.zMax; - if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin; - if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax; + } + } - if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition; + /** + * Set a nested property on an object + * When nested objects are missing, they will be created. + * For example setProp({}, 'font.color', 'red') will return {font: {color: 'red'}} + * @param {Object} object + * @param {string} path A dot separated string like 'font.color' + * @param {*} value Value for the property + * @return {Object} Returns the original object, allows for chaining. + */ + function setProp(object, path, value) { + var names = path.split('.'); + var prop = names.pop(); - if (cameraPosition !== undefined) { - this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical); - this.camera.setArmLength(cameraPosition.distance); - } else { - this.camera.setArmRotation(1, 0.5); - this.camera.setArmLength(1.7); + // traverse over the nested objects + var obj = object; + for (var i = 0; i < names.length; i++) { + var name = names[i]; + if (!(name in obj)) { + obj[name] = {}; } + obj = obj[name]; } - this._setBackgroundColor(options && options.backgroundColor); + // set the property value + obj[prop] = value; - this.setSize(this.width, this.height); + return object; + } - // re-load the data - if (this.dataTable) { - this.setData(this.dataTable); - } + /** + * Convert an object with DOT attributes to their vis.js equivalents. + * @param {Object} attr Object with DOT attributes + * @param {Object} mapping + * @return {Object} Returns an object with vis.js attributes + */ + function convertAttr(attr, mapping) { + var converted = {}; - // start animation when option is true - if (this.animationAutoStart && this.dataFilter) { - this.animationStart(); + for (var prop in attr) { + if (attr.hasOwnProperty(prop)) { + var visProp = mapping[prop]; + if (Array.isArray(visProp)) { + visProp.forEach(function (visPropI) { + setProp(converted, visPropI, attr[prop]); + }); + } else if (typeof visProp === 'string') { + setProp(converted, visProp, attr[prop]); + } else { + setProp(converted, prop, attr[prop]); + } + } } - }; + + return converted; + } /** - * Redraw the Graph. + * Convert a string containing a graph in DOT language into a map containing + * with nodes and edges in the format of graph. + * @param {String} data Text containing a graph in DOT-notation + * @return {Object} graphData */ - Graph3d.prototype.redraw = function () { - if (this.dataPoints === undefined) { - throw 'Error: graph data not initialized'; - } - - this._resizeCanvas(); - this._resizeCenter(); - this._redrawSlider(); - this._redrawClear(); - this._redrawAxis(); + function DOTToGraph(data) { + // parse the DOT file + var dotData = parseDOT(data); + var graphData = { + nodes: [], + edges: [], + options: {} + }; - if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { - this._redrawDataGrid(); - } else if (this.style === Graph3d.STYLE.LINE) { - this._redrawDataLine(); - } else if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { - this._redrawDataBar(); - } else { - // style is DOT, DOTLINE, DOTCOLOR, DOTSIZE - this._redrawDataDot(); + // copy the nodes + if (dotData.nodes) { + dotData.nodes.forEach(function (dotNode) { + var graphNode = { + id: dotNode.id, + label: String(dotNode.label || dotNode.id) + }; + merge(graphNode, convertAttr(dotNode.attr, NODE_ATTR_MAPPING)); + if (graphNode.image) { + graphNode.shape = 'image'; + } + graphData.nodes.push(graphNode); + }); } - this._redrawInfo(); - this._redrawLegend(); - }; + // copy the edges + if (dotData.edges) { + /** + * Convert an edge in DOT format to an edge with VisGraph format + * @param {Object} dotEdge + * @returns {Object} graphEdge + */ + var convertEdge = function convertEdge(dotEdge) { + var graphEdge = { + from: dotEdge.from, + to: dotEdge.to + }; + merge(graphEdge, convertAttr(dotEdge.attr, EDGE_ATTR_MAPPING)); + graphEdge.arrows = dotEdge.type === '->' ? 'to' : undefined; - /** - * Clear the canvas before redrawing - */ - Graph3d.prototype._redrawClear = function () { - var canvas = this.frame.canvas; - var ctx = canvas.getContext('2d'); + return graphEdge; + }; - ctx.clearRect(0, 0, canvas.width, canvas.height); - }; + dotData.edges.forEach(function (dotEdge) { + var from, to; + if (dotEdge.from instanceof Object) { + from = dotEdge.from.nodes; + } else { + from = { + id: dotEdge.from + }; + } - /** - * Redraw the legend showing the colors - */ - Graph3d.prototype._redrawLegend = function () { - var y; + // TODO: support of solid/dotted/dashed edges (attr = 'style') + // TODO: support for attributes 'dir' and 'arrowhead' (edge arrows) - if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { + if (dotEdge.to instanceof Object) { + to = dotEdge.to.nodes; + } else { + to = { + id: dotEdge.to + }; + } - var dotSize = this.frame.clientWidth * 0.02; + if (dotEdge.from instanceof Object && dotEdge.from.edges) { + dotEdge.from.edges.forEach(function (subEdge) { + var graphEdge = convertEdge(subEdge); + graphData.edges.push(graphEdge); + }); + } - var widthMin, widthMax; - if (this.style === Graph3d.STYLE.DOTSIZE) { - widthMin = dotSize / 2; // px - widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function - } else { - widthMin = 20; // px - widthMax = 20; // px - } + forEach2(from, to, function (from, to) { + var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr); + var graphEdge = convertEdge(subEdge); + graphData.edges.push(graphEdge); + }); - var height = Math.max(this.frame.clientHeight * 0.25, 100); - var top = this.margin; - var right = this.frame.clientWidth - this.margin; - var left = right - widthMax; - var bottom = top + height; + if (dotEdge.to instanceof Object && dotEdge.to.edges) { + dotEdge.to.edges.forEach(function (subEdge) { + var graphEdge = convertEdge(subEdge); + graphData.edges.push(graphEdge); + }); + } + }); } - var canvas = this.frame.canvas; - var ctx = canvas.getContext('2d'); - ctx.lineWidth = 1; - ctx.font = '14px arial'; // TODO: put in options + // copy the options + if (dotData.attr) { + graphData.options = dotData.attr; + } - if (this.style === Graph3d.STYLE.DOTCOLOR) { - // draw the color bar - var ymin = 0; - var ymax = height; // Todo: make height customizable - for (y = ymin; y < ymax; y++) { - var f = (y - ymin) / (ymax - ymin); + return graphData; + } - //var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function - var hue = f * 240; - var color = this._hsv2rgb(hue, 1, 1); + // exports + exports.parseDOT = parseDOT; + exports.DOTToGraph = DOTToGraph; - ctx.strokeStyle = color; - ctx.beginPath(); - ctx.moveTo(left, top + y); - ctx.lineTo(right, top + y); - ctx.stroke(); +/***/ }, +/* 39 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + function parseGephi(gephiJSON, optionsObj) { + var edges = []; + var nodes = []; + var options = { + edges: { + inheritColor: false + }, + nodes: { + fixed: false, + parseColor: false } + }; - ctx.strokeStyle = this.colorAxis; - ctx.strokeRect(left, top, widthMax, height); + if (optionsObj !== undefined) { + if (optionsObj.fixed !== undefined) { + options.nodes.fixed = optionsObj.fixed; + } + if (optionsObj.parseColor !== undefined) { + options.nodes.parseColor = optionsObj.parseColor; + } + if (optionsObj.inheritColor !== undefined) { + options.edges.inheritColor = optionsObj.inheritColor; + } } - if (this.style === Graph3d.STYLE.DOTSIZE) { - // draw border around color bar - ctx.strokeStyle = this.colorAxis; - ctx.fillStyle = this.colorDot; - ctx.beginPath(); - ctx.moveTo(left, top); - ctx.lineTo(right, top); - ctx.lineTo(right - widthMax + widthMin, bottom); - ctx.lineTo(left, bottom); - ctx.closePath(); - ctx.fill(); - ctx.stroke(); + var gEdges = gephiJSON.edges; + var gNodes = gephiJSON.nodes; + for (var i = 0; i < gEdges.length; i++) { + var edge = {}; + var gEdge = gEdges[i]; + edge['id'] = gEdge.id; + edge['from'] = gEdge.source; + edge['to'] = gEdge.target; + edge['attributes'] = gEdge.attributes; + // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined; + // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size; + if (gEdge.color && options.inheritColor === false) { + edge['color'] = gEdge.color; + } + edges.push(edge); } - if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { - // print values along the color bar - var gridLineLen = 5; // px - var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax - this.valueMin) / 5, true); - step.start(); - if (step.getCurrent() < this.valueMin) { - step.next(); + for (var i = 0; i < gNodes.length; i++) { + var node = {}; + var gNode = gNodes[i]; + node['id'] = gNode.id; + node['attributes'] = gNode.attributes; + node['title'] = gNode.title; + node['x'] = gNode.x; + node['y'] = gNode.y; + node['label'] = gNode.label; + if (options.nodes.parseColor === true) { + node['color'] = gNode.color; + } else { + node['color'] = gNode.color !== undefined ? { background: gNode.color, border: gNode.color, highlight: { background: gNode.color, border: gNode.color }, hover: { background: gNode.color, border: gNode.color } } : undefined; } - while (!step.end()) { - y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height; + node['size'] = gNode.size; + node['fixed'] = options.nodes.fixed && gNode.x !== undefined && gNode.y !== undefined; + nodes.push(node); + } - ctx.beginPath(); - ctx.moveTo(left - gridLineLen, y); - ctx.lineTo(left, y); - ctx.stroke(); + return { nodes: nodes, edges: edges }; + } - ctx.textAlign = 'right'; - ctx.textBaseline = 'middle'; - ctx.fillStyle = this.colorAxis; - ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y); + exports.parseGephi = parseGephi; - step.next(); - } +/***/ }, +/* 40 */ +/***/ function(module, exports, __webpack_require__) { - ctx.textAlign = 'right'; - ctx.textBaseline = 'top'; - var label = this.legendLabel; - ctx.fillText(label, right, bottom + this.margin); - } - }; + // first check if moment.js is already loaded in the browser window, if so, + // use this instance. Else, load via commonjs. + 'use strict'; - /** - * Redraw the filter - */ - Graph3d.prototype._redrawFilter = function () { - this.frame.filter.innerHTML = ''; + module.exports = typeof window !== 'undefined' && window['moment'] || __webpack_require__(70); - if (this.dataFilter) { - var options = { - 'visible': this.showAnimationControls - }; - var slider = new Slider(this.frame.filter, options); - this.frame.filter.slider = slider; +/***/ }, +/* 41 */ +/***/ function(module, exports, __webpack_require__) { - // TODO: css here is not nice here... - this.frame.filter.style.padding = '10px'; - //this.frame.filter.style.backgroundColor = '#EFEFEF'; + // Only load hammer.js when in a browser environment + // (loading hammer.js in a node.js environment gives errors) + 'use strict'; - slider.setValues(this.dataFilter.values); - slider.setPlayInterval(this.animationInterval); + if (typeof window !== 'undefined') { + var propagating = __webpack_require__(71); + var Hammer = window['Hammer'] || __webpack_require__(72); + module.exports = propagating(Hammer, { + preventDefault: 'mouse' + }); + } else { + module.exports = function () { + throw Error('hammer.js is only available in a browser, not in node.js.'); + }; + } - // create an event handler - var me = this; - var onchange = function onchange() { - var index = slider.getIndex(); +/***/ }, +/* 42 */ +/***/ function(module, exports, __webpack_require__) { - me.dataFilter.selectValue(index); - me.dataPoints = me.dataFilter._getDataPoints(); + /* WEBPACK VAR INJECTION */(function(global) {'use strict'; - me.redraw(); - }; - slider.setOnChangeCallback(onchange); - } else { - this.frame.filter.slider = undefined; - } - }; + var _rng; - /** - * Redraw the slider - */ - Graph3d.prototype._redrawSlider = function () { - if (this.frame.filter.slider !== undefined) { - this.frame.filter.slider.redraw(); - } - }; - - /** - * Redraw common information - */ - Graph3d.prototype._redrawInfo = function () { - if (this.dataFilter) { - var canvas = this.frame.canvas; - var ctx = canvas.getContext('2d'); + var globalVar = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : null; - ctx.font = '14px arial'; // TODO: put in options - ctx.lineStyle = 'gray'; - ctx.fillStyle = 'gray'; - ctx.textAlign = 'left'; - ctx.textBaseline = 'top'; + if (globalVar && globalVar.crypto && crypto.getRandomValues) { + // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto + // Moderately fast, high quality + var _rnds8 = new Uint8Array(16); + _rng = function whatwgRNG() { + crypto.getRandomValues(_rnds8); + return _rnds8; + }; + } - var x = this.margin; - var y = this.margin; - ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y); - } - }; + if (!_rng) { + // Math.random()-based (RNG) + // + // If all else fails, use Math.random(). It's fast, but is of unspecified + // quality. + var _rnds = new Array(16); + _rng = function () { + for (var i = 0, r; i < 16; i++) { + if ((i & 3) === 0) r = Math.random() * 4294967296; + _rnds[i] = r >>> ((i & 3) << 3) & 255; + } - /** - * Redraw the axis - */ - Graph3d.prototype._redrawAxis = function () { - var canvas = this.frame.canvas, - ctx = canvas.getContext('2d'), - from, - to, - step, - prettyStep, - text, - xText, - yText, - zText, - offset, - xOffset, - yOffset, - xMin2d, - xMax2d; + return _rnds; + }; + } - // TODO: get the actual rendered style of the containerElement - //ctx.font = this.containerElement.style.font; - ctx.font = 24 / this.camera.getArmLength() + 'px arial'; + // uuid.js + // + // Copyright (c) 2010-2012 Robert Kieffer + // MIT License - http://opensource.org/licenses/mit-license.php - // calculate the length for the short grid lines - var gridLenX = 0.025 / this.scale.x; - var gridLenY = 0.025 / this.scale.y; - var textMargin = 5 / this.camera.getArmLength(); // px - var armAngle = this.camera.getArmRotation().horizontal; + // Unique ID creation requires a high quality random # generator. We feature + // detect to determine the best RNG source, normalizing to a function that + // returns 128-bits of randomness, since that's what's usually required - // draw x-grid lines - ctx.lineWidth = 1; - prettyStep = this.defaultXStep === undefined; - step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep); - step.start(); - if (step.getCurrent() < this.xMin) { - step.next(); - } - while (!step.end()) { - var x = step.getCurrent(); + //var _rng = require('./rng'); - if (this.showGrid) { - from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); - to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); - ctx.strokeStyle = this.colorGrid; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); - } else { - from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); - to = this._convert3Dto2D(new Point3d(x, this.yMin + gridLenX, this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); + // Maps for number <-> hex string conversion + var _byteToHex = []; + var _hexToByte = {}; + for (var i = 0; i < 256; i++) { + _byteToHex[i] = (i + 256).toString(16).substr(1); + _hexToByte[_byteToHex[i]] = i; + } - from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); - to = this._convert3Dto2D(new Point3d(x, this.yMax - gridLenX, this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); - } + // **`parse()` - Parse a UUID into it's component bytes** + function parse(s, buf, offset) { + var i = buf && offset || 0, + ii = 0; - yText = Math.cos(armAngle) > 0 ? this.yMin : this.yMax; - text = this._convert3Dto2D(new Point3d(x, yText, this.zMin)); - if (Math.cos(armAngle * 2) > 0) { - ctx.textAlign = 'center'; - ctx.textBaseline = 'top'; - text.y += textMargin; - } else if (Math.sin(armAngle * 2) < 0) { - ctx.textAlign = 'right'; - ctx.textBaseline = 'middle'; - } else { - ctx.textAlign = 'left'; - ctx.textBaseline = 'middle'; + buf = buf || []; + s.toLowerCase().replace(/[0-9a-f]{2}/g, function (oct) { + if (ii < 16) { + // Don't overflow! + buf[i + ii++] = _hexToByte[oct]; } - ctx.fillStyle = this.colorAxis; - ctx.fillText(' ' + this.xValueLabel(step.getCurrent()) + ' ', text.x, text.y); + }); - step.next(); + // Zero out remaining bytes if string was short + while (ii < 16) { + buf[i + ii++] = 0; } - // draw y-grid lines - ctx.lineWidth = 1; - prettyStep = this.defaultYStep === undefined; - step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep); - step.start(); - if (step.getCurrent() < this.yMin) { - step.next(); - } - while (!step.end()) { - if (this.showGrid) { - from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); - to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); - ctx.strokeStyle = this.colorGrid; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); - } else { - from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); - to = this._convert3Dto2D(new Point3d(this.xMin + gridLenY, step.getCurrent(), this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); + return buf; + } - from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); - to = this._convert3Dto2D(new Point3d(this.xMax - gridLenY, step.getCurrent(), this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); - } + // **`unparse()` - Convert UUID byte array (ala parse()) into a string** + function unparse(buf, offset) { + var i = offset || 0, + bth = _byteToHex; + return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]]; + } - xText = Math.sin(armAngle) > 0 ? this.xMin : this.xMax; - text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin)); - if (Math.cos(armAngle * 2) < 0) { - ctx.textAlign = 'center'; - ctx.textBaseline = 'top'; - text.y += textMargin; - } else if (Math.sin(armAngle * 2) > 0) { - ctx.textAlign = 'right'; - ctx.textBaseline = 'middle'; - } else { - ctx.textAlign = 'left'; - ctx.textBaseline = 'middle'; - } - ctx.fillStyle = this.colorAxis; - ctx.fillText(' ' + this.yValueLabel(step.getCurrent()) + ' ', text.x, text.y); + // **`v1()` - Generate time-based UUID** + // + // Inspired by https://github.com/LiosK/UUID.js + // and http://docs.python.org/library/uuid.html - step.next(); - } + // random #'s we need to init node and clockseq + var _seedBytes = _rng(); - // draw z-grid lines and axis - ctx.lineWidth = 1; - prettyStep = this.defaultZStep === undefined; - step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep); - step.start(); - if (step.getCurrent() < this.zMin) { - step.next(); - } - xText = Math.cos(armAngle) > 0 ? this.xMin : this.xMax; - yText = Math.sin(armAngle) < 0 ? this.yMin : this.yMax; - while (!step.end()) { - // TODO: make z-grid lines really 3d? - from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent())); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(from.x - textMargin, from.y); - ctx.stroke(); + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + var _nodeId = [_seedBytes[0] | 1, _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]]; - ctx.textAlign = 'right'; - ctx.textBaseline = 'middle'; - ctx.fillStyle = this.colorAxis; - ctx.fillText(this.zValueLabel(step.getCurrent()) + ' ', from.x - 5, from.y); + // Per 4.2.2, randomize (14 bit) clockseq + var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 16383; - step.next(); - } - ctx.lineWidth = 1; - from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); - to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); + // Previous uuid creation time + var _lastMSecs = 0, + _lastNSecs = 0; - // draw x-axis - ctx.lineWidth = 1; - // line at yMin - xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); - xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(xMin2d.x, xMin2d.y); - ctx.lineTo(xMax2d.x, xMax2d.y); - ctx.stroke(); - // line at ymax - xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); - xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(xMin2d.x, xMin2d.y); - ctx.lineTo(xMax2d.x, xMax2d.y); - ctx.stroke(); + // See https://github.com/broofa/node-uuid for API details + function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; - // draw y-axis - ctx.lineWidth = 1; - // line at xMin - from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); - to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); - // line at xMax - from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); - to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); + options = options || {}; - // draw x-label - var xLabel = this.xLabel; - if (xLabel.length > 0) { - yOffset = 0.1 / this.scale.y; - xText = (this.xMin + this.xMax) / 2; - yText = Math.cos(armAngle) > 0 ? this.yMin - yOffset : this.yMax + yOffset; - text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); - if (Math.cos(armAngle * 2) > 0) { - ctx.textAlign = 'center'; - ctx.textBaseline = 'top'; - } else if (Math.sin(armAngle * 2) < 0) { - ctx.textAlign = 'right'; - ctx.textBaseline = 'middle'; - } else { - ctx.textAlign = 'left'; - ctx.textBaseline = 'middle'; - } - ctx.fillStyle = this.colorAxis; - ctx.fillText(xLabel, text.x, text.y); + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; + + // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); + + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; + + // Time since last uuid creation (in msecs) + var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; + + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 16383; } - // draw y-label - var yLabel = this.yLabel; - if (yLabel.length > 0) { - xOffset = 0.1 / this.scale.x; - xText = Math.sin(armAngle) > 0 ? this.xMin - xOffset : this.xMax + xOffset; - yText = (this.yMin + this.yMax) / 2; - text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); - if (Math.cos(armAngle * 2) < 0) { - ctx.textAlign = 'center'; - ctx.textBaseline = 'top'; - } else if (Math.sin(armAngle * 2) > 0) { - ctx.textAlign = 'right'; - ctx.textBaseline = 'middle'; - } else { - ctx.textAlign = 'left'; - ctx.textBaseline = 'middle'; - } - ctx.fillStyle = this.colorAxis; - ctx.fillText(yLabel, text.x, text.y); + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; } - // draw z-label - var zLabel = this.zLabel; - if (zLabel.length > 0) { - offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis? - xText = Math.cos(armAngle) > 0 ? this.xMin : this.xMax; - yText = Math.sin(armAngle) < 0 ? this.yMin : this.yMax; - zText = (this.zMin + this.zMax) / 2; - text = this._convert3Dto2D(new Point3d(xText, yText, zText)); - ctx.textAlign = 'right'; - ctx.textBaseline = 'middle'; - ctx.fillStyle = this.colorAxis; - ctx.fillText(zLabel, text.x - offset, text.y); + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); } - }; - /** - * Calculate the color based on the given value. - * @param {Number} H Hue, a value be between 0 and 360 - * @param {Number} S Saturation, a value between 0 and 1 - * @param {Number} V Value, a value between 0 and 1 - */ - Graph3d.prototype._hsv2rgb = function (H, S, V) { - var R, G, B, C, Hi, X; + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; - C = V * S; - Hi = Math.floor(H / 60); // hi = 0,1,2,3,4,5 - X = C * (1 - Math.abs(H / 60 % 2 - 1)); + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; - switch (Hi) { - case 0: - R = C;G = X;B = 0;break; - case 1: - R = X;G = C;B = 0;break; - case 2: - R = 0;G = C;B = X;break; - case 3: - R = 0;G = X;B = C;break; - case 4: - R = X;G = 0;B = C;break; - case 5: - R = C;G = 0;B = X;break; + // `time_low` + var tl = ((msecs & 268435455) * 10000 + nsecs) % 4294967296; + b[i++] = tl >>> 24 & 255; + b[i++] = tl >>> 16 & 255; + b[i++] = tl >>> 8 & 255; + b[i++] = tl & 255; - default: - R = 0;G = 0;B = 0;break; - } + // `time_mid` + var tmh = msecs / 4294967296 * 10000 & 268435455; + b[i++] = tmh >>> 8 & 255; + b[i++] = tmh & 255; - return 'RGB(' + parseInt(R * 255) + ',' + parseInt(G * 255) + ',' + parseInt(B * 255) + ')'; - }; + // `time_high_and_version` + b[i++] = tmh >>> 24 & 15 | 16; // include version + b[i++] = tmh >>> 16 & 255; - /** - * Draw all datapoints as a grid - * This function can be used when the style is 'grid' - */ - Graph3d.prototype._redrawDataGrid = function () { - var canvas = this.frame.canvas, - ctx = canvas.getContext('2d'), - point, - right, - top, - cross, - i, - topSideVisible, - fillStyle, - strokeStyle, - lineWidth, - h, - s, - v, - zAvg; + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 128; - if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? + // `clock_seq_low` + b[i++] = clockseq & 255; - // calculate the translations and screen position of all points - for (i = 0; i < this.dataPoints.length; i++) { - var trans = this._convertPointToTranslation(this.dataPoints[i].point); - var screen = this._convertTranslationToScreen(trans); + // `node` + var node = options.node || _nodeId; + for (var n = 0; n < 6; n++) { + b[i + n] = node[n]; + } - this.dataPoints[i].trans = trans; - this.dataPoints[i].screen = screen; + return buf ? buf : unparse(b); + } - // calculate the translation of the point at the bottom (needed for sorting) - var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); - this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; - } + // **`v4()` - Generate random UUID** - // sort the points on depth of their (x,y) position (not on z) - var sortDepth = function sortDepth(a, b) { - return b.dist - a.dist; - }; - this.dataPoints.sort(sortDepth); + // See https://github.com/broofa/node-uuid for API details + function v4(options, buf, offset) { + // Deprecated - 'format' argument, as supported in v1.2 + var i = buf && offset || 0; - if (this.style === Graph3d.STYLE.SURFACE) { - for (i = 0; i < this.dataPoints.length; i++) { - point = this.dataPoints[i]; - right = this.dataPoints[i].pointRight; - top = this.dataPoints[i].pointTop; - cross = this.dataPoints[i].pointCross; + if (typeof options == 'string') { + buf = options == 'binary' ? new Array(16) : null; + options = null; + } + options = options || {}; - if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) { + var rnds = options.random || (options.rng || _rng)(); - if (this.showGrayBottom || this.showShadow) { - // calculate the cross product of the two vectors from center - // to left and right, in order to know whether we are looking at the - // bottom or at the top side. We can also use the cross product - // for calculating light intensity - var aDiff = Point3d.subtract(cross.trans, point.trans); - var bDiff = Point3d.subtract(top.trans, right.trans); - var crossproduct = Point3d.crossProduct(aDiff, bDiff); - var len = crossproduct.length(); - // FIXME: there is a bug with determining the surface side (shadow or colored) + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; - topSideVisible = crossproduct.z > 0; - } else { - topSideVisible = true; - } + // Copy bytes to buffer, if provided + if (buf) { + for (var ii = 0; ii < 16; ii++) { + buf[i + ii] = rnds[ii]; + } + } - if (topSideVisible) { - // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 - zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4; - h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; - s = 1; // saturation + return buf || unparse(rnds); + } - if (this.showShadow) { - v = Math.min(1 + crossproduct.x / len / 2, 1); // value. TODO: scale - fillStyle = this._hsv2rgb(h, s, v); - strokeStyle = fillStyle; - } else { - v = 1; - fillStyle = this._hsv2rgb(h, s, v); - strokeStyle = this.colorAxis; - } - } else { - fillStyle = 'gray'; - strokeStyle = this.colorAxis; - } - lineWidth = 0.5; + // Export public API + var uuid = v4; + uuid.v1 = v1; + uuid.v4 = v4; + uuid.parse = parse; + uuid.unparse = unparse; - ctx.lineWidth = lineWidth; - ctx.fillStyle = fillStyle; - ctx.strokeStyle = strokeStyle; - ctx.beginPath(); - ctx.moveTo(point.screen.x, point.screen.y); - ctx.lineTo(right.screen.x, right.screen.y); - ctx.lineTo(cross.screen.x, cross.screen.y); - ctx.lineTo(top.screen.x, top.screen.y); - ctx.closePath(); - ctx.fill(); - ctx.stroke(); - } - } - } else { - // grid style - for (i = 0; i < this.dataPoints.length; i++) { - point = this.dataPoints[i]; - right = this.dataPoints[i].pointRight; - top = this.dataPoints[i].pointTop; + module.exports = uuid; + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - if (point !== undefined) { - if (this.showPerspective) { - lineWidth = 2 / -point.trans.z; - } else { - lineWidth = 2 * -(this.eye.z / this.camera.getArmLength()); - } - } +/***/ }, +/* 43 */ +/***/ function(module, exports, __webpack_require__) { - if (point !== undefined && right !== undefined) { - // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 - zAvg = (point.point.z + right.point.z) / 2; - h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; + + /** + * Expose `Emitter`. + */ - ctx.lineWidth = lineWidth; - ctx.strokeStyle = this._hsv2rgb(h, 1, 1); - ctx.beginPath(); - ctx.moveTo(point.screen.x, point.screen.y); - ctx.lineTo(right.screen.x, right.screen.y); - ctx.stroke(); - } + module.exports = Emitter; - if (point !== undefined && top !== undefined) { - // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 - zAvg = (point.point.z + top.point.z) / 2; - h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; + /** + * Initialize a new `Emitter`. + * + * @api public + */ - ctx.lineWidth = lineWidth; - ctx.strokeStyle = this._hsv2rgb(h, 1, 1); - ctx.beginPath(); - ctx.moveTo(point.screen.x, point.screen.y); - ctx.lineTo(top.screen.x, top.screen.y); - ctx.stroke(); - } - } - } + function Emitter(obj) { + if (obj) return mixin(obj); }; /** - * Draw all datapoints as dots. - * This function can be used when the style is 'dot' or 'dot-line' + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private */ - Graph3d.prototype._redrawDataDot = function () { - var canvas = this.frame.canvas; - var ctx = canvas.getContext('2d'); - var i; - - if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? - - // calculate the translations of all points - for (i = 0; i < this.dataPoints.length; i++) { - var trans = this._convertPointToTranslation(this.dataPoints[i].point); - var screen = this._convertTranslationToScreen(trans); - this.dataPoints[i].trans = trans; - this.dataPoints[i].screen = screen; - // calculate the distance from the point at the bottom to the camera - var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); - this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; + function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; } + return obj; + } - // order the translated points by depth - var sortDepth = function sortDepth(a, b) { - return b.dist - a.dist; - }; - this.dataPoints.sort(sortDepth); - - // draw the datapoints as colored circles - var dotSize = this.frame.clientWidth * 0.02; // px - for (i = 0; i < this.dataPoints.length; i++) { - var point = this.dataPoints[i]; - - if (this.style === Graph3d.STYLE.DOTLINE) { - // draw a vertical line from the bottom to the graph value - //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin)); - var from = this._convert3Dto2D(point.bottom); - ctx.lineWidth = 1; - ctx.strokeStyle = this.colorGrid; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(point.screen.x, point.screen.y); - ctx.stroke(); - } - - // calculate radius for the circle - var size; - if (this.style === Graph3d.STYLE.DOTSIZE) { - size = dotSize / 2 + 2 * dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin); - } else { - size = dotSize; - } - - var radius; - if (this.showPerspective) { - radius = size / -point.trans.z; - } else { - radius = size * -(this.eye.z / this.camera.getArmLength()); - } - if (radius < 0) { - radius = 0; - } - - var hue, color, borderColor; - if (this.style === Graph3d.STYLE.DOTCOLOR) { - // calculate the color based on the value - hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; - color = this._hsv2rgb(hue, 1, 1); - borderColor = this._hsv2rgb(hue, 1, 0.8); - } else if (this.style === Graph3d.STYLE.DOTSIZE) { - color = this.colorDot; - borderColor = this.colorDotBorder; - } else { - // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 - hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; - color = this._hsv2rgb(hue, 1, 1); - borderColor = this._hsv2rgb(hue, 1, 0.8); - } + /** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ - // draw the circle - ctx.lineWidth = 1; - ctx.strokeStyle = borderColor; - ctx.fillStyle = color; - ctx.beginPath(); - ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI * 2, true); - ctx.fill(); - ctx.stroke(); - } + Emitter.prototype.on = + Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks[event] = this._callbacks[event] || []) + .push(fn); + return this; }; /** - * Draw all datapoints as bars. - * This function can be used when the style is 'bar', 'bar-color', or 'bar-size' + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public */ - Graph3d.prototype._redrawDataBar = function () { - var canvas = this.frame.canvas; - var ctx = canvas.getContext('2d'); - var i, j, surface, corners; - if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? - - // calculate the translations of all points - for (i = 0; i < this.dataPoints.length; i++) { - var trans = this._convertPointToTranslation(this.dataPoints[i].point); - var screen = this._convertTranslationToScreen(trans); - this.dataPoints[i].trans = trans; - this.dataPoints[i].screen = screen; + Emitter.prototype.once = function(event, fn){ + var self = this; + this._callbacks = this._callbacks || {}; - // calculate the distance from the point at the bottom to the camera - var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); - this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; + function on() { + self.off(event, on); + fn.apply(this, arguments); } - // order the translated points by depth - var sortDepth = function sortDepth(a, b) { - return b.dist - a.dist; - }; - this.dataPoints.sort(sortDepth); - - // draw the datapoints as bars - var xWidth = this.xBarWidth / 2; - var yWidth = this.yBarWidth / 2; - for (i = 0; i < this.dataPoints.length; i++) { - var point = this.dataPoints[i]; - - // determine color - var hue, color, borderColor; - if (this.style === Graph3d.STYLE.BARCOLOR) { - // calculate the color based on the value - hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; - color = this._hsv2rgb(hue, 1, 1); - borderColor = this._hsv2rgb(hue, 1, 0.8); - } else if (this.style === Graph3d.STYLE.BARSIZE) { - color = this.colorDot; - borderColor = this.colorDotBorder; - } else { - // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 - hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; - color = this._hsv2rgb(hue, 1, 1); - borderColor = this._hsv2rgb(hue, 1, 0.8); - } - - // calculate size for the bar - if (this.style === Graph3d.STYLE.BARSIZE) { - xWidth = this.xBarWidth / 2 * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); - yWidth = this.yBarWidth / 2 * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); - } - - // calculate all corner points - var me = this; - var point3d = point.point; - var top = [{ point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z) }, { point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z) }, { point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z) }, { point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z) }]; - var bottom = [{ point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin) }, { point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin) }, { point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin) }, { point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin) }]; - - // calculate screen location of the points - top.forEach(function (obj) { - obj.screen = me._convert3Dto2D(obj.point); - }); - bottom.forEach(function (obj) { - obj.screen = me._convert3Dto2D(obj.point); - }); - - // create five sides, calculate both corner points and center points - var surfaces = [{ corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point) }, { corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point) }, { corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point) }, { corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point) }, { corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point) }]; - point.surfaces = surfaces; - - // calculate the distance of each of the surface centers to the camera - for (j = 0; j < surfaces.length; j++) { - surface = surfaces[j]; - var transCenter = this._convertPointToTranslation(surface.center); - surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z; - // TODO: this dept calculation doesn't work 100% of the cases due to perspective, - // but the current solution is fast/simple and works in 99.9% of all cases - // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9}) - } - - // order the surfaces by their (translated) depth - surfaces.sort(function (a, b) { - var diff = b.dist - a.dist; - if (diff) return diff; - - // if equal depth, sort the top surface last - if (a.corners === top) return 1; - if (b.corners === top) return -1; - - // both are equal - return 0; - }); - - // draw the ordered surfaces - ctx.lineWidth = 1; - ctx.strokeStyle = borderColor; - ctx.fillStyle = color; - // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside - for (j = 2; j < surfaces.length; j++) { - surface = surfaces[j]; - corners = surface.corners; - ctx.beginPath(); - ctx.moveTo(corners[3].screen.x, corners[3].screen.y); - ctx.lineTo(corners[0].screen.x, corners[0].screen.y); - ctx.lineTo(corners[1].screen.x, corners[1].screen.y); - ctx.lineTo(corners[2].screen.x, corners[2].screen.y); - ctx.lineTo(corners[3].screen.x, corners[3].screen.y); - ctx.fill(); - ctx.stroke(); - } - } + on.fn = fn; + this.on(event, on); + return this; }; /** - * Draw a line through all datapoints. - * This function can be used when the style is 'line' + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public */ - Graph3d.prototype._redrawDataLine = function () { - var canvas = this.frame.canvas, - ctx = canvas.getContext('2d'), - point, - i; - if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? - - // calculate the translations of all points - for (i = 0; i < this.dataPoints.length; i++) { - var trans = this._convertPointToTranslation(this.dataPoints[i].point); - var screen = this._convertTranslationToScreen(trans); + Emitter.prototype.off = + Emitter.prototype.removeListener = + Emitter.prototype.removeAllListeners = + Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; - this.dataPoints[i].trans = trans; - this.dataPoints[i].screen = screen; + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; } - // start the line - if (this.dataPoints.length > 0) { - point = this.dataPoints[0]; - - ctx.lineWidth = 1; // TODO: make customizable - ctx.strokeStyle = 'blue'; // TODO: make customizable - ctx.beginPath(); - ctx.moveTo(point.screen.x, point.screen.y); - } + // specific event + var callbacks = this._callbacks[event]; + if (!callbacks) return this; - // draw the datapoints as colored circles - for (i = 1; i < this.dataPoints.length; i++) { - point = this.dataPoints[i]; - ctx.lineTo(point.screen.x, point.screen.y); + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks[event]; + return this; } - // finish the line - if (this.dataPoints.length > 0) { - ctx.stroke(); + // 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; }; /** - * Start a moving operation inside the provided parent element - * @param {Event} event The event that occurred (required for - * retrieving the mouse position) + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} */ - Graph3d.prototype._onMouseDown = function (event) { - event = event || window.event; - - // check if mouse is still down (may be up when focus is lost for example - // in an iframe) - if (this.leftButtonDown) { - this._onMouseUp(event); - } - - // only react on left mouse button down - this.leftButtonDown = event.which ? event.which === 1 : event.button === 1; - if (!this.leftButtonDown && !this.touchDown) return; - - // get mouse position (different code for IE and all other browsers) - this.startMouseX = getMouseX(event); - this.startMouseY = getMouseY(event); - this.startStart = new Date(this.start); - this.startEnd = new Date(this.end); - this.startArmRotation = this.camera.getArmRotation(); + Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks[event]; - this.frame.style.cursor = 'move'; + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } - // 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', me.onmousemove); - util.addEventListener(document, 'mouseup', me.onmouseup); - util.preventDefault(event); + return this; }; /** - * Perform moving operating. - * This function activated from within the funcion Graph.mouseDown(). - * @param {Event} event Well, eehh, the event + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public */ - Graph3d.prototype._onMouseMove = function (event) { - event = event || window.event; - - // calculate change in mouse position - var diffX = parseFloat(getMouseX(event)) - this.startMouseX; - var diffY = parseFloat(getMouseY(event)) - this.startMouseY; - var horizontalNew = this.startArmRotation.horizontal + diffX / 200; - var verticalNew = this.startArmRotation.vertical + diffY / 200; + Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks[event] || []; + }; - var snapAngle = 4; // degrees - var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI); + /** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ - // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc... - // the -0.001 is to take care that the vertical axis is always drawn at the left front corner - if (Math.abs(Math.sin(horizontalNew)) < snapValue) { - horizontalNew = Math.round(horizontalNew / Math.PI) * Math.PI - 0.001; - } - if (Math.abs(Math.cos(horizontalNew)) < snapValue) { - horizontalNew = (Math.round(horizontalNew / Math.PI - 0.5) + 0.5) * Math.PI - 0.001; - } + Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; + }; - // snap vertically to nice angles - if (Math.abs(Math.sin(verticalNew)) < snapValue) { - verticalNew = Math.round(verticalNew / Math.PI) * Math.PI; - } - if (Math.abs(Math.cos(verticalNew)) < snapValue) { - verticalNew = (Math.round(verticalNew / Math.PI - 0.5) + 0.5) * Math.PI; - } - this.camera.setArmRotation(horizontalNew, verticalNew); - this.redraw(); +/***/ }, +/* 44 */ +/***/ function(module, exports, __webpack_require__) { - // fire a cameraPositionChange event - var parameters = this.getCameraPosition(); - this.emit('cameraPositionChange', parameters); + 'use strict'; - util.preventDefault(event); - }; + var Emitter = __webpack_require__(43); + var Hammer = __webpack_require__(41); + var hammerUtil = __webpack_require__(49); + var util = __webpack_require__(2); + var DataSet = __webpack_require__(4); + var DataView = __webpack_require__(5); + var Range = __webpack_require__(18); + var ItemSet = __webpack_require__(32); + var TimeAxis = __webpack_require__(35); + var Activator = __webpack_require__(68); + var DateUtil = __webpack_require__(16); + var CustomTime = __webpack_require__(27); /** - * Stop moving operating. - * This function activated from within the funcion Graph.mouseDown(). - * @param {event} event The event + * Create a timeline visualization + * @constructor */ - Graph3d.prototype._onMouseUp = function (event) { - this.frame.style.cursor = 'auto'; - this.leftButtonDown = false; + function Core() {} - // remove event listeners here - util.removeEventListener(document, 'mousemove', this.onmousemove); - util.removeEventListener(document, 'mouseup', this.onmouseup); - util.preventDefault(event); - }; + // turn Core into an event emitter + Emitter(Core.prototype); /** - * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point - * @param {Event} event A mouse move event - */ - Graph3d.prototype._onTooltip = function (event) { - var delay = 300; // ms - var boundingRect = this.frame.getBoundingClientRect(); - var mouseX = getMouseX(event) - boundingRect.left; - var mouseY = getMouseY(event) - boundingRect.top; + * 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 = {}; - if (!this.showTooltip) { - return; - } + 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'); - if (this.tooltipTimeout) { - clearTimeout(this.tooltipTimeout); - } + 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'; - // (delayed) display of a tooltip only if no mouse button is down - if (this.leftButtonDown) { - this._hideTooltip(); - return; - } + 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); - if (this.tooltip && this.tooltip.dataPoint) { - // tooltip is currently visible - var dataPoint = this._dataPointFromXY(mouseX, mouseY); - if (dataPoint !== this.tooltip.dataPoint) { - // datapoint changed - if (dataPoint) { - this._showTooltip(dataPoint); - } else { - this._hideTooltip(); - } - } - } else { - // tooltip is currently not visible - var me = this; - this.tooltipTimeout = setTimeout(function () { - me.tooltipTimeout = null; + this.dom.centerContainer.appendChild(this.dom.center); + this.dom.leftContainer.appendChild(this.dom.left); + this.dom.rightContainer.appendChild(this.dom.right); - // show a tooltip if we have a data point - var dataPoint = me._dataPointFromXY(mouseX, mouseY); - if (dataPoint) { - me._showTooltip(dataPoint); - } - }, delay); - } - }; + 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); - /** - * Event handler for touchstart event on mobile devices - */ - Graph3d.prototype._onTouchStart = function (event) { - this.touchDown = true; + this.on('rangechange', this.redraw.bind(this)); + this.on('touch', this._onTouch.bind(this)); + this.on('pan', this._onDrag.bind(this)); var me = this; - this.ontouchmove = function (event) { - me._onTouchMove(event); - }; - this.ontouchend = function (event) { - me._onTouchEnd(event); - }; - util.addEventListener(document, 'touchmove', me.ontouchmove); - util.addEventListener(document, 'touchend', me.ontouchend); - - this._onMouseDown(event); - }; - - /** - * Event handler for touchmove event on mobile devices - */ - Graph3d.prototype._onTouchMove = function (event) { - this._onMouseMove(event); - }; + this.on('change', function (properties) { + if (properties && properties.queue == true) { + // redraw once on next tick + if (!me._redrawTimer) { + me._redrawTimer = setTimeout(function () { + me._redrawTimer = null; + me._redraw(); + }, 0); + } + } else { + // redraw immediately + me._redraw(); + } + }); - /** - * Event handler for touchend event on mobile devices - */ - Graph3d.prototype._onTouchEnd = function (event) { - this.touchDown = false; + // create event listeners for all interesting events, these events will be + // emitted via emitter + this.hammer = new Hammer(this.dom.root); + this.hammer.get('pinch').set({ enable: true }); + this.listeners = {}; - util.removeEventListener(document, 'touchmove', this.ontouchmove); - util.removeEventListener(document, 'touchend', this.ontouchend); + 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; + }); - this._onMouseUp(event); - }; + // 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)); - /** - * Event handler for mouse wheel event, used to zoom the graph - * Code from http://adomas.org/javascript-mouse-wheel/ - * @param {event} event The event - */ - Graph3d.prototype._onWheel = function (event) { - if (!event) /* For IE. */ - event = window.event; + // emulate a release event (emitted after a pan, pinch, tap, or press) + hammerUtil.onRelease(this.hammer, (function (event) { + me.emit('release', event); + }).bind(this)); - // 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; + function onMouseWheel(event) { + if (me.isActive()) { + me.emit('mousewheel', event); + } } + this.dom.root.addEventListener('mousewheel', onMouseWheel); + this.dom.root.addEventListener('DOMMouseScroll', onMouseWheel); - // 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) { - var oldLength = this.camera.getArmLength(); - var newLength = oldLength * (1 - delta / 10); + // 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.camera.setArmLength(newLength); - this.redraw(); + this.customTimes = []; - this._hideTooltip(); - } + // store state information needed for touch events + this.touch = {}; - // fire a cameraPositionChange event - var parameters = this.getCameraPosition(); - this.emit('cameraPositionChange', parameters); + this.redrawCount = 0; - // Prevent default actions caused by mouse wheel. - // That might be ugly, but we handle scrolls somehow - // anyway, so don't bother here.. - util.preventDefault(event); + // attach the root panel to the provided container + if (!container) throw new Error('No container provided'); + container.appendChild(this.dom.root); }; /** - * Test whether a point lies inside given 2D triangle - * @param {Point2d} point - * @param {Point2d[]} triangle - * @return {boolean} Returns true if given point lies inside or on the edge of the triangle - * @private + * 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 */ - Graph3d.prototype._insideTriangle = function (point, triangle) { - var a = triangle[0], - b = triangle[1], - c = triangle[2]; - - function sign(x) { - return x > 0 ? 1 : x < 0 ? -1 : 0; - } - - var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x)); - var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x)); - var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x)); - - // each of the three signs must be either equal to each other or zero - return (as == 0 || bs == 0 || as == bs) && (bs == 0 || cs == 0 || bs == cs) && (as == 0 || cs == 0 || as == cs); - }; + Core.prototype.setOptions = function (options) { + if (options) { + // copy the known options + var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'clickToUse', 'dataAttributes', 'hiddenDates']; + util.selectiveExtend(fields, this.options, options); - /** - * Find a data point close to given screen position (x, y) - * @param {Number} x - * @param {Number} y - * @return {Object | null} The closest data point or null if not close to any data point - * @private - */ - Graph3d.prototype._dataPointFromXY = function (x, y) { - var i, - distMax = 100, - // px - dataPoint = null, - closestDataPoint = null, - closestDist = null, - center = new Point2d(x, y); + if ('orientation' in options) { + if (typeof options.orientation === 'string') { + this.options.orientation = { + item: options.orientation, + axis: options.orientation + }; + } else if (typeof 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.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { - // the data points are ordered from far away to closest - for (i = this.dataPoints.length - 1; i >= 0; i--) { - dataPoint = this.dataPoints[i]; - var surfaces = dataPoint.surfaces; - if (surfaces) { - for (var s = surfaces.length - 1; s >= 0; s--) { - // split each surface in two triangles, and see if the center point is inside one of these - var surface = surfaces[s]; - var corners = surface.corners; - var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen]; - var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen]; - if (this._insideTriangle(center, triangle1) || this._insideTriangle(center, triangle2)) { - // return immediately at the first hit - return dataPoint; - } + 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; } } - } else { - // find the closest data point, using distance to the center of the point on 2d screen - for (i = 0; i < this.dataPoints.length; i++) { - dataPoint = this.dataPoints[i]; - var point = dataPoint.screen; - if (point) { - var distX = Math.abs(x - point.x); - var distY = Math.abs(y - point.y); - var dist = Math.sqrt(distX * distX + distY * distY); - if ((closestDist === null || dist < closestDist) && dist < distMax) { - closestDist = dist; - closestDataPoint = dataPoint; + if ('hiddenDates' in this.options) { + DateUtil.convertHiddenOptions(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(); } - return closestDataPoint; + // propagate options to all components + this.components.forEach(function (component) { + return component.setOptions(options); + }); + + // enable/disable configure + if (this.configurator) { + 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 }); + } + + // redraw everything + this._redraw(); }; /** - * Display a tooltip for given data point - * @param {Object} dataPoint - * @private + * Returns true when the Timeline is active. + * @returns {boolean} */ - Graph3d.prototype._showTooltip = function (dataPoint) { - var content, line, dot; + Core.prototype.isActive = function () { + return !this.activator || this.activator.active; + }; - if (!this.tooltip) { - content = document.createElement('div'); - content.style.position = 'absolute'; - content.style.padding = '10px'; - content.style.border = '1px solid #4d4d4d'; - content.style.color = '#1a1a1a'; - content.style.background = 'rgba(255,255,255,0.7)'; - content.style.borderRadius = '2px'; - content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)'; + /** + * Destroy the Core, clean up all DOM elements and event listeners. + */ + Core.prototype.destroy = function () { + // unbind datasets + this.setItems(null); + this.setGroups(null); - line = document.createElement('div'); - line.style.position = 'absolute'; - line.style.height = '40px'; - line.style.width = '0'; - line.style.borderLeft = '1px solid #4d4d4d'; + // remove all event listeners + this.off(); - dot = document.createElement('div'); - dot.style.position = 'absolute'; - dot.style.height = '0'; - dot.style.width = '0'; - dot.style.border = '5px solid #4d4d4d'; - dot.style.borderRadius = '5px'; + // stop checking for changed size + this._stopAutoResize(); - this.tooltip = { - dataPoint: null, - dom: { - content: content, - line: line, - dot: dot - } - }; - } else { - content = this.tooltip.dom.content; - line = this.tooltip.dom.line; - dot = this.tooltip.dom.dot; + // remove from DOM + if (this.dom.root.parentNode) { + this.dom.root.parentNode.removeChild(this.dom.root); } + this.dom = null; - this._hideTooltip(); - - this.tooltip.dataPoint = dataPoint; - if (typeof this.showTooltip === 'function') { - content.innerHTML = this.showTooltip(dataPoint.point); - } else { - content.innerHTML = '' + '' + '' + '' + '
x:' + dataPoint.point.x + '
y:' + dataPoint.point.y + '
z:' + dataPoint.point.z + '
'; + // remove Activator + if (this.activator) { + this.activator.destroy(); + delete this.activator; } - content.style.left = '0'; - content.style.top = '0'; - this.frame.appendChild(content); - this.frame.appendChild(line); - this.frame.appendChild(dot); - - // calculate sizes - var contentWidth = content.offsetWidth; - var contentHeight = content.offsetHeight; - var lineHeight = line.offsetHeight; - var dotWidth = dot.offsetWidth; - var dotHeight = dot.offsetHeight; + // 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; - var left = dataPoint.screen.x - contentWidth / 2; - left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth); + // give all components the opportunity to cleanup + this.components.forEach(function (component) { + return component.destroy(); + }); - line.style.left = dataPoint.screen.x + 'px'; - line.style.top = dataPoint.screen.y - lineHeight + 'px'; - content.style.left = left + 'px'; - content.style.top = dataPoint.screen.y - lineHeight - contentHeight + 'px'; - dot.style.left = dataPoint.screen.x - dotWidth / 2 + 'px'; - dot.style.top = dataPoint.screen.y - dotHeight / 2 + 'px'; + this.body = null; }; /** - * Hide the tooltip when displayed - * @private + * Set a custom time bar + * @param {Date} time + * @param {number} [id=undefined] Optional id of the custom time bar to be adjusted. */ - Graph3d.prototype._hideTooltip = function () { - if (this.tooltip) { - this.tooltip.dataPoint = null; + Core.prototype.setCustomTime = function (time, id) { + var customTimes = this.customTimes.filter(function (component) { + return id === component.options.id; + }); - for (var prop in this.tooltip.dom) { - if (this.tooltip.dom.hasOwnProperty(prop)) { - var elem = this.tooltip.dom[prop]; - if (elem && elem.parentNode) { - elem.parentNode.removeChild(elem); - } - } - } + if (customTimes.length === 0) { + throw new Error('No custom time bar found with id ' + JSON.stringify(id)); } - }; - - /**--------------------------------------------------------------------------**/ - /** - * Get the horizontal mouse position from a mouse event - * @param {Event} event - * @return {Number} mouse x - */ - function getMouseX(event) { - if ('clientX' in event) return event.clientX; - return event.targetTouches[0] && event.targetTouches[0].clientX || 0; - } + if (customTimes.length > 0) { + customTimes[0].setCustomTime(time); + } + }; /** - * Get the vertical mouse position from a mouse event - * @param {Event} event - * @return {Number} mouse y + * Retrieve the current custom time. + * @param {number} [id=undefined] Id of the custom time bar. + * @return {Date | undefined} customTime */ - function getMouseY(event) { - if ('clientY' in event) return event.clientY; - return event.targetTouches[0] && event.targetTouches[0].clientY || 0; - } - - module.exports = Graph3d; - - // use use defaults + Core.prototype.getCustomTime = function (id) { + var customTimes = this.customTimes.filter(function (component) { + return component.options.id === id; + }); -/***/ }, -/* 26 */ -/***/ function(module, exports, __webpack_require__) { + if (customTimes.length === 0) { + throw new Error('No custom time bar found with id ' + JSON.stringify(id)); + } + return customTimes[0].getCustomTime(); + }; /** - * @prototype Point2d - * @param {Number} [x] - * @param {Number} [y] + * 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 */ - "use strict"; - - function Point2d(x, y) { - this.x = x !== undefined ? x : 0; - this.y = y !== undefined ? y : 0; - } - - module.exports = Point2d; - -/***/ }, -/* 27 */ -/***/ function(module, exports, __webpack_require__) { + Core.prototype.addCustomTime = function (time, id) { + var timestamp = time !== undefined ? util.convert(time, 'Date').valueOf() : new Date(); - - /** - * Expose `Emitter`. - */ + var exists = this.customTimes.some(function (customTime) { + return customTime.options.id === id; + }); + if (exists) { + throw new Error('A custom time with id ' + JSON.stringify(id) + ' already exists'); + } - module.exports = Emitter; + var customTime = new CustomTime(this.body, { + time: timestamp, + id: id + }); - /** - * Initialize a new `Emitter`. - * - * @api public - */ + this.customTimes.push(customTime); + this.components.push(customTime); + this.redraw(); - function Emitter(obj) { - if (obj) return mixin(obj); + return id; }; /** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private + * Remove previously added custom bar + * @param {int} id ID of the custom bar to be removed + * @return {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; + }); - function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; + if (customTimes.length === 0) { + throw new Error('No custom time bar found with id ' + JSON.stringify(id)); } - 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; + customTimes.forEach((function (customTime) { + this.customTimes.splice(this.customTimes.indexOf(customTime), 1); + this.components.splice(this.components.indexOf(customTime), 1); + customTime.destroy(); + }).bind(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 + * Get the id's of the currently visible items. + * @returns {Array} The ids of the visible items */ - - 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; + Core.prototype.getVisibleItems = function () { + return this.itemSet && this.itemSet.getVisibleItems() || []; }; /** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public + * 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'. */ + Core.prototype.fit = function (options) { + var range = this._getDataRange(); - 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; + // skip range set if there is no start and end date + if (range.start === null && range.end === null) { + return; } - // 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; + var animation = options && options.animation !== undefined ? options.animation : true; + this.range.setRange(range.start, range.end, animation); }; /** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} + * Calculate the data range of the items and applies a 5% window around it. + * @returns {{start: Date | null, end: Date | null}} + * @protected */ + Core.prototype._getDataRange = function () { + // apply the data range as range + var dataRange = this.getItemRange(); - 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); + // add 5% space on both sides + var start = dataRange.min; + var end = dataRange.max; + if (start != null && end != null) { + var interval = end.valueOf() - start.valueOf(); + if (interval <= 0) { + // prevent an empty interval + interval = 24 * 60 * 60 * 1000; // 1 day } + start = new Date(start.valueOf() - interval * 0.05); + end = new Date(end.valueOf() + interval * 0.05); } - return this; + return { + start: start, + end: end + }; }; /** - * Return array of callbacks for `event`. + * Set the visible window. Both parameters are optional, you can change only + * start or only end. Syntax: * - * @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. + * TimeLine.setWindow(start, end) + * TimeLine.setWindow(start, end, options) + * TimeLine.setWindow(range) * - * @param {String} event - * @return {Boolean} - * @api public + * 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'. */ - - Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; + Core.prototype.setWindow = function (start, end, options) { + var animation; + if (arguments.length == 1) { + var range = arguments[0]; + animation = range.animation !== undefined ? range.animation : true; + this.range.setRange(range.start, range.end, animation); + } else { + animation = options && options.animation !== undefined ? options.animation : true; + this.range.setRange(start, end, animation); + } }; - -/***/ }, -/* 28 */ -/***/ function(module, exports, __webpack_require__) { - /** - * @prototype Point3d - * @param {Number} [x] - * @param {Number} [y] - * @param {Number} [z] + * 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'. */ - "use strict"; + Core.prototype.moveTo = function (time, options) { + var interval = this.range.end - this.range.start; + var t = util.convert(time, 'Date').valueOf(); - function Point3d(x, y, z) { - this.x = x !== undefined ? x : 0; - this.y = y !== undefined ? y : 0; - this.z = z !== undefined ? z : 0; - }; + var start = t - interval / 2; + var end = t + interval / 2; + var animation = options && options.animation !== undefined ? options.animation : true; - /** - * 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; + this.range.setRange(start, end, animation); }; /** - * Add the two provided points, returns a+b - * @param {Point3d} a - * @param {Point3d} b - * @return {Point3d} a+b + * Get the visible window + * @return {{start: Date, end: Date}} Visible range */ - 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; + Core.prototype.getWindow = function () { + var range = this.range.getRange(); + return { + start: new Date(range.start), + end: new Date(range.end) + }; }; /** - * Calculate the average of two 3d points - * @param {Point3d} a - * @param {Point3d} b - * @return {Point3d} The average, (a+b)/2 + * Force a redraw. Can be overridden by implementations of Core */ - Point3d.avg = function (a, b) { - return new Point3d((a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2); + Core.prototype.redraw = function () { + this._redraw(); }; /** - * 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 + * Redraw for internal use. Redraws all components. See also the public + * method redraw. + * @protected */ - Point3d.crossProduct = function (a, b) { - var crossproduct = new Point3d(); + Core.prototype._redraw = function () { + var resized = false; + var options = this.options; + var props = this.props; + var dom = this.dom; - 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; + if (!dom) return; // when destroyed - return crossproduct; - }; + DateUtil.updateHiddenDates(this.body, this.options.hiddenDates); - /** - * 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); - }; + // 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'); + } - module.exports = Point3d; + // 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, ''); -/***/ }, -/* 29 */ -/***/ function(module, exports, __webpack_require__) { + // 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; + var borderRootHeight = dom.root.offsetHeight - dom.root.clientHeight; + var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth; - 'use strict'; + // 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) { + borderRootWidth = borderRootHeight; + } - var Point3d = __webpack_require__(28); + // 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; - /** - * @class Camera - * 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 - */ - function Camera() { - this.armLocation = new Point3d(); - this.armRotation = {}; - this.armRotation.horizontal = 0; - this.armRotation.vertical = 0; - this.armLength = 1.7; + // TODO: compensate borders when any of the panels is empty. - this.cameraLocation = new Point3d(); - this.cameraRotation = new Point3d(0.5 * Math.PI, 0, 0); + // 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 + borderRootHeight + props.border.top + props.border.bottom; + dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px'); - this.calculateCameraOrientation(); - } + // calculate heights of the content panels + props.root.height = dom.root.offsetHeight; + props.background.height = props.root.height - borderRootHeight; + var containerHeight = props.root.height - props.top.height - props.bottom.height - borderRootHeight; + props.centerContainer.height = containerHeight; + props.leftContainer.height = containerHeight; + props.rightContainer.height = props.leftContainer.height; - /** - * 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; + // calculate the widths of the panels + props.root.width = dom.root.offsetWidth; + props.background.width = props.root.width - borderRootWidth; + props.left.width = dom.leftContainer.clientWidth || -props.border.left; + props.leftContainer.width = props.left.width; + props.right.width = dom.rightContainer.clientWidth || -props.border.right; + props.rightContainer.width = props.right.width; + var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth; + props.center.width = centerWidth; + props.centerContainer.width = centerWidth; + props.top.width = centerWidth; + props.bottom.width = centerWidth; - this.calculateCameraOrientation(); - }; + // 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'; - /** - * 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; - } + 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'; - 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; + // 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'; + + // 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 + this._updateScrollTop(); + + // reposition the scrollable contents + var offset = this.props.scrollTop; + if (options.orientation.item != 'top') { + offset += Math.max(this.props.centerContainer.height - this.props.center.height - this.props.border.top - this.props.border.bottom, 0); } + dom.center.style.left = '0'; + dom.center.style.top = offset + 'px'; + dom.left.style.left = '0'; + dom.left.style.top = offset + 'px'; + dom.right.style.left = '0'; + dom.right.style.top = offset + 'px'; - if (horizontal !== undefined || vertical !== undefined) { - this.calculateCameraOrientation(); + // show shadows when vertical scrolling is available + var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : ''; + var visibilityBottom = this.props.scrollTop == this.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; + + // redraw all components + this.components.forEach(function (component) { + resized = component.redraw() || resized; + }); + if (resized) { + // keep repainting until all sizes are settled + var MAX_REDRAWS = 3; // maximum number of consecutive redraws + if (this.redrawCount < MAX_REDRAWS) { + this.redrawCount++; + this._redraw(); + } else { + console.log('WARNING: infinite loop in redraw?'); + } + this.redrawCount = 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.'); + }; + /** - * Retrieve the current arm rotation - * @return {object} An object with parameters horizontal and vertical + * 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. */ - Camera.prototype.getArmRotation = function () { - var rot = {}; - rot.horizontal = this.armRotation.horizontal; - rot.vertical = this.armRotation.vertical; + Core.prototype.setCurrentTime = function (time) { + if (!this.currentTime) { + throw new Error('Option showCurrentTime must be true'); + } - return rot; + this.currentTime.setCurrentTime(time); }; /** - * Set the (normalized) length of the camera arm. - * @param {Number} length A length between 0.71 and 5.0 + * Get the current time. + * Only applicable when option `showCurrentTime` is true. + * @return {Date} Returns the current time. */ - 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) this.armLength = 5; + Core.prototype.getCurrentTime = function () { + if (!this.currentTime) { + throw new Error('Option showCurrentTime must be true'); + } - this.calculateCameraOrientation(); + return this.currentTime.getCurrentTime(); }; /** - * Retrieve the arm length - * @return {Number} length + * 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 */ - Camera.prototype.getArmLength = function () { - return this.armLength; + // TODO: move this function to Range + Core.prototype._toTime = function (x) { + return DateUtil.toTime(this, x, this.props.center.width); }; /** - * Retrieve the camera location - * @return {Point3d} cameraLocation + * 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 */ - Camera.prototype.getCameraLocation = function () { - return this.cameraLocation; + // 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); }; /** - * Retrieve the camera rotation - * @return {Point3d} cameraRotation + * 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 */ - Camera.prototype.getCameraRotation = function () { - return this.cameraRotation; + // TODO: move this function to Range + Core.prototype._toScreen = function (time) { + return DateUtil.toScreen(this, time, this.props.center.width); }; /** - * Calculate the location and rotation of the camera based on the - * position and orientation of the camera arm + * 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 */ - 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; + // 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; }; - module.exports = Camera; - -/***/ }, -/* 30 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var DataView = __webpack_require__(24); - /** - * @class Filter - * - * @param {DataSet} data The google data table - * @param {Number} column The index of the column to be filtered - * @param {Graph} graph The graph + * Initialize watching when option autoResize is true + * @private */ - function Filter(data, column, graph) { - this.data = data; - 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 = graph.getDistinctValues(data.get(), this.column); - - // sort both numeric and string values correctly - this.values.sort(function (a, b) { - return a > b ? 1 : a < b ? -1 : 0; - }); - - 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(); + Core.prototype._initAutoResize = function () { + if (this.options.autoResize == true) { + this._startAutoResize(); } else { - this.loaded = true; + this._stopAutoResize(); } }; /** - * Return the label - * @return {string} label + * Watch for changes in the size of the container. On resize, the Panel will + * automatically redraw itself. + * @private */ - Filter.prototype.isLoaded = function () { - return this.loaded; - }; + Core.prototype._startAutoResize = function () { + var me = this; - /** - * Return the loaded progress - * @return {Number} percentage between 0 and 100 - */ - Filter.prototype.getLoadedProgress = function () { - var len = this.values.length; + this._stopAutoResize(); - var i = 0; - while (this.dataPoints[i]) { - i++; - } + this._onResize = function () { + if (me.options.autoResize != true) { + // stop watching when the option autoResize is changed to false + me._stopAutoResize(); + return; + } - return Math.round(i / len * 100); - }; + 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; - /** - * Return the label - * @return {string} label - */ - Filter.prototype.getLabel = function () { - return this.graph.filterLabel; - }; + me.emit('change'); + } + } + }; - /** - * Return the columnIndex of the filter - * @return {Number} columnIndex - */ - Filter.prototype.getColumn = function () { - return this.column; + // add event listener to window resize + util.addEventListener(window, 'resize', this._onResize); + + this.watchTimer = setInterval(this._onResize, 1000); }; /** - * Return the currently selected value. Returns undefined if there is no selection - * @return {*} value + * Stop watching for a resize of the frame. + * @private */ - Filter.prototype.getSelectedValue = function () { - if (this.index === undefined) return undefined; + Core.prototype._stopAutoResize = function () { + if (this.watchTimer) { + clearInterval(this.watchTimer); + this.watchTimer = undefined; + } - return this.values[this.index]; + // remove event listener on window.resize + util.removeEventListener(window, 'resize', this._onResize); + this._onResize = null; }; /** - * Retrieve all values of the filter - * @return {Array} values + * Start moving the timeline vertically + * @param {Event} event + * @private */ - Filter.prototype.getValues = function () { - return this.values; + Core.prototype._onTouch = function (event) { + this.touch.allowDragging = true; + this.touch.initialScrollTop = this.props.scrollTop; }; /** - * Retrieve one value of the filter - * @param {Number} index - * @return {*} value + * Start moving the timeline vertically + * @param {Event} event + * @private */ - Filter.prototype.getValue = function (index) { - if (index >= this.values.length) throw 'Error: index out of range'; - - return this.values[index]; + Core.prototype._onPinch = function (event) { + this.touch.allowDragging = false; }; /** - * Retrieve the (filtered) dataPoints for the currently selected filter index - * @param {Number} [index] (optional) - * @return {Array} dataPoints + * Move the timeline vertically + * @param {Event} event + * @private */ - Filter.prototype._getDataPoints = function (index) { - if (index === undefined) index = this.index; - - if (index === undefined) return []; + Core.prototype._onDrag = function (event) { + // 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 dataPoints; - if (this.dataPoints[index]) { - dataPoints = this.dataPoints[index]; - } else { - var f = {}; - f.column = this.column; - f.value = this.values[index]; + var delta = event.deltaY; - var dataView = new DataView(this.data, { filter: function filter(item) { - return item[f.column] == f.value; - } }).get(); - dataPoints = this.graph._getDataPoints(dataView); + var oldScrollTop = this._getScrollTop(); + var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta); - this.dataPoints[index] = dataPoints; + if (newScrollTop != oldScrollTop) { + this._redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already + this.emit('verticalDrag'); } - - return dataPoints; }; /** - * Set a callback function when the filter is fully loaded. + * Apply a scrollTop + * @param {Number} scrollTop + * @returns {Number} scrollTop Returns the applied scrollTop + * @private */ - Filter.prototype.setOnLoadCallback = function (callback) { - this.onLoadCallback = callback; + Core.prototype._setScrollTop = function (scrollTop) { + this.props.scrollTop = scrollTop; + this._updateScrollTop(); + return this.props.scrollTop; }; /** - * Add a value to the list with available values for this filter - * No double entries will be created. - * @param {Number} index + * Update the current scrollTop when the height of the containers has been changed + * @returns {Number} scrollTop Returns the applied scrollTop + * @private */ - Filter.prototype.selectValue = function (index) { - if (index >= this.values.length) throw 'Error: index out of range'; + 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; + } - this.index = index; - this.value = this.values[index]; + // 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; + + return this.props.scrollTop; }; /** - * Load all filtered rows in the background one by one - * Start this method without providing an index! + * Get the current scrollTop + * @returns {number} scrollTop + * @private */ - Filter.prototype.loadInBackground = function (index) { - if (index === undefined) index = 0; + Core.prototype._getScrollTop = function () { + return this.props.scrollTop; + }; - var frame = this.graph.frame; + module.exports = Core; - if (index < this.values.length) { - var dataPointsTemp = this._getDataPoints(index); - //this.graph.redrawInfo(); // TODO: not neat +/***/ }, +/* 45 */ +/***/ function(module, exports, __webpack_require__) { - // 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'; + 'use strict'; - var me = this; - setTimeout(function () { - me.loadInBackground(index + 1); - }, 10); - this.loaded = false; - } else { - this.loaded = true; + Object.defineProperty(exports, '__esModule', { + value: true + }); - // remove the progress box - if (frame.progress !== undefined) { - frame.removeChild(frame.progress); - frame.progress = undefined; - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - if (this.onLoadCallback) this.onLoadCallback(); - } - }; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - module.exports = Filter; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } -/***/ }, -/* 31 */ -/***/ function(module, exports, __webpack_require__) { + var _ColorPicker = __webpack_require__(73); - 'use strict'; + var _ColorPicker2 = _interopRequireDefault(_ColorPicker); var util = __webpack_require__(2); /** - * @constructor Slider + * 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, ..] * - * An html slider control with start/stop/prev/next buttons - * @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. + * The options are matched with their counterparts in each of the modules and the values used in the configuration are + * + * @param parentModule | the location where parentModule.setOptions() can be called + * @param defaultContainer | the default container of the module + * @param configureOptions | the fully configured and predefined options set found in allOptions.js + * @param pixelRatio | canvas pixel ratio */ - function Slider(container, options) { - if (container === undefined) { - throw '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); + var Configurator = (function () { + function Configurator(parentModule, defaultContainer, configureOptions) { + var pixelRatio = arguments[3] === undefined ? 1 : arguments[3]; - this.frame.prev = document.createElement('INPUT'); - this.frame.prev.type = 'BUTTON'; - this.frame.prev.value = 'Prev'; - this.frame.appendChild(this.frame.prev); + _classCallCheck(this, Configurator); - this.frame.play = document.createElement('INPUT'); - this.frame.play.type = 'BUTTON'; - this.frame.play.value = 'Play'; - this.frame.appendChild(this.frame.play); + this.parent = parentModule; + this.changedOptions = []; + this.container = defaultContainer; + this.allowCreation = false; - this.frame.next = document.createElement('INPUT'); - this.frame.next.type = 'BUTTON'; - this.frame.next.value = 'Next'; - this.frame.appendChild(this.frame.next); + this.options = {}; + this.defaultOptions = { + enabled: false, + filter: true, + container: undefined, + showButton: true + }; + util.extend(this.options, this.defaultOptions); - 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.configureOptions = configureOptions; + this.moduleOptions = {}; + this.domElements = []; + this.colorPicker = new _ColorPicker2['default'](pixelRatio); + this.wrapper = undefined; } - this.onChangeCallback = undefined; - - this.values = []; - this.index = undefined; - - this.playTimeout = undefined; - this.playInterval = 1000; // milliseconds - this.playLoop = true; - } + _createClass(Configurator, [{ + key: 'setOptions', - /** - * Select the previous index - */ - Slider.prototype.prev = function () { - var index = this.getIndex(); - if (index > 0) { - index--; - this.setIndex(index); - } - }; + /** + * refresh all options. + * Because all modules parse their options by themselves, we just use their options. We copy them here. + * + * @param options + */ + value: function setOptions(options) { + if (options !== undefined) { + 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 === '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; + } + this.options.enabled = enabled; + } + this._clean(); + } + }, { + 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(); + } + } + }, { + key: '_create', - /** - * Select the next index - */ - Slider.prototype.next = function () { - var index = this.getIndex(); - if (index < this.values.length - 1) { - index++; - this.setIndex(index); - } - }; + /** + * Create all DOM elements + * @private + */ + value: function _create() { + var _this = this; - /** - * Select the next index - */ - Slider.prototype.playNext = function () { - var start = new Date(); + this._clean(); + this.changedOptions = []; - 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 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; + } - var end = new Date(); - var diff = end - start; + if (show !== false) { + this.allowCreation = true; - // 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 + // linebreak between categories + if (counter > 0) { + this._makeItem([]); + } + // a header for the category + this._makeHeader(option); - var me = this; - this.playTimeout = setTimeout(function () { - me.playNext(); - }, interval); - }; + // get the suboptions + this._handleObject(this.configureOptions[option], [option]); + } + counter++; + } + } - /** - * Toggle start or stop playing - */ - Slider.prototype.togglePlay = function () { - if (this.playTimeout === undefined) { - this.play(); - } else { - this.stop(); - } - }; + if (this.options.showButton === true) { + (function () { + var generateButton = document.createElement('div'); + generateButton.className = 'vis-network-configuration button'; + generateButton.innerHTML = 'generate options'; + generateButton.onclick = function () { + _this._printOptions(); + }; + generateButton.onmouseover = function () { + generateButton.className = 'vis-network-configuration button hover'; + }; + generateButton.onmouseout = function () { + generateButton.className = 'vis-network-configuration button'; + }; - /** - * Start playing - */ - Slider.prototype.play = function () { - // Test whether already playing - if (this.playTimeout) return; + _this.optionsContainer = document.createElement('div'); + _this.optionsContainer.className = 'vis-network-configuration vis-option-container'; - this.playNext(); + _this.domElements.push(_this.optionsContainer); + _this.domElements.push(generateButton); + })(); + } - if (this.frame) { - this.frame.play.value = 'Stop'; - } - }; + this._push(); + this.colorPicker.insertTo(this.container); + } + }, { + key: '_push', - /** - * Stop playing - */ - Slider.prototype.stop = function () { - clearInterval(this.playTimeout); - this.playTimeout = undefined; + /** + * draw all DOM elements on the screen + * @private + */ + value: function _push() { + this.wrapper = document.createElement('div'); + this.wrapper.className = 'vis-network-configuration-wrapper'; + this.container.appendChild(this.wrapper); + for (var i = 0; i < this.domElements.length; i++) { + this.wrapper.appendChild(this.domElements[i]); + } + } + }, { + key: '_clean', - if (this.frame) { - this.frame.play.value = 'Play'; - } - }; + /** + * delete all DOM elements + * @private + */ + value: function _clean() { + for (var i = 0; i < this.domElements.length; i++) { + this.wrapper.removeChild(this.domElements[i]); + } - /** - * Set a callback function which will be triggered when the value of the - * slider bar has changed. - */ - Slider.prototype.setOnChangeCallback = function (callback) { - this.onChangeCallback = callback; - }; + if (this.wrapper !== undefined) { + this.container.removeChild(this.wrapper); + this.wrapper = undefined; + } + this.domElements = []; + } + }, { + key: '_getValue', - /** - * Set the interval for playing the list - * @param {Number} interval The interval in milliseconds - */ - Slider.prototype.setPlayInterval = function (interval) { - this.playInterval = interval; - }; + /** + * get the value from the actualOptions if it exists + * @param {array} path | where to look for the actual option + * @returns {*} + * @private + */ + 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; + } + }, { + key: '_makeItem', - /** - * Retrieve the current play interval - * @return {Number} interval The interval in milliseconds - */ - Slider.prototype.getPlayInterval = function (interval) { - return this.playInterval; - }; + /** + * all option elements are wrapped in an item + * @param path + * @param domElements + * @private + */ + value: function _makeItem(path) { + var _this2 = this; - /** - * Set looping on or off - * @pararm {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; - }; + for (var _len = arguments.length, domElements = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + domElements[_key - 1] = arguments[_key]; + } - /** - * Execute the onchange callback function - */ - Slider.prototype.onChange = function () { - if (this.onChangeCallback !== undefined) { - this.onChangeCallback(); - } - }; + if (this.allowCreation === true) { + (function () { + var item = document.createElement('div'); + item.className = 'vis-network-configuration item s' + path.length; + domElements.forEach(function (element) { + item.appendChild(element); + }); + _this2.domElements.push(item); + })(); + } + } + }, { + key: '_makeHeader', - /** - * 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'; + /** + * header for major subjects + * @param name + * @private + */ + value: function _makeHeader(name) { + var div = document.createElement('div'); + div.className = 'vis-network-configuration header'; + div.innerHTML = name; + this._makeItem([], div); + } + }, { + key: '_makeLabel', - // position the slider button - var left = this.indexToLeft(this.index); - this.frame.slide.style.left = left + 'px'; - } - }; + /** + * make a label, if it is an object label, it gets different styling. + * @param name + * @param path + * @param objectLabel + * @returns {HTMLElement} + * @private + */ + value: function _makeLabel(name, path) { + var objectLabel = arguments[2] === undefined ? false : arguments[2]; - /** - * 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; + var div = document.createElement('div'); + div.className = 'vis-network-configuration label s' + path.length; + if (objectLabel === true) { + div.innerHTML = '' + name + ':'; + } else { + div.innerHTML = name + ':'; + } + return div; + } + }, { + key: '_makeDropdown', - if (this.values.length > 0) this.setIndex(0);else this.index = undefined; - }; + /** + * make a dropdown list for multiple possible string optoins + * @param arr + * @param value + * @param path + * @private + */ + value: function _makeDropdown(arr, value, path) { + var select = document.createElement('select'); + select.className = 'vis-network-configuration select'; + var selectedValue = 0; + if (value !== undefined) { + if (arr.indexOf(value) !== -1) { + selectedValue = arr.indexOf(value); + } + } - /** - * Select a value by its index - * @param {Number} index - */ - Slider.prototype.setIndex = function (index) { - if (index < this.values.length) { - this.index = index; + 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); + } - this.redraw(); - this.onChange(); - } else { - throw 'Error: index out of range'; - } - }; + var me = this; + select.onchange = function () { + me._update(this.value, path); + }; - /** - * retrieve the index of the currently selected vaue - * @return {Number} index - */ - Slider.prototype.getIndex = function () { - return this.index; - }; + var label = this._makeLabel(path[path.length - 1], path); + this._makeItem(path, label, select); + } + }, { + key: '_makeRange', - /** - * retrieve the currently selected value - * @return {*} value - */ - Slider.prototype.get = function () { - return this.values[this.index]; - }; + /** + * make a range object for numeric options + * @param arr + * @param value + * @param path + * @private + */ + 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.type = 'range'; + range.className = 'vis-network-configuration range'; + range.min = min; + range.max = max; + range.step = step; - 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; + if (value !== undefined) { + if (value < 0 && value * 2 < min) { + range.min = value * 2; + } else if (value * 0.1 < min) { + range.min = value / 10; + } + if (value * 2 > max && max !== 1) { + range.max = value * 2; + } + range.value = value; + } else { + range.value = defaultValue; + } - this.startClientX = event.clientX; - this.startSlideX = parseFloat(this.frame.slide.style.left); + var input = document.createElement('input'); + input.className = 'vis-network-configuration rangeinput'; + input.value = range.value; - this.frame.style.cursor = 'move'; + var me = this; + range.onchange = function () { + input.value = this.value;me._update(Number(this.value), path); + }; + range.oninput = function () { + input.value = this.value; + }; - // 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); + var label = this._makeLabel(path[path.length - 1], path); + this._makeItem(path, label, range, input); + } + }, { + key: '_makeCheckbox', - this.setIndex(index); + /** + * make a checkbox for boolean options. + * @param defaultValue + * @param value + * @param path + * @private + */ + value: function _makeCheckbox(defaultValue, value, path) { + var checkbox = document.createElement('input'); + checkbox.type = 'checkbox'; + checkbox.className = 'vis-network-configuration checkbox'; + checkbox.checked = defaultValue; + if (value !== undefined) { + checkbox.checked = value; + if (value !== defaultValue) { + if (typeof defaultValue === 'object') { + if (value !== defaultValue.enabled) { + this.changedOptions.push({ path: path, value: value }); + } + } else { + this.changedOptions.push({ path: path, value: value }); + } + } + } - util.preventDefault(); - }; + var me = this; + checkbox.onchange = function () { + me._update(this.checked, path); + }; - Slider.prototype._onMouseUp = function (event) { - this.frame.style.cursor = 'auto'; + var label = this._makeLabel(path[path.length - 1], path); + this._makeItem(path, label, checkbox); + } + }, { + key: '_makeTextInput', - // remove event listeners - util.removeEventListener(document, 'mousemove', this.onmousemove); - util.removeEventListener(document, 'mouseup', this.onmouseup); + /** + * make a text input field for string options. + * @param defaultValue + * @param value + * @param path + * @private + */ + value: function _makeTextInput(defaultValue, value, path) { + var checkbox = document.createElement('input'); + checkbox.type = 'text'; + checkbox.className = 'vis-network-configuration text'; + checkbox.value = value; + if (value !== defaultValue) { + this.changedOptions.push({ path: path, value: value }); + } - util.preventDefault(); - }; + var me = this; + checkbox.onchange = function () { + me._update(this.value, path); + }; - module.exports = Slider; + var label = this._makeLabel(path[path.length - 1], path); + this._makeItem(path, label, checkbox); + } + }, { + key: '_makeColorField', -/***/ }, -/* 32 */ -/***/ function(module, exports, __webpack_require__) { + /** + * make a color field with a color picker for color fields + * @param arr + * @param value + * @param path + * @private + */ + value: function _makeColorField(arr, value, path) { + var _this3 = this; - /** - * @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, ...) - */ - "use strict"; + var defaultColor = arr[1]; + var div = document.createElement('div'); + value = value === undefined ? defaultColor : value; - function StepNumber(start, end, step, prettyStep) { - // set default values - this._start = 0; - this._end = 0; - this._step = 1; - this.prettyStep = true; - this.precision = 5; + if (value !== 'none') { + div.className = 'vis-network-configuration colorBlock'; + div.style.backgroundColor = value; + } else { + div.className = 'vis-network-configuration colorBlock none'; + } - this._current = 0; - this.setRange(start, end, step, prettyStep); - }; + value = value === undefined ? defaultColor : value; + div.onclick = function () { + _this3._showColorPicker(value, div, path); + }; - /** - * 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) { - this._start = start ? start : 0; - this._end = end ? end : 0; + var label = this._makeLabel(path[path.length - 1], path); + this._makeItem(path, label, div); + } + }, { + key: '_showColorPicker', - this.setStep(step, prettyStep); - }; + /** + * used by the color buttons to call the color picker. + * @param event + * @param value + * @param div + * @param path + * @private + */ + value: function _showColorPicker(value, div, path) { + var _this4 = this; - /** - * 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; + var rect = div.getBoundingClientRect(); + var bodyRect = document.body.getBoundingClientRect(); + var pickerX = rect.left + rect.width + 5; + var pickerY = rect.top - bodyRect.top + rect.height * 0.5; + this.colorPicker.show(pickerX, pickerY); + this.colorPicker.setColor(value); + this.colorPicker.setCallback(function (color) { + var colorString = 'rgba(' + color.r + ',' + color.g + ',' + color.b + ',' + color.a + ')'; + div.style.backgroundColor = colorString; + _this4._update(colorString, path); + }); + } + }, { + key: '_handleObject', - if (prettyStep !== undefined) this.prettyStep = prettyStep; + /** + * parse an object and draw the correct items + * @param obj + * @param path + * @private + */ + value: function _handleObject(obj) { + var path = arguments[1] === undefined ? [] : arguments[1]; + var checkOnly = arguments[2] === undefined ? false : arguments[2]; - if (this.prettyStep === true) this._step = StepNumber.calculatePrettyStep(step);else this._step = step; - }; + 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); - /** - * 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; - }; + // 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; + } + } + } - // 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))); + if (show !== false) { + visibleInSet = true; + var value = this._getValue(newPath); - // 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; + 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; + } + } - // for safety - if (prettyStep <= 0) { - prettyStep = 1; - } + 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; + } + }, { + key: '_handleArray', - return prettyStep; - }; + /** + * handle the array type of option + * @param optionName + * @param arr + * @param value + * @param path + * @private + */ + 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) }); + } + } + } + }, { + key: '_update', - /** - * returns the current value of the step - * @return {Number} current value - */ - StepNumber.prototype.getCurrent = function () { - return parseFloat(this._current.toPrecision(this.precision)); - }; + /** + * called to update the network with the new settings. + * @param value + * @param path + * @private + */ + value: function _update(value, path) { + var options = this._constructOptions(value, path); + this.parent.setOptions(options); + } + }, { + key: '_constructOptions', + value: function _constructOptions(value, path) { + var optionsObj = arguments[2] === undefined ? {} : arguments[2]; - /** - * returns the current step size - * @return {Number} current step size - */ - StepNumber.prototype.getStep = function () { - return this._step; - }; + var pointer = optionsObj; - /** - * Set the current value to the largest value smaller than start, which - * is a multiple of the step size - */ - StepNumber.prototype.start = function () { - this._current = this._start - this._start % this._step; - }; + // when dropdown boxes can be string or boolean, we typecast it into correct types + value = value === 'true' ? true : value; + value = value === 'false' ? false : value; - /** - * Do a step, add the step size to the current value - */ - StepNumber.prototype.next = function () { - this._current += this._step; - }; + 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; + } + }, { + key: '_printOptions', + value: function _printOptions() { + var options = {}; + for (var i = 0; i < this.changedOptions.length; i++) { + this._constructOptions(this.changedOptions[i].value, this.changedOptions[i].path, options); + } + this.optionsContainer.innerHTML = '
var options = ' + JSON.stringify(options, null, 2) + '
'; + } + }]); - /** - * 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; - }; + return Configurator; + })(); - module.exports = StepNumber; + exports['default'] = Configurator; + module.exports = exports['default']; /***/ }, -/* 33 */ +/* 46 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Emitter = __webpack_require__(27); - var Hammer = __webpack_require__(13); + Object.defineProperty(exports, '__esModule', { + value: true + }); + + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + var util = __webpack_require__(2); - var DataSet = __webpack_require__(22); - var DataView = __webpack_require__(24); - var Range = __webpack_require__(37); - var Core = __webpack_require__(40); - var TimeAxis = __webpack_require__(48); - var CurrentTime = __webpack_require__(34); - var CustomTime = __webpack_require__(51); - var ItemSet = __webpack_require__(10); - - var Configurator = __webpack_require__(52); - var Validator = __webpack_require__(54)['default']; - var printStyle = __webpack_require__(54).printStyle; - var allOptions = __webpack_require__(55).allOptions; - var configureOptions = __webpack_require__(55).configureOptions; + var errorFound = false; + var allOptions = undefined; + var printStyle = 'background: #FFeeee; color: #dd0000'; /** - * Create a timeline visualization - * @param {HTMLElement} container - * @param {vis.DataSet | vis.DataView | Array} [items] - * @param {vis.DataSet | vis.DataView | Array} [groups] - * @param {Object} [options] See Timeline.setOptions for the available options. - * @constructor - * @extends Core + * Used to validate options. */ - function Timeline(container, items, groups, options) { - if (!(this instanceof Timeline)) { - throw new SyntaxError('Constructor must be called with the new operator'); - } - // if the third element is options, the forth is groups (optionally); - if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) { - var forthArgument = options; - options = groups; - groups = forthArgument; + var Validator = (function () { + function Validator() { + _classCallCheck(this, Validator); } - var me = this; - this.defaultOptions = { - start: null, - end: null, + _createClass(Validator, null, [{ + key: 'validate', - autoResize: true, + /** + * Main function to be called + * @param options + * @param subObject + * @returns {boolean} + */ + 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; + } + }, { + key: 'parse', - orientation: { - axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both' - item: 'bottom' // not relevant - }, + /** + * Will traverse an object recursively and check every value + * @param options + * @param referenceOptions + * @param path + */ + value: function parse(options, referenceOptions, path) { + for (var option in options) { + if (options.hasOwnProperty(option)) { + Validator.check(option, options, referenceOptions, path); + } + } + } + }, { + key: 'check', - width: null, - height: null, - maxHeight: null, - minHeight: null - }; - this.options = util.deepExtend({}, this.defaultOptions); - - // Create the DOM, props, and emitter - this._create(container); - - // all components listed here will be repainted automatically - this.components = []; - - this.body = { - dom: this.dom, - domProps: this.props, - emitter: { - on: this.on.bind(this), - off: this.off.bind(this), - emit: this.emit.bind(this) - }, - hiddenDates: [], - util: { - getScale: function getScale() { - return me.timeAxis.step.scale; - }, - getStep: function getStep() { - return me.timeAxis.step.step; - }, - - toScreen: me._toScreen.bind(me), - toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width - toTime: me._toTime.bind(me), - toGlobalTime: me._toGlobalTime.bind(me) + /** + * Check every value. If the value is an object, call the parse function on that object. + * @param option + * @param options + * @param referenceOptions + * @param path + */ + value: function check(option, options, referenceOptions, path) { + if (referenceOptions[option] === undefined && referenceOptions.__any__ === undefined) { + Validator.getSuggestion(option, referenceOptions, path); + } else if (referenceOptions[option] === undefined && referenceOptions.__any__ !== undefined) { + // __any__ is a wildcard. Any value is accepted and will be further analysed by reference. + if (Validator.getType(options[option]) === 'object') { + Validator.checkFields(option, options, referenceOptions, '__any__', referenceOptions['__any__'].__type__, path); + } + } else { + // Since all options in the reference are objects, we can check whether they are supposed to be object to look for the __type__ field. + if (referenceOptions[option].__type__ !== undefined) { + // if this should be an object, we check if the correct type has been supplied to account for shorthand options. + Validator.checkFields(option, options, referenceOptions, option, referenceOptions[option].__type__, path); + } else { + Validator.checkFields(option, options, referenceOptions, option, referenceOptions[option], path); + } + } } - }; - - // range - this.range = new Range(this.body); - this.components.push(this.range); - this.body.range = this.range; - - // time axis - this.timeAxis = new TimeAxis(this.body); - this.timeAxis2 = null; // used in case of orientation option 'both' - this.components.push(this.timeAxis); - - // current time bar - this.currentTime = new CurrentTime(this.body); - this.components.push(this.currentTime); - - // item set - this.itemSet = new ItemSet(this.body); - this.components.push(this.itemSet); - - this.itemsData = null; // DataSet - this.groupsData = null; // DataSet - - this.on('tap', function (event) { - me.emit('click', me.getEventProperties(event)); - }); - this.on('doubletap', function (event) { - me.emit('doubleClick', me.getEventProperties(event)); - }); - this.dom.root.oncontextmenu = function (event) { - me.emit('contextmenu', me.getEventProperties(event)); - }; - - // setup configuration system - this.configurator = new Configurator(this, container, configureOptions); - - // apply options - if (options) { - this.setOptions(options); - } - - // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! - if (groups) { - this.setGroups(groups); - } - - // create itemset - if (items) { - this.setItems(items); - } else { - this._redraw(); - } - } - - // Extend the functionality from Core - Timeline.prototype = new Core(); - - /** - * Force a redraw. The size of all items will be recalculated. - * Can be useful to manually redraw when option autoResize=false and the window - * has been resized, or when the items CSS has been changed. - */ - Timeline.prototype.redraw = function () { - this.itemSet && this.itemSet.markDirty({ refreshItems: true }); - this._redraw(); - }; - - Timeline.prototype.setOptions = function (options) { - // validate options - var errorFound = Validator.validate(options, allOptions); - if (errorFound === true) { - console.log('%cErrors have been found in the supplied options object.', printStyle); - } - - Core.prototype.setOptions.call(this, options); - - if ('type' in options) { - if (options.type !== this.options.type) { - this.options.type = options.type; + }, { + key: 'checkFields', - // force recreation of all items - var itemsData = this.itemsData; - if (itemsData) { - var selection = this.getSelection(); - this.setItems(null); // remove all - this.setItems(itemsData); // add all - this.setSelection(selection); // restore selection + /** + * + * @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} refOptionType | This is the type object from the reference options + * @param {Array} path | where in the object is the option + */ + value: function checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path) { + 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') { + if (refOptionType.indexOf(options[option]) === -1) { + console.log('%cInvalid option detected in "' + option + '".' + ' Allowed values are:' + Validator.print(refOptionType) + ' not "' + options[option] + '". ' + Validator.printLocation(path, option), printStyle); + errorFound = true; + } else if (optionType === 'object') { + path = util.copyAndExtendArray(path, option); + Validator.parse(options[option], referenceOptions[referenceOption], path); + } + } else if (optionType === 'object') { + path = util.copyAndExtendArray(path, option); + Validator.parse(options[option], referenceOptions[referenceOption], path); + } + } else { + if (refOptionObj['undef'] !== undefined && optionType === 'undefined') {} else if (refOptionObj['fn'] !== undefined && optionType === 'function') {} else { + // type of the field is incorrect + console.log('%cInvalid type received for "' + option + '". Expected: ' + Validator.print(Object.keys(refOptionObj)) + '. Received [' + optionType + '] "' + options[option] + '"' + Validator.printLocation(path, option), printStyle); + errorFound = true; + } } } - } - }; - - /** - * Set items - * @param {vis.DataSet | Array | null} items - */ - Timeline.prototype.setItems = function (items) { - var initialLoad = this.itemsData == null; + }, { + key: 'getType', + value: function getType(object) { + var type = typeof object; - // convert to type DataSet when needed - var newDataSet; - if (!items) { - newDataSet = null; - } else if (items instanceof DataSet || items instanceof DataView) { - newDataSet = items; - } else { - // turn an array into a dataset - newDataSet = new DataSet(items, { - type: { - start: 'Date', - end: 'Date' + 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; + } + }, { + key: 'getSuggestion', + value: function getSuggestion(option, options, path) { + var localSearch = Validator.findInOptions(option, options, path, false); + var globalSearch = Validator.findInOptions(option, allOptions, [], true); - // set items - this.itemsData = newDataSet; - this.itemSet && this.itemSet.setItems(newDataSet); + var localSearchThreshold = 8; + var globalSearchThreshold = 4; - if (initialLoad) { - if (this.options.start != undefined || this.options.end != undefined) { - if (this.options.start == undefined || this.options.end == undefined) { - var dataRange = this._getDataRange(); + if (localSearch.indexMatch !== undefined) { + console.log('%cUnknown option detected: "' + option + '" in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was incomplete? Did you mean: "' + localSearch.indexMatch + '"?\n\n', printStyle); + } else if (globalSearch.distance <= globalSearchThreshold && localSearch.distance > globalSearch.distance) { + console.log('%cUnknown option detected: "' + option + '" in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was misplaced? Matching option found at: ' + Validator.printLocation(globalSearch.path, globalSearch.closestMatch, ''), printStyle); + } else if (localSearch.distance <= localSearchThreshold) { + console.log('%cUnknown option detected: "' + option + '". Did you mean "' + localSearch.closestMatch + '"?' + Validator.printLocation(localSearch.path, option), printStyle); + } else { + console.log('%cUnknown option detected: "' + option + '". Did you mean one of these: ' + Validator.print(Object.keys(options)) + Validator.printLocation(path, option), printStyle); } - var start = this.options.start != undefined ? this.options.start : dataRange.start; - var end = this.options.end != undefined ? this.options.end : dataRange.end; - - this.setWindow(start, end, { animation: false }); - } else { - this.fit({ animation: false }); + errorFound = true; } - } - }; - - /** - * Set groups - * @param {vis.DataSet | Array} groups - */ - Timeline.prototype.setGroups = function (groups) { - // convert to type DataSet when needed - var newDataSet; - if (!groups) { - newDataSet = null; - } else if (groups instanceof DataSet || groups instanceof DataView) { - newDataSet = groups; - } else { - // turn an array into a dataset - newDataSet = new DataSet(groups); - } + }, { + key: 'findInOptions', - this.groupsData = newDataSet; - this.itemSet.setGroups(newDataSet); - }; + /** + * traverse the options in search for a match. + * @param option + * @param options + * @param path + * @param recursive + * @returns {{closestMatch: string, path: Array, distance: number}} + */ + value: function findInOptions(option, options, path) { + var recursive = arguments[3] === undefined ? false : arguments[3]; - /** - * Set both items and groups in one go - * @param {{items: Array | vis.DataSet, groups: Array | vis.DataSet}} data - */ - Timeline.prototype.setData = function (data) { - if (data && data.groups) { - this.setGroups(data.groups); - } + var min = 1000000000; + var closestMatch = ''; + var closestMatchPath = []; + var lowerCaseOption = option.toLowerCase(); + var indexMatch = undefined; + for (var op in options) { + var distance = undefined; + 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 }; + } + }, { + key: 'printLocation', + value: function printLocation(path, option) { + var prefix = arguments[2] === undefined ? 'Problem value found at: \n' : arguments[2]; - if (data && data.items) { - this.setItems(data.items); - } - }; + 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 j = 0; j < path.length - i; j++) { + str += ' '; + } + str += '}\n'; + } + return str + '\n\n'; + } + }, { + key: 'print', + value: function print(options) { + return JSON.stringify(options).replace(/(\")|(\[)|(\])|(,"__type__")/g, '').replace(/(\,)/g, ', '); + } + }, { + key: 'levenshteinDistance', - /** - * 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. If ids is an empty array, all items will be - * unselected. - * @param {Object} [options] Available options: - * `focus: boolean` - * If true, focus will be set to the selected item(s) - * `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'. - * Only applicable when option focus is true. - */ - Timeline.prototype.setSelection = function (ids, options) { - this.itemSet && this.itemSet.setSelection(ids); + // 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. + */ + value: function levenshteinDistance(a, b) { + if (a.length === 0) return b.length; + if (b.length === 0) return a.length; - if (options && options.focus) { - this.focus(ids, options); - } - }; + var matrix = []; - /** - * Get the selected items by their id - * @return {Array} ids The ids of the selected items - */ - Timeline.prototype.getSelection = function () { - return this.itemSet && this.itemSet.getSelection() || []; - }; + // increment along the first column of each row + var i; + for (i = 0; i <= b.length; i++) { + matrix[i] = [i]; + } - /** - * Adjust the visible window such that the selected item (or multiple items) - * are centered on screen. - * @param {String | String[]} id An item id or array with item ids - * @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'. - */ - Timeline.prototype.focus = function (id, options) { - if (!this.itemsData || id == undefined) return; + // increment each column in the first row + var j; + for (j = 0; j <= a.length; j++) { + matrix[0][j] = j; + } - var ids = Array.isArray(id) ? id : [id]; + // 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 + } + } + } - // get the specified item(s) - var itemsData = this.itemsData.getDataSet().get(ids, { - type: { - start: 'Date', - end: 'Date' + return matrix[b.length][a.length]; } - }); + }]); - // calculate minimum start and maximum end of specified items - var start = null; - var end = null; - itemsData.forEach(function (itemData) { - var s = itemData.start.valueOf(); - var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf(); + return Validator; + })(); - if (start === null || s < start) { - start = s; - } + exports['default'] = Validator; + exports.printStyle = printStyle; - if (end === null || e > end) { - end = e; - } - }); + // item is undefined, which is allowed - if (start !== null && end !== null) { - // calculate the new middle and interval for the window - var middle = (start + end) / 2; - var interval = Math.max(this.range.end - this.range.start, (end - start) * 1.1); + // item is a function, which is allowed - var animation = options && options.animation !== undefined ? options.animation : true; - this.range.setRange(middle - interval / 2, middle + interval / 2, animation); - } - }; +/***/ }, +/* 47 */ +/***/ function(module, exports, __webpack_require__) { /** - * Get the data range of the item set. - * @returns {{min: Date, max: Date}} range A range with a start and end Date. - * When no minimum is found, min==null - * When no maximum is found, max==null + * This object contains all possible options. It will check if the types are correct, if required if the option is one + * of the allowed values. + * + * __any__ means that the name of the property does not matter. + * __type__ is a required field for all objects and contains the allowed types of all objects */ - Timeline.prototype.getItemRange = function () { - // calculate min from start filed - var dataset = this.itemsData && this.itemsData.getDataSet(); - var min = null; - var max = null; - - if (dataset) { - // calculate the minimum value of the field 'start' - var minItem = dataset.min('start'); - min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null; - // Note: we convert first to Date and then to number because else - // a conversion from ISODate to Number will fail + 'use strict'; - // calculate maximum value of fields 'start' and 'end' - var maxStartItem = dataset.max('start'); - if (maxStartItem) { - max = util.convert(maxStartItem.start, 'Date').valueOf(); - } - var maxEndItem = dataset.max('end'); - if (maxEndItem) { - if (max == null) { - max = util.convert(maxEndItem.end, 'Date').valueOf(); - } else { - max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf()); - } - } - } - - return { - min: min != null ? new Date(min) : null, - max: max != null ? new Date(max) : null - }; - }; - - /** - * Generate Timeline related information from an event - * @param {Event} event - * @return {Object} An object with related information, like on which area - * The event happened, whether clicked on an item, etc. - */ - Timeline.prototype.getEventProperties = function (event) { - var clientX = event.center ? event.center.x : event.clientX; - var clientY = event.center ? event.center.y : event.clientY; - var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer); - var y = clientY - util.getAbsoluteTop(this.dom.centerContainer); - - var item = this.itemSet.itemFromTarget(event); - var group = this.itemSet.groupFromTarget(event); - var customTime = CustomTime.customTimeFromTarget(event); - - var snap = this.itemSet.options.snap || null; - var scale = this.body.util.getScale(); - var step = this.body.util.getStep(); - var time = this._toTime(x); - var snappedTime = snap ? snap(time, scale, step) : time; - - var element = util.getTarget(event); - var what = null; - if (item != null) { - what = 'item'; - } else if (customTime != null) { - what = 'custom-time'; - } else if (util.hasParent(element, this.timeAxis.dom.foreground)) { - what = 'axis'; - } else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) { - what = 'axis'; - } else if (util.hasParent(element, this.itemSet.dom.labelSet)) { - what = 'group-label'; - } else if (util.hasParent(element, this.currentTime.bar)) { - what = 'current-time'; - } else if (util.hasParent(element, this.dom.center)) { - what = 'background'; - } - - return { - event: event, - item: item ? item.id : null, - group: group ? group.groupId : null, - what: what, - pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX, - pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY, - x: x, - y: y, - time: time, - snappedTime: snappedTime - }; - }; - - module.exports = Timeline; - -/***/ }, -/* 34 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var util = __webpack_require__(2); - var Component = __webpack_require__(35); - var moment = __webpack_require__(17); - var locales = __webpack_require__(36); - - /** - * 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 = { - showCurrentTime: true, - - 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(['showCurrentTime', '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 = new Date(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.html#Localization'); - this.warned = true; - } - locale = this.options.locales['en']; // fall back on english when not available - } - var title = locale.current + ' ' + locale.time + ': ' + moment(now).format('dddd, MMMM Do YYYY, H:mm:ss'); - title = title.charAt(0).toUpperCase() + title.substring(1); - - 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; - - 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(); - - // 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; - -/***/ }, -/* 35 */ -/***/ function(module, exports, __webpack_require__) { - - /** - * Prototype for visual components - * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body] - * @param {Object} [options] - */ - "use strict"; - - function Component(body, options) { - 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 () {}; - - /** - * 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; - - // should be implemented by the component - -/***/ }, -/* 36 */ -/***/ function(module, exports, __webpack_require__) { - - // English - 'use strict'; - - exports['en'] = { - current: 'current', - time: 'time' - }; - exports['en_EN'] = exports['en']; - exports['en_US'] = exports['en']; - - // Dutch - exports['nl'] = { - current: 'huidige', - time: 'tijd' - }; - exports['nl_NL'] = exports['nl']; - exports['nl_BE'] = exports['nl']; - -/***/ }, -/* 37 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var util = __webpack_require__(2); - var hammerUtil = __webpack_require__(38); - var moment = __webpack_require__(17); - var Component = __webpack_require__(35); - var DateUtil = __webpack_require__(39); - - /** - * @constructor Range - * 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 - */ - function Range(body, options) { - var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0); - this.start = now.clone().add(-3, 'days').valueOf(); // Number - this.end = now.clone().add(4, 'days').valueOf(); // Number - - this.body = body; - this.deltaDifference = 0; - this.scaleOffset = 0; - this.startToFront = false; - this.endToFront = true; - - // default options - this.defaultOptions = { - start: null, - end: null, - direction: 'horizontal', // 'horizontal' or 'vertical' - moveable: true, - zoomable: true, - min: null, - max: null, - zoomMin: 10, // milliseconds - zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds - }; - 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)); - - 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 = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable', 'activate', 'hiddenDates']; - util.selectiveExtend(fields, this.options, options); - - 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".'); - } - } - - /** - * Set a new start and end range - * @param {Date | Number | String} [start] - * @param {Date | Number | String} [end] - * @param {boolean | {duration: number, easingFunction: string}} [animation=false] - * 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 {Boolean} [byUser=false] - * - */ - Range.prototype.setRange = function (start, end, animation, byUser) { - if (byUser !== true) { - byUser = false; - } - var finalStart = start != undefined ? util.convert(start, 'Date').valueOf() : null; - var finalEnd = end != undefined ? util.convert(end, 'Date').valueOf() : null; - this._cancelAnimation(); - - if (animation) { - // true or an Object - var me = this; - var initStart = this.start; - var initEnd = this.end; - var duration = typeof animation === 'object' && 'duration' in animation ? animation.duration : 500; - var easingName = typeof animation === 'object' && 'easingFunction' in animation ? animation.easingFunction : 'easeInOutQuad'; - var easingFunction = util.easingFunctions[easingName]; - if (!easingFunction) { - throw new Error('Unknown easing function ' + JSON.stringify(easingName) + '. ' + 'Choose from: ' + Object.keys(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.body, me.options.hiddenDates); - anyChanged = anyChanged || changed; - if (changed) { - me.body.emitter.emit('rangechange', { start: new Date(me.start), end: new Date(me.end), byUser: byUser }); - } - - if (done) { - if (anyChanged) { - me.body.emitter.emit('rangechanged', { start: new Date(me.start), end: new Date(me.end), byUser: byUser }); - } - } 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.body, this.options.hiddenDates); - if (changed) { - var params = { start: new Date(this.start), end: new Date(this.end), byUser: byUser }; - this.body.emitter.emit('rangechange', params); - this.body.emitter.emit('rangechanged', params); - } - } - }; - - /** - * 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 start < end - if (newEnd < newStart) { - newEnd = newStart; - } - - // prevent start < min - if (min !== null) { - if (newStart < min) { - diff = min - newStart; - newStart += diff; - newEnd += diff; + Object.defineProperty(exports, '__esModule', { + value: true + }); + var string = 'string'; + var boolean = 'boolean'; + var number = 'number'; + var array = 'array'; + var date = 'date'; + var object = 'object'; // should only be in a __type__ property + var dom = 'dom'; + var moment = 'moment'; + var fn = 'function'; + var nada = 'null'; + var undef = 'undefined'; + var any = 'any'; - // prevent end > max - if (max != null) { - if (newEnd > max) { - newEnd = max; - } - } - } - } + var allOptions = { + configure: { + enabled: { boolean: boolean }, + filter: { boolean: boolean, fn: fn }, + container: { dom: dom }, + __type__: { object: object, boolean: boolean, fn: fn } + }, - // prevent end > max - if (max !== null) { - if (newEnd > max) { - diff = newEnd - max; - newStart -= diff; - newEnd -= diff; + //globals : + align: { string: string }, + autoResize: { boolean: boolean }, + clickToUse: { boolean: boolean }, + dataAttributes: { string: string, array: array }, + editable: { + add: { boolean: boolean, undef: undef }, + remove: { boolean: boolean, undef: undef }, + updateGroup: { boolean: boolean, undef: undef }, + updateTime: { boolean: boolean, undef: undef }, + __type__: { boolean: boolean, object: object } + }, + end: { number: number, date: date, string: string, moment: moment }, + format: { + minorLabels: { + millisecond: { string: string, undef: undef }, + second: { string: string, undef: undef }, + minute: { string: string, undef: undef }, + hour: { string: string, undef: undef }, + weekday: { string: string, undef: undef }, + day: { string: string, undef: undef }, + month: { string: string, undef: undef }, + year: { string: string, undef: undef }, + __type__: { object: object } + }, + majorLabels: { + millisecond: { string: string, undef: undef }, + second: { string: string, undef: undef }, + minute: { string: string, undef: undef }, + hour: { string: string, undef: undef }, + weekday: { string: string, undef: undef }, + day: { string: string, undef: undef }, + month: { string: string, undef: undef }, + year: { string: string, undef: undef }, + __type__: { object: object } + }, + __type__: { object: object } + }, + groupOrder: { string: string, fn: fn }, + height: { string: string, number: number }, + hiddenDates: { object: object, array: array }, + locale: { string: string }, + locales: { + __any__: { object: object }, + __type__: { object: object } + }, + margin: { + axis: { number: number }, + item: { + horizontal: { number: number, undef: undef }, + vertical: { number: number, undef: undef }, + __type__: { object: object, number: number } + }, + __type__: { object: object, number: number } + }, + max: { date: date, number: number, string: string, moment: moment }, + maxHeight: { number: number, string: string }, + min: { date: date, number: number, string: string, moment: moment }, + minHeight: { number: number, string: string }, + moveable: { boolean: boolean }, + multiselect: { boolean: boolean }, + onAdd: { fn: fn }, + onUpdate: { fn: fn }, + onMove: { fn: fn }, + onMoving: { fn: fn }, + onRemove: { fn: fn }, + order: { fn: fn }, + orientation: { + axis: { string: string, undef: undef }, + item: { string: string, undef: undef }, + __type__: { string: string, object: object } + }, + selectable: { boolean: boolean }, + showCurrentTime: { boolean: boolean }, + showMajorLabels: { boolean: boolean }, + showMinorLabels: { boolean: boolean }, + stack: { boolean: boolean }, + snap: { fn: fn, nada: nada }, + start: { date: date, number: number, string: string, moment: moment }, + template: { fn: fn }, + timeAxis: { + scale: { string: string, undef: undef }, + step: { number: number, undef: undef }, + __type__: { object: object } + }, + type: { string: string }, + width: { string: string, number: number }, + zoomable: { boolean: boolean }, + zoomMax: { number: number }, + zoomMin: { number: number }, - // prevent start < min - if (min != null) { - if (newStart < min) { - newStart = min; - } - } - } - } + __type__: { object: object } + }; - // prevent (end-start) < zoomMin - if (this.options.zoomMin !== null) { - var zoomMin = parseFloat(this.options.zoomMin); - if (zoomMin < 0) { - zoomMin = 0; - } - if (newEnd - newStart < zoomMin) { - if (this.end - this.start === zoomMin && newStart > this.start && 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; + var configureOptions = { + global: { + align: ['center', 'left', 'right'], + autoResize: true, + clickToUse: false, + // dataAttributes: ['all'], // FIXME: can be 'all' or string[] + editable: { + add: false, + remove: false, + updateGroup: false, + updateTime: false + }, + end: '', + format: { + minorLabels: { + millisecond: 'SSS', + second: 's', + minute: 'HH:mm', + hour: 'HH:mm', + weekday: 'ddd D', + day: 'D', + 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', + month: 'YYYY', + year: '' } - } - } - - // 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; + //groupOrder: {string, fn}, + height: '', + //hiddenDates: {object, array}, + locale: '', + margin: { + axis: [20, 0, 100, 1], + item: { + horizontal: [10, 0, 100, 1], + vertical: [10, 0, 100, 1] } - } - } - - 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'); + }, + max: '', + maxHeight: '', + min: '', + minHeight: '', + moveable: false, + multiselect: false, + //onAdd: {fn}, + //onUpdate: {fn}, + //onMove: {fn}, + //onMoving: {fn}, + //onRename: {fn}, + //order: {fn}, + orientation: { + axis: ['both', 'bottom', 'top'], + item: ['bottom', 'top'] + }, + selectable: true, + showCurrentTime: false, + showMajorLabels: true, + showMinorLabels: true, + stack: true, + //snap: {fn, nada}, + start: '', + //template: {fn}, + //timeAxis: { + // scale: ['millisecond', 'second', 'minute', 'hour', 'weekday', 'day', 'month', 'year'], + // step: [1, 1, 10, 1] + //}, + type: ['box', 'point', 'range', 'background'], + width: '100%', + zoomable: true, + zoomMax: [315360000000000, 10, 315360000000000, 1], + zoomMin: [10, 10, 315360000000000, 1] } - - 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 - }; - }; + exports.allOptions = allOptions; + exports.configureOptions = configureOptions; - /** - * Calculate the conversion offset and scale for current range, based on - * the provided width - * @param {Number} width - * @returns {{offset: number, scale: number}} conversion - */ - Range.prototype.conversion = function (width, totalHidden) { - return Range.conversion(this.start, this.end, width, totalHidden); - }; +/***/ }, +/* 48 */ +/***/ function(module, exports, __webpack_require__) { /** - * 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 - * @returns {{offset: number, scale: number}} conversion + * This object contains all possible options. It will check if the types are correct, if required if the option is one + * of the allowed values. + * + * __any__ means that the name of the property does not matter. + * __type__ is a required field for all objects and contains the allowed types of all objects */ - 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 - }; - } - }; + 'use strict'; - /** - * 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; + Object.defineProperty(exports, '__esModule', { + value: true + }); + var string = 'string'; + var boolean = 'boolean'; + var number = 'number'; + var array = 'array'; + var date = 'date'; + var object = 'object'; // should only be in a __type__ property + var dom = 'dom'; + var moment = 'moment'; + var fn = 'function'; + var nada = 'null'; + var undef = 'undefined'; + var any = 'any'; - // 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 allOptions = { + configure: { + enabled: { boolean: boolean }, + filter: { boolean: boolean, fn: fn }, + container: { dom: dom }, + __type__: { object: object, boolean: boolean, fn: fn } + }, - this.props.touch.start = this.start; - this.props.touch.end = this.end; - this.props.touch.dragging = true; + //globals : + yAxisOrientation: { string: ['left', 'right'] }, + defaultGroup: { string: string }, + sort: { boolean: boolean }, + sampling: { boolean: boolean }, + stack: { boolean: boolean }, + graphHeight: { string: string, number: number }, + shaded: { + enabled: { boolean: boolean }, + orientation: { string: ['bottom', 'top'] }, // top, bottom + __type__: { boolean: boolean, object: object } + }, + style: { string: ['line', 'bar', 'points'] }, // line, bar + barChart: { + width: { number: number }, + sideBySide: { boolean: boolean }, + align: { string: ['left', 'center', 'right'] }, + __type__: { object: object } + }, + interpolation: { + enabled: { boolean: boolean }, + parametrization: { string: ['centripetal', 'chordal', 'uniform'] }, // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) + alpha: { number: number }, + __type__: { object: object, boolean: boolean } + }, + drawPoints: { + enabled: { boolean: boolean }, + size: { number: number }, + style: { string: ['square', 'circle'] }, // square, circle + __type__: { object: object, boolean: boolean } + }, + dataAxis: { + showMinorLabels: { boolean: boolean }, + showMajorLabels: { boolean: boolean }, + icons: { boolean: boolean }, + width: { string: string, number: number }, + visible: { boolean: boolean }, + alignZeros: { boolean: boolean }, + left: { + range: { min: { number: number }, max: { number: number }, __type__: { object: object } }, + format: { fn: fn }, + title: { text: { string: string, number: number }, style: { string: string }, __type__: { object: object } }, + __type__: { object: object } + }, + right: { + range: { min: { number: number }, max: { number: number }, __type__: { object: object } }, + format: { fn: fn }, + title: { text: { string: string, number: number }, style: { string: string }, __type__: { object: object } }, + __type__: { object: object } + }, + __type__: { object: object } + }, + legend: { + enabled: { boolean: boolean }, + icons: { boolean: boolean }, + left: { + visible: { boolean: boolean }, + position: { string: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] }, + __type__: { object: object } + }, + right: { + visible: { boolean: boolean }, + position: { string: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] }, + __type__: { object: object } + }, + __type__: { object: object, boolean: boolean } + }, + groups: { + visibility: { any: any }, + __type__: { object: object } + }, - if (this.body.dom.root) { - this.body.dom.root.style.cursor = 'move'; - } + autoResize: { boolean: boolean }, + clickToUse: { boolean: boolean }, + end: { number: number, date: date, string: string, moment: moment }, + format: { + minorLabels: { + millisecond: { string: string, undef: undef }, + second: { string: string, undef: undef }, + minute: { string: string, undef: undef }, + hour: { string: string, undef: undef }, + weekday: { string: string, undef: undef }, + day: { string: string, undef: undef }, + month: { string: string, undef: undef }, + year: { string: string, undef: undef }, + __type__: { object: object } + }, + majorLabels: { + millisecond: { string: string, undef: undef }, + second: { string: string, undef: undef }, + minute: { string: string, undef: undef }, + hour: { string: string, undef: undef }, + weekday: { string: string, undef: undef }, + day: { string: string, undef: undef }, + month: { string: string, undef: undef }, + year: { string: string, undef: undef }, + __type__: { object: object } + }, + __type__: { object: object } + }, + height: { string: string, number: number }, + hiddenDates: { object: object, array: array }, + locale: { string: string }, + locales: { + __any__: { object: object }, + __type__: { object: object } + }, + max: { date: date, number: number, string: string, moment: moment }, + maxHeight: { number: number, string: string }, + min: { date: date, number: number, string: string, moment: moment }, + minHeight: { number: number, string: string }, + moveable: { boolean: boolean }, + multiselect: { boolean: boolean }, + orientation: { string: string }, + showCurrentTime: { boolean: boolean }, + showMajorLabels: { boolean: boolean }, + showMinorLabels: { boolean: boolean }, + start: { date: date, number: number, string: string, moment: moment }, + timeAxis: { + scale: { string: string, undef: undef }, + step: { number: number, undef: undef }, + __type__: { object: object } + }, + width: { string: string, number: number }, + zoomable: { boolean: boolean }, + zoomMax: { number: number }, + zoomMin: { number: number }, + __type__: { object: object } }; - /** - * Perform dragging operation - * @param {Event} event - * @private - */ - Range.prototype._onDrag = function (event) { - // 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 configureOptions = { + global: { + //yAxisOrientation: ['left','right'], // TDOO: enable as soon as Grahp2d doesn't crash when changing this on the fly + sort: true, + sampling: true, + stack: false, + shaded: { + enabled: false, + orientation: ['top', 'bottom'] // top, bottom + }, + style: ['line', 'bar', 'points'], // line, bar + barChart: { + width: [50, 5, 100, 5], + sideBySide: false, + align: ['left', 'center', 'right'] // left, center, right + }, + interpolation: { + enabled: true, + parametrization: ['centripetal', 'chordal', 'uniform'] // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) + }, + drawPoints: { + enabled: true, + size: [6, 2, 30, 1], + style: ['square', 'circle'] // square, circle + }, + dataAxis: { + showMinorLabels: true, + showMajorLabels: true, + icons: false, + width: [40, 0, 200, 1], + visible: true, + alignZeros: true, + left: { + //range: {min:undefined,max:undefined}, + //format: function (value) {return value;}, + title: { text: '', style: '' } + }, + right: { + //range: {min:undefined,max:undefined}, + //format: function (value) {return value;}, + title: { text: '', style: '' } + } + }, + legend: { + enabled: false, + icons: true, + left: { + visible: true, + position: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] // top/bottom - left,right + }, + right: { + visible: true, + position: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] // top/bottom - left,right + } + }, - var width = direction == 'horizontal' ? this.body.domProps.center.width : this.body.domProps.center.height; - var diffRange = -delta / width * interval; - var newStart = this.props.touch.start + diffRange; - var newEnd = this.props.touch.end + diffRange; + autoResize: true, + clickToUse: false, + end: '', + format: { + minorLabels: { + millisecond: 'SSS', + second: 's', + minute: 'HH:mm', + hour: 'HH:mm', + weekday: 'ddd D', + day: 'D', + 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', + month: 'YYYY', + year: '' + } + }, - // 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; + height: '', + locale: '', + max: '', + maxHeight: '', + min: '', + minHeight: '', + moveable: true, + orientation: ['both', 'bottom', 'top'], + showCurrentTime: false, + showMajorLabels: true, + showMinorLabels: true, + start: '', + width: '100%', + zoomable: true, + zoomMax: [315360000000000, 10, 315360000000000, 1], + zoomMin: [10, 10, 315360000000000, 1] } - - this.previousDelta = delta; - this._applyRange(newStart, newEnd); - - // fire a rangechange event - this.body.emitter.emit('rangechange', { - start: new Date(this.start), - end: new Date(this.end), - byUser: true - }); }; - /** - * Stop dragging operation - * @param {event} event - * @private - */ - Range.prototype._onDragEnd = function (event) { - // only allow dragging when configured as movable - if (!this.options.moveable) return; + exports.allOptions = allOptions; + exports.configureOptions = configureOptions; - // 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; +/***/ }, +/* 49 */ +/***/ function(module, exports, __webpack_require__) { - this.props.touch.dragging = false; - if (this.body.dom.root) { - this.body.dom.root.style.cursor = 'auto'; - } + 'use strict'; - // fire a rangechanged event - this.body.emitter.emit('rangechanged', { - start: new Date(this.start), - end: new Date(this.end), - byUser: true - }); - }; + var Hammer = __webpack_require__(41); /** - * Event handler for mouse wheel event, used to zoom - * Code from http://adomas.org/javascript-mouse-wheel/ - * @param {Event} event - * @private + * Register a touch event, taking place before a gesture + * @param {Hammer} hammer A hammer instance + * @param {function} callback Callback, called as callback(event) */ - Range.prototype._onMouseWheel = function (event) { - // only allow zooming when configured as zoomable and moveable - if (!(this.options.zoomable && this.options.moveable)) return; + exports.onTouch = function (hammer, callback) { + callback.inputHandler = function (event) { + if (event.isFirst && !isTouching) { + callback(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; - } + isTouching = true; + setTimeout(function () { + isTouching = false; + }, 0); + } + }; - // 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 + hammer.on('hammer.input', callback.inputHandler); + }; - // 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); - } + // isTouching is true while a touch action is being emitted + // this is a hack to prevent `touch` from being fired twice + var isTouching = false; - // calculate center, the date to zoom around - var pointer = getPointer({ x: event.clientX, y: event.clientY }, this.body.dom.center); - var pointerDate = this._pointerToDate(pointer); + /** + * Register a release event, taking place after a gesture + * @param {Hammer} hammer A hammer instance + * @param {function} callback Callback, called as callback(event) + */ + exports.onRelease = function (hammer, callback) { + callback.inputHandler = function (event) { + if (event.isFinal && !isReleasing) { + callback(event); - this.zoom(scale, pointerDate, delta); - } + isReleasing = true; + setTimeout(function () { + isReleasing = false; + }, 0); + } + }; - // Prevent default actions caused by mouse wheel - // (else the page and timeline both zoom and scroll) - event.preventDefault(); + return hammer.on('hammer.input', callback.inputHandler); }; + // isReleasing is true while a release action is being emitted + // this is a hack to prevent `release` from being fired twice + var isReleasing = false; + /** - * Start of a touch gesture - * @private + * Unregister a touch event, taking place before a gesture + * @param {Hammer} hammer A hammer instance + * @param {function} callback Callback, called as callback(event) */ - Range.prototype._onTouch = function (event) { - 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; + exports.offTouch = function (hammer, callback) { + hammer.off('hammer.input', callback.inputHandler); }; /** - * Handle pinch event - * @param {Event} event - * @private + * Unregister a release event, taking place before a gesture + * @param {Hammer} hammer A hammer instance + * @param {function} callback Callback, called as callback(event) */ - Range.prototype._onPinch = function (event) { - // only allow zooming when configured as zoomable and moveable - if (!(this.options.zoomable && this.options.moveable)) return; + exports.offRelease = exports.offTouch; - this.props.touch.allowDragging = false; +/***/ }, +/* 50 */ +/***/ function(module, exports, __webpack_require__) { - if (!this.props.touch.center) { - this.props.touch.center = getPointer(event.center, this.body.dom.center); - } + // English + 'use strict'; - var scale = 1 / (event.scale + this.scaleOffset); - var centerDate = this._pointerToDate(this.props.touch.center); + exports['en'] = { + current: 'current', + time: 'time' + }; + exports['en_EN'] = exports['en']; + exports['en_US'] = exports['en']; - var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end); - var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, centerDate); - var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore; + // Dutch + exports['nl'] = { + current: 'huidige', + time: 'tijd' + }; + exports['nl_NL'] = exports['nl']; + exports['nl_BE'] = exports['nl']; - // 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; +/***/ }, +/* 51 */ +/***/ function(module, exports, __webpack_require__) { - // 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 + 'use strict'; - 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 DOMutil = __webpack_require__(3); + var Points = __webpack_require__(53); - this.setRange(newStart, newEnd, false, true); + function Line(groupId, options) { + this.groupId = groupId; + this.options = options; + } - this.startToFront = false; // revert to default - this.endToFront = true; // revert to default + Line.prototype.getData = function (groupData) { + var combinedData = []; + for (var j = 0; j < groupData.length; j++) { + combinedData.push({ + x: groupData[j].x, + y: groupData[j].y, + groupId: this.groupId + }); + } + return combinedData; }; - /** - * 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; + Line.prototype.getYRange = function (groupData) { + var yMin = groupData[0].y; + var yMax = groupData[0].y; + for (var j = 0; j < groupData.length; j++) { + yMin = yMin > groupData[j].y ? groupData[j].y : yMin; + yMax = yMax < groupData[j].y ? groupData[j].y : yMax; + } + return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation }; + }; - validateDirection(direction); + Line.getStackedYRange = function (combinedData, groupRanges, groupIds, groupLabel, orientation) { + if (combinedData.length > 0) { + // sort by time and by group + combinedData.sort(function (a, b) { + if (a.x === b.x) { + return a.groupId < b.groupId ? -1 : 1; + } else { + return a.x - b.x; + } + }); + var intersections = {}; - 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; + Line._getDataIntersections(intersections, combinedData); + groupRanges[groupLabel] = Line._getStackedYRange(intersections, combinedData); + groupRanges[groupLabel].yAxisOrientation = orientation; + groupIds.push(groupLabel); + } + }; + + Line._getStackedYRange = function (intersections, combinedData) { + var key; + var yMin = combinedData[0].y; + var yMax = combinedData[0].y; + for (var i = 0; i < combinedData.length; i++) { + key = combinedData[i].x; + if (intersections[key] === undefined) { + yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin; + yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax; + } else { + if (combinedData[i].y < 0) { + intersections[key].accumulatedNegative += combinedData[i].y; + } else { + intersections[key].accumulatedPositive += combinedData[i].y; + } + } + } + for (var xpos in intersections) { + if (intersections.hasOwnProperty(xpos)) { + yMin = yMin > intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMin; + yMin = yMin > intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMin; + yMax = yMax < intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMax; + yMax = yMax < intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMax; + } } + + return { min: yMin, max: yMax }; }; /** - * 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 + * Fill the intersections object with counters of how many datapoints share the same x coordinates + * @param intersections + * @param combinedData * @private */ - function getPointer(touch, element) { - return { - x: touch.x - util.getAbsoluteLeft(element), - y: touch.y - util.getAbsoluteTop(element) - }; - } + Line._getDataIntersections = function (intersections, combinedData) { + // get intersections + var coreDistance; + for (var i = 0; i < combinedData.length; i++) { + if (i + 1 < combinedData.length) { + coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x); + } + if (i > 0) { + coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x)); + } + if (coreDistance === 0) { + if (intersections[combinedData[i].x] === undefined) { + intersections[combinedData[i].x] = { amount: 0, resolved: 0, accumulatedPositive: 0, accumulatedNegative: 0 }; + } + intersections[combinedData[i].x].amount += 1; + } + } + }; /** - * 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. + * draw a line graph + * + * @param dataset + * @param group */ - Range.prototype.zoom = function (scale, center, delta) { - // if centerDate is not provided, take it half between start Date and end Date - if (center == null) { - center = (this.start + this.end) / 2; - } + Line.prototype.draw = function (dataset, group, framework) { + if (dataset != null) { + if (dataset.length > 0) { + var path, d; + var svgHeight = Number(framework.svg.style.height.replace('px', '')); + path = DOMutil.getSVGElement('path', framework.svgElements, framework.svg); + path.setAttributeNS(null, 'class', group.className); + if (group.style !== undefined) { + path.setAttributeNS(null, 'style', group.style); + } - var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end); - var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, center); - var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore; + // construct path from dataset + if (group.options.interpolation.enabled == true) { + d = Line._catmullRom(dataset, group); + } else { + d = Line._linear(dataset); + } - // calculate new start and end - var newStart = center - hiddenDurationBefore + (this.start - (center - hiddenDurationBefore)) * scale; - var newEnd = center + hiddenDurationAfter + (this.end - (center + hiddenDurationAfter)) * scale; + // append with points for fill and finalize the path + if (group.options.shaded.enabled == true) { + var fillPath = DOMutil.getSVGElement('path', framework.svgElements, framework.svg); + var dFill; + if (group.options.shaded.orientation == 'top') { + dFill = 'M' + dataset[0].x + ',' + 0 + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + 0; + } else { + dFill = 'M' + dataset[0].x + ',' + svgHeight + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + svgHeight; + } + fillPath.setAttributeNS(null, 'class', group.className + ' vis-fill'); + if (group.options.shaded.style !== undefined) { + fillPath.setAttributeNS(null, 'style', group.options.shaded.style); + } + fillPath.setAttributeNS(null, 'd', dFill); + } + // copy properties to path for drawing. + path.setAttributeNS(null, 'd', 'M' + d); - // 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; + // draw points + if (group.options.drawPoints.enabled == true) { + Points.draw(dataset, group, framework); + } + } } - - this.setRange(newStart, newEnd, false, true); - - 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 + * This uses an uniform parametrization of the interpolation algorithm: + * 'On the Parameterization of Catmull-Rom Curves' by Cem Yuksel et al. + * @param data + * @returns {string} + * @private */ - Range.prototype.move = function (delta) { - // zoom start Date and end Date relative to the centerDate - var diff = this.end - this.start; + Line._catmullRomUniform = function (data) { + // catmull rom + var p0, p1, p2, p3, bp1, bp2; + var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' '; + var normalization = 1 / 6; + var length = data.length; + for (var i = 0; i < length - 1; i++) { - // apply new values - var newStart = this.start + diff * delta; - var newEnd = this.end + diff * delta; + p0 = i == 0 ? data[0] : data[i - 1]; + p1 = data[i]; + p2 = data[i + 1]; + p3 = i + 2 < length ? data[i + 2] : p2; - // TODO: reckon with min and max range + // Catmull-Rom to Cubic Bezier conversion matrix + // 0 1 0 0 + // -1/6 1 1/6 0 + // 0 1/6 1 -1/6 + // 0 0 1 0 - this.start = newStart; - this.end = newEnd; + // bp0 = { x: p1.x, y: p1.y }; + bp1 = { x: (-p0.x + 6 * p1.x + p2.x) * normalization, y: (-p0.y + 6 * p1.y + p2.y) * normalization }; + bp2 = { x: (p1.x + 6 * p2.x - p3.x) * normalization, y: (p1.y + 6 * p2.y - p3.y) * normalization }; + // bp0 = { x: p2.x, y: p2.y }; + + d += 'C' + bp1.x + ',' + bp1.y + ' ' + bp2.x + ',' + bp2.y + ' ' + p2.x + ',' + p2.y + ' '; + } + + return d; }; /** - * Move the range to a new center point - * @param {Number} moveTo New center point of the range + * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm. + * By default, the centripetal parameterization is used because this gives the nicest results. + * These parameterizations are relatively heavy because the distance between 4 points have to be calculated. + * + * One optimization can be used to reuse distances since this is a sliding window approach. + * @param data + * @param group + * @returns {string} + * @private */ - 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; - - this.setRange(newStart, newEnd); - }; + Line._catmullRom = function (data, group) { + var alpha = group.options.interpolation.alpha; + if (alpha == 0 || alpha === undefined) { + return this._catmullRomUniform(data); + } else { + var p0, p1, p2, p3, bp1, bp2, d1, d2, d3, A, B, N, M; + var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA; + var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' '; + var length = data.length; + for (var i = 0; i < length - 1; i++) { - module.exports = Range; + p0 = i == 0 ? data[0] : data[i - 1]; + p1 = data[i]; + p2 = data[i + 1]; + p3 = i + 2 < length ? data[i + 2] : p2; -/***/ }, -/* 38 */ -/***/ function(module, exports, __webpack_require__) { + d1 = Math.sqrt(Math.pow(p0.x - p1.x, 2) + Math.pow(p0.y - p1.y, 2)); + d2 = Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2)); + d3 = Math.sqrt(Math.pow(p2.x - p3.x, 2) + Math.pow(p2.y - p3.y, 2)); - 'use strict'; + // Catmull-Rom to Cubic Bezier conversion matrix - var Hammer = __webpack_require__(13); + // A = 2d1^2a + 3d1^a * d2^a + d3^2a + // B = 2d3^2a + 3d3^a * d2^a + d2^2a - /** - * 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 && !isTouching) { - callback(event); + // [ 0 1 0 0 ] + // [ -d2^2a /N A/N d1^2a /N 0 ] + // [ 0 d3^2a /M B/M -d2^2a /M ] + // [ 0 0 1 0 ] - isTouching = true; - setTimeout(function () { - isTouching = false; - }, 0); - } - }; + d3powA = Math.pow(d3, alpha); + d3pow2A = Math.pow(d3, 2 * alpha); + d2powA = Math.pow(d2, alpha); + d2pow2A = Math.pow(d2, 2 * alpha); + d1powA = Math.pow(d1, alpha); + d1pow2A = Math.pow(d1, 2 * alpha); - hammer.on('hammer.input', callback.inputHandler); - }; + A = 2 * d1pow2A + 3 * d1powA * d2powA + d2pow2A; + B = 2 * d3pow2A + 3 * d3powA * d2powA + d2pow2A; + N = 3 * d1powA * (d1powA + d2powA); + if (N > 0) { + N = 1 / N; + } + M = 3 * d3powA * (d3powA + d2powA); + if (M > 0) { + M = 1 / M; + } - // isTouching is true while a touch action is being emitted - // this is a hack to prevent `touch` from being fired twice - var isTouching = false; + bp1 = { x: (-d2pow2A * p0.x + A * p1.x + d1pow2A * p2.x) * N, + y: (-d2pow2A * p0.y + A * p1.y + d1pow2A * p2.y) * N }; - /** - * Register a release event, taking place after a gesture - * @param {Hammer} hammer A hammer instance - * @param {function} callback Callback, called as callback(event) - */ - exports.onRelease = function (hammer, callback) { - callback.inputHandler = function (event) { - if (event.isFinal && !isReleasing) { - callback(event); + bp2 = { x: (d3pow2A * p1.x + B * p2.x - d2pow2A * p3.x) * M, + y: (d3pow2A * p1.y + B * p2.y - d2pow2A * p3.y) * M }; - isReleasing = true; - setTimeout(function () { - isReleasing = false; - }, 0); + if (bp1.x == 0 && bp1.y == 0) { + bp1 = p1; + } + if (bp2.x == 0 && bp2.y == 0) { + bp2 = p2; + } + d += 'C' + bp1.x + ',' + bp1.y + ' ' + bp2.x + ',' + bp2.y + ' ' + p2.x + ',' + p2.y + ' '; } - }; - return hammer.on('hammer.input', callback.inputHandler); + return d; + } }; - // isReleasing is true while a release action is being emitted - // this is a hack to prevent `release` from being fired twice - var isReleasing = false; - /** - * Unregister a touch event, taking place before a gesture - * @param {Hammer} hammer A hammer instance - * @param {function} callback Callback, called as callback(event) + * this generates the SVG path for a linear drawing between datapoints. + * @param data + * @returns {string} + * @private */ - exports.offTouch = function (hammer, callback) { - hammer.off('hammer.input', callback.inputHandler); + Line._linear = function (data) { + // linear + var d = ''; + for (var i = 0; i < data.length; i++) { + if (i == 0) { + d += data[i].x + ',' + data[i].y; + } else { + d += ' ' + data[i].x + ',' + data[i].y; + } + } + return d; }; - /** - * 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; + module.exports = Line; /***/ }, -/* 39 */ +/* 52 */ /***/ function(module, exports, __webpack_require__) { - "use strict"; + 'use strict'; - var moment = __webpack_require__(17); + var DOMutil = __webpack_require__(3); + var Points = __webpack_require__(53); - /** - * used in Core to convert the options into a volatile variable - * - * @param Core - */ - exports.convertHiddenOptions = function (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 - } + function Bargraph(groupId, options) { + this.groupId = groupId; + this.options = options; + } + + Bargraph.prototype.getYRange = function (groupData) { + var yMin = groupData[0].y; + var yMax = groupData[0].y; + for (var j = 0; j < groupData.length; j++) { + yMin = yMin > groupData[j].y ? groupData[j].y : yMin; + yMax = yMax < groupData[j].y ? groupData[j].y : yMax; + } + return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation }; + }; + + Bargraph.prototype.getData = function (groupData) { + var combinedData = []; + for (var j = 0; j < groupData.length; j++) { + combinedData.push({ + x: groupData[j].x, + y: groupData[j].y, + groupId: this.groupId + }); } + return combinedData; }; /** - * create new entrees for the repeating hidden dates - * @param body - * @param hiddenDates + * draw a bar graph + * + * @param groupIds + * @param processedGroupData */ - exports.updateHiddenDates = function (body, hiddenDates) { - if (hiddenDates && body.domProps.centerContainer.width !== undefined) { - exports.convertHiddenOptions(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); + Bargraph.draw = function (groupIds, processedGroupData, framework) { + var combinedData = []; + var intersections = {}; + var coreDistance; + var key, drawData; + var group; + var i, j; + var barPoints = 0; - 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); + // combine all barchart data + for (i = 0; i < groupIds.length; i++) { + group = framework.groups[groupIds[i]]; + if (group.options.style === 'bar') { + if (group.visible === true && (framework.options.groups.visibility[groupIds[i]] === undefined || framework.options.groups.visibility[groupIds[i]] === true)) { + for (j = 0; j < processedGroupData[groupIds[i]].length; j++) { + combinedData.push({ + x: processedGroupData[groupIds[i]][j].x, + y: processedGroupData[groupIds[i]][j].y, + groupId: groupIds[i], + label: processedGroupData[groupIds[i]][j].label + }); + barPoints += 1; } + } + } + } - 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"); + if (barPoints === 0) { + return; + } - startDate.subtract(1, "weeks"); - endDate.subtract(1, "weeks"); + // sort by time and by group + combinedData.sort(function (a, b) { + if (a.x === b.x) { + return a.groupId < b.groupId ? -1 : 1; + } else { + return a.x - b.x; + } + }); - 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"); + // get intersections + Bargraph._getDataIntersections(intersections, combinedData); - endDate.month(start.month()); - endDate.year(start.year()); - endDate.subtract(1, "months"); - endDate.add(offset, "months"); + // plot barchart + for (i = 0; i < combinedData.length; i++) { + group = framework.groups[combinedData[i].groupId]; + var minWidth = 0.1 * group.options.barChart.width; - 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"); + key = combinedData[i].x; + var heightOffset = 0; + if (intersections[key] === undefined) { + if (i + 1 < combinedData.length) { + coreDistance = Math.abs(combinedData[i + 1].x - key); + } + if (i > 0) { + coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - key)); + } + drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth); + } else { + var nextKey = i + (intersections[key].amount - intersections[key].resolved); + var prevKey = i - (intersections[key].resolved + 1); + if (nextKey < combinedData.length) { + coreDistance = Math.abs(combinedData[nextKey].x - key); + } + if (prevKey > 0) { + coreDistance = Math.min(coreDistance, Math.abs(combinedData[prevKey].x - key)); + } + drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth); + intersections[key].resolved += 1; - 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() }); + if (group.options.stack === true) { + if (combinedData[i].y < group.zeroPosition) { + heightOffset = intersections[key].accumulatedNegative; + intersections[key].accumulatedNegative += group.zeroPosition - combinedData[i].y; + } else { + heightOffset = intersections[key].accumulatedPositive; + intersections[key].accumulatedPositive += group.zeroPosition - combinedData[i].y; + } + } else if (group.options.barChart.sideBySide === true) { + drawData.width = drawData.width / intersections[key].amount; + drawData.offset += intersections[key].resolved * drawData.width - 0.5 * drawData.width * (intersections[key].amount + 1); + if (group.options.barChart.align === 'left') { + drawData.offset -= 0.5 * drawData.width; + } else if (group.options.barChart.align === 'right') { + drawData.offset += 0.5 * drawData.width; } } } - // 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); + DOMutil.drawBar(combinedData[i].x + drawData.offset, combinedData[i].y - heightOffset, drawData.width, group.zeroPosition - combinedData[i].y, group.className + ' vis-bar', framework.svgElements, framework.svg, group.style); + // draw points + if (group.options.drawPoints.enabled === true) { + Points.draw([combinedData[i]], group, framework, drawData.offset); + //DOMutil.drawPoint(combinedData[i].x + drawData.offset, combinedData[i].y, group, framework.svgElements, framework.svg); } } }; /** - * remove duplicates from the hidden dates list. Duplicates are evil. They mess everything up. - * Scales with N^2 - * @param body + * Fill the intersections object with counters of how many datapoints share the same x coordinates + * @param intersections + * @param combinedData + * @private */ - 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; - } + Bargraph._getDataIntersections = function (intersections, combinedData) { + // get intersections + var coreDistance; + for (var i = 0; i < combinedData.length; i++) { + if (i + 1 < combinedData.length) { + coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x); + } + if (i > 0) { + coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x)); + } + if (coreDistance === 0) { + if (intersections[combinedData[i].x] === undefined) { + intersections[combinedData[i].x] = { amount: 0, resolved: 0, accumulatedPositive: 0, accumulatedNegative: 0 }; } + intersections[combinedData[i].x].amount += 1; } } + }; - for (var i = 0; i < hiddenDates.length; i++) { - if (hiddenDates[i].remove !== true) { - safeDates.push(hiddenDates[i]); + /** + * Get the width and offset for bargraphs based on the coredistance between datapoints + * + * @param coreDistance + * @param group + * @param minWidth + * @returns {{width: Number, offset: Number}} + * @private + */ + Bargraph._getSafeDrawData = function (coreDistance, group, minWidth) { + var width, offset; + if (coreDistance < group.options.barChart.width && coreDistance > 0) { + width = coreDistance < minWidth ? minWidth : coreDistance; + + offset = 0; // recalculate offset with the new width; + if (group.options.barChart.align === 'left') { + offset -= 0.5 * coreDistance; + } else if (group.options.barChart.align === 'right') { + offset += 0.5 * coreDistance; + } + } else { + // default settings + width = group.options.barChart.width; + offset = 0; + if (group.options.barChart.align === 'left') { + offset -= 0.5 * group.options.barChart.width; + } else if (group.options.barChart.align === 'right') { + offset += 0.5 * group.options.barChart.width; } } - body.hiddenDates = safeDates; - body.hiddenDates.sort(function (a, b) { - return a.start - b.start; - }); // sort by start time + return { width: width, offset: offset }; }; - 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); + Bargraph.getStackedYRange = function (combinedData, groupRanges, groupIds, groupLabel, orientation) { + if (combinedData.length > 0) { + // sort by time and by group + combinedData.sort(function (a, b) { + if (a.x === b.x) { + return a.groupId < b.groupId ? -1 : 1; + } else { + return a.x - b.x; + } + }); + var intersections = {}; + + Bargraph._getDataIntersections(intersections, combinedData); + groupRanges[groupLabel] = Bargraph._getStackedYRange(intersections, combinedData); + groupRanges[groupLabel].yAxisOrientation = orientation; + groupIds.push(groupLabel); } }; - /** - * Used in TimeStep to avoid the hidden times. - * @param timeStep - * @param previousTime - */ - exports.stepOverHiddenDates = function (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; + Bargraph._getStackedYRange = function (intersections, combinedData) { + var key; + var yMin = combinedData[0].y; + var yMax = combinedData[0].y; + for (var i = 0; i < combinedData.length; i++) { + key = combinedData[i].x; + if (intersections[key] === undefined) { + yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin; + yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax; + } else { + if (combinedData[i].y < 0) { + intersections[key].accumulatedNegative += combinedData[i].y; + } else { + intersections[key].accumulatedPositive += combinedData[i].y; + } } } - - 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; + for (var xpos in intersections) { + if (intersections.hasOwnProperty(xpos)) { + yMin = yMin > intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMin; + yMin = yMin > intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMin; + yMax = yMax < intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMax; + yMax = yMax < intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMax; } - - timeStep.current = newValue.toDate(); } + + return { min: yMin, max: yMax }; }; - ///** - // * 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(); - // } - //}; + module.exports = Bargraph; - /** - * replaces the Core toScreen methods - * @param Core - * @param time - * @param width - * @returns {number} - */ - exports.toScreen = function (Core, time, width) { - if (Core.body.hiddenDates.length == 0) { - var 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; - } +/***/ }, +/* 53 */ +/***/ function(module, exports, __webpack_require__) { - var duration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end); - time = exports.correctTimeForHidden(Core.body.hiddenDates, Core.range, time); + 'use strict'; - var conversion = Core.range.conversion(width, duration); - return (time.valueOf() - conversion.offset) * conversion.scale; - } - }; + var DOMutil = __webpack_require__(3); - /** - * Replaces the core toTime methods - * @param body - * @param range - * @param x - * @param 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); + function Points(groupId, options) { + this.groupId = groupId; + this.options = options; + } - var newTime = new Date(accumulatedHiddenDuration + partialDuration + Core.range.start); - return newTime; + Points.prototype.getYRange = function (groupData) { + var yMin = groupData[0].y; + var yMax = groupData[0].y; + for (var j = 0; j < groupData.length; j++) { + yMin = yMin > groupData[j].y ? groupData[j].y : yMin; + yMax = yMax < groupData[j].y ? groupData[j].y : yMax; } + return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation }; + }; + + Points.prototype.draw = function (dataset, group, framework, offset) { + Points.draw(dataset, group, framework, offset); }; /** - * Support function + * draw the data points * - * @param hiddenDates - * @param range - * @returns {number} + * @param {Array} dataset + * @param {Object} JSONcontainer + * @param {Object} svg | SVG DOM element + * @param {GraphGroup} group + * @param {Number} [offset] */ - 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; - } + Points.draw = function (dataset, group, framework, offset) { + if (offset === undefined) { + offset = 0; + } + for (var i = 0; i < dataset.length; i++) { + DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, framework.svgElements, framework.svg, dataset[i].label); } - return duration; }; + module.exports = Points; + +/***/ }, +/* 54 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var util = __webpack_require__(2); + /** - * Support function - * @param hiddenDates - * @param range - * @param time - * @returns {{duration: number, time: *, offset: number}} + * @class Groups + * This class can store groups and options specific for groups. */ - exports.correctTimeForHidden = function (hiddenDates, range, time) { - time = moment(time).toDate().valueOf(); - time -= exports.getHiddenDurationBefore(hiddenDates, range, time); - return time; - }; - exports.getHiddenDurationBefore = function (hiddenDates, range, time) { - var timeOffset = 0; - time = moment(time).toDate().valueOf(); + var Groups = (function () { + function Groups() { + _classCallCheck(this, Groups); - 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; - } - } + this.clear(); + this.defaultIndex = 0; + this.groupsArray = []; + this.groupIndex = 0; + + this.defaultGroups = [{ border: "#2B7CE9", background: "#97C2FC", highlight: { border: "#2B7CE9", background: "#D2E5FF" }, hover: { border: "#2B7CE9", background: "#D2E5FF" } }, // 0: blue + { border: "#FFA500", background: "#FFFF00", highlight: { border: "#FFA500", background: "#FFFFA3" }, hover: { border: "#FFA500", background: "#FFFFA3" } }, // 1: yellow + { border: "#FA0A10", background: "#FB7E81", highlight: { border: "#FA0A10", background: "#FFAFB1" }, hover: { border: "#FA0A10", background: "#FFAFB1" } }, // 2: red + { border: "#41A906", background: "#7BE141", highlight: { border: "#41A906", background: "#A1EC76" }, hover: { border: "#41A906", background: "#A1EC76" } }, // 3: green + { border: "#E129F0", background: "#EB7DF4", highlight: { border: "#E129F0", background: "#F0B3F5" }, hover: { border: "#E129F0", background: "#F0B3F5" } }, // 4: magenta + { border: "#7C29F0", background: "#AD85E4", highlight: { border: "#7C29F0", background: "#D3BDF0" }, hover: { border: "#7C29F0", background: "#D3BDF0" } }, // 5: purple + { border: "#C37F00", background: "#FFA807", highlight: { border: "#C37F00", background: "#FFCA66" }, hover: { border: "#C37F00", background: "#FFCA66" } }, // 6: orange + { border: "#4220FB", background: "#6E6EFD", highlight: { border: "#4220FB", background: "#9B9BFD" }, hover: { border: "#4220FB", background: "#9B9BFD" } }, // 7: darkblue + { border: "#FD5A77", background: "#FFC0CB", highlight: { border: "#FD5A77", background: "#FFD1D9" }, hover: { border: "#FD5A77", background: "#FFD1D9" } }, // 8: pink + { border: "#4AD63A", background: "#C2FABC", highlight: { border: "#4AD63A", background: "#E6FFE3" }, hover: { border: "#4AD63A", background: "#E6FFE3" } }, // 9: mint + + { border: "#990000", background: "#EE0000", highlight: { border: "#BB0000", background: "#FF3333" }, hover: { border: "#BB0000", background: "#FF3333" } }, // 10:bright red + + { border: "#FF6000", background: "#FF6000", highlight: { border: "#FF6000", background: "#FF6000" }, hover: { border: "#FF6000", background: "#FF6000" } }, // 12: real orange + { border: "#97C2FC", background: "#2B7CE9", highlight: { border: "#D2E5FF", background: "#2B7CE9" }, hover: { border: "#D2E5FF", background: "#2B7CE9" } }, // 13: blue + { border: "#399605", background: "#255C03", highlight: { border: "#399605", background: "#255C03" }, hover: { border: "#399605", background: "#255C03" } }, // 14: green + { border: "#B70054", background: "#FF007E", highlight: { border: "#B70054", background: "#FF007E" }, hover: { border: "#B70054", background: "#FF007E" } }, // 15: magenta + { border: "#AD85E4", background: "#7C29F0", highlight: { border: "#D3BDF0", background: "#7C29F0" }, hover: { border: "#D3BDF0", background: "#7C29F0" } }, // 16: purple + { border: "#4557FA", background: "#000EA1", highlight: { border: "#6E6EFD", background: "#000EA1" }, hover: { border: "#6E6EFD", background: "#000EA1" } }, // 17: darkblue + { border: "#FFC0CB", background: "#FD5A77", highlight: { border: "#FFD1D9", background: "#FD5A77" }, hover: { border: "#FFD1D9", background: "#FD5A77" } }, // 18: pink + { border: "#C2FABC", background: "#74D66A", highlight: { border: "#E6FFE3", background: "#74D66A" }, hover: { border: "#E6FFE3", background: "#74D66A" } }, // 19: mint + + { border: "#EE0000", background: "#990000", highlight: { border: "#FF3333", background: "#BB0000" }, hover: { border: "#FF3333", background: "#BB0000" } } // 20:bright red + ]; + + this.options = {}; + this.defaultOptions = { + useDefaultGroups: true + }; + util.extend(this.options, this.defaultOptions); } - 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 hiddenDates - * @param range - * @param time - * @returns {{duration: number, time: *, offset: 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; + _createClass(Groups, [{ + key: "setOptions", + value: function setOptions(options) { + var optionFields = ["useDefaultGroups"]; + + if (options !== undefined) { + for (var groupName in options) { + if (options.hasOwnProperty(groupName)) { + if (optionFields.indexOf(groupName) === -1) { + var group = options[groupName]; + this.add(groupName, group); + } + } + } } } - } + }, { + key: "clear", - return hiddenDuration; - }; + /** + * Clear all groups + */ + value: function clear() { + this.groups = {}; + this.groupsArray = []; + } + }, { + key: "get", - /** - * used to step over to either side of a hidden block. Correction is disabled on tablets, might be set to true - * @param hiddenDates - * @param time - * @param direction - * @param correctionEnabled - * @returns {*} - */ - 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; + /** + * get group options of a groupname. If groupname is not found, a new group + * is added. + * @param {*} groupname Can be a number, string, Date, etc. + * @return {Object} group The created group, containing all group options + */ + value: function get(groupname) { + var group = this.groups[groupname]; + if (group === undefined) { + if (this.options.useDefaultGroups === false && this.groupsArray.length > 0) { + // create new group + var index = this.groupIndex % this.groupsArray.length; + this.groupIndex++; + group = {}; + group.color = this.groups[this.groupsArray[index]]; + this.groups[groupname] = group; + } else { + // create new group + var index = this.defaultIndex % this.defaultGroups.length; + this.defaultIndex++; + group = {}; + group.color = this.defaultGroups[index]; + this.groups[groupname] = group; + } } - } - } else { - return time; - } - }; - /** - * Check if a time is hidden - * - * @param time - * @param 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; + return group; + } + }, { + key: "add", - if (time >= startDate && time < endDate) { - // if the start is entering a hidden zone - return { hidden: true, startDate: startDate, endDate: endDate }; - break; + /** + * Add a custom group style + * @param {String} groupName + * @param {Object} style An object containing borderColor, + * backgroundColor, etc. + * @return {Object} group The created group object + */ + value: function add(groupName, style) { + this.groups[groupName] = style; + this.groupsArray.push(groupName); + return style; } - } - return { hidden: false, startDate: startDate, endDate: endDate }; - }; + }]); + + return Groups; + })(); + + exports["default"] = Groups; + module.exports = exports["default"]; /***/ }, -/* 40 */ +/* 55 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Emitter = __webpack_require__(27); - var Hammer = __webpack_require__(13); - var hammerUtil = __webpack_require__(38); + Object.defineProperty(exports, '__esModule', { + value: true + }); + + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + var _componentsNode = __webpack_require__(74); + + var _componentsNode2 = _interopRequireDefault(_componentsNode); + + var _componentsSharedLabel = __webpack_require__(75); + + var _componentsSharedLabel2 = _interopRequireDefault(_componentsSharedLabel); + var util = __webpack_require__(2); - var DataSet = __webpack_require__(22); - var DataView = __webpack_require__(24); - var Range = __webpack_require__(37); - var ItemSet = __webpack_require__(10); - var TimeAxis = __webpack_require__(48); - var Activator = __webpack_require__(49); - var DateUtil = __webpack_require__(39); - var CustomTime = __webpack_require__(51); + var DataSet = __webpack_require__(4); + var DataView = __webpack_require__(5); - /** - * Create a timeline visualization - * @constructor - */ - function Core() {} + var NodesHandler = (function () { + function NodesHandler(body, images, groups, layoutEngine) { + var _this = this; - // turn Core into an event emitter - Emitter(Core.prototype); + _classCallCheck(this, NodesHandler); - /** - * 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.body = body; + this.images = images; + this.groups = groups; + this.layoutEngine = layoutEngine; - 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'); + // create the node API in the body container + this.body.functions.createNode = this.create.bind(this); + + this.nodesListeners = { + add: function add(event, params) { + _this.add(params.items); + }, + update: function update(event, params) { + _this.update(params.items, params.data); + }, + remove: function remove(event, params) { + _this.remove(params.items); + } + }; + + this.options = {}; + this.defaultOptions = { + borderWidth: 1, + borderWidthSelected: 2, + brokenImage: undefined, + color: { + border: '#2B7CE9', + background: '#97C2FC', + highlight: { + border: '#2B7CE9', + background: '#D2E5FF' + }, + hover: { + border: '#2B7CE9', + background: '#D2E5FF' + } + }, + fixed: { + x: false, + y: false + }, + font: { + color: '#343434', + size: 14, // px + face: 'arial', + background: 'none', + strokeWidth: 0, // px + strokeColor: '#ffffff', + align: 'horizontal' + }, + group: undefined, + hidden: false, + icon: { + face: 'FontAwesome', //'FontAwesome', + code: undefined, //'\uf007', + size: 50, //50, + color: '#2B7CE9' //'#aa00ff' + }, + image: undefined, // --> URL + label: undefined, + level: undefined, + mass: 1, + physics: true, + scaling: { + min: 10, + max: 30, + label: { + enabled: false, + min: 14, + max: 30, + maxVisible: 30, + drawThreshold: 5 + }, + customScalingFunction: function customScalingFunction(min, max, total, value) { + if (max === min) { + return 0.5; + } else { + var scale = 1 / (max - min); + return Math.max(0, (value - min) * scale); + } + } + }, + shadow: { + enabled: false, + size: 10, + x: 5, + y: 5 + }, + shape: 'ellipse', + size: 25, + title: undefined, + value: undefined, + x: undefined, + y: undefined + }; + util.extend(this.options, this.defaultOptions); + + this.bindEventListeners(); + } + + _createClass(NodesHandler, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this2 = this; + + // refresh the nodes. Used when reverting from hierarchical layout + this.body.emitter.on('refreshNodes', this.refresh.bind(this)); + this.body.emitter.on('refresh', this.refresh.bind(this)); + this.body.emitter.on('destroy', function () { + delete _this2.body.functions.createNode; + delete _this2.nodesListeners.add; + delete _this2.nodesListeners.update; + delete _this2.nodesListeners.remove; + delete _this2.nodesListeners; + }); + } + }, { + key: 'setOptions', + value: function setOptions(options) { + if (options !== undefined) { + _componentsNode2['default'].parseOptions(this.options, options); + + // update the shape in all nodes + if (options.shape !== undefined) { + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + this.body.nodes[nodeId].updateShape(); + } + } + } + + // update the shape size in all nodes + if (options.font !== undefined) { + _componentsSharedLabel2['default'].parseOptions(this.options.font, options); + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + this.body.nodes[nodeId].updateLabelModule(); + this.body.nodes[nodeId]._reset(); + } + } + } + + // update the shape size in all nodes + if (options.size !== undefined) { + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + this.body.nodes[nodeId]._reset(); + } + } + } + + // update the state of the letiables if needed + if (options.hidden !== undefined || options.physics !== undefined) { + this.body.emitter.emit('_dataChanged'); + } + } + } + }, { + key: 'setData', + + /** + * Set a data set with nodes for the network + * @param {Array | DataSet | DataView} nodes The data containing the nodes. + * @private + */ + value: function setData(nodes) { + var _this3 = this; - 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'; + var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - 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); + var oldNodesData = this.body.data.nodes; - this.dom.centerContainer.appendChild(this.dom.center); - this.dom.leftContainer.appendChild(this.dom.left); - this.dom.rightContainer.appendChild(this.dom.right); + if (nodes instanceof DataSet || nodes instanceof DataView) { + this.body.data.nodes = nodes; + } else if (Array.isArray(nodes)) { + this.body.data.nodes = new DataSet(); + this.body.data.nodes.add(nodes); + } else if (!nodes) { + this.body.data.nodes = new DataSet(); + } else { + throw new TypeError('Array or DataSet expected'); + } - 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); + if (oldNodesData) { + // unsubscribe from old dataset + util.forEach(this.nodesListeners, function (callback, event) { + oldNodesData.off(event, callback); + }); + } - this.on('rangechange', this.redraw.bind(this)); - this.on('touch', this._onTouch.bind(this)); - this.on('pan', this._onDrag.bind(this)); + // remove drawn nodes + this.body.nodes = {}; - var me = this; - this.on('change', function (properties) { - if (properties && properties.queue == true) { - // redraw once on next tick - if (!me._redrawTimer) { - me._redrawTimer = setTimeout(function () { - me._redrawTimer = null; - me._redraw(); - }, 0); + if (this.body.data.nodes) { + (function () { + // subscribe to new dataset + var me = _this3; + util.forEach(_this3.nodesListeners, function (callback, event) { + me.body.data.nodes.on(event, callback); + }); + + // draw all new nodes + var ids = _this3.body.data.nodes.getIds(); + _this3.add(ids, true); + })(); + } + + if (doNotEmit === false) { + this.body.emitter.emit('_dataChanged'); } - } else { - // redraw immediately - me._redraw(); } - }); + }, { + key: 'add', - // create event listeners for all interesting events, these events will be - // emitted via emitter - this.hammer = new Hammer(this.dom.root); - this.hammer.get('pinch').set({ enable: true }); - this.listeners = {}; + /** + * Add nodes + * @param {Number[] | String[]} ids + * @private + */ + value: function add(ids) { + var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - 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); + var id = undefined; + var newNodes = []; + for (var i = 0; i < ids.length; i++) { + id = ids[i]; + var _properties = this.body.data.nodes.get(id); + var node = this.create(_properties); + newNodes.push(node); + this.body.nodes[id] = node; // note: this may replace an existing node } - }; - 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)); + this.layoutEngine.positionInitially(newNodes); - function onMouseWheel(event) { - if (me.isActive()) { - me.emit('mousewheel', event); + if (doNotEmit === false) { + this.body.emitter.emit('_dataChanged'); + } } - } - this.dom.root.addEventListener('mousewheel', onMouseWheel); - this.dom.root.addEventListener('DOMMouseScroll', onMouseWheel); + }, { + key: 'update', - // size properties of each of the panels - this.props = { - root: {}, - background: {}, - centerContainer: {}, - leftContainer: {}, - rightContainer: {}, - center: {}, - left: {}, - right: {}, - top: {}, - bottom: {}, - border: {}, - scrollTop: 0, - scrollTopMin: 0 - }; + /** + * Update existing nodes, or create them when not yet existing + * @param {Number[] | String[]} ids + * @private + */ + value: function update(ids, changedData) { + var nodes = this.body.nodes; + var dataChanged = false; + for (var i = 0; i < ids.length; i++) { + var id = ids[i]; + var node = nodes[id]; + var data = changedData[i]; + if (node !== undefined) { + // update node + dataChanged = node.setOptions(data); + } else { + dataChanged = true; + // create node + node = this.create(properties); + nodes[id] = node; + } + } - this.customTimes = []; + if (dataChanged === true) { + this.body.emitter.emit('_dataChanged'); + } else { + this.body.emitter.emit('_dataUpdated'); + } + } + }, { + key: 'remove', - // store state information needed for touch events - this.touch = {}; + /** + * Remove existing nodes. If nodes do not exist, the method will just ignore it. + * @param {Number[] | String[]} ids + * @private + */ + value: function remove(ids) { + var nodes = this.body.nodes; - this.redrawCount = 0; + for (var i = 0; i < ids.length; i++) { + var id = ids[i]; + delete nodes[id]; + } - // attach the root panel to the provided container - if (!container) throw new Error('No container provided'); - container.appendChild(this.dom.root); - }; + this.body.emitter.emit('_dataChanged'); + } + }, { + key: 'create', - /** - * 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']; - util.selectiveExtend(fields, this.options, options); + /** + * create a node + * @param properties + * @param constructorClass + */ + value: function create(properties) { + var constructorClass = arguments[1] === undefined ? _componentsNode2['default'] : arguments[1]; - if ('orientation' in options) { - if (typeof options.orientation === 'string') { - this.options.orientation = { - item: options.orientation, - axis: options.orientation - }; - } else if (typeof options.orientation === 'object') { - if ('item' in options.orientation) { - this.options.orientation.item = options.orientation.item; + return new constructorClass(properties, this.body, this.images, this.groups, this.options); + } + }, { + key: 'refresh', + value: function refresh() { + var nodes = this.body.nodes; + for (var nodeId in nodes) { + var node = undefined; + if (nodes.hasOwnProperty(nodeId)) { + node = nodes[nodeId]; } - if ('axis' in options.orientation) { - this.options.orientation.axis = options.orientation.axis; + var data = this.body.data.nodes._data[nodeId]; + if (node !== undefined && data !== undefined) { + node.setOptions({ fixed: false }); + node.setOptions(data); } } } + }, { + key: 'getPositions', - 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); + /** + * Returns the positions of the nodes. + * @param ids --> optional, can be array of nodeIds, can be string + * @returns {{}} + */ + value: function getPositions(ids) { + var dataArray = {}; + if (ids !== undefined) { + if (Array.isArray(ids) === true) { + for (var i = 0; i < ids.length; i++) { + if (this.body.nodes[ids[i]] !== undefined) { + var node = this.body.nodes[ids[i]]; + dataArray[ids[i]] = { x: Math.round(node.x), y: Math.round(node.y) }; + } + } + } else { + if (this.body.nodes[ids] !== undefined) { + var node = this.body.nodes[ids]; + dataArray[ids] = { x: Math.round(node.x), y: Math.round(node.y) }; + } + } + } else { + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + var node = this.body.nodes[nodeId]; + dataArray[nodeId] = { x: Math.round(node.x), y: Math.round(node.y) }; + } + } } - } else { - if (this.timeAxis2) { - var index = this.components.indexOf(this.timeAxis2); - if (index !== -1) { - this.components.splice(index, 1); + return dataArray; + } + }, { + key: 'storePositions', + + /** + * Load the XY positions of the nodes into the dataset. + */ + value: function storePositions() { + // todo: add support for clusters and hierarchical. + var dataArray = []; + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + var node = this.body.nodes[nodeId]; + if (this.body.data.nodes._data[nodeId].x != Math.round(node.x) || this.body.data.nodes._data[nodeId].y != Math.round(node.y)) { + dataArray.push({ id: nodeId, x: Math.round(node.x), y: Math.round(node.y) }); + } } - this.timeAxis2.destroy(); - this.timeAxis2 = null; } + this.body.data.nodes.update(dataArray); } + }, { + key: 'getBoundingBox', - if ('hiddenDates' in this.options) { - DateUtil.convertHiddenOptions(this.body, this.options.hiddenDates); + /** + * get the bounding box of a node. + * @param nodeId + * @returns {j|*} + */ + value: function getBoundingBox(nodeId) { + if (this.body.nodes[nodeId] !== undefined) { + return this.body.nodes[nodeId].shape.boundingBox; + } } + }, { + key: 'getConnectedNodes', - 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; + /** + * Get the Ids of nodes connected to this node. + * @param nodeId + * @returns {Array} + */ + value: function getConnectedNodes(nodeId) { + var nodeList = []; + if (this.body.nodes[nodeId] !== undefined) { + var node = this.body.nodes[nodeId]; + var nodeObj = {}; // used to quickly check if node already exists + for (var i = 0; i < node.edges.length; i++) { + var edge = node.edges[i]; + if (edge.toId == nodeId) { + // these are double equals since ids can be numeric or string + if (nodeObj[edge.fromId] === undefined) { + nodeList.push(edge.fromId); + nodeObj[edge.fromId] = true; + } + } else if (edge.fromId == nodeId) { + // these are double equals since ids can be numeric or string + if (nodeObj[edge.toId] === undefined) { + nodeList.push(edge.toId); + nodeObj[edge.toId] = true; + } + } } } + return nodeList; } + }, { + key: 'getConnectedEdges', - if ('showCustomTime' in options) { - throw new Error('Option `showCustomTime` is deprecated. Create a custom time bar via timeline.addCustomTime(time [, id])'); + /** + * Get the ids of the edges connected to this node. + * @param nodeId + * @returns {*} + */ + value: function getConnectedEdges(nodeId) { + var edgeList = []; + if (this.body.nodes[nodeId] !== undefined) { + var node = this.body.nodes[nodeId]; + for (var i = 0; i < node.edges.length; i++) { + edgeList.push(node.edges[i].id); + } + } else { + console.log('NodeId provided for getConnectedEdges does not exist. Provided: ', nodeId); + } + return edgeList; } + }]); - // enable/disable autoResize - this._initAutoResize(); - } + return NodesHandler; + })(); - // propagate options to all components - this.components.forEach(function (component) { - return component.setOptions(options); - }); + exports['default'] = NodesHandler; + module.exports = exports['default']; - // enable/disable configure - if (this.configurator) { - this.configurator.setOptions(options.configure); +/***/ }, +/* 56 */ +/***/ function(module, exports, __webpack_require__) { - // 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 }); - } + 'use strict'; - // redraw everything - this._redraw(); - }; + Object.defineProperty(exports, '__esModule', { + value: true + }); - /** - * Returns true when the Timeline is active. - * @returns {boolean} - */ - Core.prototype.isActive = function () { - return !this.activator || this.activator.active; - }; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /** - * Destroy the Core, clean up all DOM elements and event listeners. - */ - Core.prototype.destroy = function () { - // unbind datasets - this.setItems(null); - this.setGroups(null); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - // remove all event listeners - this.off(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - // stop checking for changed size - this._stopAutoResize(); + var _componentsEdge = __webpack_require__(76); - // remove from DOM - if (this.dom.root.parentNode) { - this.dom.root.parentNode.removeChild(this.dom.root); - } - this.dom = null; + var _componentsEdge2 = _interopRequireDefault(_componentsEdge); - // remove Activator - if (this.activator) { - this.activator.destroy(); - delete this.activator; - } + var _componentsSharedLabel = __webpack_require__(75); - // 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; + var _componentsSharedLabel2 = _interopRequireDefault(_componentsSharedLabel); - // give all components the opportunity to cleanup - this.components.forEach(function (component) { - return component.destroy(); - }); + var util = __webpack_require__(2); + var DataSet = __webpack_require__(4); + var DataView = __webpack_require__(5); - this.body = null; - }; + var EdgesHandler = (function () { + function EdgesHandler(body, images, groups) { + var _this = this; - /** - * 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; - }); + _classCallCheck(this, EdgesHandler); - if (customTimes.length === 0) { - throw new Error('No custom time bar found with id ' + JSON.stringify(id)); - } + this.body = body; + this.images = images; + this.groups = groups; - if (customTimes.length > 0) { - customTimes[0].setCustomTime(time); - } - }; + // create the edge API in the body container + this.body.functions.createEdge = this.create.bind(this); - /** - * 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; - }); + this.edgesListeners = { + add: function add(event, params) { + _this.add(params.items); + }, + update: function update(event, params) { + _this.update(params.items); + }, + remove: function remove(event, params) { + _this.remove(params.items); + } + }; - if (customTimes.length === 0) { - throw new Error('No custom time bar found with id ' + JSON.stringify(id)); - } - return customTimes[0].getCustomTime(); - }; + this.options = {}; + this.defaultOptions = { + arrows: { + to: { enabled: false, scaleFactor: 1 }, // boolean / {arrowScaleFactor:1} / {enabled: false, arrowScaleFactor:1} + middle: { enabled: false, scaleFactor: 1 }, + from: { enabled: false, scaleFactor: 1 } + }, + color: { + color: '#848484', + highlight: '#848484', + hover: '#848484', + inherit: 'from', + opacity: 1 + }, + dashes: false, + font: { + color: '#343434', + size: 14, // px + face: 'arial', + background: 'none', + strokeWidth: 2, // px + strokeColor: '#ffffff', + align: 'horizontal' + }, + hidden: false, + hoverWidth: 1.5, + label: undefined, + length: undefined, + physics: true, + scaling: { + min: 1, + max: 15, + label: { + enabled: true, + min: 14, + max: 30, + maxVisible: 30, + drawThreshold: 5 + }, + customScalingFunction: function customScalingFunction(min, max, total, value) { + if (max === min) { + return 0.5; + } else { + var scale = 1 / (max - min); + return Math.max(0, (value - min) * scale); + } + } + }, + selectionWidth: 1.5, + selfReferenceSize: 20, + shadow: { + enabled: false, + size: 10, + x: 5, + y: 5 + }, + smooth: { + enabled: true, + type: 'dynamic', + roundness: 0.5 + }, + title: undefined, + width: 1, + value: undefined + }; - /** - * 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(); + util.extend(this.options, this.defaultOptions); - var exists = this.customTimes.some(function (customTime) { - return customTime.options.id === id; - }); - if (exists) { - throw new Error('A custom time with id ' + JSON.stringify(id) + ' already exists'); + this.bindEventListeners(); } - var customTime = new CustomTime(this.body, { - time: timestamp, - id: id - }); + _createClass(EdgesHandler, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this2 = this; - this.customTimes.push(customTime); - this.components.push(customTime); - this.redraw(); + // this allows external modules to force all dynamic curves to turn static. + this.body.emitter.on('_forceDisableDynamicCurves', function (type) { + if (type === 'dynamic') { + type = 'continuous'; + } + var emitChange = false; + for (var edgeId in _this2.body.edges) { + if (_this2.body.edges.hasOwnProperty(edgeId)) { + var edge = _this2.body.edges[edgeId]; + var edgeData = _this2.body.data.edges._data[edgeId]; - return id; - }; + // only forcilby remove the smooth curve if the data has been set of the edge has the smooth curves defined. + // this is because a change in the global would not affect these curves. + if (edgeData !== undefined) { + var edgeOptions = edgeData.smooth; + if (edgeOptions !== undefined) { + if (edgeOptions.enabled === true && edgeOptions.type === 'dynamic') { + if (type === undefined) { + edge.setOptions({ smooth: false }); + } else { + edge.setOptions({ smooth: { type: type } }); + } + emitChange = true; + } + } + } + } + } + if (emitChange === true) { + _this2.body.emitter.emit('_dataChanged'); + } + }); - /** - * Remove previously added custom bar - * @param {int} id ID of the custom bar to be removed - * @return {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; - }); + // this is called when options of EXISTING nodes or edges have changed. + this.body.emitter.on('_dataUpdated', function () { + _this2.reconnectEdges(); + _this2.markAllEdgesAsDirty(); + }); - if (customTimes.length === 0) { - throw new Error('No custom time bar found with id ' + JSON.stringify(id)); - } + // refresh the edges. Used when reverting from hierarchical layout + this.body.emitter.on('refreshEdges', this.refresh.bind(this)); + this.body.emitter.on('refresh', this.refresh.bind(this)); + this.body.emitter.on('destroy', function () { + delete _this2.body.functions.createEdge; + delete _this2.edgesListeners.add; + delete _this2.edgesListeners.update; + delete _this2.edgesListeners.remove; + delete _this2.edgesListeners; + }); + } + }, { + key: 'setOptions', + value: function setOptions(options) { + if (options !== undefined) { + // use the parser from the Edge class to fill in all shorthand notations + _componentsEdge2['default'].parseOptions(this.options, options); - customTimes.forEach((function (customTime) { - this.customTimes.splice(this.customTimes.indexOf(customTime), 1); - this.components.splice(this.components.indexOf(customTime), 1); - customTime.destroy(); - }).bind(this)); - }; + // hanlde multiple input cases for color + if (options.color !== undefined) { + this.markAllEdgesAsDirty(); + } - /** - * 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() || []; - }; + // update smooth settings in all edges + var dataChanged = false; + if (options.smooth !== undefined) { + for (var edgeId in this.body.edges) { + if (this.body.edges.hasOwnProperty(edgeId)) { + dataChanged = this.body.edges[edgeId].updateEdgeType() || dataChanged; + } + } + } - /** - * 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'. - */ - Core.prototype.fit = function (options) { - var range = this._getDataRange(); + // update fonts in all edges + if (options.font !== undefined) { + // use the parser from the Label class to fill in all shorthand notations + _componentsSharedLabel2['default'].parseOptions(this.options, options); + for (var edgeId in this.body.edges) { + if (this.body.edges.hasOwnProperty(edgeId)) { + this.body.edges[edgeId].updateLabelModule(); + } + } + } - // skip range set if there is no start and end date - if (range.start === null && range.end === null) { - return; - } + // update the state of the variables if needed + if (options.hidden !== undefined || options.physics !== undefined || dataChanged === true) { + this.body.emitter.emit('_dataChanged'); + } + } + } + }, { + key: 'setData', - var animation = options && options.animation !== undefined ? options.animation : true; - this.range.setRange(range.start, range.end, animation); - }; + /** + * Load edges by reading the data table + * @param {Array | DataSet | DataView} edges The data containing the edges. + * @private + * @private + */ + value: function setData(edges) { + var _this3 = this; - /** - * Calculate the data range of the items and applies a 5% window around it. - * @returns {{start: Date | null, end: Date | null}} - * @protected - */ - Core.prototype._getDataRange = function () { - // apply the data range as range - var dataRange = this.getItemRange(); + var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - // add 5% space on both sides - var start = dataRange.min; - var end = dataRange.max; - if (start != null && end != null) { - var interval = end.valueOf() - start.valueOf(); - if (interval <= 0) { - // prevent an empty interval - interval = 24 * 60 * 60 * 1000; // 1 day - } - start = new Date(start.valueOf() - interval * 0.05); - end = new Date(end.valueOf() + interval * 0.05); - } + var oldEdgesData = this.body.data.edges; - return { - start: start, - end: end - }; - }; + if (edges instanceof DataSet || edges instanceof DataView) { + this.body.data.edges = edges; + } else if (Array.isArray(edges)) { + this.body.data.edges = new DataSet(); + this.body.data.edges.add(edges); + } else if (!edges) { + this.body.data.edges = new DataSet(); + } else { + throw new TypeError('Array or DataSet expected'); + } - /** - * 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'. - */ - Core.prototype.setWindow = function (start, end, options) { - var animation; - if (arguments.length == 1) { - var range = arguments[0]; - animation = range.animation !== undefined ? range.animation : true; - this.range.setRange(range.start, range.end, animation); - } else { - animation = options && options.animation !== undefined ? options.animation : true; - this.range.setRange(start, end, animation); - } - }; + // TODO: is this null or undefined or false? + if (oldEdgesData) { + // unsubscribe from old dataset + util.forEach(this.edgesListeners, function (callback, event) { + oldEdgesData.off(event, 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'. - */ - Core.prototype.moveTo = function (time, options) { - var interval = this.range.end - this.range.start; - var t = util.convert(time, 'Date').valueOf(); + // remove drawn edges + this.body.edges = {}; - var start = t - interval / 2; - var end = t + interval / 2; - var animation = options && options.animation !== undefined ? options.animation : true; + // TODO: is this null or undefined or false? + if (this.body.data.edges) { + // subscribe to new dataset + util.forEach(this.edgesListeners, function (callback, event) { + _this3.body.data.edges.on(event, callback); + }); - this.range.setRange(start, end, animation); - }; + // draw all new nodes + var ids = this.body.data.edges.getIds(); + this.add(ids, true); + } - /** - * 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) - }; - }; + if (doNotEmit === false) { + this.body.emitter.emit('_dataChanged'); + } + } + }, { + key: 'add', - /** - * Force a redraw. Can be overridden by implementations of Core - */ - Core.prototype.redraw = function () { - this._redraw(); - }; + /** + * Add edges + * @param {Number[] | String[]} ids + * @private + */ + value: function add(ids) { + var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - /** - * Redraw for internal use. Redraws all components. See also the public - * method redraw. - * @protected - */ - Core.prototype._redraw = function () { - var resized = false; - var options = this.options; - var props = this.props; - var dom = this.dom; + var edges = this.body.edges; + var edgesData = this.body.data.edges; - if (!dom) return; // when destroyed + for (var i = 0; i < ids.length; i++) { + var id = ids[i]; - DateUtil.updateHiddenDates(this.body, this.options.hiddenDates); + var oldEdge = edges[id]; + if (oldEdge) { + oldEdge.disconnect(); + } - // 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'); - } + var data = edgesData.get(id, { 'showInternalIds': true }); + edges[id] = this.create(data); + } - // 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, ''); + if (doNotEmit === false) { + this.body.emitter.emit('_dataChanged'); + } + } + }, { + key: 'update', - // 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; - var borderRootHeight = dom.root.offsetHeight - dom.root.clientHeight; - var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth; + /** + * Update existing edges, or create them when not yet existing + * @param {Number[] | String[]} ids + * @private + */ + value: function update(ids) { + var edges = this.body.edges; + var edgesData = this.body.data.edges; + var dataChanged = false; + for (var i = 0; i < ids.length; i++) { + var id = ids[i]; + var data = edgesData.get(id); + var edge = edges[id]; + if (edge === null) { + // update edge + edge.disconnect(); + dataChanged = edge.setOptions(data) || dataChanged; // if a support node is added, data can be changed. + edge.connect(); + } else { + // create edge + this.body.edges[id] = this.create(data); + dataChanged = true; + } + } - // 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) { - borderRootWidth = borderRootHeight; - } + if (dataChanged === true) { + this.body.emitter.emit('_dataChanged'); + } else { + this.body.emitter.emit('_dataUpdated'); + } + } + }, { + key: 'remove', - // 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; + /** + * Remove existing edges. Non existing ids will be ignored + * @param {Number[] | String[]} ids + * @private + */ + value: function remove(ids) { + var edges = this.body.edges; + for (var i = 0; i < ids.length; i++) { + var id = ids[i]; + var edge = edges[id]; + if (edge !== undefined) { + if (edge.via != null) { + delete this.body.supportNodes[edge.via.id]; + } + edge.disconnect(); + delete edges[id]; + } + } - // TODO: compensate borders when any of the panels is empty. + this.body.emitter.emit('_dataChanged'); + } + }, { + key: 'refresh', + value: function refresh() { + var edges = this.body.edges; + for (var edgeId in edges) { + var edge = undefined; + if (edges.hasOwnProperty(edgeId)) { + edge = edges[edgeId]; + } + var data = this.body.data.edges._data[edgeId]; + if (edge !== undefined && data !== undefined) { + edge.setOptions(data); + } + } + } + }, { + key: 'create', + value: function create(properties) { + return new _componentsEdge2['default'](properties, this.body, this.options); + } + }, { + key: 'markAllEdgesAsDirty', + value: function markAllEdgesAsDirty() { + for (var edgeId in this.body.edges) { + this.body.edges[edgeId].edgeType.colorDirty = true; + } + } + }, { + key: 'reconnectEdges', - // 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 + borderRootHeight + props.border.top + props.border.bottom; - dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px'); + /** + * Reconnect all edges + * @private + */ + value: function reconnectEdges() { + var id; + var nodes = this.body.nodes; + var edges = this.body.edges; - // calculate heights of the content panels - props.root.height = dom.root.offsetHeight; - props.background.height = props.root.height - borderRootHeight; - var containerHeight = props.root.height - props.top.height - props.bottom.height - borderRootHeight; - props.centerContainer.height = containerHeight; - props.leftContainer.height = containerHeight; - props.rightContainer.height = props.leftContainer.height; + for (id in nodes) { + if (nodes.hasOwnProperty(id)) { + nodes[id].edges = []; + } + } - // calculate the widths of the panels - props.root.width = dom.root.offsetWidth; - props.background.width = props.root.width - borderRootWidth; - props.left.width = dom.leftContainer.clientWidth || -props.border.left; - props.leftContainer.width = props.left.width; - props.right.width = dom.rightContainer.clientWidth || -props.border.right; - props.rightContainer.width = props.right.width; - var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth; - props.center.width = centerWidth; - props.centerContainer.width = centerWidth; - props.top.width = centerWidth; - props.bottom.width = centerWidth; + for (id in edges) { + if (edges.hasOwnProperty(id)) { + var edge = edges[id]; + edge.from = null; + edge.to = null; + edge.connect(); + } + } + } + }, { + key: 'getConnectedNodes', + value: function getConnectedNodes(edgeId) { + var nodeList = []; + if (this.body.edges[edgeId] !== undefined) { + var edge = this.body.edges[edgeId]; + if (edge.fromId) { + nodeList.push(edge.fromId); + } + if (edge.toId) { + nodeList.push(edge.toId); + } + } + return nodeList; + } + }]); - // 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'; + return EdgesHandler; + })(); - 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'; + exports['default'] = EdgesHandler; + module.exports = exports['default']; - // 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'; +/***/ }, +/* 57 */ +/***/ function(module, exports, __webpack_require__) { - // 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 - this._updateScrollTop(); + 'use strict'; - // reposition the scrollable contents - var offset = this.props.scrollTop; - if (options.orientation.item != 'top') { - offset += Math.max(this.props.centerContainer.height - this.props.center.height - this.props.border.top - this.props.border.bottom, 0); - } - dom.center.style.left = '0'; - dom.center.style.top = offset + 'px'; - dom.left.style.left = '0'; - dom.left.style.top = offset + 'px'; - dom.right.style.left = '0'; - dom.right.style.top = offset + 'px'; + var Item = __webpack_require__(21); + var util = __webpack_require__(2); - // show shadows when vertical scrolling is available - var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : ''; - var visibilityBottom = this.props.scrollTop == this.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; + /** + * @constructor BoxItem + * @extends Item + * @param {Object} data Object containing parameters start + * content, 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 BoxItem(data, conversion, options) { + this.props = { + dot: { + width: 0, + height: 0 + }, + line: { + width: 0, + height: 0 + } + }; - // redraw all components - this.components.forEach(function (component) { - resized = component.redraw() || resized; - }); - if (resized) { - // keep repainting until all sizes are settled - var MAX_REDRAWS = 3; // maximum number of consecutive redraws - if (this.redrawCount < MAX_REDRAWS) { - this.redrawCount++; - this._redraw(); - } else { - console.log('WARNING: infinite loop in redraw?'); + // validate data + if (data) { + if (data.start == undefined) { + throw new Error('Property "start" missing in item ' + data); } - this.redrawCount = 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.'); - }; + Item.call(this, data, conversion, options); + } + + BoxItem.prototype = new Item(null, null, null); /** - * 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. + * Check whether this item is visible inside given range + * @returns {{start: Number, end: Number}} range with a timestamp for start and end + * @returns {boolean} True if visible */ - Core.prototype.setCurrentTime = function (time) { - if (!this.currentTime) { - throw new Error('Option showCurrentTime must be true'); - } - - this.currentTime.setCurrentTime(time); + BoxItem.prototype.isVisible = function (range) { + // determine visibility + // TODO: account for the real width of the item. Right now we just add 1/4 to the window + var interval = (range.end - range.start) / 4; + return this.data.start > range.start - interval && this.data.start < range.end + interval; }; /** - * Get the current time. - * Only applicable when option `showCurrentTime` is true. - * @return {Date} Returns the current time. + * Repaint the item */ - Core.prototype.getCurrentTime = function () { - if (!this.currentTime) { - throw new Error('Option showCurrentTime must be true'); - } + BoxItem.prototype.redraw = function () { + var dom = this.dom; + if (!dom) { + // create DOM + this.dom = {}; + dom = this.dom; - return this.currentTime.getCurrentTime(); - }; + // create main box + dom.box = document.createElement('DIV'); - /** - * 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); - }; + // contents box (inside the background box). used for making margins + dom.content = document.createElement('DIV'); + dom.content.className = 'vis-item-content'; + dom.box.appendChild(dom.content); - /** - * 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); - }; + // line to axis + dom.line = document.createElement('DIV'); + dom.line.className = 'vis-line'; - /** - * 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); - }; + // dot on axis + dom.dot = document.createElement('DIV'); + dom.dot.className = 'vis-dot'; - /** - * 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; - }; + // attach this item as attribute + dom.box['timeline-item'] = this; - /** - * Initialize watching when option autoResize is true - * @private - */ - Core.prototype._initAutoResize = function () { - if (this.options.autoResize == true) { - this._startAutoResize(); - } else { - this._stopAutoResize(); + this.dirty = true; } - }; - - /** - * 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(); + // append DOM to parent DOM + if (!this.parent) { + throw new Error('Cannot redraw item: no parent attached'); + } + if (!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(dom.box); + } + if (!dom.line.parentNode) { + var background = this.parent.dom.background; + if (!background) throw new Error('Cannot redraw item: parent has no background container element'); + background.appendChild(dom.line); + } + if (!dom.dot.parentNode) { + var axis = this.parent.dom.axis; + if (!background) throw new Error('Cannot redraw item: parent has no axis container element'); + axis.appendChild(dom.dot); + } + this.displayed = true; - this._onResize = function () { - if (me.options.autoResize != true) { - // stop watching when the option autoResize is changed to false - me._stopAutoResize(); - return; - } + // Update DOM when item is marked dirty. 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._updateTitle(this.dom.box); + this._updateDataAttributes(this.dom.box); + this._updateStyle(this.dom.box); - 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; + // update class + var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); + dom.box.className = 'vis-item vis-box' + className; + dom.line.className = 'vis-item vis-line' + className; + dom.dot.className = 'vis-item vis-dot' + className; - me.emit('change'); - } - } - }; + // recalculate size + this.props.dot.height = dom.dot.offsetHeight; + this.props.dot.width = dom.dot.offsetWidth; + this.props.line.width = dom.line.offsetWidth; + this.width = dom.box.offsetWidth; + this.height = dom.box.offsetHeight; - // add event listener to window resize - util.addEventListener(window, 'resize', this._onResize); + this.dirty = false; + } - this.watchTimer = setInterval(this._onResize, 1000); + this._repaintDeleteButton(dom.box); }; /** - * Stop watching for a resize of the frame. - * @private + * Show the item in the DOM (when not already displayed). The items DOM will + * be created when needed. */ - Core.prototype._stopAutoResize = function () { - if (this.watchTimer) { - clearInterval(this.watchTimer); - this.watchTimer = undefined; + BoxItem.prototype.show = function () { + if (!this.displayed) { + this.redraw(); } - - // remove event listener on window.resize - util.removeEventListener(window, 'resize', this._onResize); - this._onResize = null; }; /** - * Start moving the timeline vertically - * @param {Event} event - * @private + * Hide the item from the DOM (when visible) */ - Core.prototype._onTouch = function (event) { - this.touch.allowDragging = true; - this.touch.initialScrollTop = this.props.scrollTop; - }; + BoxItem.prototype.hide = function () { + if (this.displayed) { + var dom = this.dom; - /** - * Start moving the timeline vertically - * @param {Event} event - * @private - */ - Core.prototype._onPinch = function (event) { - this.touch.allowDragging = false; + if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box); + if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line); + if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot); + + this.displayed = false; + } }; /** - * Move the timeline vertically - * @param {Event} event - * @private + * Reposition the item horizontally + * @Override */ - Core.prototype._onDrag = function (event) { - // 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; + BoxItem.prototype.repositionX = function () { + var start = this.conversion.toScreen(this.data.start); + var align = this.options.align; + var left; - var delta = event.deltaY; + // calculate left position of the box + if (align == 'right') { + this.left = start - this.width; + } else if (align == 'left') { + this.left = start; + } else { + // default or 'center' + this.left = start - this.width / 2; + } - var oldScrollTop = this._getScrollTop(); - var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta); + // reposition box + this.dom.box.style.left = this.left + 'px'; - if (newScrollTop != oldScrollTop) { - this._redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already - this.emit('verticalDrag'); - } - }; + // reposition line + this.dom.line.style.left = start - this.props.line.width / 2 + 'px'; - /** - * 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; + // reposition dot + this.dom.dot.style.left = start - this.props.dot.width / 2 + 'px'; }; /** - * Update the current scrollTop when the height of the containers has been changed - * @returns {Number} scrollTop Returns the applied scrollTop - * @private + * Reposition the item vertically + * @Override */ - 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; - } + BoxItem.prototype.repositionY = function () { + var orientation = this.options.orientation.item; + var box = this.dom.box; + var line = this.dom.line; + var dot = this.dom.dot; - // 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 (orientation == 'top') { + box.style.top = (this.top || 0) + 'px'; - return this.props.scrollTop; - }; + line.style.top = '0'; + line.style.height = this.parent.top + this.top + 1 + 'px'; + line.style.bottom = ''; + } else { + // orientation 'bottom' + var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty + var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top; + + box.style.top = (this.parent.height - this.top - this.height || 0) + 'px'; + line.style.top = itemSetHeight - lineHeight + 'px'; + line.style.bottom = '0'; + } - /** - * Get the current scrollTop - * @returns {number} scrollTop - * @private - */ - Core.prototype._getScrollTop = function () { - return this.props.scrollTop; + dot.style.top = -this.props.dot.height / 2 + 'px'; }; - module.exports = Core; + module.exports = BoxItem; /***/ }, -/* 41 */ +/* 58 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var util = __webpack_require__(2); - var stack = __webpack_require__(42); - var RangeItem = __webpack_require__(43); - - /** - * @constructor Group - * @param {Number | String} groupId - * @param {Object} data - * @param {ItemSet} itemSet - */ - function Group(groupId, data, itemSet) { - this.groupId = groupId; - this.subgroups = {}; - this.subgroupIndex = 0; - this.subgroupOrderer = data && data.subgroupOrder; - this.itemSet = itemSet; - - 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.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; - }); + Object.defineProperty(exports, '__esModule', { + value: true + }); - this._create(); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - this.setData(data); - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - /** - * Create DOM elements for the group - * @private - */ - Group.prototype._create = function () { - var label = document.createElement('div'); - label.className = 'vis-label'; - this.dom.label = label; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var inner = document.createElement('div'); - inner.className = 'vis-inner'; - label.appendChild(inner); - this.dom.inner = inner; + var _componentsNodesCluster = __webpack_require__(85); - var foreground = document.createElement('div'); - foreground.className = 'vis-group'; - foreground['timeline-group'] = this; - this.dom.foreground = foreground; + var _componentsNodesCluster2 = _interopRequireDefault(_componentsNodesCluster); - this.dom.background = document.createElement('div'); - this.dom.background.className = 'vis-group'; + var util = __webpack_require__(2); - this.dom.axis = document.createElement('div'); - this.dom.axis.className = 'vis-group'; + var ClusterEngine = (function () { + function ClusterEngine(body) { + var _this = this; - // 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.innerHTML = '?'; - this.dom.background.appendChild(this.dom.marker); - }; + _classCallCheck(this, ClusterEngine); - /** - * 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 = data && data.content; - if (content instanceof Element) { - this.dom.inner.appendChild(content); - } else if (content !== undefined && content !== null) { - this.dom.inner.innerHTML = content; - } else { - this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null - } + this.body = body; + this.clusteredNodes = {}; - // update title - this.dom.label.title = data && data.title || ''; + this.options = {}; + this.defaultOptions = {}; + util.extend(this.options, this.defaultOptions); - if (!this.dom.inner.firstChild) { - util.addClassName(this.dom.inner, 'vis-hidden'); - } else { - util.removeClassName(this.dom.inner, 'vis-hidden'); + this.body.emitter.on('_resetData', function () { + _this.clusteredNodes = {}; + }); } - // 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); + _createClass(ClusterEngine, [{ + key: 'setOptions', + value: function setOptions(options) { + if (options !== undefined) {} } - 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; - } + }, { + key: 'clusterByHubsize', - // update style - if (this.style) { - util.removeCssText(this.dom.label, 'vis-' + this.style); - this.style = null; - } - if (data && data.style) { - util.addCssText(this.dom.label, 'vis-' + data.style); - this.style = data.style; - } - }; + /** + * + * @param hubsize + * @param options + */ + value: function clusterByHubsize(hubsize, options) { + if (hubsize === undefined) { + hubsize = this._getHubSize(); + } else if (typeof hubsize === 'object') { + options = this._checkOptions(hubsize); + hubsize = this._getHubSize(); + } - /** - * Get the width of the group label - * @return {number} width - */ - Group.prototype.getLabelWidth = function () { - return this.props.label.width; - }; + var nodesToCluster = []; + for (var i = 0; i < this.body.nodeIndices.length; i++) { + var node = this.body.nodes[this.body.nodeIndices[i]]; + if (node.edges.length >= hubsize) { + nodesToCluster.push(node.id); + } + } - /** - * Repaint this group - * @param {{start: number, end: number}} range - * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin - * @param {boolean} [restack=false] Force restacking of all items - * @return {boolean} Returns true if the group is resized - */ - Group.prototype.redraw = function (range, margin, restack) { - var resized = false; + for (var i = 0; i < nodesToCluster.length; i++) { + this.clusterByConnection(nodesToCluster[i], options, false); + } + this.body.emitter.emit('_dataChanged'); + } + }, { + key: 'cluster', - // 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) - var markerHeight = this.dom.marker.clientHeight; - if (markerHeight != this.lastMarkerHeight) { - this.lastMarkerHeight = markerHeight; + /** + * loop over all nodes, check if they adhere to the condition and cluster if needed. + * @param options + * @param refreshData + */ + value: function cluster() { + var options = arguments[0] === undefined ? {} : arguments[0]; + var refreshData = arguments[1] === undefined ? true : arguments[1]; - util.forEach(this.items, function (item) { - item.dirty = true; - if (item.displayed) item.redraw(); - }); + if (options.joinCondition === undefined) { + throw new Error('Cannot call clusterByNodeData without a joinCondition function in the options.'); + } - restack = true; - } + // check if the options object is fine, append if needed + options = this._checkOptions(options); - // reposition visible items vertically - if (typeof this.itemSet.options.order === 'function') { - // a custom order function + var childNodesObj = {}; + var childEdgesObj = {}; - if (restack) { - // brute force restack of all items + // collect the nodes that will be in the cluster + for (var i = 0; i < this.body.nodeIndices.length; i++) { + var nodeId = this.body.nodeIndices[i]; + var node = this.body.nodes[nodeId]; + var clonedOptions = this._cloneOptions(node); + if (options.joinCondition(clonedOptions) === true) { + childNodesObj[nodeId] = this.body.nodes[nodeId]; - // show all items - var me = this; - var limitSize = false; - util.forEach(this.items, function (item) { - if (!item.displayed) { - item.redraw(); - me.visibleItems.push(item); + // collect the nodes that will be in the cluster + for (var _i = 0; _i < node.edges.length; _i++) { + var edge = node.edges[_i]; + childEdgesObj[edge.id] = edge; + } } - item.repositionX(limitSize); - }); + } - // 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._cluster(childNodesObj, childEdgesObj, options, refreshData); } + }, { + key: 'clusterOutliers', - this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); - } else { - // no custom order function, lazy stacking - this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); + /** + * Cluster all nodes in the network that have only 1 edge + * @param options + * @param refreshData + */ + value: function clusterOutliers(options) { + var refreshData = arguments[1] === undefined ? true : arguments[1]; - if (this.itemSet.options.stack) { - // TODO: ugly way to access options... - stack.stack(this.visibleItems, margin, restack); - } else { - // no stacking - stack.nostack(this.visibleItems, margin, this.subgroups); - } - } + options = this._checkOptions(options); + var clusters = []; - // recalculate the height of the group - var height = this._calculateHeight(margin); + // collect the nodes that will be in the cluster + for (var i = 0; i < this.body.nodeIndices.length; i++) { + var childNodesObj = {}; + var childEdgesObj = {}; + var nodeId = this.body.nodeIndices[i]; + var visibleEdges = 0; + var edge = undefined; + for (var j = 0; j < this.body.nodes[nodeId].edges.length; j++) { + if (this.body.nodes[nodeId].edges[j].options.hidden === false) { + visibleEdges++; + edge = this.body.nodes[nodeId].edges[j]; + } + } - // calculate actual size and position - var foreground = this.dom.foreground; - this.top = foreground.offsetTop; - this.left = foreground.offsetLeft; - this.width = foreground.offsetWidth; - resized = util.updateProperty(this, 'height', height) || resized; + if (visibleEdges === 1) { + // this is an outlier + var childNodeId = this._getConnectedId(edge, nodeId); + if (childNodeId !== nodeId) { + if (options.joinCondition === undefined) { + if (this._checkIfUsed(clusters, nodeId, edge.id) === false && this._checkIfUsed(clusters, childNodeId, edge.id) === false) { + childEdgesObj[edge.id] = edge; + childNodesObj[nodeId] = this.body.nodes[nodeId]; + childNodesObj[childNodeId] = this.body.nodes[childNodeId]; + } + } else { + var clonedOptions = this._cloneOptions(this.body.nodes[nodeId]); + if (options.joinCondition(clonedOptions) === true && this._checkIfUsed(clusters, nodeId, edge.id) === false) { + childEdgesObj[edge.id] = edge; + childNodesObj[nodeId] = this.body.nodes[nodeId]; + } + clonedOptions = this._cloneOptions(this.body.nodes[childNodeId]); + if (options.joinCondition(clonedOptions) === true && this._checkIfUsed(clusters, nodeId, edge.id) === false) { + childEdgesObj[edge.id] = edge; + childNodesObj[childNodeId] = this.body.nodes[childNodeId]; + } + } - // recalculate size of label - resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized; - resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized; + if (Object.keys(childNodesObj).length > 0 && Object.keys(childEdgesObj).length > 0) { + clusters.push({ nodes: childNodesObj, edges: childEdgesObj }); + } + } + } + } - // apply new height - this.dom.background.style.height = height + 'px'; - this.dom.foreground.style.height = height + 'px'; - this.dom.label.style.height = height + 'px'; + for (var i = 0; i < clusters.length; i++) { + this._cluster(clusters[i].nodes, clusters[i].edges, options, false); + } - // 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); - } + if (refreshData === true) { + this.body.emitter.emit('_dataChanged'); + } + } + }, { + key: '_checkIfUsed', + value: function _checkIfUsed(clusters, nodeId, edgeId) { + for (var i = 0; i < clusters.length; i++) { + var cluster = clusters[i]; + if (cluster.nodes[nodeId] !== undefined || cluster.edges[edgeId] !== undefined) { + return true; + } + } + return false; + } + }, { + key: 'clusterByConnection', - return resized; - }; + /** + * suck all connected nodes of a node into the node. + * @param nodeId + * @param options + * @param refreshData + */ + value: function clusterByConnection(nodeId, options) { + var refreshData = arguments[2] === undefined ? true : arguments[2]; - /** - * 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 visibleItems = this.visibleItems; - //var visibleSubgroups = []; - //this.visibleSubgroups = 0; - this.resetSubgroups(); - var me = this; - if (visibleItems.length > 0) { - var min = visibleItems[0].top; - var max = visibleItems[0].top + visibleItems[0].height; - util.forEach(visibleItems, function (item) { - min = Math.min(min, item.top); - max = Math.max(max, item.top + item.height); - if (item.data.subgroup !== undefined) { - me.subgroups[item.data.subgroup].height = Math.max(me.subgroups[item.data.subgroup].height, item.height); - me.subgroups[item.data.subgroup].visible = true; + // kill conditions + if (nodeId === undefined) { + throw new Error('No nodeId supplied to clusterByConnection!'); + } + if (this.body.nodes[nodeId] === undefined) { + throw new Error('The nodeId given to clusterByConnection does not exist!'); } - }); - 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(visibleItems, function (item) { - item.top -= offset; - }); - } - height = max + margin.item.vertical / 2; - } else { - height = 0; - } - height = Math.max(height, this.props.label.height); - return height; - }; + var node = this.body.nodes[nodeId]; + options = this._checkOptions(options, node); + if (options.clusterNodeProperties.x === undefined) { + options.clusterNodeProperties.x = node.x; + } + if (options.clusterNodeProperties.y === undefined) { + options.clusterNodeProperties.y = node.y; + } + if (options.clusterNodeProperties.fixed === undefined) { + options.clusterNodeProperties.fixed = {}; + options.clusterNodeProperties.fixed.x = node.options.fixed.x; + options.clusterNodeProperties.fixed.y = node.options.fixed.y; + } - /** - * Show this group: attach to the DOM - */ - Group.prototype.show = function () { - if (!this.dom.label.parentNode) { - this.itemSet.dom.labelSet.appendChild(this.dom.label); - } + var childNodesObj = {}; + var childEdgesObj = {}; + var parentNodeId = node.id; + var parentClonedOptions = this._cloneOptions(node); + childNodesObj[parentNodeId] = node; - if (!this.dom.foreground.parentNode) { - this.itemSet.dom.foreground.appendChild(this.dom.foreground); - } + // collect the nodes that will be in the cluster + for (var i = 0; i < node.edges.length; i++) { + var edge = node.edges[i]; + var childNodeId = this._getConnectedId(edge, parentNodeId); - if (!this.dom.background.parentNode) { - this.itemSet.dom.background.appendChild(this.dom.background); - } + if (childNodeId !== parentNodeId) { + if (options.joinCondition === undefined) { + childEdgesObj[edge.id] = edge; + childNodesObj[childNodeId] = this.body.nodes[childNodeId]; + } else { + // clone the options and insert some additional parameters that could be interesting. + var childClonedOptions = this._cloneOptions(this.body.nodes[childNodeId]); + if (options.joinCondition(parentClonedOptions, childClonedOptions) === true) { + childEdgesObj[edge.id] = edge; + childNodesObj[childNodeId] = this.body.nodes[childNodeId]; + } + } + } else { + childEdgesObj[edge.id] = edge; + } + } - if (!this.dom.axis.parentNode) { - this.itemSet.dom.axis.appendChild(this.dom.axis); - } - }; + this._cluster(childNodesObj, childEdgesObj, options, refreshData); + } + }, { + key: '_cloneOptions', - /** - * Hide this group: remove from the DOM - */ - Group.prototype.hide = function () { - var label = this.dom.label; - if (label.parentNode) { - label.parentNode.removeChild(label); - } + /** + * 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 objId + * @param type + * @returns {{}} + * @private + */ + 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; + } + }, { + key: '_createClusterEdges', - var foreground = this.dom.foreground; - if (foreground.parentNode) { - foreground.parentNode.removeChild(foreground); - } + /** + * This function creates the edges that will be attached to the cluster. + * + * @param childNodesObj + * @param childEdgesObj + * @param newEdges + * @param options + * @private + */ + value: function _createClusterEdges(childNodesObj, childEdgesObj, newEdges, clusterNodeProperties, clusterEdgeProperties) { + var edge = undefined, + childNodeId = undefined, + childNode = undefined, + toId = undefined, + fromId = undefined, + otherNodeId = undefined; - var background = this.dom.background; - if (background.parentNode) { - background.parentNode.removeChild(background); - } + var childKeys = Object.keys(childNodesObj); + for (var i = 0; i < childKeys.length; i++) { + childNodeId = childKeys[i]; + childNode = childNodesObj[childNodeId]; - var axis = this.dom.axis; - if (axis.parentNode) { - axis.parentNode.removeChild(axis); - } - }; + // construct new edges from the cluster to others + for (var j = 0; j < childNode.edges.length; j++) { + edge = childNode.edges[j]; + childEdgesObj[edge.id] = edge; - /** - * Add an item to the group - * @param {Item} item - */ - Group.prototype.add = function (item) { - this.items[item.id] = item; - item.setParent(this); + // childNodeId position will be replaced by the cluster. + if (edge.toId == childNodeId) { + // this is a double equals because ints and strings can be interchanged here. + toId = clusterNodeProperties.id; + fromId = edge.fromId; + otherNodeId = fromId; + } else { + toId = edge.toId; + fromId = clusterNodeProperties.id; + otherNodeId = toId; + } - // add to - if (item.data.subgroup !== undefined) { - if (this.subgroups[item.data.subgroup] === undefined) { - this.subgroups[item.data.subgroup] = { height: 0, visible: false, index: this.subgroupIndex, items: [] }; - this.subgroupIndex++; + // if the node connected to the cluster is also in the cluster we do not need a new edge. + if (childNodesObj[otherNodeId] === undefined) { + var clonedOptions = this._cloneOptions(edge, 'edge'); + util.deepExtend(clonedOptions, clusterEdgeProperties); + clonedOptions.from = fromId; + clonedOptions.to = toId; + clonedOptions.id = 'clusterEdge:' + util.randomUUID(); + newEdges.push(this.body.functions.createEdge(clonedOptions)); + } + } + } } - this.subgroups[item.data.subgroup].items.push(item); - } - this.orderSubgroups(); + }, { + key: '_checkOptions', - 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); - } - }; + /** + * This function checks the options that can be supplied to the different cluster functions + * for certain fields and inserts defaults if needed + * @param options + * @returns {*} + * @private + */ + value: function _checkOptions() { + var options = arguments[0] === undefined ? {} : arguments[0]; - Group.prototype.orderSubgroups = function () { - if (this.subgroupOrderer !== undefined) { - var sortArray = []; - if (typeof this.subgroupOrderer == 'string') { - for (var 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 (var subgroup in this.subgroups) { - sortArray.push(this.subgroups[subgroup].items[0].data); + if (options.clusterEdgeProperties === undefined) { + options.clusterEdgeProperties = {}; } - sortArray.sort(this.subgroupOrderer); - } - - if (sortArray.length > 0) { - for (var i = 0; i < sortArray.length; i++) { - this.subgroups[sortArray[i].subgroup].index = i; + if (options.clusterNodeProperties === undefined) { + options.clusterNodeProperties = {}; } - } - } - }; - Group.prototype.resetSubgroups = function () { - for (var subgroup in this.subgroups) { - if (this.subgroups.hasOwnProperty(subgroup)) { - this.subgroups[subgroup].visible = false; + return options; } - } - }; - - /** - * Remove an item from the group - * @param {Item} item - */ - Group.prototype.remove = function (item) { - delete this.items[item.id]; - item.setParent(null); + }, { + key: '_cluster', - // remove from visible items - var index = this.visibleItems.indexOf(item); - if (index != -1) this.visibleItems.splice(index, 1); + /** + * + * @param {Object} childNodesObj | object with node objects, id as keys, same as childNodes except it also contains a source node + * @param {Object} childEdgesObj | object with edge objects, id as keys + * @param {Array} options | object with {clusterNodeProperties, clusterEdgeProperties, processProperties} + * @param {Boolean} refreshData | when true, do not wrap up + * @private + */ + value: function _cluster(childNodesObj, childEdgesObj, options) { + var refreshData = arguments[3] === undefined ? true : arguments[3]; - // TODO: also remove from ordered items? - }; + // kill condition: no children so cant cluster + if (Object.keys(childNodesObj).length === 0) { + return; + } - /** - * Remove an item from the corresponding DataSet - * @param {Item} item - */ - Group.prototype.removeFromDataSet = function (item) { - this.itemSet.removeItem(item.id); - }; + var clusterNodeProperties = util.deepExtend({}, options.clusterNodeProperties); - /** - * Reorder the items - */ - Group.prototype.order = function () { - var array = util.toArray(this.items); - var startArray = []; - var endArray = []; + // construct the clusterNodeProperties + if (options.processProperties !== undefined) { + // get the childNode options + var childNodesOptions = []; + for (var nodeId in childNodesObj) { + var clonedOptions = this._cloneOptions(childNodesObj[nodeId]); + childNodesOptions.push(clonedOptions); + } - 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 - }; + // get clusterproperties based on childNodes + var childEdgesOptions = []; + for (var edgeId in childEdgesObj) { + var clonedOptions = this._cloneOptions(childEdgesObj[edgeId], 'edge'); + childEdgesOptions.push(clonedOptions); + } - stack.orderByStart(this.orderedItems.byStart); - stack.orderByEnd(this.orderedItems.byEnd); - }; + clusterNodeProperties = options.processProperties(clusterNodeProperties, childNodesOptions, childEdgesOptions); + if (!clusterNodeProperties) { + throw new Error('The processProperties function does not return properties!'); + } + } - /** - * Update the visible items - * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date - * @param {Item[]} visibleItems The previously visible items. - * @param {{start: number, end: number}} range Visible range - * @return {Item[]} visibleItems The new visible items. - * @private - */ - Group.prototype._updateVisibleItems = 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; - var item, i; + // check if we have an unique id; + if (clusterNodeProperties.id === undefined) { + clusterNodeProperties.id = 'cluster:' + util.randomUUID(); + } + var clusterId = clusterNodeProperties.id; - // 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; - } - }; + if (clusterNodeProperties.label === undefined) { + clusterNodeProperties.label = 'cluster'; + } - // 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 (i = 0; i < oldVisibleItems.length; i++) { - this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range); - } - } + // give the clusterNode a postion if it does not have one. + var pos = undefined; + if (clusterNodeProperties.x === undefined) { + pos = this._getClusterPosition(childNodesObj); + clusterNodeProperties.x = pos.x; + } + if (clusterNodeProperties.y === undefined) { + if (pos === undefined) { + pos = this._getClusterPosition(childNodesObj); + } + clusterNodeProperties.y = pos.y; + } - // we do a binary search for the items that have only start values. - var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data', 'start'); + // force the ID to remain the same + clusterNodeProperties.id = clusterId; - // 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; - }); + // create the clusterNode + var clusterNode = this.body.functions.createNode(clusterNodeProperties, _componentsNodesCluster2['default']); + clusterNode.isCluster = true; + clusterNode.containedNodes = childNodesObj; + clusterNode.containedEdges = childEdgesObj; + // cache a copy from the cluster edge properties if we have to reconnect others later on + clusterNode.clusterEdgeProperties = options.clusterEdgeProperties; - // 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'); + // finally put the cluster node into global + this.body.nodes[clusterNodeProperties.id] = clusterNode; - // 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; - }); - } + // create the new edges that will connect to the cluster + var newEdges = []; + this._createClusterEdges(childNodesObj, childEdgesObj, newEdges, clusterNodeProperties, options.clusterEdgeProperties); - // finally, we reposition all the visible items. - for (i = 0; i < visibleItems.length; i++) { - item = visibleItems[i]; - if (!item.displayed) item.show(); - // reposition item horizontally - item.repositionX(); - } + // disable the childEdges + for (var edgeId in childEdgesObj) { + if (childEdgesObj.hasOwnProperty(edgeId)) { + if (this.body.edges[edgeId] !== undefined) { + var edge = this.body.edges[edgeId]; + edge.togglePhysics(false); + edge.options.hidden = true; + } + } + } - // debug - //console.log("new line") - //if (this.groupId == null) { - // for (i = 0; i < orderedItems.byStart.length; i++) { - // item = orderedItems.byStart[i].data; - // console.log('start',i,initialPosByStart, item.start.valueOf(), item.content, item.start >= lowerBound && item.start <= upperBound,i == initialPosByStart ? "<------------------- HEREEEE" : "") - // } - // for (i = 0; i < orderedItems.byEnd.length; i++) { - // item = orderedItems.byEnd[i].data; - // console.log('rangeEnd',i,initialPosByEnd, item.end.valueOf(), item.content, item.end >= range.start && item.end <= range.end,i == initialPosByEnd ? "<------------------- HEREEEE" : "") - // } - //} + // disable the childNodes + for (var nodeId in childNodesObj) { + if (childNodesObj.hasOwnProperty(nodeId)) { + this.clusteredNodes[nodeId] = { clusterId: clusterNodeProperties.id, node: this.body.nodes[nodeId] }; + this.body.nodes[nodeId].togglePhysics(false); + this.body.nodes[nodeId].options.hidden = true; + } + } - return visibleItems; - }; + // push new edges to global + for (var i = 0; i < newEdges.length; i++) { + this.body.edges[newEdges[i].id] = newEdges[i]; + this.body.edges[newEdges[i].id].connect(); + } - Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) { - var item; - var i; + // set ID to undefined so no duplicates arise + clusterNodeProperties.id = undefined; - if (initialPos != -1) { - 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); - } + // wrap up + if (refreshData === true) { + this.body.emitter.emit('_dataChanged'); } } + }, { + key: 'isCluster', - for (i = initialPos + 1; i < items.length; i++) { - item = items[i]; - if (breakCondition(item)) { - break; + /** + * Check if a node is a cluster. + * @param nodeId + * @returns {*} + */ + value: function isCluster(nodeId) { + if (this.body.nodes[nodeId] !== undefined) { + return this.body.nodes[nodeId].isCluster === true; } else { - if (visibleItemsLookup[item.id] === undefined) { - visibleItemsLookup[item.id] = true; - visibleItems.push(item); - } + console.log('Node does not exist.'); + return false; } } - } - }; + }, { + key: '_getClusterPosition', - /** - * 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(); - } - }; + /** + * get the position of the cluster node based on what's inside + * @param {object} childNodesObj | object with node objects, id as keys + * @returns {{x: number, y: number}} + * @private + */ + value: function _getClusterPosition(childNodesObj) { + var childKeys = Object.keys(childNodesObj); + var minX = childNodesObj[childKeys[0]].x; + var maxX = childNodesObj[childKeys[0]].x; + var minY = childNodesObj[childKeys[0]].y; + var maxY = childNodesObj[childKeys[0]].y; + var node = undefined; + for (var i = 1; i < childKeys.length; i++) { + node = childNodesObj[childKeys[i]]; + minX = node.x < minX ? node.x : minX; + maxX = node.x > maxX ? node.x : maxX; + minY = node.y < minY ? node.y : minY; + maxY = node.y > maxY ? node.y : maxY; + } - /** - * 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._checkIfVisibleWithReference = function (item, visibleItems, visibleItemsLookup, range) { - if (item.isVisible(range)) { - if (visibleItemsLookup[item.id] === undefined) { - visibleItemsLookup[item.id] = true; - visibleItems.push(item); + return { x: 0.5 * (minX + maxX), y: 0.5 * (minY + maxY) }; } - } else { - if (item.displayed) item.hide(); - } - }; - - module.exports = Group; - -/***/ }, -/* 42 */ -/***/ function(module, exports, __webpack_require__) { - - // Utility functions for ordering and stacking of items - 'use strict'; - - var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors - - /** - * Order items by their start data - * @param {Item[]} items - */ - exports.orderByStart = function (items) { - items.sort(function (a, b) { - return a.data.start - b.data.start; - }); - }; + }, { + key: 'openCluster', - /** - * Order items by their end date. If they have no end date, their start date - * is used. - * @param {Item[]} items - */ - exports.orderByEnd = function (items) { - items.sort(function (a, b) { - var aTime = 'end' in a.data ? a.data.end : a.data.start, - bTime = 'end' in b.data ? b.data.end : b.data.start; + /** + * Open a cluster by calling this function. + * @param {String} clusterNodeId | the ID of the cluster node + * @param {Boolean} refreshData | wrap up afterwards if not true + */ + value: function openCluster(clusterNodeId) { + var refreshData = arguments[1] === undefined ? true : arguments[1]; - return aTime - bTime; - }); - }; + // kill conditions + if (clusterNodeId === undefined) { + throw new Error('No clusterNodeId supplied to openCluster.'); + } + if (this.body.nodes[clusterNodeId] === undefined) { + throw new Error('The clusterNodeId supplied to openCluster does not exist.'); + } + if (this.body.nodes[clusterNodeId].containedNodes === undefined) { + console.log('The node:' + clusterNodeId + ' is not a cluster.'); + return; + } + var clusterNode = this.body.nodes[clusterNodeId]; + var containedNodes = clusterNode.containedNodes; + var containedEdges = clusterNode.containedEdges; - /** - * Adjust vertical positions of the items such that they don't overlap each - * other. - * @param {Item[]} items - * All visible items - * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin - * Margins between items and between items and the axis. - * @param {boolean} [force=false] - * If true, all items will be repositioned. If false (default), only - * items having a top===null will be re-stacked - */ - exports.stack = function (items, margin, force) { - var i, iMax; + // release nodes + for (var nodeId in containedNodes) { + if (containedNodes.hasOwnProperty(nodeId)) { + var containedNode = this.body.nodes[nodeId]; + containedNode = containedNodes[nodeId]; + // inherit position + containedNode.x = clusterNode.x; + containedNode.y = clusterNode.y; - if (force) { - // reset top position of all items - for (i = 0, iMax = items.length; i < iMax; i++) { - items[i].top = null; - } - } + // inherit speed + containedNode.vx = clusterNode.vx; + containedNode.vy = clusterNode.vy; - // calculate new, non-overlapping positions - for (i = 0, iMax = items.length; i < iMax; i++) { - var item = items[i]; - if (item.stack && item.top === null) { - // initialize top position - item.top = margin.axis; + containedNode.options.hidden = false; + containedNode.togglePhysics(true); - do { - // TODO: optimize checking for overlap. when there is a gap without items, - // you only need to check for items from the next item on, not from zero - var collidingItem = null; - for (var j = 0, jj = items.length; j < jj; j++) { - var other = items[j]; - if (other.top !== null && other !== item && other.stack && exports.collision(item, other, margin.item)) { - collidingItem = other; - break; - } + delete this.clusteredNodes[nodeId]; } + } - if (collidingItem != null) { - // There is a collision. Reposition the items above the colliding element - item.top = collidingItem.top + collidingItem.height + margin.item.vertical; - } - } while (collidingItem); - } - } - }; + // release edges + for (var edgeId in containedEdges) { + if (containedEdges.hasOwnProperty(edgeId)) { + var edge = containedEdges[edgeId]; + // if this edge was a temporary edge and it's connected nodes do not exist anymore, we remove it from the data + if (this.body.nodes[edge.fromId] === undefined || this.body.nodes[edge.toId] === undefined) { + edge.edgeType.cleanup(); + // this removes the edge from node.edges, which is why edgeIds is formed + edge.disconnect(); + delete this.body.edges[edgeId]; + } else { + // one of the nodes connected to this edge is in a cluster. We give the edge to that cluster so it will be released when that cluster is opened. + if (this.clusteredNodes[edge.fromId] !== undefined || this.clusteredNodes[edge.toId] !== undefined) { + var fromId = undefined, + toId = undefined; + var clusteredNode = this.clusteredNodes[edge.fromId] || this.clusteredNodes[edge.toId]; + var clusterId = clusteredNode.clusterId; + var _clusterNode = this.body.nodes[clusterId]; + _clusterNode.containedEdges[edgeId] = edge; - /** - * Adjust vertical positions of the items without stacking them - * @param {Item[]} items - * All visible items - * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin - * Margins between items and between items and the axis. - */ - exports.nostack = function (items, margin, subgroups) { - var i, iMax, newTop; + if (this.clusteredNodes[edge.fromId] !== undefined) { + fromId = clusterId; + toId = edge.toId; + } else { + fromId = edge.fromId; + toId = clusterId; + } - // reset top position of all items - for (i = 0, iMax = items.length; i < iMax; i++) { - if (items[i].data.subgroup !== undefined) { - newTop = margin.axis; - for (var subgroup in subgroups) { - if (subgroups.hasOwnProperty(subgroup)) { - if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroups[items[i].data.subgroup].index) { - newTop += subgroups[subgroup].height + margin.item.vertical; + // if both from and to nodes are visible, we create a new temporary edge + if (this.body.nodes[fromId].options.hidden !== true && this.body.nodes[toId].options.hidden !== true) { + var clonedOptions = this._cloneOptions(edge, 'edge'); + var id = 'clusterEdge:' + util.randomUUID(); + util.deepExtend(clonedOptions, _clusterNode.clusterEdgeProperties); + util.deepExtend(clonedOptions, { from: fromId, to: toId, hidden: false, physics: true, id: id }); + var newEdge = this.body.functions.createEdge(clonedOptions); + + this.body.edges[id] = newEdge; + this.body.edges[id].connect(); + } + } else { + edge.options.hidden = false; + edge.togglePhysics(true); + } } } } - items[i].top = newTop; - } else { - items[i].top = margin.axis; - } - } - }; - - /** - * Test if the two provided items collide - * The items must have parameters left, width, top, and height. - * @param {Item} a The first item - * @param {Item} b The second item - * @param {{horizontal: number, vertical: number}} margin - * An object containing a horizontal and vertical - * minimum required margin. - * @return {boolean} true if a and b collide, else false - */ - exports.collision = function (a, b, margin) { - return a.left - margin.horizontal + EPSILON < b.left + b.width && a.left + a.width + margin.horizontal - EPSILON > b.left && a.top - margin.vertical + EPSILON < b.top + b.height && a.top + a.height + margin.vertical - EPSILON > b.top; - }; - -/***/ }, -/* 43 */ -/***/ function(module, exports, __webpack_require__) { - 'use strict'; + // remove all temporary edges + for (var i = 0; i < clusterNode.edges.length; i++) { + var edgeId = clusterNode.edges[i].id; + this.body.edges[edgeId].edgeType.cleanup(); + // this removes the edge from node.edges, which is why edgeIds is formed + this.body.edges[edgeId].disconnect(); + delete this.body.edges[edgeId]; + } - var Hammer = __webpack_require__(13); - var Item = __webpack_require__(11); + // remove clusterNode + delete this.body.nodes[clusterNodeId]; - /** - * @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 + if (refreshData === true) { + this.body.emitter.emit('_dataChanged'); + } } - }; - this.overflow = false; // if contents can overflow (css styling), this flag is set to true + }, { + key: 'getNodesInCluster', + value: function getNodesInCluster(clusterId) { + var nodesArray = []; + if (this.isCluster(clusterId) === true) { + var containedNodes = this.body.nodes[clusterId].containedNodes; + for (var nodeId in containedNodes) { + if (containedNodes.hasOwnProperty(nodeId)) { + nodesArray.push(nodeId); + } + } + } - // 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); + return nodesArray; } - } - - Item.call(this, data, conversion, options); - } - - RangeItem.prototype = new Item(null, null, null); + }, { + key: 'findNode', - RangeItem.prototype.baseClassName = 'vis-item vis-range'; + /** + * Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node + * @param nodeId + * @returns {Array} + * @private + */ + value: function findNode(nodeId) { + var stack = []; + var max = 100; + var counter = 0; - /** - * Check whether this item is visible inside given range - * @returns {{start: Number, end: Number}} 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; - }; + while (this.clusteredNodes[nodeId] !== undefined && counter < max) { + stack.push(this.clusteredNodes[nodeId].node); + nodeId = this.clusteredNodes[nodeId].clusterId; + counter++; + } + stack.push(this.body.nodes[nodeId]); + return stack; + } + }, { + key: '_getConnectedId', - /** - * Repaint the item - */ - RangeItem.prototype.redraw = function () { - var dom = this.dom; - if (!dom) { - // create DOM - this.dom = {}; - dom = this.dom; + /** + * Get the Id the node is connected to + * @param edge + * @param nodeId + * @returns {*} + * @private + */ + value: function _getConnectedId(edge, nodeId) { + if (edge.toId != nodeId) { + return edge.toId; + } else if (edge.fromId != nodeId) { + return edge.fromId; + } else { + return edge.fromId; + } + } + }, { + key: '_getHubSize', - // background box - dom.box = document.createElement('div'); - // className is updated in redraw() + /** + * We determine how many connections denote an important hub. + * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%) + * + * @private + */ + value: function _getHubSize() { + var average = 0; + var averageSquared = 0; + var hubCounter = 0; + var largestHub = 0; - // frame box (to prevent the item contents from overflowing - dom.frame = document.createElement('div'); - dom.frame.className = 'vis-item-overflow'; - dom.box.appendChild(dom.frame); + for (var i = 0; i < this.body.nodeIndices.length; i++) { + var node = this.body.nodes[this.body.nodeIndices[i]]; + if (node.edges.length > largestHub) { + largestHub = node.edges.length; + } + average += node.edges.length; + averageSquared += Math.pow(node.edges.length, 2); + hubCounter += 1; + } + average = average / hubCounter; + averageSquared = averageSquared / hubCounter; - // contents box - dom.content = document.createElement('div'); - dom.content.className = 'vis-item-content'; - dom.frame.appendChild(dom.content); + var letiance = averageSquared - Math.pow(average, 2); + var standardDeviation = Math.sqrt(letiance); - // attach this item as attribute - dom.box['timeline-item'] = this; + var hubThreshold = Math.floor(average + 2 * standardDeviation); - this.dirty = true; - } + // always have at least one to cluster + if (hubThreshold > largestHub) { + hubThreshold = largestHub; + } - // append DOM to parent DOM - if (!this.parent) { - throw new Error('Cannot redraw item: no parent attached'); - } - if (!dom.box.parentNode) { - var foreground = this.parent.dom.foreground; - if (!foreground) { - throw new Error('Cannot redraw item: parent has no foreground container element'); + return hubThreshold; } - foreground.appendChild(dom.box); - } - this.displayed = true; + }]); - // Update DOM when item is marked dirty. 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._updateTitle(this.dom.box); - this._updateDataAttributes(this.dom.box); - this._updateStyle(this.dom.box); + return ClusterEngine; + })(); - // update class - var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); - dom.box.className = this.baseClassName + className; + exports['default'] = ClusterEngine; + module.exports = exports['default']; - // determine from css whether this box has overflow - this.overflow = window.getComputedStyle(dom.frame).overflow !== 'hidden'; +/***/ }, +/* 59 */ +/***/ function(module, exports, __webpack_require__) { - // recalculate size - // 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'; - this.props.content.width = this.dom.content.offsetWidth; - this.height = this.dom.box.offsetHeight; - this.dom.content.style.maxWidth = ''; + 'use strict'; - this.dirty = false; - } + Object.defineProperty(exports, '__esModule', { + value: true + }); - this._repaintDeleteButton(dom.box); - this._repaintDragLeft(); - this._repaintDragRight(); - }; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /** - * 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(); - } - }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - /** - * Hide the item from the DOM (when visible) - * @return {Boolean} changed - */ - RangeItem.prototype.hide = function () { - if (this.displayed) { - var box = this.dom.box; + if (typeof window !== 'undefined') { + window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; + } - if (box.parentNode) { - box.parentNode.removeChild(box); - } + var util = __webpack_require__(2); - this.displayed = false; - } - }; + var CanvasRenderer = (function () { + function CanvasRenderer(body, canvas) { + _classCallCheck(this, CanvasRenderer); - /** - * 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 contentLeft; - var contentWidth; + this.body = body; + this.canvas = canvas; - // limit the width of the range, as browsers cannot draw very wide divs - if (limitSize === undefined || limitSize === true) { - if (start < -parentWidth) { - start = -parentWidth; - } - if (end > 2 * parentWidth) { - end = 2 * parentWidth; - } - } - var boxWidth = Math.max(end - start, 1); + this.redrawRequested = false; + this.renderTimer = undefined; + this.requiresTimeout = true; + this.renderingActive = false; + this.renderRequests = 0; + this.pixelRatio = undefined; + this.allowRedrawRequests = true; - if (this.overflow) { - this.left = start; - this.width = boxWidth + this.props.content.width; - contentWidth = this.props.content.width; + this.dragging = false; + this.options = {}; + this.defaultOptions = { + hideEdgesOnDrag: false, + hideNodesOnDrag: false + }; + util.extend(this.options, this.defaultOptions); - // 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 { - this.left = start; - this.width = boxWidth; - contentWidth = Math.min(end - start, this.props.content.width); + this._determineBrowserMethod(); + this.bindEventListeners(); } - this.dom.box.style.left = this.left + 'px'; - this.dom.box.style.width = boxWidth + 'px'; - - switch (this.options.align) { - case 'left': - this.dom.content.style.left = '0'; - break; - - case 'right': - this.dom.content.style.left = Math.max(boxWidth - contentWidth, 0) + 'px'; - break; - - case 'center': - this.dom.content.style.left = Math.max((boxWidth - contentWidth) / 2, 0) + 'px'; - break; + _createClass(CanvasRenderer, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this = this; - 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) { - contentLeft = Math.max(-start, 0); - } else { - contentLeft = -contentWidth; // ensure it's not visible anymore + this.body.emitter.on('dragStart', function () { + _this.dragging = true; + }); + this.body.emitter.on('dragEnd', function () { + return _this.dragging = false; + }); + this.body.emitter.on('_resizeNodes', function () { + return _this._resizeNodes(); + }); + this.body.emitter.on('_redraw', function () { + if (_this.renderingActive === false) { + _this._redraw(); } - } else { - if (start < 0) { - contentLeft = -start; + }); + this.body.emitter.on('_blockRedrawRequests', function () { + _this.allowRedrawRequests = false; + }); + this.body.emitter.on('_allowRedrawRequests', function () { + _this.allowRedrawRequests = true; + }); + this.body.emitter.on('_requestRedraw', this._requestRedraw.bind(this)); + this.body.emitter.on('_startRendering', function () { + _this.renderRequests += 1; + _this.renderingActive = true; + _this._startRendering(); + }); + this.body.emitter.on('_stopRendering', function () { + _this.renderRequests -= 1; + _this.renderingActive = _this.renderRequests > 0; + _this.renderTimer = undefined; + }); + this.body.emitter.on('destroy', function () { + _this.renderRequests = 0; + _this.renderingActive = false; + if (_this.requiresTimeout === true) { + clearTimeout(_this.renderTimer); } else { - contentLeft = 0; + cancelAnimationFrame(_this.renderTimer); } + _this.body.emitter.off(); + }); + } + }, { + key: 'setOptions', + value: function setOptions(options) { + if (options !== undefined) { + var fields = ['hideEdgesOnDrag', 'hideNodesOnDrag']; + util.selectiveDeepExtend(fields, this.options, options); } - this.dom.content.style.left = contentLeft + 'px'; - } - }; - - /** - * Reposition the item vertically - * @Override - */ - RangeItem.prototype.repositionY = function () { - var orientation = this.options.orientation.item; - var box = this.dom.box; + } + }, { + key: '_startRendering', + value: function _startRendering() { + if (this.renderingActive === true) { + if (this.renderTimer === undefined) { + if (this.requiresTimeout === true) { + this.renderTimer = window.setTimeout(this._renderStep.bind(this), this.simulationInterval); // wait this.renderTimeStep milliseconds and perform the animation step function + } else { + this.renderTimer = window.requestAnimationFrame(this._renderStep.bind(this)); // wait this.renderTimeStep milliseconds and perform the animation step function + } + } + } + } + }, { + key: '_renderStep', + value: function _renderStep() { + if (this.renderingActive === true) { + // reset the renderTimer so a new scheduled animation step can be set + this.renderTimer = undefined; - if (orientation == 'top') { - box.style.top = this.top + 'px'; - } else { - box.style.top = this.parent.height - this.top - this.height + 'px'; - } - }; + if (this.requiresTimeout === true) { + // this schedules a new simulation step + this._startRendering(); + } - /** - * 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.editable.updateTime && !this.dom.dragLeft) { - // create and show drag area - var dragLeft = document.createElement('div'); - dragLeft.className = 'vis-drag-left'; - dragLeft.dragLeftItem = this; + this._redraw(); - this.dom.box.appendChild(dragLeft); - this.dom.dragLeft = dragLeft; - } else if (!this.selected && this.dom.dragLeft) { - // delete drag area - if (this.dom.dragLeft.parentNode) { - this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft); + if (this.requiresTimeout === false) { + // this schedules a new simulation step + this._startRendering(); + } + } } - this.dom.dragLeft = null; - } - }; + }, { + key: 'redraw', - /** - * 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.editable.updateTime && !this.dom.dragRight) { - // create and show drag area - var dragRight = document.createElement('div'); - dragRight.className = 'vis-drag-right'; - dragRight.dragRightItem = this; + /** + * Redraw the network with the current data + * chart will be resized too. + */ + value: function redraw() { + this.body.emitter.emit('setSize'); + this._redraw(); + } + }, { + key: '_requestRedraw', - this.dom.box.appendChild(dragRight); - this.dom.dragRight = dragRight; - } else if (!this.selected && this.dom.dragRight) { - // delete drag area - if (this.dom.dragRight.parentNode) { - this.dom.dragRight.parentNode.removeChild(this.dom.dragRight); + /** + * Redraw the network with the current data + * @param hidden | used to get the first estimate of the node sizes. only the nodes are drawn after which they are quickly drawn over. + * @private + */ + value: function _requestRedraw() { + if (this.redrawRequested !== true && this.renderingActive === false && this.allowRedrawRequests === true) { + this.redrawRequested = true; + if (this.requiresTimeout === true) { + window.setTimeout(this._redraw.bind(this, false), 0); + } else { + window.requestAnimationFrame(this._redraw.bind(this, false)); + } + } } - this.dom.dragRight = null; - } - }; + }, { + key: '_redraw', + value: function _redraw() { + var hidden = arguments[0] === undefined ? false : arguments[0]; - module.exports = RangeItem; + this.body.emitter.emit('initRedraw'); -/***/ }, -/* 44 */ -/***/ function(module, exports, __webpack_require__) { + this.redrawRequested = false; + var ctx = this.canvas.frame.canvas.getContext('2d'); - 'use strict'; + // when the container div was hidden, this fixes it back up! + if (this.canvas.frame.canvas.width === 0 || this.canvas.frame.canvas.height === 0) { + this.canvas.setSize(); + } - var moment = __webpack_require__(17); - var DateUtil = __webpack_require__(39); - var util = __webpack_require__(2); + if (this.pixelRatio === undefined) { + this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + } - /** - * @constructor TimeStep - * 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 - */ - function TimeStep(start, end, minimumStep, hiddenDates) { - // variables - this.current = new Date(); - this._start = new Date(); - this._end = new Date(); + ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); - this.autoScale = true; - this.scale = 'day'; - this.step = 1; + // clear the canvas + var w = this.canvas.frame.canvas.clientWidth; + var h = this.canvas.frame.canvas.clientHeight; + ctx.clearRect(0, 0, w, h); - // initialize the range - this.setRange(start, end, minimumStep); + // set scaling and translation + ctx.save(); + ctx.translate(this.body.view.translation.x, this.body.view.translation.y); + ctx.scale(this.body.view.scale, this.body.view.scale); - // hidden Dates options - this.switchedDay = false; - this.switchedMonth = false; - this.switchedYear = false; - this.hiddenDates = hiddenDates; - if (hiddenDates === undefined) { - this.hiddenDates = []; - } + ctx.beginPath(); + this.body.emitter.emit('beforeDrawing', ctx); + ctx.closePath(); - this.format = TimeStep.FORMAT; // default formatting - } + if (hidden === false) { + if (this.dragging === false || this.dragging === true && this.options.hideEdgesOnDrag === false) { + this._drawEdges(ctx); + } + } - // Time formatting - TimeStep.FORMAT = { - minorLabels: { - millisecond: 'SSS', - second: 's', - minute: 'HH:mm', - hour: 'HH:mm', - weekday: 'ddd D', - day: 'D', - 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', - month: 'YYYY', - year: '' - } - }; + if (this.dragging === false || this.dragging === true && this.options.hideNodesOnDrag === false) { + this._drawNodes(ctx, hidden); + } - /** - * 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', '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); - }; + if (this.controlNodesActive === true) { + this._drawControlNodes(ctx); + } - /** - * 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'; - } + ctx.beginPath(); + //this.physics.nodesSolver._debug(ctx,"#F00F0F"); + this.body.emitter.emit('afterDrawing', ctx); + ctx.closePath(); + // restore original scaling and translation + ctx.restore(); - this._start = start != undefined ? new Date(start.valueOf()) : new Date(); - this._end = end != undefined ? new Date(end.valueOf()) : new Date(); + if (hidden === true) { + ctx.clearRect(0, 0, w, h); + } + } + }, { + key: '_resizeNodes', - if (this.autoScale) { - this.setMinimumStep(minimumStep); - } - }; + /** + * Redraw all nodes + * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); + * @param {CanvasRenderingContext2D} ctx + * @param {Boolean} [alwaysShow] + * @private + */ + value: function _resizeNodes() { + var ctx = this.canvas.frame.canvas.getContext('2d'); + if (this.pixelRatio === undefined) { + this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + } + ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); + ctx.save(); + ctx.translate(this.body.view.translation.x, this.body.view.translation.y); + ctx.scale(this.body.view.scale, this.body.view.scale); - /** - * Set the range iterator to the start date. - */ - TimeStep.prototype.first = function () { - this.current = new Date(this._start.valueOf()); - this.roundToMinor(); - }; + var nodes = this.body.nodes; + var node = undefined; - /** - * 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 - // IMPORTANT: we have no breaks in this switch! (this is no bug) - // noinspection FallThroughInSwitchStatementJS - switch (this.scale) { - case 'year': - this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step)); - this.current.setMonth(0); - case 'month': - this.current.setDate(1); - case 'day': // intentional fall through - case 'weekday': - this.current.setHours(0); - case 'hour': - this.current.setMinutes(0); - case 'minute': - this.current.setSeconds(0); - case 'second': - this.current.setMilliseconds(0); - //case 'millisecond': // nothing to do for milliseconds - } + // resize all nodes + for (var nodeId in nodes) { + if (nodes.hasOwnProperty(nodeId)) { + node = nodes[nodeId]; + node.resize(ctx); + node.updateBoundingBox(ctx); + } + } - 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.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step);break; - case 'second': - this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step);break; - case 'minute': - this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step);break; - case 'hour': - this.current.setHours(this.current.getHours() - this.current.getHours() % this.step);break; - case 'weekday': // intentional fall through - case 'day': - this.current.setDate(this.current.getDate() - 1 - (this.current.getDate() - 1) % this.step + 1);break; - case 'month': - this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step);break; - case 'year': - this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step);break; - default: - break; + // restore original scaling and translation + ctx.restore(); } - } - }; + }, { + key: '_drawNodes', - /** - * 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(); - }; + /** + * Redraw all nodes + * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); + * @param {CanvasRenderingContext2D} ctx + * @param {Boolean} [alwaysShow] + * @private + */ + value: function _drawNodes(ctx) { + var alwaysShow = arguments[1] === undefined ? false : arguments[1]; - /** - * Do the next step - */ - TimeStep.prototype.next = function () { - var prev = this.current.valueOf(); + var nodes = this.body.nodes; + var nodeIndices = this.body.nodeIndices; + var node = undefined; + var selected = []; + var margin = 20; + var topLeft = this.canvas.DOMtoCanvas({ x: -margin, y: -margin }); + var bottomRight = this.canvas.DOMtoCanvas({ + x: this.canvas.frame.canvas.clientWidth + margin, + y: this.canvas.frame.canvas.clientHeight + margin + }); + var viewableArea = { top: topLeft.y, left: topLeft.x, bottom: bottomRight.y, right: bottomRight.x }; - // Two cases, needed to prevent issues with switching daylight savings - // (end of March and end of October) - if (this.current.getMonth() < 6) { - switch (this.scale) { - case 'millisecond': + // draw unselected nodes; + for (var i = 0; i < nodeIndices.length; i++) { + node = nodes[nodeIndices[i]]; + // set selected nodes aside + if (node.isSelected()) { + selected.push(nodeIndices[i]); + } else { + if (alwaysShow === true) { + node.draw(ctx); + } else if (node.isBoundingBoxOverlappingWith(viewableArea) === true) { + node.draw(ctx); + } else { + node.updateBoundingBox(ctx); + } + } + } - this.current = new Date(this.current.valueOf() + this.step);break; - case 'second': - this.current = new Date(this.current.valueOf() + this.step * 1000);break; - case 'minute': - this.current = new Date(this.current.valueOf() + this.step * 1000 * 60);break; - case 'hour': - this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60); - // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...) - var h = this.current.getHours(); - this.current.setHours(h - h % this.step); - break; - case 'weekday': // intentional fall through - case 'day': - this.current.setDate(this.current.getDate() + this.step);break; - case 'month': - this.current.setMonth(this.current.getMonth() + this.step);break; - case 'year': - this.current.setFullYear(this.current.getFullYear() + this.step);break; - default: - break; + // draw the selected nodes on top + for (var i = 0; i < selected.length; i++) { + node = nodes[selected[i]]; + node.draw(ctx); + } } - } else { - switch (this.scale) { - case 'millisecond': - this.current = new Date(this.current.valueOf() + this.step);break; - case 'second': - this.current.setSeconds(this.current.getSeconds() + this.step);break; - case 'minute': - this.current.setMinutes(this.current.getMinutes() + this.step);break; - case 'hour': - this.current.setHours(this.current.getHours() + this.step);break; - case 'weekday': // intentional fall through - case 'day': - this.current.setDate(this.current.getDate() + this.step);break; - case 'month': - this.current.setMonth(this.current.getMonth() + this.step);break; - case 'year': - this.current.setFullYear(this.current.getFullYear() + this.step);break; - default: - break; + }, { + key: '_drawEdges', + + /** + * Redraw all edges + * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); + * @param {CanvasRenderingContext2D} ctx + * @private + */ + value: function _drawEdges(ctx) { + var edges = this.body.edges; + var edgeIndices = this.body.edgeIndices; + var edge = undefined; + + for (var i = 0; i < edgeIndices.length; i++) { + edge = edges[edgeIndices[i]]; + if (edge.connected === true) { + edge.draw(ctx); + } + } } - } + }, { + key: '_drawControlNodes', - if (this.step != 1) { - // round down to the correct major value - switch (this.scale) { - case 'millisecond': - if (this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0);break; - case 'second': - if (this.current.getSeconds() < this.step) this.current.setSeconds(0);break; - case 'minute': - if (this.current.getMinutes() < this.step) this.current.setMinutes(0);break; - case 'hour': - if (this.current.getHours() < this.step) this.current.setHours(0);break; - case 'weekday': // intentional fall through - case 'day': - if (this.current.getDate() < this.step + 1) this.current.setDate(1);break; - case 'month': - if (this.current.getMonth() < this.step) this.current.setMonth(0);break; - case 'year': - break; // nothing to do for year - default: - break; + /** + * Redraw all edges + * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); + * @param {CanvasRenderingContext2D} ctx + * @private + */ + value: function _drawControlNodes(ctx) { + var edges = this.body.edges; + var edgeIndices = this.body.edgeIndices; + var edge = undefined; + + for (var i = 0; i < edgeIndices.length; i++) { + edge = edges[edgeIndices[i]]; + edge._drawControlNodes(ctx); + } } - } + }, { + key: '_determineBrowserMethod', - // safety mechanism: if current time is still unchanged, move to the end - if (this.current.valueOf() == prev) { - this.current = new Date(this._end.valueOf()); - } + /** + * Determine if the browser requires a setTimeout or a requestAnimationFrame. This was required because + * some implementations (safari and IE9) did not support requestAnimationFrame + * @private + */ + value: function _determineBrowserMethod() { + if (typeof window !== 'undefined') { + var browserType = navigator.userAgent.toLowerCase(); + this.requiresTimeout = false; + if (browserType.indexOf('msie 9.0') != -1) { + // IE 9 + this.requiresTimeout = true; + } else if (browserType.indexOf('safari') != -1) { + // safari + if (browserType.indexOf('chrome') <= -1) { + this.requiresTimeout = true; + } + } + } else { + this.requiresTimeout = true; + } + } + }]); + + return CanvasRenderer; + })(); + + exports['default'] = CanvasRenderer; + module.exports = exports['default']; + +/***/ }, +/* 60 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); - DateUtil.stepOverHiddenDates(this, prev); - }; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /** - * Get the current datetime - * @return {Date} current The current date - */ - TimeStep.prototype.getCurrent = function () { - return this.current; - }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - /** - * 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', '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; - } - }; + var Hammer = __webpack_require__(41); + var hammerUtil = __webpack_require__(49); - /** - * Enable or disable autoscaling - * @param {boolean} enable If true, autoascaling is set true - */ - TimeStep.prototype.setAutoScale = function (enable) { - this.autoScale = enable; - }; + var util = __webpack_require__(2); /** - * Automatically determine the scale that bests fits the provided minimum step - * @param {Number} [minimumStep] The minimum step size in milliseconds + * Create the main frame for the Network. + * This function is executed once when a Network object is created. The frame + * contains a canvas, and this canvas contains all objects like the axis and + * nodes. + * @private */ - TimeStep.prototype.setMinimumStep = function (minimumStep) { - if (minimumStep == undefined) { - return; - } - //var b = asc + ds; + var Canvas = (function () { + function Canvas(body) { + _classCallCheck(this, Canvas); - 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; + this.body = body; + this.pixelRatio = 1; + this.resizeTimer = undefined; + this.resizeFunction = this._onResize.bind(this); - // 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; + this.options = {}; + this.defaultOptions = { + autoResize: true, + height: '100%', + width: '100%' + }; + util.extend(this.options, this.defaultOptions); + + this.bindEventListeners(); } - }; - /** - * 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', 'month', 'year'. - * @param {number} step Current step (1, 2, 4, 5, ... - * @return {Date} snappedDate - */ - TimeStep.snap = function (date, scale, step) { - var clone = new Date(date.valueOf()); + _createClass(Canvas, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this = this; - if (scale == 'year') { - var year = clone.getFullYear() + Math.round(clone.getMonth() / 12); - clone.setFullYear(Math.round(year / step) * step); - clone.setMonth(0); - clone.setDate(0); - clone.setHours(0); - clone.setMinutes(0); - clone.setSeconds(0); - clone.setMilliseconds(0); - } else if (scale == 'month') { - if (clone.getDate() > 15) { - clone.setDate(1); - clone.setMonth(clone.getMonth() + 1); - // important: first set Date to 1, after that change the month. - } else { - clone.setDate(1); + // bind the events + this.body.emitter.once('resize', function (obj) { + if (obj.width !== 0) { + _this.body.view.translation.x = obj.width * 0.5; + } + if (obj.height !== 0) { + _this.body.view.translation.y = obj.height * 0.5; + } + }); + this.body.emitter.on('setSize', this.setSize.bind(this)); + this.body.emitter.on('destroy', function () { + _this.hammerFrame.destroy(); + _this.hammer.destroy(); + _this._cleanUp(); + }); } + }, { + key: 'setOptions', + value: function setOptions(options) { + var _this2 = this; - clone.setHours(0); - clone.setMinutes(0); - clone.setSeconds(0); - clone.setMilliseconds(0); - } else if (scale == 'day') { - //noinspection FallthroughInSwitchStatementJS - switch (step) { - case 5: - case 2: - clone.setHours(Math.round(clone.getHours() / 24) * 24);break; - default: - clone.setHours(Math.round(clone.getHours() / 12) * 12);break; - } - clone.setMinutes(0); - clone.setSeconds(0); - clone.setMilliseconds(0); - } else if (scale == 'weekday') { - //noinspection FallthroughInSwitchStatementJS - switch (step) { - case 5: - case 2: - clone.setHours(Math.round(clone.getHours() / 12) * 12);break; - default: - clone.setHours(Math.round(clone.getHours() / 6) * 6);break; + if (options !== undefined) { + var fields = ['width', 'height', 'autoResize']; + util.selectiveDeepExtend(fields, this.options, options); + } + + if (this.options.autoResize === true) { + // automatically adapt to a changing size of the browser. + this._cleanUp(); + this.resizeTimer = setInterval(function () { + _this2.setSize();_this2.body.emitter.emit('_requestRedraw'); + }, 1000); + this.resizeFunction = this._onResize.bind(this); + util.addEventListener(window, 'resize', this.resizeFunction); + } } - clone.setMinutes(0); - clone.setSeconds(0); - clone.setMilliseconds(0); - } else if (scale == 'hour') { - switch (step) { - case 4: - clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60);break; - default: - clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30);break; + }, { + key: '_cleanUp', + value: function _cleanUp() { + // automatically adapt to a changing size of the browser. + if (this.resizeTimer !== undefined) { + clearInterval(this.resizeTimer); + } + util.removeEventListener(window, 'resize', this.resizeFunction); + this.resizeFunction = undefined; } - clone.setSeconds(0); - clone.setMilliseconds(0); - } else if (scale == 'minute') { - //noinspection FallthroughInSwitchStatementJS - switch (step) { - case 15: - case 10: - clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5); - clone.setSeconds(0); - break; - case 5: - clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60);break; - default: - clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30);break; + }, { + key: '_onResize', + value: function _onResize() { + this.setSize(); + this.body.emitter.emit('_redraw'); } - clone.setMilliseconds(0); - } else if (scale == 'second') { - //noinspection FallthroughInSwitchStatementJS - switch (step) { - case 15: - case 10: - clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5); - clone.setMilliseconds(0); - break; - case 5: - clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000);break; - default: - clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500);break; + }, { + key: '_prepareValue', + value: function _prepareValue(value) { + if (typeof value === 'number') { + return value + 'px'; + } else if (typeof value === 'string') { + if (value.indexOf('%') !== -1 || value.indexOf('px') !== -1) { + return value; + } else if (value.indexOf('%') === -1) { + return value + 'px'; + } + } + throw new Error('Could not use the value supplie for width or height:' + value); } - } else if (scale == 'millisecond') { - var _step = step > 5 ? step / 2 : 1; - clone.setMilliseconds(Math.round(clone.getMilliseconds() / _step) * _step); - } + }, { + key: '_create', - return clone; - }; + /** + * Create the HTML + */ + value: function _create() { + // remove all elements from the container element. + while (this.body.container.hasChildNodes()) { + this.body.container.removeChild(this.body.container.firstChild); + } - /** - * 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) { - this.switchedYear = false; - switch (this.scale) { - case 'year': - case 'month': - case 'weekday': - case 'day': - case 'hour': - case 'minute': - case 'second': - case 'millisecond': - return true; - default: - return false; - } - } else if (this.switchedMonth == true) { - this.switchedMonth = false; - switch (this.scale) { - case 'weekday': - case 'day': - case 'hour': - case 'minute': - case 'second': - case 'millisecond': - return true; - default: - return false; - } - } else if (this.switchedDay == true) { - this.switchedDay = false; - switch (this.scale) { - case 'millisecond': - case 'second': - case 'minute': - case 'hour': - return true; - default: - return false; + this.frame = document.createElement('div'); + this.frame.className = 'vis-network'; + this.frame.style.position = 'relative'; + this.frame.style.overflow = 'hidden'; + this.frame.tabIndex = 900; // tab index is required for keycharm to bind keystrokes to the div instead of the window + + ////////////////////////////////////////////////////////////////// + + this.frame.canvas = document.createElement('canvas'); + this.frame.canvas.style.position = 'relative'; + this.frame.appendChild(this.frame.canvas); + + if (!this.frame.canvas.getContext) { + var noCanvas = document.createElement('DIV'); + noCanvas.style.color = 'red'; + noCanvas.style.fontWeight = 'bold'; + noCanvas.style.padding = '10px'; + noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; + this.frame.canvas.appendChild(noCanvas); + } else { + var ctx = this.frame.canvas.getContext('2d'); + this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + + this.frame.canvas.getContext('2d').setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); + } + + // add the frame to the container element + this.body.container.appendChild(this.frame); + + this.body.view.scale = 1; + this.body.view.translation = { x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight }; + + this._bindHammer(); } - } + }, { + key: '_bindHammer', - switch (this.scale) { - case 'millisecond': - return this.current.getMilliseconds() == 0; - case 'second': - return this.current.getSeconds() == 0; - case 'minute': - return this.current.getHours() == 0 && this.current.getMinutes() == 0; - case 'hour': - return this.current.getHours() == 0; - case 'weekday': // intentional fall through - case 'day': - return this.current.getDate() == 1; - case 'month': - return this.current.getMonth() == 0; - case 'year': - return false; - default: - return false; - } - }; + /** + * This function binds hammer, it can be repeated over and over due to the uniqueness check. + * @private + */ + value: function _bindHammer() { + var _this3 = this; - /** - * 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] custom date. if not provided, current date is taken - */ - TimeStep.prototype.getLabelMinor = function (date) { - if (date == undefined) { - date = this.current; - } + if (this.hammer !== undefined) { + this.hammer.destroy(); + } + this.drag = {}; + this.pinch = {}; - var format = this.format.minorLabels[this.scale]; - return format && format.length > 0 ? moment(date).format(format) : ''; - }; + // init hammer + this.hammer = new Hammer(this.frame.canvas); + this.hammer.get('pinch').set({ enable: true }); + // enable to get better response, todo: test on mobile. + //this.hammer.get('pan').set({threshold:2}); - /** - * 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] custom date. if not provided, current date is taken - */ - TimeStep.prototype.getLabelMajor = function (date) { - if (date == undefined) { - date = this.current; - } + hammerUtil.onTouch(this.hammer, function (event) { + _this3.body.eventListeners.onTouch(event); + }); + this.hammer.on('tap', function (event) { + _this3.body.eventListeners.onTap(event); + }); + this.hammer.on('doubletap', function (event) { + _this3.body.eventListeners.onDoubleTap(event); + }); + this.hammer.on('press', function (event) { + _this3.body.eventListeners.onHold(event); + }); + this.hammer.on('panstart', function (event) { + _this3.body.eventListeners.onDragStart(event); + }); + this.hammer.on('panmove', function (event) { + _this3.body.eventListeners.onDrag(event); + }); + this.hammer.on('panend', function (event) { + _this3.body.eventListeners.onDragEnd(event); + }); + this.hammer.on('pinch', function (event) { + _this3.body.eventListeners.onPinch(event); + }); - var format = this.format.majorLabels[this.scale]; - return format && format.length > 0 ? moment(date).format(format) : ''; - }; + // TODO: neatly cleanup these handlers when re-creating the Canvas, IF these are done with hammer, event.stopPropagation will not work? + this.frame.canvas.addEventListener('mousewheel', function (event) { + _this3.body.eventListeners.onMouseWheel(event); + }); + this.frame.canvas.addEventListener('DOMMouseScroll', function (event) { + _this3.body.eventListeners.onMouseWheel(event); + }); + + this.frame.canvas.addEventListener('mousemove', function (event) { + _this3.body.eventListeners.onMouseMove(event); + }); + this.frame.canvas.addEventListener('contextmenu', function (event) { + _this3.body.eventListeners.onContext(event); + }); + + this.hammerFrame = new Hammer(this.frame); + hammerUtil.onRelease(this.hammerFrame, function (event) { + _this3.body.eventListeners.onRelease(event); + }); + } + }, { + key: 'setSize', - TimeStep.prototype.getClassName = function () { - var m = moment(this.current); - var date = m.locale ? m.locale('en') : m.lang('en'); // old versions of moment have .lang() function - var step = this.step; + /** + * Set a new size for the network + * @param {string} width Width in pixels or percentage (for example '800px' + * or '50%') + * @param {string} height Height in pixels or percentage (for example '400px' + * or '30%') + */ + value: function setSize() { + var width = arguments[0] === undefined ? this.options.width : arguments[0]; + var height = arguments[1] === undefined ? this.options.height : arguments[1]; - function even(value) { - return value / step % 2 == 0 ? ' vis-even' : ' vis-odd'; - } + width = this._prepareValue(width); + height = this._prepareValue(height); - 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 ''; - } + var emitEvent = false; + var oldWidth = this.frame.canvas.width; + var oldHeight = this.frame.canvas.height; - function currentWeek(date) { - return date.isSame(new Date(), 'week') ? ' vis-current-week' : ''; - } + if (width != this.options.width || height != this.options.height || this.frame.style.width != width || this.frame.style.height != height) { + this.frame.style.width = width; + this.frame.style.height = height; - function currentMonth(date) { - return date.isSame(new Date(), 'month') ? ' vis-current-month' : ''; - } + this.frame.canvas.style.width = '100%'; + this.frame.canvas.style.height = '100%'; - function currentYear(date) { - return date.isSame(new Date(), 'year') ? ' vis-current-year' : ''; - } + this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio; + this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio; - switch (this.scale) { - case 'millisecond': - return even(date.milliseconds()).trim(); + this.options.width = width; + this.options.height = height; - case 'second': - return even(date.seconds()).trim(); + emitEvent = true; + } else { + // this would adapt the width of the canvas to the width from 100% if and only if + // there is a change. - case 'minute': - return even(date.minutes()).trim(); + if (this.frame.canvas.width != this.frame.canvas.clientWidth * this.pixelRatio) { + this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio; + emitEvent = true; + } + if (this.frame.canvas.height != this.frame.canvas.clientHeight * this.pixelRatio) { + this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio; + emitEvent = true; + } + } - case 'hour': - var hours = date.hours(); - if (this.step == 4) { - hours = hours + '-h' + (hours + 4); + if (emitEvent === true) { + this.body.emitter.emit('resize', { width: this.frame.canvas.width / this.pixelRatio, height: this.frame.canvas.height / this.pixelRatio, oldWidth: oldWidth / this.pixelRatio, oldHeight: oldHeight / this.pixelRatio }); } - return 'vis-h' + hours + today(date) + even(date.hours()); + } + }, { + key: '_XconvertDOMtoCanvas', - case 'weekday': - return 'vis-' + date.format('dddd').toLowerCase() + today(date) + currentWeek(date) + even(date.date()); + /** + * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to + * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) + * @param {number} x + * @returns {number} + * @private + */ + value: function _XconvertDOMtoCanvas(x) { + return (x - this.body.view.translation.x) / this.body.view.scale; + } + }, { + key: '_XconvertCanvasToDOM', - case 'day': - var day = date.date(); - var month = date.format('MMMM').toLowerCase(); - return 'vis-day' + day + ' vis-' + month + currentMonth(date) + even(day - 1); + /** + * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to + * the X coordinate in DOM-space (coordinate point in browser relative to the container div) + * @param {number} x + * @returns {number} + * @private + */ + value: function _XconvertCanvasToDOM(x) { + return x * this.body.view.scale + this.body.view.translation.x; + } + }, { + key: '_YconvertDOMtoCanvas', - case 'month': - return 'vis-' + date.format('MMMM').toLowerCase() + currentMonth(date) + even(date.month()); + /** + * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to + * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) + * @param {number} y + * @returns {number} + * @private + */ + value: function _YconvertDOMtoCanvas(y) { + return (y - this.body.view.translation.y) / this.body.view.scale; + } + }, { + key: '_YconvertCanvasToDOM', - case 'year': - var year = date.year(); - return 'vis-year' + year + currentYear(date) + even(year); + /** + * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to + * the Y coordinate in DOM-space (coordinate point in browser relative to the container div) + * @param {number} y + * @returns {number} + * @private + */ + value: function _YconvertCanvasToDOM(y) { + return y * this.body.view.scale + this.body.view.translation.y; + } + }, { + key: 'canvasToDOM', - default: - return ''; - } - }; + /** + * + * @param {object} pos = {x: number, y: number} + * @returns {{x: number, y: number}} + * @constructor + */ + value: function canvasToDOM(pos) { + return { x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y) }; + } + }, { + key: 'DOMtoCanvas', - module.exports = TimeStep; + /** + * + * @param {object} pos = {x: number, y: number} + * @returns {{x: number, y: number}} + * @constructor + */ + value: function DOMtoCanvas(pos) { + return { x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y) }; + } + }]); + + return Canvas; + })(); + + exports['default'] = Canvas; + module.exports = exports['default']; /***/ }, -/* 45 */ +/* 61 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; - - var util = __webpack_require__(2); - var Group = __webpack_require__(41); + "use strict"; - /** - * @constructor BackgroundGroup - * @param {Number | String} groupId - * @param {Object} data - * @param {ItemSet} itemSet - */ - function BackgroundGroup(groupId, data, itemSet) { - Group.call(this, groupId, data, itemSet); + Object.defineProperty(exports, "__esModule", { + value: true + }); - this.width = 0; - this.height = 0; - this.top = 0; - this.left = 0; - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - BackgroundGroup.prototype = Object.create(Group.prototype); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - /** - * Repaint this group - * @param {{start: number, end: number}} range - * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin - * @param {boolean} [restack=false] Force restacking of all items - * @return {boolean} Returns true if the group is resized - */ - BackgroundGroup.prototype.redraw = function (range, margin, restack) { - var resized = false; + var util = __webpack_require__(2); - this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); + var View = (function () { + function View(body, canvas) { + var _this = this; - // calculate actual size - this.width = this.dom.background.offsetWidth; + _classCallCheck(this, View); - // apply new height (just always zero for BackgroundGroup - this.dom.background.style.height = '0'; + this.body = body; + this.canvas = canvas; - // 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); - } + this.animationSpeed = 1 / this.renderRefreshRate; + this.animationEasingFunction = "easeInOutQuint"; + this.easingTime = 0; + this.sourceScale = 0; + this.targetScale = 0; + this.sourceTranslation = 0; + this.targetTranslation = 0; + this.lockedOnNodeId = undefined; + this.lockedOnNodeOffset = undefined; + this.touchTime = 0; - return resized; - }; + this.viewFunction = undefined; - /** - * Show this group: attach to the DOM - */ - BackgroundGroup.prototype.show = function () { - if (!this.dom.background.parentNode) { - this.itemSet.dom.background.appendChild(this.dom.background); + this.body.emitter.on("fit", this.fit.bind(this)); + this.body.emitter.on("animationFinished", function () { + _this.body.emitter.emit("_stopRendering"); + }); + this.body.emitter.on("unlockNode", this.releaseNode.bind(this)); } - }; - module.exports = BackgroundGroup; + _createClass(View, [{ + key: "setOptions", + value: function setOptions() { + var options = arguments[0] === undefined ? {} : arguments[0]; -/***/ }, -/* 46 */ -/***/ function(module, exports, __webpack_require__) { + this.options = options; + } + }, { + key: "_getRange", - 'use strict'; + /** + * Find the center position of the network + * @private + */ + value: function _getRange() { + var specificNodes = arguments[0] === undefined ? [] : arguments[0]; - var Item = __webpack_require__(11); + var minY = 1000000000, + maxY = -1000000000, + minX = 1000000000, + maxX = -1000000000, + node; + if (specificNodes.length > 0) { + for (var i = 0; i < specificNodes.length; i++) { + node = this.body.nodes[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 + } + } else { + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + node = this.body.nodes[nodeId]; + 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 + } + } + } - /** - * @constructor PointItem - * @extends Item - * @param {Object} data Object containing parameters start - * content, 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 PointItem(data, conversion, options) { - this.props = { - dot: { - top: 0, - width: 0, - height: 0 - }, - content: { - height: 0, - marginLeft: 0 + if (minX === 1000000000 && maxX === -1000000000 && minY === 1000000000 && maxY === -1000000000) { + minY = 0, maxY = 0, minX = 0, maxX = 0; + } + return { minX: minX, maxX: maxX, minY: minY, maxY: maxY }; } - }; + }, { + key: "_findCenter", - // validate data - if (data) { - if (data.start == undefined) { - throw new Error('Property "start" missing in item ' + data); + /** + * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; + * @returns {{x: number, y: number}} + * @private + */ + value: function _findCenter(range) { + return { x: 0.5 * (range.maxX + range.minX), + y: 0.5 * (range.maxY + range.minY) }; } - } + }, { + key: "fit", - Item.call(this, data, conversion, options); - } + /** + * This function zooms out to fit all data on screen based on amount of nodes + * @param {Object} Options + * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false; + */ + value: function fit() { + var options = arguments[0] === undefined ? { nodes: [] } : arguments[0]; + var initialZoom = arguments[1] === undefined ? false : arguments[1]; - PointItem.prototype = new Item(null, null, null); + var range; + var zoomLevel; - /** - * Check whether this item is visible inside given range - * @returns {{start: Number, end: Number}} range with a timestamp for start and end - * @returns {boolean} True if visible - */ - PointItem.prototype.isVisible = function (range) { - // determine visibility - // TODO: account for the real width of the item. Right now we just add 1/4 to the window - var interval = (range.end - range.start) / 4; - return this.data.start > range.start - interval && this.data.start < range.end + interval; - }; + if (initialZoom === true) { + // check if more than half of the nodes have a predefined position. If so, we use the range, not the approximation. + var positionDefined = 0; + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + var node = this.body.nodes[nodeId]; + if (node.predefinedPosition === true) { + positionDefined += 1; + } + } + } + if (positionDefined > 0.5 * this.body.nodeIndices.length) { + this.fit(options, false); + return; + } - /** - * Repaint the item - */ - PointItem.prototype.redraw = function () { - var dom = this.dom; - if (!dom) { - // create DOM - this.dom = {}; - dom = this.dom; + range = this._getRange(options.nodes); - // background box - dom.point = document.createElement('div'); - // className is updated in redraw() + var numberOfNodes = this.body.nodeIndices.length; + zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. - // contents box, right from the dot - dom.content = document.createElement('div'); - dom.content.className = 'vis-item-content'; - dom.point.appendChild(dom.content); + // correct for larger canvasses. + var factor = Math.min(this.canvas.frame.canvas.clientWidth / 600, this.canvas.frame.canvas.clientHeight / 600); + zoomLevel *= factor; + } else { + this.body.emitter.emit("_resizeNodes"); + range = this._getRange(options.nodes); + var xDistance = Math.abs(range.maxX - range.minX) * 1.1; + var yDistance = Math.abs(range.maxY - range.minY) * 1.1; - // dot at start - dom.dot = document.createElement('div'); - dom.point.appendChild(dom.dot); + var xZoomLevel = this.canvas.frame.canvas.clientWidth / xDistance; + var yZoomLevel = this.canvas.frame.canvas.clientHeight / yDistance; - // attach this item as attribute - dom.point['timeline-item'] = this; + zoomLevel = xZoomLevel <= yZoomLevel ? xZoomLevel : yZoomLevel; + } - this.dirty = true; - } + if (zoomLevel > 1) { + zoomLevel = 1; + } else if (zoomLevel === 0) { + zoomLevel = 1; + } + + var center = this._findCenter(range); + var animationOptions = { position: center, scale: zoomLevel, animation: options.animation }; + this.moveTo(animationOptions); + } + }, { + key: "focus", + + // animation + + /** + * Center a node in view. + * + * @param {Number} nodeId + * @param {Number} [options] + */ + value: function focus(nodeId) { + var options = arguments[1] === undefined ? {} : arguments[1]; + + if (this.body.nodes[nodeId] !== undefined) { + var nodePosition = { x: this.body.nodes[nodeId].x, y: this.body.nodes[nodeId].y }; + options.position = nodePosition; + options.lockedOnNode = nodeId; + + this.moveTo(options); + } else { + console.log("Node: " + nodeId + " cannot be found."); + } + } + }, { + key: "moveTo", + + /** + * + * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels + * | options.scale = Number // scale to move to + * | options.position = {x:Number, y:Number} // position to move to + * | options.animation = {duration:Number, easingFunction:String} || Boolean // position to move to + */ + value: function moveTo(options) { + if (options === undefined) { + options = {}; + return; + } + if (options.offset === undefined) { + options.offset = { x: 0, y: 0 }; + } + if (options.offset.x === undefined) { + options.offset.x = 0; + } + if (options.offset.y === undefined) { + options.offset.y = 0; + } + if (options.scale === undefined) { + options.scale = this.body.view.scale; + } + if (options.position === undefined) { + options.position = this.getViewPosition(); + } + if (options.animation === undefined) { + options.animation = { duration: 0 }; + } + if (options.animation === false) { + options.animation = { duration: 0 }; + } + if (options.animation === true) { + options.animation = {}; + } + if (options.animation.duration === undefined) { + options.animation.duration = 1000; + } // default duration + if (options.animation.easingFunction === undefined) { + options.animation.easingFunction = "easeInOutQuad"; + } // default easing function - // append DOM to parent DOM - if (!this.parent) { - throw new Error('Cannot redraw item: no parent attached'); - } - if (!dom.point.parentNode) { - var foreground = this.parent.dom.foreground; - if (!foreground) { - throw new Error('Cannot redraw item: parent has no foreground container element'); + this.animateView(options); } - foreground.appendChild(dom.point); - } - this.displayed = true; + }, { + key: "animateView", - // Update DOM when item is marked dirty. 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._updateTitle(this.dom.point); - this._updateDataAttributes(this.dom.point); - this._updateStyle(this.dom.point); + /** + * + * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels + * | options.time = Number // animation time in milliseconds + * | options.scale = Number // scale to animate to + * | options.position = {x:Number, y:Number} // position to animate to + * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad, + * // easeInCubic, easeOutCubic, easeInOutCubic, + * // easeInQuart, easeOutQuart, easeInOutQuart, + * // easeInQuint, easeOutQuint, easeInOutQuint + */ + value: function animateView(options) { + if (options === undefined) { + return; + } + this.animationEasingFunction = options.animation.easingFunction; + // release if something focussed on the node + this.releaseNode(); + if (options.locked === true) { + this.lockedOnNodeId = options.lockedOnNode; + this.lockedOnNodeOffset = options.offset; + } - // update class - var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); - dom.point.className = 'vis-item vis-point' + className; - dom.dot.className = 'vis-item vis-dot' + className; + // forcefully complete the old animation if it was still running + if (this.easingTime != 0) { + this._transitionRedraw(true); // by setting easingtime to 1, we finish the animation. + } - // recalculate size - this.width = dom.point.offsetWidth; - this.height = dom.point.offsetHeight; - this.props.dot.width = dom.dot.offsetWidth; - this.props.dot.height = dom.dot.offsetHeight; - this.props.content.height = dom.content.offsetHeight; + this.sourceScale = this.body.view.scale; + this.sourceTranslation = this.body.view.translation; + this.targetScale = options.scale; - // resize contents - dom.content.style.marginLeft = 2 * this.props.dot.width + 'px'; - //dom.content.style.marginRight = ... + 'px'; // TODO: margin right + // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw + // but at least then we'll have the target transition + this.body.view.scale = this.targetScale; + var viewCenter = this.canvas.DOMtoCanvas({ x: 0.5 * this.canvas.frame.canvas.clientWidth, y: 0.5 * this.canvas.frame.canvas.clientHeight }); - dom.dot.style.top = (this.height - this.props.dot.height) / 2 + 'px'; - dom.dot.style.left = this.props.dot.width / 2 + 'px'; + var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node + x: viewCenter.x - options.position.x, + y: viewCenter.y - options.position.y + }; + this.targetTranslation = { + x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x, + y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y + }; - this.dirty = false; - } + // if the time is set to 0, don't do an animation + if (options.animation.duration === 0) { + if (this.lockedOnNodeId != undefined) { + this.viewFunction = this._lockedRedraw.bind(this); + this.body.emitter.on("initRedraw", this.viewFunction); + } else { + this.body.view.scale = this.targetScale; + this.body.view.translation = this.targetTranslation; + this.body.emitter.emit("_requestRedraw"); + } + } else { + this.animationSpeed = 1 / (60 * options.animation.duration * 0.001) || 1 / 60; // 60 for 60 seconds, 0.001 for milli's + this.animationEasingFunction = options.animation.easingFunction; - this._repaintDeleteButton(dom.point); - }; + this.viewFunction = this._transitionRedraw.bind(this); + this.body.emitter.on("initRedraw", this.viewFunction); + this.body.emitter.emit("_startRendering"); + } + } + }, { + key: "_lockedRedraw", - /** - * Show the item in the DOM (when not already visible). The items DOM will - * be created when needed. - */ - PointItem.prototype.show = function () { - if (!this.displayed) { - this.redraw(); - } - }; + /** + * used to animate smoothly by hijacking the redraw function. + * @private + */ + value: function _lockedRedraw() { + var nodePosition = { x: this.body.nodes[this.lockedOnNodeId].x, y: this.body.nodes[this.lockedOnNodeId].y }; + var viewCenter = this.DOMtoCanvas({ x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight }); + var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node + x: viewCenter.x - nodePosition.x, + y: viewCenter.y - nodePosition.y + }; + var sourceTranslation = this.body.view.translation; + var targetTranslation = { + x: sourceTranslation.x + distanceFromCenter.x * this.body.view.scale + this.lockedOnNodeOffset.x, + y: sourceTranslation.y + distanceFromCenter.y * this.body.view.scale + this.lockedOnNodeOffset.y + }; - /** - * Hide the item from the DOM (when visible) - */ - PointItem.prototype.hide = function () { - if (this.displayed) { - if (this.dom.point.parentNode) { - this.dom.point.parentNode.removeChild(this.dom.point); + this.body.view.translation = targetTranslation; + } + }, { + key: "releaseNode", + value: function releaseNode() { + if (this.lockedOnNodeId !== undefined && this.viewFunction !== undefined) { + this.body.emitter.off("initRedraw", this.viewFunction); + this.lockedOnNodeId = undefined; + this.lockedOnNodeOffset = undefined; + } } + }, { + key: "_transitionRedraw", - this.displayed = false; - } - }; + /** + * + * @param easingTime + * @private + */ + value: function _transitionRedraw() { + var finished = arguments[0] === undefined ? false : arguments[0]; - /** - * Reposition the item horizontally - * @Override - */ - PointItem.prototype.repositionX = function () { - var start = this.conversion.toScreen(this.data.start); + this.easingTime += this.animationSpeed; + this.easingTime = finished === true ? 1 : this.easingTime; - this.left = start - this.props.dot.width; + var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime); - // reposition point - this.dom.point.style.left = this.left + 'px'; - }; + this.body.view.scale = this.sourceScale + (this.targetScale - this.sourceScale) * progress; + this.body.view.translation = { + x: this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress, + y: this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress + }; - /** - * Reposition the item vertically - * @Override - */ - PointItem.prototype.repositionY = function () { - var orientation = this.options.orientation.item; - var point = this.dom.point; + // cleanup + if (this.easingTime >= 1) { + this.body.emitter.off("initRedraw", this.viewFunction); + this.easingTime = 0; + if (this.lockedOnNodeId != undefined) { + this.viewFunction = this._lockedRedraw.bind(this); + this.body.emitter.on("initRedraw", this.viewFunction); + } + this.body.emitter.emit("animationFinished"); + } + } + }, { + key: "getScale", + value: function getScale() { + return this.body.view.scale; + } + }, { + key: "getViewPosition", + value: function getViewPosition() { + return this.canvas.DOMtoCanvas({ x: 0.5 * this.canvas.frame.canvas.clientWidth, y: 0.5 * this.canvas.frame.canvas.clientHeight }); + } + }]); - if (orientation == 'top') { - point.style.top = this.top + 'px'; - } else { - point.style.top = this.parent.height - this.top - this.height + 'px'; - } - }; + return View; + })(); - module.exports = PointItem; + exports["default"] = View; + module.exports = exports["default"]; /***/ }, -/* 47 */ +/* 62 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Hammer = __webpack_require__(13); - var Item = __webpack_require__(11); - var BackgroundGroup = __webpack_require__(45); - var RangeItem = __webpack_require__(43); - - /** - * @constructor BackgroundItem - * @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 - */ - // TODO: implement support for the BackgroundItem just having a start, then being displayed as a sort of an annotation - function BackgroundItem(data, conversion, options) { - this.props = { - content: { - width: 0 - } - }; - this.overflow = false; // if contents can overflow (css styling), this flag is set to true - - // 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); - } + Object.defineProperty(exports, '__esModule', { + value: true + }); - BackgroundItem.prototype = new Item(null, null, null); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - BackgroundItem.prototype.baseClassName = 'vis-item vis-background'; - BackgroundItem.prototype.stack = false; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - /** - * Check whether this item is visible inside given range - * @returns {{start: Number, end: Number}} range with a timestamp for start and end - * @returns {boolean} True if visible - */ - BackgroundItem.prototype.isVisible = function (range) { - // determine visibility - return this.data.start < range.end && this.data.end > range.start; - }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - /** - * Repaint the item - */ - BackgroundItem.prototype.redraw = function () { - var dom = this.dom; - if (!dom) { - // create DOM - this.dom = {}; - dom = this.dom; + var _componentsNavigationHandler = __webpack_require__(86); - // background box - dom.box = document.createElement('div'); - // className is updated in redraw() + var _componentsNavigationHandler2 = _interopRequireDefault(_componentsNavigationHandler); - // frame box (to prevent the item contents from overflowing - dom.frame = document.createElement('div'); - dom.frame.className = 'vis-item-overflow'; - dom.box.appendChild(dom.frame); + var _componentsPopup = __webpack_require__(87); - // contents box - dom.content = document.createElement('div'); - dom.content.className = 'vis-item-content'; - dom.frame.appendChild(dom.content); + var _componentsPopup2 = _interopRequireDefault(_componentsPopup); - // Note: we do NOT attach this item as attribute to the DOM, - // such that background items cannot be selected - //dom.box['timeline-item'] = this; + var util = __webpack_require__(2); - this.dirty = true; - } + var InteractionHandler = (function () { + function InteractionHandler(body, canvas, selectionHandler) { + _classCallCheck(this, InteractionHandler); - // append DOM to parent DOM - if (!this.parent) { - throw new Error('Cannot redraw item: no parent attached'); - } - if (!dom.box.parentNode) { - var background = this.parent.dom.background; - if (!background) { - throw new Error('Cannot redraw item: parent has no background container element'); - } - background.appendChild(dom.box); - } - this.displayed = true; + this.body = body; + this.canvas = canvas; + this.selectionHandler = selectionHandler; + this.navigationHandler = new _componentsNavigationHandler2['default'](body, canvas); - // Update DOM when item is marked dirty. 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._updateTitle(this.dom.content); - this._updateDataAttributes(this.dom.content); - this._updateStyle(this.dom.box); + // bind the events from hammer to functions in this object + this.body.eventListeners.onTap = this.onTap.bind(this); + this.body.eventListeners.onTouch = this.onTouch.bind(this); + this.body.eventListeners.onDoubleTap = this.onDoubleTap.bind(this); + this.body.eventListeners.onHold = this.onHold.bind(this); + this.body.eventListeners.onDragStart = this.onDragStart.bind(this); + this.body.eventListeners.onDrag = this.onDrag.bind(this); + this.body.eventListeners.onDragEnd = this.onDragEnd.bind(this); + this.body.eventListeners.onMouseWheel = this.onMouseWheel.bind(this); + this.body.eventListeners.onPinch = this.onPinch.bind(this); + this.body.eventListeners.onMouseMove = this.onMouseMove.bind(this); + this.body.eventListeners.onRelease = this.onRelease.bind(this); + this.body.eventListeners.onContext = this.onContext.bind(this); - // update class - var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); - dom.box.className = this.baseClassName + className; + this.touchTime = 0; + this.drag = {}; + this.pinch = {}; + this.popup = undefined; + this.popupObj = undefined; + this.popupTimer = undefined; - // determine from css whether this box has overflow - this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden'; + this.body.functions.getPointer = this.getPointer.bind(this); - // recalculate size - this.props.content.width = this.dom.content.offsetWidth; - this.height = 0; // set height zero, so this item will be ignored when stacking items + this.options = {}; + this.defaultOptions = { + dragNodes: true, + dragView: true, + hover: false, + keyboard: { + enabled: false, + speed: { x: 10, y: 10, zoom: 0.02 }, + bindToWindow: true + }, + navigationButtons: false, + tooltipDelay: 300, + zoomView: true + }; + util.extend(this.options, this.defaultOptions); - this.dirty = false; + this.bindEventListeners(); } - }; - - /** - * Show the item in the DOM (when not already visible). The items DOM will - * be created when needed. - */ - BackgroundItem.prototype.show = RangeItem.prototype.show; - - /** - * Hide the item from the DOM (when visible) - * @return {Boolean} changed - */ - BackgroundItem.prototype.hide = RangeItem.prototype.hide; - /** - * Reposition the item horizontally - * @Override - */ - BackgroundItem.prototype.repositionX = RangeItem.prototype.repositionX; + _createClass(InteractionHandler, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this = this; - /** - * Reposition the item vertically - * @Override - */ - BackgroundItem.prototype.repositionY = function (margin) { - var onTop = this.options.orientation.item === 'top'; - this.dom.content.style.top = onTop ? '' : '0'; - this.dom.content.style.bottom = onTop ? '0' : ''; - var height; + this.body.emitter.on('destroy', function () { + clearTimeout(_this.popupTimer); + delete _this.body.functions.getPointer; + }); + } + }, { + key: 'setOptions', + value: function setOptions(options) { + if (options !== undefined) { + // extend all but the values in fields + var fields = ['hideEdgesOnDrag', 'hideNodesOnDrag', 'keyboard', 'multiselect', 'selectable', 'selectConnectedEdges']; + util.selectiveNotDeepExtend(fields, this.options, options); - // special positioning for subgroups - if (this.data.subgroup !== undefined) { - // TODO: instead of calculating the top position of the subgroups here for every BackgroundItem, calculate the top of the subgroup once in Itemset + // merge the keyboard options in. + util.mergeOptions(this.options, options, 'keyboard'); - var itemSubgroup = this.data.subgroup; - var subgroups = this.parent.subgroups; - var subgroupIndex = subgroups[itemSubgroup].index; - // if the orientation is top, we need to take the difference in height into account. - if (onTop == true) { - // the first subgroup will have to account for the distance from the top to the first item. - height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical; - height += subgroupIndex == 0 ? margin.axis - 0.5 * margin.item.vertical : 0; - var newTop = this.parent.top; - for (var subgroup in subgroups) { - if (subgroups.hasOwnProperty(subgroup)) { - if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroupIndex) { - newTop += subgroups[subgroup].height + margin.item.vertical; + if (options.tooltip) { + util.extend(this.options.tooltip, options.tooltip); + if (options.tooltip.color) { + this.options.tooltip.color = util.parseColor(options.tooltip.color); } } } - // the others will have to be offset downwards with this same distance. - newTop += subgroupIndex != 0 ? margin.axis - 0.5 * margin.item.vertical : 0; - this.dom.box.style.top = newTop + 'px'; - this.dom.box.style.bottom = ''; + this.navigationHandler.setOptions(this.options); } - // and when the orientation is bottom: - else { - var newTop = this.parent.top; - var totalHeight = 0; - for (var subgroup in subgroups) { - if (subgroups.hasOwnProperty(subgroup)) { - if (subgroups[subgroup].visible == true) { - var newHeight = subgroups[subgroup].height + margin.item.vertical; - totalHeight += newHeight; - if (subgroups[subgroup].index > subgroupIndex) { - newTop += newHeight; - } - } - } - } - height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical; - this.dom.box.style.top = this.parent.height - totalHeight + newTop + 'px'; - this.dom.box.style.bottom = ''; + }, { + key: 'getPointer', + + /** + * Get the pointer location from a touch location + * @param {{x: Number, y: Number}} touch + * @return {{x: Number, y: Number}} pointer + * @private + */ + value: function getPointer(touch) { + return { + x: touch.x - util.getAbsoluteLeft(this.canvas.frame.canvas), + y: touch.y - util.getAbsoluteTop(this.canvas.frame.canvas) + }; } - } - // and in the case of no subgroups: - else { - // we want backgrounds with groups to only show in groups. - if (this.parent instanceof BackgroundGroup) { - // if the item is not in a group: - height = Math.max(this.parent.height, this.parent.itemSet.body.domProps.center.height, this.parent.itemSet.body.domProps.centerContainer.height); - this.dom.box.style.top = onTop ? '0' : ''; - this.dom.box.style.bottom = onTop ? '' : '0'; - } else { - height = this.parent.height; - // same alignment for items when orientation is top or bottom - this.dom.box.style.top = this.parent.top + 'px'; - this.dom.box.style.bottom = ''; + }, { + key: 'onTouch', + + /** + * On start of a touch gesture, store the pointer + * @param event + * @private + */ + value: function onTouch(event) { + if (new Date().valueOf() - this.touchTime > 50) { + this.drag.pointer = this.getPointer(event.center); + this.drag.pinched = false; + this.pinch.scale = this.body.view.scale; + // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame) + this.touchTime = new Date().valueOf(); + } } - } - this.dom.box.style.height = height + 'px'; - }; + }, { + key: 'onTap', + + /** + * handle tap/click event: select/unselect a node + * @private + */ + value: function onTap(event) { + var pointer = this.getPointer(event.center); + var multiselect = this.selectionHandler.options.multiselect && (event.changedPointers[0].ctrlKey || event.changedPointers[0].metaKey); - module.exports = BackgroundItem; + this.checkSelectionChanges(pointer, event, multiselect); + this.selectionHandler._generateClickEvent('click', event, pointer); + } + }, { + key: 'onDoubleTap', -/***/ }, -/* 48 */ -/***/ function(module, exports, __webpack_require__) { + /** + * handle doubletap event + * @private + */ + value: function onDoubleTap(event) { + var pointer = this.getPointer(event.center); + this.selectionHandler._generateClickEvent('doubleClick', event, pointer); + } + }, { + key: 'onHold', - 'use strict'; + /** + * handle long tap event: multi select nodes + * @private + */ + value: function onHold(event) { + var pointer = this.getPointer(event.center); + var multiselect = this.selectionHandler.options.multiselect; - var util = __webpack_require__(2); - var Component = __webpack_require__(35); - var TimeStep = __webpack_require__(44); - var DateUtil = __webpack_require__(39); - var moment = __webpack_require__(17); + this.checkSelectionChanges(pointer, event, multiselect); - /** - * 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.selectionHandler._generateClickEvent('click', event, pointer); + this.selectionHandler._generateClickEvent('hold', event, pointer); } - }; - this.props = { - range: { - start: 0, - end: 0, - minimumStep: 0 - }, - lineTop: 0 - }; + }, { + key: 'onRelease', - this.defaultOptions = { - orientation: { - axis: 'bottom' - }, // axis orientation: 'top' or 'bottom' - showMinorLabels: true, - showMajorLabels: true, - format: TimeStep.FORMAT, - timeAxis: null - }; - this.options = util.extend({}, this.defaultOptions); + /** + * handle the release of the screen + * + * @private + */ + value: function onRelease(event) { + if (new Date().valueOf() - this.touchTime > 10) { + var pointer = this.getPointer(event.center); + this.selectionHandler._generateClickEvent('release', event, pointer); + // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame) + this.touchTime = new Date().valueOf(); + } + } + }, { + key: 'onContext', + value: function onContext(event) { + var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); + this.selectionHandler._generateClickEvent('oncontext', event, pointer); + } + }, { + key: 'checkSelectionChanges', - this.body = body; + /** + * + * @param pointer + * @param add + */ + value: function checkSelectionChanges(pointer, event) { + var add = arguments[2] === undefined ? false : arguments[2]; - // create the HTML DOM - this._create(); + var previouslySelectedEdgeCount = this.selectionHandler._getSelectedEdgeCount(); + var previouslySelectedNodeCount = this.selectionHandler._getSelectedNodeCount(); + var previousSelection = this.selectionHandler.getSelection(); + var selected = undefined; + if (add === true) { + selected = this.selectionHandler.selectAdditionalOnPoint(pointer); + } else { + selected = this.selectionHandler.selectOnPoint(pointer); + } + var selectedEdgesCount = this.selectionHandler._getSelectedEdgeCount(); + var selectedNodesCount = this.selectionHandler._getSelectedNodeCount(); + var currentSelection = this.selectionHandler.getSelection(); - this.setOptions(options); - } + var _determineIfDifferent = this._determineIfDifferent(previousSelection, currentSelection); - TimeAxis.prototype = new Component(); + var nodesChanges = _determineIfDifferent.nodesChanges; + var edgesChanges = _determineIfDifferent.edgesChanges; - /** - * 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', 'hiddenDates', 'timeAxis'], this.options, options); + if (selectedNodesCount - previouslySelectedNodeCount > 0) { + // node was selected + this.selectionHandler._generateClickEvent('selectNode', event, pointer); + selected = true; + } else if (selectedNodesCount - previouslySelectedNodeCount < 0) { + // node was deselected + this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection); + selected = true; + } else if (selectedNodesCount === previouslySelectedNodeCount && nodesChanges === true) { + this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection); + this.selectionHandler._generateClickEvent('selectNode', event, pointer); + selected = true; + } - // deep copy the format options - util.selectiveDeepExtend(['format'], this.options, options); + if (selectedEdgesCount - previouslySelectedEdgeCount > 0) { + // edge was selected + this.selectionHandler._generateClickEvent('selectEdge', event, pointer); + selected = true; + } else if (selectedEdgesCount - previouslySelectedEdgeCount < 0) { + // edge was deselected + this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection); + selected = true; + } else if (selectedEdgesCount === previouslySelectedEdgeCount && edgesChanges === true) { + this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection); + this.selectionHandler._generateClickEvent('selectEdge', event, pointer); + selected = true; + } - if ('orientation' in options) { - if (typeof options.orientation === 'string') { - this.options.orientation.axis = options.orientation; - } else if (typeof options.orientation === 'object' && 'axis' in options.orientation) { - this.options.orientation.axis = options.orientation.axis; + if (selected === true) { + // select or unselect + this.selectionHandler._generateClickEvent('select', event, pointer); } } + }, { + key: '_determineIfDifferent', - // 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); + /** + * This function checks if the nodes and edges previously selected have changed. + * @param previousSelection + * @param currentSelection + * @returns {{nodesChanges: boolean, edgesChanges: boolean}} + * @private + */ + value: function _determineIfDifferent(previousSelection, currentSelection) { + var nodesChanges = false; + var edgesChanges = false; + + for (var i = 0; i < previousSelection.nodes.length; i++) { + if (currentSelection.nodes.indexOf(previousSelection.nodes[i]) === -1) { + nodesChanges = true; + } + } + for (var i = 0; i < currentSelection.nodes.length; i++) { + if (previousSelection.nodes.indexOf(previousSelection.nodes[i]) === -1) { + nodesChanges = true; + } + } + for (var i = 0; i < previousSelection.edges.length; i++) { + if (currentSelection.edges.indexOf(previousSelection.edges[i]) === -1) { + edgesChanges = true; + } + } + for (var i = 0; i < currentSelection.edges.length; i++) { + if (previousSelection.edges.indexOf(previousSelection.edges[i]) === -1) { + edgesChanges = true; + } } - } - } - }; - /** - * Create the HTML DOM for the TimeAxis - */ - TimeAxis.prototype._create = function () { - this.dom.foreground = document.createElement('div'); - this.dom.background = document.createElement('div'); + return { nodesChanges: nodesChanges, edgesChanges: edgesChanges }; + } + }, { + key: 'onDragStart', - this.dom.foreground.className = 'vis-time-axis vis-foreground'; - this.dom.background.className = 'vis-time-axis vis-background'; - }; + /** + * This function is called by onDragStart. + * It is separated out because we can then overload it for the datamanipulation system. + * + * @private + */ + value: function onDragStart(event) { + //in case the touch event was triggered on an external div, do the initial touch now. + if (this.drag.pointer === undefined) { + this.onTouch(event); + } - /** - * 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); - } + // note: drag.pointer is set in onTouch to get the initial touch location + var node = this.selectionHandler.getNodeAt(this.drag.pointer); - this.body = null; - }; + this.drag.dragging = true; + this.drag.selection = []; + this.drag.translation = util.extend({}, this.body.view.translation); // copy the object + this.drag.nodeId = undefined; - /** - * Repaint the component - * @return {boolean} Returns true if the component is resized - */ - TimeAxis.prototype.redraw = function () { - var options = this.options; - var props = this.props; - var foreground = this.dom.foreground; - var background = this.dom.background; + this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer); - // determine the correct parent DOM element (depending on option orientation) - var parent = options.orientation.axis == 'top' ? this.body.dom.top : this.body.dom.bottom; - var parentChanged = foreground.parentNode !== parent; + if (node !== undefined && this.options.dragNodes === true) { + this.drag.nodeId = node.id; + // select the clicked node if not yet selected + if (node.isSelected() === false) { + this.selectionHandler.unselectAll(); + this.selectionHandler.selectObject(node); + } - // calculate character width and height - this._calculateCharSize(); + var selection = this.selectionHandler.selectionObj.nodes; + // create an array with the selected nodes and their original location and status + for (var nodeId in selection) { + if (selection.hasOwnProperty(nodeId)) { + var object = selection[nodeId]; + var s = { + id: object.id, + node: object, - // TODO: recalculate sizes only needed when parent is resized or options is changed - var showMinorLabels = this.options.showMinorLabels; - var showMajorLabels = this.options.showMajorLabels; + // store original x, y, xFixed and yFixed, make the node temporarily Fixed + x: object.x, + y: object.y, + xFixed: object.options.fixed.x, + yFixed: object.options.fixed.y + }; - // 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; + object.options.fixed.x = true; + object.options.fixed.y = true; - props.minorLineHeight = this.body.domProps.root.height - props.majorLabelHeight - (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 + this.drag.selection.push(s); + } + } + } + } + }, { + key: 'onDrag', - // 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); + /** + * handle drag event + * @private + */ + value: function onDrag(event) { + var _this2 = this; - foreground.style.height = this.props.height + 'px'; + if (this.drag.pinched === true) { + return; + } - this._repaintLabels(); + // remove the focus on node if it is focussed on by the focusOnNode + this.body.emitter.emit('unlockNode'); - // 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); - } + var pointer = this.getPointer(event.center); - return this._isResized() || parentChanged; - }; + this.selectionHandler._generateClickEvent('dragging', event, pointer); - /** - * Repaint major and minor text labels and vertical grid lines - * @private - */ - TimeAxis.prototype._repaintLabels = function () { - var orientation = this.options.orientation.axis; + var selection = this.drag.selection; + if (selection && selection.length && this.options.dragNodes === true) { + (function () { + // calculate delta's and new location + var deltaX = pointer.x - _this2.drag.pointer.x; + var deltaY = pointer.y - _this2.drag.pointer.y; - // 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) * 7).valueOf(); - var minimumStep = timeLabelsize - DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this.body.range, timeLabelsize); - minimumStep -= this.body.util.toTime(0).valueOf(); + // update position of all selected nodes + selection.forEach(function (selection) { + var node = selection.node; + // only move the node if it was not fixed initially + if (selection.xFixed === false) { + node.x = _this2.canvas._XconvertDOMtoCanvas(_this2.canvas._XconvertCanvasToDOM(selection.x) + deltaX); + } + // only move the node if it was not fixed initially + if (selection.yFixed === false) { + node.y = _this2.canvas._YconvertDOMtoCanvas(_this2.canvas._YconvertCanvasToDOM(selection.y) + deltaY); + } + }); - var step = new TimeStep(new Date(start), new Date(end), minimumStep, this.body.hiddenDates); - if (this.options.format) { - step.setFormat(this.options.format); - } - if (this.options.timeAxis) { - step.setScale(this.options.timeAxis); - } - this.step = step; + // start the simulation of the physics + _this2.body.emitter.emit('startSimulation'); + })(); + } else { + // move the network + if (this.options.dragView === true) { + // if the drag was not started properly because the click started outside the network div, start it now. + if (this.drag.pointer === undefined) { + this._handleDragStart(event); + return; + } + var diffX = pointer.x - this.drag.pointer.x; + var diffY = pointer.y - this.drag.pointer.y; - // 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 = []; + this.body.view.translation = { x: this.drag.translation.x + diffX, y: this.drag.translation.y + diffY }; + this.body.emitter.emit('_redraw'); + } + } + } + }, { + key: 'onDragEnd', - var cur; - var x = 0; - var isMajor; - var xPrev = 0; - var width = 0; - var prevLine; - var xFirstMajorLabel = undefined; - var max = 0; - var className; + /** + * handle drag start event + * @private + */ + value: function onDragEnd(event) { + this.drag.dragging = false; + var selection = this.drag.selection; + if (selection && selection.length) { + selection.forEach(function (s) { + // restore original xFixed and yFixed + s.node.options.fixed.x = s.xFixed; + s.node.options.fixed.y = s.yFixed; + }); + this.body.emitter.emit('startSimulation'); + } else { + this.body.emitter.emit('_requestRedraw'); + } + this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center)); + } + }, { + key: 'onPinch', - step.first(); - while (step.hasNext() && max < 1000) { - max++; + /** + * Handle pinch event + * @param event + * @private + */ + value: function onPinch(event) { + var pointer = this.getPointer(event.center); - cur = step.getCurrent(); - isMajor = step.isMajor(); - className = step.getClassName(); + this.drag.pinched = true; + if (this.pinch['scale'] === undefined) { + this.pinch.scale = 1; + } - xPrev = x; - x = this.body.util.toScreen(cur); - width = x - xPrev; - if (prevLine) { - prevLine.style.width = width + 'px'; + // TODO: enabled moving while pinching? + var scale = this.pinch.scale * event.scale; + this.zoom(scale, pointer); } + }, { + key: 'zoom', - if (this.options.showMinorLabels) { - this._repaintMinorText(x, step.getLabelMinor(), orientation, className); - } + /** + * Zoom the network in or out + * @param {Number} scale a number around 1, and between 0.01 and 10 + * @param {{x: Number, y: Number}} pointer Position on screen + * @return {Number} appliedScale scale is limited within the boundaries + * @private + */ + value: function zoom(scale, pointer) { + if (this.options.zoomView === true) { + var scaleOld = this.body.view.scale; + if (scale < 0.00001) { + scale = 0.00001; + } + if (scale > 10) { + scale = 10; + } + + var preScaleDragPointer = undefined; + if (this.drag !== undefined) { + if (this.drag.dragging === true) { + preScaleDragPointer = this.canvas.DOMtoCanvas(this.drag.pointer); + } + } + // + this.canvas.frame.canvas.clientHeight / 2 + var translation = this.body.view.translation; + + var scaleFrac = scale / scaleOld; + var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac; + var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac; + + this.body.view.scale = scale; + this.body.view.translation = { x: tx, y: ty }; + + if (preScaleDragPointer != undefined) { + var postScaleDragPointer = this.canvas.canvasToDOM(preScaleDragPointer); + this.drag.pointer.x = postScaleDragPointer.x; + this.drag.pointer.y = postScaleDragPointer.y; + } + + this.body.emitter.emit('_requestRedraw'); - if (isMajor && this.options.showMajorLabels) { - if (x > 0) { - if (xFirstMajorLabel == undefined) { - xFirstMajorLabel = x; + if (scaleOld < scale) { + this.body.emitter.emit('zoom', { direction: '+', scale: this.body.view.scale }); + } else { + this.body.emitter.emit('zoom', { direction: '-', scale: this.body.view.scale }); } - this._repaintMajorText(x, step.getLabelMajor(), orientation, className); } - prevLine = this._repaintMajorLine(x, orientation, className); - } else { - prevLine = this._repaintMinorLine(x, orientation, className); } + }, { + key: 'onMouseWheel', - step.next(); - } + /** + * Event handler for mouse wheel event, used to zoom the timeline + * See http://adomas.org/javascript-mouse-wheel/ + * https://github.com/EightMedia/hammer.js/issues/256 + * @param {MouseEvent} event + * @private + */ + value: function onMouseWheel(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; + } - // 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 delta is nonzero, handle it. + // Basically, delta is now positive if wheel was scrolled up, + // and negative, if wheel was scrolled down. + if (delta !== 0) { - if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) { - this._repaintMajorText(0, leftText, orientation, className); - } - } + // calculate the new scale + var scale = this.body.view.scale; + var zoom = delta / 10; + if (delta < 0) { + zoom = zoom / (1 - zoom); + } + scale *= 1 + zoom; - // 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); + // calculate the pointer location + var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); + + // apply the new scale + this.zoom(scale, pointer); } + + // Prevent default actions caused by mouse wheel. + event.preventDefault(); } - }); - }; + }, { + key: 'onMouseMove', - /** - * 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 - * @private - */ - TimeAxis.prototype._repaintMinorText = function (x, text, orientation, className) { - // reuse redundant label - var label = this.dom.redundant.minorTexts.shift(); + /** + * Mouse move handler for checking whether the title moves over a node with a title. + * @param {Event} event + * @private + */ + value: function onMouseMove(event) { + var _this3 = this; - 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); + var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); + var popupVisible = false; - label.childNodes[0].nodeValue = text; + // check if the previously selected node is still selected + if (this.popup !== undefined) { + if (this.popup.hidden === false) { + this._checkHidePopup(pointer); + } - label.style.top = orientation == 'top' ? this.props.majorLabelHeight + 'px' : '0'; - label.style.left = x + 'px'; - label.className = 'vis-text vis-minor ' + className; - //label.title = title; // TODO: this is a heavy operation - }; + // if the popup was not hidden above + if (this.popup.hidden === false) { + popupVisible = true; + this.popup.setPosition(pointer.x + 3, pointer.y - 5); + this.popup.show(); + } + } - /** - * 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 - * @private - */ - TimeAxis.prototype._repaintMajorText = function (x, text, orientation, className) { - // reuse redundant label - var label = this.dom.redundant.majorTexts.shift(); + // if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over. + if (this.options.keyboard.bindToWindow === false && this.options.keyboard.enabled === true) { + this.canvas.frame.focus(); + } - if (!label) { - // create label - var content = document.createTextNode(text); - label = document.createElement('div'); - label.appendChild(content); - this.dom.foreground.appendChild(label); - } - this.dom.majorTexts.push(label); + // start a timeout that will check if the mouse is positioned above an element + if (popupVisible === false) { + if (this.popupTimer !== undefined) { + clearInterval(this.popupTimer); // stop any running calculationTimer + this.popupTimer = undefined; + } + if (!this.drag.dragging) { + this.popupTimer = setTimeout(function () { + return _this3._checkShowPopup(pointer); + }, this.options.tooltipDelay); + } + } - label.childNodes[0].nodeValue = text; - label.className = 'vis-text vis-major ' + className; - //label.title = title; // TODO: this is a heavy operation + /** + * Adding hover highlights + */ + if (this.options.hover === true) { + // adding hover highlights + var obj = this.selectionHandler.getNodeAt(pointer); + if (obj === undefined) { + obj = this.selectionHandler.getEdgeAt(pointer); + } + this.selectionHandler.hoverObject(obj); + } + } + }, { + key: '_checkShowPopup', - label.style.top = orientation == 'top' ? '0' : this.props.minorLabelHeight + 'px'; - label.style.left = x + 'px'; - }; + /** + * Check if there is an element on the given position in the network + * (a node or edge). If so, and if this element has a title, + * show a popup window with its title. + * + * @param {{x:Number, y:Number}} pointer + * @private + */ + value: function _checkShowPopup(pointer) { + var x = this.canvas._XconvertDOMtoCanvas(pointer.x); + var y = this.canvas._YconvertDOMtoCanvas(pointer.y); + var pointerObj = { + left: x, + top: y, + right: x, + bottom: y + }; - /** - * Create a minor line for the axis at position x - * @param {Number} x - * @param {String} orientation "top" or "bottom" (default) - * @param {String} className - * @return {Element} Returns the created line - * @private - */ - TimeAxis.prototype._repaintMinorLine = function (x, 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 previousPopupObjId = this.popupObj === undefined ? undefined : this.popupObj.id; + var nodeUnderCursor = false; + var popupType = 'node'; - 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'; - line.style.left = x - props.minorLineWidth / 2 + 'px'; + // check if a node is under the cursor. + if (this.popupObj === undefined) { + // search the nodes for overlap, select the top one in case of multiple nodes + var nodeIndices = this.body.nodeIndices; + var nodes = this.body.nodes; + var node = undefined; + var overlappingNodes = []; + for (var i = 0; i < nodeIndices.length; i++) { + node = nodes[nodeIndices[i]]; + if (node.isOverlappingWith(pointerObj) === true) { + if (node.getTitle() !== undefined) { + overlappingNodes.push(nodeIndices[i]); + } + } + } - line.className = 'vis-grid vis-vertical vis-minor ' + className; + if (overlappingNodes.length > 0) { + // if there are overlapping nodes, select the last one, this is the one which is drawn on top of the others + this.popupObj = nodes[overlappingNodes[overlappingNodes.length - 1]]; + // if you hover over a node, the title of the edge is not supposed to be shown. + nodeUnderCursor = true; + } + } - return line; - }; + if (this.popupObj === undefined && nodeUnderCursor === false) { + // search the edges for overlap + var edgeIndices = this.body.edgeIndices; + var edges = this.body.edges; + var edge = undefined; + var overlappingEdges = []; + for (var i = 0; i < edgeIndices.length; i++) { + edge = edges[edgeIndices[i]]; + if (edge.isOverlappingWith(pointerObj) === true) { + if (edge.connected === true && edge.getTitle() !== undefined) { + overlappingEdges.push(edgeIndices[i]); + } + } + } - /** - * Create a Major line for the axis at position x - * @param {Number} x - * @param {String} orientation "top" or "bottom" (default) - * @param {String} className - * @return {Element} Returns the created line - * @private - */ - TimeAxis.prototype._repaintMajorLine = function (x, 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); + if (overlappingEdges.length > 0) { + this.popupObj = edges[overlappingEdges[overlappingEdges.length - 1]]; + popupType = 'edge'; + } + } - var props = this.props; - if (orientation == 'top') { - line.style.top = '0'; - } else { - line.style.top = this.body.domProps.top.height + 'px'; - } - line.style.left = x - props.majorLineWidth / 2 + 'px'; - line.style.height = props.majorLineHeight + 'px'; + if (this.popupObj !== undefined) { + // show popup message window + if (this.popupObj.id !== previousPopupObjId) { + if (this.popup === undefined) { + this.popup = new _componentsPopup2['default'](this.canvas.frame); + } - line.className = 'vis-grid vis-vertical vis-major ' + className; + this.popup.popupTargetType = popupType; + this.popup.popupTargetId = this.popupObj.id; - return line; - }; + // adjust a small offset such that the mouse cursor is located in the + // bottom left location of the popup, and you can easily move over the + // popup area + this.popup.setPosition(pointer.x + 3, pointer.y - 5); + this.popup.setText(this.popupObj.getTitle()); + this.popup.show(); + this.body.emitter.emit('showPopup', this.popupObj.id); + } + } else { + if (this.popup !== undefined) { + this.popup.hide(); + this.body.emitter.emit('hidePopup'); + } + } + } + }, { + key: '_checkHidePopup', - /** - * 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. + /** + * Check if the popup must be hidden, which is the case when the mouse is no + * longer hovering on the object + * @param {{x:Number, y:Number}} pointer + * @private + */ + value: function _checkHidePopup(pointer) { + var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); - // 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'; + var stillOnObj = false; + if (this.popup.popupTargetType === 'node') { + if (this.body.nodes[this.popup.popupTargetId] !== undefined) { + stillOnObj = this.body.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj); - 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; + // if the mouse is still one the node, we have to check if it is not also on one that is drawn on top of it. + // we initially only check stillOnObj because this is much faster. + if (stillOnObj === true) { + var overNode = this.selectionHandler.getNodeAt(pointer); + stillOnObj = overNode.id === this.popup.popupTargetId; + } + } + } else { + if (this.selectionHandler.getNodeAt(pointer) === undefined) { + if (this.body.edges[this.popup.popupTargetId] !== undefined) { + stillOnObj = this.body.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj); + } + } + } - // 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'; + if (stillOnObj === false) { + this.popupObj = undefined; + this.popup.hide(); + this.body.emitter.emit('hidePopup'); + } + } + }]); - 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; - }; + return InteractionHandler; + })(); - module.exports = TimeAxis; + exports['default'] = InteractionHandler; + module.exports = exports['default']; /***/ }, -/* 49 */ +/* 63 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; + "use strict"; - var keycharm = __webpack_require__(50); - var Emitter = __webpack_require__(27); - var Hammer = __webpack_require__(13); - var util = __webpack_require__(2); + Object.defineProperty(exports, "__esModule", { + value: true + }); - /** - * 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 - */ - function Activator(container) { - this.active = false; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - this.dom = { - container: container - }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - this.dom.overlay = document.createElement('div'); - this.dom.overlay.className = 'vis-overlay'; + var Node = __webpack_require__(74); + var Edge = __webpack_require__(76); + var util = __webpack_require__(2); - this.dom.container.appendChild(this.dom.overlay); + var SelectionHandler = (function () { + function SelectionHandler(body, canvas) { + var _this = this; - this.hammer = Hammer(this.dom.overlay); - this.hammer.on('tap', this._onTapOverlay.bind(this)); + _classCallCheck(this, SelectionHandler); - // 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(); - }); - }); + this.body = body; + this.canvas = canvas; + this.selectionObj = { nodes: [], edges: [] }; + this.hoverObj = { nodes: {}, edges: {} }; - // attach a tap event to the window, in order to deactivate when clicking outside the timeline - this.bodyHammer = Hammer(document && document.body, { prevent_default: false }); - this.bodyHammer.on('tap', function (event) { - // deactivate when clicked outside the container - if (!_hasParent(event.target, container)) { - me.deactivate(); - } - }); + this.options = {}; + this.defaultOptions = { + multiselect: false, + selectable: true, + selectConnectedEdges: true, + hoverConnectedEdges: true + }; + util.extend(this.options, this.defaultOptions); - if (this.keycharm !== undefined) { - this.keycharm.destroy(); + this.body.emitter.on("_dataChanged", function () { + _this.updateSelection(); + }); } - 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(); + _createClass(SelectionHandler, [{ + key: "setOptions", + value: function setOptions(options) { + if (options !== undefined) { + var fields = ["multiselect", "hoverConnectedEdges", "selectable", "selectConnectedEdges"]; + util.selectiveDeepExtend(fields, this.options, options); + } + } + }, { + key: "selectOnPoint", - // remove dom - this.dom.overlay.parentNode.removeChild(this.dom.overlay); + /** + * handles the selection part of the tap; + * + * @param {Object} pointer + * @private + */ + value: function selectOnPoint(pointer) { + var selected = false; + if (this.options.selectable === true) { + this.unselectAll(); + var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer); + if (obj !== undefined) { + selected = this.selectObject(obj); + } + this.body.emitter.emit("_requestRedraw"); + } + return selected; + } + }, { + key: "selectAdditionalOnPoint", + value: function selectAdditionalOnPoint(pointer) { + var selectionChanged = false; + if (this.options.selectable === true) { + var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer); - // cleanup hammer instances - this.hammer = null; - this.bodyHammer = null; - // FIXME: cleaning up hammer instances doesn't work (Timeline not removed from memory) - }; + if (obj !== undefined) { + selectionChanged = true; + if (obj.isSelected() === true) { + this.deselectObject(obj); + } else { + this.selectObject(obj); + } - /** - * 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.body.emitter.emit("_requestRedraw"); + } + } + return selectionChanged; + } + }, { + key: "_generateClickEvent", + value: function _generateClickEvent(eventType, event, pointer, oldSelection) { + var properties = this.getSelection(); + properties["pointer"] = { + DOM: { x: pointer.x, y: pointer.y }, + canvas: this.canvas.DOMtoCanvas(pointer) + }; + properties["event"] = event; - this.active = true; - this.dom.overlay.style.display = 'none'; - util.addClassName(this.dom.container, 'vis-active'); + if (oldSelection !== undefined) { + properties["previousSelection"] = oldSelection; + } + this.body.emitter.emit(eventType, properties); + } + }, { + key: "selectObject", + value: function selectObject(obj) { + var highlightEdges = arguments[1] === undefined ? this.options.selectConnectedEdges : arguments[1]; - this.emit('change'); - this.emit('activate'); + if (obj !== undefined) { + if (obj instanceof Node) { + if (highlightEdges === true) { + this._selectConnectedEdges(obj); + } + } + obj.select(); + this._addToSelection(obj); + return true; + } + return false; + } + }, { + key: "deselectObject", + value: function deselectObject(obj) { + if (obj.isSelected() === true) { + obj.selected = false; + this._removeFromSelection(obj); + } + } + }, { + key: "_getAllNodesOverlappingWith", - // 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); - }; + /** + * retrieve all nodes overlapping with given object + * @param {Object} object An object with parameters left, top, right, bottom + * @return {Number[]} An array with id's of the overlapping nodes + * @private + */ + value: function _getAllNodesOverlappingWith(object) { + var overlappingNodes = []; + var nodes = this.body.nodes; + for (var i = 0; i < this.body.nodeIndices.length; i++) { + var nodeId = this.body.nodeIndices[i]; + if (nodes[nodeId].isOverlappingWith(object)) { + overlappingNodes.push(nodeId); + } + } + return overlappingNodes; + } + }, { + key: "_pointerToPositionObject", - /** - * 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); + /** + * Return a position object in canvasspace from a single point in screenspace + * + * @param pointer + * @returns {{left: number, top: number, right: number, bottom: number}} + * @private + */ + value: function _pointerToPositionObject(pointer) { + var canvasPos = this.canvas.DOMtoCanvas(pointer); + return { + left: canvasPos.x - 1, + top: canvasPos.y + 1, + right: canvasPos.x + 1, + bottom: canvasPos.y - 1 + }; + } + }, { + key: "getNodeAt", - this.emit('change'); - this.emit('deactivate'); - }; + /** + * Get the top node at the a specific point (like a click) + * + * @param {{x: Number, y: Number}} pointer + * @return {Node | undefined} node + * @private + */ + value: function getNodeAt(pointer) { + var returnNode = arguments[1] === undefined ? true : arguments[1]; - /** - * Handle a tap event: activate the container - * @param event - * @private - */ - Activator.prototype._onTapOverlay = function (event) { - // activate the container - this.activate(); - event.stopPropagation(); - }; + // we first check if this is an navigation controls element + var positionObject = this._pointerToPositionObject(pointer); + var overlappingNodes = this._getAllNodesOverlappingWith(positionObject); + // if there are overlapping nodes, select the last one, this is the + // one which is drawn on top of the others + if (overlappingNodes.length > 0) { + if (returnNode === true) { + return this.body.nodes[overlappingNodes[overlappingNodes.length - 1]]; + } else { + return overlappingNodes[overlappingNodes.length - 1]; + } + } else { + return undefined; + } + } + }, { + key: "_getEdgesOverlappingWith", - /** - * 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; + /** + * retrieve all edges overlapping with given object, selector is around center + * @param {Object} object An object with parameters left, top, right, bottom + * @return {Number[]} An array with id's of the overlapping nodes + * @private + */ + value: function _getEdgesOverlappingWith(object, overlappingEdges) { + var edges = this.body.edges; + for (var i = 0; i < this.body.edgeIndices.length; i++) { + var edgeId = this.body.edgeIndices[i]; + if (edges[edgeId].isOverlappingWith(object)) { + overlappingEdges.push(edgeId); + } + } } - element = element.parentNode; - } - return false; - } + }, { + key: "_getAllEdgesOverlappingWith", - module.exports = Activator; + /** + * retrieve all nodes overlapping with given object + * @param {Object} object An object with parameters left, top, right, bottom + * @return {Number[]} An array with id's of the overlapping nodes + * @private + */ + value: function _getAllEdgesOverlappingWith(object) { + var overlappingEdges = []; + this._getEdgesOverlappingWith(object, overlappingEdges); + return overlappingEdges; + } + }, { + key: "getEdgeAt", -/***/ }, -/* 50 */ -/***/ function(module, exports, __webpack_require__) { + /** + * Place holder. To implement change the getNodeAt to a _getObjectAt. Have the _getObjectAt call + * getNodeAt and _getEdgesAt, then priortize the selection to user preferences. + * + * @param pointer + * @returns {undefined} + * @private + */ + value: function getEdgeAt(pointer) { + var returnEdge = arguments[1] === undefined ? true : arguments[1]; - var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict"; - /** - * Created by Alex on 11/6/2014. - */ + var positionObject = this._pointerToPositionObject(pointer); + var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject); - // 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 () { + if (overlappingEdges.length > 0) { + if (returnEdge === true) { + return this.body.edges[overlappingEdges[overlappingEdges.length - 1]]; + } else { + return overlappingEdges[overlappingEdges.length - 1]; + } + } else { + return undefined; + } + } + }, { + key: "_addToSelection", - function keycharm(options) { - var preventDefault = options && options.preventDefault || false; + /** + * Add object to the selection array. + * + * @param obj + * @private + */ + value: function _addToSelection(obj) { + if (obj instanceof Node) { + this.selectionObj.nodes[obj.id] = obj; + } else { + this.selectionObj.edges[obj.id] = obj; + } + } + }, { + key: "_addToHover", - var container = options && options.container || window; + /** + * Add object to the selection array. + * + * @param obj + * @private + */ + value: function _addToHover(obj) { + if (obj instanceof Node) { + this.hoverObj.nodes[obj.id] = obj; + } else { + this.hoverObj.edges[obj.id] = obj; + } + } + }, { + key: "_removeFromSelection", - var _exportFunctions = {}; - var _bound = {keydown:{}, keyup:{}}; - var _keys = {}; - var i; + /** + * Remove a single option from selection. + * + * @param {Object} obj + * @private + */ + value: function _removeFromSelection(obj) { + if (obj instanceof Node) { + delete this.selectionObj.nodes[obj.id]; + } else { + delete this.selectionObj.edges[obj.id]; + } + } + }, { + key: "unselectAll", - // 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};} + /** + * Unselect all. The selectionObj is useful for this. + * + * @private + */ + value: function unselectAll() { + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + this.selectionObj.nodes[nodeId].unselect(); + } + } + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + this.selectionObj.edges[edgeId].unselect(); + } + } - // 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}; + this.selectionObj = { nodes: {}, edges: {} }; + } + }, { + key: "_getSelectedNodeCount", + /** + * return the number of selected nodes + * + * @returns {number} + * @private + */ + value: function _getSelectedNodeCount() { + var count = 0; + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + count += 1; + } + } + return count; + } + }, { + key: "_getSelectedNode", + /** + * return the selected node + * + * @returns {number} + * @private + */ + value: function _getSelectedNode() { + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + return this.selectionObj.nodes[nodeId]; + } + } + return undefined; + } + }, { + key: "_getSelectedEdge", - var down = function(event) {handleEvent(event,'keydown');}; - var up = function(event) {handleEvent(event,'keyup');}; + /** + * return the selected edge + * + * @returns {number} + * @private + */ + value: function _getSelectedEdge() { + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + return this.selectionObj.edges[edgeId]; + } + } + return undefined; + } + }, { + key: "_getSelectedEdgeCount", - // 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); - } + /** + * return the number of selected edges + * + * @returns {number} + * @private + */ + value: function _getSelectedEdgeCount() { + var count = 0; + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + count += 1; } + } + return count; + } + }, { + key: "_getSelectedObjectCount", - if (preventDefault == true) { - event.preventDefault(); + /** + * return the number of selected objects. + * + * @returns {number} + * @private + */ + value: function _getSelectedObjectCount() { + var count = 0; + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + count += 1; } } - }; + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + count += 1; + } + } + return count; + } + }, { + key: "_selectionIsEmpty", - // bind a key to a callback - _exportFunctions.bind = function(key, callback, type) { - if (type === undefined) { - type = 'keydown'; + /** + * Check if anything is selected + * + * @returns {boolean} + * @private + */ + value: function _selectionIsEmpty() { + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + return false; + } } - if (_keys[key] === undefined) { - throw new Error("unsupported key: " + key); + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + return false; + } } - if (_bound[type][_keys[key].code] === undefined) { - _bound[type][_keys[key].code] = []; + return true; + } + }, { + key: "_clusterInSelection", + + /** + * check if one of the selected nodes is a cluster. + * + * @returns {boolean} + * @private + */ + value: function _clusterInSelection() { + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + if (this.selectionObj.nodes[nodeId].clusterSize > 1) { + return true; + } + } + } + return false; + } + }, { + key: "_selectConnectedEdges", + + /** + * select the edges connected to the node that is being selected + * + * @param {Node} node + * @private + */ + value: function _selectConnectedEdges(node) { + for (var i = 0; i < node.edges.length; i++) { + var edge = node.edges[i]; + edge.select(); + this._addToSelection(edge); } - _bound[type][_keys[key].code].push({fn:callback, shift:_keys[key].shift}); - }; + } + }, { + key: "_hoverConnectedEdges", + /** + * select the edges connected to the node that is being selected + * + * @param {Node} node + * @private + */ + value: function _hoverConnectedEdges(node) { + for (var i = 0; i < node.edges.length; i++) { + var edge = node.edges[i]; + edge.hover = true; + this._addToHover(edge); + } + } + }, { + key: "_unselectConnectedEdges", - // bind all keys to a call back (demo purposes) - _exportFunctions.bindAll = function(callback, type) { - if (type === undefined) { - type = 'keydown'; + /** + * unselect the edges connected to the node that is being selected + * + * @param {Node} node + * @private + */ + value: function _unselectConnectedEdges(node) { + for (var i = 0; i < node.edges.length; i++) { + var edge = node.edges[i]; + edge.unselect(); + this._removeFromSelection(edge); } - for (var key in _keys) { - if (_keys.hasOwnProperty(key)) { - _exportFunctions.bind(key,callback,type); - } + } + }, { + key: "blurObject", + + /** + * This is called when someone clicks on a node. either select or deselect it. + * If there is an existing selection and we don't want to append to it, clear the existing selection + * + * @param {Node || Edge} object + * @private + */ + value: function blurObject(object) { + if (object.hover === true) { + object.hover = false; + this.body.emitter.emit("blurNode", { node: object.id }); } - }; + } + }, { + key: "hoverObject", - // 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; + /** + * This is called when someone clicks on a node. either select or deselect it. + * If there is an existing selection and we don't want to append to it, clear the existing selection + * + * @param {Node || Edge} object + * @private + */ + value: function hoverObject(object) { + var hoverChanged = false; + // remove all node hover highlights + for (var nodeId in this.hoverObj.nodes) { + if (this.hoverObj.nodes.hasOwnProperty(nodeId)) { + if (object === undefined) { + this.blurObject(this.hoverObj.nodes[nodeId]); + hoverChanged = true; + } else if (object instanceof Node && object.id != nodeId || object instanceof Edge || object === undefined) { + this.blurObject(this.hoverObj.nodes[nodeId]); + hoverChanged = true; + delete this.hoverObj.nodes[nodeId]; } } } - 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); + // removing all edge hover highlights + for (var edgeId in this.hoverObj.edges) { + if (this.hoverObj.edges.hasOwnProperty(edgeId)) { + this.hoverObj.edges[edgeId].hover = false; + delete this.hoverObj.edges[edgeId]; + } } - 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]); - } + + if (object !== undefined) { + if (object.hover === false) { + object.hover = true; + this._addToHover(object); + hoverChanged = true; + if (object instanceof Node) { + this.body.emitter.emit("hoverNode", { node: object.id }); } } - _bound[type][_keys[key].code] = newBindings; - } - else { - _bound[type][_keys[key].code] = []; + if (object instanceof Node && this.options.hoverConnectedEdges === true) { + this._hoverConnectedEdges(object); + } } - }; - - // 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; - })); - - - - -/***/ }, -/* 51 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var Hammer = __webpack_require__(13); - var util = __webpack_require__(2); - var Component = __webpack_require__(35); - var moment = __webpack_require__(17); - var locales = __webpack_require__(36); - - /** - * 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 = { - locales: locales, - locale: 'en', - id: 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(['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'; - 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)); - // TODO: cleanup - //this.hammer.on('pan', function (event) { - // event.preventDefault(); - //}); - }; - - /** - * 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); + if (hoverChanged === true) { + this.body.emitter.emit("_requestRedraw"); + } } - parent.appendChild(this.bar); - } - - var x = this.body.util.toScreen(this.customTime); + }, { + key: "getSelection", - 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.html#Localization'); - this.warned = true; + /** + * + * retrieve the currently selected objects + * @return {{nodes: Array., edges: Array.}} selection + */ + value: function getSelection() { + var nodeIds = this.getSelectedNodes(); + var edgeIds = this.getSelectedEdges(); + return { nodes: nodeIds, edges: edgeIds }; } - locale = this.options.locales['en']; // fall back on english when not available - } - var title = locale.time + ': ' + moment(this.customTime).format('dddd, MMMM Do YYYY, H:mm:ss'); - title = title.charAt(0).toUpperCase() + title.substring(1); - - this.bar.style.left = x + 'px'; - this.bar.title = title; - - return false; - }; + }, { + key: "getSelectedNodes", - /** - * 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); - } - }; + /** + * + * retrieve the currently selected nodes + * @return {String[]} selection An array with the ids of the + * selected nodes. + */ + value: function getSelectedNodes() { + var idArray = []; + if (this.options.selectable === true) { + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + idArray.push(nodeId); + } + } + } + return idArray; + } + }, { + key: "getSelectedEdges", - /** - * Set custom time. - * @param {Date | number | string} time - */ - CustomTime.prototype.setCustomTime = function (time) { - this.customTime = util.convert(time, 'Date'); - this.redraw(); - }; + /** + * + * retrieve the currently selected edges + * @return {Array} selection An array with the ids of the + * selected nodes. + */ + value: function getSelectedEdges() { + var idArray = []; + if (this.options.selectable === true) { + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + idArray.push(edgeId); + } + } + } + return idArray; + } + }, { + key: "selectNodes", - /** - * Retrieve the current custom time. - * @return {Date} customTime - */ - CustomTime.prototype.getCustomTime = function () { - return new Date(this.customTime.valueOf()); - }; + /** + * select zero or more nodes with the option to highlight edges + * @param {Number[] | String[]} selection An array with the ids of the + * selected nodes. + * @param {boolean} [highlightEdges] + */ + value: function selectNodes(selection) { + var highlightEdges = arguments[1] === undefined ? true : arguments[1]; - /** - * Start moving horizontally - * @param {Event} event - * @private - */ - CustomTime.prototype._onDragStart = function (event) { - this.eventParams.dragging = true; - this.eventParams.customTime = this.customTime; + var i = undefined, + id = undefined; - event.stopPropagation(); - }; + if (!selection || selection.length === undefined) throw "Selection must be an array with ids"; - /** - * Perform moving operating. - * @param {Event} event - * @private - */ - CustomTime.prototype._onDrag = function (event) { - if (!this.eventParams.dragging) return; + // first unselect any selected node + this.unselectAll(); - var x = this.body.util.toScreen(this.eventParams.customTime) + event.deltaX; - var time = this.body.util.toTime(x); + for (i = 0; i < selection.length; i++) { + id = selection[i]; - this.setCustomTime(time); + var node = this.body.nodes[id]; + if (!node) { + throw new RangeError("Node with id \"" + id + "\" not found"); + } + this.selectObject(node, highlightEdges); + } + this.body.emitter.emit("_requestRedraw"); + } + }, { + key: "selectEdges", - // fire a timechange event - this.body.emitter.emit('timechange', { - id: this.options.id, - time: new Date(this.customTime.valueOf()) - }); + /** + * select zero or more edges + * @param {Number[] | String[]} selection An array with the ids of the + * selected nodes. + */ + value: function selectEdges(selection) { + var i = undefined, + id = undefined; - event.stopPropagation(); - }; + if (!selection || selection.length === undefined) throw "Selection must be an array with ids"; - /** - * Stop moving operating. - * @param {Event} event - * @private - */ - CustomTime.prototype._onDragEnd = function (event) { - if (!this.eventParams.dragging) return; + // first unselect any selected objects + this.unselectAll(); - // fire a timechanged event - this.body.emitter.emit('timechanged', { - id: this.options.id, - time: new Date(this.customTime.valueOf()) - }); + for (i = 0; i < selection.length; i++) { + id = selection[i]; - event.stopPropagation(); - }; + var edge = this.body.edges[id]; + if (!edge) { + throw new RangeError("Edge with id \"" + id + "\" not found"); + } + this.selectObject(edge); + } + this.body.emitter.emit("_requestRedraw"); + } + }, { + key: "updateSelection", - /** - * 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']; + /** + * Validate the selection: remove ids of nodes which no longer exist + * @private + */ + value: function updateSelection() { + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + if (!this.body.nodes.hasOwnProperty(nodeId)) { + delete this.selectionObj.nodes[nodeId]; + } + } + } + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + if (!this.body.edges.hasOwnProperty(edgeId)) { + delete this.selectionObj.edges[edgeId]; + } + } + } } - target = target.parentNode; - } + }]); - return null; - }; + return SelectionHandler; + })(); - module.exports = CustomTime; + exports["default"] = SelectionHandler; + module.exports = exports["default"]; /***/ }, -/* 52 */ +/* 64 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -25290,1574 +25880,1708 @@ return /******/ (function(modules) { // webpackBootstrap value: true }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - var _ColorPicker = __webpack_require__(53); - - var _ColorPicker2 = _interopRequireDefault(_ColorPicker); - - var util = __webpack_require__(2); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /** - * 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 - * - * @param parentModule | the location where parentModule.setOptions() can be called - * @param defaultContainer | the default container of the module - * @param configureOptions | the fully configured and predefined options set found in allOptions.js - * @param pixelRatio | canvas pixel ratio - */ + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var Configurator = (function () { - function Configurator(parentModule, defaultContainer, configureOptions) { - var pixelRatio = arguments[3] === undefined ? 1 : arguments[3]; + var util = __webpack_require__(2); - _classCallCheck(this, Configurator); + var LayoutEngine = (function () { + function LayoutEngine(body) { + _classCallCheck(this, LayoutEngine); - this.parent = parentModule; - this.changedOptions = []; - this.container = defaultContainer; - this.allowCreation = false; + this.body = body; + this.initialRandomSeed = Math.round(Math.random() * 1000000); + this.randomSeed = this.initialRandomSeed; this.options = {}; + this.optionsBackup = {}; + this.defaultOptions = { - enabled: false, - filter: true, - container: undefined, - showButton: true + randomSeed: undefined, + hierarchical: { + enabled: false, + levelSeparation: 150, + direction: 'UD', // UD, DU, LR, RL + sortMethod: 'hubsize' // hubsize, directed + } }; util.extend(this.options, this.defaultOptions); - this.configureOptions = configureOptions; - this.moduleOptions = {}; - this.domElements = []; - this.colorPicker = new _ColorPicker2['default'](pixelRatio); - this.wrapper = undefined; + this.hierarchicalLevels = {}; + + this.bindEventListeners(); } - _createClass(Configurator, [{ - key: 'setOptions', + _createClass(LayoutEngine, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this = this; - /** - * refresh all options. - * Because all modules parse their options by themselves, we just use their options. We copy them here. - * - * @param options - */ - value: function setOptions(options) { + this.body.emitter.on('_dataChanged', function () { + _this.setupHierarchicalLayout(); + }); + this.body.emitter.on('_resetHierarchicalLayout', function () { + _this.setupHierarchicalLayout(); + }); + } + }, { + key: 'setOptions', + value: function setOptions(options, allOptions) { if (options !== undefined) { - 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 === 'object') { - if (options.container !== undefined) { - this.options.container = options.container; + var prevHierarchicalState = this.options.hierarchical.enabled; + + util.mergeOptions(this.options, options, 'hierarchical'); + if (options.randomSeed !== undefined) { + this.initialRandomSeed = options.randomSeed; + } + + if (this.options.hierarchical.enabled === true) { + // make sure the level seperation is the right way up + if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'DU') { + if (this.options.hierarchical.levelSeparation > 0) { + this.options.hierarchical.levelSeparation *= -1; + } + } else { + if (this.options.hierarchical.levelSeparation < 0) { + this.options.hierarchical.levelSeparation *= -1; + } } - if (options.filter !== undefined) { - this.options.filter = options.filter; + + this.body.emitter.emit('_resetHierarchicalLayout'); + // because the hierarchical system needs it's own physics and smooth curve settings, we adapt the other options if needed. + return this.adaptAllOptions(allOptions); + } else { + if (prevHierarchicalState === true) { + // refresh the overridden options for nodes and edges. + this.body.emitter.emit('refresh'); + return util.deepExtend(allOptions, this.optionsBackup); } - if (options.showButton !== undefined) { - this.options.showButton = options.showButton; + } + } + return allOptions; + } + }, { + key: 'adaptAllOptions', + value: function adaptAllOptions(allOptions) { + if (this.options.hierarchical.enabled === true) { + // set the physics + if (allOptions.physics === undefined || allOptions.physics === true) { + allOptions.physics = { solver: 'hierarchicalRepulsion' }; + this.optionsBackup.physics = { solver: 'barnesHut' }; + } else if (typeof allOptions.physics === 'object') { + this.optionsBackup.physics = { solver: 'barnesHut' }; + if (allOptions.physics.solver !== undefined) { + this.optionsBackup.physics = { solver: allOptions.physics.solver }; } - if (options.enabled !== undefined) { - enabled = options.enabled; + allOptions.physics['solver'] = 'hierarchicalRepulsion'; + } else if (allOptions.physics !== false) { + this.optionsBackup.physics = { solver: 'barnesHut' }; + allOptions.physics['solver'] = 'hierarchicalRepulsion'; + } + + // get the type of static smooth curve in case it is required + var type = 'horizontal'; + if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'LR') { + type = 'vertical'; + } + + // disable smooth curves if nothing is defined. If smooth curves have been turned on, turn them into static smooth curves. + if (allOptions.edges === undefined) { + this.optionsBackup.edges = { smooth: { enabled: true, type: 'dynamic' } }; + allOptions.edges = { smooth: false }; + } else if (allOptions.edges.smooth === undefined) { + this.optionsBackup.edges = { smooth: { enabled: true, type: 'dynamic' } }; + allOptions.edges.smooth = false; + } else { + if (typeof allOptions.edges.smooth === 'boolean') { + this.optionsBackup.edges = { smooth: allOptions.edges.smooth }; + allOptions.edges.smooth = { enabled: allOptions.edges.smooth, type: type }; + } else { + // allow custom types except for dynamic + if (allOptions.edges.smooth.type !== undefined && allOptions.edges.smooth.type !== 'dynamic') { + type = allOptions.edges.smooth.type; + } + + this.optionsBackup.edges = { + smooth: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled, + type: allOptions.edges.smooth.type === undefined ? 'dynamic' : allOptions.edges.smooth.type, + roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness + }; + allOptions.edges.smooth = { + enabled: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled, + type: type, + roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness + }; } - } else if (typeof options === 'boolean') { - this.options.filter = true; - enabled = options; - } else if (typeof options === 'function') { - this.options.filter = options; - enabled = true; } - this.options.enabled = enabled; + + // force all edges into static smooth curves. Only applies to edges that do not use the global options for smooth. + this.body.emitter.emit('_forceDisableDynamicCurves', type); } - this._clean(); + return allOptions; } }, { - 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; + key: 'seededRandom', + value: function seededRandom() { + var x = Math.sin(this.randomSeed++) * 10000; + return x - Math.floor(x); + } + }, { + key: 'positionInitially', + value: function positionInitially(nodesArray) { + if (this.options.hierarchical.enabled !== true) { + this.randomSeed = this.initialRandomSeed; + for (var i = 0; i < nodesArray.length; i++) { + var node = nodesArray[i]; + if (!node.isFixed() && (node.x === undefined || node.y === undefined)) { + var radius = 10 * 0.1 * nodesArray.length + 10; + var angle = 2 * Math.PI * this.seededRandom(); + if (node.options.fixed.x === false) { + node.x = radius * Math.cos(angle); + } + if (node.options.fixed.x === false) { + node.y = radius * Math.sin(angle); + } + } } - this._create(); } } }, { - key: '_create', + key: 'getSeed', + value: function getSeed() { + return this.initialRandomSeed; + } + }, { + key: 'setupHierarchicalLayout', /** - * Create all DOM elements + * This is the main function to layout the nodes in a hierarchical way. + * It checks if the node details are supplied correctly + * * @private */ - value: function _create() { - var _this = this; - - this._clean(); - this.changedOptions = []; + value: function setupHierarchicalLayout() { + if (this.options.hierarchical.enabled === true && this.body.nodeIndices.length > 0) { + // get the size of the largest hubs and check if the user has defined a level for a node. + var node = undefined, + nodeId = undefined; + var definedLevel = false; + var undefinedLevel = false; + this.hierarchicalLevels = {}; + this.nodeSpacing = 100; - 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; + for (nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + node = this.body.nodes[nodeId]; + if (node.options.level !== undefined) { + definedLevel = true; + this.hierarchicalLevels[nodeId] = node.options.level; + } else { + undefinedLevel = true; + } } + } - if (show !== false) { - this.allowCreation = true; + // if the user defined some levels but not all, alert and run without hierarchical layout + if (undefinedLevel === true && definedLevel === true) { + throw new Error('To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.'); + return; + } else { + // setup the system to use hierarchical method. + //this._changeConstants(); - // linebreak between categories - if (counter > 0) { - this._makeItem([]); + // define levels if undefined by the users. Based on hubsize + if (undefinedLevel === true) { + if (this.options.hierarchical.sortMethod === 'hubsize') { + this._determineLevelsByHubsize(); + } else if (this.options.hierarchical.sortMethod === 'directed' || 'direction') { + this._determineLevelsDirected(); } - // a header for the category - this._makeHeader(option); - - // get the suboptions - this._handleObject(this.configureOptions[option], [option]); } - counter++; - } - } - - if (this.options.showButton === true) { - (function () { - var generateButton = document.createElement('div'); - generateButton.className = 'vis-network-configuration button'; - generateButton.innerHTML = 'generate options'; - generateButton.onclick = function () { - _this._printOptions(); - }; - generateButton.onmouseover = function () { - generateButton.className = 'vis-network-configuration button hover'; - }; - generateButton.onmouseout = function () { - generateButton.className = 'vis-network-configuration button'; - }; - _this.optionsContainer = document.createElement('div'); - _this.optionsContainer.className = 'vis-network-configuration vis-option-container'; + // check the distribution of the nodes per level. + var distribution = this._getDistribution(); - _this.domElements.push(_this.optionsContainer); - _this.domElements.push(generateButton); - })(); + // place the nodes on the canvas. + this._placeNodesByHierarchy(distribution); + } } - - this._push(); - this.colorPicker.insertTo(this.container); } }, { - key: '_push', + key: '_placeNodesByHierarchy', /** - * draw all DOM elements on the screen + * This function places the nodes on the canvas based on the hierarchial distribution. + * + * @param {Object} distribution | obtained by the function this._getDistribution() * @private */ - value: function _push() { - this.wrapper = document.createElement('div'); - this.wrapper.className = 'vis-network-configuration-wrapper'; - this.container.appendChild(this.wrapper); - for (var i = 0; i < this.domElements.length; i++) { - this.wrapper.appendChild(this.domElements[i]); + value: function _placeNodesByHierarchy(distribution) { + var nodeId = undefined, + node = undefined; + this.positionedNodes = {}; + // start placing all the level 0 nodes first. Then recursively position their branches. + for (var level in distribution) { + if (distribution.hasOwnProperty(level)) { + for (nodeId in distribution[level].nodes) { + if (distribution[level].nodes.hasOwnProperty(nodeId)) { + + node = distribution[level].nodes[nodeId]; + + if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') { + if (node.x === undefined) { + node.x = distribution[level].distance; + } + distribution[level].distance = node.x + this.nodeSpacing; + } else { + if (node.y === undefined) { + node.y = distribution[level].distance; + } + distribution[level].distance = node.y + this.nodeSpacing; + } + + this.positionedNodes[nodeId] = true; + this._placeBranchNodes(node.edges, node.id, distribution, level); + } + } + } } } }, { - key: '_clean', + key: '_getDistribution', /** - * delete all DOM elements + * This function get the distribution of levels based on hubsize + * + * @returns {Object} * @private */ - value: function _clean() { - for (var i = 0; i < this.domElements.length; i++) { - this.wrapper.removeChild(this.domElements[i]); - } + value: function _getDistribution() { + var distribution = {}; + var nodeId = undefined, + node = undefined; - if (this.wrapper !== undefined) { - this.container.removeChild(this.wrapper); - this.wrapper = undefined; + // we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time. + // the fix of X is removed after the x value has been set. + for (nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + node = this.body.nodes[nodeId]; + var level = this.hierarchicalLevels[nodeId] === undefined ? 0 : this.hierarchicalLevels[nodeId]; + if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') { + node.y = this.options.hierarchical.levelSeparation * level; + node.options.fixed.y = true; + } else { + node.x = this.options.hierarchical.levelSeparation * level; + node.options.fixed.x = true; + } + if (distribution[level] === undefined) { + distribution[level] = { amount: 0, nodes: {}, distance: 0 }; + } + distribution[level].amount += 1; + distribution[level].nodes[nodeId] = node; + } } - this.domElements = []; + return distribution; } }, { - key: '_getValue', + key: '_getHubSize', /** - * get the value from the actualOptions if it exists - * @param {array} path | where to look for the actual option - * @returns {*} + * Get the hubsize from all remaining unlevelled nodes. + * + * @returns {number} * @private */ - 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; + value: function _getHubSize() { + var hubSize = 0; + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + var node = this.body.nodes[nodeId]; + if (this.hierarchicalLevels[nodeId] === undefined) { + hubSize = node.edges.length < hubSize ? hubSize : node.edges.length; + } } } - return base; + return hubSize; } }, { - key: '_makeItem', + key: '_determineLevelsByHubsize', /** - * all option elements are wrapped in an item - * @param path - * @param domElements + * this function allocates nodes in levels based on the recursive branching from the largest hubs. + * + * @param hubsize * @private */ - value: function _makeItem(path) { - var _this2 = this; + value: function _determineLevelsByHubsize() { + var nodeId = undefined, + node = undefined; + var hubSize = 1; - for (var _len = arguments.length, domElements = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - domElements[_key - 1] = arguments[_key]; - } + while (hubSize > 0) { + // determine hubs + hubSize = this._getHubSize(); + if (hubSize === 0) break; - if (this.allowCreation === true) { - (function () { - var item = document.createElement('div'); - item.className = 'vis-network-configuration item s' + path.length; - domElements.forEach(function (element) { - item.appendChild(element); - }); - _this2.domElements.push(item); - })(); + for (nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + node = this.body.nodes[nodeId]; + if (node.edges.length === hubSize) { + this._setLevelByHubsize(0, node); + } + } + } } } }, { - key: '_makeHeader', + key: '_setLevelByHubsize', /** - * header for major subjects - * @param name + * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level. + * + * @param level + * @param edges + * @param parentId * @private */ - value: function _makeHeader(name) { - var div = document.createElement('div'); - div.className = 'vis-network-configuration header'; - div.innerHTML = name; - this._makeItem([], div); + value: function _setLevelByHubsize(level, node) { + if (this.hierarchicalLevels[node.id] !== undefined) return; + + var childNode = undefined; + this.hierarchicalLevels[node.id] = level; + for (var i = 0; i < node.edges.length; i++) { + if (node.edges[i].toId === node.id) { + childNode = node.edges[i].from; + } else { + childNode = node.edges[i].to; + } + this._setLevelByHubsize(level + 1, childNode); + } } }, { - key: '_makeLabel', + key: '_determineLevelsDirected', /** - * make a label, if it is an object label, it gets different styling. - * @param name - * @param path - * @param objectLabel - * @returns {HTMLElement} + * this function allocates nodes in levels based on the direction of the edges + * + * @param hubsize * @private */ - value: function _makeLabel(name, path) { - var objectLabel = arguments[2] === undefined ? false : arguments[2]; + value: function _determineLevelsDirected() { + var nodeId = undefined, + node = undefined; + var minLevel = 10000; + + // set first node to source + for (nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + node = this.body.nodes[nodeId]; + this._setLevelDirected(minLevel, node); + } + } + + // get the minimum level + for (nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + minLevel = this.hierarchicalLevels[nodeId] < minLevel ? this.hierarchicalLevels[nodeId] : minLevel; + } + } - var div = document.createElement('div'); - div.className = 'vis-network-configuration label s' + path.length; - if (objectLabel === true) { - div.innerHTML = '' + name + ':'; - } else { - div.innerHTML = name + ':'; + // subtract the minimum from the set so we have a range starting from 0 + for (nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + this.hierarchicalLevels[nodeId] -= minLevel; + } } - return div; } }, { - key: '_makeDropdown', + key: '_setLevelDirected', /** - * make a dropdown list for multiple possible string optoins - * @param arr - * @param value - * @param path + * this function is called recursively to enumerate the branched of the first node and give each node a level based on edge direction + * + * @param level + * @param edges + * @param parentId * @private */ - value: function _makeDropdown(arr, value, path) { - var select = document.createElement('select'); - select.className = 'vis-network-configuration select'; - var selectedValue = 0; - if (value !== undefined) { - if (arr.indexOf(value) !== -1) { - selectedValue = arr.indexOf(value); - } - } + value: function _setLevelDirected(level, node) { + if (this.hierarchicalLevels[node.id] !== undefined) return; - for (var i = 0; i < arr.length; i++) { - var option = document.createElement('option'); - option.value = arr[i]; - if (i === selectedValue) { - option.selected = 'selected'; + var childNode = undefined; + this.hierarchicalLevels[node.id] = level; + + for (var i = 0; i < node.edges.length; i++) { + if (node.edges[i].toId === node.id) { + childNode = node.edges[i].from; + this._setLevelDirected(level - 1, childNode); + } else { + childNode = node.edges[i].to; + this._setLevelDirected(level + 1, childNode); } - 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); } }, { - key: '_makeRange', + key: '_placeBranchNodes', /** - * make a range object for numeric options - * @param arr - * @param value - * @param path + * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes + * on a X position that ensures there will be no overlap. + * + * @param edges + * @param parentId + * @param distribution + * @param parentLevel * @private */ - 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.type = 'range'; - range.className = 'vis-network-configuration range'; - range.min = min; - range.max = max; - range.step = step; - - if (value !== undefined) { - if (value < 0 && value * 2 < min) { - range.min = value * 2; - } else if (value * 0.1 < min) { - range.min = value / 10; + value: function _placeBranchNodes(edges, parentId, distribution, parentLevel) { + for (var i = 0; i < edges.length; i++) { + var childNode = undefined; + var parentNode = undefined; + if (edges[i].toId === parentId) { + childNode = edges[i].from; + parentNode = edges[i].to; + } else { + childNode = edges[i].to; + parentNode = edges[i].from; } - if (value * 2 > max && max !== 1) { - range.max = value * 2; + var childNodeLevel = this.hierarchicalLevels[childNode.id]; + + if (this.positionedNodes[childNode.id] === undefined) { + // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here. + if (childNodeLevel > parentLevel) { + if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') { + if (childNode.x === undefined) { + childNode.x = Math.max(distribution[childNodeLevel].distance, parentNode.x); + } + distribution[childNodeLevel].distance = childNode.x + this.nodeSpacing; + this.positionedNodes[childNode.id] = true; + } else { + if (childNode.y === undefined) { + childNode.y = Math.max(distribution[childNodeLevel].distance, parentNode.y); + } + distribution[childNodeLevel].distance = childNode.y + this.nodeSpacing; + } + this.positionedNodes[childNode.id] = true; + + if (childNode.edges.length > 1) { + this._placeBranchNodes(childNode.edges, childNode.id, distribution, childNodeLevel); + } + } } - range.value = value; - } else { - range.value = defaultValue; } + } + }]); - var input = document.createElement('input'); - input.className = 'vis-network-configuration rangeinput'; - input.value = range.value; + return LayoutEngine; + })(); - var me = this; - range.onchange = function () { - input.value = this.value;me._update(Number(this.value), path); - }; - range.oninput = function () { - input.value = this.value; - }; + exports['default'] = LayoutEngine; + module.exports = exports['default']; - var label = this._makeLabel(path[path.length - 1], path); - this._makeItem(path, label, range, input); - } - }, { - key: '_makeCheckbox', +/***/ }, +/* 65 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + var util = __webpack_require__(2); + var Hammer = __webpack_require__(41); + var hammerUtil = __webpack_require__(49); + + /** + * clears the toolbar div element of children + * + * @private + */ + + var ManipulationSystem = (function () { + function ManipulationSystem(body, canvas, selectionHandler) { + var _this = this; + + _classCallCheck(this, ManipulationSystem); + + this.body = body; + this.canvas = canvas; + this.selectionHandler = selectionHandler; + + this.editMode = false; + this.manipulationDiv = undefined; + this.editModeDiv = undefined; + this.closeDiv = undefined; + + this.manipulationHammers = []; + this.temporaryUIFunctions = {}; + this.temporaryEventFunctions = []; + + this.touchTime = 0; + this.temporaryIds = { nodes: [], edges: [] }; + this.guiEnabled = false; + this.inMode = false; + this.selectedControlNode = undefined; + + this.options = {}; + this.defaultOptions = { + enabled: false, + initiallyActive: false, + addNode: true, + addEdge: true, + editNode: undefined, + editEdge: true, + deleteNode: true, + deleteEdge: true, + controlNodeStyle: { + shape: 'dot', + size: 6, + color: { background: '#ff0000', border: '#3c3c3c', highlight: { background: '#07f968', border: '#3c3c3c' } }, + borderWidth: 2, + borderWidthSelected: 2 + } + }; + util.extend(this.options, this.defaultOptions); + + this.body.emitter.on('destroy', function () { + _this._clean(); + }); + this.body.emitter.on('_dataChanged', this._restore.bind(this)); + this.body.emitter.on('_resetData', this._restore.bind(this)); + } + + _createClass(ManipulationSystem, [{ + key: '_restore', /** - * make a checkbox for boolean options. - * @param defaultValue - * @param value - * @param path + * If something changes in the data during editing, switch back to the initial datamanipulation state and close all edit modes. * @private */ - value: function _makeCheckbox(defaultValue, value, path) { - var checkbox = document.createElement('input'); - checkbox.type = 'checkbox'; - checkbox.className = 'vis-network-configuration checkbox'; - checkbox.checked = defaultValue; - if (value !== undefined) { - checkbox.checked = value; - if (value !== defaultValue) { - if (typeof defaultValue === 'object') { - if (value !== defaultValue.enabled) { - this.changedOptions.push({ path: path, value: value }); - } - } else { - this.changedOptions.push({ path: path, value: value }); - } + value: function _restore() { + if (this.inMode !== false) { + if (this.options.initiallyActive === true) { + this.enableEditMode(); + } else { + this.disableEditMode(); } } - - 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); } }, { - key: '_makeTextInput', + key: 'setOptions', /** - * make a text input field for string options. - * @param defaultValue - * @param value - * @param path - * @private + * Set the Options + * @param options */ - value: function _makeTextInput(defaultValue, value, path) { - var checkbox = document.createElement('input'); - checkbox.type = 'text'; - checkbox.className = 'vis-network-configuration text'; - checkbox.value = value; - if (value !== defaultValue) { - this.changedOptions.push({ path: path, value: value }); + value: function setOptions(options, allOptions, globalOptions) { + if (allOptions !== undefined) { + if (allOptions.locale !== undefined) { + this.options.locale = allOptions.locale; + } else { + this.options.locale = globalOptions.locale; + } + if (allOptions.locales !== undefined) { + this.options.locales = allOptions.locales; + } else { + this.options.locales = globalOptions.locales; + } } - 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); + if (options !== undefined) { + if (typeof options === 'boolean') { + this.options.enabled = options; + } else { + this.options.enabled = true; + util.deepExtend(this.options, options); + } + if (this.options.initiallyActive === true) { + this.editMode = true; + } + this._setup(); + } } }, { - key: '_makeColorField', + key: 'toggleEditMode', /** - * make a color field with a color picker for color fields - * @param arr - * @param value - * @param path + * Enable or disable edit-mode. Draws the DOM required and cleans up after itself. + * * @private */ - value: function _makeColorField(arr, value, path) { - var _this3 = this; - - var defaultColor = arr[1]; - var div = document.createElement('div'); - value = value === undefined ? defaultColor : value; - - if (value !== 'none') { - div.className = 'vis-network-configuration colorBlock'; - div.style.backgroundColor = value; + value: function toggleEditMode() { + if (this.editMode === true) { + this.disableEditMode(); } else { - div.className = 'vis-network-configuration colorBlock none'; + this.enableEditMode(); } - - value = value === undefined ? defaultColor : value; - div.onclick = function () { - _this3._showColorPicker(value, div, path); - }; - - var label = this._makeLabel(path[path.length - 1], path); - this._makeItem(path, label, div); } }, { - key: '_showColorPicker', + key: 'enableEditMode', + value: function enableEditMode() { + this.editMode = true; - /** - * used by the color buttons to call the color picker. - * @param event - * @param value - * @param div - * @param path - * @private - */ - value: function _showColorPicker(value, div, path) { - var _this4 = this; + this._clean(); + if (this.guiEnabled === true) { + this.manipulationDiv.style.display = 'block'; + this.closeDiv.style.display = 'block'; + this.editModeDiv.style.display = 'none'; + this.showManipulatorToolbar(); + } + } + }, { + key: 'disableEditMode', + value: function disableEditMode() { + this.editMode = false; - var rect = div.getBoundingClientRect(); - var bodyRect = document.body.getBoundingClientRect(); - var pickerX = rect.left + rect.width + 5; - var pickerY = rect.top - bodyRect.top + rect.height * 0.5; - this.colorPicker.show(pickerX, pickerY); - this.colorPicker.setColor(value); - this.colorPicker.setCallback(function (color) { - var colorString = 'rgba(' + color.r + ',' + color.g + ',' + color.b + ',' + color.a + ')'; - div.style.backgroundColor = colorString; - _this4._update(colorString, path); - }); + this._clean(); + if (this.guiEnabled === true) { + this.manipulationDiv.style.display = 'none'; + this.closeDiv.style.display = 'none'; + this.editModeDiv.style.display = 'block'; + this._createEditButton(); + } } }, { - key: '_handleObject', + key: 'showManipulatorToolbar', /** - * parse an object and draw the correct items - * @param obj - * @param path + * Creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar. + * * @private */ - value: function _handleObject(obj) { - var path = arguments[1] === undefined ? [] : arguments[1]; - var checkOnly = arguments[2] === undefined ? false : arguments[2]; + value: function showManipulatorToolbar() { + // restore the state of any bound functions or events, remove control nodes, restore physics + this._clean(); - 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); + // reset global letiables + this.manipulationDOM = {}; - // 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 the gui is enabled, draw all elements. + if (this.guiEnabled === true) { + // a _restore will hide these menus + this.editMode = true; + this.manipulationDiv.style.display = 'block'; + this.closeDiv.style.display = 'block'; - if (show !== false) { - visibleInSet = true; - var value = this._getValue(newPath); + var selectedNodeCount = this.selectionHandler._getSelectedNodeCount(); + var selectedEdgeCount = this.selectionHandler._getSelectedEdgeCount(); + var selectedTotalCount = selectedNodeCount + selectedEdgeCount; + var locale = this.options.locales[this.options.locale]; + var needSeperator = false; - 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 (this.options.addNode !== false) { + this._createAddNodeButton(locale); + needSeperator = true; + } + if (this.options.addEdge !== false) { + if (needSeperator === true) { + this._createSeperator(1); + } else { + needSeperator = true; + } + this._createAddEdgeButton(locale); + } - 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); + if (selectedNodeCount === 1 && typeof this.options.editNode === 'function') { + if (needSeperator === true) { + this._createSeperator(2); + } else { + needSeperator = true; + } + this._createEditNodeButton(locale); + } else if (selectedEdgeCount === 1 && selectedNodeCount === 0 && this.options.editEdge !== false) { + if (needSeperator === true) { + this._createSeperator(3); + } else { + needSeperator = true; + } + this._createEditEdgeButton(locale); + } + + // remove buttons + if (selectedTotalCount !== 0) { + if (selectedNodeCount === 1 && this.options.deleteNode !== false) { + if (needSeperator === true) { + this._createSeperator(4); + } + this._createDeleteButton(locale); + } else if (selectedNodeCount === 0 && this.options.deleteEdge !== false) { + if (needSeperator === true) { + this._createSeperator(4); } + this._createDeleteButton(locale); } } + + // bind the close button + this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); + + // refresh this bar based on what has been selected + this._temporaryBindEvent('select', this.showManipulatorToolbar.bind(this)); } - return visibleInSet; + + // redraw to show any possible changes + this.body.emitter.emit('_redraw'); } }, { - key: '_handleArray', + key: 'addNodeMode', /** - * handle the array type of option - * @param optionName - * @param arr - * @param value - * @param path + * Create the toolbar for adding Nodes + * * @private */ - 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) }); - } + value: function addNodeMode() { + // when using the gui, enable edit mode if it wasnt already. + if (this.editMode !== true) { + this.enableEditMode(); + } + + // restore the state of any bound functions or events, remove control nodes, restore physics + this._clean(); + + this.inMode = 'addNode'; + if (this.guiEnabled === true) { + var locale = this.options.locales[this.options.locale]; + this.manipulationDOM = {}; + this._createBackButton(locale); + this._createSeperator(); + this._createDescription(locale['addDescription'] || this.options.locales['en']['addDescription']); + + // bind the close button + this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); } + + this._temporaryBindEvent('click', this._performAddNode.bind(this)); } }, { - key: '_update', + key: 'editNode', /** - * called to update the network with the new settings. - * @param value - * @param path + * call the bound function to handle the editing of the node. The node has to be selected. + * * @private */ - value: function _update(value, path) { - var options = this._constructOptions(value, path); - this.parent.setOptions(options); - } - }, { - key: '_constructOptions', - value: function _constructOptions(value, path) { - var optionsObj = arguments[2] === undefined ? {} : arguments[2]; + value: function editNode() { + var _this2 = this; - var pointer = optionsObj; + // when using the gui, enable edit mode if it wasnt already. + if (this.editMode !== true) { + this.enableEditMode(); + } - // when dropdown boxes can be string or boolean, we typecast it into correct types - value = value === 'true' ? true : value; - value = value === 'false' ? false : value; + // restore the state of any bound functions or events, remove control nodes, restore physics + this._clean(); - 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]]; + this.inMode = 'editNode'; + if (typeof this.options.editNode === 'function') { + var node = this.selectionHandler._getSelectedNode(); + if (node.isCluster !== true) { + var data = util.deepExtend({}, node.options, true); + data.x = node.x; + data.y = node.y; + + if (this.options.editNode.length === 2) { + this.options.editNode(data, function (finalizedData) { + if (finalizedData !== null && finalizedData !== undefined && _this2.inMode === 'editNode') { + // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { + _this2.body.data.nodes.update(finalizedData); + } + _this2.showManipulatorToolbar(); + }); } else { - pointer[path[i]] = value; + throw new Error('The function for edit does not support two arguments (data, callback)'); } + } else { + alert(this.options.locales[this.options.locale]['editClusterError'] || this.options.locales['en']['editClusterError']); } + } else { + throw new Error('No function has been configured to handle the editing of nodes.'); } - return optionsObj; } }, { - key: '_printOptions', - value: function _printOptions() { - var options = {}; - for (var i = 0; i < this.changedOptions.length; i++) { - this._constructOptions(this.changedOptions[i].value, this.changedOptions[i].path, options); - } - this.optionsContainer.innerHTML = '
var options = ' + JSON.stringify(options, null, 2) + '
'; - } - }]); + key: 'addEdgeMode', - return Configurator; - })(); + /** + * create the toolbar to connect nodes + * + * @private + */ + value: function addEdgeMode() { + // when using the gui, enable edit mode if it wasnt already. + if (this.editMode !== true) { + this.enableEditMode(); + } - exports['default'] = Configurator; - module.exports = exports['default']; + // restore the state of any bound functions or events, remove control nodes, restore physics + this._clean(); -/***/ }, -/* 53 */ -/***/ function(module, exports, __webpack_require__) { + this.inMode = 'addEdge'; + if (this.guiEnabled === true) { + var locale = this.options.locales[this.options.locale]; + this.manipulationDOM = {}; + this._createBackButton(locale); + this._createSeperator(); + this._createDescription(locale['edgeDescription'] || this.options.locales['en']['edgeDescription']); - 'use strict'; + // bind the close button + this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); + } - Object.defineProperty(exports, '__esModule', { - value: true - }); + // temporarily overload functions + this._temporaryBindUI('onTouch', this._handleConnect.bind(this)); + this._temporaryBindUI('onDragEnd', this._finishConnect.bind(this)); + this._temporaryBindUI('onDrag', this._dragControlNode.bind(this)); + this._temporaryBindUI('onRelease', this._finishConnect.bind(this)); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + this._temporaryBindUI('onDragStart', function () {}); + this._temporaryBindUI('onHold', function () {}); + } + }, { + key: 'editEdgeMode', - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * create the toolbar to edit edges + * + * @private + */ + value: function editEdgeMode() { + // when using the gui, enable edit mode if it wasnt already. + if (this.editMode !== true) { + this.enableEditMode(); + } - var Hammer = __webpack_require__(13); - var hammerUtil = __webpack_require__(38); - var util = __webpack_require__(2); + // restore the state of any bound functions or events, remove control nodes, restore physics + this._clean(); - var ColorPicker = (function () { - function ColorPicker() { - var pixelRatio = arguments[0] === undefined ? 1 : arguments[0]; + this.inMode = 'editEdge'; + if (this.guiEnabled === true) { + var locale = this.options.locales[this.options.locale]; + this.manipulationDOM = {}; + this._createBackButton(locale); + this._createSeperator(); + this._createDescription(locale['editEdgeDescription'] || this.options.locales['en']['editEdgeDescription']); - _classCallCheck(this, ColorPicker); + // bind the close button + this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); + } - this.pixelRatio = pixelRatio; - this.generated = false; - this.centerCoordinates = { x: 289 / 2, y: 289 / 2 }; - this.r = 289 * 0.49; - this.color = { r: 255, g: 255, b: 255, a: 1 }; - this.hueCircle = undefined; - this.initialColor = { r: 255, g: 255, b: 255, a: 1 }; - this.previousColor = undefined; - this.applied = false; + this.edgeBeingEditedId = this.selectionHandler.getSelectedEdges()[0]; + var edge = this.body.edges[this.edgeBeingEditedId]; - // bound by - this.updateCallback = function () {}; + // create control nodes + var controlNodeFrom = this._getNewTargetNode(edge.from.x, edge.from.y); + var controlNodeTo = this._getNewTargetNode(edge.to.x, edge.to.y); - // create all DOM elements - this._create(); - } + this.temporaryIds.nodes.push(controlNodeFrom.id); + this.temporaryIds.nodes.push(controlNodeTo.id); - _createClass(ColorPicker, [{ - key: 'insertTo', + this.body.nodes[controlNodeFrom.id] = controlNodeFrom; + this.body.nodeIndices.push(controlNodeFrom.id); + this.body.nodes[controlNodeTo.id] = controlNodeTo; + this.body.nodeIndices.push(controlNodeTo.id); - /** - * this inserts the colorPicker into a div from the DOM - * @param container - */ - value: function insertTo(container) { - if (this.hammer !== undefined) { - this.hammer.destroy(); - this.hammer = undefined; - } - this.container = container; - this.container.appendChild(this.frame); - this._bindHammer(); + // temporarily overload UI functions, cleaned up automatically because of _temporaryBindUI + this._temporaryBindUI('onTouch', this._controlNodeTouch.bind(this)); // used to get the position + this._temporaryBindUI('onTap', function () {}); // disabled + this._temporaryBindUI('onHold', function () {}); // disabled + this._temporaryBindUI('onDragStart', this._controlNodeDragStart.bind(this)); // used to select control node + this._temporaryBindUI('onDrag', this._controlNodeDrag.bind(this)); // used to drag control node + this._temporaryBindUI('onDragEnd', this._controlNodeDragEnd.bind(this)); // used to connect or revert control nodes + this._temporaryBindUI('onMouseMove', function () {}); // disabled - this._setSize(); - } - }, { - key: 'setCallback', + // create function to position control nodes correctly on movement + // automatically cleaned up because we use the temporary bind + this._temporaryBindEvent('beforeDrawing', function (ctx) { + var positions = edge.edgeType.findBorderPositions(ctx); + if (controlNodeFrom.selected === false) { + controlNodeFrom.x = positions.from.x; + controlNodeFrom.y = positions.from.y; + } + if (controlNodeTo.selected === false) { + controlNodeTo.x = positions.to.x; + controlNodeTo.y = positions.to.y; + } + }); - /** - * the callback is executed on apply and save. Bind it to the application - * @param callback - */ - value: function setCallback(callback) { - if (typeof callback === 'function') { - this.updateCallback = callback; - } else { - throw new Error('Function attempted to set as colorPicker callback is not a function.'); - } - } - }, { - key: '_isColorString', - value: function _isColorString(color) { - var htmlColors = { black: '#000000', navy: '#000080', darkblue: '#00008B', mediumblue: '#0000CD', blue: '#0000FF', darkgreen: '#006400', green: '#008000', teal: '#008080', darkcyan: '#008B8B', deepskyblue: '#00BFFF', darkturquoise: '#00CED1', mediumspringgreen: '#00FA9A', lime: '#00FF00', springgreen: '#00FF7F', aqua: '#00FFFF', cyan: '#00FFFF', midnightblue: '#191970', dodgerblue: '#1E90FF', lightseagreen: '#20B2AA', forestgreen: '#228B22', seagreen: '#2E8B57', darkslategray: '#2F4F4F', limegreen: '#32CD32', mediumseagreen: '#3CB371', turquoise: '#40E0D0', royalblue: '#4169E1', steelblue: '#4682B4', darkslateblue: '#483D8B', mediumturquoise: '#48D1CC', indigo: '#4B0082', darkolivegreen: '#556B2F', cadetblue: '#5F9EA0', cornflowerblue: '#6495ED', mediumaquamarine: '#66CDAA', dimgray: '#696969', slateblue: '#6A5ACD', olivedrab: '#6B8E23', slategray: '#708090', lightslategray: '#778899', mediumslateblue: '#7B68EE', lawngreen: '#7CFC00', chartreuse: '#7FFF00', aquamarine: '#7FFFD4', maroon: '#800000', purple: '#800080', olive: '#808000', gray: '#808080', skyblue: '#87CEEB', lightskyblue: '#87CEFA', blueviolet: '#8A2BE2', darkred: '#8B0000', darkmagenta: '#8B008B', saddlebrown: '#8B4513', darkseagreen: '#8FBC8F', lightgreen: '#90EE90', mediumpurple: '#9370D8', darkviolet: '#9400D3', palegreen: '#98FB98', darkorchid: '#9932CC', yellowgreen: '#9ACD32', sienna: '#A0522D', brown: '#A52A2A', darkgray: '#A9A9A9', lightblue: '#ADD8E6', greenyellow: '#ADFF2F', paleturquoise: '#AFEEEE', lightsteelblue: '#B0C4DE', powderblue: '#B0E0E6', firebrick: '#B22222', darkgoldenrod: '#B8860B', mediumorchid: '#BA55D3', rosybrown: '#BC8F8F', darkkhaki: '#BDB76B', silver: '#C0C0C0', mediumvioletred: '#C71585', indianred: '#CD5C5C', peru: '#CD853F', chocolate: '#D2691E', tan: '#D2B48C', lightgrey: '#D3D3D3', palevioletred: '#D87093', thistle: '#D8BFD8', orchid: '#DA70D6', goldenrod: '#DAA520', crimson: '#DC143C', gainsboro: '#DCDCDC', plum: '#DDA0DD', burlywood: '#DEB887', lightcyan: '#E0FFFF', lavender: '#E6E6FA', darksalmon: '#E9967A', violet: '#EE82EE', palegoldenrod: '#EEE8AA', lightcoral: '#F08080', khaki: '#F0E68C', aliceblue: '#F0F8FF', honeydew: '#F0FFF0', azure: '#F0FFFF', sandybrown: '#F4A460', wheat: '#F5DEB3', beige: '#F5F5DC', whitesmoke: '#F5F5F5', mintcream: '#F5FFFA', ghostwhite: '#F8F8FF', salmon: '#FA8072', antiquewhite: '#FAEBD7', linen: '#FAF0E6', lightgoldenrodyellow: '#FAFAD2', oldlace: '#FDF5E6', red: '#FF0000', fuchsia: '#FF00FF', magenta: '#FF00FF', deeppink: '#FF1493', orangered: '#FF4500', tomato: '#FF6347', hotpink: '#FF69B4', coral: '#FF7F50', darkorange: '#FF8C00', lightsalmon: '#FFA07A', orange: '#FFA500', lightpink: '#FFB6C1', pink: '#FFC0CB', gold: '#FFD700', peachpuff: '#FFDAB9', navajowhite: '#FFDEAD', moccasin: '#FFE4B5', bisque: '#FFE4C4', mistyrose: '#FFE4E1', blanchedalmond: '#FFEBCD', papayawhip: '#FFEFD5', lavenderblush: '#FFF0F5', seashell: '#FFF5EE', cornsilk: '#FFF8DC', lemonchiffon: '#FFFACD', floralwhite: '#FFFAF0', snow: '#FFFAFA', yellow: '#FFFF00', lightyellow: '#FFFFE0', ivory: '#FFFFF0', white: '#FFFFFF' }; - if (typeof color === 'string') { - return htmlColors[color]; - } + this.body.emitter.emit('_redraw'); } }, { - key: 'setColor', + key: 'deleteSelected', /** - * Set the color of the colorPicker - * Supported formats: - * 'red' --> HTML color string - * '#ffffff' --> hex string - * 'rbg(255,255,255)' --> rgb string - * 'rgba(255,255,255,1.0)' --> rgba string - * {r:255,g:255,b:255} --> rgb object - * {r:255,g:255,b:255,a:1.0} --> rgba object - * @param color - * @param setInitial + * delete everything in the selection + * + * @private */ - value: function setColor(color) { - var setInitial = arguments[1] === undefined ? true : arguments[1]; + value: function deleteSelected() { + var _this3 = this; - if (color === 'none') { - return; + // when using the gui, enable edit mode if it wasnt already. + if (this.editMode !== true) { + this.enableEditMode(); } - var rgba = undefined; + // restore the state of any bound functions or events, remove control nodes, restore physics + this._clean(); - // if a html color shorthand is used, convert to hex - var htmlColor = this._isColorString(color); - if (htmlColor !== undefined) { - color = htmlColor; - } + this.inMode = 'delete'; + var selectedNodes = this.selectionHandler.getSelectedNodes(); + var selectedEdges = this.selectionHandler.getSelectedEdges(); + var deleteFunction = undefined; + if (selectedNodes.length > 0) { + for (var i = 0; i < selectedNodes.length; i++) { + if (this.body.nodes[selectedNodes[i]].isCluster === true) { + alert(this.options.locales[this.options.locale]['deleteClusterError'] || this.options.locales['en']['deleteClusterError']); + return; + } + } - // check format - if (util.isString(color) === true) { - if (util.isValidRGB(color) === true) { - var rgbaArray = color.substr(4).substr(0, color.length - 5).split(','); - rgba = { r: rgbaArray[0], g: rgbaArray[1], b: rgbaArray[2], a: 1 }; - } else if (util.isValidRGBA(color) === true) { - var rgbaArray = color.substr(5).substr(0, color.length - 6).split(','); - rgba = { r: rgbaArray[0], g: rgbaArray[1], b: rgbaArray[2], a: rgbaArray[3] }; - } else if (util.isValidHex(color) === true) { - var rgbObj = util.hexToRGB(color); - rgba = { r: rgbObj.r, g: rgbObj.g, b: rgbObj.b, a: 1 }; + if (typeof this.options.deleteNode === 'function') { + deleteFunction = this.options.deleteNode; } - } else { - if (color instanceof Object) { - if (color.r !== undefined && color.g !== undefined && color.b !== undefined) { - var alpha = color.a !== undefined ? color.a : '1.0'; - rgba = { r: color.r, g: color.g, b: color.b, a: alpha }; - } + } else if (selectedEdges.length > 0) { + if (typeof this.options.deleteEdge === 'function') { + deleteFunction = this.options.deleteEdge; } } - // set color - if (rgba === undefined) { - throw new Error('Unknown color passed to the colorPicker. Supported are strings: rgb, hex, rgba. Object: rgb ({r:r,g:g,b:b,[a:a]}). Supplied: ' + JSON.stringify(color)); + if (typeof deleteFunction === 'function') { + var data = { nodes: selectedNodes, edges: selectedEdges }; + if (deleteFunction.length === 2) { + deleteFunction(data, function (finalizedData) { + if (finalizedData !== null && finalizedData !== undefined && _this3.inMode === 'delete') { + // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { + _this3.body.data.edges.remove(finalizedData.edges); + _this3.body.data.nodes.remove(finalizedData.nodes); + _this3.body.emitter.emit('startSimulation'); + _this3.showManipulatorToolbar(); + } + }); + } else { + throw new Error('The function for delete does not support two arguments (data, callback)'); + } } else { - this._setColor(rgba, setInitial); + this.body.data.edges.remove(selectedEdges); + this.body.data.nodes.remove(selectedNodes); + this.body.emitter.emit('startSimulation'); + this.showManipulatorToolbar(); } } }, { - key: 'show', + key: '_setup', + + //********************************************** PRIVATE ***************************************// /** - * this shows the color picker at a location. The hue circle is constructed once and stored. - * @param x - * @param y + * draw or remove the DOM + * @private */ - value: function show(x, y) { - this.applied = false; - this.frame.style.display = 'block'; - this.frame.style.top = y + 'px'; - this.frame.style.left = x + 'px'; - this._generateHueCircle(); + value: function _setup() { + if (this.options.enabled === true) { + // Enable the GUI + this.guiEnabled = true; + + this._createWrappers(); + if (this.editMode === false) { + this._createEditButton(); + } else { + this.showManipulatorToolbar(); + } + } else { + this._removeManipulationDOM(); + + // disable the gui + this.guiEnabled = false; + } } }, { - key: '_hide', - - // ------------------------------------------ PRIVATE ----------------------------- // + key: '_createWrappers', /** - * Hide the picker. Is called by the cancel button. - * Optional boolean to store the previous color for easy access later on. - * @param storePrevious + * create the div overlays that contain the DOM * @private */ - value: function _hide() { - var storePrevious = arguments[0] === undefined ? true : arguments[0]; - - // store the previous color for next time; - if (storePrevious === true) { - this.previousColor = util.extend({}, this.color); + value: function _createWrappers() { + // load the manipulator HTML elements. All styling done in css. + if (this.manipulationDiv === undefined) { + this.manipulationDiv = document.createElement('div'); + this.manipulationDiv.className = 'vis-manipulation'; + if (this.editMode === true) { + this.manipulationDiv.style.display = 'block'; + } else { + this.manipulationDiv.style.display = 'none'; + } + this.canvas.frame.appendChild(this.manipulationDiv); } - if (this.applied === true) { - this.updateCallback(this.initialColor); + // container for the edit button. + if (this.editModeDiv === undefined) { + this.editModeDiv = document.createElement('div'); + this.editModeDiv.className = 'vis-edit-mode'; + if (this.editMode === true) { + this.editModeDiv.style.display = 'none'; + } else { + this.editModeDiv.style.display = 'block'; + } + this.canvas.frame.appendChild(this.editModeDiv); } - this.frame.style.display = 'none'; + // container for the close div button + if (this.closeDiv === undefined) { + this.closeDiv = document.createElement('div'); + this.closeDiv.className = 'vis-close'; + this.closeDiv.style.display = this.manipulationDiv.style.display; + this.canvas.frame.appendChild(this.closeDiv); + } } }, { - key: '_save', + key: '_getNewTargetNode', /** - * bound to the save button. Saves and hides. + * generate a new target node. Used for creating new edges and editing edges + * @param x + * @param y + * @returns {*} * @private */ - value: function _save() { - this.updateCallback(this.color); - this.applied = false; - this._hide(); + value: function _getNewTargetNode(x, y) { + var controlNodeStyle = util.deepExtend({}, this.options.controlNodeStyle); + + controlNodeStyle.id = 'targetNode' + util.randomUUID(); + controlNodeStyle.hidden = false; + controlNodeStyle.physics = false; + controlNodeStyle.x = x; + controlNodeStyle.y = y; + + return this.body.functions.createNode(controlNodeStyle); } }, { - key: '_apply', + key: '_createEditButton', /** - * Bound to apply button. Saves but does not close. Is undone by the cancel button. + * Create the edit button + */ + value: function _createEditButton() { + // restore everything to it's original state (if applicable) + this._clean(); + + // reset the manipulationDOM + this.manipulationDOM = {}; + + // empty the editModeDiv + util.recursiveDOMDelete(this.editModeDiv); + + // create the contents for the editMode button + var locale = this.options.locales[this.options.locale]; + var button = this._createButton('editMode', 'vis-button vis-edit vis-edit-mode', locale['edit'] || this.options.locales['en']['edit']); + this.editModeDiv.appendChild(button); + + // bind a hammer listener to the button, calling the function toggleEditMode. + this._bindHammerToDiv(button, this.toggleEditMode.bind(this)); + } + }, { + key: '_clean', + + /** + * this function cleans up after everything this module does. Temporary elements, functions and events are removed, physics restored, hammers removed. * @private */ - value: function _apply() { - this.applied = true; - this.updateCallback(this.color); - this._updatePicker(this.color); + value: function _clean() { + // not in mode + this.inMode = false; + + // _clean the divs + if (this.guiEnabled === true) { + util.recursiveDOMDelete(this.editModeDiv); + util.recursiveDOMDelete(this.manipulationDiv); + + // removes all the bindings and overloads + this._cleanManipulatorHammers(); + } + + // remove temporary nodes and edges + this._cleanupTemporaryNodesAndEdges(); + + // restore overloaded UI functions + this._unbindTemporaryUIs(); + + // remove the temporaryEventFunctions + this._unbindTemporaryEvents(); + + // restore the physics if required + this.body.emitter.emit('restorePhysics'); } }, { - key: '_loadLast', + key: '_cleanManipulatorHammers', /** - * load the color from the previous session. + * Each dom element has it's own hammer. They are stored in this.manipulationHammers. This cleans them up. * @private */ - value: function _loadLast() { - if (this.previousColor !== undefined) { - this.setColor(this.previousColor, false); - } else { - alert('There is no last color to load...'); + value: function _cleanManipulatorHammers() { + // _clean hammer bindings + if (this.manipulationHammers.length != 0) { + for (var i = 0; i < this.manipulationHammers.length; i++) { + this.manipulationHammers[i].destroy(); + } + this.manipulationHammers = []; } } }, { - key: '_setColor', + key: '_removeManipulationDOM', /** - * set the color, place the picker - * @param rgba - * @param setInitial + * Remove all DOM elements created by this module. * @private */ - value: function _setColor(rgba) { - var setInitial = arguments[1] === undefined ? true : arguments[1]; - - // store the initial color - if (setInitial === true) { - this.initialColor = util.extend({}, rgba); - } - - this.color = rgba; - var hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b); + value: function _removeManipulationDOM() { + // removes all the bindings and overloads + this._clean(); - var angleConvert = 2 * Math.PI; - var radius = this.r * hsv.s; - var x = this.centerCoordinates.x + radius * Math.sin(angleConvert * hsv.h); - var y = this.centerCoordinates.y + radius * Math.cos(angleConvert * hsv.h); + // empty the manipulation divs + util.recursiveDOMDelete(this.manipulationDiv); + util.recursiveDOMDelete(this.editModeDiv); + util.recursiveDOMDelete(this.closeDiv); - this.colorPickerSelector.style.left = x - 0.5 * this.colorPickerSelector.clientWidth + 'px'; - this.colorPickerSelector.style.top = y - 0.5 * this.colorPickerSelector.clientHeight + 'px'; + // remove the manipulation divs + if (this.manipulationDiv) { + this.canvas.frame.removeChild(this.manipulationDiv); + } + if (this.editModeDiv) { + this.canvas.frame.removeChild(this.editModeDiv); + } + if (this.closeDiv) { + this.canvas.frame.removeChild(this.manipulationDiv); + } - this._updatePicker(rgba); + // set the references to undefined + this.manipulationDiv = undefined; + this.editModeDiv = undefined; + this.closeDiv = undefined; } }, { - key: '_setOpacity', + key: '_createSeperator', /** - * bound to opacity control - * @param value + * create a seperator line. the index is to differentiate in the manipulation dom + * @param index * @private */ - value: function _setOpacity(value) { - this.color.a = value / 100; - this._updatePicker(this.color); + value: function _createSeperator() { + var index = arguments[0] === undefined ? 1 : arguments[0]; + + this.manipulationDOM['seperatorLineDiv' + index] = document.createElement('div'); + this.manipulationDOM['seperatorLineDiv' + index].className = 'vis-separator-line'; + this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv' + index]); } }, { - key: '_setBrightness', + key: '_createAddNodeButton', + + // ---------------------- DOM functions for buttons --------------------------// + + value: function _createAddNodeButton(locale) { + var button = this._createButton('addNode', 'vis-button vis-add', locale['addNode'] || this.options.locales['en']['addNode']); + this.manipulationDiv.appendChild(button); + this._bindHammerToDiv(button, this.addNodeMode.bind(this)); + } + }, { + key: '_createAddEdgeButton', + value: function _createAddEdgeButton(locale) { + var button = this._createButton('addEdge', 'vis-button vis-connect', locale['addEdge'] || this.options.locales['en']['addEdge']); + this.manipulationDiv.appendChild(button); + this._bindHammerToDiv(button, this.addEdgeMode.bind(this)); + } + }, { + key: '_createEditNodeButton', + value: function _createEditNodeButton(locale) { + var button = this._createButton('editNode', 'vis-button vis-edit', locale['editNode'] || this.options.locales['en']['editNode']); + this.manipulationDiv.appendChild(button); + this._bindHammerToDiv(button, this.editNode.bind(this)); + } + }, { + key: '_createEditEdgeButton', + value: function _createEditEdgeButton(locale) { + var button = this._createButton('editEdge', 'vis-button vis-edit', locale['editEdge'] || this.options.locales['en']['editEdge']); + this.manipulationDiv.appendChild(button); + this._bindHammerToDiv(button, this.editEdgeMode.bind(this)); + } + }, { + key: '_createDeleteButton', + value: function _createDeleteButton(locale) { + var button = this._createButton('delete', 'vis-button vis-delete', locale['del'] || this.options.locales['en']['del']); + this.manipulationDiv.appendChild(button); + this._bindHammerToDiv(button, this.deleteSelected.bind(this)); + } + }, { + key: '_createBackButton', + value: function _createBackButton(locale) { + var button = this._createButton('back', 'vis-button vis-back', locale['back'] || this.options.locales['en']['back']); + this.manipulationDiv.appendChild(button); + this._bindHammerToDiv(button, this.showManipulatorToolbar.bind(this)); + } + }, { + key: '_createButton', + value: function _createButton(id, className, label) { + var labelClassName = arguments[3] === undefined ? 'vis-label' : arguments[3]; + + this.manipulationDOM[id + 'Div'] = document.createElement('div'); + this.manipulationDOM[id + 'Div'].className = className; + this.manipulationDOM[id + 'Label'] = document.createElement('div'); + this.manipulationDOM[id + 'Label'].className = labelClassName; + this.manipulationDOM[id + 'Label'].innerHTML = label; + this.manipulationDOM[id + 'Div'].appendChild(this.manipulationDOM[id + 'Label']); + return this.manipulationDOM[id + 'Div']; + } + }, { + key: '_createDescription', + value: function _createDescription(label) { + this.manipulationDiv.appendChild(this._createButton('description', 'vis-button vis-none', label)); + } + }, { + key: '_temporaryBindEvent', + + // -------------------------- End of DOM functions for buttons ------------------------------// /** - * bound to brightness control - * @param value + * this binds an event until cleanup by the clean functions. + * @param event + * @param newFunction * @private */ - value: function _setBrightness(value) { - var hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b); - hsv.v = value / 100; - var rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v); - rgba['a'] = this.color.a; - this.color = rgba; - this._updatePicker(); + value: function _temporaryBindEvent(event, newFunction) { + this.temporaryEventFunctions.push({ event: event, boundFunction: newFunction }); + this.body.emitter.on(event, newFunction); } }, { - key: '_updatePicker', + key: '_temporaryBindUI', /** - * update the colorpicker. A black circle overlays the hue circle to mimic the brightness decreasing. - * @param rgba + * this overrides an UI function until cleanup by the clean function + * @param UIfunctionName + * @param newFunction * @private */ - value: function _updatePicker() { - var rgba = arguments[0] === undefined ? this.color : arguments[0]; - - var hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b); - var ctx = this.colorPickerCanvas.getContext('2d'); - if (this.pixelRation === undefined) { - this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + value: function _temporaryBindUI(UIfunctionName, newFunction) { + if (this.body.eventListeners[UIfunctionName] !== undefined) { + this.temporaryUIFunctions[UIfunctionName] = this.body.eventListeners[UIfunctionName]; + this.body.eventListeners[UIfunctionName] = newFunction; + } else { + throw new Error('This UI function does not exist. Typo? You tried: ' + UIfunctionName + ' possible are: ' + JSON.stringify(Object.keys(this.body.eventListeners))); } - ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); - - // clear the canvas - var w = this.colorPickerCanvas.clientWidth; - var h = this.colorPickerCanvas.clientHeight; - ctx.clearRect(0, 0, w, h); - - ctx.putImageData(this.hueCircle, 0, 0); - ctx.fillStyle = 'rgba(0,0,0,' + (1 - hsv.v) + ')'; - ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r); - ctx.fill(); - - this.brightnessRange.value = 100 * hsv.v; - this.opacityRange.value = 100 * rgba.a; - - this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')'; - this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')'; } }, { - key: '_setSize', + key: '_unbindTemporaryUIs', /** - * used by create to set the size of the canvas. + * Restore the overridden UI functions to their original state. + * * @private */ - value: function _setSize() { - this.colorPickerCanvas.style.width = '100%'; - this.colorPickerCanvas.style.height = '100%'; - - this.colorPickerCanvas.width = 289 * this.pixelRatio; - this.colorPickerCanvas.height = 289 * this.pixelRatio; + value: function _unbindTemporaryUIs() { + for (var functionName in this.temporaryUIFunctions) { + if (this.temporaryUIFunctions.hasOwnProperty(functionName)) { + this.body.eventListeners[functionName] = this.temporaryUIFunctions[functionName]; + delete this.temporaryUIFunctions[functionName]; + } + } + this.temporaryUIFunctions = {}; } }, { - key: '_create', + key: '_unbindTemporaryEvents', /** - * create all dom elements - * TODO: cleanup, lots of similar dom elements + * Unbind the events created by _temporaryBindEvent * @private */ - value: function _create() { - this.frame = document.createElement('div'); - this.frame.className = 'vis-color-picker'; - - this.colorPickerDiv = document.createElement('div'); - this.colorPickerSelector = document.createElement('div'); - this.colorPickerSelector.className = 'vis-selector'; - this.colorPickerDiv.appendChild(this.colorPickerSelector); - - this.colorPickerCanvas = document.createElement('canvas'); - this.colorPickerDiv.appendChild(this.colorPickerCanvas); - - if (!this.colorPickerCanvas.getContext) { - var noCanvas = document.createElement('DIV'); - noCanvas.style.color = 'red'; - noCanvas.style.fontWeight = 'bold'; - noCanvas.style.padding = '10px'; - noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; - this.colorPickerCanvas.appendChild(noCanvas); - } else { - var ctx = this.colorPickerCanvas.getContext('2d'); - this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); - - this.colorPickerCanvas.getContext('2d').setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); + value: function _unbindTemporaryEvents() { + for (var i = 0; i < this.temporaryEventFunctions.length; i++) { + var eventName = this.temporaryEventFunctions[i].event; + var boundFunction = this.temporaryEventFunctions[i].boundFunction; + this.body.emitter.off(eventName, boundFunction); } - - this.colorPickerDiv.className = 'vis-color'; - - this.opacityDiv = document.createElement('div'); - this.opacityDiv.className = 'vis-opacity'; - - this.brightnessDiv = document.createElement('div'); - this.brightnessDiv.className = 'vis-brightness'; - - this.arrowDiv = document.createElement('div'); - this.arrowDiv.className = 'vis-arrow'; - - this.opacityRange = document.createElement('input'); - this.opacityRange.type = 'range'; - this.opacityRange.min = '0'; - this.opacityRange.max = '100'; - this.opacityRange.value = '100'; - this.opacityRange.className = 'vis-range'; - - this.brightnessRange = document.createElement('input'); - this.brightnessRange.type = 'range'; - this.brightnessRange.min = '0'; - this.brightnessRange.max = '100'; - this.brightnessRange.value = '100'; - this.brightnessRange.className = 'vis-range'; - - this.opacityDiv.appendChild(this.opacityRange); - this.brightnessDiv.appendChild(this.brightnessRange); - - var me = this; - this.opacityRange.onchange = function () { - me._setOpacity(this.value); - }; - this.opacityRange.oninput = function () { - me._setOpacity(this.value); - }; - this.brightnessRange.onchange = function () { - me._setBrightness(this.value); - }; - this.brightnessRange.oninput = function () { - me._setBrightness(this.value); - }; - - this.brightnessLabel = document.createElement('div'); - this.brightnessLabel.className = 'vis-label vis-brightness'; - this.brightnessLabel.innerHTML = 'brightness:'; - - this.opacityLabel = document.createElement('div'); - this.opacityLabel.className = 'vis-label vis-opacity'; - this.opacityLabel.innerHTML = 'opacity:'; - - this.newColorDiv = document.createElement('div'); - this.newColorDiv.className = 'vis-new-color'; - this.newColorDiv.innerHTML = 'new'; - - this.initialColorDiv = document.createElement('div'); - this.initialColorDiv.className = 'vis-initial-color'; - this.initialColorDiv.innerHTML = 'initial'; - - this.cancelButton = document.createElement('div'); - this.cancelButton.className = 'vis-button vis-cancel'; - this.cancelButton.innerHTML = 'cancel'; - this.cancelButton.onclick = this._hide.bind(this, false); - - this.applyButton = document.createElement('div'); - this.applyButton.className = 'vis-button vis-apply'; - this.applyButton.innerHTML = 'apply'; - this.applyButton.onclick = this._apply.bind(this); - - this.saveButton = document.createElement('div'); - this.saveButton.className = 'vis-button vis-save'; - this.saveButton.innerHTML = 'save'; - this.saveButton.onclick = this._save.bind(this); - - this.loadButton = document.createElement('div'); - this.loadButton.className = 'vis-button vis-load'; - this.loadButton.innerHTML = 'load last'; - this.loadButton.onclick = this._loadLast.bind(this); - - this.frame.appendChild(this.colorPickerDiv); - this.frame.appendChild(this.arrowDiv); - this.frame.appendChild(this.brightnessLabel); - this.frame.appendChild(this.brightnessDiv); - this.frame.appendChild(this.opacityLabel); - this.frame.appendChild(this.opacityDiv); - this.frame.appendChild(this.newColorDiv); - this.frame.appendChild(this.initialColorDiv); - - this.frame.appendChild(this.cancelButton); - this.frame.appendChild(this.applyButton); - this.frame.appendChild(this.saveButton); - this.frame.appendChild(this.loadButton); + this.temporaryEventFunctions = []; } }, { - key: '_bindHammer', + key: '_bindHammerToDiv', /** - * bind hammer to the color picker - * @private + * Bind an hammer instance to a DOM element. + * @param domElement + * @param funct */ - value: function _bindHammer() { - var _this = this; - - this.drag = {}; - this.pinch = {}; - this.hammer = new Hammer(this.colorPickerCanvas); - this.hammer.get('pinch').set({ enable: true }); - - hammerUtil.onTouch(this.hammer, function (event) { - _this._moveSelector(event); - }); - this.hammer.on('tap', function (event) { - _this._moveSelector(event); - }); - this.hammer.on('panstart', function (event) { - _this._moveSelector(event); - }); - this.hammer.on('panmove', function (event) { - _this._moveSelector(event); - }); - this.hammer.on('panend', function (event) { - _this._moveSelector(event); - }); + value: function _bindHammerToDiv(domElement, boundFunction) { + var hammer = new Hammer(domElement, {}); + hammerUtil.onTouch(hammer, boundFunction); + this.manipulationHammers.push(hammer); } }, { - key: '_generateHueCircle', + key: '_cleanupTemporaryNodesAndEdges', /** - * generate the hue circle. This is relatively heavy (200ms) and is done only once on the first time it is shown. + * Neatly clean up temporary edges and nodes * @private */ - value: function _generateHueCircle() { - if (this.generated === false) { - var ctx = this.colorPickerCanvas.getContext('2d'); - if (this.pixelRation === undefined) { - this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + value: function _cleanupTemporaryNodesAndEdges() { + // _clean temporary edges + for (var i = 0; i < this.temporaryIds.edges.length; i++) { + this.body.edges[this.temporaryIds.edges[i]].disconnect(); + delete this.body.edges[this.temporaryIds.edges[i]]; + var indexTempEdge = this.body.edgeIndices.indexOf(this.temporaryIds.edges[i]); + if (indexTempEdge !== -1) { + this.body.edgeIndices.splice(indexTempEdge, 1); } - ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); - - // clear the canvas - var w = this.colorPickerCanvas.clientWidth; - var h = this.colorPickerCanvas.clientHeight; - ctx.clearRect(0, 0, w, h); + } - // draw hue circle - var x = undefined, - y = undefined, - hue = undefined, - sat = undefined; - this.centerCoordinates = { x: w * 0.5, y: h * 0.5 }; - this.r = 0.49 * w; - var angleConvert = 2 * Math.PI / 360; - var hfac = 1 / 360; - var sfac = 1 / this.r; - var rgb = undefined; - for (hue = 0; hue < 360; hue++) { - for (sat = 0; sat < this.r; sat++) { - x = this.centerCoordinates.x + sat * Math.sin(angleConvert * hue); - y = this.centerCoordinates.y + sat * Math.cos(angleConvert * hue); - rgb = util.HSVToRGB(hue * hfac, sat * sfac, 1); - ctx.fillStyle = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')'; - ctx.fillRect(x - 0.5, y - 0.5, 2, 2); - } + // _clean temporary nodes + for (var i = 0; i < this.temporaryIds.nodes.length; i++) { + delete this.body.nodes[this.temporaryIds.nodes[i]]; + var indexTempNode = this.body.nodeIndices.indexOf(this.temporaryIds.nodes[i]); + if (indexTempNode !== -1) { + this.body.nodeIndices.splice(indexTempNode, 1); } - ctx.strokeStyle = 'rgba(0,0,0,1)'; - ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r); - ctx.stroke(); - - this.hueCircle = ctx.getImageData(0, 0, w, h); } - this.generated = true; + + this.temporaryIds = { nodes: [], edges: [] }; } }, { - key: '_moveSelector', + key: '_controlNodeTouch', + + // ------------------------------------------ EDIT EDGE FUNCTIONS -----------------------------------------// /** - * move the selector. This is called by hammer functions. - * + * the touch is used to get the position of the initial click * @param event * @private */ - value: function _moveSelector(event) { - var rect = this.colorPickerDiv.getBoundingClientRect(); - var left = event.center.x - rect.left; - var top = event.center.y - rect.top; - - var centerY = 0.5 * this.colorPickerDiv.clientHeight; - var centerX = 0.5 * this.colorPickerDiv.clientWidth; - - var x = left - centerX; - var y = top - centerY; - - var angle = Math.atan2(x, y); - var radius = 0.98 * Math.min(Math.sqrt(x * x + y * y), centerX); - - var newTop = Math.cos(angle) * radius + centerY; - var newLeft = Math.sin(angle) * radius + centerX; - - this.colorPickerSelector.style.top = newTop - 0.5 * this.colorPickerSelector.clientHeight + 'px'; - this.colorPickerSelector.style.left = newLeft - 0.5 * this.colorPickerSelector.clientWidth + 'px'; - - // set color - var h = angle / (2 * Math.PI); - h = h < 0 ? h + 1 : h; - var s = radius / this.r; - var hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b); - hsv.h = h; - hsv.s = s; - var rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v); - rgba['a'] = this.color.a; - this.color = rgba; - - // update previews - this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')'; - this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')'; - } - }]); - - return ColorPicker; - })(); - - exports['default'] = ColorPicker; - module.exports = exports['default']; - -/***/ }, -/* 54 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - var util = __webpack_require__(2); - - var errorFound = false; - var allOptions = undefined; - var printStyle = 'background: #FFeeee; color: #dd0000'; - /** - * Used to validate options. - */ - - var Validator = (function () { - function Validator() { - _classCallCheck(this, Validator); - } - - _createClass(Validator, null, [{ - key: 'validate', + value: function _controlNodeTouch(event) { + this.selectionHandler.unselectAll(); + this.lastTouch = this.body.functions.getPointer(event.center); + this.lastTouch.translation = util.extend({}, this.body.view.translation); // copy the object + } + }, { + key: '_controlNodeDragStart', /** - * Main function to be called - * @param options - * @param subObject - * @returns {boolean} + * the drag start is used to mark one of the control nodes as selected. + * @param event + * @private */ - value: function validate(options, referenceOptions, subObject) { - errorFound = false; - allOptions = referenceOptions; - var usedOptions = referenceOptions; - if (subObject !== undefined) { - usedOptions = referenceOptions[subObject]; + value: function _controlNodeDragStart(event) { + var pointer = this.lastTouch; + var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); + var from = this.body.nodes[this.temporaryIds.nodes[0]]; + var to = this.body.nodes[this.temporaryIds.nodes[1]]; + var edge = this.body.edges[this.edgeBeingEditedId]; + this.selectedControlNode = undefined; + + var fromSelect = from.isOverlappingWith(pointerObj); + var toSelect = to.isOverlappingWith(pointerObj); + + if (fromSelect === true) { + this.selectedControlNode = from; + edge.edgeType.from = from; + } else if (toSelect === true) { + this.selectedControlNode = to; + edge.edgeType.to = to; } - Validator.parse(options, usedOptions, []); - return errorFound; + + this.body.emitter.emit('_redraw'); } }, { - key: 'parse', + key: '_controlNodeDrag', /** - * Will traverse an object recursively and check every value - * @param options - * @param referenceOptions - * @param path + * dragging the control nodes or the canvas + * @param event + * @private */ - value: function parse(options, referenceOptions, path) { - for (var option in options) { - if (options.hasOwnProperty(option)) { - Validator.check(option, options, referenceOptions, path); - } + value: function _controlNodeDrag(event) { + this.body.emitter.emit('disablePhysics'); + var pointer = this.body.functions.getPointer(event.center); + var pos = this.canvas.DOMtoCanvas(pointer); + + if (this.selectedControlNode !== undefined) { + this.selectedControlNode.x = pos.x; + this.selectedControlNode.y = pos.y; + } else { + // if the drag was not started properly because the click started outside the network div, start it now. + var diffX = pointer.x - this.lastTouch.x; + var diffY = pointer.y - this.lastTouch.y; + this.body.view.translation = { x: this.lastTouch.translation.x + diffX, y: this.lastTouch.translation.y + diffY }; } + this.body.emitter.emit('_redraw'); } }, { - key: 'check', + key: '_controlNodeDragEnd', /** - * Check every value. If the value is an object, call the parse function on that object. - * @param option - * @param options - * @param referenceOptions - * @param path + * connecting or restoring the control nodes. + * @param event + * @private */ - value: function check(option, options, referenceOptions, path) { - if (referenceOptions[option] === undefined && referenceOptions.__any__ === undefined) { - Validator.getSuggestion(option, referenceOptions, path); - } else if (referenceOptions[option] === undefined && referenceOptions.__any__ !== undefined) { - // __any__ is a wildcard. Any value is accepted and will be further analysed by reference. - if (Validator.getType(options[option]) === 'object') { - Validator.checkFields(option, options, referenceOptions, '__any__', referenceOptions['__any__'].__type__, path); + value: function _controlNodeDragEnd(event) { + var pointer = this.body.functions.getPointer(event.center); + var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); + var edge = this.body.edges[this.edgeBeingEditedId]; + + var overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj); + var node = undefined; + for (var i = overlappingNodeIds.length - 1; i >= 0; i--) { + if (overlappingNodeIds[i] !== this.selectedControlNode.id) { + node = this.body.nodes[overlappingNodeIds[i]]; + break; } - } else { - // Since all options in the reference are objects, we can check whether they are supposed to be object to look for the __type__ field. - if (referenceOptions[option].__type__ !== undefined) { - // if this should be an object, we check if the correct type has been supplied to account for shorthand options. - Validator.checkFields(option, options, referenceOptions, option, referenceOptions[option].__type__, path); + } + + // perform the connection + if (node !== undefined && this.selectedControlNode !== undefined) { + if (node.isCluster === true) { + alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']); } else { - Validator.checkFields(option, options, referenceOptions, option, referenceOptions[option], path); + var from = this.body.nodes[this.temporaryIds.nodes[0]]; + if (this.selectedControlNode.id === from.id) { + this._performEditEdge(node.id, edge.to.id); + } else { + this._performEditEdge(edge.from.id, node.id); + } } + } else { + edge.updateEdgeType(); + this.body.emitter.emit('restorePhysics'); } + this.body.emitter.emit('_redraw'); } }, { - key: 'checkFields', + key: '_handleConnect', + + // ------------------------------------ END OF EDIT EDGE FUNCTIONS -----------------------------------------// + // ------------------------------------------- ADD EDGE FUNCTIONS -----------------------------------------// /** + * the function bound to the selection event. It checks if you want to connect a cluster and changes the description + * to walk the user through the process. * - * @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} refOptionType | This is the type object from the reference options - * @param {Array} path | where in the object is the option + * @private */ - value: function checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path) { - 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') { - if (refOptionType.indexOf(options[option]) === -1) { - console.log('%cInvalid option detected in "' + option + '".' + ' Allowed values are:' + Validator.print(refOptionType) + ' not "' + options[option] + '". ' + Validator.printLocation(path, option), printStyle); - errorFound = true; - } else if (optionType === 'object') { - path = util.copyAndExtendArray(path, option); - Validator.parse(options[option], referenceOptions[referenceOption], path); + value: function _handleConnect(event) { + // check to avoid double fireing of this function. + if (new Date().valueOf() - this.touchTime > 100) { + this.lastTouch = this.body.functions.getPointer(event.center); + this.lastTouch.translation = util.extend({}, this.body.view.translation); // copy the object + + var pointer = this.lastTouch; + var node = this.selectionHandler.getNodeAt(pointer); + + if (node !== undefined) { + if (node.isCluster === true) { + alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']); + } else { + // create a node the temporary line can look at + var targetNode = this._getNewTargetNode(node.x, node.y); + this.body.nodes[targetNode.id] = targetNode; + this.body.nodeIndices.push(targetNode.id); + + // create a temporary edge + var connectionEdge = this.body.functions.createEdge({ + id: 'connectionEdge' + util.randomUUID(), + from: node.id, + to: targetNode.id, + physics: false, + smooth: { + enabled: true, + type: 'continuous', + roundness: 0.5 + } + }); + this.body.edges[connectionEdge.id] = connectionEdge; + this.body.edgeIndices.push(connectionEdge.id); + + this.temporaryIds.nodes.push(targetNode.id); + this.temporaryIds.edges.push(connectionEdge.id); } - } else if (optionType === 'object') { - path = util.copyAndExtendArray(path, option); - Validator.parse(options[option], referenceOptions[referenceOption], path); - } - } else { - if (refOptionObj['undef'] !== undefined && optionType === 'undefined') {} else if (refOptionObj['fn'] !== undefined && optionType === 'function') {} else { - // type of the field is incorrect - console.log('%cInvalid type received for "' + option + '". Expected: ' + Validator.print(Object.keys(refOptionObj)) + '. Received [' + optionType + '] "' + options[option] + '"' + Validator.printLocation(path, option), printStyle); - errorFound = true; } + this.touchTime = new Date().valueOf(); } } }, { - key: 'getType', - value: function getType(object) { - var type = typeof 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'; + key: '_dragControlNode', + value: function _dragControlNode(event) { + var pointer = this.body.functions.getPointer(event.center); + if (this.temporaryIds.nodes[0] !== undefined) { + var targetNode = this.body.nodes[this.temporaryIds.nodes[0]]; // there is only one temp node in the add edge mode. + targetNode.x = this.canvas._XconvertDOMtoCanvas(pointer.x); + targetNode.y = this.canvas._YconvertDOMtoCanvas(pointer.y); + this.body.emitter.emit('_redraw'); + } else { + var diffX = pointer.x - this.lastTouch.x; + var diffY = pointer.y - this.lastTouch.y; + this.body.view.translation = { x: this.lastTouch.translation.x + diffX, y: this.lastTouch.translation.y + diffY }; } - return type; } }, { - key: 'getSuggestion', - value: function getSuggestion(option, options, path) { - var localSearch = Validator.findInOptions(option, options, path, false); - var globalSearch = Validator.findInOptions(option, allOptions, [], true); + key: '_finishConnect', - var localSearchThreshold = 8; - var globalSearchThreshold = 4; + /** + * Connect the new edge to the target if one exists, otherwise remove temp line + * @param event + * @private + */ + value: function _finishConnect(event) { + var pointer = this.body.functions.getPointer(event.center); + var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); - if (localSearch.indexMatch !== undefined) { - console.log('%cUnknown option detected: "' + option + '" in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was incomplete? Did you mean: "' + localSearch.indexMatch + '"?\n\n', printStyle); - } else if (globalSearch.distance <= globalSearchThreshold && localSearch.distance > globalSearch.distance) { - console.log('%cUnknown option detected: "' + option + '" in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was misplaced? Matching option found at: ' + Validator.printLocation(globalSearch.path, globalSearch.closestMatch, ''), printStyle); - } else if (localSearch.distance <= localSearchThreshold) { - console.log('%cUnknown option detected: "' + option + '". Did you mean "' + localSearch.closestMatch + '"?' + Validator.printLocation(localSearch.path, option), printStyle); - } else { - console.log('%cUnknown option detected: "' + option + '". Did you mean one of these: ' + Validator.print(Object.keys(options)) + Validator.printLocation(path, option), printStyle); + // remember the edge id + var connectFromId = undefined; + if (this.temporaryIds.edges[0] !== undefined) { + connectFromId = this.body.edges[this.temporaryIds.edges[0]].fromId; } - errorFound = true; - } - }, { - key: 'findInOptions', + // get the overlapping node but NOT the temporary node; + var overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj); + var node = undefined; + for (var i = overlappingNodeIds.length - 1; i >= 0; i--) { + // if the node id is NOT a temporary node, accept the node. + if (this.temporaryIds.nodes.indexOf(overlappingNodeIds[i]) === -1) { + node = this.body.nodes[overlappingNodeIds[i]]; + break; + } + } - /** - * traverse the options in search for a match. - * @param option - * @param options - * @param path - * @param recursive - * @returns {{closestMatch: string, path: Array, distance: number}} - */ - value: function findInOptions(option, options, path) { - var recursive = arguments[3] === undefined ? false : arguments[3]; + // clean temporary nodes and edges. + this._cleanupTemporaryNodesAndEdges(); - var min = 1000000000; - var closestMatch = ''; - var closestMatchPath = []; - var lowerCaseOption = option.toLowerCase(); - var indexMatch = undefined; - for (var op in options) { - var distance = undefined; - 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; - } + // perform the connection + if (node !== undefined) { + if (node.isCluster === true) { + alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']); } 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; + if (this.body.nodes[connectFromId] !== undefined && this.body.nodes[node.id] !== undefined) { + this._performAddEdge(connectFromId, node.id); } } } - return { closestMatch: closestMatch, path: closestMatchPath, distance: min, indexMatch: indexMatch }; + this.body.emitter.emit('_redraw'); } }, { - key: 'printLocation', - value: function printLocation(path, option) { - var prefix = arguments[2] === undefined ? 'Problem value found at: \n' : arguments[2]; + key: '_performAddNode', - 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 j = 0; j < path.length - i; j++) { - str += ' '; + // --------------------------------------- END OF ADD EDGE FUNCTIONS -------------------------------------// + + // ------------------------------ Performing all the actual data manipulation ------------------------// + + /** + * Adds a node on the specified location + */ + value: function _performAddNode(clickData) { + var _this4 = this; + + var defaultData = { + id: util.randomUUID(), + x: clickData.pointer.canvas.x, + y: clickData.pointer.canvas.y, + label: 'new' + }; + + if (typeof this.options.addNode === 'function') { + if (this.options.addNode.length === 2) { + this.options.addNode(defaultData, function (finalizedData) { + if (finalizedData !== null && finalizedData !== undefined && _this4.inMode === 'addNode') { + // if for whatever reason the mode has changes (due to dataset change) disregard the callback + _this4.body.data.nodes.add(finalizedData); + _this4.showManipulatorToolbar(); + } + }); + } else { + throw new Error('The function for add does not support two arguments (data,callback)'); + this.showManipulatorToolbar(); } - str += '}\n'; + } else { + this.body.data.nodes.add(defaultData); + this.showManipulatorToolbar(); } - return str + '\n\n'; - } - }, { - key: 'print', - value: function print(options) { - return JSON.stringify(options).replace(/(\")|(\[)|(\])|(,"__type__")/g, '').replace(/(\,)/g, ', '); } }, { - key: 'levenshteinDistance', + key: '_performAddEdge', - // 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. + /** + * connect two nodes with a new edge. + * + * @private */ - value: function levenshteinDistance(a, b) { - if (a.length === 0) return b.length; - if (b.length === 0) return a.length; - - var matrix = []; + value: function _performAddEdge(sourceNodeId, targetNodeId) { + var _this5 = this; - // increment along the first column of each row - var i; - for (i = 0; i <= b.length; i++) { - matrix[i] = [i]; + var defaultData = { from: sourceNodeId, to: targetNodeId }; + if (typeof this.options.addEdge === 'function') { + if (this.options.addEdge.length === 2) { + this.options.addEdge(defaultData, function (finalizedData) { + if (finalizedData !== null && finalizedData !== undefined && _this5.inMode === 'addEdge') { + // if for whatever reason the mode has changes (due to dataset change) disregard the callback + _this5.body.data.edges.add(finalizedData); + _this5.selectionHandler.unselectAll(); + _this5.showManipulatorToolbar(); + } + }); + } else { + throw new Error('The function for connect does not support two arguments (data,callback)'); + } + } else { + this.body.data.edges.add(defaultData); + this.selectionHandler.unselectAll(); + this.showManipulatorToolbar(); } + } + }, { + key: '_performEditEdge', - // increment each column in the first row - var j; - for (j = 0; j <= a.length; j++) { - matrix[0][j] = j; - } + /** + * connect two nodes with a new edge. + * + * @private + */ + value: function _performEditEdge(sourceNodeId, targetNodeId) { + var _this6 = this; - // 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 - } + var defaultData = { id: this.edgeBeingEditedId, from: sourceNodeId, to: targetNodeId }; + if (typeof this.options.editEdge === 'function') { + if (this.options.editEdge.length === 2) { + this.options.editEdge(defaultData, function (finalizedData) { + if (finalizedData === null || finalizedData === undefined || _this6.inMode !== 'editEdge') { + // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { + _this6.body.edges[defaultData.id].updateEdgeType(); + _this6.body.emitter.emit('_redraw'); + } else { + _this6.body.data.edges.update(finalizedData); + _this6.selectionHandler.unselectAll(); + _this6.showManipulatorToolbar(); + } + }); + } else { + throw new Error('The function for edit does not support two arguments (data, callback)'); } + } else { + this.body.data.edges.update(defaultData); + this.selectionHandler.unselectAll(); + this.showManipulatorToolbar(); } - - return matrix[b.length][a.length]; } }]); - return Validator; + return ManipulationSystem; })(); - exports['default'] = Validator; - exports.printStyle = printStyle; - - // item is undefined, which is allowed - - // item is a function, which is allowed + exports['default'] = ManipulationSystem; + module.exports = exports['default']; /***/ }, -/* 55 */ +/* 66 */ /***/ function(module, exports, __webpack_require__) { /** @@ -26876,197 +27600,459 @@ return /******/ (function(modules) { // webpackBootstrap var boolean = 'boolean'; var number = 'number'; var array = 'array'; - var date = 'date'; var object = 'object'; // should only be in a __type__ property var dom = 'dom'; - var moment = 'moment'; var fn = 'function'; - var nada = 'null'; var undef = 'undefined'; var any = 'any'; var allOptions = { configure: { enabled: { boolean: boolean }, - filter: { boolean: boolean, fn: fn }, + filter: { boolean: boolean, string: string, array: array, fn: fn }, container: { dom: dom }, - __type__: { object: object, boolean: boolean, fn: fn } - }, - - //globals : - align: { string: string }, - autoResize: { boolean: boolean }, - clickToUse: { boolean: boolean }, - dataAttributes: { string: string, array: array }, - editable: { - add: { boolean: boolean, undef: undef }, - remove: { boolean: boolean, undef: undef }, - updateGroup: { boolean: boolean, undef: undef }, - updateTime: { boolean: boolean, undef: undef }, - __type__: { boolean: boolean, object: object } + showButton: { boolean: boolean }, + __type__: { object: object, boolean: boolean, string: string, array: array, fn: fn } }, - end: { number: number, date: date, string: string, moment: moment }, - format: { - minorLabels: { - millisecond: { string: string, undef: undef }, - second: { string: string, undef: undef }, - minute: { string: string, undef: undef }, - hour: { string: string, undef: undef }, - weekday: { string: string, undef: undef }, - day: { string: string, undef: undef }, - month: { string: string, undef: undef }, - year: { string: string, undef: undef }, - __type__: { object: object } + edges: { + arrows: { + to: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } }, + middle: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } }, + from: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } }, + __type__: { string: ['from', 'to', 'middle'], object: object } }, - majorLabels: { - millisecond: { string: string, undef: undef }, - second: { string: string, undef: undef }, - minute: { string: string, undef: undef }, - hour: { string: string, undef: undef }, - weekday: { string: string, undef: undef }, - day: { string: string, undef: undef }, - month: { string: string, undef: undef }, - year: { string: string, undef: undef }, + color: { + color: { string: string }, + highlight: { string: string }, + hover: { string: string }, + inherit: { string: ['from', 'to', 'both'], boolean: boolean }, + opacity: { number: number }, + __type__: { object: object, string: string } + }, + dashes: { boolean: boolean, array: array }, + font: { + color: { string: string }, + size: { number: number }, // px + face: { string: string }, + background: { string: string }, + strokeWidth: { number: number }, // px + strokeColor: { string: string }, + align: { string: ['horizontal', 'top', 'middle', 'bottom'] }, + __type__: { object: object, string: string } + }, + hidden: { boolean: boolean }, + hoverWidth: { fn: fn, number: number }, + label: { string: string, undef: undef }, + length: { number: number, undef: undef }, + physics: { boolean: boolean }, + scaling: { + min: { number: number }, + max: { number: number }, + label: { + enabled: { boolean: boolean }, + min: { number: number }, + max: { number: number }, + maxVisible: { number: number }, + drawThreshold: { number: number }, + __type__: { object: object, boolean: boolean } + }, + customScalingFunction: { fn: fn }, __type__: { object: object } }, + selectionWidth: { fn: fn, number: number }, + selfReferenceSize: { number: number }, + shadow: { + enabled: { boolean: boolean }, + size: { number: number }, + x: { number: number }, + y: { number: number }, + __type__: { object: object, boolean: boolean } + }, + smooth: { + enabled: { boolean: boolean }, + type: { string: ['dynamic', 'continuous', 'discrete', 'diagonalCross', 'straightCross', 'horizontal', 'vertical', 'curvedCW', 'curvedCCW'] }, + roundness: { number: number }, + __type__: { object: object, boolean: boolean } + }, + title: { string: string, undef: undef }, + width: { number: number }, + value: { number: number, undef: undef }, __type__: { object: object } }, - groupOrder: { string: string, fn: fn }, - height: { string: string, number: number }, - hiddenDates: { object: object, array: array }, - locale: { string: string }, - locales: { - __any__: { object: object }, + groups: { + useDefaultGroups: { boolean: boolean }, + __any__: 'get from nodes, will be overwritten below', __type__: { object: object } }, - margin: { - axis: { number: number }, - item: { - horizontal: { number: number, undef: undef }, - vertical: { number: number, undef: undef }, - __type__: { object: object, number: number } + interaction: { + dragNodes: { boolean: boolean }, + dragView: { boolean: boolean }, + hideEdgesOnDrag: { boolean: boolean }, + hideNodesOnDrag: { boolean: boolean }, + hover: { boolean: boolean }, + keyboard: { + enabled: { boolean: boolean }, + speed: { x: { number: number }, y: { number: number }, zoom: { number: number }, __type__: { object: object } }, + bindToWindow: { boolean: boolean }, + __type__: { object: object, boolean: boolean } }, - __type__: { object: object, number: number } + multiselect: { boolean: boolean }, + navigationButtons: { boolean: boolean }, + selectable: { boolean: boolean }, + selectConnectedEdges: { boolean: boolean }, + hoverConnectedEdges: { boolean: boolean }, + tooltipDelay: { number: number }, + zoomView: { boolean: boolean }, + __type__: { object: object } }, - max: { date: date, number: number, string: string, moment: moment }, - maxHeight: { number: number, string: string }, - min: { date: date, number: number, string: string, moment: moment }, - minHeight: { number: number, string: string }, - moveable: { boolean: boolean }, - multiselect: { boolean: boolean }, - onAdd: { fn: fn }, - onUpdate: { fn: fn }, - onMove: { fn: fn }, - onMoving: { fn: fn }, - onRemove: { fn: fn }, - order: { fn: fn }, - orientation: { - axis: { string: string, undef: undef }, - item: { string: string, undef: undef }, - __type__: { string: string, object: object } + layout: { + randomSeed: { undef: undef, number: number }, + hierarchical: { + enabled: { boolean: boolean }, + levelSeparation: { number: number }, + direction: { string: ['UD', 'DU', 'LR', 'RL'] }, // UD, DU, LR, RL + sortMethod: { string: ['hubsize', 'directed'] }, // hubsize, directed + __type__: { object: object, boolean: boolean } + }, + __type__: { object: object } }, - selectable: { boolean: boolean }, - showCurrentTime: { boolean: boolean }, - showMajorLabels: { boolean: boolean }, - showMinorLabels: { boolean: boolean }, - stack: { boolean: boolean }, - snap: { fn: fn, nada: nada }, - start: { date: date, number: number, string: string, moment: moment }, - template: { fn: fn }, - timeAxis: { - scale: { string: string, undef: undef }, - step: { number: number, undef: undef }, + manipulation: { + enabled: { boolean: boolean }, + initiallyActive: { boolean: boolean }, + addNode: { boolean: boolean, fn: fn }, + addEdge: { boolean: boolean, fn: fn }, + editNode: { fn: fn }, + editEdge: { boolean: boolean, fn: fn }, + deleteNode: { boolean: boolean, fn: fn }, + deleteEdge: { boolean: boolean, fn: fn }, + controlNodeStyle: 'get from nodes, will be overwritten below', + __type__: { object: object, boolean: boolean } + }, + nodes: { + borderWidth: { number: number }, + borderWidthSelected: { number: number, undef: undef }, + brokenImage: { string: string, undef: undef }, + color: { + border: { string: string }, + background: { string: string }, + highlight: { + border: { string: string }, + background: { string: string }, + __type__: { object: object, string: string } + }, + hover: { + border: { string: string }, + background: { string: string }, + __type__: { object: object, string: string } + }, + __type__: { object: object, string: string } + }, + fixed: { + x: { boolean: boolean }, + y: { boolean: boolean }, + __type__: { object: object, boolean: boolean } + }, + font: { + color: { string: string }, + size: { number: number }, // px + face: { string: string }, + background: { string: string }, + strokeWidth: { number: number }, // px + strokeColor: { string: string }, + __type__: { object: object, string: string } + }, + group: { string: string, number: number, undef: undef }, + hidden: { boolean: boolean }, + icon: { + face: { string: string }, + code: { string: string }, //'\uf007', + size: { number: number }, //50, + color: { string: string }, + __type__: { object: object } + }, + id: { string: string, number: number }, + image: { string: string, undef: undef }, // --> URL + label: { string: string, undef: undef }, + level: { number: number, undef: undef }, + mass: { number: number }, + physics: { boolean: boolean }, + scaling: { + min: { number: number }, + max: { number: number }, + label: { + enabled: { boolean: boolean }, + min: { number: number }, + max: { number: number }, + maxVisible: { number: number }, + drawThreshold: { number: number }, + __type__: { object: object, boolean: boolean } + }, + customScalingFunction: { fn: fn }, + __type__: { object: object } + }, + shadow: { + enabled: { boolean: boolean }, + size: { number: number }, + x: { number: number }, + y: { number: number }, + __type__: { object: object, boolean: boolean } + }, + shape: { string: ['ellipse', 'circle', 'database', 'box', 'text', 'image', 'circularImage', 'diamond', 'dot', 'star', 'triangle', 'triangleDown', 'square', 'icon'] }, + size: { number: number }, + title: { string: string, undef: undef }, + value: { number: number, undef: undef }, + x: { number: number }, + y: { number: number }, __type__: { object: object } }, - type: { string: string }, - width: { string: string, number: number }, - zoomable: { boolean: boolean }, - zoomMax: { number: number }, - zoomMin: { number: number }, + physics: { + barnesHut: { + gravitationalConstant: { number: number }, + centralGravity: { number: number }, + springLength: { number: number }, + springConstant: { number: number }, + damping: { number: number }, + avoidOverlap: { number: number }, + __type__: { object: object } + }, + forceAtlas2Based: { + gravitationalConstant: { number: number }, + centralGravity: { number: number }, + springLength: { number: number }, + springConstant: { number: number }, + damping: { number: number }, + avoidOverlap: { number: number }, + __type__: { object: object } + }, + repulsion: { + centralGravity: { number: number }, + springLength: { number: number }, + springConstant: { number: number }, + nodeDistance: { number: number }, + damping: { number: number }, + __type__: { object: object } + }, + hierarchicalRepulsion: { + centralGravity: { number: number }, + springLength: { number: number }, + springConstant: { number: number }, + nodeDistance: { number: number }, + damping: { number: number }, + __type__: { object: object } + }, + maxVelocity: { number: number }, + minVelocity: { number: number }, // px/s + solver: { string: ['barnesHut', 'repulsion', 'hierarchicalRepulsion', 'forceAtlas2Based'] }, + stabilization: { + enabled: { boolean: boolean }, + iterations: { number: number }, // maximum number of iteration to stabilize + updateInterval: { number: number }, + onlyDynamicEdges: { boolean: boolean }, + fit: { boolean: boolean }, + __type__: { object: object, boolean: boolean } + }, + timestep: { number: number }, + __type__: { object: object, boolean: boolean } + }, + //globals : + autoResize: { boolean: boolean }, + clickToUse: { boolean: boolean }, + locale: { string: string }, + locales: { + __any__: { object: object }, + __type__: { object: object } + }, + height: { string: string }, + width: { string: string }, __type__: { object: object } }; + allOptions.groups.__any__ = allOptions.nodes; + allOptions.manipulation.controlNodeStyle = allOptions.nodes; + var configureOptions = { - global: { - align: ['center', 'left', 'right'], - autoResize: true, - clickToUse: false, - // dataAttributes: ['all'], // FIXME: can be 'all' or string[] - editable: { - add: false, - remove: false, - updateGroup: false, - updateTime: false - }, - end: '', - format: { - minorLabels: { - millisecond: 'SSS', - second: 's', - minute: 'HH:mm', - hour: 'HH:mm', - weekday: 'ddd D', - day: 'D', - month: 'MMM', - year: 'YYYY' + nodes: { + borderWidth: [1, 0, 10, 1], + borderWidthSelected: [2, 0, 10, 1], + color: { + border: ['color', '#2B7CE9'], + background: ['color', '#97C2FC'], + highlight: { + border: ['color', '#2B7CE9'], + background: ['color', '#D2E5FF'] }, - majorLabels: { - millisecond: 'HH:mm:ss', - second: 'D MMMM HH:mm', - minute: 'ddd D MMMM', - hour: 'ddd D MMMM', - weekday: 'MMMM YYYY', - day: 'MMMM YYYY', - month: 'YYYY', - year: '' + hover: { + border: ['color', '#2B7CE9'], + background: ['color', '#D2E5FF'] } }, - - //groupOrder: {string, fn}, - height: '', - //hiddenDates: {object, array}, - locale: '', - margin: { - axis: [20, 0, 100, 1], - item: { - horizontal: [10, 0, 100, 1], - vertical: [10, 0, 100, 1] + fixed: { + x: false, + y: false + }, + font: { + color: ['color', '#343434'], + size: [14, 0, 100, 1], // px + face: ['arial', 'verdana', 'tahoma'], + background: ['color', 'none'], + strokeWidth: [0, 0, 50, 1], // px + strokeColor: ['color', '#ffffff'] + }, + //group: 'string', + hidden: false, + //icon: { + // face: 'string', //'FontAwesome', + // code: 'string', //'\uf007', + // size: [50, 0, 200, 1], //50, + // color: ['color','#2B7CE9'] //'#aa00ff' + //}, + //image: 'string', // --> URL + physics: true, + scaling: { + min: [10, 0, 200, 1], + max: [30, 0, 200, 1], + label: { + enabled: false, + min: [14, 0, 200, 1], + max: [30, 0, 200, 1], + maxVisible: [30, 0, 200, 1], + drawThreshold: [5, 0, 20, 1] } }, - max: '', - maxHeight: '', - min: '', - minHeight: '', - moveable: false, + shadow: { + enabled: false, + size: [10, 0, 20, 1], + x: [5, -30, 30, 1], + y: [5, -30, 30, 1] + }, + shape: ['ellipse', 'box', 'circle', 'database', 'diamond', 'dot', 'square', 'star', 'text', 'triangle', 'triangleDown'], + size: [25, 0, 200, 1] + }, + edges: { + arrows: { + to: { enabled: false, scaleFactor: [1, 0, 3, 0.05] }, // boolean / {arrowScaleFactor:1} / {enabled: false, arrowScaleFactor:1} + middle: { enabled: false, scaleFactor: [1, 0, 3, 0.05] }, + from: { enabled: false, scaleFactor: [1, 0, 3, 0.05] } + }, + color: { + color: ['color', '#848484'], + highlight: ['color', '#848484'], + hover: ['color', '#848484'], + inherit: ['from', 'to', 'both', true, false], + opacity: [1, 0, 1, 0.05] + }, + dashes: false, + font: { + color: ['color', '#343434'], + size: [14, 0, 100, 1], // px + face: ['arial', 'verdana', 'tahoma'], + background: ['color', 'none'], + strokeWidth: [2, 0, 50, 1], // px + strokeColor: ['color', '#ffffff'], + align: ['horizontal', 'top', 'middle', 'bottom'] + }, + hidden: false, + hoverWidth: [1.5, 0, 5, 0.1], + physics: true, + scaling: { + min: [1, 0, 100, 1], + max: [15, 0, 100, 1], + label: { + enabled: true, + min: [14, 0, 200, 1], + max: [30, 0, 200, 1], + maxVisible: [30, 0, 200, 1], + drawThreshold: [5, 0, 20, 1] + } + }, + selectionWidth: [1.5, 0, 5, 0.1], + selfReferenceSize: [20, 0, 200, 1], + shadow: { + enabled: false, + size: [10, 0, 20, 1], + x: [5, -30, 30, 1], + y: [5, -30, 30, 1] + }, + smooth: { + enabled: true, + type: ['dynamic', 'continuous', 'discrete', 'diagonalCross', 'straightCross', 'horizontal', 'vertical', 'curvedCW', 'curvedCCW'], + roundness: [0.5, 0, 1, 0.05] + }, + width: [1, 0, 30, 1] + }, + layout: { + //randomSeed: [0, 0, 500, 1], + hierarchical: { + enabled: false, + levelSeparation: [150, 20, 500, 5], + direction: ['UD', 'DU', 'LR', 'RL'], // UD, DU, LR, RL + sortMethod: ['hubsize', 'directed'] // hubsize, directed + } + }, + interaction: { + dragNodes: true, + dragView: true, + hideEdgesOnDrag: false, + hideNodesOnDrag: false, + hover: false, + keyboard: { + enabled: false, + speed: { x: [10, 0, 40, 1], y: [10, 0, 40, 1], zoom: [0.02, 0, 0.1, 0.005] }, + bindToWindow: true + }, multiselect: false, - //onAdd: {fn}, - //onUpdate: {fn}, - //onMove: {fn}, - //onMoving: {fn}, - //onRename: {fn}, - //order: {fn}, - orientation: { - axis: ['both', 'bottom', 'top'], - item: ['bottom', 'top'] + navigationButtons: false, + selectable: true, + selectConnectedEdges: true, + hoverConnectedEdges: true, + tooltipDelay: [300, 0, 1000, 25], + zoomView: true + }, + manipulation: { + enabled: false, + initiallyActive: false + }, + physics: { + barnesHut: { + //theta: [0.5, 0.1, 1, 0.05], + gravitationalConstant: [-2000, -30000, 0, 50], + centralGravity: [0.3, 0, 10, 0.05], + springLength: [95, 0, 500, 5], + springConstant: [0.04, 0, 1.2, 0.005], + damping: [0.09, 0, 1, 0.01], + avoidOverlap: [0, 0, 1, 0.01] + }, + forceAtlas2Based: { + //theta: [0.5, 0.1, 1, 0.05], + gravitationalConstant: [-50, -500, 0, 1], + centralGravity: [0.01, 0, 1, 0.005], + springLength: [95, 0, 500, 5], + springConstant: [0.08, 0, 1.2, 0.005], + damping: [0.4, 0, 1, 0.01], + avoidOverlap: [0, 0, 1, 0.01] + }, + repulsion: { + centralGravity: [0.2, 0, 10, 0.05], + springLength: [200, 0, 500, 5], + springConstant: [0.05, 0, 1.2, 0.005], + nodeDistance: [100, 0, 500, 5], + damping: [0.09, 0, 1, 0.01] + }, + hierarchicalRepulsion: { + centralGravity: [0.2, 0, 10, 0.05], + springLength: [100, 0, 500, 5], + springConstant: [0.01, 0, 1.2, 0.005], + nodeDistance: [120, 0, 500, 5], + damping: [0.09, 0, 1, 0.01] }, - selectable: true, - showCurrentTime: false, - showMajorLabels: true, - showMinorLabels: true, - stack: true, - //snap: {fn, nada}, - start: '', - //template: {fn}, - //timeAxis: { - // scale: ['millisecond', 'second', 'minute', 'hour', 'weekday', 'day', 'month', 'year'], - // step: [1, 1, 10, 1] - //}, - type: ['box', 'point', 'range', 'background'], - width: '100%', - zoomable: true, - zoomMax: [315360000000000, 10, 315360000000000, 1], - zoomMin: [10, 10, 315360000000000, 1] + maxVelocity: [50, 0, 150, 1], + minVelocity: [0.1, 0.01, 0.5, 0.01], + solver: ['barnesHut', 'forceAtlas2Based', 'repulsion', 'hierarchicalRepulsion'], + timestep: [0.5, 0.01, 1, 0.01] + }, + global: { + locale: ['en', 'nl'] } }; @@ -27074,6538 +28060,6885 @@ return /******/ (function(modules) { // webpackBootstrap exports.configureOptions = configureOptions; /***/ }, -/* 56 */ +/* 67 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; - - var Emitter = __webpack_require__(27); - var Hammer = __webpack_require__(13); - var util = __webpack_require__(2); - var DataSet = __webpack_require__(22); - var DataView = __webpack_require__(24); - var Range = __webpack_require__(37); - var Core = __webpack_require__(40); - var TimeAxis = __webpack_require__(48); - var CurrentTime = __webpack_require__(34); - var CustomTime = __webpack_require__(51); - var LineGraph = __webpack_require__(57); - - var Configurator = __webpack_require__(52); - var Validator = __webpack_require__(54)['default']; - var printStyle = __webpack_require__(54).printStyle; - var allOptions = __webpack_require__(65).allOptions; - var configureOptions = __webpack_require__(65).configureOptions; - /** - * Create a timeline visualization - * @param {HTMLElement} container - * @param {vis.DataSet | Array} [items] - * @param {Object} [options] See Graph2d.setOptions for the available options. - * @constructor - * @extends Core + * Canvas shapes used by Network */ - function Graph2d(container, items, groups, options) { - // if the third element is options, the forth is groups (optionally); - if (!(Array.isArray(groups) || groups instanceof DataSet) && groups instanceof Object) { - var forthArgument = options; - options = groups; - groups = forthArgument; - } - - var me = this; - this.defaultOptions = { - start: null, - end: null, + 'use strict'; - autoResize: true, + if (typeof CanvasRenderingContext2D !== 'undefined') { - orientation: { - axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both' - item: 'bottom' // not relevant for Graph2d - }, + /** + * Draw a circle shape + */ + CanvasRenderingContext2D.prototype.circle = function (x, y, r) { + this.beginPath(); + this.arc(x, y, r, 0, 2 * Math.PI, false); + this.closePath(); + }; - width: null, - height: null, - maxHeight: null, - minHeight: null + /** + * Draw a square shape + * @param {Number} x horizontal center + * @param {Number} y vertical center + * @param {Number} r size, width and height of the square + */ + CanvasRenderingContext2D.prototype.square = function (x, y, r) { + this.beginPath(); + this.rect(x - r, y - r, r * 2, r * 2); + this.closePath(); }; - this.options = util.deepExtend({}, this.defaultOptions); - // Create the DOM, props, and emitter - this._create(container); + /** + * Draw a triangle shape + * @param {Number} x horizontal center + * @param {Number} y vertical center + * @param {Number} r radius, half the length of the sides of the triangle + */ + CanvasRenderingContext2D.prototype.triangle = function (x, y, r) { + // http://en.wikipedia.org/wiki/Equilateral_triangle + this.beginPath(); - // all components listed here will be repainted automatically - this.components = []; + // the change in radius and the offset is here to center the shape + r *= 1.15; + y += 0.275 * r; - this.body = { - dom: this.dom, - domProps: this.props, - emitter: { - on: this.on.bind(this), - off: this.off.bind(this), - emit: this.emit.bind(this) - }, - hiddenDates: [], - util: { - toScreen: me._toScreen.bind(me), - toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width - toTime: me._toTime.bind(me), - toGlobalTime: me._toGlobalTime.bind(me) - } + var s = r * 2; + var s2 = s / 2; + var ir = Math.sqrt(3) / 6 * s; // radius of inner circle + var h = Math.sqrt(s * s - s2 * s2); // height + + this.moveTo(x, y - (h - ir)); + this.lineTo(x + s2, y + ir); + this.lineTo(x - s2, y + ir); + this.lineTo(x, y - (h - ir)); + this.closePath(); }; - // range - this.range = new Range(this.body); - this.components.push(this.range); - this.body.range = this.range; + /** + * Draw a triangle shape in downward orientation + * @param {Number} x horizontal center + * @param {Number} y vertical center + * @param {Number} r radius + */ + CanvasRenderingContext2D.prototype.triangleDown = function (x, y, r) { + // http://en.wikipedia.org/wiki/Equilateral_triangle + this.beginPath(); - // time axis - this.timeAxis = new TimeAxis(this.body); - this.components.push(this.timeAxis); - //this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); + // the change in radius and the offset is here to center the shape + r *= 1.15; + y -= 0.275 * r; - // current time bar - this.currentTime = new CurrentTime(this.body); - this.components.push(this.currentTime); + var s = r * 2; + var s2 = s / 2; + var ir = Math.sqrt(3) / 6 * s; // radius of inner circle + var h = Math.sqrt(s * s - s2 * s2); // height - // item set - this.linegraph = new LineGraph(this.body); - this.components.push(this.linegraph); + this.moveTo(x, y + (h - ir)); + this.lineTo(x + s2, y - ir); + this.lineTo(x - s2, y - ir); + this.lineTo(x, y + (h - ir)); + this.closePath(); + }; - this.itemsData = null; // DataSet - this.groupsData = null; // DataSet + /** + * Draw a star shape, a star with 5 points + * @param {Number} x horizontal center + * @param {Number} y vertical center + * @param {Number} r radius, half the length of the sides of the triangle + */ + CanvasRenderingContext2D.prototype.star = function (x, y, r) { + // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/ + this.beginPath(); - this.on('tap', function (event) { - me.emit('click', me.getEventProperties(event)); - }); - this.on('doubletap', function (event) { - me.emit('doubleClick', me.getEventProperties(event)); - }); - this.dom.root.oncontextmenu = function (event) { - me.emit('contextmenu', me.getEventProperties(event)); + // the change in radius and the offset is here to center the shape + r *= 0.82; + y += 0.1 * r; + + for (var n = 0; n < 10; n++) { + var radius = n % 2 === 0 ? r * 1.3 : r * 0.5; + this.lineTo(x + radius * Math.sin(n * 2 * Math.PI / 10), y - radius * Math.cos(n * 2 * Math.PI / 10)); + } + + this.closePath(); }; - // setup configuration system - this.configurator = new Configurator(this, container, configureOptions); + /** + * Draw a Diamond shape + * @param {Number} x horizontal center + * @param {Number} y vertical center + * @param {Number} r radius, half the length of the sides of the triangle + */ + CanvasRenderingContext2D.prototype.diamond = function (x, y, r) { + // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/ + this.beginPath(); - // apply options - if (options) { - this.setOptions(options); - } + this.lineTo(x, y + r); + this.lineTo(x + r, y); + this.lineTo(x, y - r); + this.lineTo(x - r, y); - // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! - if (groups) { - this.setGroups(groups); - } + this.closePath(); + }; - // create itemset - if (items) { - this.setItems(items); - } else { - this._redraw(); - } - } + /** + * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas + */ + CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) { + var r2d = Math.PI / 180; + if (w - 2 * r < 0) { + r = w / 2; + } //ensure that the radius isn't too large for x + if (h - 2 * r < 0) { + r = h / 2; + } //ensure that the radius isn't too large for y + this.beginPath(); + this.moveTo(x + r, y); + this.lineTo(x + w - r, y); + this.arc(x + w - r, y + r, r, r2d * 270, r2d * 360, false); + this.lineTo(x + w, y + h - r); + this.arc(x + w - r, y + h - r, r, 0, r2d * 90, false); + this.lineTo(x + r, y + h); + this.arc(x + r, y + h - r, r, r2d * 90, r2d * 180, false); + this.lineTo(x, y + r); + this.arc(x + r, y + r, r, r2d * 180, r2d * 270, false); + this.closePath(); + }; - // Extend the functionality from Core - Graph2d.prototype = new Core(); + /** + * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + */ + CanvasRenderingContext2D.prototype.ellipse = function (x, y, w, h) { + var kappa = 0.5522848, + ox = w / 2 * kappa, + // control point offset horizontal + oy = h / 2 * kappa, + // control point offset vertical + xe = x + w, + // x-end + ye = y + h, + // y-end + xm = x + w / 2, + // x-middle + ym = y + h / 2; // y-middle - Graph2d.prototype.setOptions = function (options) { - // validate options - var errorFound = Validator.validate(options, allOptions); - if (errorFound === true) { - console.log('%cErrors have been found in the supplied options object.', printStyle); - } + this.beginPath(); + this.moveTo(x, ym); + this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + this.closePath(); + }; - Core.prototype.setOptions.call(this, options); - }; + /** + * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + */ + CanvasRenderingContext2D.prototype.database = function (x, y, w, h) { + var f = 1 / 3; + var wEllipse = w; + var hEllipse = h * f; - /** - * Set items - * @param {vis.DataSet | Array | null} items - */ - Graph2d.prototype.setItems = function (items) { - var initialLoad = this.itemsData == null; + var kappa = 0.5522848, + ox = wEllipse / 2 * kappa, + // control point offset horizontal + oy = hEllipse / 2 * kappa, + // control point offset vertical + xe = x + wEllipse, + // x-end + ye = y + hEllipse, + // y-end + xm = x + wEllipse / 2, + // x-middle + ym = y + hEllipse / 2, + // y-middle + ymb = y + (h - hEllipse / 2), + // y-midlle, bottom ellipse + yeb = y + h; // y-end, bottom ellipse - // convert to type DataSet when needed - var newDataSet; - if (!items) { - newDataSet = null; - } else if (items instanceof DataSet || items instanceof DataView) { - newDataSet = items; - } else { - // turn an array into a dataset - newDataSet = new DataSet(items, { - type: { - start: 'Date', - end: 'Date' - } - }); - } + this.beginPath(); + this.moveTo(xe, ym); - // set items - this.itemsData = newDataSet; - this.linegraph && this.linegraph.setItems(newDataSet); + this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); - if (initialLoad) { - if (this.options.start != undefined || this.options.end != undefined) { - var start = this.options.start != undefined ? this.options.start : null; - var end = this.options.end != undefined ? this.options.end : null; + this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); - this.setWindow(start, end, { animation: false }); - } else { - this.fit({ animation: false }); - } - } - }; + this.lineTo(xe, ymb); - /** - * Set groups - * @param {vis.DataSet | Array} groups - */ - Graph2d.prototype.setGroups = function (groups) { - // convert to type DataSet when needed - var newDataSet; - if (!groups) { - newDataSet = null; - } else if (groups instanceof DataSet || groups instanceof DataView) { - newDataSet = groups; - } else { - // turn an array into a dataset - newDataSet = new DataSet(groups); - } + this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb); + this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb); - this.groupsData = newDataSet; - this.linegraph.setGroups(newDataSet); - }; + this.lineTo(x, ym); + }; - /** - * Returns an object containing an SVG element with the icon of the group (size determined by iconWidth and iconHeight), the label of the group (content) and the yAxisOrientation of the group (left or right). - * @param groupId - * @param width - * @param height - */ - Graph2d.prototype.getLegend = function (groupId, width, height) { - if (width === undefined) { - width = 15; - } - if (height === undefined) { - height = 15; - } - if (this.linegraph.groups[groupId] !== undefined) { - return this.linegraph.groups[groupId].getLegend(width, height); - } else { - return 'cannot find group:' + groupId; - } - }; + /** + * Draw an arrow point (no line) + */ + CanvasRenderingContext2D.prototype.arrow = function (x, y, angle, length) { + // tail + var xt = x - length * Math.cos(angle); + var yt = y - length * Math.sin(angle); - /** - * This checks if the visible option of the supplied group (by ID) is true or false. - * @param groupId - * @returns {*} - */ - Graph2d.prototype.isGroupVisible = function (groupId) { - if (this.linegraph.groups[groupId] !== undefined) { - return this.linegraph.groups[groupId].visible && (this.linegraph.options.groups.visibility[groupId] === undefined || this.linegraph.options.groups.visibility[groupId] == true); - } else { - return false; - } - }; + // inner tail + var xi = x - length * 0.9 * Math.cos(angle); + var yi = y - length * 0.9 * Math.sin(angle); - /** - * Get the data range of the item set. - * @returns {{min: Date, max: Date}} range A range with a start and end Date. - * When no minimum is found, min==null - * When no maximum is found, max==null - */ - Graph2d.prototype.getItemRange = function () { - var min = null; - var max = null; + // left + var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI); + var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI); - // calculate min from start filed - for (var groupId in this.linegraph.groups) { - if (this.linegraph.groups.hasOwnProperty(groupId)) { - if (this.linegraph.groups[groupId].visible == true) { - for (var i = 0; i < this.linegraph.groups[groupId].itemsData.length; i++) { - var item = this.linegraph.groups[groupId].itemsData[i]; - var value = util.convert(item.x, 'Date').valueOf(); - min = min == null ? value : min > value ? value : min; - max = max == null ? value : max < value ? value : max; - } - } - } - } + // right + var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI); + var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI); - return { - min: min != null ? new Date(min) : null, - max: max != null ? new Date(max) : null + this.beginPath(); + this.moveTo(x, y); + this.lineTo(xl, yl); + this.lineTo(xi, yi); + this.lineTo(xr, yr); + this.closePath(); }; - }; - /** - * Generate Timeline related information from an event - * @param {Event} event - * @return {Object} An object with related information, like on which area - * The event happened, whether clicked on an item, etc. - */ - Graph2d.prototype.getEventProperties = function (event) { - var clientX = event.center ? event.center.x : event.clientX; - var clientY = event.center ? event.center.y : event.clientY; - var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer); - var y = clientY - util.getAbsoluteTop(this.dom.centerContainer); - var time = this._toTime(x); + /** + * Sets up the dashedLine functionality for drawing + * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas + * @author David Jordan + * @date 2012-08-08 + */ + CanvasRenderingContext2D.prototype.dashedLine = function (x, y, x2, y2, pattern) { + this.beginPath(); + this.moveTo(x, y); - var customTime = CustomTime.customTimeFromTarget(event); + var patternLength = pattern.length; + var dx = x2 - x; + var dy = y2 - y; + var slope = dy / dx; + var distRemaining = Math.sqrt(dx * dx + dy * dy); + var patternIndex = 0; + var draw = true; + var xStep = 0; + var dashLength = pattern[0]; - var element = util.getTarget(event); - var what = null; - if (util.hasParent(element, this.timeAxis.dom.foreground)) { - what = 'axis'; - } else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) { - what = 'axis'; - } else if (util.hasParent(element, this.linegraph.yAxisLeft.dom.frame)) { - what = 'data-axis'; - } else if (util.hasParent(element, this.linegraph.yAxisRight.dom.frame)) { - what = 'data-axis'; - } else if (util.hasParent(element, this.linegraph.legendLeft.dom.frame)) { - what = 'legend'; - } else if (util.hasParent(element, this.linegraph.legendRight.dom.frame)) { - what = 'legend'; - } else if (customTime != null) { - what = 'custom-time'; - } else if (util.hasParent(element, this.currentTime.bar)) { - what = 'current-time'; - } else if (util.hasParent(element, this.dom.center)) { - what = 'background'; - } + while (distRemaining >= 0.1) { + dashLength = pattern[patternIndex++ % patternLength]; + if (dashLength > distRemaining) { + dashLength = distRemaining; + } - var value = []; - var yAxisLeft = this.linegraph.yAxisLeft; - var yAxisRight = this.linegraph.yAxisRight; - if (!yAxisLeft.hidden) { - value.push(yAxisLeft.screenToValue(y)); - } - if (!yAxisRight.hidden) { - value.push(yAxisRight.screenToValue(y)); - } + xStep = Math.sqrt(dashLength * dashLength / (1 + slope * slope)); + xStep = dx < 0 ? -xStep : xStep; + x += xStep; + y += slope * xStep; - return { - event: event, - what: what, - pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX, - pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY, - x: x, - y: y, - time: time, - value: value - }; - }; + if (draw === true) { + this.lineTo(x, y); + } else { + this.moveTo(x, y); + } - module.exports = Graph2d; + distRemaining -= dashLength; + draw = !draw; + } + }; + } /***/ }, -/* 57 */ +/* 68 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; + var keycharm = __webpack_require__(88); + var Emitter = __webpack_require__(43); + var Hammer = __webpack_require__(41); var util = __webpack_require__(2); - var DOMutil = __webpack_require__(21); - var DataSet = __webpack_require__(22); - var DataView = __webpack_require__(24); - var Component = __webpack_require__(35); - var DataAxis = __webpack_require__(58); - var GraphGroup = __webpack_require__(60); - var Legend = __webpack_require__(64); - var BarFunctions = __webpack_require__(63); - var LineFunctions = __webpack_require__(61); - - var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items /** - * This is the constructor of the LineGraph. It requires a Timeline body and options. - * - * @param body - * @param options + * 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 */ - function LineGraph(body, options) { - this.id = util.randomUUID(); - this.body = body; + function Activator(container) { + this.active = false; - this.defaultOptions = { - yAxisOrientation: 'left', - defaultGroup: 'default', - sort: true, - sampling: true, - stack: false, - graphHeight: '400px', - shaded: { - enabled: false, - orientation: 'bottom' // top, bottom - }, - style: 'line', // line, bar - barChart: { - width: 50, - sideBySide: false, - align: 'center' // left, center, right - }, - interpolation: { - enabled: true, - parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) - alpha: 0.5 - }, - drawPoints: { - enabled: true, - size: 6, - style: 'square' // square, circle - }, - dataAxis: { - showMinorLabels: true, - showMajorLabels: true, - icons: false, - width: '40px', - visible: true, - alignZeros: true, - left: { - range: { min: undefined, max: undefined }, - format: function format(value) { - return value; - }, - title: { text: undefined, style: undefined } - }, - right: { - range: { min: undefined, max: undefined }, - format: function format(value) { - return value; - }, - title: { text: undefined, style: undefined } - } - }, - legend: { - enabled: false, - icons: true, - left: { - visible: true, - position: 'top-left' // top/bottom - left,right - }, - right: { - visible: true, - position: 'top-right' // top/bottom - left,right - } - }, - groups: { - visibility: {} - } + this.dom = { + container: container }; - // options is shared by this ItemSet and all its items - this.options = util.extend({}, this.defaultOptions); - this.dom = {}; - this.props = {}; - this.hammer = null; - this.groups = {}; - this.abortedGraphUpdate = false; - this.updateSVGheight = false; - this.updateSVGheightOnResize = false; + 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; - this.itemsData = null; // DataSet - this.groupsData = null; // DataSet + var events = ['tap', 'doubletap', 'press', 'pinch', 'pan', 'panstart', 'panmove', 'panend']; + events.forEach(function (event) { + me.hammer.on(event, function (event) { + event.stopPropagation(); + }); + }); - // listeners for the DataSet of the items - this.itemListeners = { - 'add': function add(event, params, senderId) { - me._onAdd(params.items); - }, - 'update': function update(event, params, senderId) { - me._onUpdate(params.items); - }, - 'remove': function remove(event, params, senderId) { - me._onRemove(params.items); + // attach a tap event to the window, in order to deactivate when clicking outside the timeline + this.bodyHammer = Hammer(document && document.body, { prevent_default: false }); + this.bodyHammer.on('tap', function (event) { + // deactivate when clicked outside the container + if (!_hasParent(event.target, container)) { + me.deactivate(); } - }; + }); - // listeners for the DataSet of the groups - this.groupListeners = { - 'add': function add(event, params, senderId) { - me._onAddGroups(params.items); - }, - 'update': function update(event, params, senderId) { - me._onUpdateGroups(params.items); - }, - 'remove': function remove(event, params, senderId) { - me._onRemoveGroups(params.items); - } - }; + if (this.keycharm !== undefined) { + this.keycharm.destroy(); + } + this.keycharm = keycharm(); - this.items = {}; // object with an Item for every data item - this.selection = []; // list with the ids of all selected nodes - this.lastStart = this.body.range.start; - this.touchParams = {}; // stores properties while dragging + // keycharm listener only bounded when active) + this.escListener = this.deactivate.bind(this); + } - this.svgElements = {}; - this.setOptions(options); - this.groupsUsingDefaultStyles = [0]; - this.COUNTER = 0; - this.body.emitter.on('rangechanged', function () { - me.lastStart = me.body.range.start; - me.svg.style.left = util.option.asSize(-me.props.width); - me.redraw.call(me, true); - }); + // turn into an event emitter + Emitter(Activator.prototype); - // create the HTML DOM - this._create(); - this.framework = { svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups }; - this.body.emitter.emit('change'); - } + // The currently active activator + Activator.current = null; - LineGraph.prototype = new Component(); + /** + * 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); + + // cleanup hammer instances + this.hammer = null; + this.bodyHammer = null; + // FIXME: cleaning up hammer instances doesn't work (Timeline not removed from memory) + }; /** - * Create the HTML DOM for the ItemSet + * Activate the element + * Overlay is hidden, element is decorated with a blue shadow border */ - LineGraph.prototype._create = function () { - var frame = document.createElement('div'); - frame.className = 'vis-line-graph'; - this.dom.frame = frame; + Activator.prototype.activate = function () { + // we allow only one active activator at a time + if (Activator.current) { + Activator.current.deactivate(); + } + Activator.current = this; - // create svg element for graph drawing. - this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - this.svg.style.position = 'relative'; - this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px'; - this.svg.style.display = 'block'; - frame.appendChild(this.svg); + this.active = true; + this.dom.overlay.style.display = 'none'; + util.addClassName(this.dom.container, 'vis-active'); - // data axis - this.options.dataAxis.orientation = 'left'; - this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups); + this.emit('change'); + this.emit('activate'); - this.options.dataAxis.orientation = 'right'; - this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups); - delete this.options.dataAxis.orientation; + // 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); + }; - // legends - this.legendLeft = new Legend(this.body, this.options.legend, 'left', this.options.groups); - this.legendRight = new Legend(this.body, this.options.legend, 'right', this.options.groups); + /** + * 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.show(); + this.emit('change'); + this.emit('deactivate'); }; /** - * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element. - * @param {object} options + * Handle a tap event: activate the container + * @param event + * @private */ - LineGraph.prototype.setOptions = function (options) { - if (options) { - var fields = ['sampling', 'defaultGroup', 'stack', 'height', 'graphHeight', 'yAxisOrientation', 'style', 'barChart', 'dataAxis', 'sort', 'groups']; - if (options.graphHeight === undefined && options.height !== undefined && this.body.domProps.centerContainer.height !== undefined) { - this.updateSVGheight = true; - this.updateSVGheightOnResize = true; - } else if (this.body.domProps.centerContainer.height !== undefined && options.graphHeight !== undefined) { - if (parseInt((options.graphHeight + '').replace('px', '')) < this.body.domProps.centerContainer.height) { - this.updateSVGheight = true; - } + 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; } - util.selectiveDeepExtend(fields, this.options, options); - util.mergeOptions(this.options, options, 'interpolation'); - util.mergeOptions(this.options, options, 'drawPoints'); - util.mergeOptions(this.options, options, 'shaded'); - util.mergeOptions(this.options, options, 'legend'); + element = element.parentNode; + } + return false; + } - if (options.interpolation) { - if (typeof options.interpolation == 'object') { - if (options.interpolation.parametrization) { - if (options.interpolation.parametrization == 'uniform') { - this.options.interpolation.alpha = 0; - } else if (options.interpolation.parametrization == 'chordal') { - this.options.interpolation.alpha = 1; - } else { - this.options.interpolation.parametrization = 'centripetal'; - this.options.interpolation.alpha = 0.5; - } - } - } + module.exports = Activator; + +/***/ }, +/* 69 */ +/***/ function(module, exports, __webpack_require__) { + + // English + 'use strict'; + + exports['en'] = { + edit: 'Edit', + del: 'Delete selected', + back: 'Back', + addNode: 'Add Node', + addEdge: 'Add Edge', + editNode: 'Edit Node', + editEdge: 'Edit Edge', + addDescription: 'Click in an empty space to place a new node.', + edgeDescription: 'Click on a node and drag the edge to another node to connect them.', + editEdgeDescription: 'Click on the control points and drag them to a node to connect to it.', + createEdgeError: 'Cannot link edges to a cluster.', + deleteClusterError: 'Clusters cannot be deleted.', + editClusterError: 'Clusters cannot be edited.' + }; + exports['en_EN'] = exports['en']; + exports['en_US'] = exports['en']; + + // Dutch + exports['nl'] = { + edit: 'Wijzigen', + del: 'Selectie verwijderen', + back: 'Terug', + addNode: 'Node toevoegen', + addEdge: 'Link toevoegen', + editNode: 'Node wijzigen', + editEdge: 'Link wijzigen', + addDescription: 'Klik op een leeg gebied om een nieuwe node te maken.', + edgeDescription: 'Klik op een node en sleep de link naar een andere node om ze te verbinden.', + editEdgeDescription: 'Klik op de verbindingspunten en sleep ze naar een node om daarmee te verbinden.', + createEdgeError: 'Kan geen link maken naar een cluster.', + deleteClusterError: 'Clusters kunnen niet worden verwijderd.', + editClusterError: 'Clusters kunnen niet worden aangepast.' + }; + exports['nl_NL'] = exports['nl']; + exports['nl_BE'] = exports['nl']; + +/***/ }, +/* 70 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(module) {//! moment.js + //! version : 2.10.3 + //! authors : Tim Wood, Iskren Chernev, Moment.js contributors + //! license : MIT + //! momentjs.com + + (function (global, factory) { + true ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + global.moment = factory() + }(this, function () { 'use strict'; + + var hookCallback; + + function utils_hooks__hooks () { + return hookCallback.apply(null, arguments); } - if (this.yAxisLeft) { - if (options.dataAxis !== undefined) { - this.yAxisLeft.setOptions(this.options.dataAxis); - this.yAxisRight.setOptions(this.options.dataAxis); - } + // This is done to register the method called with moment() + // without creating circular dependencies. + function setHookCallback (callback) { + hookCallback = callback; } - if (this.legendLeft) { - if (options.legend !== undefined) { - this.legendLeft.setOptions(this.options.legend); - this.legendRight.setOptions(this.options.legend); - } + function isArray(input) { + return Object.prototype.toString.call(input) === '[object Array]'; } - if (this.groups.hasOwnProperty(UNGROUPED)) { - this.groups[UNGROUPED].setOptions(options); + function isDate(input) { + return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; } - } - // this is used to redraw the graph if the visibility of the groups is changed. - if (this.dom.frame) { - this.redraw(true); - } - }; + function map(arr, fn) { + var res = [], i; + for (i = 0; i < arr.length; ++i) { + res.push(fn(arr[i], i)); + } + return res; + } - /** - * Hide the component from the DOM - */ - LineGraph.prototype.hide = function () { - // remove the frame containing the items - if (this.dom.frame.parentNode) { - this.dom.frame.parentNode.removeChild(this.dom.frame); - } - }; + function hasOwnProp(a, b) { + return Object.prototype.hasOwnProperty.call(a, b); + } - /** - * Show the component in the DOM (when not already visible). - * @return {Boolean} changed - */ - LineGraph.prototype.show = function () { - // show frame containing the items - if (!this.dom.frame.parentNode) { - this.body.dom.center.appendChild(this.dom.frame); - } - }; + function extend(a, b) { + for (var i in b) { + if (hasOwnProp(b, i)) { + a[i] = b[i]; + } + } - /** - * Set items - * @param {vis.DataSet | null} items - */ - LineGraph.prototype.setItems = function (items) { - var me = this, - ids, - oldItemsData = this.itemsData; + if (hasOwnProp(b, 'toString')) { + a.toString = b.toString; + } - // 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 (hasOwnProp(b, 'valueOf')) { + a.valueOf = b.valueOf; + } + + return a; + } + + function create_utc__createUTC (input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, true).utc(); + } + + function defaultParsingFlags() { + // We need to deep clone this object. + return { + empty : false, + unusedTokens : [], + unusedInput : [], + overflow : -2, + charsLeftOver : 0, + nullInput : false, + invalidMonth : null, + invalidFormat : false, + userInvalidated : false, + iso : false + }; + } + + function getParsingFlags(m) { + if (m._pf == null) { + m._pf = defaultParsingFlags(); + } + return m._pf; + } + + function valid__isValid(m) { + if (m._isValid == null) { + var flags = getParsingFlags(m); + m._isValid = !isNaN(m._d.getTime()) && + flags.overflow < 0 && + !flags.empty && + !flags.invalidMonth && + !flags.nullInput && + !flags.invalidFormat && + !flags.userInvalidated; + + if (m._strict) { + m._isValid = m._isValid && + flags.charsLeftOver === 0 && + flags.unusedTokens.length === 0 && + flags.bigHour === undefined; + } + } + return m._isValid; + } - if (oldItemsData) { - // unsubscribe from old dataset - util.forEach(this.itemListeners, function (callback, event) { - oldItemsData.off(event, callback); - }); + function valid__createInvalid (flags) { + var m = create_utc__createUTC(NaN); + if (flags != null) { + extend(getParsingFlags(m), flags); + } + else { + getParsingFlags(m).userInvalidated = true; + } - // remove all drawn items - ids = oldItemsData.getIds(); - this._onRemove(ids); - } + return m; + } - if (this.itemsData) { - // subscribe to new dataset - var id = this.id; - util.forEach(this.itemListeners, function (callback, event) { - me.itemsData.on(event, callback, id); - }); + var momentProperties = utils_hooks__hooks.momentProperties = []; - // add all new items - ids = this.itemsData.getIds(); - this._onAdd(ids); - } - this._updateUngrouped(); - //this._updateGraph(); - this.redraw(true); - }; + function copyConfig(to, from) { + var i, prop, val; - /** - * Set groups - * @param {vis.DataSet} groups - */ - LineGraph.prototype.setGroups = function (groups) { - var me = this; - var ids; + if (typeof from._isAMomentObject !== 'undefined') { + to._isAMomentObject = from._isAMomentObject; + } + if (typeof from._i !== 'undefined') { + to._i = from._i; + } + if (typeof from._f !== 'undefined') { + to._f = from._f; + } + if (typeof from._l !== 'undefined') { + to._l = from._l; + } + if (typeof from._strict !== 'undefined') { + to._strict = from._strict; + } + if (typeof from._tzm !== 'undefined') { + to._tzm = from._tzm; + } + if (typeof from._isUTC !== 'undefined') { + to._isUTC = from._isUTC; + } + if (typeof from._offset !== 'undefined') { + to._offset = from._offset; + } + if (typeof from._pf !== 'undefined') { + to._pf = getParsingFlags(from); + } + if (typeof from._locale !== 'undefined') { + to._locale = from._locale; + } - // unsubscribe from current dataset - if (this.groupsData) { - util.forEach(this.groupListeners, function (callback, event) { - me.groupsData.off(event, callback); - }); + if (momentProperties.length > 0) { + for (i in momentProperties) { + prop = momentProperties[i]; + val = from[prop]; + if (typeof val !== 'undefined') { + to[prop] = val; + } + } + } - // remove all drawn groups - ids = this.groupsData.getIds(); - this.groupsData = null; - this._onRemoveGroups(ids); // note: this will cause a redraw - } + return to; + } - // 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'); - } + var updateInProgress = false; - if (this.groupsData) { - // subscribe to new dataset - var id = this.id; - util.forEach(this.groupListeners, function (callback, event) { - me.groupsData.on(event, callback, id); - }); + // Moment prototype object + function Moment(config) { + copyConfig(this, config); + this._d = new Date(+config._d); + // Prevent infinite loop in case updateOffset creates new moment + // objects. + if (updateInProgress === false) { + updateInProgress = true; + utils_hooks__hooks.updateOffset(this); + updateInProgress = false; + } + } - // draw all ms - ids = this.groupsData.getIds(); - this._onAddGroups(ids); - } - this._onUpdate(); - }; + function isMoment (obj) { + return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); + } - /** - * Update the data - * @param [ids] - * @private - */ - LineGraph.prototype._onUpdate = function (ids) { - this._updateUngrouped(); - this._updateAllGroupData(); - //this._updateGraph(); - this.redraw(true); - }; - LineGraph.prototype._onAdd = function (ids) { - this._onUpdate(ids); - }; - LineGraph.prototype._onRemove = function (ids) { - this._onUpdate(ids); - }; - LineGraph.prototype._onUpdateGroups = function (groupIds) { - for (var i = 0; i < groupIds.length; i++) { - var group = this.groupsData.get(groupIds[i]); - this._updateGroup(group, groupIds[i]); - } + function toInt(argumentForCoercion) { + var coercedNumber = +argumentForCoercion, + value = 0; - //this._updateGraph(); - this.redraw(true); - }; - LineGraph.prototype._onAddGroups = function (groupIds) { - this._onUpdateGroups(groupIds); - }; + if (coercedNumber !== 0 && isFinite(coercedNumber)) { + if (coercedNumber >= 0) { + value = Math.floor(coercedNumber); + } else { + value = Math.ceil(coercedNumber); + } + } - /** - * this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph - * @param {Array} groupIds - * @private - */ - LineGraph.prototype._onRemoveGroups = function (groupIds) { - for (var i = 0; i < groupIds.length; i++) { - if (this.groups.hasOwnProperty(groupIds[i])) { - if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') { - this.yAxisRight.removeGroup(groupIds[i]); - this.legendRight.removeGroup(groupIds[i]); - this.legendRight.redraw(); - } else { - this.yAxisLeft.removeGroup(groupIds[i]); - this.legendLeft.removeGroup(groupIds[i]); - this.legendLeft.redraw(); - } - delete this.groups[groupIds[i]]; + return value; } - } - this._updateUngrouped(); - //this._updateGraph(); - this.redraw(true); - }; - /** - * update a group object with the group dataset entree - * - * @param group - * @param groupId - * @private - */ - LineGraph.prototype._updateGroup = function (group, groupId) { - if (!this.groups.hasOwnProperty(groupId)) { - this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles); - if (this.groups[groupId].options.yAxisOrientation == 'right') { - this.yAxisRight.addGroup(groupId, this.groups[groupId]); - this.legendRight.addGroup(groupId, this.groups[groupId]); - } else { - this.yAxisLeft.addGroup(groupId, this.groups[groupId]); - this.legendLeft.addGroup(groupId, this.groups[groupId]); + function compareArrays(array1, array2, dontConvert) { + var len = Math.min(array1.length, array2.length), + lengthDiff = Math.abs(array1.length - array2.length), + diffs = 0, + i; + for (i = 0; i < len; i++) { + if ((dontConvert && array1[i] !== array2[i]) || + (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { + diffs++; + } + } + return diffs + lengthDiff; } - } else { - this.groups[groupId].update(group); - if (this.groups[groupId].options.yAxisOrientation == 'right') { - this.yAxisRight.updateGroup(groupId, this.groups[groupId]); - this.legendRight.updateGroup(groupId, this.groups[groupId]); - } else { - this.yAxisLeft.updateGroup(groupId, this.groups[groupId]); - this.legendLeft.updateGroup(groupId, this.groups[groupId]); + + function Locale() { } - } - this.legendLeft.redraw(); - this.legendRight.redraw(); - }; - /** - * this updates all groups, it is used when there is an update the the itemset. - * - * @private - */ - LineGraph.prototype._updateAllGroupData = function () { - if (this.itemsData != null) { - var groupsContent = {}; - var groupId; - for (groupId in this.groups) { - if (this.groups.hasOwnProperty(groupId)) { - groupsContent[groupId] = []; - } + var locales = {}; + var globalLocale; + + function normalizeLocale(key) { + return key ? key.toLowerCase().replace('_', '-') : key; } - for (var itemId in this.itemsData._data) { - if (this.itemsData._data.hasOwnProperty(itemId)) { - var item = this.itemsData._data[itemId]; - if (groupsContent[item.group] === undefined) { - throw new Error('Cannot find referenced group. Possible reason: items added before groups? Groups need to be added before items, as items refer to groups.'); + + // pick the locale from the array + // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each + // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root + function chooseLocale(names) { + var i = 0, j, next, locale, split; + + while (i < names.length) { + split = normalizeLocale(names[i]).split('-'); + j = split.length; + next = normalizeLocale(names[i + 1]); + next = next ? next.split('-') : null; + while (j > 0) { + locale = loadLocale(split.slice(0, j).join('-')); + if (locale) { + return locale; + } + if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { + //the next array item is better than a shallower substring of this one + break; + } + j--; + } + i++; } - item.x = util.convert(item.x, 'Date'); - groupsContent[item.group].push(item); - } + return null; } - for (groupId in this.groups) { - if (this.groups.hasOwnProperty(groupId)) { - this.groups[groupId].setItems(groupsContent[groupId]); - } + + function loadLocale(name) { + var oldLocale = null; + // TODO: Find a better way to register and load all the locales in Node + if (!locales[name] && typeof module !== 'undefined' && + module && module.exports) { + try { + oldLocale = globalLocale._abbr; + !(function webpackMissingModule() { var e = new Error("Cannot find module \"./locale\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()); + // because defineLocale currently also sets the global locale, we + // want to undo that for lazy loaded locales + locale_locales__getSetGlobalLocale(oldLocale); + } catch (e) { } + } + return locales[name]; } - } - }; - /** - * Create or delete the group holding all ungrouped items. This group is used when - * there are no groups specified. This anonymous group is called 'graph'. - * @protected - */ - LineGraph.prototype._updateUngrouped = function () { - if (this.itemsData && this.itemsData != null) { - var ungroupedCounter = 0; - for (var itemId in this.itemsData._data) { - if (this.itemsData._data.hasOwnProperty(itemId)) { - var item = this.itemsData._data[itemId]; - if (item != undefined) { - if (item.hasOwnProperty('group')) { - if (item.group === undefined) { - item.group = UNGROUPED; + // This function will load locale and then set the global locale. If + // no arguments are passed in, it will simply return the current global + // locale key. + function locale_locales__getSetGlobalLocale (key, values) { + var data; + if (key) { + if (typeof values === 'undefined') { + data = locale_locales__getLocale(key); + } + else { + data = defineLocale(key, values); + } + + if (data) { + // moment.duration._locale = moment._locale = data; + globalLocale = data; } - } else { - item.group = UNGROUPED; - } - ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter; } - } - } - if (ungroupedCounter == 0) { - delete this.groups[UNGROUPED]; - this.legendLeft.removeGroup(UNGROUPED); - this.legendRight.removeGroup(UNGROUPED); - this.yAxisLeft.removeGroup(UNGROUPED); - this.yAxisRight.removeGroup(UNGROUPED); - } else { - var group = { id: UNGROUPED, content: this.options.defaultGroup }; - this._updateGroup(group, UNGROUPED); + return globalLocale._abbr; } - } else { - delete this.groups[UNGROUPED]; - this.legendLeft.removeGroup(UNGROUPED); - this.legendRight.removeGroup(UNGROUPED); - this.yAxisLeft.removeGroup(UNGROUPED); - this.yAxisRight.removeGroup(UNGROUPED); - } - this.legendLeft.redraw(); - this.legendRight.redraw(); - }; + function defineLocale (name, values) { + if (values !== null) { + values.abbr = name; + if (!locales[name]) { + locales[name] = new Locale(); + } + locales[name].set(values); - /** - * Redraw the component, mandatory function - * @return {boolean} Returns true if the component is resized - */ - LineGraph.prototype.redraw = function (forceGraphUpdate) { - var resized = false; + // backwards compat for now: also set the locale + locale_locales__getSetGlobalLocale(name); - // calculate actual size and position - this.props.width = this.dom.frame.offsetWidth; - this.props.height = this.body.domProps.centerContainer.height - this.body.domProps.border.top - this.body.domProps.border.bottom; + return locales[name]; + } else { + // useful for testing + delete locales[name]; + return null; + } + } - // update the graph if there is no lastWidth or with, used for the initial draw - if (this.lastWidth === undefined && this.props.width) { - forceGraphUpdate = true; - } + // returns locale data + function locale_locales__getLocale (key) { + var locale; - // check if this component is resized - resized = this._isResized() || resized; + if (key && key._locale && key._locale._abbr) { + key = key._locale._abbr; + } - // check whether zoomed (in that case we need to re-stack everything) - var visibleInterval = this.body.range.end - this.body.range.start; - var zoomed = visibleInterval != this.lastVisibleInterval; - this.lastVisibleInterval = visibleInterval; + if (!key) { + return globalLocale; + } - // the svg element is three times as big as the width, this allows for fully dragging left and right - // without reloading the graph. the controls for this are bound to events in the constructor - if (resized == true) { - this.svg.style.width = util.option.asSize(3 * this.props.width); - this.svg.style.left = util.option.asSize(-this.props.width); + if (!isArray(key)) { + //short-circuit everything else + locale = loadLocale(key); + if (locale) { + return locale; + } + key = [key]; + } - // if the height of the graph is set as proportional, change the height of the svg - if ((this.options.height + '').indexOf('%') != -1 || this.updateSVGheightOnResize == true) { - this.updateSVGheight = true; + return chooseLocale(key); } - } - // update the height of the graph on each redraw of the graph. - if (this.updateSVGheight == true) { - if (this.options.graphHeight != this.props.height + 'px') { - this.options.graphHeight = this.props.height + 'px'; - this.svg.style.height = this.props.height + 'px'; - } - this.updateSVGheight = false; - } else { - this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px'; - } + var aliases = {}; - // zoomed is here to ensure that animations are shown correctly. - if (resized == true || zoomed == true || this.abortedGraphUpdate == true || forceGraphUpdate == true) { - resized = this._updateGraph() || resized; - } else { - // move the whole svg while dragging - if (this.lastStart != 0) { - var offset = this.body.range.start - this.lastStart; - var range = this.body.range.end - this.body.range.start; - if (this.props.width != 0) { - var rangePerPixelInv = this.props.width / range; - var xOffset = offset * rangePerPixelInv; - this.svg.style.left = -this.props.width - xOffset + 'px'; - } + function addUnitAlias (unit, shorthand) { + var lowerCase = unit.toLowerCase(); + aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; } - } - this.legendLeft.redraw(); - this.legendRight.redraw(); - return resized; - }; + function normalizeUnits(units) { + return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; + } - /** - * Update and redraw the graph. - * - */ - LineGraph.prototype._updateGraph = function () { - // reset the svg elements - DOMutil.prepareElements(this.svgElements); - if (this.props.width != 0 && this.itemsData != null) { - var group, i; - var preprocessedGroupData = {}; - var processedGroupData = {}; - var groupRanges = {}; - var changeCalled = false; + function normalizeObjectUnits(inputObject) { + var normalizedInput = {}, + normalizedProp, + prop; - // getting group Ids - var groupIds = []; - for (var groupId in this.groups) { - if (this.groups.hasOwnProperty(groupId)) { - group = this.groups[groupId]; - if (group.visible == true && (this.options.groups.visibility[groupId] === undefined || this.options.groups.visibility[groupId] == true)) { - groupIds.push(groupId); + for (prop in inputObject) { + if (hasOwnProp(inputObject, prop)) { + normalizedProp = normalizeUnits(prop); + if (normalizedProp) { + normalizedInput[normalizedProp] = inputObject[prop]; + } + } } - } + + return normalizedInput; + } + + function makeGetSet (unit, keepTime) { + return function (value) { + if (value != null) { + get_set__set(this, unit, value); + utils_hooks__hooks.updateOffset(this, keepTime); + return this; + } else { + return get_set__get(this, unit); + } + }; } - if (groupIds.length > 0) { - // this is the range of the SVG canvas - var minDate = this.body.util.toGlobalTime(-this.body.domProps.root.width); - var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width); - var groupsData = {}; - // fill groups data, this only loads the data we require based on the timewindow - this._getRelevantData(groupIds, groupsData, minDate, maxDate); - // apply sampling, if disabled, it will pass through this function. - this._applySampling(groupIds, groupsData); + function get_set__get (mom, unit) { + return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); + } - // we transform the X coordinates to detect collisions - for (i = 0; i < groupIds.length; i++) { - preprocessedGroupData[groupIds[i]] = this._convertXcoordinates(groupsData[groupIds[i]]); - } + function get_set__set (mom, unit, value) { + return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); + } - // now all needed data has been collected we start the processing. - this._getYRanges(groupIds, preprocessedGroupData, groupRanges); + // MOMENTS - // update the Y axis first, we use this data to draw at the correct Y points - // changeCalled is required to clean the SVG on a change emit. - changeCalled = this._updateYAxis(groupIds, groupRanges); - var MAX_CYCLES = 5; - if (changeCalled == true && this.COUNTER < MAX_CYCLES) { - DOMutil.cleanupElements(this.svgElements); - this.abortedGraphUpdate = true; - this.COUNTER++; - this.body.emitter.emit('change'); - return true; - } else { - if (this.COUNTER > MAX_CYCLES) { - console.log('WARNING: there may be an infinite loop in the _updateGraph emitter cycle.'); + function getSet (units, value) { + var unit; + if (typeof units === 'object') { + for (unit in units) { + this.set(unit, units[unit]); + } + } else { + units = normalizeUnits(units); + if (typeof this[units] === 'function') { + return this[units](value); + } } - this.COUNTER = 0; - this.abortedGraphUpdate = false; + return this; + } - // With the yAxis scaled correctly, use this to get the Y values of the points. - for (i = 0; i < groupIds.length; i++) { - group = this.groups[groupIds[i]]; - processedGroupData[groupIds[i]] = this._convertYcoordinates(groupsData[groupIds[i]], group); - } + function zeroFill(number, targetLength, forceSign) { + var output = '' + Math.abs(number), + sign = number >= 0; - // draw the groups - for (i = 0; i < groupIds.length; i++) { - group = this.groups[groupIds[i]]; - if (group.options.style != 'bar') { - // bar needs to be drawn enmasse - group.draw(processedGroupData[groupIds[i]], group, this.framework); - } + while (output.length < targetLength) { + output = '0' + output; } - BarFunctions.draw(groupIds, processedGroupData, this.framework); - } + return (sign ? (forceSign ? '+' : '') : '-') + output; } - } - // cleanup unused svg elements - DOMutil.cleanupElements(this.svgElements); - return false; - }; + var formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g; - /** - * first select and preprocess the data from the datasets. - * the groups have their preselection of data, we now loop over this data to see - * what data we need to draw. Sorted data is much faster. - * more optimization is possible by doing the sampling before and using the binary search - * to find the end date to determine the increment. - * - * @param {array} groupIds - * @param {object} groupsData - * @param {date} minDate - * @param {date} maxDate - * @private - */ - LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) { - var group, i, j, item; - if (groupIds.length > 0) { - for (i = 0; i < groupIds.length; i++) { - group = this.groups[groupIds[i]]; - groupsData[groupIds[i]] = []; - var dataContainer = groupsData[groupIds[i]]; - // optimization for sorted data - if (group.options.sort == true) { - var guess = Math.max(0, util.binarySearchValue(group.itemsData, minDate, 'x', 'before')); - for (j = guess; j < group.itemsData.length; j++) { - item = group.itemsData[j]; - if (item !== undefined) { - if (item.x > maxDate) { - dataContainer.push(item); - break; - } else { - dataContainer.push(item); - } - } - } - } else { - for (j = 0; j < group.itemsData.length; j++) { - item = group.itemsData[j]; - if (item !== undefined) { - if (item.x > minDate && item.x < maxDate) { - dataContainer.push(item); - } - } - } - } - } - } - }; + var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; - /** - * - * @param groupIds - * @param groupsData - * @private - */ - LineGraph.prototype._applySampling = function (groupIds, groupsData) { - var group; - if (groupIds.length > 0) { - for (var i = 0; i < groupIds.length; i++) { - group = this.groups[groupIds[i]]; - if (group.options.sampling == true) { - var dataContainer = groupsData[groupIds[i]]; - if (dataContainer.length > 0) { - var increment = 1; - var amountOfPoints = dataContainer.length; + var formatFunctions = {}; - // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop - // of width changing of the yAxis. - var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x); - var pointsPerPixel = amountOfPoints / xDistance; - increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel))); + var formatTokenFunctions = {}; - var sampledData = []; - for (var j = 0; j < amountOfPoints; j += increment) { - sampledData.push(dataContainer[j]); - } - groupsData[groupIds[i]] = sampledData; + // token: 'M' + // padded: ['MM', 2] + // ordinal: 'Mo' + // callback: function () { this.month() + 1 } + function addFormatToken (token, padded, ordinal, callback) { + var func = callback; + if (typeof callback === 'string') { + func = function () { + return this[callback](); + }; + } + if (token) { + formatTokenFunctions[token] = func; + } + if (padded) { + formatTokenFunctions[padded[0]] = function () { + return zeroFill(func.apply(this, arguments), padded[1], padded[2]); + }; + } + if (ordinal) { + formatTokenFunctions[ordinal] = function () { + return this.localeData().ordinal(func.apply(this, arguments), token); + }; } - } } - } - }; - /** - * - * - * @param {array} groupIds - * @param {object} groupsData - * @param {object} groupRanges | this is being filled here - * @private - */ - LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) { - var groupData, group, i; - var combinedDataLeft = []; - var combinedDataRight = []; - var options; - if (groupIds.length > 0) { - for (i = 0; i < groupIds.length; i++) { - groupData = groupsData[groupIds[i]]; - options = this.groups[groupIds[i]].options; - if (groupData.length > 0) { - group = this.groups[groupIds[i]]; - // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups. - if (options.stack === true) { - if (options.yAxisOrientation == 'left') { - combinedDataLeft = combinedDataLeft.concat(group.getData(groupData)); - } else { - combinedDataRight = combinedDataRight.concat(group.getData(groupData)); - } - } else { - groupRanges[groupIds[i]] = group.getYRange(groupData, groupIds[i]); + function removeFormattingTokens(input) { + if (input.match(/\[[\s\S]/)) { + return input.replace(/^\[|\]$/g, ''); } - } + return input.replace(/\\/g, ''); } - // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups. - BarFunctions.getStackedYRange(combinedDataLeft, groupRanges, groupIds, '__barStackLeft', 'left'); - BarFunctions.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__barStackRight', 'right'); - // if line graphs are stacked, their range need to be handled differently and accumulated over all groups. - LineFunctions.getStackedYRange(combinedDataLeft, groupRanges, groupIds, '__lineStackLeft', 'left'); - LineFunctions.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__lineStackRight', 'right'); - } - }; + function makeFormatFunction(format) { + var array = format.match(formattingTokens), i, length; - /** - * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden. - * @param {Array} groupIds - * @param {Object} groupRanges - * @private - */ - LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) { - var resized = false; - var yAxisLeftUsed = false; - var yAxisRightUsed = false; - var minLeft = 1000000000, - minRight = 1000000000, - maxLeft = -1000000000, - maxRight = -1000000000, - minVal, - maxVal; - // if groups are present - if (groupIds.length > 0) { - // this is here to make sure that if there are no items in the axis but there are groups, that there is no infinite draw/redraw loop. - for (var i = 0; i < groupIds.length; i++) { - var group = this.groups[groupIds[i]]; - if (group && group.options.yAxisOrientation != 'right') { - yAxisLeftUsed = true; - minLeft = 0; - maxLeft = 0; - } else if (group && group.options.yAxisOrientation) { - yAxisRightUsed = true; - minRight = 0; - maxRight = 0; - } + for (i = 0, length = array.length; i < length; i++) { + if (formatTokenFunctions[array[i]]) { + array[i] = formatTokenFunctions[array[i]]; + } else { + array[i] = removeFormattingTokens(array[i]); + } + } + + return function (mom) { + var output = ''; + for (i = 0; i < length; i++) { + output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; + } + return output; + }; } - // if there are items: - for (var i = 0; i < groupIds.length; i++) { - if (groupRanges.hasOwnProperty(groupIds[i])) { - if (groupRanges[groupIds[i]].ignore !== true) { - minVal = groupRanges[groupIds[i]].min; - maxVal = groupRanges[groupIds[i]].max; + // format date using native date object + function formatMoment(m, format) { + if (!m.isValid()) { + return m.localeData().invalidDate(); + } - if (groupRanges[groupIds[i]].yAxisOrientation != 'right') { - yAxisLeftUsed = true; - minLeft = minLeft > minVal ? minVal : minLeft; - maxLeft = maxLeft < maxVal ? maxVal : maxLeft; - } else { - yAxisRightUsed = true; - minRight = minRight > minVal ? minVal : minRight; - maxRight = maxRight < maxVal ? maxVal : maxRight; - } + format = expandFormat(format, m.localeData()); + + if (!formatFunctions[format]) { + formatFunctions[format] = makeFormatFunction(format); } - } - } - if (yAxisLeftUsed == true) { - this.yAxisLeft.setRange(minLeft, maxLeft); - } - if (yAxisRightUsed == true) { - this.yAxisRight.setRange(minRight, maxRight); + return formatFunctions[format](m); } - } - resized = this._toggleAxisVisiblity(yAxisLeftUsed, this.yAxisLeft) || resized; - resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized; - if (yAxisRightUsed == true && yAxisLeftUsed == true) { - this.yAxisLeft.drawIcons = true; - this.yAxisRight.drawIcons = true; - } else { - this.yAxisLeft.drawIcons = false; - this.yAxisRight.drawIcons = false; - } - this.yAxisRight.master = !yAxisLeftUsed; - if (this.yAxisRight.master == false) { - if (yAxisRightUsed == true) { - this.yAxisLeft.lineOffset = this.yAxisRight.width; - } else { - this.yAxisLeft.lineOffset = 0; - } + function expandFormat(format, locale) { + var i = 5; - resized = this.yAxisLeft.redraw() || resized; - this.yAxisRight.stepPixels = this.yAxisLeft.stepPixels; - this.yAxisRight.zeroCrossing = this.yAxisLeft.zeroCrossing; - this.yAxisRight.amountOfSteps = this.yAxisLeft.amountOfSteps; - resized = this.yAxisRight.redraw() || resized; - } else { - resized = this.yAxisRight.redraw() || resized; - } + function replaceLongDateFormatTokens(input) { + return locale.longDateFormat(input) || input; + } - // clean the accumulated lists - var tempGroups = ['__barStackLeft', '__barStackRight', '__lineStackLeft', '__lineStackRight']; - for (var i = 0; i < tempGroups.length; i++) { - if (groupIds.indexOf(tempGroups[i]) != -1) { - groupIds.splice(groupIds.indexOf(tempGroups[i]), 1); + localFormattingTokens.lastIndex = 0; + while (i >= 0 && localFormattingTokens.test(format)) { + format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); + localFormattingTokens.lastIndex = 0; + i -= 1; + } + + return format; } - } - return resized; - }; + var match1 = /\d/; // 0 - 9 + var match2 = /\d\d/; // 00 - 99 + var match3 = /\d{3}/; // 000 - 999 + var match4 = /\d{4}/; // 0000 - 9999 + var match6 = /[+-]?\d{6}/; // -999999 - 999999 + var match1to2 = /\d\d?/; // 0 - 99 + var match1to3 = /\d{1,3}/; // 0 - 999 + var match1to4 = /\d{1,4}/; // 0 - 9999 + var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 - /** - * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function - * - * @param {boolean} axisUsed - * @returns {boolean} - * @private - * @param axis - */ - LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) { - var changed = false; - if (axisUsed == false) { - if (axis.dom.frame.parentNode && axis.hidden == false) { - axis.hide(); - changed = true; - } - } else { - if (!axis.dom.frame.parentNode && axis.hidden == true) { - axis.show(); - changed = true; - } - } - return changed; - }; + var matchUnsigned = /\d+/; // 0 - inf + var matchSigned = /[+-]?\d+/; // -inf - inf - /** - * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the - * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for - * the yAxis. - * - * @param datapoints - * @returns {Array} - * @private - */ - LineGraph.prototype._convertXcoordinates = function (datapoints) { - var extractedData = []; - var xValue, yValue; - var toScreen = this.body.util.toScreen; + var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z - for (var i = 0; i < datapoints.length; i++) { - xValue = toScreen(datapoints[i].x) + this.props.width; - yValue = datapoints[i].y; - extractedData.push({ x: xValue, y: yValue }); - } + var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 - return extractedData; - }; + // any word (or two) characters or numbers including two/three word month in arabic. + var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i; - /** - * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the - * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for - * the yAxis. - * - * @param datapoints - * @param group - * @returns {Array} - * @private - */ - LineGraph.prototype._convertYcoordinates = function (datapoints, group) { - var extractedData = []; - var xValue, yValue; - var toScreen = this.body.util.toScreen; - var axis = this.yAxisLeft; - var svgHeight = Number(this.svg.style.height.replace('px', '')); - if (group.options.yAxisOrientation == 'right') { - axis = this.yAxisRight; - } + var regexes = {}; - for (var i = 0; i < datapoints.length; i++) { - var labelValue = datapoints[i].label ? datapoints[i].label : null; - xValue = toScreen(datapoints[i].x) + this.props.width; - yValue = Math.round(axis.convertValue(datapoints[i].y)); - extractedData.push({ x: xValue, y: yValue, label: labelValue }); - } + function addRegexToken (token, regex, strictRegex) { + regexes[token] = typeof regex === 'function' ? regex : function (isStrict) { + return (isStrict && strictRegex) ? strictRegex : regex; + }; + } - group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0))); + function getParseRegexForToken (token, config) { + if (!hasOwnProp(regexes, token)) { + return new RegExp(unescapeFormat(token)); + } - return extractedData; - }; + return regexes[token](config._strict, config._locale); + } - module.exports = LineGraph; + // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript + function unescapeFormat(s) { + return s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { + return p1 || p2 || p3 || p4; + }).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); + } -/***/ }, -/* 58 */ -/***/ function(module, exports, __webpack_require__) { + var tokens = {}; - 'use strict'; + function addParseToken (token, callback) { + var i, func = callback; + if (typeof token === 'string') { + token = [token]; + } + if (typeof callback === 'number') { + func = function (input, array) { + array[callback] = toInt(input); + }; + } + for (i = 0; i < token.length; i++) { + tokens[token[i]] = func; + } + } - var util = __webpack_require__(2); - var DOMutil = __webpack_require__(21); - var Component = __webpack_require__(35); - var DataStep = __webpack_require__(59); + function addWeekParseToken (token, callback) { + addParseToken(token, function (input, array, config, token) { + config._w = config._w || {}; + callback(input, config._w, config, token); + }); + } - /** - * A horizontal time axis - * @param {Object} [options] See DataAxis.setOptions for the available - * options. - * @constructor DataAxis - * @extends Component - * @param body - */ - function DataAxis(body, options, svg, linegraphOptions) { - this.id = util.randomUUID(); - this.body = body; + function addTimeToArrayFromToken(token, input, config) { + if (input != null && hasOwnProp(tokens, token)) { + tokens[token](input, config._a, config, token); + } + } - this.defaultOptions = { - orientation: 'left', // supported: 'left', 'right' - showMinorLabels: true, - showMajorLabels: true, - icons: true, - majorLinesOffset: 7, - minorLinesOffset: 4, - labelOffsetX: 10, - labelOffsetY: 2, - iconWidth: 20, - width: '40px', - visible: true, - alignZeros: true, - left: { - range: { min: undefined, max: undefined }, - format: function format(value) { - return value; - }, - title: { text: undefined, style: undefined } - }, - right: { - range: { min: undefined, max: undefined }, - format: function format(value) { - return value; - }, - title: { text: undefined, style: undefined } + var YEAR = 0; + var MONTH = 1; + var DATE = 2; + var HOUR = 3; + var MINUTE = 4; + var SECOND = 5; + var MILLISECOND = 6; + + function daysInMonth(year, month) { + return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } - }; - this.linegraphOptions = linegraphOptions; - this.linegraphSVG = svg; - this.props = {}; - this.DOMelements = { // dynamic elements - lines: {}, - labels: {}, - title: {} - }; + // FORMATTING - this.dom = {}; + addFormatToken('M', ['MM', 2], 'Mo', function () { + return this.month() + 1; + }); - this.range = { start: 0, end: 0 }; + addFormatToken('MMM', 0, 0, function (format) { + return this.localeData().monthsShort(this, format); + }); - this.options = util.extend({}, this.defaultOptions); - this.conversionFactor = 1; + addFormatToken('MMMM', 0, 0, function (format) { + return this.localeData().months(this, format); + }); - this.setOptions(options); - this.width = Number(('' + this.options.width).replace('px', '')); - this.minWidth = this.width; - this.height = this.linegraphSVG.offsetHeight; - this.hidden = false; + // ALIASES - this.stepPixels = 25; - this.zeroCrossing = -1; - this.amountOfSteps = -1; + addUnitAlias('month', 'M'); - this.lineOffset = 0; - this.master = true; - this.svgElements = {}; - this.iconsRemoved = false; + // PARSING - this.groups = {}; - this.amountOfGroups = 0; + addRegexToken('M', match1to2); + addRegexToken('MM', match1to2, match2); + addRegexToken('MMM', matchWord); + addRegexToken('MMMM', matchWord); - // create the HTML DOM - this._create(); + addParseToken(['M', 'MM'], function (input, array) { + array[MONTH] = toInt(input) - 1; + }); - var me = this; - this.body.emitter.on('verticalDrag', function () { - me.dom.lineContainer.style.top = me.body.domProps.scrollTop + 'px'; - }); - } + addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { + var month = config._locale.monthsParse(input, token, config._strict); + // if we didn't find a month name, mark the date as invalid. + if (month != null) { + array[MONTH] = month; + } else { + getParsingFlags(config).invalidMonth = input; + } + }); - DataAxis.prototype = new Component(); + // LOCALES - DataAxis.prototype.addGroup = function (label, graphOptions) { - if (!this.groups.hasOwnProperty(label)) { - this.groups[label] = graphOptions; - } - this.amountOfGroups += 1; - }; + var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); + function localeMonths (m) { + return this._months[m.month()]; + } - DataAxis.prototype.updateGroup = function (label, graphOptions) { - this.groups[label] = graphOptions; - }; + var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); + function localeMonthsShort (m) { + return this._monthsShort[m.month()]; + } - DataAxis.prototype.removeGroup = function (label) { - if (this.groups.hasOwnProperty(label)) { - delete this.groups[label]; - this.amountOfGroups -= 1; - } - }; + function localeMonthsParse (monthName, format, strict) { + var i, mom, regex; - DataAxis.prototype.setOptions = function (options) { - if (options) { - var redraw = false; - if (this.options.orientation != options.orientation && options.orientation !== undefined) { - redraw = true; + if (!this._monthsParse) { + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + } + + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = create_utc__createUTC([2000, i]); + if (strict && !this._longMonthsParse[i]) { + this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); + this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); + } + if (!strict && !this._monthsParse[i]) { + regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); + this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { + return i; + } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { + return i; + } else if (!strict && this._monthsParse[i].test(monthName)) { + return i; + } + } } - var fields = ['orientation', 'showMinorLabels', 'showMajorLabels', 'icons', 'majorLinesOffset', 'minorLinesOffset', 'labelOffsetX', 'labelOffsetY', 'iconWidth', 'width', 'visible', 'left', 'right', 'alignZeros']; - util.selectiveExtend(fields, this.options, options); - this.minWidth = Number(('' + this.options.width).replace('px', '')); + // MOMENTS - if (redraw === true && this.dom.frame) { - this.hide(); - this.show(); + function setMonth (mom, value) { + var dayOfMonth; + + // TODO: Move this out of here! + if (typeof value === 'string') { + value = mom.localeData().monthsParse(value); + // TODO: Another silent failure? + if (typeof value !== 'number') { + return mom; + } + } + + dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); + mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); + return mom; } - } - }; - /** - * Create the HTML DOM for the DataAxis - */ - DataAxis.prototype._create = function () { - this.dom.frame = document.createElement('div'); - this.dom.frame.style.width = this.options.width; - this.dom.frame.style.height = this.height; + function getSetMonth (value) { + if (value != null) { + setMonth(this, value); + utils_hooks__hooks.updateOffset(this, true); + return this; + } else { + return get_set__get(this, 'Month'); + } + } - this.dom.lineContainer = document.createElement('div'); - this.dom.lineContainer.style.width = '100%'; - this.dom.lineContainer.style.height = this.height; - this.dom.lineContainer.style.position = 'relative'; + function getDaysInMonth () { + return daysInMonth(this.year(), this.month()); + } - // create svg element for graph drawing. - this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - this.svg.style.position = 'absolute'; - this.svg.style.top = '0px'; - this.svg.style.height = '100%'; - this.svg.style.width = '100%'; - this.svg.style.display = 'block'; - this.dom.frame.appendChild(this.svg); - }; + function checkOverflow (m) { + var overflow; + var a = m._a; - DataAxis.prototype._redrawGroupIcons = function () { - DOMutil.prepareElements(this.svgElements); + if (a && getParsingFlags(m).overflow === -2) { + overflow = + a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : + a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : + a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : + a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : + a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : + a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : + -1; - var x; - var iconWidth = this.options.iconWidth; - var iconHeight = 15; - var iconOffset = 4; - var y = iconOffset + 0.5 * iconHeight; + if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { + overflow = DATE; + } - if (this.options.orientation === 'left') { - x = iconOffset; - } else { - x = this.width - iconWidth - iconOffset; - } + getParsingFlags(m).overflow = overflow; + } - var groupArray = Object.keys(this.groups); - groupArray.sort(function (a, b) { - return a < b ? -1 : 1; - }); + return m; + } - for (var i = 0; i < groupArray.length; i++) { - var groupId = groupArray[i]; - if (this.groups[groupId].visible === true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] === true)) { - this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight); - y += iconHeight + iconOffset; + function warn(msg) { + if (utils_hooks__hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { + console.warn('Deprecation warning: ' + msg); + } } - } - DOMutil.cleanupElements(this.svgElements); - this.iconsRemoved = false; - }; + function deprecate(msg, fn) { + var firstTime = true, + msgWithStack = msg + '\n' + (new Error()).stack; - DataAxis.prototype._cleanupIcons = function () { - if (this.iconsRemoved === false) { - DOMutil.prepareElements(this.svgElements); - DOMutil.cleanupElements(this.svgElements); - this.iconsRemoved = true; - } - }; + return extend(function () { + if (firstTime) { + warn(msgWithStack); + firstTime = false; + } + return fn.apply(this, arguments); + }, fn); + } - /** - * Create the HTML DOM for the DataAxis - */ - DataAxis.prototype.show = function () { - this.hidden = false; - if (!this.dom.frame.parentNode) { - if (this.options.orientation === 'left') { - this.body.dom.left.appendChild(this.dom.frame); - } else { - this.body.dom.right.appendChild(this.dom.frame); + var deprecations = {}; + + function deprecateSimple(name, msg) { + if (!deprecations[name]) { + warn(msg); + deprecations[name] = true; + } } - } - if (!this.dom.lineContainer.parentNode) { - this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer); - } - }; + utils_hooks__hooks.suppressDeprecationWarnings = false; - /** - * Create the HTML DOM for the DataAxis - */ - DataAxis.prototype.hide = function () { - this.hidden = true; - if (this.dom.frame.parentNode) { - this.dom.frame.parentNode.removeChild(this.dom.frame); - } + var from_string__isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; - if (this.dom.lineContainer.parentNode) { - this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer); - } - }; + var isoDates = [ + ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], + ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], + ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], + ['GGGG-[W]WW', /\d{4}-W\d{2}/], + ['YYYY-DDD', /\d{4}-\d{3}/] + ]; - /** - * Set a range (start and end) - * @param end - * @param start - * @param end - */ - DataAxis.prototype.setRange = function (start, end) { - if (this.master === false && this.options.alignZeros === true && this.zeroCrossing != -1) { - if (start > 0) { - start = 0; + // iso time formats and regexes + var isoTimes = [ + ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], + ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], + ['HH:mm', /(T| )\d\d:\d\d/], + ['HH', /(T| )\d\d/] + ]; + + var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; + + // date from iso format + function configFromISO(config) { + var i, l, + string = config._i, + match = from_string__isoRegex.exec(string); + + if (match) { + getParsingFlags(config).iso = true; + for (i = 0, l = isoDates.length; i < l; i++) { + if (isoDates[i][1].exec(string)) { + // match[5] should be 'T' or undefined + config._f = isoDates[i][0] + (match[6] || ' '); + break; + } + } + for (i = 0, l = isoTimes.length; i < l; i++) { + if (isoTimes[i][1].exec(string)) { + config._f += isoTimes[i][0]; + break; + } + } + if (string.match(matchOffset)) { + config._f += 'Z'; + } + configFromStringAndFormat(config); + } else { + config._isValid = false; + } } - } - this.range.start = start; - this.range.end = end; - }; - /** - * Repaint the component - * @return {boolean} Returns true if the component is resized - */ - DataAxis.prototype.redraw = function () { - var resized = false; - var activeGroups = 0; + // date from iso format or fallback + function configFromString(config) { + var matched = aspNetJsonRegex.exec(config._i); - // Make sure the line container adheres to the vertical scrolling. - this.dom.lineContainer.style.top = this.body.domProps.scrollTop + 'px'; + if (matched !== null) { + config._d = new Date(+matched[1]); + return; + } - for (var groupId in this.groups) { - if (this.groups.hasOwnProperty(groupId)) { - if (this.groups[groupId].visible === true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] === true)) { - activeGroups++; - } + configFromISO(config); + if (config._isValid === false) { + delete config._isValid; + utils_hooks__hooks.createFromInputFallback(config); + } } - } - if (this.amountOfGroups === 0 || activeGroups === 0) { - this.hide(); - } else { - this.show(); - this.height = Number(this.linegraphSVG.style.height.replace('px', '')); - // svg offsetheight did not work in firefox and explorer... - this.dom.lineContainer.style.height = this.height + 'px'; - this.width = this.options.visible === true ? Number(('' + this.options.width).replace('px', '')) : 0; + utils_hooks__hooks.createFromInputFallback = deprecate( + 'moment construction falls back to js Date. This is ' + + 'discouraged and will be removed in upcoming major ' + + 'release. Please refer to ' + + 'https://github.com/moment/moment/issues/1407 for more info.', + function (config) { + config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); + } + ); - var props = this.props; - var frame = this.dom.frame; + function createDate (y, m, d, h, M, s, ms) { + //can't just apply() to create a date: + //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply + var date = new Date(y, m, d, h, M, s, ms); - // update classname - frame.className = 'vis-data-axis'; + //the date constructor doesn't accept years < 1970 + if (y < 1970) { + date.setFullYear(y); + } + return date; + } - // calculate character width and height - this._calculateCharSize(); + function createUTCDate (y) { + var date = new Date(Date.UTC.apply(null, arguments)); + if (y < 1970) { + date.setUTCFullYear(y); + } + return date; + } - var orientation = this.options.orientation; - var showMinorLabels = this.options.showMinorLabels; - var showMajorLabels = this.options.showMajorLabels; + addFormatToken(0, ['YY', 2], 0, function () { + return this.year() % 100; + }); - // determine the width and height of the elements for the axis - props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0; - props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0; + addFormatToken(0, ['YYYY', 4], 0, 'year'); + addFormatToken(0, ['YYYYY', 5], 0, 'year'); + addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); - props.minorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.minorLinesOffset; - props.minorLineHeight = 1; - props.majorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.majorLinesOffset; - props.majorLineHeight = 1; + // ALIASES - // take frame offline while updating (is almost twice as fast) - if (orientation === 'left') { - frame.style.top = '0'; - frame.style.left = '0'; - frame.style.bottom = ''; - frame.style.width = this.width + 'px'; - frame.style.height = this.height + 'px'; - this.props.width = this.body.domProps.left.width; - this.props.height = this.body.domProps.left.height; - } else { - // right - frame.style.top = ''; - frame.style.bottom = '0'; - frame.style.left = '0'; - frame.style.width = this.width + 'px'; - frame.style.height = this.height + 'px'; - this.props.width = this.body.domProps.right.width; - this.props.height = this.body.domProps.right.height; - } + addUnitAlias('year', 'y'); - resized = this._redrawLabels(); - resized = this._isResized() || resized; + // PARSING - if (this.options.icons === true) { - this._redrawGroupIcons(); - } else { - this._cleanupIcons(); - } + addRegexToken('Y', matchSigned); + addRegexToken('YY', match1to2, match2); + addRegexToken('YYYY', match1to4, match4); + addRegexToken('YYYYY', match1to6, match6); + addRegexToken('YYYYYY', match1to6, match6); - this._redrawTitle(orientation); - } - return resized; - }; + addParseToken(['YYYY', 'YYYYY', 'YYYYYY'], YEAR); + addParseToken('YY', function (input, array) { + array[YEAR] = utils_hooks__hooks.parseTwoDigitYear(input); + }); - /** - * Repaint major and minor text labels and vertical grid lines - * @private - */ - DataAxis.prototype._redrawLabels = function () { - var resized = false; - DOMutil.prepareElements(this.DOMelements.lines); - DOMutil.prepareElements(this.DOMelements.labels); - var orientation = this.options['orientation']; + // HELPERS - // get the range for the slaved axis - var step; - if (this.master === false) { - var stepSize, rangeStart, rangeEnd, minimumStep; - if (this.zeroCrossing !== -1 && this.options.alignZeros === true) { - if (this.range.end > 0) { - stepSize = this.range.end / this.zeroCrossing; // size of one step - rangeStart = this.range.end - this.amountOfSteps * stepSize; - rangeEnd = this.range.end; - } else { - // all of the range (including start) has to be done before the zero crossing. - stepSize = -1 * this.range.start / (this.amountOfSteps - this.zeroCrossing); // absolute size of a step - rangeStart = this.range.start; - rangeEnd = this.range.start + stepSize * this.amountOfSteps; - } - } else { - rangeStart = this.range.start; - rangeEnd = this.range.end; + function daysInYear(year) { + return isLeapYear(year) ? 366 : 365; + } + + function isLeapYear(year) { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } - minimumStep = this.stepPixels; - } else { - // calculate range and step (step such that we have space for 7 characters per label) - minimumStep = this.props.majorCharHeight; - rangeStart = this.range.start; - rangeEnd = this.range.end; - } - this.step = step = new DataStep(rangeStart, rangeEnd, minimumStep, this.dom.frame.offsetHeight, this.options[this.options.orientation].range, this.options[this.options.orientation].format, this.master === false && this.options.alignZeros // does the step have to align zeros? only if not master and the options is on - ); + // HOOKS - // the slave axis needs to use the same horizontal lines as the master axis. - if (this.master === true) { - this.stepPixels = this.dom.frame.offsetHeight / step.marginRange * step.step; - this.amountOfSteps = Math.ceil(this.dom.frame.offsetHeight / this.stepPixels); - } else { - // align with zero - if (this.options.alignZeros === true && this.zeroCrossing !== -1) { - // distance is the amount of steps away from the zero crossing we are. - var distance = (step.current - this.zeroCrossing * step.step) / step.step; - this.step.shift(distance); + utils_hooks__hooks.parseTwoDigitYear = function (input) { + return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); + }; + + // MOMENTS + + var getSetYear = makeGetSet('FullYear', false); + + function getIsLeapYear () { + return isLeapYear(this.year()); } - } - // value at the bottom of the SVG - this.valueAtBottom = step.marginEnd; + addFormatToken('w', ['ww', 2], 'wo', 'week'); + addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); - this.maxLabelSize = 0; - var y = 0; // init value - var stepIndex = 0; // init value - var isMajor = false; // init value - while (stepIndex < this.amountOfSteps) { - y = Math.round(stepIndex * this.stepPixels); - isMajor = step.isMajor(); + // ALIASES - if (stepIndex > 0 && stepIndex !== this.amountOfSteps) { - if (this.options['showMinorLabels'] && isMajor === false || this.master === false && this.options['showMinorLabels'] === true) { - this._redrawLabel(y - 2, step.getCurrent(), orientation, 'vis-y-axis vis-minor', this.props.minorCharHeight); - } + addUnitAlias('week', 'w'); + addUnitAlias('isoWeek', 'W'); - if (isMajor && this.options['showMajorLabels'] && this.master === true || this.options['showMinorLabels'] === false && this.master === false && isMajor === true) { - if (y >= 0) { - this._redrawLabel(y - 2, step.getCurrent(), orientation, 'vis-y-axis vis-major', this.props.majorCharHeight); + // PARSING + + addRegexToken('w', match1to2); + addRegexToken('ww', match1to2, match2); + addRegexToken('W', match1to2); + addRegexToken('WW', match1to2, match2); + + addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { + week[token.substr(0, 1)] = toInt(input); + }); + + // HELPERS + + // firstDayOfWeek 0 = sun, 6 = sat + // the day of the week that starts the week + // (usually sunday or monday) + // firstDayOfWeekOfYear 0 = sun, 6 = sat + // the first week is the week that contains the first + // of this day of the week + // (eg. ISO weeks use thursday (4)) + function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { + var end = firstDayOfWeekOfYear - firstDayOfWeek, + daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), + adjustedMoment; + + + if (daysToDayOfWeek > end) { + daysToDayOfWeek -= 7; } - this._redrawLine(y, orientation, 'vis-grid vis-horizontal vis-major', this.options.majorLinesOffset, this.props.majorLineWidth); - } else { - this._redrawLine(y, orientation, 'vis-grid vis-horizontal vis-minor', this.options.minorLinesOffset, this.props.minorLineWidth); - } + + if (daysToDayOfWeek < end - 7) { + daysToDayOfWeek += 7; + } + + adjustedMoment = local__createLocal(mom).add(daysToDayOfWeek, 'd'); + return { + week: Math.ceil(adjustedMoment.dayOfYear() / 7), + year: adjustedMoment.year() + }; } - // get zero crossing - if (this.master === true && step.current === 0) { - this.zeroCrossing = stepIndex; + // LOCALES + + function localeWeek (mom) { + return weekOfYear(mom, this._week.dow, this._week.doy).week; } - step.next(); - stepIndex += 1; - } + var defaultLocaleWeek = { + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 1st is the first week of the year. + }; - // get zero crossing if it's the last step - if (this.master === true && step.current === 0) { - this.zeroCrossing = stepIndex; - } + function localeFirstDayOfWeek () { + return this._week.dow; + } - this.conversionFactor = this.stepPixels / step.step; + function localeFirstDayOfYear () { + return this._week.doy; + } - // Note that title is rotated, so we're using the height, not width! - var titleWidth = 0; - if (this.options[orientation].title !== undefined && this.options[orientation].title.text !== undefined) { - titleWidth = this.props.titleCharHeight; - } - var offset = this.options.icons === true ? Math.max(this.options.iconWidth, titleWidth) + this.options.labelOffsetX + 15 : titleWidth + this.options.labelOffsetX + 15; + // MOMENTS - // this will resize the yAxis to accommodate the labels. - if (this.maxLabelSize > this.width - offset && this.options.visible === true) { - this.width = this.maxLabelSize + offset; - this.options.width = this.width + 'px'; - DOMutil.cleanupElements(this.DOMelements.lines); - DOMutil.cleanupElements(this.DOMelements.labels); - this.redraw(); - resized = true; - } - // this will resize the yAxis if it is too big for the labels. - else if (this.maxLabelSize < this.width - offset && this.options.visible === true && this.width > this.minWidth) { - this.width = Math.max(this.minWidth, this.maxLabelSize + offset); - this.options.width = this.width + 'px'; - DOMutil.cleanupElements(this.DOMelements.lines); - DOMutil.cleanupElements(this.DOMelements.labels); - this.redraw(); - resized = true; - } else { - DOMutil.cleanupElements(this.DOMelements.lines); - DOMutil.cleanupElements(this.DOMelements.labels); - resized = false; - } + function getSetWeek (input) { + var week = this.localeData().week(this); + return input == null ? week : this.add((input - week) * 7, 'd'); + } - return resized; - }; + function getSetISOWeek (input) { + var week = weekOfYear(this, 1, 4).week; + return input == null ? week : this.add((input - week) * 7, 'd'); + } - DataAxis.prototype.convertValue = function (value) { - var invertedValue = this.valueAtBottom - value; - var convertedValue = invertedValue * this.conversionFactor; - return convertedValue; - }; + addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); - DataAxis.prototype.screenToValue = function (x) { - return this.valueAtBottom - x / this.conversionFactor; - }; + // ALIASES - /** - * Create a label for the axis at position x - * @private - * @param y - * @param text - * @param orientation - * @param className - * @param characterHeight - */ - DataAxis.prototype._redrawLabel = function (y, text, orientation, className, characterHeight) { - // reuse redundant label - var label = DOMutil.getDOMElement('div', this.DOMelements.labels, this.dom.frame); //this.dom.redundant.labels.shift(); - label.className = className; - label.innerHTML = text; - if (orientation === 'left') { - label.style.left = '-' + this.options.labelOffsetX + 'px'; - label.style.textAlign = 'right'; - } else { - label.style.right = '-' + this.options.labelOffsetX + 'px'; - label.style.textAlign = 'left'; - } + addUnitAlias('dayOfYear', 'DDD'); - label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px'; + // PARSING - text += ''; + addRegexToken('DDD', match1to3); + addRegexToken('DDDD', match3); + addParseToken(['DDD', 'DDDD'], function (input, array, config) { + config._dayOfYear = toInt(input); + }); - var largestWidth = Math.max(this.props.majorCharWidth, this.props.minorCharWidth); - if (this.maxLabelSize < text.length * largestWidth) { - this.maxLabelSize = text.length * largestWidth; - } - }; + // HELPERS - /** - * Create a minor line for the axis at position y - * @param y - * @param orientation - * @param className - * @param offset - * @param width - */ - DataAxis.prototype._redrawLine = function (y, orientation, className, offset, width) { - if (this.master === true) { - var line = DOMutil.getDOMElement('div', this.DOMelements.lines, this.dom.lineContainer); //this.dom.redundant.lines.shift(); - line.className = className; - line.innerHTML = ''; + //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday + function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { + var d = createUTCDate(year, 0, 1).getUTCDay(); + var daysToAdd; + var dayOfYear; - if (orientation === 'left') { - line.style.left = this.width - offset + 'px'; - } else { - line.style.right = this.width - offset + 'px'; - } + d = d === 0 ? 7 : d; + weekday = weekday != null ? weekday : firstDayOfWeek; + daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); + dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; - line.style.width = width + 'px'; - line.style.top = y + 'px'; - } - }; + return { + year : dayOfYear > 0 ? year : year - 1, + dayOfYear : dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear + }; + } - /** - * Create a title for the axis - * @private - * @param orientation - */ - DataAxis.prototype._redrawTitle = function (orientation) { - DOMutil.prepareElements(this.DOMelements.title); + // MOMENTS - // Check if the title is defined for this axes - if (this.options[orientation].title !== undefined && this.options[orientation].title.text !== undefined) { - var title = DOMutil.getDOMElement('div', this.DOMelements.title, this.dom.frame); - title.className = 'vis-y-axis vis-title vis-' + orientation; - title.innerHTML = this.options[orientation].title.text; + function getSetDayOfYear (input) { + var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; + return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); + } - // Add style - if provided - if (this.options[orientation].title.style !== undefined) { - util.addCssText(title, this.options[orientation].title.style); + // Pick the first defined of two or three arguments. + function defaults(a, b, c) { + if (a != null) { + return a; + } + if (b != null) { + return b; + } + return c; } - if (orientation === 'left') { - title.style.left = this.props.titleCharHeight + 'px'; - } else { - title.style.right = this.props.titleCharHeight + 'px'; + function currentDateArray(config) { + var now = new Date(); + if (config._useUTC) { + return [now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()]; + } + return [now.getFullYear(), now.getMonth(), now.getDate()]; } - title.style.width = this.height + 'px'; - } + // convert an array to a date. + // the array should mirror the parameters below + // note: all values past the year are optional and will default to the lowest possible value. + // [year, month, day , hour, minute, second, millisecond] + function configFromArray (config) { + var i, date, input = [], currentDate, yearToUse; - // we need to clean up in case we did not use all elements. - DOMutil.cleanupElements(this.DOMelements.title); - }; + if (config._d) { + return; + } - /** - * 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 - */ - DataAxis.prototype._calculateCharSize = function () { - // determine the char width and height on the minor axis - if (!('minorCharHeight' in this.props)) { - var textMinor = document.createTextNode('0'); - var measureCharMinor = document.createElement('div'); - measureCharMinor.className = 'vis-y-axis vis-minor vis-measure'; - measureCharMinor.appendChild(textMinor); - this.dom.frame.appendChild(measureCharMinor); + currentDate = currentDateArray(config); - this.props.minorCharHeight = measureCharMinor.clientHeight; - this.props.minorCharWidth = measureCharMinor.clientWidth; + //compute day of the year from weeks and weekdays + if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { + dayOfYearFromWeekInfo(config); + } - this.dom.frame.removeChild(measureCharMinor); - } + //if the day of the year is set, figure out what it is + if (config._dayOfYear) { + yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); - if (!('majorCharHeight' in this.props)) { - var textMajor = document.createTextNode('0'); - var measureCharMajor = document.createElement('div'); - measureCharMajor.className = 'vis-y-axis vis-major vis-measure'; - measureCharMajor.appendChild(textMajor); - this.dom.frame.appendChild(measureCharMajor); + if (config._dayOfYear > daysInYear(yearToUse)) { + getParsingFlags(config)._overflowDayOfYear = true; + } - this.props.majorCharHeight = measureCharMajor.clientHeight; - this.props.majorCharWidth = measureCharMajor.clientWidth; + date = createUTCDate(yearToUse, 0, config._dayOfYear); + config._a[MONTH] = date.getUTCMonth(); + config._a[DATE] = date.getUTCDate(); + } - this.dom.frame.removeChild(measureCharMajor); - } + // Default to current date. + // * if no year, month, day of month are given, default to today + // * if day of month is given, default month and year + // * if month is given, default only year + // * if year is given, don't default anything + for (i = 0; i < 3 && config._a[i] == null; ++i) { + config._a[i] = input[i] = currentDate[i]; + } - if (!('titleCharHeight' in this.props)) { - var textTitle = document.createTextNode('0'); - var measureCharTitle = document.createElement('div'); - measureCharTitle.className = 'vis-y-axis vis-title vis-measure'; - measureCharTitle.appendChild(textTitle); - this.dom.frame.appendChild(measureCharTitle); + // Zero out whatever was not defaulted, including time + for (; i < 7; i++) { + config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; + } - this.props.titleCharHeight = measureCharTitle.clientHeight; - this.props.titleCharWidth = measureCharTitle.clientWidth; + // Check for 24:00:00.000 + if (config._a[HOUR] === 24 && + config._a[MINUTE] === 0 && + config._a[SECOND] === 0 && + config._a[MILLISECOND] === 0) { + config._nextDay = true; + config._a[HOUR] = 0; + } - this.dom.frame.removeChild(measureCharTitle); - } - }; + config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); + // Apply timezone offset from input. The actual utcOffset can be changed + // with parseZone. + if (config._tzm != null) { + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + } - module.exports = DataAxis; + if (config._nextDay) { + config._a[HOUR] = 24; + } + } -/***/ }, -/* 59 */ -/***/ function(module, exports, __webpack_require__) { + function dayOfYearFromWeekInfo(config) { + var w, weekYear, week, weekday, dow, doy, temp; - /** - * @constructor DataStep - * The class DataStep is an iterator for data for the lineGraph. You provide a start data point and an - * end data point. 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 DataStep 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 - */ - 'use strict'; + w = config._w; + if (w.GG != null || w.W != null || w.E != null) { + dow = 1; + doy = 4; - function DataStep(start, end, minimumStep, containerHeight, customRange, formattingFunction, alignZeros) { - // variables - this.current = 0; + // TODO: We need to take the current isoWeekYear, but that depends on + // how we interpret now (local, utc, fixed offset). So create + // a now version of current config (take local/utc/offset flags, and + // create now). + weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(local__createLocal(), 1, 4).year); + week = defaults(w.W, 1); + weekday = defaults(w.E, 1); + } else { + dow = config._locale._week.dow; + doy = config._locale._week.doy; - this.autoScale = true; - this.stepIndex = 0; - this.step = 1; - this.scale = 1; - this.formattingFunction = formattingFunction; + weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(local__createLocal(), dow, doy).year); + week = defaults(w.w, 1); - this.marginStart; - this.marginEnd; - this.deadSpace = 0; + if (w.d != null) { + // weekday -- low day numbers are considered next week + weekday = w.d; + if (weekday < dow) { + ++week; + } + } else if (w.e != null) { + // local weekday -- counting starts from begining of week + weekday = w.e + dow; + } else { + // default to begining of week + weekday = dow; + } + } + temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); - this.majorSteps = [1, 2, 5, 10]; - this.minorSteps = [0.25, 0.5, 1, 2]; + config._a[YEAR] = temp.year; + config._dayOfYear = temp.dayOfYear; + } - this.alignZeros = alignZeros; + utils_hooks__hooks.ISO_8601 = function () {}; - this.setRange(start, end, minimumStep, containerHeight, customRange); - } + // date from string and format string + function configFromStringAndFormat(config) { + // TODO: Move this to another part of the creation flow to prevent circular deps + if (config._f === utils_hooks__hooks.ISO_8601) { + configFromISO(config); + return; + } - /** - * 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 {Number} [start] The start date and time. - * @param {Number} [end] The end date and time. - * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds - */ - DataStep.prototype.setRange = function (start, end, minimumStep, containerHeight, customRange) { - this._start = customRange.min === undefined ? start : customRange.min; - this._end = customRange.max === undefined ? end : customRange.max; - if (this._start === this._end) { - this._start = customRange.min === undefined ? this._start - 0.75 : this._start; - this._end = customRange.max === undefined ? this._end + 1 : this._end;; - } + config._a = []; + getParsingFlags(config).empty = true; - if (this.autoScale === true) { - this.setMinimumStep(minimumStep, containerHeight); - } + // This array is used to make a Date, either with `new Date` or `Date.UTC` + var string = '' + config._i, + i, parsedInput, tokens, token, skipped, + stringLength = string.length, + totalParsedInputLength = 0; - this.setFirst(customRange); - }; + tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; - /** - * Automatically determine the scale that bests fits the provided minimum step - * @param {Number} [minimumStep] The minimum step size in pixels - */ - DataStep.prototype.setMinimumStep = function (minimumStep, containerHeight) { - // round to floor - var range = this._end - this._start; - var safeRange = range * 1.2; - var minimumStepValue = minimumStep * (safeRange / containerHeight); - var orderOfMagnitude = Math.round(Math.log(safeRange) / Math.LN10); + for (i = 0; i < tokens.length; i++) { + token = tokens[i]; + parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; + if (parsedInput) { + skipped = string.substr(0, string.indexOf(parsedInput)); + if (skipped.length > 0) { + getParsingFlags(config).unusedInput.push(skipped); + } + string = string.slice(string.indexOf(parsedInput) + parsedInput.length); + totalParsedInputLength += parsedInput.length; + } + // don't parse if it's not a known token + if (formatTokenFunctions[token]) { + if (parsedInput) { + getParsingFlags(config).empty = false; + } + else { + getParsingFlags(config).unusedTokens.push(token); + } + addTimeToArrayFromToken(token, parsedInput, config); + } + else if (config._strict && !parsedInput) { + getParsingFlags(config).unusedTokens.push(token); + } + } - var minorStepIdx = -1; - var magnitudefactor = Math.pow(10, orderOfMagnitude); + // add remaining unparsed input length to the string + getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; + if (string.length > 0) { + getParsingFlags(config).unusedInput.push(string); + } - var start = 0; - if (orderOfMagnitude < 0) { - start = orderOfMagnitude; - } + // clear _12h flag if hour is <= 12 + if (getParsingFlags(config).bigHour === true && + config._a[HOUR] <= 12 && + config._a[HOUR] > 0) { + getParsingFlags(config).bigHour = undefined; + } + // handle meridiem + config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); - var solutionFound = false; - for (var i = start; Math.abs(i) <= Math.abs(orderOfMagnitude); i++) { - magnitudefactor = Math.pow(10, i); - for (var j = 0; j < this.minorSteps.length; j++) { - var stepSize = magnitudefactor * this.minorSteps[j]; - if (stepSize >= minimumStepValue) { - solutionFound = true; - minorStepIdx = j; - break; - } - } - if (solutionFound === true) { - break; + configFromArray(config); + checkOverflow(config); } - } - this.stepIndex = minorStepIdx; - this.scale = magnitudefactor; - this.step = magnitudefactor * this.minorSteps[minorStepIdx]; - }; - - /** - * Round the current date to the first minor date value - * This must be executed once when the current date is set to start Date - */ - DataStep.prototype.setFirst = function (customRange) { - if (customRange === undefined) { - customRange = {}; - } - - var niceStart = customRange.min === undefined ? this._start - this.scale * 2 * this.minorSteps[this.stepIndex] : customRange.min; - var niceEnd = customRange.max === undefined ? this._end + this.scale * this.minorSteps[this.stepIndex] : customRange.max; - this.marginEnd = customRange.max === undefined ? this.roundToMinor(niceEnd) : customRange.max; - this.marginStart = customRange.min === undefined ? this.roundToMinor(niceStart) : customRange.min; - // if we need to align the zero's we need to make sure that there is a zero to use. - if (this.alignZeros === true && (this.marginEnd - this.marginStart) % this.step != 0) { - this.marginEnd += this.marginEnd % this.step; - } + function meridiemFixWrap (locale, hour, meridiem) { + var isPm; - this.deadSpace = this.roundToMinor(niceEnd) - niceEnd + this.roundToMinor(niceStart) - niceStart; - this.marginRange = this.marginEnd - this.marginStart; + if (meridiem == null) { + // nothing to do + return hour; + } + if (locale.meridiemHour != null) { + return locale.meridiemHour(hour, meridiem); + } else if (locale.isPM != null) { + // Fallback + isPm = locale.isPM(meridiem); + if (isPm && hour < 12) { + hour += 12; + } + if (!isPm && hour === 12) { + hour = 0; + } + return hour; + } else { + // this is not supposed to happen + return hour; + } + } - this.current = this.marginEnd; - }; + function configFromStringAndArray(config) { + var tempConfig, + bestMoment, - DataStep.prototype.roundToMinor = function (value) { - var rounded = value - value % (this.scale * this.minorSteps[this.stepIndex]); - if (value % (this.scale * this.minorSteps[this.stepIndex]) > 0.5 * (this.scale * this.minorSteps[this.stepIndex])) { - return rounded + this.scale * this.minorSteps[this.stepIndex]; - } else { - return rounded; - } - }; + scoreToBeat, + i, + currentScore; - /** - * Check if the there is a next step - * @return {boolean} true if the current date has not passed the end date - */ - DataStep.prototype.hasNext = function () { - return this.current >= this.marginStart; - }; + if (config._f.length === 0) { + getParsingFlags(config).invalidFormat = true; + config._d = new Date(NaN); + return; + } - /** - * Do the next step - */ - DataStep.prototype.next = function () { - var prev = this.current; - this.current -= this.step; + for (i = 0; i < config._f.length; i++) { + currentScore = 0; + tempConfig = copyConfig({}, config); + if (config._useUTC != null) { + tempConfig._useUTC = config._useUTC; + } + tempConfig._f = config._f[i]; + configFromStringAndFormat(tempConfig); - // safety mechanism: if current time is still unchanged, move to the end - if (this.current === prev) { - this.current = this._end; - } - }; + if (!valid__isValid(tempConfig)) { + continue; + } - /** - * Do the next step - */ - DataStep.prototype.previous = function () { - this.current += this.step; - this.marginEnd += this.step; - this.marginRange = this.marginEnd - this.marginStart; - }; + // if there is any input that was not parsed add a penalty for that format + currentScore += getParsingFlags(tempConfig).charsLeftOver; - /** - * Get the current datetime - * @return {String} current The current date - */ - DataStep.prototype.getCurrent = function () { - // prevent round-off errors when close to zero - var current = Math.abs(this.current) < this.step / 2 ? 0 : this.current; - var returnValue = current.toPrecision(5); - if (typeof this.formattingFunction === 'function') { - returnValue = this.formattingFunction(current); - } + //or tokens + currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; - if (typeof returnValue === 'number') { - return '' + returnValue; - } else if (typeof returnValue === 'string') { - return returnValue; - } else { - return current.toPrecision(5); - } - }; + getParsingFlags(tempConfig).score = currentScore; - /** - * 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. - */ - DataStep.prototype.isMajor = function () { - return this.current % (this.scale * this.majorSteps[this.stepIndex]) === 0; - }; + if (scoreToBeat == null || currentScore < scoreToBeat) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + } + } - DataStep.prototype.shift = function (steps) { - if (steps < 0) { - for (var i = 0; i < -steps; i++) { - this.previous(); - } - } else if (steps > 0) { - for (var i = 0; i < steps; i++) { - this.next(); + extend(config, bestMoment || tempConfig); } - } - }; - - module.exports = DataStep; -/***/ }, -/* 60 */ -/***/ function(module, exports, __webpack_require__) { + function configFromObject(config) { + if (config._d) { + return; + } - 'use strict'; + var i = normalizeObjectUnits(config._i); + config._a = [i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond]; - var util = __webpack_require__(2); - var DOMutil = __webpack_require__(21); - var Line = __webpack_require__(61); - var Bar = __webpack_require__(63); - var Points = __webpack_require__(62); + configFromArray(config); + } - /** - * /** - * @param {object} group | the object of the group from the dataset - * @param {string} groupId | ID of the group - * @param {object} options | the default options - * @param {array} groupsUsingDefaultStyles | this array has one entree. - * It is passed as an array so it is passed by reference. - * It enumerates through the default styles - * @constructor - */ - function GraphGroup(group, groupId, options, groupsUsingDefaultStyles) { - this.id = groupId; - var fields = ['sampling', 'style', 'sort', 'yAxisOrientation', 'barChart', 'drawPoints', 'shaded', 'interpolation']; - this.options = util.selectiveBridgeObject(fields, options); - this.usingDefaultStyle = group.className === undefined; - this.groupsUsingDefaultStyles = groupsUsingDefaultStyles; - this.zeroPosition = 0; - this.update(group); - if (this.usingDefaultStyle == true) { - this.groupsUsingDefaultStyles[0] += 1; - } - this.itemsData = []; - this.visible = group.visible === undefined ? true : group.visible; - } + function createFromConfig (config) { + var input = config._i, + format = config._f, + res; - /** - * this loads a reference to all items in this group into this group. - * @param {array} items - */ - GraphGroup.prototype.setItems = function (items) { - if (items != null) { - this.itemsData = items; - if (this.options.sort == true) { - this.itemsData.sort(function (a, b) { - return a.x - b.x; - }); - } - } else { - this.itemsData = []; - } - }; + config._locale = config._locale || locale_locales__getLocale(config._l); - /** - * this is used for plotting barcharts, this way, we only have to calculate it once. - * @param pos - */ - GraphGroup.prototype.setZeroPosition = function (pos) { - this.zeroPosition = pos; - }; + if (input === null || (format === undefined && input === '')) { + return valid__createInvalid({nullInput: true}); + } - /** - * set the options of the graph group over the default options. - * @param options - */ - GraphGroup.prototype.setOptions = function (options) { - if (options !== undefined) { - var fields = ['sampling', 'style', 'sort', 'yAxisOrientation', 'barChart']; - util.selectiveDeepExtend(fields, this.options, options); + if (typeof input === 'string') { + config._i = input = config._locale.preparse(input); + } - util.mergeOptions(this.options, options, 'interpolation'); - util.mergeOptions(this.options, options, 'drawPoints'); - util.mergeOptions(this.options, options, 'shaded'); + if (isMoment(input)) { + return new Moment(checkOverflow(input)); + } else if (isArray(format)) { + configFromStringAndArray(config); + } else if (format) { + configFromStringAndFormat(config); + } else if (isDate(input)) { + config._d = input; + } else { + configFromInput(config); + } - if (options.interpolation) { - if (typeof options.interpolation == 'object') { - if (options.interpolation.parametrization) { - if (options.interpolation.parametrization == 'uniform') { - this.options.interpolation.alpha = 0; - } else if (options.interpolation.parametrization == 'chordal') { - this.options.interpolation.alpha = 1; - } else { - this.options.interpolation.parametrization = 'centripetal'; - this.options.interpolation.alpha = 0.5; - } + res = new Moment(checkOverflow(config)); + if (res._nextDay) { + // Adding is smart enough around DST + res.add(1, 'd'); + res._nextDay = undefined; } - } - } - } - if (this.options.style == 'line') { - this.type = new Line(this.id, this.options); - } else if (this.options.style == 'bar') { - this.type = new Bar(this.id, this.options); - } else if (this.options.style == 'points') { - this.type = new Points(this.id, this.options); - } - }; + return res; + } - /** - * this updates the current group class with the latest group dataset entree, used in _updateGroup in linegraph - * @param group - */ - GraphGroup.prototype.update = function (group) { - this.group = group; - this.content = group.content || 'graph'; - this.className = group.className || this.className || 'vis-graph-group' + this.groupsUsingDefaultStyles[0] % 10; - this.visible = group.visible === undefined ? true : group.visible; - this.style = group.style; - this.setOptions(group.options); - }; + function configFromInput(config) { + var input = config._i; + if (input === undefined) { + config._d = new Date(); + } else if (isDate(input)) { + config._d = new Date(+input); + } else if (typeof input === 'string') { + configFromString(config); + } else if (isArray(input)) { + config._a = map(input.slice(0), function (obj) { + return parseInt(obj, 10); + }); + configFromArray(config); + } else if (typeof(input) === 'object') { + configFromObject(config); + } else if (typeof(input) === 'number') { + // from milliseconds + config._d = new Date(input); + } else { + utils_hooks__hooks.createFromInputFallback(config); + } + } - /** - * draw the icon for the legend. - * - * @param x - * @param y - * @param JSONcontainer - * @param SVGcontainer - * @param iconWidth - * @param iconHeight - */ - GraphGroup.prototype.drawIcon = function (x, y, JSONcontainer, SVGcontainer, iconWidth, iconHeight) { - var fillHeight = iconHeight * 0.5; - var path, fillPath; + function createLocalOrUTC (input, format, locale, strict, isUTC) { + var c = {}; - var outline = DOMutil.getSVGElement('rect', JSONcontainer, SVGcontainer); - 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'); + if (typeof(locale) === 'boolean') { + strict = locale; + locale = undefined; + } + // object construction must be done this way. + // https://github.com/moment/moment/issues/1423 + c._isAMomentObject = true; + c._useUTC = c._isUTC = isUTC; + c._l = locale; + c._i = input; + c._f = format; + c._strict = strict; - if (this.options.style == 'line') { - path = DOMutil.getSVGElement('path', JSONcontainer, SVGcontainer); - path.setAttributeNS(null, 'class', this.className); - if (this.style !== undefined) { - path.setAttributeNS(null, 'style', this.style); + return createFromConfig(c); } - path.setAttributeNS(null, 'd', 'M' + x + ',' + y + ' L' + (x + iconWidth) + ',' + y + ''); - if (this.options.shaded.enabled == true) { - fillPath = DOMutil.getSVGElement('path', JSONcontainer, SVGcontainer); - if (this.options.shaded.orientation == 'top') { - fillPath.setAttributeNS(null, 'd', 'M' + x + ', ' + (y - fillHeight) + 'L' + x + ',' + y + ' L' + (x + iconWidth) + ',' + y + ' L' + (x + iconWidth) + ',' + (y - fillHeight)); - } else { - fillPath.setAttributeNS(null, 'd', 'M' + x + ',' + y + ' ' + 'L' + x + ',' + (y + fillHeight) + ' ' + 'L' + (x + iconWidth) + ',' + (y + fillHeight) + 'L' + (x + iconWidth) + ',' + y); - } - fillPath.setAttributeNS(null, 'class', this.className + ' vis-icon-fill'); + function local__createLocal (input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, false); } - if (this.options.drawPoints.enabled == true) { - DOMutil.drawPoint(x + 0.5 * iconWidth, y, this, JSONcontainer, SVGcontainer); + var prototypeMin = deprecate( + 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548', + function () { + var other = local__createLocal.apply(null, arguments); + return other < this ? this : other; + } + ); + + var prototypeMax = deprecate( + 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548', + function () { + var other = local__createLocal.apply(null, arguments); + return other > this ? this : other; + } + ); + + // Pick a moment m from moments so that m[fn](other) is true for all + // other. This relies on the function fn to be transitive. + // + // moments should either be an array of moment objects or an array, whose + // first element is an array of moment objects. + function pickBy(fn, moments) { + var res, i; + if (moments.length === 1 && isArray(moments[0])) { + moments = moments[0]; + } + if (!moments.length) { + return local__createLocal(); + } + res = moments[0]; + for (i = 1; i < moments.length; ++i) { + if (moments[i][fn](res)) { + res = moments[i]; + } + } + return res; } - } else { - var barWidth = Math.round(0.3 * iconWidth); - var bar1Height = Math.round(0.4 * iconHeight); - var bar2Height = Math.round(0.75 * iconHeight); - var offset = Math.round((iconWidth - 2 * barWidth) / 3); + // TODO: Use [].sort instead? + function min () { + var args = [].slice.call(arguments, 0); - DOMutil.drawBar(x + 0.5 * barWidth + offset, y + fillHeight - bar1Height - 1, barWidth, bar1Height, this.className + ' vis-bar', JSONcontainer, SVGcontainer, this.style); - DOMutil.drawBar(x + 1.5 * barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, this.className + ' vis-bar', JSONcontainer, SVGcontainer, this.style); - } - }; + return pickBy('isBefore', args); + } - /** - * return the legend entree for this group. - * - * @param iconWidth - * @param iconHeight - * @returns {{icon: HTMLElement, label: (group.content|*|string), orientation: (.options.yAxisOrientation|*)}} - */ - GraphGroup.prototype.getLegend = function (iconWidth, iconHeight) { - var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - this.drawIcon(0, 0.5 * iconHeight, [], svg, iconWidth, iconHeight); - return { icon: svg, label: this.content, orientation: this.options.yAxisOrientation }; - }; + function max () { + var args = [].slice.call(arguments, 0); - GraphGroup.prototype.getYRange = function (groupData) { - return this.type.getYRange(groupData); - }; + return pickBy('isAfter', args); + } - GraphGroup.prototype.getData = function (groupData) { - return this.type.getData(groupData); - }; + function Duration (duration) { + var normalizedInput = normalizeObjectUnits(duration), + years = normalizedInput.year || 0, + quarters = normalizedInput.quarter || 0, + months = normalizedInput.month || 0, + weeks = normalizedInput.week || 0, + days = normalizedInput.day || 0, + hours = normalizedInput.hour || 0, + minutes = normalizedInput.minute || 0, + seconds = normalizedInput.second || 0, + milliseconds = normalizedInput.millisecond || 0; - GraphGroup.prototype.draw = function (dataset, group, framework) { - this.type.draw(dataset, group, framework); - }; + // representation for dateAddRemove + this._milliseconds = +milliseconds + + seconds * 1e3 + // 1000 + minutes * 6e4 + // 1000 * 60 + hours * 36e5; // 1000 * 60 * 60 + // Because of dateAddRemove treats 24 hours as different from a + // day when working around DST, we need to store them separately + this._days = +days + + weeks * 7; + // It is impossible translate months into days without knowing + // which months you are are talking about, so we have to store + // it separately. + this._months = +months + + quarters * 3 + + years * 12; - module.exports = GraphGroup; + this._data = {}; -/***/ }, -/* 61 */ -/***/ function(module, exports, __webpack_require__) { + this._locale = locale_locales__getLocale(); - 'use strict'; + this._bubble(); + } - var DOMutil = __webpack_require__(21); - var Points = __webpack_require__(62); + function isDuration (obj) { + return obj instanceof Duration; + } - function Line(groupId, options) { - this.groupId = groupId; - this.options = options; - } + function offset (token, separator) { + addFormatToken(token, 0, 0, function () { + var offset = this.utcOffset(); + var sign = '+'; + if (offset < 0) { + offset = -offset; + sign = '-'; + } + return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); + }); + } - Line.prototype.getData = function (groupData) { - var combinedData = []; - for (var j = 0; j < groupData.length; j++) { - combinedData.push({ - x: groupData[j].x, - y: groupData[j].y, - groupId: this.groupId - }); - } - return combinedData; - }; + offset('Z', ':'); + offset('ZZ', ''); - Line.prototype.getYRange = function (groupData) { - var yMin = groupData[0].y; - var yMax = groupData[0].y; - for (var j = 0; j < groupData.length; j++) { - yMin = yMin > groupData[j].y ? groupData[j].y : yMin; - yMax = yMax < groupData[j].y ? groupData[j].y : yMax; - } - return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation }; - }; + // PARSING - Line.getStackedYRange = function (combinedData, groupRanges, groupIds, groupLabel, orientation) { - if (combinedData.length > 0) { - // sort by time and by group - combinedData.sort(function (a, b) { - if (a.x === b.x) { - return a.groupId < b.groupId ? -1 : 1; - } else { - return a.x - b.x; - } + addRegexToken('Z', matchOffset); + addRegexToken('ZZ', matchOffset); + addParseToken(['Z', 'ZZ'], function (input, array, config) { + config._useUTC = true; + config._tzm = offsetFromString(input); }); - var intersections = {}; - Line._getDataIntersections(intersections, combinedData); - groupRanges[groupLabel] = Line._getStackedYRange(intersections, combinedData); - groupRanges[groupLabel].yAxisOrientation = orientation; - groupIds.push(groupLabel); - } - }; + // HELPERS - Line._getStackedYRange = function (intersections, combinedData) { - var key; - var yMin = combinedData[0].y; - var yMax = combinedData[0].y; - for (var i = 0; i < combinedData.length; i++) { - key = combinedData[i].x; - if (intersections[key] === undefined) { - yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin; - yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax; - } else { - if (combinedData[i].y < 0) { - intersections[key].accumulatedNegative += combinedData[i].y; - } else { - intersections[key].accumulatedPositive += combinedData[i].y; - } - } - } - for (var xpos in intersections) { - if (intersections.hasOwnProperty(xpos)) { - yMin = yMin > intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMin; - yMin = yMin > intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMin; - yMax = yMax < intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMax; - yMax = yMax < intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMax; - } - } + // timezone chunker + // '+10:00' > ['10', '00'] + // '-1530' > ['-15', '30'] + var chunkOffset = /([\+\-]|\d\d)/gi; - return { min: yMin, max: yMax }; - }; + function offsetFromString(string) { + var matches = ((string || '').match(matchOffset) || []); + var chunk = matches[matches.length - 1] || []; + var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; + var minutes = +(parts[1] * 60) + toInt(parts[2]); - /** - * Fill the intersections object with counters of how many datapoints share the same x coordinates - * @param intersections - * @param combinedData - * @private - */ - Line._getDataIntersections = function (intersections, combinedData) { - // get intersections - var coreDistance; - for (var i = 0; i < combinedData.length; i++) { - if (i + 1 < combinedData.length) { - coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x); + return parts[0] === '+' ? minutes : -minutes; } - if (i > 0) { - coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x)); + + // Return a moment from input, that is local/utc/zone equivalent to model. + function cloneWithOffset(input, model) { + var res, diff; + if (model._isUTC) { + res = model.clone(); + diff = (isMoment(input) || isDate(input) ? +input : +local__createLocal(input)) - (+res); + // Use low-level api, because this fn is low-level api. + res._d.setTime(+res._d + diff); + utils_hooks__hooks.updateOffset(res, false); + return res; + } else { + return local__createLocal(input).local(); + } + return model._isUTC ? local__createLocal(input).zone(model._offset || 0) : local__createLocal(input).local(); } - if (coreDistance === 0) { - if (intersections[combinedData[i].x] === undefined) { - intersections[combinedData[i].x] = { amount: 0, resolved: 0, accumulatedPositive: 0, accumulatedNegative: 0 }; - } - intersections[combinedData[i].x].amount += 1; + + function getDateOffset (m) { + // On Firefox.24 Date#getTimezoneOffset returns a floating point. + // https://github.com/moment/moment/pull/1871 + return -Math.round(m._d.getTimezoneOffset() / 15) * 15; } - } - }; - /** - * draw a line graph - * - * @param dataset - * @param group - */ - Line.prototype.draw = function (dataset, group, framework) { - if (dataset != null) { - if (dataset.length > 0) { - var path, d; - var svgHeight = Number(framework.svg.style.height.replace('px', '')); - path = DOMutil.getSVGElement('path', framework.svgElements, framework.svg); - path.setAttributeNS(null, 'class', group.className); - if (group.style !== undefined) { - path.setAttributeNS(null, 'style', group.style); - } + // HOOKS - // construct path from dataset - if (group.options.interpolation.enabled == true) { - d = Line._catmullRom(dataset, group); - } else { - d = Line._linear(dataset); - } + // This function will be called whenever a moment is mutated. + // It is intended to keep the offset in sync with the timezone. + utils_hooks__hooks.updateOffset = function () {}; - // append with points for fill and finalize the path - if (group.options.shaded.enabled == true) { - var fillPath = DOMutil.getSVGElement('path', framework.svgElements, framework.svg); - var dFill; - if (group.options.shaded.orientation == 'top') { - dFill = 'M' + dataset[0].x + ',' + 0 + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + 0; + // MOMENTS + + // keepLocalTime = true means only change the timezone, without + // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> + // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset + // +0200, so we adjust the time as needed, to be valid. + // + // Keeping the time actually adds/subtracts (one hour) + // from the actual represented time. That is why we call updateOffset + // a second time. In case it wants us to change the offset again + // _changeInProgress == true case, then we have to adjust, because + // there is no such time in the given timezone. + function getSetOffset (input, keepLocalTime) { + var offset = this._offset || 0, + localAdjust; + if (input != null) { + if (typeof input === 'string') { + input = offsetFromString(input); + } + if (Math.abs(input) < 16) { + input = input * 60; + } + if (!this._isUTC && keepLocalTime) { + localAdjust = getDateOffset(this); + } + this._offset = input; + this._isUTC = true; + if (localAdjust != null) { + this.add(localAdjust, 'm'); + } + if (offset !== input) { + if (!keepLocalTime || this._changeInProgress) { + add_subtract__addSubtract(this, create__createDuration(input - offset, 'm'), 1, false); + } else if (!this._changeInProgress) { + this._changeInProgress = true; + utils_hooks__hooks.updateOffset(this, true); + this._changeInProgress = null; + } + } + return this; } else { - dFill = 'M' + dataset[0].x + ',' + svgHeight + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + svgHeight; + return this._isUTC ? offset : getDateOffset(this); } - fillPath.setAttributeNS(null, 'class', group.className + ' vis-fill'); - if (group.options.shaded.style !== undefined) { - fillPath.setAttributeNS(null, 'style', group.options.shaded.style); + } + + function getSetZone (input, keepLocalTime) { + if (input != null) { + if (typeof input !== 'string') { + input = -input; + } + + this.utcOffset(input, keepLocalTime); + + return this; + } else { + return -this.utcOffset(); } - fillPath.setAttributeNS(null, 'd', dFill); - } - // copy properties to path for drawing. - path.setAttributeNS(null, 'd', 'M' + d); + } - // draw points - if (group.options.drawPoints.enabled == true) { - Points.draw(dataset, group, framework); - } + function setOffsetToUTC (keepLocalTime) { + return this.utcOffset(0, keepLocalTime); } - } - }; - /** - * This uses an uniform parametrization of the interpolation algorithm: - * 'On the Parameterization of Catmull-Rom Curves' by Cem Yuksel et al. - * @param data - * @returns {string} - * @private - */ - Line._catmullRomUniform = function (data) { - // catmull rom - var p0, p1, p2, p3, bp1, bp2; - var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' '; - var normalization = 1 / 6; - var length = data.length; - for (var i = 0; i < length - 1; i++) { + function setOffsetToLocal (keepLocalTime) { + if (this._isUTC) { + this.utcOffset(0, keepLocalTime); + this._isUTC = false; - p0 = i == 0 ? data[0] : data[i - 1]; - p1 = data[i]; - p2 = data[i + 1]; - p3 = i + 2 < length ? data[i + 2] : p2; + if (keepLocalTime) { + this.subtract(getDateOffset(this), 'm'); + } + } + return this; + } - // Catmull-Rom to Cubic Bezier conversion matrix - // 0 1 0 0 - // -1/6 1 1/6 0 - // 0 1/6 1 -1/6 - // 0 0 1 0 + function setOffsetToParsedOffset () { + if (this._tzm) { + this.utcOffset(this._tzm); + } else if (typeof this._i === 'string') { + this.utcOffset(offsetFromString(this._i)); + } + return this; + } - // bp0 = { x: p1.x, y: p1.y }; - bp1 = { x: (-p0.x + 6 * p1.x + p2.x) * normalization, y: (-p0.y + 6 * p1.y + p2.y) * normalization }; - bp2 = { x: (p1.x + 6 * p2.x - p3.x) * normalization, y: (p1.y + 6 * p2.y - p3.y) * normalization }; - // bp0 = { x: p2.x, y: p2.y }; + function hasAlignedHourOffset (input) { + if (!input) { + input = 0; + } + else { + input = local__createLocal(input).utcOffset(); + } - d += 'C' + bp1.x + ',' + bp1.y + ' ' + bp2.x + ',' + bp2.y + ' ' + p2.x + ',' + p2.y + ' '; - } + return (this.utcOffset() - input) % 60 === 0; + } - return d; - }; + function isDaylightSavingTime () { + return ( + this.utcOffset() > this.clone().month(0).utcOffset() || + this.utcOffset() > this.clone().month(5).utcOffset() + ); + } - /** - * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm. - * By default, the centripetal parameterization is used because this gives the nicest results. - * These parameterizations are relatively heavy because the distance between 4 points have to be calculated. - * - * One optimization can be used to reuse distances since this is a sliding window approach. - * @param data - * @param group - * @returns {string} - * @private - */ - Line._catmullRom = function (data, group) { - var alpha = group.options.interpolation.alpha; - if (alpha == 0 || alpha === undefined) { - return this._catmullRomUniform(data); - } else { - var p0, p1, p2, p3, bp1, bp2, d1, d2, d3, A, B, N, M; - var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA; - var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' '; - var length = data.length; - for (var i = 0; i < length - 1; i++) { + function isDaylightSavingTimeShifted () { + if (this._a) { + var other = this._isUTC ? create_utc__createUTC(this._a) : local__createLocal(this._a); + return this.isValid() && compareArrays(this._a, other.toArray()) > 0; + } - p0 = i == 0 ? data[0] : data[i - 1]; - p1 = data[i]; - p2 = data[i + 1]; - p3 = i + 2 < length ? data[i + 2] : p2; + return false; + } - d1 = Math.sqrt(Math.pow(p0.x - p1.x, 2) + Math.pow(p0.y - p1.y, 2)); - d2 = Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2)); - d3 = Math.sqrt(Math.pow(p2.x - p3.x, 2) + Math.pow(p2.y - p3.y, 2)); + function isLocal () { + return !this._isUTC; + } - // Catmull-Rom to Cubic Bezier conversion matrix + function isUtcOffset () { + return this._isUTC; + } - // A = 2d1^2a + 3d1^a * d2^a + d3^2a - // B = 2d3^2a + 3d3^a * d2^a + d2^2a + function isUtc () { + return this._isUTC && this._offset === 0; + } - // [ 0 1 0 0 ] - // [ -d2^2a /N A/N d1^2a /N 0 ] - // [ 0 d3^2a /M B/M -d2^2a /M ] - // [ 0 0 1 0 ] + var aspNetRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/; - d3powA = Math.pow(d3, alpha); - d3pow2A = Math.pow(d3, 2 * alpha); - d2powA = Math.pow(d2, alpha); - d2pow2A = Math.pow(d2, 2 * alpha); - d1powA = Math.pow(d1, alpha); - d1pow2A = Math.pow(d1, 2 * alpha); + // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html + // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere + var create__isoRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/; - A = 2 * d1pow2A + 3 * d1powA * d2powA + d2pow2A; - B = 2 * d3pow2A + 3 * d3powA * d2powA + d2pow2A; - N = 3 * d1powA * (d1powA + d2powA); - if (N > 0) { - N = 1 / N; - } - M = 3 * d3powA * (d3powA + d2powA); - if (M > 0) { - M = 1 / M; - } + function create__createDuration (input, key) { + var duration = input, + // matching against regexp is expensive, do it on demand + match = null, + sign, + ret, + diffRes; - bp1 = { x: (-d2pow2A * p0.x + A * p1.x + d1pow2A * p2.x) * N, - y: (-d2pow2A * p0.y + A * p1.y + d1pow2A * p2.y) * N }; + if (isDuration(input)) { + duration = { + ms : input._milliseconds, + d : input._days, + M : input._months + }; + } else if (typeof input === 'number') { + duration = {}; + if (key) { + duration[key] = input; + } else { + duration.milliseconds = input; + } + } else if (!!(match = aspNetRegex.exec(input))) { + sign = (match[1] === '-') ? -1 : 1; + duration = { + y : 0, + d : toInt(match[DATE]) * sign, + h : toInt(match[HOUR]) * sign, + m : toInt(match[MINUTE]) * sign, + s : toInt(match[SECOND]) * sign, + ms : toInt(match[MILLISECOND]) * sign + }; + } else if (!!(match = create__isoRegex.exec(input))) { + sign = (match[1] === '-') ? -1 : 1; + duration = { + y : parseIso(match[2], sign), + M : parseIso(match[3], sign), + d : parseIso(match[4], sign), + h : parseIso(match[5], sign), + m : parseIso(match[6], sign), + s : parseIso(match[7], sign), + w : parseIso(match[8], sign) + }; + } else if (duration == null) {// checks for null or undefined + duration = {}; + } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { + diffRes = momentsDifference(local__createLocal(duration.from), local__createLocal(duration.to)); - bp2 = { x: (d3pow2A * p1.x + B * p2.x - d2pow2A * p3.x) * M, - y: (d3pow2A * p1.y + B * p2.y - d2pow2A * p3.y) * M }; + duration = {}; + duration.ms = diffRes.milliseconds; + duration.M = diffRes.months; + } - if (bp1.x == 0 && bp1.y == 0) { - bp1 = p1; - } - if (bp2.x == 0 && bp2.y == 0) { - bp2 = p2; - } - d += 'C' + bp1.x + ',' + bp1.y + ' ' + bp2.x + ',' + bp2.y + ' ' + p2.x + ',' + p2.y + ' '; - } + ret = new Duration(duration); - return d; - } - }; + if (isDuration(input) && hasOwnProp(input, '_locale')) { + ret._locale = input._locale; + } - /** - * this generates the SVG path for a linear drawing between datapoints. - * @param data - * @returns {string} - * @private - */ - Line._linear = function (data) { - // linear - var d = ''; - for (var i = 0; i < data.length; i++) { - if (i == 0) { - d += data[i].x + ',' + data[i].y; - } else { - d += ' ' + data[i].x + ',' + data[i].y; + return ret; } - } - return d; - }; - - module.exports = Line; - -/***/ }, -/* 62 */ -/***/ function(module, exports, __webpack_require__) { - 'use strict'; + create__createDuration.fn = Duration.prototype; - var DOMutil = __webpack_require__(21); + function parseIso (inp, sign) { + // We'd normally use ~~inp for this, but unfortunately it also + // converts floats to ints. + // inp may be undefined, so careful calling replace on it. + var res = inp && parseFloat(inp.replace(',', '.')); + // apply sign while we're at it + return (isNaN(res) ? 0 : res) * sign; + } - function Points(groupId, options) { - this.groupId = groupId; - this.options = options; - } + function positiveMomentsDifference(base, other) { + var res = {milliseconds: 0, months: 0}; - Points.prototype.getYRange = function (groupData) { - var yMin = groupData[0].y; - var yMax = groupData[0].y; - for (var j = 0; j < groupData.length; j++) { - yMin = yMin > groupData[j].y ? groupData[j].y : yMin; - yMax = yMax < groupData[j].y ? groupData[j].y : yMax; - } - return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation }; - }; + res.months = other.month() - base.month() + + (other.year() - base.year()) * 12; + if (base.clone().add(res.months, 'M').isAfter(other)) { + --res.months; + } - Points.prototype.draw = function (dataset, group, framework, offset) { - Points.draw(dataset, group, framework, offset); - }; + res.milliseconds = +other - +(base.clone().add(res.months, 'M')); - /** - * draw the data points - * - * @param {Array} dataset - * @param {Object} JSONcontainer - * @param {Object} svg | SVG DOM element - * @param {GraphGroup} group - * @param {Number} [offset] - */ - Points.draw = function (dataset, group, framework, offset) { - if (offset === undefined) { - offset = 0; - } - for (var i = 0; i < dataset.length; i++) { - DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, framework.svgElements, framework.svg, dataset[i].label); - } - }; + return res; + } - module.exports = Points; + function momentsDifference(base, other) { + var res; + other = cloneWithOffset(other, base); + if (base.isBefore(other)) { + res = positiveMomentsDifference(base, other); + } else { + res = positiveMomentsDifference(other, base); + res.milliseconds = -res.milliseconds; + res.months = -res.months; + } -/***/ }, -/* 63 */ -/***/ function(module, exports, __webpack_require__) { + return res; + } - 'use strict'; + function createAdder(direction, name) { + return function (val, period) { + var dur, tmp; + //invert the arguments, but complain about it + if (period !== null && !isNaN(+period)) { + deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).'); + tmp = val; val = period; period = tmp; + } - var DOMutil = __webpack_require__(21); - var Points = __webpack_require__(62); + val = typeof val === 'string' ? +val : val; + dur = create__createDuration(val, period); + add_subtract__addSubtract(this, dur, direction); + return this; + }; + } - function Bargraph(groupId, options) { - this.groupId = groupId; - this.options = options; - } + function add_subtract__addSubtract (mom, duration, isAdding, updateOffset) { + var milliseconds = duration._milliseconds, + days = duration._days, + months = duration._months; + updateOffset = updateOffset == null ? true : updateOffset; - Bargraph.prototype.getYRange = function (groupData) { - var yMin = groupData[0].y; - var yMax = groupData[0].y; - for (var j = 0; j < groupData.length; j++) { - yMin = yMin > groupData[j].y ? groupData[j].y : yMin; - yMax = yMax < groupData[j].y ? groupData[j].y : yMax; - } - return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation }; - }; + if (milliseconds) { + mom._d.setTime(+mom._d + milliseconds * isAdding); + } + if (days) { + get_set__set(mom, 'Date', get_set__get(mom, 'Date') + days * isAdding); + } + if (months) { + setMonth(mom, get_set__get(mom, 'Month') + months * isAdding); + } + if (updateOffset) { + utils_hooks__hooks.updateOffset(mom, days || months); + } + } - Bargraph.prototype.getData = function (groupData) { - var combinedData = []; - for (var j = 0; j < groupData.length; j++) { - combinedData.push({ - x: groupData[j].x, - y: groupData[j].y, - groupId: this.groupId - }); - } - return combinedData; - }; + var add_subtract__add = createAdder(1, 'add'); + var add_subtract__subtract = createAdder(-1, 'subtract'); - /** - * draw a bar graph - * - * @param groupIds - * @param processedGroupData - */ - Bargraph.draw = function (groupIds, processedGroupData, framework) { - var combinedData = []; - var intersections = {}; - var coreDistance; - var key, drawData; - var group; - var i, j; - var barPoints = 0; + function moment_calendar__calendar (time) { + // We want to compare the start of today, vs this. + // Getting start-of-today depends on whether we're local/utc/offset or not. + var now = time || local__createLocal(), + sod = cloneWithOffset(now, this).startOf('day'), + diff = this.diff(sod, 'days', true), + format = diff < -6 ? 'sameElse' : + diff < -1 ? 'lastWeek' : + diff < 0 ? 'lastDay' : + diff < 1 ? 'sameDay' : + diff < 2 ? 'nextDay' : + diff < 7 ? 'nextWeek' : 'sameElse'; + return this.format(this.localeData().calendar(format, this, local__createLocal(now))); + } - // combine all barchart data - for (i = 0; i < groupIds.length; i++) { - group = framework.groups[groupIds[i]]; - if (group.options.style === 'bar') { - if (group.visible === true && (framework.options.groups.visibility[groupIds[i]] === undefined || framework.options.groups.visibility[groupIds[i]] === true)) { - for (j = 0; j < processedGroupData[groupIds[i]].length; j++) { - combinedData.push({ - x: processedGroupData[groupIds[i]][j].x, - y: processedGroupData[groupIds[i]][j].y, - groupId: groupIds[i], - label: processedGroupData[groupIds[i]][j].label - }); - barPoints += 1; + function clone () { + return new Moment(this); + } + + function isAfter (input, units) { + var inputMs; + units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); + if (units === 'millisecond') { + input = isMoment(input) ? input : local__createLocal(input); + return +this > +input; + } else { + inputMs = isMoment(input) ? +input : +local__createLocal(input); + return inputMs < +this.clone().startOf(units); } - } } - } - if (barPoints === 0) { - return; - } + function isBefore (input, units) { + var inputMs; + units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); + if (units === 'millisecond') { + input = isMoment(input) ? input : local__createLocal(input); + return +this < +input; + } else { + inputMs = isMoment(input) ? +input : +local__createLocal(input); + return +this.clone().endOf(units) < inputMs; + } + } - // sort by time and by group - combinedData.sort(function (a, b) { - if (a.x === b.x) { - return a.groupId < b.groupId ? -1 : 1; - } else { - return a.x - b.x; + function isBetween (from, to, units) { + return this.isAfter(from, units) && this.isBefore(to, units); } - }); - // get intersections - Bargraph._getDataIntersections(intersections, combinedData); + function isSame (input, units) { + var inputMs; + units = normalizeUnits(units || 'millisecond'); + if (units === 'millisecond') { + input = isMoment(input) ? input : local__createLocal(input); + return +this === +input; + } else { + inputMs = +local__createLocal(input); + return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units)); + } + } - // plot barchart - for (i = 0; i < combinedData.length; i++) { - group = framework.groups[combinedData[i].groupId]; - var minWidth = 0.1 * group.options.barChart.width; + function absFloor (number) { + if (number < 0) { + return Math.ceil(number); + } else { + return Math.floor(number); + } + } - key = combinedData[i].x; - var heightOffset = 0; - if (intersections[key] === undefined) { - if (i + 1 < combinedData.length) { - coreDistance = Math.abs(combinedData[i + 1].x - key); - } - if (i > 0) { - coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - key)); - } - drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth); - } else { - var nextKey = i + (intersections[key].amount - intersections[key].resolved); - var prevKey = i - (intersections[key].resolved + 1); - if (nextKey < combinedData.length) { - coreDistance = Math.abs(combinedData[nextKey].x - key); - } - if (prevKey > 0) { - coreDistance = Math.min(coreDistance, Math.abs(combinedData[prevKey].x - key)); - } - drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth); - intersections[key].resolved += 1; + function diff (input, units, asFloat) { + var that = cloneWithOffset(input, this), + zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4, + delta, output; - if (group.options.stack === true) { - if (combinedData[i].y < group.zeroPosition) { - heightOffset = intersections[key].accumulatedNegative; - intersections[key].accumulatedNegative += group.zeroPosition - combinedData[i].y; + units = normalizeUnits(units); + + if (units === 'year' || units === 'month' || units === 'quarter') { + output = monthDiff(this, that); + if (units === 'quarter') { + output = output / 3; + } else if (units === 'year') { + output = output / 12; + } } else { - heightOffset = intersections[key].accumulatedPositive; - intersections[key].accumulatedPositive += group.zeroPosition - combinedData[i].y; + delta = this - that; + output = units === 'second' ? delta / 1e3 : // 1000 + units === 'minute' ? delta / 6e4 : // 1000 * 60 + units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60 + units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst + units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst + delta; } - } else if (group.options.barChart.sideBySide === true) { - drawData.width = drawData.width / intersections[key].amount; - drawData.offset += intersections[key].resolved * drawData.width - 0.5 * drawData.width * (intersections[key].amount + 1); - if (group.options.barChart.align === 'left') { - drawData.offset -= 0.5 * drawData.width; - } else if (group.options.barChart.align === 'right') { - drawData.offset += 0.5 * drawData.width; + return asFloat ? output : absFloor(output); + } + + function monthDiff (a, b) { + // difference in months + var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), + // b is in (anchor - 1 month, anchor + 1 month) + anchor = a.clone().add(wholeMonthDiff, 'months'), + anchor2, adjust; + + if (b - anchor < 0) { + anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor - anchor2); + } else { + anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor2 - anchor); } - } + + return -(wholeMonthDiff + adjust); } - DOMutil.drawBar(combinedData[i].x + drawData.offset, combinedData[i].y - heightOffset, drawData.width, group.zeroPosition - combinedData[i].y, group.className + ' vis-bar', framework.svgElements, framework.svg, group.style); - // draw points - if (group.options.drawPoints.enabled === true) { - Points.draw([combinedData[i]], group, framework, drawData.offset); - //DOMutil.drawPoint(combinedData[i].x + drawData.offset, combinedData[i].y, group, framework.svgElements, framework.svg); + + utils_hooks__hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; + + function toString () { + return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); } - } - }; - /** - * Fill the intersections object with counters of how many datapoints share the same x coordinates - * @param intersections - * @param combinedData - * @private - */ - Bargraph._getDataIntersections = function (intersections, combinedData) { - // get intersections - var coreDistance; - for (var i = 0; i < combinedData.length; i++) { - if (i + 1 < combinedData.length) { - coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x); + function moment_format__toISOString () { + var m = this.clone().utc(); + if (0 < m.year() && m.year() <= 9999) { + if ('function' === typeof Date.prototype.toISOString) { + // native implementation is ~50x faster, use it when we can + return this.toDate().toISOString(); + } else { + return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); + } + } else { + return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); + } } - if (i > 0) { - coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x)); + + function format (inputString) { + var output = formatMoment(this, inputString || utils_hooks__hooks.defaultFormat); + return this.localeData().postformat(output); } - if (coreDistance === 0) { - if (intersections[combinedData[i].x] === undefined) { - intersections[combinedData[i].x] = { amount: 0, resolved: 0, accumulatedPositive: 0, accumulatedNegative: 0 }; - } - intersections[combinedData[i].x].amount += 1; + + function from (time, withoutSuffix) { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + return create__createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); } - } - }; - /** - * Get the width and offset for bargraphs based on the coredistance between datapoints - * - * @param coreDistance - * @param group - * @param minWidth - * @returns {{width: Number, offset: Number}} - * @private - */ - Bargraph._getSafeDrawData = function (coreDistance, group, minWidth) { - var width, offset; - if (coreDistance < group.options.barChart.width && coreDistance > 0) { - width = coreDistance < minWidth ? minWidth : coreDistance; + function fromNow (withoutSuffix) { + return this.from(local__createLocal(), withoutSuffix); + } - offset = 0; // recalculate offset with the new width; - if (group.options.barChart.align === 'left') { - offset -= 0.5 * coreDistance; - } else if (group.options.barChart.align === 'right') { - offset += 0.5 * coreDistance; + function to (time, withoutSuffix) { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + return create__createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix); } - } else { - // default settings - width = group.options.barChart.width; - offset = 0; - if (group.options.barChart.align === 'left') { - offset -= 0.5 * group.options.barChart.width; - } else if (group.options.barChart.align === 'right') { - offset += 0.5 * group.options.barChart.width; + + function toNow (withoutSuffix) { + return this.to(local__createLocal(), withoutSuffix); } - } - return { width: width, offset: offset }; - }; + function locale (key) { + var newLocaleData; - Bargraph.getStackedYRange = function (combinedData, groupRanges, groupIds, groupLabel, orientation) { - if (combinedData.length > 0) { - // sort by time and by group - combinedData.sort(function (a, b) { - if (a.x === b.x) { - return a.groupId < b.groupId ? -1 : 1; - } else { - return a.x - b.x; - } - }); - var intersections = {}; + if (key === undefined) { + return this._locale._abbr; + } else { + newLocaleData = locale_locales__getLocale(key); + if (newLocaleData != null) { + this._locale = newLocaleData; + } + return this; + } + } - Bargraph._getDataIntersections(intersections, combinedData); - groupRanges[groupLabel] = Bargraph._getStackedYRange(intersections, combinedData); - groupRanges[groupLabel].yAxisOrientation = orientation; - groupIds.push(groupLabel); - } - }; + var lang = deprecate( + 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', + function (key) { + if (key === undefined) { + return this.localeData(); + } else { + return this.locale(key); + } + } + ); - Bargraph._getStackedYRange = function (intersections, combinedData) { - var key; - var yMin = combinedData[0].y; - var yMax = combinedData[0].y; - for (var i = 0; i < combinedData.length; i++) { - key = combinedData[i].x; - if (intersections[key] === undefined) { - yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin; - yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax; - } else { - if (combinedData[i].y < 0) { - intersections[key].accumulatedNegative += combinedData[i].y; - } else { - intersections[key].accumulatedPositive += combinedData[i].y; - } - } - } - for (var xpos in intersections) { - if (intersections.hasOwnProperty(xpos)) { - yMin = yMin > intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMin; - yMin = yMin > intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMin; - yMax = yMax < intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMax; - yMax = yMax < intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMax; + function localeData () { + return this._locale; } - } - return { min: yMin, max: yMax }; - }; + function startOf (units) { + units = normalizeUnits(units); + // the following switch intentionally omits break keywords + // to utilize falling through the cases. + switch (units) { + case 'year': + this.month(0); + /* falls through */ + case 'quarter': + case 'month': + this.date(1); + /* falls through */ + case 'week': + case 'isoWeek': + case 'day': + this.hours(0); + /* falls through */ + case 'hour': + this.minutes(0); + /* falls through */ + case 'minute': + this.seconds(0); + /* falls through */ + case 'second': + this.milliseconds(0); + } - module.exports = Bargraph; + // weeks are a special case + if (units === 'week') { + this.weekday(0); + } + if (units === 'isoWeek') { + this.isoWeekday(1); + } -/***/ }, -/* 64 */ -/***/ function(module, exports, __webpack_require__) { + // quarters are also special + if (units === 'quarter') { + this.month(Math.floor(this.month() / 3) * 3); + } - 'use strict'; + return this; + } - var util = __webpack_require__(2); - var DOMutil = __webpack_require__(21); - var Component = __webpack_require__(35); + function endOf (units) { + units = normalizeUnits(units); + if (units === undefined || units === 'millisecond') { + return this; + } + return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); + } - /** - * Legend for Graph2d - */ - function Legend(body, options, side, linegraphOptions) { - this.body = body; - this.defaultOptions = { - enabled: true, - icons: true, - iconSize: 20, - iconSpacing: 6, - left: { - visible: true, - position: 'top-left' // top/bottom - left,center,right - }, - right: { - visible: true, - position: 'top-left' // top/bottom - left,center,right + function to_type__valueOf () { + return +this._d - ((this._offset || 0) * 60000); + } + + function unix () { + return Math.floor(+this / 1000); } - }; - this.side = side; - this.options = util.extend({}, this.defaultOptions); - this.linegraphOptions = linegraphOptions; - this.svgElements = {}; - this.dom = {}; - this.groups = {}; - this.amountOfGroups = 0; - this._create(); + function toDate () { + return this._offset ? new Date(+this) : this._d; + } - this.setOptions(options); - } + function toArray () { + var m = this; + return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; + } - Legend.prototype = new Component(); + function moment_valid__isValid () { + return valid__isValid(this); + } - Legend.prototype.clear = function () { - this.groups = {}; - this.amountOfGroups = 0; - }; + function parsingFlags () { + return extend({}, getParsingFlags(this)); + } - Legend.prototype.addGroup = function (label, graphOptions) { + function invalidAt () { + return getParsingFlags(this).overflow; + } - if (!this.groups.hasOwnProperty(label)) { - this.groups[label] = graphOptions; - } - this.amountOfGroups += 1; - }; + addFormatToken(0, ['gg', 2], 0, function () { + return this.weekYear() % 100; + }); - Legend.prototype.updateGroup = function (label, graphOptions) { - this.groups[label] = graphOptions; - }; + addFormatToken(0, ['GG', 2], 0, function () { + return this.isoWeekYear() % 100; + }); - Legend.prototype.removeGroup = function (label) { - if (this.groups.hasOwnProperty(label)) { - delete this.groups[label]; - this.amountOfGroups -= 1; - } - }; + function addWeekYearFormatToken (token, getter) { + addFormatToken(0, [token, token.length], 0, getter); + } - Legend.prototype._create = function () { - this.dom.frame = document.createElement('div'); - this.dom.frame.className = 'vis-legend'; - this.dom.frame.style.position = 'absolute'; - this.dom.frame.style.top = '10px'; - this.dom.frame.style.display = 'block'; + addWeekYearFormatToken('gggg', 'weekYear'); + addWeekYearFormatToken('ggggg', 'weekYear'); + addWeekYearFormatToken('GGGG', 'isoWeekYear'); + addWeekYearFormatToken('GGGGG', 'isoWeekYear'); - this.dom.textArea = document.createElement('div'); - this.dom.textArea.className = 'vis-legend-text'; - this.dom.textArea.style.position = 'relative'; - this.dom.textArea.style.top = '0px'; + // ALIASES - this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - this.svg.style.position = 'absolute'; - this.svg.style.top = 0 + 'px'; - this.svg.style.width = this.options.iconSize + 5 + 'px'; - this.svg.style.height = '100%'; + addUnitAlias('weekYear', 'gg'); + addUnitAlias('isoWeekYear', 'GG'); - this.dom.frame.appendChild(this.svg); - this.dom.frame.appendChild(this.dom.textArea); - }; + // PARSING - /** - * Hide the component from the DOM - */ - Legend.prototype.hide = function () { - // remove the frame containing the items - if (this.dom.frame.parentNode) { - this.dom.frame.parentNode.removeChild(this.dom.frame); - } - }; + addRegexToken('G', matchSigned); + addRegexToken('g', matchSigned); + addRegexToken('GG', match1to2, match2); + addRegexToken('gg', match1to2, match2); + addRegexToken('GGGG', match1to4, match4); + addRegexToken('gggg', match1to4, match4); + addRegexToken('GGGGG', match1to6, match6); + addRegexToken('ggggg', match1to6, match6); - /** - * Show the component in the DOM (when not already visible). - * @return {Boolean} changed - */ - Legend.prototype.show = function () { - // show frame containing the items - if (!this.dom.frame.parentNode) { - this.body.dom.center.appendChild(this.dom.frame); - } - }; + addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { + week[token.substr(0, 2)] = toInt(input); + }); - Legend.prototype.setOptions = function (options) { - var fields = ['enabled', 'orientation', 'icons', 'left', 'right']; - util.selectiveDeepExtend(fields, this.options, options); - }; + addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { + week[token] = utils_hooks__hooks.parseTwoDigitYear(input); + }); - Legend.prototype.redraw = function () { - var activeGroups = 0; - var groupArray = Object.keys(this.groups); - groupArray.sort(function (a, b) { - return a < b ? -1 : 1; - }); + // HELPERS - for (var i = 0; i < groupArray.length; i++) { - var groupId = groupArray[i]; - if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { - activeGroups++; + function weeksInYear(year, dow, doy) { + return weekOfYear(local__createLocal([year, 11, 31 + dow - doy]), dow, doy).week; } - } - if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false || activeGroups == 0) { - this.hide(); - } else { - this.show(); - if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'bottom-left') { - this.dom.frame.style.left = '4px'; - this.dom.frame.style.textAlign = 'left'; - this.dom.textArea.style.textAlign = 'left'; - this.dom.textArea.style.left = this.options.iconSize + 15 + 'px'; - this.dom.textArea.style.right = ''; - this.svg.style.left = 0 + 'px'; - this.svg.style.right = ''; - } else { - this.dom.frame.style.right = '4px'; - this.dom.frame.style.textAlign = 'right'; - this.dom.textArea.style.textAlign = 'right'; - this.dom.textArea.style.right = this.options.iconSize + 15 + 'px'; - this.dom.textArea.style.left = ''; - this.svg.style.right = 0 + 'px'; - this.svg.style.left = ''; - } + // MOMENTS - if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'top-right') { - this.dom.frame.style.top = 4 - Number(this.body.dom.center.style.top.replace('px', '')) + 'px'; - this.dom.frame.style.bottom = ''; - } else { - var scrollableHeight = this.body.domProps.center.height - this.body.domProps.centerContainer.height; - this.dom.frame.style.bottom = 4 + scrollableHeight + Number(this.body.dom.center.style.top.replace('px', '')) + 'px'; - this.dom.frame.style.top = ''; + function getSetWeekYear (input) { + var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year; + return input == null ? year : this.add((input - year), 'y'); } - if (this.options.icons == false) { - this.dom.frame.style.width = this.dom.textArea.offsetWidth + 10 + 'px'; - this.dom.textArea.style.right = ''; - this.dom.textArea.style.left = ''; - this.svg.style.width = '0px'; - } else { - this.dom.frame.style.width = this.options.iconSize + 15 + this.dom.textArea.offsetWidth + 10 + 'px'; - this.drawLegendIcons(); + function getSetISOWeekYear (input) { + var year = weekOfYear(this, 1, 4).year; + return input == null ? year : this.add((input - year), 'y'); } - var content = ''; - for (var i = 0; i < groupArray.length; i++) { - var groupId = groupArray[i]; - if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { - content += this.groups[groupId].content + '
'; - } + function getISOWeeksInYear () { + return weeksInYear(this.year(), 1, 4); } - this.dom.textArea.innerHTML = content; - this.dom.textArea.style.lineHeight = 0.75 * this.options.iconSize + this.options.iconSpacing + 'px'; - } - }; - - Legend.prototype.drawLegendIcons = function () { - if (this.dom.frame.parentNode) { - var groupArray = Object.keys(this.groups); - groupArray.sort(function (a, b) { - return a < b ? -1 : 1; - }); - - DOMutil.prepareElements(this.svgElements); - var padding = window.getComputedStyle(this.dom.frame).paddingTop; - var iconOffset = Number(padding.replace('px', '')); - var x = iconOffset; - var iconWidth = this.options.iconSize; - var iconHeight = 0.75 * this.options.iconSize; - var y = iconOffset + 0.5 * iconHeight + 3; - this.svg.style.width = iconWidth + 5 + iconOffset + 'px'; - - for (var i = 0; i < groupArray.length; i++) { - var groupId = groupArray[i]; - if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { - this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight); - y += iconHeight + this.options.iconSpacing; - } + function getWeeksInYear () { + var weekInfo = this.localeData()._week; + return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); } - DOMutil.cleanupElements(this.svgElements); - } - }; + addFormatToken('Q', 0, 0, 'quarter'); - module.exports = Legend; + // ALIASES -/***/ }, -/* 65 */ -/***/ function(module, exports, __webpack_require__) { + addUnitAlias('quarter', 'Q'); - /** - * This object contains all possible options. It will check if the types are correct, if required if the option is one - * of the allowed values. - * - * __any__ means that the name of the property does not matter. - * __type__ is a required field for all objects and contains the allowed types of all objects - */ - 'use strict'; + // PARSING - Object.defineProperty(exports, '__esModule', { - value: true - }); - var string = 'string'; - var boolean = 'boolean'; - var number = 'number'; - var array = 'array'; - var date = 'date'; - var object = 'object'; // should only be in a __type__ property - var dom = 'dom'; - var moment = 'moment'; - var fn = 'function'; - var nada = 'null'; - var undef = 'undefined'; - var any = 'any'; + addRegexToken('Q', match1); + addParseToken('Q', function (input, array) { + array[MONTH] = (toInt(input) - 1) * 3; + }); - var allOptions = { - configure: { - enabled: { boolean: boolean }, - filter: { boolean: boolean, fn: fn }, - container: { dom: dom }, - __type__: { object: object, boolean: boolean, fn: fn } - }, + // MOMENTS - //globals : - yAxisOrientation: { string: ['left', 'right'] }, - defaultGroup: { string: string }, - sort: { boolean: boolean }, - sampling: { boolean: boolean }, - stack: { boolean: boolean }, - graphHeight: { string: string, number: number }, - shaded: { - enabled: { boolean: boolean }, - orientation: { string: ['bottom', 'top'] }, // top, bottom - __type__: { boolean: boolean, object: object } - }, - style: { string: ['line', 'bar', 'points'] }, // line, bar - barChart: { - width: { number: number }, - sideBySide: { boolean: boolean }, - align: { string: ['left', 'center', 'right'] }, - __type__: { object: object } - }, - interpolation: { - enabled: { boolean: boolean }, - parametrization: { string: ['centripetal', 'chordal', 'uniform'] }, // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) - alpha: { number: number }, - __type__: { object: object, boolean: boolean } - }, - drawPoints: { - enabled: { boolean: boolean }, - size: { number: number }, - style: { string: ['square', 'circle'] }, // square, circle - __type__: { object: object, boolean: boolean } - }, - dataAxis: { - showMinorLabels: { boolean: boolean }, - showMajorLabels: { boolean: boolean }, - icons: { boolean: boolean }, - width: { string: string, number: number }, - visible: { boolean: boolean }, - alignZeros: { boolean: boolean }, - left: { - range: { min: { number: number }, max: { number: number }, __type__: { object: object } }, - format: { fn: fn }, - title: { text: { string: string, number: number }, style: { string: string }, __type__: { object: object } }, - __type__: { object: object } - }, - right: { - range: { min: { number: number }, max: { number: number }, __type__: { object: object } }, - format: { fn: fn }, - title: { text: { string: string, number: number }, style: { string: string }, __type__: { object: object } }, - __type__: { object: object } - }, - __type__: { object: object } - }, - legend: { - enabled: { boolean: boolean }, - icons: { boolean: boolean }, - left: { - visible: { boolean: boolean }, - position: { string: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] }, - __type__: { object: object } - }, - right: { - visible: { boolean: boolean }, - position: { string: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] }, - __type__: { object: object } - }, - __type__: { object: object, boolean: boolean } - }, - groups: { - visibility: { any: any }, - __type__: { object: object } - }, + function getSetQuarter (input) { + return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); + } - autoResize: { boolean: boolean }, - clickToUse: { boolean: boolean }, - end: { number: number, date: date, string: string, moment: moment }, - format: { - minorLabels: { - millisecond: { string: string, undef: undef }, - second: { string: string, undef: undef }, - minute: { string: string, undef: undef }, - hour: { string: string, undef: undef }, - weekday: { string: string, undef: undef }, - day: { string: string, undef: undef }, - month: { string: string, undef: undef }, - year: { string: string, undef: undef }, - __type__: { object: object } - }, - majorLabels: { - millisecond: { string: string, undef: undef }, - second: { string: string, undef: undef }, - minute: { string: string, undef: undef }, - hour: { string: string, undef: undef }, - weekday: { string: string, undef: undef }, - day: { string: string, undef: undef }, - month: { string: string, undef: undef }, - year: { string: string, undef: undef }, - __type__: { object: object } - }, - __type__: { object: object } - }, - height: { string: string, number: number }, - hiddenDates: { object: object, array: array }, - locale: { string: string }, - locales: { - __any__: { object: object }, - __type__: { object: object } - }, - max: { date: date, number: number, string: string, moment: moment }, - maxHeight: { number: number, string: string }, - min: { date: date, number: number, string: string, moment: moment }, - minHeight: { number: number, string: string }, - moveable: { boolean: boolean }, - multiselect: { boolean: boolean }, - orientation: { string: string }, - showCurrentTime: { boolean: boolean }, - showMajorLabels: { boolean: boolean }, - showMinorLabels: { boolean: boolean }, - start: { date: date, number: number, string: string, moment: moment }, - timeAxis: { - scale: { string: string, undef: undef }, - step: { number: number, undef: undef }, - __type__: { object: object } - }, - width: { string: string, number: number }, - zoomable: { boolean: boolean }, - zoomMax: { number: number }, - zoomMin: { number: number }, - __type__: { object: object } - }; + addFormatToken('D', ['DD', 2], 'Do', 'date'); - var configureOptions = { - global: { - yAxisOrientation: ['left', 'right'], - sort: true, - sampling: true, - stack: false, - shaded: { - enabled: false, - orientation: ['top', 'bottom'] // top, bottom - }, - style: ['line', 'bar', 'points'], // line, bar - barChart: { - width: [50, 5, 100, 5], - sideBySide: false, - align: ['left', 'center', 'right'] // left, center, right - }, - interpolation: { - enabled: true, - parametrization: ['centripetal', 'chordal', 'uniform'] // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) - }, - drawPoints: { - enabled: true, - size: [6, 2, 30, 1], - style: ['square', 'circle'] // square, circle - }, - dataAxis: { - showMinorLabels: true, - showMajorLabels: true, - icons: false, - width: [40, 0, 200, 1], - visible: true, - alignZeros: true, - left: { - //range: {min:undefined,max:undefined}, - //format: function (value) {return value;}, - title: { text: '', style: '' } - }, - right: { - //range: {min:undefined,max:undefined}, - //format: function (value) {return value;}, - title: { text: '', style: '' } - } - }, - legend: { - enabled: false, - icons: true, - left: { - visible: true, - position: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] // top/bottom - left,right - }, - right: { - visible: true, - position: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] // top/bottom - left,right - } - }, + // ALIASES - autoResize: true, - clickToUse: false, - end: '', - format: { - minorLabels: { - millisecond: 'SSS', - second: 's', - minute: 'HH:mm', - hour: 'HH:mm', - weekday: 'ddd D', - day: 'D', - 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', - month: 'YYYY', - year: '' - } - }, + addUnitAlias('date', 'D'); - height: '', - locale: '', - max: '', - maxHeight: '', - min: '', - minHeight: '', - moveable: true, - orientation: ['both', 'bottom', 'top'], - showCurrentTime: false, - showMajorLabels: true, - showMinorLabels: true, - start: '', - width: '100%', - zoomable: true, - zoomMax: [315360000000000, 10, 315360000000000, 1], - zoomMin: [10, 10, 315360000000000, 1] - } - }; + // PARSING - exports.allOptions = allOptions; - exports.configureOptions = configureOptions; + addRegexToken('D', match1to2); + addRegexToken('DD', match1to2, match2); + addRegexToken('Do', function (isStrict, locale) { + return isStrict ? locale._ordinalParse : locale._ordinalParseLenient; + }); -/***/ }, -/* 66 */ -/***/ function(module, exports, __webpack_require__) { + addParseToken(['D', 'DD'], DATE); + addParseToken('Do', function (input, array) { + array[DATE] = toInt(input.match(match1to2)[0], 10); + }); - // Load custom shapes into CanvasRenderingContext2D - 'use strict'; + // MOMENTS - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var getSetDayOfMonth = makeGetSet('Date', true); - var _modulesGroups = __webpack_require__(67); + addFormatToken('d', 0, 'do', 'day'); - var _modulesGroups2 = _interopRequireDefault(_modulesGroups); + addFormatToken('dd', 0, 0, function (format) { + return this.localeData().weekdaysMin(this, format); + }); - var _modulesNodesHandler = __webpack_require__(4); + addFormatToken('ddd', 0, 0, function (format) { + return this.localeData().weekdaysShort(this, format); + }); - var _modulesNodesHandler2 = _interopRequireDefault(_modulesNodesHandler); + addFormatToken('dddd', 0, 0, function (format) { + return this.localeData().weekdays(this, format); + }); - var _modulesEdgesHandler = __webpack_require__(86); + addFormatToken('e', 0, 0, 'weekday'); + addFormatToken('E', 0, 0, 'isoWeekday'); - var _modulesEdgesHandler2 = _interopRequireDefault(_modulesEdgesHandler); + // ALIASES - var _modulesPhysicsEngine = __webpack_require__(92); + addUnitAlias('day', 'd'); + addUnitAlias('weekday', 'e'); + addUnitAlias('isoWeekday', 'E'); - var _modulesPhysicsEngine2 = _interopRequireDefault(_modulesPhysicsEngine); + // PARSING - var _modulesClustering = __webpack_require__(100); + addRegexToken('d', match1to2); + addRegexToken('e', match1to2); + addRegexToken('E', match1to2); + addRegexToken('dd', matchWord); + addRegexToken('ddd', matchWord); + addRegexToken('dddd', matchWord); - var _modulesClustering2 = _interopRequireDefault(_modulesClustering); + addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config) { + var weekday = config._locale.weekdaysParse(input); + // if we didn't get a weekday name, mark the date as invalid + if (weekday != null) { + week.d = weekday; + } else { + getParsingFlags(config).invalidWeekday = input; + } + }); - var _modulesCanvasRenderer = __webpack_require__(102); + addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { + week[token] = toInt(input); + }); - var _modulesCanvasRenderer2 = _interopRequireDefault(_modulesCanvasRenderer); + // HELPERS - var _modulesCanvas = __webpack_require__(103); + function parseWeekday(input, locale) { + if (typeof input === 'string') { + if (!isNaN(input)) { + input = parseInt(input, 10); + } + else { + input = locale.weekdaysParse(input); + if (typeof input !== 'number') { + return null; + } + } + } + return input; + } - var _modulesCanvas2 = _interopRequireDefault(_modulesCanvas); + // LOCALES - var _modulesView = __webpack_require__(104); + var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); + function localeWeekdays (m) { + return this._weekdays[m.day()]; + } - var _modulesView2 = _interopRequireDefault(_modulesView); + var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); + function localeWeekdaysShort (m) { + return this._weekdaysShort[m.day()]; + } - var _modulesInteractionHandler = __webpack_require__(12); + var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); + function localeWeekdaysMin (m) { + return this._weekdaysMin[m.day()]; + } - var _modulesInteractionHandler2 = _interopRequireDefault(_modulesInteractionHandler); + function localeWeekdaysParse (weekdayName) { + var i, mom, regex; - var _modulesSelectionHandler = __webpack_require__(107); + if (!this._weekdaysParse) { + this._weekdaysParse = []; + } - var _modulesSelectionHandler2 = _interopRequireDefault(_modulesSelectionHandler); + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + if (!this._weekdaysParse[i]) { + mom = local__createLocal([2000, 1]).day(i); + regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); + this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if (this._weekdaysParse[i].test(weekdayName)) { + return i; + } + } + } - var _modulesLayoutEngine = __webpack_require__(6); + // MOMENTS - var _modulesLayoutEngine2 = _interopRequireDefault(_modulesLayoutEngine); + function getSetDayOfWeek (input) { + var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); + if (input != null) { + input = parseWeekday(input, this.localeData()); + return this.add(input - day, 'd'); + } else { + return day; + } + } - var _modulesManipulationSystem = __webpack_require__(7); + function getSetLocaleDayOfWeek (input) { + var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; + return input == null ? weekday : this.add(input - weekday, 'd'); + } - var _modulesManipulationSystem2 = _interopRequireDefault(_modulesManipulationSystem); + function getSetISODayOfWeek (input) { + // behaves the same as moment#day except + // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) + // as a setter, sunday should belong to the previous week. + return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); + } - var _sharedConfigurator = __webpack_require__(52); + addFormatToken('H', ['HH', 2], 0, 'hour'); + addFormatToken('h', ['hh', 2], 0, function () { + return this.hours() % 12 || 12; + }); - var _sharedConfigurator2 = _interopRequireDefault(_sharedConfigurator); + function meridiem (token, lowercase) { + addFormatToken(token, 0, 0, function () { + return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); + }); + } - var _sharedValidator = __webpack_require__(54); + meridiem('a', true); + meridiem('A', false); - var _sharedValidator2 = _interopRequireDefault(_sharedValidator); + // ALIASES - var _optionsJs = __webpack_require__(108); + addUnitAlias('hour', 'h'); - __webpack_require__(109); + // PARSING - var Emitter = __webpack_require__(27); - var Hammer = __webpack_require__(13); - var util = __webpack_require__(2); - var DataSet = __webpack_require__(22); - var DataView = __webpack_require__(24); - var dotparser = __webpack_require__(110); - var gephiParser = __webpack_require__(111); - var Images = __webpack_require__(112); - var Activator = __webpack_require__(49); - var locales = __webpack_require__(113); + function matchMeridiem (isStrict, locale) { + return locale._meridiemParse; + } - /** - * @constructor Network - * Create a network visualization, displaying nodes and edges. - * - * @param {Element} container The DOM element in which the Network will - * be created. Normally a div element. - * @param {Object} data An object containing parameters - * {Array} nodes - * {Array} edges - * @param {Object} options Options - */ - function Network(container, data, options) { - var _this = this; + addRegexToken('a', matchMeridiem); + addRegexToken('A', matchMeridiem); + addRegexToken('H', match1to2); + addRegexToken('h', match1to2); + addRegexToken('HH', match1to2, match2); + addRegexToken('hh', match1to2, match2); - if (!(this instanceof Network)) { - throw new SyntaxError('Constructor must be called with the new operator'); - } + addParseToken(['H', 'HH'], HOUR); + addParseToken(['a', 'A'], function (input, array, config) { + config._isPm = config._locale.isPM(input); + config._meridiem = input; + }); + addParseToken(['h', 'hh'], function (input, array, config) { + array[HOUR] = toInt(input); + getParsingFlags(config).bigHour = true; + }); - // set constant values - this.options = {}; - this.defaultOptions = { - locale: 'en', - locales: locales, - clickToUse: false - }; - util.extend(this.options, this.defaultOptions); + // LOCALES - // containers for nodes and edges - this.body = { - nodes: {}, - nodeIndices: [], - edges: {}, - edgeIndices: [], - data: { - nodes: null, // A DataSet or DataView - edges: null // A DataSet or DataView - }, - functions: { - createNode: function createNode() {}, - createEdge: function createEdge() {}, - getPointer: function getPointer() {} - }, - emitter: { - on: this.on.bind(this), - off: this.off.bind(this), - emit: this.emit.bind(this), - once: this.once.bind(this) - }, - eventListeners: { - onTap: function onTap() {}, - onTouch: function onTouch() {}, - onDoubleTap: function onDoubleTap() {}, - onHold: function onHold() {}, - onDragStart: function onDragStart() {}, - onDrag: function onDrag() {}, - onDragEnd: function onDragEnd() {}, - onMouseWheel: function onMouseWheel() {}, - onPinch: function onPinch() {}, - onMouseMove: function onMouseMove() {}, - onRelease: function onRelease() {}, - onContext: function onContext() {} - }, - container: container, - view: { - scale: 1, - translation: { x: 0, y: 0 } + function localeIsPM (input) { + // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays + // Using charAt should be more compatible. + return ((input + '').toLowerCase().charAt(0) === 'p'); } - }; - - // bind the event listeners - this.bindEventListeners(); - - // setting up all modules - this.images = new Images(function () { - return _this.body.emitter.emit('_requestRedraw'); - }); // object with images - this.groups = new _modulesGroups2['default'](); // object with groups - this.canvas = new _modulesCanvas2['default'](this.body); // DOM handler - this.selectionHandler = new _modulesSelectionHandler2['default'](this.body, this.canvas); // Selection handler - this.interactionHandler = new _modulesInteractionHandler2['default'](this.body, this.canvas, this.selectionHandler); // Interaction handler handles all the hammer bindings (that are bound by canvas), key - this.view = new _modulesView2['default'](this.body, this.canvas); // camera handler, does animations and zooms - this.renderer = new _modulesCanvasRenderer2['default'](this.body, this.canvas); // renderer, starts renderloop, has events that modules can hook into - this.physics = new _modulesPhysicsEngine2['default'](this.body); // physics engine, does all the simulations - this.layoutEngine = new _modulesLayoutEngine2['default'](this.body); // layout engine for inital layout and hierarchical layout - this.clustering = new _modulesClustering2['default'](this.body); // clustering api - this.manipulation = new _modulesManipulationSystem2['default'](this.body, this.canvas, this.selectionHandler); // data manipulation system - this.nodesHandler = new _modulesNodesHandler2['default'](this.body, this.images, this.groups, this.layoutEngine); // Handle adding, deleting and updating of nodes as well as global options - this.edgesHandler = new _modulesEdgesHandler2['default'](this.body, this.images, this.groups); // Handle adding, deleting and updating of edges as well as global options + var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; + function localeMeridiem (hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'pm' : 'PM'; + } else { + return isLower ? 'am' : 'AM'; + } + } - // create the DOM elements - this.canvas._create(); - // setup configuration system - this.configurator = new _sharedConfigurator2['default'](this, this.body.container, _optionsJs.configureOptions, this.canvas.pixelRatio); + // MOMENTS - // apply options - this.setOptions(options); + // Setting the hour should keep the time, because the user explicitly + // specified which hour he wants. So trying to maintain the same hour (in + // a new timezone) makes sense. Adding/subtracting hours does not follow + // this rule. + var getSetHour = makeGetSet('Hours', true); - // load data (the disable start variable will be the same as the enabled clustering) - this.setData(data); - } + addFormatToken('m', ['mm', 2], 0, 'minute'); - // Extend Network with an Emitter mixin - Emitter(Network.prototype); + // ALIASES - /** - * Set options - * @param {Object} options - */ - Network.prototype.setOptions = function (options) { - var _this2 = this; + addUnitAlias('minute', 'm'); - if (options !== undefined) { + // PARSING - var errorFound = _sharedValidator2['default'].validate(options, _optionsJs.allOptions); - if (errorFound === true) { - console.log('%cErrors have been found in the supplied options object.', _sharedValidator.printStyle); - } + addRegexToken('m', match1to2); + addRegexToken('mm', match1to2, match2); + addParseToken(['m', 'mm'], MINUTE); - // copy the global fields over - var fields = ['locale', 'locales', 'clickToUse']; - util.selectiveDeepExtend(fields, this.options, options); + // MOMENTS - // the hierarchical system can adapt the edges and the physics to it's own options because not all combinations work with the hierarichical system. - options = this.layoutEngine.setOptions(options.layout, options); + var getSetMinute = makeGetSet('Minutes', false); - this.canvas.setOptions(options); // options for canvas are in globals + addFormatToken('s', ['ss', 2], 0, 'second'); - // pass the options to the modules - this.groups.setOptions(options.groups); - this.nodesHandler.setOptions(options.nodes); - this.edgesHandler.setOptions(options.edges); - this.physics.setOptions(options.physics); - this.manipulation.setOptions(options.manipulation, options, this.options); // manipulation uses the locales in the globals + // ALIASES - this.interactionHandler.setOptions(options.interaction); - this.renderer.setOptions(options.interaction); // options for rendering are in interaction - this.selectionHandler.setOptions(options.interaction); // options for selection are in interaction + addUnitAlias('second', 's'); - // reload the settings of the nodes to apply changes in groups that are not referenced by pointer. - if (options.groups !== undefined) { - this.body.emitter.emit('refreshNodes'); - } - // these two do not have options at the moment, here for completeness - //this.view.setOptions(options.view); - //this.clustering.setOptions(options.clustering); + // PARSING - this.configurator.setOptions(options.configure); + addRegexToken('s', match1to2); + addRegexToken('ss', match1to2, match2); + addParseToken(['s', 'ss'], SECOND); - // if the configuration system is enabled, copy all options and put them into the config system - if (this.configurator.options.enabled === true) { - var networkOptions = { nodes: {}, edges: {}, layout: {}, interaction: {}, manipulation: {}, physics: {}, global: {} }; - util.deepExtend(networkOptions.nodes, this.nodesHandler.options); - util.deepExtend(networkOptions.edges, this.edgesHandler.options); - util.deepExtend(networkOptions.layout, this.layoutEngine.options); - // load the selectionHandler and rendere default options in to the interaction group - util.deepExtend(networkOptions.interaction, this.selectionHandler.options); - util.deepExtend(networkOptions.interaction, this.renderer.options); + // MOMENTS - util.deepExtend(networkOptions.interaction, this.interactionHandler.options); - util.deepExtend(networkOptions.manipulation, this.manipulation.options); - util.deepExtend(networkOptions.physics, this.physics.options); + var getSetSecond = makeGetSet('Seconds', false); - // load globals into the global object - util.deepExtend(networkOptions.global, this.canvas.options); - util.deepExtend(networkOptions.global, this.options); + addFormatToken('S', 0, 0, function () { + return ~~(this.millisecond() / 100); + }); - this.configurator.setModuleOptions(networkOptions); - } + addFormatToken(0, ['SS', 2], 0, function () { + return ~~(this.millisecond() / 10); + }); - // handle network global options - if (options.clickToUse !== undefined) { - if (options.clickToUse === true) { - if (this.activator === undefined) { - this.activator = new Activator(this.canvas.frame); - this.activator.on('change', function () { - _this2.body.emitter.emit('activate'); - }); - } - } else { - if (this.activator !== undefined) { - this.activator.destroy(); - delete this.activator; - } - this.body.emitter.emit('activate'); - } - } else { - this.body.emitter.emit('activate'); + function millisecond__milliseconds (token) { + addFormatToken(0, [token, 3], 0, 'millisecond'); } - this.canvas.setSize(); - - // start the physics simulation. Can be safely called multiple times. - this.body.emitter.emit('startSimulation'); - } - }; + millisecond__milliseconds('SSS'); + millisecond__milliseconds('SSSS'); - /** - * Update the this.body.nodeIndices with the most recent node index list - * @private - */ - Network.prototype._updateVisibleIndices = function () { - var nodes = this.body.nodes; - var edges = this.body.edges; - this.body.nodeIndices = []; - this.body.edgeIndices = []; + // ALIASES - for (var nodeId in nodes) { - if (nodes.hasOwnProperty(nodeId)) { - if (nodes[nodeId].options.hidden === false) { - this.body.nodeIndices.push(nodeId); - } - } - } + addUnitAlias('millisecond', 'ms'); - for (var edgeId in edges) { - if (edges.hasOwnProperty(edgeId)) { - if (edges[edgeId].options.hidden === false) { - this.body.edgeIndices.push(edgeId); - } - } - } - }; + // PARSING - /** - * Bind all events - */ - Network.prototype.bindEventListeners = function () { - var _this3 = this; + addRegexToken('S', match1to3, match1); + addRegexToken('SS', match1to3, match2); + addRegexToken('SSS', match1to3, match3); + addRegexToken('SSSS', matchUnsigned); + addParseToken(['S', 'SS', 'SSS', 'SSSS'], function (input, array) { + array[MILLISECOND] = toInt(('0.' + input) * 1000); + }); - // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed. - this.body.emitter.on('_dataChanged', function () { - // update shortcut lists - _this3._updateVisibleIndices(); - _this3.physics.updatePhysicsData(); + // MOMENTS - // call the dataUpdated event because the only difference between the two is the updating of the indices - _this3.body.emitter.emit('_dataUpdated'); - }); + var getSetMillisecond = makeGetSet('Milliseconds', false); - // this is called when options of EXISTING nodes or edges have changed. - this.body.emitter.on('_dataUpdated', function () { - // update values - _this3._updateValueRange(_this3.body.nodes); - _this3._updateValueRange(_this3.body.edges); - // start simulation (can be called safely, even if already running) - _this3.body.emitter.emit('startSimulation'); - }); - }; + addFormatToken('z', 0, 0, 'zoneAbbr'); + addFormatToken('zz', 0, 0, 'zoneName'); - /** - * Set nodes and edges, and optionally options as well. - * - * @param {Object} data Object containing parameters: - * {Array | DataSet | DataView} [nodes] Array with nodes - * {Array | DataSet | DataView} [edges] Array with edges - * {String} [dot] String containing data in DOT format - * {String} [gephi] String containing data in gephi JSON format - * {Options} [options] Object with options - */ - Network.prototype.setData = function (data) { - // reset the physics engine. - this.body.emitter.emit('resetPhysics'); - this.body.emitter.emit('_resetData'); + // MOMENTS - // unselect all to ensure no selections from old data are carried over. - this.selectionHandler.unselectAll(); + function getZoneAbbr () { + return this._isUTC ? 'UTC' : ''; + } - if (data && data.dot && (data.nodes || data.edges)) { - throw new SyntaxError('Data must contain either parameter "dot" or ' + ' parameter pair "nodes" and "edges", but not both.'); - } + function getZoneName () { + return this._isUTC ? 'Coordinated Universal Time' : ''; + } - // set options - this.setOptions(data && data.options); - // set all data - if (data && data.dot) { - console.log('The dot property has been depricated. Please use the static convertDot method to convert DOT into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertDot(dotString);'); - // parse DOT file - var dotData = dotparser.DOTToGraph(data.dot); - this.setData(dotData); - return; - } else if (data && data.gephi) { - // parse DOT file - console.log('The gephi property has been depricated. Please use the static convertGephi method to convert gephi into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertGephi(gephiJson);'); - var gephiData = gephiParser.parseGephi(data.gephi); - this.setData(gephiData); - return; - } else { - this.nodesHandler.setData(data && data.nodes, true); - this.edgesHandler.setData(data && data.edges, true); - } + var momentPrototype__proto = Moment.prototype; - // emit change in data - this.body.emitter.emit('_dataChanged'); + momentPrototype__proto.add = add_subtract__add; + momentPrototype__proto.calendar = moment_calendar__calendar; + momentPrototype__proto.clone = clone; + momentPrototype__proto.diff = diff; + momentPrototype__proto.endOf = endOf; + momentPrototype__proto.format = format; + momentPrototype__proto.from = from; + momentPrototype__proto.fromNow = fromNow; + momentPrototype__proto.to = to; + momentPrototype__proto.toNow = toNow; + momentPrototype__proto.get = getSet; + momentPrototype__proto.invalidAt = invalidAt; + momentPrototype__proto.isAfter = isAfter; + momentPrototype__proto.isBefore = isBefore; + momentPrototype__proto.isBetween = isBetween; + momentPrototype__proto.isSame = isSame; + momentPrototype__proto.isValid = moment_valid__isValid; + momentPrototype__proto.lang = lang; + momentPrototype__proto.locale = locale; + momentPrototype__proto.localeData = localeData; + momentPrototype__proto.max = prototypeMax; + momentPrototype__proto.min = prototypeMin; + momentPrototype__proto.parsingFlags = parsingFlags; + momentPrototype__proto.set = getSet; + momentPrototype__proto.startOf = startOf; + momentPrototype__proto.subtract = add_subtract__subtract; + momentPrototype__proto.toArray = toArray; + momentPrototype__proto.toDate = toDate; + momentPrototype__proto.toISOString = moment_format__toISOString; + momentPrototype__proto.toJSON = moment_format__toISOString; + momentPrototype__proto.toString = toString; + momentPrototype__proto.unix = unix; + momentPrototype__proto.valueOf = to_type__valueOf; - // find a stable position or start animating to a stable position - this.body.emitter.emit('initPhysics'); - }; + // Year + momentPrototype__proto.year = getSetYear; + momentPrototype__proto.isLeapYear = getIsLeapYear; - /** - * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function. - * var network = new vis.Network(..); - * network.destroy(); - * network = null; - */ - Network.prototype.destroy = function () { - this.body.emitter.emit('destroy'); - // clear events - this.body.emitter.off(); - this.off(); + // Week Year + momentPrototype__proto.weekYear = getSetWeekYear; + momentPrototype__proto.isoWeekYear = getSetISOWeekYear; - // delete modules - delete this.groups; - delete this.canvas; - delete this.selectionHandler; - delete this.interactionHandler; - delete this.view; - delete this.renderer; - delete this.physics; - delete this.layoutEngine; - delete this.clustering; - delete this.manipulation; - delete this.nodesHandler; - delete this.edgesHandler; - delete this.configurator; - delete this.images; + // Quarter + momentPrototype__proto.quarter = momentPrototype__proto.quarters = getSetQuarter; - // delete emitter bindings - delete this.body.emitter.emit; - delete this.body.emitter.on; - delete this.body.emitter.off; - delete this.body.emitter.once; - delete this.body.emitter; + // Month + momentPrototype__proto.month = getSetMonth; + momentPrototype__proto.daysInMonth = getDaysInMonth; - for (var nodeId in this.body.nodes) { - delete this.body.nodes[nodeId]; - } - for (var edgeId in this.body.edges) { - delete this.body.edges[edgeId]; - } + // Week + momentPrototype__proto.week = momentPrototype__proto.weeks = getSetWeek; + momentPrototype__proto.isoWeek = momentPrototype__proto.isoWeeks = getSetISOWeek; + momentPrototype__proto.weeksInYear = getWeeksInYear; + momentPrototype__proto.isoWeeksInYear = getISOWeeksInYear; - // remove the container and everything inside it recursively - util.recursiveDOMDelete(this.body.container); - }; + // Day + momentPrototype__proto.date = getSetDayOfMonth; + momentPrototype__proto.day = momentPrototype__proto.days = getSetDayOfWeek; + momentPrototype__proto.weekday = getSetLocaleDayOfWeek; + momentPrototype__proto.isoWeekday = getSetISODayOfWeek; + momentPrototype__proto.dayOfYear = getSetDayOfYear; - /** - * Update the values of all object in the given array according to the current - * value range of the objects in the array. - * @param {Object} obj An object containing a set of Edges or Nodes - * The objects must have a method getValue() and - * setValueRange(min, max). - * @private - */ - Network.prototype._updateValueRange = function (obj) { - var id; + // Hour + momentPrototype__proto.hour = momentPrototype__proto.hours = getSetHour; - // determine the range of the objects - var valueMin = undefined; - var valueMax = undefined; - var valueTotal = 0; - for (id in obj) { - if (obj.hasOwnProperty(id)) { - var value = obj[id].getValue(); - if (value !== undefined) { - valueMin = valueMin === undefined ? value : Math.min(value, valueMin); - valueMax = valueMax === undefined ? value : Math.max(value, valueMax); - valueTotal += value; - } - } - } + // Minute + momentPrototype__proto.minute = momentPrototype__proto.minutes = getSetMinute; - // adjust the range of all objects - if (valueMin !== undefined && valueMax !== undefined) { - for (id in obj) { - if (obj.hasOwnProperty(id)) { - obj[id].setValueRange(valueMin, valueMax, valueTotal); - } - } - } - }; + // Second + momentPrototype__proto.second = momentPrototype__proto.seconds = getSetSecond; - /** - * Returns true when the Network is active. - * @returns {boolean} - */ - Network.prototype.isActive = function () { - return !this.activator || this.activator.active; - }; + // Millisecond + momentPrototype__proto.millisecond = momentPrototype__proto.milliseconds = getSetMillisecond; - Network.prototype.setSize = function () { - return this.canvas.setSize.apply(this.canvas, arguments); - }; - Network.prototype.canvasToDOM = function () { - return this.canvas.canvasToDOM.apply(this.canvas, arguments); - }; - Network.prototype.DOMtoCanvas = function () { - return this.canvas.setSize.DOMtoCanvas(this.canvas, arguments); - }; - Network.prototype.findNode = function () { - return this.clustering.findNode.apply(this.clustering, arguments); - }; - Network.prototype.isCluster = function () { - return this.clustering.isCluster.apply(this.clustering, arguments); - }; - Network.prototype.openCluster = function () { - return this.clustering.openCluster.apply(this.clustering, arguments); - }; - Network.prototype.cluster = function () { - return this.clustering.cluster.apply(this.clustering, arguments); - }; - Network.prototype.getNodesInCluster = function () { - return this.clustering.getNodesInCluster.apply(this.clustering, arguments); - }; - Network.prototype.clusterByConnection = function () { - return this.clustering.clusterByConnection.apply(this.clustering, arguments); - }; - Network.prototype.clusterByHubsize = function () { - return this.clustering.clusterByHubsize.apply(this.clustering, arguments); - }; - Network.prototype.clusterOutliers = function () { - return this.clustering.clusterOutliers.apply(this.clustering, arguments); - }; - Network.prototype.getSeed = function () { - return this.layoutEngine.getSeed.apply(this.layoutEngine, arguments); - }; - Network.prototype.enableEditMode = function () { - return this.manipulation.enableEditMode.apply(this.manipulation, arguments); - }; - Network.prototype.disableEditMode = function () { - return this.manipulation.disableEditMode.apply(this.manipulation, arguments); - }; - Network.prototype.addNodeMode = function () { - return this.manipulation.addNodeMode.apply(this.manipulation, arguments); - }; - Network.prototype.editNode = function () { - return this.manipulation.editNode.apply(this.manipulation, arguments); - }; - Network.prototype.editNodeMode = function () { - console.log('Depricated: Please use editNode instead of editNodeMode.');return this.manipulation.editNode.apply(this.manipulation, arguments); - }; - Network.prototype.addEdgeMode = function () { - return this.manipulation.addEdgeMode.apply(this.manipulation, arguments); - }; - Network.prototype.editEdgeMode = function () { - return this.manipulation.editEdgeMode.apply(this.manipulation, arguments); - }; - Network.prototype.deleteSelected = function () { - return this.manipulation.deleteSelected.apply(this.manipulation, arguments); - }; - Network.prototype.getPositions = function () { - return this.nodesHandler.getPositions.apply(this.nodesHandler, arguments); - }; - Network.prototype.storePositions = function () { - return this.nodesHandler.storePositions.apply(this.nodesHandler, arguments); - }; - Network.prototype.getBoundingBox = function () { - return this.nodesHandler.getBoundingBox.apply(this.nodesHandler, arguments); - }; - Network.prototype.getConnectedNodes = function (objectId) { - if (this.body.nodes[objectId] !== undefined) { - return this.nodesHandler.getConnectedNodes.apply(this.nodesHandler, arguments); - } else { - return this.edgesHandler.getConnectedNodes.apply(this.edgesHandler, arguments); - } - }; - Network.prototype.getConnectedEdges = function () { - return this.nodesHandler.getConnectedEdges.apply(this.nodesHandler, arguments); - }; - Network.prototype.startSimulation = function () { - return this.physics.startSimulation.apply(this.physics, arguments); - }; - Network.prototype.stopSimulation = function () { - return this.physics.stopSimulation.apply(this.physics, arguments); - }; - Network.prototype.stabilize = function () { - return this.physics.stabilize.apply(this.physics, arguments); - }; - Network.prototype.getSelection = function () { - return this.selectionHandler.getSelection.apply(this.selectionHandler, arguments); - }; - Network.prototype.getSelectedNodes = function () { - return this.selectionHandler.getSelectedNodes.apply(this.selectionHandler, arguments); - }; - Network.prototype.getSelectedEdges = function () { - return this.selectionHandler.getSelectedEdges.apply(this.selectionHandler, arguments); - }; - Network.prototype.getNodeAt = function () { - var node = this.selectionHandler.getNodeAt.apply(this.selectionHandler, arguments); - if (node !== undefined && node.id !== undefined) { - return node.id; - } - return node; - }; - Network.prototype.getEdgeAt = function () { - var edge = this.selectionHandler.getEdgeAt.apply(this.selectionHandler, arguments); - if (edge !== undefined && edge.id !== undefined) { - return edge.id; - } - return edge; - }; - Network.prototype.selectNodes = function () { - return this.selectionHandler.selectNodes.apply(this.selectionHandler, arguments); - }; - Network.prototype.selectEdges = function () { - return this.selectionHandler.selectEdges.apply(this.selectionHandler, arguments); - }; - Network.prototype.unselectAll = function () { - return this.selectionHandler.unselectAll.apply(this.selectionHandler, arguments); - }; - Network.prototype.redraw = function () { - return this.renderer.redraw.apply(this.renderer, arguments); - }; - Network.prototype.getScale = function () { - return this.view.getScale.apply(this.view, arguments); - }; - Network.prototype.getViewPosition = function () { - return this.view.getViewPosition.apply(this.view, arguments); - }; - Network.prototype.fit = function () { - return this.view.fit.apply(this.view, arguments); - }; - Network.prototype.moveTo = function () { - return this.view.moveTo.apply(this.view, arguments); - }; - Network.prototype.focus = function () { - return this.view.focus.apply(this.view, arguments); - }; - Network.prototype.releaseNode = function () { - return this.view.releaseNode.apply(this.view, arguments); - }; + // Offset + momentPrototype__proto.utcOffset = getSetOffset; + momentPrototype__proto.utc = setOffsetToUTC; + momentPrototype__proto.local = setOffsetToLocal; + momentPrototype__proto.parseZone = setOffsetToParsedOffset; + momentPrototype__proto.hasAlignedHourOffset = hasAlignedHourOffset; + momentPrototype__proto.isDST = isDaylightSavingTime; + momentPrototype__proto.isDSTShifted = isDaylightSavingTimeShifted; + momentPrototype__proto.isLocal = isLocal; + momentPrototype__proto.isUtcOffset = isUtcOffset; + momentPrototype__proto.isUtc = isUtc; + momentPrototype__proto.isUTC = isUtc; - module.exports = Network; + // Timezone + momentPrototype__proto.zoneAbbr = getZoneAbbr; + momentPrototype__proto.zoneName = getZoneName; -/***/ }, -/* 67 */ -/***/ function(module, exports, __webpack_require__) { + // Deprecations + momentPrototype__proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); + momentPrototype__proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); + momentPrototype__proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); + momentPrototype__proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779', getSetZone); - "use strict"; + var momentPrototype = momentPrototype__proto; - Object.defineProperty(exports, "__esModule", { - value: true - }); + function moment__createUnix (input) { + return local__createLocal(input * 1000); + } - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + function moment__createInZone () { + return local__createLocal.apply(null, arguments).parseZone(); + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var defaultCalendar = { + sameDay : '[Today at] LT', + nextDay : '[Tomorrow at] LT', + nextWeek : 'dddd [at] LT', + lastDay : '[Yesterday at] LT', + lastWeek : '[Last] dddd [at] LT', + sameElse : 'L' + }; - var util = __webpack_require__(2); + function locale_calendar__calendar (key, mom, now) { + var output = this._calendar[key]; + return typeof output === 'function' ? output.call(mom, now) : output; + } - /** - * @class Groups - * This class can store groups and options specific for groups. - */ + var defaultLongDateFormat = { + LTS : 'h:mm:ss A', + LT : 'h:mm A', + L : 'MM/DD/YYYY', + LL : 'MMMM D, YYYY', + LLL : 'MMMM D, YYYY LT', + LLLL : 'dddd, MMMM D, YYYY LT' + }; - var Groups = (function () { - function Groups() { - _classCallCheck(this, Groups); + function longDateFormat (key) { + var output = this._longDateFormat[key]; + if (!output && this._longDateFormat[key.toUpperCase()]) { + output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { + return val.slice(1); + }); + this._longDateFormat[key] = output; + } + return output; + } - this.clear(); - this.defaultIndex = 0; - this.groupsArray = []; - this.groupIndex = 0; + var defaultInvalidDate = 'Invalid date'; - this.defaultGroups = [{ border: "#2B7CE9", background: "#97C2FC", highlight: { border: "#2B7CE9", background: "#D2E5FF" }, hover: { border: "#2B7CE9", background: "#D2E5FF" } }, // 0: blue - { border: "#FFA500", background: "#FFFF00", highlight: { border: "#FFA500", background: "#FFFFA3" }, hover: { border: "#FFA500", background: "#FFFFA3" } }, // 1: yellow - { border: "#FA0A10", background: "#FB7E81", highlight: { border: "#FA0A10", background: "#FFAFB1" }, hover: { border: "#FA0A10", background: "#FFAFB1" } }, // 2: red - { border: "#41A906", background: "#7BE141", highlight: { border: "#41A906", background: "#A1EC76" }, hover: { border: "#41A906", background: "#A1EC76" } }, // 3: green - { border: "#E129F0", background: "#EB7DF4", highlight: { border: "#E129F0", background: "#F0B3F5" }, hover: { border: "#E129F0", background: "#F0B3F5" } }, // 4: magenta - { border: "#7C29F0", background: "#AD85E4", highlight: { border: "#7C29F0", background: "#D3BDF0" }, hover: { border: "#7C29F0", background: "#D3BDF0" } }, // 5: purple - { border: "#C37F00", background: "#FFA807", highlight: { border: "#C37F00", background: "#FFCA66" }, hover: { border: "#C37F00", background: "#FFCA66" } }, // 6: orange - { border: "#4220FB", background: "#6E6EFD", highlight: { border: "#4220FB", background: "#9B9BFD" }, hover: { border: "#4220FB", background: "#9B9BFD" } }, // 7: darkblue - { border: "#FD5A77", background: "#FFC0CB", highlight: { border: "#FD5A77", background: "#FFD1D9" }, hover: { border: "#FD5A77", background: "#FFD1D9" } }, // 8: pink - { border: "#4AD63A", background: "#C2FABC", highlight: { border: "#4AD63A", background: "#E6FFE3" }, hover: { border: "#4AD63A", background: "#E6FFE3" } }, // 9: mint + function invalidDate () { + return this._invalidDate; + } - { border: "#990000", background: "#EE0000", highlight: { border: "#BB0000", background: "#FF3333" }, hover: { border: "#BB0000", background: "#FF3333" } }, // 10:bright red + var defaultOrdinal = '%d'; + var defaultOrdinalParse = /\d{1,2}/; - { border: "#FF6000", background: "#FF6000", highlight: { border: "#FF6000", background: "#FF6000" }, hover: { border: "#FF6000", background: "#FF6000" } }, // 12: real orange - { border: "#97C2FC", background: "#2B7CE9", highlight: { border: "#D2E5FF", background: "#2B7CE9" }, hover: { border: "#D2E5FF", background: "#2B7CE9" } }, // 13: blue - { border: "#399605", background: "#255C03", highlight: { border: "#399605", background: "#255C03" }, hover: { border: "#399605", background: "#255C03" } }, // 14: green - { border: "#B70054", background: "#FF007E", highlight: { border: "#B70054", background: "#FF007E" }, hover: { border: "#B70054", background: "#FF007E" } }, // 15: magenta - { border: "#AD85E4", background: "#7C29F0", highlight: { border: "#D3BDF0", background: "#7C29F0" }, hover: { border: "#D3BDF0", background: "#7C29F0" } }, // 16: purple - { border: "#4557FA", background: "#000EA1", highlight: { border: "#6E6EFD", background: "#000EA1" }, hover: { border: "#6E6EFD", background: "#000EA1" } }, // 17: darkblue - { border: "#FFC0CB", background: "#FD5A77", highlight: { border: "#FFD1D9", background: "#FD5A77" }, hover: { border: "#FFD1D9", background: "#FD5A77" } }, // 18: pink - { border: "#C2FABC", background: "#74D66A", highlight: { border: "#E6FFE3", background: "#74D66A" }, hover: { border: "#E6FFE3", background: "#74D66A" } }, // 19: mint + function ordinal (number) { + return this._ordinal.replace('%d', number); + } - { border: "#EE0000", background: "#990000", highlight: { border: "#FF3333", background: "#BB0000" }, hover: { border: "#FF3333", background: "#BB0000" } } // 20:bright red - ]; + function preParsePostFormat (string) { + return string; + } - this.options = {}; - this.defaultOptions = { - useDefaultGroups: true + var defaultRelativeTime = { + future : 'in %s', + past : '%s ago', + s : 'a few seconds', + m : 'a minute', + mm : '%d minutes', + h : 'an hour', + hh : '%d hours', + d : 'a day', + dd : '%d days', + M : 'a month', + MM : '%d months', + y : 'a year', + yy : '%d years' }; - util.extend(this.options, this.defaultOptions); - } - _createClass(Groups, [{ - key: "setOptions", - value: function setOptions(options) { - var optionFields = ["useDefaultGroups"]; + function relative__relativeTime (number, withoutSuffix, string, isFuture) { + var output = this._relativeTime[string]; + return (typeof output === 'function') ? + output(number, withoutSuffix, string, isFuture) : + output.replace(/%d/i, number); + } - if (options !== undefined) { - for (var groupName in options) { - if (options.hasOwnProperty(groupName)) { - if (optionFields.indexOf(groupName) === -1) { - var group = options[groupName]; - this.add(groupName, group); + function pastFuture (diff, output) { + var format = this._relativeTime[diff > 0 ? 'future' : 'past']; + return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); + } + + function locale_set__set (config) { + var prop, i; + for (i in config) { + prop = config[i]; + if (typeof prop === 'function') { + this[i] = prop; + } else { + this['_' + i] = prop; } - } } - } + // Lenient ordinal parsing accepts just a number in addition to + // number + (possibly) stuff coming from _ordinalParseLenient. + this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + (/\d{1,2}/).source); } - }, { - key: "clear", - /** - * Clear all groups - */ - value: function clear() { - this.groups = {}; - this.groupsArray = []; + var prototype__proto = Locale.prototype; + + prototype__proto._calendar = defaultCalendar; + prototype__proto.calendar = locale_calendar__calendar; + prototype__proto._longDateFormat = defaultLongDateFormat; + prototype__proto.longDateFormat = longDateFormat; + prototype__proto._invalidDate = defaultInvalidDate; + prototype__proto.invalidDate = invalidDate; + prototype__proto._ordinal = defaultOrdinal; + prototype__proto.ordinal = ordinal; + prototype__proto._ordinalParse = defaultOrdinalParse; + prototype__proto.preparse = preParsePostFormat; + prototype__proto.postformat = preParsePostFormat; + prototype__proto._relativeTime = defaultRelativeTime; + prototype__proto.relativeTime = relative__relativeTime; + prototype__proto.pastFuture = pastFuture; + prototype__proto.set = locale_set__set; + + // Month + prototype__proto.months = localeMonths; + prototype__proto._months = defaultLocaleMonths; + prototype__proto.monthsShort = localeMonthsShort; + prototype__proto._monthsShort = defaultLocaleMonthsShort; + prototype__proto.monthsParse = localeMonthsParse; + + // Week + prototype__proto.week = localeWeek; + prototype__proto._week = defaultLocaleWeek; + prototype__proto.firstDayOfYear = localeFirstDayOfYear; + prototype__proto.firstDayOfWeek = localeFirstDayOfWeek; + + // Day of Week + prototype__proto.weekdays = localeWeekdays; + prototype__proto._weekdays = defaultLocaleWeekdays; + prototype__proto.weekdaysMin = localeWeekdaysMin; + prototype__proto._weekdaysMin = defaultLocaleWeekdaysMin; + prototype__proto.weekdaysShort = localeWeekdaysShort; + prototype__proto._weekdaysShort = defaultLocaleWeekdaysShort; + prototype__proto.weekdaysParse = localeWeekdaysParse; + + // Hours + prototype__proto.isPM = localeIsPM; + prototype__proto._meridiemParse = defaultLocaleMeridiemParse; + prototype__proto.meridiem = localeMeridiem; + + function lists__get (format, index, field, setter) { + var locale = locale_locales__getLocale(); + var utc = create_utc__createUTC().set(setter, index); + return locale[field](utc, format); } - }, { - key: "get", - /** - * get group options of a groupname. If groupname is not found, a new group - * is added. - * @param {*} groupname Can be a number, string, Date, etc. - * @return {Object} group The created group, containing all group options - */ - value: function get(groupname) { - var group = this.groups[groupname]; - if (group === undefined) { - if (this.options.useDefaultGroups === false && this.groupsArray.length > 0) { - // create new group - var index = this.groupIndex % this.groupsArray.length; - this.groupIndex++; - group = {}; - group.color = this.groups[this.groupsArray[index]]; - this.groups[groupname] = group; - } else { - // create new group - var index = this.defaultIndex % this.defaultGroups.length; - this.defaultIndex++; - group = {}; - group.color = this.defaultGroups[index]; - this.groups[groupname] = group; + function list (format, index, field, count, setter) { + if (typeof format === 'number') { + index = format; + format = undefined; + } + + format = format || ''; + + if (index != null) { + return lists__get(format, index, field, setter); + } + + var i; + var out = []; + for (i = 0; i < count; i++) { + out[i] = lists__get(format, i, field, setter); } - } - - return group; + return out; } - }, { - key: "add", - /** - * Add a custom group style - * @param {String} groupName - * @param {Object} style An object containing borderColor, - * backgroundColor, etc. - * @return {Object} group The created group object - */ - value: function add(groupName, style) { - this.groups[groupName] = style; - this.groupsArray.push(groupName); - return style; + function lists__listMonths (format, index) { + return list(format, index, 'months', 12, 'month'); } - }]); - return Groups; - })(); + function lists__listMonthsShort (format, index) { + return list(format, index, 'monthsShort', 12, 'month'); + } - exports["default"] = Groups; - module.exports = exports["default"]; + function lists__listWeekdays (format, index) { + return list(format, index, 'weekdays', 7, 'day'); + } -/***/ }, -/* 68 */ -/***/ function(module, exports, __webpack_require__) { + function lists__listWeekdaysShort (format, index) { + return list(format, index, 'weekdaysShort', 7, 'day'); + } - 'use strict'; + function lists__listWeekdaysMin (format, index) { + return list(format, index, 'weekdaysMin', 7, 'day'); + } - Object.defineProperty(exports, '__esModule', { - value: true - }); + locale_locales__getSetGlobalLocale('en', { + ordinalParse: /\d{1,2}(th|st|nd|rd)/, + ordinal : function (number) { + var b = number % 10, + output = (toInt(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; + } + }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // Side effect imports + utils_hooks__hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', locale_locales__getSetGlobalLocale); + utils_hooks__hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', locale_locales__getLocale); - function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _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; } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } } + var mathAbs = Math.abs; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + function duration_abs__abs () { + var data = this._data; - var util = __webpack_require__(2); + this._milliseconds = mathAbs(this._milliseconds); + this._days = mathAbs(this._days); + this._months = mathAbs(this._months); - var Label = (function () { - function Label(body, options) { - _classCallCheck(this, Label); + data.milliseconds = mathAbs(data.milliseconds); + data.seconds = mathAbs(data.seconds); + data.minutes = mathAbs(data.minutes); + data.hours = mathAbs(data.hours); + data.months = mathAbs(data.months); + data.years = mathAbs(data.years); - this.body = body; + return this; + } - this.baseSize = undefined; - this.setOptions(options); - this.size = { top: 0, left: 0, width: 0, height: 0, yLine: 0 }; // could be cached - } + function duration_add_subtract__addSubtract (duration, input, value, direction) { + var other = create__createDuration(input, value); - _createClass(Label, [{ - key: 'setOptions', - value: function setOptions(options) { - var allowDeletion = arguments[1] === undefined ? false : arguments[1]; + duration._milliseconds += direction * other._milliseconds; + duration._days += direction * other._days; + duration._months += direction * other._months; - this.options = options; + return duration._bubble(); + } - if (options.label !== undefined) { - this.labelDirty = true; - } + // supports only 2.0-style add(1, 's') or add(duration) + function duration_add_subtract__add (input, value) { + return duration_add_subtract__addSubtract(this, input, value, 1); + } - if (options.font !== undefined) { - Label.parseOptions(this.options.font, options, allowDeletion); - if (typeof options.font === 'string') { - this.baseSize = this.options.font.size; - } else if (typeof options.font === 'object') { - if (options.font.size !== undefined) { - this.baseSize = options.font.size; - } - } - } + // supports only 2.0-style subtract(1, 's') or subtract(duration) + function duration_add_subtract__subtract (input, value) { + return duration_add_subtract__addSubtract(this, input, value, -1); } - }, { - key: 'draw', - /** - * Main function. This is called from anything that wants to draw a label. - * @param ctx - * @param x - * @param y - * @param selected - * @param baseline - */ - value: function draw(ctx, x, y, selected) { - var baseline = arguments[4] === undefined ? 'middle' : arguments[4]; + function bubble () { + var milliseconds = this._milliseconds; + var days = this._days; + var months = this._months; + var data = this._data; + var seconds, minutes, hours, years = 0; - // if no label, return - if (this.options.label === undefined) return; + // The following code bubbles up values, see the tests for + // examples of what that means. + data.milliseconds = milliseconds % 1000; - // check if we have to render the label - var viewFontSize = this.options.font.size * this.body.view.scale; - if (this.options.label && viewFontSize < this.options.scaling.label.drawThreshold - 1) return; + seconds = absFloor(milliseconds / 1000); + data.seconds = seconds % 60; - // update the size cache if required - this.calculateLabelSize(ctx, selected, x, y, baseline); + minutes = absFloor(seconds / 60); + data.minutes = minutes % 60; - // create the fontfill background - this._drawBackground(ctx); - // draw text - this._drawText(ctx, selected, x, y, baseline); + hours = absFloor(minutes / 60); + data.hours = hours % 24; + + days += absFloor(hours / 24); + + // Accurately convert days to years, assume start from year 0. + years = absFloor(daysToYears(days)); + days -= absFloor(yearsToDays(years)); + + // 30 days to a month + // TODO (iskren): Use anchor date (like 1st Jan) to compute this. + months += absFloor(days / 30); + days %= 30; + + // 12 months -> 1 year + years += absFloor(months / 12); + months %= 12; + + data.days = days; + data.months = months; + data.years = years; + + return this; } - }, { - key: '_drawBackground', - /** - * Draws the label background - * @param {CanvasRenderingContext2D} ctx - * @private - */ - value: function _drawBackground(ctx) { - if (this.options.font.background !== undefined && this.options.font.background !== 'none') { - ctx.fillStyle = this.options.font.background; + function daysToYears (days) { + // 400 years have 146097 days (taking into account leap year rules) + return days * 400 / 146097; + } - var lineMargin = 2; + function yearsToDays (years) { + // years * 365 + absFloor(years / 4) - + // absFloor(years / 100) + absFloor(years / 400); + return years * 146097 / 400; + } - switch (this.options.font.align) { - case 'middle': - ctx.fillRect(-this.size.width * 0.5, -this.size.height * 0.5, this.size.width, this.size.height); - break; - case 'top': - ctx.fillRect(-this.size.width * 0.5, -(this.size.height + lineMargin), this.size.width, this.size.height); - break; - case 'bottom': - ctx.fillRect(-this.size.width * 0.5, lineMargin, this.size.width, this.size.height); - break; - default: - ctx.fillRect(this.size.left, this.size.top - 0.5 * lineMargin, this.size.width, this.size.height); - break; + function as (units) { + var days; + var months; + var milliseconds = this._milliseconds; + + units = normalizeUnits(units); + + if (units === 'month' || units === 'year') { + days = this._days + milliseconds / 864e5; + months = this._months + daysToYears(days) * 12; + return units === 'month' ? months : months / 12; + } else { + // handle milliseconds separately because of floating point math errors (issue #1867) + days = this._days + Math.round(yearsToDays(this._months / 12)); + switch (units) { + case 'week' : return days / 7 + milliseconds / 6048e5; + case 'day' : return days + milliseconds / 864e5; + case 'hour' : return days * 24 + milliseconds / 36e5; + case 'minute' : return days * 1440 + milliseconds / 6e4; + case 'second' : return days * 86400 + milliseconds / 1000; + // Math.floor prevents floating point math errors here + case 'millisecond': return Math.floor(days * 864e5) + milliseconds; + default: throw new Error('Unknown unit ' + units); + } } - } } - }, { - key: '_drawText', - /** - * - * @param ctx - * @param x - * @param baseline - * @private - */ - value: function _drawText(ctx, selected, x, y) { - var baseline = arguments[4] === undefined ? 'middle' : arguments[4]; + // TODO: Use this.as('ms')? + function duration_as__valueOf () { + return ( + this._milliseconds + + this._days * 864e5 + + (this._months % 12) * 2592e6 + + toInt(this._months / 12) * 31536e6 + ); + } - var fontSize = this.options.font.size; - var viewFontSize = fontSize * this.body.view.scale; - // this ensures that there will not be HUGE letters on screen by setting an upper limit on the visible text size (regardless of zoomLevel) - if (viewFontSize >= this.options.scaling.label.maxVisible) { - fontSize = Number(this.options.scaling.label.maxVisible) / this.body.view.scale; - } + function makeAs (alias) { + return function () { + return this.as(alias); + }; + } - var yLine = this.size.yLine; + var asMilliseconds = makeAs('ms'); + var asSeconds = makeAs('s'); + var asMinutes = makeAs('m'); + var asHours = makeAs('h'); + var asDays = makeAs('d'); + var asWeeks = makeAs('w'); + var asMonths = makeAs('M'); + var asYears = makeAs('y'); - var _getColor = this._getColor(viewFontSize); + function duration_get__get (units) { + units = normalizeUnits(units); + return this[units + 's'](); + } - var _getColor2 = _slicedToArray(_getColor, 2); + function makeGetter(name) { + return function () { + return this._data[name]; + }; + } - var fontColor = _getColor2[0]; - var strokeColor = _getColor2[1]; + var duration_get__milliseconds = makeGetter('milliseconds'); + var seconds = makeGetter('seconds'); + var minutes = makeGetter('minutes'); + var hours = makeGetter('hours'); + var days = makeGetter('days'); + var months = makeGetter('months'); + var years = makeGetter('years'); - var _setAlignment = this._setAlignment(ctx, x, yLine, baseline); + function weeks () { + return absFloor(this.days() / 7); + } - var _setAlignment2 = _slicedToArray(_setAlignment, 2); + var round = Math.round; + var thresholds = { + s: 45, // seconds to minute + m: 45, // minutes to hour + h: 22, // hours to day + d: 26, // days to month + M: 11 // months to year + }; - x = _setAlignment2[0]; - yLine = _setAlignment2[1]; + // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize + function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { + return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); + } - // configure context for drawing the text - ctx.font = (selected ? 'bold ' : '') + fontSize + 'px ' + this.options.font.face; - ctx.fillStyle = fontColor; - ctx.textAlign = 'center'; + function duration_humanize__relativeTime (posNegDuration, withoutSuffix, locale) { + var duration = create__createDuration(posNegDuration).abs(); + var seconds = round(duration.as('s')); + var minutes = round(duration.as('m')); + var hours = round(duration.as('h')); + var days = round(duration.as('d')); + var months = round(duration.as('M')); + var years = round(duration.as('y')); - // set the strokeWidth - if (this.options.font.strokeWidth > 0) { - ctx.lineWidth = this.options.font.strokeWidth; - ctx.strokeStyle = strokeColor; - ctx.lineJoin = 'round'; - } + var a = seconds < thresholds.s && ['s', seconds] || + minutes === 1 && ['m'] || + minutes < thresholds.m && ['mm', minutes] || + hours === 1 && ['h'] || + hours < thresholds.h && ['hh', hours] || + days === 1 && ['d'] || + days < thresholds.d && ['dd', days] || + months === 1 && ['M'] || + months < thresholds.M && ['MM', months] || + years === 1 && ['y'] || ['yy', years]; - // draw the text - for (var i = 0; i < this.lineCount; i++) { - if (this.options.font.strokeWidth > 0) { - ctx.strokeText(this.lines[i], x, yLine); + a[2] = withoutSuffix; + a[3] = +posNegDuration > 0; + a[4] = locale; + return substituteTimeAgo.apply(null, a); + } + + // This function allows you to set a threshold for relative time strings + function duration_humanize__getSetRelativeTimeThreshold (threshold, limit) { + if (thresholds[threshold] === undefined) { + return false; } - ctx.fillText(this.lines[i], x, yLine); - yLine += fontSize; - } + if (limit === undefined) { + return thresholds[threshold]; + } + thresholds[threshold] = limit; + return true; } - }, { - key: '_setAlignment', - value: function _setAlignment(ctx, x, yLine, baseline) { - // check for label alignment (for edges) - // TODO: make alignment for nodes - if (this.options.font.align !== 'horizontal') { - x = 0; - yLine = 0; - var lineMargin = 2; - if (this.options.font.align === 'top') { - ctx.textBaseline = 'alphabetic'; - yLine -= 2 * lineMargin; // distance from edge, required because we use alphabetic. Alphabetic has less difference between browsers - } else if (this.options.font.align === 'bottom') { - ctx.textBaseline = 'hanging'; - yLine += 2 * lineMargin; // distance from edge, required because we use hanging. Hanging has less difference between browsers - } else { - ctx.textBaseline = 'middle'; + function humanize (withSuffix) { + var locale = this.localeData(); + var output = duration_humanize__relativeTime(this, !withSuffix, locale); + + if (withSuffix) { + output = locale.pastFuture(+this, output); } - } else { - ctx.textBaseline = baseline; - } - return [x, yLine]; + return locale.postformat(output); } - }, { - key: '_getColor', - /** - * fade in when relative scale is between threshold and threshold - 1. - * If the relative scale would be smaller than threshold -1 the draw function would have returned before coming here. - * - * @param viewFontSize - * @returns {*[]} - * @private - */ - value: function _getColor(viewFontSize) { - var fontColor = this.options.font.color || '#000000'; - var strokeColor = this.options.font.strokeColor || '#ffffff'; - if (viewFontSize <= this.options.scaling.label.drawThreshold) { - var opacity = Math.max(0, Math.min(1, 1 - (this.options.scaling.label.drawThreshold - viewFontSize))); - fontColor = util.overrideOpacity(fontColor, opacity); - strokeColor = util.overrideOpacity(strokeColor, opacity); - } - return [fontColor, strokeColor]; - } - }, { - key: 'getTextSize', + var iso_string__abs = Math.abs; - /** - * - * @param ctx - * @param selected - * @returns {{width: number, height: number}} - */ - value: function getTextSize(ctx) { - var selected = arguments[1] === undefined ? false : arguments[1]; + function iso_string__toISOString() { + // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js + var Y = iso_string__abs(this.years()); + var M = iso_string__abs(this.months()); + var D = iso_string__abs(this.days()); + var h = iso_string__abs(this.hours()); + var m = iso_string__abs(this.minutes()); + var s = iso_string__abs(this.seconds() + this.milliseconds() / 1000); + var total = this.asSeconds(); - var size = { - width: this._processLabel(ctx, selected), - height: this.options.font.size * this.lineCount, - lineCount: this.lineCount - }; - return size; + if (!total) { + // this is the same as C#'s (Noda) and python (isodate)... + // but not other JS (goog.date) + return 'P0D'; + } + + return (total < 0 ? '-' : '') + + 'P' + + (Y ? Y + 'Y' : '') + + (M ? M + 'M' : '') + + (D ? D + 'D' : '') + + ((h || m || s) ? 'T' : '') + + (h ? h + 'H' : '') + + (m ? m + 'M' : '') + + (s ? s + 'S' : ''); } - }, { - key: 'calculateLabelSize', - /** - * - * @param ctx - * @param selected - * @param x - * @param y - * @param baseline - */ - value: function calculateLabelSize(ctx, selected) { - var x = arguments[2] === undefined ? 0 : arguments[2]; - var y = arguments[3] === undefined ? 0 : arguments[3]; - var baseline = arguments[4] === undefined ? 'middle' : arguments[4]; + var duration_prototype__proto = Duration.prototype; + + duration_prototype__proto.abs = duration_abs__abs; + duration_prototype__proto.add = duration_add_subtract__add; + duration_prototype__proto.subtract = duration_add_subtract__subtract; + duration_prototype__proto.as = as; + duration_prototype__proto.asMilliseconds = asMilliseconds; + duration_prototype__proto.asSeconds = asSeconds; + duration_prototype__proto.asMinutes = asMinutes; + duration_prototype__proto.asHours = asHours; + duration_prototype__proto.asDays = asDays; + duration_prototype__proto.asWeeks = asWeeks; + duration_prototype__proto.asMonths = asMonths; + duration_prototype__proto.asYears = asYears; + duration_prototype__proto.valueOf = duration_as__valueOf; + duration_prototype__proto._bubble = bubble; + duration_prototype__proto.get = duration_get__get; + duration_prototype__proto.milliseconds = duration_get__milliseconds; + duration_prototype__proto.seconds = seconds; + duration_prototype__proto.minutes = minutes; + duration_prototype__proto.hours = hours; + duration_prototype__proto.days = days; + duration_prototype__proto.weeks = weeks; + duration_prototype__proto.months = months; + duration_prototype__proto.years = years; + duration_prototype__proto.humanize = humanize; + duration_prototype__proto.toISOString = iso_string__toISOString; + duration_prototype__proto.toString = iso_string__toISOString; + duration_prototype__proto.toJSON = iso_string__toISOString; + duration_prototype__proto.locale = locale; + duration_prototype__proto.localeData = localeData; + + // Deprecations + duration_prototype__proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', iso_string__toISOString); + duration_prototype__proto.lang = lang; + + // Side effect imports + + addFormatToken('X', 0, 0, 'unix'); + addFormatToken('x', 0, 0, 'valueOf'); + + // PARSING + + addRegexToken('x', matchSigned); + addRegexToken('X', matchTimestamp); + addParseToken('X', function (input, array, config) { + config._d = new Date(parseFloat(input, 10) * 1000); + }); + addParseToken('x', function (input, array, config) { + config._d = new Date(toInt(input)); + }); - if (this.labelDirty === true) { - this.size.width = this._processLabel(ctx, selected); - } - this.size.height = this.options.font.size * this.lineCount; - this.size.left = x - this.size.width * 0.5; - this.size.top = y - this.size.height * 0.5; - this.size.yLine = y + (1 - this.lineCount) * 0.5 * this.options.font.size; - if (baseline === 'hanging') { - this.size.top += 0.5 * this.options.font.size; - this.size.top += 4; // distance from node, required because we use hanging. Hanging has less difference between browsers - this.size.yLine += 4; // distance from node - } + // Side effect imports - this.labelDirty = false; - } - }, { - key: '_processLabel', - /** - * This calculates the width as well as explodes the label string and calculates the amount of lines. - * @param ctx - * @param selected - * @returns {number} - * @private - */ - value: function _processLabel(ctx, selected) { - var width = 0; - var lines = ['']; - var lineCount = 0; - if (this.options.label !== undefined) { - lines = String(this.options.label).split('\n'); - lineCount = lines.length; - ctx.font = (selected ? 'bold ' : '') + this.options.font.size + 'px ' + this.options.font.face; - width = ctx.measureText(lines[0]).width; - for (var i = 1; i < lineCount; i++) { - var lineWidth = ctx.measureText(lines[i]).width; - width = lineWidth > width ? lineWidth : width; - } - } - this.lines = lines; - this.lineCount = lineCount; + utils_hooks__hooks.version = '2.10.3'; - return width; - } - }], [{ - key: 'parseOptions', - value: function parseOptions(parentOptions, newOptions) { - var allowDeletion = arguments[2] === undefined ? false : arguments[2]; + setHookCallback(local__createLocal); - if (typeof newOptions.font === 'string') { - var newOptionsArray = newOptions.font.split(' '); - parentOptions.size = newOptionsArray[0].replace('px', ''); - parentOptions.face = newOptionsArray[1]; - parentOptions.color = newOptionsArray[2]; - } else if (typeof newOptions.font === 'object') { - util.fillIfDefined(parentOptions, newOptions.font, allowDeletion); - } - parentOptions.size = Number(parentOptions.size); - } - }]); + utils_hooks__hooks.fn = momentPrototype; + utils_hooks__hooks.min = min; + utils_hooks__hooks.max = max; + utils_hooks__hooks.utc = create_utc__createUTC; + utils_hooks__hooks.unix = moment__createUnix; + utils_hooks__hooks.months = lists__listMonths; + utils_hooks__hooks.isDate = isDate; + utils_hooks__hooks.locale = locale_locales__getSetGlobalLocale; + utils_hooks__hooks.invalid = valid__createInvalid; + utils_hooks__hooks.duration = create__createDuration; + utils_hooks__hooks.isMoment = isMoment; + utils_hooks__hooks.weekdays = lists__listWeekdays; + utils_hooks__hooks.parseZone = moment__createInZone; + utils_hooks__hooks.localeData = locale_locales__getLocale; + utils_hooks__hooks.isDuration = isDuration; + utils_hooks__hooks.monthsShort = lists__listMonthsShort; + utils_hooks__hooks.weekdaysMin = lists__listWeekdaysMin; + utils_hooks__hooks.defineLocale = defineLocale; + utils_hooks__hooks.weekdaysShort = lists__listWeekdaysShort; + utils_hooks__hooks.normalizeUnits = normalizeUnits; + utils_hooks__hooks.relativeTimeThreshold = duration_humanize__getSetRelativeTimeThreshold; - return Label; - })(); + var _moment = utils_hooks__hooks; - exports['default'] = Label; - module.exports = exports['default']; + return _moment; + + })); + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(90)(module))) /***/ }, -/* 69 */ +/* 71 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; + var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); + (function (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) + window.propagating = factory(); + } + }(function () { + var _firstTarget = null; // singleton, will contain the target element where the touch event started + var _processing = false; // singleton, true when a touch event is being handled - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + /** + * Extend an Hammer.js instance with event propagation. + * + * Features: + * - Events emitted by hammer will propagate in order from child to parent + * elements. + * - Events are extended with a function `event.stopPropagation()` to stop + * propagation to parent elements. + * - An option `preventDefault` to stop all default browser behavior. + * + * Usage: + * var hammer = propagatingHammer(new Hammer(element)); + * var hammer = propagatingHammer(new Hammer(element), {preventDefault: true}); + * + * @param {Hammer.Manager} hammer An hammer instance. + * @param {Object} [options] Available options: + * - `preventDefault: true | 'mouse' | 'touch' | 'pen'`. + * Enforce preventing the default browser behavior. + * Cannot be set to `false`. + * @return {Hammer.Manager} Returns the same hammer instance with extended + * functionality + */ + return function propagating(hammer, options) { + if (options && options.preventDefault === false) { + throw new Error('Only supports preventDefault == true'); + } + var _options = options || { + preventDefault: false + }; - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + if (hammer.Manager) { + // This looks like the Hammer constructor. + // Overload the constructors with our own. + var Hammer = hammer; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var PropagatingHammer = function(element, options) { + return propagating(new Hammer(element, options), _options); + }; + Hammer.extend(PropagatingHammer, Hammer); + PropagatingHammer.Manager = function (element, options) { + return propagating(new Hammer.Manager(element, options), _options); + }; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + return PropagatingHammer; + } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + // attach to DOM element + var element = hammer.element; + element.hammer = hammer; - var _utilNodeBase = __webpack_require__(70); + // move the original functions that we will wrap + hammer._on = hammer.on; + hammer._off = hammer.off; + hammer._emit = hammer.emit; + hammer._destroy = hammer.destroy; - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + /** @type {Object.>} */ + hammer._handlers = {}; - var Box = (function (_NodeBase) { - function Box(options, body, labelModule) { - _classCallCheck(this, Box); + // register an event to catch the start of a gesture and store the + // target in a singleton + hammer._on('hammer.input', function (event) { + if (_options.preventDefault === true || (_options.preventDefault === event.pointerType)) { + event.preventDefault(); + } + if (event.isFirst) { + _firstTarget = event.target; + _processing = true; + } + if (event.isFinal) { + _processing = false; + } + }); - _get(Object.getPrototypeOf(Box.prototype), 'constructor', this).call(this, options, body, labelModule); - } + /** + * Register a handler for one or multiple events + * @param {String} events A space separated string with events + * @param {function} handler A callback function, called as handler(event) + * @returns {Hammer.Manager} Returns the hammer instance + */ + hammer.on = function (events, handler) { + // register the handler + split(events).forEach(function (event) { + var _handlers = hammer._handlers[event]; + if (!_handlers) { + hammer._handlers[event] = _handlers = []; - _inherits(Box, _NodeBase); + // register the static, propagated handler + hammer._on(event, propagatedHandler); + } + _handlers.push(handler); + }); - _createClass(Box, [{ - key: 'resize', - value: function resize(ctx, selected) { - if (this.width === undefined) { - var margin = 5; - var textSize = this.labelModule.getTextSize(ctx, selected); - this.width = textSize.width + 2 * margin; - this.height = textSize.height + 2 * margin; - this.radius = 0.5 * this.width; - } - } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(ctx, selected); - this.left = x - this.width / 2; - this.top = y - this.height / 2; + return hammer; + }; - var borderWidth = this.options.borderWidth; - var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; + /** + * Unregister a handler for one or multiple events + * @param {String} events A space separated string with events + * @param {function} [handler] Optional. The registered handler. If not + * provided, all handlers for given events + * are removed. + * @returns {Hammer.Manager} Returns the hammer instance + */ + hammer.off = function (events, handler) { + // unregister the handler + split(events).forEach(function (event) { + var _handlers = hammer._handlers[event]; + if (_handlers) { + _handlers = handler ? _handlers.filter(function (h) { + return h !== handler; + }) : []; - ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; - ctx.lineWidth = selected ? selectionLineWidth : borderWidth; - ctx.lineWidth /= this.body.view.scale; - ctx.lineWidth = Math.min(this.width, ctx.lineWidth); + if (_handlers.length > 0) { + hammer._handlers[event] = _handlers; + } + else { + // remove static, propagated handler + hammer._off(event, propagatedHandler); + delete hammer._handlers[event]; + } + } + }); - ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; + return hammer; + }; - var borderRadius = 6; - ctx.roundRect(this.left, this.top, this.width, this.height, borderRadius); + /** + * Emit to the event listeners + * @param {string} eventType + * @param {Event} event + */ + hammer.emit = function(eventType, event) { + if (!_processing) { + _firstTarget = event.target; + } + hammer._emit(eventType, event); + }; - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); + hammer.destroy = function () { + // Detach from DOM element + var element = hammer.element; + delete element.hammer; - // disable shadows for other elements. - this.disableShadow(ctx); + // clear all handlers + hammer._handlers = {}; - ctx.stroke(); + // call original hammer destroy + hammer._destroy(); + }; - this.updateBoundingBox(x, y); - this.labelModule.draw(ctx, x, y, selected); + // split a string with space separated words + function split(events) { + return events.match(/[^ ]+/g); } - }, { - key: 'updateBoundingBox', - value: function updateBoundingBox(x, y) { - this.left = x - this.width * 0.5; - this.top = y - this.height * 0.5; - this.boundingBox.left = this.left; - this.boundingBox.top = this.top; - this.boundingBox.bottom = this.top + this.height; - this.boundingBox.right = this.left + this.width; - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - var a = this.width / 2; - var b = this.height / 2; - var w = Math.sin(angle) * a; - var h = Math.cos(angle) * b; - return a * b / Math.sqrt(w * w + h * h); + /** + * A static event handler, applying event propagation. + * @param {Object} event + */ + function propagatedHandler(event) { + // let only a single hammer instance handle this event + if (event.type !== 'hammer.input') { + // it is possible that the same srcEvent is used with multiple hammer events, + // we keep track on which events are handled in an object _handled + if (!event.srcEvent._handled) { + event.srcEvent._handled = {}; + } + + if (event.srcEvent._handled[event.type]) { + return; + } + else { + event.srcEvent._handled[event.type] = true; + } + } + + // attach a stopPropagation function to the event + var stopped = false; + event.stopPropagation = function () { + stopped = true; + }; + + // attach firstTarget property to the event + event.firstTarget = _firstTarget; + + // propagate over all elements (until stopped) + var elem = _firstTarget; + while (elem && !stopped) { + var _handlers = elem.hammer && elem.hammer._handlers[event.type]; + if (_handlers) { + for (var i = 0; i < _handlers.length && !stopped; i++) { + _handlers[i](event); + } + } + + elem = elem.parentNode; + } } - }]); - return Box; - })(_utilNodeBase2['default']); + return hammer; + }; + })); - exports['default'] = Box; - module.exports = exports['default']; /***/ }, -/* 70 */ +/* 72 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); + var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v2.0.4 - 2014-09-28 + * http://hammerjs.github.io/ + * + * Copyright (c) 2014 Jorik Tangelder; + * Licensed under the MIT license */ + (function(window, document, exportName, undefined) { + 'use strict'; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var VENDOR_PREFIXES = ['', 'webkit', 'moz', 'MS', 'ms', 'o']; + var TEST_ELEMENT = document.createElement('div'); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + var TYPE_FUNCTION = 'function'; - var NodeBase = (function () { - function NodeBase(options, body, labelModule) { - _classCallCheck(this, NodeBase); + var round = Math.round; + var abs = Math.abs; + var now = Date.now; - 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.boundingBox = { top: 0, left: 0, right: 0, bottom: 0 }; - } + /** + * set a timeout with a given scope + * @param {Function} fn + * @param {Number} timeout + * @param {Object} context + * @returns {number} + */ + function setTimeoutContext(fn, timeout, context) { + return setTimeout(bindFn(fn, context), timeout); + } - _createClass(NodeBase, [{ - key: 'setOptions', - value: function setOptions(options) { - this.options = options; - } - }, { - key: '_distanceToBorder', - value: function _distanceToBorder(angle) { - var borderWidth = 1; - return Math.min(Math.abs(this.width / 2 / Math.cos(angle)), Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth; - } - }, { - key: 'enableShadow', - value: function enableShadow(ctx) { - if (this.options.shadow.enabled === true) { - ctx.shadowColor = 'rgba(0,0,0,0.5)'; - ctx.shadowBlur = this.options.shadow.size; - ctx.shadowOffsetX = this.options.shadow.x; - ctx.shadowOffsetY = this.options.shadow.y; - } - } - }, { - key: 'disableShadow', - value: function disableShadow(ctx) { - if (this.options.shadow.enabled === true) { - ctx.shadowColor = 'rgba(0,0,0,0)'; - ctx.shadowBlur = 0; - ctx.shadowOffsetX = 0; - ctx.shadowOffsetY = 0; - } + /** + * if the argument is an array, we want to execute the fn on each entry + * if it aint an array we don't want to do a thing. + * this is used by all the methods that accept a single and array argument. + * @param {*|Array} arg + * @param {String} fn + * @param {Object} [context] + * @returns {Boolean} + */ + function invokeArrayArg(arg, fn, context) { + if (Array.isArray(arg)) { + each(arg, context[fn], context); + return true; } - }]); - - return NodeBase; - })(); + return false; + } - exports['default'] = NodeBase; - module.exports = exports['default']; + /** + * walk objects and arrays + * @param {Object} obj + * @param {Function} iterator + * @param {Object} context + */ + function each(obj, iterator, context) { + var i; -/***/ }, -/* 71 */ -/***/ function(module, exports, __webpack_require__) { + if (!obj) { + return; + } - 'use strict'; + if (obj.forEach) { + obj.forEach(iterator, context); + } else if (obj.length !== undefined) { + i = 0; + while (i < obj.length) { + iterator.call(context, obj[i], i, obj); + i++; + } + } else { + for (i in obj) { + obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj); + } + } + } - Object.defineProperty(exports, '__esModule', { - value: true - }); + /** + * extend object. + * means that properties in dest will be overwritten by the ones in src. + * @param {Object} dest + * @param {Object} src + * @param {Boolean} [merge] + * @returns {Object} dest + */ + function extend(dest, src, merge) { + var keys = Object.keys(src); + var i = 0; + while (i < keys.length) { + if (!merge || (merge && dest[keys[i]] === undefined)) { + dest[keys[i]] = src[keys[i]]; + } + i++; + } + return dest; + } - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + /** + * merge the values from src in the dest. + * means that properties that exist in dest will not be overwritten by src + * @param {Object} dest + * @param {Object} src + * @returns {Object} dest + */ + function merge(dest, src) { + return extend(dest, src, true); + } - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + /** + * simple class inheritance + * @param {Function} child + * @param {Function} base + * @param {Object} [properties] + */ + function inherit(child, base, properties) { + var baseP = base.prototype, + childP; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + childP = child.prototype = Object.create(baseP); + childP.constructor = child; + childP._super = baseP; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + if (properties) { + extend(childP, properties); + } + } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + /** + * simple function bind + * @param {Function} fn + * @param {Object} context + * @returns {Function} + */ + function bindFn(fn, context) { + return function boundFn() { + return fn.apply(context, arguments); + }; + } - var _utilCircleImageBase = __webpack_require__(72); + /** + * let a boolean value also be a function that must return a boolean + * this first item in args will be used as the context + * @param {Boolean|Function} val + * @param {Array} [args] + * @returns {Boolean} + */ + function boolOrFn(val, args) { + if (typeof val == TYPE_FUNCTION) { + return val.apply(args ? args[0] || undefined : undefined, args); + } + return val; + } - var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); + /** + * use the val2 when val1 is undefined + * @param {*} val1 + * @param {*} val2 + * @returns {*} + */ + function ifUndefined(val1, val2) { + return (val1 === undefined) ? val2 : val1; + } - var Circle = (function (_CircleImageBase) { - function Circle(options, body, labelModule) { - _classCallCheck(this, Circle); + /** + * addEventListener with multiple events at once + * @param {EventTarget} target + * @param {String} types + * @param {Function} handler + */ + function addEventListeners(target, types, handler) { + each(splitStr(types), function(type) { + target.addEventListener(type, handler, false); + }); + } - _get(Object.getPrototypeOf(Circle.prototype), 'constructor', this).call(this, options, body, labelModule); - } + /** + * removeEventListener with multiple events at once + * @param {EventTarget} target + * @param {String} types + * @param {Function} handler + */ + function removeEventListeners(target, types, handler) { + each(splitStr(types), function(type) { + target.removeEventListener(type, handler, false); + }); + } - _inherits(Circle, _CircleImageBase); + /** + * find if a node is in the given parent + * @method hasParent + * @param {HTMLElement} node + * @param {HTMLElement} parent + * @return {Boolean} found + */ + function hasParent(node, parent) { + while (node) { + if (node == parent) { + return true; + } + node = node.parentNode; + } + return false; + } - _createClass(Circle, [{ - key: 'resize', - value: function resize(ctx, selected) { - if (this.width === undefined) { - var margin = 5; - var textSize = this.labelModule.getTextSize(ctx, selected); - var diameter = Math.max(textSize.width, textSize.height) + 2 * margin; - this.options.size = diameter / 2; + /** + * small indexOf wrapper + * @param {String} str + * @param {String} find + * @returns {Boolean} found + */ + function inStr(str, find) { + return str.indexOf(find) > -1; + } - this.width = diameter; - this.height = diameter; - this.radius = 0.5 * this.width; - } + /** + * split string on whitespace + * @param {String} str + * @returns {Array} words + */ + function splitStr(str) { + return str.trim().split(/\s+/g); + } + + /** + * find if a array contains the object using indexOf or a simple polyFill + * @param {Array} src + * @param {String} find + * @param {String} [findByKey] + * @return {Boolean|Number} false when not found, or the index + */ + function inArray(src, find, findByKey) { + if (src.indexOf && !findByKey) { + return src.indexOf(find); + } else { + var i = 0; + while (i < src.length) { + if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) { + return i; + } + i++; + } + return -1; } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(ctx, selected); - this.left = x - this.width / 2; - this.top = y - this.height / 2; + } - this._drawRawCircle(ctx, x, y, selected, hover, this.options.size); + /** + * convert array-like objects to real arrays + * @param {Object} obj + * @returns {Array} + */ + function toArray(obj) { + return Array.prototype.slice.call(obj, 0); + } - 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; + /** + * unique array with objects based on a key (like 'id') or just by the array's value + * @param {Array} src [{id:1},{id:2},{id:1}] + * @param {String} [key] + * @param {Boolean} [sort=False] + * @returns {Array} [{id:1},{id:2}] + */ + function uniqueArray(src, key, sort) { + var results = []; + var values = []; + var i = 0; - this.updateBoundingBox(x, y); - this.labelModule.draw(ctx, x, y, selected); - } - }, { - 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; - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - var a = this.width / 2; - var b = this.height / 2; - var w = Math.sin(angle) * a; - var h = Math.cos(angle) * b; - return a * b / Math.sqrt(w * w + h * h); + while (i < src.length) { + var val = key ? src[i][key] : src[i]; + if (inArray(values, val) < 0) { + results.push(src[i]); + } + values[i] = val; + i++; } - }]); - - return Circle; - })(_utilCircleImageBase2['default']); - exports['default'] = Circle; - module.exports = exports['default']; + if (sort) { + if (!key) { + results = results.sort(); + } else { + results = results.sort(function sortUniqueArray(a, b) { + return a[key] > b[key]; + }); + } + } -/***/ }, -/* 72 */ -/***/ function(module, exports, __webpack_require__) { + return results; + } - 'use strict'; + /** + * get the prefixed property + * @param {Object} obj + * @param {String} property + * @returns {String|Undefined} prefixed + */ + function prefixed(obj, property) { + var prefix, prop; + var camelProp = property[0].toUpperCase() + property.slice(1); - Object.defineProperty(exports, '__esModule', { - value: true - }); + var i = 0; + while (i < VENDOR_PREFIXES.length) { + prefix = VENDOR_PREFIXES[i]; + prop = (prefix) ? prefix + camelProp : property; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + if (prop in obj) { + return prop; + } + i++; + } + return undefined; + } - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + /** + * get a unique id + * @returns {number} uniqueId + */ + var _uniqueId = 1; + function uniqueId() { + return _uniqueId++; + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + /** + * get the window object of an element + * @param {HTMLElement} element + * @returns {DocumentView|Window} + */ + function getWindowForElement(element) { + var doc = element.ownerDocument; + return (doc.defaultView || doc.parentWindow); + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i; - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + var SUPPORT_TOUCH = ('ontouchstart' in window); + var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined; + var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent); - var _utilNodeBase = __webpack_require__(70); + var INPUT_TYPE_TOUCH = 'touch'; + var INPUT_TYPE_PEN = 'pen'; + var INPUT_TYPE_MOUSE = 'mouse'; + var INPUT_TYPE_KINECT = 'kinect'; - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + var COMPUTE_INTERVAL = 25; - var CircleImageBase = (function (_NodeBase) { - function CircleImageBase(options, body, labelModule) { - _classCallCheck(this, CircleImageBase); + var INPUT_START = 1; + var INPUT_MOVE = 2; + var INPUT_END = 4; + var INPUT_CANCEL = 8; - _get(Object.getPrototypeOf(CircleImageBase.prototype), 'constructor', this).call(this, options, body, labelModule); - this.labelOffset = 0; - this.imageLoaded = false; - } + var DIRECTION_NONE = 1; + var DIRECTION_LEFT = 2; + var DIRECTION_RIGHT = 4; + var DIRECTION_UP = 8; + var DIRECTION_DOWN = 16; - _inherits(CircleImageBase, _NodeBase); + var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT; + var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN; + var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL; - _createClass(CircleImageBase, [{ - key: '_resizeImage', + var PROPS_XY = ['x', 'y']; + var PROPS_CLIENT_XY = ['clientX', 'clientY']; - /** - * This function resizes the image by the options size when the image has not yet loaded. If the image has loaded, we - * force the update of the size again. - * - * @private - */ - value: function _resizeImage() { - var force = false; - if (!this.imageObj.width || !this.imageObj.height) { - // undefined or 0 - this.imageLoaded = false; - } else if (this.imageLoaded === false) { - this.imageLoaded = true; - force = true; - } + /** + * create new input type manager + * @param {Manager} manager + * @param {Function} callback + * @returns {Input} + * @constructor + */ + function Input(manager, callback) { + var self = this; + this.manager = manager; + this.callback = callback; + this.element = manager.element; + this.target = manager.options.inputTarget; - if (!this.width || !this.height || force === true) { - // undefined or 0 - var width, height, ratio; - if (this.imageObj.width && this.imageObj.height) { - // not undefined or 0 - width = 0; - height = 0; - } - if (this.imageObj.width > this.imageObj.height) { - ratio = this.imageObj.width / this.imageObj.height; - width = this.options.size * 2 * ratio || this.imageObj.width; - height = this.options.size * 2 || this.imageObj.height; - } else { - if (this.imageObj.width && this.imageObj.height) { - // not undefined or 0 - ratio = this.imageObj.height / this.imageObj.width; - } else { - ratio = 1; - } - width = this.options.size * 2 || this.imageObj.width; - height = this.options.size * 2 * ratio || this.imageObj.height; + // smaller wrapper around the handler, for the scope and the enabled state of the manager, + // so when disabled the input events are completely bypassed. + this.domHandler = function(ev) { + if (boolOrFn(manager.options.enable, [manager])) { + self.handler(ev); } - this.width = width; - this.height = height; - this.radius = 0.5 * this.width; - } - } - }, { - key: '_drawRawCircle', - value: function _drawRawCircle(ctx, x, y, selected, hover, size) { - var borderWidth = this.options.borderWidth; - var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - - ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; + }; - ctx.lineWidth = selected ? selectionLineWidth : borderWidth; - ctx.lineWidth *= this.networkScaleInv; - ctx.lineWidth = Math.min(this.width, ctx.lineWidth); + this.init(); - ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; - ctx.circle(x, y, size); + } - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); + Input.prototype = { + /** + * should handle the inputEvent data and trigger the callback + * @virtual + */ + handler: function() { }, - // disable shadows for other elements. - this.disableShadow(ctx); + /** + * bind the events + */ + init: function() { + this.evEl && addEventListeners(this.element, this.evEl, this.domHandler); + this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler); + this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); + }, - ctx.stroke(); + /** + * unbind the events + */ + destroy: function() { + this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler); + this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler); + this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); } - }, { - key: '_drawImageAtPosition', - value: function _drawImageAtPosition(ctx) { - if (this.imageObj.width != 0) { - // draw the image - ctx.globalAlpha = 1; + }; - // draw shadow if enabled - this.enableShadow(ctx); - ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height); + /** + * create new input type manager + * called by the Manager constructor + * @param {Hammer} manager + * @returns {Input} + */ + function createInputInstance(manager) { + var Type; + var inputClass = manager.options.inputClass; - // disable shadows for other elements. - this.disableShadow(ctx); - } + if (inputClass) { + Type = inputClass; + } else if (SUPPORT_POINTER_EVENTS) { + Type = PointerEventInput; + } else if (SUPPORT_ONLY_TOUCH) { + Type = TouchInput; + } else if (!SUPPORT_TOUCH) { + Type = MouseInput; + } else { + Type = TouchMouseInput; } - }, { - key: '_drawImageLabel', - value: function _drawImageLabel(ctx, x, y, selected) { - var yLabel; - var offset = 0; + return new (Type)(manager, inputHandler); + } - if (this.height !== undefined) { - offset = this.height * 0.5; - var labelDimensions = this.labelModule.getTextSize(ctx); - if (labelDimensions.lineCount >= 1) { - offset += labelDimensions.height / 2; - } - } + /** + * handle input events + * @param {Manager} manager + * @param {String} eventType + * @param {Object} input + */ + function inputHandler(manager, eventType, input) { + var pointersLen = input.pointers.length; + var changedPointersLen = input.changedPointers.length; + var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0)); + var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0)); - yLabel = y + offset; + input.isFirst = !!isFirst; + input.isFinal = !!isFinal; - if (this.options.label) { - this.labelOffset = offset; - } - this.labelModule.draw(ctx, x, yLabel, selected, 'hanging'); + if (isFirst) { + manager.session = {}; } - }]); - - return CircleImageBase; - })(_utilNodeBase2['default']); - - exports['default'] = CircleImageBase; - module.exports = exports['default']; - -/***/ }, -/* 73 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - - var _utilCircleImageBase = __webpack_require__(72); + // source event is the normalized value of the domEvents + // like 'touchstart, mouseup, pointerdown' + input.eventType = eventType; - var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); + // compute scale, rotation etc + computeInputData(manager, input); - var CircularImage = (function (_CircleImageBase) { - function CircularImage(options, body, labelModule, imageObj) { - _classCallCheck(this, CircularImage); + // emit secret event + manager.emit('hammer.input', input); - _get(Object.getPrototypeOf(CircularImage.prototype), 'constructor', this).call(this, options, body, labelModule); - this.imageObj = imageObj; - this._swapToImageResizeWhenImageLoaded = true; - } + manager.recognize(input); + manager.session.prevInput = input; + } - _inherits(CircularImage, _CircleImageBase); + /** + * extend the data with some usable properties like scale, rotate, velocity etc + * @param {Object} manager + * @param {Object} input + */ + function computeInputData(manager, input) { + var session = manager.session; + var pointers = input.pointers; + var pointersLength = pointers.length; - _createClass(CircularImage, [{ - key: 'resize', - value: function resize() { - if (this.imageObj.src === undefined || this.imageObj.width === undefined || this.imageObj.height === undefined) { - if (!this.width) { - var diameter = this.options.size * 2; - this.width = diameter; - this.height = diameter; - this._swapToImageResizeWhenImageLoaded = true; - this.radius = 0.5 * this.width; - } - } else { - if (this._swapToImageResizeWhenImageLoaded) { - this.width = undefined; - this.height = undefined; - this._swapToImageResizeWhenImageLoaded = false; - } - this._resizeImage(); - } + // store the first input to calculate the distance and direction + if (!session.firstInput) { + session.firstInput = simpleCloneInputData(input); } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(); - this.left = x - this.width / 2; - this.top = y - this.height / 2; + // to compute scale and rotation we need to store the multiple touches + if (pointersLength > 1 && !session.firstMultiple) { + session.firstMultiple = simpleCloneInputData(input); + } else if (pointersLength === 1) { + session.firstMultiple = false; + } - var size = Math.min(0.5 * this.height, 0.5 * this.width); + var firstInput = session.firstInput; + var firstMultiple = session.firstMultiple; + var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center; - this._drawRawCircle(ctx, x, y, selected, hover, size); + var center = input.center = getCenter(pointers); + input.timeStamp = now(); + input.deltaTime = input.timeStamp - firstInput.timeStamp; - ctx.save(); - ctx.circle(x, y, size); - ctx.stroke(); - ctx.clip(); + input.angle = getAngle(offsetCenter, center); + input.distance = getDistance(offsetCenter, center); - this._drawImageAtPosition(ctx); + computeDeltaXY(session, input); + input.offsetDirection = getDirection(input.deltaX, input.deltaY); - ctx.restore(); + input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1; + input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0; - this._drawImageLabel(ctx, x, y, selected); + computeIntervalInputData(session, input); - this.updateBoundingBox(x, 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; - 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.labelOffset); + // find the correct target + var target = manager.element; + if (hasParent(input.srcEvent.target, target)) { + target = input.srcEvent.target; } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - return this._distanceToBorder(angle); + input.target = target; + } + + function computeDeltaXY(session, input) { + var center = input.center; + var offset = session.offsetDelta || {}; + var prevDelta = session.prevDelta || {}; + var prevInput = session.prevInput || {}; + + if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) { + prevDelta = session.prevDelta = { + x: prevInput.deltaX || 0, + y: prevInput.deltaY || 0 + }; + + offset = session.offsetDelta = { + x: center.x, + y: center.y + }; } - }]); - return CircularImage; - })(_utilCircleImageBase2['default']); + input.deltaX = prevDelta.x + (center.x - offset.x); + input.deltaY = prevDelta.y + (center.y - offset.y); + } - exports['default'] = CircularImage; - module.exports = exports['default']; + /** + * velocity is calculated every x ms + * @param {Object} session + * @param {Object} input + */ + function computeIntervalInputData(session, input) { + var last = session.lastInterval || input, + deltaTime = input.timeStamp - last.timeStamp, + velocity, velocityX, velocityY, direction; -/***/ }, -/* 74 */ -/***/ function(module, exports, __webpack_require__) { + if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) { + var deltaX = last.deltaX - input.deltaX; + var deltaY = last.deltaY - input.deltaY; - 'use strict'; + var v = getVelocity(deltaTime, deltaX, deltaY); + velocityX = v.x; + velocityY = v.y; + velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y; + direction = getDirection(deltaX, deltaY); - Object.defineProperty(exports, '__esModule', { - value: true - }); + session.lastInterval = input; + } else { + // use latest velocity info if it doesn't overtake a minimum period + velocity = last.velocity; + velocityX = last.velocityX; + velocityY = last.velocityY; + direction = last.direction; + } - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + input.velocity = velocity; + input.velocityX = velocityX; + input.velocityY = velocityY; + input.direction = direction; + } - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + /** + * create a simple clone from the input used for storage of firstInput and firstMultiple + * @param {Object} input + * @returns {Object} clonedInputData + */ + function simpleCloneInputData(input) { + // make a simple copy of the pointers because we will get a reference if we don't + // we only need clientXY for the calculations + var pointers = []; + var i = 0; + while (i < input.pointers.length) { + pointers[i] = { + clientX: round(input.pointers[i].clientX), + clientY: round(input.pointers[i].clientY) + }; + i++; + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + return { + timeStamp: now(), + pointers: pointers, + center: getCenter(pointers), + deltaX: input.deltaX, + deltaY: input.deltaY + }; + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * get the center of all the pointers + * @param {Array} pointers + * @return {Object} center contains `x` and `y` properties + */ + function getCenter(pointers) { + var pointersLength = pointers.length; - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + // no need to loop when only one touch + if (pointersLength === 1) { + return { + x: round(pointers[0].clientX), + y: round(pointers[0].clientY) + }; + } - var _utilNodeBase = __webpack_require__(70); + var x = 0, y = 0, i = 0; + while (i < pointersLength) { + x += pointers[i].clientX; + y += pointers[i].clientY; + i++; + } - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + return { + x: round(x / pointersLength), + y: round(y / pointersLength) + }; + } - var Database = (function (_NodeBase) { - function Database(options, body, labelModule) { - _classCallCheck(this, Database); + /** + * calculate the velocity between two points. unit is in px per ms. + * @param {Number} deltaTime + * @param {Number} x + * @param {Number} y + * @return {Object} velocity `x` and `y` + */ + function getVelocity(deltaTime, x, y) { + return { + x: x / deltaTime || 0, + y: y / deltaTime || 0 + }; + } - _get(Object.getPrototypeOf(Database.prototype), 'constructor', this).call(this, options, body, labelModule); - } + /** + * get the direction between two points + * @param {Number} x + * @param {Number} y + * @return {Number} direction + */ + function getDirection(x, y) { + if (x === y) { + return DIRECTION_NONE; + } - _inherits(Database, _NodeBase); + if (abs(x) >= abs(y)) { + return x > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; + } + return y > 0 ? DIRECTION_UP : DIRECTION_DOWN; + } - _createClass(Database, [{ - key: 'resize', - value: function resize(ctx, selected) { - if (this.width === undefined) { - var margin = 5; - var textSize = this.labelModule.getTextSize(ctx, selected); - var size = textSize.width + 2 * margin; - this.width = size; - this.height = size; - this.radius = 0.5 * this.width; - } + /** + * calculate the absolute distance between two points + * @param {Object} p1 {x, y} + * @param {Object} p2 {x, y} + * @param {Array} [props] containing x and y keys + * @return {Number} distance + */ + function getDistance(p1, p2, props) { + if (!props) { + props = PROPS_XY; } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(ctx, selected); - this.left = x - this.width / 2; - this.top = y - this.height / 2; + var x = p2[props[0]] - p1[props[0]], + y = p2[props[1]] - p1[props[1]]; - var borderWidth = this.options.borderWidth; - var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; + return Math.sqrt((x * x) + (y * y)); + } - ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; - ctx.lineWidth = this.selected ? selectionLineWidth : borderWidth; - ctx.lineWidth *= this.networkScaleInv; - ctx.lineWidth = Math.min(this.width, ctx.lineWidth); + /** + * calculate the angle between two coordinates + * @param {Object} p1 + * @param {Object} p2 + * @param {Array} [props] containing x and y keys + * @return {Number} angle + */ + function getAngle(p1, p2, props) { + if (!props) { + props = PROPS_XY; + } + var x = p2[props[0]] - p1[props[0]], + y = p2[props[1]] - p1[props[1]]; + return Math.atan2(y, x) * 180 / Math.PI; + } - ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; - ctx.database(x - this.width / 2, y - this.height * 0.5, this.width, this.height); + /** + * calculate the rotation degrees between two pointersets + * @param {Array} start array of pointers + * @param {Array} end array of pointers + * @return {Number} rotation + */ + function getRotation(start, end) { + return getAngle(end[1], end[0], PROPS_CLIENT_XY) - getAngle(start[1], start[0], PROPS_CLIENT_XY); + } - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); + /** + * calculate the scale factor between two pointersets + * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out + * @param {Array} start array of pointers + * @param {Array} end array of pointers + * @return {Number} scale + */ + function getScale(start, end) { + return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY); + } - // disable shadows for other elements. - this.disableShadow(ctx); + var MOUSE_INPUT_MAP = { + mousedown: INPUT_START, + mousemove: INPUT_MOVE, + mouseup: INPUT_END + }; - ctx.stroke(); + var MOUSE_ELEMENT_EVENTS = 'mousedown'; + var MOUSE_WINDOW_EVENTS = 'mousemove mouseup'; - this.updateBoundingBox(x, y); + /** + * Mouse events input + * @constructor + * @extends Input + */ + function MouseInput() { + this.evEl = MOUSE_ELEMENT_EVENTS; + this.evWin = MOUSE_WINDOW_EVENTS; - this.labelModule.draw(ctx, x, y, selected); - } - }, { - key: 'updateBoundingBox', - value: function updateBoundingBox(x, y) { - this.left = x - this.width * 0.5; - this.top = y - this.height * 0.5; + this.allow = true; // used by Input.TouchMouse to disable mouse events + this.pressed = false; // mousedown state - this.boundingBox.left = this.left; - this.boundingBox.top = this.top; - this.boundingBox.bottom = this.top + this.height; - this.boundingBox.right = this.left + this.width; - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - var a = this.width / 2; - var b = this.height / 2; - var w = Math.sin(angle) * a; - var h = Math.cos(angle) * b; - return a * b / Math.sqrt(w * w + h * h); - } - }]); + Input.apply(this, arguments); + } - return Database; - })(_utilNodeBase2['default']); + inherit(MouseInput, Input, { + /** + * handle mouse events + * @param {Object} ev + */ + handler: function MEhandler(ev) { + var eventType = MOUSE_INPUT_MAP[ev.type]; - exports['default'] = Database; - module.exports = exports['default']; + // on start we want to have the left mouse button down + if (eventType & INPUT_START && ev.button === 0) { + this.pressed = true; + } -/***/ }, -/* 75 */ -/***/ function(module, exports, __webpack_require__) { + if (eventType & INPUT_MOVE && ev.which !== 1) { + eventType = INPUT_END; + } - 'use strict'; + // mouse must be down, and mouse events are allowed (see the TouchMouse input) + if (!this.pressed || !this.allow) { + return; + } - Object.defineProperty(exports, '__esModule', { - value: true + if (eventType & INPUT_END) { + this.pressed = false; + } + + this.callback(this.manager, eventType, { + pointers: [ev], + changedPointers: [ev], + pointerType: INPUT_TYPE_MOUSE, + srcEvent: ev + }); + } }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var POINTER_INPUT_MAP = { + pointerdown: INPUT_START, + pointermove: INPUT_MOVE, + pointerup: INPUT_END, + pointercancel: INPUT_CANCEL, + pointerout: INPUT_CANCEL + }; - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + // in IE10 the pointer types is defined as an enum + var IE10_POINTER_TYPE_ENUM = { + 2: INPUT_TYPE_TOUCH, + 3: INPUT_TYPE_PEN, + 4: INPUT_TYPE_MOUSE, + 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816 + }; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var POINTER_ELEMENT_EVENTS = 'pointerdown'; + var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel'; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + // IE10 has prefixed support, and case-sensitive + if (window.MSPointerEvent) { + POINTER_ELEMENT_EVENTS = 'MSPointerDown'; + POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel'; + } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + /** + * Pointer events input + * @constructor + * @extends Input + */ + function PointerEventInput() { + this.evEl = POINTER_ELEMENT_EVENTS; + this.evWin = POINTER_WINDOW_EVENTS; - var _utilShapeBase = __webpack_require__(76); + Input.apply(this, arguments); - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + this.store = (this.manager.session.pointerEvents = []); + } - var Diamond = (function (_ShapeBase) { - function Diamond(options, body, labelModule) { - _classCallCheck(this, Diamond); + inherit(PointerEventInput, Input, { + /** + * handle mouse events + * @param {Object} ev + */ + handler: function PEhandler(ev) { + var store = this.store; + var removePointer = false; - _get(Object.getPrototypeOf(Diamond.prototype), 'constructor', this).call(this, options, body, labelModule); - } + var eventTypeNormalized = ev.type.toLowerCase().replace('ms', ''); + var eventType = POINTER_INPUT_MAP[eventTypeNormalized]; + var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType; - _inherits(Diamond, _ShapeBase); + var isTouch = (pointerType == INPUT_TYPE_TOUCH); - _createClass(Diamond, [{ - key: 'resize', - value: function resize(ctx) { - this._resizeShape(); - } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'diamond', 4, x, y, selected, hover); - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - return this._distanceToBorder(angle); - } - }]); + // get index of the event in the store + var storeIndex = inArray(store, ev.pointerId, 'pointerId'); - return Diamond; - })(_utilShapeBase2['default']); + // start and mouse must be down + if (eventType & INPUT_START && (ev.button === 0 || isTouch)) { + if (storeIndex < 0) { + store.push(ev); + storeIndex = store.length - 1; + } + } else if (eventType & (INPUT_END | INPUT_CANCEL)) { + removePointer = true; + } - exports['default'] = Diamond; - module.exports = exports['default']; + // it not found, so the pointer hasn't been down (so it's probably a hover) + if (storeIndex < 0) { + return; + } -/***/ }, -/* 76 */ -/***/ function(module, exports, __webpack_require__) { + // update the event in the store + store[storeIndex] = ev; - 'use strict'; + this.callback(this.manager, eventType, { + pointers: store, + changedPointers: [ev], + pointerType: pointerType, + srcEvent: ev + }); - Object.defineProperty(exports, '__esModule', { - value: true + if (removePointer) { + // remove from the store + store.splice(storeIndex, 1); + } + } }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + var SINGLE_TOUCH_INPUT_MAP = { + touchstart: INPUT_START, + touchmove: INPUT_MOVE, + touchend: INPUT_END, + touchcancel: INPUT_CANCEL + }; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart'; + var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel'; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * Touch events input + * @constructor + * @extends Input + */ + function SingleTouchInput() { + this.evTarget = SINGLE_TOUCH_TARGET_EVENTS; + this.evWin = SINGLE_TOUCH_WINDOW_EVENTS; + this.started = false; - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + Input.apply(this, arguments); + } - var _utilNodeBase = __webpack_require__(70); + inherit(SingleTouchInput, Input, { + handler: function TEhandler(ev) { + var type = SINGLE_TOUCH_INPUT_MAP[ev.type]; - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + // should we handle the touch events? + if (type === INPUT_START) { + this.started = true; + } - var ShapeBase = (function (_NodeBase) { - function ShapeBase(options, body, labelModule) { - _classCallCheck(this, ShapeBase); + if (!this.started) { + return; + } - _get(Object.getPrototypeOf(ShapeBase.prototype), 'constructor', this).call(this, options, body, labelModule); - } + var touches = normalizeSingleTouches.call(this, ev, type); - _inherits(ShapeBase, _NodeBase); + // when done, reset the started state + if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) { + this.started = false; + } - _createClass(ShapeBase, [{ - key: '_resizeShape', - value: function _resizeShape() { - if (this.width === undefined) { - var size = 2 * this.options.size; - this.width = size; - this.height = size; - this.radius = 0.5 * this.width; - } + this.callback(this.manager, type, { + pointers: touches[0], + changedPointers: touches[1], + pointerType: INPUT_TYPE_TOUCH, + srcEvent: ev + }); } - }, { - key: '_drawShape', - value: function _drawShape(ctx, shape, sizeMultiplier, x, y, selected, hover) { - this._resizeShape(); + }); - this.left = x - this.width / 2; - this.top = y - this.height / 2; + /** + * @this {TouchInput} + * @param {Object} ev + * @param {Number} type flag + * @returns {undefined|Array} [all, changed] + */ + function normalizeSingleTouches(ev, type) { + var all = toArray(ev.touches); + var changed = toArray(ev.changedTouches); - var borderWidth = this.options.borderWidth; - var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; + if (type & (INPUT_END | INPUT_CANCEL)) { + all = uniqueArray(all.concat(changed), 'identifier', true); + } - ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; - ctx.lineWidth = selected ? selectionLineWidth : borderWidth; - ctx.lineWidth /= this.body.view.scale; - ctx.lineWidth = Math.min(this.width, ctx.lineWidth); - ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; - ctx[shape](x, y, this.options.size); + return [all, changed]; + } - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); + var TOUCH_INPUT_MAP = { + touchstart: INPUT_START, + touchmove: INPUT_MOVE, + touchend: INPUT_END, + touchcancel: INPUT_CANCEL + }; - // disable shadows for other elements. - this.disableShadow(ctx); + var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel'; - ctx.stroke(); + /** + * Multi-user touch events input + * @constructor + * @extends Input + */ + function TouchInput() { + this.evTarget = TOUCH_TARGET_EVENTS; + this.targetIds = {}; - if (this.options.label !== undefined) { - var yLabel = y + 0.5 * this.height + 3; // the + 3 is to offset it a bit below the node. - this.labelModule.draw(ctx, x, yLabel, selected, 'hanging'); - } + Input.apply(this, arguments); + } - this.updateBoundingBox(x, 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; + inherit(TouchInput, Input, { + handler: function MTEhandler(ev) { + var type = TOUCH_INPUT_MAP[ev.type]; + var touches = getTouches.call(this, ev, type); + if (!touches) { + return; + } - if (this.options.label !== undefined) { - 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 + 3); - } + this.callback(this.manager, type, { + pointers: touches[0], + changedPointers: touches[1], + pointerType: INPUT_TYPE_TOUCH, + srcEvent: ev + }); } - }]); + }); - return ShapeBase; - })(_utilNodeBase2['default']); + /** + * @this {TouchInput} + * @param {Object} ev + * @param {Number} type flag + * @returns {undefined|Array} [all, changed] + */ + function getTouches(ev, type) { + var allTouches = toArray(ev.touches); + var targetIds = this.targetIds; - exports['default'] = ShapeBase; - module.exports = exports['default']; + // when there is only one touch, the process can be simplified + if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) { + targetIds[allTouches[0].identifier] = true; + return [allTouches, allTouches]; + } -/***/ }, -/* 77 */ -/***/ function(module, exports, __webpack_require__) { + var i, + targetTouches, + changedTouches = toArray(ev.changedTouches), + changedTargetTouches = [], + target = this.target; - 'use strict'; + // get target touches from touches + targetTouches = allTouches.filter(function(touch) { + return hasParent(touch.target, target); + }); - Object.defineProperty(exports, '__esModule', { - value: true - }); + // collect touches + if (type === INPUT_START) { + i = 0; + while (i < targetTouches.length) { + targetIds[targetTouches[i].identifier] = true; + i++; + } + } - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // filter changed touches to only contain touches that exist in the collected target ids + i = 0; + while (i < changedTouches.length) { + if (targetIds[changedTouches[i].identifier]) { + changedTargetTouches.push(changedTouches[i]); + } - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + // cleanup removed touches + if (type & (INPUT_END | INPUT_CANCEL)) { + delete targetIds[changedTouches[i].identifier]; + } + i++; + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + if (!changedTargetTouches.length) { + return; + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + return [ + // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel' + uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true), + changedTargetTouches + ]; + } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + /** + * Combined touch and mouse input + * + * Touch has a higher priority then mouse, and while touching no mouse events are allowed. + * This because touch devices also emit mouse events while doing a touch. + * + * @constructor + * @extends Input + */ + function TouchMouseInput() { + Input.apply(this, arguments); - var _utilShapeBase = __webpack_require__(76); + var handler = bindFn(this.handler, this); + this.touch = new TouchInput(this.manager, handler); + this.mouse = new MouseInput(this.manager, handler); + } - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + inherit(TouchMouseInput, Input, { + /** + * handle mouse and touch events + * @param {Hammer} manager + * @param {String} inputEvent + * @param {Object} inputData + */ + handler: function TMEhandler(manager, inputEvent, inputData) { + var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH), + isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE); - var Dot = (function (_ShapeBase) { - function Dot(options, body, labelModule) { - _classCallCheck(this, Dot); + // when we're in a touch event, so block all upcoming mouse events + // most mobile browser also emit mouseevents, right after touchstart + if (isTouch) { + this.mouse.allow = false; + } else if (isMouse && !this.mouse.allow) { + return; + } - _get(Object.getPrototypeOf(Dot.prototype), 'constructor', this).call(this, options, body, labelModule); - } + // reset the allowMouse when we're done + if (inputEvent & (INPUT_END | INPUT_CANCEL)) { + this.mouse.allow = true; + } - _inherits(Dot, _ShapeBase); + this.callback(manager, inputEvent, inputData); + }, - _createClass(Dot, [{ - key: 'resize', - value: function resize(ctx) { - this._resizeShape(); - } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'circle', 2, x, y, selected, hover); - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - return this.options.size + this.options.borderWidth; + /** + * remove the event listeners + */ + destroy: function destroy() { + this.touch.destroy(); + this.mouse.destroy(); } - }]); + }); - return Dot; - })(_utilShapeBase2['default']); + var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction'); + var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined; - exports['default'] = Dot; - module.exports = exports['default']; + // magical touchAction value + var TOUCH_ACTION_COMPUTE = 'compute'; + var TOUCH_ACTION_AUTO = 'auto'; + var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented + var TOUCH_ACTION_NONE = 'none'; + var TOUCH_ACTION_PAN_X = 'pan-x'; + var TOUCH_ACTION_PAN_Y = 'pan-y'; -/***/ }, -/* 78 */ -/***/ function(module, exports, __webpack_require__) { + /** + * Touch Action + * sets the touchAction property or uses the js alternative + * @param {Manager} manager + * @param {String} value + * @constructor + */ + function TouchAction(manager, value) { + this.manager = manager; + this.set(value); + } - 'use strict'; + TouchAction.prototype = { + /** + * set the touchAction value on the element or enable the polyfill + * @param {String} value + */ + set: function(value) { + // find out the touch-action by the event handlers + if (value == TOUCH_ACTION_COMPUTE) { + value = this.compute(); + } - Object.defineProperty(exports, '__esModule', { - value: true - }); + if (NATIVE_TOUCH_ACTION) { + this.manager.element.style[PREFIXED_TOUCH_ACTION] = value; + } + this.actions = value.toLowerCase().trim(); + }, - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + /** + * just re-set the touchAction value + */ + update: function() { + this.set(this.manager.options.touchAction); + }, - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + /** + * compute the value for the touchAction property based on the recognizer's settings + * @returns {String} value + */ + compute: function() { + var actions = []; + each(this.manager.recognizers, function(recognizer) { + if (boolOrFn(recognizer.options.enable, [recognizer])) { + actions = actions.concat(recognizer.getTouchAction()); + } + }); + return cleanTouchActions(actions.join(' ')); + }, - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + /** + * this method is called on each input cycle and provides the preventing of the browser behavior + * @param {Object} input + */ + preventDefaults: function(input) { + // not needed with native support for the touchAction property + if (NATIVE_TOUCH_ACTION) { + return; + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + var srcEvent = input.srcEvent; + var direction = input.offsetDirection; - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + // if the touch action did prevented once this session + if (this.manager.session.prevented) { + srcEvent.preventDefault(); + return; + } - var _utilNodeBase = __webpack_require__(70); + var actions = this.actions; + var hasNone = inStr(actions, TOUCH_ACTION_NONE); + var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); + var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + if (hasNone || + (hasPanY && direction & DIRECTION_HORIZONTAL) || + (hasPanX && direction & DIRECTION_VERTICAL)) { + return this.preventSrc(srcEvent); + } + }, - var Ellipse = (function (_NodeBase) { - function Ellipse(options, body, labelModule) { - _classCallCheck(this, Ellipse); + /** + * call preventDefault to prevent the browser's default behavior (scrolling in most cases) + * @param {Object} srcEvent + */ + preventSrc: function(srcEvent) { + this.manager.session.prevented = true; + srcEvent.preventDefault(); + } + }; - _get(Object.getPrototypeOf(Ellipse.prototype), 'constructor', this).call(this, options, body, labelModule); - } + /** + * when the touchActions are collected they are not a valid value, so we need to clean things up. * + * @param {String} actions + * @returns {*} + */ + function cleanTouchActions(actions) { + // none + if (inStr(actions, TOUCH_ACTION_NONE)) { + return TOUCH_ACTION_NONE; + } - _inherits(Ellipse, _NodeBase); + var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); + var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); - _createClass(Ellipse, [{ - key: 'resize', - value: function resize(ctx, selected) { - if (this.width === undefined) { - var textSize = this.labelModule.getTextSize(ctx, selected); + // pan-x and pan-y can be combined + if (hasPanX && hasPanY) { + return TOUCH_ACTION_PAN_X + ' ' + TOUCH_ACTION_PAN_Y; + } - this.width = textSize.width * 1.5; - this.height = textSize.height * 2; - if (this.width < this.height) { - this.width = this.height; - } - this.radius = 0.5 * this.width; - } + // pan-x OR pan-y + if (hasPanX || hasPanY) { + return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y; } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(ctx, selected); - this.left = x - this.width * 0.5; - this.top = y - this.height * 0.5; - var borderWidth = this.options.borderWidth; - var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; + // manipulation + if (inStr(actions, TOUCH_ACTION_MANIPULATION)) { + return TOUCH_ACTION_MANIPULATION; + } - ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; + return TOUCH_ACTION_AUTO; + } - ctx.lineWidth = selected ? selectionLineWidth : borderWidth; - ctx.lineWidth /= this.body.view.scale; - ctx.lineWidth = Math.min(this.width, ctx.lineWidth); + /** + * Recognizer flow explained; * + * All recognizers have the initial state of POSSIBLE when a input session starts. + * The definition of a input session is from the first input until the last input, with all it's movement in it. * + * Example session for mouse-input: mousedown -> mousemove -> mouseup + * + * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed + * which determines with state it should be. + * + * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to + * POSSIBLE to give it another change on the next cycle. + * + * Possible + * | + * +-----+---------------+ + * | | + * +-----+-----+ | + * | | | + * Failed Cancelled | + * +-------+------+ + * | | + * Recognized Began + * | + * Changed + * | + * Ended/Recognized + */ + var STATE_POSSIBLE = 1; + var STATE_BEGAN = 2; + var STATE_CHANGED = 4; + var STATE_ENDED = 8; + var STATE_RECOGNIZED = STATE_ENDED; + var STATE_CANCELLED = 16; + var STATE_FAILED = 32; - ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; - ctx.ellipse(this.left, this.top, this.width, this.height); + /** + * Recognizer + * Every recognizer needs to extend from this class. + * @constructor + * @param {Object} options + */ + function Recognizer(options) { + this.id = uniqueId(); - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); + this.manager = null; + this.options = merge(options || {}, this.defaults); - // disable shadows for other elements. - this.disableShadow(ctx); + // default is enable true + this.options.enable = ifUndefined(this.options.enable, true); - ctx.stroke(); + this.state = STATE_POSSIBLE; - this.updateBoundingBox(x, y); - this.labelModule.draw(ctx, x, y, selected); - } - }, { - key: 'updateBoundingBox', - value: function updateBoundingBox(x, y) { - this.left = x - this.width * 0.5; - this.top = y - this.height * 0.5; + this.simultaneous = {}; + this.requireFail = []; + } - this.boundingBox.left = this.left; - this.boundingBox.top = this.top; - this.boundingBox.bottom = this.top + this.height; - this.boundingBox.right = this.left + this.width; - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - var a = this.width * 0.5; - var b = this.height * 0.5; - var w = Math.sin(angle) * a; - var h = Math.cos(angle) * b; - return a * b / Math.sqrt(w * w + h * h); - } - }]); + Recognizer.prototype = { + /** + * @virtual + * @type {Object} + */ + defaults: {}, - return Ellipse; - })(_utilNodeBase2['default']); + /** + * set options + * @param {Object} options + * @return {Recognizer} + */ + set: function(options) { + extend(this.options, options); - exports['default'] = Ellipse; - module.exports = exports['default']; + // also update the touchAction, in case something changed about the directions/enabled state + this.manager && this.manager.touchAction.update(); + return this; + }, -/***/ }, -/* 79 */ -/***/ function(module, exports, __webpack_require__) { + /** + * recognize simultaneous with an other recognizer. + * @param {Recognizer} otherRecognizer + * @returns {Recognizer} this + */ + recognizeWith: function(otherRecognizer) { + if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) { + return this; + } - 'use strict'; + var simultaneous = this.simultaneous; + otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); + if (!simultaneous[otherRecognizer.id]) { + simultaneous[otherRecognizer.id] = otherRecognizer; + otherRecognizer.recognizeWith(this); + } + return this; + }, - Object.defineProperty(exports, '__esModule', { - value: true - }); + /** + * drop the simultaneous link. it doesnt remove the link on the other recognizer. + * @param {Recognizer} otherRecognizer + * @returns {Recognizer} this + */ + dropRecognizeWith: function(otherRecognizer) { + if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) { + return this; + } - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); + delete this.simultaneous[otherRecognizer.id]; + return this; + }, - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + /** + * recognizer can only run when an other is failing + * @param {Recognizer} otherRecognizer + * @returns {Recognizer} this + */ + requireFailure: function(otherRecognizer) { + if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) { + return this; + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var requireFail = this.requireFail; + otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); + if (inArray(requireFail, otherRecognizer) === -1) { + requireFail.push(otherRecognizer); + otherRecognizer.requireFailure(this); + } + return this; + }, - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * drop the requireFailure link. it does not remove the link on the other recognizer. + * @param {Recognizer} otherRecognizer + * @returns {Recognizer} this + */ + dropRequireFailure: function(otherRecognizer) { + if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) { + return this; + } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); + var index = inArray(this.requireFail, otherRecognizer); + if (index > -1) { + this.requireFail.splice(index, 1); + } + return this; + }, - var _utilNodeBase = __webpack_require__(70); + /** + * has require failures boolean + * @returns {boolean} + */ + hasRequireFailures: function() { + return this.requireFail.length > 0; + }, - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + /** + * if the recognizer can recognize simultaneous with an other recognizer + * @param {Recognizer} otherRecognizer + * @returns {Boolean} + */ + canRecognizeWith: function(otherRecognizer) { + return !!this.simultaneous[otherRecognizer.id]; + }, - var Icon = (function (_NodeBase) { - function Icon(options, body, labelModule) { - _classCallCheck(this, Icon); + /** + * You should use `tryEmit` instead of `emit` directly to check + * that all the needed recognizers has failed before emitting. + * @param {Object} input + */ + emit: function(input) { + var self = this; + var state = this.state; - _get(Object.getPrototypeOf(Icon.prototype), 'constructor', this).call(this, options, body, labelModule); - } + function emit(withState) { + self.manager.emit(self.options.event + (withState ? stateStr(state) : ''), input); + } - _inherits(Icon, _NodeBase); + // 'panstart' and 'panmove' + if (state < STATE_ENDED) { + emit(true); + } - _createClass(Icon, [{ - key: 'resize', - value: function resize(ctx) { - if (this.width === undefined) { - var margin = 5; - var iconSize = { - width: Number(this.options.icon.size), - height: Number(this.options.icon.size) - }; - this.width = iconSize.width + 2 * margin; - this.height = iconSize.height + 2 * margin; - this.radius = 0.5 * this.width; - } - } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(ctx); - this.options.icon.size = this.options.icon.size || 50; + emit(); // simple 'eventName' events - this.left = x - this.width * 0.5; - this.top = y - this.height * 0.5; - this._icon(ctx, x, y, selected); + // panend and pancancel + if (state >= STATE_ENDED) { + emit(true); + } + }, - if (this.options.label !== undefined) { - var iconTextSpacing = 5; - this.labelModule.draw(ctx, x, y + this.height * 0.5 + iconTextSpacing, selected); - } + /** + * Check that all the require failure recognizers has failed, + * if true, it emits a gesture event, + * otherwise, setup the state to FAILED. + * @param {Object} input + */ + tryEmit: function(input) { + if (this.canEmit()) { + return this.emit(input); + } + // it's failing anyway + this.state = STATE_FAILED; + }, - this.updateBoundingBox(x, y); - } - }, { - key: 'updateBoundingBox', - value: function updateBoundingBox(x, y) { - this.boundingBox.top = y - this.options.icon.size * 0.5; - this.boundingBox.left = x - this.options.icon.size * 0.5; - this.boundingBox.right = x + this.options.icon.size * 0.5; - this.boundingBox.bottom = y + this.options.icon.size * 0.5; + /** + * can we emit? + * @returns {boolean} + */ + canEmit: function() { + var i = 0; + while (i < this.requireFail.length) { + if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) { + return false; + } + i++; + } + return true; + }, - if (this.options.label !== undefined) { - var iconTextSpacing = 5; - 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 + iconTextSpacing); - } - } - }, { - key: '_icon', - value: function _icon(ctx, x, y, selected) { - var iconSize = Number(this.options.icon.size); + /** + * update the recognizer + * @param {Object} inputData + */ + recognize: function(inputData) { + // make a new copy of the inputData + // so we can change the inputData without messing up the other recognizers + var inputDataClone = extend({}, inputData); - if (this.options.icon.code !== undefined) { - ctx.font = (selected ? 'bold ' : '') + iconSize + 'px ' + this.options.icon.face; + // is is enabled and allow recognizing? + if (!boolOrFn(this.options.enable, [this, inputDataClone])) { + this.reset(); + this.state = STATE_FAILED; + return; + } - // draw icon - ctx.fillStyle = this.options.icon.color || 'black'; - ctx.textAlign = 'center'; - ctx.textBaseline = 'middle'; + // reset when we've reached the end + if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) { + this.state = STATE_POSSIBLE; + } - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fillText(this.options.icon.code, x, y); + this.state = this.process(inputDataClone); - // disable shadows for other elements. - this.disableShadow(ctx); - } else { - console.error('When using the icon shape, you need to define the code in the icon options object. This can be done per node or globally.'); - } - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - this._distanceToBorder(angle); - } - }]); + // the recognizer has recognized a gesture + // so trigger an event + if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) { + this.tryEmit(inputDataClone); + } + }, - return Icon; - })(_utilNodeBase2['default']); + /** + * return the state of the recognizer + * the actual recognizing happens in this method + * @virtual + * @param {Object} inputData + * @returns {Const} STATE + */ + process: function(inputData) { }, // jshint ignore:line - exports['default'] = Icon; - module.exports = exports['default']; + /** + * return the preferred touch-action + * @virtual + * @returns {Array} + */ + getTouchAction: function() { }, -/***/ }, -/* 80 */ -/***/ function(module, exports, __webpack_require__) { + /** + * called when the gesture isn't allowed to recognize + * like when another is being recognized or it is disabled + * @virtual + */ + reset: function() { } + }; - 'use strict'; + /** + * get a usable string, used as event postfix + * @param {Const} state + * @returns {String} state + */ + function stateStr(state) { + if (state & STATE_CANCELLED) { + return 'cancel'; + } else if (state & STATE_ENDED) { + return 'end'; + } else if (state & STATE_CHANGED) { + return 'move'; + } else if (state & STATE_BEGAN) { + return 'start'; + } + return ''; + } - Object.defineProperty(exports, '__esModule', { - value: true - }); + /** + * direction cons to string + * @param {Const} direction + * @returns {String} + */ + function directionStr(direction) { + if (direction == DIRECTION_DOWN) { + return 'down'; + } else if (direction == DIRECTION_UP) { + return 'up'; + } else if (direction == DIRECTION_LEFT) { + return 'left'; + } else if (direction == DIRECTION_RIGHT) { + return 'right'; + } + return ''; + } - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + /** + * get a recognizer by name if it is bound to a manager + * @param {Recognizer|String} otherRecognizer + * @param {Recognizer} recognizer + * @returns {Recognizer} + */ + function getRecognizerByNameIfManager(otherRecognizer, recognizer) { + var manager = recognizer.manager; + if (manager) { + return manager.get(otherRecognizer); + } + return otherRecognizer; + } - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + /** + * This recognizer is just used as a base for the simple attribute recognizers. + * @constructor + * @extends Recognizer + */ + function AttrRecognizer() { + Recognizer.apply(this, arguments); + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + inherit(AttrRecognizer, Recognizer, { + /** + * @namespace + * @memberof AttrRecognizer + */ + defaults: { + /** + * @type {Number} + * @default 1 + */ + pointers: 1 + }, - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * Used to check if it the recognizer receives valid input, like input.distance > 10. + * @memberof AttrRecognizer + * @param {Object} input + * @returns {Boolean} recognized + */ + attrTest: function(input) { + var optionPointers = this.options.pointers; + return optionPointers === 0 || input.pointers.length === optionPointers; + }, - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + /** + * Process the input and return the state for the recognizer + * @memberof AttrRecognizer + * @param {Object} input + * @returns {*} State + */ + process: function(input) { + var state = this.state; + var eventType = input.eventType; - var _utilCircleImageBase = __webpack_require__(72); + var isRecognized = state & (STATE_BEGAN | STATE_CHANGED); + var isValid = this.attrTest(input); - var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); + // on cancel input and we've recognized before, return STATE_CANCELLED + if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) { + return state | STATE_CANCELLED; + } else if (isRecognized || isValid) { + if (eventType & INPUT_END) { + return state | STATE_ENDED; + } else if (!(state & STATE_BEGAN)) { + return STATE_BEGAN; + } + return state | STATE_CHANGED; + } + return STATE_FAILED; + } + }); - var Image = (function (_CircleImageBase) { - function Image(options, body, labelModule, imageObj) { - _classCallCheck(this, Image); + /** + * Pan + * Recognized when the pointer is down and moved in the allowed direction. + * @constructor + * @extends AttrRecognizer + */ + function PanRecognizer() { + AttrRecognizer.apply(this, arguments); - _get(Object.getPrototypeOf(Image.prototype), 'constructor', this).call(this, options, body, labelModule); - this.imageObj = imageObj; - } + this.pX = null; + this.pY = null; + } - _inherits(Image, _CircleImageBase); + inherit(PanRecognizer, AttrRecognizer, { + /** + * @namespace + * @memberof PanRecognizer + */ + defaults: { + event: 'pan', + threshold: 10, + pointers: 1, + direction: DIRECTION_ALL + }, - _createClass(Image, [{ - key: 'resize', - value: function resize() { - this._resizeImage(); - } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(); - this.left = x - this.width / 2; - this.top = y - this.height / 2; + getTouchAction: function() { + var direction = this.options.direction; + var actions = []; + if (direction & DIRECTION_HORIZONTAL) { + actions.push(TOUCH_ACTION_PAN_Y); + } + if (direction & DIRECTION_VERTICAL) { + actions.push(TOUCH_ACTION_PAN_X); + } + return actions; + }, - this._drawImageAtPosition(ctx); + directionTest: function(input) { + var options = this.options; + var hasMoved = true; + var distance = input.distance; + var direction = input.direction; + var x = input.deltaX; + var y = input.deltaY; - this._drawImageLabel(ctx, x, y, selected || hover); + // lock to axis? + if (!(direction & options.direction)) { + if (options.direction & DIRECTION_HORIZONTAL) { + direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; + hasMoved = x != this.pX; + distance = Math.abs(input.deltaX); + } else { + direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN; + hasMoved = y != this.pY; + distance = Math.abs(input.deltaY); + } + } + input.direction = direction; + return hasMoved && distance > options.threshold && direction & options.direction; + }, - this.updateBoundingBox(x, y); - } - }, { - key: 'updateBoundingBox', - value: function updateBoundingBox(x, y) { - this.left = x - this.width / 2; - this.top = y - this.height / 2; + attrTest: function(input) { + return AttrRecognizer.prototype.attrTest.call(this, input) && + (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input))); + }, - this.boundingBox.top = this.top; - this.boundingBox.left = this.left; - this.boundingBox.right = this.left + this.width; - this.boundingBox.bottom = this.top + this.height; + emit: function(input) { + this.pX = input.deltaX; + this.pY = input.deltaY; - if (this.options.label !== undefined) { - 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.labelOffset); - } - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - var a = this.width / 2; - var b = this.height / 2; - var w = Math.sin(angle) * a; - var h = Math.cos(angle) * b; - return a * b / Math.sqrt(w * w + h * h); + var direction = directionStr(input.direction); + if (direction) { + this.manager.emit(this.options.event + direction, input); + } + + this._super.emit.call(this, input); } - }]); + }); - return Image; - })(_utilCircleImageBase2['default']); + /** + * Pinch + * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out). + * @constructor + * @extends AttrRecognizer + */ + function PinchRecognizer() { + AttrRecognizer.apply(this, arguments); + } - exports['default'] = Image; - module.exports = exports['default']; + inherit(PinchRecognizer, AttrRecognizer, { + /** + * @namespace + * @memberof PinchRecognizer + */ + defaults: { + event: 'pinch', + threshold: 0, + pointers: 2 + }, -/***/ }, -/* 81 */ -/***/ function(module, exports, __webpack_require__) { + getTouchAction: function() { + return [TOUCH_ACTION_NONE]; + }, - 'use strict'; + attrTest: function(input) { + return this._super.attrTest.call(this, input) && + (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN); + }, - Object.defineProperty(exports, '__esModule', { - value: true + emit: function(input) { + this._super.emit.call(this, input); + if (input.scale !== 1) { + var inOut = input.scale < 1 ? 'in' : 'out'; + this.manager.emit(this.options.event + inOut, input); + } + } }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + /** + * Press + * Recognized when the pointer is down for x ms without any movement. + * @constructor + * @extends Recognizer + */ + function PressRecognizer() { + Recognizer.apply(this, arguments); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + this._timer = null; + this._input = null; + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + inherit(PressRecognizer, Recognizer, { + /** + * @namespace + * @memberof PressRecognizer + */ + defaults: { + event: 'press', + pointers: 1, + time: 500, // minimal time of the pointer to be pressed + threshold: 5 // a minimal movement is ok, but keep it low + }, - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + getTouchAction: function() { + return [TOUCH_ACTION_AUTO]; + }, - var _utilShapeBase = __webpack_require__(76); + process: function(input) { + var options = this.options; + var validPointers = input.pointers.length === options.pointers; + var validMovement = input.distance < options.threshold; + var validTime = input.deltaTime > options.time; - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + this._input = input; - var Square = (function (_ShapeBase) { - function Square(options, body, labelModule) { - _classCallCheck(this, Square); + // we only allow little movement + // and we've reached an end event, so a tap is possible + if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) { + this.reset(); + } else if (input.eventType & INPUT_START) { + this.reset(); + this._timer = setTimeoutContext(function() { + this.state = STATE_RECOGNIZED; + this.tryEmit(); + }, options.time, this); + } else if (input.eventType & INPUT_END) { + return STATE_RECOGNIZED; + } + return STATE_FAILED; + }, - _get(Object.getPrototypeOf(Square.prototype), 'constructor', this).call(this, options, body, labelModule); - } + reset: function() { + clearTimeout(this._timer); + }, - _inherits(Square, _ShapeBase); + emit: function(input) { + if (this.state !== STATE_RECOGNIZED) { + return; + } - _createClass(Square, [{ - key: 'resize', - value: function resize() { - this._resizeShape(); - } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'square', 2, x, y, selected, hover); - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - return this._distanceToBorder(angle); + if (input && (input.eventType & INPUT_END)) { + this.manager.emit(this.options.event + 'up', input); + } else { + this._input.timeStamp = now(); + this.manager.emit(this.options.event, this._input); + } } - }]); - - return Square; - })(_utilShapeBase2['default']); + }); - exports['default'] = Square; - module.exports = exports['default']; + /** + * Rotate + * Recognized when two or more pointer are moving in a circular motion. + * @constructor + * @extends AttrRecognizer + */ + function RotateRecognizer() { + AttrRecognizer.apply(this, arguments); + } -/***/ }, -/* 82 */ -/***/ function(module, exports, __webpack_require__) { + inherit(RotateRecognizer, AttrRecognizer, { + /** + * @namespace + * @memberof RotateRecognizer + */ + defaults: { + event: 'rotate', + threshold: 0, + pointers: 2 + }, - 'use strict'; + getTouchAction: function() { + return [TOUCH_ACTION_NONE]; + }, - Object.defineProperty(exports, '__esModule', { - value: true + attrTest: function(input) { + return this._super.attrTest.call(this, input) && + (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN); + } }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + /** + * Swipe + * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction. + * @constructor + * @extends AttrRecognizer + */ + function SwipeRecognizer() { + AttrRecognizer.apply(this, arguments); + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + inherit(SwipeRecognizer, AttrRecognizer, { + /** + * @namespace + * @memberof SwipeRecognizer + */ + defaults: { + event: 'swipe', + threshold: 10, + velocity: 0.65, + direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL, + pointers: 1 + }, - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + getTouchAction: function() { + return PanRecognizer.prototype.getTouchAction.call(this); + }, - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + attrTest: function(input) { + var direction = this.options.direction; + var velocity; - var _utilShapeBase = __webpack_require__(76); + if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) { + velocity = input.velocity; + } else if (direction & DIRECTION_HORIZONTAL) { + velocity = input.velocityX; + } else if (direction & DIRECTION_VERTICAL) { + velocity = input.velocityY; + } - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + return this._super.attrTest.call(this, input) && + direction & input.direction && + input.distance > this.options.threshold && + abs(velocity) > this.options.velocity && input.eventType & INPUT_END; + }, - var Star = (function (_ShapeBase) { - function Star(options, body, labelModule) { - _classCallCheck(this, Star); + emit: function(input) { + var direction = directionStr(input.direction); + if (direction) { + this.manager.emit(this.options.event + direction, input); + } - _get(Object.getPrototypeOf(Star.prototype), 'constructor', this).call(this, options, body, labelModule); - } + this.manager.emit(this.options.event, input); + } + }); - _inherits(Star, _ShapeBase); + /** + * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur + * between the given interval and position. The delay option can be used to recognize multi-taps without firing + * a single tap. + * + * The eventData from the emitted event contains the property `tapCount`, which contains the amount of + * multi-taps being recognized. + * @constructor + * @extends Recognizer + */ + function TapRecognizer() { + Recognizer.apply(this, arguments); - _createClass(Star, [{ - key: 'resize', - value: function resize(ctx) { - this._resizeShape(); - } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'star', 4, x, y, selected, hover); - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - return this._distanceToBorder(angle); - } - }]); + // previous time and center, + // used for tap counting + this.pTime = false; + this.pCenter = false; - return Star; - })(_utilShapeBase2['default']); + this._timer = null; + this._input = null; + this.count = 0; + } - exports['default'] = Star; - module.exports = exports['default']; + inherit(TapRecognizer, Recognizer, { + /** + * @namespace + * @memberof PinchRecognizer + */ + defaults: { + event: 'tap', + pointers: 1, + taps: 1, + interval: 300, // max time between the multi-tap taps + time: 250, // max time of the pointer to be down (like finger on the screen) + threshold: 2, // a minimal movement is ok, but keep it low + posThreshold: 10 // a multi-tap can be a bit off the initial position + }, -/***/ }, -/* 83 */ -/***/ function(module, exports, __webpack_require__) { + getTouchAction: function() { + return [TOUCH_ACTION_MANIPULATION]; + }, - 'use strict'; + process: function(input) { + var options = this.options; - Object.defineProperty(exports, '__esModule', { - value: true - }); + var validPointers = input.pointers.length === options.pointers; + var validMovement = input.distance < options.threshold; + var validTouchTime = input.deltaTime < options.time; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + this.reset(); - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + if ((input.eventType & INPUT_START) && (this.count === 0)) { + return this.failTimeout(); + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + // we only allow little movement + // and we've reached an end event, so a tap is possible + if (validMovement && validTouchTime && validPointers) { + if (input.eventType != INPUT_END) { + return this.failTimeout(); + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true; + var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold; - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + this.pTime = input.timeStamp; + this.pCenter = input.center; - var _utilNodeBase = __webpack_require__(70); + if (!validMultiTap || !validInterval) { + this.count = 1; + } else { + this.count += 1; + } - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + this._input = input; - var Text = (function (_NodeBase) { - function Text(options, body, labelModule) { - _classCallCheck(this, Text); + // if tap count matches we have recognized it, + // else it has began recognizing... + var tapCount = this.count % options.taps; + if (tapCount === 0) { + // no failing requirements, immediately trigger the tap event + // or wait as long as the multitap interval to trigger + if (!this.hasRequireFailures()) { + return STATE_RECOGNIZED; + } else { + this._timer = setTimeoutContext(function() { + this.state = STATE_RECOGNIZED; + this.tryEmit(); + }, options.interval, this); + return STATE_BEGAN; + } + } + } + return STATE_FAILED; + }, - _get(Object.getPrototypeOf(Text.prototype), 'constructor', this).call(this, options, body, labelModule); - } + failTimeout: function() { + this._timer = setTimeoutContext(function() { + this.state = STATE_FAILED; + }, this.options.interval, this); + return STATE_FAILED; + }, - _inherits(Text, _NodeBase); + reset: function() { + clearTimeout(this._timer); + }, - _createClass(Text, [{ - key: 'resize', - value: function resize(ctx, selected) { - if (this.width === undefined) { - var margin = 5; - var textSize = this.labelModule.getTextSize(ctx, selected); - this.width = textSize.width + 2 * margin; - this.height = textSize.height + 2 * margin; - this.radius = 0.5 * this.width; - } + emit: function() { + if (this.state == STATE_RECOGNIZED ) { + this._input.tapCount = this.count; + this.manager.emit(this.options.event, this._input); + } } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(ctx, selected || hover); - this.left = x - this.width / 2; - this.top = y - this.height / 2; + }); - // draw shadow if enabled - this.enableShadow(ctx); - this.labelModule.draw(ctx, x, y, selected || hover); + /** + * Simple way to create an manager with a default set of recognizers. + * @param {HTMLElement} element + * @param {Object} [options] + * @constructor + */ + function Hammer(element, options) { + options = options || {}; + options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset); + return new Manager(element, options); + } - // disable shadows for other elements. - this.disableShadow(ctx); + /** + * @const {string} + */ + Hammer.VERSION = '2.0.4'; - this.updateBoundingBox(x, y); - } - }, { - key: 'updateBoundingBox', - value: function updateBoundingBox(x, y) { - this.left = x - this.width / 2; - this.top = y - this.height / 2; + /** + * default settings + * @namespace + */ + Hammer.defaults = { + /** + * set if DOM events are being triggered. + * But this is slower and unused by simple implementations, so disabled by default. + * @type {Boolean} + * @default false + */ + domEvents: false, - this.boundingBox.top = this.top; - this.boundingBox.left = this.left; - this.boundingBox.right = this.left + this.width; - this.boundingBox.bottom = this.top + this.height; - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - return this._distanceToBorder(angle); - } - }]); + /** + * The value for the touchAction property/fallback. + * When set to `compute` it will magically set the correct value based on the added recognizers. + * @type {String} + * @default compute + */ + touchAction: TOUCH_ACTION_COMPUTE, - return Text; - })(_utilNodeBase2['default']); + /** + * @type {Boolean} + * @default true + */ + enable: true, + + /** + * EXPERIMENTAL FEATURE -- can be removed/changed + * Change the parent input target element. + * If Null, then it is being set the to main element. + * @type {Null|EventTarget} + * @default null + */ + inputTarget: null, + + /** + * force an input class + * @type {Null|Function} + * @default null + */ + inputClass: null, + + /** + * Default recognizer setup when calling `Hammer()` + * When creating a new Manager these will be skipped. + * @type {Array} + */ + preset: [ + // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...] + [RotateRecognizer, { enable: false }], + [PinchRecognizer, { enable: false }, ['rotate']], + [SwipeRecognizer,{ direction: DIRECTION_HORIZONTAL }], + [PanRecognizer, { direction: DIRECTION_HORIZONTAL }, ['swipe']], + [TapRecognizer], + [TapRecognizer, { event: 'doubletap', taps: 2 }, ['tap']], + [PressRecognizer] + ], + + /** + * Some CSS properties can be used to improve the working of Hammer. + * Add them to this method and they will be set when creating a new Manager. + * @namespace + */ + cssProps: { + /** + * Disables text selection to improve the dragging gesture. Mainly for desktop browsers. + * @type {String} + * @default 'none' + */ + userSelect: 'none', - exports['default'] = Text; - module.exports = exports['default']; + /** + * Disable the Windows Phone grippers when pressing an element. + * @type {String} + * @default 'none' + */ + touchSelect: 'none', -/***/ }, -/* 84 */ -/***/ function(module, exports, __webpack_require__) { + /** + * Disables the default callout shown when you touch and hold a touch target. + * On iOS, when you touch and hold a touch target such as a link, Safari displays + * a callout containing information about the link. This property allows you to disable that callout. + * @type {String} + * @default 'none' + */ + touchCallout: 'none', - 'use strict'; + /** + * Specifies whether zooming is enabled. Used by IE10> + * @type {String} + * @default 'none' + */ + contentZooming: 'none', - Object.defineProperty(exports, '__esModule', { - value: true - }); + /** + * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers. + * @type {String} + * @default 'none' + */ + userDrag: 'none', - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + /** + * Overrides the highlight color shown when the user taps a link or a JavaScript + * clickable element in iOS. This property obeys the alpha value, if specified. + * @type {String} + * @default 'rgba(0,0,0,0)' + */ + tapHighlightColor: 'rgba(0,0,0,0)' + } + }; - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + var STOP = 1; + var FORCED_STOP = 2; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + /** + * Manager + * @param {HTMLElement} element + * @param {Object} [options] + * @constructor + */ + function Manager(element, options) { + options = options || {}; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + this.options = merge(options, Hammer.defaults); + this.options.inputTarget = this.options.inputTarget || element; - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + this.handlers = {}; + this.session = {}; + this.recognizers = []; - var _utilShapeBase = __webpack_require__(76); + this.element = element; + this.input = createInputInstance(this); + this.touchAction = new TouchAction(this, this.options.touchAction); - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + toggleCssProps(this, true); - var Triangle = (function (_ShapeBase) { - function Triangle(options, body, labelModule) { - _classCallCheck(this, Triangle); + each(options.recognizers, function(item) { + var recognizer = this.add(new (item[0])(item[1])); + item[2] && recognizer.recognizeWith(item[2]); + item[3] && recognizer.requireFailure(item[3]); + }, this); + } - _get(Object.getPrototypeOf(Triangle.prototype), 'constructor', this).call(this, options, body, labelModule); - } + Manager.prototype = { + /** + * set options + * @param {Object} options + * @returns {Manager} + */ + set: function(options) { + extend(this.options, options); - _inherits(Triangle, _ShapeBase); + // Options that need a little more setup + if (options.touchAction) { + this.touchAction.update(); + } + if (options.inputTarget) { + // Clean up existing event listeners and reinitialize + this.input.destroy(); + this.input.target = options.inputTarget; + this.input.init(); + } + return this; + }, - _createClass(Triangle, [{ - key: 'resize', - value: function resize(ctx) { - this._resizeShape(); - } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'triangle', 3, x, y, selected, hover); - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - return this._distanceToBorder(angle); - } - }]); + /** + * stop recognizing for this session. + * This session will be discarded, when a new [input]start event is fired. + * When forced, the recognizer cycle is stopped immediately. + * @param {Boolean} [force] + */ + stop: function(force) { + this.session.stopped = force ? FORCED_STOP : STOP; + }, - return Triangle; - })(_utilShapeBase2['default']); + /** + * run the recognizers! + * called by the inputHandler function on every movement of the pointers (touches) + * it walks through all the recognizers and tries to detect the gesture that is being made + * @param {Object} inputData + */ + recognize: function(inputData) { + var session = this.session; + if (session.stopped) { + return; + } - exports['default'] = Triangle; - module.exports = exports['default']; + // run the touch-action polyfill + this.touchAction.preventDefaults(inputData); -/***/ }, -/* 85 */ -/***/ function(module, exports, __webpack_require__) { + var recognizer; + var recognizers = this.recognizers; - 'use strict'; + // this holds the recognizer that is being recognized. + // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED + // if no recognizer is detecting a thing, it is set to `null` + var curRecognizer = session.curRecognizer; - Object.defineProperty(exports, '__esModule', { - value: true - }); + // reset when the last recognizer is recognized + // or when we're in a new session + if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) { + curRecognizer = session.curRecognizer = null; + } - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var i = 0; + while (i < recognizers.length) { + recognizer = recognizers[i]; - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + // find out if we are allowed try to recognize the input for this one. + // 1. allow if the session is NOT forced stopped (see the .stop() method) + // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one + // that is being recognized. + // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer. + // this can be setup with the `recognizeWith()` method on the recognizer. + if (session.stopped !== FORCED_STOP && ( // 1 + !curRecognizer || recognizer == curRecognizer || // 2 + recognizer.canRecognizeWith(curRecognizer))) { // 3 + recognizer.recognize(inputData); + } else { + recognizer.reset(); + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the + // current active recognizer. but only if we don't already have an active recognizer + if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) { + curRecognizer = session.curRecognizer = recognizer; + } + i++; + } + }, - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * get a recognizer by its event name. + * @param {Recognizer|String} recognizer + * @returns {Recognizer|Null} + */ + get: function(recognizer) { + if (recognizer instanceof Recognizer) { + return recognizer; + } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + var recognizers = this.recognizers; + for (var i = 0; i < recognizers.length; i++) { + if (recognizers[i].options.event == recognizer) { + return recognizers[i]; + } + } + return null; + }, - var _utilShapeBase = __webpack_require__(76); + /** + * add a recognizer to the manager + * existing recognizers with the same event name will be removed + * @param {Recognizer} recognizer + * @returns {Recognizer|Manager} + */ + add: function(recognizer) { + if (invokeArrayArg(recognizer, 'add', this)) { + return this; + } - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + // remove existing + var existing = this.get(recognizer.options.event); + if (existing) { + this.remove(existing); + } - var TriangleDown = (function (_ShapeBase) { - function TriangleDown(options, body, labelModule) { - _classCallCheck(this, TriangleDown); + this.recognizers.push(recognizer); + recognizer.manager = this; - _get(Object.getPrototypeOf(TriangleDown.prototype), 'constructor', this).call(this, options, body, labelModule); - } + this.touchAction.update(); + return recognizer; + }, - _inherits(TriangleDown, _ShapeBase); + /** + * remove a recognizer by name or instance + * @param {Recognizer|String} recognizer + * @returns {Manager} + */ + remove: function(recognizer) { + if (invokeArrayArg(recognizer, 'remove', this)) { + return this; + } - _createClass(TriangleDown, [{ - key: 'resize', - value: function resize(ctx) { - this._resizeShape(); - } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'triangleDown', 3, x, y, selected, hover); - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - return this._distanceToBorder(angle); - } - }]); + var recognizers = this.recognizers; + recognizer = this.get(recognizer); + recognizers.splice(inArray(recognizers, recognizer), 1); - return TriangleDown; - })(_utilShapeBase2['default']); + this.touchAction.update(); + return this; + }, - exports['default'] = TriangleDown; - module.exports = exports['default']; + /** + * bind event + * @param {String} events + * @param {Function} handler + * @returns {EventEmitter} this + */ + on: function(events, handler) { + var handlers = this.handlers; + each(splitStr(events), function(event) { + handlers[event] = handlers[event] || []; + handlers[event].push(handler); + }); + return this; + }, -/***/ }, -/* 86 */ -/***/ function(module, exports, __webpack_require__) { + /** + * unbind event, leave emit blank to remove all handlers + * @param {String} events + * @param {Function} [handler] + * @returns {EventEmitter} this + */ + off: function(events, handler) { + var handlers = this.handlers; + each(splitStr(events), function(event) { + if (!handler) { + delete handlers[event]; + } else { + handlers[event].splice(inArray(handlers[event], handler), 1); + } + }); + return this; + }, - 'use strict'; + /** + * emit event to the listeners + * @param {String} event + * @param {Object} data + */ + emit: function(event, data) { + // we also want to trigger dom events + if (this.options.domEvents) { + triggerDomEvent(event, data); + } - Object.defineProperty(exports, '__esModule', { - value: true - }); + // no handlers, so skip it all + var handlers = this.handlers[event] && this.handlers[event].slice(); + if (!handlers || !handlers.length) { + return; + } - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + data.type = event; + data.preventDefault = function() { + data.srcEvent.preventDefault(); + }; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var i = 0; + while (i < handlers.length) { + handlers[i](data); + i++; + } + }, - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * destroy the manager and unbinds all events + * it doesn't unbind dom events, that is the user own responsibility + */ + destroy: function() { + this.element && toggleCssProps(this, false); - var _componentsEdge = __webpack_require__(9); + this.handlers = {}; + this.session = {}; + this.input.destroy(); + this.element = null; + } + }; - var _componentsEdge2 = _interopRequireDefault(_componentsEdge); + /** + * add/remove the css properties as defined in manager.options.cssProps + * @param {Manager} manager + * @param {Boolean} add + */ + function toggleCssProps(manager, add) { + var element = manager.element; + each(manager.options.cssProps, function(value, name) { + element.style[prefixed(element.style, name)] = add ? value : ''; + }); + } - var _componentsSharedLabel = __webpack_require__(68); + /** + * trigger dom event + * @param {String} event + * @param {Object} data + */ + function triggerDomEvent(event, data) { + var gestureEvent = document.createEvent('Event'); + gestureEvent.initEvent(event, true, true); + gestureEvent.gesture = data; + data.target.dispatchEvent(gestureEvent); + } - var _componentsSharedLabel2 = _interopRequireDefault(_componentsSharedLabel); + extend(Hammer, { + INPUT_START: INPUT_START, + INPUT_MOVE: INPUT_MOVE, + INPUT_END: INPUT_END, + INPUT_CANCEL: INPUT_CANCEL, - var util = __webpack_require__(2); - var DataSet = __webpack_require__(22); - var DataView = __webpack_require__(24); + STATE_POSSIBLE: STATE_POSSIBLE, + STATE_BEGAN: STATE_BEGAN, + STATE_CHANGED: STATE_CHANGED, + STATE_ENDED: STATE_ENDED, + STATE_RECOGNIZED: STATE_RECOGNIZED, + STATE_CANCELLED: STATE_CANCELLED, + STATE_FAILED: STATE_FAILED, - var EdgesHandler = (function () { - function EdgesHandler(body, images, groups) { - var _this = this; + DIRECTION_NONE: DIRECTION_NONE, + DIRECTION_LEFT: DIRECTION_LEFT, + DIRECTION_RIGHT: DIRECTION_RIGHT, + DIRECTION_UP: DIRECTION_UP, + DIRECTION_DOWN: DIRECTION_DOWN, + DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL, + DIRECTION_VERTICAL: DIRECTION_VERTICAL, + DIRECTION_ALL: DIRECTION_ALL, - _classCallCheck(this, EdgesHandler); + Manager: Manager, + Input: Input, + TouchAction: TouchAction, - this.body = body; - this.images = images; - this.groups = groups; + TouchInput: TouchInput, + MouseInput: MouseInput, + PointerEventInput: PointerEventInput, + TouchMouseInput: TouchMouseInput, + SingleTouchInput: SingleTouchInput, - // create the edge API in the body container - this.body.functions.createEdge = this.create.bind(this); + Recognizer: Recognizer, + AttrRecognizer: AttrRecognizer, + Tap: TapRecognizer, + Pan: PanRecognizer, + Swipe: SwipeRecognizer, + Pinch: PinchRecognizer, + Rotate: RotateRecognizer, + Press: PressRecognizer, - this.edgesListeners = { - add: function add(event, params) { - _this.add(params.items); - }, - update: function update(event, params) { - _this.update(params.items); - }, - remove: function remove(event, params) { - _this.remove(params.items); - } - }; + on: addEventListeners, + off: removeEventListeners, + each: each, + merge: merge, + extend: extend, + inherit: inherit, + bindFn: bindFn, + prefixed: prefixed + }); - this.options = {}; - this.defaultOptions = { - arrows: { - to: { enabled: false, scaleFactor: 1 }, // boolean / {arrowScaleFactor:1} / {enabled: false, arrowScaleFactor:1} - middle: { enabled: false, scaleFactor: 1 }, - from: { enabled: false, scaleFactor: 1 } - }, - color: { - color: '#848484', - highlight: '#848484', - hover: '#848484', - inherit: 'from', - opacity: 1 - }, - dashes: false, - font: { - color: '#343434', - size: 14, // px - face: 'arial', - background: 'none', - strokeWidth: 2, // px - strokeColor: '#ffffff', - align: 'horizontal' - }, - hidden: false, - hoverWidth: 1.5, - label: undefined, - length: undefined, - physics: true, - scaling: { - min: 1, - max: 15, - label: { - enabled: true, - min: 14, - max: 30, - maxVisible: 30, - drawThreshold: 5 - }, - customScalingFunction: function customScalingFunction(min, max, total, value) { - if (max === min) { - return 0.5; - } else { - var scale = 1 / (max - min); - return Math.max(0, (value - min) * scale); - } - } - }, - selectionWidth: 1.5, - selfReferenceSize: 20, - shadow: { - enabled: false, - size: 10, - x: 5, - y: 5 - }, - smooth: { - enabled: true, - type: 'dynamic', - roundness: 0.5 - }, - title: undefined, - width: 1, - value: undefined - }; + if ("function" == TYPE_FUNCTION && __webpack_require__(91)) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { + return Hammer; + }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else if (typeof module != 'undefined' && module.exports) { + module.exports = Hammer; + } else { + window[exportName] = Hammer; + } - util.extend(this.options, this.defaultOptions); + })(window, document, 'Hammer'); - this.bindEventListeners(); - } - _createClass(EdgesHandler, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this2 = this; +/***/ }, +/* 73 */ +/***/ function(module, exports, __webpack_require__) { - // this allows external modules to force all dynamic curves to turn static. - this.body.emitter.on('_forceDisableDynamicCurves', function (type) { - if (type === 'dynamic') { - type = 'continuous'; - } - var emitChange = false; - for (var edgeId in _this2.body.edges) { - if (_this2.body.edges.hasOwnProperty(edgeId)) { - var edge = _this2.body.edges[edgeId]; - var edgeData = _this2.body.data.edges._data[edgeId]; + 'use strict'; - // only forcilby remove the smooth curve if the data has been set of the edge has the smooth curves defined. - // this is because a change in the global would not affect these curves. - if (edgeData !== undefined) { - var edgeOptions = edgeData.smooth; - if (edgeOptions !== undefined) { - if (edgeOptions.enabled === true && edgeOptions.type === 'dynamic') { - if (type === undefined) { - edge.setOptions({ smooth: false }); - } else { - edge.setOptions({ smooth: { type: type } }); - } - emitChange = true; - } - } - } - } - } - if (emitChange === true) { - _this2.body.emitter.emit('_dataChanged'); - } - }); + Object.defineProperty(exports, '__esModule', { + value: true + }); - // this is called when options of EXISTING nodes or edges have changed. - this.body.emitter.on('_dataUpdated', function () { - _this2.reconnectEdges(); - _this2.markAllEdgesAsDirty(); - }); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // refresh the edges. Used when reverting from hierarchical layout - this.body.emitter.on('refreshEdges', this.refresh.bind(this)); - this.body.emitter.on('refresh', this.refresh.bind(this)); - this.body.emitter.on('destroy', function () { - delete _this2.body.functions.createEdge; - delete _this2.edgesListeners.add; - delete _this2.edgesListeners.update; - delete _this2.edgesListeners.remove; - delete _this2.edgesListeners; - }); - } - }, { - key: 'setOptions', - value: function setOptions(options) { - if (options !== undefined) { - // use the parser from the Edge class to fill in all shorthand notations - _componentsEdge2['default'].parseOptions(this.options, options); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - // hanlde multiple input cases for color - if (options.color !== undefined) { - this.markAllEdgesAsDirty(); - } + var Hammer = __webpack_require__(41); + var hammerUtil = __webpack_require__(49); + var util = __webpack_require__(2); - // update smooth settings in all edges - var dataChanged = false; - if (options.smooth !== undefined) { - for (var edgeId in this.body.edges) { - if (this.body.edges.hasOwnProperty(edgeId)) { - dataChanged = this.body.edges[edgeId].updateEdgeType() || dataChanged; - } - } - } + var ColorPicker = (function () { + function ColorPicker() { + var pixelRatio = arguments[0] === undefined ? 1 : arguments[0]; - // update fonts in all edges - if (options.font !== undefined) { - // use the parser from the Label class to fill in all shorthand notations - _componentsSharedLabel2['default'].parseOptions(this.options, options); - for (var edgeId in this.body.edges) { - if (this.body.edges.hasOwnProperty(edgeId)) { - this.body.edges[edgeId].updateLabelModule(); - } - } - } + _classCallCheck(this, ColorPicker); - // update the state of the variables if needed - if (options.hidden !== undefined || options.physics !== undefined || dataChanged === true) { - this.body.emitter.emit('_dataChanged'); - } + this.pixelRatio = pixelRatio; + this.generated = false; + this.centerCoordinates = { x: 289 / 2, y: 289 / 2 }; + this.r = 289 * 0.49; + this.color = { r: 255, g: 255, b: 255, a: 1 }; + this.hueCircle = undefined; + this.initialColor = { r: 255, g: 255, b: 255, a: 1 }; + this.previousColor = undefined; + this.applied = false; + + // bound by + this.updateCallback = function () {}; + + // create all DOM elements + this._create(); + } + + _createClass(ColorPicker, [{ + key: 'insertTo', + + /** + * this inserts the colorPicker into a div from the DOM + * @param container + */ + value: function insertTo(container) { + if (this.hammer !== undefined) { + this.hammer.destroy(); + this.hammer = undefined; } + this.container = container; + this.container.appendChild(this.frame); + this._bindHammer(); + + this._setSize(); } }, { - key: 'setData', + key: 'setCallback', /** - * Load edges by reading the data table - * @param {Array | DataSet | DataView} edges The data containing the edges. - * @private - * @private + * the callback is executed on apply and save. Bind it to the application + * @param callback */ - value: function setData(edges) { - var _this3 = this; - - var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - - var oldEdgesData = this.body.data.edges; - - if (edges instanceof DataSet || edges instanceof DataView) { - this.body.data.edges = edges; - } else if (Array.isArray(edges)) { - this.body.data.edges = new DataSet(); - this.body.data.edges.add(edges); - } else if (!edges) { - this.body.data.edges = new DataSet(); + value: function setCallback(callback) { + if (typeof callback === 'function') { + this.updateCallback = callback; } else { - throw new TypeError('Array or DataSet expected'); + throw new Error('Function attempted to set as colorPicker callback is not a function.'); + } + } + }, { + key: '_isColorString', + value: function _isColorString(color) { + var htmlColors = { black: '#000000', navy: '#000080', darkblue: '#00008B', mediumblue: '#0000CD', blue: '#0000FF', darkgreen: '#006400', green: '#008000', teal: '#008080', darkcyan: '#008B8B', deepskyblue: '#00BFFF', darkturquoise: '#00CED1', mediumspringgreen: '#00FA9A', lime: '#00FF00', springgreen: '#00FF7F', aqua: '#00FFFF', cyan: '#00FFFF', midnightblue: '#191970', dodgerblue: '#1E90FF', lightseagreen: '#20B2AA', forestgreen: '#228B22', seagreen: '#2E8B57', darkslategray: '#2F4F4F', limegreen: '#32CD32', mediumseagreen: '#3CB371', turquoise: '#40E0D0', royalblue: '#4169E1', steelblue: '#4682B4', darkslateblue: '#483D8B', mediumturquoise: '#48D1CC', indigo: '#4B0082', darkolivegreen: '#556B2F', cadetblue: '#5F9EA0', cornflowerblue: '#6495ED', mediumaquamarine: '#66CDAA', dimgray: '#696969', slateblue: '#6A5ACD', olivedrab: '#6B8E23', slategray: '#708090', lightslategray: '#778899', mediumslateblue: '#7B68EE', lawngreen: '#7CFC00', chartreuse: '#7FFF00', aquamarine: '#7FFFD4', maroon: '#800000', purple: '#800080', olive: '#808000', gray: '#808080', skyblue: '#87CEEB', lightskyblue: '#87CEFA', blueviolet: '#8A2BE2', darkred: '#8B0000', darkmagenta: '#8B008B', saddlebrown: '#8B4513', darkseagreen: '#8FBC8F', lightgreen: '#90EE90', mediumpurple: '#9370D8', darkviolet: '#9400D3', palegreen: '#98FB98', darkorchid: '#9932CC', yellowgreen: '#9ACD32', sienna: '#A0522D', brown: '#A52A2A', darkgray: '#A9A9A9', lightblue: '#ADD8E6', greenyellow: '#ADFF2F', paleturquoise: '#AFEEEE', lightsteelblue: '#B0C4DE', powderblue: '#B0E0E6', firebrick: '#B22222', darkgoldenrod: '#B8860B', mediumorchid: '#BA55D3', rosybrown: '#BC8F8F', darkkhaki: '#BDB76B', silver: '#C0C0C0', mediumvioletred: '#C71585', indianred: '#CD5C5C', peru: '#CD853F', chocolate: '#D2691E', tan: '#D2B48C', lightgrey: '#D3D3D3', palevioletred: '#D87093', thistle: '#D8BFD8', orchid: '#DA70D6', goldenrod: '#DAA520', crimson: '#DC143C', gainsboro: '#DCDCDC', plum: '#DDA0DD', burlywood: '#DEB887', lightcyan: '#E0FFFF', lavender: '#E6E6FA', darksalmon: '#E9967A', violet: '#EE82EE', palegoldenrod: '#EEE8AA', lightcoral: '#F08080', khaki: '#F0E68C', aliceblue: '#F0F8FF', honeydew: '#F0FFF0', azure: '#F0FFFF', sandybrown: '#F4A460', wheat: '#F5DEB3', beige: '#F5F5DC', whitesmoke: '#F5F5F5', mintcream: '#F5FFFA', ghostwhite: '#F8F8FF', salmon: '#FA8072', antiquewhite: '#FAEBD7', linen: '#FAF0E6', lightgoldenrodyellow: '#FAFAD2', oldlace: '#FDF5E6', red: '#FF0000', fuchsia: '#FF00FF', magenta: '#FF00FF', deeppink: '#FF1493', orangered: '#FF4500', tomato: '#FF6347', hotpink: '#FF69B4', coral: '#FF7F50', darkorange: '#FF8C00', lightsalmon: '#FFA07A', orange: '#FFA500', lightpink: '#FFB6C1', pink: '#FFC0CB', gold: '#FFD700', peachpuff: '#FFDAB9', navajowhite: '#FFDEAD', moccasin: '#FFE4B5', bisque: '#FFE4C4', mistyrose: '#FFE4E1', blanchedalmond: '#FFEBCD', papayawhip: '#FFEFD5', lavenderblush: '#FFF0F5', seashell: '#FFF5EE', cornsilk: '#FFF8DC', lemonchiffon: '#FFFACD', floralwhite: '#FFFAF0', snow: '#FFFAFA', yellow: '#FFFF00', lightyellow: '#FFFFE0', ivory: '#FFFFF0', white: '#FFFFFF' }; + if (typeof color === 'string') { + return htmlColors[color]; } + } + }, { + key: 'setColor', - // TODO: is this null or undefined or false? - if (oldEdgesData) { - // unsubscribe from old dataset - util.forEach(this.edgesListeners, function (callback, event) { - oldEdgesData.off(event, callback); - }); + /** + * Set the color of the colorPicker + * Supported formats: + * 'red' --> HTML color string + * '#ffffff' --> hex string + * 'rbg(255,255,255)' --> rgb string + * 'rgba(255,255,255,1.0)' --> rgba string + * {r:255,g:255,b:255} --> rgb object + * {r:255,g:255,b:255,a:1.0} --> rgba object + * @param color + * @param setInitial + */ + value: function setColor(color) { + var setInitial = arguments[1] === undefined ? true : arguments[1]; + + if (color === 'none') { + return; } - // remove drawn edges - this.body.edges = {}; + var rgba = undefined; - // TODO: is this null or undefined or false? - if (this.body.data.edges) { - // subscribe to new dataset - util.forEach(this.edgesListeners, function (callback, event) { - _this3.body.data.edges.on(event, callback); - }); + // if a html color shorthand is used, convert to hex + var htmlColor = this._isColorString(color); + if (htmlColor !== undefined) { + color = htmlColor; + } - // draw all new nodes - var ids = this.body.data.edges.getIds(); - this.add(ids, true); + // check format + if (util.isString(color) === true) { + if (util.isValidRGB(color) === true) { + var rgbaArray = color.substr(4).substr(0, color.length - 5).split(','); + rgba = { r: rgbaArray[0], g: rgbaArray[1], b: rgbaArray[2], a: 1 }; + } else if (util.isValidRGBA(color) === true) { + var rgbaArray = color.substr(5).substr(0, color.length - 6).split(','); + rgba = { r: rgbaArray[0], g: rgbaArray[1], b: rgbaArray[2], a: rgbaArray[3] }; + } else if (util.isValidHex(color) === true) { + var rgbObj = util.hexToRGB(color); + rgba = { r: rgbObj.r, g: rgbObj.g, b: rgbObj.b, a: 1 }; + } + } else { + if (color instanceof Object) { + if (color.r !== undefined && color.g !== undefined && color.b !== undefined) { + var alpha = color.a !== undefined ? color.a : '1.0'; + rgba = { r: color.r, g: color.g, b: color.b, a: alpha }; + } + } } - if (doNotEmit === false) { - this.body.emitter.emit('_dataChanged'); + // set color + if (rgba === undefined) { + throw new Error('Unknown color passed to the colorPicker. Supported are strings: rgb, hex, rgba. Object: rgb ({r:r,g:g,b:b,[a:a]}). Supplied: ' + JSON.stringify(color)); + } else { + this._setColor(rgba, setInitial); } } }, { - key: 'add', + key: 'show', /** - * Add edges - * @param {Number[] | String[]} ids - * @private + * this shows the color picker at a location. The hue circle is constructed once and stored. + * @param x + * @param y */ - value: function add(ids) { - var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - - var edges = this.body.edges; - var edgesData = this.body.data.edges; + value: function show(x, y) { + this.applied = false; + this.frame.style.display = 'block'; + this.frame.style.top = y + 'px'; + this.frame.style.left = x + 'px'; + this._generateHueCircle(); + } + }, { + key: '_hide', - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; + // ------------------------------------------ PRIVATE ----------------------------- // - var oldEdge = edges[id]; - if (oldEdge) { - oldEdge.disconnect(); - } + /** + * Hide the picker. Is called by the cancel button. + * Optional boolean to store the previous color for easy access later on. + * @param storePrevious + * @private + */ + value: function _hide() { + var storePrevious = arguments[0] === undefined ? true : arguments[0]; - var data = edgesData.get(id, { 'showInternalIds': true }); - edges[id] = this.create(data); + // store the previous color for next time; + if (storePrevious === true) { + this.previousColor = util.extend({}, this.color); } - if (doNotEmit === false) { - this.body.emitter.emit('_dataChanged'); + if (this.applied === true) { + this.updateCallback(this.initialColor); } + + this.frame.style.display = 'none'; } }, { - key: 'update', + key: '_save', /** - * Update existing edges, or create them when not yet existing - * @param {Number[] | String[]} ids + * bound to the save button. Saves and hides. * @private */ - value: function update(ids) { - var edges = this.body.edges; - var edgesData = this.body.data.edges; - var dataChanged = false; - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; - var data = edgesData.get(id); - var edge = edges[id]; - if (edge === null) { - // update edge - edge.disconnect(); - dataChanged = edge.setOptions(data) || dataChanged; // if a support node is added, data can be changed. - edge.connect(); - } else { - // create edge - this.body.edges[id] = this.create(data); - dataChanged = true; - } - } + value: function _save() { + this.updateCallback(this.color); + this.applied = false; + this._hide(); + } + }, { + key: '_apply', - if (dataChanged === true) { - this.body.emitter.emit('_dataChanged'); + /** + * Bound to apply button. Saves but does not close. Is undone by the cancel button. + * @private + */ + value: function _apply() { + this.applied = true; + this.updateCallback(this.color); + this._updatePicker(this.color); + } + }, { + key: '_loadLast', + + /** + * load the color from the previous session. + * @private + */ + value: function _loadLast() { + if (this.previousColor !== undefined) { + this.setColor(this.previousColor, false); } else { - this.body.emitter.emit('_dataUpdated'); + alert('There is no last color to load...'); } } }, { - key: 'remove', + key: '_setColor', /** - * Remove existing edges. Non existing ids will be ignored - * @param {Number[] | String[]} ids + * set the color, place the picker + * @param rgba + * @param setInitial * @private */ - value: function remove(ids) { - var edges = this.body.edges; - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; - var edge = edges[id]; - if (edge !== undefined) { - if (edge.via != null) { - delete this.body.supportNodes[edge.via.id]; - } - edge.disconnect(); - delete edges[id]; - } + value: function _setColor(rgba) { + var setInitial = arguments[1] === undefined ? true : arguments[1]; + + // store the initial color + if (setInitial === true) { + this.initialColor = util.extend({}, rgba); } - this.body.emitter.emit('_dataChanged'); + this.color = rgba; + var hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b); + + var angleConvert = 2 * Math.PI; + var radius = this.r * hsv.s; + var x = this.centerCoordinates.x + radius * Math.sin(angleConvert * hsv.h); + var y = this.centerCoordinates.y + radius * Math.cos(angleConvert * hsv.h); + + this.colorPickerSelector.style.left = x - 0.5 * this.colorPickerSelector.clientWidth + 'px'; + this.colorPickerSelector.style.top = y - 0.5 * this.colorPickerSelector.clientHeight + 'px'; + + this._updatePicker(rgba); } }, { - key: 'refresh', - value: function refresh() { - var edges = this.body.edges; - for (var edgeId in edges) { - var edge = undefined; - if (edges.hasOwnProperty(edgeId)) { - edge = edges[edgeId]; - } - var data = this.body.data.edges._data[edgeId]; - if (edge !== undefined && data !== undefined) { - edge.setOptions(data); - } - } + key: '_setOpacity', + + /** + * bound to opacity control + * @param value + * @private + */ + value: function _setOpacity(value) { + this.color.a = value / 100; + this._updatePicker(this.color); } }, { - key: 'create', - value: function create(properties) { - return new _componentsEdge2['default'](properties, this.body, this.options); + key: '_setBrightness', + + /** + * bound to brightness control + * @param value + * @private + */ + value: function _setBrightness(value) { + var hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b); + hsv.v = value / 100; + var rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v); + rgba['a'] = this.color.a; + this.color = rgba; + this._updatePicker(); } }, { - key: 'markAllEdgesAsDirty', - value: function markAllEdgesAsDirty() { - for (var edgeId in this.body.edges) { - this.body.edges[edgeId].edgeType.colorDirty = true; + key: '_updatePicker', + + /** + * update the colorpicker. A black circle overlays the hue circle to mimic the brightness decreasing. + * @param rgba + * @private + */ + value: function _updatePicker() { + var rgba = arguments[0] === undefined ? this.color : arguments[0]; + + var hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b); + var ctx = this.colorPickerCanvas.getContext('2d'); + if (this.pixelRation === undefined) { + this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); } + ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); + + // clear the canvas + var w = this.colorPickerCanvas.clientWidth; + var h = this.colorPickerCanvas.clientHeight; + ctx.clearRect(0, 0, w, h); + + ctx.putImageData(this.hueCircle, 0, 0); + ctx.fillStyle = 'rgba(0,0,0,' + (1 - hsv.v) + ')'; + ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r); + ctx.fill(); + + this.brightnessRange.value = 100 * hsv.v; + this.opacityRange.value = 100 * rgba.a; + + this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')'; + this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')'; } }, { - key: 'reconnectEdges', + key: '_setSize', /** - * Reconnect all edges + * used by create to set the size of the canvas. * @private */ - value: function reconnectEdges() { - var id; - var nodes = this.body.nodes; - var edges = this.body.edges; + value: function _setSize() { + this.colorPickerCanvas.style.width = '100%'; + this.colorPickerCanvas.style.height = '100%'; - for (id in nodes) { - if (nodes.hasOwnProperty(id)) { - nodes[id].edges = []; - } + this.colorPickerCanvas.width = 289 * this.pixelRatio; + this.colorPickerCanvas.height = 289 * this.pixelRatio; + } + }, { + key: '_create', + + /** + * create all dom elements + * TODO: cleanup, lots of similar dom elements + * @private + */ + value: function _create() { + this.frame = document.createElement('div'); + this.frame.className = 'vis-color-picker'; + + this.colorPickerDiv = document.createElement('div'); + this.colorPickerSelector = document.createElement('div'); + this.colorPickerSelector.className = 'vis-selector'; + this.colorPickerDiv.appendChild(this.colorPickerSelector); + + this.colorPickerCanvas = document.createElement('canvas'); + this.colorPickerDiv.appendChild(this.colorPickerCanvas); + + if (!this.colorPickerCanvas.getContext) { + var noCanvas = document.createElement('DIV'); + noCanvas.style.color = 'red'; + noCanvas.style.fontWeight = 'bold'; + noCanvas.style.padding = '10px'; + noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; + this.colorPickerCanvas.appendChild(noCanvas); + } else { + var ctx = this.colorPickerCanvas.getContext('2d'); + this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + + this.colorPickerCanvas.getContext('2d').setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); } - for (id in edges) { - if (edges.hasOwnProperty(id)) { - var edge = edges[id]; - edge.from = null; - edge.to = null; - edge.connect(); - } - } - } - }, { - key: 'getConnectedNodes', - value: function getConnectedNodes(edgeId) { - var nodeList = []; - if (this.body.edges[edgeId] !== undefined) { - var edge = this.body.edges[edgeId]; - if (edge.fromId) { - nodeList.push(edge.fromId); - } - if (edge.toId) { - nodeList.push(edge.toId); - } - } - return nodeList; - } - }]); + this.colorPickerDiv.className = 'vis-color'; - return EdgesHandler; - })(); + this.opacityDiv = document.createElement('div'); + this.opacityDiv.className = 'vis-opacity'; - exports['default'] = EdgesHandler; - module.exports = exports['default']; + this.brightnessDiv = document.createElement('div'); + this.brightnessDiv.className = 'vis-brightness'; -/***/ }, -/* 87 */ -/***/ function(module, exports, __webpack_require__) { + this.arrowDiv = document.createElement('div'); + this.arrowDiv.className = 'vis-arrow'; - 'use strict'; + this.opacityRange = document.createElement('input'); + this.opacityRange.type = 'range'; + this.opacityRange.min = '0'; + this.opacityRange.max = '100'; + this.opacityRange.value = '100'; + this.opacityRange.className = 'vis-range'; - Object.defineProperty(exports, '__esModule', { - value: true - }); + this.brightnessRange = document.createElement('input'); + this.brightnessRange.type = 'range'; + this.brightnessRange.min = '0'; + this.brightnessRange.max = '100'; + this.brightnessRange.value = '100'; + this.brightnessRange.className = 'vis-range'; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + this.opacityDiv.appendChild(this.opacityRange); + this.brightnessDiv.appendChild(this.brightnessRange); - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + var me = this; + this.opacityRange.onchange = function () { + me._setOpacity(this.value); + }; + this.opacityRange.oninput = function () { + me._setOpacity(this.value); + }; + this.brightnessRange.onchange = function () { + me._setBrightness(this.value); + }; + this.brightnessRange.oninput = function () { + me._setBrightness(this.value); + }; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + this.brightnessLabel = document.createElement('div'); + this.brightnessLabel.className = 'vis-label vis-brightness'; + this.brightnessLabel.innerHTML = 'brightness:'; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + this.opacityLabel = document.createElement('div'); + this.opacityLabel.className = 'vis-label vis-opacity'; + this.opacityLabel.innerHTML = 'opacity:'; - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + this.newColorDiv = document.createElement('div'); + this.newColorDiv.className = 'vis-new-color'; + this.newColorDiv.innerHTML = 'new'; - var _utilBezierEdgeBase = __webpack_require__(88); + this.initialColorDiv = document.createElement('div'); + this.initialColorDiv.className = 'vis-initial-color'; + this.initialColorDiv.innerHTML = 'initial'; - var _utilBezierEdgeBase2 = _interopRequireDefault(_utilBezierEdgeBase); + this.cancelButton = document.createElement('div'); + this.cancelButton.className = 'vis-button vis-cancel'; + this.cancelButton.innerHTML = 'cancel'; + this.cancelButton.onclick = this._hide.bind(this, false); - var BezierEdgeDynamic = (function (_BezierEdgeBase) { - function BezierEdgeDynamic(options, body, labelModule) { - _classCallCheck(this, BezierEdgeDynamic); + this.applyButton = document.createElement('div'); + this.applyButton.className = 'vis-button vis-apply'; + this.applyButton.innerHTML = 'apply'; + this.applyButton.onclick = this._apply.bind(this); - //this.via = undefined; // Here for completeness but not allowed to defined before super() is invoked. - _get(Object.getPrototypeOf(BezierEdgeDynamic.prototype), 'constructor', this).call(this, options, body, labelModule); // --> this calls the setOptions below - } + this.saveButton = document.createElement('div'); + this.saveButton.className = 'vis-button vis-save'; + this.saveButton.innerHTML = 'save'; + this.saveButton.onclick = this._save.bind(this); - _inherits(BezierEdgeDynamic, _BezierEdgeBase); + this.loadButton = document.createElement('div'); + this.loadButton.className = 'vis-button vis-load'; + this.loadButton.innerHTML = 'load last'; + this.loadButton.onclick = this._loadLast.bind(this); - _createClass(BezierEdgeDynamic, [{ - key: 'setOptions', - value: function setOptions(options) { - this.options = options; - this.id = this.options.id; - this.setupSupportNode(); - this.connect(); - } - }, { - key: 'connect', - value: function connect() { - this.from = this.body.nodes[this.options.from]; - this.to = this.body.nodes[this.options.to]; - if (this.from === undefined || this.to === undefined) { - this.via.setOptions({ physics: false }); - } else { - // fix weird behaviour where a selfreferencing node has physics enabled - if (this.from.id === this.to.id) { - this.via.setOptions({ physics: false }); - } else { - this.via.setOptions({ physics: true }); - } - } - } - }, { - key: 'cleanup', - value: function cleanup() { - if (this.via !== undefined) { - delete this.body.nodes[this.via.id]; - this.via = undefined; - return true; - } - return false; - } - }, { - key: 'togglePhysics', - value: function togglePhysics(status) { - this.via.setOptions({ physics: status }); + this.frame.appendChild(this.colorPickerDiv); + this.frame.appendChild(this.arrowDiv); + this.frame.appendChild(this.brightnessLabel); + this.frame.appendChild(this.brightnessDiv); + this.frame.appendChild(this.opacityLabel); + this.frame.appendChild(this.opacityDiv); + this.frame.appendChild(this.newColorDiv); + this.frame.appendChild(this.initialColorDiv); + + this.frame.appendChild(this.cancelButton); + this.frame.appendChild(this.applyButton); + this.frame.appendChild(this.saveButton); + this.frame.appendChild(this.loadButton); } }, { - key: 'setupSupportNode', + key: '_bindHammer', /** - * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but - * are used for the force calculation. - * - * The changed data is not called, if needed, it is returned by the main edge constructor. + * bind hammer to the color picker * @private */ - value: function setupSupportNode() { - if (this.via === undefined) { - var nodeId = 'edgeId:' + this.id; - var node = this.body.functions.createNode({ - id: nodeId, - shape: 'circle', - physics: true, - hidden: true - }); - this.body.nodes[nodeId] = node; - this.via = node; - this.via.parentEdgeId = this.id; - this.positionBezierNode(); - } - } - }, { - key: 'positionBezierNode', - value: function positionBezierNode() { - if (this.via !== undefined && this.from !== undefined && this.to !== undefined) { - this.via.x = 0.5 * (this.from.x + this.to.x); - this.via.y = 0.5 * (this.from.y + this.to.y); - } else if (this.via !== undefined) { - this.via.x = 0; - this.via.y = 0; - } + value: function _bindHammer() { + var _this = this; + + this.drag = {}; + this.pinch = {}; + this.hammer = new Hammer(this.colorPickerCanvas); + this.hammer.get('pinch').set({ enable: true }); + + hammerUtil.onTouch(this.hammer, function (event) { + _this._moveSelector(event); + }); + this.hammer.on('tap', function (event) { + _this._moveSelector(event); + }); + this.hammer.on('panstart', function (event) { + _this._moveSelector(event); + }); + this.hammer.on('panmove', function (event) { + _this._moveSelector(event); + }); + this.hammer.on('panend', function (event) { + _this._moveSelector(event); + }); } }, { - key: '_line', + key: '_generateHueCircle', /** - * Draw a line between two nodes - * @param {CanvasRenderingContext2D} ctx + * generate the hue circle. This is relatively heavy (200ms) and is done only once on the first time it is shown. * @private */ - value: function _line(ctx) { - // draw a straight line - ctx.beginPath(); - ctx.moveTo(this.from.x, this.from.y); - ctx.quadraticCurveTo(this.via.x, this.via.y, this.to.x, this.to.y); - // draw shadow if enabled - this.enableShadow(ctx); - ctx.stroke(); - this.disableShadow(ctx); - return this.via; + value: function _generateHueCircle() { + if (this.generated === false) { + var ctx = this.colorPickerCanvas.getContext('2d'); + if (this.pixelRation === undefined) { + this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + } + ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); + + // clear the canvas + var w = this.colorPickerCanvas.clientWidth; + var h = this.colorPickerCanvas.clientHeight; + ctx.clearRect(0, 0, w, h); + + // draw hue circle + var x = undefined, + y = undefined, + hue = undefined, + sat = undefined; + this.centerCoordinates = { x: w * 0.5, y: h * 0.5 }; + this.r = 0.49 * w; + var angleConvert = 2 * Math.PI / 360; + var hfac = 1 / 360; + var sfac = 1 / this.r; + var rgb = undefined; + for (hue = 0; hue < 360; hue++) { + for (sat = 0; sat < this.r; sat++) { + x = this.centerCoordinates.x + sat * Math.sin(angleConvert * hue); + y = this.centerCoordinates.y + sat * Math.cos(angleConvert * hue); + rgb = util.HSVToRGB(hue * hfac, sat * sfac, 1); + ctx.fillStyle = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')'; + ctx.fillRect(x - 0.5, y - 0.5, 2, 2); + } + } + ctx.strokeStyle = 'rgba(0,0,0,1)'; + ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r); + ctx.stroke(); + + this.hueCircle = ctx.getImageData(0, 0, w, h); + } + this.generated = true; } }, { - key: 'getPoint', + key: '_moveSelector', /** - * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way - * @param percentage - * @param via - * @returns {{x: number, y: number}} + * move the selector. This is called by hammer functions. + * + * @param event * @private */ - value: function getPoint(percentage) { - var t = percentage; - var x = Math.pow(1 - t, 2) * this.from.x + 2 * t * (1 - t) * this.via.x + Math.pow(t, 2) * this.to.x; - var y = Math.pow(1 - t, 2) * this.from.y + 2 * t * (1 - t) * this.via.y + Math.pow(t, 2) * this.to.y; + value: function _moveSelector(event) { + var rect = this.colorPickerDiv.getBoundingClientRect(); + var left = event.center.x - rect.left; + var top = event.center.y - rect.top; - return { x: x, y: y }; - } - }, { - key: '_findBorderPosition', - value: function _findBorderPosition(nearNode, ctx) { - return this._findBorderPositionBezier(nearNode, ctx, this.via); - } - }, { - key: '_getDistanceToEdge', - value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) { - // x3,y3 is the point - return this._getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, this.via); + var centerY = 0.5 * this.colorPickerDiv.clientHeight; + var centerX = 0.5 * this.colorPickerDiv.clientWidth; + + var x = left - centerX; + var y = top - centerY; + + var angle = Math.atan2(x, y); + var radius = 0.98 * Math.min(Math.sqrt(x * x + y * y), centerX); + + var newTop = Math.cos(angle) * radius + centerY; + var newLeft = Math.sin(angle) * radius + centerX; + + this.colorPickerSelector.style.top = newTop - 0.5 * this.colorPickerSelector.clientHeight + 'px'; + this.colorPickerSelector.style.left = newLeft - 0.5 * this.colorPickerSelector.clientWidth + 'px'; + + // set color + var h = angle / (2 * Math.PI); + h = h < 0 ? h + 1 : h; + var s = radius / this.r; + var hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b); + hsv.h = h; + hsv.s = s; + var rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v); + rgba['a'] = this.color.a; + this.color = rgba; + + // update previews + this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')'; + this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')'; } }]); - return BezierEdgeDynamic; - })(_utilBezierEdgeBase2['default']); + return ColorPicker; + })(); - exports['default'] = BezierEdgeDynamic; + exports['default'] = ColorPicker; module.exports = exports['default']; /***/ }, -/* 88 */ +/* 74 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -33616,737 +34949,516 @@ return /******/ (function(modules) { // webpackBootstrap var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + var _sharedLabel = __webpack_require__(75); - var _EdgeBase2 = __webpack_require__(89); + var _sharedLabel2 = _interopRequireDefault(_sharedLabel); - var _EdgeBase3 = _interopRequireDefault(_EdgeBase2); + var _nodesShapesBox = __webpack_require__(92); - var BezierEdgeBase = (function (_EdgeBase) { - function BezierEdgeBase(options, body, labelModule) { - _classCallCheck(this, BezierEdgeBase); + var _nodesShapesBox2 = _interopRequireDefault(_nodesShapesBox); - _get(Object.getPrototypeOf(BezierEdgeBase.prototype), 'constructor', this).call(this, options, body, labelModule); - } + var _nodesShapesCircle = __webpack_require__(93); - _inherits(BezierEdgeBase, _EdgeBase); + var _nodesShapesCircle2 = _interopRequireDefault(_nodesShapesCircle); - _createClass(BezierEdgeBase, [{ - key: '_findBorderPositionBezier', + var _nodesShapesCircularImage = __webpack_require__(94); - /** - * This function uses binary search to look for the point where the bezier curve crosses the border of the node. - * - * @param nearNode - * @param ctx - * @param viaNode - * @param nearNode - * @param ctx - * @param viaNode - * @param nearNode - * @param ctx - * @param viaNode - */ - value: function _findBorderPositionBezier(nearNode, ctx) { - var viaNode = arguments[2] === undefined ? this._getViaCoordinates() : arguments[2]; + var _nodesShapesCircularImage2 = _interopRequireDefault(_nodesShapesCircularImage); - 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; - } + var _nodesShapesDatabase = __webpack_require__(95); - while (low <= high && iteration < maxIterations) { - var middle = (low + high) * 0.5; + var _nodesShapesDatabase2 = _interopRequireDefault(_nodesShapesDatabase); - 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; - } - } + var _nodesShapesDiamond = __webpack_require__(96); - iteration++; - } - pos.t = middle; + var _nodesShapesDiamond2 = _interopRequireDefault(_nodesShapesDiamond); - return pos; - } - }, { - key: '_getDistanceToBezierEdge', + var _nodesShapesDot = __webpack_require__(97); - /** - * 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 - * @param {number} y1 - * @param {number} x2 - * @param {number} y2 - * @param {number} x3 - * @param {number} y3 - * @private - */ - value: function _getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via) { - // x3,y3 is the point - var xVia = undefined, - yVia = undefined; - xVia = via.x; - yVia = via.y; - var minDistance = 1000000000; - var distance = undefined; - var i = undefined, - t = undefined, - x = undefined, - y = undefined; - 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) * xVia + Math.pow(t, 2) * x2; - y = Math.pow(1 - t, 2) * y1 + 2 * t * (1 - t) * yVia + 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; - } + var _nodesShapesDot2 = _interopRequireDefault(_nodesShapesDot); - return minDistance; - } - }]); + var _nodesShapesEllipse = __webpack_require__(98); - return BezierEdgeBase; - })(_EdgeBase3['default']); + var _nodesShapesEllipse2 = _interopRequireDefault(_nodesShapesEllipse); - exports['default'] = BezierEdgeBase; - module.exports = exports['default']; + var _nodesShapesIcon = __webpack_require__(99); -/***/ }, -/* 89 */ -/***/ function(module, exports, __webpack_require__) { + var _nodesShapesIcon2 = _interopRequireDefault(_nodesShapesIcon); - 'use strict'; + var _nodesShapesImage = __webpack_require__(100); - Object.defineProperty(exports, '__esModule', { - value: true - }); + var _nodesShapesImage2 = _interopRequireDefault(_nodesShapesImage); + + var _nodesShapesSquare = __webpack_require__(101); + + var _nodesShapesSquare2 = _interopRequireDefault(_nodesShapesSquare); + + var _nodesShapesStar = __webpack_require__(102); + + var _nodesShapesStar2 = _interopRequireDefault(_nodesShapesStar); + + var _nodesShapesText = __webpack_require__(103); + + var _nodesShapesText2 = _interopRequireDefault(_nodesShapesText); + + var _nodesShapesTriangle = __webpack_require__(104); + + var _nodesShapesTriangle2 = _interopRequireDefault(_nodesShapesTriangle); + + var _nodesShapesTriangleDown = __webpack_require__(105); + + var _nodesShapesTriangleDown2 = _interopRequireDefault(_nodesShapesTriangleDown); + + var _sharedValidator = __webpack_require__(46); + + var _sharedValidator2 = _interopRequireDefault(_sharedValidator); + + var util = __webpack_require__(2); + + /** + * @class Node + * A node. A node can be connected to other nodes via one or multiple edges. + * @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, available: + * "database", "circle", "ellipse", + * "box", "image", "text", "dot", + * "star", "triangle", "triangleDown", + * "square", "icon" + * {string} image An image url + * {string} title An title text, can be HTML + * {anytype} group A group name or number + * @param {Network.Images} imagelist A list with images. Only needed + * when the node has an image + * @param {Network.Groups} grouplist A list with groups. Needed for + * retrieving group options + * @param {Object} constants An object with default values for + * example for the color + * + */ - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var Node = (function () { + function Node(options, body, imagelist, grouplist, globalOptions) { + _classCallCheck(this, Node); - function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _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; } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } } + this.options = util.bridgeObject(globalOptions); + this.body = body; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + this.edges = []; // all edges connected to this node - var util = __webpack_require__(2); + // set defaults for the options + this.id = undefined; + this.imagelist = imagelist; + this.grouplist = grouplist; - var EdgeBase = (function () { - function EdgeBase(options, body, labelModule) { - _classCallCheck(this, EdgeBase); + // 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.body = body; - this.labelModule = labelModule; + this.labelModule = new _sharedLabel2['default'](this.body, this.options); this.setOptions(options); - this.colorDirty = true; - this.color = {}; - this.selectionWidth = 2; - this.hoverWidth = 1.5; } - _createClass(EdgeBase, [{ - key: 'connect', - value: function connect() {} - }, { - key: 'cleanup', - value: function cleanup() { - return false; + _createClass(Node, [{ + key: 'attachEdge', + + /** + * Attach a edge to the node + * @param {Edge} edge + */ + value: function attachEdge(edge) { + if (this.edges.indexOf(edge) === -1) { + this.edges.push(edge); + } } }, { - key: 'setOptions', - value: function setOptions(options) { - this.options = options; - this.from = this.body.nodes[this.options.from]; - this.to = this.body.nodes[this.options.to]; - this.id = this.options.id; + key: 'detachEdge', + + /** + * Detach a edge from the node + * @param {Edge} edge + */ + value: function detachEdge(edge) { + var index = this.edges.indexOf(edge); + if (index != -1) { + this.edges.splice(index, 1); + } } }, { key: 'togglePhysics', /** - * overloadable if the shape has to toggle the via node to disabled + * Enable or disable the physics. * @param status */ - value: function togglePhysics(status) {} + value: function togglePhysics(status) { + this.options.physics = status; + } }, { - key: 'drawLine', + key: 'setOptions', /** - * Redraw a edge as a line - * Draw this edge in the given canvas - * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); - * @param {CanvasRenderingContext2D} ctx - * @private + * Set or overwrite options for the node + * @param {Object} options an object with options + * @param {Object} constants and object with default, global options */ - value: function drawLine(ctx, selected, hover) { - // set style - ctx.strokeStyle = this.getColor(ctx, selected, hover); - ctx.lineWidth = this.getLineWidth(selected, hover); - var via = undefined; - if (this.options.dashes !== false) { - via = this._drawDashedLine(ctx); - } else { - via = this._drawLine(ctx); + value: function setOptions(options) { + if (!options) { + return; + } + // basic options + if (options.id !== undefined) { + this.id = options.id; } - return via; - } - }, { - key: '_drawLine', - value: function _drawLine(ctx) { - var via = undefined; - if (this.from != this.to) { - // draw line - via = this._line(ctx); - } else { - var _getCircleData = this._getCircleData(ctx); - - var _getCircleData2 = _slicedToArray(_getCircleData, 3); - var x = _getCircleData2[0]; - var y = _getCircleData2[1]; - var radius = _getCircleData2[2]; + if (this.id === undefined) { + throw 'Node must have an id'; + } - this._circle(ctx, x, y, radius); + // set these options locally + if (options.x !== undefined) { + this.x = parseInt(options.x);this.predefinedPosition = true; } - return via; - } - }, { - key: '_drawDashedLine', - value: function _drawDashedLine(ctx) { - var via = undefined; - ctx.lineCap = 'round'; - var pattern = [5, 5]; - if (Array.isArray(this.options.dashes) === true) { - pattern = this.options.dashes; + if (options.y !== undefined) { + this.y = parseInt(options.y);this.predefinedPosition = true; + } + if (options.size !== undefined) { + this.baseSize = options.size; + } + if (options.value !== undefined) { + options.value = parseInt(options.value); } - // only firefox and chrome support this method, else we use the legacy one. - if (ctx.setLineDash !== undefined) { - ctx.save(); + // copy group options + if (typeof options.group === 'number' || typeof options.group === 'string' && options.group != '') { + var groupObj = this.grouplist.get(options.group); + util.deepExtend(this.options, groupObj); + // the color object needs to be completely defined. Since groups can partially overwrite the colors, we parse it again, just in case. + this.options.color = util.parseColor(this.options.color); + } - // set dash settings for chrome or firefox - ctx.setLineDash(pattern); - ctx.lineDashOffset = 0; + // this transforms all shorthands into fully defined options + Node.parseOptions(this.options, options, true); - // draw the line - if (this.from != this.to) { - // draw line - via = this._line(ctx); + // load the images + if (this.options.image !== undefined && this.options.image != '') { + if (this.imagelist) { + this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage, this.id); } else { - var _getCircleData3 = this._getCircleData(ctx); - - var _getCircleData32 = _slicedToArray(_getCircleData3, 3); - - var x = _getCircleData32[0]; - var y = _getCircleData32[1]; - var radius = _getCircleData32[2]; - - this._circle(ctx, x, y, radius); + throw 'No imagelist provided'; } + } - // restore the dash settings. - ctx.setLineDash([0]); - ctx.lineDashOffset = 0; - ctx.restore(); - } else { - // unsupporting smooth lines - - if (this.from != this.to) { - // draw line - ctx.dashedLine(this.from.x, this.from.y, this.to.x, this.to.y, pattern); - } else { - var _getCircleData4 = this._getCircleData(ctx); - - var _getCircleData42 = _slicedToArray(_getCircleData4, 3); - - var x = _getCircleData42[0]; - var y = _getCircleData42[1]; - var radius = _getCircleData42[2]; - - this._circle(ctx, x, y, radius); - } - // draw shadow if enabled - this.enableShadow(ctx); + this.updateShape(); + this.updateLabelModule(); - ctx.stroke(); + // reset the size of the node, this can be changed + this._reset(); - // disable shadows for other elements. - this.disableShadow(ctx); + if (options.hidden !== undefined || options.physics !== undefined) { + return true; } - return via; + return false; } }, { - key: 'findBorderPosition', - value: function findBorderPosition(nearNode, ctx, options) { - if (this.from != this.to) { - return this._findBorderPosition(nearNode, ctx, options); - } else { - return this._findBorderPositionCircle(nearNode, ctx, options); + key: 'updateLabelModule', + value: function updateLabelModule() { + if (this.options.label === undefined || this.options.label === null) { + this.options.label = ''; + } + this.labelModule.setOptions(this.options, true); + if (this.labelModule.baseSize !== undefined) { + this.baseFontSize = this.labelModule.baseSize; } } }, { - key: 'findBorderPositions', - value: function findBorderPositions(ctx) { - var from = {}; - var to = {}; - if (this.from != this.to) { - from = this._findBorderPosition(this.from, ctx); - to = this._findBorderPosition(this.to, ctx); - } else { - var _getCircleData5 = this._getCircleData(ctx); - - var _getCircleData52 = _slicedToArray(_getCircleData5, 3); - - var x = _getCircleData52[0]; - var y = _getCircleData52[1]; - var radius = _getCircleData52[2]; - - from = this._findBorderPositionCircle(this.from, ctx, { x: x, y: y, low: 0.25, high: 0.6, direction: -1 }); - to = this._findBorderPositionCircle(this.from, ctx, { x: x, y: y, low: 0.6, high: 0.8, direction: 1 }); + key: 'updateShape', + value: function updateShape() { + // choose draw method depending on the shape + switch (this.options.shape) { + case 'box': + this.shape = new _nodesShapesBox2['default'](this.options, this.body, this.labelModule); + break; + case 'circle': + this.shape = new _nodesShapesCircle2['default'](this.options, this.body, this.labelModule); + break; + case 'circularImage': + this.shape = new _nodesShapesCircularImage2['default'](this.options, this.body, this.labelModule, this.imageObj); + break; + case 'database': + this.shape = new _nodesShapesDatabase2['default'](this.options, this.body, this.labelModule); + break; + case 'diamond': + this.shape = new _nodesShapesDiamond2['default'](this.options, this.body, this.labelModule); + break; + case 'dot': + this.shape = new _nodesShapesDot2['default'](this.options, this.body, this.labelModule); + break; + case 'ellipse': + this.shape = new _nodesShapesEllipse2['default'](this.options, this.body, this.labelModule); + break; + case 'icon': + this.shape = new _nodesShapesIcon2['default'](this.options, this.body, this.labelModule); + break; + case 'image': + this.shape = new _nodesShapesImage2['default'](this.options, this.body, this.labelModule, this.imageObj); + break; + case 'square': + this.shape = new _nodesShapesSquare2['default'](this.options, this.body, this.labelModule); + break; + case 'star': + this.shape = new _nodesShapesStar2['default'](this.options, this.body, this.labelModule); + break; + case 'text': + this.shape = new _nodesShapesText2['default'](this.options, this.body, this.labelModule); + break; + case 'triangle': + this.shape = new _nodesShapesTriangle2['default'](this.options, this.body, this.labelModule); + break; + case 'triangleDown': + this.shape = new _nodesShapesTriangleDown2['default'](this.options, this.body, this.labelModule); + break; + default: + this.shape = new _nodesShapesEllipse2['default'](this.options, this.body, this.labelModule); + break; } - return { from: from, to: to }; + this._reset(); } }, { - key: '_getCircleData', - value: function _getCircleData(ctx) { - var x = undefined, - y = undefined; - var node = this.from; - var radius = this.options.selfReferenceSize; - - if (ctx !== undefined) { - if (node.shape.width === undefined) { - node.shape.resize(ctx); - } - } + key: 'select', - // get circle coordinates - if (node.shape.width > node.shape.height) { - x = node.x + node.shape.width * 0.5; - y = node.y - radius; - } else { - x = node.x + radius; - y = node.y - node.shape.height * 0.5; - } - return [x, y, radius]; + /** + * select this node + */ + value: function select() { + this.selected = true; + this._reset(); } }, { - key: '_pointOnCircle', + key: 'unselect', /** - * 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 + * unselect this node */ - 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) - }; + value: function unselect() { + this.selected = false; + this._reset(); } }, { - key: '_findBorderPositionCircle', + key: '_reset', /** - * This function uses binary search to look for the point where the circle crosses the border of the node. - * @param node - * @param ctx - * @param options - * @returns {*} + * Reset the calculated size of the node, forces it to recalculate its size * @private */ - value: function _findBorderPositionCircle(node, ctx, options) { - var x = options.x; - var y = options.y; - var low = options.low; - var high = options.high; - var direction = options.direction; - - var maxIterations = 10; - var iteration = 0; - var radius = this.options.selfReferenceSize; - var pos = undefined, - angle = undefined, - distanceToBorder = undefined, - distanceToPoint = undefined, - difference = undefined; - var threshold = 0.05; - var middle = (low + high) * 0.5; - - while (low <= high && iteration < maxIterations) { - middle = (low + high) * 0.5; - - pos = this._pointOnCircle(x, y, radius, middle); - 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 (direction > 0) { - low = middle; - } else { - high = middle; - } - } else { - if (direction > 0) { - high = middle; - } else { - low = middle; - } - } - iteration++; - } - pos.t = middle; - - return pos; + value: function _reset() { + this.shape.width = undefined; + this.shape.height = undefined; } }, { - key: 'getLineWidth', + key: 'getTitle', /** - * Get the line width of the edge. Depends on width and whether one of the - * connected nodes is selected. - * @return {Number} width - * @private + * get the title of this node. + * @return {string} title The title of the node, or undefined when no title + * has been set. */ - value: function getLineWidth(selected, hover) { - if (selected === true) { - return Math.max(this.selectionWidth, 0.3 / this.body.view.scale); - } else { - if (hover === true) { - return Math.max(this.hoverWidth, 0.3 / this.body.view.scale); - } else { - return Math.max(this.options.width, 0.3 / this.body.view.scale); - } - } + value: function getTitle() { + return this.options.title; } }, { - key: 'getColor', - value: function getColor(ctx, selected, hover) { - var colorOptions = this.options.color; - if (colorOptions.inherit !== false) { - // when this is a loop edge, just use the 'from' method - if (colorOptions.inherit === 'both' && this.from.id !== this.to.id) { - var grd = ctx.createLinearGradient(this.from.x, this.from.y, this.to.x, this.to.y); - var fromColor = undefined, - toColor = undefined; - fromColor = this.from.options.color.highlight.border; - toColor = this.to.options.color.highlight.border; + key: 'distanceToBorder', - if (this.from.selected === false && this.to.selected === false) { - fromColor = util.overrideOpacity(this.from.options.color.border, this.options.color.opacity); - toColor = util.overrideOpacity(this.to.options.color.border, this.options.color.opacity); - } else if (this.from.selected === true && this.to.selected === false) { - toColor = this.to.options.color.border; - } else if (this.from.selected === false && this.to.selected === true) { - fromColor = this.from.options.color.border; - } - grd.addColorStop(0, fromColor); - grd.addColorStop(1, toColor); + /** + * 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 + */ + value: function distanceToBorder(ctx, angle) { + return this.shape.distanceToBorder(ctx, angle); + } + }, { + key: 'isFixed', - // -------------------- this returns -------------------- // - return grd; - } + /** + * Check if this node has a fixed x and y position + * @return {boolean} true if fixed, false if not + */ + value: function isFixed() { + return this.options.fixed.x && this.options.fixed.y; + } + }, { + key: 'isSelected', - if (this.colorDirty === true) { - if (colorOptions.inherit === 'to') { - this.color.highlight = this.to.options.color.highlight.border; - this.color.hover = this.to.options.color.hover.border; - this.color.color = util.overrideOpacity(this.to.options.color.border, colorOptions.opacity); - } else { - // (this.options.color.inherit.source === "from") { - this.color.highlight = this.from.options.color.highlight.border; - this.color.hover = this.from.options.color.hover.border; - this.color.color = util.overrideOpacity(this.from.options.color.border, colorOptions.opacity); - } - } - } else if (this.colorDirty === true) { - this.color.highlight = colorOptions.highlight; - this.color.hover = colorOptions.hover; - this.color.color = util.overrideOpacity(colorOptions.color, colorOptions.opacity); - } + /** + * check if this node is selecte + * @return {boolean} selected True if node is selected, else false + */ + value: function isSelected() { + return this.selected; + } + }, { + key: 'getValue', - // if color inherit is on and gradients are used, the function has already returned by now. - this.colorDirty = false; + /** + * Retrieve the value of the node. Can be undefined + * @return {Number} value + */ + value: function getValue() { + return this.options.value; + } + }, { + key: 'setValueRange', - if (selected === true) { - return this.color.highlight; - } else if (hover === true) { - return this.color.hover; + /** + * Adjust the value range of the node. The node will adjust it's size + * based on its value. + * @param {Number} min + * @param {Number} max + */ + 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 { - return this.color.color; + this.options.size = this.baseSize; + this.options.font.size = this.baseFontSize; } } }, { - key: '_circle', + key: 'draw', /** - * Draw a line from a node to itself, a circle - * @param {CanvasRenderingContext2D} ctx - * @param {Number} x - * @param {Number} y - * @param {Number} radius - * @private + * Draw this node in the given canvas + * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); + * @param {CanvasRenderingContext2D} ctx */ - value: function _circle(ctx, x, y, radius) { - // draw shadow if enabled - this.enableShadow(ctx); - - // draw a circle - ctx.beginPath(); - ctx.arc(x, y, radius, 0, 2 * Math.PI, false); - ctx.stroke(); - - // disable shadows for other elements. - this.disableShadow(ctx); + value: function draw(ctx) { + this.shape.draw(ctx, this.x, this.y, this.selected, this.hover); } }, { - key: 'getDistanceToEdge', + key: 'updateBoundingBox', /** - * 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 - * @param {number} y1 - * @param {number} x2 - * @param {number} y2 - * @param {number} x3 - * @param {number} y3 - * @private + * Update the bounding box of the shape */ - value: function getDistanceToEdge(x1, y1, x2, y2, x3, y3, via) { - // x3,y3 is the point - var returnValue = 0; - if (this.from != this.to) { - returnValue = this._getDistanceToEdge(x1, y1, x2, y2, x3, y3, via); - } else { - var _getCircleData6 = this._getCircleData(); - - var _getCircleData62 = _slicedToArray(_getCircleData6, 3); - - var x = _getCircleData62[0]; - var y = _getCircleData62[1]; - var radius = _getCircleData62[2]; - - var dx = x - x3; - var dy = y - y3; - returnValue = Math.abs(Math.sqrt(dx * dx + dy * dy) - radius); - } - - if (this.labelModule.size.left < x3 && this.labelModule.size.left + this.labelModule.size.width > x3 && this.labelModule.size.top < y3 && this.labelModule.size.top + this.labelModule.size.height > y3) { - return 0; - } else { - return returnValue; - } + value: function updateBoundingBox() { + this.shape.updateBoundingBox(this.x, this.y); } }, { - key: '_getDistanceToLine', - value: function _getDistanceToLine(x1, y1, x2, y2, x3, y3) { - var px = x2 - x1; - var py = y2 - y1; - var something = px * px + py * py; - var u = ((x3 - x1) * px + (y3 - y1) * py) / something; - - if (u > 1) { - u = 1; - } else if (u < 0) { - u = 0; - } - - var x = x1 + u * px; - var y = y1 + u * py; - var dx = x - x3; - var dy = y - y3; - - //# Note: If the actual distance does not matter, - //# if you only want to compare what this function - //# returns to other results of this function, you - //# can just return the squared distance instead - //# (i.e. remove the sqrt) to gain a little performance + key: 'resize', - return Math.sqrt(dx * dx + dy * dy); + /** + * 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 + */ + value: function resize(ctx) { + this.shape.resize(ctx); } }, { - key: 'drawArrowHead', + key: 'isOverlappingWith', /** - * - * @param ctx - * @param position - * @param viaNode + * 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 */ - value: function drawArrowHead(ctx, position, viaNode, selected, hover) { - // set style - ctx.strokeStyle = this.getColor(ctx, selected, hover); - ctx.fillStyle = ctx.strokeStyle; - ctx.lineWidth = this.getLineWidth(selected, hover); - - // set lets - var angle = undefined; - var length = undefined; - var arrowPos = undefined; - var node1 = undefined; - var node2 = undefined; - var guideOffset = undefined; - var scaleFactor = undefined; - - if (position === 'from') { - node1 = this.from; - node2 = this.to; - guideOffset = 0.1; - scaleFactor = this.options.arrows.from.scaleFactor; - } else if (position === 'to') { - node1 = this.to; - node2 = this.from; - guideOffset = -0.1; - scaleFactor = this.options.arrows.to.scaleFactor; - } else { - node1 = this.to; - node2 = this.from; - scaleFactor = this.options.arrows.middle.scaleFactor; - } - - // if not connected to itself - if (node1 != node2) { - if (position !== 'middle') { - // draw arrow head - if (this.options.smooth.enabled === true) { - arrowPos = this.findBorderPosition(node1, ctx, { via: viaNode }); - var guidePos = this.getPoint(Math.max(0, Math.min(1, arrowPos.t + guideOffset)), viaNode); - angle = Math.atan2(arrowPos.y - guidePos.y, arrowPos.x - guidePos.x); - } else { - angle = Math.atan2(node1.y - node2.y, node1.x - node2.x); - arrowPos = this.findBorderPosition(node1, ctx); - } - } else { - angle = Math.atan2(node1.y - node2.y, node1.x - node2.x); - arrowPos = this.getPoint(0.6, viaNode); // this is 0.6 to account for the size of the arrow. - } - // draw arrow at the end of the line - length = (10 + 5 * this.options.width) * scaleFactor; - ctx.arrow(arrowPos.x, arrowPos.y, angle, length); + 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; + } + }, { + key: 'isBoundingBoxOverlappingWith', - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); + /** + * 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 + */ + 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; + } + }], [{ + key: 'parseOptions', - // disable shadows for other elements. - this.disableShadow(ctx); - ctx.stroke(); - } else { - // draw circle - var _angle = undefined, - point = undefined; + /** + * 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 parentOptions + * @param newOptions + */ + value: function parseOptions(parentOptions, newOptions) { + var allowDeletion = arguments[2] === undefined ? false : arguments[2]; - var _getCircleData7 = this._getCircleData(ctx); + var fields = ['color', 'font', 'fixed', 'shadow']; + util.selectiveNotDeepExtend(fields, parentOptions, newOptions, allowDeletion); - var _getCircleData72 = _slicedToArray(_getCircleData7, 3); + // merge the shadow options into the parent. + util.mergeOptions(parentOptions, newOptions, 'shadow'); - var x = _getCircleData72[0]; - var y = _getCircleData72[1]; - var radius = _getCircleData72[2]; + // 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 = undefined; + delete parentOptions.color; + } - if (position === 'from') { - point = this.findBorderPosition(this.from, ctx, { x: x, y: y, low: 0.25, high: 0.6, direction: -1 }); - _angle = point.t * -2 * Math.PI + 1.5 * Math.PI + 0.1 * Math.PI; - } else if (position === 'to') { - point = this.findBorderPosition(this.from, ctx, { x: x, y: y, low: 0.6, high: 1, direction: 1 }); - _angle = point.t * -2 * Math.PI + 1.5 * Math.PI - 1.1 * Math.PI; + // 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 { - point = this._pointOnCircle(x, y, radius, 0.175); - _angle = 3.9269908169872414; // === 0.175 * -2 * Math.PI + 1.5 * Math.PI + 0.1 * Math.PI; + 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; + } } - - // draw the arrowhead - var _length = (10 + 5 * this.options.width) * scaleFactor; - ctx.arrow(point.x, point.y, _angle, _length); - - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); - - // disable shadows for other elements. - this.disableShadow(ctx); - ctx.stroke(); } - } - }, { - key: 'enableShadow', - value: function enableShadow(ctx) { - if (this.options.shadow.enabled === true) { - ctx.shadowColor = 'rgba(0,0,0,0.5)'; - ctx.shadowBlur = this.options.shadow.size; - ctx.shadowOffsetX = this.options.shadow.x; - ctx.shadowOffsetY = this.options.shadow.y; + + // handle the font options + if (newOptions.font !== undefined) { + _sharedLabel2['default'].parseOptions(parentOptions.font, newOptions); } - } - }, { - key: 'disableShadow', - value: function disableShadow(ctx) { - if (this.options.shadow.enabled === true) { - ctx.shadowColor = 'rgba(0,0,0,0)'; - ctx.shadowBlur = 0; - ctx.shadowOffsetX = 0; - ctx.shadowOffsetY = 0; + + // handle the scaling options, specifically the label part + if (newOptions.scaling !== undefined) { + util.mergeOptions(parentOptions.scaling, newOptions.scaling, 'label'); } } }]); - return EdgeBase; + return Node; })(); - exports['default'] = EdgeBase; + exports['default'] = Node; module.exports = exports['default']; /***/ }, -/* 90 */ +/* 75 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -34357,360 +35469,311 @@ return /******/ (function(modules) { // webpackBootstrap var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var _get = function get(_x4, _x5, _x6) { var _again = true; _function: while (_again) { var object = _x4, property = _x5, receiver = _x6; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x4 = parent; _x5 = property; _x6 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _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; } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - - var _utilBezierEdgeBase = __webpack_require__(88); + var util = __webpack_require__(2); - var _utilBezierEdgeBase2 = _interopRequireDefault(_utilBezierEdgeBase); + var Label = (function () { + function Label(body, options) { + _classCallCheck(this, Label); - var BezierEdgeStatic = (function (_BezierEdgeBase) { - function BezierEdgeStatic(options, body, labelModule) { - _classCallCheck(this, BezierEdgeStatic); + this.body = body; - _get(Object.getPrototypeOf(BezierEdgeStatic.prototype), 'constructor', this).call(this, options, body, labelModule); + this.baseSize = undefined; + this.setOptions(options); + this.size = { top: 0, left: 0, width: 0, height: 0, yLine: 0 }; // could be cached } - _inherits(BezierEdgeStatic, _BezierEdgeBase); - - _createClass(BezierEdgeStatic, [{ - key: '_line', + _createClass(Label, [{ + key: 'setOptions', + value: function setOptions(options) { + var allowDeletion = arguments[1] === undefined ? false : arguments[1]; - /** - * Draw a line between two nodes - * @param {CanvasRenderingContext2D} ctx - * @private - */ - value: function _line(ctx) { - // draw a straight line - ctx.beginPath(); - ctx.moveTo(this.from.x, this.from.y); - var via = this._getViaCoordinates(); - var returnValue = via; + this.options = options; - // fallback to normal straight edges - if (via.x === undefined) { - ctx.lineTo(this.to.x, this.to.y); - returnValue = undefined; - } else { - ctx.quadraticCurveTo(via.x, via.y, this.to.x, this.to.y); + if (options.label !== undefined) { + this.labelDirty = true; } - // draw shadow if enabled - this.enableShadow(ctx); - ctx.stroke(); - this.disableShadow(ctx); - return returnValue; - } - }, { - key: '_getViaCoordinates', - value: function _getViaCoordinates() { - var xVia = undefined; - var yVia = undefined; - var factor = this.options.smooth.roundness; - var type = this.options.smooth.type; - var dx = Math.abs(this.from.x - this.to.x); - var dy = Math.abs(this.from.y - this.to.y); - if (type === 'discrete' || type === 'diagonalCross') { - if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { - if (this.from.y > this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dy; - yVia = this.from.y - factor * dy; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dy; - yVia = this.from.y - factor * dy; - } - } else if (this.from.y < this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dy; - yVia = this.from.y + factor * dy; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dy; - yVia = this.from.y + factor * dy; - } - } - if (type === 'discrete') { - xVia = dx < factor * dy ? this.from.x : xVia; - } - } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { - if (this.from.y > this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dx; - yVia = this.from.y - factor * dx; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dx; - yVia = this.from.y - factor * dx; - } - } else if (this.from.y < this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dx; - yVia = this.from.y + factor * dx; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dx; - yVia = this.from.y + factor * dx; - } - } - if (type === 'discrete') { - yVia = dy < factor * dx ? this.from.y : yVia; - } - } - } else if (type === 'straightCross') { - if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { - // up - down - xVia = this.from.x; - if (this.from.y < this.to.y) { - yVia = this.to.y - (1 - factor) * dy; - } else { - yVia = this.to.y + (1 - factor) * dy; - } - } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { - // left - right - if (this.from.x < this.to.x) { - xVia = this.to.x - (1 - factor) * dx; - } else { - xVia = this.to.x + (1 - factor) * dx; - } - yVia = this.from.y; - } - } else if (type === 'horizontal') { - if (this.from.x < this.to.x) { - xVia = this.to.x - (1 - factor) * dx; - } else { - xVia = this.to.x + (1 - factor) * dx; - } - yVia = this.from.y; - } else if (type === 'vertical') { - xVia = this.from.x; - if (this.from.y < this.to.y) { - yVia = this.to.y - (1 - factor) * dy; - } else { - yVia = this.to.y + (1 - factor) * dy; - } - } else if (type === 'curvedCW') { - dx = this.to.x - this.from.x; - dy = this.from.y - this.to.y; - var radius = Math.sqrt(dx * dx + dy * dy); - var pi = Math.PI; - - var originalAngle = Math.atan2(dy, dx); - var myAngle = (originalAngle + (factor * 0.5 + 0.5) * pi) % (2 * pi); - - xVia = this.from.x + (factor * 0.5 + 0.5) * radius * Math.sin(myAngle); - yVia = this.from.y + (factor * 0.5 + 0.5) * radius * Math.cos(myAngle); - } else if (type === 'curvedCCW') { - dx = this.to.x - this.from.x; - dy = this.from.y - this.to.y; - var radius = Math.sqrt(dx * dx + dy * dy); - var pi = Math.PI; - var originalAngle = Math.atan2(dy, dx); - var myAngle = (originalAngle + (-factor * 0.5 + 0.5) * pi) % (2 * pi); - - xVia = this.from.x + (factor * 0.5 + 0.5) * radius * Math.sin(myAngle); - yVia = this.from.y + (factor * 0.5 + 0.5) * radius * Math.cos(myAngle); - } else { - // continuous - if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { - if (this.from.y > this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dy; - yVia = this.from.y - factor * dy; - xVia = this.to.x < xVia ? this.to.x : xVia; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dy; - yVia = this.from.y - factor * dy; - xVia = this.to.x > xVia ? this.to.x : xVia; - } - } else if (this.from.y < this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dy; - yVia = this.from.y + factor * dy; - xVia = this.to.x < xVia ? this.to.x : xVia; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dy; - yVia = this.from.y + factor * dy; - xVia = this.to.x > xVia ? this.to.x : xVia; - } - } - } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { - if (this.from.y > this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dx; - yVia = this.from.y - factor * dx; - yVia = this.to.y > yVia ? this.to.y : yVia; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dx; - yVia = this.from.y - factor * dx; - yVia = this.to.y > yVia ? this.to.y : yVia; - } - } else if (this.from.y < this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dx; - yVia = this.from.y + factor * dx; - yVia = this.to.y < yVia ? this.to.y : yVia; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dx; - yVia = this.from.y + factor * dx; - yVia = this.to.y < yVia ? this.to.y : yVia; - } + if (options.font !== undefined) { + Label.parseOptions(this.options.font, options, allowDeletion); + if (typeof options.font === 'string') { + this.baseSize = this.options.font.size; + } else if (typeof options.font === 'object') { + if (options.font.size !== undefined) { + this.baseSize = options.font.size; } } } - return { x: xVia, y: yVia }; } }, { - key: '_findBorderPosition', - value: function _findBorderPosition(nearNode, ctx) { - var options = arguments[2] === undefined ? {} : arguments[2]; + key: 'draw', + + /** + * Main function. This is called from anything that wants to draw a label. + * @param ctx + * @param x + * @param y + * @param selected + * @param baseline + */ + value: function draw(ctx, x, y, selected) { + var baseline = arguments[4] === undefined ? 'middle' : arguments[4]; + + // if no label, return + if (this.options.label === undefined) return; + + // check if we have to render the label + var viewFontSize = this.options.font.size * this.body.view.scale; + if (this.options.label && viewFontSize < this.options.scaling.label.drawThreshold - 1) return; - return this._findBorderPositionBezier(nearNode, ctx, options.via); - } - }, { - key: '_getDistanceToEdge', - value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) { - var via = arguments[6] === undefined ? this._getViaCoordinates() : arguments[6]; - // x3,y3 is the point - return this._getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via); + // update the size cache if required + this.calculateLabelSize(ctx, selected, x, y, baseline); + + // create the fontfill background + this._drawBackground(ctx); + // draw text + this._drawText(ctx, selected, x, y, baseline); } }, { - key: 'getPoint', + key: '_drawBackground', /** - * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way - * @param percentage - * @param via - * @returns {{x: number, y: number}} + * Draws the label background + * @param {CanvasRenderingContext2D} ctx * @private */ - value: function getPoint(percentage) { - var via = arguments[1] === undefined ? this._getViaCoordinates() : arguments[1]; + value: function _drawBackground(ctx) { + if (this.options.font.background !== undefined && this.options.font.background !== 'none') { + ctx.fillStyle = this.options.font.background; - var t = percentage; - var x = Math.pow(1 - t, 2) * this.from.x + 2 * t * (1 - t) * via.x + Math.pow(t, 2) * this.to.x; - var y = Math.pow(1 - t, 2) * this.from.y + 2 * t * (1 - t) * via.y + Math.pow(t, 2) * this.to.y; + var lineMargin = 2; - return { x: x, y: y }; + switch (this.options.font.align) { + case 'middle': + ctx.fillRect(-this.size.width * 0.5, -this.size.height * 0.5, this.size.width, this.size.height); + break; + case 'top': + ctx.fillRect(-this.size.width * 0.5, -(this.size.height + lineMargin), this.size.width, this.size.height); + break; + case 'bottom': + ctx.fillRect(-this.size.width * 0.5, lineMargin, this.size.width, this.size.height); + break; + default: + ctx.fillRect(this.size.left, this.size.top - 0.5 * lineMargin, this.size.width, this.size.height); + break; + } + } } - }]); - - return BezierEdgeStatic; - })(_utilBezierEdgeBase2['default']); - - exports['default'] = BezierEdgeStatic; - module.exports = exports['default']; + }, { + key: '_drawText', -/***/ }, -/* 91 */ -/***/ function(module, exports, __webpack_require__) { + /** + * + * @param ctx + * @param x + * @param baseline + * @private + */ + value: function _drawText(ctx, selected, x, y) { + var baseline = arguments[4] === undefined ? 'middle' : arguments[4]; - 'use strict'; + var fontSize = this.options.font.size; + var viewFontSize = fontSize * this.body.view.scale; + // this ensures that there will not be HUGE letters on screen by setting an upper limit on the visible text size (regardless of zoomLevel) + if (viewFontSize >= this.options.scaling.label.maxVisible) { + fontSize = Number(this.options.scaling.label.maxVisible) / this.body.view.scale; + } - Object.defineProperty(exports, '__esModule', { - value: true - }); + var yLine = this.size.yLine; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var _getColor = this._getColor(viewFontSize); - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + var _getColor2 = _slicedToArray(_getColor, 2); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var fontColor = _getColor2[0]; + var strokeColor = _getColor2[1]; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + var _setAlignment = this._setAlignment(ctx, x, yLine, baseline); - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + var _setAlignment2 = _slicedToArray(_setAlignment, 2); - var _utilEdgeBase = __webpack_require__(89); + x = _setAlignment2[0]; + yLine = _setAlignment2[1]; - var _utilEdgeBase2 = _interopRequireDefault(_utilEdgeBase); + // configure context for drawing the text + ctx.font = (selected ? 'bold ' : '') + fontSize + 'px ' + this.options.font.face; + ctx.fillStyle = fontColor; + ctx.textAlign = 'center'; - var StraightEdge = (function (_EdgeBase) { - function StraightEdge(options, body, labelModule) { - _classCallCheck(this, StraightEdge); + // set the strokeWidth + if (this.options.font.strokeWidth > 0) { + ctx.lineWidth = this.options.font.strokeWidth; + ctx.strokeStyle = strokeColor; + ctx.lineJoin = 'round'; + } - _get(Object.getPrototypeOf(StraightEdge.prototype), 'constructor', this).call(this, options, body, labelModule); - } + // draw the text + for (var i = 0; i < this.lineCount; i++) { + if (this.options.font.strokeWidth > 0) { + ctx.strokeText(this.lines[i], x, yLine); + } + ctx.fillText(this.lines[i], x, yLine); + yLine += fontSize; + } + } + }, { + key: '_setAlignment', + value: function _setAlignment(ctx, x, yLine, baseline) { + // check for label alignment (for edges) + // TODO: make alignment for nodes + if (this.options.font.align !== 'horizontal') { + x = 0; + yLine = 0; - _inherits(StraightEdge, _EdgeBase); + var lineMargin = 2; + if (this.options.font.align === 'top') { + ctx.textBaseline = 'alphabetic'; + yLine -= 2 * lineMargin; // distance from edge, required because we use alphabetic. Alphabetic has less difference between browsers + } else if (this.options.font.align === 'bottom') { + ctx.textBaseline = 'hanging'; + yLine += 2 * lineMargin; // distance from edge, required because we use hanging. Hanging has less difference between browsers + } else { + ctx.textBaseline = 'middle'; + } + } else { + ctx.textBaseline = baseline; + } - _createClass(StraightEdge, [{ - key: '_line', + return [x, yLine]; + } + }, { + key: '_getColor', /** - * Draw a line between two nodes - * @param {CanvasRenderingContext2D} ctx + * fade in when relative scale is between threshold and threshold - 1. + * If the relative scale would be smaller than threshold -1 the draw function would have returned before coming here. + * + * @param viewFontSize + * @returns {*[]} * @private */ - value: function _line(ctx) { - // draw a straight line - ctx.beginPath(); - ctx.moveTo(this.from.x, this.from.y); - ctx.lineTo(this.to.x, this.to.y); - // draw shadow if enabled - this.enableShadow(ctx); - ctx.stroke(); - this.disableShadow(ctx); - return undefined; + value: function _getColor(viewFontSize) { + var fontColor = this.options.font.color || '#000000'; + var strokeColor = this.options.font.strokeColor || '#ffffff'; + if (viewFontSize <= this.options.scaling.label.drawThreshold) { + var opacity = Math.max(0, Math.min(1, 1 - (this.options.scaling.label.drawThreshold - viewFontSize))); + fontColor = util.overrideOpacity(fontColor, opacity); + strokeColor = util.overrideOpacity(strokeColor, opacity); + } + return [fontColor, strokeColor]; } }, { - key: 'getPoint', + key: 'getTextSize', /** - * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way - * @param percentage - * @param via - * @returns {{x: number, y: number}} - * @private + * + * @param ctx + * @param selected + * @returns {{width: number, height: number}} */ - value: function getPoint(percentage) { - return { - x: (1 - percentage) * this.from.x + percentage * this.to.x, - y: (1 - percentage) * this.from.y + percentage * this.to.y + value: function getTextSize(ctx) { + var selected = arguments[1] === undefined ? false : arguments[1]; + + var size = { + width: this._processLabel(ctx, selected), + height: this.options.font.size * this.lineCount, + lineCount: this.lineCount }; + return size; } }, { - key: '_findBorderPosition', - value: function _findBorderPosition(nearNode, ctx) { - var node1 = this.to; - var node2 = this.from; - if (nearNode.id === this.from.id) { - node1 = this.from; - node2 = this.to; - } + key: 'calculateLabelSize', - var angle = Math.atan2(node1.y - node2.y, node1.x - node2.x); - var dx = node1.x - node2.x; - var dy = node1.y - node2.y; - var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); - var toBorderDist = nearNode.distanceToBorder(ctx, angle); - var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength; + /** + * + * @param ctx + * @param selected + * @param x + * @param y + * @param baseline + */ + value: function calculateLabelSize(ctx, selected) { + var x = arguments[2] === undefined ? 0 : arguments[2]; + var y = arguments[3] === undefined ? 0 : arguments[3]; + var baseline = arguments[4] === undefined ? 'middle' : arguments[4]; - var borderPos = {}; - borderPos.x = (1 - toBorderPoint) * node2.x + toBorderPoint * node1.x; - borderPos.y = (1 - toBorderPoint) * node2.y + toBorderPoint * node1.y; + if (this.labelDirty === true) { + this.size.width = this._processLabel(ctx, selected); + } + this.size.height = this.options.font.size * this.lineCount; + this.size.left = x - this.size.width * 0.5; + this.size.top = y - this.size.height * 0.5; + this.size.yLine = y + (1 - this.lineCount) * 0.5 * this.options.font.size; + if (baseline === 'hanging') { + this.size.top += 0.5 * this.options.font.size; + this.size.top += 4; // distance from node, required because we use hanging. Hanging has less difference between browsers + this.size.yLine += 4; // distance from node + } - return borderPos; + this.labelDirty = false; } }, { - key: '_getDistanceToEdge', - value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) { - // x3,y3 is the point - return this._getDistanceToLine(x1, y1, x2, y2, x3, y3); + key: '_processLabel', + + /** + * This calculates the width as well as explodes the label string and calculates the amount of lines. + * @param ctx + * @param selected + * @returns {number} + * @private + */ + value: function _processLabel(ctx, selected) { + var width = 0; + var lines = ['']; + var lineCount = 0; + if (this.options.label !== undefined) { + lines = String(this.options.label).split('\n'); + lineCount = lines.length; + ctx.font = (selected ? 'bold ' : '') + this.options.font.size + 'px ' + this.options.font.face; + width = ctx.measureText(lines[0]).width; + for (var i = 1; i < lineCount; i++) { + var lineWidth = ctx.measureText(lines[i]).width; + width = lineWidth > width ? lineWidth : width; + } + } + this.lines = lines; + this.lineCount = lineCount; + + return width; + } + }], [{ + key: 'parseOptions', + value: function parseOptions(parentOptions, newOptions) { + var allowDeletion = arguments[2] === undefined ? false : arguments[2]; + + if (typeof newOptions.font === 'string') { + var newOptionsArray = newOptions.font.split(' '); + parentOptions.size = newOptionsArray[0].replace('px', ''); + parentOptions.face = newOptionsArray[1]; + parentOptions.color = newOptionsArray[2]; + } else if (typeof newOptions.font === 'object') { + util.fillIfDefined(parentOptions, newOptions.font, allowDeletion); + } + parentOptions.size = Number(parentOptions.size); } }]); - return StraightEdge; - })(_utilEdgeBase2['default']); + return Label; + })(); - exports['default'] = StraightEdge; + exports['default'] = Label; module.exports = exports['default']; /***/ }, -/* 92 */ +/* 76 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -34725,615 +35788,553 @@ return /******/ (function(modules) { // webpackBootstrap function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var _componentsPhysicsBarnesHutSolver = __webpack_require__(3); - - var _componentsPhysicsBarnesHutSolver2 = _interopRequireDefault(_componentsPhysicsBarnesHutSolver); - - var _componentsPhysicsRepulsionSolver = __webpack_require__(93); - - var _componentsPhysicsRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsRepulsionSolver); - - var _componentsPhysicsHierarchicalRepulsionSolver = __webpack_require__(94); - - var _componentsPhysicsHierarchicalRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsHierarchicalRepulsionSolver); - - var _componentsPhysicsSpringSolver = __webpack_require__(95); - - var _componentsPhysicsSpringSolver2 = _interopRequireDefault(_componentsPhysicsSpringSolver); - - var _componentsPhysicsHierarchicalSpringSolver = __webpack_require__(96); + var _sharedLabel = __webpack_require__(75); - var _componentsPhysicsHierarchicalSpringSolver2 = _interopRequireDefault(_componentsPhysicsHierarchicalSpringSolver); + var _sharedLabel2 = _interopRequireDefault(_sharedLabel); - var _componentsPhysicsCentralGravitySolver = __webpack_require__(97); + var _edgesBezierEdgeDynamic = __webpack_require__(106); - var _componentsPhysicsCentralGravitySolver2 = _interopRequireDefault(_componentsPhysicsCentralGravitySolver); + var _edgesBezierEdgeDynamic2 = _interopRequireDefault(_edgesBezierEdgeDynamic); - var _componentsPhysicsFA2BasedRepulsionSolver = __webpack_require__(98); + var _edgesBezierEdgeStatic = __webpack_require__(107); - var _componentsPhysicsFA2BasedRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsFA2BasedRepulsionSolver); + var _edgesBezierEdgeStatic2 = _interopRequireDefault(_edgesBezierEdgeStatic); - var _componentsPhysicsFA2BasedCentralGravitySolver = __webpack_require__(99); + var _edgesStraightEdge = __webpack_require__(108); - var _componentsPhysicsFA2BasedCentralGravitySolver2 = _interopRequireDefault(_componentsPhysicsFA2BasedCentralGravitySolver); + var _edgesStraightEdge2 = _interopRequireDefault(_edgesStraightEdge); var util = __webpack_require__(2); - var PhysicsEngine = (function () { - function PhysicsEngine(body) { - _classCallCheck(this, PhysicsEngine); + /** + * @class Edge + * + * A edge connects two nodes + * @param {Object} properties Object with options. Must contain + * At least options from and to. + * Available options: from (number), + * to (number), label (string, color (string), + * width (number), style (string), + * length (number), title (string) + * @param {Network} network A Network object, used to find and edge to + * nodes. + * @param {Object} constants An object with default values for + * example for the color + */ + + var Edge = (function () { + function Edge(options, body, globalOptions) { + _classCallCheck(this, Edge); + if (body === undefined) { + throw 'No body provided'; + } + this.options = util.bridgeObject(globalOptions); this.body = body; - this.physicsBody = { physicsNodeIndices: [], physicsEdgeIndices: [], forces: {}, velocities: {} }; - this.physicsEnabled = true; - this.simulationInterval = 1000 / 60; - this.requiresTimeout = true; - this.previousStates = {}; - this.freezeCache = {}; - this.renderTimer = undefined; + // initialize variables + this.id = undefined; + this.fromId = undefined; + this.toId = undefined; + this.selected = false; + this.hover = false; + this.labelDirty = true; + this.colorDirty = true; - this.stabilized = false; - this.startedStabilization = false; - this.stabilizationIterations = 0; - this.ready = false; // will be set to true if the stabilize + this.baseWidth = this.options.width; + this.baseFontSize = this.options.font.size; - // default options - this.options = {}; - this.defaultOptions = { - barnesHut: { - theta: 0.5, - gravitationalConstant: -2000, - centralGravity: 0.3, - springLength: 95, - springConstant: 0.04, - damping: 0.09, - avoidOverlap: 0 - }, - forceAtlas2Based: { - theta: 0.5, - gravitationalConstant: -50, - centralGravity: 0.01, - springConstant: 0.08, - springLength: 100, - damping: 0.4, - avoidOverlap: 0 - }, - repulsion: { - centralGravity: 0.2, - springLength: 200, - springConstant: 0.05, - nodeDistance: 100, - damping: 0.09, - avoidOverlap: 0 - }, - hierarchicalRepulsion: { - centralGravity: 0, - springLength: 100, - springConstant: 0.01, - nodeDistance: 120, - damping: 0.09 - }, - maxVelocity: 50, - minVelocity: 0.1, // px/s - solver: 'barnesHut', - stabilization: { - enabled: true, - iterations: 1000, // maximum number of iteration to stabilize - updateInterval: 50, - onlyDynamicEdges: false, - fit: true - }, - timestep: 0.5 - }; - util.extend(this.options, this.defaultOptions); + this.from = undefined; // a node + this.to = undefined; // a node - this.bindEventListeners(); - } + this.edgeType = undefined; - _createClass(PhysicsEngine, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this = this; + this.connected = false; - this.body.emitter.on('initPhysics', function () { - _this.initPhysics(); - }); - this.body.emitter.on('resetPhysics', function () { - _this.stopSimulation();_this.ready = false; - }); - this.body.emitter.on('disablePhysics', function () { - _this.physicsEnabled = false;_this.stopSimulation(); - }); - this.body.emitter.on('restorePhysics', function () { - _this.setOptions(_this.options); - if (_this.ready === true) { - _this.startSimulation(); - } - }); - this.body.emitter.on('startSimulation', function () { - if (_this.ready === true) { - _this.startSimulation(); - } - }); - this.body.emitter.on('stopSimulation', function () { - _this.stopSimulation(); - }); - this.body.emitter.on('destroy', function () { - _this.stopSimulation(false); - _this.body.emitter.off(); - }); - } - }, { - key: 'setOptions', - value: function setOptions(options) { - if (options !== undefined) { - if (options === false) { - this.physicsEnabled = false; - this.stopSimulation(); - } else { - this.physicsEnabled = true; - util.selectiveNotDeepExtend(['stabilization'], this.options, options); - util.mergeOptions(this.options, options, 'stabilization'); - } - } - this.init(); - } - }, { - key: 'init', - value: function init() { - var options; - if (this.options.solver === 'forceAtlas2Based') { - options = this.options.forceAtlas2Based; - this.nodesSolver = new _componentsPhysicsFA2BasedRepulsionSolver2['default'](this.body, this.physicsBody, options); - this.edgesSolver = new _componentsPhysicsSpringSolver2['default'](this.body, this.physicsBody, options); - this.gravitySolver = new _componentsPhysicsFA2BasedCentralGravitySolver2['default'](this.body, this.physicsBody, options); - } else if (this.options.solver === 'repulsion') { - options = this.options.repulsion; - this.nodesSolver = new _componentsPhysicsRepulsionSolver2['default'](this.body, this.physicsBody, options); - this.edgesSolver = new _componentsPhysicsSpringSolver2['default'](this.body, this.physicsBody, options); - this.gravitySolver = new _componentsPhysicsCentralGravitySolver2['default'](this.body, this.physicsBody, options); - } else if (this.options.solver === 'hierarchicalRepulsion') { - options = this.options.hierarchicalRepulsion; - this.nodesSolver = new _componentsPhysicsHierarchicalRepulsionSolver2['default'](this.body, this.physicsBody, options); - this.edgesSolver = new _componentsPhysicsHierarchicalSpringSolver2['default'](this.body, this.physicsBody, options); - this.gravitySolver = new _componentsPhysicsCentralGravitySolver2['default'](this.body, this.physicsBody, options); - } else { - // barnesHut - options = this.options.barnesHut; - this.nodesSolver = new _componentsPhysicsBarnesHutSolver2['default'](this.body, this.physicsBody, options); - this.edgesSolver = new _componentsPhysicsSpringSolver2['default'](this.body, this.physicsBody, options); - this.gravitySolver = new _componentsPhysicsCentralGravitySolver2['default'](this.body, this.physicsBody, options); - } + this.labelModule = new _sharedLabel2['default'](this.body, this.options); - this.modelOptions = options; - } - }, { - key: 'initPhysics', - value: function initPhysics() { - if (this.physicsEnabled === true) { - if (this.options.stabilization.enabled === true) { - this.stabilize(); - } else { - this.stabilized = false; - this.ready = true; - this.body.emitter.emit('fit', {}, true); - this.startSimulation(); - } - } else { - this.ready = true; - this.body.emitter.emit('fit'); - } - } - }, { - key: 'startSimulation', + this.setOptions(options); + } + + _createClass(Edge, [{ + key: 'setOptions', /** - * Start the simulation + * Set or overwrite options for the edge + * @param {Object} options an object with options + * @param doNotEmit */ - value: function startSimulation() { - if (this.physicsEnabled === true) { - this.stabilized = false; + value: function setOptions(options) { + if (!options) { + return; + } + this.colorDirty = true; - // this sets the width of all nodes initially which could be required for the avoidOverlap - this.body.emitter.emit('_resizeNodes'); + Edge.parseOptions(this.options, options, true); - if (this.viewFunction === undefined) { - this.viewFunction = this.simulationStep.bind(this); - this.body.emitter.on('initRedraw', this.viewFunction); - this.body.emitter.emit('_startRendering'); - } - } else { - this.body.emitter.emit('_redraw'); + 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 = parseInt(options.value); + } + + // update label Module + this.updateLabelModule(); + + 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; } }, { - key: 'stopSimulation', + key: 'updateLabelModule', /** - * Stop the simulation, force stabilization. + * update the options in the label module */ - value: function stopSimulation() { - var emit = arguments[0] === undefined ? true : arguments[0]; - - this.stabilized = true; - if (emit === true) { - this._emitStabilized(); - } - if (this.viewFunction !== undefined) { - this.body.emitter.off('initRedraw', this.viewFunction); - this.viewFunction = undefined; - if (emit === true) { - this.body.emitter.emit('_stopRendering'); - } + value: function updateLabelModule() { + this.labelModule.setOptions(this.options, true); + if (this.labelModule.baseSize !== undefined) { + this.baseFontSize = this.labelModule.baseSize; } } }, { - key: 'simulationStep', + key: 'updateEdgeType', /** - * The viewFunction inserts this step into each renderloop. It calls the physics tick and handles the cleanup at stabilized. - * + * update the edge type, set the options + * @returns {boolean} */ - value: function simulationStep() { - // check if the physics have settled - var startTime = Date.now(); - this.physicsTick(); - var physicsTime = Date.now() - startTime; - - // run double speed if it is a little graph - if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) { - this.physicsTick(); + value: function updateEdgeType() { + var dataChanged = false; + var changeInType = true; + if (this.edgeType !== undefined) { + if (this.edgeType instanceof _edgesBezierEdgeDynamic2['default'] && this.options.smooth.enabled === true && this.options.smooth.type === 'dynamic') { + changeInType = false; + } + if (this.edgeType instanceof _edgesBezierEdgeStatic2['default'] && this.options.smooth.enabled === true && this.options.smooth.type !== 'dynamic') { + changeInType = false; + } + if (this.edgeType instanceof _edgesStraightEdge2['default'] && this.options.smooth.enabled === false) { + changeInType = false; + } - // this makes sure there is no jitter. The decision is taken once to run it at double speed. - this.runDoubleSpeed = true; + if (changeInType === true) { + dataChanged = this.edgeType.cleanup(); + } } - if (this.stabilized === true) { - if (this.stabilizationIterations > 1) { - // trigger the 'stabilized' event. - // The event is triggered on the next tick, to prevent the case that - // it is fired while initializing the Network, in which case you would not - // be able to catch it - this.startedStabilization = false; - //this._emitStabilized(); + if (changeInType === true) { + if (this.options.smooth.enabled === true) { + if (this.options.smooth.type === 'dynamic') { + dataChanged = true; + this.edgeType = new _edgesBezierEdgeDynamic2['default'](this.options, this.body, this.labelModule); + } else { + this.edgeType = new _edgesBezierEdgeStatic2['default'](this.options, this.body, this.labelModule); + } + } else { + this.edgeType = new _edgesStraightEdge2['default'](this.options, this.body, this.labelModule); } - this.stopSimulation(); + } else { + // if nothing changes, we just set the options. + this.edgeType.setOptions(this.options); } - } - }, { - key: '_emitStabilized', - value: function _emitStabilized() { - var _this2 = this; - if (this.stabilizationIterations > 1) { - setTimeout(function () { - _this2.body.emitter.emit('stabilized', { iterations: _this2.stabilizationIterations }); - _this2.stabilizationIterations = 0; - }, 0); - } + return dataChanged; } }, { - key: 'physicsTick', + key: 'togglePhysics', /** - * A single simulation step (or 'tick') in the physics simulation - * - * @private + * Enable or disable the physics. + * @param status */ - value: function physicsTick() { - if (this.stabilized === false) { - this.calculateForces(); - this.stabilized = this.moveNodes(); - - // determine if the network has stabilzied - if (this.stabilized === true) { - this.revert(); - } else { - // this is here to ensure that there is no start event when the network is already stable. - if (this.startedStabilization === false) { - this.body.emitter.emit('startStabilizing'); - this.startedStabilization = true; - } - } - - this.stabilizationIterations++; - } + value: function togglePhysics(status) { + this.options.physics = status; + this.edgeType.togglePhysics(status); } }, { - key: 'updatePhysicsData', + key: 'connect', /** - * Nodes and edges can have the physics toggles on or off. A collection of indices is created here so we can skip the check all the time. - * - * @private + * Connect an edge to its nodes */ - value: function updatePhysicsData() { - this.physicsBody.forces = {}; - this.physicsBody.physicsNodeIndices = []; - this.physicsBody.physicsEdgeIndices = []; - var nodes = this.body.nodes; - var edges = this.body.edges; + value: function connect() { + this.disconnect(); - // get node indices for physics - for (var nodeId in nodes) { - if (nodes.hasOwnProperty(nodeId)) { - if (nodes[nodeId].options.physics === true) { - this.physicsBody.physicsNodeIndices.push(nodeId); - } - } - } + this.from = this.body.nodes[this.fromId] || undefined; + this.to = this.body.nodes[this.toId] || undefined; + this.connected = this.from !== undefined && this.to !== undefined; - // get edge indices for physics - for (var edgeId in edges) { - if (edges.hasOwnProperty(edgeId)) { - if (edges[edgeId].options.physics === true) { - this.physicsBody.physicsEdgeIndices.push(edgeId); - } + if (this.connected === true) { + this.from.attachEdge(this); + this.to.attachEdge(this); + } else { + if (this.from) { + this.from.detachEdge(this); } - } - - // get the velocity and the forces vector - for (var i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) { - var nodeId = this.physicsBody.physicsNodeIndices[i]; - this.physicsBody.forces[nodeId] = { x: 0, y: 0 }; - - // forces can be reset because they are recalculated. Velocities have to persist. - if (this.physicsBody.velocities[nodeId] === undefined) { - this.physicsBody.velocities[nodeId] = { x: 0, y: 0 }; + if (this.to) { + this.to.detachEdge(this); } } - // clean deleted nodes from the velocity vector - for (var nodeId in this.physicsBody.velocities) { - if (nodes[nodeId] === undefined) { - delete this.physicsBody.velocities[nodeId]; - } - } + this.edgeType.connect(); } }, { - key: 'revert', + key: 'disconnect', /** - * Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized. + * Disconnect an edge from its nodes */ - value: function revert() { - var nodeIds = Object.keys(this.previousStates); - var nodes = this.body.nodes; - var velocities = this.physicsBody.velocities; - - for (var i = 0; i < nodeIds.length; i++) { - var nodeId = nodeIds[i]; - if (nodes[nodeId] !== undefined) { - if (nodes[nodeId].options.physics === true) { - velocities[nodeId].x = this.previousStates[nodeId].vx; - velocities[nodeId].y = this.previousStates[nodeId].vy; - nodes[nodeId].x = this.previousStates[nodeId].x; - nodes[nodeId].y = this.previousStates[nodeId].y; - } - } else { - delete this.previousStates[nodeId]; - } + 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; } }, { - key: 'moveNodes', + key: 'getTitle', /** - * move the nodes one timestap and check if they are stabilized - * @returns {boolean} + * get the title of this edge. + * @return {string} title The title of the edge, or undefined when no title + * has been set. */ - value: function moveNodes() { - var nodesPresent = false; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var maxVelocity = this.options.maxVelocity ? this.options.maxVelocity : 1000000000; - var stabilized = true; - var vminCorrected = this.options.minVelocity / Math.max(this.body.view.scale, 0.05); - - for (var i = 0; i < nodeIndices.length; i++) { - var nodeId = nodeIndices[i]; - var nodeVelocity = this._performStep(nodeId, maxVelocity); - // stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized - stabilized = nodeVelocity < vminCorrected && stabilized === true; - nodesPresent = true; - } - - if (nodesPresent === true) { - if (vminCorrected > 0.5 * this.options.maxVelocity) { - return false; - } else { - return stabilized; - } - } - return true; + value: function getTitle() { + return this.title; } }, { - key: '_performStep', + key: 'isSelected', /** - * Perform the actual step - * - * @param nodeId - * @param maxVelocity - * @returns {number} - * @private + * check if this node is selecte + * @return {boolean} selected True if node is selected, else false */ - value: function _performStep(nodeId, maxVelocity) { - var node = this.body.nodes[nodeId]; - var timestep = this.options.timestep; - var forces = this.physicsBody.forces; - var velocities = this.physicsBody.velocities; + value: function isSelected() { + return this.selected; + } + }, { + key: 'getValue', - // store the state so we can revert - this.previousStates[nodeId] = { x: node.x, y: node.y, vx: velocities[nodeId].x, vy: velocities[nodeId].y }; + /** + * Retrieve the value of the edge. Can be undefined + * @return {Number} value + */ + value: function getValue() { + return this.options.value; + } + }, { + key: 'setValueRange', - if (node.options.fixed.x === false) { - var dx = this.modelOptions.damping * velocities[nodeId].x; // damping force - var ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration - velocities[nodeId].x += ax * timestep; // velocity - velocities[nodeId].x = Math.abs(velocities[nodeId].x) > maxVelocity ? velocities[nodeId].x > 0 ? maxVelocity : -maxVelocity : velocities[nodeId].x; - node.x += velocities[nodeId].x * timestep; // position + /** + * 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 total + */ + 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 { - forces[nodeId].x = 0; - velocities[nodeId].x = 0; + this.options.width = this.baseWidth; + this.options.font.size = this.baseFontSize; } - if (node.options.fixed.y === false) { - var dy = this.modelOptions.damping * velocities[nodeId].y; // damping force - var ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration - velocities[nodeId].y += ay * timestep; // velocity - velocities[nodeId].y = Math.abs(velocities[nodeId].y) > maxVelocity ? velocities[nodeId].y > 0 ? maxVelocity : -maxVelocity : velocities[nodeId].y; - node.y += velocities[nodeId].y * timestep; // position + this._setInteractionWidths(); + } + }, { + key: '_setInteractionWidths', + value: function _setInteractionWidths() { + if (typeof this.options.hoverWidth === 'function') { + this.edgeType.hoverWidth = this.options.hoverWidth(this.options.width); } else { - forces[nodeId].y = 0; - velocities[nodeId].y = 0; + this.edgeType.hoverWidth = this.options.hoverWidth + this.options.width; } - var totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x, 2) + Math.pow(velocities[nodeId].y, 2)); - return totalVelocity; + 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; + } } }, { - key: 'calculateForces', + key: 'draw', /** - * calculate the forces for one physics iteration. + * 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 */ - value: function calculateForces() { - this.gravitySolver.solve(); - this.nodesSolver.solve(); - this.edgesSolver.solve(); + value: function draw(ctx) { + var via = this.edgeType.drawLine(ctx, this.selected, this.hover); + this.drawArrows(ctx, via); + this.drawLabel(ctx, via); } }, { - key: '_freezeNodes', - - /** - * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization - * because only the supportnodes for the smoothCurves have to settle. - * - * @private - */ - value: function _freezeNodes() { - var nodes = this.body.nodes; - for (var id in nodes) { - if (nodes.hasOwnProperty(id)) { - if (nodes[id].x && nodes[id].y) { - this.freezeCache[id] = { x: nodes[id].options.fixed.x, y: nodes[id].options.fixed.y }; - nodes[id].options.fixed.x = true; - nodes[id].options.fixed.y = true; - } - } + key: 'drawArrows', + value: function drawArrows(ctx, viaNode) { + if (this.options.arrows.from.enabled === true) { + this.edgeType.drawArrowHead(ctx, 'from', viaNode, this.selected, this.hover); + } + if (this.options.arrows.middle.enabled === true) { + this.edgeType.drawArrowHead(ctx, 'middle', viaNode, this.selected, this.hover); + } + if (this.options.arrows.to.enabled === true) { + this.edgeType.drawArrowHead(ctx, 'to', viaNode, this.selected, this.hover); } } }, { - key: '_restoreFrozenNodes', + key: 'drawLabel', + value: function drawLabel(ctx, viaNode) { + if (this.options.label !== undefined) { + // set style + var node1 = this.from; + var node2 = this.to; + var selected = this.from.selected || this.to.selected || this.selected; + if (node1.id != node2.id) { + var point = this.edgeType.getPoint(0.5, viaNode); + ctx.save(); - /** - * Unfreezes the nodes that have been frozen by _freezeDefinedNodes. - * - * @private - */ - value: function _restoreFrozenNodes() { - var nodes = this.body.nodes; - for (var id in nodes) { - if (nodes.hasOwnProperty(id)) { - if (this.freezeCache[id] !== undefined) { - nodes[id].options.fixed.x = this.freezeCache[id].x; - nodes[id].options.fixed.y = this.freezeCache[id].y; + // if the label has to be rotated: + if (this.options.font.align !== 'horizontal') { + this.labelModule.calculateLabelSize(ctx, selected, point.x, point.y); + ctx.translate(point.x, this.labelModule.size.yLine); + this._rotateForLabelAlignment(ctx); + } + + // draw the label + this.labelModule.draw(ctx, point.x, point.y, selected); + ctx.restore(); + } else { + 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, selected); } } - this.freezeCache = {}; } }, { - key: 'stabilize', + key: 'isOverlappingWith', /** - * Find a stable position for all nodes - * @private + * 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 */ - value: function stabilize() { - var _this3 = this; + 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 iterations = arguments[0] === undefined ? this.options.stabilization.iterations : arguments[0]; + var dist = this.edgeType.getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj); - if (typeof iterations !== 'number') { - console.log('The stabilize method needs a numeric amount of iterations. Switching to default: ', this.options.stabilization.iterations); - iterations = this.options.stabilization.iterations; + return dist < distMax; + } else { + return false; } + } + }, { + key: '_rotateForLabelAlignment', - // this sets the width of all nodes initially which could be required for the avoidOverlap - this.body.emitter.emit('_resizeNodes'); - - // stop the render loop - this.stopSimulation(); - - // set stabilze to false - this.stabilized = false; - - // block redraw requests - this.body.emitter.emit('_blockRedrawRequests'); - this.targetIterations = iterations; + /** + * Rotates the canvas so the text is most readable + * @param {CanvasRenderingContext2D} ctx + * @private + */ + value: function _rotateForLabelAlignment(ctx) { + var dy = this.from.y - this.to.y; + var dx = this.from.x - this.to.x; + var angleInDegrees = Math.atan2(dy, dx); - // start the stabilization - if (this.options.stabilization.onlyDynamicEdges === true) { - this._freezeNodes(); + // rotate so label it is readable + if (angleInDegrees < -1 && dx < 0 || angleInDegrees > 0 && dx < 0) { + angleInDegrees = angleInDegrees + Math.PI; } - this.stabilizationIterations = 0; - setTimeout(function () { - return _this3._stabilizationBatch(); - }, 0); + ctx.rotate(angleInDegrees); } }, { - key: '_stabilizationBatch', - value: function _stabilizationBatch() { - var count = 0; - while (this.stabilized === false && count < this.options.stabilization.updateInterval && this.stabilizationIterations < this.targetIterations) { - this.physicsTick(); - this.stabilizationIterations++; - count++; - } + key: '_pointOnCircle', - if (this.stabilized === false && this.stabilizationIterations < this.targetIterations) { - this.body.emitter.emit('stabilizationProgress', { iterations: this.stabilizationIterations, total: this.targetIterations }); - setTimeout(this._stabilizationBatch.bind(this), 0); - } else { - this._finalizeStabilization(); - } + /** + * 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 + */ + 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) + }; } }, { - key: '_finalizeStabilization', - value: function _finalizeStabilization() { - this.body.emitter.emit('_allowRedrawRequests'); - if (this.options.stabilization.fit === true) { - this.body.emitter.emit('fit'); + key: 'select', + value: function select() { + this.selected = true; + } + }, { + key: 'unselect', + value: function unselect() { + this.selected = false; + } + }], [{ + key: 'parseOptions', + value: function parseOptions(parentOptions, newOptions) { + var allowDeletion = arguments[2] === undefined ? false : arguments[2]; + + var fields = ['id', 'from', 'hidden', 'hoverWidth', 'label', 'length', 'line', 'opacity', 'physics', 'selectionWidth', 'selfReferenceSize', 'to', 'title', 'value', 'width']; + + // only deep extend the items in the field array. These do not have shorthand. + util.selectiveDeepExtend(fields, parentOptions, newOptions, allowDeletion); + + util.mergeOptions(parentOptions, newOptions, 'smooth'); + util.mergeOptions(parentOptions, newOptions, 'shadow'); + + if (newOptions.dashes !== undefined && newOptions.dashes !== null) { + parentOptions.dashes = newOptions.dashes; + } else if (allowDeletion === true && newOptions.dashes === null) { + parentOptions.dashes = undefined; + delete parentOptions.dashes; } - if (this.options.stabilization.onlyDynamicEdges === true) { - this._restoreFrozenNodes(); + // 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'); + } else if (allowDeletion === true && newOptions.scaling === null) { + parentOptions.scaling = undefined; + delete parentOptions.scaling; } - this.body.emitter.emit('stabilizationIterationsDone'); - this.body.emitter.emit('_requestRedraw'); + // hanlde multiple input cases for arrows + if (newOptions.arrows !== undefined && newOptions.arrows !== null) { + if (typeof newOptions.arrows === 'string') { + var arrows = newOptions.arrows.toLowerCase(); + if (arrows.indexOf('to') != -1) { + parentOptions.arrows.to.enabled = true; + } + if (arrows.indexOf('middle') != -1) { + parentOptions.arrows.middle.enabled = true; + } + if (arrows.indexOf('from') != -1) { + parentOptions.arrows.from.enabled = true; + } + } else if (typeof newOptions.arrows === 'object') { + util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'to'); + util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'middle'); + util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'from'); + } else { + throw new Error('The arrow newOptions can only be an object or a string. Refer to the documentation. You used:' + JSON.stringify(newOptions.arrows)); + } + } else if (allowDeletion === true && newOptions.arrows === null) { + parentOptions.arrows = undefined; + delete parentOptions.arrows; + } - if (this.stabilized === true) { - this._emitStabilized(); - } else { - this.startSimulation(); + // hanlde multiple input cases for color + if (newOptions.color !== undefined && newOptions.color !== null) { + if (util.isString(newOptions.color)) { + parentOptions.color.color = newOptions.color; + parentOptions.color.highlight = newOptions.color; + parentOptions.color.hover = newOptions.color; + parentOptions.color.inherit = false; + } else { + var colorsDefined = false; + if (newOptions.color.color !== undefined) { + parentOptions.color.color = newOptions.color.color;colorsDefined = true; + } + if (newOptions.color.highlight !== undefined) { + parentOptions.color.highlight = newOptions.color.highlight;colorsDefined = true; + } + if (newOptions.color.hover !== undefined) { + parentOptions.color.hover = newOptions.color.hover;colorsDefined = true; + } + if (newOptions.color.inherit !== undefined) { + parentOptions.color.inherit = newOptions.color.inherit; + } + if (newOptions.color.opacity !== undefined) { + parentOptions.color.opacity = Math.min(1, Math.max(0, newOptions.color.opacity)); + } + + if (newOptions.color.inherit === undefined && colorsDefined === true) { + parentOptions.color.inherit = false; + } + } + } else if (allowDeletion === true && newOptions.color === null) { + parentOptions.color = undefined; + delete parentOptions.color; } - this.ready = true; + // handle the font settings + if (newOptions.font !== undefined) { + _sharedLabel2['default'].parseOptions(parentOptions.font, newOptions); + } } }]); - return PhysicsEngine; + return Edge; })(); - exports['default'] = PhysicsEngine; + exports['default'] = Edge; module.exports = exports['default']; /***/ }, -/* 93 */ +/* 77 */ /***/ function(module, exports, __webpack_require__) { "use strict"; @@ -35346,411 +36347,488 @@ return /******/ (function(modules) { // webpackBootstrap function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var RepulsionSolver = (function () { - function RepulsionSolver(body, physicsBody, options) { - _classCallCheck(this, RepulsionSolver); + var BarnesHutSolver = (function () { + function BarnesHutSolver(body, physicsBody, options) { + _classCallCheck(this, BarnesHutSolver); this.body = body; this.physicsBody = physicsBody; + this.barnesHutTree; this.setOptions(options); } - _createClass(RepulsionSolver, [{ + _createClass(BarnesHutSolver, [{ key: "setOptions", value: function setOptions(options) { this.options = options; + this.thetaInversed = 1 / this.options.theta; + this.overlapAvoidanceFactor = 1 - Math.max(0, Math.min(1, this.options.avoidOverlap)); // if 1 then min distance = 0.5, if 0.5 then min distance = 0.5 + 0.5*node.shape.radius } }, { key: "solve", /** - * Calculate the forces the nodes apply on each other based on a repulsion field. - * This field is linearly approximated. + * This function calculates the forces the nodes apply on eachother based on a gravitational model. + * The Barnes Hut method is used to speed up this N-body simulation. * * @private */ value: function solve() { - var dx, dy, distance, fx, fy, repulsingForce, node1, node2; - - var nodes = this.body.nodes; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var forces = this.physicsBody.forces; - - // repulsing forces between nodes - var nodeDistance = this.options.nodeDistance; - - // approximation constants - var a = -2 / 3 / nodeDistance; - var b = 4 / 3; + if (this.options.gravitationalConstant !== 0 && this.physicsBody.physicsNodeIndices.length > 0) { + var node = undefined; + var nodes = this.body.nodes; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var nodeCount = nodeIndices.length; - // we loop from i over all but the last entree in the array - // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j - for (var i = 0; i < nodeIndices.length - 1; i++) { - node1 = nodes[nodeIndices[i]]; - for (var j = i + 1; j < nodeIndices.length; j++) { - node2 = nodes[nodeIndices[j]]; + // create the tree + var barnesHutTree = this._formBarnesHutTree(nodes, nodeIndices); - dx = node2.x - node1.x; - dy = node2.y - node1.y; - distance = Math.sqrt(dx * dx + dy * dy); + // for debugging + this.barnesHutTree = barnesHutTree; - // same condition as BarnesHutSolver, making sure nodes are never 100% overlapping. - if (distance === 0) { - distance = 0.1 * Math.random(); - dx = distance; + // place the nodes one by one recursively + for (var i = 0; i < nodeCount; i++) { + node = nodes[nodeIndices[i]]; + if (node.options.mass > 0) { + // starting with root is irrelevant, it never passes the BarnesHutSolver condition + this._getForceContribution(barnesHutTree.root.children.NW, node); + this._getForceContribution(barnesHutTree.root.children.NE, node); + this._getForceContribution(barnesHutTree.root.children.SW, node); + this._getForceContribution(barnesHutTree.root.children.SE, node); } + } + } + } + }, { + key: "_getForceContribution", - if (distance < 2 * nodeDistance) { - if (distance < 0.5 * nodeDistance) { - repulsingForce = 1; - } else { - repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / nodeDistance - 1) * steepness)) - } - repulsingForce = repulsingForce / distance; + /** + * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass. + * If a region contains a single node, we check if it is not itself, then we apply the force. + * + * @param parentBranch + * @param node + * @private + */ + value: function _getForceContribution(parentBranch, node) { + // we get no force contribution from an empty region + if (parentBranch.childrenCount > 0) { + var dx = undefined, + dy = undefined, + distance = undefined; - fx = dx * repulsingForce; - fy = dy * repulsingForce; + // get the distance from the center of mass to the node. + dx = parentBranch.centerOfMass.x - node.x; + dy = parentBranch.centerOfMass.y - node.y; + distance = Math.sqrt(dx * dx + dy * dy); - forces[node1.id].x -= fx; - forces[node1.id].y -= fy; - forces[node2.id].x += fx; - forces[node2.id].y += fy; + // BarnesHutSolver condition + // original condition : s/d < theta = passed === d/s > 1/theta = passed + // calcSize = 1/s --> d * 1/s > 1/theta = passed + if (distance * parentBranch.calcSize > this.thetaInversed) { + this._calculateForces(distance, dx, dy, node, parentBranch); + } else { + // Did not pass the condition, go into children if available + if (parentBranch.childrenCount === 4) { + this._getForceContribution(parentBranch.children.NW, node); + this._getForceContribution(parentBranch.children.NE, node); + this._getForceContribution(parentBranch.children.SW, node); + this._getForceContribution(parentBranch.children.SE, node); + } else { + // parentBranch must have only one node, if it was empty we wouldnt be here + if (parentBranch.children.data.id != node.id) { + // if it is not self + this._calculateForces(distance, dx, dy, node, parentBranch); + } } } } } - }]); - - return RepulsionSolver; - })(); - - exports["default"] = RepulsionSolver; - module.exports = exports["default"]; - -/***/ }, -/* 94 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + }, { + key: "_calculateForces", - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** + * Calculate the forces based on the distance. + * + * @param distance + * @param dx + * @param dy + * @param node + * @param parentBranch + * @private + */ + value: function _calculateForces(distance, dx, dy, node, parentBranch) { + if (distance === 0) { + distance = 0.1; + dx = distance; + } - var HierarchicalRepulsionSolver = (function () { - function HierarchicalRepulsionSolver(body, physicsBody, options) { - _classCallCheck(this, HierarchicalRepulsionSolver); + if (this.overlapAvoidanceFactor < 1) { + distance = Math.max(0.1 + this.overlapAvoidanceFactor * node.shape.radius, distance - node.shape.radius); + } - this.body = body; - this.physicsBody = physicsBody; - this.setOptions(options); - } + // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines + // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce + var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass / Math.pow(distance, 3); + var fx = dx * gravityForce; + var fy = dy * gravityForce; - _createClass(HierarchicalRepulsionSolver, [{ - key: "setOptions", - value: function setOptions(options) { - this.options = options; + this.physicsBody.forces[node.id].x += fx; + this.physicsBody.forces[node.id].y += fy; } }, { - key: "solve", + key: "_formBarnesHutTree", /** - * Calculate the forces the nodes apply on each other based on a repulsion field. - * This field is linearly approximated. + * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes. * + * @param nodes + * @param nodeIndices * @private */ - value: function solve() { - var dx, dy, distance, fx, fy, repulsingForce, node1, node2, i, j; - - var nodes = this.body.nodes; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var forces = this.physicsBody.forces; - - // repulsing forces between nodes - var nodeDistance = this.options.nodeDistance; - - // we loop from i over all but the last entree in the array - // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j - for (i = 0; i < nodeIndices.length - 1; i++) { - node1 = nodes[nodeIndices[i]]; - for (j = i + 1; j < nodeIndices.length; j++) { - node2 = nodes[nodeIndices[j]]; - - // nodes only affect nodes on their level - if (node1.level === node2.level) { - dx = node2.x - node1.x; - dy = node2.y - node1.y; - distance = Math.sqrt(dx * dx + dy * dy); + value: function _formBarnesHutTree(nodes, nodeIndices) { + var node = undefined; + var nodeCount = nodeIndices.length; - var steepness = 0.05; - if (distance < nodeDistance) { - repulsingForce = -Math.pow(steepness * distance, 2) + Math.pow(steepness * nodeDistance, 2); - } else { - repulsingForce = 0; - } - // normalize force with - if (distance === 0) { - distance = 0.01; - } else { - repulsingForce = repulsingForce / distance; - } - fx = dx * repulsingForce; - fy = dy * repulsingForce; + var minX = nodes[nodeIndices[0]].x; + var minY = nodes[nodeIndices[0]].y; + var maxX = nodes[nodeIndices[0]].x; + var maxY = nodes[nodeIndices[0]].y; - forces[node1.id].x -= fx; - forces[node1.id].y -= fy; - forces[node2.id].x += fx; - forces[node2.id].y += fy; + // get the range of the nodes + for (var i = 1; i < nodeCount; i++) { + var x = nodes[nodeIndices[i]].x; + var y = nodes[nodeIndices[i]].y; + if (nodes[nodeIndices[i]].options.mass > 0) { + if (x < minX) { + minX = x; + } + if (x > maxX) { + maxX = x; + } + if (y < minY) { + minY = y; + } + if (y > maxY) { + maxY = y; } } } - } - }]); + // make the range a square + var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y + if (sizeDiff > 0) { + minY -= 0.5 * sizeDiff; + maxY += 0.5 * sizeDiff; + } // xSize > ySize + else { + minX += 0.5 * sizeDiff; + maxX -= 0.5 * sizeDiff; + } // xSize < ySize - return HierarchicalRepulsionSolver; - })(); + var minimumTreeSize = 0.00001; + var rootSize = Math.max(minimumTreeSize, Math.abs(maxX - minX)); + var halfRootSize = 0.5 * rootSize; + var centerX = 0.5 * (minX + maxX), + centerY = 0.5 * (minY + maxY); - exports["default"] = HierarchicalRepulsionSolver; - module.exports = exports["default"]; + // construct the barnesHutTree + var barnesHutTree = { + root: { + centerOfMass: { x: 0, y: 0 }, + mass: 0, + range: { + minX: centerX - halfRootSize, maxX: centerX + halfRootSize, + minY: centerY - halfRootSize, maxY: centerY + halfRootSize + }, + size: rootSize, + calcSize: 1 / rootSize, + children: { data: null }, + maxWidth: 0, + level: 0, + childrenCount: 4 + } + }; + this._splitBranch(barnesHutTree.root); -/***/ }, -/* 95 */ -/***/ function(module, exports, __webpack_require__) { + // place the nodes one by one recursively + for (var i = 0; i < nodeCount; i++) { + node = nodes[nodeIndices[i]]; + if (node.options.mass > 0) { + this._placeInTree(barnesHutTree.root, node); + } + } - "use strict"; + // make global + return barnesHutTree; + } + }, { + key: "_updateBranchMass", - Object.defineProperty(exports, "__esModule", { - value: true - }); + /** + * this updates the mass of a branch. this is increased by adding a node. + * + * @param parentBranch + * @param node + * @private + */ + value: function _updateBranchMass(parentBranch, node) { + var totalMass = parentBranch.mass + node.options.mass; + var totalMassInv = 1 / totalMass; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass; + parentBranch.centerOfMass.x *= totalMassInv; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass; + parentBranch.centerOfMass.y *= totalMassInv; - var SpringSolver = (function () { - function SpringSolver(body, physicsBody, options) { - _classCallCheck(this, SpringSolver); + parentBranch.mass = totalMass; + var biggestSize = Math.max(Math.max(node.height, node.radius), node.width); + parentBranch.maxWidth = parentBranch.maxWidth < biggestSize ? biggestSize : parentBranch.maxWidth; + } + }, { + key: "_placeInTree", - this.body = body; - this.physicsBody = physicsBody; - this.setOptions(options); - } + /** + * determine in which branch the node will be placed. + * + * @param parentBranch + * @param node + * @param skipMassUpdate + * @private + */ + value: function _placeInTree(parentBranch, node, skipMassUpdate) { + if (skipMassUpdate != true || skipMassUpdate === undefined) { + // update the mass of the branch. + this._updateBranchMass(parentBranch, node); + } - _createClass(SpringSolver, [{ - key: "setOptions", - value: function setOptions(options) { - this.options = options; + if (parentBranch.children.NW.range.maxX > node.x) { + // in NW or SW + if (parentBranch.children.NW.range.maxY > node.y) { + // in NW + this._placeInRegion(parentBranch, node, "NW"); + } else { + // in SW + this._placeInRegion(parentBranch, node, "SW"); + } + } else { + // in NE or SE + if (parentBranch.children.NW.range.maxY > node.y) { + // in NE + this._placeInRegion(parentBranch, node, "NE"); + } else { + // in SE + this._placeInRegion(parentBranch, node, "SE"); + } + } } }, { - key: "solve", + key: "_placeInRegion", /** - * This function calculates the springforces on the nodes, accounting for the support nodes. + * actually place the node in a region (or branch) * + * @param parentBranch + * @param node + * @param region * @private */ - value: function solve() { - var edgeLength = undefined, - edge = undefined; - var edgeIndices = this.physicsBody.physicsEdgeIndices; - var edges = this.body.edges; - var node1 = undefined, - node2 = undefined, - node3 = undefined; - - // forces caused by the edges, modelled as springs - for (var i = 0; i < edgeIndices.length; i++) { - edge = edges[edgeIndices[i]]; - if (edge.connected === true && edge.toId !== edge.fromId) { - // only calculate forces if nodes are in the same sector - if (this.body.nodes[edge.toId] !== undefined && this.body.nodes[edge.fromId] !== undefined) { - if (edge.edgeType.via !== undefined) { - edgeLength = edge.options.length === undefined ? this.options.springLength : edge.options.length; - node1 = edge.to; - node2 = edge.edgeType.via; - node3 = edge.from; - - this._calculateSpringForce(node1, node2, 0.5 * edgeLength); - this._calculateSpringForce(node2, node3, 0.5 * edgeLength); - } else { - // the * 1.5 is here so the edge looks as large as a smooth edge. It does not initially because the smooth edges use - // the support nodes which exert a repulsive force on the to and from nodes, making the edge appear larger. - edgeLength = edge.options.length === undefined ? this.options.springLength * 1.5 : edge.options.length; - this._calculateSpringForce(edge.from, edge.to, edgeLength); - } + value: function _placeInRegion(parentBranch, node, region) { + switch (parentBranch.children[region].childrenCount) { + case 0: + // place node here + parentBranch.children[region].children.data = node; + parentBranch.children[region].childrenCount = 1; + this._updateBranchMass(parentBranch.children[region], node); + break; + case 1: + // convert into children + // if there are two nodes exactly overlapping (on init, on opening of cluster etc.) + // we move one node a pixel and we do not put it in the tree. + if (parentBranch.children[region].children.data.x === node.x && parentBranch.children[region].children.data.y === node.y) { + //node.x += Math.random(); + //node.y += Math.random(); + node.x += 0.1; + node.y += 0.1; + } else { + this._splitBranch(parentBranch.children[region]); + this._placeInTree(parentBranch.children[region], node); } - } + break; + case 4: + // place in branch + this._placeInTree(parentBranch.children[region], node); + break; } } }, { - key: "_calculateSpringForce", + key: "_splitBranch", /** - * This is the code actually performing the calculation for the function above. + * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch + * after the split is complete. * - * @param node1 - * @param node2 - * @param edgeLength + * @param parentBranch * @private */ - value: function _calculateSpringForce(node1, node2, edgeLength) { - var dx = node1.x - node2.x; - var dy = node1.y - node2.y; - var distance = Math.max(Math.sqrt(dx * dx + dy * dy), 0.01); - - // the 1/distance is so the fx and fy can be calculated without sine or cosine. - var springForce = this.options.springConstant * (edgeLength - distance) / distance; - - var fx = dx * springForce; - var fy = dy * springForce; - - // handle the case where one node is not part of the physcis - if (this.physicsBody.forces[node1.id] !== undefined) { - this.physicsBody.forces[node1.id].x += fx; - this.physicsBody.forces[node1.id].y += fy; + value: function _splitBranch(parentBranch) { + // if the branch is shaded with a node, replace the node in the new subset. + var containedNode = null; + if (parentBranch.childrenCount === 1) { + containedNode = parentBranch.children.data; + parentBranch.mass = 0; + parentBranch.centerOfMass.x = 0; + parentBranch.centerOfMass.y = 0; } + parentBranch.childrenCount = 4; + parentBranch.children.data = null; + this._insertRegion(parentBranch, "NW"); + this._insertRegion(parentBranch, "NE"); + this._insertRegion(parentBranch, "SW"); + this._insertRegion(parentBranch, "SE"); - if (this.physicsBody.forces[node2.id] !== undefined) { - this.physicsBody.forces[node2.id].x -= fx; - this.physicsBody.forces[node2.id].y -= fy; + if (containedNode != null) { + this._placeInTree(parentBranch, containedNode); } } - }]); - - return SpringSolver; - })(); - - exports["default"] = SpringSolver; - module.exports = exports["default"]; - -/***/ }, -/* 96 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; + }, { + key: "_insertRegion", - Object.defineProperty(exports, "__esModule", { - value: true - }); + /** + * This function subdivides the region into four new segments. + * Specifically, this inserts a single new segment. + * It fills the children section of the parentBranch + * + * @param parentBranch + * @param region + * @param parentRange + * @private + */ + value: function _insertRegion(parentBranch, region) { + var minX = undefined, + maxX = undefined, + minY = undefined, + maxY = undefined; + var childSize = 0.5 * parentBranch.size; + switch (region) { + case "NW": + minX = parentBranch.range.minX; + maxX = parentBranch.range.minX + childSize; + minY = parentBranch.range.minY; + maxY = parentBranch.range.minY + childSize; + break; + case "NE": + minX = parentBranch.range.minX + childSize; + maxX = parentBranch.range.maxX; + minY = parentBranch.range.minY; + maxY = parentBranch.range.minY + childSize; + break; + case "SW": + minX = parentBranch.range.minX; + maxX = parentBranch.range.minX + childSize; + minY = parentBranch.range.minY + childSize; + maxY = parentBranch.range.maxY; + break; + case "SE": + minX = parentBranch.range.minX + childSize; + maxX = parentBranch.range.maxX; + minY = parentBranch.range.minY + childSize; + maxY = parentBranch.range.maxY; + break; + } - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + parentBranch.children[region] = { + centerOfMass: { x: 0, y: 0 }, + mass: 0, + range: { minX: minX, maxX: maxX, minY: minY, maxY: maxY }, + size: 0.5 * parentBranch.size, + calcSize: 2 * parentBranch.calcSize, + children: { data: null }, + maxWidth: 0, + level: parentBranch.level + 1, + childrenCount: 0 + }; + } + }, { + key: "_debug", - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + //--------------------------- DEBUGGING BELOW ---------------------------// - var HierarchicalSpringSolver = (function () { - function HierarchicalSpringSolver(body, physicsBody, options) { - _classCallCheck(this, HierarchicalSpringSolver); + /** + * This function is for debugging purposed, it draws the tree. + * + * @param ctx + * @param color + * @private + */ + value: function _debug(ctx, color) { + if (this.barnesHutTree !== undefined) { - this.body = body; - this.physicsBody = physicsBody; - this.setOptions(options); - } + ctx.lineWidth = 1; - _createClass(HierarchicalSpringSolver, [{ - key: "setOptions", - value: function setOptions(options) { - this.options = options; + this._drawBranch(this.barnesHutTree.root, ctx, color); + } } }, { - key: "solve", + key: "_drawBranch", /** - * This function calculates the springforces on the nodes, accounting for the support nodes. + * This function is for debugging purposes. It draws the branches recursively. * + * @param branch + * @param ctx + * @param color * @private */ - value: function solve() { - var edgeLength, edge; - var dx, dy, fx, fy, springForce, distance; - var edges = this.body.edges; - var factor = 0.5; - - var edgeIndices = this.physicsBody.physicsEdgeIndices; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var forces = this.physicsBody.forces; - - // initialize the spring force counters - for (var i = 0; i < nodeIndices.length; i++) { - var nodeId = nodeIndices[i]; - forces[nodeId].springFx = 0; - forces[nodeId].springFy = 0; + value: function _drawBranch(branch, ctx, color) { + if (color === undefined) { + color = "#FF0000"; } - // forces caused by the edges, modelled as springs - for (var i = 0; i < edgeIndices.length; i++) { - edge = edges[edgeIndices[i]]; - if (edge.connected === true) { - edgeLength = edge.options.length === undefined ? this.options.springLength : edge.options.length; - - dx = edge.from.x - edge.to.x; - dy = edge.from.y - edge.to.y; - distance = Math.sqrt(dx * dx + dy * dy); - distance = distance === 0 ? 0.01 : distance; - - // the 1/distance is so the fx and fy can be calculated without sine or cosine. - springForce = this.options.springConstant * (edgeLength - distance) / distance; - - fx = dx * springForce; - fy = dy * springForce; - - if (edge.to.level != edge.from.level) { - forces[edge.toId].springFx -= fx; - forces[edge.toId].springFy -= fy; - forces[edge.fromId].springFx += fx; - forces[edge.fromId].springFy += fy; - } else { - forces[edge.toId].x -= factor * fx; - forces[edge.toId].y -= factor * fy; - forces[edge.fromId].x += factor * fx; - forces[edge.fromId].y += factor * fy; - } - } + if (branch.childrenCount === 4) { + this._drawBranch(branch.children.NW, ctx); + this._drawBranch(branch.children.NE, ctx); + this._drawBranch(branch.children.SE, ctx); + this._drawBranch(branch.children.SW, ctx); } + ctx.strokeStyle = color; + ctx.beginPath(); + ctx.moveTo(branch.range.minX, branch.range.minY); + ctx.lineTo(branch.range.maxX, branch.range.minY); + ctx.stroke(); - // normalize spring forces - var springForce = 1; - var springFx, springFy; - for (var i = 0; i < nodeIndices.length; i++) { - var nodeId = nodeIndices[i]; - springFx = Math.min(springForce, Math.max(-springForce, forces[nodeId].springFx)); - springFy = Math.min(springForce, Math.max(-springForce, forces[nodeId].springFy)); + ctx.beginPath(); + ctx.moveTo(branch.range.maxX, branch.range.minY); + ctx.lineTo(branch.range.maxX, branch.range.maxY); + ctx.stroke(); - forces[nodeId].x += springFx; - forces[nodeId].y += springFy; - } + ctx.beginPath(); + ctx.moveTo(branch.range.maxX, branch.range.maxY); + ctx.lineTo(branch.range.minX, branch.range.maxY); + ctx.stroke(); - // retain energy balance - var totalFx = 0; - var totalFy = 0; - for (var i = 0; i < nodeIndices.length; i++) { - var nodeId = nodeIndices[i]; - totalFx += forces[nodeId].x; - totalFy += forces[nodeId].y; - } - var correctionFx = totalFx / nodeIndices.length; - var correctionFy = totalFy / nodeIndices.length; + ctx.beginPath(); + ctx.moveTo(branch.range.minX, branch.range.maxY); + ctx.lineTo(branch.range.minX, branch.range.minY); + ctx.stroke(); - for (var i = 0; i < nodeIndices.length; i++) { - var nodeId = nodeIndices[i]; - forces[nodeId].x -= correctionFx; - forces[nodeId].y -= correctionFy; - } + /* + if (branch.mass > 0) { + ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass); + ctx.stroke(); + } + */ } }]); - return HierarchicalSpringSolver; + return BarnesHutSolver; })(); - exports["default"] = HierarchicalSpringSolver; + exports["default"] = BarnesHutSolver; module.exports = exports["default"]; /***/ }, -/* 97 */ +/* 78 */ /***/ function(module, exports, __webpack_require__) { "use strict"; @@ -35763,918 +36841,610 @@ return /******/ (function(modules) { // webpackBootstrap function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var CentralGravitySolver = (function () { - function CentralGravitySolver(body, physicsBody, options) { - _classCallCheck(this, CentralGravitySolver); + var RepulsionSolver = (function () { + function RepulsionSolver(body, physicsBody, options) { + _classCallCheck(this, RepulsionSolver); this.body = body; this.physicsBody = physicsBody; this.setOptions(options); } - _createClass(CentralGravitySolver, [{ + _createClass(RepulsionSolver, [{ key: "setOptions", value: function setOptions(options) { this.options = options; } }, { key: "solve", - value: function solve() { - var dx = undefined, - dy = undefined, - distance = undefined, - node = undefined; - var nodes = this.body.nodes; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var forces = this.physicsBody.forces; - - for (var i = 0; i < nodeIndices.length; i++) { - var nodeId = nodeIndices[i]; - node = nodes[nodeId]; - dx = -node.x; - dy = -node.y; - distance = Math.sqrt(dx * dx + dy * dy); - - this._calculateForces(distance, dx, dy, forces, node); - } - } - }, { - key: "_calculateForces", - - /** - * Calculate the forces based on the distance. - * @private - */ - value: function _calculateForces(distance, dx, dy, forces, node) { - var gravityForce = distance === 0 ? 0 : this.options.centralGravity / distance; - forces[node.id].x = dx * gravityForce; - forces[node.id].y = dy * gravityForce; - } - }]); - - return CentralGravitySolver; - })(); - - exports["default"] = CentralGravitySolver; - module.exports = exports["default"]; - -/***/ }, -/* 98 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - - var _BarnesHutSolver2 = __webpack_require__(3); - - var _BarnesHutSolver3 = _interopRequireDefault(_BarnesHutSolver2); - - var ForceAtlas2BasedRepulsionSolver = (function (_BarnesHutSolver) { - function ForceAtlas2BasedRepulsionSolver(body, physicsBody, options) { - _classCallCheck(this, ForceAtlas2BasedRepulsionSolver); - - _get(Object.getPrototypeOf(ForceAtlas2BasedRepulsionSolver.prototype), "constructor", this).call(this, body, physicsBody, options); - } - - _inherits(ForceAtlas2BasedRepulsionSolver, _BarnesHutSolver); - - _createClass(ForceAtlas2BasedRepulsionSolver, [{ - key: "_calculateForces", /** - * Calculate the forces based on the distance. + * Calculate the forces the nodes apply on each other based on a repulsion field. + * This field is linearly approximated. * - * @param distance - * @param dx - * @param dy - * @param node - * @param parentBranch * @private */ - value: function _calculateForces(distance, dx, dy, node, parentBranch) { - if (distance === 0) { - distance = 0.1 * Math.random(); - dx = distance; - } - - if (this.overlapAvoidanceFactor < 1) { - distance = Math.max(0.1 + this.overlapAvoidanceFactor * node.shape.radius, distance - node.shape.radius); - } - - var degree = node.edges.length + 1; - // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines - // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce - var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass * degree / Math.pow(distance, 2); - var fx = dx * gravityForce; - var fy = dy * gravityForce; - - this.physicsBody.forces[node.id].x += fx; - this.physicsBody.forces[node.id].y += fy; - } - }]); - - return ForceAtlas2BasedRepulsionSolver; - })(_BarnesHutSolver3["default"]); - - exports["default"] = ForceAtlas2BasedRepulsionSolver; - module.exports = exports["default"]; - -/***/ }, -/* 99 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + value: function solve() { + var dx, dy, distance, fx, fy, repulsingForce, node1, node2; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var nodes = this.body.nodes; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var forces = this.physicsBody.forces; - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + // repulsing forces between nodes + var nodeDistance = this.options.nodeDistance; - var _CentralGravitySolver2 = __webpack_require__(97); + // approximation constants + var a = -2 / 3 / nodeDistance; + var b = 4 / 3; - var _CentralGravitySolver3 = _interopRequireDefault(_CentralGravitySolver2); + // we loop from i over all but the last entree in the array + // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j + for (var i = 0; i < nodeIndices.length - 1; i++) { + node1 = nodes[nodeIndices[i]]; + for (var j = i + 1; j < nodeIndices.length; j++) { + node2 = nodes[nodeIndices[j]]; - var ForceAtlas2BasedCentralGravitySolver = (function (_CentralGravitySolver) { - function ForceAtlas2BasedCentralGravitySolver(body, physicsBody, options) { - _classCallCheck(this, ForceAtlas2BasedCentralGravitySolver); + dx = node2.x - node1.x; + dy = node2.y - node1.y; + distance = Math.sqrt(dx * dx + dy * dy); - _get(Object.getPrototypeOf(ForceAtlas2BasedCentralGravitySolver.prototype), "constructor", this).call(this, body, physicsBody, options); - } + // same condition as BarnesHutSolver, making sure nodes are never 100% overlapping. + if (distance === 0) { + distance = 0.1 * Math.random(); + dx = distance; + } - _inherits(ForceAtlas2BasedCentralGravitySolver, _CentralGravitySolver); + if (distance < 2 * nodeDistance) { + if (distance < 0.5 * nodeDistance) { + repulsingForce = 1; + } else { + repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / nodeDistance - 1) * steepness)) + } + repulsingForce = repulsingForce / distance; - _createClass(ForceAtlas2BasedCentralGravitySolver, [{ - key: "_calculateForces", + fx = dx * repulsingForce; + fy = dy * repulsingForce; - /** - * Calculate the forces based on the distance. - * @private - */ - value: function _calculateForces(distance, dx, dy, forces, node) { - if (distance > 0) { - var degree = node.edges.length + 1; - var gravityForce = this.options.centralGravity * degree * node.options.mass; - forces[node.id].x = dx * gravityForce; - forces[node.id].y = dy * gravityForce; + forces[node1.id].x -= fx; + forces[node1.id].y -= fy; + forces[node2.id].x += fx; + forces[node2.id].y += fy; + } + } } } }]); - return ForceAtlas2BasedCentralGravitySolver; - })(_CentralGravitySolver3["default"]); + return RepulsionSolver; + })(); - exports["default"] = ForceAtlas2BasedCentralGravitySolver; + exports["default"] = RepulsionSolver; module.exports = exports["default"]; /***/ }, -/* 100 */ +/* 79 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; + "use strict"; - Object.defineProperty(exports, '__esModule', { + Object.defineProperty(exports, "__esModule", { value: true }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - var _componentsNodesCluster = __webpack_require__(101); - - var _componentsNodesCluster2 = _interopRequireDefault(_componentsNodesCluster); - - var util = __webpack_require__(2); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var ClusterEngine = (function () { - function ClusterEngine(body) { - var _this = this; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - _classCallCheck(this, ClusterEngine); + var HierarchicalRepulsionSolver = (function () { + function HierarchicalRepulsionSolver(body, physicsBody, options) { + _classCallCheck(this, HierarchicalRepulsionSolver); this.body = body; - this.clusteredNodes = {}; - - this.options = {}; - this.defaultOptions = {}; - util.extend(this.options, this.defaultOptions); - - this.body.emitter.on('_resetData', function () { - _this.clusteredNodes = {}; - }); + this.physicsBody = physicsBody; + this.setOptions(options); } - _createClass(ClusterEngine, [{ - key: 'setOptions', + _createClass(HierarchicalRepulsionSolver, [{ + key: "setOptions", value: function setOptions(options) { - if (options !== undefined) {} + this.options = options; } }, { - key: 'clusterByHubsize', + key: "solve", /** - * - * @param hubsize - * @param options - */ - value: function clusterByHubsize(hubsize, options) { - if (hubsize === undefined) { - hubsize = this._getHubSize(); - } else if (typeof hubsize === 'object') { - options = this._checkOptions(hubsize); - hubsize = this._getHubSize(); - } - - var nodesToCluster = []; - for (var i = 0; i < this.body.nodeIndices.length; i++) { - var node = this.body.nodes[this.body.nodeIndices[i]]; - if (node.edges.length >= hubsize) { - nodesToCluster.push(node.id); - } - } - - for (var i = 0; i < nodesToCluster.length; i++) { - this.clusterByConnection(nodesToCluster[i], options, false); - } - this.body.emitter.emit('_dataChanged'); - } - }, { - key: 'cluster', + * Calculate the forces the nodes apply on each other based on a repulsion field. + * This field is linearly approximated. + * + * @private + */ + value: function solve() { + var dx, dy, distance, fx, fy, repulsingForce, node1, node2, i, j; - /** - * loop over all nodes, check if they adhere to the condition and cluster if needed. - * @param options - * @param refreshData - */ - value: function cluster() { - var options = arguments[0] === undefined ? {} : arguments[0]; - var refreshData = arguments[1] === undefined ? true : arguments[1]; + var nodes = this.body.nodes; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var forces = this.physicsBody.forces; - if (options.joinCondition === undefined) { - throw new Error('Cannot call clusterByNodeData without a joinCondition function in the options.'); - } + // repulsing forces between nodes + var nodeDistance = this.options.nodeDistance; - // check if the options object is fine, append if needed - options = this._checkOptions(options); + // we loop from i over all but the last entree in the array + // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j + for (i = 0; i < nodeIndices.length - 1; i++) { + node1 = nodes[nodeIndices[i]]; + for (j = i + 1; j < nodeIndices.length; j++) { + node2 = nodes[nodeIndices[j]]; - var childNodesObj = {}; - var childEdgesObj = {}; + // nodes only affect nodes on their level + if (node1.level === node2.level) { + dx = node2.x - node1.x; + dy = node2.y - node1.y; + distance = Math.sqrt(dx * dx + dy * dy); - // collect the nodes that will be in the cluster - for (var i = 0; i < this.body.nodeIndices.length; i++) { - var nodeId = this.body.nodeIndices[i]; - var node = this.body.nodes[nodeId]; - var clonedOptions = this._cloneOptions(node); - if (options.joinCondition(clonedOptions) === true) { - childNodesObj[nodeId] = this.body.nodes[nodeId]; + var steepness = 0.05; + if (distance < nodeDistance) { + repulsingForce = -Math.pow(steepness * distance, 2) + Math.pow(steepness * nodeDistance, 2); + } else { + repulsingForce = 0; + } + // normalize force with + if (distance === 0) { + distance = 0.01; + } else { + repulsingForce = repulsingForce / distance; + } + fx = dx * repulsingForce; + fy = dy * repulsingForce; - // collect the nodes that will be in the cluster - for (var _i = 0; _i < node.edges.length; _i++) { - var edge = node.edges[_i]; - childEdgesObj[edge.id] = edge; + forces[node1.id].x -= fx; + forces[node1.id].y -= fy; + forces[node2.id].x += fx; + forces[node2.id].y += fy; } } } - - this._cluster(childNodesObj, childEdgesObj, options, refreshData); } - }, { - key: 'clusterOutliers', + }]); - /** - * Cluster all nodes in the network that have only 1 edge - * @param options - * @param refreshData - */ - value: function clusterOutliers(options) { - var refreshData = arguments[1] === undefined ? true : arguments[1]; + return HierarchicalRepulsionSolver; + })(); - options = this._checkOptions(options); - var clusters = []; + exports["default"] = HierarchicalRepulsionSolver; + module.exports = exports["default"]; - // collect the nodes that will be in the cluster - for (var i = 0; i < this.body.nodeIndices.length; i++) { - var childNodesObj = {}; - var childEdgesObj = {}; - var nodeId = this.body.nodeIndices[i]; - var visibleEdges = 0; - var edge = undefined; - for (var j = 0; j < this.body.nodes[nodeId].edges.length; j++) { - if (this.body.nodes[nodeId].edges[j].options.hidden === false) { - visibleEdges++; - edge = this.body.nodes[nodeId].edges[j]; - } - } +/***/ }, +/* 80 */ +/***/ function(module, exports, __webpack_require__) { - if (visibleEdges === 1) { - // this is an outlier - var childNodeId = this._getConnectedId(edge, nodeId); - if (childNodeId !== nodeId) { - if (options.joinCondition === undefined) { - if (this._checkIfUsed(clusters, nodeId, edge.id) === false && this._checkIfUsed(clusters, childNodeId, edge.id) === false) { - childEdgesObj[edge.id] = edge; - childNodesObj[nodeId] = this.body.nodes[nodeId]; - childNodesObj[childNodeId] = this.body.nodes[childNodeId]; - } - } else { - var clonedOptions = this._cloneOptions(this.body.nodes[nodeId]); - if (options.joinCondition(clonedOptions) === true && this._checkIfUsed(clusters, nodeId, edge.id) === false) { - childEdgesObj[edge.id] = edge; - childNodesObj[nodeId] = this.body.nodes[nodeId]; - } - clonedOptions = this._cloneOptions(this.body.nodes[childNodeId]); - if (options.joinCondition(clonedOptions) === true && this._checkIfUsed(clusters, nodeId, edge.id) === false) { - childEdgesObj[edge.id] = edge; - childNodesObj[childNodeId] = this.body.nodes[childNodeId]; - } - } + "use strict"; - if (Object.keys(childNodesObj).length > 0 && Object.keys(childEdgesObj).length > 0) { - clusters.push({ nodes: childNodesObj, edges: childEdgesObj }); - } - } - } - } + Object.defineProperty(exports, "__esModule", { + value: true + }); - for (var i = 0; i < clusters.length; i++) { - this._cluster(clusters[i].nodes, clusters[i].edges, options, false); - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - if (refreshData === true) { - this.body.emitter.emit('_dataChanged'); - } - } - }, { - key: '_checkIfUsed', - value: function _checkIfUsed(clusters, nodeId, edgeId) { - for (var i = 0; i < clusters.length; i++) { - var cluster = clusters[i]; - if (cluster.nodes[nodeId] !== undefined || cluster.edges[edgeId] !== undefined) { - return true; - } - } - return false; - } - }, { - key: 'clusterByConnection', + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - /** - * suck all connected nodes of a node into the node. - * @param nodeId - * @param options - * @param refreshData - */ - value: function clusterByConnection(nodeId, options) { - var refreshData = arguments[2] === undefined ? true : arguments[2]; + var SpringSolver = (function () { + function SpringSolver(body, physicsBody, options) { + _classCallCheck(this, SpringSolver); - // kill conditions - if (nodeId === undefined) { - throw new Error('No nodeId supplied to clusterByConnection!'); - } - if (this.body.nodes[nodeId] === undefined) { - throw new Error('The nodeId given to clusterByConnection does not exist!'); - } + this.body = body; + this.physicsBody = physicsBody; + this.setOptions(options); + } - var node = this.body.nodes[nodeId]; - options = this._checkOptions(options, node); - if (options.clusterNodeProperties.x === undefined) { - options.clusterNodeProperties.x = node.x; - } - if (options.clusterNodeProperties.y === undefined) { - options.clusterNodeProperties.y = node.y; - } - if (options.clusterNodeProperties.fixed === undefined) { - options.clusterNodeProperties.fixed = {}; - options.clusterNodeProperties.fixed.x = node.options.fixed.x; - options.clusterNodeProperties.fixed.y = node.options.fixed.y; - } + _createClass(SpringSolver, [{ + key: "setOptions", + value: function setOptions(options) { + this.options = options; + } + }, { + key: "solve", - var childNodesObj = {}; - var childEdgesObj = {}; - var parentNodeId = node.id; - var parentClonedOptions = this._cloneOptions(node); - childNodesObj[parentNodeId] = node; + /** + * This function calculates the springforces on the nodes, accounting for the support nodes. + * + * @private + */ + value: function solve() { + var edgeLength = undefined, + edge = undefined; + var edgeIndices = this.physicsBody.physicsEdgeIndices; + var edges = this.body.edges; + var node1 = undefined, + node2 = undefined, + node3 = undefined; - // collect the nodes that will be in the cluster - for (var i = 0; i < node.edges.length; i++) { - var edge = node.edges[i]; - var childNodeId = this._getConnectedId(edge, parentNodeId); + // forces caused by the edges, modelled as springs + for (var i = 0; i < edgeIndices.length; i++) { + edge = edges[edgeIndices[i]]; + if (edge.connected === true && edge.toId !== edge.fromId) { + // only calculate forces if nodes are in the same sector + if (this.body.nodes[edge.toId] !== undefined && this.body.nodes[edge.fromId] !== undefined) { + if (edge.edgeType.via !== undefined) { + edgeLength = edge.options.length === undefined ? this.options.springLength : edge.options.length; + node1 = edge.to; + node2 = edge.edgeType.via; + node3 = edge.from; - if (childNodeId !== parentNodeId) { - if (options.joinCondition === undefined) { - childEdgesObj[edge.id] = edge; - childNodesObj[childNodeId] = this.body.nodes[childNodeId]; - } else { - // clone the options and insert some additional parameters that could be interesting. - var childClonedOptions = this._cloneOptions(this.body.nodes[childNodeId]); - if (options.joinCondition(parentClonedOptions, childClonedOptions) === true) { - childEdgesObj[edge.id] = edge; - childNodesObj[childNodeId] = this.body.nodes[childNodeId]; + this._calculateSpringForce(node1, node2, 0.5 * edgeLength); + this._calculateSpringForce(node2, node3, 0.5 * edgeLength); + } else { + // the * 1.5 is here so the edge looks as large as a smooth edge. It does not initially because the smooth edges use + // the support nodes which exert a repulsive force on the to and from nodes, making the edge appear larger. + edgeLength = edge.options.length === undefined ? this.options.springLength * 1.5 : edge.options.length; + this._calculateSpringForce(edge.from, edge.to, edgeLength); } } - } else { - childEdgesObj[edge.id] = edge; } } - - this._cluster(childNodesObj, childEdgesObj, options, refreshData); } }, { - key: '_cloneOptions', + key: "_calculateSpringForce", /** - * 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 objId - * @param type - * @returns {{}} - * @private - */ - 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); + * This is the code actually performing the calculation for the function above. + * + * @param node1 + * @param node2 + * @param edgeLength + * @private + */ + value: function _calculateSpringForce(node1, node2, edgeLength) { + var dx = node1.x - node2.x; + var dy = node1.y - node2.y; + var distance = Math.max(Math.sqrt(dx * dx + dy * dy), 0.01); + + // the 1/distance is so the fx and fy can be calculated without sine or cosine. + var springForce = this.options.springConstant * (edgeLength - distance) / distance; + + var fx = dx * springForce; + var fy = dy * springForce; + + // handle the case where one node is not part of the physcis + if (this.physicsBody.forces[node1.id] !== undefined) { + this.physicsBody.forces[node1.id].x += fx; + this.physicsBody.forces[node1.id].y += fy; + } + + if (this.physicsBody.forces[node2.id] !== undefined) { + this.physicsBody.forces[node2.id].x -= fx; + this.physicsBody.forces[node2.id].y -= fy; } - return clonedOptions; } - }, { - key: '_createClusterEdges', + }]); - /** - * This function creates the edges that will be attached to the cluster. - * - * @param childNodesObj - * @param childEdgesObj - * @param newEdges - * @param options - * @private - */ - value: function _createClusterEdges(childNodesObj, childEdgesObj, newEdges, clusterNodeProperties, clusterEdgeProperties) { - var edge = undefined, - childNodeId = undefined, - childNode = undefined, - toId = undefined, - fromId = undefined, - otherNodeId = undefined; + return SpringSolver; + })(); - var childKeys = Object.keys(childNodesObj); - for (var i = 0; i < childKeys.length; i++) { - childNodeId = childKeys[i]; - childNode = childNodesObj[childNodeId]; + exports["default"] = SpringSolver; + module.exports = exports["default"]; - // construct new edges from the cluster to others - for (var j = 0; j < childNode.edges.length; j++) { - edge = childNode.edges[j]; - childEdgesObj[edge.id] = edge; +/***/ }, +/* 81 */ +/***/ function(module, exports, __webpack_require__) { - // childNodeId position will be replaced by the cluster. - if (edge.toId == childNodeId) { - // this is a double equals because ints and strings can be interchanged here. - toId = clusterNodeProperties.id; - fromId = edge.fromId; - otherNodeId = fromId; - } else { - toId = edge.toId; - fromId = clusterNodeProperties.id; - otherNodeId = toId; - } + "use strict"; - // if the node connected to the cluster is also in the cluster we do not need a new edge. - if (childNodesObj[otherNodeId] === undefined) { - var clonedOptions = this._cloneOptions(edge, 'edge'); - util.deepExtend(clonedOptions, clusterEdgeProperties); - clonedOptions.from = fromId; - clonedOptions.to = toId; - clonedOptions.id = 'clusterEdge:' + util.randomUUID(); - newEdges.push(this.body.functions.createEdge(clonedOptions)); - } - } - } - } - }, { - key: '_checkOptions', + Object.defineProperty(exports, "__esModule", { + value: true + }); - /** - * This function checks the options that can be supplied to the different cluster functions - * for certain fields and inserts defaults if needed - * @param options - * @returns {*} - * @private - */ - value: function _checkOptions() { - var options = arguments[0] === undefined ? {} : arguments[0]; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - if (options.clusterEdgeProperties === undefined) { - options.clusterEdgeProperties = {}; - } - if (options.clusterNodeProperties === undefined) { - options.clusterNodeProperties = {}; - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - return options; + var HierarchicalSpringSolver = (function () { + function HierarchicalSpringSolver(body, physicsBody, options) { + _classCallCheck(this, HierarchicalSpringSolver); + + this.body = body; + this.physicsBody = physicsBody; + this.setOptions(options); + } + + _createClass(HierarchicalSpringSolver, [{ + key: "setOptions", + value: function setOptions(options) { + this.options = options; } }, { - key: '_cluster', + key: "solve", /** - * - * @param {Object} childNodesObj | object with node objects, id as keys, same as childNodes except it also contains a source node - * @param {Object} childEdgesObj | object with edge objects, id as keys - * @param {Array} options | object with {clusterNodeProperties, clusterEdgeProperties, processProperties} - * @param {Boolean} refreshData | when true, do not wrap up - * @private - */ - value: function _cluster(childNodesObj, childEdgesObj, options) { - var refreshData = arguments[3] === undefined ? true : arguments[3]; + * This function calculates the springforces on the nodes, accounting for the support nodes. + * + * @private + */ + value: function solve() { + var edgeLength, edge; + var dx, dy, fx, fy, springForce, distance; + var edges = this.body.edges; + var factor = 0.5; - // kill condition: no children so cant cluster - if (Object.keys(childNodesObj).length === 0) { - return; + var edgeIndices = this.physicsBody.physicsEdgeIndices; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var forces = this.physicsBody.forces; + + // initialize the spring force counters + for (var i = 0; i < nodeIndices.length; i++) { + var nodeId = nodeIndices[i]; + forces[nodeId].springFx = 0; + forces[nodeId].springFy = 0; } - var clusterNodeProperties = util.deepExtend({}, options.clusterNodeProperties); + // forces caused by the edges, modelled as springs + for (var i = 0; i < edgeIndices.length; i++) { + edge = edges[edgeIndices[i]]; + if (edge.connected === true) { + edgeLength = edge.options.length === undefined ? this.options.springLength : edge.options.length; + + dx = edge.from.x - edge.to.x; + dy = edge.from.y - edge.to.y; + distance = Math.sqrt(dx * dx + dy * dy); + distance = distance === 0 ? 0.01 : distance; - // construct the clusterNodeProperties - if (options.processProperties !== undefined) { - // get the childNode options - var childNodesOptions = []; - for (var nodeId in childNodesObj) { - var clonedOptions = this._cloneOptions(childNodesObj[nodeId]); - childNodesOptions.push(clonedOptions); - } + // the 1/distance is so the fx and fy can be calculated without sine or cosine. + springForce = this.options.springConstant * (edgeLength - distance) / distance; - // get clusterproperties based on childNodes - var childEdgesOptions = []; - for (var edgeId in childEdgesObj) { - var clonedOptions = this._cloneOptions(childEdgesObj[edgeId], 'edge'); - childEdgesOptions.push(clonedOptions); - } + fx = dx * springForce; + fy = dy * springForce; - clusterNodeProperties = options.processProperties(clusterNodeProperties, childNodesOptions, childEdgesOptions); - if (!clusterNodeProperties) { - throw new Error('The processProperties function does not return properties!'); + if (edge.to.level != edge.from.level) { + forces[edge.toId].springFx -= fx; + forces[edge.toId].springFy -= fy; + forces[edge.fromId].springFx += fx; + forces[edge.fromId].springFy += fy; + } else { + forces[edge.toId].x -= factor * fx; + forces[edge.toId].y -= factor * fy; + forces[edge.fromId].x += factor * fx; + forces[edge.fromId].y += factor * fy; + } } } - // check if we have an unique id; - if (clusterNodeProperties.id === undefined) { - clusterNodeProperties.id = 'cluster:' + util.randomUUID(); - } - var clusterId = clusterNodeProperties.id; + // normalize spring forces + var springForce = 1; + var springFx, springFy; + for (var i = 0; i < nodeIndices.length; i++) { + var nodeId = nodeIndices[i]; + springFx = Math.min(springForce, Math.max(-springForce, forces[nodeId].springFx)); + springFy = Math.min(springForce, Math.max(-springForce, forces[nodeId].springFy)); - if (clusterNodeProperties.label === undefined) { - clusterNodeProperties.label = 'cluster'; + forces[nodeId].x += springFx; + forces[nodeId].y += springFy; } - // give the clusterNode a postion if it does not have one. - var pos = undefined; - if (clusterNodeProperties.x === undefined) { - pos = this._getClusterPosition(childNodesObj); - clusterNodeProperties.x = pos.x; + // retain energy balance + var totalFx = 0; + var totalFy = 0; + for (var i = 0; i < nodeIndices.length; i++) { + var nodeId = nodeIndices[i]; + totalFx += forces[nodeId].x; + totalFy += forces[nodeId].y; } - if (clusterNodeProperties.y === undefined) { - if (pos === undefined) { - pos = this._getClusterPosition(childNodesObj); - } - clusterNodeProperties.y = pos.y; + var correctionFx = totalFx / nodeIndices.length; + var correctionFy = totalFy / nodeIndices.length; + + for (var i = 0; i < nodeIndices.length; i++) { + var nodeId = nodeIndices[i]; + forces[nodeId].x -= correctionFx; + forces[nodeId].y -= correctionFy; } + } + }]); - // force the ID to remain the same - clusterNodeProperties.id = clusterId; + return HierarchicalSpringSolver; + })(); - // create the clusterNode - var clusterNode = this.body.functions.createNode(clusterNodeProperties, _componentsNodesCluster2['default']); - clusterNode.isCluster = true; - clusterNode.containedNodes = childNodesObj; - clusterNode.containedEdges = childEdgesObj; - // cache a copy from the cluster edge properties if we have to reconnect others later on - clusterNode.clusterEdgeProperties = options.clusterEdgeProperties; + exports["default"] = HierarchicalSpringSolver; + module.exports = exports["default"]; - // finally put the cluster node into global - this.body.nodes[clusterNodeProperties.id] = clusterNode; +/***/ }, +/* 82 */ +/***/ function(module, exports, __webpack_require__) { - // create the new edges that will connect to the cluster - var newEdges = []; - this._createClusterEdges(childNodesObj, childEdgesObj, newEdges, clusterNodeProperties, options.clusterEdgeProperties); + "use strict"; - // disable the childEdges - for (var edgeId in childEdgesObj) { - if (childEdgesObj.hasOwnProperty(edgeId)) { - if (this.body.edges[edgeId] !== undefined) { - var edge = this.body.edges[edgeId]; - edge.togglePhysics(false); - edge.options.hidden = true; - } - } - } + Object.defineProperty(exports, "__esModule", { + value: true + }); - // disable the childNodes - for (var nodeId in childNodesObj) { - if (childNodesObj.hasOwnProperty(nodeId)) { - this.clusteredNodes[nodeId] = { clusterId: clusterNodeProperties.id, node: this.body.nodes[nodeId] }; - this.body.nodes[nodeId].togglePhysics(false); - this.body.nodes[nodeId].options.hidden = true; - } - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // push new edges to global - for (var i = 0; i < newEdges.length; i++) { - this.body.edges[newEdges[i].id] = newEdges[i]; - this.body.edges[newEdges[i].id].connect(); - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - // set ID to undefined so no duplicates arise - clusterNodeProperties.id = undefined; + var CentralGravitySolver = (function () { + function CentralGravitySolver(body, physicsBody, options) { + _classCallCheck(this, CentralGravitySolver); - // wrap up - if (refreshData === true) { - this.body.emitter.emit('_dataChanged'); - } + this.body = body; + this.physicsBody = physicsBody; + this.setOptions(options); + } + + _createClass(CentralGravitySolver, [{ + key: "setOptions", + value: function setOptions(options) { + this.options = options; } }, { - key: 'isCluster', + key: "solve", + value: function solve() { + var dx = undefined, + dy = undefined, + distance = undefined, + node = undefined; + var nodes = this.body.nodes; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var forces = this.physicsBody.forces; - /** - * Check if a node is a cluster. - * @param nodeId - * @returns {*} - */ - value: function isCluster(nodeId) { - if (this.body.nodes[nodeId] !== undefined) { - return this.body.nodes[nodeId].isCluster === true; - } else { - console.log('Node does not exist.'); - return false; + for (var i = 0; i < nodeIndices.length; i++) { + var nodeId = nodeIndices[i]; + node = nodes[nodeId]; + dx = -node.x; + dy = -node.y; + distance = Math.sqrt(dx * dx + dy * dy); + + this._calculateForces(distance, dx, dy, forces, node); } } }, { - key: '_getClusterPosition', + key: "_calculateForces", /** - * get the position of the cluster node based on what's inside - * @param {object} childNodesObj | object with node objects, id as keys - * @returns {{x: number, y: number}} - * @private - */ - value: function _getClusterPosition(childNodesObj) { - var childKeys = Object.keys(childNodesObj); - var minX = childNodesObj[childKeys[0]].x; - var maxX = childNodesObj[childKeys[0]].x; - var minY = childNodesObj[childKeys[0]].y; - var maxY = childNodesObj[childKeys[0]].y; - var node = undefined; - for (var i = 1; i < childKeys.length; i++) { - node = childNodesObj[childKeys[i]]; - minX = node.x < minX ? node.x : minX; - maxX = node.x > maxX ? node.x : maxX; - minY = node.y < minY ? node.y : minY; - maxY = node.y > maxY ? node.y : maxY; - } - - return { x: 0.5 * (minX + maxX), y: 0.5 * (minY + maxY) }; + * Calculate the forces based on the distance. + * @private + */ + value: function _calculateForces(distance, dx, dy, forces, node) { + var gravityForce = distance === 0 ? 0 : this.options.centralGravity / distance; + forces[node.id].x = dx * gravityForce; + forces[node.id].y = dy * gravityForce; } - }, { - key: 'openCluster', + }]); - /** - * Open a cluster by calling this function. - * @param {String} clusterNodeId | the ID of the cluster node - * @param {Boolean} refreshData | wrap up afterwards if not true - */ - value: function openCluster(clusterNodeId) { - var refreshData = arguments[1] === undefined ? true : arguments[1]; + return CentralGravitySolver; + })(); - // kill conditions - if (clusterNodeId === undefined) { - throw new Error('No clusterNodeId supplied to openCluster.'); - } - if (this.body.nodes[clusterNodeId] === undefined) { - throw new Error('The clusterNodeId supplied to openCluster does not exist.'); - } - if (this.body.nodes[clusterNodeId].containedNodes === undefined) { - console.log('The node:' + clusterNodeId + ' is not a cluster.'); - return; - } - var clusterNode = this.body.nodes[clusterNodeId]; - var containedNodes = clusterNode.containedNodes; - var containedEdges = clusterNode.containedEdges; + exports["default"] = CentralGravitySolver; + module.exports = exports["default"]; - // release nodes - for (var nodeId in containedNodes) { - if (containedNodes.hasOwnProperty(nodeId)) { - var containedNode = this.body.nodes[nodeId]; - containedNode = containedNodes[nodeId]; - // inherit position - containedNode.x = clusterNode.x; - containedNode.y = clusterNode.y; +/***/ }, +/* 83 */ +/***/ function(module, exports, __webpack_require__) { - // inherit speed - containedNode.vx = clusterNode.vx; - containedNode.vy = clusterNode.vy; + "use strict"; - containedNode.options.hidden = false; - containedNode.togglePhysics(true); + Object.defineProperty(exports, "__esModule", { + value: true + }); - delete this.clusteredNodes[nodeId]; - } - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // release edges - for (var edgeId in containedEdges) { - if (containedEdges.hasOwnProperty(edgeId)) { - var edge = containedEdges[edgeId]; - // if this edge was a temporary edge and it's connected nodes do not exist anymore, we remove it from the data - if (this.body.nodes[edge.fromId] === undefined || this.body.nodes[edge.toId] === undefined) { - edge.edgeType.cleanup(); - // this removes the edge from node.edges, which is why edgeIds is formed - edge.disconnect(); - delete this.body.edges[edgeId]; - } else { - // one of the nodes connected to this edge is in a cluster. We give the edge to that cluster so it will be released when that cluster is opened. - if (this.clusteredNodes[edge.fromId] !== undefined || this.clusteredNodes[edge.toId] !== undefined) { - var fromId = undefined, - toId = undefined; - var clusteredNode = this.clusteredNodes[edge.fromId] || this.clusteredNodes[edge.toId]; - var clusterId = clusteredNode.clusterId; - var _clusterNode = this.body.nodes[clusterId]; - _clusterNode.containedEdges[edgeId] = edge; + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - if (this.clusteredNodes[edge.fromId] !== undefined) { - fromId = clusterId; - toId = edge.toId; - } else { - fromId = edge.fromId; - toId = clusterId; - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - // if both from and to nodes are visible, we create a new temporary edge - if (this.body.nodes[fromId].options.hidden !== true && this.body.nodes[toId].options.hidden !== true) { - var clonedOptions = this._cloneOptions(edge, 'edge'); - var id = 'clusterEdge:' + util.randomUUID(); - util.deepExtend(clonedOptions, _clusterNode.clusterEdgeProperties); - util.deepExtend(clonedOptions, { from: fromId, to: toId, hidden: false, physics: true, id: id }); - var newEdge = this.body.functions.createEdge(clonedOptions); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - this.body.edges[id] = newEdge; - this.body.edges[id].connect(); - } - } else { - edge.options.hidden = false; - edge.togglePhysics(true); - } - } - } - } + function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - // remove all temporary edges - for (var i = 0; i < clusterNode.edges.length; i++) { - var edgeId = clusterNode.edges[i].id; - this.body.edges[edgeId].edgeType.cleanup(); - // this removes the edge from node.edges, which is why edgeIds is formed - this.body.edges[edgeId].disconnect(); - delete this.body.edges[edgeId]; - } + var _BarnesHutSolver2 = __webpack_require__(77); - // remove clusterNode - delete this.body.nodes[clusterNodeId]; + var _BarnesHutSolver3 = _interopRequireDefault(_BarnesHutSolver2); - if (refreshData === true) { - this.body.emitter.emit('_dataChanged'); - } - } - }, { - key: 'getNodesInCluster', - value: function getNodesInCluster(clusterId) { - var nodesArray = []; - if (this.isCluster(clusterId) === true) { - var containedNodes = this.body.nodes[clusterId].containedNodes; - for (var nodeId in containedNodes) { - if (containedNodes.hasOwnProperty(nodeId)) { - nodesArray.push(nodeId); - } - } - } + var ForceAtlas2BasedRepulsionSolver = (function (_BarnesHutSolver) { + function ForceAtlas2BasedRepulsionSolver(body, physicsBody, options) { + _classCallCheck(this, ForceAtlas2BasedRepulsionSolver); - return nodesArray; - } - }, { - key: 'findNode', + _get(Object.getPrototypeOf(ForceAtlas2BasedRepulsionSolver.prototype), "constructor", this).call(this, body, physicsBody, options); + } - /** - * Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node - * @param nodeId - * @returns {Array} - * @private - */ - value: function findNode(nodeId) { - var stack = []; - var max = 100; - var counter = 0; + _inherits(ForceAtlas2BasedRepulsionSolver, _BarnesHutSolver); - while (this.clusteredNodes[nodeId] !== undefined && counter < max) { - stack.push(this.clusteredNodes[nodeId].node); - nodeId = this.clusteredNodes[nodeId].clusterId; - counter++; - } - stack.push(this.body.nodes[nodeId]); - return stack; - } - }, { - key: '_getConnectedId', + _createClass(ForceAtlas2BasedRepulsionSolver, [{ + key: "_calculateForces", /** - * Get the Id the node is connected to - * @param edge - * @param nodeId - * @returns {*} - * @private - */ - value: function _getConnectedId(edge, nodeId) { - if (edge.toId != nodeId) { - return edge.toId; - } else if (edge.fromId != nodeId) { - return edge.fromId; - } else { - return edge.fromId; + * Calculate the forces based on the distance. + * + * @param distance + * @param dx + * @param dy + * @param node + * @param parentBranch + * @private + */ + value: function _calculateForces(distance, dx, dy, node, parentBranch) { + if (distance === 0) { + distance = 0.1 * Math.random(); + dx = distance; + } + + if (this.overlapAvoidanceFactor < 1) { + distance = Math.max(0.1 + this.overlapAvoidanceFactor * node.shape.radius, distance - node.shape.radius); } + + var degree = node.edges.length + 1; + // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines + // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce + var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass * degree / Math.pow(distance, 2); + var fx = dx * gravityForce; + var fy = dy * gravityForce; + + this.physicsBody.forces[node.id].x += fx; + this.physicsBody.forces[node.id].y += fy; } - }, { - key: '_getHubSize', + }]); - /** - * We determine how many connections denote an important hub. - * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%) - * - * @private - */ - value: function _getHubSize() { - var average = 0; - var averageSquared = 0; - var hubCounter = 0; - var largestHub = 0; + return ForceAtlas2BasedRepulsionSolver; + })(_BarnesHutSolver3["default"]); - for (var i = 0; i < this.body.nodeIndices.length; i++) { - var node = this.body.nodes[this.body.nodeIndices[i]]; - if (node.edges.length > largestHub) { - largestHub = node.edges.length; - } - average += node.edges.length; - averageSquared += Math.pow(node.edges.length, 2); - hubCounter += 1; - } - average = average / hubCounter; - averageSquared = averageSquared / hubCounter; + exports["default"] = ForceAtlas2BasedRepulsionSolver; + module.exports = exports["default"]; - var letiance = averageSquared - Math.pow(average, 2); - var standardDeviation = Math.sqrt(letiance); +/***/ }, +/* 84 */ +/***/ function(module, exports, __webpack_require__) { - var hubThreshold = Math.floor(average + 2 * standardDeviation); + "use strict"; - // always have at least one to cluster - if (hubThreshold > largestHub) { - hubThreshold = largestHub; - } + Object.defineProperty(exports, "__esModule", { + value: true + }); - return hubThreshold; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + + var _CentralGravitySolver2 = __webpack_require__(82); + + var _CentralGravitySolver3 = _interopRequireDefault(_CentralGravitySolver2); + + var ForceAtlas2BasedCentralGravitySolver = (function (_CentralGravitySolver) { + function ForceAtlas2BasedCentralGravitySolver(body, physicsBody, options) { + _classCallCheck(this, ForceAtlas2BasedCentralGravitySolver); + + _get(Object.getPrototypeOf(ForceAtlas2BasedCentralGravitySolver.prototype), "constructor", this).call(this, body, physicsBody, options); + } + + _inherits(ForceAtlas2BasedCentralGravitySolver, _CentralGravitySolver); + + _createClass(ForceAtlas2BasedCentralGravitySolver, [{ + key: "_calculateForces", + + /** + * Calculate the forces based on the distance. + * @private + */ + value: function _calculateForces(distance, dx, dy, forces, node) { + if (distance > 0) { + var degree = node.edges.length + 1; + var gravityForce = this.options.centralGravity * degree * node.options.mass; + forces[node.id].x = dx * gravityForce; + forces[node.id].y = dy * gravityForce; + } } }]); - return ClusterEngine; - })(); + return ForceAtlas2BasedCentralGravitySolver; + })(_CentralGravitySolver3["default"]); - exports['default'] = ClusterEngine; - module.exports = exports['default']; + exports["default"] = ForceAtlas2BasedCentralGravitySolver; + module.exports = exports["default"]; /***/ }, -/* 101 */ +/* 85 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -36691,7 +37461,7 @@ return /******/ (function(modules) { // webpackBootstrap function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - var _Node2 = __webpack_require__(8); + var _Node2 = __webpack_require__(74); var _Node3 = _interopRequireDefault(_Node2); @@ -36719,7 +37489,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = exports['default']; /***/ }, -/* 102 */ +/* 86 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -36732,1145 +37502,923 @@ return /******/ (function(modules) { // webpackBootstrap function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - if (typeof window !== 'undefined') { - window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; - } - var util = __webpack_require__(2); + var Hammer = __webpack_require__(41); + var hammerUtil = __webpack_require__(49); + var keycharm = __webpack_require__(88); - var CanvasRenderer = (function () { - function CanvasRenderer(body, canvas) { - _classCallCheck(this, CanvasRenderer); + var NavigationHandler = (function () { + function NavigationHandler(body, canvas) { + var _this = this; + + _classCallCheck(this, NavigationHandler); this.body = body; this.canvas = canvas; - this.redrawRequested = false; - this.renderTimer = undefined; - this.requiresTimeout = true; - this.renderingActive = false; - this.renderRequests = 0; - this.pixelRatio = undefined; - this.allowRedrawRequests = true; + this.iconsCreated = false; + this.navigationHammers = []; + this.boundFunctions = {}; + this.touchTime = 0; + this.activated = false; + + this.body.emitter.on('release', function () { + _this._stopMovement(); + }); + this.body.emitter.on('activate', function () { + _this.activated = true;_this.configureKeyboardBindings(); + }); + this.body.emitter.on('deactivate', function () { + _this.activated = false;_this.configureKeyboardBindings(); + }); + this.body.emitter.on('destroy', function () { + if (_this.keycharm !== undefined) { + _this.keycharm.destroy(); + } + }); - this.dragging = false; this.options = {}; - this.defaultOptions = { - hideEdgesOnDrag: false, - hideNodesOnDrag: false - }; - util.extend(this.options, this.defaultOptions); - - this._determineBrowserMethod(); - this.bindEventListeners(); } - _createClass(CanvasRenderer, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this = this; - - this.body.emitter.on('dragStart', function () { - _this.dragging = true; - }); - this.body.emitter.on('dragEnd', function () { - return _this.dragging = false; - }); - this.body.emitter.on('_resizeNodes', function () { - return _this._resizeNodes(); - }); - this.body.emitter.on('_redraw', function () { - if (_this.renderingActive === false) { - _this._redraw(); - } - }); - this.body.emitter.on('_blockRedrawRequests', function () { - _this.allowRedrawRequests = false; - }); - this.body.emitter.on('_allowRedrawRequests', function () { - _this.allowRedrawRequests = true; - }); - this.body.emitter.on('_requestRedraw', this._requestRedraw.bind(this)); - this.body.emitter.on('_startRendering', function () { - _this.renderRequests += 1; - _this.renderingActive = true; - _this._startRendering(); - }); - this.body.emitter.on('_stopRendering', function () { - _this.renderRequests -= 1; - _this.renderingActive = _this.renderRequests > 0; - _this.renderTimer = undefined; - }); - this.body.emitter.on('destroy', function () { - _this.renderRequests = 0; - _this.renderingActive = false; - if (_this.requiresTimeout === true) { - clearTimeout(_this.renderTimer); - } else { - cancelAnimationFrame(_this.renderTimer); - } - _this.body.emitter.off(); - }); - } - }, { + _createClass(NavigationHandler, [{ key: 'setOptions', value: function setOptions(options) { if (options !== undefined) { - var fields = ['hideEdgesOnDrag', 'hideNodesOnDrag']; - util.selectiveDeepExtend(fields, this.options, options); + this.options = options; + this.create(); } } }, { - key: '_startRendering', - value: function _startRendering() { - if (this.renderingActive === true) { - if (this.renderTimer === undefined) { - if (this.requiresTimeout === true) { - this.renderTimer = window.setTimeout(this._renderStep.bind(this), this.simulationInterval); // wait this.renderTimeStep milliseconds and perform the animation step function - } else { - this.renderTimer = window.requestAnimationFrame(this._renderStep.bind(this)); // wait this.renderTimeStep milliseconds and perform the animation step function - } + key: 'create', + value: function create() { + if (this.options.navigationButtons === true) { + if (this.iconsCreated === false) { + this.loadNavigationElements(); } + } else if (this.iconsCreated === true) { + this.cleanNavigation(); } + + this.configureKeyboardBindings(); } }, { - key: '_renderStep', - value: function _renderStep() { - if (this.renderingActive === true) { - // reset the renderTimer so a new scheduled animation step can be set - this.renderTimer = undefined; - - if (this.requiresTimeout === true) { - // this schedules a new simulation step - this._startRendering(); + key: 'cleanNavigation', + value: function cleanNavigation() { + // clean hammer bindings + if (this.navigationHammers.length != 0) { + for (var i = 0; i < this.navigationHammers.length; i++) { + this.navigationHammers[i].destroy(); } + this.navigationHammers = []; + } - this._redraw(); + // clean up previous navigation items + if (this.navigationDOM && this.navigationDOM['wrapper'] && this.navigationDOM['wrapper'].parentNode) { + this.navigationDOM['wrapper'].parentNode.removeChild(this.navigationDOM['wrapper']); + } - if (this.requiresTimeout === false) { - // this schedules a new simulation step - this._startRendering(); + this.iconsCreated = false; + } + }, { + key: 'loadNavigationElements', + + /** + * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation + * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent + * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false. + * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas. + * + * @private + */ + value: function loadNavigationElements() { + this.cleanNavigation(); + + this.navigationDOM = {}; + var navigationDivs = ['up', 'down', 'left', 'right', 'zoomIn', 'zoomOut', 'zoomExtends']; + var navigationDivActions = ['_moveUp', '_moveDown', '_moveLeft', '_moveRight', '_zoomIn', '_zoomOut', '_fit']; + + this.navigationDOM['wrapper'] = document.createElement('div'); + this.navigationDOM['wrapper'].className = 'vis-navigation'; + this.canvas.frame.appendChild(this.navigationDOM['wrapper']); + + for (var i = 0; i < navigationDivs.length; i++) { + this.navigationDOM[navigationDivs[i]] = document.createElement('div'); + this.navigationDOM[navigationDivs[i]].className = 'vis-button vis-' + navigationDivs[i]; + this.navigationDOM['wrapper'].appendChild(this.navigationDOM[navigationDivs[i]]); + + var hammer = new Hammer(this.navigationDOM[navigationDivs[i]]); + if (navigationDivActions[i] === '_fit') { + hammerUtil.onTouch(hammer, this._fit.bind(this)); + } else { + hammerUtil.onTouch(hammer, this.bindToRedraw.bind(this, navigationDivActions[i])); } + + this.navigationHammers.push(hammer); } + + this.iconsCreated = true; } }, { - key: 'redraw', + key: 'bindToRedraw', + value: function bindToRedraw(action) { + if (this.boundFunctions[action] === undefined) { + this.boundFunctions[action] = this[action].bind(this); + this.body.emitter.on('initRedraw', this.boundFunctions[action]); + this.body.emitter.emit('_startRendering'); + } + } + }, { + key: 'unbindFromRedraw', + value: function unbindFromRedraw(action) { + if (this.boundFunctions[action] !== undefined) { + this.body.emitter.off('initRedraw', this.boundFunctions[action]); + this.body.emitter.emit('_stopRendering'); + delete this.boundFunctions[action]; + } + } + }, { + key: '_fit', /** - * Redraw the network with the current data - * chart will be resized too. + * this stops all movement induced by the navigation buttons + * + * @private */ - value: function redraw() { - this.body.emitter.emit('setSize'); - this._redraw(); + value: function _fit() { + if (new Date().valueOf() - this.touchTime > 700) { + // TODO: fix ugly hack to avoid hammer's double fireing of event (because we use release?) + this.body.emitter.emit('fit', { duration: 700 }); + this.touchTime = new Date().valueOf(); + } } }, { - key: '_requestRedraw', + key: '_stopMovement', /** - * Redraw the network with the current data - * @param hidden | used to get the first estimate of the node sizes. only the nodes are drawn after which they are quickly drawn over. + * this stops all movement induced by the navigation buttons + * * @private */ - value: function _requestRedraw() { - if (this.redrawRequested !== true && this.renderingActive === false && this.allowRedrawRequests === true) { - this.redrawRequested = true; - if (this.requiresTimeout === true) { - window.setTimeout(this._redraw.bind(this, false), 0); - } else { - window.requestAnimationFrame(this._redraw.bind(this, false)); + value: function _stopMovement() { + for (var boundAction in this.boundFunctions) { + if (this.boundFunctions.hasOwnProperty(boundAction)) { + this.body.emitter.off('initRedraw', this.boundFunctions[boundAction]); + this.body.emitter.emit('_stopRendering'); } } + this.boundFunctions = {}; } }, { - key: '_redraw', - value: function _redraw() { - var hidden = arguments[0] === undefined ? false : arguments[0]; + key: '_moveUp', + value: function _moveUp() { + this.body.view.translation.y += this.options.keyboard.speed.y; + } + }, { + key: '_moveDown', + value: function _moveDown() { + this.body.view.translation.y -= this.options.keyboard.speed.y; + } + }, { + key: '_moveLeft', + value: function _moveLeft() { + this.body.view.translation.x += this.options.keyboard.speed.x; + } + }, { + key: '_moveRight', + value: function _moveRight() { + this.body.view.translation.x -= this.options.keyboard.speed.x; + } + }, { + key: '_zoomIn', + value: function _zoomIn() { + this.body.view.scale *= 1 + this.options.keyboard.speed.zoom; + } + }, { + key: '_zoomOut', + value: function _zoomOut() { + this.body.view.scale /= 1 + this.options.keyboard.speed.zoom; + } + }, { + key: 'configureKeyboardBindings', - this.body.emitter.emit('initRedraw'); + /** + * bind all keys using keycharm. + */ + value: function configureKeyboardBindings() { + if (this.keycharm !== undefined) { + this.keycharm.destroy(); + } - this.redrawRequested = false; - var ctx = this.canvas.frame.canvas.getContext('2d'); + if (this.options.keyboard.enabled === true) { + if (this.options.keyboard.bindToWindow === true) { + this.keycharm = keycharm({ container: window, preventDefault: true }); + } else { + this.keycharm = keycharm({ container: this.canvas.frame, preventDefault: true }); + } - // when the container div was hidden, this fixes it back up! - if (this.canvas.frame.canvas.width === 0 || this.canvas.frame.canvas.height === 0) { - this.canvas.setSize(); - } + this.keycharm.reset(); - if (this.pixelRatio === undefined) { - this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + if (this.activated === true) { + this.keycharm.bind('up', this.bindToRedraw.bind(this, '_moveUp'), 'keydown'); + this.keycharm.bind('down', this.bindToRedraw.bind(this, '_moveDown'), 'keydown'); + this.keycharm.bind('left', this.bindToRedraw.bind(this, '_moveLeft'), 'keydown'); + this.keycharm.bind('right', this.bindToRedraw.bind(this, '_moveRight'), 'keydown'); + this.keycharm.bind('=', this.bindToRedraw.bind(this, '_zoomIn'), 'keydown'); + this.keycharm.bind('num+', this.bindToRedraw.bind(this, '_zoomIn'), 'keydown'); + this.keycharm.bind('num-', this.bindToRedraw.bind(this, '_zoomOut'), 'keydown'); + this.keycharm.bind('-', this.bindToRedraw.bind(this, '_zoomOut'), 'keydown'); + this.keycharm.bind('[', this.bindToRedraw.bind(this, '_zoomOut'), 'keydown'); + this.keycharm.bind(']', this.bindToRedraw.bind(this, '_zoomIn'), 'keydown'); + this.keycharm.bind('pageup', this.bindToRedraw.bind(this, '_zoomIn'), 'keydown'); + this.keycharm.bind('pagedown', this.bindToRedraw.bind(this, '_zoomOut'), 'keydown'); + + this.keycharm.bind('up', this.unbindFromRedraw.bind(this, '_moveUp'), 'keyup'); + this.keycharm.bind('down', this.unbindFromRedraw.bind(this, '_moveDown'), 'keyup'); + this.keycharm.bind('left', this.unbindFromRedraw.bind(this, '_moveLeft'), 'keyup'); + this.keycharm.bind('right', this.unbindFromRedraw.bind(this, '_moveRight'), 'keyup'); + this.keycharm.bind('=', this.unbindFromRedraw.bind(this, '_zoomIn'), 'keyup'); + this.keycharm.bind('num+', this.unbindFromRedraw.bind(this, '_zoomIn'), 'keyup'); + this.keycharm.bind('num-', this.unbindFromRedraw.bind(this, '_zoomOut'), 'keyup'); + this.keycharm.bind('-', this.unbindFromRedraw.bind(this, '_zoomOut'), 'keyup'); + this.keycharm.bind('[', this.unbindFromRedraw.bind(this, '_zoomOut'), 'keyup'); + this.keycharm.bind(']', this.unbindFromRedraw.bind(this, '_zoomIn'), 'keyup'); + this.keycharm.bind('pageup', this.unbindFromRedraw.bind(this, '_zoomIn'), 'keyup'); + this.keycharm.bind('pagedown', this.unbindFromRedraw.bind(this, '_zoomOut'), 'keyup'); + } } + } + }]); - ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); + return NavigationHandler; + })(); - // clear the canvas - var w = this.canvas.frame.canvas.clientWidth; - var h = this.canvas.frame.canvas.clientHeight; - ctx.clearRect(0, 0, w, h); + exports['default'] = NavigationHandler; + module.exports = exports['default']; - // set scaling and translation - ctx.save(); - ctx.translate(this.body.view.translation.x, this.body.view.translation.y); - ctx.scale(this.body.view.scale, this.body.view.scale); +/***/ }, +/* 87 */ +/***/ function(module, exports, __webpack_require__) { - ctx.beginPath(); - this.body.emitter.emit('beforeDrawing', ctx); - ctx.closePath(); + /** + * Popup is a class to create a popup window with some text + * @param {Element} container The container object. + * @param {Number} [x] + * @param {Number} [y] + * @param {String} [text] + * @param {Object} [style] An object containing borderColor, + * backgroundColor, etc. + */ + 'use strict'; - if (hidden === false) { - if (this.dragging === false || this.dragging === true && this.options.hideEdgesOnDrag === false) { - this._drawEdges(ctx); - } - } + Object.defineProperty(exports, '__esModule', { + value: true + }); - if (this.dragging === false || this.dragging === true && this.options.hideNodesOnDrag === false) { - this._drawNodes(ctx, hidden); - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - if (this.controlNodesActive === true) { - this._drawControlNodes(ctx); - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - ctx.beginPath(); - //this.physics.nodesSolver._debug(ctx,"#F00F0F"); - this.body.emitter.emit('afterDrawing', ctx); - ctx.closePath(); - // restore original scaling and translation - ctx.restore(); + var Popup = (function () { + function Popup(container) { + _classCallCheck(this, Popup); - if (hidden === true) { - ctx.clearRect(0, 0, w, h); - } - } - }, { - key: '_resizeNodes', + this.container = container; - /** - * Redraw all nodes - * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); - * @param {CanvasRenderingContext2D} ctx - * @param {Boolean} [alwaysShow] - * @private - */ - value: function _resizeNodes() { - var ctx = this.canvas.frame.canvas.getContext('2d'); - if (this.pixelRatio === undefined) { - this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); - } - ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); - ctx.save(); - ctx.translate(this.body.view.translation.x, this.body.view.translation.y); - ctx.scale(this.body.view.scale, this.body.view.scale); + this.x = 0; + this.y = 0; + this.padding = 5; + this.hidden = false; - var nodes = this.body.nodes; - var node = undefined; + // create the frame + this.frame = document.createElement('div'); + this.frame.className = 'vis-network-tooltip'; + this.container.appendChild(this.frame); + } - // resize all nodes - for (var nodeId in nodes) { - if (nodes.hasOwnProperty(nodeId)) { - node = nodes[nodeId]; - node.resize(ctx); - node.updateBoundingBox(ctx); - } - } + _createClass(Popup, [{ + key: 'setPosition', - // restore original scaling and translation - ctx.restore(); + /** + * @param {number} x Horizontal position of the popup window + * @param {number} y Vertical position of the popup window + */ + value: function setPosition(x, y) { + this.x = parseInt(x); + this.y = parseInt(y); } }, { - key: '_drawNodes', + key: 'setText', /** - * Redraw all nodes - * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); - * @param {CanvasRenderingContext2D} ctx - * @param {Boolean} [alwaysShow] - * @private + * Set the content for the popup window. This can be HTML code or text. + * @param {string | Element} content */ - value: function _drawNodes(ctx) { - var alwaysShow = arguments[1] === undefined ? false : arguments[1]; - - var nodes = this.body.nodes; - var nodeIndices = this.body.nodeIndices; - var node = undefined; - var selected = []; - var margin = 20; - var topLeft = this.canvas.DOMtoCanvas({ x: -margin, y: -margin }); - var bottomRight = this.canvas.DOMtoCanvas({ - x: this.canvas.frame.canvas.clientWidth + margin, - y: this.canvas.frame.canvas.clientHeight + margin - }); - var viewableArea = { top: topLeft.y, left: topLeft.x, bottom: bottomRight.y, right: bottomRight.x }; - - // draw unselected nodes; - for (var i = 0; i < nodeIndices.length; i++) { - node = nodes[nodeIndices[i]]; - // set selected nodes aside - if (node.isSelected()) { - selected.push(nodeIndices[i]); - } else { - if (alwaysShow === true) { - node.draw(ctx); - } else if (node.isBoundingBoxOverlappingWith(viewableArea) === true) { - node.draw(ctx); - } else { - node.updateBoundingBox(ctx); - } - } - } - - // draw the selected nodes on top - for (var i = 0; i < selected.length; i++) { - node = nodes[selected[i]]; - node.draw(ctx); + value: function setText(content) { + if (content instanceof Element) { + this.frame.innerHTML = ''; + this.frame.appendChild(content); + } else { + this.frame.innerHTML = content; // string containing text or HTML } } }, { - key: '_drawEdges', + key: 'show', /** - * Redraw all edges - * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); - * @param {CanvasRenderingContext2D} ctx - * @private + * Show the popup window + * @param {boolean} [doShow] Show or hide the window */ - value: function _drawEdges(ctx) { - var edges = this.body.edges; - var edgeIndices = this.body.edgeIndices; - var edge = undefined; + value: function show(doShow) { + if (doShow === undefined) { + doShow = true; + } - for (var i = 0; i < edgeIndices.length; i++) { - edge = edges[edgeIndices[i]]; - if (edge.connected === true) { - edge.draw(ctx); + if (doShow === true) { + var height = this.frame.clientHeight; + var width = this.frame.clientWidth; + var maxHeight = this.frame.parentNode.clientHeight; + var maxWidth = this.frame.parentNode.clientWidth; + + var top = this.y - height; + if (top + height + this.padding > maxHeight) { + top = maxHeight - height - this.padding; + } + if (top < this.padding) { + top = this.padding; } - } - } - }, { - key: '_drawControlNodes', - /** - * Redraw all edges - * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); - * @param {CanvasRenderingContext2D} ctx - * @private - */ - value: function _drawControlNodes(ctx) { - var edges = this.body.edges; - var edgeIndices = this.body.edgeIndices; - var edge = undefined; + var left = this.x; + if (left + width + this.padding > maxWidth) { + left = maxWidth - width - this.padding; + } + if (left < this.padding) { + left = this.padding; + } - for (var i = 0; i < edgeIndices.length; i++) { - edge = edges[edgeIndices[i]]; - edge._drawControlNodes(ctx); + this.frame.style.left = left + 'px'; + this.frame.style.top = top + 'px'; + this.frame.style.visibility = 'visible'; + this.hidden = false; + } else { + this.hide(); } } }, { - key: '_determineBrowserMethod', + key: 'hide', /** - * Determine if the browser requires a setTimeout or a requestAnimationFrame. This was required because - * some implementations (safari and IE9) did not support requestAnimationFrame - * @private + * Hide the popup window */ - value: function _determineBrowserMethod() { - if (typeof window !== 'undefined') { - var browserType = navigator.userAgent.toLowerCase(); - this.requiresTimeout = false; - if (browserType.indexOf('msie 9.0') != -1) { - // IE 9 - this.requiresTimeout = true; - } else if (browserType.indexOf('safari') != -1) { - // safari - if (browserType.indexOf('chrome') <= -1) { - this.requiresTimeout = true; - } - } - } else { - this.requiresTimeout = true; - } + value: function hide() { + this.hidden = true; + this.frame.style.visibility = 'hidden'; } }]); - return CanvasRenderer; + return Popup; })(); - exports['default'] = CanvasRenderer; + exports['default'] = Popup; module.exports = exports['default']; /***/ }, -/* 103 */ +/* 88 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict"; + /** + * Created by Alex on 11/6/2014. + */ - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + // 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 () { - var Hammer = __webpack_require__(13); - var hammerUtil = __webpack_require__(38); + function keycharm(options) { + var preventDefault = options && options.preventDefault || false; - var util = __webpack_require__(2); + var container = options && options.container || window; - /** - * Create the main frame for the Network. - * This function is executed once when a Network object is created. The frame - * contains a canvas, and this canvas contains all objects like the axis and - * nodes. - * @private - */ + var _exportFunctions = {}; + var _bound = {keydown:{}, keyup:{}}; + var _keys = {}; + var i; - var Canvas = (function () { - function Canvas(body) { - _classCallCheck(this, Canvas); + // 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};} - this.body = body; - this.pixelRatio = 1; - this.resizeTimer = undefined; - this.resizeFunction = this._onResize.bind(this); + // 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}; - this.options = {}; - this.defaultOptions = { - autoResize: true, - height: '100%', - width: '100%' - }; - util.extend(this.options, this.defaultOptions); - this.bindEventListeners(); - } - _createClass(Canvas, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this = this; + var down = function(event) {handleEvent(event,'keydown');}; + var up = function(event) {handleEvent(event,'keyup');}; - // bind the events - this.body.emitter.once('resize', function (obj) { - if (obj.width !== 0) { - _this.body.view.translation.x = obj.width * 0.5; - } - if (obj.height !== 0) { - _this.body.view.translation.y = obj.height * 0.5; + // 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); + } } - }); - this.body.emitter.on('setSize', this.setSize.bind(this)); - this.body.emitter.on('destroy', function () { - _this.hammerFrame.destroy(); - _this.hammer.destroy(); - _this._cleanUp(); - }); - } - }, { - key: 'setOptions', - value: function setOptions(options) { - var _this2 = this; - if (options !== undefined) { - var fields = ['width', 'height', 'autoResize']; - util.selectiveDeepExtend(fields, this.options, options); + if (preventDefault == true) { + event.preventDefault(); + } } + }; - if (this.options.autoResize === true) { - // automatically adapt to a changing size of the browser. - this._cleanUp(); - this.resizeTimer = setInterval(function () { - _this2.setSize();_this2.body.emitter.emit('_requestRedraw'); - }, 1000); - this.resizeFunction = this._onResize.bind(this); - util.addEventListener(window, 'resize', this.resizeFunction); - } - } - }, { - key: '_cleanUp', - value: function _cleanUp() { - // automatically adapt to a changing size of the browser. - if (this.resizeTimer !== undefined) { - clearInterval(this.resizeTimer); + // bind a key to a callback + _exportFunctions.bind = function(key, callback, type) { + if (type === undefined) { + type = 'keydown'; } - util.removeEventListener(window, 'resize', this.resizeFunction); - this.resizeFunction = undefined; - } - }, { - key: '_onResize', - value: function _onResize() { - this.setSize(); - this.body.emitter.emit('_redraw'); - } - }, { - key: '_prepareValue', - value: function _prepareValue(value) { - if (typeof value === 'number') { - return value + 'px'; - } else if (typeof value === 'string') { - if (value.indexOf('%') !== -1 || value.indexOf('px') !== -1) { - return value; - } else if (value.indexOf('%') === -1) { - return value + 'px'; - } + if (_keys[key] === undefined) { + throw new Error("unsupported key: " + key); } - throw new Error('Could not use the value supplie for width or height:' + value); - } - }, { - key: '_create', - - /** - * Create the HTML - */ - value: function _create() { - // remove all elements from the container element. - while (this.body.container.hasChildNodes()) { - this.body.container.removeChild(this.body.container.firstChild); + if (_bound[type][_keys[key].code] === undefined) { + _bound[type][_keys[key].code] = []; } + _bound[type][_keys[key].code].push({fn:callback, shift:_keys[key].shift}); + }; - this.frame = document.createElement('div'); - this.frame.className = 'vis-network'; - this.frame.style.position = 'relative'; - this.frame.style.overflow = 'hidden'; - this.frame.tabIndex = 900; // tab index is required for keycharm to bind keystrokes to the div instead of the window - - ////////////////////////////////////////////////////////////////// - - this.frame.canvas = document.createElement('canvas'); - this.frame.canvas.style.position = 'relative'; - this.frame.appendChild(this.frame.canvas); - - if (!this.frame.canvas.getContext) { - var noCanvas = document.createElement('DIV'); - noCanvas.style.color = 'red'; - noCanvas.style.fontWeight = 'bold'; - noCanvas.style.padding = '10px'; - noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; - this.frame.canvas.appendChild(noCanvas); - } else { - var ctx = this.frame.canvas.getContext('2d'); - this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); - this.frame.canvas.getContext('2d').setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); + // bind all keys to a call back (demo purposes) + _exportFunctions.bindAll = function(callback, type) { + if (type === undefined) { + type = 'keydown'; } - - // add the frame to the container element - this.body.container.appendChild(this.frame); - - this.body.view.scale = 1; - this.body.view.translation = { x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight }; - - this._bindHammer(); - } - }, { - key: '_bindHammer', - - /** - * This function binds hammer, it can be repeated over and over due to the uniqueness check. - * @private - */ - value: function _bindHammer() { - var _this3 = this; - - if (this.hammer !== undefined) { - this.hammer.destroy(); + for (var key in _keys) { + if (_keys.hasOwnProperty(key)) { + _exportFunctions.bind(key,callback,type); + } } - this.drag = {}; - this.pinch = {}; - - // init hammer - this.hammer = new Hammer(this.frame.canvas); - this.hammer.get('pinch').set({ enable: true }); - // enable to get better response, todo: test on mobile. - //this.hammer.get('pan').set({threshold:2}); - - hammerUtil.onTouch(this.hammer, function (event) { - _this3.body.eventListeners.onTouch(event); - }); - this.hammer.on('tap', function (event) { - _this3.body.eventListeners.onTap(event); - }); - this.hammer.on('doubletap', function (event) { - _this3.body.eventListeners.onDoubleTap(event); - }); - this.hammer.on('press', function (event) { - _this3.body.eventListeners.onHold(event); - }); - this.hammer.on('panstart', function (event) { - _this3.body.eventListeners.onDragStart(event); - }); - this.hammer.on('panmove', function (event) { - _this3.body.eventListeners.onDrag(event); - }); - this.hammer.on('panend', function (event) { - _this3.body.eventListeners.onDragEnd(event); - }); - this.hammer.on('pinch', function (event) { - _this3.body.eventListeners.onPinch(event); - }); - - // TODO: neatly cleanup these handlers when re-creating the Canvas, IF these are done with hammer, event.stopPropagation will not work? - this.frame.canvas.addEventListener('mousewheel', function (event) { - _this3.body.eventListeners.onMouseWheel(event); - }); - this.frame.canvas.addEventListener('DOMMouseScroll', function (event) { - _this3.body.eventListeners.onMouseWheel(event); - }); - - this.frame.canvas.addEventListener('mousemove', function (event) { - _this3.body.eventListeners.onMouseMove(event); - }); - this.frame.canvas.addEventListener('contextmenu', function (event) { - _this3.body.eventListeners.onContext(event); - }); - - this.hammerFrame = new Hammer(this.frame); - hammerUtil.onRelease(this.hammerFrame, function (event) { - _this3.body.eventListeners.onRelease(event); - }); - } - }, { - key: 'setSize', + }; - /** - * Set a new size for the network - * @param {string} width Width in pixels or percentage (for example '800px' - * or '50%') - * @param {string} height Height in pixels or percentage (for example '400px' - * or '30%') - */ - value: function setSize() { - var width = arguments[0] === undefined ? this.options.width : arguments[0]; - var height = arguments[1] === undefined ? this.options.height : arguments[1]; + // 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"; + }; - width = this._prepareValue(width); - height = this._prepareValue(height); + // 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] = []; + } + }; - var emitEvent = false; - var oldWidth = this.frame.canvas.width; - var oldHeight = this.frame.canvas.height; + // reset all bound variables. + _exportFunctions.reset = function() { + _bound = {keydown:{}, keyup:{}}; + }; - if (width != this.options.width || height != this.options.height || this.frame.style.width != width || this.frame.style.height != height) { - this.frame.style.width = width; - this.frame.style.height = height; + // unbind all listeners and reset all variables. + _exportFunctions.destroy = function() { + _bound = {keydown:{}, keyup:{}}; + container.removeEventListener('keydown', down, true); + container.removeEventListener('keyup', up, true); + }; - this.frame.canvas.style.width = '100%'; - this.frame.canvas.style.height = '100%'; + // create listeners. + container.addEventListener('keydown',down,true); + container.addEventListener('keyup',up,true); - this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio; - this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio; + // return the public functions. + return _exportFunctions; + } - this.options.width = width; - this.options.height = height; + return keycharm; + })); - emitEvent = true; - } else { - // this would adapt the width of the canvas to the width from 100% if and only if - // there is a change. - if (this.frame.canvas.width != this.frame.canvas.clientWidth * this.pixelRatio) { - this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio; - emitEvent = true; - } - if (this.frame.canvas.height != this.frame.canvas.clientHeight * this.pixelRatio) { - this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio; - emitEvent = true; - } - } - if (emitEvent === true) { - this.body.emitter.emit('resize', { width: this.frame.canvas.width / this.pixelRatio, height: this.frame.canvas.height / this.pixelRatio, oldWidth: oldWidth / this.pixelRatio, oldHeight: oldHeight / this.pixelRatio }); - } - } - }, { - key: '_XconvertDOMtoCanvas', - /** - * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to - * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) - * @param {number} x - * @returns {number} - * @private - */ - value: function _XconvertDOMtoCanvas(x) { - return (x - this.body.view.translation.x) / this.body.view.scale; - } - }, { - key: '_XconvertCanvasToDOM', +/***/ }, +/* 89 */ +/***/ function(module, exports, __webpack_require__) { - /** - * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to - * the X coordinate in DOM-space (coordinate point in browser relative to the container div) - * @param {number} x - * @returns {number} - * @private - */ - value: function _XconvertCanvasToDOM(x) { - return x * this.body.view.scale + this.body.view.translation.x; - } - }, { - key: '_YconvertDOMtoCanvas', + function webpackContext(req) { + throw new Error("Cannot find module '" + req + "'."); + } + webpackContext.keys = function() { return []; }; + webpackContext.resolve = webpackContext; + module.exports = webpackContext; + webpackContext.id = 89; - /** - * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to - * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) - * @param {number} y - * @returns {number} - * @private - */ - value: function _YconvertDOMtoCanvas(y) { - return (y - this.body.view.translation.y) / this.body.view.scale; - } - }, { - key: '_YconvertCanvasToDOM', - /** - * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to - * the Y coordinate in DOM-space (coordinate point in browser relative to the container div) - * @param {number} y - * @returns {number} - * @private - */ - value: function _YconvertCanvasToDOM(y) { - return y * this.body.view.scale + this.body.view.translation.y; - } - }, { - key: 'canvasToDOM', +/***/ }, +/* 90 */ +/***/ function(module, exports, __webpack_require__) { - /** - * - * @param {object} pos = {x: number, y: number} - * @returns {{x: number, y: number}} - * @constructor - */ - value: function canvasToDOM(pos) { - return { x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y) }; - } - }, { - key: 'DOMtoCanvas', + module.exports = function(module) { + if(!module.webpackPolyfill) { + module.deprecate = function() {}; + module.paths = []; + // module.parent = undefined by default + module.children = []; + module.webpackPolyfill = 1; + } + return module; + } - /** - * - * @param {object} pos = {x: number, y: number} - * @returns {{x: number, y: number}} - * @constructor - */ - value: function DOMtoCanvas(pos) { - return { x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y) }; - } - }]); - return Canvas; - })(); +/***/ }, +/* 91 */ +/***/ function(module, exports, __webpack_require__) { - exports['default'] = Canvas; - module.exports = exports['default']; + /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__; + + /* WEBPACK VAR INJECTION */}.call(exports, {})) /***/ }, -/* 104 */ +/* 92 */ /***/ function(module, exports, __webpack_require__) { - "use strict"; + 'use strict'; - Object.defineProperty(exports, "__esModule", { + Object.defineProperty(exports, '__esModule', { value: true }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - var util = __webpack_require__(2); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - var View = (function () { - function View(body, canvas) { - var _this = this; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - _classCallCheck(this, View); + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - this.body = body; - this.canvas = canvas; + var _utilNodeBase = __webpack_require__(109); - this.animationSpeed = 1 / this.renderRefreshRate; - this.animationEasingFunction = "easeInOutQuint"; - this.easingTime = 0; - this.sourceScale = 0; - this.targetScale = 0; - this.sourceTranslation = 0; - this.targetTranslation = 0; - this.lockedOnNodeId = undefined; - this.lockedOnNodeOffset = undefined; - this.touchTime = 0; + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - this.viewFunction = undefined; + var Box = (function (_NodeBase) { + function Box(options, body, labelModule) { + _classCallCheck(this, Box); - this.body.emitter.on("fit", this.fit.bind(this)); - this.body.emitter.on("animationFinished", function () { - _this.body.emitter.emit("_stopRendering"); - }); - this.body.emitter.on("unlockNode", this.releaseNode.bind(this)); + _get(Object.getPrototypeOf(Box.prototype), 'constructor', this).call(this, options, body, labelModule); } - _createClass(View, [{ - key: "setOptions", - value: function setOptions() { - var options = arguments[0] === undefined ? {} : arguments[0]; + _inherits(Box, _NodeBase); - this.options = options; + _createClass(Box, [{ + key: 'resize', + value: function resize(ctx, selected) { + if (this.width === undefined) { + var margin = 5; + var textSize = this.labelModule.getTextSize(ctx, selected); + this.width = textSize.width + 2 * margin; + this.height = textSize.height + 2 * margin; + this.radius = 0.5 * this.width; + } } }, { - key: "_getRange", + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(ctx, selected); + this.left = x - this.width / 2; + this.top = y - this.height / 2; - /** - * Find the center position of the network - * @private - */ - value: function _getRange() { - var specificNodes = arguments[0] === undefined ? [] : arguments[0]; + var borderWidth = this.options.borderWidth; + var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - var minY = 1000000000, - maxY = -1000000000, - minX = 1000000000, - maxX = -1000000000, - node; - if (specificNodes.length > 0) { - for (var i = 0; i < specificNodes.length; i++) { - node = this.body.nodes[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 - } - } else { - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - node = this.body.nodes[nodeId]; - 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 - } - } - } + ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; + ctx.lineWidth = selected ? selectionLineWidth : borderWidth; + ctx.lineWidth /= this.body.view.scale; + ctx.lineWidth = Math.min(this.width, ctx.lineWidth); - if (minX === 1000000000 && maxX === -1000000000 && minY === 1000000000 && maxY === -1000000000) { - minY = 0, maxY = 0, minX = 0, maxX = 0; - } - return { minX: minX, maxX: maxX, minY: minY, maxY: maxY }; + ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; + + var borderRadius = 6; + ctx.roundRect(this.left, this.top, this.width, this.height, borderRadius); + + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); + + // disable shadows for other elements. + this.disableShadow(ctx); + + ctx.stroke(); + + this.updateBoundingBox(x, y); + this.labelModule.draw(ctx, x, y, selected); } }, { - key: "_findCenter", + key: 'updateBoundingBox', + value: function updateBoundingBox(x, y) { + this.left = x - this.width * 0.5; + this.top = y - this.height * 0.5; - /** - * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; - * @returns {{x: number, y: number}} - * @private - */ - value: function _findCenter(range) { - return { x: 0.5 * (range.maxX + range.minX), - y: 0.5 * (range.maxY + range.minY) }; + this.boundingBox.left = this.left; + this.boundingBox.top = this.top; + this.boundingBox.bottom = this.top + this.height; + this.boundingBox.right = this.left + this.width; } }, { - key: "fit", + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + var a = this.width / 2; + var b = this.height / 2; + var w = Math.sin(angle) * a; + var h = Math.cos(angle) * b; + return a * b / Math.sqrt(w * w + h * h); + } + }]); - /** - * This function zooms out to fit all data on screen based on amount of nodes - * @param {Object} Options - * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false; - */ - value: function fit() { - var options = arguments[0] === undefined ? { nodes: [] } : arguments[0]; - var initialZoom = arguments[1] === undefined ? false : arguments[1]; + return Box; + })(_utilNodeBase2['default']); - var range; - var zoomLevel; + exports['default'] = Box; + module.exports = exports['default']; - if (initialZoom === true) { - // check if more than half of the nodes have a predefined position. If so, we use the range, not the approximation. - var positionDefined = 0; - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - var node = this.body.nodes[nodeId]; - if (node.predefinedPosition === true) { - positionDefined += 1; - } - } - } - if (positionDefined > 0.5 * this.body.nodeIndices.length) { - this.fit(options, false); - return; - } +/***/ }, +/* 93 */ +/***/ function(module, exports, __webpack_require__) { - range = this._getRange(options.nodes); + 'use strict'; - var numberOfNodes = this.body.nodeIndices.length; - zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. + Object.defineProperty(exports, '__esModule', { + value: true + }); - // correct for larger canvasses. - var factor = Math.min(this.canvas.frame.canvas.clientWidth / 600, this.canvas.frame.canvas.clientHeight / 600); - zoomLevel *= factor; - } else { - this.body.emitter.emit("_resizeNodes"); - range = this._getRange(options.nodes); - var xDistance = Math.abs(range.maxX - range.minX) * 1.1; - var yDistance = Math.abs(range.maxY - range.minY) * 1.1; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var xZoomLevel = this.canvas.frame.canvas.clientWidth / xDistance; - var yZoomLevel = this.canvas.frame.canvas.clientHeight / yDistance; + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - zoomLevel = xZoomLevel <= yZoomLevel ? xZoomLevel : yZoomLevel; - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - if (zoomLevel > 1) { - zoomLevel = 1; - } else if (zoomLevel === 0) { - zoomLevel = 1; - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var center = this._findCenter(range); - var animationOptions = { position: center, scale: zoomLevel, animation: options.animation }; - this.moveTo(animationOptions); - } - }, { - key: "focus", + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - // animation + var _utilCircleImageBase = __webpack_require__(110); - /** - * Center a node in view. - * - * @param {Number} nodeId - * @param {Number} [options] - */ - value: function focus(nodeId) { - var options = arguments[1] === undefined ? {} : arguments[1]; + var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); - if (this.body.nodes[nodeId] !== undefined) { - var nodePosition = { x: this.body.nodes[nodeId].x, y: this.body.nodes[nodeId].y }; - options.position = nodePosition; - options.lockedOnNode = nodeId; + var Circle = (function (_CircleImageBase) { + function Circle(options, body, labelModule) { + _classCallCheck(this, Circle); - this.moveTo(options); - } else { - console.log("Node: " + nodeId + " cannot be found."); + _get(Object.getPrototypeOf(Circle.prototype), 'constructor', this).call(this, options, body, labelModule); + } + + _inherits(Circle, _CircleImageBase); + + _createClass(Circle, [{ + key: 'resize', + value: function resize(ctx, selected) { + if (this.width === undefined) { + var margin = 5; + var textSize = this.labelModule.getTextSize(ctx, selected); + var diameter = Math.max(textSize.width, textSize.height) + 2 * margin; + this.options.size = diameter / 2; + + this.width = diameter; + this.height = diameter; + this.radius = 0.5 * this.width; } } }, { - key: "moveTo", + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(ctx, selected); + this.left = x - this.width / 2; + this.top = y - this.height / 2; - /** - * - * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels - * | options.scale = Number // scale to move to - * | options.position = {x:Number, y:Number} // position to move to - * | options.animation = {duration:Number, easingFunction:String} || Boolean // position to move to - */ - value: function moveTo(options) { - if (options === undefined) { - options = {}; - return; - } - if (options.offset === undefined) { - options.offset = { x: 0, y: 0 }; - } - if (options.offset.x === undefined) { - options.offset.x = 0; - } - if (options.offset.y === undefined) { - options.offset.y = 0; - } - if (options.scale === undefined) { - options.scale = this.body.view.scale; - } - if (options.position === undefined) { - options.position = this.getViewPosition(); - } - if (options.animation === undefined) { - options.animation = { duration: 0 }; - } - if (options.animation === false) { - options.animation = { duration: 0 }; - } - if (options.animation === true) { - options.animation = {}; - } - if (options.animation.duration === undefined) { - options.animation.duration = 1000; - } // default duration - if (options.animation.easingFunction === undefined) { - options.animation.easingFunction = "easeInOutQuad"; - } // default easing function + this._drawRawCircle(ctx, x, y, selected, hover, this.options.size); - this.animateView(options); + 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; + + this.updateBoundingBox(x, y); + this.labelModule.draw(ctx, x, y, selected); } }, { - key: "animateView", + 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; + } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + var a = this.width / 2; + var b = this.height / 2; + var w = Math.sin(angle) * a; + var h = Math.cos(angle) * b; + return a * b / Math.sqrt(w * w + h * h); + } + }]); - /** - * - * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels - * | options.time = Number // animation time in milliseconds - * | options.scale = Number // scale to animate to - * | options.position = {x:Number, y:Number} // position to animate to - * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad, - * // easeInCubic, easeOutCubic, easeInOutCubic, - * // easeInQuart, easeOutQuart, easeInOutQuart, - * // easeInQuint, easeOutQuint, easeInOutQuint - */ - value: function animateView(options) { - if (options === undefined) { - return; - } - this.animationEasingFunction = options.animation.easingFunction; - // release if something focussed on the node - this.releaseNode(); - if (options.locked === true) { - this.lockedOnNodeId = options.lockedOnNode; - this.lockedOnNodeOffset = options.offset; - } + return Circle; + })(_utilCircleImageBase2['default']); - // forcefully complete the old animation if it was still running - if (this.easingTime != 0) { - this._transitionRedraw(true); // by setting easingtime to 1, we finish the animation. - } + exports['default'] = Circle; + module.exports = exports['default']; - this.sourceScale = this.body.view.scale; - this.sourceTranslation = this.body.view.translation; - this.targetScale = options.scale; +/***/ }, +/* 94 */ +/***/ function(module, exports, __webpack_require__) { - // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw - // but at least then we'll have the target transition - this.body.view.scale = this.targetScale; - var viewCenter = this.canvas.DOMtoCanvas({ x: 0.5 * this.canvas.frame.canvas.clientWidth, y: 0.5 * this.canvas.frame.canvas.clientHeight }); + 'use strict'; - var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node - x: viewCenter.x - options.position.x, - y: viewCenter.y - options.position.y - }; - this.targetTranslation = { - x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x, - y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y - }; + Object.defineProperty(exports, '__esModule', { + value: true + }); - // if the time is set to 0, don't do an animation - if (options.animation.duration === 0) { - if (this.lockedOnNodeId != undefined) { - this.viewFunction = this._lockedRedraw.bind(this); - this.body.emitter.on("initRedraw", this.viewFunction); - } else { - this.body.view.scale = this.targetScale; - this.body.view.translation = this.targetTranslation; - this.body.emitter.emit("_requestRedraw"); - } - } else { - this.animationSpeed = 1 / (60 * options.animation.duration * 0.001) || 1 / 60; // 60 for 60 seconds, 0.001 for milli's - this.animationEasingFunction = options.animation.easingFunction; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - this.viewFunction = this._transitionRedraw.bind(this); - this.body.emitter.on("initRedraw", this.viewFunction); - this.body.emitter.emit("_startRendering"); - } - } - }, { - key: "_lockedRedraw", + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - /** - * used to animate smoothly by hijacking the redraw function. - * @private - */ - value: function _lockedRedraw() { - var nodePosition = { x: this.body.nodes[this.lockedOnNodeId].x, y: this.body.nodes[this.lockedOnNodeId].y }; - var viewCenter = this.DOMtoCanvas({ x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight }); - var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node - x: viewCenter.x - nodePosition.x, - y: viewCenter.y - nodePosition.y - }; - var sourceTranslation = this.body.view.translation; - var targetTranslation = { - x: sourceTranslation.x + distanceFromCenter.x * this.body.view.scale + this.lockedOnNodeOffset.x, - y: sourceTranslation.y + distanceFromCenter.y * this.body.view.scale + this.lockedOnNodeOffset.y - }; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - this.body.view.translation = targetTranslation; - } - }, { - key: "releaseNode", - value: function releaseNode() { - if (this.lockedOnNodeId !== undefined && this.viewFunction !== undefined) { - this.body.emitter.off("initRedraw", this.viewFunction); - this.lockedOnNodeId = undefined; - this.lockedOnNodeOffset = undefined; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + + var _utilCircleImageBase = __webpack_require__(110); + + var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); + + var CircularImage = (function (_CircleImageBase) { + function CircularImage(options, body, labelModule, imageObj) { + _classCallCheck(this, CircularImage); + + _get(Object.getPrototypeOf(CircularImage.prototype), 'constructor', this).call(this, options, body, labelModule); + this.imageObj = imageObj; + this._swapToImageResizeWhenImageLoaded = true; + } + + _inherits(CircularImage, _CircleImageBase); + + _createClass(CircularImage, [{ + key: 'resize', + value: function resize() { + if (this.imageObj.src === undefined || this.imageObj.width === undefined || this.imageObj.height === undefined) { + if (!this.width) { + var diameter = this.options.size * 2; + this.width = diameter; + this.height = diameter; + this._swapToImageResizeWhenImageLoaded = true; + this.radius = 0.5 * this.width; + } + } else { + if (this._swapToImageResizeWhenImageLoaded) { + this.width = undefined; + this.height = undefined; + this._swapToImageResizeWhenImageLoaded = false; + } + this._resizeImage(); } } }, { - key: "_transitionRedraw", + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(); - /** - * - * @param easingTime - * @private - */ - value: function _transitionRedraw() { - var finished = arguments[0] === undefined ? false : arguments[0]; + this.left = x - this.width / 2; + this.top = y - this.height / 2; - this.easingTime += this.animationSpeed; - this.easingTime = finished === true ? 1 : this.easingTime; + var size = Math.min(0.5 * this.height, 0.5 * this.width); - var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime); + this._drawRawCircle(ctx, x, y, selected, hover, size); - this.body.view.scale = this.sourceScale + (this.targetScale - this.sourceScale) * progress; - this.body.view.translation = { - x: this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress, - y: this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress - }; + ctx.save(); + ctx.circle(x, y, size); + ctx.stroke(); + ctx.clip(); - // cleanup - if (this.easingTime >= 1) { - this.body.emitter.off("initRedraw", this.viewFunction); - this.easingTime = 0; - if (this.lockedOnNodeId != undefined) { - this.viewFunction = this._lockedRedraw.bind(this); - this.body.emitter.on("initRedraw", this.viewFunction); - } - this.body.emitter.emit("animationFinished"); - } + this._drawImageAtPosition(ctx); + + ctx.restore(); + + this._drawImageLabel(ctx, x, y, selected); + + this.updateBoundingBox(x, y); } }, { - key: "getScale", - value: function getScale() { - return this.body.view.scale; + 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; + 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.labelOffset); } }, { - key: "getViewPosition", - value: function getViewPosition() { - return this.canvas.DOMtoCanvas({ x: 0.5 * this.canvas.frame.canvas.clientWidth, y: 0.5 * this.canvas.frame.canvas.clientHeight }); + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + return this._distanceToBorder(angle); } }]); - return View; - })(); + return CircularImage; + })(_utilCircleImageBase2['default']); - exports["default"] = View; - module.exports = exports["default"]; + exports['default'] = CircularImage; + module.exports = exports['default']; /***/ }, -/* 105 */ +/* 95 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -37881,274 +38429,215 @@ return /******/ (function(modules) { // webpackBootstrap var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - var util = __webpack_require__(2); - var Hammer = __webpack_require__(13); - var hammerUtil = __webpack_require__(38); - var keycharm = __webpack_require__(50); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - var NavigationHandler = (function () { - function NavigationHandler(body, canvas) { - var _this = this; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - _classCallCheck(this, NavigationHandler); + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - this.body = body; - this.canvas = canvas; + var _utilNodeBase = __webpack_require__(109); - this.iconsCreated = false; - this.navigationHammers = []; - this.boundFunctions = {}; - this.touchTime = 0; - this.activated = false; + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - this.body.emitter.on('release', function () { - _this._stopMovement(); - }); - this.body.emitter.on('activate', function () { - _this.activated = true;_this.configureKeyboardBindings(); - }); - this.body.emitter.on('deactivate', function () { - _this.activated = false;_this.configureKeyboardBindings(); - }); - this.body.emitter.on('destroy', function () { - if (_this.keycharm !== undefined) { - _this.keycharm.destroy(); - } - }); + var Database = (function (_NodeBase) { + function Database(options, body, labelModule) { + _classCallCheck(this, Database); - this.options = {}; + _get(Object.getPrototypeOf(Database.prototype), 'constructor', this).call(this, options, body, labelModule); } - _createClass(NavigationHandler, [{ - key: 'setOptions', - value: function setOptions(options) { - if (options !== undefined) { - this.options = options; - this.create(); - } - } - }, { - key: 'create', - value: function create() { - if (this.options.navigationButtons === true) { - if (this.iconsCreated === false) { - this.loadNavigationElements(); - } - } else if (this.iconsCreated === true) { - this.cleanNavigation(); - } - - this.configureKeyboardBindings(); - } - }, { - key: 'cleanNavigation', - value: function cleanNavigation() { - // clean hammer bindings - if (this.navigationHammers.length != 0) { - for (var i = 0; i < this.navigationHammers.length; i++) { - this.navigationHammers[i].destroy(); - } - this.navigationHammers = []; - } + _inherits(Database, _NodeBase); - // clean up previous navigation items - if (this.navigationDOM && this.navigationDOM['wrapper'] && this.navigationDOM['wrapper'].parentNode) { - this.navigationDOM['wrapper'].parentNode.removeChild(this.navigationDOM['wrapper']); + _createClass(Database, [{ + key: 'resize', + value: function resize(ctx, selected) { + if (this.width === undefined) { + var margin = 5; + var textSize = this.labelModule.getTextSize(ctx, selected); + var size = textSize.width + 2 * margin; + this.width = size; + this.height = size; + this.radius = 0.5 * this.width; } - - this.iconsCreated = false; } }, { - key: 'loadNavigationElements', + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(ctx, selected); + this.left = x - this.width / 2; + this.top = y - this.height / 2; - /** - * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation - * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent - * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false. - * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas. - * - * @private - */ - value: function loadNavigationElements() { - this.cleanNavigation(); + var borderWidth = this.options.borderWidth; + var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - this.navigationDOM = {}; - var navigationDivs = ['up', 'down', 'left', 'right', 'zoomIn', 'zoomOut', 'zoomExtends']; - var navigationDivActions = ['_moveUp', '_moveDown', '_moveLeft', '_moveRight', '_zoomIn', '_zoomOut', '_fit']; + ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; + ctx.lineWidth = this.selected ? selectionLineWidth : borderWidth; + ctx.lineWidth *= this.networkScaleInv; + ctx.lineWidth = Math.min(this.width, ctx.lineWidth); - this.navigationDOM['wrapper'] = document.createElement('div'); - this.navigationDOM['wrapper'].className = 'vis-navigation'; - this.canvas.frame.appendChild(this.navigationDOM['wrapper']); + ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; + ctx.database(x - this.width / 2, y - this.height * 0.5, this.width, this.height); - for (var i = 0; i < navigationDivs.length; i++) { - this.navigationDOM[navigationDivs[i]] = document.createElement('div'); - this.navigationDOM[navigationDivs[i]].className = 'vis-button vis-' + navigationDivs[i]; - this.navigationDOM['wrapper'].appendChild(this.navigationDOM[navigationDivs[i]]); + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); - var hammer = new Hammer(this.navigationDOM[navigationDivs[i]]); - if (navigationDivActions[i] === '_fit') { - hammerUtil.onTouch(hammer, this._fit.bind(this)); - } else { - hammerUtil.onTouch(hammer, this.bindToRedraw.bind(this, navigationDivActions[i])); - } + // disable shadows for other elements. + this.disableShadow(ctx); - this.navigationHammers.push(hammer); - } + ctx.stroke(); - this.iconsCreated = true; - } - }, { - key: 'bindToRedraw', - value: function bindToRedraw(action) { - if (this.boundFunctions[action] === undefined) { - this.boundFunctions[action] = this[action].bind(this); - this.body.emitter.on('initRedraw', this.boundFunctions[action]); - this.body.emitter.emit('_startRendering'); - } - } - }, { - key: 'unbindFromRedraw', - value: function unbindFromRedraw(action) { - if (this.boundFunctions[action] !== undefined) { - this.body.emitter.off('initRedraw', this.boundFunctions[action]); - this.body.emitter.emit('_stopRendering'); - delete this.boundFunctions[action]; - } - } - }, { - key: '_fit', + this.updateBoundingBox(x, y); - /** - * this stops all movement induced by the navigation buttons - * - * @private - */ - value: function _fit() { - if (new Date().valueOf() - this.touchTime > 700) { - // TODO: fix ugly hack to avoid hammer's double fireing of event (because we use release?) - this.body.emitter.emit('fit', { duration: 700 }); - this.touchTime = new Date().valueOf(); - } + this.labelModule.draw(ctx, x, y, selected); } }, { - key: '_stopMovement', + key: 'updateBoundingBox', + value: function updateBoundingBox(x, y) { + this.left = x - this.width * 0.5; + this.top = y - this.height * 0.5; - /** - * this stops all movement induced by the navigation buttons - * - * @private - */ - value: function _stopMovement() { - for (var boundAction in this.boundFunctions) { - if (this.boundFunctions.hasOwnProperty(boundAction)) { - this.body.emitter.off('initRedraw', this.boundFunctions[boundAction]); - this.body.emitter.emit('_stopRendering'); - } - } - this.boundFunctions = {}; - } - }, { - key: '_moveUp', - value: function _moveUp() { - this.body.view.translation.y += this.options.keyboard.speed.y; - } - }, { - key: '_moveDown', - value: function _moveDown() { - this.body.view.translation.y -= this.options.keyboard.speed.y; + this.boundingBox.left = this.left; + this.boundingBox.top = this.top; + this.boundingBox.bottom = this.top + this.height; + this.boundingBox.right = this.left + this.width; } }, { - key: '_moveLeft', - value: function _moveLeft() { - this.body.view.translation.x += this.options.keyboard.speed.x; + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + var a = this.width / 2; + var b = this.height / 2; + var w = Math.sin(angle) * a; + var h = Math.cos(angle) * b; + return a * b / Math.sqrt(w * w + h * h); } - }, { - key: '_moveRight', - value: function _moveRight() { - this.body.view.translation.x -= this.options.keyboard.speed.x; + }]); + + return Database; + })(_utilNodeBase2['default']); + + exports['default'] = Database; + module.exports = exports['default']; + +/***/ }, +/* 96 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + + var _utilShapeBase = __webpack_require__(111); + + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + + var Diamond = (function (_ShapeBase) { + function Diamond(options, body, labelModule) { + _classCallCheck(this, Diamond); + + _get(Object.getPrototypeOf(Diamond.prototype), 'constructor', this).call(this, options, body, labelModule); + } + + _inherits(Diamond, _ShapeBase); + + _createClass(Diamond, [{ + key: 'resize', + value: function resize(ctx) { + this._resizeShape(); } }, { - key: '_zoomIn', - value: function _zoomIn() { - this.body.view.scale *= 1 + this.options.keyboard.speed.zoom; + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this._drawShape(ctx, 'diamond', 4, x, y, selected, hover); } }, { - key: '_zoomOut', - value: function _zoomOut() { - this.body.view.scale /= 1 + this.options.keyboard.speed.zoom; + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + return this._distanceToBorder(angle); } - }, { - key: 'configureKeyboardBindings', + }]); - /** - * bind all keys using keycharm. - */ - value: function configureKeyboardBindings() { - if (this.keycharm !== undefined) { - this.keycharm.destroy(); - } + return Diamond; + })(_utilShapeBase2['default']); - if (this.options.keyboard.enabled === true) { - if (this.options.keyboard.bindToWindow === true) { - this.keycharm = keycharm({ container: window, preventDefault: true }); - } else { - this.keycharm = keycharm({ container: this.canvas.frame, preventDefault: true }); - } + exports['default'] = Diamond; + module.exports = exports['default']; - this.keycharm.reset(); +/***/ }, +/* 97 */ +/***/ function(module, exports, __webpack_require__) { - if (this.activated === true) { - this.keycharm.bind('up', this.bindToRedraw.bind(this, '_moveUp'), 'keydown'); - this.keycharm.bind('down', this.bindToRedraw.bind(this, '_moveDown'), 'keydown'); - this.keycharm.bind('left', this.bindToRedraw.bind(this, '_moveLeft'), 'keydown'); - this.keycharm.bind('right', this.bindToRedraw.bind(this, '_moveRight'), 'keydown'); - this.keycharm.bind('=', this.bindToRedraw.bind(this, '_zoomIn'), 'keydown'); - this.keycharm.bind('num+', this.bindToRedraw.bind(this, '_zoomIn'), 'keydown'); - this.keycharm.bind('num-', this.bindToRedraw.bind(this, '_zoomOut'), 'keydown'); - this.keycharm.bind('-', this.bindToRedraw.bind(this, '_zoomOut'), 'keydown'); - this.keycharm.bind('[', this.bindToRedraw.bind(this, '_zoomOut'), 'keydown'); - this.keycharm.bind(']', this.bindToRedraw.bind(this, '_zoomIn'), 'keydown'); - this.keycharm.bind('pageup', this.bindToRedraw.bind(this, '_zoomIn'), 'keydown'); - this.keycharm.bind('pagedown', this.bindToRedraw.bind(this, '_zoomOut'), 'keydown'); + 'use strict'; - this.keycharm.bind('up', this.unbindFromRedraw.bind(this, '_moveUp'), 'keyup'); - this.keycharm.bind('down', this.unbindFromRedraw.bind(this, '_moveDown'), 'keyup'); - this.keycharm.bind('left', this.unbindFromRedraw.bind(this, '_moveLeft'), 'keyup'); - this.keycharm.bind('right', this.unbindFromRedraw.bind(this, '_moveRight'), 'keyup'); - this.keycharm.bind('=', this.unbindFromRedraw.bind(this, '_zoomIn'), 'keyup'); - this.keycharm.bind('num+', this.unbindFromRedraw.bind(this, '_zoomIn'), 'keyup'); - this.keycharm.bind('num-', this.unbindFromRedraw.bind(this, '_zoomOut'), 'keyup'); - this.keycharm.bind('-', this.unbindFromRedraw.bind(this, '_zoomOut'), 'keyup'); - this.keycharm.bind('[', this.unbindFromRedraw.bind(this, '_zoomOut'), 'keyup'); - this.keycharm.bind(']', this.unbindFromRedraw.bind(this, '_zoomIn'), 'keyup'); - this.keycharm.bind('pageup', this.unbindFromRedraw.bind(this, '_zoomIn'), 'keyup'); - this.keycharm.bind('pagedown', this.unbindFromRedraw.bind(this, '_zoomOut'), 'keyup'); - } - } + Object.defineProperty(exports, '__esModule', { + value: true + }); + + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + + var _utilShapeBase = __webpack_require__(111); + + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + + var Dot = (function (_ShapeBase) { + function Dot(options, body, labelModule) { + _classCallCheck(this, Dot); + + _get(Object.getPrototypeOf(Dot.prototype), 'constructor', this).call(this, options, body, labelModule); + } + + _inherits(Dot, _ShapeBase); + + _createClass(Dot, [{ + key: 'resize', + value: function resize(ctx) { + this._resizeShape(); + } + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this._drawShape(ctx, 'circle', 2, x, y, selected, hover); + } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + return this.options.size + this.options.borderWidth; } }]); - return NavigationHandler; - })(); + return Dot; + })(_utilShapeBase2['default']); - exports['default'] = NavigationHandler; + exports['default'] = Dot; module.exports = exports['default']; /***/ }, -/* 106 */ +/* 98 */ /***/ function(module, exports, __webpack_require__) { - /** - * Popup is a class to create a popup window with some text - * @param {Element} container The container object. - * @param {Number} [x] - * @param {Number} [y] - * @param {String} [text] - * @param {Object} [style] An object containing borderColor, - * backgroundColor, etc. - */ 'use strict'; Object.defineProperty(exports, '__esModule', { @@ -38157,2687 +38646,2198 @@ return /******/ (function(modules) { // webpackBootstrap var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var Popup = (function () { - function Popup(container) { - _classCallCheck(this, Popup); + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - this.container = container; + var _utilNodeBase = __webpack_require__(109); - this.x = 0; - this.y = 0; - this.padding = 5; - this.hidden = false; + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - // create the frame - this.frame = document.createElement('div'); - this.frame.className = 'vis-network-tooltip'; - this.container.appendChild(this.frame); - } + var Ellipse = (function (_NodeBase) { + function Ellipse(options, body, labelModule) { + _classCallCheck(this, Ellipse); - _createClass(Popup, [{ - key: 'setPosition', + _get(Object.getPrototypeOf(Ellipse.prototype), 'constructor', this).call(this, options, body, labelModule); + } - /** - * @param {number} x Horizontal position of the popup window - * @param {number} y Vertical position of the popup window - */ - value: function setPosition(x, y) { - this.x = parseInt(x); - this.y = parseInt(y); - } - }, { - key: 'setText', + _inherits(Ellipse, _NodeBase); - /** - * Set the content for the popup window. This can be HTML code or text. - * @param {string | Element} content - */ - value: function setText(content) { - if (content instanceof Element) { - this.frame.innerHTML = ''; - this.frame.appendChild(content); - } else { - this.frame.innerHTML = content; // string containing text or HTML + _createClass(Ellipse, [{ + key: 'resize', + value: function resize(ctx, selected) { + if (this.width === undefined) { + var textSize = this.labelModule.getTextSize(ctx, selected); + + this.width = textSize.width * 1.5; + this.height = textSize.height * 2; + if (this.width < this.height) { + this.width = this.height; + } + this.radius = 0.5 * this.width; } } }, { - key: 'show', + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(ctx, selected); + this.left = x - this.width * 0.5; + this.top = y - this.height * 0.5; - /** - * Show the popup window - * @param {boolean} [doShow] Show or hide the window - */ - value: function show(doShow) { - if (doShow === undefined) { - doShow = true; - } + var borderWidth = this.options.borderWidth; + var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - if (doShow === true) { - var height = this.frame.clientHeight; - var width = this.frame.clientWidth; - var maxHeight = this.frame.parentNode.clientHeight; - var maxWidth = this.frame.parentNode.clientWidth; + ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; - var top = this.y - height; - if (top + height + this.padding > maxHeight) { - top = maxHeight - height - this.padding; - } - if (top < this.padding) { - top = this.padding; - } + ctx.lineWidth = selected ? selectionLineWidth : borderWidth; + ctx.lineWidth /= this.body.view.scale; + ctx.lineWidth = Math.min(this.width, ctx.lineWidth); - var left = this.x; - if (left + width + this.padding > maxWidth) { - left = maxWidth - width - this.padding; - } - if (left < this.padding) { - left = this.padding; - } + ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; + ctx.ellipse(this.left, this.top, this.width, this.height); - this.frame.style.left = left + 'px'; - this.frame.style.top = top + 'px'; - this.frame.style.visibility = 'visible'; - this.hidden = false; - } else { - this.hide(); - } + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); + + // disable shadows for other elements. + this.disableShadow(ctx); + + ctx.stroke(); + + this.updateBoundingBox(x, y); + this.labelModule.draw(ctx, x, y, selected); } }, { - key: 'hide', + key: 'updateBoundingBox', + value: function updateBoundingBox(x, y) { + this.left = x - this.width * 0.5; + this.top = y - this.height * 0.5; - /** - * Hide the popup window - */ - value: function hide() { - this.hidden = true; - this.frame.style.visibility = 'hidden'; + this.boundingBox.left = this.left; + this.boundingBox.top = this.top; + this.boundingBox.bottom = this.top + this.height; + this.boundingBox.right = this.left + this.width; + } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + var a = this.width * 0.5; + var b = this.height * 0.5; + var w = Math.sin(angle) * a; + var h = Math.cos(angle) * b; + return a * b / Math.sqrt(w * w + h * h); } }]); - return Popup; - })(); + return Ellipse; + })(_utilNodeBase2['default']); - exports['default'] = Popup; + exports['default'] = Ellipse; module.exports = exports['default']; /***/ }, -/* 107 */ +/* 99 */ /***/ function(module, exports, __webpack_require__) { - "use strict"; + 'use strict'; - Object.defineProperty(exports, "__esModule", { + Object.defineProperty(exports, '__esModule', { value: true }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - var Node = __webpack_require__(8); - var Edge = __webpack_require__(9); - var util = __webpack_require__(2); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - var SelectionHandler = (function () { - function SelectionHandler(body, canvas) { - var _this = this; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - _classCallCheck(this, SelectionHandler); + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - this.body = body; - this.canvas = canvas; - this.selectionObj = { nodes: [], edges: [] }; - this.hoverObj = { nodes: {}, edges: {} }; + var _utilNodeBase = __webpack_require__(109); - this.options = {}; - this.defaultOptions = { - multiselect: false, - selectable: true, - selectConnectedEdges: true, - hoverConnectedEdges: true - }; - util.extend(this.options, this.defaultOptions); + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - this.body.emitter.on("_dataChanged", function () { - _this.updateSelection(); - }); + var Icon = (function (_NodeBase) { + function Icon(options, body, labelModule) { + _classCallCheck(this, Icon); + + _get(Object.getPrototypeOf(Icon.prototype), 'constructor', this).call(this, options, body, labelModule); } - _createClass(SelectionHandler, [{ - key: "setOptions", - value: function setOptions(options) { - if (options !== undefined) { - var fields = ["multiselect", "hoverConnectedEdges", "selectable", "selectConnectedEdges"]; - util.selectiveDeepExtend(fields, this.options, options); - } - } - }, { - key: "selectOnPoint", + _inherits(Icon, _NodeBase); - /** - * handles the selection part of the tap; - * - * @param {Object} pointer - * @private - */ - value: function selectOnPoint(pointer) { - var selected = false; - if (this.options.selectable === true) { - this.unselectAll(); - var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer); - if (obj !== undefined) { - selected = this.selectObject(obj); - } - this.body.emitter.emit("_requestRedraw"); + _createClass(Icon, [{ + key: 'resize', + value: function resize(ctx) { + if (this.width === undefined) { + var margin = 5; + var iconSize = { + width: Number(this.options.icon.size), + height: Number(this.options.icon.size) + }; + this.width = iconSize.width + 2 * margin; + this.height = iconSize.height + 2 * margin; + this.radius = 0.5 * this.width; } - return selected; } }, { - key: "selectAdditionalOnPoint", - value: function selectAdditionalOnPoint(pointer) { - var selectionChanged = false; - if (this.options.selectable === true) { - var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer); + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(ctx); + this.options.icon.size = this.options.icon.size || 50; - if (obj !== undefined) { - selectionChanged = true; - if (obj.isSelected() === true) { - this.deselectObject(obj); - } else { - this.selectObject(obj); - } + this.left = x - this.width * 0.5; + this.top = y - this.height * 0.5; + this._icon(ctx, x, y, selected); - this.body.emitter.emit("_requestRedraw"); - } + if (this.options.label !== undefined) { + var iconTextSpacing = 5; + this.labelModule.draw(ctx, x, y + this.height * 0.5 + iconTextSpacing, selected); } - return selectionChanged; - } - }, { - key: "_generateClickEvent", - value: function _generateClickEvent(eventType, event, pointer, oldSelection) { - var properties = this.getSelection(); - properties["pointer"] = { - DOM: { x: pointer.x, y: pointer.y }, - canvas: this.canvas.DOMtoCanvas(pointer) - }; - properties["event"] = event; - if (oldSelection !== undefined) { - properties["previousSelection"] = oldSelection; - } - this.body.emitter.emit(eventType, properties); + this.updateBoundingBox(x, y); } }, { - key: "selectObject", - value: function selectObject(obj) { - var highlightEdges = arguments[1] === undefined ? this.options.selectConnectedEdges : arguments[1]; + key: 'updateBoundingBox', + value: function updateBoundingBox(x, y) { + this.boundingBox.top = y - this.options.icon.size * 0.5; + this.boundingBox.left = x - this.options.icon.size * 0.5; + this.boundingBox.right = x + this.options.icon.size * 0.5; + this.boundingBox.bottom = y + this.options.icon.size * 0.5; - if (obj !== undefined) { - if (obj instanceof Node) { - if (highlightEdges === true) { - this._selectConnectedEdges(obj); - } - } - obj.select(); - this._addToSelection(obj); - return true; - } - return false; - } - }, { - key: "deselectObject", - value: function deselectObject(obj) { - if (obj.isSelected() === true) { - obj.selected = false; - this._removeFromSelection(obj); + if (this.options.label !== undefined) { + var iconTextSpacing = 5; + 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 + iconTextSpacing); } } }, { - key: "_getAllNodesOverlappingWith", + key: '_icon', + value: function _icon(ctx, x, y, selected) { + var iconSize = Number(this.options.icon.size); - /** - * retrieve all nodes overlapping with given object - * @param {Object} object An object with parameters left, top, right, bottom - * @return {Number[]} An array with id's of the overlapping nodes - * @private - */ - value: function _getAllNodesOverlappingWith(object) { - var overlappingNodes = []; - var nodes = this.body.nodes; - for (var i = 0; i < this.body.nodeIndices.length; i++) { - var nodeId = this.body.nodeIndices[i]; - if (nodes[nodeId].isOverlappingWith(object)) { - overlappingNodes.push(nodeId); - } - } - return overlappingNodes; - } - }, { - key: "_pointerToPositionObject", + if (this.options.icon.code !== undefined) { + ctx.font = (selected ? 'bold ' : '') + iconSize + 'px ' + this.options.icon.face; - /** - * Return a position object in canvasspace from a single point in screenspace - * - * @param pointer - * @returns {{left: number, top: number, right: number, bottom: number}} - * @private - */ - value: function _pointerToPositionObject(pointer) { - var canvasPos = this.canvas.DOMtoCanvas(pointer); - return { - left: canvasPos.x - 1, - top: canvasPos.y + 1, - right: canvasPos.x + 1, - bottom: canvasPos.y - 1 - }; - } - }, { - key: "getNodeAt", + // draw icon + ctx.fillStyle = this.options.icon.color || 'black'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; - /** - * Get the top node at the a specific point (like a click) - * - * @param {{x: Number, y: Number}} pointer - * @return {Node | undefined} node - * @private - */ - value: function getNodeAt(pointer) { - var returnNode = arguments[1] === undefined ? true : arguments[1]; + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fillText(this.options.icon.code, x, y); - // we first check if this is an navigation controls element - var positionObject = this._pointerToPositionObject(pointer); - var overlappingNodes = this._getAllNodesOverlappingWith(positionObject); - // if there are overlapping nodes, select the last one, this is the - // one which is drawn on top of the others - if (overlappingNodes.length > 0) { - if (returnNode === true) { - return this.body.nodes[overlappingNodes[overlappingNodes.length - 1]]; - } else { - return overlappingNodes[overlappingNodes.length - 1]; - } + // disable shadows for other elements. + this.disableShadow(ctx); } else { - return undefined; + console.error('When using the icon shape, you need to define the code in the icon options object. This can be done per node or globally.'); } } }, { - key: "_getEdgesOverlappingWith", - - /** - * retrieve all edges overlapping with given object, selector is around center - * @param {Object} object An object with parameters left, top, right, bottom - * @return {Number[]} An array with id's of the overlapping nodes - * @private - */ - value: function _getEdgesOverlappingWith(object, overlappingEdges) { - var edges = this.body.edges; - for (var i = 0; i < this.body.edgeIndices.length; i++) { - var edgeId = this.body.edgeIndices[i]; - if (edges[edgeId].isOverlappingWith(object)) { - overlappingEdges.push(edgeId); - } - } + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + this._distanceToBorder(angle); } - }, { - key: "_getAllEdgesOverlappingWith", + }]); - /** - * retrieve all nodes overlapping with given object - * @param {Object} object An object with parameters left, top, right, bottom - * @return {Number[]} An array with id's of the overlapping nodes - * @private - */ - value: function _getAllEdgesOverlappingWith(object) { - var overlappingEdges = []; - this._getEdgesOverlappingWith(object, overlappingEdges); - return overlappingEdges; - } - }, { - key: "getEdgeAt", + return Icon; + })(_utilNodeBase2['default']); - /** - * Place holder. To implement change the getNodeAt to a _getObjectAt. Have the _getObjectAt call - * getNodeAt and _getEdgesAt, then priortize the selection to user preferences. - * - * @param pointer - * @returns {undefined} - * @private - */ - value: function getEdgeAt(pointer) { - var returnEdge = arguments[1] === undefined ? true : arguments[1]; + exports['default'] = Icon; + module.exports = exports['default']; - var positionObject = this._pointerToPositionObject(pointer); - var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject); +/***/ }, +/* 100 */ +/***/ function(module, exports, __webpack_require__) { - if (overlappingEdges.length > 0) { - if (returnEdge === true) { - return this.body.edges[overlappingEdges[overlappingEdges.length - 1]]; - } else { - return overlappingEdges[overlappingEdges.length - 1]; - } - } else { - return undefined; - } - } - }, { - key: "_addToSelection", + 'use strict'; - /** - * Add object to the selection array. - * - * @param obj - * @private - */ - value: function _addToSelection(obj) { - if (obj instanceof Node) { - this.selectionObj.nodes[obj.id] = obj; - } else { - this.selectionObj.edges[obj.id] = obj; - } - } - }, { - key: "_addToHover", + Object.defineProperty(exports, '__esModule', { + value: true + }); - /** - * Add object to the selection array. - * - * @param obj - * @private - */ - value: function _addToHover(obj) { - if (obj instanceof Node) { - this.hoverObj.nodes[obj.id] = obj; - } else { - this.hoverObj.edges[obj.id] = obj; - } - } - }, { - key: "_removeFromSelection", + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /** - * Remove a single option from selection. - * - * @param {Object} obj - * @private - */ - value: function _removeFromSelection(obj) { - if (obj instanceof Node) { - delete this.selectionObj.nodes[obj.id]; - } else { - delete this.selectionObj.edges[obj.id]; - } - } - }, { - key: "unselectAll", + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - /** - * Unselect all. The selectionObj is useful for this. - * - * @private - */ - value: function unselectAll() { - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - this.selectionObj.nodes[nodeId].unselect(); - } - } - for (var edgeId in this.selectionObj.edges) { - if (this.selectionObj.edges.hasOwnProperty(edgeId)) { - this.selectionObj.edges[edgeId].unselect(); - } - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - this.selectionObj = { nodes: {}, edges: {} }; - } - }, { - key: "_getSelectedNodeCount", + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - /** - * return the number of selected nodes - * - * @returns {number} - * @private - */ - value: function _getSelectedNodeCount() { - var count = 0; - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - count += 1; - } - } - return count; - } - }, { - key: "_getSelectedNode", + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - /** - * return the selected node - * - * @returns {number} - * @private - */ - value: function _getSelectedNode() { - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - return this.selectionObj.nodes[nodeId]; - } - } - return undefined; + var _utilCircleImageBase = __webpack_require__(110); + + var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); + + var Image = (function (_CircleImageBase) { + function Image(options, body, labelModule, imageObj) { + _classCallCheck(this, Image); + + _get(Object.getPrototypeOf(Image.prototype), 'constructor', this).call(this, options, body, labelModule); + this.imageObj = imageObj; + } + + _inherits(Image, _CircleImageBase); + + _createClass(Image, [{ + key: 'resize', + value: function resize() { + this._resizeImage(); } }, { - key: "_getSelectedEdge", + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(); + this.left = x - this.width / 2; + this.top = y - this.height / 2; - /** - * return the selected edge - * - * @returns {number} - * @private - */ - value: function _getSelectedEdge() { - for (var edgeId in this.selectionObj.edges) { - if (this.selectionObj.edges.hasOwnProperty(edgeId)) { - return this.selectionObj.edges[edgeId]; - } - } - return undefined; + this._drawImageAtPosition(ctx); + + this._drawImageLabel(ctx, x, y, selected || hover); + + this.updateBoundingBox(x, y); } }, { - key: "_getSelectedEdgeCount", + key: 'updateBoundingBox', + value: function updateBoundingBox(x, y) { + this.left = x - this.width / 2; + this.top = y - this.height / 2; - /** - * return the number of selected edges - * - * @returns {number} - * @private - */ - value: function _getSelectedEdgeCount() { - var count = 0; - for (var edgeId in this.selectionObj.edges) { - if (this.selectionObj.edges.hasOwnProperty(edgeId)) { - count += 1; - } + this.boundingBox.top = this.top; + this.boundingBox.left = this.left; + this.boundingBox.right = this.left + this.width; + this.boundingBox.bottom = this.top + this.height; + + if (this.options.label !== undefined) { + 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.labelOffset); } - return count; } }, { - key: "_getSelectedObjectCount", + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + var a = this.width / 2; + var b = this.height / 2; + var w = Math.sin(angle) * a; + var h = Math.cos(angle) * b; + return a * b / Math.sqrt(w * w + h * h); + } + }]); - /** - * return the number of selected objects. - * - * @returns {number} - * @private - */ - value: function _getSelectedObjectCount() { - var count = 0; - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - count += 1; - } - } - for (var edgeId in this.selectionObj.edges) { - if (this.selectionObj.edges.hasOwnProperty(edgeId)) { - count += 1; - } - } - return count; + return Image; + })(_utilCircleImageBase2['default']); + + exports['default'] = Image; + module.exports = exports['default']; + +/***/ }, +/* 101 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + + var _utilShapeBase = __webpack_require__(111); + + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + + var Square = (function (_ShapeBase) { + function Square(options, body, labelModule) { + _classCallCheck(this, Square); + + _get(Object.getPrototypeOf(Square.prototype), 'constructor', this).call(this, options, body, labelModule); + } + + _inherits(Square, _ShapeBase); + + _createClass(Square, [{ + key: 'resize', + value: function resize() { + this._resizeShape(); } }, { - key: "_selectionIsEmpty", - - /** - * Check if anything is selected - * - * @returns {boolean} - * @private - */ - value: function _selectionIsEmpty() { - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - return false; - } - } - for (var edgeId in this.selectionObj.edges) { - if (this.selectionObj.edges.hasOwnProperty(edgeId)) { - return false; - } - } - return true; + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this._drawShape(ctx, 'square', 2, x, y, selected, hover); } }, { - key: "_clusterInSelection", + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + return this._distanceToBorder(angle); + } + }]); - /** - * check if one of the selected nodes is a cluster. - * - * @returns {boolean} - * @private - */ - value: function _clusterInSelection() { - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - if (this.selectionObj.nodes[nodeId].clusterSize > 1) { - return true; - } - } - } - return false; + return Square; + })(_utilShapeBase2['default']); + + exports['default'] = Square; + module.exports = exports['default']; + +/***/ }, +/* 102 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + + var _utilShapeBase = __webpack_require__(111); + + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + + var Star = (function (_ShapeBase) { + function Star(options, body, labelModule) { + _classCallCheck(this, Star); + + _get(Object.getPrototypeOf(Star.prototype), 'constructor', this).call(this, options, body, labelModule); + } + + _inherits(Star, _ShapeBase); + + _createClass(Star, [{ + key: 'resize', + value: function resize(ctx) { + this._resizeShape(); } }, { - key: "_selectConnectedEdges", - - /** - * select the edges connected to the node that is being selected - * - * @param {Node} node - * @private - */ - value: function _selectConnectedEdges(node) { - for (var i = 0; i < node.edges.length; i++) { - var edge = node.edges[i]; - edge.select(); - this._addToSelection(edge); - } + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this._drawShape(ctx, 'star', 4, x, y, selected, hover); } }, { - key: "_hoverConnectedEdges", + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + return this._distanceToBorder(angle); + } + }]); - /** - * select the edges connected to the node that is being selected - * - * @param {Node} node - * @private - */ - value: function _hoverConnectedEdges(node) { - for (var i = 0; i < node.edges.length; i++) { - var edge = node.edges[i]; - edge.hover = true; - this._addToHover(edge); + return Star; + })(_utilShapeBase2['default']); + + exports['default'] = Star; + module.exports = exports['default']; + +/***/ }, +/* 103 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + + var _utilNodeBase = __webpack_require__(109); + + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + + var Text = (function (_NodeBase) { + function Text(options, body, labelModule) { + _classCallCheck(this, Text); + + _get(Object.getPrototypeOf(Text.prototype), 'constructor', this).call(this, options, body, labelModule); + } + + _inherits(Text, _NodeBase); + + _createClass(Text, [{ + key: 'resize', + value: function resize(ctx, selected) { + if (this.width === undefined) { + var margin = 5; + var textSize = this.labelModule.getTextSize(ctx, selected); + this.width = textSize.width + 2 * margin; + this.height = textSize.height + 2 * margin; + this.radius = 0.5 * this.width; } } }, { - key: "_unselectConnectedEdges", + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(ctx, selected || hover); + this.left = x - this.width / 2; + this.top = y - this.height / 2; - /** - * unselect the edges connected to the node that is being selected - * - * @param {Node} node - * @private - */ - value: function _unselectConnectedEdges(node) { - for (var i = 0; i < node.edges.length; i++) { - var edge = node.edges[i]; - edge.unselect(); - this._removeFromSelection(edge); - } + // draw shadow if enabled + this.enableShadow(ctx); + this.labelModule.draw(ctx, x, y, selected || hover); + + // disable shadows for other elements. + this.disableShadow(ctx); + + this.updateBoundingBox(x, y); } }, { - key: "blurObject", + key: 'updateBoundingBox', + value: function updateBoundingBox(x, y) { + this.left = x - this.width / 2; + this.top = y - this.height / 2; - /** - * This is called when someone clicks on a node. either select or deselect it. - * If there is an existing selection and we don't want to append to it, clear the existing selection - * - * @param {Node || Edge} object - * @private - */ - value: function blurObject(object) { - if (object.hover === true) { - object.hover = false; - this.body.emitter.emit("blurNode", { node: object.id }); - } + this.boundingBox.top = this.top; + this.boundingBox.left = this.left; + this.boundingBox.right = this.left + this.width; + this.boundingBox.bottom = this.top + this.height; } }, { - key: "hoverObject", + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + return this._distanceToBorder(angle); + } + }]); - /** - * This is called when someone clicks on a node. either select or deselect it. - * If there is an existing selection and we don't want to append to it, clear the existing selection - * - * @param {Node || Edge} object - * @private - */ - value: function hoverObject(object) { - var hoverChanged = false; - // remove all node hover highlights - for (var nodeId in this.hoverObj.nodes) { - if (this.hoverObj.nodes.hasOwnProperty(nodeId)) { - if (object === undefined) { - this.blurObject(this.hoverObj.nodes[nodeId]); - hoverChanged = true; - } else if (object instanceof Node && object.id != nodeId || object instanceof Edge || object === undefined) { - this.blurObject(this.hoverObj.nodes[nodeId]); - hoverChanged = true; - delete this.hoverObj.nodes[nodeId]; - } - } - } + return Text; + })(_utilNodeBase2['default']); - // removing all edge hover highlights - for (var edgeId in this.hoverObj.edges) { - if (this.hoverObj.edges.hasOwnProperty(edgeId)) { - this.hoverObj.edges[edgeId].hover = false; - delete this.hoverObj.edges[edgeId]; - } - } + exports['default'] = Text; + module.exports = exports['default']; - if (object !== undefined) { - if (object.hover === false) { - object.hover = true; - this._addToHover(object); - hoverChanged = true; - if (object instanceof Node) { - this.body.emitter.emit("hoverNode", { node: object.id }); - } - } - if (object instanceof Node && this.options.hoverConnectedEdges === true) { - this._hoverConnectedEdges(object); - } - } +/***/ }, +/* 104 */ +/***/ function(module, exports, __webpack_require__) { - if (hoverChanged === true) { - this.body.emitter.emit("_requestRedraw"); - } - } - }, { - key: "getSelection", + 'use strict'; - /** - * - * retrieve the currently selected objects - * @return {{nodes: Array., edges: Array.}} selection - */ - value: function getSelection() { - var nodeIds = this.getSelectedNodes(); - var edgeIds = this.getSelectedEdges(); - return { nodes: nodeIds, edges: edgeIds }; - } - }, { - key: "getSelectedNodes", + Object.defineProperty(exports, '__esModule', { + value: true + }); - /** - * - * retrieve the currently selected nodes - * @return {String[]} selection An array with the ids of the - * selected nodes. - */ - value: function getSelectedNodes() { - var idArray = []; - if (this.options.selectable === true) { - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - idArray.push(nodeId); - } - } - } - return idArray; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + + var _utilShapeBase = __webpack_require__(111); + + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + + var Triangle = (function (_ShapeBase) { + function Triangle(options, body, labelModule) { + _classCallCheck(this, Triangle); + + _get(Object.getPrototypeOf(Triangle.prototype), 'constructor', this).call(this, options, body, labelModule); + } + + _inherits(Triangle, _ShapeBase); + + _createClass(Triangle, [{ + key: 'resize', + value: function resize(ctx) { + this._resizeShape(); } }, { - key: "getSelectedEdges", - - /** - * - * retrieve the currently selected edges - * @return {Array} selection An array with the ids of the - * selected nodes. - */ - value: function getSelectedEdges() { - var idArray = []; - if (this.options.selectable === true) { - for (var edgeId in this.selectionObj.edges) { - if (this.selectionObj.edges.hasOwnProperty(edgeId)) { - idArray.push(edgeId); - } - } - } - return idArray; + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this._drawShape(ctx, 'triangle', 3, x, y, selected, hover); } }, { - key: "selectNodes", + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + return this._distanceToBorder(angle); + } + }]); - /** - * select zero or more nodes with the option to highlight edges - * @param {Number[] | String[]} selection An array with the ids of the - * selected nodes. - * @param {boolean} [highlightEdges] - */ - value: function selectNodes(selection) { - var highlightEdges = arguments[1] === undefined ? true : arguments[1]; + return Triangle; + })(_utilShapeBase2['default']); - var i = undefined, - id = undefined; + exports['default'] = Triangle; + module.exports = exports['default']; + +/***/ }, +/* 105 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - if (!selection || selection.length === undefined) throw "Selection must be an array with ids"; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - // first unselect any selected node - this.unselectAll(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - for (i = 0; i < selection.length; i++) { - id = selection[i]; + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - var node = this.body.nodes[id]; - if (!node) { - throw new RangeError("Node with id \"" + id + "\" not found"); - } - this.selectObject(node, highlightEdges); - } - this.body.emitter.emit("_requestRedraw"); - } - }, { - key: "selectEdges", + var _utilShapeBase = __webpack_require__(111); - /** - * select zero or more edges - * @param {Number[] | String[]} selection An array with the ids of the - * selected nodes. - */ - value: function selectEdges(selection) { - var i = undefined, - id = undefined; + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); - if (!selection || selection.length === undefined) throw "Selection must be an array with ids"; + var TriangleDown = (function (_ShapeBase) { + function TriangleDown(options, body, labelModule) { + _classCallCheck(this, TriangleDown); - // first unselect any selected objects - this.unselectAll(); + _get(Object.getPrototypeOf(TriangleDown.prototype), 'constructor', this).call(this, options, body, labelModule); + } - for (i = 0; i < selection.length; i++) { - id = selection[i]; + _inherits(TriangleDown, _ShapeBase); - var edge = this.body.edges[id]; - if (!edge) { - throw new RangeError("Edge with id \"" + id + "\" not found"); - } - this.selectObject(edge); - } - this.body.emitter.emit("_requestRedraw"); + _createClass(TriangleDown, [{ + key: 'resize', + value: function resize(ctx) { + this._resizeShape(); } }, { - key: "updateSelection", - - /** - * Validate the selection: remove ids of nodes which no longer exist - * @private - */ - value: function updateSelection() { - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - if (!this.body.nodes.hasOwnProperty(nodeId)) { - delete this.selectionObj.nodes[nodeId]; - } - } - } - for (var edgeId in this.selectionObj.edges) { - if (this.selectionObj.edges.hasOwnProperty(edgeId)) { - if (!this.body.edges.hasOwnProperty(edgeId)) { - delete this.selectionObj.edges[edgeId]; - } - } - } + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this._drawShape(ctx, 'triangleDown', 3, x, y, selected, hover); + } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + return this._distanceToBorder(angle); } }]); - return SelectionHandler; - })(); + return TriangleDown; + })(_utilShapeBase2['default']); - exports["default"] = SelectionHandler; - module.exports = exports["default"]; + exports['default'] = TriangleDown; + module.exports = exports['default']; /***/ }, -/* 108 */ +/* 106 */ /***/ function(module, exports, __webpack_require__) { - /** - * This object contains all possible options. It will check if the types are correct, if required if the option is one - * of the allowed values. - * - * __any__ means that the name of the property does not matter. - * __type__ is a required field for all objects and contains the allowed types of all objects - */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); - var string = 'string'; - var boolean = 'boolean'; - var number = 'number'; - var array = 'array'; - var object = 'object'; // should only be in a __type__ property - var dom = 'dom'; - var fn = 'function'; - var undef = 'undefined'; - var any = 'any'; - var allOptions = { - configure: { - enabled: { boolean: boolean }, - filter: { boolean: boolean, string: string, array: array, fn: fn }, - container: { dom: dom }, - showButton: { boolean: boolean }, - __type__: { object: object, boolean: boolean, string: string, array: array, fn: fn } - }, - edges: { - arrows: { - to: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } }, - middle: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } }, - from: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } }, - __type__: { string: ['from', 'to', 'middle'], object: object } - }, - color: { - color: { string: string }, - highlight: { string: string }, - hover: { string: string }, - inherit: { string: ['from', 'to', 'both'], boolean: boolean }, - opacity: { number: number }, - __type__: { object: object, string: string } - }, - dashes: { boolean: boolean, array: array }, - font: { - color: { string: string }, - size: { number: number }, // px - face: { string: string }, - background: { string: string }, - strokeWidth: { number: number }, // px - strokeColor: { string: string }, - align: { string: ['horizontal', 'top', 'middle', 'bottom'] }, - __type__: { object: object, string: string } - }, - hidden: { boolean: boolean }, - hoverWidth: { fn: fn, number: number }, - label: { string: string, undef: undef }, - length: { number: number, undef: undef }, - physics: { boolean: boolean }, - scaling: { - min: { number: number }, - max: { number: number }, - label: { - enabled: { boolean: boolean }, - min: { number: number }, - max: { number: number }, - maxVisible: { number: number }, - drawThreshold: { number: number }, - __type__: { object: object, boolean: boolean } - }, - customScalingFunction: { fn: fn }, - __type__: { object: object } - }, - selectionWidth: { fn: fn, number: number }, - selfReferenceSize: { number: number }, - shadow: { - enabled: { boolean: boolean }, - size: { number: number }, - x: { number: number }, - y: { number: number }, - __type__: { object: object, boolean: boolean } - }, - smooth: { - enabled: { boolean: boolean }, - type: { string: ['dynamic', 'continuous', 'discrete', 'diagonalCross', 'straightCross', 'horizontal', 'vertical', 'curvedCW', 'curvedCCW'] }, - roundness: { number: number }, - __type__: { object: object, boolean: boolean } - }, - title: { string: string, undef: undef }, - width: { number: number }, - value: { number: number, undef: undef }, - __type__: { object: object } - }, - groups: { - useDefaultGroups: { boolean: boolean }, - __any__: 'get from nodes, will be overwritten below', - __type__: { object: object } - }, - interaction: { - dragNodes: { boolean: boolean }, - dragView: { boolean: boolean }, - hideEdgesOnDrag: { boolean: boolean }, - hideNodesOnDrag: { boolean: boolean }, - hover: { boolean: boolean }, - keyboard: { - enabled: { boolean: boolean }, - speed: { x: { number: number }, y: { number: number }, zoom: { number: number }, __type__: { object: object } }, - bindToWindow: { boolean: boolean }, - __type__: { object: object, boolean: boolean } - }, - multiselect: { boolean: boolean }, - navigationButtons: { boolean: boolean }, - selectable: { boolean: boolean }, - selectConnectedEdges: { boolean: boolean }, - hoverConnectedEdges: { boolean: boolean }, - tooltipDelay: { number: number }, - zoomView: { boolean: boolean }, - __type__: { object: object } - }, - layout: { - randomSeed: { undef: undef, number: number }, - hierarchical: { - enabled: { boolean: boolean }, - levelSeparation: { number: number }, - direction: { string: ['UD', 'DU', 'LR', 'RL'] }, // UD, DU, LR, RL - sortMethod: { string: ['hubsize', 'directed'] }, // hubsize, directed - __type__: { object: object, boolean: boolean } - }, - __type__: { object: object } - }, - manipulation: { - enabled: { boolean: boolean }, - initiallyActive: { boolean: boolean }, - addNode: { boolean: boolean, fn: fn }, - addEdge: { boolean: boolean, fn: fn }, - editNode: { fn: fn }, - editEdge: { boolean: boolean, fn: fn }, - deleteNode: { boolean: boolean, fn: fn }, - deleteEdge: { boolean: boolean, fn: fn }, - controlNodeStyle: 'get from nodes, will be overwritten below', - __type__: { object: object, boolean: boolean } - }, - nodes: { - borderWidth: { number: number }, - borderWidthSelected: { number: number, undef: undef }, - brokenImage: { string: string, undef: undef }, - color: { - border: { string: string }, - background: { string: string }, - highlight: { - border: { string: string }, - background: { string: string }, - __type__: { object: object, string: string } - }, - hover: { - border: { string: string }, - background: { string: string }, - __type__: { object: object, string: string } - }, - __type__: { object: object, string: string } - }, - fixed: { - x: { boolean: boolean }, - y: { boolean: boolean }, - __type__: { object: object, boolean: boolean } - }, - font: { - color: { string: string }, - size: { number: number }, // px - face: { string: string }, - background: { string: string }, - strokeWidth: { number: number }, // px - strokeColor: { string: string }, - __type__: { object: object, string: string } - }, - group: { string: string, number: number, undef: undef }, - hidden: { boolean: boolean }, - icon: { - face: { string: string }, - code: { string: string }, //'\uf007', - size: { number: number }, //50, - color: { string: string }, - __type__: { object: object } - }, - id: { string: string, number: number }, - image: { string: string, undef: undef }, // --> URL - label: { string: string, undef: undef }, - level: { number: number, undef: undef }, - mass: { number: number }, - physics: { boolean: boolean }, - scaling: { - min: { number: number }, - max: { number: number }, - label: { - enabled: { boolean: boolean }, - min: { number: number }, - max: { number: number }, - maxVisible: { number: number }, - drawThreshold: { number: number }, - __type__: { object: object, boolean: boolean } - }, - customScalingFunction: { fn: fn }, - __type__: { object: object } - }, - shadow: { - enabled: { boolean: boolean }, - size: { number: number }, - x: { number: number }, - y: { number: number }, - __type__: { object: object, boolean: boolean } - }, - shape: { string: ['ellipse', 'circle', 'database', 'box', 'text', 'image', 'circularImage', 'diamond', 'dot', 'star', 'triangle', 'triangleDown', 'square', 'icon'] }, - size: { number: number }, - title: { string: string, undef: undef }, - value: { number: number, undef: undef }, - x: { number: number }, - y: { number: number }, - __type__: { object: object } - }, - physics: { - barnesHut: { - gravitationalConstant: { number: number }, - centralGravity: { number: number }, - springLength: { number: number }, - springConstant: { number: number }, - damping: { number: number }, - avoidOverlap: { number: number }, - __type__: { object: object } - }, - forceAtlas2Based: { - gravitationalConstant: { number: number }, - centralGravity: { number: number }, - springLength: { number: number }, - springConstant: { number: number }, - damping: { number: number }, - avoidOverlap: { number: number }, - __type__: { object: object } - }, - repulsion: { - centralGravity: { number: number }, - springLength: { number: number }, - springConstant: { number: number }, - nodeDistance: { number: number }, - damping: { number: number }, - __type__: { object: object } - }, - hierarchicalRepulsion: { - centralGravity: { number: number }, - springLength: { number: number }, - springConstant: { number: number }, - nodeDistance: { number: number }, - damping: { number: number }, - __type__: { object: object } - }, - maxVelocity: { number: number }, - minVelocity: { number: number }, // px/s - solver: { string: ['barnesHut', 'repulsion', 'hierarchicalRepulsion', 'forceAtlas2Based'] }, - stabilization: { - enabled: { boolean: boolean }, - iterations: { number: number }, // maximum number of iteration to stabilize - updateInterval: { number: number }, - onlyDynamicEdges: { boolean: boolean }, - fit: { boolean: boolean }, - __type__: { object: object, boolean: boolean } - }, - timestep: { number: number }, - __type__: { object: object, boolean: boolean } - }, + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - //globals : - autoResize: { boolean: boolean }, - clickToUse: { boolean: boolean }, - locale: { string: string }, - locales: { - __any__: { object: object }, - __type__: { object: object } - }, - height: { string: string }, - width: { string: string }, - __type__: { object: object } - }; + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - allOptions.groups.__any__ = allOptions.nodes; - allOptions.manipulation.controlNodeStyle = allOptions.nodes; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - var configureOptions = { - nodes: { - borderWidth: [1, 0, 10, 1], - borderWidthSelected: [2, 0, 10, 1], - color: { - border: ['color', '#2B7CE9'], - background: ['color', '#97C2FC'], - highlight: { - border: ['color', '#2B7CE9'], - background: ['color', '#D2E5FF'] - }, - hover: { - border: ['color', '#2B7CE9'], - background: ['color', '#D2E5FF'] + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + + var _utilBezierEdgeBase = __webpack_require__(112); + + var _utilBezierEdgeBase2 = _interopRequireDefault(_utilBezierEdgeBase); + + var BezierEdgeDynamic = (function (_BezierEdgeBase) { + function BezierEdgeDynamic(options, body, labelModule) { + _classCallCheck(this, BezierEdgeDynamic); + + //this.via = undefined; // Here for completeness but not allowed to defined before super() is invoked. + _get(Object.getPrototypeOf(BezierEdgeDynamic.prototype), 'constructor', this).call(this, options, body, labelModule); // --> this calls the setOptions below + } + + _inherits(BezierEdgeDynamic, _BezierEdgeBase); + + _createClass(BezierEdgeDynamic, [{ + key: 'setOptions', + value: function setOptions(options) { + this.options = options; + this.id = this.options.id; + this.setupSupportNode(); + this.connect(); + } + }, { + key: 'connect', + value: function connect() { + this.from = this.body.nodes[this.options.from]; + this.to = this.body.nodes[this.options.to]; + if (this.from === undefined || this.to === undefined) { + this.via.setOptions({ physics: false }); + } else { + // fix weird behaviour where a selfreferencing node has physics enabled + if (this.from.id === this.to.id) { + this.via.setOptions({ physics: false }); + } else { + this.via.setOptions({ physics: true }); + } } - }, - fixed: { - x: false, - y: false - }, - font: { - color: ['color', '#343434'], - size: [14, 0, 100, 1], // px - face: ['arial', 'verdana', 'tahoma'], - background: ['color', 'none'], - strokeWidth: [0, 0, 50, 1], // px - strokeColor: ['color', '#ffffff'] - }, - //group: 'string', - hidden: false, - //icon: { - // face: 'string', //'FontAwesome', - // code: 'string', //'\uf007', - // size: [50, 0, 200, 1], //50, - // color: ['color','#2B7CE9'] //'#aa00ff' - //}, - //image: 'string', // --> URL - physics: true, - scaling: { - min: [10, 0, 200, 1], - max: [30, 0, 200, 1], - label: { - enabled: false, - min: [14, 0, 200, 1], - max: [30, 0, 200, 1], - maxVisible: [30, 0, 200, 1], - drawThreshold: [5, 0, 20, 1] + } + }, { + key: 'cleanup', + value: function cleanup() { + if (this.via !== undefined) { + delete this.body.nodes[this.via.id]; + this.via = undefined; + return true; } - }, - shadow: { - enabled: false, - size: [10, 0, 20, 1], - x: [5, -30, 30, 1], - y: [5, -30, 30, 1] - }, - shape: ['ellipse', 'box', 'circle', 'database', 'diamond', 'dot', 'square', 'star', 'text', 'triangle', 'triangleDown'], - size: [25, 0, 200, 1] - }, - edges: { - arrows: { - to: { enabled: false, scaleFactor: [1, 0, 3, 0.05] }, // boolean / {arrowScaleFactor:1} / {enabled: false, arrowScaleFactor:1} - middle: { enabled: false, scaleFactor: [1, 0, 3, 0.05] }, - from: { enabled: false, scaleFactor: [1, 0, 3, 0.05] } - }, - color: { - color: ['color', '#848484'], - highlight: ['color', '#848484'], - hover: ['color', '#848484'], - inherit: ['from', 'to', 'both', true, false], - opacity: [1, 0, 1, 0.05] - }, - dashes: false, - font: { - color: ['color', '#343434'], - size: [14, 0, 100, 1], // px - face: ['arial', 'verdana', 'tahoma'], - background: ['color', 'none'], - strokeWidth: [2, 0, 50, 1], // px - strokeColor: ['color', '#ffffff'], - align: ['horizontal', 'top', 'middle', 'bottom'] - }, - hidden: false, - hoverWidth: [1.5, 0, 5, 0.1], - physics: true, - scaling: { - min: [1, 0, 100, 1], - max: [15, 0, 100, 1], - label: { - enabled: true, - min: [14, 0, 200, 1], - max: [30, 0, 200, 1], - maxVisible: [30, 0, 200, 1], - drawThreshold: [5, 0, 20, 1] + return false; + } + }, { + key: 'togglePhysics', + value: function togglePhysics(status) { + this.via.setOptions({ physics: status }); + } + }, { + key: 'setupSupportNode', + + /** + * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but + * are used for the force calculation. + * + * The changed data is not called, if needed, it is returned by the main edge constructor. + * @private + */ + value: function setupSupportNode() { + if (this.via === undefined) { + var nodeId = 'edgeId:' + this.id; + var node = this.body.functions.createNode({ + id: nodeId, + shape: 'circle', + physics: true, + hidden: true + }); + this.body.nodes[nodeId] = node; + this.via = node; + this.via.parentEdgeId = this.id; + this.positionBezierNode(); } - }, - selectionWidth: [1.5, 0, 5, 0.1], - selfReferenceSize: [20, 0, 200, 1], - shadow: { - enabled: false, - size: [10, 0, 20, 1], - x: [5, -30, 30, 1], - y: [5, -30, 30, 1] - }, - smooth: { - enabled: true, - type: ['dynamic', 'continuous', 'discrete', 'diagonalCross', 'straightCross', 'horizontal', 'vertical', 'curvedCW', 'curvedCCW'], - roundness: [0.5, 0, 1, 0.05] - }, - width: [1, 0, 30, 1] - }, - layout: { - //randomSeed: [0, 0, 500, 1], - hierarchical: { - enabled: false, - levelSeparation: [150, 20, 500, 5], - direction: ['UD', 'DU', 'LR', 'RL'], // UD, DU, LR, RL - sortMethod: ['hubsize', 'directed'] // hubsize, directed } - }, - interaction: { - dragNodes: true, - dragView: true, - hideEdgesOnDrag: false, - hideNodesOnDrag: false, - hover: false, - keyboard: { - enabled: false, - speed: { x: [10, 0, 40, 1], y: [10, 0, 40, 1], zoom: [0.02, 0, 0.1, 0.005] }, - bindToWindow: true - }, - multiselect: false, - navigationButtons: false, - selectable: true, - selectConnectedEdges: true, - hoverConnectedEdges: true, - tooltipDelay: [300, 0, 1000, 25], - zoomView: true - }, - manipulation: { - enabled: false, - initiallyActive: false - }, - physics: { - barnesHut: { - //theta: [0.5, 0.1, 1, 0.05], - gravitationalConstant: [-2000, -30000, 0, 50], - centralGravity: [0.3, 0, 10, 0.05], - springLength: [95, 0, 500, 5], - springConstant: [0.04, 0, 1.2, 0.005], - damping: [0.09, 0, 1, 0.01], - avoidOverlap: [0, 0, 1, 0.01] - }, - forceAtlas2Based: { - //theta: [0.5, 0.1, 1, 0.05], - gravitationalConstant: [-50, -500, 0, 1], - centralGravity: [0.01, 0, 1, 0.005], - springLength: [95, 0, 500, 5], - springConstant: [0.08, 0, 1.2, 0.005], - damping: [0.4, 0, 1, 0.01], - avoidOverlap: [0, 0, 1, 0.01] - }, - repulsion: { - centralGravity: [0.2, 0, 10, 0.05], - springLength: [200, 0, 500, 5], - springConstant: [0.05, 0, 1.2, 0.005], - nodeDistance: [100, 0, 500, 5], - damping: [0.09, 0, 1, 0.01] - }, - hierarchicalRepulsion: { - centralGravity: [0.2, 0, 10, 0.05], - springLength: [100, 0, 500, 5], - springConstant: [0.01, 0, 1.2, 0.005], - nodeDistance: [120, 0, 500, 5], - damping: [0.09, 0, 1, 0.01] - }, - maxVelocity: [50, 0, 150, 1], - minVelocity: [0.1, 0.01, 0.5, 0.01], - solver: ['barnesHut', 'forceAtlas2Based', 'repulsion', 'hierarchicalRepulsion'], - timestep: [0.5, 0.01, 1, 0.01] - }, - global: { - locale: ['en', 'nl'] - } - }; + }, { + key: 'positionBezierNode', + value: function positionBezierNode() { + if (this.via !== undefined && this.from !== undefined && this.to !== undefined) { + this.via.x = 0.5 * (this.from.x + this.to.x); + this.via.y = 0.5 * (this.from.y + this.to.y); + } else if (this.via !== undefined) { + this.via.x = 0; + this.via.y = 0; + } + } + }, { + key: '_line', - exports.allOptions = allOptions; - exports.configureOptions = configureOptions; + /** + * Draw a line between two nodes + * @param {CanvasRenderingContext2D} ctx + * @private + */ + value: function _line(ctx) { + // draw a straight line + ctx.beginPath(); + ctx.moveTo(this.from.x, this.from.y); + ctx.quadraticCurveTo(this.via.x, this.via.y, this.to.x, this.to.y); + // draw shadow if enabled + this.enableShadow(ctx); + ctx.stroke(); + this.disableShadow(ctx); + return this.via; + } + }, { + key: 'getPoint', + + /** + * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way + * @param percentage + * @param via + * @returns {{x: number, y: number}} + * @private + */ + value: function getPoint(percentage) { + var t = percentage; + var x = Math.pow(1 - t, 2) * this.from.x + 2 * t * (1 - t) * this.via.x + Math.pow(t, 2) * this.to.x; + var y = Math.pow(1 - t, 2) * this.from.y + 2 * t * (1 - t) * this.via.y + Math.pow(t, 2) * this.to.y; + + return { x: x, y: y }; + } + }, { + key: '_findBorderPosition', + value: function _findBorderPosition(nearNode, ctx) { + return this._findBorderPositionBezier(nearNode, ctx, this.via); + } + }, { + key: '_getDistanceToEdge', + value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) { + // x3,y3 is the point + return this._getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, this.via); + } + }]); + + return BezierEdgeDynamic; + })(_utilBezierEdgeBase2['default']); + + exports['default'] = BezierEdgeDynamic; + module.exports = exports['default']; /***/ }, -/* 109 */ +/* 107 */ /***/ function(module, exports, __webpack_require__) { - /** - * Canvas shapes used by Network - */ 'use strict'; - if (typeof CanvasRenderingContext2D !== 'undefined') { + Object.defineProperty(exports, '__esModule', { + value: true + }); - /** - * Draw a circle shape - */ - CanvasRenderingContext2D.prototype.circle = function (x, y, r) { - this.beginPath(); - this.arc(x, y, r, 0, 2 * Math.PI, false); - this.closePath(); - }; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /** - * Draw a square shape - * @param {Number} x horizontal center - * @param {Number} y vertical center - * @param {Number} r size, width and height of the square - */ - CanvasRenderingContext2D.prototype.square = function (x, y, r) { - this.beginPath(); - this.rect(x - r, y - r, r * 2, r * 2); - this.closePath(); - }; + var _get = function get(_x4, _x5, _x6) { var _again = true; _function: while (_again) { var object = _x4, property = _x5, receiver = _x6; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x4 = parent; _x5 = property; _x6 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - /** - * Draw a triangle shape - * @param {Number} x horizontal center - * @param {Number} y vertical center - * @param {Number} r radius, half the length of the sides of the triangle - */ - CanvasRenderingContext2D.prototype.triangle = function (x, y, r) { - // http://en.wikipedia.org/wiki/Equilateral_triangle - this.beginPath(); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - // the change in radius and the offset is here to center the shape - r *= 1.15; - y += 0.275 * r; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var s = r * 2; - var s2 = s / 2; - var ir = Math.sqrt(3) / 6 * s; // radius of inner circle - var h = Math.sqrt(s * s - s2 * s2); // height + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - this.moveTo(x, y - (h - ir)); - this.lineTo(x + s2, y + ir); - this.lineTo(x - s2, y + ir); - this.lineTo(x, y - (h - ir)); - this.closePath(); - }; + var _utilBezierEdgeBase = __webpack_require__(112); - /** - * Draw a triangle shape in downward orientation - * @param {Number} x horizontal center - * @param {Number} y vertical center - * @param {Number} r radius - */ - CanvasRenderingContext2D.prototype.triangleDown = function (x, y, r) { - // http://en.wikipedia.org/wiki/Equilateral_triangle - this.beginPath(); + var _utilBezierEdgeBase2 = _interopRequireDefault(_utilBezierEdgeBase); - // the change in radius and the offset is here to center the shape - r *= 1.15; - y -= 0.275 * r; + var BezierEdgeStatic = (function (_BezierEdgeBase) { + function BezierEdgeStatic(options, body, labelModule) { + _classCallCheck(this, BezierEdgeStatic); - var s = r * 2; - var s2 = s / 2; - var ir = Math.sqrt(3) / 6 * s; // radius of inner circle - var h = Math.sqrt(s * s - s2 * s2); // height + _get(Object.getPrototypeOf(BezierEdgeStatic.prototype), 'constructor', this).call(this, options, body, labelModule); + } - this.moveTo(x, y + (h - ir)); - this.lineTo(x + s2, y - ir); - this.lineTo(x - s2, y - ir); - this.lineTo(x, y + (h - ir)); - this.closePath(); - }; + _inherits(BezierEdgeStatic, _BezierEdgeBase); - /** - * Draw a star shape, a star with 5 points - * @param {Number} x horizontal center - * @param {Number} y vertical center - * @param {Number} r radius, half the length of the sides of the triangle - */ - CanvasRenderingContext2D.prototype.star = function (x, y, r) { - // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/ - this.beginPath(); + _createClass(BezierEdgeStatic, [{ + key: '_line', - // the change in radius and the offset is here to center the shape - r *= 0.82; - y += 0.1 * r; + /** + * Draw a line between two nodes + * @param {CanvasRenderingContext2D} ctx + * @private + */ + value: function _line(ctx) { + // draw a straight line + ctx.beginPath(); + ctx.moveTo(this.from.x, this.from.y); + var via = this._getViaCoordinates(); + var returnValue = via; - for (var n = 0; n < 10; n++) { - var radius = n % 2 === 0 ? r * 1.3 : r * 0.5; - this.lineTo(x + radius * Math.sin(n * 2 * Math.PI / 10), y - radius * Math.cos(n * 2 * Math.PI / 10)); + // fallback to normal straight edges + if (via.x === undefined) { + ctx.lineTo(this.to.x, this.to.y); + returnValue = undefined; + } else { + ctx.quadraticCurveTo(via.x, via.y, this.to.x, this.to.y); + } + // draw shadow if enabled + this.enableShadow(ctx); + ctx.stroke(); + this.disableShadow(ctx); + return returnValue; + } + }, { + key: '_getViaCoordinates', + value: function _getViaCoordinates() { + var xVia = undefined; + var yVia = undefined; + var factor = this.options.smooth.roundness; + var type = this.options.smooth.type; + var dx = Math.abs(this.from.x - this.to.x); + var dy = Math.abs(this.from.y - this.to.y); + if (type === 'discrete' || type === 'diagonalCross') { + if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { + if (this.from.y > this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dy; + yVia = this.from.y - factor * dy; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dy; + yVia = this.from.y - factor * dy; + } + } else if (this.from.y < this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dy; + yVia = this.from.y + factor * dy; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dy; + yVia = this.from.y + factor * dy; + } + } + if (type === 'discrete') { + xVia = dx < factor * dy ? this.from.x : xVia; + } + } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { + if (this.from.y > this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dx; + yVia = this.from.y - factor * dx; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dx; + yVia = this.from.y - factor * dx; + } + } else if (this.from.y < this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dx; + yVia = this.from.y + factor * dx; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dx; + yVia = this.from.y + factor * dx; + } + } + if (type === 'discrete') { + yVia = dy < factor * dx ? this.from.y : yVia; + } + } + } else if (type === 'straightCross') { + if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { + // up - down + xVia = this.from.x; + if (this.from.y < this.to.y) { + yVia = this.to.y - (1 - factor) * dy; + } else { + yVia = this.to.y + (1 - factor) * dy; + } + } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { + // left - right + if (this.from.x < this.to.x) { + xVia = this.to.x - (1 - factor) * dx; + } else { + xVia = this.to.x + (1 - factor) * dx; + } + yVia = this.from.y; + } + } else if (type === 'horizontal') { + if (this.from.x < this.to.x) { + xVia = this.to.x - (1 - factor) * dx; + } else { + xVia = this.to.x + (1 - factor) * dx; + } + yVia = this.from.y; + } else if (type === 'vertical') { + xVia = this.from.x; + if (this.from.y < this.to.y) { + yVia = this.to.y - (1 - factor) * dy; + } else { + yVia = this.to.y + (1 - factor) * dy; + } + } else if (type === 'curvedCW') { + dx = this.to.x - this.from.x; + dy = this.from.y - this.to.y; + var radius = Math.sqrt(dx * dx + dy * dy); + var pi = Math.PI; + + var originalAngle = Math.atan2(dy, dx); + var myAngle = (originalAngle + (factor * 0.5 + 0.5) * pi) % (2 * pi); + + xVia = this.from.x + (factor * 0.5 + 0.5) * radius * Math.sin(myAngle); + yVia = this.from.y + (factor * 0.5 + 0.5) * radius * Math.cos(myAngle); + } else if (type === 'curvedCCW') { + dx = this.to.x - this.from.x; + dy = this.from.y - this.to.y; + var radius = Math.sqrt(dx * dx + dy * dy); + var pi = Math.PI; + + var originalAngle = Math.atan2(dy, dx); + var myAngle = (originalAngle + (-factor * 0.5 + 0.5) * pi) % (2 * pi); + + xVia = this.from.x + (factor * 0.5 + 0.5) * radius * Math.sin(myAngle); + yVia = this.from.y + (factor * 0.5 + 0.5) * radius * Math.cos(myAngle); + } else { + // continuous + if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { + if (this.from.y > this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dy; + yVia = this.from.y - factor * dy; + xVia = this.to.x < xVia ? this.to.x : xVia; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dy; + yVia = this.from.y - factor * dy; + xVia = this.to.x > xVia ? this.to.x : xVia; + } + } else if (this.from.y < this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dy; + yVia = this.from.y + factor * dy; + xVia = this.to.x < xVia ? this.to.x : xVia; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dy; + yVia = this.from.y + factor * dy; + xVia = this.to.x > xVia ? this.to.x : xVia; + } + } + } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { + if (this.from.y > this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dx; + yVia = this.from.y - factor * dx; + yVia = this.to.y > yVia ? this.to.y : yVia; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dx; + yVia = this.from.y - factor * dx; + yVia = this.to.y > yVia ? this.to.y : yVia; + } + } else if (this.from.y < this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dx; + yVia = this.from.y + factor * dx; + yVia = this.to.y < yVia ? this.to.y : yVia; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dx; + yVia = this.from.y + factor * dx; + yVia = this.to.y < yVia ? this.to.y : yVia; + } + } + } + } + return { x: xVia, y: yVia }; + } + }, { + key: '_findBorderPosition', + value: function _findBorderPosition(nearNode, ctx) { + var options = arguments[2] === undefined ? {} : arguments[2]; + + return this._findBorderPositionBezier(nearNode, ctx, options.via); + } + }, { + key: '_getDistanceToEdge', + value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) { + var via = arguments[6] === undefined ? this._getViaCoordinates() : arguments[6]; + // x3,y3 is the point + return this._getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via); + } + }, { + key: 'getPoint', + + /** + * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way + * @param percentage + * @param via + * @returns {{x: number, y: number}} + * @private + */ + value: function getPoint(percentage) { + var via = arguments[1] === undefined ? this._getViaCoordinates() : arguments[1]; + + var t = percentage; + var x = Math.pow(1 - t, 2) * this.from.x + 2 * t * (1 - t) * via.x + Math.pow(t, 2) * this.to.x; + var y = Math.pow(1 - t, 2) * this.from.y + 2 * t * (1 - t) * via.y + Math.pow(t, 2) * this.to.y; + + return { x: x, y: y }; } + }]); + + return BezierEdgeStatic; + })(_utilBezierEdgeBase2['default']); + + exports['default'] = BezierEdgeStatic; + module.exports = exports['default']; + +/***/ }, +/* 108 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); - this.closePath(); - }; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /** - * Draw a Diamond shape - * @param {Number} x horizontal center - * @param {Number} y vertical center - * @param {Number} r radius, half the length of the sides of the triangle - */ - CanvasRenderingContext2D.prototype.diamond = function (x, y, r) { - // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/ - this.beginPath(); + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - this.lineTo(x, y + r); - this.lineTo(x + r, y); - this.lineTo(x, y - r); - this.lineTo(x - r, y); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - this.closePath(); - }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - /** - * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas - */ - CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) { - var r2d = Math.PI / 180; - if (w - 2 * r < 0) { - r = w / 2; - } //ensure that the radius isn't too large for x - if (h - 2 * r < 0) { - r = h / 2; - } //ensure that the radius isn't too large for y - this.beginPath(); - this.moveTo(x + r, y); - this.lineTo(x + w - r, y); - this.arc(x + w - r, y + r, r, r2d * 270, r2d * 360, false); - this.lineTo(x + w, y + h - r); - this.arc(x + w - r, y + h - r, r, 0, r2d * 90, false); - this.lineTo(x + r, y + h); - this.arc(x + r, y + h - r, r, r2d * 90, r2d * 180, false); - this.lineTo(x, y + r); - this.arc(x + r, y + r, r, r2d * 180, r2d * 270, false); - this.closePath(); - }; + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - /** - * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas - */ - CanvasRenderingContext2D.prototype.ellipse = function (x, y, w, h) { - var kappa = 0.5522848, - ox = w / 2 * kappa, - // control point offset horizontal - oy = h / 2 * kappa, - // control point offset vertical - xe = x + w, - // x-end - ye = y + h, - // y-end - xm = x + w / 2, - // x-middle - ym = y + h / 2; // y-middle + var _utilEdgeBase = __webpack_require__(113); - this.beginPath(); - this.moveTo(x, ym); - this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); - this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); - this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); - this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); - this.closePath(); - }; + var _utilEdgeBase2 = _interopRequireDefault(_utilEdgeBase); - /** - * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas - */ - CanvasRenderingContext2D.prototype.database = function (x, y, w, h) { - var f = 1 / 3; - var wEllipse = w; - var hEllipse = h * f; + var StraightEdge = (function (_EdgeBase) { + function StraightEdge(options, body, labelModule) { + _classCallCheck(this, StraightEdge); - var kappa = 0.5522848, - ox = wEllipse / 2 * kappa, - // control point offset horizontal - oy = hEllipse / 2 * kappa, - // control point offset vertical - xe = x + wEllipse, - // x-end - ye = y + hEllipse, - // y-end - xm = x + wEllipse / 2, - // x-middle - ym = y + hEllipse / 2, - // y-middle - ymb = y + (h - hEllipse / 2), - // y-midlle, bottom ellipse - yeb = y + h; // y-end, bottom ellipse + _get(Object.getPrototypeOf(StraightEdge.prototype), 'constructor', this).call(this, options, body, labelModule); + } - this.beginPath(); - this.moveTo(xe, ym); + _inherits(StraightEdge, _EdgeBase); - this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); - this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + _createClass(StraightEdge, [{ + key: '_line', - this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); - this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + /** + * Draw a line between two nodes + * @param {CanvasRenderingContext2D} ctx + * @private + */ + value: function _line(ctx) { + // draw a straight line + ctx.beginPath(); + ctx.moveTo(this.from.x, this.from.y); + ctx.lineTo(this.to.x, this.to.y); + // draw shadow if enabled + this.enableShadow(ctx); + ctx.stroke(); + this.disableShadow(ctx); + return undefined; + } + }, { + key: 'getPoint', - this.lineTo(xe, ymb); + /** + * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way + * @param percentage + * @param via + * @returns {{x: number, y: number}} + * @private + */ + value: function getPoint(percentage) { + return { + x: (1 - percentage) * this.from.x + percentage * this.to.x, + y: (1 - percentage) * this.from.y + percentage * this.to.y + }; + } + }, { + key: '_findBorderPosition', + value: function _findBorderPosition(nearNode, ctx) { + var node1 = this.to; + var node2 = this.from; + if (nearNode.id === this.from.id) { + node1 = this.from; + node2 = this.to; + } - this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb); - this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb); + var angle = Math.atan2(node1.y - node2.y, node1.x - node2.x); + var dx = node1.x - node2.x; + var dy = node1.y - node2.y; + var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); + var toBorderDist = nearNode.distanceToBorder(ctx, angle); + var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength; - this.lineTo(x, ym); - }; + var borderPos = {}; + borderPos.x = (1 - toBorderPoint) * node2.x + toBorderPoint * node1.x; + borderPos.y = (1 - toBorderPoint) * node2.y + toBorderPoint * node1.y; - /** - * Draw an arrow point (no line) - */ - CanvasRenderingContext2D.prototype.arrow = function (x, y, angle, length) { - // tail - var xt = x - length * Math.cos(angle); - var yt = y - length * Math.sin(angle); + return borderPos; + } + }, { + key: '_getDistanceToEdge', + value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) { + // x3,y3 is the point + return this._getDistanceToLine(x1, y1, x2, y2, x3, y3); + } + }]); - // inner tail - var xi = x - length * 0.9 * Math.cos(angle); - var yi = y - length * 0.9 * Math.sin(angle); + return StraightEdge; + })(_utilEdgeBase2['default']); - // left - var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI); - var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI); + exports['default'] = StraightEdge; + module.exports = exports['default']; - // right - var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI); - var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI); +/***/ }, +/* 109 */ +/***/ function(module, exports, __webpack_require__) { - this.beginPath(); - this.moveTo(x, y); - this.lineTo(xl, yl); - this.lineTo(xi, yi); - this.lineTo(xr, yr); - this.closePath(); - }; + 'use strict'; - /** - * Sets up the dashedLine functionality for drawing - * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas - * @author David Jordan - * @date 2012-08-08 - */ - CanvasRenderingContext2D.prototype.dashedLine = function (x, y, x2, y2, pattern) { - this.beginPath(); - this.moveTo(x, y); + Object.defineProperty(exports, '__esModule', { + value: true + }); - var patternLength = pattern.length; - var dx = x2 - x; - var dy = y2 - y; - var slope = dy / dx; - var distRemaining = Math.sqrt(dx * dx + dy * dy); - var patternIndex = 0; - var draw = true; - var xStep = 0; - var dashLength = pattern[0]; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - while (distRemaining >= 0.1) { - dashLength = pattern[patternIndex++ % patternLength]; - if (dashLength > distRemaining) { - dashLength = distRemaining; - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - xStep = Math.sqrt(dashLength * dashLength / (1 + slope * slope)); - xStep = dx < 0 ? -xStep : xStep; - x += xStep; - y += slope * xStep; + var NodeBase = (function () { + function NodeBase(options, body, labelModule) { + _classCallCheck(this, NodeBase); - if (draw === true) { - this.lineTo(x, y); - } else { - this.moveTo(x, y); - } + 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.boundingBox = { top: 0, left: 0, right: 0, bottom: 0 }; + } - distRemaining -= dashLength; - draw = !draw; + _createClass(NodeBase, [{ + key: 'setOptions', + value: function setOptions(options) { + this.options = options; } - }; - } + }, { + key: '_distanceToBorder', + value: function _distanceToBorder(angle) { + var borderWidth = 1; + return Math.min(Math.abs(this.width / 2 / Math.cos(angle)), Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth; + } + }, { + key: 'enableShadow', + value: function enableShadow(ctx) { + if (this.options.shadow.enabled === true) { + ctx.shadowColor = 'rgba(0,0,0,0.5)'; + ctx.shadowBlur = this.options.shadow.size; + ctx.shadowOffsetX = this.options.shadow.x; + ctx.shadowOffsetY = this.options.shadow.y; + } + } + }, { + key: 'disableShadow', + value: function disableShadow(ctx) { + if (this.options.shadow.enabled === true) { + ctx.shadowColor = 'rgba(0,0,0,0)'; + ctx.shadowBlur = 0; + ctx.shadowOffsetX = 0; + ctx.shadowOffsetY = 0; + } + } + }]); + + return NodeBase; + })(); + + exports['default'] = NodeBase; + module.exports = exports['default']; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { - /** - * Parse a text source containing data in DOT language into a JSON object. - * The object contains two lists: one with nodes and one with edges. - * - * DOT language reference: http://www.graphviz.org/doc/info/lang.html - * - * DOT language attributes: http://graphviz.org/content/attrs - * - * @param {String} data Text containing a graph in DOT-notation - * @return {Object} graph An object containing two parameters: - * {Object[]} nodes - * {Object[]} edges - */ 'use strict'; - function parseDOT(data) { - dot = data; - return parseGraph(); - } - - // mapping of attributes from DOT (the keys) to vis.js (the values) - var NODE_ATTR_MAPPING = { - 'fontsize': 'font.size', - 'fontcolor': 'font.color', - 'labelfontcolor': 'font.color', - 'fontname': 'font.face', - 'color': ['color.border', 'color.background'], - 'fillcolor': 'color.background', - 'tooltip': 'title', - 'labeltooltip': 'title' - }; - var EDGE_ATTR_MAPPING = Object.create(NODE_ATTR_MAPPING); - EDGE_ATTR_MAPPING.color = 'color.color'; + Object.defineProperty(exports, '__esModule', { + value: true + }); - // token types enumeration - var TOKENTYPE = { - NULL: 0, - DELIMITER: 1, - IDENTIFIER: 2, - UNKNOWN: 3 - }; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // map with all delimiters - var DELIMITERS = { - '{': true, - '}': true, - '[': true, - ']': true, - ';': true, - '=': true, - ',': true, + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - '->': true, - '--': true - }; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - var dot = ''; // current dot file - var index = 0; // current index in dot file - var c = ''; // current token character in expr - var token = ''; // current token - var tokenType = TOKENTYPE.NULL; // type of the token + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - /** - * Get the first character from the dot file. - * The character is stored into the char c. If the end of the dot file is - * reached, the function puts an empty string in c. - */ - function first() { - index = 0; - c = dot.charAt(0); - } + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - /** - * Get the next character from the dot file. - * The character is stored into the char c. If the end of the dot file is - * reached, the function puts an empty string in c. - */ - function next() { - index++; - c = dot.charAt(index); - } + var _utilNodeBase = __webpack_require__(109); - /** - * Preview the next character from the dot file. - * @return {String} cNext - */ - function nextPreview() { - return dot.charAt(index + 1); - } + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - /** - * Test whether given character is alphabetic or numeric - * @param {String} c - * @return {Boolean} isAlphaNumeric - */ - var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/; - function isAlphaNumeric(c) { - return regexAlphaNumeric.test(c); - } + var CircleImageBase = (function (_NodeBase) { + function CircleImageBase(options, body, labelModule) { + _classCallCheck(this, CircleImageBase); - /** - * Merge all options of object b into object b - * @param {Object} a - * @param {Object} b - * @return {Object} a - */ - function merge(a, b) { - if (!a) { - a = {}; + _get(Object.getPrototypeOf(CircleImageBase.prototype), 'constructor', this).call(this, options, body, labelModule); + this.labelOffset = 0; + this.imageLoaded = false; } - if (b) { - for (var name in b) { - if (b.hasOwnProperty(name)) { - a[name] = b[name]; + _inherits(CircleImageBase, _NodeBase); + + _createClass(CircleImageBase, [{ + key: '_resizeImage', + + /** + * This function resizes the image by the options size when the image has not yet loaded. If the image has loaded, we + * force the update of the size again. + * + * @private + */ + value: function _resizeImage() { + var force = false; + if (!this.imageObj.width || !this.imageObj.height) { + // undefined or 0 + this.imageLoaded = false; + } else if (this.imageLoaded === false) { + this.imageLoaded = true; + force = true; + } + + if (!this.width || !this.height || force === true) { + // undefined or 0 + var width, height, ratio; + if (this.imageObj.width && this.imageObj.height) { + // not undefined or 0 + width = 0; + height = 0; + } + if (this.imageObj.width > this.imageObj.height) { + ratio = this.imageObj.width / this.imageObj.height; + width = this.options.size * 2 * ratio || this.imageObj.width; + height = this.options.size * 2 || this.imageObj.height; + } else { + if (this.imageObj.width && this.imageObj.height) { + // not undefined or 0 + ratio = this.imageObj.height / this.imageObj.width; + } else { + ratio = 1; + } + width = this.options.size * 2 || this.imageObj.width; + height = this.options.size * 2 * ratio || this.imageObj.height; + } + this.width = width; + this.height = height; + this.radius = 0.5 * this.width; } } - } - return a; - } + }, { + key: '_drawRawCircle', + value: function _drawRawCircle(ctx, x, y, selected, hover, size) { + var borderWidth = this.options.borderWidth; + var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - /** - * Set a value in an object, where the provided parameter name can be a - * path with nested parameters. For example: - * - * var obj = {a: 2}; - * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}} - * - * @param {Object} obj - * @param {String} path A parameter name or dot-separated parameter path, - * like "color.highlight.border". - * @param {*} value - */ - function setValue(obj, path, value) { - var keys = path.split('.'); - var o = obj; - while (keys.length) { - var key = keys.shift(); - if (keys.length) { - // this isn't the end point - if (!o[key]) { - o[key] = {}; + ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; + + ctx.lineWidth = selected ? selectionLineWidth : borderWidth; + ctx.lineWidth *= this.networkScaleInv; + ctx.lineWidth = Math.min(this.width, ctx.lineWidth); + + ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; + ctx.circle(x, y, size); + + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); + + // disable shadows for other elements. + this.disableShadow(ctx); + + ctx.stroke(); + } + }, { + key: '_drawImageAtPosition', + value: function _drawImageAtPosition(ctx) { + if (this.imageObj.width != 0) { + // draw the image + ctx.globalAlpha = 1; + + // draw shadow if enabled + this.enableShadow(ctx); + ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height); + + // disable shadows for other elements. + this.disableShadow(ctx); } - o = o[key]; - } else { - // this is the end point - o[key] = value; } - } - } + }, { + key: '_drawImageLabel', + value: function _drawImageLabel(ctx, x, y, selected) { + var yLabel; + var offset = 0; - /** - * Add a node to a graph object. If there is already a node with - * the same id, their attributes will be merged. - * @param {Object} graph - * @param {Object} node - */ - function addNode(graph, node) { - var i, len; - var current = null; + if (this.height !== undefined) { + offset = this.height * 0.5; + var labelDimensions = this.labelModule.getTextSize(ctx); + if (labelDimensions.lineCount >= 1) { + offset += labelDimensions.height / 2; + } + } - // find root graph (in case of subgraph) - var graphs = [graph]; // list with all graphs from current graph to root graph - var root = graph; - while (root.parent) { - graphs.push(root.parent); - root = root.parent; - } + yLabel = y + offset; - // find existing node (at root level) by its id - if (root.nodes) { - for (i = 0, len = root.nodes.length; i < len; i++) { - if (node.id === root.nodes[i].id) { - current = root.nodes[i]; - break; + if (this.options.label) { + this.labelOffset = offset; } + this.labelModule.draw(ctx, x, yLabel, selected, 'hanging'); } - } + }]); - if (!current) { - // this is a new node - current = { - id: node.id - }; - if (graph.node) { - // clone default attributes - current.attr = merge(current.attr, graph.node); - } - } + return CircleImageBase; + })(_utilNodeBase2['default']); - // add node to this (sub)graph and all its parent graphs - for (i = graphs.length - 1; i >= 0; i--) { - var g = graphs[i]; + exports['default'] = CircleImageBase; + module.exports = exports['default']; - if (!g.nodes) { - g.nodes = []; - } - if (g.nodes.indexOf(current) === -1) { - g.nodes.push(current); - } - } +/***/ }, +/* 111 */ +/***/ function(module, exports, __webpack_require__) { - // merge attributes - if (node.attr) { - current.attr = merge(current.attr, node.attr); - } - } + 'use strict'; - /** - * Add an edge to a graph object - * @param {Object} graph - * @param {Object} edge - */ - function addEdge(graph, edge) { - if (!graph.edges) { - graph.edges = []; - } - graph.edges.push(edge); - if (graph.edge) { - var attr = merge({}, graph.edge); // clone default attributes - edge.attr = merge(attr, edge.attr); // merge attributes - } - } + Object.defineProperty(exports, '__esModule', { + value: true + }); - /** - * Create an edge to a graph object - * @param {Object} graph - * @param {String | Number | Object} from - * @param {String | Number | Object} to - * @param {String} type - * @param {Object | null} attr - * @return {Object} edge - */ - function createEdge(graph, from, to, type, attr) { - var edge = { - from: from, - to: to, - type: type - }; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - if (graph.edge) { - edge.attr = merge({}, graph.edge); // clone default attributes - } - edge.attr = merge(edge.attr || {}, attr); // merge attributes + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - return edge; - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - /** - * Get next token in the current dot file. - * The token and token type are available as token and tokenType - */ - function getToken() { - tokenType = TOKENTYPE.NULL; - token = ''; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - // skip over whitespaces - while (c === ' ' || c === '\t' || c === '\n' || c === '\r') { - // space, tab, enter - next(); + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + + var _utilNodeBase = __webpack_require__(109); + + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + + var ShapeBase = (function (_NodeBase) { + function ShapeBase(options, body, labelModule) { + _classCallCheck(this, ShapeBase); + + _get(Object.getPrototypeOf(ShapeBase.prototype), 'constructor', this).call(this, options, body, labelModule); } - do { - var isComment = false; + _inherits(ShapeBase, _NodeBase); - // skip comment - if (c === '#') { - // find the previous non-space character - var i = index - 1; - while (dot.charAt(i) === ' ' || dot.charAt(i) === '\t') { - i--; - } - if (dot.charAt(i) === '\n' || dot.charAt(i) === '') { - // the # is at the start of a line, this is indeed a line comment - while (c != '' && c != '\n') { - next(); - } - isComment = true; + _createClass(ShapeBase, [{ + key: '_resizeShape', + value: function _resizeShape() { + if (this.width === undefined) { + var size = 2 * this.options.size; + this.width = size; + this.height = size; + this.radius = 0.5 * this.width; } } - if (c === '/' && nextPreview() === '/') { - // skip line comment - while (c != '' && c != '\n') { - next(); + }, { + key: '_drawShape', + value: function _drawShape(ctx, shape, sizeMultiplier, x, y, selected, hover) { + this._resizeShape(); + + this.left = x - this.width / 2; + this.top = y - this.height / 2; + + var borderWidth = this.options.borderWidth; + var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; + + ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; + ctx.lineWidth = selected ? selectionLineWidth : borderWidth; + ctx.lineWidth /= this.body.view.scale; + ctx.lineWidth = Math.min(this.width, ctx.lineWidth); + ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; + ctx[shape](x, y, this.options.size); + + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); + + // disable shadows for other elements. + this.disableShadow(ctx); + + ctx.stroke(); + + if (this.options.label !== undefined) { + var yLabel = y + 0.5 * this.height + 3; // the + 3 is to offset it a bit below the node. + this.labelModule.draw(ctx, x, yLabel, selected, 'hanging'); } - isComment = true; + + this.updateBoundingBox(x, y); } - if (c === '/' && nextPreview() === '*') { - // skip block comment - while (c != '') { - if (c === '*' && nextPreview() === '/') { - // end of block comment found. skip these last two characters - next(); - next(); - break; - } else { - next(); - } + }, { + 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.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 + 3); } - isComment = true; } + }]); - // skip over whitespaces - while (c === ' ' || c === '\t' || c === '\n' || c === '\r') { - // space, tab, enter - next(); - } - } while (isComment); + return ShapeBase; + })(_utilNodeBase2['default']); - // check for end of dot file - if (c === '') { - // token is still empty - tokenType = TOKENTYPE.DELIMITER; - return; - } + exports['default'] = ShapeBase; + module.exports = exports['default']; - // check for delimiters consisting of 2 characters - var c2 = c + nextPreview(); - if (DELIMITERS[c2]) { - tokenType = TOKENTYPE.DELIMITER; - token = c2; - next(); - next(); - return; - } +/***/ }, +/* 112 */ +/***/ function(module, exports, __webpack_require__) { - // check for delimiters consisting of 1 character - if (DELIMITERS[c]) { - tokenType = TOKENTYPE.DELIMITER; - token = c; - next(); - return; - } + 'use strict'; - // check for an identifier (number or string) - // TODO: more precise parsing of numbers/strings (and the port separator ':') - if (isAlphaNumeric(c) || c === '-') { - token += c; - next(); + Object.defineProperty(exports, '__esModule', { + value: true + }); - while (isAlphaNumeric(c)) { - token += c; - next(); - } - if (token === 'false') { - token = false; // convert to boolean - } else if (token === 'true') { - token = true; // convert to boolean - } else if (!isNaN(Number(token))) { - token = Number(token); // convert to number - } - tokenType = TOKENTYPE.IDENTIFIER; - return; - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // check for a string enclosed by double quotes - if (c === '"') { - next(); - while (c != '' && (c != '"' || c === '"' && nextPreview() === '"')) { - token += c; - if (c === '"') { - // skip the escape character - next(); - } - next(); - } - if (c != '"') { - throw newSyntaxError('End of string " expected'); - } - next(); - tokenType = TOKENTYPE.IDENTIFIER; - return; - } + var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - // something unknown is found, wrong characters, a syntax error - tokenType = TOKENTYPE.UNKNOWN; - while (c != '') { - token += c; - next(); - } - throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"'); - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - /** - * Parse a graph. - * @returns {Object} graph - */ - function parseGraph() { - var graph = {}; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - first(); - getToken(); + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - // optional strict keyword - if (token === 'strict') { - graph.strict = true; - getToken(); - } + var _EdgeBase2 = __webpack_require__(113); - // graph or digraph keyword - if (token === 'graph' || token === 'digraph') { - graph.type = token; - getToken(); - } + var _EdgeBase3 = _interopRequireDefault(_EdgeBase2); - // optional graph id - if (tokenType === TOKENTYPE.IDENTIFIER) { - graph.id = token; - getToken(); - } + var BezierEdgeBase = (function (_EdgeBase) { + function BezierEdgeBase(options, body, labelModule) { + _classCallCheck(this, BezierEdgeBase); - // open angle bracket - if (token != '{') { - throw newSyntaxError('Angle bracket { expected'); + _get(Object.getPrototypeOf(BezierEdgeBase.prototype), 'constructor', this).call(this, options, body, labelModule); } - getToken(); - // statements - parseStatements(graph); + _inherits(BezierEdgeBase, _EdgeBase); - // close angle bracket - if (token != '}') { - throw newSyntaxError('Angle bracket } expected'); - } - getToken(); + _createClass(BezierEdgeBase, [{ + key: '_findBorderPositionBezier', - // end of file - if (token !== '') { - throw newSyntaxError('End of file expected'); - } - getToken(); + /** + * This function uses binary search to look for the point where the bezier curve crosses the border of the node. + * + * @param nearNode + * @param ctx + * @param viaNode + * @param nearNode + * @param ctx + * @param viaNode + * @param nearNode + * @param ctx + * @param viaNode + */ + value: function _findBorderPositionBezier(nearNode, ctx) { + var viaNode = arguments[2] === undefined ? this._getViaCoordinates() : arguments[2]; - // remove temporary default options - delete graph.node; - delete graph.edge; - delete graph.graph; + 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; + } - return graph; - } + while (low <= high && iteration < maxIterations) { + var middle = (low + high) * 0.5; - /** - * Parse a list with statements. - * @param {Object} graph - */ - function parseStatements(graph) { - while (token !== '' && token != '}') { - parseStatement(graph); - if (token === ';') { - getToken(); + 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; } - } - } + }, { + key: '_getDistanceToBezierEdge', - /** - * Parse a single statement. Can be a an attribute statement, node - * statement, a series of node statements and edge statements, or a - * parameter. - * @param {Object} graph - */ - function parseStatement(graph) { - // parse subgraph - var subgraph = parseSubgraph(graph); - if (subgraph) { - // edge statements - parseEdge(graph, subgraph); + /** + * 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 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {number} x3 + * @param {number} y3 + * @private + */ + value: function _getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via) { + // x3,y3 is the point + var xVia = undefined, + yVia = undefined; + xVia = via.x; + yVia = via.y; + var minDistance = 1000000000; + var distance = undefined; + var i = undefined, + t = undefined, + x = undefined, + y = undefined; + 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) * xVia + Math.pow(t, 2) * x2; + y = Math.pow(1 - t, 2) * y1 + 2 * t * (1 - t) * yVia + 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; - } + return minDistance; + } + }]); + + return BezierEdgeBase; + })(_EdgeBase3['default']); + + exports['default'] = BezierEdgeBase; + module.exports = exports['default']; + +/***/ }, +/* 113 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); - // parse an attribute statement - var attr = parseAttributeStatement(graph); - if (attr) { - return; - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // parse node - if (tokenType != TOKENTYPE.IDENTIFIER) { - throw newSyntaxError('Identifier expected'); - } - var id = token; // id can be a string or a number - getToken(); + function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _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; } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } } - if (token === '=') { - // id statement - getToken(); - if (tokenType != TOKENTYPE.IDENTIFIER) { - throw newSyntaxError('Identifier expected'); - } - graph[id] = token; - getToken(); - // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] " - } else { - parseNodeStatement(graph, id); - } - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - /** - * Parse a subgraph - * @param {Object} graph parent graph object - * @return {Object | null} subgraph - */ - function parseSubgraph(graph) { - var subgraph = null; + var util = __webpack_require__(2); - // optional subgraph keyword - if (token === 'subgraph') { - subgraph = {}; - subgraph.type = 'subgraph'; - getToken(); + var EdgeBase = (function () { + function EdgeBase(options, body, labelModule) { + _classCallCheck(this, EdgeBase); - // optional graph id - if (tokenType === TOKENTYPE.IDENTIFIER) { - subgraph.id = token; - getToken(); - } + this.body = body; + this.labelModule = labelModule; + this.setOptions(options); + this.colorDirty = true; + this.color = {}; + this.selectionWidth = 2; + this.hoverWidth = 1.5; } - // open angle bracket - if (token === '{') { - getToken(); - - if (!subgraph) { - subgraph = {}; + _createClass(EdgeBase, [{ + key: 'connect', + value: function connect() {} + }, { + key: 'cleanup', + value: function cleanup() { + return false; } - subgraph.parent = graph; - subgraph.node = graph.node; - subgraph.edge = graph.edge; - subgraph.graph = graph.graph; + }, { + key: 'setOptions', + value: function setOptions(options) { + this.options = options; + this.from = this.body.nodes[this.options.from]; + this.to = this.body.nodes[this.options.to]; + this.id = this.options.id; + } + }, { + key: 'togglePhysics', - // statements - parseStatements(subgraph); + /** + * overloadable if the shape has to toggle the via node to disabled + * @param status + */ + value: function togglePhysics(status) {} + }, { + key: 'drawLine', - // close angle bracket - if (token != '}') { - throw newSyntaxError('Angle bracket } expected'); + /** + * Redraw a edge as a line + * Draw this edge in the given canvas + * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); + * @param {CanvasRenderingContext2D} ctx + * @private + */ + value: function drawLine(ctx, selected, hover) { + // set style + ctx.strokeStyle = this.getColor(ctx, selected, hover); + ctx.lineWidth = this.getLineWidth(selected, hover); + var via = undefined; + if (this.options.dashes !== false) { + via = this._drawDashedLine(ctx); + } else { + via = this._drawLine(ctx); + } + return via; } - getToken(); + }, { + key: '_drawLine', + value: function _drawLine(ctx) { + var via = undefined; + if (this.from != this.to) { + // draw line + via = this._line(ctx); + } else { + var _getCircleData = this._getCircleData(ctx); - // remove temporary default options - delete subgraph.node; - delete subgraph.edge; - delete subgraph.graph; - delete subgraph.parent; + var _getCircleData2 = _slicedToArray(_getCircleData, 3); - // register at the parent graph - if (!graph.subgraphs) { - graph.subgraphs = []; + var x = _getCircleData2[0]; + var y = _getCircleData2[1]; + var radius = _getCircleData2[2]; + + this._circle(ctx, x, y, radius); + } + return via; } - graph.subgraphs.push(subgraph); - } + }, { + key: '_drawDashedLine', + value: function _drawDashedLine(ctx) { + var via = undefined; + ctx.lineCap = 'round'; + var pattern = [5, 5]; + if (Array.isArray(this.options.dashes) === true) { + pattern = this.options.dashes; + } - return subgraph; - } + // only firefox and chrome support this method, else we use the legacy one. + if (ctx.setLineDash !== undefined) { + ctx.save(); - /** - * parse an attribute statement like "node [shape=circle fontSize=16]". - * Available keywords are 'node', 'edge', 'graph'. - * The previous list with default attributes will be replaced - * @param {Object} graph - * @returns {String | null} keyword Returns the name of the parsed attribute - * (node, edge, graph), or null if nothing - * is parsed. - */ - function parseAttributeStatement(graph) { - // attribute statements - if (token === 'node') { - getToken(); + // set dash settings for chrome or firefox + ctx.setLineDash(pattern); + ctx.lineDashOffset = 0; - // node attributes - graph.node = parseAttributeList(); - return 'node'; - } else if (token === 'edge') { - getToken(); + // draw the line + if (this.from != this.to) { + // draw line + via = this._line(ctx); + } else { + var _getCircleData3 = this._getCircleData(ctx); - // edge attributes - graph.edge = parseAttributeList(); - return 'edge'; - } else if (token === 'graph') { - getToken(); + var _getCircleData32 = _slicedToArray(_getCircleData3, 3); - // graph attributes - graph.graph = parseAttributeList(); - return 'graph'; - } + var x = _getCircleData32[0]; + var y = _getCircleData32[1]; + var radius = _getCircleData32[2]; - return null; - } + this._circle(ctx, x, y, radius); + } - /** - * parse a node statement - * @param {Object} graph - * @param {String | Number} id - */ - function parseNodeStatement(graph, id) { - // node statement - var node = { - id: id - }; - var attr = parseAttributeList(); - if (attr) { - node.attr = attr; - } - addNode(graph, node); + // restore the dash settings. + ctx.setLineDash([0]); + ctx.lineDashOffset = 0; + ctx.restore(); + } else { + // unsupporting smooth lines - // edge statements - parseEdge(graph, id); - } + if (this.from != this.to) { + // draw line + ctx.dashedLine(this.from.x, this.from.y, this.to.x, this.to.y, pattern); + } else { + var _getCircleData4 = this._getCircleData(ctx); - /** - * Parse an edge or a series of edges - * @param {Object} graph - * @param {String | Number} from Id of the from node - */ - function parseEdge(graph, from) { - while (token === '->' || token === '--') { - var to; - var type = token; - getToken(); + var _getCircleData42 = _slicedToArray(_getCircleData4, 3); - var subgraph = parseSubgraph(graph); - if (subgraph) { - to = subgraph; - } else { - if (tokenType != TOKENTYPE.IDENTIFIER) { - throw newSyntaxError('Identifier or subgraph expected'); - } - to = token; - addNode(graph, { - id: to - }); - getToken(); - } + var x = _getCircleData42[0]; + var y = _getCircleData42[1]; + var radius = _getCircleData42[2]; - // parse edge attributes - var attr = parseAttributeList(); + this._circle(ctx, x, y, radius); + } + // draw shadow if enabled + this.enableShadow(ctx); - // create edge - var edge = createEdge(graph, from, to, type, attr); - addEdge(graph, edge); + ctx.stroke(); - from = to; - } - } + // disable shadows for other elements. + this.disableShadow(ctx); + } + return via; + } + }, { + key: 'findBorderPosition', + value: function findBorderPosition(nearNode, ctx, options) { + if (this.from != this.to) { + return this._findBorderPosition(nearNode, ctx, options); + } else { + return this._findBorderPositionCircle(nearNode, ctx, options); + } + } + }, { + key: 'findBorderPositions', + value: function findBorderPositions(ctx) { + var from = {}; + var to = {}; + if (this.from != this.to) { + from = this._findBorderPosition(this.from, ctx); + to = this._findBorderPosition(this.to, ctx); + } else { + var _getCircleData5 = this._getCircleData(ctx); - /** - * Parse a set with attributes, - * for example [label="1.000", shape=solid] - * @return {Object | null} attr - */ - function parseAttributeList() { - var attr = null; + var _getCircleData52 = _slicedToArray(_getCircleData5, 3); - while (token === '[') { - getToken(); - attr = {}; - while (token !== '' && token != ']') { - if (tokenType != TOKENTYPE.IDENTIFIER) { - throw newSyntaxError('Attribute name expected'); - } - var name = token; + var x = _getCircleData52[0]; + var y = _getCircleData52[1]; + var radius = _getCircleData52[2]; - getToken(); - if (token != '=') { - throw newSyntaxError('Equal sign = expected'); + from = this._findBorderPositionCircle(this.from, ctx, { x: x, y: y, low: 0.25, high: 0.6, direction: -1 }); + to = this._findBorderPositionCircle(this.from, ctx, { x: x, y: y, low: 0.6, high: 0.8, direction: 1 }); } - getToken(); + return { from: from, to: to }; + } + }, { + key: '_getCircleData', + value: function _getCircleData(ctx) { + var x = undefined, + y = undefined; + var node = this.from; + var radius = this.options.selfReferenceSize; - if (tokenType != TOKENTYPE.IDENTIFIER) { - throw newSyntaxError('Attribute value expected'); + if (ctx !== undefined) { + if (node.shape.width === undefined) { + node.shape.resize(ctx); + } } - var value = token; - setValue(attr, name, value); // name can be a path - getToken(); - if (token == ',') { - getToken(); + // get circle coordinates + if (node.shape.width > node.shape.height) { + x = node.x + node.shape.width * 0.5; + y = node.y - radius; + } else { + x = node.x + radius; + y = node.y - node.shape.height * 0.5; } + return [x, y, radius]; } + }, { + key: '_pointOnCircle', - if (token != ']') { - throw newSyntaxError('Bracket ] expected'); + /** + * 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 + */ + 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) + }; } - getToken(); - } + }, { + key: '_findBorderPositionCircle', - return attr; - } + /** + * This function uses binary search to look for the point where the circle crosses the border of the node. + * @param node + * @param ctx + * @param options + * @returns {*} + * @private + */ + value: function _findBorderPositionCircle(node, ctx, options) { + var x = options.x; + var y = options.y; + var low = options.low; + var high = options.high; + var direction = options.direction; - /** - * Create a syntax error with extra information on current token and index. - * @param {String} message - * @returns {SyntaxError} err - */ - function newSyntaxError(message) { - return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')'); - } + var maxIterations = 10; + var iteration = 0; + var radius = this.options.selfReferenceSize; + var pos = undefined, + angle = undefined, + distanceToBorder = undefined, + distanceToPoint = undefined, + difference = undefined; + var threshold = 0.05; + var middle = (low + high) * 0.5; - /** - * Chop off text after a maximum length - * @param {String} text - * @param {Number} maxLength - * @returns {String} - */ - function chop(text, maxLength) { - return text.length <= maxLength ? text : text.substr(0, 27) + '...'; - } + while (low <= high && iteration < maxIterations) { + middle = (low + high) * 0.5; - /** - * Execute a function fn for each pair of elements in two arrays - * @param {Array | *} array1 - * @param {Array | *} array2 - * @param {function} fn - */ - function forEach2(array1, array2, fn) { - if (Array.isArray(array1)) { - array1.forEach(function (elem1) { - if (Array.isArray(array2)) { - array2.forEach(function (elem2) { - fn(elem1, elem2); - }); - } else { - fn(elem1, array2); + pos = this._pointOnCircle(x, y, radius, middle); + 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 (direction > 0) { + low = middle; + } else { + high = middle; + } + } else { + if (direction > 0) { + high = middle; + } else { + low = middle; + } + } + iteration++; } - }); - } else { - if (Array.isArray(array2)) { - array2.forEach(function (elem2) { - fn(array1, elem2); - }); - } else { - fn(array1, array2); - } - } - } + pos.t = middle; - /** - * Set a nested property on an object - * When nested objects are missing, they will be created. - * For example setProp({}, 'font.color', 'red') will return {font: {color: 'red'}} - * @param {Object} object - * @param {string} path A dot separated string like 'font.color' - * @param {*} value Value for the property - * @return {Object} Returns the original object, allows for chaining. - */ - function setProp(object, path, value) { - var names = path.split('.'); - var prop = names.pop(); + return pos; + } + }, { + key: 'getLineWidth', - // traverse over the nested objects - var obj = object; - for (var i = 0; i < names.length; i++) { - var name = names[i]; - if (!(name in obj)) { - obj[name] = {}; + /** + * Get the line width of the edge. Depends on width and whether one of the + * connected nodes is selected. + * @return {Number} width + * @private + */ + value: function getLineWidth(selected, hover) { + if (selected === true) { + return Math.max(this.selectionWidth, 0.3 / this.body.view.scale); + } else { + if (hover === true) { + return Math.max(this.hoverWidth, 0.3 / this.body.view.scale); + } else { + return Math.max(this.options.width, 0.3 / this.body.view.scale); + } + } } - obj = obj[name]; - } + }, { + key: 'getColor', + value: function getColor(ctx, selected, hover) { + var colorOptions = this.options.color; + if (colorOptions.inherit !== false) { + // when this is a loop edge, just use the 'from' method + if (colorOptions.inherit === 'both' && this.from.id !== this.to.id) { + var grd = ctx.createLinearGradient(this.from.x, this.from.y, this.to.x, this.to.y); + var fromColor = undefined, + toColor = undefined; + fromColor = this.from.options.color.highlight.border; + toColor = this.to.options.color.highlight.border; - // set the property value - obj[prop] = value; + if (this.from.selected === false && this.to.selected === false) { + fromColor = util.overrideOpacity(this.from.options.color.border, this.options.color.opacity); + toColor = util.overrideOpacity(this.to.options.color.border, this.options.color.opacity); + } else if (this.from.selected === true && this.to.selected === false) { + toColor = this.to.options.color.border; + } else if (this.from.selected === false && this.to.selected === true) { + fromColor = this.from.options.color.border; + } + grd.addColorStop(0, fromColor); + grd.addColorStop(1, toColor); - return object; - } + // -------------------- this returns -------------------- // + return grd; + } - /** - * Convert an object with DOT attributes to their vis.js equivalents. - * @param {Object} attr Object with DOT attributes - * @param {Object} mapping - * @return {Object} Returns an object with vis.js attributes - */ - function convertAttr(attr, mapping) { - var converted = {}; + if (this.colorDirty === true) { + if (colorOptions.inherit === 'to') { + this.color.highlight = this.to.options.color.highlight.border; + this.color.hover = this.to.options.color.hover.border; + this.color.color = util.overrideOpacity(this.to.options.color.border, colorOptions.opacity); + } else { + // (this.options.color.inherit.source === "from") { + this.color.highlight = this.from.options.color.highlight.border; + this.color.hover = this.from.options.color.hover.border; + this.color.color = util.overrideOpacity(this.from.options.color.border, colorOptions.opacity); + } + } + } else if (this.colorDirty === true) { + this.color.highlight = colorOptions.highlight; + this.color.hover = colorOptions.hover; + this.color.color = util.overrideOpacity(colorOptions.color, colorOptions.opacity); + } - for (var prop in attr) { - if (attr.hasOwnProperty(prop)) { - var visProp = mapping[prop]; - if (Array.isArray(visProp)) { - visProp.forEach(function (visPropI) { - setProp(converted, visPropI, attr[prop]); - }); - } else if (typeof visProp === 'string') { - setProp(converted, visProp, attr[prop]); + // if color inherit is on and gradients are used, the function has already returned by now. + this.colorDirty = false; + + if (selected === true) { + return this.color.highlight; + } else if (hover === true) { + return this.color.hover; } else { - setProp(converted, prop, attr[prop]); + return this.color.color; } } - } + }, { + key: '_circle', - return converted; - } + /** + * Draw a line from a node to itself, a circle + * @param {CanvasRenderingContext2D} ctx + * @param {Number} x + * @param {Number} y + * @param {Number} radius + * @private + */ + value: function _circle(ctx, x, y, radius) { + // draw shadow if enabled + this.enableShadow(ctx); - /** - * Convert a string containing a graph in DOT language into a map containing - * with nodes and edges in the format of graph. - * @param {String} data Text containing a graph in DOT-notation - * @return {Object} graphData - */ - function DOTToGraph(data) { - // parse the DOT file - var dotData = parseDOT(data); - var graphData = { - nodes: [], - edges: [], - options: {} - }; + // draw a circle + ctx.beginPath(); + ctx.arc(x, y, radius, 0, 2 * Math.PI, false); + ctx.stroke(); - // copy the nodes - if (dotData.nodes) { - dotData.nodes.forEach(function (dotNode) { - var graphNode = { - id: dotNode.id, - label: String(dotNode.label || dotNode.id) - }; - merge(graphNode, convertAttr(dotNode.attr, NODE_ATTR_MAPPING)); - if (graphNode.image) { - graphNode.shape = 'image'; - } - graphData.nodes.push(graphNode); - }); - } + // disable shadows for other elements. + this.disableShadow(ctx); + } + }, { + key: 'getDistanceToEdge', - // copy the edges - if (dotData.edges) { /** - * Convert an edge in DOT format to an edge with VisGraph format - * @param {Object} dotEdge - * @returns {Object} graphEdge + * 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 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {number} x3 + * @param {number} y3 + * @private */ - var convertEdge = function convertEdge(dotEdge) { - var graphEdge = { - from: dotEdge.from, - to: dotEdge.to - }; - merge(graphEdge, convertAttr(dotEdge.attr, EDGE_ATTR_MAPPING)); - graphEdge.arrows = dotEdge.type === '->' ? 'to' : undefined; - - return graphEdge; - }; - - dotData.edges.forEach(function (dotEdge) { - var from, to; - if (dotEdge.from instanceof Object) { - from = dotEdge.from.nodes; + value: function getDistanceToEdge(x1, y1, x2, y2, x3, y3, via) { + // x3,y3 is the point + var returnValue = 0; + if (this.from != this.to) { + returnValue = this._getDistanceToEdge(x1, y1, x2, y2, x3, y3, via); } else { - from = { - id: dotEdge.from - }; - } + var _getCircleData6 = this._getCircleData(); - // TODO: support of solid/dotted/dashed edges (attr = 'style') - // TODO: support for attributes 'dir' and 'arrowhead' (edge arrows) + var _getCircleData62 = _slicedToArray(_getCircleData6, 3); - if (dotEdge.to instanceof Object) { - to = dotEdge.to.nodes; - } else { - to = { - id: dotEdge.to - }; - } + var x = _getCircleData62[0]; + var y = _getCircleData62[1]; + var radius = _getCircleData62[2]; - if (dotEdge.from instanceof Object && dotEdge.from.edges) { - dotEdge.from.edges.forEach(function (subEdge) { - var graphEdge = convertEdge(subEdge); - graphData.edges.push(graphEdge); - }); + var dx = x - x3; + var dy = y - y3; + returnValue = Math.abs(Math.sqrt(dx * dx + dy * dy) - radius); } - forEach2(from, to, function (from, to) { - var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr); - var graphEdge = convertEdge(subEdge); - graphData.edges.push(graphEdge); - }); - - if (dotEdge.to instanceof Object && dotEdge.to.edges) { - dotEdge.to.edges.forEach(function (subEdge) { - var graphEdge = convertEdge(subEdge); - graphData.edges.push(graphEdge); - }); + if (this.labelModule.size.left < x3 && this.labelModule.size.left + this.labelModule.size.width > x3 && this.labelModule.size.top < y3 && this.labelModule.size.top + this.labelModule.size.height > y3) { + return 0; + } else { + return returnValue; } - }); - } - - // copy the options - if (dotData.attr) { - graphData.options = dotData.attr; - } - - return graphData; - } - - // exports - exports.parseDOT = parseDOT; - exports.DOTToGraph = DOTToGraph; + } + }, { + key: '_getDistanceToLine', + value: function _getDistanceToLine(x1, y1, x2, y2, x3, y3) { + var px = x2 - x1; + var py = y2 - y1; + var something = px * px + py * py; + var u = ((x3 - x1) * px + (y3 - y1) * py) / something; -/***/ }, -/* 111 */ -/***/ function(module, exports, __webpack_require__) { + if (u > 1) { + u = 1; + } else if (u < 0) { + u = 0; + } - 'use strict'; + var x = x1 + u * px; + var y = y1 + u * py; + var dx = x - x3; + var dy = y - y3; - function parseGephi(gephiJSON, optionsObj) { - var edges = []; - var nodes = []; - var options = { - edges: { - inheritColor: false - }, - nodes: { - fixed: false, - parseColor: false - } - }; + //# Note: If the actual distance does not matter, + //# if you only want to compare what this function + //# returns to other results of this function, you + //# can just return the squared distance instead + //# (i.e. remove the sqrt) to gain a little performance - if (optionsObj !== undefined) { - if (optionsObj.fixed !== undefined) { - options.nodes.fixed = optionsObj.fixed; - } - if (optionsObj.parseColor !== undefined) { - options.nodes.parseColor = optionsObj.parseColor; - } - if (optionsObj.inheritColor !== undefined) { - options.edges.inheritColor = optionsObj.inheritColor; + return Math.sqrt(dx * dx + dy * dy); } - } + }, { + key: 'drawArrowHead', - var gEdges = gephiJSON.edges; - var gNodes = gephiJSON.nodes; - for (var i = 0; i < gEdges.length; i++) { - var edge = {}; - var gEdge = gEdges[i]; - edge['id'] = gEdge.id; - edge['from'] = gEdge.source; - edge['to'] = gEdge.target; - edge['attributes'] = gEdge.attributes; - // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined; - // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size; - if (gEdge.color && options.inheritColor === false) { - edge['color'] = gEdge.color; - } - edges.push(edge); - } + /** + * + * @param ctx + * @param position + * @param viaNode + */ + value: function drawArrowHead(ctx, position, viaNode, selected, hover) { + // set style + ctx.strokeStyle = this.getColor(ctx, selected, hover); + ctx.fillStyle = ctx.strokeStyle; + ctx.lineWidth = this.getLineWidth(selected, hover); - for (var i = 0; i < gNodes.length; i++) { - var node = {}; - var gNode = gNodes[i]; - node['id'] = gNode.id; - node['attributes'] = gNode.attributes; - node['title'] = gNode.title; - node['x'] = gNode.x; - node['y'] = gNode.y; - node['label'] = gNode.label; - if (options.nodes.parseColor === true) { - node['color'] = gNode.color; - } else { - node['color'] = gNode.color !== undefined ? { background: gNode.color, border: gNode.color, highlight: { background: gNode.color, border: gNode.color }, hover: { background: gNode.color, border: gNode.color } } : undefined; - } - node['size'] = gNode.size; - node['fixed'] = options.nodes.fixed && gNode.x !== undefined && gNode.y !== undefined; - nodes.push(node); - } + // set lets + var angle = undefined; + var length = undefined; + var arrowPos = undefined; + var node1 = undefined; + var node2 = undefined; + var guideOffset = undefined; + var scaleFactor = undefined; - return { nodes: nodes, edges: edges }; - } + if (position === 'from') { + node1 = this.from; + node2 = this.to; + guideOffset = 0.1; + scaleFactor = this.options.arrows.from.scaleFactor; + } else if (position === 'to') { + node1 = this.to; + node2 = this.from; + guideOffset = -0.1; + scaleFactor = this.options.arrows.to.scaleFactor; + } else { + node1 = this.to; + node2 = this.from; + scaleFactor = this.options.arrows.middle.scaleFactor; + } - exports.parseGephi = parseGephi; + // if not connected to itself + if (node1 != node2) { + if (position !== 'middle') { + // draw arrow head + if (this.options.smooth.enabled === true) { + arrowPos = this.findBorderPosition(node1, ctx, { via: viaNode }); + var guidePos = this.getPoint(Math.max(0, Math.min(1, arrowPos.t + guideOffset)), viaNode); + angle = Math.atan2(arrowPos.y - guidePos.y, arrowPos.x - guidePos.x); + } else { + angle = Math.atan2(node1.y - node2.y, node1.x - node2.x); + arrowPos = this.findBorderPosition(node1, ctx); + } + } else { + angle = Math.atan2(node1.y - node2.y, node1.x - node2.x); + arrowPos = this.getPoint(0.6, viaNode); // this is 0.6 to account for the size of the arrow. + } + // draw arrow at the end of the line + length = (10 + 5 * this.options.width) * scaleFactor; + ctx.arrow(arrowPos.x, arrowPos.y, angle, length); -/***/ }, -/* 112 */ -/***/ function(module, exports, __webpack_require__) { + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); - /** - * @class Images - * This class loads images and keeps them stored. - */ - "use strict"; + // disable shadows for other elements. + this.disableShadow(ctx); + ctx.stroke(); + } else { + // draw circle + var _angle = undefined, + point = undefined; - function Images(callback) { - this.images = {}; - this.imageBroken = {}; - this.callback = callback; - } + var _getCircleData7 = this._getCircleData(ctx); - /** - * - * @param {string} url Url of the image - * @param {string} url Url of an image to use if the url image is not found - * @return {Image} img The image object - */ - Images.prototype.load = function (url, brokenUrl, id) { - var img = this.images[url]; // make a pointer - if (img === undefined) { - // create the image - var me = this; - img = new Image(); - img.onload = function () { - // IE11 fix -- thanks dponch! - if (this.width === 0) { - document.body.appendChild(this); - this.width = this.offsetWidth; - this.height = this.offsetHeight; - document.body.removeChild(this); - } + var _getCircleData72 = _slicedToArray(_getCircleData7, 3); - if (me.callback) { - me.images[url] = img; - me.callback(this); - } - }; + var x = _getCircleData72[0]; + var y = _getCircleData72[1]; + var radius = _getCircleData72[2]; - img.onerror = function () { - if (brokenUrl === undefined) { - console.error("Could not load image:", url); - delete this.src; - if (me.callback) { - me.callback(this); - } - } else { - if (me.imageBroken[id] && me.imageBroken[id][url] === true) { - console.error("Could not load brokenImage:", brokenUrl); - delete this.src; - if (me.callback) { - me.callback(this); - } + if (position === 'from') { + point = this.findBorderPosition(this.from, ctx, { x: x, y: y, low: 0.25, high: 0.6, direction: -1 }); + _angle = point.t * -2 * Math.PI + 1.5 * Math.PI + 0.1 * Math.PI; + } else if (position === 'to') { + point = this.findBorderPosition(this.from, ctx, { x: x, y: y, low: 0.6, high: 1, direction: 1 }); + _angle = point.t * -2 * Math.PI + 1.5 * Math.PI - 1.1 * Math.PI; } else { - console.error("Could not load image:", url); - this.src = brokenUrl; - if (me.imageBroken[id] === undefined) { - me.imageBroken[id] = {}; - } - me.imageBroken[id][url] = true; + point = this._pointOnCircle(x, y, radius, 0.175); + _angle = 3.9269908169872414; // === 0.175 * -2 * Math.PI + 1.5 * Math.PI + 0.1 * Math.PI; } - } - }; - - img.src = url; - } - return img; - }; - - module.exports = Images; + // draw the arrowhead + var _length = (10 + 5 * this.options.width) * scaleFactor; + ctx.arrow(point.x, point.y, _angle, _length); -/***/ }, -/* 113 */ -/***/ function(module, exports, __webpack_require__) { + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); - // English - 'use strict'; + // disable shadows for other elements. + this.disableShadow(ctx); + ctx.stroke(); + } + } + }, { + key: 'enableShadow', + value: function enableShadow(ctx) { + if (this.options.shadow.enabled === true) { + ctx.shadowColor = 'rgba(0,0,0,0.5)'; + ctx.shadowBlur = this.options.shadow.size; + ctx.shadowOffsetX = this.options.shadow.x; + ctx.shadowOffsetY = this.options.shadow.y; + } + } + }, { + key: 'disableShadow', + value: function disableShadow(ctx) { + if (this.options.shadow.enabled === true) { + ctx.shadowColor = 'rgba(0,0,0,0)'; + ctx.shadowBlur = 0; + ctx.shadowOffsetX = 0; + ctx.shadowOffsetY = 0; + } + } + }]); - exports['en'] = { - edit: 'Edit', - del: 'Delete selected', - back: 'Back', - addNode: 'Add Node', - addEdge: 'Add Edge', - editNode: 'Edit Node', - editEdge: 'Edit Edge', - addDescription: 'Click in an empty space to place a new node.', - edgeDescription: 'Click on a node and drag the edge to another node to connect them.', - editEdgeDescription: 'Click on the control points and drag them to a node to connect to it.', - createEdgeError: 'Cannot link edges to a cluster.', - deleteClusterError: 'Clusters cannot be deleted.', - editClusterError: 'Clusters cannot be edited.' - }; - exports['en_EN'] = exports['en']; - exports['en_US'] = exports['en']; + return EdgeBase; + })(); - // Dutch - exports['nl'] = { - edit: 'Wijzigen', - del: 'Selectie verwijderen', - back: 'Terug', - addNode: 'Node toevoegen', - addEdge: 'Link toevoegen', - editNode: 'Node wijzigen', - editEdge: 'Link wijzigen', - addDescription: 'Klik op een leeg gebied om een nieuwe node te maken.', - edgeDescription: 'Klik op een node en sleep de link naar een andere node om ze te verbinden.', - editEdgeDescription: 'Klik op de verbindingspunten en sleep ze naar een node om daarmee te verbinden.', - createEdgeError: 'Kan geen link maken naar een cluster.', - deleteClusterError: 'Clusters kunnen niet worden verwijderd.', - editClusterError: 'Clusters kunnen niet worden aangepast.' - }; - exports['nl_NL'] = exports['nl']; - exports['nl_BE'] = exports['nl']; + exports['default'] = EdgeBase; + module.exports = exports['default']; /***/ } /******/ ]) diff --git a/examples/graph2d/16_bothAxis_titles.html b/examples/graph2d/16_bothAxisTitles.html similarity index 100% rename from examples/graph2d/16_bothAxis_titles.html rename to examples/graph2d/16_bothAxisTitles.html diff --git a/examples/network/basic_usage.html b/examples/network/basicUsage.html similarity index 100% rename from examples/network/basic_usage.html rename to examples/network/basicUsage.html diff --git a/examples/network/data/importing_from_gephi.html b/examples/network/data/importingFromGephi.html similarity index 100% rename from examples/network/data/importing_from_gephi.html rename to examples/network/data/importingFromGephi.html diff --git a/examples/network/data/scaling_custom.html b/examples/network/data/scalingCustom.html similarity index 100% rename from examples/network/data/scaling_custom.html rename to examples/network/data/scalingCustom.html diff --git a/examples/network/data/scaling_nodes_edges.html b/examples/network/data/scalingNodesEdges.html similarity index 100% rename from examples/network/data/scaling_nodes_edges.html rename to examples/network/data/scalingNodesEdges.html diff --git a/examples/network/data/scaling_nodes_edges_labels.html b/examples/network/data/scalingNodesEdgesLabels.html similarity index 100% rename from examples/network/data/scaling_nodes_edges_labels.html rename to examples/network/data/scalingNodesEdgesLabels.html diff --git a/examples/network/exampleApplications/les_miserables.html b/examples/network/exampleApplications/lesMiserables.html similarity index 100% rename from examples/network/exampleApplications/les_miserables.html rename to examples/network/exampleApplications/lesMiserables.html diff --git a/examples/network/exampleApplications/neighbourhood_highlight.html b/examples/network/exampleApplications/neighbourhoodHighlight.html similarity index 100% rename from examples/network/exampleApplications/neighbourhood_highlight.html rename to examples/network/exampleApplications/neighbourhoodHighlight.html diff --git a/examples/network/index.html b/examples/network/index.html deleted file mode 100644 index efba4e2c..00000000 --- a/examples/network/index.html +++ /dev/null @@ -1,57 +0,0 @@ - - - - - vis.js | Network examples - - - - - - - - - \ No newline at end of file diff --git a/examples/network/labels/label_alignment.html b/examples/network/labels/labelAlignment.html similarity index 100% rename from examples/network/labels/label_alignment.html rename to examples/network/labels/labelAlignment.html diff --git a/examples/network/labels/label_background.html b/examples/network/labels/labelBackground.html similarity index 100% rename from examples/network/labels/label_background.html rename to examples/network/labels/labelBackground.html diff --git a/examples/network/labels/label_color_and_size.html b/examples/network/labels/labelColorAndSize.html similarity index 100% rename from examples/network/labels/label_color_and_size.html rename to examples/network/labels/labelColorAndSize.html diff --git a/examples/network/labels/label_stroke.html b/examples/network/labels/labelStroke.html similarity index 100% rename from examples/network/labels/label_stroke.html rename to examples/network/labels/labelStroke.html diff --git a/examples/network/labels/multiline_text.html b/examples/network/labels/multilineText.html similarity index 100% rename from examples/network/labels/multiline_text.html rename to examples/network/labels/multilineText.html diff --git a/examples/network/layout/hierarchical_layout.html b/examples/network/layout/hierarchicalLayout.html similarity index 100% rename from examples/network/layout/hierarchical_layout.html rename to examples/network/layout/hierarchicalLayout.html diff --git a/examples/network/layout/hierarchical_layout_methods.html b/examples/network/layout/hierarchicalLayoutMethods.html similarity index 100% rename from examples/network/layout/hierarchical_layout_methods.html rename to examples/network/layout/hierarchicalLayoutMethods.html diff --git a/examples/network/layout/hierarchical_layout_userdefined.html b/examples/network/layout/hierarchicalLayoutUserdefined.html similarity index 100% rename from examples/network/layout/hierarchical_layout_userdefined.html rename to examples/network/layout/hierarchicalLayoutUserdefined.html diff --git a/examples/network/nodeStyles/circular_images.html b/examples/network/nodeStyles/circularImages.html similarity index 100% rename from examples/network/nodeStyles/circular_images.html rename to examples/network/nodeStyles/circularImages.html From 6ef9d20a7a13570ddbe6306bd1dbf1ca0c351124 Mon Sep 17 00:00:00 2001 From: jos Date: Thu, 28 May 2015 15:42:29 +0200 Subject: [PATCH 05/11] Fixed two links --- docs/network/index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/network/index.html b/docs/network/index.html index 48f6468e..74c6ed86 100644 --- a/docs/network/index.html +++ b/docs/network/index.html @@ -187,7 +187,7 @@ </body> </html> -

The result of the code above will be the basic example which is shown here.

+

The result of the code above will be the basic example which is shown here.


@@ -1417,7 +1417,7 @@ var options = {
 // load the JSON file containing the Gephi network.
-var gephiJSON = loadJSON("./datasources/WorldCup2014.json"); // code in importing_from_gephi.
+var gephiJSON = loadJSON("./datasources/WorldCup2014.json"); // code in importing_from_gephi.
 
 // you can customize the result like with these options. These are explained below.
 // These are the default options.

From 6b0a55bf1670eb0b7624fef989f478de80c9dd71 Mon Sep 17 00:00:00 2001
From: jos 
Date: Thu, 28 May 2015 15:42:45 +0200
Subject: [PATCH 06/11] Deleted old docs

---
 docs/old/dataset.html                |  949 ----------
 docs/old/dataview.html               |  338 ----
 docs/old/graph3d.html                |  673 -------
 docs/old/index.html                  |  225 ---
 docs/old/lib/prettify/lang-apollo.js |    2 -
 docs/old/lib/prettify/lang-css.js    |    2 -
 docs/old/lib/prettify/lang-hs.js     |    2 -
 docs/old/lib/prettify/lang-lisp.js   |    2 -
 docs/old/lib/prettify/lang-lua.js    |    2 -
 docs/old/lib/prettify/lang-ml.js     |    2 -
 docs/old/lib/prettify/lang-proto.js  |    1 -
 docs/old/lib/prettify/lang-scala.js  |    2 -
 docs/old/lib/prettify/lang-sql.js    |    2 -
 docs/old/lib/prettify/lang-vb.js     |    2 -
 docs/old/lib/prettify/lang-vhdl.js   |    3 -
 docs/old/lib/prettify/lang-wiki.js   |    2 -
 docs/old/lib/prettify/lang-yaml.js   |    2 -
 docs/old/lib/prettify/prettify.css   |    1 -
 docs/old/lib/prettify/prettify.js    |   33 -
 docs/old/old_graph2d.html            | 1165 ------------
 docs/old/old_network.html            | 2625 --------------------------
 docs/old/old_network/canvas.html     |  211 ---
 docs/old/old_network/clustering.html |  182 --
 docs/old/old_network/rendering.html  |  127 --
 docs/old/old_network/selection.html  |  135 --
 docs/old/old_network/view.html       |  161 --
 docs/old/old_timeline.html           | 1510 ---------------
 27 files changed, 8361 deletions(-)
 delete mode 100644 docs/old/dataset.html
 delete mode 100644 docs/old/dataview.html
 delete mode 100644 docs/old/graph3d.html
 delete mode 100644 docs/old/index.html
 delete mode 100644 docs/old/lib/prettify/lang-apollo.js
 delete mode 100644 docs/old/lib/prettify/lang-css.js
 delete mode 100644 docs/old/lib/prettify/lang-hs.js
 delete mode 100644 docs/old/lib/prettify/lang-lisp.js
 delete mode 100644 docs/old/lib/prettify/lang-lua.js
 delete mode 100644 docs/old/lib/prettify/lang-ml.js
 delete mode 100644 docs/old/lib/prettify/lang-proto.js
 delete mode 100644 docs/old/lib/prettify/lang-scala.js
 delete mode 100644 docs/old/lib/prettify/lang-sql.js
 delete mode 100644 docs/old/lib/prettify/lang-vb.js
 delete mode 100644 docs/old/lib/prettify/lang-vhdl.js
 delete mode 100644 docs/old/lib/prettify/lang-wiki.js
 delete mode 100644 docs/old/lib/prettify/lang-yaml.js
 delete mode 100644 docs/old/lib/prettify/prettify.css
 delete mode 100644 docs/old/lib/prettify/prettify.js
 delete mode 100644 docs/old/old_graph2d.html
 delete mode 100644 docs/old/old_network.html
 delete mode 100644 docs/old/old_network/canvas.html
 delete mode 100644 docs/old/old_network/clustering.html
 delete mode 100644 docs/old/old_network/rendering.html
 delete mode 100644 docs/old/old_network/selection.html
 delete mode 100644 docs/old/old_network/view.html
 delete mode 100644 docs/old/old_timeline.html

diff --git a/docs/old/dataset.html b/docs/old/dataset.html
deleted file mode 100644
index 48007fad..00000000
--- a/docs/old/dataset.html
+++ /dev/null
@@ -1,949 +0,0 @@
-
-
-
-
-  vis.js | DataSet documentation
-
-  
-  
-
-  
-
-
-
-
- -

DataSet documentation

- -

Contents

- - - -

Overview

- -

- Vis.js comes with a flexible DataSet, which can be used to hold and - manipulate unstructured data and listen for changes in the data. - The DataSet is key/value based. Data items can be added, updated and - removed from the DatSet, and one can subscribe to changes in the DataSet. - The data in the DataSet can be filtered and ordered, and fields (like - dates) can be converted to a specific type. Data can be normalized when - appending it to the DataSet as well. -

- - -

Example

- -

- The following example shows how to use a DataSet. -

- -
-// create a DataSet
-var options = {};
-var data = new vis.DataSet(options);
-
-// add items
-// note that the data items can contain different properties and data formats
-data.add([
-  {id: 1, text: 'item 1', date: new Date(2013, 6, 20), group: 1, first: true},
-  {id: 2, text: 'item 2', date: '2013-06-23', group: 2},
-  {id: 3, text: 'item 3', date: '2013-06-25', group: 2},
-  {id: 4, text: 'item 4'}
-]);
-
-// subscribe to any change in the DataSet
-data.on('*', function (event, properties, senderId) {
-  console.log('event', event, properties);
-});
-
-// update an existing item
-data.update({id: 2, group: 1});
-
-// remove an item
-data.remove(4);
-
-// get all ids
-var ids = data.getIds();
-console.log('ids', ids);
-
-// get a specific item
-var item1 = data.get(1);
-console.log('item1', item1);
-
-// retrieve a filtered subset of the data
-var items = data.get({
-  filter: function (item) {
-    return item.group == 1;
-  }
-});
-console.log('filtered items', items);
-
-// retrieve formatted items
-var items = data.get({
-  fields: ['id', 'date'],
-  type: {
-    date: 'ISODate'
-  }
-});
-console.log('formatted items', items);
-
- - - -

Construction

- -

- A DataSet can be constructed as: -

- -
-var data = new vis.DataSet([data] [, options])
-
- -

- After construction, data can be added to the DataSet using the methods - add and update, as described in section - Data Manipulation. -

- -

- The parameter data is optional and is an Array with items. -

- -

- The parameter options is optional and is an object which can - contain the following properties: -

- - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDefault valueDescription
fieldIdString"id" - The name of the field containing the id of the items. - - When data is fetched from a server which uses some specific - field to identify items, this field name can be specified - in the DataSet using the option fieldId. - For example CouchDB uses the field - "_id" to identify documents. -
typeObject.<String, String>none - An object containing field names as key, and data types as - value. By default, the type of the properties of items are left - unchanged. Item properties can be normalized by specifying a - field type. This is useful for example to automatically convert - stringified dates coming from a server into JavaScript Date - objects. The available data types are listed in section - Data Types. -
queueObject | booleannone - Queue data changes ('add', 'update', 'remove') and flush them at once. - The queue can be flushed manually by calling - DataSet.flush(), or can be flushed after a configured delay - or maximum number of entries. -
-
- When queue is true, a queue is created - with default options. Options can be specified by providing an object: -
    -
  • delay: number
    - 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 is Infinity. -
  • -
-
- - -

Methods

- -

DataSet contains the following methods.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MethodReturn TypeDescription
add(data [, senderId])Number[]Add one or multiple items to the DataSet. data can be a single item or an array with items. Adding an item will fail when there already is an item with the same id. The function returns an array with the ids of the added items. See section Data Manipulation.
clear([senderId])Number[]Clear all data from the DataSet. The function returns an array with the ids of the removed items.
distinct(field)ArrayFind all distinct values of a specified field. Returns an unordered array containing all distinct values. If data items do not contain the specified field are ignored.
flush()noneFlush queued changes. Only available when the DataSet is configured with the option queue, see section Construction.
forEach(callback [, options])none - Execute a callback function for every item in the dataset. - The available options are described in section Data Selection. -
- get([options] [, data])
- get(id [,options] [, data])
- get(ids [, options] [, data]) -
Object | Array - Get a single item, multiple items, or all items from the DataSet. - Usage examples can be found in section Getting Data, and the available options are described in section Data Selection. -
- getDataSet() - DataSet - Get the DataSet itself. In case of a DataView, this function does not - return the DataSet to which the DataView is connected. -
- getIds([options]) - Number[] - Get ids of all items or of a filtered set of items. - Available options are described in section Data Selection, except that options fields and type are not applicable in case of getIds. -
map(callback [, options])Array - Map every item in the DataSet. - The available options are described in section Data Selection. -
max(field)Object | null - Find the item with maximum value of specified field. Returns null if no item is found. -
min(field)Object | null - Find the item with minimum value of specified field. Returns null if no item is found. -
off(event, callback)none - Unsubscribe from an event, remove an event listener. See section Subscriptions. -
on(event, callback)none - Subscribe to an event, add an event listener. See section Subscriptions. -
- remove(id [, senderId])
- remove(ids [, senderId]) -
Number[] - Remove one or multiple items by id or by the items themselves. Returns an array with the ids of the removed items. See section Data Manipulation. -
- setOptions(options) - none - Set options for the DataSet. Available options: - -
    -
  • - queue
    - Queue data changes ('add', 'update', 'remove') and flush them at once. - The queue can be flushed manually by calling - DataSet.flush(), or can be flushed after a configured delay - or maximum number of entries. -
    -
    - When queue is true, a queue is created with default options. - When queue is false, an existing queue will be flushed and removed. - Options can be specified by providing an object: -
      -
    • delay: number
      - 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 is Infinity. -
    • -
    -
  • -
-
- update(data [, senderId]) - Number[] - Update on ore multiple existing items. data can be a single item or an array with items. When an item doesn't exist, it will be created. Returns an array with the ids of the removed items. See section Data Manipulation. -
- - -

Properties

- -

DataSet contains the following properties.

- - - - - - - - - - - - - - - - - -
PropertyTypeDescription
lengthNumberThe number of items in the DataSet.
- - -

Subscriptions

- -

- One can subscribe on changes in a DataSet. - A subscription can be created using the method on, - and removed with off. -

- -
-// create a DataSet
-var data = new vis.DataSet();
-
-// subscribe to any change in the DataSet
-data.on('*', function (event, properties, senderId) {
-  console.log('event:', event, 'properties:', properties, 'senderId:', senderId);
-});
-
-// add an item
-data.add({id: 1, text: 'item 1'});              // triggers an 'add' event
-data.update({id: 1, text: 'item 1 (updated)'}); // triggers an 'update' event
-data.remove(1);                                 // triggers an 'remove' event
-
- - -

On

- -

- Subscribe to an event. -

- -Syntax: -
DataSet.on(event, callback)
- -Where: -
    -
  • - event is a String containing any of the events listed - in section Events. -
  • -
  • - callback is a callback function which will be called - each time the event occurs. The callback function is described in - section Callback. -
  • -
- -

Off

- -

- Unsubscribe from an event. -

- -Syntax: -
DataSet.off(event, callback)
- -Where event and callback correspond with the -parameters used to subscribe to the event. - -

Events

- -

- The following events are available for subscription: -

- - - - - - - - - - - - - - - - - - - - - - -
EventDescription
add - The add event is triggered when an item - or a set of items is added, or when an item is updated while - not yet existing. -
update - The update event is triggered when an existing item - or a set of existing items is updated. -
remove - The remove event is triggered when an item - or a set of items is removed. -
* - The * event is triggered when any of the events - add, update, and remove - occurs. -
- -

Callback

- -

- The callback functions of subscribers are called with the following - parameters: -

- -
-function (event, properties, senderId) {
-  // handle the event
-});
-
- -

- where the parameters are defined as -

- - - - - - - - - - - - - - - - - - - - - - -
ParameterTypeDescription
eventString - Any of the available events: add, - update, or remove. -
propertiesObject | null - Optional properties providing more information on the event. - In case of the events add, - update, and remove, - properties is always an object containing a property - items, which contains an array with the ids of the affected - items. The update event has an extra field data - containing the original data of the updated items, i.e. the gives the - changed fields of the changed items. -
senderIdString | Number - An senderId, optionally provided by the application code - which triggered the event. If senderId is not provided, the - argument will be null. -
- - -

Data Manipulation

- -

- The data in a DataSet can be manipulated using the methods - add, - update, - and remove. - The DataSet can be emptied using the method - clear. -

- -
-// create a DataSet
-var data = new vis.DataSet();
-
-// add items
-data.add([
-  {id: 1, text: 'item 1'},
-  {id: 2, text: 'item 2'},
-  {id: 3, text: 'item 3'}
-]);
-
-// update an item
-data.update({id: 2, text: 'item 2 (updated)'});
-
-// remove an item
-data.remove(3);
-
- -

Add

- -

- Add a data item or an array with items. -

- -Syntax: -
var addedIds = DataSet.add(data [, senderId])
- -The argument data can contain: -
    -
  • - An Object containing a single item to be - added. The item must contain an id. -
  • -
  • - An Array containing a list with items to be added. Each item must contain an id. -
  • -
- -

- After the items are added to the DataSet, the DataSet will - trigger an event add. When a senderId - is provided, this id will be passed with the triggered - event to all subscribers. -

- -

- The method will throw an Error when an item with the same id - as any of the added items already exists. -

- -

Update

- -

- Update a data item or an array with items. -

- -Syntax: -
var updatedIds = DataSet.update(data [, senderId])
- -The argument data can contain: -
    -
  • - An Object containing a single item to be - updated. The item must contain an id. -
  • -
  • - An Array containing a list with items to be updated. Each item must contain an id. -
  • -
- -

- The provided properties will be merged in the existing item. - When an item does not exist, it will be created. -

- -

- After the items are updated, the DataSet will - trigger an event add for the added items, and - an event update. When a senderId - is provided, this id will be passed with the triggered - event to all subscribers. -

- -

Remove

- -

- Remove a data item or an array with items. -

- -Syntax: -
var removedIds = DataSet.remove(id [, senderId])
- -

- The argument id can be: -

-
    -
  • - A Number or String containing the id - of a single item to be removed. -
  • -
  • - An Object containing the item to be deleted. - The item will be deleted by its id. -
  • -
  • - An Array containing ids or items to be removed. -
  • -
- -

- The method ignores removal of non-existing items, and returns an array - containing the ids of the items which are actually removed from the - DataSet. -

- -

- After the items are removed, the DataSet will - trigger an event remove for the removed items. - When a senderId is provided, this id will be passed with - the triggered event to all subscribers. -

- - -

Clear

- -

- Clear the complete DataSet. -

- -Syntax: -
var removedIds = DataSet.clear([senderId])
- -

- After the items are removed, the DataSet will - trigger an event remove for all removed items. - When a senderId is provided, this id will be passed with - the triggered event to all subscribers. -

- - -

Data Selection

- -

- The DataSet contains functionality to format, filter, and sort data retrieved via the - methods get, getIds, forEach, and map. These methods have the following syntax: -

- -
-DataSet.get([id] [, options]);
-DataSet.getIds([options]);
-DataSet.forEach(callback [, options]);
-DataSet.map(callback [, options]);
-
- -

- Where options is an Object which can have the following - properties: -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
fieldsString[ ] | Object.<String, String> - An array with field names, or an object with current field name and - new field name that the field is returned as. - By default, all properties of the items are emitted. - When fields is defined, only the properties - whose name is specified in fields will be included - in the returned items. -
typeObject.<String, String> - An object containing field names as key, and data types as value. - By default, the type of the properties of an item are left - unchanged. When a field type is specified, this field in the - items will be converted to the specified type. This can be used - for example to convert ISO strings containing a date to a - JavaScript Date object, or convert strings to numbers or vice - versa. The available data types are listed in section - Data Types. -
filterFunctionItems can be filtered on specific properties by providing a filter - function. A filter function is executed for each of the items in the - DataSet, and is called with the item as parameter. The function must - return a boolean. All items for which the filter function returns - true will be emitted. - See section Data Filtering.
orderString | FunctionOrder the items by a field name or custom sort function.
returnTypeStringDetermine the type of output of the get function. Allowed values are 'Array' | 'Object'. - The default returnType is an Array. The Object type will return a JSON object with the ID's as keys.
- -

- The following example demonstrates formatting properties and filtering - properties from items. -

- -
-// create a DataSet
-var data = new vis.DataSet();
-data.add([
-  {id: 1, text: 'item 1', date: '2013-06-20', group: 1, first: true},
-  {id: 2, text: 'item 2', date: '2013-06-23', group: 2},
-  {id: 3, text: 'item 3', date: '2013-06-25', group: 2},
-  {id: 4, text: 'item 4'}
-]);
-
-// retrieve formatted items
-var items = data.get({
-  fields: ['id', 'date', 'group'],    // output the specified fields only
-  type: {
-    date: 'Date',                   // convert the date fields to Date objects
-    group: 'String'                 // convert the group fields to Strings
-  }
-});
-
- -

Getting Data

- -

- Data can be retrieved from the DataSet using the method get. - This method can return a single item or a list with items. -

- -

A single item can be retrieved by its id:

- -
-var item1 = dataset.get(1);
-
- -

A selection of items can be retrieved by providing an array with ids:

- -
-var items = dataset.get([1, 3, 4]); // retrieve items 1, 3, and 4
-
- -

All items can be retrieved by simply calling get without - specifying an id:

- -
-var items = dataset.get();          // retrieve all items
-
- - -

Data Filtering

- -

- Items can be filtered on specific properties by providing a filter - function. A filter function is executed for each of the items in the - DataSet, and is called with the item as parameter. The function must - return a boolean. All items for which the filter function returns - true will be emitted. -

- -
-// retrieve all items having a property group with value 2
-var group2 = dataset.get({
-  filter: function (item) {
-    return (item.group == 2);
-  }
-});
-
-// retrieve all items having a property balance with a value above zero
-var positiveBalance = dataset.get({
-  filter: function (item) {
-    return (item.balance > 0);
-  }
-});
-
-
- - -

Data Types

- -

- DataSet supports the following data types: -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDescriptionExamples
BooleanA JavaScript Boolean - true
- false -
NumberA JavaScript Number - 32
- 2.4 -
StringA JavaScript String - "hello world"
- "2013-06-28" -
DateA JavaScript Date object - new Date()
- new Date(2013, 5, 28)
- new Date(1372370400000) -
MomentA Moment object, created with - moment.js - moment()
- moment('2013-06-28') -
ISODateA string containing an ISO Date - new Date().toISOString()
- "2013-06-27T22:00:00.000Z" -
ASPDateA string containing an ASP Date - "/Date(1372370400000)/"
- "/Date(1198908717056-0700)/" -
- - -

Data Policy

-

- All code and data is processed and rendered in the browser. - No data is sent to any server. -

- -
- - diff --git a/docs/old/dataview.html b/docs/old/dataview.html deleted file mode 100644 index c6046d64..00000000 --- a/docs/old/dataview.html +++ /dev/null @@ -1,338 +0,0 @@ - - - - - vis.js | DataView documentation - - - - - - - - -
- -

DataView documentation

- -

Contents

- - - -

Overview

- -

- A DataView offers a filtered and/or formatted view on a - DataSet. - One can subscribe on changes in a DataView, and easily get filtered or - formatted data without having to specify filters and field types all - the time. -

- -

Example

- -

- The following example shows how to use a DataView. -

- -
-// create a DataSet
-var data = new vis.DataSet();
-data.add([
-  {id: 1, text: 'item 1', date: new Date(2013, 6, 20), group: 1, first: true},
-  {id: 2, text: 'item 2', date: '2013-06-23', group: 2},
-  {id: 3, text: 'item 3', date: '2013-06-25', group: 2},
-  {id: 4, text: 'item 4'}
-]);
-
-// create a DataView
-// the view will only contain items having a property group with value 1,
-// and will only output fields id, text, and date.
-var view = new vis.DataView(data, {
-  filter: function (item) {
-    return (item.group == 1);
-  },
-  fields: ['id', 'text', 'date']
-});
-
-// subscribe to any change in the DataView
-view.on('*', function (event, properties, senderId) {
-  console.log('event', event, properties);
-});
-
-// update an item in the data set
-data.update({id: 2, group: 1});
-
-// get all ids in the view
-var ids = view.getIds();
-console.log('ids', ids); // will output [1, 2]
-
-// get all items in the view
-var items = view.get();
-
- -

Construction

- - -

- A DataView can be constructed as: -

- -
-var data = new vis.DataView(dataset, options)
-
- -

- where: -

- -
    -
  • - dataset is a DataSet or DataView. -
  • -
  • - options is an object which can - contain the following properties. Note that these properties - are exactly the same as the properties available in methods - DataSet.get and DataView.get. - - - - - - - - - - - - - - - - - - - - - - - - - - -
    NameTypeDescription
    convertObject.<String, String> - An object containing field names as key, and data types as value. - By default, the type of the properties of an item are left - unchanged. When a field type is specified, this field in the - items will be converted to the specified type. This can be used - for example to convert ISO strings containing a date to a - JavaScript Date object, or convert strings to numbers or vice - versa. The available data types are listed in section - Data Types. -
    fieldsString[ ] | Object.<String, String> - An array with field names, or an object with current field name and - new field name that the field is returned as. - By default, all properties of the items are emitted. - When fields is defined, only the properties - whose name is specified in fields will be included - in the returned items. -
    filterfunctionItems can be filtered on specific properties by providing a filter - function. A filter function is executed for each of the items in the - DataSet, and is called with the item as parameter. The function must - return a boolean. All items for which the filter function returns - true will be emitted. - See also section Data Filtering.
    -
  • -
- -

Methods

- -

DataView contains the following methods.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MethodReturn TypeDescription
- get([options] [, data])
- get(id [,options] [, data])
- get(ids [, options] [, data]) -
Object | Array - Get a single item, multiple items, or all items from the DataView. - Usage examples can be found in section Getting Data, and the available options are described in section Data Selection. -
- getDataSet() - DataSet - Get the DataSet to which the DataView is connected. -
- getIds([options]) - Number[] - Get ids of all items or of a filtered set of items. - Available options are described in section Data Selection, except that options fields and type are not applicable in case of getIds. -
off(event, callback)none - Unsubscribe from an event, remove an event listener. See section Subscriptions. -
on(event, callback)none - Subscribe to an event, add an event listener. See section Subscriptions. -
refresh()none - Refresh the filter results of a DataView. Useful when the filter function contains dynamic properties, like: - -
var data = new vis.DataSet(...);
-var view = new vis.DataView(data, {
-  filter: function (item) {
-    return item.value > threshold;
-  }
-});
- In this example, threshold is an external parameter. When the value of threshold changes, the DataView must be notified that the filter results may have changed by calling DataView.refresh(). -
- setDataSet(data) - none - Replace the DataSet of the DataView. Parameter data can be a DataSet or a DataView. -
- - -

Properties

- -

DataView contains the following properties.

- - - - - - - - - - - - - - - - - -
PropertyTypeDescription
lengthNumberThe number of items in the DataView.
- -

Getting Data

- -

- Data of the DataView can be retrieved using the method get. -

- -
-var items = view.get();
-
- -

- Data of a DataView can be filtered and formatted again, in exactly the - same way as in a DataSet. See sections - Data Manipulation and - Data Selection for more - information. -

- -
-var items = view.get({
-  fields: ['id', 'score'],
-  filter: function (item) {
-    return (item.score > 50);
-  }
-});
-
- - - -

Subscriptions

-

- One can subscribe on changes in the DataView. Subscription works exactly - the same as for DataSets. See the documentation on - subscriptions in a DataSet - for more information. -

- -
-// create a DataSet and a view on the data set
-var data = new vis.DataSet();
-var view = new vis.DataView({
-  filter: function (item) {
-    return (item.group == 2);
-  }
-});
-
-// subscribe to any change in the DataView
-view.on('*', function (event, properties, senderId) {
-  console.log('event:', event, 'properties:', properties, 'senderId:', senderId);
-});
-
-// add, update, and remove data in the DataSet...
-
- - - -

Data Policy

-

- All code and data is processed and rendered in the browser. - No data is sent to any server. -

- -
- - \ No newline at end of file diff --git a/docs/old/graph3d.html b/docs/old/graph3d.html deleted file mode 100644 index 54250778..00000000 --- a/docs/old/graph3d.html +++ /dev/null @@ -1,673 +0,0 @@ - - - - vis.js | graph3d documentation - - - - - - - - -
- -

Graph3d documentation

- -

Overview

-

- Graph3d is an interactive visualization chart to draw data in a three dimensional - graph. You can freely move and zoom in the graph by dragging and scrolling in the - window. Graph3d also supports animation of a graph. -

-

- Graph3d uses HTML canvas - to render graphs, and can render up to a few thousands of data points smoothly. -

- -

Contents

- - -

Example

-

- The following code shows how to create a Graph3d and provide it with data. - More examples can be found in the examples directory. -

- -
-<!DOCTYPE HTML>
-<html>
-<head>
-  <title>Graph 3D demo</title>
-
-  <style>
-    body {font: 10pt arial;}
-  </style>
-
-  <script type="text/javascript" src="../../dist/vis.js"></script>
-
-  <script type="text/javascript">
-  var data = null;
-  var graph = null;
-
-  function custom(x, y) {
-    return (Math.sin(x/50) * Math.cos(y/50) * 50 + 50);
-  }
-
-  // Called when the Visualization API is loaded.
-  function drawVisualization() {
-    // Create and populate a data table.
-    var data = new vis.DataSet();
-    // create some nice looking data with sin/cos
-    var steps = 50;  // number of datapoints will be steps*steps
-    var axisMax = 314;
-    var axisStep = axisMax / steps;
-    for (var x = 0; x < axisMax; x+=axisStep) {
-      for (var y = 0; y < axisMax; y+=axisStep) {
-        var value = custom(x, y);
-        data.add({
-          x: x,
-          y: y,
-          z: value,
-          style: value
-        });
-      }
-    }
-
-    // specify options
-    var options = {
-      width:  '600px',
-      height: '600px',
-      style: 'surface',
-      showPerspective: true,
-      showGrid: true,
-      showShadow: false,
-      keepAspectRatio: true,
-      verticalRatio: 0.5
-    };
-
-    // create a graph3d
-    var container = document.getElementById('mygraph');
-    graph3d = new vis.Graph3d(container, data, options);
-  }
-  </script>
-</head>
-
-<body onload="drawVisualization();">
-  <div id="mygraph"></div>
-</body>
-</html>
-
-
- - -

Loading

- -

- The class name of the Graph3d is vis.Graph3d. - When constructing a Graph3d, an HTML DOM container must be provided to attach - the graph to. Optionally, data an options can be provided. - Data is a vis DataSet or an Array, described in - section Data Format. - Options is a name-value map in the JSON format. The available options - are described in section Configuration Options. -

-
var graph = new vis.Graph3d(container [, data] [, options]);
- -

- Data and options can be set or changed later on using the functions - Graph3d.setData(data) and Graph3d.setOptions(options). -

- -

Data Format

-

- Graph3d can load data from an Array, a DataSet or a DataView. - JSON objects are added to this DataSet by using the add() function. - Data points must have properties x, y, and z, - and can optionally have a property style and filter. - -

Definition

-

- The DataSet JSON objects are defined as: -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeRequiredDescription
xnumberyesLocation on the x-axis.
ynumberyesLocation on the y-axis.
znumberyesLocation on the z-axis.
stylenumbernoThe data value, required for graph styles dot-color and - dot-size. -
filter*noFilter values used for the animation. - This column may have any type, such as a number, string, or Date.
- - - -

Configuration Options

- -

- Options can be used to customize the graph. Options are defined as a JSON object. - All options are optional. -

- -
-var options = {
-    width:  '100%',
-    height: '400px',
-    style: 'surface'
-};
-
- -

- The following options are available. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDefaultDescription
animationIntervalnumber1000The animation interval in milliseconds. This determines how fast - the animation runs.
animationPreloadbooleanfalseIf false, the animation frames are loaded as soon as they are requested. - if animationPreload is true, the graph will automatically load - all frames in the background, resulting in a smoother animation as soon as - all frames are loaded. The load progress is shown on screen.
animationAutoStartbooleanfalseIf true, the animation starts playing automatically after the graph - is created.
backgroundColorstring or Object'white'The background color for the main area of the chart. - Can be either a simple HTML color string, for example: 'red' or '#00cc00', - or an object with the following properties.
backgroundColor.strokestring'gray'The color of the chart border, as an HTML color string.
backgroundColor.strokeWidthnumber1The border width, in pixels.
backgroundColor.fillstring'white'The chart fill color, as an HTML color string.
cameraPositionObject{horizontal: 1.0, vertical: 0.5, distance: 1.7}Set the initial rotation and position of the camera. - The object cameraPosition contains three parameters: - horizontal, vertical, and distance. - Parameter horizontal is a value in radians and can have any - value (but normally in the range of 0 and 2*Pi). - Parameter vertical is a value in radians between 0 and 0.5*Pi. - Parameter distance is the (normalized) distance from the - camera to the center of the graph, in the range of 0.71 to 5.0. A - larger distance puts the graph further away, making it smaller. - All parameters are optional. -
heightstring'400px'The height of the graph in pixels or as a percentage.
keepAspectRatiobooleantrueIf keepAspectRatio is true, the x-axis and the y-axis - keep their aspect ratio. If false, the axes are scaled such that they - both have the same, maximum with.
showAnimationControlsbooleantrueIf true, animation controls are created at the bottom of the Graph. - The animation controls consists of buttons previous, start/stop, next, - and a slider showing the current frame. - Only applicable when the provided data contains an animation.
showGridbooleantrueIf true, grid lines are draw in the x-y surface (the bottom of the 3d - graph).
showPerspectivebooleantrueIf true, the graph is drawn in perspective: points and lines which - are further away are drawn smaller. - Note that the graph currently does not support a gray colored bottom side - when drawn in perspective. -
showShadowbooleanfalseShow shadow on the graph.
stylestring'dot'The style of the 3d graph. Available styles: - bar, - bar-color, - bar-size, - dot, - dot-line, - dot-color, - dot-size, - line, - grid, - or surface
tooltipboolean | functionfalseShow a tooltip showing the values of the hovered data point. - The contents of the tooltip can be customized by providing a callback - function as tooltip. In this case the function is called - with an object containing parameters x, - y, and z argument, - and must return a string which may contain HTML. -
valueMaxnumbernoneThe maximum value for the value-axis. Only available in combination - with the styles dot-color and dot-size.
valueMinnumbernoneThe minimum value for the value-axis. Only available in combination - with the styles dot-color and dot-size.
verticalRationumber0.5A value between 0.1 and 1.0. This scales the vertical size of the graph - When keepAspectRatio is set to false, and verticalRatio is set to 1.0, - the graph will be a cube.
widthstring'400px'The width of the graph in pixels or as a percentage.
xBarWidthnumbernoneThe width of bars in x direction. By default, the width is equal to the distance - between the data points, such that bars adjoin each other. - Only applicable for styles 'bar' and 'bar-color'.
xCenterstring'55%'The horizontal center position of the graph, as a percentage or in - pixels.
xMaxnumbernoneThe maximum value for the x-axis.
xMinnumbernoneThe minimum value for the x-axis.
xStepnumbernoneStep size for the grid on the x-axis.
xValueLabelfunctionnoneA function for custom formatting of the labels along the x-axis, - for example function (x) {return (x * 100) + '%'}. -
yBarWidthnumbernoneThe width of bars in y direction. By default, the width is equal to the distance - between the data points, such that bars adjoin each other. - Only applicable for styles 'bar' and 'bar-color'.
yCenterstring'45%'The vertical center position of the graph, as a percentage or in - pixels.
yMaxnumbernoneThe maximum value for the y-axis.
yMinnumbernoneThe minimum value for the y-axis.
yStepnumbernoneStep size for the grid on the y-axis.
yValueLabelfunctionnoneA function for custom formatting of the labels along the y-axis, - for example function (y) {return (y * 100) + '%'}. -
zMinnumbernoneThe minimum value for the z-axis.
zMaxnumbernoneThe maximum value for the z-axis.
zStepnumbernoneStep size for the grid on the z-axis.
zValueLabelfunctionnoneA function for custom formatting of the labels along the z-axis, - for example function (z) {return (z * 100) + '%'}. -
xLabelStringxLabel on the X axis.
yLabelStringyLabel on the Y axis.
zLabelStringzLabel on the Z axis.
filterLabelStringtimeLabel for the filter column.
legendLabelStringvalueLabel for the style description.
- - -

Methods

-

- Graph3d supports the following methods. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MethodReturn TypeDescription
animationStart()noneStart playing the animation. - Only applicable when animation data is available.
animationStop()noneStop playing the animation. - Only applicable when animation data is available.
getCameraPosition()An object with parameters horizontal, - vertical and distanceReturns an object with parameters horizontal, - vertical and distance, - which each one of them is a number, representing the rotation and position - of the camera.
redraw()noneRedraw the graph. Useful after the camera position is changed externally, - when data is changed, or when the layout of the webpage changed.
setData(data)noneReplace the data in the Graph3d.
setOptions(options)noneUpdate options of Graph3d. - The provided options will be merged with current options.
setSize(width, height)noneParameters width and height are strings, - containing a new size for the graph. Size can be provided in pixels - or in percentages.
setCameraPosition (pos){horizontal: 1.0, vertical: 0.5, distance: 1.7}Set the rotation and position of the camera. Parameter pos - is an object which contains three parameters: horizontal, - vertical, and distance. - Parameter horizontal is a value in radians and can have any - value (but normally in the range of 0 and 2*Pi). - Parameter vertical is a value in radians between 0 and 0.5*Pi. - Parameter distance is the (normalized) distance from the - camera to the center of the graph, in the range of 0.71 to 5.0. A - larger distance puts the graph further away, making it smaller. - All parameters are optional. -
- -

Events

-

- Graph3d fires events after the camera position has been changed. - The event can be catched by creating a listener. - Here an example on how to catch a cameraPositionChange event. -

- -
-function onCameraPositionChange(event) {
-  alert('The camera position changed to:\n' +
-        'Horizontal: ' + event.horizontal + '\n' +
-        'Vertical: ' + event.vertical + '\n' +
-        'Distance: ' + event.distance);
-}
-// assuming var graph3d = new vis.Graph3d(document.getElementById('mygraph'));
-graph3d.on('cameraPositionChange', onCameraPositionChange);
-
- -

- The following events are available. -

- - - - - - - - - - - - - - - - - -
nameDescriptionProperties
cameraPositionChangeThe camera position changed. Fired after the user modified the camera position - by moving (dragging) the graph, or by zooming (scrolling), - but not after a call to setCameraPosition method. - The new camera position can be retrieved by calling the method - getCameraPosition. -
    -
  • horizontal: Number. The horizontal angle of the camera.
  • -
  • vertical: Number. The vertical angle of the camera.
  • -
  • distance: Number. The distance of the camera to the center of the graph.
  • -
-
- -

Data Policy

-

- All code and data are processed and rendered in the browser. No data is sent to any server. -

- -
- - diff --git a/docs/old/index.html b/docs/old/index.html deleted file mode 100644 index 349712f5..00000000 --- a/docs/old/index.html +++ /dev/null @@ -1,225 +0,0 @@ - - - - - vis.js | documentation - - - - - - - - -
- -

vis.js documentation

- -

- Vis.js is a dynamic, browser based visualization library. - The library is designed to be easy to use, handle large amounts - of dynamic data, and enable manipulation of the data. -

- -

- The library is developed by - Almende B.V.. - Vis.js runs fine on Chrome, Firefox, Opera, Safari, IE9+, and most mobile - browsers (with full touch support). -

- -

Components

- -

- Vis.js contains of the following components: -

- - - -
    -
  • - DataSet. - A flexible key/value based data set. - Add, update, and remove items. Subscribe on changes in the data set. - A DataSet can filter and order items, and convert fields of items. -
  • -
  • - DataView. - A filtered and/or formatted view on a DataSet. -
  • -
  • - Network. - Display a network (force directed graph) with nodes and edges (previously called Graph). -
  • -
  • - Graph2d. - Plot data on a timeline with lines or barcharts. -
  • -
  • - Graph3d. - Display data in a three dimensional graph. -
  • -
  • - Timeline. - Display different types of data on a timeline. -
  • -
- -

Install

- -

npm

- -
-npm install vis
-
- -

bower

- -
-bower install vis
-
- -

download

- Download the library from the website: - http://visjs.org. - -

Load

- -

- To load vis.js, include the javascript and css files of vis in your web page: -

- -
<!DOCTYPE HTML>
-<html>
-<head>
-  <script src="components/vis/vis.js"></script>
-  <link href="components/vis/vis.css" rel="stylesheet" type="text/css" />
-</head>
-<body>
-<script type="text/javascript">
-  // ... load a visualization
-</script>
-</body>
-</html>
-
- -

- or load vis.js using require.js: -

- -
-require.config({
-  paths: {
-    vis: 'path/to/vis',
-  }
-});
-
-require(['vis'], function (math) {
-  // ... load a visualization
-});
-
- -

- A timeline can be instantiated as follows. Other components can be - created in a similar way. -

- -
-var timeline = new vis.Timeline(container, data, options);
-
- -

- Where container is an HTML element, data is - an Array with data or a DataSet, and options is an optional - object with configuration options for the component. -

- -

Use

- -

- A basic example on using a Timeline is shown below. More examples can be - found in the examples directory of the project. -

- -
-<!DOCTYPE HTML>
-<html>
-<head>
-  <title>Timeline basic demo</title>
-
-  <script src="components/vis/vis.js"></script>
-  <link href="components/vis/vis.css" rel="stylesheet" type="text/css" />
-
-  <style type="text/css">
-    body, html {
-      font-family: sans-serif;
-    }
-  </style>
-</head>
-<body>
-<div id="visualization"></div>
-
-<script type="text/javascript">
-  // DOM element where the Timeline will be attached
-  var container = document.getElementById('visualization');
-
-  // Create a DataSet (allows two way data-binding)
-  var data = new vis.DataSet([
-    {id: 1, content: 'item 1', start: '2013-04-20'},
-    {id: 2, content: 'item 2', start: '2013-04-14'},
-    {id: 3, content: 'item 3', start: '2013-04-18'},
-    {id: 4, content: 'item 4', start: '2013-04-16', end: '2013-04-19'},
-    {id: 5, content: 'item 5', start: '2013-04-25'},
-    {id: 6, content: 'item 6', start: '2013-04-27'}
-  ]);
-
-    // Configuration for the Timeline
-  var options = {};
-
-  // Create a Timeline
-  var timeline = new vis.Timeline(container, data, options);
-</script>
-</body>
-</html>
-
- - -

License

- -

- Copyright 2010-2014 Almende B.V. -

- -

- Vis.js is dual licensed under both -

- -

- and -

- - -

- Vis.js may be distributed under either license. -

- - -
- - \ No newline at end of file diff --git a/docs/old/lib/prettify/lang-apollo.js b/docs/old/lib/prettify/lang-apollo.js deleted file mode 100644 index bfc0014c..00000000 --- a/docs/old/lib/prettify/lang-apollo.js +++ /dev/null @@ -1,2 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["com",/^#[^\r\n]*/,null,"#"],["pln",/^[\t\n\r \xA0]+/,null,"\t\n\r \u00a0"],["str",/^\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)/,null,'"']],[["kwd",/^(?:ADS|AD|AUG|BZF|BZMF|CAE|CAF|CA|CCS|COM|CS|DAS|DCA|DCOM|DCS|DDOUBL|DIM|DOUBLE|DTCB|DTCF|DV|DXCH|EDRUPT|EXTEND|INCR|INDEX|NDX|INHINT|LXCH|MASK|MSK|MP|MSU|NOOP|OVSK|QXCH|RAND|READ|RELINT|RESUME|RETURN|ROR|RXOR|SQUARE|SU|TCR|TCAA|OVSK|TCF|TC|TS|WAND|WOR|WRITE|XCH|XLQ|XXALQ|ZL|ZQ|ADD|ADZ|SUB|SUZ|MPY|MPR|MPZ|DVP|COM|ABS|CLA|CLZ|LDQ|STO|STQ|ALS|LLS|LRS|TRA|TSQ|TMI|TOV|AXT|TIX|DLY|INP|OUT)\s/, -null],["typ",/^(?:-?GENADR|=MINUS|2BCADR|VN|BOF|MM|-?2CADR|-?[1-6]DNADR|ADRES|BBCON|[SE]?BANK\=?|BLOCK|BNKSUM|E?CADR|COUNT\*?|2?DEC\*?|-?DNCHAN|-?DNPTR|EQUALS|ERASE|MEMORY|2?OCT|REMADR|SETLOC|SUBRO|ORG|BSS|BES|SYN|EQU|DEFINE|END)\s/,null],["lit",/^\'(?:-*(?:\w|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?)?/],["pln",/^-*(?:[!-z_]|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?/i],["pun",/^[^\w\t\n\r \xA0()\"\\\';]+/]]),["apollo","agc","aea"]) \ No newline at end of file diff --git a/docs/old/lib/prettify/lang-css.js b/docs/old/lib/prettify/lang-css.js deleted file mode 100644 index 61157f38..00000000 --- a/docs/old/lib/prettify/lang-css.js +++ /dev/null @@ -1,2 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[ \t\r\n\f]+/,null," \t\r\n\u000c"]],[["str",/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],["str",/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],["kwd",/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//], -["com",/^(?: - - - - - - - - - - - - - - - - - - - - - - -
-

Network - canvas

- -

Handles the HTML part of the canvas.

- -

Options

- -

The options for the canvas have to be contained in an object titled 'canvas'.

-

Click on the options shown to show how these options are supposed to be used.

- -
- -

All of the individual options are explained here:

- - - - - - - - - - - - - - - - - - - - - - - - - -
nametypedefaultdescription
widthString'100%'the width of the canvas. Can be in percentages or pixels (ie. '400px').
heightString'100%'the height of the canvas. Can be in percentages or pixels (ie. '400px').
autoResizeBooleantrueIf true, the Network will automatically detect when its container is resized, and redraw itself - accordingly. If false, the Network can be forced to repaint after its container has been resized - using the function redraw() and setSize().
- -

Methods

- -

This is a list of all the methods in the public API. Options can be set directly to the module or you can use the - setOptions method of the network itself and use the module name as an object name.

- - - - - - - - - - - - - - - - - - - - - -
namereturnsdescription
setSize(
   String width,
   String - height
) -
noneSet the size of the canvas. This is automatically done on a window resize.
canvasToDOM({
   x: Number,
   y: - Number
}) -
ObjectThis function converts canvas coordinates to coordinates on the DOM. Input and output are in the form of - {x:Number,y:Number}. The DOM values are relative to the network container. -
DOMtoCanvas({
   x: Number,
   y: - Number
}) -
ObjectThis function converts DOM coordinates to coordinates on the canvas. Input and output are in the form of - {x:Number,y:Number}. The DOM values are relative to the network container. -
- -

Events

- -

This is a list of all the events in the public API. They are collected here from all individual modules.

- - - - - - - - - - - - -
namepropertiesdescription
resize -
-{
-  width: Number     // the new width  of the canvas
-  height: Number    // the new height of the canvas
-  oldWidth: Number  // the old width  of the canvas
-  oldHeight: Number // the old height of the canvas
-}
-
-
    -
-
Fired when the size of the canvas has been resized, either by a redraw call when the container div has - changed in size, a setSize() call with new values or a setOptions() with new width and/or height values. -
- -
-
-
-
-
-
-
-
- - - - - - - \ No newline at end of file diff --git a/docs/old/old_network/clustering.html b/docs/old/old_network/clustering.html deleted file mode 100644 index cb355f7f..00000000 --- a/docs/old/old_network/clustering.html +++ /dev/null @@ -1,182 +0,0 @@ - - - - - - - - - vis.js - A dynamic, browser based visualization library. - - - - - - - - - - - - - - - - - - - - - - - -
-

Network - clustering

-

Handles the HTML part of the canvas.

- -

Options

-

Clustering has no options, everything is done with methods.

- - -

Methods

-

This is a list of all the methods in the public API. Options can be set directly to the module or you can use the setOptions method of the network itself and use the module name as an object name.

- - - - - - - - - - -
namereturnsdescription
findNode(
-   String nodeId
)
Array Nodes can be in clusters. Clusters can also be in clusters. This function returns and array of nodeIds showing where the node is. Example:
- cluster 'A' contains cluster 'B',
- cluster 'B' contains cluster 'C',
- cluster 'C' contains node 'fred'.
- network.clustering.findNode('fred') will return ['A','B','C','fred']. -
isCluster(
-   String nodeId
)
Boolean Returns true if the node whose ID has been supplied is a cluster.
openCluster(
   - String nodeId
)
none Opens the cluster, releases the contained nodes and edges, removing the cluster node and cluster edges.
cluster(
   - Object options
)
none The options object is explained in full below. The joinCondition function is presented with all nodes.
clusterByConnection(
-   String nodeId,
-   [Object options]
- )
none This method looks at the provided node and makes a cluster of it and all it's connected nodes. The behaviour can be customized by proving the options object. All options of this object are explained below. The joinCondition is only presented with the connected nodes.
clusterByHubsize(
-   Number hubsize,
-   [Object options]
)
none This method checks all nodes in the network and those with a equal or higher amount of edges than specified with the hubsize qualify. Cluster by connection is performed on each of them. The options object is described for clusterByConnection and does the same here.
clusterOutliers(
-   [Object options]
)
none This method will cluster all nodes with 1 edge with their respective connected node.
-
-

Cluster options object

-

The options object supplied to the cluster functions can contain these properties:

- - - - - - - -
nameTypedescription
joinCondition(
  Object nodeOptions
)
FunctionOptional for all but the cluster method. The cluster module loops over all nodes that are selected to be in the cluster and calls this function with their data as argument. - If this function returns true, this node will be added to the cluster. You have access to all options (including the default) - as well as any custom fields you may have added to the node to determine whether or not to include it in the cluster. Example: -
-var nodes = [
-  {id: 4, label: 'Node 4'},
-  {id: 5, label: 'Node 5'},
-  {id: 6, label: 'Node 6', cid:1},
-  {id: 7, label: 'Node 7', cid:1}
-]
-
-var options = {
-  joinCondition:function(nodeOptions) {
-    return nodeOptions.cid === 1;
-  }
-}
-
-network.clustering.cluster(options);
-
processProperties(
  Object nodeOptions
)
Function Optional. Before creating the new cluster node, this (optional) function will be called with the properties supplied by you (clusterNodeProperties), all contained nodes and all contained edges. You can use this to update the - properties of the cluster based on which items it contains. The function should return the properties to create the cluster node. In the example below, we ensure preservation of mass and value when forming the cluster: -
-var options = {
-  processProperties: function (clusterOptions, childNodes, childEdges) {
-    var totalMass = 0;
-    var totalValue = 0;
-    for (var i = 0; i < childNodes.length; i++) {
-        totalMass += childNodes[i].mass;
-        totalValue = childNodes[i].value ? totalValue + childNodes[i].value : totalValue;
-    }
-    clusterOptions.mass = totalMass;
-    if (totalValue > 0) {
-      clusterOptions.value = totalValue;
-    }
-    return clusterOptions;
-  },
-}
-
clusterNodeProperties Object Optional. This is an object containing the options for the cluster node. All options described in the nodes module are allowed. This allows you to style your cluster node any way you want. This is also the style object that is provided in the processProperties function for fine tuning. If undefined, default node options will be used.
clusterEdgeProperties Object Optional. This is an object containing the options for the edges connected to the cluster. All options described in the edges module are allowed. Using this, you can style the edges connecting to the cluster any way you want. If none are provided, the optoins from the edges that are replaced are used. If undefined, default edge options will be used.
-

- -

- -

-

Events

-

The clustering module does not have any events.

- -
-
-
-
-
-
-
-
- - - - - - - \ No newline at end of file diff --git a/docs/old/old_network/rendering.html b/docs/old/old_network/rendering.html deleted file mode 100644 index 15b285ca..00000000 --- a/docs/old/old_network/rendering.html +++ /dev/null @@ -1,127 +0,0 @@ - - - - - - - - - vis.js - A dynamic, browser based visualization library. - - - - - - - - - - - - - - - - - - - - - - - - -
-

Network - rendering

-

Handles the rendering aspect of vis. It governs the render loop, it draws the nodes and edges and provides events to allow users to hook into the drawing.

- -

Options

-

The options for the rendering have to be contained in an object titled 'rendering'.

-

Click on the options shown to show how these options are supposed to be used.

- -
- -

All of the individual options are explained here:

- - - - -
nametypedefaultdescription
hideEdgesOnDragBooleanfalseWhen true, the edges are not drawn when dragging the view. This can greatly speed up responsiveness on dragging, improving user experience.
hideNodesOnDragBooleanfalseWhen true, the nodes are not drawn when dragging the view. This can greatly speed up responsiveness on dragging, improving user experience.
- -

Methods

-

This is a list of all the methods in the public API. Options can be set directly to the module or you can use the setOptions method of the network itself and use the module name as an object name.

- - - -
namereturnsdescription
redraw()noneRedraw the network.
- -

Events

-

These events are fired by the renderer and can be used to move and draw custom elements on the same canvas as the rest of the network.

- - - - - -
namepropertiesdescription
initRedrawnoneFired before the redrawing begins. The simulation step has completed at this point. Can be used to move custom elements before starting drawing the new frame.
beforeDrawingcanvas contextFired after the canvas has been cleared, scaled and translated to the viewing position but before all edges and nodes are drawn. Can be used to draw behind the network.
initRedrawcanvas contextFired after drawing on the canvas has been completed. Can be used to draw on top of the network.
- -
-
-
-
-
-
-
-
- - - - - - - \ No newline at end of file diff --git a/docs/old/old_network/selection.html b/docs/old/old_network/selection.html deleted file mode 100644 index d1c45de6..00000000 --- a/docs/old/old_network/selection.html +++ /dev/null @@ -1,135 +0,0 @@ - - - - - - - - - - vis.js - A dynamic, browser based visualization library. - - - - - - - - - - - - - - - - - - - - - - - - -
-

Network - selection

-

Handles the selection of nodes and edges.

- -

Options

-

The options for the selection have to be contained in an object titled 'selection'.

-

Click on the options shown to show how these options are supposed to be used.

- -
- -

All of the individual options are explained here:

- - - - -
nametypedefaultdescription
selectable BooleantrueWhen true, the nodes and edges can be selected by the user.
selectConnectedEdges BooleantrueWhen true, on selecting a node, its connecting edges are highlighted.
- -

Methods

-

This is a list of all the methods in the public API. Options can be set directly to the module or you can use the setOptions method of the network itself and use the module name as an object name.

- - - - - - - - - - - -
namereturnsdescription
getSelection() -
-{
-  nodes: [Array of selected nodeIds],
-  edges: [Array of selected edgeIds]
-}
Returns an object with selected nodes and edges ids.
getSelectedNodes() [nodeId1, nodeId2, ..]Returns an array of selected node ids.
getSelectedEdges() [edgeId1, edgeId2, ..]Returns an array of selected edge ids.
getNodeAt(
   {x: xPosition DOM,
   y: yPosition DOM}

)
nodeIdReturns a nodeId or undefined. The DOM positions are expected to be in pixels from the top left corner of the canvas.
getEdgeAt(
   {x: xPosition DOM,
   y: yPosition DOM}

)
edgeIdReturns a edgeId or undefined. The DOM positions are expected to be in pixels from the top left corner of the canvas..
selectNodes(
   Array with nodeIds,
   [Boolean highlightEdges]
)
noneSelects the nodes corresponding to the id's in the input array. If highlightEdges is true or undefined, the neighbouring edges will also be selected. This method unselects all other objects before selecting its own objects. Does not fire events.
selectEdges(
   Array with edgeIds
)
noneSelects the edges corresponding to the id's in the input array. This method unselects all other objects before selecting its own objects. Does not fire events.
unselectAll() none Unselect all objects. Does not fire events.
- -

Events

-

The selection handler does not fire events. All related events are fired by the interaction module because they are triggered by user interaction.

- -
-
-
-
-
-
-
-
- - - - - - - \ No newline at end of file diff --git a/docs/old/old_network/view.html b/docs/old/old_network/view.html deleted file mode 100644 index d038923f..00000000 --- a/docs/old/old_network/view.html +++ /dev/null @@ -1,161 +0,0 @@ - - - - - - - - - vis.js - A dynamic, browser based visualization library. - - - - - - - - - - - - - - - - - - - - - - - - -
-

Network - view

-

Acts as the camera that looks on the canvas. Does the animation, zooming and focusing.

- -

Options

-

The view has no options.

- -

Methods

-

This is a list of all the methods in the public API. Options can be set directly to the module or you can use the setOptions method of the network itself and use the module name as an object name.

- - - - - - - - - - - - - - -
namereturnsdescription
getScale() NumberReturns the current scale of the network. 1.0 is comparible to 100%, 0 is zoomed out infinitely.
getPosition() NumberReturns the current central focus point of the camera.
fit([Object options])noneZooms out so all nodes fit on the canvas. You can supply options to customize this: -
-{
-  nodes:[Array of nodeIds],
-  animation: { // -------------------> can be a boolean too!
-    duration: Number
-    easingFunction: String
-  }
-}
-
- The nodes can be used to zoom to fit only specific nodes in the view.

- The other options are explained in the moveTo() description below. - All options are optional for the fit method. -
focus(
-    String nodeId,
-    [Object options]
)
noneYou can focus on a node with this function. What that means is the view will lock onto that node, if it is moving, the view will also move accordingly. If the view is dragged by the user, the focus is broken. - You can supply options to customize the effect: -
-{
-  scale: Number,
-  offset: {x:Number, y:Number}
-  locked: boolean
-  animation: { // -------------------> can be a boolean too!
-    duration: Number
-    easingFunction: String
-  }
-}
-
- All options except for locked are explained in the moveTo() description below. Locked denotes whether or not the view remains locked to the node once the zoom-in animation is finished. Default value is true. The options object is optional in the focus method.
moveTo(Object options) noneYou can animate or move the camera using the moveTo method. Options are: -
-{
-  position: {x:Number, y:Number},
-  scale: Number,
-  offset: {x:Number, y:Number}
-  animation: { // -------------------> can be a boolean too!
-    duration: Number
-    easingFunction: String
-  }
-}
-
- The position (in canvas units!) is the position of the central focus point of the camera.

- The scale is the target zoomlevel. Default value is 1.0.

- The offset (in DOM units) is how many pixels from the center the view is focussed. Default value is {x:0,y:0}.

- For animation you can either use a Boolean to use it with the default options or disable it or you can define the duration (in milliseconds) and easing function manually. Available are: - linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint.

- You will have to define at least a scale or a position. Otherwise, there is nothing to move to. -
releaseNode()noneProgramatically release the focussed node.
- -

Events

-

These events are fired by the renderer and can be used to move and draw custom elements on the same canvas as the rest of the network.

- - - -
namepropertiesdescription
animationFinishednoneFired when an animation is finished.
- -
-
-
-
-
-
-
-
- - - - - - - - diff --git a/docs/old/old_timeline.html b/docs/old/old_timeline.html deleted file mode 100644 index a7013b53..00000000 --- a/docs/old/old_timeline.html +++ /dev/null @@ -1,1510 +0,0 @@ - - - - vis.js | timeline documentation - - - - - - - - -
- -

Timeline documentation

- -

Overview

-

- The Timeline is an interactive visualization chart to visualize data in time. - The data items can take place on a single date, or have a start and end date (a range). - You can freely move and zoom in the timeline by dragging and scrolling in the - Timeline. Items can be created, edited, and deleted in the timeline. - The time scale on the axis is adjusted automatically, and supports scales ranging - from milliseconds to years. -

-

- Timeline uses regular HTML DOM to render the timeline and items put on the - timeline. This allows for flexible customization using css styling. -

- -

Contents

- - -

Example

-

- The following code shows how to create a Timeline and provide it with data. - More examples can be found in the examples directory. -

- -
<!DOCTYPE HTML>
-<html>
-<head>
-  <title>Timeline | Basic demo</title>
-
-  <style type="text/css">
-    body, html {
-      font-family: sans-serif;
-    }
-  </style>
-
-  <script src="../../dist/vis.js"></script>
-  <link href="../../dist/vis.css" rel="stylesheet" type="text/css" />
-</head>
-<body>
-<div id="visualization"></div>
-
-<script type="text/javascript">
-  // DOM element where the Timeline will be attached
-  var container = document.getElementById('visualization');
-
-  // Create a DataSet (allows two way data-binding)
-  var items = new vis.DataSet([
-    {id: 1, content: 'item 1', start: '2013-04-20'},
-    {id: 2, content: 'item 2', start: '2013-04-14'},
-    {id: 3, content: 'item 3', start: '2013-04-18'},
-    {id: 4, content: 'item 4', start: '2013-04-16', end: '2013-04-19'},
-    {id: 5, content: 'item 5', start: '2013-04-25'},
-    {id: 6, content: 'item 6', start: '2013-04-27'}
-  ]);
-
-  // Configuration for the Timeline
-  var options = {};
-
-  // Create a Timeline
-  var timeline = new vis.Timeline(container, items, options);
-</script>
-</body>
-</html>
-
- - -

Loading

-

- Install or download the vis.js library. - in a subfolder of your project. Include the libraries script and css files in the - head of your html code: -

- -
-<script src="vis/dist/vis.js"></script>
-<link href="vis/dist/vis.css" rel="stylesheet" type="text/css" />
-
- -The constructor of the Timeline is vis.Timeline -
var timeline = new vis.Timeline(container, items, options);
-or when using groups: -
var timeline = new vis.Timeline(container, items, groups, options);
- -The constructor accepts four parameters: -
    -
  • - container is the DOM element in which to create the timeline. -
  • -
  • - items is an Array containing items. The properties of an - item are described in section Data Format, items. -
  • - groups is an Array containing groups. The properties of a - group are described in section Data Format, groups. -
  • -
  • - options is an optional Object containing a name-value map - with options. Options can also be set using the method - setOptions. -
  • -
- -

Data Format

- -

- The timeline can be provided with two types of data: -

-
    -
  • Items containing a set of items to be displayed in time.
  • -
  • Groups containing a set of groups used to group items - together.
  • -
- -

Items

-

- The Timeline uses regular Arrays and Objects as data format. - Data items can contain the properties start, - end (optional), content, - group (optional), className (optional), - and style (optional). -

- -

- A table is constructed as: -

- -
-var items = [
-  {
-    start: new Date(2010, 7, 15),
-    end: new Date(2010, 8, 2),  // end is optional
-    content: 'Trajectory A'
-    // Optional: fields 'id', 'type', 'group', 'className', 'style'
-  }
-  // more items...
-]);
-
- -

- The item properties are defined as: -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeRequiredDescription
classNameStringnoThis field is optional. A className can be used to give items - an individual css style. For example, when an item has className - 'red', one can define a css style like: -
-.vis.timeline .red {
-  color: white;
-  background-color: red;
-  border-color: darkred;
-}
- More details on how to style items can be found in the section - Styles. -
contentStringyesThe contents of the item. This can be plain text or html code.
endDate | number | string | MomentnoThe end date of the item. The end date is optional, and can be left null. - If end date is provided, the item is displayed as a range. - If not, the item is displayed as a box.
groupany typenoThis field is optional. When the group column is provided, - all items with the same group are placed on one line. - A vertical axis is displayed showing the groups. - Grouping items can be useful for example when showing availability of multiple - people, rooms, or other resources next to each other.
-
idString | NumbernoAn id for the item. Using an id is not required but highly - recommended. An id is needed when dynamically adding, updating, - and removing items in a DataSet.
startDate | number | string | MomentyesThe start date of the item, for example new Date(2010,9,23).
styleStringno - A css text string to apply custom styling for an individual item, for - example "color: red; background-color: pink;". -
subgroupString | NumbernoneThe id of a subgroup. - Groups all items within a group per subgroup, and positions them on the - same height instead of staking them on top of each other. can be ordered - by specifying the option subgroupOrder of a group. -
titleStringnoneAdd a title for the item, displayed when holding the mouse on the item. - The title can only contain plain text. -
typeString'box'The type of the item. Can be 'box' (default), 'point', 'range', or 'background'. - Types 'box' and 'point' need a start date, the types 'range' and 'background' needs both a start and end date. -
- -

Groups

-

- Like the items, groups are regular JavaScript Arrays and Objects. - Using groups, items can be grouped together. - Items are filtered per group, and displayed as - - Group items can contain the properties id, - content, and className (optional). -

-

- Groups can be applied to a timeline using the method setGroups or supplied in the constructor. - A table with groups can be created like: -

- -
-var groups = [
-  {
-    id: 1,
-    content: 'Group 1'
-    // Optional: a field 'className', 'style'
-  }
-  // more groups...
-]);
-
- - -

- Groups can have the following properties: -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeRequiredDescription
classNameStringnoThis field is optional. A className can be used to give groups - an individual css style. For example, when a group has className - 'red', one can define a css style - - .red { - color: red; - } - . - More details on how to style groups can be found in the section - Styles. -
contentStringyesThe contents of the group. This can be plain text or html code.
idString | NumberyesAn id for the group. The group will display all items having a - property group which matches the id - of the group.
styleStringno - A css text string to apply custom styling for an individual group label, for - example "color: red; background-color: pink;". -
subgroupOrderString | FunctionnoneOrder the subgroups by a field name or custom sort function. - By default, groups are ordered by first-come, first-show. -
titleStringnoneA title for the group, displayed when holding the mouse on the groups label. - The title can only contain plain text. -
- - - -

Configuration Options

- -

- Options can be used to customize the timeline. - Options are defined as a JSON object. All options are optional. -

- -
-var options = {
-  width: '100%',
-  height: '30px',
-  margin: {
-    item: 20
-  }
-};
-
- -

- The following options are available. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDefaultDescription
alignString"center"Alignment of items with type 'box', 'range', and 'background'. Available values are 'auto' (default), 'center', 'left', or 'right'. For 'box' items, the 'auto' alignment is 'center'. For 'range' items, the auto alignment is dynamic: positioned left and shifted such that the contents is always visible on screen.
autoResizebooleantrueIf true, the Timeline will automatically detect when its container is resized, and redraw itself accordingly. If false, the Timeline can be forced to repaint after its container has been resized using the function redraw().
clickToUsebooleanfalseWhen a Timeline is configured to be clickToUse, it will react to mouse and touch events only when active. - When active, a blue shadow border is displayed around the Timeline. The Timeline is set active by clicking on it, and is changed to inactive again by clicking outside the Timeline or by pressing the ESC key.
dataAttributesArray[String] | 'all'falseAn array of fields optionally defined on the timeline items that will be appended as data- attributes to the DOM element of the items.
- If value is 'all' then each field defined on the timeline item will become a data- attribute.
editableBoolean | ObjectfalseIf true, the items in the timeline can be manipulated. Only applicable when option selectable is true. See also the callbacks onAdd, onUpdate, onMove, and onRemove. When editable is an object, one can enable or disable individual manipulation actions. - See section Editing Items for a detailed explanation. -
editable.addBooleanfalseIf true, new items can be created by double tapping an empty space in the Timeline. See section Editing Items for a detailed explanation.
editable.removeBooleanfalseIf true, items can be deleted by first selecting them, and then clicking the delete button on the top right of the item. See section Editing Items for a detailed explanation.
editable.updateGroupBooleanfalseIf true, items can be dragged from one group to another. Only applicable when the Timeline has groups. See section Editing Items for a detailed explanation.
editable.updateTimeBooleanfalseIf true, items can be dragged to another moment in time. See section Editing Items for a detailed explanation.
endDate | Number | String | MomentnoneThe initial end date for the axis of the timeline. - If not provided, the latest date present in the items set is taken as - end date.
formatObjectnone - Apply custom date formatting of the labels on the time axis. The default value of format is: -
{
-  minorLabels: {
-    millisecond:'SSS',
-    second:     's',
-    minute:     'HH:mm',
-    hour:       'HH:mm',
-    weekday:    'ddd D',
-    day:        'D',
-    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',
-    month:      'YYYY',
-    year:       ''
-  }
-}
- For values which not provided in the customized options.format, the default values will be used. - All available formatting syntax is described in the docs of moment.js. -
groupOrderString | FunctionnoneOrder the groups by a field name or custom sort function. - By default, groups are not ordered. -
heightNumber | StringnoneThe height of the timeline in pixels or as a percentage. - When height is undefined or null, the height of the timeline is automatically - adjusted to fit the contents. - It is possible to set a maximum height using option maxHeight - to prevent the timeline from getting too high in case of automatically - calculated height. -
hiddenDatesObjectnoneThis option allows you to hide specific timespans from the time axis. The dates can be supplied as an object: - {start: '2014-03-21 00:00:00', end: '2014-03-28 00:00:00', [repeat:'daily']} or as an Array of these objects. The repeat argument is optional. - The possible values are (case-sensitive): daily, weekly, monthly, yearly. To hide a weekend, pick any Saturday as start and the following Monday as end - and set repeat to weekly. -
localeStringnoneSelect a locale for the Timeline. See section Localization for more information.
localesObjectnoneA map with i18n locales. See section Localization for more information.
marginNumber | ObjectObjectWhen a number, applies the margin to margin.axis, margin.item.horizontal, and margin.item.vertical.
margin.axisNumber20The minimal margin in pixels between items and the time axis.
margin.itemNumber10The minimal margin in pixels between items in both horizontal and vertical direction.
margin.item.horizontalNumber10The minimal horizontal margin in pixels between items.
margin.item.verticalNumber10The minimal vertical margin in pixels between items.
maxDate | Number | String | MomentnoneSet a maximum Date for the visible range. - It will not be possible to move beyond this maximum. -
maxHeightNumber | StringnoneSpecifies the maximum height for the Timeline. Can be a number in pixels or a string like "300px".
minDate | Number | String | MomentnoneSet a minimum Date for the visible range. - It will not be possible to move beyond this minimum. -
minHeightNumber | StringnoneSpecifies the minimum height for the Timeline. Can be a number in pixels or a string like "300px".
moveableBooleantrue - Specifies whether the Timeline can be moved and zoomed by dragging the window. - See also option zoomable. -
onAddFunctionnoneCallback function triggered when an item is about to be added: when the user double taps an empty space in the Timeline. See section Editing Items for more information. Only applicable when both options selectable and editable.add are set true. -
onUpdateFunctionnoneCallback function triggered when an item is about to be updated, when the user double taps an item in the Timeline. See section Editing Items for more information. Only applicable when both options selectable and editable.updateTime or editable.updateGroup are set true. -
onMoveFunctionnoneCallback function triggered when an item has been moved: after the user has dragged the item to an other position. See section Editing Items for more information. Only applicable when both options selectable and editable.updateTime or editable.updateGroup are set true. -
onMovingFunctionnoneCallback function triggered repeatedly when an item is being moved. See section Editing Items for more information. Only applicable when both options selectable and editable.updateTime or editable.updateGroup are set true. -
onRemoveFunctionnoneCallback function triggered when an item is about to be removed: when the user tapped the delete button on the top right of a selected item. See section Editing Items for more information. Only applicable when both options selectable and editable.remove are set true. -
orderFunctionnone -

Provide a custom sort function to order the items. The order of the - items is determining the way they are stacked. The function - order is called with two arguments containing the data of two items to be - compared. -

-

WARNING: Use with caution. Custom ordering is not suitable for large amounts of items. On load, the Timeline will render all items once to determine their width and height. Keep the number of items in this configuration limited to a maximum of a few hundred items.

-
orientationString | Object'bottom'Orientation of the timelines axis and items. When orientation is a string, the value is applied to both items and axis. Can be 'top', 'bottom' (default), or 'both'.
orientation.axisString'bottom'Orientation of the timeline axis: 'top', 'bottom' (default), or 'both'. If orientation is 'bottom', the time axis is drawn at the bottom. When 'top', the axis is drawn on top. When 'both', two axes are drawn, both on top and at the bottom.
orientation.itemString'bottom'Orientation of the timeline items: 'top' or 'bottom' (default). Determines whether items are aligned to the top or bottom of the Timeline.
selectableBooleantrueIf true, the items on the timeline can be selected. Multiple items can be selected by long pressing them, or by using ctrl+click or shift+click. The event select is fired each time the selection has changed (see section Events).
showCurrentTimebooleantrueShow a vertical bar at the current time.
showMajorLabelsbooleantrueBy default, the timeline shows both minor and major date labels on the - time axis. - For example the minor labels show minutes and the major labels show hours. - When showMajorLabels is false, no major labels - are shown.
showMinorLabelsbooleantrueBy default, the timeline shows both minor and major date labels on the - time axis. - For example the minor labels show minutes and the major labels show hours. - When showMinorLabels is false, no minor labels - are shown. When both showMajorLabels and - showMinorLabels are false, no horizontal axis will be - visible.
stackBooleantrueIf true (default), items will be stacked on top of each other such that they do not overlap.
snapfunction | nullfunctionWhen moving items on the Timeline, they will be snapped to nice dates like full hours or days, depending on the current scale. The snap function can be replaced with a custom function, or can be set to null to disable snapping. The signature of the snap function is: -
function snap(date: Date, scale: string, step: number) : Date | number
- The parameter scale can be can be 'millisecond', 'second', 'minute', 'hour', 'weekday, 'day, 'month, or 'year'. The parameter step is a number like 1, 2, 4, 5. -
startDate | Number | String | MomentnoneThe initial start date for the axis of the timeline. - If not provided, the earliest date present in the events is taken as start date.
templateFunctionnoneA template function used to generate the contents of the items. The function is called by the Timeline with an items data as argument, and must return HTML code as result. When the option template is specified, the items do not need to have a field content. See section Templates for a detailed explanation.
timeAxis.scalestringnoneSet a fixed scale for the time axis of the Timeline. Choose from 'millisecond', 'second', 'minute', 'hour', 'weekday', 'day', 'month', 'year'. Example usage: -
var options = {
-  timeAxis: {scale: 'minute', step: 5}
-}
-
timeAxis.stepnumber1 - Set a fixed step size for the time axis. Only applicable when used together with timeAxis.scale. - Choose for example 1, 2, 5, or 10.
typeStringnoneSpecifies the default type for the timeline items. Choose from 'box', 'point', 'range', and 'background'. Note that individual items can override this default type. If undefined, the Timeline will auto detect the type from the items data: if a start and end date is available, a 'range' will be created, and else, a 'box' is created. Items of type 'background' are not editable. -
widthString'100%'The width of the timeline in pixels or as a percentage.
zoomableBooleantrue - Specifies whether the Timeline can be zoomed by pinching or scrolling in the window. - Only applicable when option moveable is set true. -
zoomMaxNumber315360000000000Set a maximum zoom interval for the visible range in milliseconds. - It will not be possible to zoom out further than this maximum. - Default value equals about 10000 years. -
zoomMinNumber10Set a minimum zoom interval for the visible range in milliseconds. - It will not be possible to zoom in further than this minimum. -
- -

Methods

-

- The Timeline supports the following methods. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MethodReturn TypeDescription
addCustomTime([time] [, id])Number | String - Add new vertical bar representing a custom time that can be dragged by the user. - Parameter time can be a Date, Number, or String, and is new Date() by default. - Parameter id can be Number or String and is undefined by default.
- Returns id of the created bar. -
destroy()noneDestroy the Timeline. The timeline is removed from memory. all DOM elements and event listeners are cleaned up. -
fit([options])noneAdjust the visible window such that it fits all items. See also function focus(id). - Available options: -
    -
  • animation: boolean | {duration: number, easingFunction: string}
    If true (default) or an Object, 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'. Available easing functions: "linear", "easeInQuad", "easeOutQuad", "easeInOutQuad", "easeInCubic", "easeOutCubic", "easeInOutCubic", "easeInQuart", "easeOutQuart", "easeInOutQuart", "easeInQuint", "easeOutQuint", "easeInOutQuint". -
  • -
-
focus(id | ids [, options])noneAdjust the visible window such that the selected item (or multiple items) are centered on screen. See also function fit(). Available options: -
    -
  • animation: boolean | {duration: number, easingFunction: string}
    If true (default) or an Object, 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'. Available easing functions: "linear", "easeInQuad", "easeOutQuad", "easeInOutQuad", "easeInCubic", "easeOutCubic", "easeInOutCubic", "easeInQuart", "easeOutQuart", "easeInOutQuart", "easeInQuint", "easeOutQuint", "easeInOutQuint".
  • -
-
getCurrentTime()DateGet the current time. Only applicable when option showCurrentTime is true. -
getCustomTime([id])DateRetrieve the custom time from the custom time bar with given id. Id is undefined by default. -
getEventProperties(event)Object - Returns an Object with relevant properties from an event: -
    -
  • group (Number | null): the id of the clicked group.
  • -
  • item (Number | null): the id of the clicked item.
  • -
  • pageX (Number): absolute horizontal position of the click event.
  • -
  • pageY (Number): absolute vertical position of the click event.
  • -
  • x (Number): relative horizontal position of the click event.
  • -
  • y (Number): relative vertical position of the click event.
  • -
  • time (Date): Date of the clicked event.
  • -
  • snappedTime (Date): Date of the clicked event, snapped to a nice value.
  • -
  • what (String | null): name of the clicked thing: item, background, axis, group-label, custom-time, or current-time.
  • -
  • event (Object): the original click event.
  • -
-
getSelection()Number[]Get an array with the ids of the currently selected items.
getVisibleItems()Number[]Get an array with the ids of the currently visible items.
getWindow()ObjectGet the current visible window. Returns an object with properties start: Date and end: Date.
moveTo(time [, options])noneMove the window such that given time is centered on screen. Parameter time can be a Date, Number, or String. Available options: -
    -
  • animation: boolean | {duration: number, easingFunction: string}
    If true (default) or an Object, 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'. Available easing functions: "linear", "easeInQuad", "easeOutQuad", "easeInOutQuad", "easeInCubic", "easeOutCubic", "easeInOutCubic", "easeInQuart", "easeOutQuart", "easeInOutQuart", "easeInQuint", "easeOutQuint", "easeInOutQuint".
  • -
-
on(event, callback)noneCreate an event listener. The callback function is invoked every time the event is triggered. Avialable events: rangechange, rangechanged, select. The callback function is invoked as callback(properties), where properties is an object containing event specific properties. See section Events for more information.
off(event, callback)noneRemove an event listener created before via function on(event, callback). See section Events for more information.
redraw()noneForce a redraw of the Timeline. The size of all items will be recalculated. - Can be useful to manually redraw when option autoResize=false and the window - has been resized, or when the items CSS has been changed. -
removeCustomTime(id)none - Remove vertical bars previously added to the timeline via addCustomTime method. Parameter id is the ID of the custom vertical bar returned by addCustomTime method. -
setCurrentTime(time)noneSet a current time. This can be used for example to ensure that a client's time is synchronized with a shared server time. - time can be a Date object, numeric timestamp, or ISO date string. - Only applicable when option showCurrentTime is true.
setCustomTime(time [, id])noneAdjust the time of a custom time bar. - Parameter time can be a Date object, numeric timestamp, or ISO date string. - Parameter id is the idof the custom time bar, and is undefined by default. -
setData({
  groups: groups,
  items: items
})
noneSet both groups and items at once. Both properties are optional. This is a convenience method for individually calling both setItems(items) and setGroups(groups). - Both items and groups can be an Array with Objects, - a DataSet, or a DataView. For each of the groups, the items of the - timeline are filtered on the property group, which - must correspond with the id of the group. -
setGroups(groups)noneSet a data set with groups for the Timeline. - groups can be an Array with Objects, - a DataSet, or a DataView. For each of the groups, the items of the - timeline are filtered on the property group, which - must correspond with the id of the group. -
setItems(items)noneSet a data set with items for the Timeline. - items can be an Array with Objects, - a DataSet, or a DataView. -
setOptions(options)noneSet or update options. It is possible to change any option of the timeline at any time. You can for example switch orientation on the fly. -
setSelection(id | ids [, options])noneSelect one or multiple items by their id. The currently selected items will be unselected. To unselect all selected items, call `setSelection([])`. Available options: -
    -
  • focus: boolean
    If true, focus will be set to the selected item(s)
  • -
  • animation: boolean | {duration: number, easingFunction: string}
    If true (default) or an Object, 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'. Only applicable when option focus is true. Available easing functions: "linear", "easeInQuad", "easeOutQuad", "easeInOutQuad", "easeInCubic", "easeOutCubic", "easeInOutCubic", "easeInQuart", "easeOutQuart", "easeInOutQuart", "easeInQuint", "easeOutQuint", "easeInOutQuint".
  • -
-
setWindow(start, end [, options])noneSet the current visible window. The parameters start and end can be a Date, Number, or String. If the parameter value of start or end is null, the parameter will be left unchanged. Available options: -
    -
  • animation: boolean | {duration: number, easingFunction: string}
    If true (default) or an Object, 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'. Available easing functions: "linear", "easeInQuad", "easeOutQuad", "easeInOutQuad", "easeInCubic", "easeOutCubic", "easeInOutCubic", "easeInQuart", "easeOutQuart", "easeInOutQuart", "easeInQuint", "easeOutQuint", "easeInOutQuint".
  • -
-
- - - -

Events

-

- Timeline fires events when changing the visible window by dragging, when - selecting items, and when dragging the custom time bar. -

- -

- Here an example on how to listen for a select event. -

- -
-timeline.on('select', function (properties) {
-  alert('selected items: ' + properties.nodes);
-});
-
- -

- A listener can be removed via the function off: -

- -
-function onSelect (properties) {
-  alert('selected items: ' + properties.nodes);
-}
-
-// add event listener
-timeline.on('select', onSelect);
-
-// do stuff...
-
-// remove event listener
-timeline.off('select', onSelect);
-
- - -

- The following events are available. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
nameDescriptionProperties
clickFired when clicked inside the Timeline. - - Passes a properties object as returned by the method Timeline.getEventProperties(event). -
contextmenuFired when right-clicked inside the Timeline. Note that in order to prevent the context menu from showing up, default behavior of the event must be stopped: -
timeline.on('contextmenu', function (props) {
-  alert('Right click!');
-  props.event.preventDefault();
-});
-
-
- Passes a properties object as returned by the method Timeline.getEventProperties(event). -
doubleClickFired when double clicked inside the Timeline. - - Passes a properties object as returned by the method Timeline.getEventProperties(event). -
rangechangeFired repeatedly when the timeline window is being changed. - -
    -
  • start (Number): timestamp of the current start of the window.
  • -
  • end (Number): timestamp of the current end of the window.
  • -
  • byUser (Boolean): change happened because of user drag/zoom.
  • -
-
rangechangedFired once after the timeline window has been changed. - -
    -
  • start (Number): timestamp of the current start of the window.
  • -
  • end (Number): timestamp of the current end of the window.
  • -
  • byUser (Boolean): change happened because of user drag/zoom.
  • -
-
selectFired after the user selects or deselects items by tapping or holding them. - When a use taps an already selected item, the select event is fired again. - Not fired when the method setSelectionis executed. - -
    -
  • items: an array with the ids of the selected items
  • -
-
timechangeFired repeatedly when the user is dragging the custom time bar. - Only available when the custom time bar is enabled. - -
    -
  • id (Number | String): custom time bar id.
  • -
  • time (Date): the custom time.
  • -
-
timechangedFired once after the user has dragged the custom time bar. - Only available when the custom time bar is enabled. - -
    -
  • id (Number | String): custom time bar id.
  • -
  • time (Date): the custom time.
  • -
-
- -

Editing Items

-

- When the Timeline is configured to be editable (both options selectable and editable are true), the user can: -

-
    -
  • Select an item by clicking it, and use ctrl+click to or shift+click to select multiple items
  • -
  • Move selected items by dragging them.
  • -
  • Create a new item by double tapping on an empty space.
  • -
  • Create a new range item by dragging on an empty space with the ctrl key down.
  • -
  • Update an item by double tapping it.
  • -
  • Delete a selected item by clicking the delete button on the top right.
  • -
- -

Option editable accepts a boolean or an object. When editable is a boolean, all manipulation actions will be either enabled or disabled. When editable is an object, one can enable individual manipulation actions:

- -
// enable or disable all manipulation actions
-var options = {
-  editable: true       // true or false
-};
-
-// enable or disable individual manipulation actions
-var options = {
-  editable: {
-    add: true,         // add new items by double tapping
-    updateTime: true,  // drag items horizontally
-    updateGroup: true, // drag items from one group to another
-    remove: true       // delete an item by tapping the delete button top right
-  }
-};
- - -

- One can specify callback functions to validate changes made by the user. There are a number of callback functions for this purpose: -

- -
    -
  • onAdd(item, callback) Fired when a new item is about to be added. If not implemented, the item will be added with default text contents.
  • -
  • onUpdate(item, callback) 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.
  • -
  • onMove(item, callback) Fired when an item has been moved. If not implemented, the move action will be accepted.
  • -
  • onMoving(item, callback) Fired repeatedly while an item is being moved (dragged). Can be used to adjust the items start, end, and/or group to allowed regions.
  • -
  • onRemove(item, callback) Fired when an item is about to be deleted. If not implemented, the item will be always removed.
  • -
- -

- Each of the callbacks is invoked with two arguments: -

-
    -
  • item: the item being manipulated
  • -
  • callback: a callback function which must be invoked to report back. The callback must be invoked as callback(item | null). Here, item can contain changes to the passed item. Parameter `item` typically contains fields `content`, `start`, and optionally `end`. The type of `start` and `end` is determined by the DataSet type configuration and is `Date` by default. When invoked as callback(null), the action will be cancelled.
  • -
- -

- Example code: -

- -
var options = {
-  onUpdate: function (item, callback) {
-    item.content = prompt('Edit items text:', item.content);
-    if (item.content != null) {
-      callback(item); // send back adjusted item
-    }
-    else {
-      callback(null); // cancel updating the item
-    }
-  }
-};
-
- -A full example is available here: 08_edit_items.html. - - -

Templates

- -

- Timeline supports templates to format item contents. Any template engine (such as handlebars or mustache) can be used, and one can also manually build HTML. In the options, one can provide a template handler. This handler is a function accepting an items data as argument, and outputs formatted HTML: -

- -
var options = {
-  template: function (item) {
-    var html = ... // generate HTML markup for this item
-    return html;
-  }
-};
-
- -

Create HTML manually

- -The HTML for an item can be created manually: - -
var options = {
-  template: function (item) {
-    return '<h1>' + item.header + '</h1><p>' + item.description + '</p>';
-  }
-};
-
- -

Using a template engine

- -Using handlebars, one can write the template in HTML: - -
-<script id="item-template" type="text/x-handlebars-template">
-  <h1>{{header}}</h1>
-  <p>{{description}}</p>
-</script>
-
- -Compile the template: - -
-var source = document.getElementById('item-template').innerHTML;
-var template = Handlebars.compile(source);
-
- -And then specify the template in the Timeline options - -
var options = {
-  template: template
-};
-
- -

Multiple templates

- -In order to support multiple templates, the template handler can be extended to switch between different templates, depending on a specific item property: - -
-var templates = {
-  template1: Handlebars.compile(...),
-  template2: Handlebars.compile(...),
-  template2: Handlebars.compile(...),
-  ...
-};
-
-var options = {
-  template: function (item) {
-    var template = templates[item.template];  // choose the right template
-    return template(item);                    // execute the template
-  }
-};
-
- -Now the items can be extended with a property template, specifying which template to use for the item. - - -

Localization

-

- Timeline can be localized. For localization, Timeline depends largely on the localization of moment.js. Locales are not included in vis.js by default. To enable localization, moment.js must be loaded with locales. Moment.js offers a bundle named "moment-with-locales.min.js" for this and there are various alternative ways to load locales. -

- -

- To set a locale for the Timeline, specify the option locale: -

- -
var options = {
-  locale: 'nl'
-};
-
- -

Create a new locale

- -To load a locale into the Timeline not supported by default, one can add a new locale to the option locales: - -
var options = {
-  locales: {
-    // create a new locale (text strings should be replaced with localized strings)
-    mylocale: {
-      current: 'current',
-      time: 'time',
-    }
-  },
-
-  // use the new locale
-  locale: 'mylocale'
-};
-
- -

Available locales

- -

- Timeline comes with support for the following locales: -

- - - - - - - - - - - -
LanguageCode
English - en
- en_EN
- en_US -
Dutch - nl
- nl_NL
- nl_BE -
- - -

Styles

-

- All parts of the Timeline have a class name and a default css style. - The styles can be overwritten, which enables full customization of the layout - of the Timeline. -

- -

For example, to change the border and background color of all items, include the - following code inside the head of your html code or in a separate stylesheet.

-
<style>
-  .vis-item {
-    border-color: orange;
-    background-color: yellow;
-  }
-</style>
-
- -

Grid Backgrounds

-

- The background grid of the time axis can be styled, for example to highlight - weekends or to create grids with an alternating white/lightgray background. -

-

- Depending on the zoom level, the grids get certain css classes attached. - The following classes are available: -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Descriptionvalues
Alternating columnseven, odd
Current datetoday, tomorrow, yesterday, current-week, current-month, current-year
Hoursh0, h1, ..., h23
Grouped hoursh0-h4 to h20-h24
Weekdaymonday, tuesday, wednesday, thursday, friday, saturday, sunday
Daysdate1, date2, ..., date31
Monthsjanuari, februari, march, april, may, june, july, august, september, october, november, december
Yearsyear2014, year2015, ...
- -

Examples:

- -
<style>
-  /* alternating column backgrounds */
-  .vis-time-axis .grid.odd {
-    background: #f5f5f5;
-  }
-
-  /* gray background in weekends, white text color */
-  .vis-time-axis .vis-grid.saturday,
-  .vis-time-axis .vis-grid.sunday {
-    background: gray;
-  }
-  .vis-time-axis .vis-text.saturday,
-  .vis-time-axis .vis-text.sunday {
-    color: white;
-  }
-</style>
-
- - -

Data Policy

-

- All code and data is processed and rendered in the browser. - No data is sent to any server. -

- -
- - From f70982d0db6b18f8e0f794f3d9b4348d5cabad3e Mon Sep 17 00:00:00 2001 From: jos Date: Thu, 28 May 2015 15:46:29 +0200 Subject: [PATCH 07/11] Renamed example --- examples/network/data/{dynamic_data.html => dynamicData.html} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename examples/network/data/{dynamic_data.html => dynamicData.html} (100%) diff --git a/examples/network/data/dynamic_data.html b/examples/network/data/dynamicData.html similarity index 100% rename from examples/network/data/dynamic_data.html rename to examples/network/data/dynamicData.html From 62a844de3fd82a571dd07a045635f277e6635735 Mon Sep 17 00:00:00 2001 From: jos Date: Thu, 28 May 2015 16:52:22 +0200 Subject: [PATCH 08/11] Released version 4.1.0 --- HISTORY.md | 2 +- bower.json | 2 +- dist/vis.js | 66938 +++++++++++++++++++++++----------------------- dist/vis.map | 2 +- dist/vis.min.js | 38 +- package.json | 2 +- 6 files changed, 33492 insertions(+), 33492 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index d210f5b4..9ed7c690 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,7 +1,7 @@ # vis.js history http://visjs.org -## UNRELEASED, version 4.0.1 +## 2015-05-28, version 4.1.0 ### Network diff --git a/bower.json b/bower.json index 3de35e6c..4713737b 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "vis", - "version": "4.0.1-SNAPSHOT", + "version": "4.1.0", "main": ["dist/vis.min.js", "dist/vis.min.css"], "description": "A dynamic, browser-based visualization library.", "homepage": "http://visjs.org/", diff --git a/dist/vis.js b/dist/vis.js index 705e0546..fa8be5bd 100644 --- a/dist/vis.js +++ b/dist/vis.js @@ -4,7 +4,7 @@ * * A dynamic, browser-based visualization library. * - * @version 4.0.1-SNAPSHOT + * @version 4.1.0 * @date 2015-05-28 * * @license @@ -84,64 +84,64 @@ return /******/ (function(modules) { // webpackBootstrap // utils 'use strict'; - exports.util = __webpack_require__(2); - exports.DOMutil = __webpack_require__(3); + exports.util = __webpack_require__(7); + exports.DOMutil = __webpack_require__(13); // data - exports.DataSet = __webpack_require__(4); - exports.DataView = __webpack_require__(5); - exports.Queue = __webpack_require__(6); + exports.DataSet = __webpack_require__(14); + exports.DataView = __webpack_require__(16); + exports.Queue = __webpack_require__(15); // Graph3d - exports.Graph3d = __webpack_require__(7); + exports.Graph3d = __webpack_require__(17); exports.graph3d = { - Camera: __webpack_require__(8), - Filter: __webpack_require__(9), - Point2d: __webpack_require__(10), - Point3d: __webpack_require__(11), - Slider: __webpack_require__(12), - StepNumber: __webpack_require__(13) + Camera: __webpack_require__(21), + Filter: __webpack_require__(22), + Point2d: __webpack_require__(18), + Point3d: __webpack_require__(20), + Slider: __webpack_require__(23), + StepNumber: __webpack_require__(24) }; // Timeline - exports.Timeline = __webpack_require__(14); - exports.Graph2d = __webpack_require__(15); + exports.Timeline = __webpack_require__(25); + exports.Graph2d = __webpack_require__(49); exports.timeline = { - DateUtil: __webpack_require__(16), - DataStep: __webpack_require__(17), - Range: __webpack_require__(18), - stack: __webpack_require__(19), - TimeStep: __webpack_require__(20), + DateUtil: __webpack_require__(31), + DataStep: __webpack_require__(52), + Range: __webpack_require__(29), + stack: __webpack_require__(35), + TimeStep: __webpack_require__(37), components: { items: { - Item: __webpack_require__(21), - BackgroundItem: __webpack_require__(22), - BoxItem: __webpack_require__(57), - PointItem: __webpack_require__(23), - RangeItem: __webpack_require__(24) + Item: __webpack_require__(2), + BackgroundItem: __webpack_require__(40), + BoxItem: __webpack_require__(1), + PointItem: __webpack_require__(39), + RangeItem: __webpack_require__(36) }, - Component: __webpack_require__(25), + Component: __webpack_require__(27), CurrentTime: __webpack_require__(26), - CustomTime: __webpack_require__(27), - DataAxis: __webpack_require__(28), - GraphGroup: __webpack_require__(29), - Group: __webpack_require__(30), - BackgroundGroup: __webpack_require__(31), - ItemSet: __webpack_require__(32), - Legend: __webpack_require__(33), - LineGraph: __webpack_require__(34), - TimeAxis: __webpack_require__(35) + CustomTime: __webpack_require__(44), + DataAxis: __webpack_require__(51), + GraphGroup: __webpack_require__(53), + Group: __webpack_require__(34), + BackgroundGroup: __webpack_require__(38), + ItemSet: __webpack_require__(33), + Legend: __webpack_require__(57), + LineGraph: __webpack_require__(50), + TimeAxis: __webpack_require__(41) } }; // Network - exports.Network = __webpack_require__(36); + exports.Network = __webpack_require__(59); exports.network = { - Images: __webpack_require__(37), - dotparser: __webpack_require__(38), - gephiParser: __webpack_require__(39) + Images: __webpack_require__(112), + dotparser: __webpack_require__(110), + gephiParser: __webpack_require__(111) }; exports.network.convertDot = function (input) { return exports.network.dotparser.DOTToGraph(input); @@ -156,9 +156,9 @@ return /******/ (function(modules) { // webpackBootstrap }; // bundled external libraries - exports.moment = __webpack_require__(40); - exports.hammer = __webpack_require__(41); // TODO: deprecate exports.hammer some day - exports.Hammer = __webpack_require__(41); + exports.moment = __webpack_require__(8); + exports.hammer = __webpack_require__(3); // TODO: deprecate exports.hammer some day + exports.Hammer = __webpack_require__(3); /***/ }, /* 1 */ @@ -166,22217 +166,19434 @@ return /******/ (function(modules) { // webpackBootstrap 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var Item = __webpack_require__(2); + var util = __webpack_require__(7); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * @constructor BoxItem + * @extends Item + * @param {Object} data Object containing parameters start + * content, 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 BoxItem(data, conversion, options) { + this.props = { + dot: { + width: 0, + height: 0 + }, + line: { + width: 0, + height: 0 + } + }; - var _componentsPhysicsBarnesHutSolver = __webpack_require__(77); + // validate data + if (data) { + if (data.start == undefined) { + throw new Error('Property "start" missing in item ' + data); + } + } - var _componentsPhysicsBarnesHutSolver2 = _interopRequireDefault(_componentsPhysicsBarnesHutSolver); + Item.call(this, data, conversion, options); + } - var _componentsPhysicsRepulsionSolver = __webpack_require__(78); + BoxItem.prototype = new Item(null, null, null); - var _componentsPhysicsRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsRepulsionSolver); + /** + * Check whether this item is visible inside given range + * @returns {{start: Number, end: Number}} range with a timestamp for start and end + * @returns {boolean} True if visible + */ + BoxItem.prototype.isVisible = function (range) { + // determine visibility + // TODO: account for the real width of the item. Right now we just add 1/4 to the window + var interval = (range.end - range.start) / 4; + return this.data.start > range.start - interval && this.data.start < range.end + interval; + }; - var _componentsPhysicsHierarchicalRepulsionSolver = __webpack_require__(79); + /** + * Repaint the item + */ + BoxItem.prototype.redraw = function () { + var dom = this.dom; + if (!dom) { + // create DOM + this.dom = {}; + dom = this.dom; - var _componentsPhysicsHierarchicalRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsHierarchicalRepulsionSolver); + // create main box + dom.box = document.createElement('DIV'); - var _componentsPhysicsSpringSolver = __webpack_require__(80); + // contents box (inside the background box). used for making margins + dom.content = document.createElement('DIV'); + dom.content.className = 'vis-item-content'; + dom.box.appendChild(dom.content); - var _componentsPhysicsSpringSolver2 = _interopRequireDefault(_componentsPhysicsSpringSolver); + // line to axis + dom.line = document.createElement('DIV'); + dom.line.className = 'vis-line'; - var _componentsPhysicsHierarchicalSpringSolver = __webpack_require__(81); + // dot on axis + dom.dot = document.createElement('DIV'); + dom.dot.className = 'vis-dot'; - var _componentsPhysicsHierarchicalSpringSolver2 = _interopRequireDefault(_componentsPhysicsHierarchicalSpringSolver); + // attach this item as attribute + dom.box['timeline-item'] = this; - var _componentsPhysicsCentralGravitySolver = __webpack_require__(82); + this.dirty = true; + } - var _componentsPhysicsCentralGravitySolver2 = _interopRequireDefault(_componentsPhysicsCentralGravitySolver); + // append DOM to parent DOM + if (!this.parent) { + throw new Error('Cannot redraw item: no parent attached'); + } + if (!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(dom.box); + } + if (!dom.line.parentNode) { + var background = this.parent.dom.background; + if (!background) throw new Error('Cannot redraw item: parent has no background container element'); + background.appendChild(dom.line); + } + if (!dom.dot.parentNode) { + var axis = this.parent.dom.axis; + if (!background) throw new Error('Cannot redraw item: parent has no axis container element'); + axis.appendChild(dom.dot); + } + this.displayed = true; - var _componentsPhysicsFA2BasedRepulsionSolver = __webpack_require__(83); + // Update DOM when item is marked dirty. 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._updateTitle(this.dom.box); + this._updateDataAttributes(this.dom.box); + this._updateStyle(this.dom.box); - var _componentsPhysicsFA2BasedRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsFA2BasedRepulsionSolver); + // update class + var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); + dom.box.className = 'vis-item vis-box' + className; + dom.line.className = 'vis-item vis-line' + className; + dom.dot.className = 'vis-item vis-dot' + className; - var _componentsPhysicsFA2BasedCentralGravitySolver = __webpack_require__(84); + // recalculate size + this.props.dot.height = dom.dot.offsetHeight; + this.props.dot.width = dom.dot.offsetWidth; + this.props.line.width = dom.line.offsetWidth; + this.width = dom.box.offsetWidth; + this.height = dom.box.offsetHeight; - var _componentsPhysicsFA2BasedCentralGravitySolver2 = _interopRequireDefault(_componentsPhysicsFA2BasedCentralGravitySolver); + this.dirty = false; + } - var util = __webpack_require__(2); + this._repaintDeleteButton(dom.box); + }; - var PhysicsEngine = (function () { - function PhysicsEngine(body) { - _classCallCheck(this, PhysicsEngine); + /** + * Show the item in the DOM (when not already displayed). The items DOM will + * be created when needed. + */ + BoxItem.prototype.show = function () { + if (!this.displayed) { + this.redraw(); + } + }; - this.body = body; - this.physicsBody = { physicsNodeIndices: [], physicsEdgeIndices: [], forces: {}, velocities: {} }; + /** + * Hide the item from the DOM (when visible) + */ + BoxItem.prototype.hide = function () { + if (this.displayed) { + var dom = this.dom; - this.physicsEnabled = true; - this.simulationInterval = 1000 / 60; - this.requiresTimeout = true; - this.previousStates = {}; - this.freezeCache = {}; - this.renderTimer = undefined; + if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box); + if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line); + if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot); - this.stabilized = false; - this.startedStabilization = false; - this.stabilizationIterations = 0; - this.ready = false; // will be set to true if the stabilize + this.displayed = false; + } + }; - // default options - this.options = {}; - this.defaultOptions = { - barnesHut: { - theta: 0.5, - gravitationalConstant: -2000, - centralGravity: 0.3, - springLength: 95, - springConstant: 0.04, - damping: 0.09, - avoidOverlap: 0 - }, - forceAtlas2Based: { - theta: 0.5, - gravitationalConstant: -50, - centralGravity: 0.01, - springConstant: 0.08, - springLength: 100, - damping: 0.4, - avoidOverlap: 0 - }, - repulsion: { - centralGravity: 0.2, - springLength: 200, - springConstant: 0.05, - nodeDistance: 100, - damping: 0.09, - avoidOverlap: 0 - }, - hierarchicalRepulsion: { - centralGravity: 0, - springLength: 100, - springConstant: 0.01, - nodeDistance: 120, - damping: 0.09 - }, - maxVelocity: 50, - minVelocity: 0.1, // px/s - solver: 'barnesHut', - stabilization: { - enabled: true, - iterations: 1000, // maximum number of iteration to stabilize - updateInterval: 50, - onlyDynamicEdges: false, - fit: true - }, - timestep: 0.5 - }; - util.extend(this.options, this.defaultOptions); + /** + * Reposition the item horizontally + * @Override + */ + BoxItem.prototype.repositionX = function () { + var start = this.conversion.toScreen(this.data.start); + var align = this.options.align; + var left; - this.bindEventListeners(); + // calculate left position of the box + if (align == 'right') { + this.left = start - this.width; + } else if (align == 'left') { + this.left = start; + } else { + // default or 'center' + this.left = start - this.width / 2; } - _createClass(PhysicsEngine, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this = this; + // reposition box + this.dom.box.style.left = this.left + 'px'; - this.body.emitter.on('initPhysics', function () { - _this.initPhysics(); - }); - this.body.emitter.on('resetPhysics', function () { - _this.stopSimulation();_this.ready = false; - }); - this.body.emitter.on('disablePhysics', function () { - _this.physicsEnabled = false;_this.stopSimulation(); - }); - this.body.emitter.on('restorePhysics', function () { - _this.setOptions(_this.options); - if (_this.ready === true) { - _this.startSimulation(); - } - }); - this.body.emitter.on('startSimulation', function () { - if (_this.ready === true) { - _this.startSimulation(); - } - }); - this.body.emitter.on('stopSimulation', function () { - _this.stopSimulation(); - }); - this.body.emitter.on('destroy', function () { - _this.stopSimulation(false); - _this.body.emitter.off(); - }); - } - }, { - key: 'setOptions', - value: function setOptions(options) { - if (options !== undefined) { - if (options === false) { - this.physicsEnabled = false; - this.stopSimulation(); - } else { - this.physicsEnabled = true; - util.selectiveNotDeepExtend(['stabilization'], this.options, options); - util.mergeOptions(this.options, options, 'stabilization'); - } - } - this.init(); - } - }, { - key: 'init', - value: function init() { - var options; - if (this.options.solver === 'forceAtlas2Based') { - options = this.options.forceAtlas2Based; - this.nodesSolver = new _componentsPhysicsFA2BasedRepulsionSolver2['default'](this.body, this.physicsBody, options); - this.edgesSolver = new _componentsPhysicsSpringSolver2['default'](this.body, this.physicsBody, options); - this.gravitySolver = new _componentsPhysicsFA2BasedCentralGravitySolver2['default'](this.body, this.physicsBody, options); - } else if (this.options.solver === 'repulsion') { - options = this.options.repulsion; - this.nodesSolver = new _componentsPhysicsRepulsionSolver2['default'](this.body, this.physicsBody, options); - this.edgesSolver = new _componentsPhysicsSpringSolver2['default'](this.body, this.physicsBody, options); - this.gravitySolver = new _componentsPhysicsCentralGravitySolver2['default'](this.body, this.physicsBody, options); - } else if (this.options.solver === 'hierarchicalRepulsion') { - options = this.options.hierarchicalRepulsion; - this.nodesSolver = new _componentsPhysicsHierarchicalRepulsionSolver2['default'](this.body, this.physicsBody, options); - this.edgesSolver = new _componentsPhysicsHierarchicalSpringSolver2['default'](this.body, this.physicsBody, options); - this.gravitySolver = new _componentsPhysicsCentralGravitySolver2['default'](this.body, this.physicsBody, options); - } else { - // barnesHut - options = this.options.barnesHut; - this.nodesSolver = new _componentsPhysicsBarnesHutSolver2['default'](this.body, this.physicsBody, options); - this.edgesSolver = new _componentsPhysicsSpringSolver2['default'](this.body, this.physicsBody, options); - this.gravitySolver = new _componentsPhysicsCentralGravitySolver2['default'](this.body, this.physicsBody, options); - } + // reposition line + this.dom.line.style.left = start - this.props.line.width / 2 + 'px'; - this.modelOptions = options; - } - }, { - key: 'initPhysics', - value: function initPhysics() { - if (this.physicsEnabled === true) { - if (this.options.stabilization.enabled === true) { - this.stabilize(); - } else { - this.stabilized = false; - this.ready = true; - this.body.emitter.emit('fit', {}, true); - this.startSimulation(); - } - } else { - this.ready = true; - this.body.emitter.emit('fit'); - } - } - }, { - key: 'startSimulation', + // reposition dot + this.dom.dot.style.left = start - this.props.dot.width / 2 + 'px'; + }; - /** - * Start the simulation - */ - value: function startSimulation() { - if (this.physicsEnabled === true) { - this.stabilized = false; + /** + * Reposition the item vertically + * @Override + */ + BoxItem.prototype.repositionY = function () { + var orientation = this.options.orientation.item; + var box = this.dom.box; + var line = this.dom.line; + var dot = this.dom.dot; - // this sets the width of all nodes initially which could be required for the avoidOverlap - this.body.emitter.emit('_resizeNodes'); + if (orientation == 'top') { + box.style.top = (this.top || 0) + 'px'; - if (this.viewFunction === undefined) { - this.viewFunction = this.simulationStep.bind(this); - this.body.emitter.on('initRedraw', this.viewFunction); - this.body.emitter.emit('_startRendering'); - } - } else { - this.body.emitter.emit('_redraw'); - } - } - }, { - key: 'stopSimulation', + line.style.top = '0'; + line.style.height = this.parent.top + this.top + 1 + 'px'; + line.style.bottom = ''; + } else { + // orientation 'bottom' + var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty + var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top; - /** - * Stop the simulation, force stabilization. - */ - value: function stopSimulation() { - var emit = arguments[0] === undefined ? true : arguments[0]; + box.style.top = (this.parent.height - this.top - this.height || 0) + 'px'; + line.style.top = itemSetHeight - lineHeight + 'px'; + line.style.bottom = '0'; + } - this.stabilized = true; - if (emit === true) { - this._emitStabilized(); - } - if (this.viewFunction !== undefined) { - this.body.emitter.off('initRedraw', this.viewFunction); - this.viewFunction = undefined; - if (emit === true) { - this.body.emitter.emit('_stopRendering'); - } - } - } - }, { - key: 'simulationStep', + dot.style.top = -this.props.dot.height / 2 + 'px'; + }; - /** - * The viewFunction inserts this step into each renderloop. It calls the physics tick and handles the cleanup at stabilized. - * - */ - value: function simulationStep() { - // check if the physics have settled - var startTime = Date.now(); - this.physicsTick(); - var physicsTime = Date.now() - startTime; + module.exports = BoxItem; - // run double speed if it is a little graph - if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) { - this.physicsTick(); +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { - // this makes sure there is no jitter. The decision is taken once to run it at double speed. - this.runDoubleSpeed = true; - } + 'use strict'; - if (this.stabilized === true) { - if (this.stabilizationIterations > 1) { - // trigger the 'stabilized' event. - // The event is triggered on the next tick, to prevent the case that - // it is fired while initializing the Network, in which case you would not - // be able to catch it - this.startedStabilization = false; - //this._emitStabilized(); - } - this.stopSimulation(); - } - } - }, { - key: '_emitStabilized', - value: function _emitStabilized() { - var _this2 = this; + var Hammer = __webpack_require__(3); + var util = __webpack_require__(7); - if (this.stabilizationIterations > 1) { - setTimeout(function () { - _this2.body.emitter.emit('stabilized', { iterations: _this2.stabilizationIterations }); - _this2.stabilizationIterations = 0; - }, 0); - } - } - }, { - key: 'physicsTick', + /** + * @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 || {}; - /** - * A single simulation step (or 'tick') in the physics simulation - * - * @private - */ - value: function physicsTick() { - if (this.stabilized === false) { - this.calculateForces(); - this.stabilized = this.moveNodes(); + this.selected = false; + this.displayed = false; + this.dirty = true; - // determine if the network has stabilzied - if (this.stabilized === true) { - this.revert(); - } else { - // this is here to ensure that there is no start event when the network is already stable. - if (this.startedStabilization === false) { - this.body.emitter.emit('startStabilizing'); - this.startedStabilization = true; - } - } + this.top = null; + this.left = null; + this.width = null; + this.height = null; + } - this.stabilizationIterations++; - } - } - }, { - key: 'updatePhysicsData', + Item.prototype.stack = true; - /** - * Nodes and edges can have the physics toggles on or off. A collection of indices is created here so we can skip the check all the time. - * - * @private - */ - value: function updatePhysicsData() { - this.physicsBody.forces = {}; - this.physicsBody.physicsNodeIndices = []; - this.physicsBody.physicsEdgeIndices = []; - var nodes = this.body.nodes; - var edges = this.body.edges; - - // get node indices for physics - for (var nodeId in nodes) { - if (nodes.hasOwnProperty(nodeId)) { - if (nodes[nodeId].options.physics === true) { - this.physicsBody.physicsNodeIndices.push(nodeId); - } - } - } - - // get edge indices for physics - for (var edgeId in edges) { - if (edges.hasOwnProperty(edgeId)) { - if (edges[edgeId].options.physics === true) { - this.physicsBody.physicsEdgeIndices.push(edgeId); - } - } - } - - // get the velocity and the forces vector - for (var i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) { - var nodeId = this.physicsBody.physicsNodeIndices[i]; - this.physicsBody.forces[nodeId] = { x: 0, y: 0 }; - - // forces can be reset because they are recalculated. Velocities have to persist. - if (this.physicsBody.velocities[nodeId] === undefined) { - this.physicsBody.velocities[nodeId] = { x: 0, y: 0 }; - } - } - - // clean deleted nodes from the velocity vector - for (var nodeId in this.physicsBody.velocities) { - if (nodes[nodeId] === undefined) { - delete this.physicsBody.velocities[nodeId]; - } - } - } - }, { - key: 'revert', - - /** - * Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized. - */ - value: function revert() { - var nodeIds = Object.keys(this.previousStates); - var nodes = this.body.nodes; - var velocities = this.physicsBody.velocities; - - for (var i = 0; i < nodeIds.length; i++) { - var nodeId = nodeIds[i]; - if (nodes[nodeId] !== undefined) { - if (nodes[nodeId].options.physics === true) { - velocities[nodeId].x = this.previousStates[nodeId].vx; - velocities[nodeId].y = this.previousStates[nodeId].vy; - nodes[nodeId].x = this.previousStates[nodeId].x; - nodes[nodeId].y = this.previousStates[nodeId].y; - } - } else { - delete this.previousStates[nodeId]; - } - } - } - }, { - key: 'moveNodes', - - /** - * move the nodes one timestap and check if they are stabilized - * @returns {boolean} - */ - value: function moveNodes() { - var nodesPresent = false; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var maxVelocity = this.options.maxVelocity ? this.options.maxVelocity : 1000000000; - var stabilized = true; - var vminCorrected = this.options.minVelocity / Math.max(this.body.view.scale, 0.05); - - for (var i = 0; i < nodeIndices.length; i++) { - var nodeId = nodeIndices[i]; - var nodeVelocity = this._performStep(nodeId, maxVelocity); - // stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized - stabilized = nodeVelocity < vminCorrected && stabilized === true; - nodesPresent = true; - } - - if (nodesPresent === true) { - if (vminCorrected > 0.5 * this.options.maxVelocity) { - return false; - } else { - return stabilized; - } - } - return true; - } - }, { - key: '_performStep', - - /** - * Perform the actual step - * - * @param nodeId - * @param maxVelocity - * @returns {number} - * @private - */ - value: function _performStep(nodeId, maxVelocity) { - var node = this.body.nodes[nodeId]; - var timestep = this.options.timestep; - var forces = this.physicsBody.forces; - var velocities = this.physicsBody.velocities; - - // store the state so we can revert - this.previousStates[nodeId] = { x: node.x, y: node.y, vx: velocities[nodeId].x, vy: velocities[nodeId].y }; - - if (node.options.fixed.x === false) { - var dx = this.modelOptions.damping * velocities[nodeId].x; // damping force - var ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration - velocities[nodeId].x += ax * timestep; // velocity - velocities[nodeId].x = Math.abs(velocities[nodeId].x) > maxVelocity ? velocities[nodeId].x > 0 ? maxVelocity : -maxVelocity : velocities[nodeId].x; - node.x += velocities[nodeId].x * timestep; // position - } else { - forces[nodeId].x = 0; - velocities[nodeId].x = 0; - } - - if (node.options.fixed.y === false) { - var dy = this.modelOptions.damping * velocities[nodeId].y; // damping force - var ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration - velocities[nodeId].y += ay * timestep; // velocity - velocities[nodeId].y = Math.abs(velocities[nodeId].y) > maxVelocity ? velocities[nodeId].y > 0 ? maxVelocity : -maxVelocity : velocities[nodeId].y; - node.y += velocities[nodeId].y * timestep; // position - } else { - forces[nodeId].y = 0; - velocities[nodeId].y = 0; - } - - var totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x, 2) + Math.pow(velocities[nodeId].y, 2)); - return totalVelocity; - } - }, { - key: 'calculateForces', - - /** - * calculate the forces for one physics iteration. - */ - value: function calculateForces() { - this.gravitySolver.solve(); - this.nodesSolver.solve(); - this.edgesSolver.solve(); - } - }, { - key: '_freezeNodes', - - /** - * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization - * because only the supportnodes for the smoothCurves have to settle. - * - * @private - */ - value: function _freezeNodes() { - var nodes = this.body.nodes; - for (var id in nodes) { - if (nodes.hasOwnProperty(id)) { - if (nodes[id].x && nodes[id].y) { - this.freezeCache[id] = { x: nodes[id].options.fixed.x, y: nodes[id].options.fixed.y }; - nodes[id].options.fixed.x = true; - nodes[id].options.fixed.y = true; - } - } - } - } - }, { - key: '_restoreFrozenNodes', - - /** - * Unfreezes the nodes that have been frozen by _freezeDefinedNodes. - * - * @private - */ - value: function _restoreFrozenNodes() { - var nodes = this.body.nodes; - for (var id in nodes) { - if (nodes.hasOwnProperty(id)) { - if (this.freezeCache[id] !== undefined) { - nodes[id].options.fixed.x = this.freezeCache[id].x; - nodes[id].options.fixed.y = this.freezeCache[id].y; - } - } - } - this.freezeCache = {}; - } - }, { - key: 'stabilize', - - /** - * Find a stable position for all nodes - * @private - */ - value: function stabilize() { - var _this3 = this; - - var iterations = arguments[0] === undefined ? this.options.stabilization.iterations : arguments[0]; - - if (typeof iterations !== 'number') { - console.log('The stabilize method needs a numeric amount of iterations. Switching to default: ', this.options.stabilization.iterations); - iterations = this.options.stabilization.iterations; - } - - // this sets the width of all nodes initially which could be required for the avoidOverlap - this.body.emitter.emit('_resizeNodes'); - - // stop the render loop - this.stopSimulation(); - - // set stabilze to false - this.stabilized = false; - - // block redraw requests - this.body.emitter.emit('_blockRedrawRequests'); - this.targetIterations = iterations; - - // start the stabilization - if (this.options.stabilization.onlyDynamicEdges === true) { - this._freezeNodes(); - } - this.stabilizationIterations = 0; - - setTimeout(function () { - return _this3._stabilizationBatch(); - }, 0); - } - }, { - key: '_stabilizationBatch', - value: function _stabilizationBatch() { - var count = 0; - while (this.stabilized === false && count < this.options.stabilization.updateInterval && this.stabilizationIterations < this.targetIterations) { - this.physicsTick(); - this.stabilizationIterations++; - count++; - } - - if (this.stabilized === false && this.stabilizationIterations < this.targetIterations) { - this.body.emitter.emit('stabilizationProgress', { iterations: this.stabilizationIterations, total: this.targetIterations }); - setTimeout(this._stabilizationBatch.bind(this), 0); - } else { - this._finalizeStabilization(); - } - } - }, { - key: '_finalizeStabilization', - value: function _finalizeStabilization() { - this.body.emitter.emit('_allowRedrawRequests'); - if (this.options.stabilization.fit === true) { - this.body.emitter.emit('fit'); - } - - if (this.options.stabilization.onlyDynamicEdges === true) { - this._restoreFrozenNodes(); - } - - this.body.emitter.emit('stabilizationIterationsDone'); - this.body.emitter.emit('_requestRedraw'); - - if (this.stabilized === true) { - this._emitStabilized(); - } else { - this.startSimulation(); - } - - this.ready = true; - } - }]); - - return PhysicsEngine; - })(); - - exports['default'] = PhysicsEngine; - module.exports = exports['default']; - -/***/ }, -/* 2 */ -/***/ function(module, exports, __webpack_require__) { - - // utility functions - - // first check if moment.js is already loaded in the browser window, if so, - // use this instance. Else, load via commonjs. - - 'use strict'; - - var moment = __webpack_require__(40); - var uuid = __webpack_require__(42); + /** + * Select current item + */ + Item.prototype.select = function () { + this.selected = true; + this.dirty = true; + if (this.displayed) this.redraw(); + }; /** - * Test whether given object is a number - * @param {*} object - * @return {Boolean} isNumber + * Unselect current item */ - exports.isNumber = function (object) { - return object instanceof Number || typeof object == 'number'; + Item.prototype.unselect = function () { + this.selected = false; + this.dirty = true; + if (this.displayed) this.redraw(); }; /** - * Remove everything in the DOM object - * @param DOMobject + * 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 */ - exports.recursiveDOMDelete = function (DOMobject) { - if (DOMobject) { - while (DOMobject.hasChildNodes() === true) { - exports.recursiveDOMDelete(DOMobject.firstChild); - DOMobject.removeChild(DOMobject.firstChild); - } + Item.prototype.setData = function (data) { + var groupChanged = data.group != undefined && this.data.group != data.group; + if (groupChanged) { + this.parent.itemSet._moveToGroup(this, data.group); } + + this.data = data; + this.dirty = true; + if (this.displayed) this.redraw(); }; /** - * 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 min - * @param max - * @param total - * @param value - * @returns {number} + * Set a parent for the item + * @param {ItemSet | Group} parent */ - exports.giveRange = function (min, max, total, value) { - if (max == min) { - return 0.5; + Item.prototype.setParent = function (parent) { + if (this.displayed) { + this.hide(); + this.parent = parent; + if (this.parent) { + this.show(); + } } else { - var scale = 1 / (max - min); - return Math.max(0, (value - min) * scale); + this.parent = parent; } }; /** - * Test whether given object is a string - * @param {*} object - * @return {Boolean} isString + * Check whether this item is visible inside given range + * @returns {{start: Number, end: Number}} range with a timestamp for start and end + * @returns {boolean} True if visible */ - exports.isString = function (object) { - return object instanceof String || typeof object == 'string'; + Item.prototype.isVisible = function (range) { + // Should be implemented by Item implementations + return false; }; /** - * Test whether given object is a Date, or a String containing a Date - * @param {Date | String} object - * @return {Boolean} isDate + * Show the Item in the DOM (when not already visible) + * @return {Boolean} changed */ - 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; - } - } - + Item.prototype.show = function () { return false; }; /** - * Create a semi UUID - * source: http://stackoverflow.com/a/105074/1262753 - * @return {String} uuid + * Hide the Item from the DOM (when visible) + * @return {Boolean} changed */ - exports.randomUUID = function () { - return uuid.v4(); + Item.prototype.hide = function () { + return false; }; /** - * assign all keys of an object that are not nested objects to a certain value (used for color objects). - * @param obj - * @param value + * Repaint the item */ - exports.assignAllKeys = function (obj, value) { - for (var prop in obj) { - if (obj.hasOwnProperty(prop)) { - if (typeof obj[prop] !== 'object') { - obj[prop] = value; - } - } - } - }; + Item.prototype.redraw = function () {}; /** - * Fill an object with a possibly partially defined other object. Only copies values if the a object has an object requiring values. - * That means an object is not created on a property if only the b object has it. - * @param obj - * @param value + * Reposition the Item horizontally */ - exports.fillIfDefined = function (a, b) { - var allowDeletion = arguments[2] === undefined ? false : arguments[2]; - - for (var prop in a) { - if (b[prop] !== undefined) { - if (typeof b[prop] !== 'object') { - if ((b[prop] === undefined || b[prop] === null) && a[prop] !== undefined && allowDeletion === true) { - delete a[prop]; - } else { - a[prop] = b[prop]; - } - } else { - if (typeof a[prop] === 'object') { - exports.fillIfDefined(a[prop], b[prop], allowDeletion); - } - } - } - } - }; + Item.prototype.repositionX = function () {}; /** - * 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 + * Reposition the Item vertically */ - exports.protoExtend = function (a, b) { - for (var i = 1; i < arguments.length; i++) { - var other = arguments[i]; - for (var prop in other) { - a[prop] = other[prop]; - } - } - return a; - }; + Item.prototype.repositionY = function () {}; /** - * 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 + * Repaint a delete button on the top right of the item when the item is selected + * @param {HTMLElement} anchor + * @protected */ - exports.extend = function (a, b) { - 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]; - } + Item.prototype._repaintDeleteButton = function (anchor) { + if (this.selected && this.options.editable.remove && !this.dom.deleteButton) { + // create and show button + var me = this; + + var deleteButton = document.createElement('div'); + 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; } - 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 + * Set HTML contents for the item + * @param {Element} element HTML element to fill with the contents + * @private */ - exports.selectiveExtend = function (props, a, b) { - if (!Array.isArray(props)) { - throw new Error('Array with property names expected as first argument'); + Item.prototype._updateContents = function (element) { + var content; + if (this.options.template) { + var itemData = this.parent.itemSet.itemsData.get(this.id); // get a clone of the data from the dataset + content = this.options.template(itemData); + } else { + content = this.data.content; } - 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.hasOwnProperty(prop)) { - a[prop] = other[prop]; + var 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; } - 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.selectiveDeepExtend = function (props, a, b) { - var allowDeletion = arguments[3] === undefined ? false : arguments[3]; - - // TODO: add support for Arrays to deepExtend - if (Array.isArray(b)) { - throw new TypeError('Arrays are not supported by deepExtend'); - } - 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.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 { - if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) { - delete a[prop]; - } else { - a[prop] = b[prop]; - } - } - } else if (Array.isArray(b[prop])) { - throw new TypeError('Arrays are not supported by deepExtend'); - } else { - a[prop] = b[prop]; - } - } - } + * Set HTML contents for the item + * @param {Element} element HTML element to fill with the contents + * @private + */ + Item.prototype._updateTitle = function (element) { + if (this.data.title != null) { + element.title = this.data.title || ''; + } else { + element.removeAttribute('vis-title'); } - 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 + * 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 */ - exports.selectiveNotDeepExtend = function (props, a, b) { - var allowDeletion = arguments[3] === undefined ? false : arguments[3]; + Item.prototype._updateDataAttributes = function (element) { + if (this.options.dataAttributes && this.options.dataAttributes.length > 0) { + var attributes = []; - // TODO: add support for Arrays to deepExtend - if (Array.isArray(b)) { - throw new TypeError('Arrays are not supported by deepExtend'); - } - for (var prop in b) { - if (b.hasOwnProperty(prop)) { - if (props.indexOf(prop) == -1) { - if (b[prop] && b[prop].constructor === Object) { - if (a[prop] === undefined) { - a[prop] = {}; - } - if (a[prop].constructor === Object) { - exports.deepExtend(a[prop], b[prop]); - } else { - if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) { - delete a[prop]; - } else { - a[prop] = b[prop]; - } - } - } else if (Array.isArray(b[prop])) { - throw new TypeError('Arrays are not supported by deepExtend'); - } else { - a[prop] = b[prop]; - } - } + if (Array.isArray(this.options.dataAttributes)) { + attributes = this.options.dataAttributes; + } else if (this.options.dataAttributes == 'all') { + attributes = Object.keys(this.data); + } else { + return; } - } - return a; - }; - /** - * Deep extend an object a with the properties of object b - * @param {Object} a - * @param {Object} b - * @param [Boolean] protoExtend --> optional parameter. 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] global --> optional parameter. If true, the values of fields that are null will not deleted - * @returns {Object} - */ - exports.deepExtend = function (a, b, protoExtend, allowDeletion) { - 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); - } else { - if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) { - delete a[prop]; - } else { - a[prop] = b[prop]; - } - } - } else if (Array.isArray(b[prop])) { - a[prop] = []; - for (var i = 0; i < b[prop].length; i++) { - a[prop].push(b[prop][i]); - } + 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 { - a[prop] = b[prop]; + element.removeAttribute('data-' + name); } } } - 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. + * Update custom styles of the element + * @param element + * @private */ - 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; + Item.prototype._updateStyle = function (element) { + // remove old styles + if (this.style) { + util.removeCssText(element, this.style); + this.style = null; } - return true; + // append new styles + if (this.data.style) { + util.addCssText(element, this.data.style); + this.style = this.data.style; + } }; /** - * 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 + * Stringify the items contents + * @param {string | Element | undefined} content + * @returns {string | undefined} + * @private */ - exports.convert = function (object, type) { - var match; + Item.prototype._contentToString = function (content) { + if (typeof content === 'string') return content; + if (content && 'outerHTML' in content) return content.outerHTML; + return content; + }; - if (object === undefined) { - return undefined; - } - if (object === null) { - return null; - } + module.exports = Item; - if (!type) { - return object; - } - if (!(typeof type === 'string') && !(type instanceof String)) { - throw new Error('Type must be a string'); - } + // should be implemented by the item - //noinspection FallthroughInSwitchStatementJS - switch (type) { - case 'boolean': - case 'Boolean': - return Boolean(object); + // should be implemented by the item - case 'number': - case 'Number': - return Number(object.valueOf()); + // should be implemented by the item - case 'string': - case 'String': - return String(object); +/***/ }, +/* 3 */ +/***/ function(module, exports, __webpack_require__) { - 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(object).toDate(); // parse string - } - } else { - throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type Date'); - } + // Only load hammer.js when in a browser environment + // (loading hammer.js in a node.js environment gives errors) + 'use strict'; - 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'); - } + if (typeof window !== 'undefined') { + var propagating = __webpack_require__(4); + var Hammer = window['Hammer'] || __webpack_require__(5); + module.exports = propagating(Hammer, { + preventDefault: 'mouse' + }); + } else { + module.exports = function () { + throw Error('hammer.js is only available in a browser, not in node.js.'); + }; + } - 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 new Date(object).toISOString(); // parse string - } - } else { - throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type ISODate'); - } +/***/ }, +/* 4 */ +/***/ function(module, exports, __webpack_require__) { - 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'); - } + var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; - default: - throw new Error('Unknown type "' + type + '"'); + (function (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) + window.propagating = factory(); } - }; + }(function () { + var _firstTarget = null; // singleton, will contain the target element where the touch event started + var _processing = false; // singleton, true when a touch event is being handled - // parse ASP.Net Date pattern, - // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/' - // code from http://momentjs.com/ - var ASPDateRegex = /^\/?Date\((\-?\d+)/i; + /** + * Extend an Hammer.js instance with event propagation. + * + * Features: + * - Events emitted by hammer will propagate in order from child to parent + * elements. + * - Events are extended with a function `event.stopPropagation()` to stop + * propagation to parent elements. + * - An option `preventDefault` to stop all default browser behavior. + * + * Usage: + * var hammer = propagatingHammer(new Hammer(element)); + * var hammer = propagatingHammer(new Hammer(element), {preventDefault: true}); + * + * @param {Hammer.Manager} hammer An hammer instance. + * @param {Object} [options] Available options: + * - `preventDefault: true | 'mouse' | 'touch' | 'pen'`. + * Enforce preventing the default browser behavior. + * Cannot be set to `false`. + * @return {Hammer.Manager} Returns the same hammer instance with extended + * functionality + */ + return function propagating(hammer, options) { + if (options && options.preventDefault === false) { + throw new Error('Only supports preventDefault == true'); + } + var _options = options || { + preventDefault: false + }; - /** - * 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; + if (hammer.Manager) { + // This looks like the Hammer constructor. + // Overload the constructors with our own. + var Hammer = hammer; - 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'; + var PropagatingHammer = function(element, options) { + return propagating(new Hammer(element, options), _options); + }; + Hammer.extend(PropagatingHammer, Hammer); + PropagatingHammer.Manager = function (element, options) { + return propagating(new Hammer.Manager(element, options), _options); + }; + + return PropagatingHammer; } - 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; - }; + // attach to DOM element + var element = hammer.element; + element.hammer = hammer; - /** - * Used to extend an array and copy it. This is used to propagate paths recursively. - * - * @param 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; - }; + // move the original functions that we will wrap + hammer._on = hammer.on; + hammer._off = hammer.off; + hammer._emit = hammer.emit; + hammer._destroy = hammer.destroy; - /** - * Used to extend an array and copy it. This is used to propagate paths recursively. - * - * @param arr - * @param newValue - * @returns {Array} - */ - exports.copyArray = function (arr) { - var newArr = []; - for (var i = 0; i < arr.length; i++) { - newArr.push(arr[i]); - } - return newArr; - }; + /** @type {Object.>} */ + hammer._handlers = {}; - /** - * 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; - }; + // register an event to catch the start of a gesture and store the + // target in a singleton + hammer._on('hammer.input', function (event) { + if (_options.preventDefault === true || (_options.preventDefault === event.pointerType)) { + event.preventDefault(); + } + if (event.isFirst) { + _firstTarget = event.target; + _processing = true; + } + if (event.isFinal) { + _processing = false; + } + }); - /** - * 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; - }; + /** + * Register a handler for one or multiple events + * @param {String} events A space separated string with events + * @param {function} handler A callback function, called as handler(event) + * @returns {Hammer.Manager} Returns the hammer instance + */ + hammer.on = function (events, handler) { + // register the handler + split(events).forEach(function (event) { + var _handlers = hammer._handlers[event]; + if (!_handlers) { + hammer._handlers[event] = _handlers = []; - /** - * add a className to the given elements style - * @param {Element} elem - * @param {String} className - */ - exports.addClassName = function (elem, className) { - var classes = elem.className.split(' '); - if (classes.indexOf(className) == -1) { - classes.push(className); // add the class to the array - elem.className = classes.join(' '); - } - }; + // register the static, propagated handler + hammer._on(event, propagatedHandler); + } + _handlers.push(handler); + }); - /** - * add a className to the given elements style - * @param {Element} elem - * @param {String} className - */ - exports.removeClassName = function (elem, className) { - var classes = elem.className.split(' '); - var index = classes.indexOf(className); - if (index != -1) { - classes.splice(index, 1); // remove the class from the array - elem.className = classes.join(' '); - } - }; + return hammer; + }; - /** - * For each method for both arrays and objects. - * In case of an array, the built-in Array.forEach() is applied. - * 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); - } - } - } - }; + /** + * Unregister a handler for one or multiple events + * @param {String} events A space separated string with events + * @param {function} [handler] Optional. The registered handler. If not + * provided, all handlers for given events + * are removed. + * @returns {Hammer.Manager} Returns the hammer instance + */ + hammer.off = function (events, handler) { + // unregister the handler + split(events).forEach(function (event) { + var _handlers = hammer._handlers[event]; + if (_handlers) { + _handlers = handler ? _handlers.filter(function (h) { + return h !== handler; + }) : []; - /** - * Convert an object into an array: all objects properties are put into the - * array. The resulting array is unordered. - * @param {Object} object - * @param {Array} array - */ - exports.toArray = function (object) { - var array = []; + if (_handlers.length > 0) { + hammer._handlers[event] = _handlers; + } + else { + // remove static, propagated handler + hammer._off(event, propagatedHandler); + delete hammer._handlers[event]; + } + } + }); - for (var prop in object) { - if (object.hasOwnProperty(prop)) array.push(object[prop]); - } + return hammer; + }; - return array; - }; + /** + * Emit to the event listeners + * @param {string} eventType + * @param {Event} event + */ + hammer.emit = function(eventType, event) { + if (!_processing) { + _firstTarget = event.target; + } + hammer._emit(eventType, event); + }; - /** - * 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; - } - }; + hammer.destroy = function () { + // Detach from DOM element + var element = hammer.element; + delete element.hammer; - /** - * 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; + // clear all handlers + hammer._handlers = {}; - if (action === 'mousewheel' && navigator.userAgent.indexOf('Firefox') >= 0) { - action = 'DOMMouseScroll'; // For Firefox + // call original hammer destroy + hammer._destroy(); + }; + + // split a string with space separated words + function split(events) { + return events.match(/[^ ]+/g); } - element.addEventListener(action, listener, useCapture); - } else { - element.attachEvent('on' + action, listener); // IE browsers - } - }; + /** + * A static event handler, applying event propagation. + * @param {Object} event + */ + function propagatedHandler(event) { + // let only a single hammer instance handle this event + if (event.type !== 'hammer.input') { + // it is possible that the same srcEvent is used with multiple hammer events, + // we keep track on which events are handled in an object _handled + if (!event.srcEvent._handled) { + event.srcEvent._handled = {}; + } - /** - * 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 (event.srcEvent._handled[event.type]) { + return; + } + else { + event.srcEvent._handled[event.type] = true; + } + } - if (action === 'mousewheel' && navigator.userAgent.indexOf('Firefox') >= 0) { - action = 'DOMMouseScroll'; // For Firefox - } + // attach a stopPropagation function to the event + var stopped = false; + event.stopPropagation = function () { + stopped = true; + }; - element.removeEventListener(action, listener, useCapture); - } else { - // IE browsers - element.detachEvent('on' + action, listener); - } - }; + // attach firstTarget property to the event + event.firstTarget = _firstTarget; - /** - * Cancels the event if it is cancelable, without stopping further propagation of the event. - */ - exports.preventDefault = function (event) { - if (!event) event = window.event; + // propagate over all elements (until stopped) + var elem = _firstTarget; + while (elem && !stopped) { + var _handlers = elem.hammer && elem.hammer._handlers[event.type]; + if (_handlers) { + for (var i = 0; i < _handlers.length && !stopped; i++) { + _handlers[i](event); + } + } - if (event.preventDefault) { - event.preventDefault(); // non-IE browsers - } else { - event.returnValue = false; // IE browsers - } - }; + elem = elem.parentNode; + } + } - /** - * 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; - } + return hammer; + }; + })); - var target; - if (event.target) { - target = event.target; - } else if (event.srcElement) { - target = event.srcElement; - } +/***/ }, +/* 5 */ +/***/ function(module, exports, __webpack_require__) { - if (target.nodeType != undefined && target.nodeType == 3) { - // defeat Safari bug - target = target.parentNode; - } + var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v2.0.4 - 2014-09-28 + * http://hammerjs.github.io/ + * + * Copyright (c) 2014 Jorik Tangelder; + * Licensed under the MIT license */ + (function(window, document, exportName, undefined) { + 'use strict'; - return target; - }; + var VENDOR_PREFIXES = ['', 'webkit', 'moz', 'MS', 'ms', 'o']; + var TEST_ELEMENT = document.createElement('div'); + + var TYPE_FUNCTION = 'function'; + + var round = Math.round; + var abs = Math.abs; + var now = Date.now; /** - * Check if given element contains given parent somewhere in the DOM tree - * @param {Element} element - * @param {Element} parent + * set a timeout with a given scope + * @param {Function} fn + * @param {Number} timeout + * @param {Object} context + * @returns {number} */ - exports.hasParent = function (element, parent) { - var e = element; + function setTimeoutContext(fn, timeout, context) { + return setTimeout(bindFn(fn, context), timeout); + } - while (e) { - if (e === parent) { - return true; + /** + * if the argument is an array, we want to execute the fn on each entry + * if it aint an array we don't want to do a thing. + * this is used by all the methods that accept a single and array argument. + * @param {*|Array} arg + * @param {String} fn + * @param {Object} [context] + * @returns {Boolean} + */ + function invokeArrayArg(arg, fn, context) { + if (Array.isArray(arg)) { + each(arg, context[fn], context); + return true; } - e = e.parentNode; - } - - return false; - }; - - exports.option = {}; + return false; + } /** - * Convert a value into a boolean - * @param {Boolean | function | undefined} value - * @param {Boolean} [defaultValue] - * @returns {Boolean} bool + * walk objects and arrays + * @param {Object} obj + * @param {Function} iterator + * @param {Object} context */ - exports.option.asBoolean = function (value, defaultValue) { - if (typeof value == 'function') { - value = value(); - } + function each(obj, iterator, context) { + var i; - if (value != null) { - return value != false; - } + if (!obj) { + return; + } - return defaultValue || null; - }; + if (obj.forEach) { + obj.forEach(iterator, context); + } else if (obj.length !== undefined) { + i = 0; + while (i < obj.length) { + iterator.call(context, obj[i], i, obj); + i++; + } + } else { + for (i in obj) { + obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj); + } + } + } /** - * Convert a value into a number - * @param {Boolean | function | undefined} value - * @param {Number} [defaultValue] - * @returns {Number} number + * extend object. + * means that properties in dest will be overwritten by the ones in src. + * @param {Object} dest + * @param {Object} src + * @param {Boolean} [merge] + * @returns {Object} dest */ - exports.option.asNumber = function (value, defaultValue) { - if (typeof value == 'function') { - value = value(); - } - - if (value != null) { - return Number(value) || defaultValue || null; - } + function extend(dest, src, merge) { + var keys = Object.keys(src); + var i = 0; + while (i < keys.length) { + if (!merge || (merge && dest[keys[i]] === undefined)) { + dest[keys[i]] = src[keys[i]]; + } + i++; + } + return dest; + } - return defaultValue || null; - }; + /** + * merge the values from src in the dest. + * means that properties that exist in dest will not be overwritten by src + * @param {Object} dest + * @param {Object} src + * @returns {Object} dest + */ + function merge(dest, src) { + return extend(dest, src, true); + } /** - * Convert a value into a string - * @param {String | function | undefined} value - * @param {String} [defaultValue] - * @returns {String} str + * simple class inheritance + * @param {Function} child + * @param {Function} base + * @param {Object} [properties] */ - exports.option.asString = function (value, defaultValue) { - if (typeof value == 'function') { - value = value(); - } + function inherit(child, base, properties) { + var baseP = base.prototype, + childP; - if (value != null) { - return String(value); - } + childP = child.prototype = Object.create(baseP); + childP.constructor = child; + childP._super = baseP; - return defaultValue || null; - }; + if (properties) { + extend(childP, properties); + } + } /** - * 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 + * simple function bind + * @param {Function} fn + * @param {Object} context + * @returns {Function} */ - 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; - } - }; + function bindFn(fn, context) { + return function boundFn() { + return fn.apply(context, arguments); + }; + } /** - * Convert a value into a DOM element - * @param {HTMLElement | function | undefined} value - * @param {HTMLElement} [defaultValue] - * @returns {HTMLElement | null} dom + * let a boolean value also be a function that must return a boolean + * this first item in args will be used as the context + * @param {Boolean|Function} val + * @param {Array} [args] + * @returns {Boolean} */ - exports.option.asElement = function (value, defaultValue) { - if (typeof value == 'function') { - value = value(); - } - - return value || defaultValue || null; - }; + function boolOrFn(val, args) { + if (typeof val == TYPE_FUNCTION) { + return val.apply(args ? args[0] || undefined : undefined, args); + } + return val; + } /** - * http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb - * - * @param {String} hex - * @returns {{r: *, g: *, b: *}} | 255 range + * use the val2 when val1 is undefined + * @param {*} val1 + * @param {*} val2 + * @returns {*} */ - 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; - }; + function ifUndefined(val1, val2) { + return (val1 === undefined) ? val2 : val1; + } /** - * This function takes color in hex format or rgb() or rgba() format and overrides the opacity. Returns rgba() string. - * @param color - * @param opacity - * @returns {*} + * addEventListener with multiple events at once + * @param {EventTarget} target + * @param {String} types + * @param {Function} handler */ - exports.overrideOpacity = function (color, opacity) { - if (color.indexOf('rgba') != -1) { - return color; - } else if (color.indexOf('rgb') != -1) { - var rgb = color.substr(color.indexOf('(') + 1).replace(')', '').split(','); - return 'rgba(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ',' + opacity + ')'; - } else { - var rgb = exports.hexToRGB(color); - if (rgb == null) { - return color; - } else { - return 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + opacity + ')'; - } - } - }; + function addEventListeners(target, types, handler) { + each(splitStr(types), function(type) { + target.addEventListener(type, handler, false); + }); + } /** - * - * @param red 0 -- 255 - * @param green 0 -- 255 - * @param blue 0 -- 255 - * @returns {string} - * @constructor + * removeEventListener with multiple events at once + * @param {EventTarget} target + * @param {String} types + * @param {Function} handler */ - exports.RGBToHex = function (red, green, blue) { - return '#' + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1); - }; + function removeEventListeners(target, types, handler) { + each(splitStr(types), function(type) { + target.removeEventListener(type, handler, false); + }); + } /** - * Parse a color property into an object with border, background, and - * highlight colors - * @param {Object | String} color - * @return {Object} colorObject + * find if a node is in the given parent + * @method hasParent + * @param {HTMLElement} node + * @param {HTMLElement} parent + * @return {Boolean} found */ - 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 + function hasParent(node, parent) { + while (node) { + if (node == parent) { + return true; } - }; + node = node.parentNode; } - } else { - c = {}; - c.background = color.background || undefined; - c.border = color.border || undefined; + return false; + } - 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; - } + /** + * small indexOf wrapper + * @param {String} str + * @param {String} find + * @returns {Boolean} found + */ + function inStr(str, find) { + return str.indexOf(find) > -1; + } - if (exports.isString(color.hover)) { - c.hover = { - border: color.hover, - background: color.hover - }; + /** + * split string on whitespace + * @param {String} str + * @returns {Array} words + */ + function splitStr(str) { + return str.trim().split(/\s+/g); + } + + /** + * find if a array contains the object using indexOf or a simple polyFill + * @param {Array} src + * @param {String} find + * @param {String} [findByKey] + * @return {Boolean|Number} false when not found, or the index + */ + function inArray(src, find, findByKey) { + if (src.indexOf && !findByKey) { + return src.indexOf(find); } else { - c.hover = {}; - c.hover.background = color.hover && color.hover.background || undefined; - c.hover.border = color.hover && color.hover.border || undefined; + var i = 0; + while (i < src.length) { + if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) { + return i; + } + i++; + } + return -1; } - } - - return c; - }; + } /** - * http://www.javascripter.net/faq/rgb2hsv.htm - * - * @param red - * @param green - * @param blue - * @returns {*} - * @constructor + * convert array-like objects to real arrays + * @param {Object} obj + * @returns {Array} */ - 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 }; - }; + function toArray(obj) { + return Array.prototype.slice.call(obj, 0); + } - var cssUtil = { - // split a string with css styles into an object with key/values - split: function split(cssText) { - var styles = {}; + /** + * unique array with objects based on a key (like 'id') or just by the array's value + * @param {Array} src [{id:1},{id:2},{id:1}] + * @param {String} [key] + * @param {Boolean} [sort=False] + * @returns {Array} [{id:1},{id:2}] + */ + function uniqueArray(src, key, sort) { + var results = []; + var values = []; + var i = 0; - 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; - } - }); + while (i < src.length) { + var val = key ? src[i][key] : src[i]; + if (inArray(values, val) < 0) { + results.push(src[i]); + } + values[i] = val; + i++; + } - return styles; - }, + if (sort) { + if (!key) { + results = results.sort(); + } else { + results = results.sort(function sortUniqueArray(a, b) { + return a[key] > b[key]; + }); + } + } - // build a css text string from an object with key/values - join: function join(styles) { - return Object.keys(styles).map(function (key) { - return key + ': ' + styles[key]; - }).join('; '); - } - }; + return results; + } /** - * Append a string with css styles to an element - * @param {Element} element - * @param {String} cssText + * get the prefixed property + * @param {Object} obj + * @param {String} property + * @returns {String|Undefined} prefixed */ - 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); - }; + function prefixed(obj, property) { + var prefix, prop; + var camelProp = property[0].toUpperCase() + property.slice(1); - /** - * 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); + var i = 0; + while (i < VENDOR_PREFIXES.length) { + prefix = VENDOR_PREFIXES[i]; + prop = (prefix) ? prefix + camelProp : property; - for (var key in removeStyles) { - if (removeStyles.hasOwnProperty(key)) { - delete styles[key]; + if (prop in obj) { + return prop; + } + i++; } - } + return undefined; + } - element.style.cssText = cssUtil.join(styles); - }; + /** + * get a unique id + * @returns {number} uniqueId + */ + var _uniqueId = 1; + function uniqueId() { + return _uniqueId++; + } /** - * https://gist.github.com/mjijackson/5311256 - * @param h - * @param s - * @param v - * @returns {{r: number, g: number, b: number}} - * @constructor + * get the window object of an element + * @param {HTMLElement} element + * @returns {DocumentView|Window} */ - exports.HSVToRGB = function (h, s, v) { - var r, g, b; + function getWindowForElement(element) { + var doc = element.ownerDocument; + return (doc.defaultView || doc.parentWindow); + } - 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); + var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i; - 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; - } + var SUPPORT_TOUCH = ('ontouchstart' in window); + var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined; + var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent); - return { r: Math.floor(r * 255), g: Math.floor(g * 255), b: Math.floor(b * 255) }; - }; + var INPUT_TYPE_TOUCH = 'touch'; + var INPUT_TYPE_PEN = 'pen'; + var INPUT_TYPE_MOUSE = 'mouse'; + var INPUT_TYPE_KINECT = 'kinect'; - exports.HSVToHex = function (h, s, v) { - var rgb = exports.HSVToRGB(h, s, v); - return exports.RGBToHex(rgb.r, rgb.g, rgb.b); - }; + var COMPUTE_INTERVAL = 25; - exports.hexToHSV = function (hex) { - var rgb = exports.hexToRGB(hex); - return exports.RGBToHSV(rgb.r, rgb.g, rgb.b); - }; + var INPUT_START = 1; + var INPUT_MOVE = 2; + var INPUT_END = 4; + var INPUT_CANCEL = 8; - exports.isValidHex = function (hex) { - var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex); - return isOk; - }; + var DIRECTION_NONE = 1; + var DIRECTION_LEFT = 2; + var DIRECTION_RIGHT = 4; + var DIRECTION_UP = 8; + var DIRECTION_DOWN = 16; - 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; - }; + var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT; + var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN; + var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL; - /** - * This recursively redirects the prototype of JSON objects to the referenceObject - * This is used for default options. - * - * @param referenceObject - * @returns {*} - */ - exports.selectiveBridgeObject = function (fields, referenceObject) { - if (typeof referenceObject == 'object') { - var objectTo = Object.create(referenceObject); - for (var i = 0; i < fields.length; i++) { - if (referenceObject.hasOwnProperty(fields[i])) { - if (typeof referenceObject[fields[i]] == 'object') { - objectTo[fields[i]] = exports.bridgeObject(referenceObject[fields[i]]); - } - } - } - return objectTo; - } else { - return null; - } - }; + var PROPS_XY = ['x', 'y']; + var PROPS_CLIENT_XY = ['clientX', 'clientY']; /** - * This recursively redirects the prototype of JSON objects to the referenceObject - * This is used for default options. - * - * @param referenceObject - * @returns {*} + * create new input type manager + * @param {Manager} manager + * @param {Function} callback + * @returns {Input} + * @constructor */ - exports.bridgeObject = function (referenceObject) { - if (typeof referenceObject == 'object') { - var objectTo = Object.create(referenceObject); - for (var i in referenceObject) { - if (referenceObject.hasOwnProperty(i)) { - if (typeof referenceObject[i] == 'object') { - objectTo[i] = exports.bridgeObject(referenceObject[i]); + function Input(manager, callback) { + var self = this; + this.manager = manager; + this.callback = callback; + this.element = manager.element; + this.target = manager.options.inputTarget; + + // smaller wrapper around the handler, for the scope and the enabled state of the manager, + // so when disabled the input events are completely bypassed. + this.domHandler = function(ev) { + if (boolOrFn(manager.options.enable, [manager])) { + self.handler(ev); } - } + }; + + this.init(); + + } + + Input.prototype = { + /** + * should handle the inputEvent data and trigger the callback + * @virtual + */ + handler: function() { }, + + /** + * bind the events + */ + init: function() { + this.evEl && addEventListeners(this.element, this.evEl, this.domHandler); + this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler); + this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); + }, + + /** + * unbind the events + */ + destroy: function() { + this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler); + this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler); + this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); } - return objectTo; - } else { - return null; - } }; /** - * 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. - * - * @param [object] mergeTarget | this is either this.options or the options used for the groups. - * @param [object] options | options - * @param [String] option | this is the option key in the options argument - * @private + * create new input type manager + * called by the Manager constructor + * @param {Hammer} manager + * @returns {Input} */ - exports.mergeOptions = function (mergeTarget, options, option) { - var allowDeletion = arguments[3] === undefined ? false : arguments[3]; + function createInputInstance(manager) { + var Type; + var inputClass = manager.options.inputClass; - if (options[option] === null) { - mergeTarget[option] = undefined; - delete mergeTarget[option]; - } else { - if (options[option] !== undefined) { - if (typeof options[option] === 'boolean') { - mergeTarget[option].enabled = options[option]; - } else { - if (options[option].enabled === undefined) { - mergeTarget[option].enabled = true; - } - for (var prop in options[option]) { - if (options[option].hasOwnProperty(prop)) { - mergeTarget[option][prop] = options[option][prop]; - } - } - } + if (inputClass) { + Type = inputClass; + } else if (SUPPORT_POINTER_EVENTS) { + Type = PointerEventInput; + } else if (SUPPORT_ONLY_TOUCH) { + Type = TouchInput; + } else if (!SUPPORT_TOUCH) { + Type = MouseInput; + } else { + Type = TouchMouseInput; } - } - }; + return new (Type)(manager, inputHandler); + } /** - * 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} searchFunction | -1 is lower, 0 is found, 1 is higher - * @param {String} field - * @param {String} field2 - * @returns {number} - * @private + * handle input events + * @param {Manager} manager + * @param {String} eventType + * @param {Object} input */ - exports.binarySearchCustom = function (orderedItems, searchFunction, 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); + function inputHandler(manager, eventType, input) { + var pointersLen = input.pointers.length; + var changedPointersLen = input.changedPointers.length; + var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0)); + var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0)); - var item = orderedItems[middle]; - var value = field2 === undefined ? item[field] : item[field][field2]; + input.isFirst = !!isFirst; + input.isFinal = !!isFinal; - var searchResult = searchFunction(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; + if (isFirst) { + manager.session = {}; } - iteration++; - } + // source event is the normalized value of the domEvents + // like 'touchstart, mouseup, pointerdown' + input.eventType = eventType; - return -1; - }; + // compute scale, rotation etc + computeInputData(manager, input); + + // emit secret event + manager.emit('hammer.input', input); + + manager.recognize(input); + manager.session.prevInput = input; + } /** - * 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' - * @returns {number} - * @private - */ - exports.binarySearchValue = function (orderedItems, target, field, sidePreference) { - var maxIterations = 10000; - var iteration = 0; - var low = 0; - var high = orderedItems.length - 1; - var prevValue, value, nextValue, middle; + * extend the data with some usable properties like scale, rotate, velocity etc + * @param {Object} manager + * @param {Object} input + */ + function computeInputData(manager, input) { + var session = manager.session; + var pointers = input.pointers; + var pointersLength = pointers.length; - 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]; + // store the first input to calculate the distance and direction + if (!session.firstInput) { + session.firstInput = simpleCloneInputData(input); + } - if (value == target) { - // we found the target - return middle; - } else if (prevValue < target && value > target) { - // target is in between of the previous and the current - return sidePreference == 'before' ? Math.max(0, middle - 1) : middle; - } else if (value < target && nextValue > target) { - // 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 (value < target) { - // it is too small --> increase low - low = middle + 1; - } else { - // it is too big --> decrease high - high = middle - 1; - } + // to compute scale and rotation we need to store the multiple touches + if (pointersLength > 1 && !session.firstMultiple) { + session.firstMultiple = simpleCloneInputData(input); + } else if (pointersLength === 1) { + session.firstMultiple = false; } - iteration++; - } - // didnt find anything. Return -1. - return -1; - }; + var firstInput = session.firstInput; + var firstMultiple = session.firstMultiple; + var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center; - /* - * 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 < 0.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 < 0.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 < 0.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 < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t; - } - }; + var center = input.center = getCenter(pointers); + input.timeStamp = now(); + input.deltaTime = input.timeStamp - firstInput.timeStamp; -/***/ }, -/* 3 */ -/***/ function(module, exports, __webpack_require__) { + input.angle = getAngle(offsetCenter, center); + input.distance = getDistance(offsetCenter, center); - // DOM utility methods + computeDeltaXY(session, input); + input.offsetDirection = getDirection(input.deltaX, input.deltaY); - /** - * this prepares the JSON container for allocating SVG elements - * @param JSONcontainer - * @private - */ - 'use strict'; + input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1; + input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0; - 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 = []; + computeIntervalInputData(session, input); + + // find the correct target + var target = manager.element; + if (hasParent(input.srcEvent.target, target)) { + target = input.srcEvent.target; } - } - }; + input.target = target; + } - /** - * 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 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 = []; - } + function computeDeltaXY(session, input) { + var center = input.center; + var offset = session.offsetDelta || {}; + var prevDelta = session.prevDelta || {}; + var prevInput = session.prevInput || {}; + + if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) { + prevDelta = session.prevDelta = { + x: prevInput.deltaX || 0, + y: prevInput.deltaY || 0 + }; + + offset = session.offsetDelta = { + x: center.x, + y: center.y + }; } - } - }; + + input.deltaX = prevDelta.x + (center.x - offset.x); + input.deltaY = prevDelta.y + (center.y - offset.y); + } /** - * 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 elementType - * @param JSONcontainer - * @param svgContainer - * @returns {*} - * @private + * velocity is calculated every x ms + * @param {Object} session + * @param {Object} input */ - 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(); + function computeIntervalInputData(session, input) { + var last = session.lastInterval || input, + deltaTime = input.timeStamp - last.timeStamp, + velocity, velocityX, velocityY, direction; + + if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) { + var deltaX = last.deltaX - input.deltaX; + var deltaY = last.deltaY - input.deltaY; + + var v = getVelocity(deltaTime, deltaX, deltaY); + velocityX = v.x; + velocityY = v.y; + velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y; + direction = getDirection(deltaX, deltaY); + + session.lastInterval = input; } else { - // create a new element and add it to the SVG - element = document.createElementNS('http://www.w3.org/2000/svg', elementType); - svgContainer.appendChild(element); + // use latest velocity info if it doesn't overtake a minimum period + velocity = last.velocity; + velocityX = last.velocityX; + velocityY = last.velocityY; + direction = last.direction; } - } 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; - }; + + input.velocity = velocity; + input.velocityX = velocityX; + input.velocityY = velocityY; + input.direction = direction; + } /** - * 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 elementType - * @param JSONcontainer - * @param DOMContainer - * @returns {*} - * @private + * create a simple clone from the input used for storage of firstInput and firstMultiple + * @param {Object} input + * @returns {Object} clonedInputData */ - 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); + function simpleCloneInputData(input) { + // make a simple copy of the pointers because we will get a reference if we don't + // we only need clientXY for the calculations + var pointers = []; + var i = 0; + while (i < input.pointers.length) { + pointers[i] = { + clientX: round(input.pointers[i].clientX), + clientY: round(input.pointers[i].clientY) + }; + i++; } - } - JSONcontainer[elementType].used.push(element); - return element; - }; + + return { + timeStamp: now(), + pointers: pointers, + center: getCenter(pointers), + deltaX: input.deltaX, + deltaY: input.deltaY + }; + } /** - * draw a point object. this is a seperate 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 x - * @param y - * @param group - * @param JSONcontainer - * @param svgContainer - * @param labelObj - * @returns {*} + * get the center of all the pointers + * @param {Array} pointers + * @return {Object} center contains `x` and `y` properties */ - exports.drawPoint = function (x, y, group, JSONcontainer, svgContainer, labelObj) { - var point; - if (group.options.drawPoints.style == 'circle') { - point = exports.getSVGElement('circle', JSONcontainer, svgContainer); - point.setAttributeNS(null, 'cx', x); - point.setAttributeNS(null, 'cy', y); - point.setAttributeNS(null, 'r', 0.5 * group.options.drawPoints.size); - } else { - point = exports.getSVGElement('rect', JSONcontainer, svgContainer); - point.setAttributeNS(null, 'x', x - 0.5 * group.options.drawPoints.size); - point.setAttributeNS(null, 'y', y - 0.5 * group.options.drawPoints.size); - point.setAttributeNS(null, 'width', group.options.drawPoints.size); - point.setAttributeNS(null, 'height', group.options.drawPoints.size); - } - - if (group.options.drawPoints.styles !== undefined) { - point.setAttributeNS(null, 'style', group.group.options.drawPoints.styles); - } - point.setAttributeNS(null, 'class', group.className + ' vis-point'); - //handle label + function getCenter(pointers) { + var pointersLength = pointers.length; - if (labelObj) { - var label = exports.getSVGElement('text', JSONcontainer, svgContainer); - if (labelObj.xOffset) { - x = x + labelObj.xOffset; + // no need to loop when only one touch + if (pointersLength === 1) { + return { + x: round(pointers[0].clientX), + y: round(pointers[0].clientY) + }; } - if (labelObj.yOffset) { - y = y + labelObj.yOffset; - } - if (labelObj.content) { - label.textContent = labelObj.content; + var x = 0, y = 0, i = 0; + while (i < pointersLength) { + x += pointers[i].clientX; + y += pointers[i].clientY; + i++; } - if (labelObj.className) { - label.setAttributeNS(null, 'class', labelObj.className + ' vis-label'); - } - label.setAttributeNS(null, 'x', x); - label.setAttributeNS(null, 'y', y); - } + return { + x: round(x / pointersLength), + y: round(y / pointersLength) + }; + } - return point; - }; + /** + * calculate the velocity between two points. unit is in px per ms. + * @param {Number} deltaTime + * @param {Number} x + * @param {Number} y + * @return {Object} velocity `x` and `y` + */ + function getVelocity(deltaTime, x, y) { + return { + x: x / deltaTime || 0, + y: y / deltaTime || 0 + }; + } /** - * draw a bar SVG element centered on the X coordinate - * - * @param x - * @param y - * @param className + * get the direction between two points + * @param {Number} x + * @param {Number} y + * @return {Number} direction */ - exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer, style) { - if (height != 0) { - if (height < 0) { - height *= -1; - y -= height; + function getDirection(x, y) { + if (x === y) { + return DIRECTION_NONE; } - 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); + + if (abs(x) >= abs(y)) { + return x > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; } - } - }; + return y > 0 ? DIRECTION_UP : DIRECTION_DOWN; + } -/***/ }, -/* 4 */ -/***/ function(module, exports, __webpack_require__) { + /** + * calculate the absolute distance between two points + * @param {Object} p1 {x, y} + * @param {Object} p2 {x, y} + * @param {Array} [props] containing x and y keys + * @return {Number} distance + */ + function getDistance(p1, p2, props) { + if (!props) { + props = PROPS_XY; + } + var x = p2[props[0]] - p1[props[0]], + y = p2[props[1]] - p1[props[1]]; - 'use strict'; + return Math.sqrt((x * x) + (y * y)); + } - var util = __webpack_require__(2); - var Queue = __webpack_require__(6); + /** + * calculate the angle between two coordinates + * @param {Object} p1 + * @param {Object} p2 + * @param {Array} [props] containing x and y keys + * @return {Number} angle + */ + function getAngle(p1, p2, props) { + if (!props) { + props = PROPS_XY; + } + var x = p2[props[0]] - p1[props[0]], + y = p2[props[1]] - p1[props[1]]; + return Math.atan2(y, x) * 180 / Math.PI; + } /** - * DataSet - * - * 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.} [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. - * @throws Error + * @constructor + * @extends Input */ - DataSet.prototype.get = function (args) { - var me = this; + function TouchMouseInput() { + Input.apply(this, arguments); - // 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]; - } + var handler = bindFn(this.handler, this); + this.touch = new TouchInput(this.manager, handler); + this.mouse = new MouseInput(this.manager, handler); + } - // 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'; - } + inherit(TouchMouseInput, Input, { + /** + * handle mouse and touch events + * @param {Hammer} manager + * @param {String} inputEvent + * @param {Object} inputData + */ + handler: function TMEhandler(manager, inputEvent, inputData) { + var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH), + isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE); - // build options - var type = options && options.type || this._options.type; - var filter = options && options.filter; - var items = [], - item, - itemId, - i, - len; + // when we're in a touch event, so block all upcoming mouse events + // most mobile browser also emit mouseevents, right after touchstart + if (isTouch) { + this.mouse.allow = false; + } else if (isMouse && !this.mouse.allow) { + return; + } - // convert items - if (id != undefined) { - // return a single item - item = me._getItem(id, type); - if (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 - for (itemId in this._data) { - if (this._data.hasOwnProperty(itemId)) { - item = me._getItem(itemId, type); - if (!filter || filter(item)) { - items.push(item); + // reset the allowMouse when we're done + if (inputEvent & (INPUT_END | INPUT_CANCEL)) { + this.mouse.allow = true; } - } - } - } - // order the results - if (options && options.order && id == undefined) { - this._sort(items, options.order); - } + this.callback(manager, inputEvent, inputData); + }, - // 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); - } + /** + * remove the event listeners + */ + destroy: function destroy() { + this.touch.destroy(); + this.mouse.destroy(); } - } + }); - // return the results - if (returnType == 'Object') { - var result = {}; - for (i = 0; i < items.length; i++) { - result[items[i].id] = items[i]; - } - return result; - } else { - if (id != undefined) { - // a single item - return item; - } else { - // just return our array - return items; - } - } - }; + var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction'); + var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined; + + // magical touchAction value + var TOUCH_ACTION_COMPUTE = 'compute'; + var TOUCH_ACTION_AUTO = 'auto'; + var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented + var TOUCH_ACTION_NONE = 'none'; + var TOUCH_ACTION_PAN_X = 'pan-x'; + var TOUCH_ACTION_PAN_Y = 'pan-y'; /** - * 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 + * Touch Action + * sets the touchAction property or uses the js alternative + * @param {Manager} manager + * @param {String} value + * @constructor */ - DataSet.prototype.getIds = function (options) { - var data = this._data, - filter = options && options.filter, - order = options && options.order, - type = options && options.type || this._options.type, - i, - len, - id, - item, - items, - ids = []; + function TouchAction(manager, value) { + this.manager = manager; + this.set(value); + } - if (filter) { - // get filtered items - if (order) { - // create ordered list - items = []; - for (id in data) { - if (data.hasOwnProperty(id)) { - item = this._getItem(id, type); - if (filter(item)) { - items.push(item); - } + TouchAction.prototype = { + /** + * set the touchAction value on the element or enable the polyfill + * @param {String} value + */ + set: function(value) { + // find out the touch-action by the event handlers + if (value == TOUCH_ACTION_COMPUTE) { + value = this.compute(); } - } - - this._sort(items, order); - for (i = 0, len = items.length; i < len; i++) { - ids[i] = items[i][this._fieldId]; - } - } else { - // create unordered list - for (id in data) { - if (data.hasOwnProperty(id)) { - 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 (id in data) { - if (data.hasOwnProperty(id)) { - items.push(data[id]); + if (NATIVE_TOUCH_ACTION) { + this.manager.element.style[PREFIXED_TOUCH_ACTION] = value; } - } + this.actions = value.toLowerCase().trim(); + }, - this._sort(items, order); + /** + * just re-set the touchAction value + */ + update: function() { + this.set(this.manager.options.touchAction); + }, - for (i = 0, len = items.length; i < len; i++) { - ids[i] = items[i][this._fieldId]; - } - } else { - // create unordered list - for (id in data) { - if (data.hasOwnProperty(id)) { - item = data[id]; - ids.push(item[this._fieldId]); - } - } - } - } + /** + * compute the value for the touchAction property based on the recognizer's settings + * @returns {String} value + */ + compute: function() { + var actions = []; + each(this.manager.recognizers, function(recognizer) { + if (boolOrFn(recognizer.options.enable, [recognizer])) { + actions = actions.concat(recognizer.getTouchAction()); + } + }); + return cleanTouchActions(actions.join(' ')); + }, - return ids; - }; + /** + * this method is called on each input cycle and provides the preventing of the browser behavior + * @param {Object} input + */ + preventDefaults: function(input) { + // not needed with native support for the touchAction property + if (NATIVE_TOUCH_ACTION) { + return; + } - /** - * Returns the DataSet itself. Is overwritten for example by the DataView, - * which returns the DataSet it is connected to instead. - */ - DataSet.prototype.getDataSet = function () { - return this; - }; + var srcEvent = input.srcEvent; + var direction = input.offsetDirection; - /** - * 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, - item, - id; + // if the touch action did prevented once this session + if (this.manager.session.prevented) { + srcEvent.preventDefault(); + return; + } - if (options && options.order) { - // execute forEach on ordered list - var items = this.get(options); + var actions = this.actions; + var hasNone = inStr(actions, TOUCH_ACTION_NONE); + var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); + var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); - for (var i = 0, len = items.length; i < len; i++) { - item = items[i]; - id = item[this._fieldId]; - callback(item, id); - } - } else { - // unordered - for (id in data) { - if (data.hasOwnProperty(id)) { - item = this._getItem(id, type); - if (!filter || filter(item)) { - callback(item, id); + if (hasNone || + (hasPanY && direction & DIRECTION_HORIZONTAL) || + (hasPanX && direction & DIRECTION_VERTICAL)) { + return this.preventSrc(srcEvent); } - } + }, + + /** + * call preventDefault to prevent the browser's default behavior (scrolling in most cases) + * @param {Object} srcEvent + */ + preventSrc: function(srcEvent) { + this.manager.session.prevented = true; + srcEvent.preventDefault(); } - } }; /** - * 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 + * when the touchActions are collected they are not a valid value, so we need to clean things up. * + * @param {String} actions + * @returns {*} */ - DataSet.prototype.map = function (callback, options) { - var filter = options && options.filter, - type = options && options.type || this._options.type, - mappedItems = [], - data = this._data, - item; - - // convert and filter items - for (var id in data) { - if (data.hasOwnProperty(id)) { - item = this._getItem(id, type); - if (!filter || filter(item)) { - mappedItems.push(callback(item, id)); - } + function cleanTouchActions(actions) { + // none + if (inStr(actions, TOUCH_ACTION_NONE)) { + return TOUCH_ACTION_NONE; } - } - - // 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 hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); + var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); - var filteredItem = {}; + // pan-x and pan-y can be combined + if (hasPanX && hasPanY) { + return TOUCH_ACTION_PAN_X + ' ' + TOUCH_ACTION_PAN_Y; + } - if (Array.isArray(fields)) { - for (var field in item) { - if (item.hasOwnProperty(field) && fields.indexOf(field) != -1) { - filteredItem[field] = item[field]; - } + // pan-x OR pan-y + if (hasPanX || hasPanY) { + return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y; } - } else { - for (var field in item) { - if (item.hasOwnProperty(field) && fields.hasOwnProperty(field)) { - filteredItem[fields[field]] = item[field]; - } + + // manipulation + if (inStr(actions, TOUCH_ACTION_MANIPULATION)) { + return TOUCH_ACTION_MANIPULATION; } - } - return filteredItem; - }; + return TOUCH_ACTION_AUTO; + } /** - * Sort the provided array with items - * @param {Object[]} items - * @param {String | function} order A field name or custom sort function. - * @private + * Recognizer flow explained; * + * All recognizers have the initial state of POSSIBLE when a input session starts. + * The definition of a input session is from the first input until the last input, with all it's movement in it. * + * Example session for mouse-input: mousedown -> mousemove -> mouseup + * + * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed + * which determines with state it should be. + * + * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to + * POSSIBLE to give it another change on the next cycle. + * + * Possible + * | + * +-----+---------------+ + * | | + * +-----+-----+ | + * | | | + * Failed Cancelled | + * +-------+------+ + * | | + * Recognized Began + * | + * Changed + * | + * Ended/Recognized */ - 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'); - } - }; + var STATE_POSSIBLE = 1; + var STATE_BEGAN = 2; + var STATE_CHANGED = 4; + var STATE_ENDED = 8; + var STATE_RECOGNIZED = STATE_ENDED; + var STATE_CANCELLED = 16; + var STATE_FAILED = 32; /** - * 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 + * Recognizer + * Every recognizer needs to extend from this class. + * @constructor + * @param {Object} options */ - DataSet.prototype.remove = function (id, senderId) { - var removedIds = [], - i, - len, - removedId; - - if (Array.isArray(id)) { - for (i = 0, len = id.length; i < len; i++) { - removedId = this._remove(id[i]); - if (removedId != null) { - removedIds.push(removedId); - } - } - } else { - removedId = this._remove(id); - if (removedId != null) { - removedIds.push(removedId); - } - } - - if (removedIds.length) { - this._trigger('remove', { items: removedIds }, senderId); - } - - return removedIds; - }; + function Recognizer(options) { + this.id = uniqueId(); - /** - * 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) { - if (util.isNumber(id) || util.isString(id)) { - if (this._data[id]) { - delete this._data[id]; - this.length--; - return id; - } - } else if (id instanceof Object) { - var itemId = id[this._fieldId]; - if (itemId && this._data[itemId]) { - delete this._data[itemId]; - this.length--; - return itemId; - } - } - return null; - }; + this.manager = null; + this.options = merge(options || {}, this.defaults); - /** - * Clear the data - * @param {String} [senderId] Optional sender id - * @return {Array} removedIds The ids of all removed items - */ - DataSet.prototype.clear = function (senderId) { - var ids = Object.keys(this._data); + // default is enable true + this.options.enable = ifUndefined(this.options.enable, true); - this._data = {}; - this.length = 0; + this.state = STATE_POSSIBLE; - this._trigger('remove', { items: ids }, senderId); + this.simultaneous = {}; + this.requireFail = []; + } - return ids; - }; + Recognizer.prototype = { + /** + * @virtual + * @type {Object} + */ + defaults: {}, - /** - * 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, - max = null, - maxField = null; - - for (var id in data) { - if (data.hasOwnProperty(id)) { - var item = data[id]; - var itemField = item[field]; - if (itemField != null && (!max || itemField > maxField)) { - max = item; - maxField = itemField; - } - } - } + /** + * set options + * @param {Object} options + * @return {Recognizer} + */ + set: function(options) { + extend(this.options, options); - return max; - }; + // also update the touchAction, in case something changed about the directions/enabled state + this.manager && this.manager.touchAction.update(); + return this; + }, - /** - * 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, - min = null, - minField = null; + /** + * recognize simultaneous with an other recognizer. + * @param {Recognizer} otherRecognizer + * @returns {Recognizer} this + */ + recognizeWith: function(otherRecognizer) { + if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) { + return this; + } - for (var id in data) { - if (data.hasOwnProperty(id)) { - var item = data[id]; - var itemField = item[field]; - if (itemField != null && (!min || itemField < minField)) { - min = item; - minField = itemField; - } - } - } + var simultaneous = this.simultaneous; + otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); + if (!simultaneous[otherRecognizer.id]) { + simultaneous[otherRecognizer.id] = otherRecognizer; + otherRecognizer.recognizeWith(this); + } + return this; + }, - return min; - }; + /** + * drop the simultaneous link. it doesnt remove the link on the other recognizer. + * @param {Recognizer} otherRecognizer + * @returns {Recognizer} this + */ + dropRecognizeWith: function(otherRecognizer) { + if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) { + return this; + } - /** - * 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 values = []; - var fieldType = this._options.type && this._options.type[field] || null; - var count = 0; - var i; + otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); + delete this.simultaneous[otherRecognizer.id]; + return this; + }, - for (var prop in data) { - if (data.hasOwnProperty(prop)) { - var item = data[prop]; - var value = item[field]; - var exists = false; - for (i = 0; i < count; i++) { - if (values[i] == value) { - exists = true; - break; + /** + * recognizer can only run when an other is failing + * @param {Recognizer} otherRecognizer + * @returns {Recognizer} this + */ + requireFailure: function(otherRecognizer) { + if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) { + return this; } - } - if (!exists && value !== undefined) { - values[count] = value; - count++; - } - } - } - if (fieldType) { - for (i = 0; i < values.length; i++) { - values[i] = util.convert(values[i], fieldType); - } - } + var requireFail = this.requireFail; + otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); + if (inArray(requireFail, otherRecognizer) === -1) { + requireFail.push(otherRecognizer); + otherRecognizer.requireFailure(this); + } + return this; + }, - return values; - }; + /** + * drop the requireFailure link. it does not remove the link on the other recognizer. + * @param {Recognizer} otherRecognizer + * @returns {Recognizer} this + */ + dropRequireFailure: function(otherRecognizer) { + if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) { + return this; + } - /** - * 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]; + otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); + var index = inArray(this.requireFail, otherRecognizer); + if (index > -1) { + this.requireFail.splice(index, 1); + } + return this; + }, - 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; - } + /** + * has require failures boolean + * @returns {boolean} + */ + hasRequireFailures: function() { + return this.requireFail.length > 0; + }, - var d = {}; - for (var field in item) { - if (item.hasOwnProperty(field)) { - var fieldType = this._type[field]; // type may be undefined - d[field] = util.convert(item[field], fieldType); - } - } - this._data[id] = d; - this.length++; + /** + * if the recognizer can recognize simultaneous with an other recognizer + * @param {Recognizer} otherRecognizer + * @returns {Boolean} + */ + canRecognizeWith: function(otherRecognizer) { + return !!this.simultaneous[otherRecognizer.id]; + }, - return id; - }; + /** + * You should use `tryEmit` instead of `emit` directly to check + * that all the needed recognizers has failed before emitting. + * @param {Object} input + */ + emit: function(input) { + var self = this; + var state = this.state; - /** - * 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; + function emit(withState) { + self.manager.emit(self.options.event + (withState ? stateStr(state) : ''), input); + } - // get the item from the dataset - var raw = this._data[id]; - if (!raw) { - return null; - } + // 'panstart' and 'panmove' + if (state < STATE_ENDED) { + emit(true); + } - // convert the items field types - var converted = {}; - if (types) { - for (field in raw) { - if (raw.hasOwnProperty(field)) { - value = raw[field]; - converted[field] = util.convert(value, types[field]); - } - } - } else { - // no field types specified, no converting needed - for (field in raw) { - if (raw.hasOwnProperty(field)) { - value = raw[field]; - converted[field] = value; - } - } - } - return converted; - }; + emit(); // simple 'eventName' events - /** - * 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: ' + JSON.stringify(item) + ')'); - } - var d = this._data[id]; - if (!d) { - // item doesn't exist - throw new Error('Cannot update item: no item with id ' + id + ' found'); - } + // panend and pancancel + if (state >= STATE_ENDED) { + emit(true); + } + }, - // merge with current item - for (var field in item) { - if (item.hasOwnProperty(field)) { - var fieldType = this._type[field]; // type may be undefined - d[field] = util.convert(item[field], fieldType); - } - } + /** + * Check that all the require failure recognizers has failed, + * if true, it emits a gesture event, + * otherwise, setup the state to FAILED. + * @param {Object} input + */ + tryEmit: function(input) { + if (this.canEmit()) { + return this.emit(input); + } + // it's failing anyway + this.state = STATE_FAILED; + }, - return id; - }; + /** + * can we emit? + * @returns {boolean} + */ + canEmit: function() { + var i = 0; + while (i < this.requireFail.length) { + if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) { + return false; + } + i++; + } + return true; + }, - module.exports = DataSet; + /** + * update the recognizer + * @param {Object} inputData + */ + recognize: function(inputData) { + // make a new copy of the inputData + // so we can change the inputData without messing up the other recognizers + var inputDataClone = extend({}, inputData); -/***/ }, -/* 5 */ -/***/ function(module, exports, __webpack_require__) { + // is is enabled and allow recognizing? + if (!boolOrFn(this.options.enable, [this, inputDataClone])) { + this.reset(); + this.state = STATE_FAILED; + return; + } - 'use strict'; + // reset when we've reached the end + if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) { + this.state = STATE_POSSIBLE; + } - var util = __webpack_require__(2); - var DataSet = __webpack_require__(4); + this.state = this.process(inputDataClone); - /** - * 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 + // the recognizer has recognized a gesture + // so trigger an event + if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) { + this.tryEmit(inputDataClone); + } + }, - var me = this; - this.listener = function () { - me._onEvent.apply(me, arguments); - }; + /** + * return the state of the recognizer + * the actual recognizing happens in this method + * @virtual + * @param {Object} inputData + * @returns {Const} STATE + */ + process: function(inputData) { }, // jshint ignore:line - this.setData(data); - } + /** + * return the preferred touch-action + * @virtual + * @returns {Array} + */ + getTouchAction: function() { }, - // TODO: implement a function .config() to dynamically update things like configured filter - // and trigger changes accordingly + /** + * called when the gesture isn't allowed to recognize + * like when another is being recognized or it is disabled + * @virtual + */ + reset: function() { } + }; /** - * Set a data source for the view - * @param {DataSet | DataView} data + * get a usable string, used as event postfix + * @param {Const} state + * @returns {String} state */ - DataView.prototype.setData = function (data) { - var ids, i, len; - - 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 = []; - for (var id in this._ids) { - if (this._ids.hasOwnProperty(id)) { - ids.push(id); - } + function stateStr(state) { + if (state & STATE_CANCELLED) { + return 'cancel'; + } else if (state & STATE_ENDED) { + return 'end'; + } else if (state & STATE_CHANGED) { + return 'move'; + } else if (state & STATE_BEGAN) { + return 'start'; } - this._ids = {}; - this.length = 0; - this._trigger('remove', { items: ids }); - } - - this._data = data; - - if (this._data) { - // update fieldId - this._fieldId = this._options.fieldId || this._data && this._data.options && this._data.options.fieldId || 'id'; + return ''; + } - // 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; + /** + * direction cons to string + * @param {Const} direction + * @returns {String} + */ + function directionStr(direction) { + if (direction == DIRECTION_DOWN) { + return 'down'; + } else if (direction == DIRECTION_UP) { + return 'up'; + } else if (direction == DIRECTION_LEFT) { + return 'left'; + } else if (direction == DIRECTION_RIGHT) { + return 'right'; } - this.length = ids.length; - this._trigger('add', { items: ids }); + return ''; + } - // subscribe to new dataset - if (this._data.on) { - this._data.on('*', this.listener); + /** + * get a recognizer by name if it is bound to a manager + * @param {Recognizer|String} otherRecognizer + * @param {Recognizer} recognizer + * @returns {Recognizer} + */ + function getRecognizerByNameIfManager(otherRecognizer, recognizer) { + var manager = recognizer.manager; + if (manager) { + return manager.get(otherRecognizer); } - } - }; + return otherRecognizer; + } /** - * Refresh the DataView. Useful when the DataView has a filter function - * containing a variable parameter. + * This recognizer is just used as a base for the simple attribute recognizers. + * @constructor + * @extends Recognizer */ - DataView.prototype.refresh = function () { - var id; - var ids = this._data.getIds({ filter: this._options && this._options.filter }); - var newIds = {}; - var added = []; - var removed = []; - - // check for additions - for (var i = 0; i < ids.length; i++) { - id = ids[i]; - newIds[id] = true; - if (!this._ids[id]) { - added.push(id); - this._ids[id] = true; - this.length++; - } - } + function AttrRecognizer() { + Recognizer.apply(this, arguments); + } - // check for removals - for (id in this._ids) { - if (this._ids.hasOwnProperty(id)) { - if (!newIds[id]) { - removed.push(id); - delete this._ids[id]; - this.length--; - } - } - } + inherit(AttrRecognizer, Recognizer, { + /** + * @namespace + * @memberof AttrRecognizer + */ + defaults: { + /** + * @type {Number} + * @default 1 + */ + pointers: 1 + }, - // trigger events - if (added.length) { - this._trigger('add', { items: added }); - } - if (removed.length) { - this._trigger('remove', { items: removed }); - } - }; + /** + * Used to check if it the recognizer receives valid input, like input.distance > 10. + * @memberof AttrRecognizer + * @param {Object} input + * @returns {Boolean} recognized + */ + attrTest: function(input) { + var optionPointers = this.options.pointers; + return optionPointers === 0 || input.pointers.length === optionPointers; + }, + + /** + * Process the input and return the state for the recognizer + * @memberof AttrRecognizer + * @param {Object} input + * @returns {*} State + */ + process: function(input) { + var state = this.state; + var eventType = input.eventType; + + var isRecognized = state & (STATE_BEGAN | STATE_CHANGED); + var isValid = this.attrTest(input); + + // on cancel input and we've recognized before, return STATE_CANCELLED + if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) { + return state | STATE_CANCELLED; + } else if (isRecognized || isValid) { + if (eventType & INPUT_END) { + return state | STATE_ENDED; + } else if (!(state & STATE_BEGAN)) { + return STATE_BEGAN; + } + return state | STATE_CHANGED; + } + return STATE_FAILED; + } + }); /** - * 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 args + * Pan + * Recognized when the pointer is down and moved in the allowed direction. + * @constructor + * @extends AttrRecognizer */ - DataView.prototype.get = function (args) { - var me = this; + function PanRecognizer() { + AttrRecognizer.apply(this, arguments); - // 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]; - } + this.pX = null; + this.pY = null; + } - // extend the options with the default options and provided options - var viewOptions = util.extend({}, this._options, options); + inherit(PanRecognizer, AttrRecognizer, { + /** + * @namespace + * @memberof PanRecognizer + */ + defaults: { + event: 'pan', + threshold: 10, + pointers: 1, + direction: DIRECTION_ALL + }, - // 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); - }; - } + getTouchAction: function() { + var direction = this.options.direction; + var actions = []; + if (direction & DIRECTION_HORIZONTAL) { + actions.push(TOUCH_ACTION_PAN_Y); + } + if (direction & DIRECTION_VERTICAL) { + actions.push(TOUCH_ACTION_PAN_X); + } + return actions; + }, - // build up the call to the linked data set - var getArguments = []; - if (ids != undefined) { - getArguments.push(ids); - } - getArguments.push(viewOptions); - getArguments.push(data); + directionTest: function(input) { + var options = this.options; + var hasMoved = true; + var distance = input.distance; + var direction = input.direction; + var x = input.deltaX; + var y = input.deltaY; - return this._data && this._data.get.apply(this._data, getArguments); - }; + // lock to axis? + if (!(direction & options.direction)) { + if (options.direction & DIRECTION_HORIZONTAL) { + direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; + hasMoved = x != this.pX; + distance = Math.abs(input.deltaX); + } else { + direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN; + hasMoved = y != this.pY; + distance = Math.abs(input.deltaY); + } + } + input.direction = direction; + return hasMoved && distance > options.threshold && direction & options.direction; + }, + + attrTest: function(input) { + return AttrRecognizer.prototype.attrTest.call(this, input) && + (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input))); + }, + + emit: function(input) { + this.pX = input.deltaX; + this.pY = input.deltaY; + + var direction = directionStr(input.direction); + if (direction) { + this.manager.emit(this.options.event + direction, input); + } + + this._super.emit.call(this, input); + } + }); /** - * 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 + * Pinch + * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out). + * @constructor + * @extends AttrRecognizer */ - DataView.prototype.getIds = function (options) { - var ids; + function PinchRecognizer() { + AttrRecognizer.apply(this, arguments); + } - if (this._data) { - var defaultFilter = this._options.filter; - var filter; + inherit(PinchRecognizer, AttrRecognizer, { + /** + * @namespace + * @memberof PinchRecognizer + */ + defaults: { + event: 'pinch', + threshold: 0, + pointers: 2 + }, - if (options && options.filter) { - if (defaultFilter) { - filter = function (item) { - return defaultFilter(item) && options.filter(item); - }; - } else { - filter = options.filter; - } - } else { - filter = defaultFilter; - } + getTouchAction: function() { + return [TOUCH_ACTION_NONE]; + }, - ids = this._data.getIds({ - filter: filter, - order: options && options.order - }); - } else { - ids = []; - } + attrTest: function(input) { + return this._super.attrTest.call(this, input) && + (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN); + }, - return ids; - }; + emit: function(input) { + this._super.emit.call(this, input); + if (input.scale !== 1) { + var inOut = input.scale < 1 ? 'in' : 'out'; + this.manager.emit(this.options.event + inOut, input); + } + } + }); /** - * 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 + * Press + * Recognized when the pointer is down for x ms without any movement. + * @constructor + * @extends Recognizer */ - DataView.prototype.getDataSet = function () { - var dataSet = this; - while (dataSet instanceof DataView) { - dataSet = dataSet._data; - } - return dataSet || null; - }; + function PressRecognizer() { + Recognizer.apply(this, arguments); - /** - * 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 data = this._data; - var updatedData = []; - var added = []; - var updated = []; - var removed = []; + this._timer = null; + this._input = null; + } - if (ids && 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; - added.push(id); - } - } + inherit(PressRecognizer, Recognizer, { + /** + * @namespace + * @memberof PressRecognizer + */ + defaults: { + event: 'press', + pointers: 1, + time: 500, // minimal time of the pointer to be pressed + threshold: 5 // a minimal movement is ok, but keep it low + }, - break; + getTouchAction: function() { + return [TOUCH_ACTION_AUTO]; + }, - 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); + process: function(input) { + var options = this.options; + var validPointers = input.pointers.length === options.pointers; + var validMovement = input.distance < options.threshold; + var validTime = input.deltaTime > options.time; - if (item) { - if (this._ids[id]) { - updated.push(id); - updatedData.push(params.data[i]); - } else { - this._ids[id] = true; - added.push(id); - } - } else { - if (this._ids[id]) { - delete this._ids[id]; - removed.push(id); - } else {} - } + this._input = input; + + // we only allow little movement + // and we've reached an end event, so a tap is possible + if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) { + this.reset(); + } else if (input.eventType & INPUT_START) { + this.reset(); + this._timer = setTimeoutContext(function() { + this.state = STATE_RECOGNIZED; + this.tryEmit(); + }, options.time, this); + } else if (input.eventType & INPUT_END) { + return STATE_RECOGNIZED; } + return STATE_FAILED; + }, - break; + reset: function() { + clearTimeout(this._timer); + }, - 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]; - removed.push(id); - } + emit: function(input) { + if (this.state !== STATE_RECOGNIZED) { + return; } - break; + if (input && (input.eventType & INPUT_END)) { + this.manager.emit(this.options.event + 'up', input); + } else { + this._input.timeStamp = now(); + this.manager.emit(this.options.event, this._input); + } } + }); - this.length += added.length - removed.length; + /** + * Rotate + * Recognized when two or more pointer are moving in a circular motion. + * @constructor + * @extends AttrRecognizer + */ + function RotateRecognizer() { + AttrRecognizer.apply(this, arguments); + } - if (added.length) { - this._trigger('add', { items: added }, senderId); - } - if (updated.length) { - this._trigger('update', { items: updated, data: updatedData }, senderId); - } - if (removed.length) { - this._trigger('remove', { items: removed }, senderId); + inherit(RotateRecognizer, AttrRecognizer, { + /** + * @namespace + * @memberof RotateRecognizer + */ + defaults: { + event: 'rotate', + threshold: 0, + pointers: 2 + }, + + getTouchAction: function() { + return [TOUCH_ACTION_NONE]; + }, + + attrTest: function(input) { + return this._super.attrTest.call(this, input) && + (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN); } - } - }; + }); - // copy subscription functionality from DataSet - DataView.prototype.on = DataSet.prototype.on; - DataView.prototype.off = DataSet.prototype.off; - DataView.prototype._trigger = DataSet.prototype._trigger; + /** + * Swipe + * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction. + * @constructor + * @extends AttrRecognizer + */ + function SwipeRecognizer() { + AttrRecognizer.apply(this, arguments); + } - // 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; + inherit(SwipeRecognizer, AttrRecognizer, { + /** + * @namespace + * @memberof SwipeRecognizer + */ + defaults: { + event: 'swipe', + threshold: 10, + velocity: 0.65, + direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL, + pointers: 1 + }, - module.exports = DataView; + getTouchAction: function() { + return PanRecognizer.prototype.getTouchAction.call(this); + }, - // nothing interesting for me :-( + attrTest: function(input) { + var direction = this.options.direction; + var velocity; -/***/ }, -/* 6 */ -/***/ function(module, exports, __webpack_require__) { + if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) { + velocity = input.velocity; + } else if (direction & DIRECTION_HORIZONTAL) { + velocity = input.velocityX; + } else if (direction & DIRECTION_VERTICAL) { + velocity = input.velocityY; + } + + return this._super.attrTest.call(this, input) && + direction & input.direction && + input.distance > this.options.threshold && + abs(velocity) > this.options.velocity && input.eventType & INPUT_END; + }, + + emit: function(input) { + var direction = directionStr(input.direction); + if (direction) { + this.manager.emit(this.options.event + direction, input); + } + + this.manager.emit(this.options.event, input); + } + }); /** - * 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. + * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur + * between the given interval and position. The delay option can be used to recognize multi-taps without firing + * a single tap. + * + * The eventData from the emitted event contains the property `tapCount`, which contains the amount of + * multi-taps being recognized. * @constructor + * @extends Recognizer */ - 'use strict'; - - function Queue(options) { - // options - this.delay = null; - this.max = Infinity; + function TapRecognizer() { + Recognizer.apply(this, arguments); - // properties - this._queue = []; - this._timeout = null; - this._extended = null; + // previous time and center, + // used for tap counting + this.pTime = false; + this.pCenter = false; - this.setOptions(options); + this._timer = null; + this._input = null; + this.count = 0; } - /** - * 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. - * @param options - */ - 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; - } + inherit(TapRecognizer, Recognizer, { + /** + * @namespace + * @memberof PinchRecognizer + */ + defaults: { + event: 'tap', + pointers: 1, + taps: 1, + interval: 300, // max time between the multi-tap taps + time: 250, // max time of the pointer to be down (like finger on the screen) + threshold: 2, // a minimal movement is ok, but keep it low + posThreshold: 10 // a multi-tap can be a bit off the initial position + }, - this._flushIfNeeded(); - }; + getTouchAction: function() { + return [TOUCH_ACTION_MANIPULATION]; + }, - /** - * 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); + process: function(input) { + var options = this.options; - if (object.flush !== undefined) { - throw new Error('Target object already has a property flush'); - } - object.flush = function () { - queue.flush(); - }; + var validPointers = input.pointers.length === options.pointers; + var validMovement = input.distance < options.threshold; + var validTouchTime = input.deltaTime < options.time; - var methods = [{ - name: 'flush', - original: undefined - }]; + this.reset(); - 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); - } - } + if ((input.eventType & INPUT_START) && (this.count === 0)) { + return this.failTimeout(); + } - queue._extended = { - object: object, - methods: methods - }; + // we only allow little movement + // and we've reached an end event, so a tap is possible + if (validMovement && validTouchTime && validPointers) { + if (input.eventType != INPUT_END) { + return this.failTimeout(); + } - return queue; - }; + var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true; + var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold; - /** - * 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(); + this.pTime = input.timeStamp; + this.pCenter = input.center; - 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; - } - }; + if (!validMultiTap || !validInterval) { + this.count = 1; + } else { + this.count += 1; + } - /** - * 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'); - } + this._input = input; - object[method] = function () { - // create an Array with the arguments - var args = []; - for (var i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } + // if tap count matches we have recognized it, + // else it has began recognizing... + var tapCount = this.count % options.taps; + if (tapCount === 0) { + // no failing requirements, immediately trigger the tap event + // or wait as long as the multitap interval to trigger + if (!this.hasRequireFailures()) { + return STATE_RECOGNIZED; + } else { + this._timer = setTimeoutContext(function() { + this.state = STATE_RECOGNIZED; + this.tryEmit(); + }, options.interval, this); + return STATE_BEGAN; + } + } + } + return STATE_FAILED; + }, - // add this call to the queue - me.queue({ - args: args, - fn: original, - context: this - }); - }; - }; + failTimeout: function() { + this._timer = setTimeoutContext(function() { + this.state = STATE_FAILED; + }, this.options.interval, this); + return STATE_FAILED; + }, - /** - * 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); - } + reset: function() { + clearTimeout(this._timer); + }, - this._flushIfNeeded(); - }; + emit: function() { + if (this.state == STATE_RECOGNIZED ) { + this._input.tapCount = this.count; + this.manager.emit(this.options.event, this._input); + } + } + }); /** - * Check whether the queue needs to be flushed - * @private + * Simple way to create an manager with a default set of recognizers. + * @param {HTMLElement} element + * @param {Object} [options] + * @constructor */ - 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); - } - }; + function Hammer(element, options) { + options = options || {}; + options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset); + return new Manager(element, options); + } /** - * Flush all queued calls + * @const {string} */ - Queue.prototype.flush = function () { - while (this._queue.length > 0) { - var entry = this._queue.shift(); - entry.fn.apply(entry.context || entry.fn, entry.args || []); - } - }; + Hammer.VERSION = '2.0.4'; - module.exports = Queue; + /** + * default settings + * @namespace + */ + Hammer.defaults = { + /** + * set if DOM events are being triggered. + * But this is slower and unused by simple implementations, so disabled by default. + * @type {Boolean} + * @default false + */ + domEvents: false, -/***/ }, -/* 7 */ -/***/ function(module, exports, __webpack_require__) { + /** + * The value for the touchAction property/fallback. + * When set to `compute` it will magically set the correct value based on the added recognizers. + * @type {String} + * @default compute + */ + touchAction: TOUCH_ACTION_COMPUTE, - 'use strict'; + /** + * @type {Boolean} + * @default true + */ + enable: true, - var Emitter = __webpack_require__(43); - var DataSet = __webpack_require__(4); - var DataView = __webpack_require__(5); - var util = __webpack_require__(2); - var Point3d = __webpack_require__(11); - var Point2d = __webpack_require__(10); - var Camera = __webpack_require__(8); - var Filter = __webpack_require__(9); - var Slider = __webpack_require__(12); - var StepNumber = __webpack_require__(13); + /** + * EXPERIMENTAL FEATURE -- can be removed/changed + * Change the parent input target element. + * If Null, then it is being set the to main element. + * @type {Null|EventTarget} + * @default null + */ + inputTarget: null, - /** - * @constructor Graph3d - * Graph3d displays data in 3d. - * - * Graph3d is developed in javascript as a Google Visualization Chart. - * - * @param {Element} container The DOM element in which the Graph3d will - * be created. Normally a div element. - * @param {DataSet | DataView | Array} [data] - * @param {Object} [options] - */ - function Graph3d(container, data, options) { - if (!(this instanceof Graph3d)) { - throw new SyntaxError('Constructor must be called with the new operator'); - } + /** + * force an input class + * @type {Null|Function} + * @default null + */ + inputClass: null, - // create variables and set default values - this.containerElement = container; - this.width = '400px'; - this.height = '400px'; - this.margin = 10; // px - this.defaultXCenter = '55%'; - this.defaultYCenter = '50%'; + /** + * Default recognizer setup when calling `Hammer()` + * When creating a new Manager these will be skipped. + * @type {Array} + */ + preset: [ + // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...] + [RotateRecognizer, { enable: false }], + [PinchRecognizer, { enable: false }, ['rotate']], + [SwipeRecognizer,{ direction: DIRECTION_HORIZONTAL }], + [PanRecognizer, { direction: DIRECTION_HORIZONTAL }, ['swipe']], + [TapRecognizer], + [TapRecognizer, { event: 'doubletap', taps: 2 }, ['tap']], + [PressRecognizer] + ], - this.xLabel = 'x'; - this.yLabel = 'y'; - this.zLabel = 'z'; + /** + * Some CSS properties can be used to improve the working of Hammer. + * Add them to this method and they will be set when creating a new Manager. + * @namespace + */ + cssProps: { + /** + * Disables text selection to improve the dragging gesture. Mainly for desktop browsers. + * @type {String} + * @default 'none' + */ + userSelect: 'none', - var passValueFn = function passValueFn(v) { - return v; - }; - this.xValueLabel = passValueFn; - this.yValueLabel = passValueFn; - this.zValueLabel = passValueFn; + /** + * Disable the Windows Phone grippers when pressing an element. + * @type {String} + * @default 'none' + */ + touchSelect: 'none', - this.filterLabel = 'time'; - this.legendLabel = 'value'; + /** + * Disables the default callout shown when you touch and hold a touch target. + * On iOS, when you touch and hold a touch target such as a link, Safari displays + * a callout containing information about the link. This property allows you to disable that callout. + * @type {String} + * @default 'none' + */ + touchCallout: 'none', - this.style = Graph3d.STYLE.DOT; - this.showPerspective = true; - this.showGrid = true; - this.keepAspectRatio = true; - this.showShadow = false; - this.showGrayBottom = false; // TODO: this does not work correctly - this.showTooltip = false; - this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube' + /** + * Specifies whether zooming is enabled. Used by IE10> + * @type {String} + * @default 'none' + */ + contentZooming: 'none', - this.animationInterval = 1000; // milliseconds - this.animationPreload = false; + /** + * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers. + * @type {String} + * @default 'none' + */ + userDrag: 'none', - this.camera = new Camera(); - this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window? + /** + * Overrides the highlight color shown when the user taps a link or a JavaScript + * clickable element in iOS. This property obeys the alpha value, if specified. + * @type {String} + * @default 'rgba(0,0,0,0)' + */ + tapHighlightColor: 'rgba(0,0,0,0)' + } + }; - this.dataTable = null; // The original data table - this.dataPoints = null; // The table with point objects + var STOP = 1; + var FORCED_STOP = 2; - // the column indexes - this.colX = undefined; - this.colY = undefined; - this.colZ = undefined; - this.colValue = undefined; - this.colFilter = undefined; + /** + * Manager + * @param {HTMLElement} element + * @param {Object} [options] + * @constructor + */ + function Manager(element, options) { + options = options || {}; - this.xMin = 0; - this.xStep = undefined; // auto by default - this.xMax = 1; - this.yMin = 0; - this.yStep = undefined; // auto by default - this.yMax = 1; - this.zMin = 0; - this.zStep = undefined; // auto by default - this.zMax = 1; - this.valueMin = 0; - this.valueMax = 1; - this.xBarWidth = 1; - this.yBarWidth = 1; - // TODO: customize axis range + this.options = merge(options, Hammer.defaults); + this.options.inputTarget = this.options.inputTarget || element; - // constants - this.colorAxis = '#4D4D4D'; - this.colorGrid = '#D3D3D3'; - this.colorDot = '#7DC1FF'; - this.colorDotBorder = '#3267D2'; + this.handlers = {}; + this.session = {}; + this.recognizers = []; - // create a frame and canvas - this.create(); + this.element = element; + this.input = createInputInstance(this); + this.touchAction = new TouchAction(this, this.options.touchAction); - // apply options (also when undefined) - this.setOptions(options); + toggleCssProps(this, true); - // apply data - if (data) { - this.setData(data); - } + each(options.recognizers, function(item) { + var recognizer = this.add(new (item[0])(item[1])); + item[2] && recognizer.recognizeWith(item[2]); + item[3] && recognizer.requireFailure(item[3]); + }, this); } - // Extend Graph3d with an Emitter mixin - Emitter(Graph3d.prototype); + Manager.prototype = { + /** + * set options + * @param {Object} options + * @returns {Manager} + */ + set: function(options) { + extend(this.options, options); - /** - * Calculate the scaling values, dependent on the range in x, y, and z direction - */ - Graph3d.prototype._setScale = function () { - this.scale = new Point3d(1 / (this.xMax - this.xMin), 1 / (this.yMax - this.yMin), 1 / (this.zMax - this.zMin)); + // Options that need a little more setup + if (options.touchAction) { + this.touchAction.update(); + } + if (options.inputTarget) { + // Clean up existing event listeners and reinitialize + this.input.destroy(); + this.input.target = options.inputTarget; + this.input.init(); + } + return this; + }, - // keep aspect ration between x and y scale if desired - if (this.keepAspectRatio) { - if (this.scale.x < this.scale.y) { - //noinspection JSSuspiciousNameCombination - this.scale.y = this.scale.x; - } else { - //noinspection JSSuspiciousNameCombination - this.scale.x = this.scale.y; - } - } + /** + * stop recognizing for this session. + * This session will be discarded, when a new [input]start event is fired. + * When forced, the recognizer cycle is stopped immediately. + * @param {Boolean} [force] + */ + stop: function(force) { + this.session.stopped = force ? FORCED_STOP : STOP; + }, - // scale the vertical axis - this.scale.z *= this.verticalRatio; - // TODO: can this be automated? verticalRatio? + /** + * run the recognizers! + * called by the inputHandler function on every movement of the pointers (touches) + * it walks through all the recognizers and tries to detect the gesture that is being made + * @param {Object} inputData + */ + recognize: function(inputData) { + var session = this.session; + if (session.stopped) { + return; + } - // determine scale for (optional) value - this.scale.value = 1 / (this.valueMax - this.valueMin); + // run the touch-action polyfill + this.touchAction.preventDefaults(inputData); - // position the camera arm - var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x; - var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y; - var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z; - this.camera.setArmLocation(xCenter, yCenter, zCenter); - }; + var recognizer; + var recognizers = this.recognizers; - /** - * Convert a 3D location to a 2D location on screen - * http://en.wikipedia.org/wiki/3D_projection - * @param {Point3d} point3d A 3D point with parameters x, y, z - * @return {Point2d} point2d A 2D point with parameters x, y - */ - Graph3d.prototype._convert3Dto2D = function (point3d) { - var translation = this._convertPointToTranslation(point3d); - return this._convertTranslationToScreen(translation); - }; + // this holds the recognizer that is being recognized. + // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED + // if no recognizer is detecting a thing, it is set to `null` + var curRecognizer = session.curRecognizer; - /** - * Convert a 3D location its translation seen from the camera - * http://en.wikipedia.org/wiki/3D_projection - * @param {Point3d} point3d A 3D point with parameters x, y, z - * @return {Point3d} translation A 3D point with parameters x, y, z This is - * the translation of the point, seen from the - * camera - */ - Graph3d.prototype._convertPointToTranslation = function (point3d) { - var ax = point3d.x * this.scale.x, - ay = point3d.y * this.scale.y, - az = point3d.z * this.scale.z, - cx = this.camera.getCameraLocation().x, - cy = this.camera.getCameraLocation().y, - cz = this.camera.getCameraLocation().z, + // reset when the last recognizer is recognized + // or when we're in a new session + if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) { + curRecognizer = session.curRecognizer = null; + } - // calculate angles - sinTx = Math.sin(this.camera.getCameraRotation().x), - cosTx = Math.cos(this.camera.getCameraRotation().x), - sinTy = Math.sin(this.camera.getCameraRotation().y), - cosTy = Math.cos(this.camera.getCameraRotation().y), - sinTz = Math.sin(this.camera.getCameraRotation().z), - cosTz = Math.cos(this.camera.getCameraRotation().z), + var i = 0; + while (i < recognizers.length) { + recognizer = recognizers[i]; - // calculate translation - dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz), - dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax - cx)), - dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax - cx)); + // find out if we are allowed try to recognize the input for this one. + // 1. allow if the session is NOT forced stopped (see the .stop() method) + // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one + // that is being recognized. + // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer. + // this can be setup with the `recognizeWith()` method on the recognizer. + if (session.stopped !== FORCED_STOP && ( // 1 + !curRecognizer || recognizer == curRecognizer || // 2 + recognizer.canRecognizeWith(curRecognizer))) { // 3 + recognizer.recognize(inputData); + } else { + recognizer.reset(); + } - return new Point3d(dx, dy, dz); - }; + // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the + // current active recognizer. but only if we don't already have an active recognizer + if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) { + curRecognizer = session.curRecognizer = recognizer; + } + i++; + } + }, - /** - * Convert a translation point to a point on the screen - * @param {Point3d} translation A 3D point with parameters x, y, z This is - * the translation of the point, seen from the - * camera - * @return {Point2d} point2d A 2D point with parameters x, y - */ - Graph3d.prototype._convertTranslationToScreen = function (translation) { - var ex = this.eye.x, - ey = this.eye.y, - ez = this.eye.z, - dx = translation.x, - dy = translation.y, - dz = translation.z; + /** + * get a recognizer by its event name. + * @param {Recognizer|String} recognizer + * @returns {Recognizer|Null} + */ + get: function(recognizer) { + if (recognizer instanceof Recognizer) { + return recognizer; + } - // calculate position on screen from translation - var bx; - var by; - if (this.showPerspective) { - bx = (dx - ex) * (ez / dz); - by = (dy - ey) * (ez / dz); - } else { - bx = dx * -(ez / this.camera.getArmLength()); - by = dy * -(ez / this.camera.getArmLength()); - } + var recognizers = this.recognizers; + for (var i = 0; i < recognizers.length; i++) { + if (recognizers[i].options.event == recognizer) { + return recognizers[i]; + } + } + return null; + }, - // shift and scale the point to the center of the screen - // use the width of the graph to scale both horizontally and vertically. - return new Point2d(this.xcenter + bx * this.frame.canvas.clientWidth, this.ycenter - by * this.frame.canvas.clientWidth); - }; + /** + * add a recognizer to the manager + * existing recognizers with the same event name will be removed + * @param {Recognizer} recognizer + * @returns {Recognizer|Manager} + */ + add: function(recognizer) { + if (invokeArrayArg(recognizer, 'add', this)) { + return this; + } - /** - * Set the background styling for the graph - * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor - */ - Graph3d.prototype._setBackgroundColor = function (backgroundColor) { - var fill = 'white'; - var stroke = 'gray'; - var strokeWidth = 1; + // remove existing + var existing = this.get(recognizer.options.event); + if (existing) { + this.remove(existing); + } - if (typeof backgroundColor === 'string') { - fill = backgroundColor; - stroke = 'none'; - strokeWidth = 0; - } else if (typeof backgroundColor === 'object') { - if (backgroundColor.fill !== undefined) fill = backgroundColor.fill; - if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke; - if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth; - } else if (backgroundColor === undefined) {} else { - throw 'Unsupported type of backgroundColor'; - } + this.recognizers.push(recognizer); + recognizer.manager = this; - this.frame.style.backgroundColor = fill; - this.frame.style.borderColor = stroke; - this.frame.style.borderWidth = strokeWidth + 'px'; - this.frame.style.borderStyle = 'solid'; - }; + this.touchAction.update(); + return recognizer; + }, - /// enumerate the available styles - Graph3d.STYLE = { - BAR: 0, - BARCOLOR: 1, - BARSIZE: 2, - DOT: 3, - DOTLINE: 4, - DOTCOLOR: 5, - DOTSIZE: 6, - GRID: 7, - LINE: 8, - SURFACE: 9 - }; + /** + * remove a recognizer by name or instance + * @param {Recognizer|String} recognizer + * @returns {Manager} + */ + remove: function(recognizer) { + if (invokeArrayArg(recognizer, 'remove', this)) { + return this; + } - /** - * 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 - */ - Graph3d.prototype._getStyleNumber = function (styleName) { - switch (styleName) { - case 'dot': - return Graph3d.STYLE.DOT; - case 'dot-line': - return Graph3d.STYLE.DOTLINE; - case 'dot-color': - return Graph3d.STYLE.DOTCOLOR; - case 'dot-size': - return Graph3d.STYLE.DOTSIZE; - case 'line': - return Graph3d.STYLE.LINE; - case 'grid': - return Graph3d.STYLE.GRID; - case 'surface': - return Graph3d.STYLE.SURFACE; - case 'bar': - return Graph3d.STYLE.BAR; - case 'bar-color': - return Graph3d.STYLE.BARCOLOR; - case 'bar-size': - return Graph3d.STYLE.BARSIZE; - } + var recognizers = this.recognizers; + recognizer = this.get(recognizer); + recognizers.splice(inArray(recognizers, recognizer), 1); - return -1; - }; + this.touchAction.update(); + return this; + }, - /** - * Determine the indexes of the data columns, based on the given style and data - * @param {DataSet} data - * @param {Number} style - */ - Graph3d.prototype._determineColumnIndexes = function (data, style) { - if (this.style === Graph3d.STYLE.DOT || this.style === Graph3d.STYLE.DOTLINE || this.style === Graph3d.STYLE.LINE || this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE || this.style === Graph3d.STYLE.BAR) { - // 3 columns expected, and optionally a 4th with filter values - this.colX = 0; - this.colY = 1; - this.colZ = 2; - this.colValue = undefined; + /** + * bind event + * @param {String} events + * @param {Function} handler + * @returns {EventEmitter} this + */ + on: function(events, handler) { + var handlers = this.handlers; + each(splitStr(events), function(event) { + handlers[event] = handlers[event] || []; + handlers[event].push(handler); + }); + return this; + }, - if (data.getNumberOfColumns() > 3) { - this.colFilter = 3; - } - } else if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { - // 4 columns expected, and optionally a 5th with filter values - this.colX = 0; - this.colY = 1; - this.colZ = 2; - this.colValue = 3; + /** + * unbind event, leave emit blank to remove all handlers + * @param {String} events + * @param {Function} [handler] + * @returns {EventEmitter} this + */ + off: function(events, handler) { + var handlers = this.handlers; + each(splitStr(events), function(event) { + if (!handler) { + delete handlers[event]; + } else { + handlers[event].splice(inArray(handlers[event], handler), 1); + } + }); + return this; + }, - if (data.getNumberOfColumns() > 4) { - this.colFilter = 4; - } - } else { - throw 'Unknown style "' + this.style + '"'; - } - }; + /** + * emit event to the listeners + * @param {String} event + * @param {Object} data + */ + emit: function(event, data) { + // we also want to trigger dom events + if (this.options.domEvents) { + triggerDomEvent(event, data); + } - Graph3d.prototype.getNumberOfRows = function (data) { - return data.length; - }; + // no handlers, so skip it all + var handlers = this.handlers[event] && this.handlers[event].slice(); + if (!handlers || !handlers.length) { + return; + } - Graph3d.prototype.getNumberOfColumns = function (data) { - var counter = 0; - for (var column in data[0]) { - if (data[0].hasOwnProperty(column)) { - counter++; - } - } - return counter; - }; + data.type = event; + data.preventDefault = function() { + data.srcEvent.preventDefault(); + }; - Graph3d.prototype.getDistinctValues = function (data, column) { - var distinctValues = []; - for (var i = 0; i < data.length; i++) { - if (distinctValues.indexOf(data[i][column]) == -1) { - distinctValues.push(data[i][column]); - } - } - return distinctValues; - }; + var i = 0; + while (i < handlers.length) { + handlers[i](data); + i++; + } + }, - Graph3d.prototype.getColumnRange = function (data, column) { - var minMax = { min: data[0][column], max: data[0][column] }; - for (var i = 0; i < data.length; i++) { - if (minMax.min > data[i][column]) { - minMax.min = data[i][column]; - } - if (minMax.max < data[i][column]) { - minMax.max = data[i][column]; + /** + * destroy the manager and unbinds all events + * it doesn't unbind dom events, that is the user own responsibility + */ + destroy: function() { + this.element && toggleCssProps(this, false); + + this.handlers = {}; + this.session = {}; + this.input.destroy(); + this.element = null; } - } - return minMax; }; /** - * Initialize the data from the data table. Calculate minimum and maximum values - * and column index values - * @param {Array | DataSet | DataView} rawData The data containing the items for the Graph. - * @param {Number} style Style Number + * add/remove the css properties as defined in manager.options.cssProps + * @param {Manager} manager + * @param {Boolean} add */ - Graph3d.prototype._dataInitialize = function (rawData, style) { - var me = this; + function toggleCssProps(manager, add) { + var element = manager.element; + each(manager.options.cssProps, function(value, name) { + element.style[prefixed(element.style, name)] = add ? value : ''; + }); + } - // unsubscribe from the dataTable - if (this.dataSet) { - this.dataSet.off('*', this._onChange); - } + /** + * trigger dom event + * @param {String} event + * @param {Object} data + */ + function triggerDomEvent(event, data) { + var gestureEvent = document.createEvent('Event'); + gestureEvent.initEvent(event, true, true); + gestureEvent.gesture = data; + data.target.dispatchEvent(gestureEvent); + } - if (rawData === undefined) return; + extend(Hammer, { + INPUT_START: INPUT_START, + INPUT_MOVE: INPUT_MOVE, + INPUT_END: INPUT_END, + INPUT_CANCEL: INPUT_CANCEL, - if (Array.isArray(rawData)) { - rawData = new DataSet(rawData); - } + STATE_POSSIBLE: STATE_POSSIBLE, + STATE_BEGAN: STATE_BEGAN, + STATE_CHANGED: STATE_CHANGED, + STATE_ENDED: STATE_ENDED, + STATE_RECOGNIZED: STATE_RECOGNIZED, + STATE_CANCELLED: STATE_CANCELLED, + STATE_FAILED: STATE_FAILED, - var data; - if (rawData instanceof DataSet || rawData instanceof DataView) { - data = rawData.get(); - } else { - throw new Error('Array, DataSet, or DataView expected'); - } + DIRECTION_NONE: DIRECTION_NONE, + DIRECTION_LEFT: DIRECTION_LEFT, + DIRECTION_RIGHT: DIRECTION_RIGHT, + DIRECTION_UP: DIRECTION_UP, + DIRECTION_DOWN: DIRECTION_DOWN, + DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL, + DIRECTION_VERTICAL: DIRECTION_VERTICAL, + DIRECTION_ALL: DIRECTION_ALL, - if (data.length == 0) return; + Manager: Manager, + Input: Input, + TouchAction: TouchAction, - this.dataSet = rawData; - this.dataTable = data; + TouchInput: TouchInput, + MouseInput: MouseInput, + PointerEventInput: PointerEventInput, + TouchMouseInput: TouchMouseInput, + SingleTouchInput: SingleTouchInput, - // subscribe to changes in the dataset - this._onChange = function () { - me.setData(me.dataSet); - }; - this.dataSet.on('*', this._onChange); + Recognizer: Recognizer, + AttrRecognizer: AttrRecognizer, + Tap: TapRecognizer, + Pan: PanRecognizer, + Swipe: SwipeRecognizer, + Pinch: PinchRecognizer, + Rotate: RotateRecognizer, + Press: PressRecognizer, - // _determineColumnIndexes - // getNumberOfRows (points) - // getNumberOfColumns (x,y,z,v,t,t1,t2...) - // getDistinctValues (unique values?) - // getColumnRange + on: addEventListeners, + off: removeEventListeners, + each: each, + merge: merge, + extend: extend, + inherit: inherit, + bindFn: bindFn, + prefixed: prefixed + }); - // determine the location of x,y,z,value,filter columns - this.colX = 'x'; - this.colY = 'y'; - this.colZ = 'z'; - this.colValue = 'style'; - this.colFilter = 'filter'; + if ("function" == TYPE_FUNCTION && __webpack_require__(6)) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { + return Hammer; + }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else if (typeof module != 'undefined' && module.exports) { + module.exports = Hammer; + } else { + window[exportName] = Hammer; + } - // check if a filter column is provided - if (data[0].hasOwnProperty('filter')) { - if (this.dataFilter === undefined) { - this.dataFilter = new Filter(rawData, this.colFilter, this); - this.dataFilter.setOnLoadCallback(function () { - me.redraw(); - }); - } - } + })(window, document, 'Hammer'); - var withBars = this.style == Graph3d.STYLE.BAR || this.style == Graph3d.STYLE.BARCOLOR || this.style == Graph3d.STYLE.BARSIZE; - // determine barWidth from data - if (withBars) { - if (this.defaultXBarWidth !== undefined) { - this.xBarWidth = this.defaultXBarWidth; - } else { - var dataX = this.getDistinctValues(data, this.colX); - this.xBarWidth = dataX[1] - dataX[0] || 1; - } +/***/ }, +/* 6 */ +/***/ function(module, exports, __webpack_require__) { - if (this.defaultYBarWidth !== undefined) { - this.yBarWidth = this.defaultYBarWidth; - } else { - var dataY = this.getDistinctValues(data, this.colY); - this.yBarWidth = dataY[1] - dataY[0] || 1; - } - } + /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__; - // calculate minimums and maximums - var xRange = this.getColumnRange(data, this.colX); - if (withBars) { - xRange.min -= this.xBarWidth / 2; - xRange.max += this.xBarWidth / 2; - } - this.xMin = this.defaultXMin !== undefined ? this.defaultXMin : xRange.min; - this.xMax = this.defaultXMax !== undefined ? this.defaultXMax : xRange.max; - if (this.xMax <= this.xMin) this.xMax = this.xMin + 1; - this.xStep = this.defaultXStep !== undefined ? this.defaultXStep : (this.xMax - this.xMin) / 5; + /* WEBPACK VAR INJECTION */}.call(exports, {})) - var yRange = this.getColumnRange(data, this.colY); - if (withBars) { - yRange.min -= this.yBarWidth / 2; - yRange.max += this.yBarWidth / 2; - } - this.yMin = this.defaultYMin !== undefined ? this.defaultYMin : yRange.min; - this.yMax = this.defaultYMax !== undefined ? this.defaultYMax : yRange.max; - if (this.yMax <= this.yMin) this.yMax = this.yMin + 1; - this.yStep = this.defaultYStep !== undefined ? this.defaultYStep : (this.yMax - this.yMin) / 5; +/***/ }, +/* 7 */ +/***/ function(module, exports, __webpack_require__) { - var zRange = this.getColumnRange(data, this.colZ); - this.zMin = this.defaultZMin !== undefined ? this.defaultZMin : zRange.min; - this.zMax = this.defaultZMax !== undefined ? this.defaultZMax : zRange.max; - if (this.zMax <= this.zMin) this.zMax = this.zMin + 1; - this.zStep = this.defaultZStep !== undefined ? this.defaultZStep : (this.zMax - this.zMin) / 5; + // utility functions - if (this.colValue !== undefined) { - var valueRange = this.getColumnRange(data, this.colValue); - this.valueMin = this.defaultValueMin !== undefined ? this.defaultValueMin : valueRange.min; - this.valueMax = this.defaultValueMax !== undefined ? this.defaultValueMax : valueRange.max; - if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1; - } + // first check if moment.js is already loaded in the browser window, if so, + // use this instance. Else, load via commonjs. - // set the scale dependent on the ranges. - this._setScale(); - }; + 'use strict'; + + var moment = __webpack_require__(8); + var uuid = __webpack_require__(12); /** - * Filter the data based on the current filter - * @param {Array} data - * @return {Array} dataPoints Array with point objects which can be drawn on screen + * Test whether given object is a number + * @param {*} object + * @return {Boolean} isNumber */ - Graph3d.prototype._getDataPoints = function (data) { - // TODO: store the created matrix dataPoints in the filters instead of reloading each time - var x, y, i, z, obj, point; - - var dataPoints = []; - - if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { - // copy all values from the google data table to a matrix - // the provided values are supposed to form a grid of (x,y) positions - - // create two lists with all present x and y values - var dataX = []; - var dataY = []; - for (i = 0; i < this.getNumberOfRows(data); i++) { - x = data[i][this.colX] || 0; - y = data[i][this.colY] || 0; - - if (dataX.indexOf(x) === -1) { - dataX.push(x); - } - if (dataY.indexOf(y) === -1) { - dataY.push(y); - } - } - - var sortNumber = function sortNumber(a, b) { - return a - b; - }; - dataX.sort(sortNumber); - dataY.sort(sortNumber); - - // create a grid, a 2d matrix, with all values. - var dataMatrix = []; // temporary data matrix - for (i = 0; i < data.length; i++) { - x = data[i][this.colX] || 0; - y = data[i][this.colY] || 0; - z = data[i][this.colZ] || 0; - - var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer - var yIndex = dataY.indexOf(y); - - if (dataMatrix[xIndex] === undefined) { - dataMatrix[xIndex] = []; - } - - var point3d = new Point3d(); - point3d.x = x; - point3d.y = y; - point3d.z = z; - - obj = {}; - obj.point = point3d; - obj.trans = undefined; - obj.screen = undefined; - obj.bottom = new Point3d(x, y, this.zMin); - - dataMatrix[xIndex][yIndex] = obj; - - dataPoints.push(obj); - } - - // fill in the pointers to the neighbors. - for (x = 0; x < dataMatrix.length; x++) { - for (y = 0; y < dataMatrix[x].length; y++) { - if (dataMatrix[x][y]) { - dataMatrix[x][y].pointRight = x < dataMatrix.length - 1 ? dataMatrix[x + 1][y] : undefined; - dataMatrix[x][y].pointTop = y < dataMatrix[x].length - 1 ? dataMatrix[x][y + 1] : undefined; - dataMatrix[x][y].pointCross = x < dataMatrix.length - 1 && y < dataMatrix[x].length - 1 ? dataMatrix[x + 1][y + 1] : undefined; - } - } - } - } else { - // 'dot', 'dot-line', etc. - // copy all values from the google data table to a list with Point3d objects - for (i = 0; i < data.length; i++) { - point = new Point3d(); - point.x = data[i][this.colX] || 0; - point.y = data[i][this.colY] || 0; - point.z = data[i][this.colZ] || 0; - - if (this.colValue !== undefined) { - point.value = data[i][this.colValue] || 0; - } - - obj = {}; - obj.point = point; - obj.bottom = new Point3d(point.x, point.y, this.zMin); - obj.trans = undefined; - obj.screen = undefined; + exports.isNumber = function (object) { + return object instanceof Number || typeof object == 'number'; + }; - dataPoints.push(obj); + /** + * Remove everything in the DOM object + * @param DOMobject + */ + exports.recursiveDOMDelete = function (DOMobject) { + if (DOMobject) { + while (DOMobject.hasChildNodes() === true) { + exports.recursiveDOMDelete(DOMobject.firstChild); + DOMobject.removeChild(DOMobject.firstChild); } } - - return dataPoints; }; /** - * Create the main frame for the Graph3d. - * This function is executed once when a Graph3d object is created. The frame - * contains a canvas, and this canvas contains all objects like the axis and - * nodes. + * 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 min + * @param max + * @param total + * @param value + * @returns {number} */ - Graph3d.prototype.create = function () { - // remove all elements from the container element. - while (this.containerElement.hasChildNodes()) { - this.containerElement.removeChild(this.containerElement.firstChild); - } - - this.frame = document.createElement('div'); - this.frame.style.position = 'relative'; - this.frame.style.overflow = 'hidden'; - - // create the graph canvas (HTML canvas element) - this.frame.canvas = document.createElement('canvas'); - this.frame.canvas.style.position = 'relative'; - this.frame.appendChild(this.frame.canvas); - //if (!this.frame.canvas.getContext) { - { - var noCanvas = document.createElement('DIV'); - noCanvas.style.color = 'red'; - noCanvas.style.fontWeight = 'bold'; - noCanvas.style.padding = '10px'; - noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; - this.frame.canvas.appendChild(noCanvas); + 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); } - - this.frame.filter = document.createElement('div'); - this.frame.filter.style.position = 'absolute'; - this.frame.filter.style.bottom = '0px'; - this.frame.filter.style.left = '0px'; - this.frame.filter.style.width = '100%'; - this.frame.appendChild(this.frame.filter); - - // add event listeners to handle moving and zooming the contents - var me = this; - var onmousedown = function onmousedown(event) { - me._onMouseDown(event); - }; - var ontouchstart = function ontouchstart(event) { - me._onTouchStart(event); - }; - var onmousewheel = function onmousewheel(event) { - me._onWheel(event); - }; - var ontooltip = function ontooltip(event) { - me._onTooltip(event); - }; - // TODO: these events are never cleaned up... can give a 'memory leakage' - - util.addEventListener(this.frame.canvas, 'keydown', onkeydown); - util.addEventListener(this.frame.canvas, 'mousedown', onmousedown); - util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart); - util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel); - util.addEventListener(this.frame.canvas, 'mousemove', ontooltip); - - // add the new graph to the container element - this.containerElement.appendChild(this.frame); }; /** - * Set a new size for the graph - * @param {string} width Width in pixels or percentage (for example '800px' - * or '50%') - * @param {string} height Height in pixels or percentage (for example '400px' - * or '30%') + * Test whether given object is a string + * @param {*} object + * @return {Boolean} isString */ - Graph3d.prototype.setSize = function (width, height) { - this.frame.style.width = width; - this.frame.style.height = height; - - this._resizeCanvas(); + exports.isString = function (object) { + return object instanceof String || typeof object == 'string'; }; /** - * Resize the canvas to the current size of the frame + * Test whether given object is a Date, or a String containing a Date + * @param {Date | String} object + * @return {Boolean} isDate */ - Graph3d.prototype._resizeCanvas = function () { - this.frame.canvas.style.width = '100%'; - this.frame.canvas.style.height = '100%'; - - this.frame.canvas.width = this.frame.canvas.clientWidth; - this.frame.canvas.height = this.frame.canvas.clientHeight; + 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; + } + } - // adjust with for margin - this.frame.filter.style.width = this.frame.canvas.clientWidth - 2 * 10 + 'px'; + return false; }; /** - * Start animation + * Create a semi UUID + * source: http://stackoverflow.com/a/105074/1262753 + * @return {String} uuid */ - Graph3d.prototype.animationStart = function () { - if (!this.frame.filter || !this.frame.filter.slider) throw 'No animation available'; + exports.randomUUID = function () { + return uuid.v4(); + }; - this.frame.filter.slider.play(); + /** + * assign all keys of an object that are not nested objects to a certain value (used for color objects). + * @param obj + * @param value + */ + exports.assignAllKeys = function (obj, value) { + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + if (typeof obj[prop] !== 'object') { + obj[prop] = value; + } + } + } }; /** - * Stop animation + * Fill an object with a possibly partially defined other object. Only copies values if the a object has an object requiring values. + * That means an object is not created on a property if only the b object has it. + * @param obj + * @param value */ - Graph3d.prototype.animationStop = function () { - if (!this.frame.filter || !this.frame.filter.slider) return; + exports.fillIfDefined = function (a, b) { + var allowDeletion = arguments[2] === undefined ? false : arguments[2]; - this.frame.filter.slider.stop(); + for (var prop in a) { + if (b[prop] !== undefined) { + if (typeof b[prop] !== 'object') { + if ((b[prop] === undefined || b[prop] === null) && a[prop] !== undefined && allowDeletion === true) { + delete a[prop]; + } else { + a[prop] = b[prop]; + } + } else { + if (typeof a[prop] === 'object') { + exports.fillIfDefined(a[prop], b[prop], allowDeletion); + } + } + } + } }; /** - * Resize the center position based on the current values in this.defaultXCenter - * and this.defaultYCenter (which are strings with a percentage or a value - * in pixels). The center positions are the variables this.xCenter - * and this.yCenter + * 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 */ - Graph3d.prototype._resizeCenter = function () { - // calculate the horizontal center position - if (this.defaultXCenter.charAt(this.defaultXCenter.length - 1) === '%') { - this.xcenter = parseFloat(this.defaultXCenter) / 100 * this.frame.canvas.clientWidth; - } else { - this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px + exports.protoExtend = function (a, b) { + for (var i = 1; i < arguments.length; i++) { + var other = arguments[i]; + for (var prop in other) { + a[prop] = other[prop]; + } } + return a; + }; - // calculate the vertical center position - if (this.defaultYCenter.charAt(this.defaultYCenter.length - 1) === '%') { - this.ycenter = parseFloat(this.defaultYCenter) / 100 * (this.frame.canvas.clientHeight - this.frame.filter.clientHeight); - } else { - this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px + /** + * 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) { + 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; }; /** - * Set the rotation and distance of the camera - * @param {Object} pos An object with the camera position. The object - * contains three parameters: - * - horizontal {Number} - * The horizontal rotation, between 0 and 2*PI. - * Optional, can be left undefined. - * - vertical {Number} - * 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. - * - distance {Number} - * The (normalized) distance of the camera to the - * center of the graph, a value between 0.71 and 5.0. - * Optional, can be left undefined. + * 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 */ - Graph3d.prototype.setCameraPosition = function (pos) { - if (pos === undefined) { - return; + exports.selectiveExtend = function (props, a, b) { + if (!Array.isArray(props)) { + throw new Error('Array with property names expected as first argument'); } - if (pos.horizontal !== undefined && pos.vertical !== undefined) { - this.camera.setArmRotation(pos.horizontal, pos.vertical); - } + for (var i = 2; i < arguments.length; i++) { + var other = arguments[i]; - if (pos.distance !== undefined) { - this.camera.setArmLength(pos.distance); + for (var p = 0; p < props.length; p++) { + var prop = props[p]; + if (other.hasOwnProperty(prop)) { + a[prop] = other[prop]; + } + } } - - this.redraw(); + return a; }; /** - * Retrieve the current camera rotation - * @return {object} An object with parameters horizontal, vertical, and - * distance + * 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 */ - Graph3d.prototype.getCameraPosition = function () { - var pos = this.camera.getArmRotation(); - pos.distance = this.camera.getArmLength(); - return pos; + exports.selectiveDeepExtend = function (props, a, b) { + var allowDeletion = arguments[3] === undefined ? false : arguments[3]; + + // TODO: add support for Arrays to deepExtend + if (Array.isArray(b)) { + throw new TypeError('Arrays are not supported by deepExtend'); + } + 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.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 { + if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) { + delete a[prop]; + } else { + a[prop] = b[prop]; + } + } + } else if (Array.isArray(b[prop])) { + throw new TypeError('Arrays are not supported by deepExtend'); + } else { + a[prop] = b[prop]; + } + } + } + } + return a; }; /** - * Load data into the 3D Graph + * 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 */ - Graph3d.prototype._readData = function (data) { - // read the data - this._dataInitialize(data, this.style); + exports.selectiveNotDeepExtend = function (props, a, b) { + var allowDeletion = arguments[3] === undefined ? false : arguments[3]; - if (this.dataFilter) { - // apply filtering - this.dataPoints = this.dataFilter._getDataPoints(); - } else { - // no filtering. load all data - this.dataPoints = this._getDataPoints(this.dataTable); + // TODO: add support for Arrays to deepExtend + if (Array.isArray(b)) { + throw new TypeError('Arrays are not supported by deepExtend'); } - - // draw the filter - this._redrawFilter(); + for (var prop in b) { + if (b.hasOwnProperty(prop)) { + if (props.indexOf(prop) == -1) { + if (b[prop] && b[prop].constructor === Object) { + if (a[prop] === undefined) { + a[prop] = {}; + } + if (a[prop].constructor === Object) { + exports.deepExtend(a[prop], b[prop]); + } else { + if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) { + delete a[prop]; + } else { + a[prop] = b[prop]; + } + } + } else if (Array.isArray(b[prop])) { + throw new TypeError('Arrays are not supported by deepExtend'); + } else { + a[prop] = b[prop]; + } + } + } + } + return a; }; /** - * Replace the dataset of the Graph3d - * @param {Array | DataSet | DataView} data + * Deep extend an object a with the properties of object b + * @param {Object} a + * @param {Object} b + * @param [Boolean] protoExtend --> optional parameter. 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] global --> optional parameter. If true, the values of fields that are null will not deleted + * @returns {Object} */ - Graph3d.prototype.setData = function (data) { - this._readData(data); - this.redraw(); - - // start animation when option is true - if (this.animationAutoStart && this.dataFilter) { - this.animationStart(); + exports.deepExtend = function (a, b, protoExtend, allowDeletion) { + 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); + } else { + if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) { + delete a[prop]; + } else { + a[prop] = b[prop]; + } + } + } else if (Array.isArray(b[prop])) { + a[prop] = []; + for (var i = 0; i < b[prop].length; i++) { + a[prop].push(b[prop][i]); + } + } else { + a[prop] = b[prop]; + } + } } + return a; }; /** - * Update the options. Options will be merged with current options - * @param {Object} options + * 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. */ - Graph3d.prototype.setOptions = function (options) { - var cameraPosition = undefined; - - this.animationStop(); - - if (options !== undefined) { - // retrieve parameter values - if (options.width !== undefined) this.width = options.width; - if (options.height !== undefined) this.height = options.height; + exports.equalArray = function (a, b) { + if (a.length != b.length) return false; - if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter; - if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter; + for (var i = 0, len = a.length; i < len; i++) { + if (a[i] != b[i]) return false; + } - if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel; - if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel; - if (options.xLabel !== undefined) this.xLabel = options.xLabel; - if (options.yLabel !== undefined) this.yLabel = options.yLabel; - if (options.zLabel !== undefined) this.zLabel = options.zLabel; + return true; + }; - if (options.xValueLabel !== undefined) this.xValueLabel = options.xValueLabel; - if (options.yValueLabel !== undefined) this.yValueLabel = options.yValueLabel; - if (options.zValueLabel !== undefined) this.zValueLabel = options.zValueLabel; + /** + * 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 (options.style !== undefined) { - var styleNumber = this._getStyleNumber(options.style); - if (styleNumber !== -1) { - this.style = styleNumber; - } - } - if (options.showGrid !== undefined) this.showGrid = options.showGrid; - if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective; - if (options.showShadow !== undefined) this.showShadow = options.showShadow; - if (options.tooltip !== undefined) this.showTooltip = options.tooltip; - if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls; - if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio; - if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio; + if (object === undefined) { + return undefined; + } + if (object === null) { + return null; + } - if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval; - if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload; - if (options.animationAutoStart !== undefined) this.animationAutoStart = options.animationAutoStart; + if (!type) { + return object; + } + if (!(typeof type === 'string') && !(type instanceof String)) { + throw new Error('Type must be a string'); + } - if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth; - if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth; + //noinspection FallthroughInSwitchStatementJS + switch (type) { + case 'boolean': + case 'Boolean': + return Boolean(object); - if (options.xMin !== undefined) this.defaultXMin = options.xMin; - if (options.xStep !== undefined) this.defaultXStep = options.xStep; - if (options.xMax !== undefined) this.defaultXMax = options.xMax; - if (options.yMin !== undefined) this.defaultYMin = options.yMin; - if (options.yStep !== undefined) this.defaultYStep = options.yStep; - if (options.yMax !== undefined) this.defaultYMax = options.yMax; - if (options.zMin !== undefined) this.defaultZMin = options.zMin; - if (options.zStep !== undefined) this.defaultZStep = options.zStep; - if (options.zMax !== undefined) this.defaultZMax = options.zMax; - if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin; - if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax; + case 'number': + case 'Number': + return Number(object.valueOf()); - if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition; + case 'string': + case 'String': + return String(object); - if (cameraPosition !== undefined) { - this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical); - this.camera.setArmLength(cameraPosition.distance); - } else { - this.camera.setArmRotation(1, 0.5); - this.camera.setArmLength(1.7); - } - } + 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(object).toDate(); // parse string + } + } else { + throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type Date'); + } - this._setBackgroundColor(options && options.backgroundColor); + 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'); + } - this.setSize(this.width, this.height); + 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 new Date(object).toISOString(); // parse string + } + } else { + throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type ISODate'); + } - // re-load the data - if (this.dataTable) { - this.setData(this.dataTable); - } + 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'); + } - // start animation when option is true - if (this.animationAutoStart && this.dataFilter) { - this.animationStart(); + 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; + /** - * Redraw the Graph. + * Get the type of an object, for example exports.getType([]) returns 'Array' + * @param {*} object + * @return {String} type */ - Graph3d.prototype.redraw = function () { - if (this.dataPoints === undefined) { - throw 'Error: graph data not initialized'; - } - - this._resizeCanvas(); - this._resizeCenter(); - this._redrawSlider(); - this._redrawClear(); - this._redrawAxis(); + exports.getType = function (object) { + var type = typeof object; - if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { - this._redrawDataGrid(); - } else if (this.style === Graph3d.STYLE.LINE) { - this._redrawDataLine(); - } else if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { - this._redrawDataBar(); - } else { - // style is DOT, DOTLINE, DOTCOLOR, DOTSIZE - this._redrawDataDot(); + 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'; } - this._redrawInfo(); - this._redrawLegend(); + return type; }; /** - * Clear the canvas before redrawing + * Used to extend an array and copy it. This is used to propagate paths recursively. + * + * @param arr + * @param newValue + * @returns {Array} */ - Graph3d.prototype._redrawClear = function () { - var canvas = this.frame.canvas; - var ctx = canvas.getContext('2d'); - - ctx.clearRect(0, 0, canvas.width, canvas.height); + exports.copyAndExtendArray = function (arr, newValue) { + var newArr = []; + for (var i = 0; i < arr.length; i++) { + newArr.push(arr[i]); + } + newArr.push(newValue); + return newArr; }; /** - * Redraw the legend showing the colors + * Used to extend an array and copy it. This is used to propagate paths recursively. + * + * @param arr + * @param newValue + * @returns {Array} */ - Graph3d.prototype._redrawLegend = function () { - var y; - - if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { - - var dotSize = this.frame.clientWidth * 0.02; - - var widthMin, widthMax; - if (this.style === Graph3d.STYLE.DOTSIZE) { - widthMin = dotSize / 2; // px - widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function - } else { - widthMin = 20; // px - widthMax = 20; // px - } - - var height = Math.max(this.frame.clientHeight * 0.25, 100); - var top = this.margin; - var right = this.frame.clientWidth - this.margin; - var left = right - widthMax; - var bottom = top + height; + exports.copyArray = function (arr) { + var newArr = []; + for (var i = 0; i < arr.length; i++) { + newArr.push(arr[i]); } + return newArr; + }; - var canvas = this.frame.canvas; - var ctx = canvas.getContext('2d'); - ctx.lineWidth = 1; - ctx.font = '14px arial'; // TODO: put in options - - if (this.style === Graph3d.STYLE.DOTCOLOR) { - // draw the color bar - var ymin = 0; - var ymax = height; // Todo: make height customizable - for (y = ymin; y < ymax; y++) { - var f = (y - ymin) / (ymax - ymin); - - //var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function - var hue = f * 240; - var color = this._hsv2rgb(hue, 1, 1); + /** + * 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; + }; - ctx.strokeStyle = color; - ctx.beginPath(); - ctx.moveTo(left, top + y); - ctx.lineTo(right, top + y); - ctx.stroke(); - } + /** + * 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; + }; - ctx.strokeStyle = this.colorAxis; - ctx.strokeRect(left, top, widthMax, height); + /** + * add a className to the given elements style + * @param {Element} elem + * @param {String} className + */ + exports.addClassName = function (elem, className) { + var classes = elem.className.split(' '); + if (classes.indexOf(className) == -1) { + classes.push(className); // add the class to the array + elem.className = classes.join(' '); } + }; - if (this.style === Graph3d.STYLE.DOTSIZE) { - // draw border around color bar - ctx.strokeStyle = this.colorAxis; - ctx.fillStyle = this.colorDot; - ctx.beginPath(); - ctx.moveTo(left, top); - ctx.lineTo(right, top); - ctx.lineTo(right - widthMax + widthMin, bottom); - ctx.lineTo(left, bottom); - ctx.closePath(); - ctx.fill(); - ctx.stroke(); + /** + * add a className to the given elements style + * @param {Element} elem + * @param {String} className + */ + exports.removeClassName = function (elem, className) { + var classes = elem.className.split(' '); + var index = classes.indexOf(className); + if (index != -1) { + classes.splice(index, 1); // remove the class from the array + elem.className = classes.join(' '); } + }; - if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { - // print values along the color bar - var gridLineLen = 5; // px - var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax - this.valueMin) / 5, true); - step.start(); - if (step.getCurrent() < this.valueMin) { - step.next(); + /** + * For each method for both arrays and objects. + * In case of an array, the built-in Array.forEach() is applied. + * 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); } - while (!step.end()) { - y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height; - - ctx.beginPath(); - ctx.moveTo(left - gridLineLen, y); - ctx.lineTo(left, y); - ctx.stroke(); - - ctx.textAlign = 'right'; - ctx.textBaseline = 'middle'; - ctx.fillStyle = this.colorAxis; - ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y); - - step.next(); + } else { + // object + for (i in object) { + if (object.hasOwnProperty(i)) { + callback(object[i], i, object); + } } - - ctx.textAlign = 'right'; - ctx.textBaseline = 'top'; - var label = this.legendLabel; - ctx.fillText(label, right, bottom + this.margin); } }; /** - * Redraw the filter + * Convert an object into an array: all objects properties are put into the + * array. The resulting array is unordered. + * @param {Object} object + * @param {Array} array */ - Graph3d.prototype._redrawFilter = function () { - this.frame.filter.innerHTML = ''; - - if (this.dataFilter) { - var options = { - 'visible': this.showAnimationControls - }; - var slider = new Slider(this.frame.filter, options); - this.frame.filter.slider = slider; - - // TODO: css here is not nice here... - this.frame.filter.style.padding = '10px'; - //this.frame.filter.style.backgroundColor = '#EFEFEF'; - - slider.setValues(this.dataFilter.values); - slider.setPlayInterval(this.animationInterval); - - // create an event handler - var me = this; - var onchange = function onchange() { - var index = slider.getIndex(); - - me.dataFilter.selectValue(index); - me.dataPoints = me.dataFilter._getDataPoints(); + exports.toArray = function (object) { + var array = []; - me.redraw(); - }; - slider.setOnChangeCallback(onchange); - } else { - this.frame.filter.slider = undefined; + for (var prop in object) { + if (object.hasOwnProperty(prop)) array.push(object[prop]); } + + return array; }; /** - * Redraw the slider + * Update a property in an object + * @param {Object} object + * @param {String} key + * @param {*} value + * @return {Boolean} changed */ - Graph3d.prototype._redrawSlider = function () { - if (this.frame.filter.slider !== undefined) { - this.frame.filter.slider.redraw(); + exports.updateProperty = function (object, key, value) { + if (object[key] !== value) { + object[key] = value; + return true; + } else { + return false; } }; /** - * Redraw common information + * 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] */ - Graph3d.prototype._redrawInfo = function () { - if (this.dataFilter) { - var canvas = this.frame.canvas; - var ctx = canvas.getContext('2d'); + exports.addEventListener = function (element, action, listener, useCapture) { + if (element.addEventListener) { + if (useCapture === undefined) useCapture = false; - ctx.font = '14px arial'; // TODO: put in options - ctx.lineStyle = 'gray'; - ctx.fillStyle = 'gray'; - ctx.textAlign = 'left'; - ctx.textBaseline = 'top'; + if (action === 'mousewheel' && navigator.userAgent.indexOf('Firefox') >= 0) { + action = 'DOMMouseScroll'; // For Firefox + } - var x = this.margin; - var y = this.margin; - ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y); + element.addEventListener(action, listener, useCapture); + } else { + element.attachEvent('on' + action, listener); // IE browsers } }; /** - * Redraw the axis - */ - Graph3d.prototype._redrawAxis = function () { - var canvas = this.frame.canvas, - ctx = canvas.getContext('2d'), - from, - to, - step, - prettyStep, - text, - xText, - yText, - zText, - offset, - xOffset, - yOffset, - xMin2d, - xMax2d; - - // TODO: get the actual rendered style of the containerElement - //ctx.font = this.containerElement.style.font; - ctx.font = 24 / this.camera.getArmLength() + 'px arial'; + * 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; - // calculate the length for the short grid lines - var gridLenX = 0.025 / this.scale.x; - var gridLenY = 0.025 / this.scale.y; - var textMargin = 5 / this.camera.getArmLength(); // px - var armAngle = this.camera.getArmRotation().horizontal; + if (action === 'mousewheel' && navigator.userAgent.indexOf('Firefox') >= 0) { + action = 'DOMMouseScroll'; // For Firefox + } - // draw x-grid lines - ctx.lineWidth = 1; - prettyStep = this.defaultXStep === undefined; - step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep); - step.start(); - if (step.getCurrent() < this.xMin) { - step.next(); + element.removeEventListener(action, listener, useCapture); + } else { + // IE browsers + element.detachEvent('on' + action, listener); } - while (!step.end()) { - var x = step.getCurrent(); - - if (this.showGrid) { - from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); - to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); - ctx.strokeStyle = this.colorGrid; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); - } else { - from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); - to = this._convert3Dto2D(new Point3d(x, this.yMin + gridLenX, this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); - - from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); - to = this._convert3Dto2D(new Point3d(x, this.yMax - gridLenX, this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); - } + }; - yText = Math.cos(armAngle) > 0 ? this.yMin : this.yMax; - text = this._convert3Dto2D(new Point3d(x, yText, this.zMin)); - if (Math.cos(armAngle * 2) > 0) { - ctx.textAlign = 'center'; - ctx.textBaseline = 'top'; - text.y += textMargin; - } else if (Math.sin(armAngle * 2) < 0) { - ctx.textAlign = 'right'; - ctx.textBaseline = 'middle'; - } else { - ctx.textAlign = 'left'; - ctx.textBaseline = 'middle'; - } - ctx.fillStyle = this.colorAxis; - ctx.fillText(' ' + this.xValueLabel(step.getCurrent()) + ' ', text.x, text.y); + /** + * Cancels the event if it is cancelable, without stopping further propagation of the event. + */ + exports.preventDefault = function (event) { + if (!event) event = window.event; - step.next(); + if (event.preventDefault) { + event.preventDefault(); // non-IE browsers + } else { + event.returnValue = false; // IE browsers } + }; - // draw y-grid lines - ctx.lineWidth = 1; - prettyStep = this.defaultYStep === undefined; - step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep); - step.start(); - if (step.getCurrent() < this.yMin) { - step.next(); + /** + * 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; } - while (!step.end()) { - if (this.showGrid) { - from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); - to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); - ctx.strokeStyle = this.colorGrid; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); - } else { - from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); - to = this._convert3Dto2D(new Point3d(this.xMin + gridLenY, step.getCurrent(), this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); - - from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); - to = this._convert3Dto2D(new Point3d(this.xMax - gridLenY, step.getCurrent(), this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); - } - xText = Math.sin(armAngle) > 0 ? this.xMin : this.xMax; - text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin)); - if (Math.cos(armAngle * 2) < 0) { - ctx.textAlign = 'center'; - ctx.textBaseline = 'top'; - text.y += textMargin; - } else if (Math.sin(armAngle * 2) > 0) { - ctx.textAlign = 'right'; - ctx.textBaseline = 'middle'; - } else { - ctx.textAlign = 'left'; - ctx.textBaseline = 'middle'; - } - ctx.fillStyle = this.colorAxis; - ctx.fillText(' ' + this.yValueLabel(step.getCurrent()) + ' ', text.x, text.y); + var target; - step.next(); + if (event.target) { + target = event.target; + } else if (event.srcElement) { + target = event.srcElement; } - // draw z-grid lines and axis - ctx.lineWidth = 1; - prettyStep = this.defaultZStep === undefined; - step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep); - step.start(); - if (step.getCurrent() < this.zMin) { - step.next(); + if (target.nodeType != undefined && target.nodeType == 3) { + // defeat Safari bug + target = target.parentNode; } - xText = Math.cos(armAngle) > 0 ? this.xMin : this.xMax; - yText = Math.sin(armAngle) < 0 ? this.yMin : this.yMax; - while (!step.end()) { - // TODO: make z-grid lines really 3d? - from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent())); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(from.x - textMargin, from.y); - ctx.stroke(); - ctx.textAlign = 'right'; - ctx.textBaseline = 'middle'; - ctx.fillStyle = this.colorAxis; - ctx.fillText(this.zValueLabel(step.getCurrent()) + ' ', from.x - 5, from.y); + return target; + }; - step.next(); + /** + * Check if given element contains given parent somewhere in the DOM tree + * @param {Element} element + * @param {Element} parent + */ + exports.hasParent = function (element, parent) { + var e = element; + + while (e) { + if (e === parent) { + return true; + } + e = e.parentNode; } - ctx.lineWidth = 1; - from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); - to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); - // draw x-axis - ctx.lineWidth = 1; - // line at yMin - xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); - xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(xMin2d.x, xMin2d.y); - ctx.lineTo(xMax2d.x, xMax2d.y); - ctx.stroke(); - // line at ymax - xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); - xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(xMin2d.x, xMin2d.y); - ctx.lineTo(xMax2d.x, xMax2d.y); - ctx.stroke(); + return false; + }; - // draw y-axis - ctx.lineWidth = 1; - // line at xMin - from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); - to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); - // line at xMax - from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); - to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); - ctx.strokeStyle = this.colorAxis; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(to.x, to.y); - ctx.stroke(); + exports.option = {}; - // draw x-label - var xLabel = this.xLabel; - if (xLabel.length > 0) { - yOffset = 0.1 / this.scale.y; - xText = (this.xMin + this.xMax) / 2; - yText = Math.cos(armAngle) > 0 ? this.yMin - yOffset : this.yMax + yOffset; - text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); - if (Math.cos(armAngle * 2) > 0) { - ctx.textAlign = 'center'; - ctx.textBaseline = 'top'; - } else if (Math.sin(armAngle * 2) < 0) { - ctx.textAlign = 'right'; - ctx.textBaseline = 'middle'; - } else { - ctx.textAlign = 'left'; - ctx.textBaseline = 'middle'; - } - ctx.fillStyle = this.colorAxis; - ctx.fillText(xLabel, text.x, text.y); + /** + * 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(); } - // draw y-label - var yLabel = this.yLabel; - if (yLabel.length > 0) { - xOffset = 0.1 / this.scale.x; - xText = Math.sin(armAngle) > 0 ? this.xMin - xOffset : this.xMax + xOffset; - yText = (this.yMin + this.yMax) / 2; - text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); - if (Math.cos(armAngle * 2) < 0) { - ctx.textAlign = 'center'; - ctx.textBaseline = 'top'; - } else if (Math.sin(armAngle * 2) > 0) { - ctx.textAlign = 'right'; - ctx.textBaseline = 'middle'; - } else { - ctx.textAlign = 'left'; - ctx.textBaseline = 'middle'; - } - ctx.fillStyle = this.colorAxis; - ctx.fillText(yLabel, text.x, text.y); + if (value != null) { + return value != false; } - // draw z-label - var zLabel = this.zLabel; - if (zLabel.length > 0) { - offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis? - xText = Math.cos(armAngle) > 0 ? this.xMin : this.xMax; - yText = Math.sin(armAngle) < 0 ? this.yMin : this.yMax; - zText = (this.zMin + this.zMax) / 2; - text = this._convert3Dto2D(new Point3d(xText, yText, zText)); - ctx.textAlign = 'right'; - ctx.textBaseline = 'middle'; - ctx.fillStyle = this.colorAxis; - ctx.fillText(zLabel, text.x - offset, text.y); - } + return defaultValue || null; }; /** - * Calculate the color based on the given value. - * @param {Number} H Hue, a value be between 0 and 360 - * @param {Number} S Saturation, a value between 0 and 1 - * @param {Number} V Value, a value between 0 and 1 + * Convert a value into a number + * @param {Boolean | function | undefined} value + * @param {Number} [defaultValue] + * @returns {Number} number */ - Graph3d.prototype._hsv2rgb = function (H, S, V) { - var R, G, B, C, Hi, X; - - C = V * S; - Hi = Math.floor(H / 60); // hi = 0,1,2,3,4,5 - X = C * (1 - Math.abs(H / 60 % 2 - 1)); - - switch (Hi) { - case 0: - R = C;G = X;B = 0;break; - case 1: - R = X;G = C;B = 0;break; - case 2: - R = 0;G = C;B = X;break; - case 3: - R = 0;G = X;B = C;break; - case 4: - R = X;G = 0;B = C;break; - case 5: - R = C;G = 0;B = X;break; + exports.option.asNumber = function (value, defaultValue) { + if (typeof value == 'function') { + value = value(); + } - default: - R = 0;G = 0;B = 0;break; + if (value != null) { + return Number(value) || defaultValue || null; } - return 'RGB(' + parseInt(R * 255) + ',' + parseInt(G * 255) + ',' + parseInt(B * 255) + ')'; + return defaultValue || null; }; /** - * Draw all datapoints as a grid - * This function can be used when the style is 'grid' + * Convert a value into a string + * @param {String | function | undefined} value + * @param {String} [defaultValue] + * @returns {String} str */ - Graph3d.prototype._redrawDataGrid = function () { - var canvas = this.frame.canvas, - ctx = canvas.getContext('2d'), - point, - right, - top, - cross, - i, - topSideVisible, - fillStyle, - strokeStyle, - lineWidth, - h, - s, - v, - zAvg; - - if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? + exports.option.asString = function (value, defaultValue) { + if (typeof value == 'function') { + value = value(); + } - // calculate the translations and screen position of all points - for (i = 0; i < this.dataPoints.length; i++) { - var trans = this._convertPointToTranslation(this.dataPoints[i].point); - var screen = this._convertTranslationToScreen(trans); + if (value != null) { + return String(value); + } - this.dataPoints[i].trans = trans; - this.dataPoints[i].screen = screen; + return defaultValue || null; + }; - // calculate the translation of the point at the bottom (needed for sorting) - var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); - this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; + /** + * 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(); } - // sort the points on depth of their (x,y) position (not on z) - var sortDepth = function sortDepth(a, b) { - return b.dist - a.dist; - }; - this.dataPoints.sort(sortDepth); + if (exports.isString(value)) { + return value; + } else if (exports.isNumber(value)) { + return value + 'px'; + } else { + return defaultValue || null; + } + }; - if (this.style === Graph3d.STYLE.SURFACE) { - for (i = 0; i < this.dataPoints.length; i++) { - point = this.dataPoints[i]; - right = this.dataPoints[i].pointRight; - top = this.dataPoints[i].pointTop; - cross = this.dataPoints[i].pointCross; + /** + * 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(); + } - if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) { + return value || defaultValue || null; + }; - if (this.showGrayBottom || this.showShadow) { - // calculate the cross product of the two vectors from center - // to left and right, in order to know whether we are looking at the - // bottom or at the top side. We can also use the cross product - // for calculating light intensity - var aDiff = Point3d.subtract(cross.trans, point.trans); - var bDiff = Point3d.subtract(top.trans, right.trans); - var crossproduct = Point3d.crossProduct(aDiff, bDiff); - var len = crossproduct.length(); - // FIXME: there is a bug with determining the surface side (shadow or colored) + /** + * 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; + }; - topSideVisible = crossproduct.z > 0; - } else { - topSideVisible = true; - } + /** + * This function takes color in hex format or rgb() or rgba() format and overrides the opacity. Returns rgba() string. + * @param color + * @param opacity + * @returns {*} + */ + exports.overrideOpacity = function (color, opacity) { + if (color.indexOf('rgba') != -1) { + return color; + } else if (color.indexOf('rgb') != -1) { + var rgb = color.substr(color.indexOf('(') + 1).replace(')', '').split(','); + return 'rgba(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ',' + opacity + ')'; + } else { + var rgb = exports.hexToRGB(color); + if (rgb == null) { + return color; + } else { + return 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + opacity + ')'; + } + } + }; - if (topSideVisible) { - // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 - zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4; - h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; - s = 1; // saturation - - if (this.showShadow) { - v = Math.min(1 + crossproduct.x / len / 2, 1); // value. TODO: scale - fillStyle = this._hsv2rgb(h, s, v); - strokeStyle = fillStyle; - } else { - v = 1; - fillStyle = this._hsv2rgb(h, s, v); - strokeStyle = this.colorAxis; - } - } else { - fillStyle = 'gray'; - strokeStyle = this.colorAxis; - } - lineWidth = 0.5; - - ctx.lineWidth = lineWidth; - ctx.fillStyle = fillStyle; - ctx.strokeStyle = strokeStyle; - ctx.beginPath(); - ctx.moveTo(point.screen.x, point.screen.y); - ctx.lineTo(right.screen.x, right.screen.y); - ctx.lineTo(cross.screen.x, cross.screen.y); - ctx.lineTo(top.screen.x, top.screen.y); - ctx.closePath(); - ctx.fill(); - ctx.stroke(); - } - } - } else { - // grid style - for (i = 0; i < this.dataPoints.length; i++) { - point = this.dataPoints[i]; - right = this.dataPoints[i].pointRight; - top = this.dataPoints[i].pointTop; - - if (point !== undefined) { - if (this.showPerspective) { - lineWidth = 2 / -point.trans.z; - } else { - lineWidth = 2 * -(this.eye.z / this.camera.getArmLength()); - } - } - - if (point !== undefined && right !== undefined) { - // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 - zAvg = (point.point.z + right.point.z) / 2; - h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; - - ctx.lineWidth = lineWidth; - ctx.strokeStyle = this._hsv2rgb(h, 1, 1); - ctx.beginPath(); - ctx.moveTo(point.screen.x, point.screen.y); - ctx.lineTo(right.screen.x, right.screen.y); - ctx.stroke(); - } - - if (point !== undefined && top !== undefined) { - // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 - zAvg = (point.point.z + top.point.z) / 2; - h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; - - ctx.lineWidth = lineWidth; - ctx.strokeStyle = this._hsv2rgb(h, 1, 1); - ctx.beginPath(); - ctx.moveTo(point.screen.x, point.screen.y); - ctx.lineTo(top.screen.x, top.screen.y); - ctx.stroke(); - } - } - } - }; + /** + * + * @param red 0 -- 255 + * @param green 0 -- 255 + * @param blue 0 -- 255 + * @returns {string} + * @constructor + */ + exports.RGBToHex = function (red, green, blue) { + return '#' + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1); + }; /** - * Draw all datapoints as dots. - * This function can be used when the style is 'dot' or 'dot-line' + * Parse a color property into an object with border, background, and + * highlight colors + * @param {Object | String} color + * @return {Object} colorObject */ - Graph3d.prototype._redrawDataDot = function () { - var canvas = this.frame.canvas; - var ctx = canvas.getContext('2d'); - var i; - - if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? - - // calculate the translations of all points - for (i = 0; i < this.dataPoints.length; i++) { - var trans = this._convertPointToTranslation(this.dataPoints[i].point); - var screen = this._convertTranslationToScreen(trans); - this.dataPoints[i].trans = trans; - this.dataPoints[i].screen = screen; - - // calculate the distance from the point at the bottom to the camera - var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); - this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; - } - - // order the translated points by depth - var sortDepth = function sortDepth(a, b) { - return b.dist - a.dist; - }; - this.dataPoints.sort(sortDepth); - - // draw the datapoints as colored circles - var dotSize = this.frame.clientWidth * 0.02; // px - for (i = 0; i < this.dataPoints.length; i++) { - var point = this.dataPoints[i]; - - if (this.style === Graph3d.STYLE.DOTLINE) { - // draw a vertical line from the bottom to the graph value - //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin)); - var from = this._convert3Dto2D(point.bottom); - ctx.lineWidth = 1; - ctx.strokeStyle = this.colorGrid; - ctx.beginPath(); - ctx.moveTo(from.x, from.y); - ctx.lineTo(point.screen.x, point.screen.y); - ctx.stroke(); + 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]); } - - // calculate radius for the circle - var size; - if (this.style === Graph3d.STYLE.DOTSIZE) { - size = dotSize / 2 + 2 * dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin); + 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 { - size = dotSize; + 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; - var radius; - if (this.showPerspective) { - radius = size / -point.trans.z; + if (exports.isString(color.highlight)) { + c.highlight = { + border: color.highlight, + background: color.highlight + }; } else { - radius = size * -(this.eye.z / this.camera.getArmLength()); - } - if (radius < 0) { - radius = 0; + c.highlight = {}; + c.highlight.background = color.highlight && color.highlight.background || undefined; + c.highlight.border = color.highlight && color.highlight.border || undefined; } - var hue, color, borderColor; - if (this.style === Graph3d.STYLE.DOTCOLOR) { - // calculate the color based on the value - hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; - color = this._hsv2rgb(hue, 1, 1); - borderColor = this._hsv2rgb(hue, 1, 0.8); - } else if (this.style === Graph3d.STYLE.DOTSIZE) { - color = this.colorDot; - borderColor = this.colorDotBorder; + if (exports.isString(color.hover)) { + c.hover = { + border: color.hover, + background: color.hover + }; } else { - // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 - hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; - color = this._hsv2rgb(hue, 1, 1); - borderColor = this._hsv2rgb(hue, 1, 0.8); + c.hover = {}; + c.hover.background = color.hover && color.hover.background || undefined; + c.hover.border = color.hover && color.hover.border || undefined; } - - // draw the circle - ctx.lineWidth = 1; - ctx.strokeStyle = borderColor; - ctx.fillStyle = color; - ctx.beginPath(); - ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI * 2, true); - ctx.fill(); - ctx.stroke(); } + + return c; }; /** - * Draw all datapoints as bars. - * This function can be used when the style is 'bar', 'bar-color', or 'bar-size' + * http://www.javascripter.net/faq/rgb2hsv.htm + * + * @param red + * @param green + * @param blue + * @returns {*} + * @constructor */ - Graph3d.prototype._redrawDataBar = function () { - var canvas = this.frame.canvas; - var ctx = canvas.getContext('2d'); - var i, j, surface, corners; - - if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? - - // calculate the translations of all points - for (i = 0; i < this.dataPoints.length; i++) { - var trans = this._convertPointToTranslation(this.dataPoints[i].point); - var screen = this._convertTranslationToScreen(trans); - this.dataPoints[i].trans = trans; - this.dataPoints[i].screen = screen; + 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)); - // calculate the distance from the point at the bottom to the camera - var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); - this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; + // Black-gray-white + if (minRGB == maxRGB) { + return { h: 0, s: 0, v: minRGB }; } - // order the translated points by depth - var sortDepth = function sortDepth(a, b) { - return b.dist - a.dist; - }; - this.dataPoints.sort(sortDepth); - - // draw the datapoints as bars - var xWidth = this.xBarWidth / 2; - var yWidth = this.yBarWidth / 2; - for (i = 0; i < this.dataPoints.length; i++) { - var point = this.dataPoints[i]; - - // determine color - var hue, color, borderColor; - if (this.style === Graph3d.STYLE.BARCOLOR) { - // calculate the color based on the value - hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; - color = this._hsv2rgb(hue, 1, 1); - borderColor = this._hsv2rgb(hue, 1, 0.8); - } else if (this.style === Graph3d.STYLE.BARSIZE) { - color = this.colorDot; - borderColor = this.colorDotBorder; - } else { - // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 - hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; - color = this._hsv2rgb(hue, 1, 1); - borderColor = this._hsv2rgb(hue, 1, 0.8); - } - - // calculate size for the bar - if (this.style === Graph3d.STYLE.BARSIZE) { - xWidth = this.xBarWidth / 2 * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); - yWidth = this.yBarWidth / 2 * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); - } + // 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 }; + }; - // calculate all corner points - var me = this; - var point3d = point.point; - var top = [{ point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z) }, { point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z) }, { point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z) }, { point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z) }]; - var bottom = [{ point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin) }, { point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin) }, { point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin) }, { point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin) }]; + var cssUtil = { + // split a string with css styles into an object with key/values + split: function split(cssText) { + var styles = {}; - // calculate screen location of the points - top.forEach(function (obj) { - obj.screen = me._convert3Dto2D(obj.point); - }); - bottom.forEach(function (obj) { - obj.screen = me._convert3Dto2D(obj.point); + 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; + } }); - // create five sides, calculate both corner points and center points - var surfaces = [{ corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point) }, { corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point) }, { corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point) }, { corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point) }, { corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point) }]; - point.surfaces = surfaces; - - // calculate the distance of each of the surface centers to the camera - for (j = 0; j < surfaces.length; j++) { - surface = surfaces[j]; - var transCenter = this._convertPointToTranslation(surface.center); - surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z; - // TODO: this dept calculation doesn't work 100% of the cases due to perspective, - // but the current solution is fast/simple and works in 99.9% of all cases - // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9}) - } - - // order the surfaces by their (translated) depth - surfaces.sort(function (a, b) { - var diff = b.dist - a.dist; - if (diff) return diff; - - // if equal depth, sort the top surface last - if (a.corners === top) return 1; - if (b.corners === top) return -1; - - // both are equal - return 0; - }); + return styles; + }, - // draw the ordered surfaces - ctx.lineWidth = 1; - ctx.strokeStyle = borderColor; - ctx.fillStyle = color; - // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside - for (j = 2; j < surfaces.length; j++) { - surface = surfaces[j]; - corners = surface.corners; - ctx.beginPath(); - ctx.moveTo(corners[3].screen.x, corners[3].screen.y); - ctx.lineTo(corners[0].screen.x, corners[0].screen.y); - ctx.lineTo(corners[1].screen.x, corners[1].screen.y); - ctx.lineTo(corners[2].screen.x, corners[2].screen.y); - ctx.lineTo(corners[3].screen.x, corners[3].screen.y); - ctx.fill(); - ctx.stroke(); - } + // build a css text string from an object with key/values + join: function join(styles) { + return Object.keys(styles).map(function (key) { + return key + ': ' + styles[key]; + }).join('; '); } }; /** - * Draw a line through all datapoints. - * This function can be used when the style is 'line' + * Append a string with css styles to an element + * @param {Element} element + * @param {String} cssText */ - Graph3d.prototype._redrawDataLine = function () { - var canvas = this.frame.canvas, - ctx = canvas.getContext('2d'), - point, - i; - - if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? - - // calculate the translations of all points - for (i = 0; i < this.dataPoints.length; i++) { - var trans = this._convertPointToTranslation(this.dataPoints[i].point); - var screen = this._convertTranslationToScreen(trans); - - this.dataPoints[i].trans = trans; - this.dataPoints[i].screen = screen; - } + exports.addCssText = function (element, cssText) { + var currentStyles = cssUtil.split(element.style.cssText); + var newStyles = cssUtil.split(cssText); + var styles = exports.extend(currentStyles, newStyles); - // start the line - if (this.dataPoints.length > 0) { - point = this.dataPoints[0]; + element.style.cssText = cssUtil.join(styles); + }; - ctx.lineWidth = 1; // TODO: make customizable - ctx.strokeStyle = 'blue'; // TODO: make customizable - ctx.beginPath(); - ctx.moveTo(point.screen.x, point.screen.y); - } + /** + * 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); - // draw the datapoints as colored circles - for (i = 1; i < this.dataPoints.length; i++) { - point = this.dataPoints[i]; - ctx.lineTo(point.screen.x, point.screen.y); + for (var key in removeStyles) { + if (removeStyles.hasOwnProperty(key)) { + delete styles[key]; + } } - // finish the line - if (this.dataPoints.length > 0) { - ctx.stroke(); - } + element.style.cssText = cssUtil.join(styles); }; /** - * Start a moving operation inside the provided parent element - * @param {Event} event The event that occurred (required for - * retrieving the mouse position) + * https://gist.github.com/mjijackson/5311256 + * @param h + * @param s + * @param v + * @returns {{r: number, g: number, b: number}} + * @constructor */ - Graph3d.prototype._onMouseDown = function (event) { - event = event || window.event; + exports.HSVToRGB = function (h, s, v) { + var r, g, b; - // check if mouse is still down (may be up when focus is lost for example - // in an iframe) - if (this.leftButtonDown) { - this._onMouseUp(event); + 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; } - // only react on left mouse button down - this.leftButtonDown = event.which ? event.which === 1 : event.button === 1; - if (!this.leftButtonDown && !this.touchDown) return; + return { r: Math.floor(r * 255), g: Math.floor(g * 255), b: Math.floor(b * 255) }; + }; - // get mouse position (different code for IE and all other browsers) - this.startMouseX = getMouseX(event); - this.startMouseY = getMouseY(event); + exports.HSVToHex = function (h, s, v) { + var rgb = exports.HSVToRGB(h, s, v); + return exports.RGBToHex(rgb.r, rgb.g, rgb.b); + }; - this.startStart = new Date(this.start); - this.startEnd = new Date(this.end); - this.startArmRotation = this.camera.getArmRotation(); + exports.hexToHSV = function (hex) { + var rgb = exports.hexToRGB(hex); + return exports.RGBToHSV(rgb.r, rgb.g, rgb.b); + }; - this.frame.style.cursor = 'move'; + exports.isValidHex = function (hex) { + var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex); + return isOk; + }; - // 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', me.onmousemove); - util.addEventListener(document, 'mouseup', me.onmouseup); - util.preventDefault(event); + 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; }; /** - * Perform moving operating. - * This function activated from within the funcion Graph.mouseDown(). - * @param {Event} event Well, eehh, the event + * This recursively redirects the prototype of JSON objects to the referenceObject + * This is used for default options. + * + * @param referenceObject + * @returns {*} */ - Graph3d.prototype._onMouseMove = function (event) { - event = event || window.event; - - // calculate change in mouse position - var diffX = parseFloat(getMouseX(event)) - this.startMouseX; - var diffY = parseFloat(getMouseY(event)) - this.startMouseY; - - var horizontalNew = this.startArmRotation.horizontal + diffX / 200; - var verticalNew = this.startArmRotation.vertical + diffY / 200; - - var snapAngle = 4; // degrees - var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI); - - // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc... - // the -0.001 is to take care that the vertical axis is always drawn at the left front corner - if (Math.abs(Math.sin(horizontalNew)) < snapValue) { - horizontalNew = Math.round(horizontalNew / Math.PI) * Math.PI - 0.001; - } - if (Math.abs(Math.cos(horizontalNew)) < snapValue) { - horizontalNew = (Math.round(horizontalNew / Math.PI - 0.5) + 0.5) * Math.PI - 0.001; - } - - // snap vertically to nice angles - if (Math.abs(Math.sin(verticalNew)) < snapValue) { - verticalNew = Math.round(verticalNew / Math.PI) * Math.PI; - } - if (Math.abs(Math.cos(verticalNew)) < snapValue) { - verticalNew = (Math.round(verticalNew / Math.PI - 0.5) + 0.5) * Math.PI; + exports.selectiveBridgeObject = function (fields, referenceObject) { + if (typeof referenceObject == 'object') { + var objectTo = Object.create(referenceObject); + for (var i = 0; i < fields.length; i++) { + if (referenceObject.hasOwnProperty(fields[i])) { + if (typeof referenceObject[fields[i]] == 'object') { + objectTo[fields[i]] = exports.bridgeObject(referenceObject[fields[i]]); + } + } + } + return objectTo; + } else { + return null; } - - this.camera.setArmRotation(horizontalNew, verticalNew); - this.redraw(); - - // fire a cameraPositionChange event - var parameters = this.getCameraPosition(); - this.emit('cameraPositionChange', parameters); - - util.preventDefault(event); }; /** - * Stop moving operating. - * This function activated from within the funcion Graph.mouseDown(). - * @param {event} event The event + * This recursively redirects the prototype of JSON objects to the referenceObject + * This is used for default options. + * + * @param referenceObject + * @returns {*} */ - Graph3d.prototype._onMouseUp = function (event) { - this.frame.style.cursor = 'auto'; - this.leftButtonDown = false; - - // remove event listeners here - util.removeEventListener(document, 'mousemove', this.onmousemove); - util.removeEventListener(document, 'mouseup', this.onmouseup); - util.preventDefault(event); + exports.bridgeObject = function (referenceObject) { + if (typeof referenceObject == 'object') { + var objectTo = Object.create(referenceObject); + for (var i in referenceObject) { + if (referenceObject.hasOwnProperty(i)) { + if (typeof referenceObject[i] == 'object') { + objectTo[i] = exports.bridgeObject(referenceObject[i]); + } + } + } + return objectTo; + } else { + return null; + } }; /** - * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point - * @param {Event} event A mouse move event + * 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. + * + * @param [object] mergeTarget | this is either this.options or the options used for the groups. + * @param [object] options | options + * @param [String] option | this is the option key in the options argument + * @private */ - Graph3d.prototype._onTooltip = function (event) { - var delay = 300; // ms - var boundingRect = this.frame.getBoundingClientRect(); - var mouseX = getMouseX(event) - boundingRect.left; - var mouseY = getMouseY(event) - boundingRect.top; - - if (!this.showTooltip) { - return; - } - - if (this.tooltipTimeout) { - clearTimeout(this.tooltipTimeout); - } - - // (delayed) display of a tooltip only if no mouse button is down - if (this.leftButtonDown) { - this._hideTooltip(); - return; - } + exports.mergeOptions = function (mergeTarget, options, option) { + var allowDeletion = arguments[3] === undefined ? false : arguments[3]; - if (this.tooltip && this.tooltip.dataPoint) { - // tooltip is currently visible - var dataPoint = this._dataPointFromXY(mouseX, mouseY); - if (dataPoint !== this.tooltip.dataPoint) { - // datapoint changed - if (dataPoint) { - this._showTooltip(dataPoint); + if (options[option] === null) { + mergeTarget[option] = undefined; + delete mergeTarget[option]; + } else { + if (options[option] !== undefined) { + if (typeof options[option] === 'boolean') { + mergeTarget[option].enabled = options[option]; } else { - this._hideTooltip(); + if (options[option].enabled === undefined) { + mergeTarget[option].enabled = true; + } + for (var prop in options[option]) { + if (options[option].hasOwnProperty(prop)) { + mergeTarget[option][prop] = options[option][prop]; + } + } } } - } else { - // tooltip is currently not visible - var me = this; - this.tooltipTimeout = setTimeout(function () { - me.tooltipTimeout = null; - - // show a tooltip if we have a data point - var dataPoint = me._dataPointFromXY(mouseX, mouseY); - if (dataPoint) { - me._showTooltip(dataPoint); - } - }, delay); } }; /** - * Event handler for touchstart event on mobile devices + * 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} searchFunction | -1 is lower, 0 is found, 1 is higher + * @param {String} field + * @param {String} field2 + * @returns {number} + * @private */ - Graph3d.prototype._onTouchStart = function (event) { - this.touchDown = true; + exports.binarySearchCustom = function (orderedItems, searchFunction, field, field2) { + var maxIterations = 10000; + var iteration = 0; + var low = 0; + var high = orderedItems.length - 1; - var me = this; - this.ontouchmove = function (event) { - me._onTouchMove(event); - }; - this.ontouchend = function (event) { - me._onTouchEnd(event); - }; - util.addEventListener(document, 'touchmove', me.ontouchmove); - util.addEventListener(document, 'touchend', me.ontouchend); + while (low <= high && iteration < maxIterations) { + var middle = Math.floor((low + high) / 2); - this._onMouseDown(event); - }; + var item = orderedItems[middle]; + var value = field2 === undefined ? item[field] : item[field][field2]; - /** - * Event handler for touchmove event on mobile devices - */ - Graph3d.prototype._onTouchMove = function (event) { - this._onMouseMove(event); + var searchResult = searchFunction(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; }; /** - * Event handler for touchend event on mobile devices + * 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' + * @returns {number} + * @private */ - Graph3d.prototype._onTouchEnd = function (event) { - this.touchDown = false; + exports.binarySearchValue = function (orderedItems, target, field, sidePreference) { + var maxIterations = 10000; + var iteration = 0; + var low = 0; + var high = orderedItems.length - 1; + var prevValue, value, nextValue, middle; - util.removeEventListener(document, 'touchmove', this.ontouchmove); - util.removeEventListener(document, 'touchend', this.ontouchend); + 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]; - this._onMouseUp(event); + if (value == target) { + // we found the target + return middle; + } else if (prevValue < target && value > target) { + // target is in between of the previous and the current + return sidePreference == 'before' ? Math.max(0, middle - 1) : middle; + } else if (value < target && nextValue > target) { + // 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 (value < target) { + // 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; }; - /** - * Event handler for mouse wheel event, used to zoom the graph - * Code from http://adomas.org/javascript-mouse-wheel/ - * @param {event} event The event + /* + * 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 */ - Graph3d.prototype._onWheel = function (event) { - if (!event) /* For IE. */ - event = window.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; + 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 < 0.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 < 0.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 < 0.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 < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t; } + }; - // 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) { - var oldLength = this.camera.getArmLength(); - var newLength = oldLength * (1 - delta / 10); +/***/ }, +/* 8 */ +/***/ function(module, exports, __webpack_require__) { - this.camera.setArmLength(newLength); - this.redraw(); + // first check if moment.js is already loaded in the browser window, if so, + // use this instance. Else, load via commonjs. + 'use strict'; - this._hideTooltip(); - } + module.exports = typeof window !== 'undefined' && window['moment'] || __webpack_require__(9); - // fire a cameraPositionChange event - var parameters = this.getCameraPosition(); - this.emit('cameraPositionChange', parameters); +/***/ }, +/* 9 */ +/***/ function(module, exports, __webpack_require__) { - // Prevent default actions caused by mouse wheel. - // That might be ugly, but we handle scrolls somehow - // anyway, so don't bother here.. - util.preventDefault(event); - }; + /* WEBPACK VAR INJECTION */(function(module) {//! moment.js + //! version : 2.10.3 + //! authors : Tim Wood, Iskren Chernev, Moment.js contributors + //! license : MIT + //! momentjs.com - /** - * Test whether a point lies inside given 2D triangle - * @param {Point2d} point - * @param {Point2d[]} triangle - * @return {boolean} Returns true if given point lies inside or on the edge of the triangle - * @private - */ - Graph3d.prototype._insideTriangle = function (point, triangle) { - var a = triangle[0], - b = triangle[1], - c = triangle[2]; + (function (global, factory) { + true ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + global.moment = factory() + }(this, function () { 'use strict'; - function sign(x) { - return x > 0 ? 1 : x < 0 ? -1 : 0; - } + var hookCallback; - var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x)); - var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x)); - var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x)); + function utils_hooks__hooks () { + return hookCallback.apply(null, arguments); + } - // each of the three signs must be either equal to each other or zero - return (as == 0 || bs == 0 || as == bs) && (bs == 0 || cs == 0 || bs == cs) && (as == 0 || cs == 0 || as == cs); - }; + // This is done to register the method called with moment() + // without creating circular dependencies. + function setHookCallback (callback) { + hookCallback = callback; + } - /** - * Find a data point close to given screen position (x, y) - * @param {Number} x - * @param {Number} y - * @return {Object | null} The closest data point or null if not close to any data point - * @private - */ - Graph3d.prototype._dataPointFromXY = function (x, y) { - var i, - distMax = 100, - // px - dataPoint = null, - closestDataPoint = null, - closestDist = null, - center = new Point2d(x, y); + function isArray(input) { + return Object.prototype.toString.call(input) === '[object Array]'; + } - if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { - // the data points are ordered from far away to closest - for (i = this.dataPoints.length - 1; i >= 0; i--) { - dataPoint = this.dataPoints[i]; - var surfaces = dataPoint.surfaces; - if (surfaces) { - for (var s = surfaces.length - 1; s >= 0; s--) { - // split each surface in two triangles, and see if the center point is inside one of these - var surface = surfaces[s]; - var corners = surface.corners; - var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen]; - var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen]; - if (this._insideTriangle(center, triangle1) || this._insideTriangle(center, triangle2)) { - // return immediately at the first hit - return dataPoint; - } - } - } + function isDate(input) { + return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; } - } else { - // find the closest data point, using distance to the center of the point on 2d screen - for (i = 0; i < this.dataPoints.length; i++) { - dataPoint = this.dataPoints[i]; - var point = dataPoint.screen; - if (point) { - var distX = Math.abs(x - point.x); - var distY = Math.abs(y - point.y); - var dist = Math.sqrt(distX * distX + distY * distY); - if ((closestDist === null || dist < closestDist) && dist < distMax) { - closestDist = dist; - closestDataPoint = dataPoint; + function map(arr, fn) { + var res = [], i; + for (i = 0; i < arr.length; ++i) { + res.push(fn(arr[i], i)); } - } + return res; } - } - - return closestDataPoint; - }; - - /** - * Display a tooltip for given data point - * @param {Object} dataPoint - * @private - */ - Graph3d.prototype._showTooltip = function (dataPoint) { - var content, line, dot; - if (!this.tooltip) { - content = document.createElement('div'); - content.style.position = 'absolute'; - content.style.padding = '10px'; - content.style.border = '1px solid #4d4d4d'; - content.style.color = '#1a1a1a'; - content.style.background = 'rgba(255,255,255,0.7)'; - content.style.borderRadius = '2px'; - content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)'; + function hasOwnProp(a, b) { + return Object.prototype.hasOwnProperty.call(a, b); + } - line = document.createElement('div'); - line.style.position = 'absolute'; - line.style.height = '40px'; - line.style.width = '0'; - line.style.borderLeft = '1px solid #4d4d4d'; + function extend(a, b) { + for (var i in b) { + if (hasOwnProp(b, i)) { + a[i] = b[i]; + } + } - dot = document.createElement('div'); - dot.style.position = 'absolute'; - dot.style.height = '0'; - dot.style.width = '0'; - dot.style.border = '5px solid #4d4d4d'; - dot.style.borderRadius = '5px'; + if (hasOwnProp(b, 'toString')) { + a.toString = b.toString; + } - this.tooltip = { - dataPoint: null, - dom: { - content: content, - line: line, - dot: dot - } - }; - } else { - content = this.tooltip.dom.content; - line = this.tooltip.dom.line; - dot = this.tooltip.dom.dot; - } + if (hasOwnProp(b, 'valueOf')) { + a.valueOf = b.valueOf; + } - this._hideTooltip(); + return a; + } - this.tooltip.dataPoint = dataPoint; - if (typeof this.showTooltip === 'function') { - content.innerHTML = this.showTooltip(dataPoint.point); - } else { - content.innerHTML = '' + '' + '' + '' + '
x:' + dataPoint.point.x + '
y:' + dataPoint.point.y + '
z:' + dataPoint.point.z + '
'; - } + function create_utc__createUTC (input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, true).utc(); + } - content.style.left = '0'; - content.style.top = '0'; - this.frame.appendChild(content); - this.frame.appendChild(line); - this.frame.appendChild(dot); - - // calculate sizes - var contentWidth = content.offsetWidth; - var contentHeight = content.offsetHeight; - var lineHeight = line.offsetHeight; - var dotWidth = dot.offsetWidth; - var dotHeight = dot.offsetHeight; + function defaultParsingFlags() { + // We need to deep clone this object. + return { + empty : false, + unusedTokens : [], + unusedInput : [], + overflow : -2, + charsLeftOver : 0, + nullInput : false, + invalidMonth : null, + invalidFormat : false, + userInvalidated : false, + iso : false + }; + } - var left = dataPoint.screen.x - contentWidth / 2; - left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth); + function getParsingFlags(m) { + if (m._pf == null) { + m._pf = defaultParsingFlags(); + } + return m._pf; + } - line.style.left = dataPoint.screen.x + 'px'; - line.style.top = dataPoint.screen.y - lineHeight + 'px'; - content.style.left = left + 'px'; - content.style.top = dataPoint.screen.y - lineHeight - contentHeight + 'px'; - dot.style.left = dataPoint.screen.x - dotWidth / 2 + 'px'; - dot.style.top = dataPoint.screen.y - dotHeight / 2 + 'px'; - }; + function valid__isValid(m) { + if (m._isValid == null) { + var flags = getParsingFlags(m); + m._isValid = !isNaN(m._d.getTime()) && + flags.overflow < 0 && + !flags.empty && + !flags.invalidMonth && + !flags.nullInput && + !flags.invalidFormat && + !flags.userInvalidated; - /** - * Hide the tooltip when displayed - * @private - */ - Graph3d.prototype._hideTooltip = function () { - if (this.tooltip) { - this.tooltip.dataPoint = null; + if (m._strict) { + m._isValid = m._isValid && + flags.charsLeftOver === 0 && + flags.unusedTokens.length === 0 && + flags.bigHour === undefined; + } + } + return m._isValid; + } - for (var prop in this.tooltip.dom) { - if (this.tooltip.dom.hasOwnProperty(prop)) { - var elem = this.tooltip.dom[prop]; - if (elem && elem.parentNode) { - elem.parentNode.removeChild(elem); + function valid__createInvalid (flags) { + var m = create_utc__createUTC(NaN); + if (flags != null) { + extend(getParsingFlags(m), flags); } - } + else { + getParsingFlags(m).userInvalidated = true; + } + + return m; } - } - }; - /**--------------------------------------------------------------------------**/ + var momentProperties = utils_hooks__hooks.momentProperties = []; - /** - * Get the horizontal mouse position from a mouse event - * @param {Event} event - * @return {Number} mouse x - */ - function getMouseX(event) { - if ('clientX' in event) return event.clientX; - return event.targetTouches[0] && event.targetTouches[0].clientX || 0; - } + function copyConfig(to, from) { + var i, prop, val; - /** - * Get the vertical mouse position from a mouse event - * @param {Event} event - * @return {Number} mouse y - */ - function getMouseY(event) { - if ('clientY' in event) return event.clientY; - return event.targetTouches[0] && event.targetTouches[0].clientY || 0; - } + if (typeof from._isAMomentObject !== 'undefined') { + to._isAMomentObject = from._isAMomentObject; + } + if (typeof from._i !== 'undefined') { + to._i = from._i; + } + if (typeof from._f !== 'undefined') { + to._f = from._f; + } + if (typeof from._l !== 'undefined') { + to._l = from._l; + } + if (typeof from._strict !== 'undefined') { + to._strict = from._strict; + } + if (typeof from._tzm !== 'undefined') { + to._tzm = from._tzm; + } + if (typeof from._isUTC !== 'undefined') { + to._isUTC = from._isUTC; + } + if (typeof from._offset !== 'undefined') { + to._offset = from._offset; + } + if (typeof from._pf !== 'undefined') { + to._pf = getParsingFlags(from); + } + if (typeof from._locale !== 'undefined') { + to._locale = from._locale; + } - module.exports = Graph3d; + if (momentProperties.length > 0) { + for (i in momentProperties) { + prop = momentProperties[i]; + val = from[prop]; + if (typeof val !== 'undefined') { + to[prop] = val; + } + } + } - // use use defaults + return to; + } -/***/ }, -/* 8 */ -/***/ function(module, exports, __webpack_require__) { + var updateInProgress = false; - 'use strict'; + // Moment prototype object + function Moment(config) { + copyConfig(this, config); + this._d = new Date(+config._d); + // Prevent infinite loop in case updateOffset creates new moment + // objects. + if (updateInProgress === false) { + updateInProgress = true; + utils_hooks__hooks.updateOffset(this); + updateInProgress = false; + } + } - var Point3d = __webpack_require__(11); + function isMoment (obj) { + return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); + } - /** - * @class Camera - * 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 - */ - function Camera() { - this.armLocation = new Point3d(); - this.armRotation = {}; - this.armRotation.horizontal = 0; - this.armRotation.vertical = 0; - this.armLength = 1.7; + function toInt(argumentForCoercion) { + var coercedNumber = +argumentForCoercion, + value = 0; - this.cameraLocation = new Point3d(); - this.cameraRotation = new Point3d(0.5 * Math.PI, 0, 0); + if (coercedNumber !== 0 && isFinite(coercedNumber)) { + if (coercedNumber >= 0) { + value = Math.floor(coercedNumber); + } else { + value = Math.ceil(coercedNumber); + } + } - this.calculateCameraOrientation(); - } + return value; + } - /** - * 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; + function compareArrays(array1, array2, dontConvert) { + var len = Math.min(array1.length, array2.length), + lengthDiff = Math.abs(array1.length - array2.length), + diffs = 0, + i; + for (i = 0; i < len; i++) { + if ((dontConvert && array1[i] !== array2[i]) || + (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { + diffs++; + } + } + return diffs + lengthDiff; + } - this.calculateCameraOrientation(); - }; + function Locale() { + } - /** - * 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; - } + var locales = {}; + var globalLocale; - 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; - } + function normalizeLocale(key) { + return key ? key.toLowerCase().replace('_', '-') : key; + } - if (horizontal !== undefined || vertical !== undefined) { - this.calculateCameraOrientation(); - } - }; + // pick the locale from the array + // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each + // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root + function chooseLocale(names) { + var i = 0, j, next, locale, split; - /** - * 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; + while (i < names.length) { + split = normalizeLocale(names[i]).split('-'); + j = split.length; + next = normalizeLocale(names[i + 1]); + next = next ? next.split('-') : null; + while (j > 0) { + locale = loadLocale(split.slice(0, j).join('-')); + if (locale) { + return locale; + } + if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { + //the next array item is better than a shallower substring of this one + break; + } + j--; + } + i++; + } + return null; + } - return rot; - }; + function loadLocale(name) { + var oldLocale = null; + // TODO: Find a better way to register and load all the locales in Node + if (!locales[name] && typeof module !== 'undefined' && + module && module.exports) { + try { + oldLocale = globalLocale._abbr; + !(function webpackMissingModule() { var e = new Error("Cannot find module \"./locale\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()); + // because defineLocale currently also sets the global locale, we + // want to undo that for lazy loaded locales + locale_locales__getSetGlobalLocale(oldLocale); + } catch (e) { } + } + return locales[name]; + } - /** - * 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 function will load locale and then set the global locale. If + // no arguments are passed in, it will simply return the current global + // locale key. + function locale_locales__getSetGlobalLocale (key, values) { + var data; + if (key) { + if (typeof values === 'undefined') { + data = locale_locales__getLocale(key); + } + else { + data = defineLocale(key, values); + } - this.armLength = length; + if (data) { + // moment.duration._locale = moment._locale = data; + globalLocale = data; + } + } - // 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) this.armLength = 5; + return globalLocale._abbr; + } - this.calculateCameraOrientation(); - }; + function defineLocale (name, values) { + if (values !== null) { + values.abbr = name; + if (!locales[name]) { + locales[name] = new Locale(); + } + locales[name].set(values); - /** - * Retrieve the arm length - * @return {Number} length - */ - Camera.prototype.getArmLength = function () { - return this.armLength; - }; + // backwards compat for now: also set the locale + locale_locales__getSetGlobalLocale(name); - /** - * Retrieve the camera location - * @return {Point3d} cameraLocation - */ - Camera.prototype.getCameraLocation = function () { - return this.cameraLocation; - }; + return locales[name]; + } else { + // useful for testing + delete locales[name]; + return null; + } + } - /** - * Retrieve the camera rotation - * @return {Point3d} cameraRotation - */ - Camera.prototype.getCameraRotation = function () { - return this.cameraRotation; - }; + // returns locale data + function locale_locales__getLocale (key) { + var locale; - /** - * 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); + if (key && key._locale && key._locale._abbr) { + key = key._locale._abbr; + } - // calculate rotation of the camera - this.cameraRotation.x = Math.PI / 2 - this.armRotation.vertical; - this.cameraRotation.y = 0; - this.cameraRotation.z = -this.armRotation.horizontal; - }; + if (!key) { + return globalLocale; + } - module.exports = Camera; + if (!isArray(key)) { + //short-circuit everything else + locale = loadLocale(key); + if (locale) { + return locale; + } + key = [key]; + } -/***/ }, -/* 9 */ -/***/ function(module, exports, __webpack_require__) { + return chooseLocale(key); + } - 'use strict'; + var aliases = {}; - var DataView = __webpack_require__(5); + function addUnitAlias (unit, shorthand) { + var lowerCase = unit.toLowerCase(); + aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; + } - /** - * @class Filter - * - * @param {DataSet} data The google data table - * @param {Number} column The index of the column to be filtered - * @param {Graph} graph The graph - */ - function Filter(data, column, graph) { - this.data = data; - this.column = column; - this.graph = graph; // the parent graph + function normalizeUnits(units) { + return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; + } - this.index = undefined; - this.value = undefined; + function normalizeObjectUnits(inputObject) { + var normalizedInput = {}, + normalizedProp, + prop; - // read all distinct values and select the first one - this.values = graph.getDistinctValues(data.get(), this.column); + for (prop in inputObject) { + if (hasOwnProp(inputObject, prop)) { + normalizedProp = normalizeUnits(prop); + if (normalizedProp) { + normalizedInput[normalizedProp] = inputObject[prop]; + } + } + } - // sort both numeric and string values correctly - this.values.sort(function (a, b) { - return a > b ? 1 : a < b ? -1 : 0; - }); + return normalizedInput; + } - if (this.values.length > 0) { - this.selectValue(0); - } + function makeGetSet (unit, keepTime) { + return function (value) { + if (value != null) { + get_set__set(this, unit, value); + utils_hooks__hooks.updateOffset(this, keepTime); + return this; + } else { + return get_set__get(this, unit); + } + }; + } - // create an array with the filtered datapoints. this will be loaded afterwards - this.dataPoints = []; + function get_set__get (mom, unit) { + return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); + } - this.loaded = false; - this.onLoadCallback = undefined; + function get_set__set (mom, unit, value) { + return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); + } - if (graph.animationPreload) { - this.loaded = false; - this.loadInBackground(); - } else { - this.loaded = true; - } - }; + // MOMENTS - /** - * Return the label - * @return {string} label - */ - Filter.prototype.isLoaded = function () { - return this.loaded; - }; + function getSet (units, value) { + var unit; + if (typeof units === 'object') { + for (unit in units) { + this.set(unit, units[unit]); + } + } else { + units = normalizeUnits(units); + if (typeof this[units] === 'function') { + return this[units](value); + } + } + return this; + } - /** - * Return the loaded progress - * @return {Number} percentage between 0 and 100 - */ - Filter.prototype.getLoadedProgress = function () { - var len = this.values.length; + function zeroFill(number, targetLength, forceSign) { + var output = '' + Math.abs(number), + sign = number >= 0; - var i = 0; - while (this.dataPoints[i]) { - i++; - } + while (output.length < targetLength) { + output = '0' + output; + } + return (sign ? (forceSign ? '+' : '') : '-') + output; + } - return Math.round(i / len * 100); - }; + var formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g; - /** - * Return the label - * @return {string} label - */ - Filter.prototype.getLabel = function () { - return this.graph.filterLabel; - }; + var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; - /** - * Return the columnIndex of the filter - * @return {Number} columnIndex - */ - Filter.prototype.getColumn = function () { - return this.column; - }; + var formatFunctions = {}; - /** - * Return the currently selected value. Returns undefined if there is no selection - * @return {*} value - */ - Filter.prototype.getSelectedValue = function () { - if (this.index === undefined) return undefined; + var formatTokenFunctions = {}; - return this.values[this.index]; - }; + // token: 'M' + // padded: ['MM', 2] + // ordinal: 'Mo' + // callback: function () { this.month() + 1 } + function addFormatToken (token, padded, ordinal, callback) { + var func = callback; + if (typeof callback === 'string') { + func = function () { + return this[callback](); + }; + } + if (token) { + formatTokenFunctions[token] = func; + } + if (padded) { + formatTokenFunctions[padded[0]] = function () { + return zeroFill(func.apply(this, arguments), padded[1], padded[2]); + }; + } + if (ordinal) { + formatTokenFunctions[ordinal] = function () { + return this.localeData().ordinal(func.apply(this, arguments), token); + }; + } + } - /** - * Retrieve all values of the filter - * @return {Array} values - */ - Filter.prototype.getValues = function () { - return this.values; - }; + function removeFormattingTokens(input) { + if (input.match(/\[[\s\S]/)) { + return input.replace(/^\[|\]$/g, ''); + } + return input.replace(/\\/g, ''); + } - /** - * Retrieve one value of the filter - * @param {Number} index - * @return {*} value - */ - Filter.prototype.getValue = function (index) { - if (index >= this.values.length) throw 'Error: index out of range'; + function makeFormatFunction(format) { + var array = format.match(formattingTokens), i, length; - return this.values[index]; - }; + for (i = 0, length = array.length; i < length; i++) { + if (formatTokenFunctions[array[i]]) { + array[i] = formatTokenFunctions[array[i]]; + } else { + array[i] = removeFormattingTokens(array[i]); + } + } - /** - * 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; + return function (mom) { + var output = ''; + for (i = 0; i < length; i++) { + output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; + } + return output; + }; + } - if (index === undefined) return []; + // format date using native date object + function formatMoment(m, format) { + if (!m.isValid()) { + return m.localeData().invalidDate(); + } - var dataPoints; - if (this.dataPoints[index]) { - dataPoints = this.dataPoints[index]; - } else { - var f = {}; - f.column = this.column; - f.value = this.values[index]; + format = expandFormat(format, m.localeData()); - var dataView = new DataView(this.data, { filter: function filter(item) { - return item[f.column] == f.value; - } }).get(); - dataPoints = this.graph._getDataPoints(dataView); + if (!formatFunctions[format]) { + formatFunctions[format] = makeFormatFunction(format); + } - this.dataPoints[index] = dataPoints; - } + return formatFunctions[format](m); + } - return dataPoints; - }; + function expandFormat(format, locale) { + var i = 5; - /** - * Set a callback function when the filter is fully loaded. - */ - Filter.prototype.setOnLoadCallback = function (callback) { - this.onLoadCallback = callback; - }; + function replaceLongDateFormatTokens(input) { + return locale.longDateFormat(input) || input; + } - /** - * 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 'Error: index out of range'; + localFormattingTokens.lastIndex = 0; + while (i >= 0 && localFormattingTokens.test(format)) { + format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); + localFormattingTokens.lastIndex = 0; + i -= 1; + } - this.index = index; - this.value = this.values[index]; - }; + return format; + } - /** - * Load all filtered rows in the background one by one - * Start this method without providing an index! - */ - Filter.prototype.loadInBackground = function (index) { - if (index === undefined) index = 0; + var match1 = /\d/; // 0 - 9 + var match2 = /\d\d/; // 00 - 99 + var match3 = /\d{3}/; // 000 - 999 + var match4 = /\d{4}/; // 0000 - 9999 + var match6 = /[+-]?\d{6}/; // -999999 - 999999 + var match1to2 = /\d\d?/; // 0 - 99 + var match1to3 = /\d{1,3}/; // 0 - 999 + var match1to4 = /\d{1,4}/; // 0 - 9999 + var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 - var frame = this.graph.frame; + var matchUnsigned = /\d+/; // 0 - inf + var matchSigned = /[+-]?\d+/; // -inf - inf - if (index < this.values.length) { - var dataPointsTemp = this._getDataPoints(index); - //this.graph.redrawInfo(); // TODO: not neat + var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z - // 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 matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 - var me = this; - setTimeout(function () { - me.loadInBackground(index + 1); - }, 10); - this.loaded = false; - } else { - this.loaded = true; + // any word (or two) characters or numbers including two/three word month in arabic. + var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i; - // remove the progress box - if (frame.progress !== undefined) { - frame.removeChild(frame.progress); - frame.progress = undefined; - } + var regexes = {}; - if (this.onLoadCallback) this.onLoadCallback(); - } - }; + function addRegexToken (token, regex, strictRegex) { + regexes[token] = typeof regex === 'function' ? regex : function (isStrict) { + return (isStrict && strictRegex) ? strictRegex : regex; + }; + } - module.exports = Filter; + function getParseRegexForToken (token, config) { + if (!hasOwnProp(regexes, token)) { + return new RegExp(unescapeFormat(token)); + } -/***/ }, -/* 10 */ -/***/ function(module, exports, __webpack_require__) { + return regexes[token](config._strict, config._locale); + } - /** - * @prototype Point2d - * @param {Number} [x] - * @param {Number} [y] - */ - "use strict"; + // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript + function unescapeFormat(s) { + return s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { + return p1 || p2 || p3 || p4; + }).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); + } - function Point2d(x, y) { - this.x = x !== undefined ? x : 0; - this.y = y !== undefined ? y : 0; - } + var tokens = {}; - module.exports = Point2d; + function addParseToken (token, callback) { + var i, func = callback; + if (typeof token === 'string') { + token = [token]; + } + if (typeof callback === 'number') { + func = function (input, array) { + array[callback] = toInt(input); + }; + } + for (i = 0; i < token.length; i++) { + tokens[token[i]] = func; + } + } -/***/ }, -/* 11 */ -/***/ function(module, exports, __webpack_require__) { + function addWeekParseToken (token, callback) { + addParseToken(token, function (input, array, config, token) { + config._w = config._w || {}; + callback(input, config._w, config, token); + }); + } - /** - * @prototype Point3d - * @param {Number} [x] - * @param {Number} [y] - * @param {Number} [z] - */ - "use strict"; + function addTimeToArrayFromToken(token, input, config) { + if (input != null && hasOwnProp(tokens, token)) { + tokens[token](input, config._a, config, token); + } + } - function Point3d(x, y, z) { - this.x = x !== undefined ? x : 0; - this.y = y !== undefined ? y : 0; - this.z = z !== undefined ? z : 0; - }; + var YEAR = 0; + var MONTH = 1; + var DATE = 2; + var HOUR = 3; + var MINUTE = 4; + var SECOND = 5; + var MILLISECOND = 6; - /** - * 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; - }; + function daysInMonth(year, month) { + return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); + } - /** - * 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; - }; + // FORMATTING - /** - * 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); - }; + addFormatToken('M', ['MM', 2], 'Mo', function () { + return this.month() + 1; + }); - /** - * 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(); + addFormatToken('MMM', 0, 0, function (format) { + return this.localeData().monthsShort(this, format); + }); - 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; + addFormatToken('MMMM', 0, 0, function (format) { + return this.localeData().months(this, format); + }); - return crossproduct; - }; + // ALIASES - /** - * 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); - }; + addUnitAlias('month', 'M'); - module.exports = Point3d; + // PARSING -/***/ }, -/* 12 */ -/***/ function(module, exports, __webpack_require__) { + addRegexToken('M', match1to2); + addRegexToken('MM', match1to2, match2); + addRegexToken('MMM', matchWord); + addRegexToken('MMMM', matchWord); - 'use strict'; + addParseToken(['M', 'MM'], function (input, array) { + array[MONTH] = toInt(input) - 1; + }); - var util = __webpack_require__(2); + addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { + var month = config._locale.monthsParse(input, token, config._strict); + // if we didn't find a month name, mark the date as invalid. + if (month != null) { + array[MONTH] = month; + } else { + getParsingFlags(config).invalidMonth = input; + } + }); - /** - * @constructor Slider - * - * An html slider control with start/stop/prev/next buttons - * @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 'Error: No container element defined'; - } - this.container = container; - this.visible = options && options.visible != undefined ? options.visible : true; + // LOCALES - 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); + var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); + function localeMonths (m) { + return this._months[m.month()]; + } - this.frame.prev = document.createElement('INPUT'); - this.frame.prev.type = 'BUTTON'; - this.frame.prev.value = 'Prev'; - this.frame.appendChild(this.frame.prev); + var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); + function localeMonthsShort (m) { + return this._monthsShort[m.month()]; + } - this.frame.play = document.createElement('INPUT'); - this.frame.play.type = 'BUTTON'; - this.frame.play.value = 'Play'; - this.frame.appendChild(this.frame.play); + function localeMonthsParse (monthName, format, strict) { + var i, mom, regex; - this.frame.next = document.createElement('INPUT'); - this.frame.next.type = 'BUTTON'; - this.frame.next.value = 'Next'; - this.frame.appendChild(this.frame.next); + if (!this._monthsParse) { + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + } - 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); + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = create_utc__createUTC([2000, i]); + if (strict && !this._longMonthsParse[i]) { + this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); + this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); + } + if (!strict && !this._monthsParse[i]) { + regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); + this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { + return i; + } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { + return i; + } else if (!strict && this._monthsParse[i].test(monthName)) { + return i; + } + } + } - 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); + // MOMENTS - // 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); - }; - } + function setMonth (mom, value) { + var dayOfMonth; - this.onChangeCallback = undefined; + // TODO: Move this out of here! + if (typeof value === 'string') { + value = mom.localeData().monthsParse(value); + // TODO: Another silent failure? + if (typeof value !== 'number') { + return mom; + } + } - this.values = []; - this.index = undefined; + dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); + mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); + return mom; + } - this.playTimeout = undefined; - this.playInterval = 1000; // milliseconds - this.playLoop = true; - } + function getSetMonth (value) { + if (value != null) { + setMonth(this, value); + utils_hooks__hooks.updateOffset(this, true); + return this; + } else { + return get_set__get(this, 'Month'); + } + } - /** - * Select the previous index - */ - Slider.prototype.prev = function () { - var index = this.getIndex(); - if (index > 0) { - index--; - this.setIndex(index); - } - }; + function getDaysInMonth () { + return daysInMonth(this.year(), this.month()); + } - /** - * Select the next index - */ - Slider.prototype.next = function () { - var index = this.getIndex(); - if (index < this.values.length - 1) { - index++; - this.setIndex(index); - } - }; + function checkOverflow (m) { + var overflow; + var a = m._a; - /** - * Select the next index - */ - Slider.prototype.playNext = function () { - var start = new Date(); + if (a && getParsingFlags(m).overflow === -2) { + overflow = + a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : + a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : + a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : + a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : + a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : + a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : + -1; - 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); - } + if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { + overflow = DATE; + } - var end = new Date(); - var diff = end - start; + getParsingFlags(m).overflow = overflow; + } - // 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 + return m; + } - var me = this; - this.playTimeout = setTimeout(function () { - me.playNext(); - }, interval); - }; + function warn(msg) { + if (utils_hooks__hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { + console.warn('Deprecation warning: ' + msg); + } + } - /** - * Toggle start or stop playing - */ - Slider.prototype.togglePlay = function () { - if (this.playTimeout === undefined) { - this.play(); - } else { - this.stop(); - } - }; + function deprecate(msg, fn) { + var firstTime = true, + msgWithStack = msg + '\n' + (new Error()).stack; - /** - * Start playing - */ - Slider.prototype.play = function () { - // Test whether already playing - if (this.playTimeout) return; + return extend(function () { + if (firstTime) { + warn(msgWithStack); + firstTime = false; + } + return fn.apply(this, arguments); + }, fn); + } - this.playNext(); + var deprecations = {}; - if (this.frame) { - this.frame.play.value = 'Stop'; - } - }; + function deprecateSimple(name, msg) { + if (!deprecations[name]) { + warn(msg); + deprecations[name] = true; + } + } - /** - * Stop playing - */ - Slider.prototype.stop = function () { - clearInterval(this.playTimeout); - this.playTimeout = undefined; + utils_hooks__hooks.suppressDeprecationWarnings = false; - if (this.frame) { - this.frame.play.value = 'Play'; - } - }; + var from_string__isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; - /** - * Set a callback function which will be triggered when the value of the - * slider bar has changed. - */ - Slider.prototype.setOnChangeCallback = function (callback) { - this.onChangeCallback = callback; - }; + var isoDates = [ + ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], + ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], + ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], + ['GGGG-[W]WW', /\d{4}-W\d{2}/], + ['YYYY-DDD', /\d{4}-\d{3}/] + ]; - /** - * Set the interval for playing the list - * @param {Number} interval The interval in milliseconds - */ - Slider.prototype.setPlayInterval = function (interval) { - this.playInterval = interval; - }; + // iso time formats and regexes + var isoTimes = [ + ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], + ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], + ['HH:mm', /(T| )\d\d:\d\d/], + ['HH', /(T| )\d\d/] + ]; - /** - * Retrieve the current play interval - * @return {Number} interval The interval in milliseconds - */ - Slider.prototype.getPlayInterval = function (interval) { - return this.playInterval; - }; + var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; - /** - * Set looping on or off - * @pararm {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; - }; + // date from iso format + function configFromISO(config) { + var i, l, + string = config._i, + match = from_string__isoRegex.exec(string); - /** - * Execute the onchange callback function - */ - Slider.prototype.onChange = function () { - if (this.onChangeCallback !== undefined) { - this.onChangeCallback(); - } - }; + if (match) { + getParsingFlags(config).iso = true; + for (i = 0, l = isoDates.length; i < l; i++) { + if (isoDates[i][1].exec(string)) { + // match[5] should be 'T' or undefined + config._f = isoDates[i][0] + (match[6] || ' '); + break; + } + } + for (i = 0, l = isoTimes.length; i < l; i++) { + if (isoTimes[i][1].exec(string)) { + config._f += isoTimes[i][0]; + break; + } + } + if (string.match(matchOffset)) { + config._f += 'Z'; + } + configFromStringAndFormat(config); + } else { + config._isValid = false; + } + } - /** - * 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'; + // date from iso format or fallback + function configFromString(config) { + var matched = aspNetJsonRegex.exec(config._i); - // position the slider button - var left = this.indexToLeft(this.index); - this.frame.slide.style.left = left + 'px'; - } - }; + if (matched !== null) { + config._d = new Date(+matched[1]); + return; + } - /** - * 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; + configFromISO(config); + if (config._isValid === false) { + delete config._isValid; + utils_hooks__hooks.createFromInputFallback(config); + } + } - if (this.values.length > 0) this.setIndex(0);else this.index = undefined; - }; + utils_hooks__hooks.createFromInputFallback = deprecate( + 'moment construction falls back to js Date. This is ' + + 'discouraged and will be removed in upcoming major ' + + 'release. Please refer to ' + + 'https://github.com/moment/moment/issues/1407 for more info.', + function (config) { + config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); + } + ); - /** - * Select a value by its index - * @param {Number} index - */ - Slider.prototype.setIndex = function (index) { - if (index < this.values.length) { - this.index = index; + function createDate (y, m, d, h, M, s, ms) { + //can't just apply() to create a date: + //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply + var date = new Date(y, m, d, h, M, s, ms); - this.redraw(); - this.onChange(); - } else { - throw 'Error: index out of range'; - } - }; + //the date constructor doesn't accept years < 1970 + if (y < 1970) { + date.setFullYear(y); + } + return date; + } - /** - * retrieve the index of the currently selected vaue - * @return {Number} index - */ - Slider.prototype.getIndex = function () { - return this.index; - }; + function createUTCDate (y) { + var date = new Date(Date.UTC.apply(null, arguments)); + if (y < 1970) { + date.setUTCFullYear(y); + } + return date; + } - /** - * retrieve the currently selected value - * @return {*} value - */ - Slider.prototype.get = function () { - return this.values[this.index]; - }; + addFormatToken(0, ['YY', 2], 0, function () { + return this.year() % 100; + }); - 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; + addFormatToken(0, ['YYYY', 4], 0, 'year'); + addFormatToken(0, ['YYYYY', 5], 0, 'year'); + addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); - this.startClientX = event.clientX; - this.startSlideX = parseFloat(this.frame.slide.style.left); + // ALIASES - this.frame.style.cursor = 'move'; + addUnitAlias('year', 'y'); - // 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); - }; + // PARSING - Slider.prototype.leftToIndex = function (left) { - var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10; - var x = left - 3; + addRegexToken('Y', matchSigned); + addRegexToken('YY', match1to2, match2); + addRegexToken('YYYY', match1to4, match4); + addRegexToken('YYYYY', match1to6, match6); + addRegexToken('YYYYYY', match1to6, match6); - 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; + addParseToken(['YYYY', 'YYYYY', 'YYYYYY'], YEAR); + addParseToken('YY', function (input, array) { + array[YEAR] = utils_hooks__hooks.parseTwoDigitYear(input); + }); - return index; - }; + // HELPERS - Slider.prototype.indexToLeft = function (index) { - var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10; + function daysInYear(year) { + return isLeapYear(year) ? 366 : 365; + } - var x = index / (this.values.length - 1) * width; - var left = x + 3; + function isLeapYear(year) { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + } - return left; - }; + // HOOKS - Slider.prototype._onMouseMove = function (event) { - var diff = event.clientX - this.startClientX; - var x = this.startSlideX + diff; + utils_hooks__hooks.parseTwoDigitYear = function (input) { + return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); + }; - var index = this.leftToIndex(x); + // MOMENTS - this.setIndex(index); + var getSetYear = makeGetSet('FullYear', false); - util.preventDefault(); - }; + function getIsLeapYear () { + return isLeapYear(this.year()); + } - Slider.prototype._onMouseUp = function (event) { - this.frame.style.cursor = 'auto'; + addFormatToken('w', ['ww', 2], 'wo', 'week'); + addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); - // remove event listeners - util.removeEventListener(document, 'mousemove', this.onmousemove); - util.removeEventListener(document, 'mouseup', this.onmouseup); + // ALIASES - util.preventDefault(); - }; + addUnitAlias('week', 'w'); + addUnitAlias('isoWeek', 'W'); - module.exports = Slider; + // PARSING -/***/ }, -/* 13 */ -/***/ function(module, exports, __webpack_require__) { + addRegexToken('w', match1to2); + addRegexToken('ww', match1to2, match2); + addRegexToken('W', match1to2); + addRegexToken('WW', match1to2, match2); - /** - * @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, ...) - */ - "use strict"; + addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { + week[token.substr(0, 1)] = toInt(input); + }); - function StepNumber(start, end, step, prettyStep) { - // set default values - this._start = 0; - this._end = 0; - this._step = 1; - this.prettyStep = true; - this.precision = 5; + // HELPERS - this._current = 0; - this.setRange(start, end, step, prettyStep); - }; + // firstDayOfWeek 0 = sun, 6 = sat + // the day of the week that starts the week + // (usually sunday or monday) + // firstDayOfWeekOfYear 0 = sun, 6 = sat + // the first week is the week that contains the first + // of this day of the week + // (eg. ISO weeks use thursday (4)) + function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { + var end = firstDayOfWeekOfYear - firstDayOfWeek, + daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), + adjustedMoment; - /** - * 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) { - this._start = start ? start : 0; - this._end = end ? end : 0; - this.setStep(step, prettyStep); - }; + if (daysToDayOfWeek > end) { + daysToDayOfWeek -= 7; + } - /** - * 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 (daysToDayOfWeek < end - 7) { + daysToDayOfWeek += 7; + } - if (prettyStep !== undefined) this.prettyStep = prettyStep; + adjustedMoment = local__createLocal(mom).add(daysToDayOfWeek, 'd'); + return { + week: Math.ceil(adjustedMoment.dayOfYear() / 7), + year: adjustedMoment.year() + }; + } - if (this.prettyStep === true) this._step = StepNumber.calculatePrettyStep(step);else this._step = step; - }; + // LOCALES - /** - * 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; - }; + function localeWeek (mom) { + return weekOfYear(mom, this._week.dow, this._week.doy).week; + } - // 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))); + var defaultLocaleWeek = { + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 1st is the first week of the year. + }; - // 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; + function localeFirstDayOfWeek () { + return this._week.dow; + } - // for safety - if (prettyStep <= 0) { - prettyStep = 1; - } + function localeFirstDayOfYear () { + return this._week.doy; + } - return prettyStep; - }; + // MOMENTS - /** - * returns the current value of the step - * @return {Number} current value - */ - StepNumber.prototype.getCurrent = function () { - return parseFloat(this._current.toPrecision(this.precision)); - }; + function getSetWeek (input) { + var week = this.localeData().week(this); + return input == null ? week : this.add((input - week) * 7, 'd'); + } - /** - * returns the current step size - * @return {Number} current step size - */ - StepNumber.prototype.getStep = function () { - return this._step; - }; + function getSetISOWeek (input) { + var week = weekOfYear(this, 1, 4).week; + return input == null ? week : this.add((input - week) * 7, 'd'); + } - /** - * Set the current value to the largest value smaller than start, which - * is a multiple of the step size - */ - StepNumber.prototype.start = function () { - this._current = this._start - this._start % this._step; - }; + addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); - /** - * Do a step, add the step size to the current value - */ - StepNumber.prototype.next = function () { - this._current += this._step; - }; + // ALIASES - /** - * 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; - }; + addUnitAlias('dayOfYear', 'DDD'); - module.exports = StepNumber; + // PARSING -/***/ }, -/* 14 */ -/***/ function(module, exports, __webpack_require__) { + addRegexToken('DDD', match1to3); + addRegexToken('DDDD', match3); + addParseToken(['DDD', 'DDDD'], function (input, array, config) { + config._dayOfYear = toInt(input); + }); - 'use strict'; + // HELPERS - var Emitter = __webpack_require__(43); - var Hammer = __webpack_require__(41); - var util = __webpack_require__(2); - var DataSet = __webpack_require__(4); - var DataView = __webpack_require__(5); - var Range = __webpack_require__(18); - var Core = __webpack_require__(44); - var TimeAxis = __webpack_require__(35); - var CurrentTime = __webpack_require__(26); - var CustomTime = __webpack_require__(27); - var ItemSet = __webpack_require__(32); + //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday + function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { + var d = createUTCDate(year, 0, 1).getUTCDay(); + var daysToAdd; + var dayOfYear; - var Configurator = __webpack_require__(45); - var Validator = __webpack_require__(46)['default']; - var printStyle = __webpack_require__(46).printStyle; - var allOptions = __webpack_require__(47).allOptions; - var configureOptions = __webpack_require__(47).configureOptions; + d = d === 0 ? 7 : d; + weekday = weekday != null ? weekday : firstDayOfWeek; + daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); + dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; - /** - * Create a timeline visualization - * @param {HTMLElement} container - * @param {vis.DataSet | vis.DataView | Array} [items] - * @param {vis.DataSet | vis.DataView | Array} [groups] - * @param {Object} [options] See Timeline.setOptions for the available options. - * @constructor - * @extends Core - */ - function Timeline(container, items, groups, options) { - if (!(this instanceof Timeline)) { - throw new SyntaxError('Constructor must be called with the new operator'); - } + return { + year : dayOfYear > 0 ? year : year - 1, + dayOfYear : dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear + }; + } - // if the third element is options, the forth is groups (optionally); - if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) { - var forthArgument = options; - options = groups; - groups = forthArgument; - } + // MOMENTS - var me = this; - this.defaultOptions = { - start: null, - end: null, + function getSetDayOfYear (input) { + var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; + return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); + } - autoResize: true, + // Pick the first defined of two or three arguments. + function defaults(a, b, c) { + if (a != null) { + return a; + } + if (b != null) { + return b; + } + return c; + } - orientation: { - axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both' - item: 'bottom' // not relevant - }, + function currentDateArray(config) { + var now = new Date(); + if (config._useUTC) { + return [now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()]; + } + return [now.getFullYear(), now.getMonth(), now.getDate()]; + } - width: null, - height: null, - maxHeight: null, - minHeight: null - }; - this.options = util.deepExtend({}, this.defaultOptions); + // convert an array to a date. + // the array should mirror the parameters below + // note: all values past the year are optional and will default to the lowest possible value. + // [year, month, day , hour, minute, second, millisecond] + function configFromArray (config) { + var i, date, input = [], currentDate, yearToUse; - // Create the DOM, props, and emitter - this._create(container); + if (config._d) { + return; + } - // all components listed here will be repainted automatically - this.components = []; + currentDate = currentDateArray(config); - this.body = { - dom: this.dom, - domProps: this.props, - emitter: { - on: this.on.bind(this), - off: this.off.bind(this), - emit: this.emit.bind(this) - }, - hiddenDates: [], - util: { - getScale: function getScale() { - return me.timeAxis.step.scale; - }, - getStep: function getStep() { - return me.timeAxis.step.step; - }, + //compute day of the year from weeks and weekdays + if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { + dayOfYearFromWeekInfo(config); + } - toScreen: me._toScreen.bind(me), - toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width - toTime: me._toTime.bind(me), - toGlobalTime: me._toGlobalTime.bind(me) - } - }; + //if the day of the year is set, figure out what it is + if (config._dayOfYear) { + yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); - // range - this.range = new Range(this.body); - this.components.push(this.range); - this.body.range = this.range; + if (config._dayOfYear > daysInYear(yearToUse)) { + getParsingFlags(config)._overflowDayOfYear = true; + } - // time axis - this.timeAxis = new TimeAxis(this.body); - this.timeAxis2 = null; // used in case of orientation option 'both' - this.components.push(this.timeAxis); + date = createUTCDate(yearToUse, 0, config._dayOfYear); + config._a[MONTH] = date.getUTCMonth(); + config._a[DATE] = date.getUTCDate(); + } - // current time bar - this.currentTime = new CurrentTime(this.body); - this.components.push(this.currentTime); + // Default to current date. + // * if no year, month, day of month are given, default to today + // * if day of month is given, default month and year + // * if month is given, default only year + // * if year is given, don't default anything + for (i = 0; i < 3 && config._a[i] == null; ++i) { + config._a[i] = input[i] = currentDate[i]; + } - // item set - this.itemSet = new ItemSet(this.body); - this.components.push(this.itemSet); + // Zero out whatever was not defaulted, including time + for (; i < 7; i++) { + config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; + } - this.itemsData = null; // DataSet - this.groupsData = null; // DataSet + // Check for 24:00:00.000 + if (config._a[HOUR] === 24 && + config._a[MINUTE] === 0 && + config._a[SECOND] === 0 && + config._a[MILLISECOND] === 0) { + config._nextDay = true; + config._a[HOUR] = 0; + } - this.on('tap', function (event) { - me.emit('click', me.getEventProperties(event)); - }); - this.on('doubletap', function (event) { - me.emit('doubleClick', me.getEventProperties(event)); - }); - this.dom.root.oncontextmenu = function (event) { - me.emit('contextmenu', me.getEventProperties(event)); - }; + config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); + // Apply timezone offset from input. The actual utcOffset can be changed + // with parseZone. + if (config._tzm != null) { + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + } - // setup configuration system - this.configurator = new Configurator(this, container, configureOptions); + if (config._nextDay) { + config._a[HOUR] = 24; + } + } - // apply options - if (options) { - this.setOptions(options); - } + function dayOfYearFromWeekInfo(config) { + var w, weekYear, week, weekday, dow, doy, temp; - // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! - if (groups) { - this.setGroups(groups); - } + w = config._w; + if (w.GG != null || w.W != null || w.E != null) { + dow = 1; + doy = 4; - // create itemset - if (items) { - this.setItems(items); - } else { - this._redraw(); - } - } + // TODO: We need to take the current isoWeekYear, but that depends on + // how we interpret now (local, utc, fixed offset). So create + // a now version of current config (take local/utc/offset flags, and + // create now). + weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(local__createLocal(), 1, 4).year); + week = defaults(w.W, 1); + weekday = defaults(w.E, 1); + } else { + dow = config._locale._week.dow; + doy = config._locale._week.doy; - // Extend the functionality from Core - Timeline.prototype = new Core(); + weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(local__createLocal(), dow, doy).year); + week = defaults(w.w, 1); - /** - * Force a redraw. The size of all items will be recalculated. - * Can be useful to manually redraw when option autoResize=false and the window - * has been resized, or when the items CSS has been changed. - */ - Timeline.prototype.redraw = function () { - this.itemSet && this.itemSet.markDirty({ refreshItems: true }); - this._redraw(); - }; + if (w.d != null) { + // weekday -- low day numbers are considered next week + weekday = w.d; + if (weekday < dow) { + ++week; + } + } else if (w.e != null) { + // local weekday -- counting starts from begining of week + weekday = w.e + dow; + } else { + // default to begining of week + weekday = dow; + } + } + temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); - Timeline.prototype.setOptions = function (options) { - // validate options - var errorFound = Validator.validate(options, allOptions); - if (errorFound === true) { - console.log('%cErrors have been found in the supplied options object.', printStyle); - } + config._a[YEAR] = temp.year; + config._dayOfYear = temp.dayOfYear; + } - Core.prototype.setOptions.call(this, options); + utils_hooks__hooks.ISO_8601 = function () {}; - if ('type' in options) { - if (options.type !== this.options.type) { - this.options.type = options.type; + // date from string and format string + function configFromStringAndFormat(config) { + // TODO: Move this to another part of the creation flow to prevent circular deps + if (config._f === utils_hooks__hooks.ISO_8601) { + configFromISO(config); + return; + } - // force recreation of all items - var itemsData = this.itemsData; - if (itemsData) { - var selection = this.getSelection(); - this.setItems(null); // remove all - this.setItems(itemsData); // add all - this.setSelection(selection); // restore selection - } - } - } - }; + config._a = []; + getParsingFlags(config).empty = true; - /** - * Set items - * @param {vis.DataSet | Array | null} items - */ - Timeline.prototype.setItems = function (items) { - var initialLoad = this.itemsData == null; + // This array is used to make a Date, either with `new Date` or `Date.UTC` + var string = '' + config._i, + i, parsedInput, tokens, token, skipped, + stringLength = string.length, + totalParsedInputLength = 0; - // convert to type DataSet when needed - var newDataSet; - if (!items) { - newDataSet = null; - } else if (items instanceof DataSet || items instanceof DataView) { - newDataSet = items; - } else { - // turn an array into a dataset - newDataSet = new DataSet(items, { - type: { - start: 'Date', - end: 'Date' - } - }); - } + tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; - // set items - this.itemsData = newDataSet; - this.itemSet && this.itemSet.setItems(newDataSet); + for (i = 0; i < tokens.length; i++) { + token = tokens[i]; + parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; + if (parsedInput) { + skipped = string.substr(0, string.indexOf(parsedInput)); + if (skipped.length > 0) { + getParsingFlags(config).unusedInput.push(skipped); + } + string = string.slice(string.indexOf(parsedInput) + parsedInput.length); + totalParsedInputLength += parsedInput.length; + } + // don't parse if it's not a known token + if (formatTokenFunctions[token]) { + if (parsedInput) { + getParsingFlags(config).empty = false; + } + else { + getParsingFlags(config).unusedTokens.push(token); + } + addTimeToArrayFromToken(token, parsedInput, config); + } + else if (config._strict && !parsedInput) { + getParsingFlags(config).unusedTokens.push(token); + } + } - if (initialLoad) { - if (this.options.start != undefined || this.options.end != undefined) { - if (this.options.start == undefined || this.options.end == undefined) { - var dataRange = this._getDataRange(); - } + // add remaining unparsed input length to the string + getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; + if (string.length > 0) { + getParsingFlags(config).unusedInput.push(string); + } - var start = this.options.start != undefined ? this.options.start : dataRange.start; - var end = this.options.end != undefined ? this.options.end : dataRange.end; + // clear _12h flag if hour is <= 12 + if (getParsingFlags(config).bigHour === true && + config._a[HOUR] <= 12 && + config._a[HOUR] > 0) { + getParsingFlags(config).bigHour = undefined; + } + // handle meridiem + config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); - this.setWindow(start, end, { animation: false }); - } else { - this.fit({ animation: false }); + configFromArray(config); + checkOverflow(config); } - } - }; - - /** - * Set groups - * @param {vis.DataSet | Array} groups - */ - Timeline.prototype.setGroups = function (groups) { - // convert to type DataSet when needed - var newDataSet; - if (!groups) { - newDataSet = null; - } else if (groups instanceof DataSet || groups instanceof DataView) { - newDataSet = groups; - } else { - // turn an array into a dataset - newDataSet = new DataSet(groups); - } - this.groupsData = newDataSet; - this.itemSet.setGroups(newDataSet); - }; - /** - * Set both items and groups in one go - * @param {{items: Array | vis.DataSet, groups: Array | vis.DataSet}} data - */ - Timeline.prototype.setData = function (data) { - if (data && data.groups) { - this.setGroups(data.groups); - } + function meridiemFixWrap (locale, hour, meridiem) { + var isPm; - if (data && data.items) { - this.setItems(data.items); - } - }; + if (meridiem == null) { + // nothing to do + return hour; + } + if (locale.meridiemHour != null) { + return locale.meridiemHour(hour, meridiem); + } else if (locale.isPM != null) { + // Fallback + isPm = locale.isPM(meridiem); + if (isPm && hour < 12) { + hour += 12; + } + if (!isPm && hour === 12) { + hour = 0; + } + return hour; + } else { + // this is not supposed to happen + return hour; + } + } - /** - * 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. If ids is an empty array, all items will be - * unselected. - * @param {Object} [options] Available options: - * `focus: boolean` - * If true, focus will be set to the selected item(s) - * `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'. - * Only applicable when option focus is true. - */ - Timeline.prototype.setSelection = function (ids, options) { - this.itemSet && this.itemSet.setSelection(ids); + function configFromStringAndArray(config) { + var tempConfig, + bestMoment, - if (options && options.focus) { - this.focus(ids, options); - } - }; + scoreToBeat, + i, + currentScore; - /** - * Get the selected items by their id - * @return {Array} ids The ids of the selected items - */ - Timeline.prototype.getSelection = function () { - return this.itemSet && this.itemSet.getSelection() || []; - }; - - /** - * Adjust the visible window such that the selected item (or multiple items) - * are centered on screen. - * @param {String | String[]} id An item id or array with item ids - * @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'. - */ - Timeline.prototype.focus = function (id, options) { - if (!this.itemsData || id == undefined) return; + if (config._f.length === 0) { + getParsingFlags(config).invalidFormat = true; + config._d = new Date(NaN); + return; + } - var ids = Array.isArray(id) ? id : [id]; + for (i = 0; i < config._f.length; i++) { + currentScore = 0; + tempConfig = copyConfig({}, config); + if (config._useUTC != null) { + tempConfig._useUTC = config._useUTC; + } + tempConfig._f = config._f[i]; + configFromStringAndFormat(tempConfig); - // get the specified item(s) - var itemsData = this.itemsData.getDataSet().get(ids, { - type: { - start: 'Date', - end: 'Date' - } - }); + if (!valid__isValid(tempConfig)) { + continue; + } - // calculate minimum start and maximum end of specified items - var start = null; - var end = null; - itemsData.forEach(function (itemData) { - var s = itemData.start.valueOf(); - var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf(); + // if there is any input that was not parsed add a penalty for that format + currentScore += getParsingFlags(tempConfig).charsLeftOver; - if (start === null || s < start) { - start = s; - } + //or tokens + currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; - if (end === null || e > end) { - end = e; - } - }); + getParsingFlags(tempConfig).score = currentScore; - if (start !== null && end !== null) { - // calculate the new middle and interval for the window - var middle = (start + end) / 2; - var interval = Math.max(this.range.end - this.range.start, (end - start) * 1.1); + if (scoreToBeat == null || currentScore < scoreToBeat) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + } + } - var animation = options && options.animation !== undefined ? options.animation : true; - this.range.setRange(middle - interval / 2, middle + interval / 2, animation); - } - }; + extend(config, bestMoment || tempConfig); + } - /** - * Get the data range of the item set. - * @returns {{min: Date, max: Date}} range A range with a start and end Date. - * When no minimum is found, min==null - * When no maximum is found, max==null - */ - Timeline.prototype.getItemRange = function () { - // calculate min from start filed - var dataset = this.itemsData && this.itemsData.getDataSet(); - var min = null; - var max = null; + function configFromObject(config) { + if (config._d) { + return; + } - if (dataset) { - // calculate the minimum value of the field 'start' - var minItem = dataset.min('start'); - min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null; - // Note: we convert first to Date and then to number because else - // a conversion from ISODate to Number will fail + var i = normalizeObjectUnits(config._i); + config._a = [i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond]; - // calculate maximum value of fields 'start' and 'end' - var maxStartItem = dataset.max('start'); - if (maxStartItem) { - max = util.convert(maxStartItem.start, 'Date').valueOf(); - } - var maxEndItem = dataset.max('end'); - if (maxEndItem) { - if (max == null) { - max = util.convert(maxEndItem.end, 'Date').valueOf(); - } else { - max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf()); - } + configFromArray(config); } - } - - return { - min: min != null ? new Date(min) : null, - max: max != null ? new Date(max) : null - }; - }; - - /** - * Generate Timeline related information from an event - * @param {Event} event - * @return {Object} An object with related information, like on which area - * The event happened, whether clicked on an item, etc. - */ - Timeline.prototype.getEventProperties = function (event) { - var clientX = event.center ? event.center.x : event.clientX; - var clientY = event.center ? event.center.y : event.clientY; - var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer); - var y = clientY - util.getAbsoluteTop(this.dom.centerContainer); - var item = this.itemSet.itemFromTarget(event); - var group = this.itemSet.groupFromTarget(event); - var customTime = CustomTime.customTimeFromTarget(event); + function createFromConfig (config) { + var input = config._i, + format = config._f, + res; - var snap = this.itemSet.options.snap || null; - var scale = this.body.util.getScale(); - var step = this.body.util.getStep(); - var time = this._toTime(x); - var snappedTime = snap ? snap(time, scale, step) : time; + config._locale = config._locale || locale_locales__getLocale(config._l); - var element = util.getTarget(event); - var what = null; - if (item != null) { - what = 'item'; - } else if (customTime != null) { - what = 'custom-time'; - } else if (util.hasParent(element, this.timeAxis.dom.foreground)) { - what = 'axis'; - } else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) { - what = 'axis'; - } else if (util.hasParent(element, this.itemSet.dom.labelSet)) { - what = 'group-label'; - } else if (util.hasParent(element, this.currentTime.bar)) { - what = 'current-time'; - } else if (util.hasParent(element, this.dom.center)) { - what = 'background'; - } + if (input === null || (format === undefined && input === '')) { + return valid__createInvalid({nullInput: true}); + } - return { - event: event, - item: item ? item.id : null, - group: group ? group.groupId : null, - what: what, - pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX, - pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY, - x: x, - y: y, - time: time, - snappedTime: snappedTime - }; - }; + if (typeof input === 'string') { + config._i = input = config._locale.preparse(input); + } - module.exports = Timeline; + if (isMoment(input)) { + return new Moment(checkOverflow(input)); + } else if (isArray(format)) { + configFromStringAndArray(config); + } else if (format) { + configFromStringAndFormat(config); + } else if (isDate(input)) { + config._d = input; + } else { + configFromInput(config); + } -/***/ }, -/* 15 */ -/***/ function(module, exports, __webpack_require__) { + res = new Moment(checkOverflow(config)); + if (res._nextDay) { + // Adding is smart enough around DST + res.add(1, 'd'); + res._nextDay = undefined; + } - 'use strict'; + return res; + } - var Emitter = __webpack_require__(43); - var Hammer = __webpack_require__(41); - var util = __webpack_require__(2); - var DataSet = __webpack_require__(4); - var DataView = __webpack_require__(5); - var Range = __webpack_require__(18); - var Core = __webpack_require__(44); - var TimeAxis = __webpack_require__(35); - var CurrentTime = __webpack_require__(26); - var CustomTime = __webpack_require__(27); - var LineGraph = __webpack_require__(34); + function configFromInput(config) { + var input = config._i; + if (input === undefined) { + config._d = new Date(); + } else if (isDate(input)) { + config._d = new Date(+input); + } else if (typeof input === 'string') { + configFromString(config); + } else if (isArray(input)) { + config._a = map(input.slice(0), function (obj) { + return parseInt(obj, 10); + }); + configFromArray(config); + } else if (typeof(input) === 'object') { + configFromObject(config); + } else if (typeof(input) === 'number') { + // from milliseconds + config._d = new Date(input); + } else { + utils_hooks__hooks.createFromInputFallback(config); + } + } - var Configurator = __webpack_require__(45); - var Validator = __webpack_require__(46)['default']; - var printStyle = __webpack_require__(46).printStyle; - var allOptions = __webpack_require__(48).allOptions; - var configureOptions = __webpack_require__(48).configureOptions; + function createLocalOrUTC (input, format, locale, strict, isUTC) { + var c = {}; - /** - * Create a timeline visualization - * @param {HTMLElement} container - * @param {vis.DataSet | Array} [items] - * @param {Object} [options] See Graph2d.setOptions for the available options. - * @constructor - * @extends Core - */ - function Graph2d(container, items, groups, options) { - // if the third element is options, the forth is groups (optionally); - if (!(Array.isArray(groups) || groups instanceof DataSet) && groups instanceof Object) { - var forthArgument = options; - options = groups; - groups = forthArgument; - } + if (typeof(locale) === 'boolean') { + strict = locale; + locale = undefined; + } + // object construction must be done this way. + // https://github.com/moment/moment/issues/1423 + c._isAMomentObject = true; + c._useUTC = c._isUTC = isUTC; + c._l = locale; + c._i = input; + c._f = format; + c._strict = strict; - var me = this; - this.defaultOptions = { - start: null, - end: null, + return createFromConfig(c); + } - autoResize: true, + function local__createLocal (input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, false); + } - orientation: { - axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both' - item: 'bottom' // not relevant for Graph2d - }, + var prototypeMin = deprecate( + 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548', + function () { + var other = local__createLocal.apply(null, arguments); + return other < this ? this : other; + } + ); - width: null, - height: null, - maxHeight: null, - minHeight: null - }; - this.options = util.deepExtend({}, this.defaultOptions); + var prototypeMax = deprecate( + 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548', + function () { + var other = local__createLocal.apply(null, arguments); + return other > this ? this : other; + } + ); - // Create the DOM, props, and emitter - this._create(container); + // Pick a moment m from moments so that m[fn](other) is true for all + // other. This relies on the function fn to be transitive. + // + // moments should either be an array of moment objects or an array, whose + // first element is an array of moment objects. + function pickBy(fn, moments) { + var res, i; + if (moments.length === 1 && isArray(moments[0])) { + moments = moments[0]; + } + if (!moments.length) { + return local__createLocal(); + } + res = moments[0]; + for (i = 1; i < moments.length; ++i) { + if (moments[i][fn](res)) { + res = moments[i]; + } + } + return res; + } - // all components listed here will be repainted automatically - this.components = []; + // TODO: Use [].sort instead? + function min () { + var args = [].slice.call(arguments, 0); - this.body = { - dom: this.dom, - domProps: this.props, - emitter: { - on: this.on.bind(this), - off: this.off.bind(this), - emit: this.emit.bind(this) - }, - hiddenDates: [], - util: { - toScreen: me._toScreen.bind(me), - toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width - toTime: me._toTime.bind(me), - toGlobalTime: me._toGlobalTime.bind(me) + return pickBy('isBefore', args); } - }; - // range - this.range = new Range(this.body); - this.components.push(this.range); - this.body.range = this.range; + function max () { + var args = [].slice.call(arguments, 0); - // time axis - this.timeAxis = new TimeAxis(this.body); - this.components.push(this.timeAxis); - //this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); + return pickBy('isAfter', args); + } - // current time bar - this.currentTime = new CurrentTime(this.body); - this.components.push(this.currentTime); + function Duration (duration) { + var normalizedInput = normalizeObjectUnits(duration), + years = normalizedInput.year || 0, + quarters = normalizedInput.quarter || 0, + months = normalizedInput.month || 0, + weeks = normalizedInput.week || 0, + days = normalizedInput.day || 0, + hours = normalizedInput.hour || 0, + minutes = normalizedInput.minute || 0, + seconds = normalizedInput.second || 0, + milliseconds = normalizedInput.millisecond || 0; - // item set - this.linegraph = new LineGraph(this.body); - this.components.push(this.linegraph); + // representation for dateAddRemove + this._milliseconds = +milliseconds + + seconds * 1e3 + // 1000 + minutes * 6e4 + // 1000 * 60 + hours * 36e5; // 1000 * 60 * 60 + // Because of dateAddRemove treats 24 hours as different from a + // day when working around DST, we need to store them separately + this._days = +days + + weeks * 7; + // It is impossible translate months into days without knowing + // which months you are are talking about, so we have to store + // it separately. + this._months = +months + + quarters * 3 + + years * 12; - this.itemsData = null; // DataSet - this.groupsData = null; // DataSet + this._data = {}; - this.on('tap', function (event) { - me.emit('click', me.getEventProperties(event)); - }); - this.on('doubletap', function (event) { - me.emit('doubleClick', me.getEventProperties(event)); - }); - this.dom.root.oncontextmenu = function (event) { - me.emit('contextmenu', me.getEventProperties(event)); - }; + this._locale = locale_locales__getLocale(); - // setup configuration system - this.configurator = new Configurator(this, container, configureOptions); + this._bubble(); + } - // apply options - if (options) { - this.setOptions(options); - } + function isDuration (obj) { + return obj instanceof Duration; + } - // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! - if (groups) { - this.setGroups(groups); - } + function offset (token, separator) { + addFormatToken(token, 0, 0, function () { + var offset = this.utcOffset(); + var sign = '+'; + if (offset < 0) { + offset = -offset; + sign = '-'; + } + return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); + }); + } - // create itemset - if (items) { - this.setItems(items); - } else { - this._redraw(); - } - } + offset('Z', ':'); + offset('ZZ', ''); - // Extend the functionality from Core - Graph2d.prototype = new Core(); + // PARSING - Graph2d.prototype.setOptions = function (options) { - // validate options - var errorFound = Validator.validate(options, allOptions); - if (errorFound === true) { - console.log('%cErrors have been found in the supplied options object.', printStyle); - } + addRegexToken('Z', matchOffset); + addRegexToken('ZZ', matchOffset); + addParseToken(['Z', 'ZZ'], function (input, array, config) { + config._useUTC = true; + config._tzm = offsetFromString(input); + }); - Core.prototype.setOptions.call(this, options); - }; + // HELPERS - /** - * Set items - * @param {vis.DataSet | Array | null} items - */ - Graph2d.prototype.setItems = function (items) { - var initialLoad = this.itemsData == null; + // timezone chunker + // '+10:00' > ['10', '00'] + // '-1530' > ['-15', '30'] + var chunkOffset = /([\+\-]|\d\d)/gi; - // convert to type DataSet when needed - var newDataSet; - if (!items) { - newDataSet = null; - } else if (items instanceof DataSet || items instanceof DataView) { - newDataSet = items; - } else { - // turn an array into a dataset - newDataSet = new DataSet(items, { - type: { - start: 'Date', - end: 'Date' - } - }); - } + function offsetFromString(string) { + var matches = ((string || '').match(matchOffset) || []); + var chunk = matches[matches.length - 1] || []; + var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; + var minutes = +(parts[1] * 60) + toInt(parts[2]); - // set items - this.itemsData = newDataSet; - this.linegraph && this.linegraph.setItems(newDataSet); + return parts[0] === '+' ? minutes : -minutes; + } - if (initialLoad) { - if (this.options.start != undefined || this.options.end != undefined) { - var start = this.options.start != undefined ? this.options.start : null; - var end = this.options.end != undefined ? this.options.end : null; + // Return a moment from input, that is local/utc/zone equivalent to model. + function cloneWithOffset(input, model) { + var res, diff; + if (model._isUTC) { + res = model.clone(); + diff = (isMoment(input) || isDate(input) ? +input : +local__createLocal(input)) - (+res); + // Use low-level api, because this fn is low-level api. + res._d.setTime(+res._d + diff); + utils_hooks__hooks.updateOffset(res, false); + return res; + } else { + return local__createLocal(input).local(); + } + return model._isUTC ? local__createLocal(input).zone(model._offset || 0) : local__createLocal(input).local(); + } - this.setWindow(start, end, { animation: false }); - } else { - this.fit({ animation: false }); + function getDateOffset (m) { + // On Firefox.24 Date#getTimezoneOffset returns a floating point. + // https://github.com/moment/moment/pull/1871 + return -Math.round(m._d.getTimezoneOffset() / 15) * 15; } - } - }; - /** - * Set groups - * @param {vis.DataSet | Array} groups - */ - Graph2d.prototype.setGroups = function (groups) { - // convert to type DataSet when needed - var newDataSet; - if (!groups) { - newDataSet = null; - } else if (groups instanceof DataSet || groups instanceof DataView) { - newDataSet = groups; - } else { - // turn an array into a dataset - newDataSet = new DataSet(groups); - } - - this.groupsData = newDataSet; - this.linegraph.setGroups(newDataSet); - }; - - /** - * Returns an object containing an SVG element with the icon of the group (size determined by iconWidth and iconHeight), the label of the group (content) and the yAxisOrientation of the group (left or right). - * @param groupId - * @param width - * @param height - */ - Graph2d.prototype.getLegend = function (groupId, width, height) { - if (width === undefined) { - width = 15; - } - if (height === undefined) { - height = 15; - } - if (this.linegraph.groups[groupId] !== undefined) { - return this.linegraph.groups[groupId].getLegend(width, height); - } else { - return 'cannot find group:' + groupId; - } - }; + // HOOKS - /** - * This checks if the visible option of the supplied group (by ID) is true or false. - * @param groupId - * @returns {*} - */ - Graph2d.prototype.isGroupVisible = function (groupId) { - if (this.linegraph.groups[groupId] !== undefined) { - return this.linegraph.groups[groupId].visible && (this.linegraph.options.groups.visibility[groupId] === undefined || this.linegraph.options.groups.visibility[groupId] == true); - } else { - return false; - } - }; + // This function will be called whenever a moment is mutated. + // It is intended to keep the offset in sync with the timezone. + utils_hooks__hooks.updateOffset = function () {}; - /** - * Get the data range of the item set. - * @returns {{min: Date, max: Date}} range A range with a start and end Date. - * When no minimum is found, min==null - * When no maximum is found, max==null - */ - Graph2d.prototype.getItemRange = function () { - var min = null; - var max = null; + // MOMENTS - // calculate min from start filed - for (var groupId in this.linegraph.groups) { - if (this.linegraph.groups.hasOwnProperty(groupId)) { - if (this.linegraph.groups[groupId].visible == true) { - for (var i = 0; i < this.linegraph.groups[groupId].itemsData.length; i++) { - var item = this.linegraph.groups[groupId].itemsData[i]; - var value = util.convert(item.x, 'Date').valueOf(); - min = min == null ? value : min > value ? value : min; - max = max == null ? value : max < value ? value : max; + // keepLocalTime = true means only change the timezone, without + // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> + // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset + // +0200, so we adjust the time as needed, to be valid. + // + // Keeping the time actually adds/subtracts (one hour) + // from the actual represented time. That is why we call updateOffset + // a second time. In case it wants us to change the offset again + // _changeInProgress == true case, then we have to adjust, because + // there is no such time in the given timezone. + function getSetOffset (input, keepLocalTime) { + var offset = this._offset || 0, + localAdjust; + if (input != null) { + if (typeof input === 'string') { + input = offsetFromString(input); + } + if (Math.abs(input) < 16) { + input = input * 60; + } + if (!this._isUTC && keepLocalTime) { + localAdjust = getDateOffset(this); + } + this._offset = input; + this._isUTC = true; + if (localAdjust != null) { + this.add(localAdjust, 'm'); + } + if (offset !== input) { + if (!keepLocalTime || this._changeInProgress) { + add_subtract__addSubtract(this, create__createDuration(input - offset, 'm'), 1, false); + } else if (!this._changeInProgress) { + this._changeInProgress = true; + utils_hooks__hooks.updateOffset(this, true); + this._changeInProgress = null; + } + } + return this; + } else { + return this._isUTC ? offset : getDateOffset(this); } - } } - } - return { - min: min != null ? new Date(min) : null, - max: max != null ? new Date(max) : null - }; - }; + function getSetZone (input, keepLocalTime) { + if (input != null) { + if (typeof input !== 'string') { + input = -input; + } - /** - * Generate Timeline related information from an event - * @param {Event} event - * @return {Object} An object with related information, like on which area - * The event happened, whether clicked on an item, etc. - */ - Graph2d.prototype.getEventProperties = function (event) { - var clientX = event.center ? event.center.x : event.clientX; - var clientY = event.center ? event.center.y : event.clientY; - var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer); - var y = clientY - util.getAbsoluteTop(this.dom.centerContainer); - var time = this._toTime(x); + this.utcOffset(input, keepLocalTime); - var customTime = CustomTime.customTimeFromTarget(event); + return this; + } else { + return -this.utcOffset(); + } + } - var element = util.getTarget(event); - var what = null; - if (util.hasParent(element, this.timeAxis.dom.foreground)) { - what = 'axis'; - } else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) { - what = 'axis'; - } else if (util.hasParent(element, this.linegraph.yAxisLeft.dom.frame)) { - what = 'data-axis'; - } else if (util.hasParent(element, this.linegraph.yAxisRight.dom.frame)) { - what = 'data-axis'; - } else if (util.hasParent(element, this.linegraph.legendLeft.dom.frame)) { - what = 'legend'; - } else if (util.hasParent(element, this.linegraph.legendRight.dom.frame)) { - what = 'legend'; - } else if (customTime != null) { - what = 'custom-time'; - } else if (util.hasParent(element, this.currentTime.bar)) { - what = 'current-time'; - } else if (util.hasParent(element, this.dom.center)) { - what = 'background'; - } + function setOffsetToUTC (keepLocalTime) { + return this.utcOffset(0, keepLocalTime); + } - var value = []; - var yAxisLeft = this.linegraph.yAxisLeft; - var yAxisRight = this.linegraph.yAxisRight; - if (!yAxisLeft.hidden) { - value.push(yAxisLeft.screenToValue(y)); - } - if (!yAxisRight.hidden) { - value.push(yAxisRight.screenToValue(y)); - } + function setOffsetToLocal (keepLocalTime) { + if (this._isUTC) { + this.utcOffset(0, keepLocalTime); + this._isUTC = false; - return { - event: event, - what: what, - pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX, - pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY, - x: x, - y: y, - time: time, - value: value - }; - }; + if (keepLocalTime) { + this.subtract(getDateOffset(this), 'm'); + } + } + return this; + } - module.exports = Graph2d; + function setOffsetToParsedOffset () { + if (this._tzm) { + this.utcOffset(this._tzm); + } else if (typeof this._i === 'string') { + this.utcOffset(offsetFromString(this._i)); + } + return this; + } -/***/ }, -/* 16 */ -/***/ function(module, exports, __webpack_require__) { + function hasAlignedHourOffset (input) { + if (!input) { + input = 0; + } + else { + input = local__createLocal(input).utcOffset(); + } - "use strict"; + return (this.utcOffset() - input) % 60 === 0; + } - var moment = __webpack_require__(40); + function isDaylightSavingTime () { + return ( + this.utcOffset() > this.clone().month(0).utcOffset() || + this.utcOffset() > this.clone().month(5).utcOffset() + ); + } - /** - * used in Core to convert the options into a volatile variable - * - * @param Core - */ - exports.convertHiddenOptions = function (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); + function isDaylightSavingTimeShifted () { + if (this._a) { + var other = this._isUTC ? create_utc__createUTC(this._a) : local__createLocal(this._a); + return this.isValid() && compareArrays(this._a, other.toArray()) > 0; } - } - body.hiddenDates.sort(function (a, b) { - return a.start - b.start; - }); // sort by start time - } - } - }; - /** - * create new entrees for the repeating hidden dates - * @param body - * @param hiddenDates - */ - exports.updateHiddenDates = function (body, hiddenDates) { - if (hiddenDates && body.domProps.centerContainer.width !== undefined) { - exports.convertHiddenOptions(body, hiddenDates); + return false; + } - var start = moment(body.range.start); - var end = moment(body.range.end); + function isLocal () { + return !this._isUTC; + } - var totalRange = body.range.end - body.range.start; - var pixelTime = totalRange / body.domProps.centerContainer.width; + function isUtcOffset () { + return this._isUTC; + } - 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); + function isUtc () { + return this._isUTC && this._offset === 0; + } - 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 aspNetRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/; - var duration = endDate - startDate; - if (duration >= 4 * pixelTime) { + // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html + // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere + var create__isoRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/; - 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"); + function create__createDuration (input, key) { + var duration = input, + // matching against regexp is expensive, do it on demand + match = null, + sign, + ret, + diffRes; - endDate.dayOfYear(start.dayOfYear()); - endDate.year(start.year()); - endDate.subtract(7 - offset, "days"); + if (isDuration(input)) { + duration = { + ms : input._milliseconds, + d : input._days, + M : input._months + }; + } else if (typeof input === 'number') { + duration = {}; + if (key) { + duration[key] = input; + } else { + duration.milliseconds = input; + } + } else if (!!(match = aspNetRegex.exec(input))) { + sign = (match[1] === '-') ? -1 : 1; + duration = { + y : 0, + d : toInt(match[DATE]) * sign, + h : toInt(match[HOUR]) * sign, + m : toInt(match[MINUTE]) * sign, + s : toInt(match[SECOND]) * sign, + ms : toInt(match[MILLISECOND]) * sign + }; + } else if (!!(match = create__isoRegex.exec(input))) { + sign = (match[1] === '-') ? -1 : 1; + duration = { + y : parseIso(match[2], sign), + M : parseIso(match[3], sign), + d : parseIso(match[4], sign), + h : parseIso(match[5], sign), + m : parseIso(match[6], sign), + s : parseIso(match[7], sign), + w : parseIso(match[8], sign) + }; + } else if (duration == null) {// checks for null or undefined + duration = {}; + } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { + diffRes = momentsDifference(local__createLocal(duration.from), local__createLocal(duration.to)); - runUntil.add(1, "weeks"); - break; - case "weekly": - var dayOffset = endDate.diff(startDate, "days"); - var day = startDate.day(); + duration = {}; + duration.ms = diffRes.milliseconds; + duration.M = diffRes.months; + } - // set the start date to the range.start - startDate.date(start.date()); - startDate.month(start.month()); - startDate.year(start.year()); - endDate = startDate.clone(); + ret = new Duration(duration); - // force - startDate.day(day); - endDate.day(day); - endDate.add(dayOffset, "days"); + if (isDuration(input) && hasOwnProp(input, '_locale')) { + ret._locale = input._locale; + } - startDate.subtract(1, "weeks"); - endDate.subtract(1, "weeks"); + return ret; + } - 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"); + create__createDuration.fn = Duration.prototype; - endDate.month(start.month()); - endDate.year(start.year()); - endDate.subtract(1, "months"); - endDate.add(offset, "months"); + function parseIso (inp, sign) { + // We'd normally use ~~inp for this, but unfortunately it also + // converts floats to ints. + // inp may be undefined, so careful calling replace on it. + var res = inp && parseFloat(inp.replace(',', '.')); + // apply sign while we're at it + return (isNaN(res) ? 0 : res) * sign; + } - 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"); + function positiveMomentsDifference(base, other) { + var res = {milliseconds: 0, months: 0}; - 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() }); + res.months = other.month() - base.month() + + (other.year() - base.year()) * 12; + if (base.clone().add(res.months, 'M').isAfter(other)) { + --res.months; } - } - } - // 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); + + res.milliseconds = +other - +(base.clone().add(res.months, 'M')); + + return res; } - } - }; - /** - * remove duplicates from the hidden dates list. Duplicates are evil. They mess everything up. - * Scales with N^2 - * @param 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; + function momentsDifference(base, other) { + var res; + other = cloneWithOffset(other, base); + if (base.isBefore(other)) { + res = positiveMomentsDifference(base, other); + } else { + res = positiveMomentsDifference(other, base); + res.milliseconds = -res.milliseconds; + res.months = -res.months; } - } - } - } - for (var i = 0; i < hiddenDates.length; i++) { - if (hiddenDates[i].remove !== true) { - safeDates.push(hiddenDates[i]); + return res; } - } - 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); - } - }; + function createAdder(direction, name) { + return function (val, period) { + var dur, tmp; + //invert the arguments, but complain about it + if (period !== null && !isNaN(+period)) { + deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).'); + tmp = val; val = period; period = tmp; + } - /** - * Used in TimeStep to avoid the hidden times. - * @param timeStep - * @param previousTime - */ - exports.stepOverHiddenDates = function (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; + val = typeof val === 'string' ? +val : val; + dur = create__createDuration(val, period); + add_subtract__addSubtract(this, dur, direction); + return this; + }; } - } - 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; + function add_subtract__addSubtract (mom, duration, isAdding, updateOffset) { + var milliseconds = duration._milliseconds, + days = duration._days, + months = duration._months; + updateOffset = updateOffset == null ? true : updateOffset; + + if (milliseconds) { + mom._d.setTime(+mom._d + milliseconds * isAdding); + } + if (days) { + get_set__set(mom, 'Date', get_set__get(mom, 'Date') + days * isAdding); + } + if (months) { + setMonth(mom, get_set__get(mom, 'Month') + months * isAdding); + } + if (updateOffset) { + utils_hooks__hooks.updateOffset(mom, days || months); + } } - timeStep.current = newValue.toDate(); - } - }; + var add_subtract__add = createAdder(1, 'add'); + var add_subtract__subtract = createAdder(-1, 'subtract'); - ///** - // * 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(); - // } - //}; + function moment_calendar__calendar (time) { + // We want to compare the start of today, vs this. + // Getting start-of-today depends on whether we're local/utc/offset or not. + var now = time || local__createLocal(), + sod = cloneWithOffset(now, this).startOf('day'), + diff = this.diff(sod, 'days', true), + format = diff < -6 ? 'sameElse' : + diff < -1 ? 'lastWeek' : + diff < 0 ? 'lastDay' : + diff < 1 ? 'sameDay' : + diff < 2 ? 'nextDay' : + diff < 7 ? 'nextWeek' : 'sameElse'; + return this.format(this.localeData().calendar(format, this, local__createLocal(now))); + } - /** - * replaces the Core toScreen methods - * @param Core - * @param time - * @param width - * @returns {number} - */ - exports.toScreen = function (Core, time, width) { - if (Core.body.hiddenDates.length == 0) { - var 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; + function clone () { + return new Moment(this); } - var duration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end); - time = exports.correctTimeForHidden(Core.body.hiddenDates, Core.range, time); + function isAfter (input, units) { + var inputMs; + units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); + if (units === 'millisecond') { + input = isMoment(input) ? input : local__createLocal(input); + return +this > +input; + } else { + inputMs = isMoment(input) ? +input : +local__createLocal(input); + return inputMs < +this.clone().startOf(units); + } + } - var conversion = Core.range.conversion(width, duration); - return (time.valueOf() - conversion.offset) * conversion.scale; - } - }; + function isBefore (input, units) { + var inputMs; + units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); + if (units === 'millisecond') { + input = isMoment(input) ? input : local__createLocal(input); + return +this < +input; + } else { + inputMs = isMoment(input) ? +input : +local__createLocal(input); + return +this.clone().endOf(units) < inputMs; + } + } - /** - * Replaces the core toTime methods - * @param body - * @param range - * @param x - * @param 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); + function isBetween (from, to, units) { + return this.isAfter(from, units) && this.isBefore(to, units); + } - var newTime = new Date(accumulatedHiddenDuration + partialDuration + Core.range.start); - return newTime; - } - }; + function isSame (input, units) { + var inputMs; + units = normalizeUnits(units || 'millisecond'); + if (units === 'millisecond') { + input = isMoment(input) ? input : local__createLocal(input); + return +this === +input; + } else { + inputMs = +local__createLocal(input); + return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units)); + } + } - /** - * Support function - * - * @param hiddenDates - * @param range - * @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; + function absFloor (number) { + if (number < 0) { + return Math.ceil(number); + } else { + return Math.floor(number); + } } - } - return duration; - }; - /** - * Support function - * @param hiddenDates - * @param range - * @param time - * @returns {{duration: number, time: *, offset: number}} - */ - exports.correctTimeForHidden = function (hiddenDates, range, time) { - time = moment(time).toDate().valueOf(); - time -= exports.getHiddenDurationBefore(hiddenDates, range, time); - return time; - }; + function diff (input, units, asFloat) { + var that = cloneWithOffset(input, this), + zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4, + delta, output; - exports.getHiddenDurationBefore = function (hiddenDates, range, time) { - var timeOffset = 0; - time = moment(time).toDate().valueOf(); + units = normalizeUnits(units); - 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; - } + if (units === 'year' || units === 'month' || units === 'quarter') { + output = monthDiff(this, that); + if (units === 'quarter') { + output = output / 3; + } else if (units === 'year') { + output = output / 12; + } + } else { + delta = this - that; + output = units === 'second' ? delta / 1e3 : // 1000 + units === 'minute' ? delta / 6e4 : // 1000 * 60 + units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60 + units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst + units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst + delta; + } + return asFloat ? output : absFloor(output); } - } - 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 hiddenDates - * @param range - * @param time - * @returns {{duration: number, time: *, offset: 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; - } - } - } + function monthDiff (a, b) { + // difference in months + var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), + // b is in (anchor - 1 month, anchor + 1 month) + anchor = a.clone().add(wholeMonthDiff, 'months'), + anchor2, adjust; - return hiddenDuration; - }; + if (b - anchor < 0) { + anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor - anchor2); + } else { + anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor2 - anchor); + } - /** - * used to step over to either side of a hidden block. Correction is disabled on tablets, might be set to true - * @param hiddenDates - * @param time - * @param direction - * @param correctionEnabled - * @returns {*} - */ - 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; - } + return -(wholeMonthDiff + adjust); } - } else { - return time; - } - }; - /** - * Check if a time is hidden - * - * @param time - * @param 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; + utils_hooks__hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; - if (time >= startDate && time < endDate) { - // if the start is entering a hidden zone - return { hidden: true, startDate: startDate, endDate: endDate }; - break; + function toString () { + return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); } - } - return { hidden: false, startDate: startDate, endDate: endDate }; - }; -/***/ }, -/* 17 */ -/***/ function(module, exports, __webpack_require__) { + function moment_format__toISOString () { + var m = this.clone().utc(); + if (0 < m.year() && m.year() <= 9999) { + if ('function' === typeof Date.prototype.toISOString) { + // native implementation is ~50x faster, use it when we can + return this.toDate().toISOString(); + } else { + return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); + } + } else { + return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); + } + } - /** - * @constructor DataStep - * The class DataStep is an iterator for data for the lineGraph. You provide a start data point and an - * end data point. 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 DataStep 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 - */ - 'use strict'; + function format (inputString) { + var output = formatMoment(this, inputString || utils_hooks__hooks.defaultFormat); + return this.localeData().postformat(output); + } - function DataStep(start, end, minimumStep, containerHeight, customRange, formattingFunction, alignZeros) { - // variables - this.current = 0; + function from (time, withoutSuffix) { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + return create__createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); + } - this.autoScale = true; - this.stepIndex = 0; - this.step = 1; - this.scale = 1; - this.formattingFunction = formattingFunction; + function fromNow (withoutSuffix) { + return this.from(local__createLocal(), withoutSuffix); + } - this.marginStart; - this.marginEnd; - this.deadSpace = 0; + function to (time, withoutSuffix) { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + return create__createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix); + } - this.majorSteps = [1, 2, 5, 10]; - this.minorSteps = [0.25, 0.5, 1, 2]; + function toNow (withoutSuffix) { + return this.to(local__createLocal(), withoutSuffix); + } - this.alignZeros = alignZeros; + function locale (key) { + var newLocaleData; - this.setRange(start, end, minimumStep, containerHeight, customRange); - } + if (key === undefined) { + return this._locale._abbr; + } else { + newLocaleData = locale_locales__getLocale(key); + if (newLocaleData != null) { + this._locale = newLocaleData; + } + return this; + } + } - /** - * 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 {Number} [start] The start date and time. - * @param {Number} [end] The end date and time. - * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds - */ - DataStep.prototype.setRange = function (start, end, minimumStep, containerHeight, customRange) { - this._start = customRange.min === undefined ? start : customRange.min; - this._end = customRange.max === undefined ? end : customRange.max; - if (this._start === this._end) { - this._start = customRange.min === undefined ? this._start - 0.75 : this._start; - this._end = customRange.max === undefined ? this._end + 1 : this._end;; - } + var lang = deprecate( + 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', + function (key) { + if (key === undefined) { + return this.localeData(); + } else { + return this.locale(key); + } + } + ); - if (this.autoScale === true) { - this.setMinimumStep(minimumStep, containerHeight); - } + function localeData () { + return this._locale; + } - this.setFirst(customRange); - }; + function startOf (units) { + units = normalizeUnits(units); + // the following switch intentionally omits break keywords + // to utilize falling through the cases. + switch (units) { + case 'year': + this.month(0); + /* falls through */ + case 'quarter': + case 'month': + this.date(1); + /* falls through */ + case 'week': + case 'isoWeek': + case 'day': + this.hours(0); + /* falls through */ + case 'hour': + this.minutes(0); + /* falls through */ + case 'minute': + this.seconds(0); + /* falls through */ + case 'second': + this.milliseconds(0); + } - /** - * Automatically determine the scale that bests fits the provided minimum step - * @param {Number} [minimumStep] The minimum step size in pixels - */ - DataStep.prototype.setMinimumStep = function (minimumStep, containerHeight) { - // round to floor - var range = this._end - this._start; - var safeRange = range * 1.2; - var minimumStepValue = minimumStep * (safeRange / containerHeight); - var orderOfMagnitude = Math.round(Math.log(safeRange) / Math.LN10); + // weeks are a special case + if (units === 'week') { + this.weekday(0); + } + if (units === 'isoWeek') { + this.isoWeekday(1); + } - var minorStepIdx = -1; - var magnitudefactor = Math.pow(10, orderOfMagnitude); + // quarters are also special + if (units === 'quarter') { + this.month(Math.floor(this.month() / 3) * 3); + } - var start = 0; - if (orderOfMagnitude < 0) { - start = orderOfMagnitude; - } + return this; + } - var solutionFound = false; - for (var i = start; Math.abs(i) <= Math.abs(orderOfMagnitude); i++) { - magnitudefactor = Math.pow(10, i); - for (var j = 0; j < this.minorSteps.length; j++) { - var stepSize = magnitudefactor * this.minorSteps[j]; - if (stepSize >= minimumStepValue) { - solutionFound = true; - minorStepIdx = j; - break; - } + function endOf (units) { + units = normalizeUnits(units); + if (units === undefined || units === 'millisecond') { + return this; + } + return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); } - if (solutionFound === true) { - break; + + function to_type__valueOf () { + return +this._d - ((this._offset || 0) * 60000); } - } - this.stepIndex = minorStepIdx; - this.scale = magnitudefactor; - this.step = magnitudefactor * this.minorSteps[minorStepIdx]; - }; - /** - * Round the current date to the first minor date value - * This must be executed once when the current date is set to start Date - */ - DataStep.prototype.setFirst = function (customRange) { - if (customRange === undefined) { - customRange = {}; - } + function unix () { + return Math.floor(+this / 1000); + } - var niceStart = customRange.min === undefined ? this._start - this.scale * 2 * this.minorSteps[this.stepIndex] : customRange.min; - var niceEnd = customRange.max === undefined ? this._end + this.scale * this.minorSteps[this.stepIndex] : customRange.max; + function toDate () { + return this._offset ? new Date(+this) : this._d; + } - this.marginEnd = customRange.max === undefined ? this.roundToMinor(niceEnd) : customRange.max; - this.marginStart = customRange.min === undefined ? this.roundToMinor(niceStart) : customRange.min; + function toArray () { + var m = this; + return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; + } - // if we need to align the zero's we need to make sure that there is a zero to use. - if (this.alignZeros === true && (this.marginEnd - this.marginStart) % this.step != 0) { - this.marginEnd += this.marginEnd % this.step; - } + function moment_valid__isValid () { + return valid__isValid(this); + } - this.deadSpace = this.roundToMinor(niceEnd) - niceEnd + this.roundToMinor(niceStart) - niceStart; - this.marginRange = this.marginEnd - this.marginStart; + function parsingFlags () { + return extend({}, getParsingFlags(this)); + } - this.current = this.marginEnd; - }; + function invalidAt () { + return getParsingFlags(this).overflow; + } - DataStep.prototype.roundToMinor = function (value) { - var rounded = value - value % (this.scale * this.minorSteps[this.stepIndex]); - if (value % (this.scale * this.minorSteps[this.stepIndex]) > 0.5 * (this.scale * this.minorSteps[this.stepIndex])) { - return rounded + this.scale * this.minorSteps[this.stepIndex]; - } else { - return rounded; - } - }; + addFormatToken(0, ['gg', 2], 0, function () { + return this.weekYear() % 100; + }); - /** - * Check if the there is a next step - * @return {boolean} true if the current date has not passed the end date - */ - DataStep.prototype.hasNext = function () { - return this.current >= this.marginStart; - }; + addFormatToken(0, ['GG', 2], 0, function () { + return this.isoWeekYear() % 100; + }); - /** - * Do the next step - */ - DataStep.prototype.next = function () { - var prev = this.current; - this.current -= this.step; + function addWeekYearFormatToken (token, getter) { + addFormatToken(0, [token, token.length], 0, getter); + } - // safety mechanism: if current time is still unchanged, move to the end - if (this.current === prev) { - this.current = this._end; - } - }; + addWeekYearFormatToken('gggg', 'weekYear'); + addWeekYearFormatToken('ggggg', 'weekYear'); + addWeekYearFormatToken('GGGG', 'isoWeekYear'); + addWeekYearFormatToken('GGGGG', 'isoWeekYear'); - /** - * Do the next step - */ - DataStep.prototype.previous = function () { - this.current += this.step; - this.marginEnd += this.step; - this.marginRange = this.marginEnd - this.marginStart; - }; + // ALIASES - /** - * Get the current datetime - * @return {String} current The current date - */ - DataStep.prototype.getCurrent = function () { - // prevent round-off errors when close to zero - var current = Math.abs(this.current) < this.step / 2 ? 0 : this.current; - var returnValue = current.toPrecision(5); - if (typeof this.formattingFunction === 'function') { - returnValue = this.formattingFunction(current); - } + addUnitAlias('weekYear', 'gg'); + addUnitAlias('isoWeekYear', 'GG'); - if (typeof returnValue === 'number') { - return '' + returnValue; - } else if (typeof returnValue === 'string') { - return returnValue; - } else { - return current.toPrecision(5); - } - }; + // PARSING - /** - * 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. - */ - DataStep.prototype.isMajor = function () { - return this.current % (this.scale * this.majorSteps[this.stepIndex]) === 0; - }; + addRegexToken('G', matchSigned); + addRegexToken('g', matchSigned); + addRegexToken('GG', match1to2, match2); + addRegexToken('gg', match1to2, match2); + addRegexToken('GGGG', match1to4, match4); + addRegexToken('gggg', match1to4, match4); + addRegexToken('GGGGG', match1to6, match6); + addRegexToken('ggggg', match1to6, match6); - DataStep.prototype.shift = function (steps) { - if (steps < 0) { - for (var i = 0; i < -steps; i++) { - this.previous(); + addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { + week[token.substr(0, 2)] = toInt(input); + }); + + addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { + week[token] = utils_hooks__hooks.parseTwoDigitYear(input); + }); + + // HELPERS + + function weeksInYear(year, dow, doy) { + return weekOfYear(local__createLocal([year, 11, 31 + dow - doy]), dow, doy).week; } - } else if (steps > 0) { - for (var i = 0; i < steps; i++) { - this.next(); + + // MOMENTS + + function getSetWeekYear (input) { + var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year; + return input == null ? year : this.add((input - year), 'y'); } - } - }; - module.exports = DataStep; + function getSetISOWeekYear (input) { + var year = weekOfYear(this, 1, 4).year; + return input == null ? year : this.add((input - year), 'y'); + } -/***/ }, -/* 18 */ -/***/ function(module, exports, __webpack_require__) { + function getISOWeeksInYear () { + return weeksInYear(this.year(), 1, 4); + } - 'use strict'; + function getWeeksInYear () { + var weekInfo = this.localeData()._week; + return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); + } - var util = __webpack_require__(2); - var hammerUtil = __webpack_require__(49); - var moment = __webpack_require__(40); - var Component = __webpack_require__(25); - var DateUtil = __webpack_require__(16); + addFormatToken('Q', 0, 0, 'quarter'); - /** - * @constructor Range - * 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 - */ - function Range(body, options) { - var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0); - this.start = now.clone().add(-3, 'days').valueOf(); // Number - this.end = now.clone().add(4, 'days').valueOf(); // Number + // ALIASES - this.body = body; - this.deltaDifference = 0; - this.scaleOffset = 0; - this.startToFront = false; - this.endToFront = true; + addUnitAlias('quarter', 'Q'); - // default options - this.defaultOptions = { - start: null, - end: null, - direction: 'horizontal', // 'horizontal' or 'vertical' - moveable: true, - zoomable: true, - min: null, - max: null, - zoomMin: 10, // milliseconds - zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds - }; - this.options = util.extend({}, this.defaultOptions); + // PARSING - this.props = { - touch: {} - }; - this.animationTimer = null; + addRegexToken('Q', match1); + addParseToken('Q', function (input, array) { + array[MONTH] = (toInt(input) - 1) * 3; + }); - // 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)); + // MOMENTS - // mouse wheel for zooming - this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this)); + function getSetQuarter (input) { + return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); + } - // pinch to zoom - this.body.emitter.on('touch', this._onTouch.bind(this)); - this.body.emitter.on('pinch', this._onPinch.bind(this)); + addFormatToken('D', ['DD', 2], 'Do', 'date'); - this.setOptions(options); - } + // ALIASES - Range.prototype = new Component(); + addUnitAlias('date', 'D'); - /** - * 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 = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable', 'activate', 'hiddenDates']; - util.selectiveExtend(fields, this.options, options); + // PARSING - if ('start' in options || 'end' in options) { - // apply a new range. both start and end are optional - this.setRange(options.start, options.end); - } - } - }; + addRegexToken('D', match1to2); + addRegexToken('DD', match1to2, match2); + addRegexToken('Do', function (isStrict, locale) { + return isStrict ? locale._ordinalParse : locale._ordinalParseLenient; + }); - /** - * 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".'); - } - } + addParseToken(['D', 'DD'], DATE); + addParseToken('Do', function (input, array) { + array[DATE] = toInt(input.match(match1to2)[0], 10); + }); - /** - * Set a new start and end range - * @param {Date | Number | String} [start] - * @param {Date | Number | String} [end] - * @param {boolean | {duration: number, easingFunction: string}} [animation=false] - * 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 {Boolean} [byUser=false] - * - */ - Range.prototype.setRange = function (start, end, animation, byUser) { - if (byUser !== true) { - byUser = false; - } - var finalStart = start != undefined ? util.convert(start, 'Date').valueOf() : null; - var finalEnd = end != undefined ? util.convert(end, 'Date').valueOf() : null; - this._cancelAnimation(); + // MOMENTS - if (animation) { - // true or an Object - var me = this; - var initStart = this.start; - var initEnd = this.end; - var duration = typeof animation === 'object' && 'duration' in animation ? animation.duration : 500; - var easingName = typeof animation === 'object' && 'easingFunction' in animation ? animation.easingFunction : 'easeInOutQuad'; - var easingFunction = util.easingFunctions[easingName]; - if (!easingFunction) { - throw new Error('Unknown easing function ' + JSON.stringify(easingName) + '. ' + 'Choose from: ' + Object.keys(util.easingFunctions).join(', ')); - } + var getSetDayOfMonth = makeGetSet('Date', true); - var initTime = new Date().valueOf(); - var anyChanged = false; + addFormatToken('d', 0, 'do', 'day'); - 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; + addFormatToken('dd', 0, 0, function (format) { + return this.localeData().weekdaysMin(this, format); + }); - changed = me._applyRange(s, e); - DateUtil.updateHiddenDates(me.body, me.options.hiddenDates); - anyChanged = anyChanged || changed; - if (changed) { - me.body.emitter.emit('rangechange', { start: new Date(me.start), end: new Date(me.end), byUser: byUser }); - } + addFormatToken('ddd', 0, 0, function (format) { + return this.localeData().weekdaysShort(this, format); + }); - if (done) { - if (anyChanged) { - me.body.emitter.emit('rangechanged', { start: new Date(me.start), end: new Date(me.end), byUser: byUser }); - } - } 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); - } - } - }; + addFormatToken('dddd', 0, 0, function (format) { + return this.localeData().weekdays(this, format); + }); - return next(); - } else { - var changed = this._applyRange(finalStart, finalEnd); - DateUtil.updateHiddenDates(this.body, this.options.hiddenDates); - if (changed) { - var params = { start: new Date(this.start), end: new Date(this.end), byUser: byUser }; - this.body.emitter.emit('rangechange', params); - this.body.emitter.emit('rangechanged', params); - } - } - }; + addFormatToken('e', 0, 0, 'weekday'); + addFormatToken('E', 0, 0, 'isoWeekday'); - /** - * Stop an animation - * @private - */ - Range.prototype._cancelAnimation = function () { - if (this.animationTimer) { - clearTimeout(this.animationTimer); - this.animationTimer = null; - } - }; + // ALIASES - /** - * 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; + addUnitAlias('day', 'd'); + addUnitAlias('weekday', 'e'); + addUnitAlias('isoWeekday', 'E'); - // 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 + '"'); - } + // PARSING - // prevent start < end - if (newEnd < newStart) { - newEnd = newStart; - } + addRegexToken('d', match1to2); + addRegexToken('e', match1to2); + addRegexToken('E', match1to2); + addRegexToken('dd', matchWord); + addRegexToken('ddd', matchWord); + addRegexToken('dddd', matchWord); - // prevent start < min - if (min !== null) { - if (newStart < min) { - diff = min - newStart; - newStart += diff; - newEnd += diff; + addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config) { + var weekday = config._locale.weekdaysParse(input); + // if we didn't get a weekday name, mark the date as invalid + if (weekday != null) { + week.d = weekday; + } else { + getParsingFlags(config).invalidWeekday = input; + } + }); - // prevent end > max - if (max != null) { - if (newEnd > max) { - newEnd = max; + addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { + week[token] = toInt(input); + }); + + // HELPERS + + function parseWeekday(input, locale) { + if (typeof input === 'string') { + if (!isNaN(input)) { + input = parseInt(input, 10); + } + else { + input = locale.weekdaysParse(input); + if (typeof input !== 'number') { + return null; + } + } } - } + return input; } - } - // prevent end > max - if (max !== null) { - if (newEnd > max) { - diff = newEnd - max; - newStart -= diff; - newEnd -= diff; + // LOCALES - // prevent start < min - if (min != null) { - if (newStart < min) { - newStart = min; - } - } + var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); + function localeWeekdays (m) { + return this._weekdays[m.day()]; } - } - // prevent (end-start) < zoomMin - if (this.options.zoomMin !== null) { - var zoomMin = parseFloat(this.options.zoomMin); - if (zoomMin < 0) { - zoomMin = 0; - } - if (newEnd - newStart < zoomMin) { - if (this.end - this.start === zoomMin && newStart > this.start && 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; + var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); + function localeWeekdaysShort (m) { + return this._weekdaysShort[m.day()]; } - 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 defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); + function localeWeekdaysMin (m) { + return this._weekdaysMin[m.day()]; } - } - - 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 - * @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 - * @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; - - // 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.start = this.start; - this.props.touch.end = this.end; - this.props.touch.dragging = true; + function localeWeekdaysParse (weekdayName) { + var i, mom, regex; - if (this.body.dom.root) { - this.body.dom.root.style.cursor = 'move'; - } - }; + if (!this._weekdaysParse) { + this._weekdaysParse = []; + } - /** - * Perform dragging operation - * @param {Event} event - * @private - */ - Range.prototype._onDrag = function (event) { - // only allow dragging when configured as movable - if (!this.options.moveable) return; + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + if (!this._weekdaysParse[i]) { + mom = local__createLocal([2000, 1]).day(i); + regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); + this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if (this._weekdaysParse[i].test(weekdayName)) { + return i; + } + } + } - // 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; + // MOMENTS - 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; + function getSetDayOfWeek (input) { + var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); + if (input != null) { + input = parseWeekday(input, this.localeData()); + return this.add(input - day, 'd'); + } else { + return day; + } + } - // normalize dragging speed if cutout is in between. - var duration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end); - interval -= duration; + function getSetLocaleDayOfWeek (input) { + var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; + return input == null ? weekday : this.add(input - weekday, 'd'); + } - var width = direction == 'horizontal' ? this.body.domProps.center.width : this.body.domProps.center.height; - var diffRange = -delta / width * interval; - var newStart = this.props.touch.start + diffRange; - var newEnd = this.props.touch.end + diffRange; + function getSetISODayOfWeek (input) { + // behaves the same as moment#day except + // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) + // as a setter, sunday should belong to the previous week. + return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); + } - // 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; - } + addFormatToken('H', ['HH', 2], 0, 'hour'); + addFormatToken('h', ['hh', 2], 0, function () { + return this.hours() % 12 || 12; + }); - this.previousDelta = delta; - this._applyRange(newStart, newEnd); + function meridiem (token, lowercase) { + addFormatToken(token, 0, 0, function () { + return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); + }); + } - // fire a rangechange event - this.body.emitter.emit('rangechange', { - start: new Date(this.start), - end: new Date(this.end), - byUser: true - }); - }; + meridiem('a', true); + meridiem('A', false); - /** - * Stop dragging operation - * @param {event} event - * @private - */ - Range.prototype._onDragEnd = function (event) { - // only allow dragging when configured as movable - if (!this.options.moveable) return; + // ALIASES - // 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; + addUnitAlias('hour', 'h'); - this.props.touch.dragging = false; - if (this.body.dom.root) { - this.body.dom.root.style.cursor = 'auto'; - } + // PARSING - // fire a rangechanged event - this.body.emitter.emit('rangechanged', { - start: new Date(this.start), - end: new Date(this.end), - byUser: true - }); - }; + function matchMeridiem (isStrict, locale) { + return locale._meridiemParse; + } - /** - * 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) { - // only allow zooming when configured as zoomable and moveable - if (!(this.options.zoomable && this.options.moveable)) return; + addRegexToken('a', matchMeridiem); + addRegexToken('A', matchMeridiem); + addRegexToken('H', match1to2); + addRegexToken('h', match1to2); + addRegexToken('HH', match1to2, match2); + addRegexToken('hh', match1to2, match2); - // 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; - } + addParseToken(['H', 'HH'], HOUR); + addParseToken(['a', 'A'], function (input, array, config) { + config._isPm = config._locale.isPM(input); + config._meridiem = input; + }); + addParseToken(['h', 'hh'], function (input, array, config) { + array[HOUR] = toInt(input); + getParsingFlags(config).bigHour = true; + }); - // 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 + // LOCALES - // 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); + function localeIsPM (input) { + // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays + // Using charAt should be more compatible. + return ((input + '').toLowerCase().charAt(0) === 'p'); } - // calculate center, the date to zoom around - var pointer = getPointer({ x: event.clientX, y: event.clientY }, this.body.dom.center); - var pointerDate = this._pointerToDate(pointer); + var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; + function localeMeridiem (hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'pm' : 'PM'; + } else { + return isLower ? 'am' : 'AM'; + } + } - this.zoom(scale, pointerDate, delta); - } - // Prevent default actions caused by mouse wheel - // (else the page and timeline both zoom and scroll) - event.preventDefault(); - }; + // MOMENTS - /** - * Start of a touch gesture - * @private - */ - Range.prototype._onTouch = function (event) { - 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; - }; + // Setting the hour should keep the time, because the user explicitly + // specified which hour he wants. So trying to maintain the same hour (in + // a new timezone) makes sense. Adding/subtracting hours does not follow + // this rule. + var getSetHour = makeGetSet('Hours', true); - /** - * 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; + addFormatToken('m', ['mm', 2], 0, 'minute'); - this.props.touch.allowDragging = false; + // ALIASES - if (!this.props.touch.center) { - this.props.touch.center = getPointer(event.center, this.body.dom.center); - } + addUnitAlias('minute', 'm'); - var scale = 1 / (event.scale + this.scaleOffset); - var centerDate = this._pointerToDate(this.props.touch.center); + // PARSING - var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end); - var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, centerDate); - var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore; + addRegexToken('m', match1to2); + addRegexToken('mm', match1to2, match2); + addParseToken(['m', 'mm'], MINUTE); - // 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; + // MOMENTS - // 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 getSetMinute = makeGetSet('Minutes', false); - 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; - } + addFormatToken('s', ['ss', 2], 0, 'second'); - this.setRange(newStart, newEnd, false, true); + // ALIASES - this.startToFront = false; // revert to default - this.endToFront = true; // revert to default - }; + addUnitAlias('second', 's'); - /** - * 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; + // PARSING - validateDirection(direction); + addRegexToken('s', match1to2); + addRegexToken('ss', match1to2, match2); + addParseToken(['s', 'ss'], SECOND); - 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; - } - }; + // MOMENTS - /** - * 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 - */ - function getPointer(touch, element) { - return { - x: touch.x - util.getAbsoluteLeft(element), - y: touch.y - util.getAbsoluteTop(element) - }; - } + var getSetSecond = makeGetSet('Seconds', false); - /** - * 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. - */ - Range.prototype.zoom = function (scale, center, delta) { - // if centerDate is not provided, take it half between start Date and end Date - if (center == null) { - center = (this.start + this.end) / 2; - } + addFormatToken('S', 0, 0, function () { + return ~~(this.millisecond() / 100); + }); - var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end); - var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, center); - var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore; + addFormatToken(0, ['SS', 2], 0, function () { + return ~~(this.millisecond() / 10); + }); - // calculate new start and end - var newStart = center - hiddenDurationBefore + (this.start - (center - hiddenDurationBefore)) * scale; - var newEnd = center + hiddenDurationAfter + (this.end - (center + hiddenDurationAfter)) * scale; + function millisecond__milliseconds (token) { + addFormatToken(0, [token, 3], 0, 'millisecond'); + } - // 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; - } + millisecond__milliseconds('SSS'); + millisecond__milliseconds('SSSS'); - this.setRange(newStart, newEnd, false, true); + // ALIASES - this.startToFront = false; // revert to default - this.endToFront = true; // revert to default - }; + addUnitAlias('millisecond', 'ms'); - /** - * 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; + // PARSING - // apply new values - var newStart = this.start + diff * delta; - var newEnd = this.end + diff * delta; + addRegexToken('S', match1to3, match1); + addRegexToken('SS', match1to3, match2); + addRegexToken('SSS', match1to3, match3); + addRegexToken('SSSS', matchUnsigned); + addParseToken(['S', 'SS', 'SSS', 'SSSS'], function (input, array) { + array[MILLISECOND] = toInt(('0.' + input) * 1000); + }); - // TODO: reckon with min and max range + // MOMENTS - this.start = newStart; - this.end = newEnd; - }; + var getSetMillisecond = makeGetSet('Milliseconds', false); - /** - * 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; + addFormatToken('z', 0, 0, 'zoneAbbr'); + addFormatToken('zz', 0, 0, 'zoneName'); - var diff = center - moveTo; + // MOMENTS - // calculate new start and end - var newStart = this.start - diff; - var newEnd = this.end - diff; + function getZoneAbbr () { + return this._isUTC ? 'UTC' : ''; + } - this.setRange(newStart, newEnd); - }; + function getZoneName () { + return this._isUTC ? 'Coordinated Universal Time' : ''; + } - module.exports = Range; + var momentPrototype__proto = Moment.prototype; -/***/ }, -/* 19 */ -/***/ function(module, exports, __webpack_require__) { + momentPrototype__proto.add = add_subtract__add; + momentPrototype__proto.calendar = moment_calendar__calendar; + momentPrototype__proto.clone = clone; + momentPrototype__proto.diff = diff; + momentPrototype__proto.endOf = endOf; + momentPrototype__proto.format = format; + momentPrototype__proto.from = from; + momentPrototype__proto.fromNow = fromNow; + momentPrototype__proto.to = to; + momentPrototype__proto.toNow = toNow; + momentPrototype__proto.get = getSet; + momentPrototype__proto.invalidAt = invalidAt; + momentPrototype__proto.isAfter = isAfter; + momentPrototype__proto.isBefore = isBefore; + momentPrototype__proto.isBetween = isBetween; + momentPrototype__proto.isSame = isSame; + momentPrototype__proto.isValid = moment_valid__isValid; + momentPrototype__proto.lang = lang; + momentPrototype__proto.locale = locale; + momentPrototype__proto.localeData = localeData; + momentPrototype__proto.max = prototypeMax; + momentPrototype__proto.min = prototypeMin; + momentPrototype__proto.parsingFlags = parsingFlags; + momentPrototype__proto.set = getSet; + momentPrototype__proto.startOf = startOf; + momentPrototype__proto.subtract = add_subtract__subtract; + momentPrototype__proto.toArray = toArray; + momentPrototype__proto.toDate = toDate; + momentPrototype__proto.toISOString = moment_format__toISOString; + momentPrototype__proto.toJSON = moment_format__toISOString; + momentPrototype__proto.toString = toString; + momentPrototype__proto.unix = unix; + momentPrototype__proto.valueOf = to_type__valueOf; - // Utility functions for ordering and stacking of items - 'use strict'; + // Year + momentPrototype__proto.year = getSetYear; + momentPrototype__proto.isLeapYear = getIsLeapYear; - var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors + // Week Year + momentPrototype__proto.weekYear = getSetWeekYear; + momentPrototype__proto.isoWeekYear = getSetISOWeekYear; - /** - * Order items by their start data - * @param {Item[]} items - */ - exports.orderByStart = function (items) { - items.sort(function (a, b) { - return a.data.start - b.data.start; - }); - }; + // Quarter + momentPrototype__proto.quarter = momentPrototype__proto.quarters = getSetQuarter; - /** - * Order items by their end date. If they have no end date, their start date - * is used. - * @param {Item[]} items - */ - exports.orderByEnd = function (items) { - items.sort(function (a, b) { - var aTime = 'end' in a.data ? a.data.end : a.data.start, - bTime = 'end' in b.data ? b.data.end : b.data.start; + // Month + momentPrototype__proto.month = getSetMonth; + momentPrototype__proto.daysInMonth = getDaysInMonth; - return aTime - bTime; - }); - }; + // Week + momentPrototype__proto.week = momentPrototype__proto.weeks = getSetWeek; + momentPrototype__proto.isoWeek = momentPrototype__proto.isoWeeks = getSetISOWeek; + momentPrototype__proto.weeksInYear = getWeeksInYear; + momentPrototype__proto.isoWeeksInYear = getISOWeeksInYear; - /** - * Adjust vertical positions of the items such that they don't overlap each - * other. - * @param {Item[]} items - * All visible items - * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin - * Margins between items and between items and the axis. - * @param {boolean} [force=false] - * If true, all items will be repositioned. If false (default), only - * items having a top===null will be re-stacked - */ - exports.stack = function (items, margin, force) { - var i, iMax; + // Day + momentPrototype__proto.date = getSetDayOfMonth; + momentPrototype__proto.day = momentPrototype__proto.days = getSetDayOfWeek; + momentPrototype__proto.weekday = getSetLocaleDayOfWeek; + momentPrototype__proto.isoWeekday = getSetISODayOfWeek; + momentPrototype__proto.dayOfYear = getSetDayOfYear; - if (force) { - // reset top position of all items - for (i = 0, iMax = items.length; i < iMax; i++) { - items[i].top = null; + // Hour + momentPrototype__proto.hour = momentPrototype__proto.hours = getSetHour; + + // Minute + momentPrototype__proto.minute = momentPrototype__proto.minutes = getSetMinute; + + // Second + momentPrototype__proto.second = momentPrototype__proto.seconds = getSetSecond; + + // Millisecond + momentPrototype__proto.millisecond = momentPrototype__proto.milliseconds = getSetMillisecond; + + // Offset + momentPrototype__proto.utcOffset = getSetOffset; + momentPrototype__proto.utc = setOffsetToUTC; + momentPrototype__proto.local = setOffsetToLocal; + momentPrototype__proto.parseZone = setOffsetToParsedOffset; + momentPrototype__proto.hasAlignedHourOffset = hasAlignedHourOffset; + momentPrototype__proto.isDST = isDaylightSavingTime; + momentPrototype__proto.isDSTShifted = isDaylightSavingTimeShifted; + momentPrototype__proto.isLocal = isLocal; + momentPrototype__proto.isUtcOffset = isUtcOffset; + momentPrototype__proto.isUtc = isUtc; + momentPrototype__proto.isUTC = isUtc; + + // Timezone + momentPrototype__proto.zoneAbbr = getZoneAbbr; + momentPrototype__proto.zoneName = getZoneName; + + // Deprecations + momentPrototype__proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); + momentPrototype__proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); + momentPrototype__proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); + momentPrototype__proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779', getSetZone); + + var momentPrototype = momentPrototype__proto; + + function moment__createUnix (input) { + return local__createLocal(input * 1000); } - } - // calculate new, non-overlapping positions - for (i = 0, iMax = items.length; i < iMax; i++) { - var item = items[i]; - if (item.stack && item.top === null) { - // initialize top position - item.top = margin.axis; + function moment__createInZone () { + return local__createLocal.apply(null, arguments).parseZone(); + } - do { - // TODO: optimize checking for overlap. when there is a gap without items, - // you only need to check for items from the next item on, not from zero - var collidingItem = null; - for (var j = 0, jj = items.length; j < jj; j++) { - var other = items[j]; - if (other.top !== null && other !== item && other.stack && exports.collision(item, other, margin.item)) { - collidingItem = other; - break; - } - } + var defaultCalendar = { + sameDay : '[Today at] LT', + nextDay : '[Tomorrow at] LT', + nextWeek : 'dddd [at] LT', + lastDay : '[Yesterday at] LT', + lastWeek : '[Last] dddd [at] LT', + sameElse : 'L' + }; - if (collidingItem != null) { - // There is a collision. Reposition the items above the colliding element - item.top = collidingItem.top + collidingItem.height + margin.item.vertical; - } - } while (collidingItem); + function locale_calendar__calendar (key, mom, now) { + var output = this._calendar[key]; + return typeof output === 'function' ? output.call(mom, now) : output; } - } - }; - /** - * Adjust vertical positions of the items without stacking them - * @param {Item[]} items - * All visible items - * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin - * Margins between items and between items and the axis. - */ - exports.nostack = function (items, margin, subgroups) { - var i, iMax, newTop; + var defaultLongDateFormat = { + LTS : 'h:mm:ss A', + LT : 'h:mm A', + L : 'MM/DD/YYYY', + LL : 'MMMM D, YYYY', + LLL : 'MMMM D, YYYY LT', + LLLL : 'dddd, MMMM D, YYYY LT' + }; - // reset top position of all items - for (i = 0, iMax = items.length; i < iMax; i++) { - if (items[i].data.subgroup !== undefined) { - newTop = margin.axis; - for (var subgroup in subgroups) { - if (subgroups.hasOwnProperty(subgroup)) { - if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroups[items[i].data.subgroup].index) { - newTop += subgroups[subgroup].height + margin.item.vertical; - } + function longDateFormat (key) { + var output = this._longDateFormat[key]; + if (!output && this._longDateFormat[key.toUpperCase()]) { + output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { + return val.slice(1); + }); + this._longDateFormat[key] = output; } - } - items[i].top = newTop; - } else { - items[i].top = margin.axis; + return output; } - } - }; - - /** - * Test if the two provided items collide - * The items must have parameters left, width, top, and height. - * @param {Item} a The first item - * @param {Item} b The second item - * @param {{horizontal: number, vertical: number}} margin - * An object containing a horizontal and vertical - * minimum required margin. - * @return {boolean} true if a and b collide, else false - */ - exports.collision = function (a, b, margin) { - return a.left - margin.horizontal + EPSILON < b.left + b.width && a.left + a.width + margin.horizontal - EPSILON > b.left && a.top - margin.vertical + EPSILON < b.top + b.height && a.top + a.height + margin.vertical - EPSILON > b.top; - }; -/***/ }, -/* 20 */ -/***/ function(module, exports, __webpack_require__) { + var defaultInvalidDate = 'Invalid date'; - 'use strict'; + function invalidDate () { + return this._invalidDate; + } - var moment = __webpack_require__(40); - var DateUtil = __webpack_require__(16); - var util = __webpack_require__(2); + var defaultOrdinal = '%d'; + var defaultOrdinalParse = /\d{1,2}/; - /** - * @constructor TimeStep - * 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 - */ - function TimeStep(start, end, minimumStep, hiddenDates) { - // variables - this.current = new Date(); - this._start = new Date(); - this._end = new Date(); + function ordinal (number) { + return this._ordinal.replace('%d', number); + } - this.autoScale = true; - this.scale = 'day'; - this.step = 1; + function preParsePostFormat (string) { + return string; + } - // initialize the range - this.setRange(start, end, minimumStep); + var defaultRelativeTime = { + future : 'in %s', + past : '%s ago', + s : 'a few seconds', + m : 'a minute', + mm : '%d minutes', + h : 'an hour', + hh : '%d hours', + d : 'a day', + dd : '%d days', + M : 'a month', + MM : '%d months', + y : 'a year', + yy : '%d years' + }; - // hidden Dates options - this.switchedDay = false; - this.switchedMonth = false; - this.switchedYear = false; - this.hiddenDates = hiddenDates; - if (hiddenDates === undefined) { - this.hiddenDates = []; - } + function relative__relativeTime (number, withoutSuffix, string, isFuture) { + var output = this._relativeTime[string]; + return (typeof output === 'function') ? + output(number, withoutSuffix, string, isFuture) : + output.replace(/%d/i, number); + } - this.format = TimeStep.FORMAT; // default formatting - } + function pastFuture (diff, output) { + var format = this._relativeTime[diff > 0 ? 'future' : 'past']; + return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); + } - // Time formatting - TimeStep.FORMAT = { - minorLabels: { - millisecond: 'SSS', - second: 's', - minute: 'HH:mm', - hour: 'HH:mm', - weekday: 'ddd D', - day: 'D', - 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', - month: 'YYYY', - year: '' - } - }; + function locale_set__set (config) { + var prop, i; + for (i in config) { + prop = config[i]; + if (typeof prop === 'function') { + this[i] = prop; + } else { + this['_' + i] = prop; + } + } + // Lenient ordinal parsing accepts just a number in addition to + // number + (possibly) stuff coming from _ordinalParseLenient. + this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + (/\d{1,2}/).source); + } - /** - * 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', '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); - }; + var prototype__proto = Locale.prototype; - /** - * 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'; - } + prototype__proto._calendar = defaultCalendar; + prototype__proto.calendar = locale_calendar__calendar; + prototype__proto._longDateFormat = defaultLongDateFormat; + prototype__proto.longDateFormat = longDateFormat; + prototype__proto._invalidDate = defaultInvalidDate; + prototype__proto.invalidDate = invalidDate; + prototype__proto._ordinal = defaultOrdinal; + prototype__proto.ordinal = ordinal; + prototype__proto._ordinalParse = defaultOrdinalParse; + prototype__proto.preparse = preParsePostFormat; + prototype__proto.postformat = preParsePostFormat; + prototype__proto._relativeTime = defaultRelativeTime; + prototype__proto.relativeTime = relative__relativeTime; + prototype__proto.pastFuture = pastFuture; + prototype__proto.set = locale_set__set; - this._start = start != undefined ? new Date(start.valueOf()) : new Date(); - this._end = end != undefined ? new Date(end.valueOf()) : new Date(); + // Month + prototype__proto.months = localeMonths; + prototype__proto._months = defaultLocaleMonths; + prototype__proto.monthsShort = localeMonthsShort; + prototype__proto._monthsShort = defaultLocaleMonthsShort; + prototype__proto.monthsParse = localeMonthsParse; - if (this.autoScale) { - this.setMinimumStep(minimumStep); - } - }; + // Week + prototype__proto.week = localeWeek; + prototype__proto._week = defaultLocaleWeek; + prototype__proto.firstDayOfYear = localeFirstDayOfYear; + prototype__proto.firstDayOfWeek = localeFirstDayOfWeek; - /** - * Set the range iterator to the start date. - */ - TimeStep.prototype.first = function () { - this.current = new Date(this._start.valueOf()); - this.roundToMinor(); - }; + // Day of Week + prototype__proto.weekdays = localeWeekdays; + prototype__proto._weekdays = defaultLocaleWeekdays; + prototype__proto.weekdaysMin = localeWeekdaysMin; + prototype__proto._weekdaysMin = defaultLocaleWeekdaysMin; + prototype__proto.weekdaysShort = localeWeekdaysShort; + prototype__proto._weekdaysShort = defaultLocaleWeekdaysShort; + prototype__proto.weekdaysParse = localeWeekdaysParse; - /** - * 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 - // IMPORTANT: we have no breaks in this switch! (this is no bug) - // noinspection FallThroughInSwitchStatementJS - switch (this.scale) { - case 'year': - this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step)); - this.current.setMonth(0); - case 'month': - this.current.setDate(1); - case 'day': // intentional fall through - case 'weekday': - this.current.setHours(0); - case 'hour': - this.current.setMinutes(0); - case 'minute': - this.current.setSeconds(0); - case 'second': - this.current.setMilliseconds(0); - //case 'millisecond': // nothing to do for milliseconds - } + // Hours + prototype__proto.isPM = localeIsPM; + prototype__proto._meridiemParse = defaultLocaleMeridiemParse; + prototype__proto.meridiem = localeMeridiem; - 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.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step);break; - case 'second': - this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step);break; - case 'minute': - this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step);break; - case 'hour': - this.current.setHours(this.current.getHours() - this.current.getHours() % this.step);break; - case 'weekday': // intentional fall through - case 'day': - this.current.setDate(this.current.getDate() - 1 - (this.current.getDate() - 1) % this.step + 1);break; - case 'month': - this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step);break; - case 'year': - this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step);break; - default: - break; + function lists__get (format, index, field, setter) { + var locale = locale_locales__getLocale(); + var utc = create_utc__createUTC().set(setter, index); + return locale[field](utc, format); } - } - }; - /** - * 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(); - }; + function list (format, index, field, count, setter) { + if (typeof format === 'number') { + index = format; + format = undefined; + } - /** - * Do the next step - */ - TimeStep.prototype.next = function () { - var prev = this.current.valueOf(); + format = format || ''; - // Two cases, needed to prevent issues with switching daylight savings - // (end of March and end of October) - if (this.current.getMonth() < 6) { - switch (this.scale) { - case 'millisecond': + if (index != null) { + return lists__get(format, index, field, setter); + } - this.current = new Date(this.current.valueOf() + this.step);break; - case 'second': - this.current = new Date(this.current.valueOf() + this.step * 1000);break; - case 'minute': - this.current = new Date(this.current.valueOf() + this.step * 1000 * 60);break; - case 'hour': - this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60); - // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...) - var h = this.current.getHours(); - this.current.setHours(h - h % this.step); - break; - case 'weekday': // intentional fall through - case 'day': - this.current.setDate(this.current.getDate() + this.step);break; - case 'month': - this.current.setMonth(this.current.getMonth() + this.step);break; - case 'year': - this.current.setFullYear(this.current.getFullYear() + this.step);break; - default: - break; - } - } else { - switch (this.scale) { - case 'millisecond': - this.current = new Date(this.current.valueOf() + this.step);break; - case 'second': - this.current.setSeconds(this.current.getSeconds() + this.step);break; - case 'minute': - this.current.setMinutes(this.current.getMinutes() + this.step);break; - case 'hour': - this.current.setHours(this.current.getHours() + this.step);break; - case 'weekday': // intentional fall through - case 'day': - this.current.setDate(this.current.getDate() + this.step);break; - case 'month': - this.current.setMonth(this.current.getMonth() + this.step);break; - case 'year': - this.current.setFullYear(this.current.getFullYear() + this.step);break; - default: - break; + var i; + var out = []; + for (i = 0; i < count; i++) { + out[i] = lists__get(format, i, field, setter); + } + return out; } - } - if (this.step != 1) { - // round down to the correct major value - switch (this.scale) { - case 'millisecond': - if (this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0);break; - case 'second': - if (this.current.getSeconds() < this.step) this.current.setSeconds(0);break; - case 'minute': - if (this.current.getMinutes() < this.step) this.current.setMinutes(0);break; - case 'hour': - if (this.current.getHours() < this.step) this.current.setHours(0);break; - case 'weekday': // intentional fall through - case 'day': - if (this.current.getDate() < this.step + 1) this.current.setDate(1);break; - case 'month': - if (this.current.getMonth() < this.step) this.current.setMonth(0);break; - case 'year': - break; // nothing to do for year - default: - break; + function lists__listMonths (format, index) { + return list(format, index, 'months', 12, 'month'); } - } - // safety mechanism: if current time is still unchanged, move to the end - if (this.current.valueOf() == prev) { - this.current = new Date(this._end.valueOf()); - } + function lists__listMonthsShort (format, index) { + return list(format, index, 'monthsShort', 12, 'month'); + } - DateUtil.stepOverHiddenDates(this, prev); - }; + function lists__listWeekdays (format, index) { + return list(format, index, 'weekdays', 7, 'day'); + } - /** - * Get the current datetime - * @return {Date} current The current date - */ - TimeStep.prototype.getCurrent = function () { - return this.current; - }; + function lists__listWeekdaysShort (format, index) { + return list(format, index, 'weekdaysShort', 7, 'day'); + } - /** - * 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', '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; - } - }; + function lists__listWeekdaysMin (format, index) { + return list(format, index, 'weekdaysMin', 7, 'day'); + } - /** - * Enable or disable autoscaling - * @param {boolean} enable If true, autoascaling is set true - */ - TimeStep.prototype.setAutoScale = function (enable) { - this.autoScale = enable; - }; + locale_locales__getSetGlobalLocale('en', { + ordinalParse: /\d{1,2}(th|st|nd|rd)/, + ordinal : function (number) { + var b = number % 10, + output = (toInt(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; + } + }); - /** - * 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; - } + // Side effect imports + utils_hooks__hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', locale_locales__getSetGlobalLocale); + utils_hooks__hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', locale_locales__getLocale); - //var b = asc + ds; + var mathAbs = Math.abs; - 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; + function duration_abs__abs () { + var data = this._data; - // 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; - } - }; + this._milliseconds = mathAbs(this._milliseconds); + this._days = mathAbs(this._days); + this._months = mathAbs(this._months); - /** - * 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', 'month', 'year'. - * @param {number} step Current step (1, 2, 4, 5, ... - * @return {Date} snappedDate - */ - TimeStep.snap = function (date, scale, step) { - var clone = new Date(date.valueOf()); + data.milliseconds = mathAbs(data.milliseconds); + data.seconds = mathAbs(data.seconds); + data.minutes = mathAbs(data.minutes); + data.hours = mathAbs(data.hours); + data.months = mathAbs(data.months); + data.years = mathAbs(data.years); - if (scale == 'year') { - var year = clone.getFullYear() + Math.round(clone.getMonth() / 12); - clone.setFullYear(Math.round(year / step) * step); - clone.setMonth(0); - clone.setDate(0); - clone.setHours(0); - clone.setMinutes(0); - clone.setSeconds(0); - clone.setMilliseconds(0); - } else if (scale == 'month') { - if (clone.getDate() > 15) { - clone.setDate(1); - clone.setMonth(clone.getMonth() + 1); - // important: first set Date to 1, after that change the month. - } else { - clone.setDate(1); + return this; } - clone.setHours(0); - clone.setMinutes(0); - clone.setSeconds(0); - clone.setMilliseconds(0); - } else if (scale == 'day') { - //noinspection FallthroughInSwitchStatementJS - switch (step) { - case 5: - case 2: - clone.setHours(Math.round(clone.getHours() / 24) * 24);break; - default: - clone.setHours(Math.round(clone.getHours() / 12) * 12);break; - } - clone.setMinutes(0); - clone.setSeconds(0); - clone.setMilliseconds(0); - } else if (scale == 'weekday') { - //noinspection FallthroughInSwitchStatementJS - switch (step) { - case 5: - case 2: - clone.setHours(Math.round(clone.getHours() / 12) * 12);break; - default: - clone.setHours(Math.round(clone.getHours() / 6) * 6);break; - } - clone.setMinutes(0); - clone.setSeconds(0); - clone.setMilliseconds(0); - } else if (scale == 'hour') { - switch (step) { - case 4: - clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60);break; - default: - clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30);break; - } - clone.setSeconds(0); - clone.setMilliseconds(0); - } else if (scale == 'minute') { - //noinspection FallthroughInSwitchStatementJS - switch (step) { - case 15: - case 10: - clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5); - clone.setSeconds(0); - break; - case 5: - clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60);break; - default: - clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30);break; - } - clone.setMilliseconds(0); - } else if (scale == 'second') { - //noinspection FallthroughInSwitchStatementJS - switch (step) { - case 15: - case 10: - clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5); - clone.setMilliseconds(0); - break; - case 5: - clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000);break; - default: - clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500);break; - } - } else if (scale == 'millisecond') { - var _step = step > 5 ? step / 2 : 1; - clone.setMilliseconds(Math.round(clone.getMilliseconds() / _step) * _step); - } + function duration_add_subtract__addSubtract (duration, input, value, direction) { + var other = create__createDuration(input, value); - return clone; - }; + duration._milliseconds += direction * other._milliseconds; + duration._days += direction * other._days; + duration._months += direction * other._months; - /** - * 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) { - this.switchedYear = false; - switch (this.scale) { - case 'year': - case 'month': - case 'weekday': - case 'day': - case 'hour': - case 'minute': - case 'second': - case 'millisecond': - return true; - default: - return false; + return duration._bubble(); } - } else if (this.switchedMonth == true) { - this.switchedMonth = false; - switch (this.scale) { - case 'weekday': - case 'day': - case 'hour': - case 'minute': - case 'second': - case 'millisecond': - return true; - default: - return false; + + // supports only 2.0-style add(1, 's') or add(duration) + function duration_add_subtract__add (input, value) { + return duration_add_subtract__addSubtract(this, input, value, 1); } - } else if (this.switchedDay == true) { - this.switchedDay = false; - switch (this.scale) { - case 'millisecond': - case 'second': - case 'minute': - case 'hour': - return true; - default: - return false; + + // supports only 2.0-style subtract(1, 's') or subtract(duration) + function duration_add_subtract__subtract (input, value) { + return duration_add_subtract__addSubtract(this, input, value, -1); } - } - switch (this.scale) { - case 'millisecond': - return this.current.getMilliseconds() == 0; - case 'second': - return this.current.getSeconds() == 0; - case 'minute': - return this.current.getHours() == 0 && this.current.getMinutes() == 0; - case 'hour': - return this.current.getHours() == 0; - case 'weekday': // intentional fall through - case 'day': - return this.current.getDate() == 1; - case 'month': - return this.current.getMonth() == 0; - case 'year': - return false; - default: - return false; - } - }; + function bubble () { + var milliseconds = this._milliseconds; + var days = this._days; + var months = this._months; + var data = this._data; + var seconds, minutes, hours, years = 0; - /** - * 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] custom date. if not provided, current date is taken - */ - TimeStep.prototype.getLabelMinor = function (date) { - if (date == undefined) { - date = this.current; - } + // The following code bubbles up values, see the tests for + // examples of what that means. + data.milliseconds = milliseconds % 1000; - var format = this.format.minorLabels[this.scale]; - return format && format.length > 0 ? moment(date).format(format) : ''; - }; + seconds = absFloor(milliseconds / 1000); + data.seconds = seconds % 60; - /** - * 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] custom date. if not provided, current date is taken - */ - TimeStep.prototype.getLabelMajor = function (date) { - if (date == undefined) { - date = this.current; - } + minutes = absFloor(seconds / 60); + data.minutes = minutes % 60; - var format = this.format.majorLabels[this.scale]; - return format && format.length > 0 ? moment(date).format(format) : ''; - }; + hours = absFloor(minutes / 60); + data.hours = hours % 24; - TimeStep.prototype.getClassName = function () { - var m = moment(this.current); - var date = m.locale ? m.locale('en') : m.lang('en'); // old versions of moment have .lang() function - var step = this.step; + days += absFloor(hours / 24); - function even(value) { - return value / step % 2 == 0 ? ' vis-even' : ' vis-odd'; - } + // Accurately convert days to years, assume start from year 0. + years = absFloor(daysToYears(days)); + days -= absFloor(yearsToDays(years)); - function today(date) { - if (date.isSame(new Date(), 'day')) { - return ' vis-today'; + // 30 days to a month + // TODO (iskren): Use anchor date (like 1st Jan) to compute this. + months += absFloor(days / 30); + days %= 30; + + // 12 months -> 1 year + years += absFloor(months / 12); + months %= 12; + + data.days = days; + data.months = months; + data.years = years; + + return this; } - if (date.isSame(moment().add(1, 'day'), 'day')) { - return ' vis-tomorrow'; + + function daysToYears (days) { + // 400 years have 146097 days (taking into account leap year rules) + return days * 400 / 146097; } - if (date.isSame(moment().add(-1, 'day'), 'day')) { - return ' vis-yesterday'; + + function yearsToDays (years) { + // years * 365 + absFloor(years / 4) - + // absFloor(years / 100) + absFloor(years / 400); + return years * 146097 / 400; } - return ''; - } - function currentWeek(date) { - return date.isSame(new Date(), 'week') ? ' vis-current-week' : ''; - } + function as (units) { + var days; + var months; + var milliseconds = this._milliseconds; - function currentMonth(date) { - return date.isSame(new Date(), 'month') ? ' vis-current-month' : ''; - } - - function currentYear(date) { - return date.isSame(new Date(), 'year') ? ' vis-current-year' : ''; - } - - switch (this.scale) { - case 'millisecond': - return even(date.milliseconds()).trim(); + units = normalizeUnits(units); - case 'second': - return even(date.seconds()).trim(); + if (units === 'month' || units === 'year') { + days = this._days + milliseconds / 864e5; + months = this._months + daysToYears(days) * 12; + return units === 'month' ? months : months / 12; + } else { + // handle milliseconds separately because of floating point math errors (issue #1867) + days = this._days + Math.round(yearsToDays(this._months / 12)); + switch (units) { + case 'week' : return days / 7 + milliseconds / 6048e5; + case 'day' : return days + milliseconds / 864e5; + case 'hour' : return days * 24 + milliseconds / 36e5; + case 'minute' : return days * 1440 + milliseconds / 6e4; + case 'second' : return days * 86400 + milliseconds / 1000; + // Math.floor prevents floating point math errors here + case 'millisecond': return Math.floor(days * 864e5) + milliseconds; + default: throw new Error('Unknown unit ' + units); + } + } + } - case 'minute': - return even(date.minutes()).trim(); + // TODO: Use this.as('ms')? + function duration_as__valueOf () { + return ( + this._milliseconds + + this._days * 864e5 + + (this._months % 12) * 2592e6 + + toInt(this._months / 12) * 31536e6 + ); + } - case 'hour': - var hours = date.hours(); - if (this.step == 4) { - hours = hours + '-h' + (hours + 4); - } - return 'vis-h' + hours + today(date) + even(date.hours()); + function makeAs (alias) { + return function () { + return this.as(alias); + }; + } - case 'weekday': - return 'vis-' + date.format('dddd').toLowerCase() + today(date) + currentWeek(date) + even(date.date()); + var asMilliseconds = makeAs('ms'); + var asSeconds = makeAs('s'); + var asMinutes = makeAs('m'); + var asHours = makeAs('h'); + var asDays = makeAs('d'); + var asWeeks = makeAs('w'); + var asMonths = makeAs('M'); + var asYears = makeAs('y'); - case 'day': - var day = date.date(); - var month = date.format('MMMM').toLowerCase(); - return 'vis-day' + day + ' vis-' + month + currentMonth(date) + even(day - 1); + function duration_get__get (units) { + units = normalizeUnits(units); + return this[units + 's'](); + } - case 'month': - return 'vis-' + date.format('MMMM').toLowerCase() + currentMonth(date) + even(date.month()); + function makeGetter(name) { + return function () { + return this._data[name]; + }; + } - case 'year': - var year = date.year(); - return 'vis-year' + year + currentYear(date) + even(year); + var duration_get__milliseconds = makeGetter('milliseconds'); + var seconds = makeGetter('seconds'); + var minutes = makeGetter('minutes'); + var hours = makeGetter('hours'); + var days = makeGetter('days'); + var months = makeGetter('months'); + var years = makeGetter('years'); - default: - return ''; - } - }; + function weeks () { + return absFloor(this.days() / 7); + } - module.exports = TimeStep; + var round = Math.round; + var thresholds = { + s: 45, // seconds to minute + m: 45, // minutes to hour + h: 22, // hours to day + d: 26, // days to month + M: 11 // months to year + }; -/***/ }, -/* 21 */ -/***/ function(module, exports, __webpack_require__) { + // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize + function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { + return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); + } - 'use strict'; + function duration_humanize__relativeTime (posNegDuration, withoutSuffix, locale) { + var duration = create__createDuration(posNegDuration).abs(); + var seconds = round(duration.as('s')); + var minutes = round(duration.as('m')); + var hours = round(duration.as('h')); + var days = round(duration.as('d')); + var months = round(duration.as('M')); + var years = round(duration.as('y')); - var Hammer = __webpack_require__(41); - var util = __webpack_require__(2); + var a = seconds < thresholds.s && ['s', seconds] || + minutes === 1 && ['m'] || + minutes < thresholds.m && ['mm', minutes] || + hours === 1 && ['h'] || + hours < thresholds.h && ['hh', hours] || + days === 1 && ['d'] || + days < thresholds.d && ['dd', days] || + months === 1 && ['M'] || + months < thresholds.M && ['MM', months] || + years === 1 && ['y'] || ['yy', years]; - /** - * @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 || {}; + a[2] = withoutSuffix; + a[3] = +posNegDuration > 0; + a[4] = locale; + return substituteTimeAgo.apply(null, a); + } - this.selected = false; - this.displayed = false; - this.dirty = true; + // This function allows you to set a threshold for relative time strings + function duration_humanize__getSetRelativeTimeThreshold (threshold, limit) { + if (thresholds[threshold] === undefined) { + return false; + } + if (limit === undefined) { + return thresholds[threshold]; + } + thresholds[threshold] = limit; + return true; + } - this.top = null; - this.left = null; - this.width = null; - this.height = null; - } + function humanize (withSuffix) { + var locale = this.localeData(); + var output = duration_humanize__relativeTime(this, !withSuffix, locale); - Item.prototype.stack = true; + if (withSuffix) { + output = locale.pastFuture(+this, output); + } - /** - * Select current item - */ - Item.prototype.select = function () { - this.selected = true; - this.dirty = true; - if (this.displayed) this.redraw(); - }; + return locale.postformat(output); + } - /** - * Unselect current item - */ - Item.prototype.unselect = function () { - this.selected = false; - this.dirty = true; - if (this.displayed) this.redraw(); - }; + var iso_string__abs = Math.abs; - /** - * 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.itemSet._moveToGroup(this, data.group); - } + function iso_string__toISOString() { + // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js + var Y = iso_string__abs(this.years()); + var M = iso_string__abs(this.months()); + var D = iso_string__abs(this.days()); + var h = iso_string__abs(this.hours()); + var m = iso_string__abs(this.minutes()); + var s = iso_string__abs(this.seconds() + this.milliseconds() / 1000); + var total = this.asSeconds(); - this.data = data; - this.dirty = true; - if (this.displayed) this.redraw(); - }; + if (!total) { + // this is the same as C#'s (Noda) and python (isodate)... + // but not other JS (goog.date) + return 'P0D'; + } - /** - * Set a parent for the item - * @param {ItemSet | Group} parent - */ - Item.prototype.setParent = function (parent) { - if (this.displayed) { - this.hide(); - this.parent = parent; - if (this.parent) { - this.show(); + return (total < 0 ? '-' : '') + + 'P' + + (Y ? Y + 'Y' : '') + + (M ? M + 'M' : '') + + (D ? D + 'D' : '') + + ((h || m || s) ? 'T' : '') + + (h ? h + 'H' : '') + + (m ? m + 'M' : '') + + (s ? s + 'S' : ''); } - } else { - this.parent = parent; - } - }; - - /** - * Check whether this item is visible inside given range - * @returns {{start: Number, end: Number}} range with a timestamp for start and end - * @returns {boolean} True if visible - */ - Item.prototype.isVisible = function (range) { - // Should be implemented by Item implementations - 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; - }; + var duration_prototype__proto = Duration.prototype; - /** - * Repaint the item - */ - Item.prototype.redraw = function () {}; + duration_prototype__proto.abs = duration_abs__abs; + duration_prototype__proto.add = duration_add_subtract__add; + duration_prototype__proto.subtract = duration_add_subtract__subtract; + duration_prototype__proto.as = as; + duration_prototype__proto.asMilliseconds = asMilliseconds; + duration_prototype__proto.asSeconds = asSeconds; + duration_prototype__proto.asMinutes = asMinutes; + duration_prototype__proto.asHours = asHours; + duration_prototype__proto.asDays = asDays; + duration_prototype__proto.asWeeks = asWeeks; + duration_prototype__proto.asMonths = asMonths; + duration_prototype__proto.asYears = asYears; + duration_prototype__proto.valueOf = duration_as__valueOf; + duration_prototype__proto._bubble = bubble; + duration_prototype__proto.get = duration_get__get; + duration_prototype__proto.milliseconds = duration_get__milliseconds; + duration_prototype__proto.seconds = seconds; + duration_prototype__proto.minutes = minutes; + duration_prototype__proto.hours = hours; + duration_prototype__proto.days = days; + duration_prototype__proto.weeks = weeks; + duration_prototype__proto.months = months; + duration_prototype__proto.years = years; + duration_prototype__proto.humanize = humanize; + duration_prototype__proto.toISOString = iso_string__toISOString; + duration_prototype__proto.toString = iso_string__toISOString; + duration_prototype__proto.toJSON = iso_string__toISOString; + duration_prototype__proto.locale = locale; + duration_prototype__proto.localeData = localeData; - /** - * Reposition the Item horizontally - */ - Item.prototype.repositionX = function () {}; + // Deprecations + duration_prototype__proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', iso_string__toISOString); + duration_prototype__proto.lang = lang; - /** - * Reposition the Item vertically - */ - Item.prototype.repositionY = function () {}; + // Side effect imports - /** - * 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) { - if (this.selected && this.options.editable.remove && !this.dom.deleteButton) { - // create and show button - var me = this; + addFormatToken('X', 0, 0, 'unix'); + addFormatToken('x', 0, 0, 'valueOf'); - var deleteButton = document.createElement('div'); - deleteButton.className = 'vis-delete'; - deleteButton.title = 'Delete this item'; + // PARSING - // TODO: be able to destroy the delete button - new Hammer(deleteButton).on('tap', function (event) { - event.stopPropagation(); - me.parent.removeFromDataSet(me); + addRegexToken('x', matchSigned); + addRegexToken('X', matchTimestamp); + addParseToken('X', function (input, array, config) { + config._d = new Date(parseFloat(input, 10) * 1000); + }); + addParseToken('x', function (input, array, config) { + config._d = new Date(toInt(input)); }); - 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; - } - }; - - /** - * Set HTML contents for the item - * @param {Element} element HTML element to fill with the contents - * @private - */ - Item.prototype._updateContents = function (element) { - var content; - if (this.options.template) { - var itemData = this.parent.itemSet.itemsData.get(this.id); // get a clone of the data from the dataset - content = this.options.template(itemData); - } else { - content = this.data.content; - } - - var 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); - } - } + // Side effect imports - this.content = content; - } - }; - /** - * Set HTML contents for the item - * @param {Element} element HTML element to fill with the contents - * @private - */ - Item.prototype._updateTitle = function (element) { - if (this.data.title != null) { - element.title = this.data.title || ''; - } else { - element.removeAttribute('vis-title'); - } - }; + utils_hooks__hooks.version = '2.10.3'; - /** - * 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 = []; + setHookCallback(local__createLocal); - if (Array.isArray(this.options.dataAttributes)) { - attributes = this.options.dataAttributes; - } else if (this.options.dataAttributes == 'all') { - attributes = Object.keys(this.data); - } else { - return; - } + utils_hooks__hooks.fn = momentPrototype; + utils_hooks__hooks.min = min; + utils_hooks__hooks.max = max; + utils_hooks__hooks.utc = create_utc__createUTC; + utils_hooks__hooks.unix = moment__createUnix; + utils_hooks__hooks.months = lists__listMonths; + utils_hooks__hooks.isDate = isDate; + utils_hooks__hooks.locale = locale_locales__getSetGlobalLocale; + utils_hooks__hooks.invalid = valid__createInvalid; + utils_hooks__hooks.duration = create__createDuration; + utils_hooks__hooks.isMoment = isMoment; + utils_hooks__hooks.weekdays = lists__listWeekdays; + utils_hooks__hooks.parseZone = moment__createInZone; + utils_hooks__hooks.localeData = locale_locales__getLocale; + utils_hooks__hooks.isDuration = isDuration; + utils_hooks__hooks.monthsShort = lists__listMonthsShort; + utils_hooks__hooks.weekdaysMin = lists__listWeekdaysMin; + utils_hooks__hooks.defineLocale = defineLocale; + utils_hooks__hooks.weekdaysShort = lists__listWeekdaysShort; + utils_hooks__hooks.normalizeUnits = normalizeUnits; + utils_hooks__hooks.relativeTimeThreshold = duration_humanize__getSetRelativeTimeThreshold; - for (var i = 0; i < attributes.length; i++) { - var name = attributes[i]; - var value = this.data[name]; + var _moment = utils_hooks__hooks; - if (value != null) { - element.setAttribute('data-' + name, value); - } else { - element.removeAttribute('data-' + name); - } - } - } - }; + return _moment; - /** - * Update custom styles of the element - * @param element - * @private - */ - Item.prototype._updateStyle = function (element) { - // remove old styles - if (this.style) { - util.removeCssText(element, this.style); - this.style = null; - } + })); + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10)(module))) - // append new styles - if (this.data.style) { - util.addCssText(element, this.data.style); - this.style = this.data.style; - } - }; +/***/ }, +/* 10 */ +/***/ function(module, exports, __webpack_require__) { - /** - * 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; - }; + module.exports = function(module) { + if(!module.webpackPolyfill) { + module.deprecate = function() {}; + module.paths = []; + // module.parent = undefined by default + module.children = []; + module.webpackPolyfill = 1; + } + return module; + } - module.exports = Item; - // should be implemented by the item +/***/ }, +/* 11 */ +/***/ function(module, exports, __webpack_require__) { - // should be implemented by the item + function webpackContext(req) { + throw new Error("Cannot find module '" + req + "'."); + } + webpackContext.keys = function() { return []; }; + webpackContext.resolve = webpackContext; + module.exports = webpackContext; + webpackContext.id = 11; - // should be implemented by the item /***/ }, -/* 22 */ +/* 12 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; + /* WEBPACK VAR INJECTION */(function(global) {'use strict'; - var Hammer = __webpack_require__(41); - var Item = __webpack_require__(21); - var BackgroundGroup = __webpack_require__(31); - var RangeItem = __webpack_require__(24); + var _rng; - /** - * @constructor BackgroundItem - * @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 - */ - // TODO: implement support for the BackgroundItem just having a start, then being displayed as a sort of an annotation - function BackgroundItem(data, conversion, options) { - this.props = { - content: { - width: 0 - } + var globalVar = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : null; + + if (globalVar && globalVar.crypto && crypto.getRandomValues) { + // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto + // Moderately fast, high quality + var _rnds8 = new Uint8Array(16); + _rng = function whatwgRNG() { + crypto.getRandomValues(_rnds8); + return _rnds8; }; - this.overflow = false; // if contents can overflow (css styling), this flag is set to true + } - // 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); + if (!_rng) { + // Math.random()-based (RNG) + // + // If all else fails, use Math.random(). It's fast, but is of unspecified + // quality. + var _rnds = new Array(16); + _rng = function () { + for (var i = 0, r; i < 16; i++) { + if ((i & 3) === 0) r = Math.random() * 4294967296; + _rnds[i] = r >>> ((i & 3) << 3) & 255; } - } - Item.call(this, data, conversion, options); + return _rnds; + }; } - BackgroundItem.prototype = new Item(null, null, null); - - BackgroundItem.prototype.baseClassName = 'vis-item vis-background'; - BackgroundItem.prototype.stack = false; - - /** - * Check whether this item is visible inside given range - * @returns {{start: Number, end: Number}} range with a timestamp for start and end - * @returns {boolean} True if visible - */ - BackgroundItem.prototype.isVisible = function (range) { - // determine visibility - return this.data.start < range.end && this.data.end > range.start; - }; + // uuid.js + // + // Copyright (c) 2010-2012 Robert Kieffer + // MIT License - http://opensource.org/licenses/mit-license.php - /** - * Repaint the item - */ - BackgroundItem.prototype.redraw = function () { - var dom = this.dom; - if (!dom) { - // create DOM - this.dom = {}; - dom = this.dom; + // Unique ID creation requires a high quality random # generator. We feature + // detect to determine the best RNG source, normalizing to a function that + // returns 128-bits of randomness, since that's what's usually required - // background box - dom.box = document.createElement('div'); - // className is updated in redraw() + //var _rng = require('./rng'); - // frame box (to prevent the item contents from overflowing - dom.frame = document.createElement('div'); - dom.frame.className = 'vis-item-overflow'; - dom.box.appendChild(dom.frame); + // Maps for number <-> hex string conversion + var _byteToHex = []; + var _hexToByte = {}; + for (var i = 0; i < 256; i++) { + _byteToHex[i] = (i + 256).toString(16).substr(1); + _hexToByte[_byteToHex[i]] = i; + } - // contents box - dom.content = document.createElement('div'); - dom.content.className = 'vis-item-content'; - dom.frame.appendChild(dom.content); + // **`parse()` - Parse a UUID into it's component bytes** + function parse(s, buf, offset) { + var i = buf && offset || 0, + ii = 0; - // Note: we do NOT attach this item as attribute to the DOM, - // such that background items cannot be selected - //dom.box['timeline-item'] = this; + buf = buf || []; + s.toLowerCase().replace(/[0-9a-f]{2}/g, function (oct) { + if (ii < 16) { + // Don't overflow! + buf[i + ii++] = _hexToByte[oct]; + } + }); - this.dirty = true; + // Zero out remaining bytes if string was short + while (ii < 16) { + buf[i + ii++] = 0; } - // append DOM to parent DOM - if (!this.parent) { - throw new Error('Cannot redraw item: no parent attached'); - } - if (!dom.box.parentNode) { - var background = this.parent.dom.background; - if (!background) { - throw new Error('Cannot redraw item: parent has no background container element'); - } - background.appendChild(dom.box); - } - this.displayed = true; + return buf; + } - // Update DOM when item is marked dirty. 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._updateTitle(this.dom.content); - this._updateDataAttributes(this.dom.content); - this._updateStyle(this.dom.box); + // **`unparse()` - Convert UUID byte array (ala parse()) into a string** + function unparse(buf, offset) { + var i = offset || 0, + bth = _byteToHex; + return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]]; + } - // update class - var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); - dom.box.className = this.baseClassName + className; + // **`v1()` - Generate time-based UUID** + // + // Inspired by https://github.com/LiosK/UUID.js + // and http://docs.python.org/library/uuid.html - // determine from css whether this box has overflow - this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden'; + // random #'s we need to init node and clockseq + var _seedBytes = _rng(); - // recalculate size - this.props.content.width = this.dom.content.offsetWidth; - this.height = 0; // set height zero, so this item will be ignored when stacking items + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + var _nodeId = [_seedBytes[0] | 1, _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]]; - this.dirty = false; - } - }; + // Per 4.2.2, randomize (14 bit) clockseq + var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 16383; - /** - * Show the item in the DOM (when not already visible). The items DOM will - * be created when needed. - */ - BackgroundItem.prototype.show = RangeItem.prototype.show; + // Previous uuid creation time + var _lastMSecs = 0, + _lastNSecs = 0; - /** - * Hide the item from the DOM (when visible) - * @return {Boolean} changed - */ - BackgroundItem.prototype.hide = RangeItem.prototype.hide; + // See https://github.com/broofa/node-uuid for API details + function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; - /** - * Reposition the item horizontally - * @Override - */ - BackgroundItem.prototype.repositionX = RangeItem.prototype.repositionX; + options = options || {}; - /** - * Reposition the item vertically - * @Override - */ - BackgroundItem.prototype.repositionY = function (margin) { - var onTop = this.options.orientation.item === 'top'; - this.dom.content.style.top = onTop ? '' : '0'; - this.dom.content.style.bottom = onTop ? '0' : ''; - var height; + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; - // special positioning for subgroups - if (this.data.subgroup !== undefined) { - // TODO: instead of calculating the top position of the subgroups here for every BackgroundItem, calculate the top of the subgroup once in Itemset + // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); - var itemSubgroup = this.data.subgroup; - var subgroups = this.parent.subgroups; - var subgroupIndex = subgroups[itemSubgroup].index; - // if the orientation is top, we need to take the difference in height into account. - if (onTop == true) { - // the first subgroup will have to account for the distance from the top to the first item. - height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical; - height += subgroupIndex == 0 ? margin.axis - 0.5 * margin.item.vertical : 0; - var newTop = this.parent.top; - for (var subgroup in subgroups) { - if (subgroups.hasOwnProperty(subgroup)) { - if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroupIndex) { - newTop += subgroups[subgroup].height + margin.item.vertical; - } - } - } + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - // the others will have to be offset downwards with this same distance. - newTop += subgroupIndex != 0 ? margin.axis - 0.5 * margin.item.vertical : 0; - this.dom.box.style.top = newTop + 'px'; - this.dom.box.style.bottom = ''; - } - // and when the orientation is bottom: - else { - var newTop = this.parent.top; - var totalHeight = 0; - for (var subgroup in subgroups) { - if (subgroups.hasOwnProperty(subgroup)) { - if (subgroups[subgroup].visible == true) { - var newHeight = subgroups[subgroup].height + margin.item.vertical; - totalHeight += newHeight; - if (subgroups[subgroup].index > subgroupIndex) { - newTop += newHeight; - } - } - } - } - height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical; - this.dom.box.style.top = this.parent.height - totalHeight + newTop + 'px'; - this.dom.box.style.bottom = ''; - } + // Time since last uuid creation (in msecs) + var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; + + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 16383; } - // and in the case of no subgroups: - else { - // we want backgrounds with groups to only show in groups. - if (this.parent instanceof BackgroundGroup) { - // if the item is not in a group: - height = Math.max(this.parent.height, this.parent.itemSet.body.domProps.center.height, this.parent.itemSet.body.domProps.centerContainer.height); - this.dom.box.style.top = onTop ? '0' : ''; - this.dom.box.style.bottom = onTop ? '' : '0'; - } else { - height = this.parent.height; - // same alignment for items when orientation is top or bottom - this.dom.box.style.top = this.parent.top + 'px'; - this.dom.box.style.bottom = ''; - } + + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; } - this.dom.box.style.height = height + 'px'; - }; - module.exports = BackgroundItem; + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + } -/***/ }, -/* 23 */ -/***/ function(module, exports, __webpack_require__) { + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; - 'use strict'; + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; - var Item = __webpack_require__(21); + // `time_low` + var tl = ((msecs & 268435455) * 10000 + nsecs) % 4294967296; + b[i++] = tl >>> 24 & 255; + b[i++] = tl >>> 16 & 255; + b[i++] = tl >>> 8 & 255; + b[i++] = tl & 255; - /** - * @constructor PointItem - * @extends Item - * @param {Object} data Object containing parameters start - * content, 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 PointItem(data, conversion, options) { - this.props = { - dot: { - top: 0, - width: 0, - height: 0 - }, - content: { - height: 0, - marginLeft: 0 - } - }; + // `time_mid` + var tmh = msecs / 4294967296 * 10000 & 268435455; + b[i++] = tmh >>> 8 & 255; + b[i++] = tmh & 255; - // validate data - if (data) { - if (data.start == undefined) { - throw new Error('Property "start" missing in item ' + data); - } - } + // `time_high_and_version` + b[i++] = tmh >>> 24 & 15 | 16; // include version + b[i++] = tmh >>> 16 & 255; - Item.call(this, data, conversion, options); - } + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 128; - PointItem.prototype = new Item(null, null, null); + // `clock_seq_low` + b[i++] = clockseq & 255; - /** - * Check whether this item is visible inside given range - * @returns {{start: Number, end: Number}} range with a timestamp for start and end - * @returns {boolean} True if visible - */ - PointItem.prototype.isVisible = function (range) { - // determine visibility - // TODO: account for the real width of the item. Right now we just add 1/4 to the window - var interval = (range.end - range.start) / 4; - return this.data.start > range.start - interval && this.data.start < range.end + interval; - }; + // `node` + var node = options.node || _nodeId; + for (var n = 0; n < 6; n++) { + b[i + n] = node[n]; + } - /** - * Repaint the item - */ - PointItem.prototype.redraw = function () { - var dom = this.dom; - if (!dom) { - // create DOM - this.dom = {}; - dom = this.dom; + return buf ? buf : unparse(b); + } - // background box - dom.point = document.createElement('div'); - // className is updated in redraw() + // **`v4()` - Generate random UUID** - // contents box, right from the dot - dom.content = document.createElement('div'); - dom.content.className = 'vis-item-content'; - dom.point.appendChild(dom.content); + // See https://github.com/broofa/node-uuid for API details + function v4(options, buf, offset) { + // Deprecated - 'format' argument, as supported in v1.2 + var i = buf && offset || 0; - // dot at start - dom.dot = document.createElement('div'); - dom.point.appendChild(dom.dot); + if (typeof options == 'string') { + buf = options == 'binary' ? new Array(16) : null; + options = null; + } + options = options || {}; - // attach this item as attribute - dom.point['timeline-item'] = this; + var rnds = options.random || (options.rng || _rng)(); - this.dirty = true; - } + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; - // append DOM to parent DOM - if (!this.parent) { - throw new Error('Cannot redraw item: no parent attached'); - } - if (!dom.point.parentNode) { - var foreground = this.parent.dom.foreground; - if (!foreground) { - throw new Error('Cannot redraw item: parent has no foreground container element'); + // Copy bytes to buffer, if provided + if (buf) { + for (var ii = 0; ii < 16; ii++) { + buf[i + ii] = rnds[ii]; } - foreground.appendChild(dom.point); } - this.displayed = true; - - // Update DOM when item is marked dirty. 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._updateTitle(this.dom.point); - this._updateDataAttributes(this.dom.point); - this._updateStyle(this.dom.point); - // update class - var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); - dom.point.className = 'vis-item vis-point' + className; - dom.dot.className = 'vis-item vis-dot' + className; - - // recalculate size - this.width = dom.point.offsetWidth; - this.height = dom.point.offsetHeight; - this.props.dot.width = dom.dot.offsetWidth; - this.props.dot.height = dom.dot.offsetHeight; - this.props.content.height = dom.content.offsetHeight; + return buf || unparse(rnds); + } - // resize contents - dom.content.style.marginLeft = 2 * this.props.dot.width + 'px'; - //dom.content.style.marginRight = ... + 'px'; // TODO: margin right + // Export public API + var uuid = v4; + uuid.v1 = v1; + uuid.v4 = v4; + uuid.parse = parse; + uuid.unparse = unparse; - dom.dot.style.top = (this.height - this.props.dot.height) / 2 + 'px'; - dom.dot.style.left = this.props.dot.width / 2 + 'px'; + module.exports = uuid; + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - this.dirty = false; - } +/***/ }, +/* 13 */ +/***/ function(module, exports, __webpack_require__) { - this._repaintDeleteButton(dom.point); - }; + // DOM utility methods /** - * Show the item in the DOM (when not already visible). The items DOM will - * be created when needed. + * this prepares the JSON container for allocating SVG elements + * @param JSONcontainer + * @private */ - PointItem.prototype.show = function () { - if (!this.displayed) { - this.redraw(); - } - }; + 'use strict'; - /** - * Hide the item from the DOM (when visible) - */ - PointItem.prototype.hide = function () { - if (this.displayed) { - if (this.dom.point.parentNode) { - this.dom.point.parentNode.removeChild(this.dom.point); + 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.displayed = false; } }; /** - * Reposition the item horizontally - * @Override + * 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 JSONcontainer + * @private */ - PointItem.prototype.repositionX = function () { - var start = this.conversion.toScreen(this.data.start); - - this.left = start - this.props.dot.width; - - // reposition point - this.dom.point.style.left = this.left + 'px'; + 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 = []; + } + } + } }; /** - * Reposition the item vertically - * @Override + * 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 elementType + * @param JSONcontainer + * @param svgContainer + * @returns {*} + * @private */ - PointItem.prototype.repositionY = function () { - var orientation = this.options.orientation.item; - var point = this.dom.point; - - if (orientation == 'top') { - point.style.top = this.top + 'px'; + 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 { - point.style.top = this.parent.height - this.top - this.height + 'px'; + // 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; }; - module.exports = PointItem; - -/***/ }, -/* 24 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var Hammer = __webpack_require__(41); - var Item = __webpack_require__(21); - /** - * @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 + * 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 elementType + * @param JSONcontainer + * @param DOMContainer + * @returns {*} + * @private */ - 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 - - // validate data - if (data) { - if (data.start == undefined) { - throw new Error('Property "start" missing in item ' + data.id); + 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); + } } - if (data.end == undefined) { - throw new Error('Property "end" missing in item ' + data.id); + } 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); } } - - 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 - * @returns {{start: Number, end: Number}} 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; + JSONcontainer[elementType].used.push(element); + return element; }; /** - * Repaint the item + * draw a point object. this is a seperate 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 x + * @param y + * @param group + * @param JSONcontainer + * @param svgContainer + * @param labelObj + * @returns {*} */ - RangeItem.prototype.redraw = function () { - var dom = this.dom; - if (!dom) { - // create DOM - this.dom = {}; - dom = this.dom; - - // background box - dom.box = document.createElement('div'); - // className is updated in redraw() - - // frame box (to prevent the item contents from overflowing - dom.frame = document.createElement('div'); - dom.frame.className = 'vis-item-overflow'; - dom.box.appendChild(dom.frame); - - // contents box - dom.content = document.createElement('div'); - dom.content.className = 'vis-item-content'; - dom.frame.appendChild(dom.content); - - // attach this item as attribute - dom.box['timeline-item'] = this; - - this.dirty = true; + exports.drawPoint = function (x, y, group, JSONcontainer, svgContainer, labelObj) { + var point; + if (group.options.drawPoints.style == 'circle') { + point = exports.getSVGElement('circle', JSONcontainer, svgContainer); + point.setAttributeNS(null, 'cx', x); + point.setAttributeNS(null, 'cy', y); + point.setAttributeNS(null, 'r', 0.5 * group.options.drawPoints.size); + } else { + point = exports.getSVGElement('rect', JSONcontainer, svgContainer); + point.setAttributeNS(null, 'x', x - 0.5 * group.options.drawPoints.size); + point.setAttributeNS(null, 'y', y - 0.5 * group.options.drawPoints.size); + point.setAttributeNS(null, 'width', group.options.drawPoints.size); + point.setAttributeNS(null, 'height', group.options.drawPoints.size); } - // append DOM to parent DOM - if (!this.parent) { - throw new Error('Cannot redraw item: no parent attached'); - } - if (!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(dom.box); + if (group.options.drawPoints.styles !== undefined) { + point.setAttributeNS(null, 'style', group.group.options.drawPoints.styles); } - this.displayed = true; - - // Update DOM when item is marked dirty. 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._updateTitle(this.dom.box); - this._updateDataAttributes(this.dom.box); - this._updateStyle(this.dom.box); - - // update class - var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); - dom.box.className = this.baseClassName + className; + point.setAttributeNS(null, 'class', group.className + ' vis-point'); + //handle label - // determine from css whether this box has overflow - this.overflow = window.getComputedStyle(dom.frame).overflow !== 'hidden'; + if (labelObj) { + var label = exports.getSVGElement('text', JSONcontainer, svgContainer); + if (labelObj.xOffset) { + x = x + labelObj.xOffset; + } - // recalculate size - // 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'; - this.props.content.width = this.dom.content.offsetWidth; - this.height = this.dom.box.offsetHeight; - this.dom.content.style.maxWidth = ''; + if (labelObj.yOffset) { + y = y + labelObj.yOffset; + } + if (labelObj.content) { + label.textContent = labelObj.content; + } - this.dirty = false; + if (labelObj.className) { + label.setAttributeNS(null, 'class', labelObj.className + ' vis-label'); + } + label.setAttributeNS(null, 'x', x); + label.setAttributeNS(null, 'y', y); } - this._repaintDeleteButton(dom.box); - this._repaintDragLeft(); - this._repaintDragRight(); + return point; }; /** - * Show the item in the DOM (when not already visible). The items DOM will - * be created when needed. + * draw a bar SVG element centered on the X coordinate + * + * @param x + * @param y + * @param className */ - RangeItem.prototype.show = function () { - if (!this.displayed) { - this.redraw(); + 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); + } } }; - /** - * Hide the item from the DOM (when visible) - * @return {Boolean} changed - */ - RangeItem.prototype.hide = function () { - if (this.displayed) { - var box = this.dom.box; +/***/ }, +/* 14 */ +/***/ function(module, exports, __webpack_require__) { - if (box.parentNode) { - box.parentNode.removeChild(box); - } + 'use strict'; - this.displayed = false; - } - }; + var util = __webpack_require__(7); + var Queue = __webpack_require__(15); /** - * 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 + * DataSet + * + * 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. 2 * parentWidth) { - end = 2 * parentWidth; + this._options = options || {}; + this._data = {}; // map with data indexed by id + this.length = 0; // number of items in the DataSet + this._fieldId = this._options.fieldId || 'id'; // name of the field containing id + this._type = {}; // internal field types (NOTE: this can differ from this._options.type) + + // all variants of a Date are internally stored as Date, so we can convert + // from everything to everything (also from ISODate to Number for example) + if (this._options.type) { + for (var field in this._options.type) { + if (this._options.type.hasOwnProperty(field)) { + var value = this._options.type[field]; + if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') { + this._type[field] = 'Date'; + } else { + this._type[field] = value; + } + } } } - var boxWidth = Math.max(end - start, 1); - - if (this.overflow) { - 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 { - this.left = start; - this.width = boxWidth; - contentWidth = Math.min(end - start, this.props.content.width); + // TODO: deprecated since version 1.1.1 (or 2.0.0?) + if (this._options.convert) { + throw new Error('Option "convert" is deprecated. Use "type" instead.'); } - this.dom.box.style.left = this.left + 'px'; - this.dom.box.style.width = boxWidth + 'px'; + this._subscribers = {}; // event subscribers - switch (this.options.align) { - case 'left': - this.dom.content.style.left = '0'; - break; + // add initial data when provided + if (data) { + this.add(data); + } - case 'right': - this.dom.content.style.left = Math.max(boxWidth - contentWidth, 0) + 'px'; - break; + this.setOptions(options); + } - case 'center': - this.dom.content.style.left = Math.max((boxWidth - contentWidth) / 2, 0) + 'px'; - break; + /** + * @param {Object} [options] Available options: + * {Object} queue Queue changes to the DataSet, + * flush them all at once. + * Queue options: + * - {number} delay Delay in ms, null by default + * - {number} max Maximum number of entries in the queue, Infinity by default + * @param options + */ + DataSet.prototype.setOptions = function (options) { + if (options && options.queue !== undefined) { + if (options.queue === false) { + // delete queue if loaded + if (this._queue) { + this._queue.destroy(); + delete this._queue; + } + } else { + // create queue and update its options + if (!this._queue) { + this._queue = Queue.extend(this, { + replace: ['add', 'update', 'remove'] + }); + } - 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) { - contentLeft = Math.max(-start, 0); - } else { - contentLeft = -contentWidth; // ensure it's not visible anymore - } - } else { - if (start < 0) { - contentLeft = -start; - } else { - contentLeft = 0; - } + if (typeof options.queue === 'object') { + this._queue.setOptions(options.queue); } - this.dom.content.style.left = contentLeft + 'px'; + } } }; /** - * Reposition the item vertically - * @Override + * Subscribe to an event, add an event listener + * @param {String} event Event name. Available events: 'put', 'update', + * 'remove' + * @param {function} callback Callback method. Called with three parameters: + * {String} event + * {Object | null} params + * {String | Number} senderId */ - 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'; + DataSet.prototype.on = function (event, callback) { + var subscribers = this._subscribers[event]; + if (!subscribers) { + subscribers = []; + this._subscribers[event] = subscribers; } - }; - /** - * 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.editable.updateTime && !this.dom.dragLeft) { - // create and show drag area - var dragLeft = document.createElement('div'); - dragLeft.className = 'vis-drag-left'; - dragLeft.dragLeftItem = this; + subscribers.push({ + callback: callback + }); + }; - this.dom.box.appendChild(dragLeft); - this.dom.dragLeft = dragLeft; - } else if (!this.selected && this.dom.dragLeft) { - // delete drag area - if (this.dom.dragLeft.parentNode) { - this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft); - } - this.dom.dragLeft = null; - } + // TODO: remove this deprecated function some day (replaced with `on` since version 0.5, deprecated since v4.0) + DataSet.prototype.subscribe = function () { + throw new Error('DataSet.subscribe is deprecated. Use DataSet.on instead.'); }; /** - * Repaint a drag area on the right side of the range when the range is selected - * @protected + * Unsubscribe from an event, remove an event listener + * @param {String} event + * @param {function} callback */ - RangeItem.prototype._repaintDragRight = function () { - if (this.selected && 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.dom.dragRight) { - // delete drag area - if (this.dom.dragRight.parentNode) { - this.dom.dragRight.parentNode.removeChild(this.dom.dragRight); - } - this.dom.dragRight = null; + DataSet.prototype.off = function (event, callback) { + var subscribers = this._subscribers[event]; + if (subscribers) { + this._subscribers[event] = subscribers.filter(function (listener) { + return listener.callback != callback; + }); } }; - module.exports = RangeItem; - -/***/ }, -/* 25 */ -/***/ function(module, exports, __webpack_require__) { + // TODO: remove this deprecated function some day (replaced with `on` since version 0.5, deprecated since v4.0) + DataSet.prototype.unsubscribe = function () { + throw new Error('DataSet.unsubscribe is deprecated. Use DataSet.off instead.'); + }; /** - * Prototype for visual components - * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body] - * @param {Object} [options] - */ - "use strict"; - - function Component(body, options) { - this.options = null; - this.props = null; - } - - /** - * Set options for the component. The new options will be merged into the - * current options. - * @param {Object} options + * Trigger an event + * @param {String} event + * @param {Object | null} params + * @param {String} [senderId] Optional id of the sender. + * @private */ - Component.prototype.setOptions = function (options) { - if (options) { - util.extend(this.options, options); + DataSet.prototype._trigger = function (event, params, senderId) { + if (event == '*') { + throw new Error('Cannot trigger event *'); } - }; - /** - * Repaint the component - * @return {boolean} Returns true if the component is resized - */ - Component.prototype.redraw = function () { - // should be implemented by the component - return false; + var subscribers = []; + if (event in this._subscribers) { + subscribers = subscribers.concat(this._subscribers[event]); + } + if ('*' in this._subscribers) { + subscribers = subscribers.concat(this._subscribers['*']); + } + + for (var i = 0; i < subscribers.length; i++) { + var subscriber = subscribers[i]; + if (subscriber.callback) { + subscriber.callback(event, params, senderId || null); + } + } }; /** - * Destroy the component. Cleanup DOM and event listeners + * Add data. + * Adding an item will fail when there already is an item with the same id. + * @param {Object | Array} data + * @param {String} [senderId] Optional sender id + * @return {Array} addedIds Array with the ids of the added items */ - Component.prototype.destroy = function () {}; + DataSet.prototype.add = function (data, senderId) { + var addedIds = [], + id, + me = this; - /** - * 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; + 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 instanceof Object) { + // Single item + id = me._addItem(data); + addedIds.push(id); + } else { + throw new Error('Unknown dataType'); + } - this.props._previousWidth = this.props.width; - this.props._previousHeight = this.props.height; + if (addedIds.length) { + this._trigger('add', { items: addedIds }, senderId); + } - return resized; + return addedIds; }; - module.exports = Component; - - // should be implemented by the component - -/***/ }, -/* 26 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var util = __webpack_require__(2); - var Component = __webpack_require__(25); - var moment = __webpack_require__(40); - var locales = __webpack_require__(50); - /** - * A current time bar - * @param {{range: Range, dom: Object, domProps: Object}} body - * @param {Object} [options] Available parameters: - * {Boolean} [showCurrentTime] - * @constructor CurrentTime - * @extends Component + * 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 */ - function CurrentTime(body, options) { - this.body = body; - - // default options - this.defaultOptions = { - showCurrentTime: true, + DataSet.prototype.update = function (data, senderId) { + var addedIds = []; + var updatedIds = []; + var updatedData = []; + var me = this; + var fieldId = me._fieldId; - locales: locales, - locale: 'en' + var addOrUpdate = function addOrUpdate(item) { + var id = item[fieldId]; + if (me._data[id]) { + // update item + id = me._updateItem(item); + updatedIds.push(id); + updatedData.push(item); + } else { + // add new item + id = me._addItem(item); + addedIds.push(id); + } }; - this.options = util.extend({}, this.defaultOptions); - this.offset = 0; - - this._create(); - - this.setOptions(options); - } - CurrentTime.prototype = new Component(); + if (Array.isArray(data)) { + // Array + for (var i = 0, len = data.length; i < len; i++) { + addOrUpdate(data[i]); + } + } else if (data instanceof Object) { + // Single item + addOrUpdate(data); + } else { + throw new Error('Unknown dataType'); + } - /** - * 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%'; + if (addedIds.length) { + this._trigger('add', { items: addedIds }, senderId); + } + if (updatedIds.length) { + this._trigger('update', { items: updatedIds, data: updatedData }, senderId); + } - this.bar = bar; + return addedIds.concat(updatedIds); }; /** - * Destroy the CurrentTime bar + * 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. + * @throws Error */ - CurrentTime.prototype.destroy = function () { - this.options.showCurrentTime = false; - this.redraw(); // will remove the bar from the DOM and stop refreshing + DataSet.prototype.get = function (args) { + var me = this; - this.body = null; - }; + // 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]; + } - /** - * 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(['showCurrentTime', 'locale', 'locales'], this.options, options); + // 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'; } - }; - /** - * 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); + // build options + var type = options && options.type || this._options.type; + var filter = options && options.filter; + var items = [], + item, + itemId, + i, + len; - this.start(); + // convert items + if (id != undefined) { + // return a single item + item = me._getItem(id, type); + if (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 + for (itemId in this._data) { + if (this._data.hasOwnProperty(itemId)) { + item = me._getItem(itemId, type); + if (!filter || filter(item)) { + items.push(item); + } + } } + } - var now = new Date(new Date().valueOf() + this.offset); - var x = this.body.util.toScreen(now); + // order the results + if (options && options.order && id == undefined) { + this._sort(items, options.order); + } - 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.html#Localization'); - this.warned = true; + // 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); } - locale = this.options.locales['en']; // fall back on english when not available } - var title = locale.current + ' ' + locale.time + ': ' + moment(now).format('dddd, MMMM Do YYYY, H:mm:ss'); - title = title.charAt(0).toUpperCase() + title.substring(1); + } - this.bar.style.left = x + 'px'; - this.bar.title = title; + // return the results + if (returnType == 'Object') { + var result = {}; + for (i = 0; i < items.length; i++) { + result[items[i].id] = items[i]; + } + return result; } else { - // remove the line from the DOM - if (this.bar.parentNode) { - this.bar.parentNode.removeChild(this.bar); + if (id != undefined) { + // a single item + return item; + } else { + // just return our array + return items; } - this.stop(); } - - return false; }; /** - * Start auto refreshing the current time bar + * 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 */ - CurrentTime.prototype.start = function () { - var me = this; + DataSet.prototype.getIds = function (options) { + var data = this._data, + filter = options && options.filter, + order = options && options.order, + type = options && options.type || this._options.type, + i, + len, + id, + item, + items, + ids = []; - function update() { - me.stop(); + if (filter) { + // get filtered items + if (order) { + // create ordered list + items = []; + for (id in data) { + if (data.hasOwnProperty(id)) { + item = this._getItem(id, type); + if (filter(item)) { + items.push(item); + } + } + } - // 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; + this._sort(items, order); - me.redraw(); + for (i = 0, len = items.length; i < len; i++) { + ids[i] = items[i][this._fieldId]; + } + } else { + // create unordered list + for (id in data) { + if (data.hasOwnProperty(id)) { + 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 (id in data) { + if (data.hasOwnProperty(id)) { + items.push(data[id]); + } + } - // start a renderTimer to adjust for the new time - me.currentTimeTimer = setTimeout(update, interval); + this._sort(items, order); + + for (i = 0, len = items.length; i < len; i++) { + ids[i] = items[i][this._fieldId]; + } + } else { + // create unordered list + for (id in data) { + if (data.hasOwnProperty(id)) { + item = data[id]; + ids.push(item[this._fieldId]); + } + } + } } - update(); + return ids; }; /** - * Stop auto refreshing the current time bar + * Returns the DataSet itself. Is overwritten for example by the DataView, + * which returns the DataSet it is connected to instead. */ - CurrentTime.prototype.stop = function () { - if (this.currentTimeTimer !== undefined) { - clearTimeout(this.currentTimeTimer); - delete this.currentTimeTimer; - } + DataSet.prototype.getDataSet = function () { + return this; }; /** - * 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. + * 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. */ - CurrentTime.prototype.setCurrentTime = function (time) { - var t = util.convert(time, 'Date').valueOf(); - var now = new Date().valueOf(); - this.offset = t - now; - this.redraw(); + DataSet.prototype.forEach = function (callback, options) { + var filter = options && options.filter, + type = options && options.type || this._options.type, + data = this._data, + item, + id; + + if (options && options.order) { + // execute forEach on ordered list + var items = this.get(options); + + for (var i = 0, len = items.length; i < len; i++) { + item = items[i]; + id = item[this._fieldId]; + callback(item, id); + } + } else { + // unordered + for (id in data) { + if (data.hasOwnProperty(id)) { + item = this._getItem(id, type); + if (!filter || filter(item)) { + callback(item, id); + } + } + } + } }; /** - * Get the current time. - * @return {Date} Returns the current time. + * 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 */ - CurrentTime.prototype.getCurrentTime = function () { - return new Date(new Date().valueOf() + this.offset); - }; - - module.exports = CurrentTime; + DataSet.prototype.map = function (callback, options) { + var filter = options && options.filter, + type = options && options.type || this._options.type, + mappedItems = [], + data = this._data, + item; -/***/ }, -/* 27 */ -/***/ function(module, exports, __webpack_require__) { + // convert and filter items + for (var id in data) { + if (data.hasOwnProperty(id)) { + item = this._getItem(id, type); + if (!filter || filter(item)) { + mappedItems.push(callback(item, id)); + } + } + } - 'use strict'; + // order items + if (options && options.order) { + this._sort(mappedItems, options.order); + } - var Hammer = __webpack_require__(41); - var util = __webpack_require__(2); - var Component = __webpack_require__(25); - var moment = __webpack_require__(40); - var locales = __webpack_require__(50); + return mappedItems; + }; /** - * 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; + * 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; + } - // default options - this.defaultOptions = { - locales: locales, - locale: 'en', - id: undefined - }; - this.options = util.extend({}, this.defaultOptions); + var filteredItem = {}; - if (options && options.time) { - this.customTime = options.time; + if (Array.isArray(fields)) { + for (var field in item) { + if (item.hasOwnProperty(field) && fields.indexOf(field) != -1) { + filteredItem[field] = item[field]; + } + } } else { - this.customTime = new Date(); + for (var field in item) { + if (item.hasOwnProperty(field) && fields.hasOwnProperty(field)) { + filteredItem[fields[field]] = item[field]; + } + } } - 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(['locale', 'locales', 'id'], this.options, options); - } + return filteredItem; }; /** - * Create the DOM for the custom time + * Sort the provided array with items + * @param {Object[]} items + * @param {String | function} order A field name or custom sort function. * @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'; - 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)); - // TODO: cleanup - //this.hammer.on('pan', function (event) { - // event.preventDefault(); - //}); + 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'); + } }; /** - * Destroy the CustomTime bar + * 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 */ - CustomTime.prototype.destroy = function () { - this.hide(); + DataSet.prototype.remove = function (id, senderId) { + var removedIds = [], + i, + len, + removedId; - this.hammer.destroy(); - this.hammer = null; + if (Array.isArray(id)) { + for (i = 0, len = id.length; i < len; i++) { + removedId = this._remove(id[i]); + if (removedId != null) { + removedIds.push(removedId); + } + } + } else { + removedId = this._remove(id); + if (removedId != null) { + removedIds.push(removedId); + } + } - this.body = null; + if (removedIds.length) { + this._trigger('remove', { items: removedIds }, senderId); + } + + return removedIds; }; /** - * Repaint the component - * @return {boolean} Returns true if the component is resized + * Remove an item by its id + * @param {Number | String | Object} id id or item + * @returns {Number | String | null} id + * @private */ - 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); + DataSet.prototype._remove = function (id) { + if (util.isNumber(id) || util.isString(id)) { + if (this._data[id]) { + delete this._data[id]; + this.length--; + return id; + } + } else if (id instanceof Object) { + var itemId = id[this._fieldId]; + if (itemId && this._data[itemId]) { + delete this._data[itemId]; + this.length--; + return itemId; } - parent.appendChild(this.bar); } + return null; + }; - var x = this.body.util.toScreen(this.customTime); + /** + * Clear the data + * @param {String} [senderId] Optional sender id + * @return {Array} removedIds The ids of all removed items + */ + DataSet.prototype.clear = function (senderId) { + var ids = Object.keys(this._data); - 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.html#Localization'); - this.warned = true; - } - locale = this.options.locales['en']; // fall back on english when not available - } - var title = locale.time + ': ' + moment(this.customTime).format('dddd, MMMM Do YYYY, H:mm:ss'); - title = title.charAt(0).toUpperCase() + title.substring(1); + this._data = {}; + this.length = 0; - this.bar.style.left = x + 'px'; - this.bar.title = title; + this._trigger('remove', { items: ids }, senderId); - return false; + return ids; }; /** - * Remove the CustomTime from the DOM + * 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 */ - CustomTime.prototype.hide = function () { - // remove the line from the DOM - if (this.bar.parentNode) { - this.bar.parentNode.removeChild(this.bar); + DataSet.prototype.max = function (field) { + var data = this._data, + max = null, + maxField = null; + + for (var id in data) { + if (data.hasOwnProperty(id)) { + var item = data[id]; + var itemField = item[field]; + if (itemField != null && (!max || itemField > maxField)) { + max = item; + maxField = itemField; + } + } } - }; - /** - * Set custom time. - * @param {Date | number | string} time - */ - CustomTime.prototype.setCustomTime = function (time) { - this.customTime = util.convert(time, 'Date'); - this.redraw(); + return max; }; /** - * Retrieve the current custom time. - * @return {Date} customTime + * 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 */ - CustomTime.prototype.getCustomTime = function () { - return new Date(this.customTime.valueOf()); + DataSet.prototype.min = function (field) { + var data = this._data, + min = null, + minField = null; + + for (var id in data) { + if (data.hasOwnProperty(id)) { + var item = data[id]; + var itemField = item[field]; + if (itemField != null && (!min || itemField < minField)) { + min = item; + minField = itemField; + } + } + } + + return min; }; /** - * Start moving horizontally - * @param {Event} event - * @private + * 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. */ - CustomTime.prototype._onDragStart = function (event) { - this.eventParams.dragging = true; - this.eventParams.customTime = this.customTime; + DataSet.prototype.distinct = function (field) { + var data = this._data; + var values = []; + var fieldType = this._options.type && this._options.type[field] || null; + var count = 0; + var i; - event.stopPropagation(); + for (var prop in data) { + if (data.hasOwnProperty(prop)) { + var item = data[prop]; + var value = item[field]; + var exists = false; + for (i = 0; i < count; i++) { + if (values[i] == value) { + exists = true; + break; + } + } + if (!exists && value !== undefined) { + values[count] = value; + count++; + } + } + } + + if (fieldType) { + for (i = 0; i < values.length; i++) { + values[i] = util.convert(values[i], fieldType); + } + } + + return values; }; /** - * Perform moving operating. - * @param {Event} event + * Add a single item. Will fail when an item with the same id already exists. + * @param {Object} item + * @return {String} id * @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); + DataSet.prototype._addItem = function (item) { + var id = item[this._fieldId]; - this.setCustomTime(time); + 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; + } - // fire a timechange event - this.body.emitter.emit('timechange', { - id: this.options.id, - time: new Date(this.customTime.valueOf()) - }); + var d = {}; + for (var field in item) { + if (item.hasOwnProperty(field)) { + var fieldType = this._type[field]; // type may be undefined + d[field] = util.convert(item[field], fieldType); + } + } + this._data[id] = d; + this.length++; - event.stopPropagation(); + return id; }; /** - * Stop moving operating. - * @param {Event} event + * 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 */ - CustomTime.prototype._onDragEnd = function (event) { - if (!this.eventParams.dragging) return; + DataSet.prototype._getItem = function (id, types) { + var field, value; - // fire a timechanged event - this.body.emitter.emit('timechanged', { - id: this.options.id, - time: new Date(this.customTime.valueOf()) - }); + // get the item from the dataset + var raw = this._data[id]; + if (!raw) { + return null; + } - event.stopPropagation(); + // convert the items field types + var converted = {}; + if (types) { + for (field in raw) { + if (raw.hasOwnProperty(field)) { + value = raw[field]; + converted[field] = util.convert(value, types[field]); + } + } + } else { + // no field types specified, no converting needed + for (field in raw) { + if (raw.hasOwnProperty(field)) { + value = raw[field]; + converted[field] = value; + } + } + } + return converted; }; /** - * 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 + * 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 */ - CustomTime.customTimeFromTarget = function (event) { - var target = event.target; - while (target) { - if (target.hasOwnProperty('custom-time')) { - return target['custom-time']; + DataSet.prototype._updateItem = function (item) { + var id = item[this._fieldId]; + if (id == undefined) { + throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(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 + for (var field in item) { + if (item.hasOwnProperty(field)) { + var fieldType = this._type[field]; // type may be undefined + d[field] = util.convert(item[field], fieldType); } - target = target.parentNode; } - return null; + return id; }; - module.exports = CustomTime; + module.exports = DataSet; /***/ }, -/* 28 */ +/* 15 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; - - var util = __webpack_require__(2); - var DOMutil = __webpack_require__(3); - var Component = __webpack_require__(25); - var DataStep = __webpack_require__(17); - /** - * A horizontal time axis - * @param {Object} [options] See DataAxis.setOptions for the available - * options. - * @constructor DataAxis - * @extends Component - * @param body + * 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 */ - function DataAxis(body, options, svg, linegraphOptions) { - this.id = util.randomUUID(); - this.body = body; - - this.defaultOptions = { - orientation: 'left', // supported: 'left', 'right' - showMinorLabels: true, - showMajorLabels: true, - icons: true, - majorLinesOffset: 7, - minorLinesOffset: 4, - labelOffsetX: 10, - labelOffsetY: 2, - iconWidth: 20, - width: '40px', - visible: true, - alignZeros: true, - left: { - range: { min: undefined, max: undefined }, - format: function format(value) { - return value; - }, - title: { text: undefined, style: undefined } - }, - right: { - range: { min: undefined, max: undefined }, - format: function format(value) { - return value; - }, - title: { text: undefined, style: undefined } - } - }; - - this.linegraphOptions = linegraphOptions; - this.linegraphSVG = svg; - this.props = {}; - this.DOMelements = { // dynamic elements - lines: {}, - labels: {}, - title: {} - }; - - this.dom = {}; + 'use strict'; - this.range = { start: 0, end: 0 }; + function Queue(options) { + // options + this.delay = null; + this.max = Infinity; - this.options = util.extend({}, this.defaultOptions); - this.conversionFactor = 1; + // properties + this._queue = []; + this._timeout = null; + this._extended = null; this.setOptions(options); - this.width = Number(('' + this.options.width).replace('px', '')); - this.minWidth = this.width; - this.height = this.linegraphSVG.offsetHeight; - this.hidden = false; - - this.stepPixels = 25; - this.zeroCrossing = -1; - this.amountOfSteps = -1; - - this.lineOffset = 0; - this.master = true; - this.svgElements = {}; - this.iconsRemoved = false; - - this.groups = {}; - this.amountOfGroups = 0; - - // create the HTML DOM - this._create(); - - var me = this; - this.body.emitter.on('verticalDrag', function () { - me.dom.lineContainer.style.top = me.body.domProps.scrollTop + 'px'; - }); } - DataAxis.prototype = new Component(); - - DataAxis.prototype.addGroup = function (label, graphOptions) { - if (!this.groups.hasOwnProperty(label)) { - this.groups[label] = graphOptions; + /** + * 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. + * @param options + */ + 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.amountOfGroups += 1; - }; - DataAxis.prototype.updateGroup = function (label, graphOptions) { - this.groups[label] = graphOptions; + this._flushIfNeeded(); }; - DataAxis.prototype.removeGroup = function (label) { - if (this.groups.hasOwnProperty(label)) { - delete this.groups[label]; - this.amountOfGroups -= 1; - } - }; + /** + * 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); - DataAxis.prototype.setOptions = function (options) { - if (options) { - var redraw = false; - if (this.options.orientation != options.orientation && options.orientation !== undefined) { - redraw = true; - } - var fields = ['orientation', 'showMinorLabels', 'showMajorLabels', 'icons', 'majorLinesOffset', 'minorLinesOffset', 'labelOffsetX', 'labelOffsetY', 'iconWidth', 'width', 'visible', 'left', 'right', 'alignZeros']; - util.selectiveExtend(fields, this.options, options); + if (object.flush !== undefined) { + throw new Error('Target object already has a property flush'); + } + object.flush = function () { + queue.flush(); + }; - this.minWidth = Number(('' + this.options.width).replace('px', '')); + var methods = [{ + name: 'flush', + original: undefined + }]; - if (redraw === true && this.dom.frame) { - this.hide(); - this.show(); + 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; }; /** - * Create the HTML DOM for the DataAxis + * Destroy the queue. The queue will first flush all queued actions, and in + * case it has extended an object, will restore the original object. */ - DataAxis.prototype._create = function () { - this.dom.frame = document.createElement('div'); - this.dom.frame.style.width = this.options.width; - this.dom.frame.style.height = this.height; - - this.dom.lineContainer = document.createElement('div'); - this.dom.lineContainer.style.width = '100%'; - this.dom.lineContainer.style.height = this.height; - this.dom.lineContainer.style.position = 'relative'; + Queue.prototype.destroy = function () { + this.flush(); - // create svg element for graph drawing. - this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - this.svg.style.position = 'absolute'; - this.svg.style.top = '0px'; - this.svg.style.height = '100%'; - this.svg.style.width = '100%'; - this.svg.style.display = 'block'; - this.dom.frame.appendChild(this.svg); + 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; + } }; - DataAxis.prototype._redrawGroupIcons = function () { - DOMutil.prepareElements(this.svgElements); - - var x; - var iconWidth = this.options.iconWidth; - var iconHeight = 15; - var iconOffset = 4; - var y = iconOffset + 0.5 * iconHeight; - - if (this.options.orientation === 'left') { - x = iconOffset; - } else { - x = this.width - iconWidth - iconOffset; + /** + * 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'); } - var groupArray = Object.keys(this.groups); - groupArray.sort(function (a, b) { - return a < b ? -1 : 1; - }); - - for (var i = 0; i < groupArray.length; i++) { - var groupId = groupArray[i]; - if (this.groups[groupId].visible === true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] === true)) { - this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight); - y += iconHeight + iconOffset; + object[method] = function () { + // create an Array with the arguments + var args = []; + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; } - } - - DOMutil.cleanupElements(this.svgElements); - this.iconsRemoved = false; - }; - DataAxis.prototype._cleanupIcons = function () { - if (this.iconsRemoved === false) { - DOMutil.prepareElements(this.svgElements); - DOMutil.cleanupElements(this.svgElements); - this.iconsRemoved = true; - } + // add this call to the queue + me.queue({ + args: args, + fn: original, + context: this + }); + }; }; /** - * Create the HTML DOM for the DataAxis + * Queue a call + * @param {function | {fn: function, args: Array} | {fn: function, args: Array, context: Object}} entry */ - DataAxis.prototype.show = function () { - this.hidden = false; - if (!this.dom.frame.parentNode) { - if (this.options.orientation === 'left') { - this.body.dom.left.appendChild(this.dom.frame); - } else { - this.body.dom.right.appendChild(this.dom.frame); - } + Queue.prototype.queue = function (entry) { + if (typeof entry === 'function') { + this._queue.push({ fn: entry }); + } else { + this._queue.push(entry); } - if (!this.dom.lineContainer.parentNode) { - this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer); - } + this._flushIfNeeded(); }; /** - * Create the HTML DOM for the DataAxis + * Check whether the queue needs to be flushed + * @private */ - DataAxis.prototype.hide = function () { - this.hidden = true; - if (this.dom.frame.parentNode) { - this.dom.frame.parentNode.removeChild(this.dom.frame); + Queue.prototype._flushIfNeeded = function () { + // flush when the maximum is exceeded. + if (this._queue.length > this.max) { + this.flush(); } - if (this.dom.lineContainer.parentNode) { - this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer); + // 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); } }; /** - * Set a range (start and end) - * @param end - * @param start - * @param end + * Flush all queued calls */ - DataAxis.prototype.setRange = function (start, end) { - if (this.master === false && this.options.alignZeros === true && this.zeroCrossing != -1) { - if (start > 0) { - start = 0; - } + Queue.prototype.flush = function () { + while (this._queue.length > 0) { + var entry = this._queue.shift(); + entry.fn.apply(entry.context || entry.fn, entry.args || []); } - this.range.start = start; - this.range.end = end; }; - /** - * Repaint the component - * @return {boolean} Returns true if the component is resized - */ - DataAxis.prototype.redraw = function () { - var resized = false; - var activeGroups = 0; + module.exports = Queue; - // Make sure the line container adheres to the vertical scrolling. - this.dom.lineContainer.style.top = this.body.domProps.scrollTop + 'px'; +/***/ }, +/* 16 */ +/***/ function(module, exports, __webpack_require__) { - for (var groupId in this.groups) { - if (this.groups.hasOwnProperty(groupId)) { - if (this.groups[groupId].visible === true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] === true)) { - activeGroups++; - } - } - } - if (this.amountOfGroups === 0 || activeGroups === 0) { - this.hide(); - } else { - this.show(); - this.height = Number(this.linegraphSVG.style.height.replace('px', '')); + 'use strict'; - // svg offsetheight did not work in firefox and explorer... - this.dom.lineContainer.style.height = this.height + 'px'; - this.width = this.options.visible === true ? Number(('' + this.options.width).replace('px', '')) : 0; + var util = __webpack_require__(7); + var DataSet = __webpack_require__(14); - var props = this.props; - var frame = this.dom.frame; + /** + * 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 - // update classname - frame.className = 'vis-data-axis'; + var me = this; + this.listener = function () { + me._onEvent.apply(me, arguments); + }; - // calculate character width and height - this._calculateCharSize(); + this.setData(data); + } - var orientation = this.options.orientation; - var showMinorLabels = this.options.showMinorLabels; - var showMajorLabels = this.options.showMajorLabels; + // TODO: implement a function .config() to dynamically update things like configured filter + // and trigger changes accordingly - // determine the width and height of the elements for the axis - props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0; - props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0; + /** + * Set a data source for the view + * @param {DataSet | DataView} data + */ + DataView.prototype.setData = function (data) { + var ids, i, len; - props.minorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.minorLinesOffset; - props.minorLineHeight = 1; - props.majorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.majorLinesOffset; - props.majorLineHeight = 1; + if (this._data) { + // unsubscribe from current dataset + if (this._data.off) { + this._data.off('*', this.listener); + } - // take frame offline while updating (is almost twice as fast) - if (orientation === 'left') { - frame.style.top = '0'; - frame.style.left = '0'; - frame.style.bottom = ''; - frame.style.width = this.width + 'px'; - frame.style.height = this.height + 'px'; - this.props.width = this.body.domProps.left.width; - this.props.height = this.body.domProps.left.height; - } else { - // right - frame.style.top = ''; - frame.style.bottom = '0'; - frame.style.left = '0'; - frame.style.width = this.width + 'px'; - frame.style.height = this.height + 'px'; - this.props.width = this.body.domProps.right.width; - this.props.height = this.body.domProps.right.height; + // trigger a remove of all items in memory + ids = []; + for (var id in this._ids) { + if (this._ids.hasOwnProperty(id)) { + ids.push(id); + } } + this._ids = {}; + this.length = 0; + this._trigger('remove', { items: ids }); + } - resized = this._redrawLabels(); - resized = this._isResized() || resized; + this._data = data; - if (this.options.icons === true) { - this._redrawGroupIcons(); - } else { - this._cleanupIcons(); + 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 }); - this._redrawTitle(orientation); + // subscribe to new dataset + if (this._data.on) { + this._data.on('*', this.listener); + } } - return resized; }; /** - * Repaint major and minor text labels and vertical grid lines - * @private + * Refresh the DataView. Useful when the DataView has a filter function + * containing a variable parameter. */ - DataAxis.prototype._redrawLabels = function () { - var resized = false; - DOMutil.prepareElements(this.DOMelements.lines); - DOMutil.prepareElements(this.DOMelements.labels); - var orientation = this.options['orientation']; - - // get the range for the slaved axis - var step; - if (this.master === false) { - var stepSize, rangeStart, rangeEnd, minimumStep; - if (this.zeroCrossing !== -1 && this.options.alignZeros === true) { - if (this.range.end > 0) { - stepSize = this.range.end / this.zeroCrossing; // size of one step - rangeStart = this.range.end - this.amountOfSteps * stepSize; - rangeEnd = this.range.end; - } else { - // all of the range (including start) has to be done before the zero crossing. - stepSize = -1 * this.range.start / (this.amountOfSteps - this.zeroCrossing); // absolute size of a step - rangeStart = this.range.start; - rangeEnd = this.range.start + stepSize * this.amountOfSteps; - } - } else { - rangeStart = this.range.start; - rangeEnd = this.range.end; - } - minimumStep = this.stepPixels; - } else { - // calculate range and step (step such that we have space for 7 characters per label) - minimumStep = this.props.majorCharHeight; - rangeStart = this.range.start; - rangeEnd = this.range.end; - } - - this.step = step = new DataStep(rangeStart, rangeEnd, minimumStep, this.dom.frame.offsetHeight, this.options[this.options.orientation].range, this.options[this.options.orientation].format, this.master === false && this.options.alignZeros // does the step have to align zeros? only if not master and the options is on - ); + DataView.prototype.refresh = function () { + var id; + var ids = this._data.getIds({ filter: this._options && this._options.filter }); + var newIds = {}; + var added = []; + var removed = []; - // the slave axis needs to use the same horizontal lines as the master axis. - if (this.master === true) { - this.stepPixels = this.dom.frame.offsetHeight / step.marginRange * step.step; - this.amountOfSteps = Math.ceil(this.dom.frame.offsetHeight / this.stepPixels); - } else { - // align with zero - if (this.options.alignZeros === true && this.zeroCrossing !== -1) { - // distance is the amount of steps away from the zero crossing we are. - var distance = (step.current - this.zeroCrossing * step.step) / step.step; - this.step.shift(distance); + // check for additions + for (var i = 0; i < ids.length; i++) { + id = ids[i]; + newIds[id] = true; + if (!this._ids[id]) { + added.push(id); + this._ids[id] = true; + this.length++; } } - // value at the bottom of the SVG - this.valueAtBottom = step.marginEnd; - - this.maxLabelSize = 0; - var y = 0; // init value - var stepIndex = 0; // init value - var isMajor = false; // init value - while (stepIndex < this.amountOfSteps) { - y = Math.round(stepIndex * this.stepPixels); - isMajor = step.isMajor(); - - if (stepIndex > 0 && stepIndex !== this.amountOfSteps) { - if (this.options['showMinorLabels'] && isMajor === false || this.master === false && this.options['showMinorLabels'] === true) { - this._redrawLabel(y - 2, step.getCurrent(), orientation, 'vis-y-axis vis-minor', this.props.minorCharHeight); - } - - if (isMajor && this.options['showMajorLabels'] && this.master === true || this.options['showMinorLabels'] === false && this.master === false && isMajor === true) { - if (y >= 0) { - this._redrawLabel(y - 2, step.getCurrent(), orientation, 'vis-y-axis vis-major', this.props.majorCharHeight); - } - this._redrawLine(y, orientation, 'vis-grid vis-horizontal vis-major', this.options.majorLinesOffset, this.props.majorLineWidth); - } else { - this._redrawLine(y, orientation, 'vis-grid vis-horizontal vis-minor', this.options.minorLinesOffset, this.props.minorLineWidth); + // check for removals + for (id in this._ids) { + if (this._ids.hasOwnProperty(id)) { + if (!newIds[id]) { + removed.push(id); + delete this._ids[id]; + this.length--; } } - - // get zero crossing - if (this.master === true && step.current === 0) { - this.zeroCrossing = stepIndex; - } - - step.next(); - stepIndex += 1; - } - - // get zero crossing if it's the last step - if (this.master === true && step.current === 0) { - this.zeroCrossing = stepIndex; - } - - this.conversionFactor = this.stepPixels / step.step; - - // Note that title is rotated, so we're using the height, not width! - var titleWidth = 0; - if (this.options[orientation].title !== undefined && this.options[orientation].title.text !== undefined) { - titleWidth = this.props.titleCharHeight; } - var offset = this.options.icons === true ? Math.max(this.options.iconWidth, titleWidth) + this.options.labelOffsetX + 15 : titleWidth + this.options.labelOffsetX + 15; - // this will resize the yAxis to accommodate the labels. - if (this.maxLabelSize > this.width - offset && this.options.visible === true) { - this.width = this.maxLabelSize + offset; - this.options.width = this.width + 'px'; - DOMutil.cleanupElements(this.DOMelements.lines); - DOMutil.cleanupElements(this.DOMelements.labels); - this.redraw(); - resized = true; + // trigger events + if (added.length) { + this._trigger('add', { items: added }); } - // this will resize the yAxis if it is too big for the labels. - else if (this.maxLabelSize < this.width - offset && this.options.visible === true && this.width > this.minWidth) { - this.width = Math.max(this.minWidth, this.maxLabelSize + offset); - this.options.width = this.width + 'px'; - DOMutil.cleanupElements(this.DOMelements.lines); - DOMutil.cleanupElements(this.DOMelements.labels); - this.redraw(); - resized = true; - } else { - DOMutil.cleanupElements(this.DOMelements.lines); - DOMutil.cleanupElements(this.DOMelements.labels); - resized = false; + if (removed.length) { + this._trigger('remove', { items: removed }); } - - return resized; - }; - - DataAxis.prototype.convertValue = function (value) { - var invertedValue = this.valueAtBottom - value; - var convertedValue = invertedValue * this.conversionFactor; - return convertedValue; - }; - - DataAxis.prototype.screenToValue = function (x) { - return this.valueAtBottom - x / this.conversionFactor; }; /** - * Create a label for the axis at position x - * @private - * @param y - * @param text - * @param orientation - * @param className - * @param characterHeight + * 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 args */ - DataAxis.prototype._redrawLabel = function (y, text, orientation, className, characterHeight) { - // reuse redundant label - var label = DOMutil.getDOMElement('div', this.DOMelements.labels, this.dom.frame); //this.dom.redundant.labels.shift(); - label.className = className; - label.innerHTML = text; - if (orientation === 'left') { - label.style.left = '-' + this.options.labelOffsetX + 'px'; - label.style.textAlign = 'right'; + DataView.prototype.get = function (args) { + 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 { - label.style.right = '-' + this.options.labelOffsetX + 'px'; - label.style.textAlign = 'left'; + // get([, options] [, data]) + options = arguments[0]; + data = arguments[1]; } - label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px'; + // extend the options with the default options and provided options + var viewOptions = util.extend({}, this._options, options); - text += ''; + // 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); + }; + } - var largestWidth = Math.max(this.props.majorCharWidth, this.props.minorCharWidth); - if (this.maxLabelSize < text.length * largestWidth) { - this.maxLabelSize = text.length * largestWidth; + // 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); }; /** - * Create a minor line for the axis at position y - * @param y - * @param orientation - * @param className - * @param offset - * @param width + * 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 */ - DataAxis.prototype._redrawLine = function (y, orientation, className, offset, width) { - if (this.master === true) { - var line = DOMutil.getDOMElement('div', this.DOMelements.lines, this.dom.lineContainer); //this.dom.redundant.lines.shift(); - line.className = className; - line.innerHTML = ''; + DataView.prototype.getIds = function (options) { + var ids; - if (orientation === 'left') { - line.style.left = this.width - offset + 'px'; + if (this._data) { + var defaultFilter = this._options.filter; + var filter; + + if (options && options.filter) { + if (defaultFilter) { + filter = function (item) { + return defaultFilter(item) && options.filter(item); + }; + } else { + filter = options.filter; + } } else { - line.style.right = this.width - offset + 'px'; + filter = defaultFilter; } - line.style.width = width + 'px'; - line.style.top = y + 'px'; + ids = this._data.getIds({ + filter: filter, + order: options && options.order + }); + } else { + ids = []; } + + return ids; }; /** - * Create a title for the axis - * @private - * @param orientation + * 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 */ - DataAxis.prototype._redrawTitle = function (orientation) { - DOMutil.prepareElements(this.DOMelements.title); - - // Check if the title is defined for this axes - if (this.options[orientation].title !== undefined && this.options[orientation].title.text !== undefined) { - var title = DOMutil.getDOMElement('div', this.DOMelements.title, this.dom.frame); - title.className = 'vis-y-axis vis-title vis-' + orientation; - title.innerHTML = this.options[orientation].title.text; - - // Add style - if provided - if (this.options[orientation].title.style !== undefined) { - util.addCssText(title, this.options[orientation].title.style); - } - - if (orientation === 'left') { - title.style.left = this.props.titleCharHeight + 'px'; - } else { - title.style.right = this.props.titleCharHeight + 'px'; - } - - title.style.width = this.height + 'px'; + DataView.prototype.getDataSet = function () { + var dataSet = this; + while (dataSet instanceof DataView) { + dataSet = dataSet._data; } - - // we need to clean up in case we did not use all elements. - DOMutil.cleanupElements(this.DOMelements.title); + return dataSet || null; }; /** - * 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. + * 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 */ - DataAxis.prototype._calculateCharSize = function () { - // determine the char width and height on the minor axis - if (!('minorCharHeight' in this.props)) { - var textMinor = document.createTextNode('0'); - var measureCharMinor = document.createElement('div'); - measureCharMinor.className = 'vis-y-axis vis-minor vis-measure'; - measureCharMinor.appendChild(textMinor); - this.dom.frame.appendChild(measureCharMinor); + DataView.prototype._onEvent = function (event, params, senderId) { + var i, len, id, item; + var ids = params && params.items; + var data = this._data; + var updatedData = []; + var added = []; + var updated = []; + var removed = []; - this.props.minorCharHeight = measureCharMinor.clientHeight; - this.props.minorCharWidth = measureCharMinor.clientWidth; + if (ids && 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; + added.push(id); + } + } - this.dom.frame.removeChild(measureCharMinor); - } + break; - if (!('majorCharHeight' in this.props)) { - var textMajor = document.createTextNode('0'); - var measureCharMajor = document.createElement('div'); - measureCharMajor.className = 'vis-y-axis vis-major vis-measure'; - measureCharMajor.appendChild(textMajor); - this.dom.frame.appendChild(measureCharMajor); + 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); - this.props.majorCharHeight = measureCharMajor.clientHeight; - this.props.majorCharWidth = measureCharMajor.clientWidth; + if (item) { + if (this._ids[id]) { + updated.push(id); + updatedData.push(params.data[i]); + } else { + this._ids[id] = true; + added.push(id); + } + } else { + if (this._ids[id]) { + delete this._ids[id]; + removed.push(id); + } else {} + } + } - this.dom.frame.removeChild(measureCharMajor); - } + break; - if (!('titleCharHeight' in this.props)) { - var textTitle = document.createTextNode('0'); - var measureCharTitle = document.createElement('div'); - measureCharTitle.className = 'vis-y-axis vis-title vis-measure'; - measureCharTitle.appendChild(textTitle); - this.dom.frame.appendChild(measureCharTitle); + 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]; + removed.push(id); + } + } - this.props.titleCharHeight = measureCharTitle.clientHeight; - this.props.titleCharWidth = measureCharTitle.clientWidth; + break; + } - this.dom.frame.removeChild(measureCharTitle); + this.length += added.length - removed.length; + + if (added.length) { + this._trigger('add', { items: added }, senderId); + } + if (updated.length) { + this._trigger('update', { items: updated, data: updatedData }, senderId); + } + if (removed.length) { + this._trigger('remove', { items: removed }, senderId); + } } }; - module.exports = DataAxis; + // 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; + + // nothing interesting for me :-( /***/ }, -/* 29 */ +/* 17 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var util = __webpack_require__(2); - var DOMutil = __webpack_require__(3); - var Line = __webpack_require__(51); - var Bar = __webpack_require__(52); - var Points = __webpack_require__(53); + var Emitter = __webpack_require__(19); + var DataSet = __webpack_require__(14); + var DataView = __webpack_require__(16); + var util = __webpack_require__(7); + var Point3d = __webpack_require__(20); + var Point2d = __webpack_require__(18); + var Camera = __webpack_require__(21); + var Filter = __webpack_require__(22); + var Slider = __webpack_require__(23); + var StepNumber = __webpack_require__(24); /** - * /** - * @param {object} group | the object of the group from the dataset - * @param {string} groupId | ID of the group - * @param {object} options | the default options - * @param {array} groupsUsingDefaultStyles | this array has one entree. - * It is passed as an array so it is passed by reference. - * It enumerates through the default styles - * @constructor + * @constructor Graph3d + * Graph3d displays data in 3d. + * + * Graph3d is developed in javascript as a Google Visualization Chart. + * + * @param {Element} container The DOM element in which the Graph3d will + * be created. Normally a div element. + * @param {DataSet | DataView | Array} [data] + * @param {Object} [options] */ - function GraphGroup(group, groupId, options, groupsUsingDefaultStyles) { - this.id = groupId; - var fields = ['sampling', 'style', 'sort', 'yAxisOrientation', 'barChart', 'drawPoints', 'shaded', 'interpolation']; - this.options = util.selectiveBridgeObject(fields, options); - this.usingDefaultStyle = group.className === undefined; - this.groupsUsingDefaultStyles = groupsUsingDefaultStyles; - this.zeroPosition = 0; - this.update(group); - if (this.usingDefaultStyle == true) { - this.groupsUsingDefaultStyles[0] += 1; + function Graph3d(container, data, options) { + if (!(this instanceof Graph3d)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + // create variables and set default values + this.containerElement = container; + this.width = '400px'; + this.height = '400px'; + this.margin = 10; // px + this.defaultXCenter = '55%'; + this.defaultYCenter = '50%'; + + this.xLabel = 'x'; + this.yLabel = 'y'; + this.zLabel = 'z'; + + var passValueFn = function passValueFn(v) { + return v; + }; + this.xValueLabel = passValueFn; + this.yValueLabel = passValueFn; + this.zValueLabel = passValueFn; + + this.filterLabel = 'time'; + this.legendLabel = 'value'; + + this.style = Graph3d.STYLE.DOT; + this.showPerspective = true; + this.showGrid = true; + this.keepAspectRatio = true; + this.showShadow = false; + this.showGrayBottom = false; // TODO: this does not work correctly + this.showTooltip = false; + this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube' + + this.animationInterval = 1000; // milliseconds + this.animationPreload = false; + + this.camera = new Camera(); + this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window? + + this.dataTable = null; // The original data table + this.dataPoints = null; // The table with point objects + + // the column indexes + this.colX = undefined; + this.colY = undefined; + this.colZ = undefined; + this.colValue = undefined; + this.colFilter = undefined; + + this.xMin = 0; + this.xStep = undefined; // auto by default + this.xMax = 1; + this.yMin = 0; + this.yStep = undefined; // auto by default + this.yMax = 1; + this.zMin = 0; + this.zStep = undefined; // auto by default + this.zMax = 1; + this.valueMin = 0; + this.valueMax = 1; + this.xBarWidth = 1; + this.yBarWidth = 1; + // TODO: customize axis range + + // constants + this.colorAxis = '#4D4D4D'; + this.colorGrid = '#D3D3D3'; + this.colorDot = '#7DC1FF'; + this.colorDotBorder = '#3267D2'; + + // create a frame and canvas + this.create(); + + // apply options (also when undefined) + this.setOptions(options); + + // apply data + if (data) { + this.setData(data); } - this.itemsData = []; - this.visible = group.visible === undefined ? true : group.visible; } + // Extend Graph3d with an Emitter mixin + Emitter(Graph3d.prototype); + /** - * this loads a reference to all items in this group into this group. - * @param {array} items + * Calculate the scaling values, dependent on the range in x, y, and z direction */ - GraphGroup.prototype.setItems = function (items) { - if (items != null) { - this.itemsData = items; - if (this.options.sort == true) { - this.itemsData.sort(function (a, b) { - return a.x - b.x; - }); + Graph3d.prototype._setScale = function () { + this.scale = new Point3d(1 / (this.xMax - this.xMin), 1 / (this.yMax - this.yMin), 1 / (this.zMax - this.zMin)); + + // keep aspect ration between x and y scale if desired + if (this.keepAspectRatio) { + if (this.scale.x < this.scale.y) { + //noinspection JSSuspiciousNameCombination + this.scale.y = this.scale.x; + } else { + //noinspection JSSuspiciousNameCombination + this.scale.x = this.scale.y; } - } else { - this.itemsData = []; } + + // scale the vertical axis + this.scale.z *= this.verticalRatio; + // TODO: can this be automated? verticalRatio? + + // determine scale for (optional) value + this.scale.value = 1 / (this.valueMax - this.valueMin); + + // position the camera arm + var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x; + var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y; + var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z; + this.camera.setArmLocation(xCenter, yCenter, zCenter); }; /** - * this is used for plotting barcharts, this way, we only have to calculate it once. - * @param pos + * Convert a 3D location to a 2D location on screen + * http://en.wikipedia.org/wiki/3D_projection + * @param {Point3d} point3d A 3D point with parameters x, y, z + * @return {Point2d} point2d A 2D point with parameters x, y */ - GraphGroup.prototype.setZeroPosition = function (pos) { - this.zeroPosition = pos; + Graph3d.prototype._convert3Dto2D = function (point3d) { + var translation = this._convertPointToTranslation(point3d); + return this._convertTranslationToScreen(translation); }; /** - * set the options of the graph group over the default options. - * @param options + * Convert a 3D location its translation seen from the camera + * http://en.wikipedia.org/wiki/3D_projection + * @param {Point3d} point3d A 3D point with parameters x, y, z + * @return {Point3d} translation A 3D point with parameters x, y, z This is + * the translation of the point, seen from the + * camera */ - GraphGroup.prototype.setOptions = function (options) { - if (options !== undefined) { - var fields = ['sampling', 'style', 'sort', 'yAxisOrientation', 'barChart']; - util.selectiveDeepExtend(fields, this.options, options); + Graph3d.prototype._convertPointToTranslation = function (point3d) { + var ax = point3d.x * this.scale.x, + ay = point3d.y * this.scale.y, + az = point3d.z * this.scale.z, + cx = this.camera.getCameraLocation().x, + cy = this.camera.getCameraLocation().y, + cz = this.camera.getCameraLocation().z, - util.mergeOptions(this.options, options, 'interpolation'); - util.mergeOptions(this.options, options, 'drawPoints'); - util.mergeOptions(this.options, options, 'shaded'); + // calculate angles + sinTx = Math.sin(this.camera.getCameraRotation().x), + cosTx = Math.cos(this.camera.getCameraRotation().x), + sinTy = Math.sin(this.camera.getCameraRotation().y), + cosTy = Math.cos(this.camera.getCameraRotation().y), + sinTz = Math.sin(this.camera.getCameraRotation().z), + cosTz = Math.cos(this.camera.getCameraRotation().z), - if (options.interpolation) { - if (typeof options.interpolation == 'object') { - if (options.interpolation.parametrization) { - if (options.interpolation.parametrization == 'uniform') { - this.options.interpolation.alpha = 0; - } else if (options.interpolation.parametrization == 'chordal') { - this.options.interpolation.alpha = 1; - } else { - this.options.interpolation.parametrization = 'centripetal'; - this.options.interpolation.alpha = 0.5; - } - } - } - } - } + // calculate translation + dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz), + dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax - cx)), + dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax - cx)); - if (this.options.style == 'line') { - this.type = new Line(this.id, this.options); - } else if (this.options.style == 'bar') { - this.type = new Bar(this.id, this.options); - } else if (this.options.style == 'points') { - this.type = new Points(this.id, this.options); - } + return new Point3d(dx, dy, dz); }; /** - * this updates the current group class with the latest group dataset entree, used in _updateGroup in linegraph - * @param group - */ - GraphGroup.prototype.update = function (group) { - this.group = group; - this.content = group.content || 'graph'; - this.className = group.className || this.className || 'vis-graph-group' + this.groupsUsingDefaultStyles[0] % 10; - this.visible = group.visible === undefined ? true : group.visible; - this.style = group.style; - this.setOptions(group.options); - }; - - /** - * draw the icon for the legend. - * - * @param x - * @param y - * @param JSONcontainer - * @param SVGcontainer - * @param iconWidth - * @param iconHeight + * Convert a translation point to a point on the screen + * @param {Point3d} translation A 3D point with parameters x, y, z This is + * the translation of the point, seen from the + * camera + * @return {Point2d} point2d A 2D point with parameters x, y */ - GraphGroup.prototype.drawIcon = function (x, y, JSONcontainer, SVGcontainer, iconWidth, iconHeight) { - var fillHeight = iconHeight * 0.5; - var path, fillPath; - - var outline = DOMutil.getSVGElement('rect', JSONcontainer, SVGcontainer); - 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'); - - if (this.options.style == 'line') { - path = DOMutil.getSVGElement('path', JSONcontainer, SVGcontainer); - path.setAttributeNS(null, 'class', this.className); - if (this.style !== undefined) { - path.setAttributeNS(null, 'style', this.style); - } - - path.setAttributeNS(null, 'd', 'M' + x + ',' + y + ' L' + (x + iconWidth) + ',' + y + ''); - if (this.options.shaded.enabled == true) { - fillPath = DOMutil.getSVGElement('path', JSONcontainer, SVGcontainer); - if (this.options.shaded.orientation == 'top') { - fillPath.setAttributeNS(null, 'd', 'M' + x + ', ' + (y - fillHeight) + 'L' + x + ',' + y + ' L' + (x + iconWidth) + ',' + y + ' L' + (x + iconWidth) + ',' + (y - fillHeight)); - } else { - fillPath.setAttributeNS(null, 'd', 'M' + x + ',' + y + ' ' + 'L' + x + ',' + (y + fillHeight) + ' ' + 'L' + (x + iconWidth) + ',' + (y + fillHeight) + 'L' + (x + iconWidth) + ',' + y); - } - fillPath.setAttributeNS(null, 'class', this.className + ' vis-icon-fill'); - } + Graph3d.prototype._convertTranslationToScreen = function (translation) { + var ex = this.eye.x, + ey = this.eye.y, + ez = this.eye.z, + dx = translation.x, + dy = translation.y, + dz = translation.z; - if (this.options.drawPoints.enabled == true) { - DOMutil.drawPoint(x + 0.5 * iconWidth, y, this, JSONcontainer, SVGcontainer); - } + // calculate position on screen from translation + var bx; + var by; + if (this.showPerspective) { + bx = (dx - ex) * (ez / dz); + by = (dy - ey) * (ez / dz); } else { - var barWidth = Math.round(0.3 * iconWidth); - var bar1Height = Math.round(0.4 * iconHeight); - var bar2Height = Math.round(0.75 * iconHeight); - - var offset = Math.round((iconWidth - 2 * barWidth) / 3); - - DOMutil.drawBar(x + 0.5 * barWidth + offset, y + fillHeight - bar1Height - 1, barWidth, bar1Height, this.className + ' vis-bar', JSONcontainer, SVGcontainer, this.style); - DOMutil.drawBar(x + 1.5 * barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, this.className + ' vis-bar', JSONcontainer, SVGcontainer, this.style); + bx = dx * -(ez / this.camera.getArmLength()); + by = dy * -(ez / this.camera.getArmLength()); } + + // shift and scale the point to the center of the screen + // use the width of the graph to scale both horizontally and vertically. + return new Point2d(this.xcenter + bx * this.frame.canvas.clientWidth, this.ycenter - by * this.frame.canvas.clientWidth); }; /** - * return the legend entree for this group. - * - * @param iconWidth - * @param iconHeight - * @returns {{icon: HTMLElement, label: (group.content|*|string), orientation: (.options.yAxisOrientation|*)}} + * Set the background styling for the graph + * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor */ - GraphGroup.prototype.getLegend = function (iconWidth, iconHeight) { - var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - this.drawIcon(0, 0.5 * iconHeight, [], svg, iconWidth, iconHeight); - return { icon: svg, label: this.content, orientation: this.options.yAxisOrientation }; - }; + Graph3d.prototype._setBackgroundColor = function (backgroundColor) { + var fill = 'white'; + var stroke = 'gray'; + var strokeWidth = 1; - GraphGroup.prototype.getYRange = function (groupData) { - return this.type.getYRange(groupData); - }; + if (typeof backgroundColor === 'string') { + fill = backgroundColor; + stroke = 'none'; + strokeWidth = 0; + } else if (typeof backgroundColor === 'object') { + if (backgroundColor.fill !== undefined) fill = backgroundColor.fill; + if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke; + if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth; + } else if (backgroundColor === undefined) {} else { + throw 'Unsupported type of backgroundColor'; + } - GraphGroup.prototype.getData = function (groupData) { - return this.type.getData(groupData); + this.frame.style.backgroundColor = fill; + this.frame.style.borderColor = stroke; + this.frame.style.borderWidth = strokeWidth + 'px'; + this.frame.style.borderStyle = 'solid'; }; - GraphGroup.prototype.draw = function (dataset, group, framework) { - this.type.draw(dataset, group, framework); + /// enumerate the available styles + Graph3d.STYLE = { + BAR: 0, + BARCOLOR: 1, + BARSIZE: 2, + DOT: 3, + DOTLINE: 4, + DOTCOLOR: 5, + DOTSIZE: 6, + GRID: 7, + LINE: 8, + SURFACE: 9 }; - module.exports = GraphGroup; - -/***/ }, -/* 30 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var util = __webpack_require__(2); - var stack = __webpack_require__(19); - var RangeItem = __webpack_require__(24); - /** - * @constructor Group - * @param {Number | String} groupId - * @param {Object} data - * @param {ItemSet} itemSet + * 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 Group(groupId, data, itemSet) { - this.groupId = groupId; - this.subgroups = {}; - this.subgroupIndex = 0; - this.subgroupOrderer = data && data.subgroupOrder; - this.itemSet = itemSet; - - 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.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(); + Graph3d.prototype._getStyleNumber = function (styleName) { + switch (styleName) { + case 'dot': + return Graph3d.STYLE.DOT; + case 'dot-line': + return Graph3d.STYLE.DOTLINE; + case 'dot-color': + return Graph3d.STYLE.DOTCOLOR; + case 'dot-size': + return Graph3d.STYLE.DOTSIZE; + case 'line': + return Graph3d.STYLE.LINE; + case 'grid': + return Graph3d.STYLE.GRID; + case 'surface': + return Graph3d.STYLE.SURFACE; + case 'bar': + return Graph3d.STYLE.BAR; + case 'bar-color': + return Graph3d.STYLE.BARCOLOR; + case 'bar-size': + return Graph3d.STYLE.BARSIZE; + } - this.setData(data); - } + return -1; + }; /** - * Create DOM elements for the group - * @private + * Determine the indexes of the data columns, based on the given style and data + * @param {DataSet} data + * @param {Number} style */ - Group.prototype._create = function () { - var label = document.createElement('div'); - 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'; + Graph3d.prototype._determineColumnIndexes = function (data, style) { + if (this.style === Graph3d.STYLE.DOT || this.style === Graph3d.STYLE.DOTLINE || this.style === Graph3d.STYLE.LINE || this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE || this.style === Graph3d.STYLE.BAR) { + // 3 columns expected, and optionally a 4th with filter values + this.colX = 0; + this.colY = 1; + this.colZ = 2; + this.colValue = undefined; - // 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.innerHTML = '?'; - this.dom.background.appendChild(this.dom.marker); - }; + if (data.getNumberOfColumns() > 3) { + this.colFilter = 3; + } + } else if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { + // 4 columns expected, and optionally a 5th with filter values + this.colX = 0; + this.colY = 1; + this.colZ = 2; + this.colValue = 3; - /** - * 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 = data && data.content; - if (content instanceof Element) { - this.dom.inner.appendChild(content); - } else if (content !== undefined && content !== null) { - this.dom.inner.innerHTML = content; + if (data.getNumberOfColumns() > 4) { + this.colFilter = 4; + } } else { - this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null + throw 'Unknown style "' + this.style + '"'; } + }; - // update title - this.dom.label.title = data && data.title || ''; + Graph3d.prototype.getNumberOfRows = function (data) { + return data.length; + }; - if (!this.dom.inner.firstChild) { - util.addClassName(this.dom.inner, 'vis-hidden'); - } else { - util.removeClassName(this.dom.inner, 'vis-hidden'); + Graph3d.prototype.getNumberOfColumns = function (data) { + var counter = 0; + for (var column in data[0]) { + if (data[0].hasOwnProperty(column)) { + counter++; + } } + return counter; + }; - // 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); + Graph3d.prototype.getDistinctValues = function (data, column) { + var distinctValues = []; + for (var i = 0; i < data.length; i++) { + if (distinctValues.indexOf(data[i][column]) == -1) { + distinctValues.push(data[i][column]); } - 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; } + return distinctValues; + }; - // update style - if (this.style) { - util.removeCssText(this.dom.label, 'vis-' + this.style); - this.style = null; - } - if (data && data.style) { - util.addCssText(this.dom.label, 'vis-' + data.style); - this.style = data.style; + Graph3d.prototype.getColumnRange = function (data, column) { + var minMax = { min: data[0][column], max: data[0][column] }; + for (var i = 0; i < data.length; i++) { + if (minMax.min > data[i][column]) { + minMax.min = data[i][column]; + } + if (minMax.max < data[i][column]) { + minMax.max = data[i][column]; + } } + return minMax; }; /** - * Get the width of the group label - * @return {number} width + * Initialize the data from the data table. Calculate minimum and maximum values + * and column index values + * @param {Array | DataSet | DataView} rawData The data containing the items for the Graph. + * @param {Number} style Style Number */ - Group.prototype.getLabelWidth = function () { - return this.props.label.width; - }; + Graph3d.prototype._dataInitialize = function (rawData, style) { + var me = this; - /** - * Repaint this group - * @param {{start: number, end: number}} range - * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin - * @param {boolean} [restack=false] Force restacking of all items - * @return {boolean} Returns true if the group is resized - */ - Group.prototype.redraw = function (range, margin, restack) { - var resized = false; + // unsubscribe from the dataTable + if (this.dataSet) { + this.dataSet.off('*', this._onChange); + } - // 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) - var markerHeight = this.dom.marker.clientHeight; - if (markerHeight != this.lastMarkerHeight) { - this.lastMarkerHeight = markerHeight; + if (rawData === undefined) return; - util.forEach(this.items, function (item) { - item.dirty = true; - if (item.displayed) item.redraw(); - }); + if (Array.isArray(rawData)) { + rawData = new DataSet(rawData); + } - restack = true; + var data; + if (rawData instanceof DataSet || rawData instanceof DataView) { + data = rawData.get(); + } else { + throw new Error('Array, DataSet, or DataView expected'); } - // reposition visible items vertically - if (typeof this.itemSet.options.order === 'function') { - // a custom order function + if (data.length == 0) return; - if (restack) { - // brute force restack of all items + this.dataSet = rawData; + this.dataTable = data; - // show all items - var me = this; - var limitSize = false; - util.forEach(this.items, function (item) { - if (!item.displayed) { - item.redraw(); - me.visibleItems.push(item); - } - item.repositionX(limitSize); - }); + // subscribe to changes in the dataset + this._onChange = function () { + me.setData(me.dataSet); + }; + this.dataSet.on('*', this._onChange); - // 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); + // _determineColumnIndexes + // getNumberOfRows (points) + // getNumberOfColumns (x,y,z,v,t,t1,t2...) + // getDistinctValues (unique values?) + // getColumnRange + + // determine the location of x,y,z,value,filter columns + this.colX = 'x'; + this.colY = 'y'; + this.colZ = 'z'; + this.colValue = 'style'; + this.colFilter = 'filter'; + + // check if a filter column is provided + if (data[0].hasOwnProperty('filter')) { + if (this.dataFilter === undefined) { + this.dataFilter = new Filter(rawData, this.colFilter, this); + this.dataFilter.setOnLoadCallback(function () { + me.redraw(); }); - stack.stack(customOrderedItems, margin, true /* restack=true */); } + } - this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); - } else { - // no custom order function, lazy stacking - this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); + var withBars = this.style == Graph3d.STYLE.BAR || this.style == Graph3d.STYLE.BARCOLOR || this.style == Graph3d.STYLE.BARSIZE; - if (this.itemSet.options.stack) { - // TODO: ugly way to access options... - stack.stack(this.visibleItems, margin, restack); + // determine barWidth from data + if (withBars) { + if (this.defaultXBarWidth !== undefined) { + this.xBarWidth = this.defaultXBarWidth; } else { - // no stacking - stack.nostack(this.visibleItems, margin, this.subgroups); + var dataX = this.getDistinctValues(data, this.colX); + this.xBarWidth = dataX[1] - dataX[0] || 1; } - } - // recalculate the height of the group - var height = this._calculateHeight(margin); + if (this.defaultYBarWidth !== undefined) { + this.yBarWidth = this.defaultYBarWidth; + } else { + var dataY = this.getDistinctValues(data, this.colY); + this.yBarWidth = dataY[1] - dataY[0] || 1; + } + } - // calculate actual size and position - var foreground = this.dom.foreground; - this.top = foreground.offsetTop; - this.left = foreground.offsetLeft; - this.width = foreground.offsetWidth; - resized = util.updateProperty(this, 'height', height) || resized; + // calculate minimums and maximums + var xRange = this.getColumnRange(data, this.colX); + if (withBars) { + xRange.min -= this.xBarWidth / 2; + xRange.max += this.xBarWidth / 2; + } + this.xMin = this.defaultXMin !== undefined ? this.defaultXMin : xRange.min; + this.xMax = this.defaultXMax !== undefined ? this.defaultXMax : xRange.max; + if (this.xMax <= this.xMin) this.xMax = this.xMin + 1; + this.xStep = this.defaultXStep !== undefined ? this.defaultXStep : (this.xMax - this.xMin) / 5; - // recalculate size of label - resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized; - resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized; + var yRange = this.getColumnRange(data, this.colY); + if (withBars) { + yRange.min -= this.yBarWidth / 2; + yRange.max += this.yBarWidth / 2; + } + this.yMin = this.defaultYMin !== undefined ? this.defaultYMin : yRange.min; + this.yMax = this.defaultYMax !== undefined ? this.defaultYMax : yRange.max; + if (this.yMax <= this.yMin) this.yMax = this.yMin + 1; + this.yStep = this.defaultYStep !== undefined ? this.defaultYStep : (this.yMax - this.yMin) / 5; - // apply new height - this.dom.background.style.height = height + 'px'; - this.dom.foreground.style.height = height + 'px'; - this.dom.label.style.height = height + 'px'; + var zRange = this.getColumnRange(data, this.colZ); + this.zMin = this.defaultZMin !== undefined ? this.defaultZMin : zRange.min; + this.zMax = this.defaultZMax !== undefined ? this.defaultZMax : zRange.max; + if (this.zMax <= this.zMin) this.zMax = this.zMin + 1; + this.zStep = this.defaultZStep !== undefined ? this.defaultZStep : (this.zMax - this.zMin) / 5; - // 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); + if (this.colValue !== undefined) { + var valueRange = this.getColumnRange(data, this.colValue); + this.valueMin = this.defaultValueMin !== undefined ? this.defaultValueMin : valueRange.min; + this.valueMax = this.defaultValueMax !== undefined ? this.defaultValueMax : valueRange.max; + if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1; } - return resized; + // set the scale dependent on the ranges. + this._setScale(); }; /** - * recalculate the height of the group - * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin - * @returns {number} Returns the height - * @private + * Filter the data based on the current filter + * @param {Array} data + * @return {Array} dataPoints Array with point objects which can be drawn on screen */ - Group.prototype._calculateHeight = function (margin) { - // recalculate the height of the group - var height; - var visibleItems = this.visibleItems; - //var visibleSubgroups = []; - //this.visibleSubgroups = 0; - this.resetSubgroups(); - var me = this; - if (visibleItems.length > 0) { - var min = visibleItems[0].top; - var max = visibleItems[0].top + visibleItems[0].height; - util.forEach(visibleItems, function (item) { - min = Math.min(min, item.top); - max = Math.max(max, item.top + item.height); - if (item.data.subgroup !== undefined) { - me.subgroups[item.data.subgroup].height = Math.max(me.subgroups[item.data.subgroup].height, item.height); - me.subgroups[item.data.subgroup].visible = true; - } - }); - 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(visibleItems, function (item) { - item.top -= offset; - }); - } - height = max + margin.item.vertical / 2; - } else { - height = 0; - } - height = Math.max(height, this.props.label.height); + Graph3d.prototype._getDataPoints = function (data) { + // TODO: store the created matrix dataPoints in the filters instead of reloading each time + var x, y, i, z, obj, point; - return height; - }; + var dataPoints = []; - /** - * 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.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { + // copy all values from the google data table to a matrix + // the provided values are supposed to form a grid of (x,y) positions - if (!this.dom.foreground.parentNode) { - this.itemSet.dom.foreground.appendChild(this.dom.foreground); - } + // create two lists with all present x and y values + var dataX = []; + var dataY = []; + for (i = 0; i < this.getNumberOfRows(data); i++) { + x = data[i][this.colX] || 0; + y = data[i][this.colY] || 0; - if (!this.dom.background.parentNode) { - this.itemSet.dom.background.appendChild(this.dom.background); - } + if (dataX.indexOf(x) === -1) { + dataX.push(x); + } + if (dataY.indexOf(y) === -1) { + dataY.push(y); + } + } - if (!this.dom.axis.parentNode) { - this.itemSet.dom.axis.appendChild(this.dom.axis); - } - }; + var sortNumber = function sortNumber(a, b) { + return a - b; + }; + dataX.sort(sortNumber); + dataY.sort(sortNumber); - /** - * Hide this group: remove from the DOM - */ - Group.prototype.hide = function () { - var label = this.dom.label; - if (label.parentNode) { - label.parentNode.removeChild(label); - } + // create a grid, a 2d matrix, with all values. + var dataMatrix = []; // temporary data matrix + for (i = 0; i < data.length; i++) { + x = data[i][this.colX] || 0; + y = data[i][this.colY] || 0; + z = data[i][this.colZ] || 0; - var foreground = this.dom.foreground; - if (foreground.parentNode) { - foreground.parentNode.removeChild(foreground); - } + var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer + var yIndex = dataY.indexOf(y); - var background = this.dom.background; - if (background.parentNode) { - background.parentNode.removeChild(background); - } + if (dataMatrix[xIndex] === undefined) { + dataMatrix[xIndex] = []; + } - var axis = this.dom.axis; - if (axis.parentNode) { - axis.parentNode.removeChild(axis); - } - }; + var point3d = new Point3d(); + point3d.x = x; + point3d.y = y; + point3d.z = z; - /** - * Add an item to the group - * @param {Item} item - */ - Group.prototype.add = function (item) { - this.items[item.id] = item; - item.setParent(this); + obj = {}; + obj.point = point3d; + obj.trans = undefined; + obj.screen = undefined; + obj.bottom = new Point3d(x, y, this.zMin); - // add to - if (item.data.subgroup !== undefined) { - if (this.subgroups[item.data.subgroup] === undefined) { - this.subgroups[item.data.subgroup] = { height: 0, visible: false, index: this.subgroupIndex, items: [] }; - this.subgroupIndex++; - } - this.subgroups[item.data.subgroup].items.push(item); - } - this.orderSubgroups(); + dataMatrix[xIndex][yIndex] = obj; - 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); - } - }; + dataPoints.push(obj); + } - Group.prototype.orderSubgroups = function () { - if (this.subgroupOrderer !== undefined) { - var sortArray = []; - if (typeof this.subgroupOrderer == 'string') { - for (var 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 (var subgroup in this.subgroups) { - sortArray.push(this.subgroups[subgroup].items[0].data); + // fill in the pointers to the neighbors. + for (x = 0; x < dataMatrix.length; x++) { + for (y = 0; y < dataMatrix[x].length; y++) { + if (dataMatrix[x][y]) { + dataMatrix[x][y].pointRight = x < dataMatrix.length - 1 ? dataMatrix[x + 1][y] : undefined; + dataMatrix[x][y].pointTop = y < dataMatrix[x].length - 1 ? dataMatrix[x][y + 1] : undefined; + dataMatrix[x][y].pointCross = x < dataMatrix.length - 1 && y < dataMatrix[x].length - 1 ? dataMatrix[x + 1][y + 1] : undefined; + } } - sortArray.sort(this.subgroupOrderer); } + } else { + // 'dot', 'dot-line', etc. + // copy all values from the google data table to a list with Point3d objects + for (i = 0; i < data.length; i++) { + point = new Point3d(); + point.x = data[i][this.colX] || 0; + point.y = data[i][this.colY] || 0; + point.z = data[i][this.colZ] || 0; - if (sortArray.length > 0) { - for (var i = 0; i < sortArray.length; i++) { - this.subgroups[sortArray[i].subgroup].index = i; + if (this.colValue !== undefined) { + point.value = data[i][this.colValue] || 0; } - } - } - }; - Group.prototype.resetSubgroups = function () { - for (var subgroup in this.subgroups) { - if (this.subgroups.hasOwnProperty(subgroup)) { - this.subgroups[subgroup].visible = false; + obj = {}; + obj.point = point; + obj.bottom = new Point3d(point.x, point.y, this.zMin); + obj.trans = undefined; + obj.screen = undefined; + + dataPoints.push(obj); } } + + return dataPoints; }; /** - * Remove an item from the group - * @param {Item} item + * Create the main frame for the Graph3d. + * This function is executed once when a Graph3d object is created. The frame + * contains a canvas, and this canvas contains all objects like the axis and + * nodes. */ - Group.prototype.remove = function (item) { - delete this.items[item.id]; - item.setParent(null); + Graph3d.prototype.create = function () { + // remove all elements from the container element. + while (this.containerElement.hasChildNodes()) { + this.containerElement.removeChild(this.containerElement.firstChild); + } - // remove from visible items - var index = this.visibleItems.indexOf(item); - if (index != -1) this.visibleItems.splice(index, 1); + this.frame = document.createElement('div'); + this.frame.style.position = 'relative'; + this.frame.style.overflow = 'hidden'; - // TODO: also remove from ordered items? + // create the graph canvas (HTML canvas element) + this.frame.canvas = document.createElement('canvas'); + this.frame.canvas.style.position = 'relative'; + this.frame.appendChild(this.frame.canvas); + //if (!this.frame.canvas.getContext) { + { + var noCanvas = document.createElement('DIV'); + noCanvas.style.color = 'red'; + noCanvas.style.fontWeight = 'bold'; + noCanvas.style.padding = '10px'; + noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; + this.frame.canvas.appendChild(noCanvas); + } + + this.frame.filter = document.createElement('div'); + this.frame.filter.style.position = 'absolute'; + this.frame.filter.style.bottom = '0px'; + this.frame.filter.style.left = '0px'; + this.frame.filter.style.width = '100%'; + this.frame.appendChild(this.frame.filter); + + // add event listeners to handle moving and zooming the contents + var me = this; + var onmousedown = function onmousedown(event) { + me._onMouseDown(event); + }; + var ontouchstart = function ontouchstart(event) { + me._onTouchStart(event); + }; + var onmousewheel = function onmousewheel(event) { + me._onWheel(event); + }; + var ontooltip = function ontooltip(event) { + me._onTooltip(event); + }; + // TODO: these events are never cleaned up... can give a 'memory leakage' + + util.addEventListener(this.frame.canvas, 'keydown', onkeydown); + util.addEventListener(this.frame.canvas, 'mousedown', onmousedown); + util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart); + util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel); + util.addEventListener(this.frame.canvas, 'mousemove', ontooltip); + + // add the new graph to the container element + this.containerElement.appendChild(this.frame); }; /** - * Remove an item from the corresponding DataSet - * @param {Item} item + * Set a new size for the graph + * @param {string} width Width in pixels or percentage (for example '800px' + * or '50%') + * @param {string} height Height in pixels or percentage (for example '400px' + * or '30%') */ - Group.prototype.removeFromDataSet = function (item) { - this.itemSet.removeItem(item.id); + Graph3d.prototype.setSize = function (width, height) { + this.frame.style.width = width; + this.frame.style.height = height; + + this._resizeCanvas(); }; /** - * Reorder the items + * Resize the canvas to the current size of the frame */ - Group.prototype.order = function () { - var array = util.toArray(this.items); - var startArray = []; - var endArray = []; + Graph3d.prototype._resizeCanvas = function () { + this.frame.canvas.style.width = '100%'; + this.frame.canvas.style.height = '100%'; - 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 - }; + this.frame.canvas.width = this.frame.canvas.clientWidth; + this.frame.canvas.height = this.frame.canvas.clientHeight; - stack.orderByStart(this.orderedItems.byStart); - stack.orderByEnd(this.orderedItems.byEnd); + // adjust with for margin + this.frame.filter.style.width = this.frame.canvas.clientWidth - 2 * 10 + 'px'; }; /** - * Update the visible items - * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date - * @param {Item[]} visibleItems The previously visible items. - * @param {{start: number, end: number}} range Visible range - * @return {Item[]} visibleItems The new visible items. - * @private + * Start animation */ - Group.prototype._updateVisibleItems = 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; - var item, i; + Graph3d.prototype.animationStart = function () { + if (!this.frame.filter || !this.frame.filter.slider) throw 'No animation available'; - // 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; - } - }; + this.frame.filter.slider.play(); + }; - // 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 (i = 0; i < oldVisibleItems.length; i++) { - this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range); - } - } + /** + * Stop animation + */ + Graph3d.prototype.animationStop = function () { + if (!this.frame.filter || !this.frame.filter.slider) return; - // we do a binary search for the items that have only start values. - var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data', 'start'); + this.frame.filter.slider.stop(); + }; - // 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; - }); + /** + * Resize the center position based on the current values in this.defaultXCenter + * and this.defaultYCenter (which are strings with a percentage or a value + * in pixels). The center positions are the variables this.xCenter + * and this.yCenter + */ + Graph3d.prototype._resizeCenter = function () { + // calculate the horizontal center position + if (this.defaultXCenter.charAt(this.defaultXCenter.length - 1) === '%') { + this.xcenter = parseFloat(this.defaultXCenter) / 100 * this.frame.canvas.clientWidth; + } else { + this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px + } - // 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); - } + // calculate the vertical center position + if (this.defaultYCenter.charAt(this.defaultYCenter.length - 1) === '%') { + this.ycenter = parseFloat(this.defaultYCenter) / 100 * (this.frame.canvas.clientHeight - this.frame.filter.clientHeight); } else { - // we do a binary search for the items that have defined end times. - var initialPosByEnd = util.binarySearchCustom(orderedItems.byEnd, searchFunction, 'data', 'end'); + this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px + } + }; - // 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; - }); + /** + * Set the rotation and distance of the camera + * @param {Object} pos An object with the camera position. The object + * contains three parameters: + * - horizontal {Number} + * The horizontal rotation, between 0 and 2*PI. + * Optional, can be left undefined. + * - vertical {Number} + * 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. + * - distance {Number} + * The (normalized) distance of the camera to the + * center of the graph, a value between 0.71 and 5.0. + * Optional, can be left undefined. + */ + Graph3d.prototype.setCameraPosition = function (pos) { + if (pos === undefined) { + return; } - // finally, we reposition all the visible items. - for (i = 0; i < visibleItems.length; i++) { - item = visibleItems[i]; - if (!item.displayed) item.show(); - // reposition item horizontally - item.repositionX(); + if (pos.horizontal !== undefined && pos.vertical !== undefined) { + this.camera.setArmRotation(pos.horizontal, pos.vertical); } - // debug - //console.log("new line") - //if (this.groupId == null) { - // for (i = 0; i < orderedItems.byStart.length; i++) { - // item = orderedItems.byStart[i].data; - // console.log('start',i,initialPosByStart, item.start.valueOf(), item.content, item.start >= lowerBound && item.start <= upperBound,i == initialPosByStart ? "<------------------- HEREEEE" : "") - // } - // for (i = 0; i < orderedItems.byEnd.length; i++) { - // item = orderedItems.byEnd[i].data; - // console.log('rangeEnd',i,initialPosByEnd, item.end.valueOf(), item.content, item.end >= range.start && item.end <= range.end,i == initialPosByEnd ? "<------------------- HEREEEE" : "") - // } - //} + if (pos.distance !== undefined) { + this.camera.setArmLength(pos.distance); + } - return visibleItems; + this.redraw(); }; - Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) { - var item; - var i; - - if (initialPos != -1) { - 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); - } - } - } - } + /** + * Retrieve the current camera rotation + * @return {object} An object with parameters horizontal, vertical, and + * distance + */ + Graph3d.prototype.getCameraPosition = function () { + var pos = this.camera.getArmRotation(); + pos.distance = this.camera.getArmLength(); + return pos; }; /** - * 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 + * Load data into the 3D Graph */ - Group.prototype._checkIfVisible = function (item, visibleItems, range) { - if (item.isVisible(range)) { - if (!item.displayed) item.show(); - // reposition item horizontally - item.repositionX(); - visibleItems.push(item); + Graph3d.prototype._readData = function (data) { + // read the data + this._dataInitialize(data, this.style); + + if (this.dataFilter) { + // apply filtering + this.dataPoints = this.dataFilter._getDataPoints(); } else { - if (item.displayed) item.hide(); + // no filtering. load all data + this.dataPoints = this._getDataPoints(this.dataTable); } + + // draw the filter + this._redrawFilter(); }; /** - * 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 + * Replace the dataset of the Graph3d + * @param {Array | DataSet | DataView} data */ - 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(); + Graph3d.prototype.setData = function (data) { + this._readData(data); + this.redraw(); + + // start animation when option is true + if (this.animationAutoStart && this.dataFilter) { + this.animationStart(); } }; - module.exports = Group; - -/***/ }, -/* 31 */ -/***/ function(module, exports, __webpack_require__) { + /** + * Update the options. Options will be merged with current options + * @param {Object} options + */ + Graph3d.prototype.setOptions = function (options) { + var cameraPosition = undefined; - 'use strict'; + this.animationStop(); - var util = __webpack_require__(2); - var Group = __webpack_require__(30); + if (options !== undefined) { + // retrieve parameter values + if (options.width !== undefined) this.width = options.width; + if (options.height !== undefined) this.height = options.height; - /** - * @constructor BackgroundGroup - * @param {Number | String} groupId - * @param {Object} data - * @param {ItemSet} itemSet - */ - function BackgroundGroup(groupId, data, itemSet) { - Group.call(this, groupId, data, itemSet); + if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter; + if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter; - this.width = 0; - this.height = 0; - this.top = 0; - this.left = 0; - } + if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel; + if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel; + if (options.xLabel !== undefined) this.xLabel = options.xLabel; + if (options.yLabel !== undefined) this.yLabel = options.yLabel; + if (options.zLabel !== undefined) this.zLabel = options.zLabel; - BackgroundGroup.prototype = Object.create(Group.prototype); + if (options.xValueLabel !== undefined) this.xValueLabel = options.xValueLabel; + if (options.yValueLabel !== undefined) this.yValueLabel = options.yValueLabel; + if (options.zValueLabel !== undefined) this.zValueLabel = options.zValueLabel; - /** - * Repaint this group - * @param {{start: number, end: number}} range - * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin - * @param {boolean} [restack=false] Force restacking of all items - * @return {boolean} Returns true if the group is resized - */ - BackgroundGroup.prototype.redraw = function (range, margin, restack) { - var resized = false; + if (options.style !== undefined) { + var styleNumber = this._getStyleNumber(options.style); + if (styleNumber !== -1) { + this.style = styleNumber; + } + } + if (options.showGrid !== undefined) this.showGrid = options.showGrid; + if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective; + if (options.showShadow !== undefined) this.showShadow = options.showShadow; + if (options.tooltip !== undefined) this.showTooltip = options.tooltip; + if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls; + if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio; + if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio; - this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); + if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval; + if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload; + if (options.animationAutoStart !== undefined) this.animationAutoStart = options.animationAutoStart; - // calculate actual size - this.width = this.dom.background.offsetWidth; + if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth; + if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth; - // apply new height (just always zero for BackgroundGroup - this.dom.background.style.height = '0'; + if (options.xMin !== undefined) this.defaultXMin = options.xMin; + if (options.xStep !== undefined) this.defaultXStep = options.xStep; + if (options.xMax !== undefined) this.defaultXMax = options.xMax; + if (options.yMin !== undefined) this.defaultYMin = options.yMin; + if (options.yStep !== undefined) this.defaultYStep = options.yStep; + if (options.yMax !== undefined) this.defaultYMax = options.yMax; + if (options.zMin !== undefined) this.defaultZMin = options.zMin; + if (options.zStep !== undefined) this.defaultZStep = options.zStep; + if (options.zMax !== undefined) this.defaultZMax = options.zMax; + if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin; + if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax; - // 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); + if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition; + + if (cameraPosition !== undefined) { + this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical); + this.camera.setArmLength(cameraPosition.distance); + } else { + this.camera.setArmRotation(1, 0.5); + this.camera.setArmLength(1.7); + } } - return resized; + this._setBackgroundColor(options && options.backgroundColor); + + this.setSize(this.width, this.height); + + // re-load the data + if (this.dataTable) { + this.setData(this.dataTable); + } + + // start animation when option is true + if (this.animationAutoStart && this.dataFilter) { + this.animationStart(); + } }; /** - * Show this group: attach to the DOM + * Redraw the Graph. */ - BackgroundGroup.prototype.show = function () { - if (!this.dom.background.parentNode) { - this.itemSet.dom.background.appendChild(this.dom.background); + Graph3d.prototype.redraw = function () { + if (this.dataPoints === undefined) { + throw 'Error: graph data not initialized'; } - }; - module.exports = BackgroundGroup; + this._resizeCanvas(); + this._resizeCenter(); + this._redrawSlider(); + this._redrawClear(); + this._redrawAxis(); -/***/ }, -/* 32 */ -/***/ function(module, exports, __webpack_require__) { + if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { + this._redrawDataGrid(); + } else if (this.style === Graph3d.STYLE.LINE) { + this._redrawDataLine(); + } else if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { + this._redrawDataBar(); + } else { + // style is DOT, DOTLINE, DOTCOLOR, DOTSIZE + this._redrawDataDot(); + } - 'use strict'; + this._redrawInfo(); + this._redrawLegend(); + }; - var Hammer = __webpack_require__(41); - var util = __webpack_require__(2); - var DataSet = __webpack_require__(4); - var DataView = __webpack_require__(5); - var TimeStep = __webpack_require__(20); - var Component = __webpack_require__(25); - var Group = __webpack_require__(30); - var BackgroundGroup = __webpack_require__(31); - var BoxItem = __webpack_require__(57); - var PointItem = __webpack_require__(23); - var RangeItem = __webpack_require__(24); - var BackgroundItem = __webpack_require__(22); + /** + * Clear the canvas before redrawing + */ + Graph3d.prototype._redrawClear = function () { + var canvas = this.frame.canvas; + var ctx = canvas.getContext('2d'); - var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items - var BACKGROUND = '__background__'; // reserved group id for background items without group + ctx.clearRect(0, 0, canvas.width, canvas.height); + }; /** - * 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 + * Redraw the legend showing the colors */ - function ItemSet(body, options) { - this.body = body; + Graph3d.prototype._redrawLegend = function () { + var y; - this.defaultOptions = { - type: null, // 'box', 'point', 'range', 'background' - orientation: { - item: 'bottom' // item orientation: 'top' or 'bottom' - }, - align: 'auto', // alignment of box items - stack: true, - groupOrder: null, + if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { - selectable: true, - multiselect: false, + var dotSize = this.frame.clientWidth * 0.02; - editable: { - updateTime: false, - updateGroup: false, - add: false, - remove: false - }, + var widthMin, widthMax; + if (this.style === Graph3d.STYLE.DOTSIZE) { + widthMin = dotSize / 2; // px + widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function + } else { + widthMin = 20; // px + widthMax = 20; // px + } - snap: TimeStep.snap, + var height = Math.max(this.frame.clientHeight * 0.25, 100); + var top = this.margin; + var right = this.frame.clientWidth - this.margin; + var left = right - widthMax; + var bottom = top + height; + } - 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); - }, + var canvas = this.frame.canvas; + var ctx = canvas.getContext('2d'); + ctx.lineWidth = 1; + ctx.font = '14px arial'; // TODO: put in options - margin: { - item: { - horizontal: 10, - vertical: 10 - }, - axis: 20 - } - }; + if (this.style === Graph3d.STYLE.DOTCOLOR) { + // draw the color bar + var ymin = 0; + var ymax = height; // Todo: make height customizable + for (y = ymin; y < ymax; y++) { + var f = (y - ymin) / (ymax - ymin); - // options is shared by this ItemSet and all its items - this.options = util.extend({}, this.defaultOptions); + //var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function + var hue = f * 240; + var color = this._hsv2rgb(hue, 1, 1); - // options for getting items from the DataSet with the correct type - this.itemOptions = { - type: { start: 'Date', end: 'Date' } - }; + ctx.strokeStyle = color; + ctx.beginPath(); + ctx.moveTo(left, top + y); + ctx.lineTo(right, top + y); + ctx.stroke(); + } - this.conversion = { - toScreen: body.util.toScreen, - toTime: body.util.toTime - }; - this.dom = {}; - this.props = {}; - this.hammer = null; + ctx.strokeStyle = this.colorAxis; + ctx.strokeRect(left, top, widthMax, height); + } - var me = this; - this.itemsData = null; // DataSet - this.groupsData = null; // DataSet + if (this.style === Graph3d.STYLE.DOTSIZE) { + // draw border around color bar + ctx.strokeStyle = this.colorAxis; + ctx.fillStyle = this.colorDot; + ctx.beginPath(); + ctx.moveTo(left, top); + ctx.lineTo(right, top); + ctx.lineTo(right - widthMax + widthMin, bottom); + ctx.lineTo(left, bottom); + ctx.closePath(); + ctx.fill(); + ctx.stroke(); + } - // listeners for the DataSet of the items - this.itemListeners = { - 'add': function add(event, params, senderId) { - me._onAdd(params.items); - }, - 'update': function update(event, params, senderId) { - me._onUpdate(params.items); - }, - 'remove': function remove(event, params, senderId) { - me._onRemove(params.items); + if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { + // print values along the color bar + var gridLineLen = 5; // px + var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax - this.valueMin) / 5, true); + step.start(); + if (step.getCurrent() < this.valueMin) { + step.next(); } - }; + while (!step.end()) { + y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height; - // listeners for the DataSet of the groups - this.groupListeners = { - 'add': function add(event, params, senderId) { - me._onAddGroups(params.items); - }, - 'update': function update(event, params, senderId) { - me._onUpdateGroups(params.items); - }, - 'remove': function remove(event, params, senderId) { - me._onRemoveGroups(params.items); + ctx.beginPath(); + ctx.moveTo(left - gridLineLen, y); + ctx.lineTo(left, y); + ctx.stroke(); + + ctx.textAlign = 'right'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = this.colorAxis; + ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y); + + step.next(); } - }; - this.items = {}; // object with an Item for every data item - this.groups = {}; // Group object for every group - this.groupIds = []; + ctx.textAlign = 'right'; + ctx.textBaseline = 'top'; + var label = this.legendLabel; + ctx.fillText(label, right, bottom + this.margin); + } + }; - this.selection = []; // list with the ids of all selected nodes - this.stackDirty = true; // if true, all items will be restacked on next redraw + /** + * Redraw the filter + */ + Graph3d.prototype._redrawFilter = function () { + this.frame.filter.innerHTML = ''; - this.touchParams = {}; // stores properties while dragging - // create the HTML DOM + if (this.dataFilter) { + var options = { + 'visible': this.showAnimationControls + }; + var slider = new Slider(this.frame.filter, options); + this.frame.filter.slider = slider; - this._create(); + // TODO: css here is not nice here... + this.frame.filter.style.padding = '10px'; + //this.frame.filter.style.backgroundColor = '#EFEFEF'; - this.setOptions(options); - } + slider.setValues(this.dataFilter.values); + slider.setPlayInterval(this.animationInterval); - ItemSet.prototype = new Component(); + // create an event handler + var me = this; + var onchange = function onchange() { + var index = slider.getIndex(); - // available item types will be registered here - ItemSet.types = { - background: BackgroundItem, - box: BoxItem, - range: RangeItem, - point: PointItem + me.dataFilter.selectValue(index); + me.dataPoints = me.dataFilter._getDataPoints(); + + me.redraw(); + }; + slider.setOnChangeCallback(onchange); + } else { + this.frame.filter.slider = undefined; + } }; /** - * Create the HTML DOM for the ItemSet + * Redraw the slider */ - 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; + Graph3d.prototype._redrawSlider = function () { + if (this.frame.filter.slider !== undefined) { + this.frame.filter.slider.redraw(); + } + }; - // create foreground panel - var foreground = document.createElement('div'); - foreground.className = 'vis-foreground'; - frame.appendChild(foreground); - this.dom.foreground = foreground; + /** + * Redraw common information + */ + Graph3d.prototype._redrawInfo = function () { + if (this.dataFilter) { + var canvas = this.frame.canvas; + var ctx = canvas.getContext('2d'); - // create axis panel - var axis = document.createElement('div'); - axis.className = 'vis-axis'; - this.dom.axis = axis; + ctx.font = '14px arial'; // TODO: put in options + ctx.lineStyle = 'gray'; + ctx.fillStyle = 'gray'; + ctx.textAlign = 'left'; + ctx.textBaseline = 'top'; - // create labelset - var labelSet = document.createElement('div'); - labelSet.className = 'vis-labelset'; - this.dom.labelSet = labelSet; + var x = this.margin; + var y = this.margin; + ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y); + } + }; - // create ungrouped Group - this._updateUngrouped(); + /** + * Redraw the axis + */ + Graph3d.prototype._redrawAxis = function () { + var canvas = this.frame.canvas, + ctx = canvas.getContext('2d'), + from, + to, + step, + prettyStep, + text, + xText, + yText, + zText, + offset, + xOffset, + yOffset, + xMin2d, + xMax2d; - // create background Group - var backgroundGroup = new BackgroundGroup(BACKGROUND, null, this); - backgroundGroup.show(); - this.groups[BACKGROUND] = backgroundGroup; + // TODO: get the actual rendered style of the containerElement + //ctx.font = this.containerElement.style.font; + ctx.font = 24 / this.camera.getArmLength() + 'px arial'; - // 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); + // calculate the length for the short grid lines + var gridLenX = 0.025 / this.scale.x; + var gridLenY = 0.025 / this.scale.y; + var textMargin = 5 / this.camera.getArmLength(); // px + var armAngle = this.camera.getArmRotation().horizontal; - // 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)); + // draw x-grid lines + ctx.lineWidth = 1; + prettyStep = this.defaultXStep === undefined; + step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep); + step.start(); + if (step.getCurrent() < this.xMin) { + step.next(); + } + while (!step.end()) { + var x = step.getCurrent(); - // single select (or unselect) when tapping an item - this.hammer.on('tap', this._onSelectItem.bind(this)); + if (this.showGrid) { + from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); + to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); + ctx.strokeStyle = this.colorGrid; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); + } else { + from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); + to = this._convert3Dto2D(new Point3d(x, this.yMin + gridLenX, this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); - // multi select when holding mouse/touch, or on ctrl+click - this.hammer.on('press', this._onMultiSelectItem.bind(this)); + from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); + to = this._convert3Dto2D(new Point3d(x, this.yMax - gridLenX, this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); + } - // add item on doubletap - this.hammer.on('doubletap', this._onAddItem.bind(this)); + yText = Math.cos(armAngle) > 0 ? this.yMin : this.yMax; + text = this._convert3Dto2D(new Point3d(x, yText, this.zMin)); + if (Math.cos(armAngle * 2) > 0) { + ctx.textAlign = 'center'; + ctx.textBaseline = 'top'; + text.y += textMargin; + } else if (Math.sin(armAngle * 2) < 0) { + ctx.textAlign = 'right'; + ctx.textBaseline = 'middle'; + } else { + ctx.textAlign = 'left'; + ctx.textBaseline = 'middle'; + } + ctx.fillStyle = this.colorAxis; + ctx.fillText(' ' + this.xValueLabel(step.getCurrent()) + ' ', text.x, text.y); - // attach to the DOM - this.show(); - }; + step.next(); + } - /** - * 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', 'align', 'order', 'stack', 'selectable', 'multiselect', 'groupOrder', 'dataAttributes', 'template', 'hide', 'snap']; - util.selectiveExtend(fields, this.options, options); - - if ('orientation' in options) { - if (typeof options.orientation === 'string') { - this.options.orientation.item = options.orientation === 'top' ? 'top' : 'bottom'; - } else if (typeof options.orientation === 'object' && 'item' in options.orientation) { - this.options.orientation.item = options.orientation.item; - } - } + // draw y-grid lines + ctx.lineWidth = 1; + prettyStep = this.defaultYStep === undefined; + step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep); + step.start(); + if (step.getCurrent() < this.yMin) { + step.next(); + } + while (!step.end()) { + if (this.showGrid) { + from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); + to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); + ctx.strokeStyle = this.colorGrid; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); + } else { + from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); + to = this._convert3Dto2D(new Point3d(this.xMin + gridLenY, step.getCurrent(), this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); - 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 (typeof 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 (typeof options.margin.item === 'object') { - util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item); - } - } - } + from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); + to = this._convert3Dto2D(new Point3d(this.xMax - gridLenY, step.getCurrent(), this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); } - 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; - } else if (typeof options.editable === 'object') { - util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable); - } + xText = Math.sin(armAngle) > 0 ? this.xMin : this.xMax; + text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin)); + if (Math.cos(armAngle * 2) < 0) { + ctx.textAlign = 'center'; + ctx.textBaseline = 'top'; + text.y += textMargin; + } else if (Math.sin(armAngle * 2) > 0) { + ctx.textAlign = 'right'; + ctx.textBaseline = 'middle'; + } else { + ctx.textAlign = 'left'; + ctx.textBaseline = 'middle'; } + ctx.fillStyle = this.colorAxis; + ctx.fillText(' ' + this.yValueLabel(step.getCurrent()) + ' ', text.x, text.y); - // 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); - ['onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving'].forEach(addCallback); - - // force the itemSet to refresh: options like orientation and margins may be changed - this.markDirty(); + step.next(); } - }; - /** - * 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 = []; - this.stackDirty = true; - - if (options && options.refreshItems) { - util.forEach(this.items, function (item) { - item.dirty = true; - if (item.displayed) item.redraw(); - }); + // draw z-grid lines and axis + ctx.lineWidth = 1; + prettyStep = this.defaultZStep === undefined; + step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep); + step.start(); + if (step.getCurrent() < this.zMin) { + step.next(); } - }; - - /** - * Destroy the ItemSet - */ - ItemSet.prototype.destroy = function () { - this.hide(); - this.setItems(null); - this.setGroups(null); - - this.hammer = null; + xText = Math.cos(armAngle) > 0 ? this.xMin : this.xMax; + yText = Math.sin(armAngle) < 0 ? this.yMin : this.yMax; + while (!step.end()) { + // TODO: make z-grid lines really 3d? + from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent())); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(from.x - textMargin, from.y); + ctx.stroke(); - this.body = null; - this.conversion = null; - }; + ctx.textAlign = 'right'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = this.colorAxis; + ctx.fillText(this.zValueLabel(step.getCurrent()) + ' ', from.x - 5, from.y); - /** - * 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); + step.next(); } + ctx.lineWidth = 1; + from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); + to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); - // remove the axis with dots - if (this.dom.axis.parentNode) { - this.dom.axis.parentNode.removeChild(this.dom.axis); - } + // draw x-axis + ctx.lineWidth = 1; + // line at yMin + xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); + xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(xMin2d.x, xMin2d.y); + ctx.lineTo(xMax2d.x, xMax2d.y); + ctx.stroke(); + // line at ymax + xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); + xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(xMin2d.x, xMin2d.y); + ctx.lineTo(xMax2d.x, xMax2d.y); + ctx.stroke(); - // remove the labelset containing all group labels - if (this.dom.labelSet.parentNode) { - this.dom.labelSet.parentNode.removeChild(this.dom.labelSet); - } - }; + // draw y-axis + ctx.lineWidth = 1; + // line at xMin + from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); + to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); + // line at xMax + from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); + to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); + ctx.strokeStyle = this.colorAxis; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); - /** - * Show the component in the DOM (when not already visible). - * @return {Boolean} changed - */ - ItemSet.prototype.show = function () { - // show frame containing the items - if (!this.dom.frame.parentNode) { - this.body.dom.center.appendChild(this.dom.frame); + // draw x-label + var xLabel = this.xLabel; + if (xLabel.length > 0) { + yOffset = 0.1 / this.scale.y; + xText = (this.xMin + this.xMax) / 2; + yText = Math.cos(armAngle) > 0 ? this.yMin - yOffset : this.yMax + yOffset; + text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); + if (Math.cos(armAngle * 2) > 0) { + ctx.textAlign = 'center'; + ctx.textBaseline = 'top'; + } else if (Math.sin(armAngle * 2) < 0) { + ctx.textAlign = 'right'; + ctx.textBaseline = 'middle'; + } else { + ctx.textAlign = 'left'; + ctx.textBaseline = 'middle'; + } + ctx.fillStyle = this.colorAxis; + ctx.fillText(xLabel, text.x, text.y); } - // show axis with dots - if (!this.dom.axis.parentNode) { - this.body.dom.backgroundVertical.appendChild(this.dom.axis); + // draw y-label + var yLabel = this.yLabel; + if (yLabel.length > 0) { + xOffset = 0.1 / this.scale.x; + xText = Math.sin(armAngle) > 0 ? this.xMin - xOffset : this.xMax + xOffset; + yText = (this.yMin + this.yMax) / 2; + text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); + if (Math.cos(armAngle * 2) < 0) { + ctx.textAlign = 'center'; + ctx.textBaseline = 'top'; + } else if (Math.sin(armAngle * 2) > 0) { + ctx.textAlign = 'right'; + ctx.textBaseline = 'middle'; + } else { + ctx.textAlign = 'left'; + ctx.textBaseline = 'middle'; + } + ctx.fillStyle = this.colorAxis; + ctx.fillText(yLabel, text.x, text.y); } - // show labelset containing labels - if (!this.dom.labelSet.parentNode) { - this.body.dom.left.appendChild(this.dom.labelSet); + // draw z-label + var zLabel = this.zLabel; + if (zLabel.length > 0) { + offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis? + xText = Math.cos(armAngle) > 0 ? this.xMin : this.xMax; + yText = Math.sin(armAngle) < 0 ? this.yMin : this.yMax; + zText = (this.zMin + this.zMax) / 2; + text = this._convert3Dto2D(new Point3d(xText, yText, zText)); + ctx.textAlign = 'right'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = this.colorAxis; + ctx.fillText(zLabel, text.x - offset, text.y); } }; /** - * 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. + * Calculate the color based on the given value. + * @param {Number} H Hue, a value be between 0 and 360 + * @param {Number} S Saturation, a value between 0 and 1 + * @param {Number} V Value, a value between 0 and 1 */ - ItemSet.prototype.setSelection = function (ids) { - var i, ii, id, item; + Graph3d.prototype._hsv2rgb = function (H, S, V) { + var R, G, B, C, Hi, X; - if (ids == undefined) ids = []; - if (!Array.isArray(ids)) ids = [ids]; + C = V * S; + Hi = Math.floor(H / 60); // hi = 0,1,2,3,4,5 + X = C * (1 - Math.abs(H / 60 % 2 - 1)); - // 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(); - } + switch (Hi) { + case 0: + R = C;G = X;B = 0;break; + case 1: + R = X;G = C;B = 0;break; + case 2: + R = 0;G = C;B = X;break; + case 3: + R = 0;G = X;B = C;break; + case 4: + R = X;G = 0;B = C;break; + case 5: + R = C;G = 0;B = X;break; - // 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(); - } + default: + R = 0;G = 0;B = 0;break; } - }; - /** - * Get the selected items by their id - * @return {Array} ids The ids of the selected items - */ - ItemSet.prototype.getSelection = function () { - return this.selection.concat([]); + return 'RGB(' + parseInt(R * 255) + ',' + parseInt(G * 255) + ',' + parseInt(B * 255) + ')'; }; /** - * Get the id's of the currently visible items. - * @returns {Array} The ids of the visible items + * Draw all datapoints as a grid + * This function can be used when the style is 'grid' */ - ItemSet.prototype.getVisibleItems = function () { - var range = this.body.range.getRange(); - var left = this.body.util.toScreen(range.start); - var right = this.body.util.toScreen(range.end); + Graph3d.prototype._redrawDataGrid = function () { + var canvas = this.frame.canvas, + ctx = canvas.getContext('2d'), + point, + right, + top, + cross, + i, + topSideVisible, + fillStyle, + strokeStyle, + lineWidth, + h, + s, + v, + zAvg; - var ids = []; - for (var groupId in this.groups) { - if (this.groups.hasOwnProperty(groupId)) { - var group = this.groups[groupId]; - var rawVisibleItems = group.visibleItems; + if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? - // 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 (item.left < right && item.left + item.width > left) { - ids.push(item.id); - } - } - } - } + // calculate the translations and screen position of all points + for (i = 0; i < this.dataPoints.length; i++) { + var trans = this._convertPointToTranslation(this.dataPoints[i].point); + var screen = this._convertTranslationToScreen(trans); - return ids; - }; + this.dataPoints[i].trans = trans; + this.dataPoints[i].screen = screen; - /** - * 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; - } + // calculate the translation of the point at the bottom (needed for sorting) + var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); + this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; } - }; - /** - * 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, - editable = options.editable.updateTime || options.editable.updateGroup; + // sort the points on depth of their (x,y) position (not on z) + var sortDepth = function sortDepth(a, b) { + return b.dist - a.dist; + }; + this.dataPoints.sort(sortDepth); - // recalculate absolute position (before redrawing groups) - this.props.top = this.body.domProps.top.height + this.body.domProps.border.top; - this.props.left = this.body.domProps.left.width + this.body.domProps.border.left; + if (this.style === Graph3d.STYLE.SURFACE) { + for (i = 0; i < this.dataPoints.length; i++) { + point = this.dataPoints[i]; + right = this.dataPoints[i].pointRight; + top = this.dataPoints[i].pointTop; + cross = this.dataPoints[i].pointCross; - // update class name - frame.className = 'vis-itemset' + (editable ? ' vis-editable' : ''); + if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) { - // reorder the groups (if needed) - resized = this._orderGroups() || resized; + if (this.showGrayBottom || this.showShadow) { + // calculate the cross product of the two vectors from center + // to left and right, in order to know whether we are looking at the + // bottom or at the top side. We can also use the cross product + // for calculating light intensity + var aDiff = Point3d.subtract(cross.trans, point.trans); + var bDiff = Point3d.subtract(top.trans, right.trans); + var crossproduct = Point3d.crossProduct(aDiff, bDiff); + var len = crossproduct.length(); + // FIXME: there is a bug with determining the surface side (shadow or colored) - // 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; - if (zoomed) this.stackDirty = true; - this.lastVisibleInterval = visibleInterval; - this.props.lastWidth = this.props.width; + topSideVisible = crossproduct.z > 0; + } else { + topSideVisible = true; + } - var restack = this.stackDirty; - 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; + if (topSideVisible) { + // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 + zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4; + h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; + s = 1; // saturation - // redraw the background group - this.groups[BACKGROUND].redraw(range, nonFirstMargin, restack); + if (this.showShadow) { + v = Math.min(1 + crossproduct.x / len / 2, 1); // value. TODO: scale + fillStyle = this._hsv2rgb(h, s, v); + strokeStyle = fillStyle; + } else { + v = 1; + fillStyle = this._hsv2rgb(h, s, v); + strokeStyle = this.colorAxis; + } + } else { + fillStyle = 'gray'; + strokeStyle = this.colorAxis; + } + lineWidth = 0.5; - // redraw all regular groups - util.forEach(this.groups, function (group) { - var groupMargin = group == firstGroup ? firstMargin : nonFirstMargin; - var groupResized = group.redraw(range, groupMargin, restack); - resized = groupResized || resized; - height += group.height; - }); - height = Math.max(height, minHeight); - this.stackDirty = false; + ctx.lineWidth = lineWidth; + ctx.fillStyle = fillStyle; + ctx.strokeStyle = strokeStyle; + ctx.beginPath(); + ctx.moveTo(point.screen.x, point.screen.y); + ctx.lineTo(right.screen.x, right.screen.y); + ctx.lineTo(cross.screen.x, cross.screen.y); + ctx.lineTo(top.screen.x, top.screen.y); + ctx.closePath(); + ctx.fill(); + ctx.stroke(); + } + } + } else { + // grid style + for (i = 0; i < this.dataPoints.length; i++) { + point = this.dataPoints[i]; + right = this.dataPoints[i].pointRight; + top = this.dataPoints[i].pointTop; - // update frame height - frame.style.height = asSize(height); + if (point !== undefined) { + if (this.showPerspective) { + lineWidth = 2 / -point.trans.z; + } else { + lineWidth = 2 * -(this.eye.z / this.camera.getArmLength()); + } + } - // calculate actual size - this.props.width = frame.offsetWidth; - this.props.height = height; + if (point !== undefined && right !== undefined) { + // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 + zAvg = (point.point.z + right.point.z) / 2; + h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; - // 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); - this.dom.axis.style.left = '0'; + ctx.lineWidth = lineWidth; + ctx.strokeStyle = this._hsv2rgb(h, 1, 1); + ctx.beginPath(); + ctx.moveTo(point.screen.x, point.screen.y); + ctx.lineTo(right.screen.x, right.screen.y); + ctx.stroke(); + } - // check if this component is resized - resized = this._isResized() || resized; + if (point !== undefined && top !== undefined) { + // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 + zAvg = (point.point.z + top.point.z) / 2; + h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; - return resized; + ctx.lineWidth = lineWidth; + ctx.strokeStyle = this._hsv2rgb(h, 1, 1); + ctx.beginPath(); + ctx.moveTo(point.screen.x, point.screen.y); + ctx.lineTo(top.screen.x, top.screen.y); + ctx.stroke(); + } + } + } }; /** - * Get the first group, aligned with the axis - * @return {Group | null} firstGroup - * @private + * Draw all datapoints as dots. + * This function can be used when the style is 'dot' or 'dot-line' */ - 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]; + Graph3d.prototype._redrawDataDot = function () { + var canvas = this.frame.canvas; + var ctx = canvas.getContext('2d'); + var i; - return firstGroup || null; - }; + if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? - /** - * 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 background = this.groups[BACKGROUND]; - var item, itemId; + // calculate the translations of all points + for (i = 0; i < this.dataPoints.length; i++) { + var trans = this._convertPointToTranslation(this.dataPoints[i].point); + var screen = this._convertTranslationToScreen(trans); + this.dataPoints[i].trans = trans; + this.dataPoints[i].screen = screen; - if (this.groupsData) { - // remove the group holding all ungrouped items - if (ungrouped) { - ungrouped.hide(); - delete this.groups[UNGROUPED]; + // calculate the distance from the point at the bottom to the camera + var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); + this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; + } - 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(); - } - } + // order the translated points by depth + var sortDepth = function sortDepth(a, b) { + return b.dist - a.dist; + }; + this.dataPoints.sort(sortDepth); + + // draw the datapoints as colored circles + var dotSize = this.frame.clientWidth * 0.02; // px + for (i = 0; i < this.dataPoints.length; i++) { + var point = this.dataPoints[i]; + + if (this.style === Graph3d.STYLE.DOTLINE) { + // draw a vertical line from the bottom to the graph value + //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin)); + var from = this._convert3Dto2D(point.bottom); + ctx.lineWidth = 1; + ctx.strokeStyle = this.colorGrid; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(point.screen.x, point.screen.y); + ctx.stroke(); } - } 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); - } - } + // calculate radius for the circle + var size; + if (this.style === Graph3d.STYLE.DOTSIZE) { + size = dotSize / 2 + 2 * dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin); + } else { + size = dotSize; + } - ungrouped.show(); + var radius; + if (this.showPerspective) { + radius = size / -point.trans.z; + } else { + radius = size * -(this.eye.z / this.camera.getArmLength()); + } + if (radius < 0) { + radius = 0; } - } - }; - /** - * Get the element for the labelset - * @return {HTMLElement} labelSet - */ - ItemSet.prototype.getLabelSet = function () { - return this.dom.labelSet; + var hue, color, borderColor; + if (this.style === Graph3d.STYLE.DOTCOLOR) { + // calculate the color based on the value + hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; + color = this._hsv2rgb(hue, 1, 1); + borderColor = this._hsv2rgb(hue, 1, 0.8); + } else if (this.style === Graph3d.STYLE.DOTSIZE) { + color = this.colorDot; + borderColor = this.colorDotBorder; + } else { + // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 + hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; + color = this._hsv2rgb(hue, 1, 1); + borderColor = this._hsv2rgb(hue, 1, 0.8); + } + + // draw the circle + ctx.lineWidth = 1; + ctx.strokeStyle = borderColor; + ctx.fillStyle = color; + ctx.beginPath(); + ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI * 2, true); + ctx.fill(); + ctx.stroke(); + } }; /** - * Set items - * @param {vis.DataSet | null} items + * Draw all datapoints as bars. + * This function can be used when the style is 'bar', 'bar-color', or 'bar-size' */ - ItemSet.prototype.setItems = function (items) { - var me = this, - ids, - oldItemsData = this.itemsData; + Graph3d.prototype._redrawDataBar = function () { + var canvas = this.frame.canvas; + var ctx = canvas.getContext('2d'); + var i, j, surface, corners; - // 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 (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? - if (oldItemsData) { - // unsubscribe from old dataset - util.forEach(this.itemListeners, function (callback, event) { - oldItemsData.off(event, callback); - }); + // calculate the translations of all points + for (i = 0; i < this.dataPoints.length; i++) { + var trans = this._convertPointToTranslation(this.dataPoints[i].point); + var screen = this._convertTranslationToScreen(trans); + this.dataPoints[i].trans = trans; + this.dataPoints[i].screen = screen; - // remove all drawn items - ids = oldItemsData.getIds(); - this._onRemove(ids); + // calculate the distance from the point at the bottom to the camera + var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); + this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; } - if (this.itemsData) { - // subscribe to new dataset - var id = this.id; - util.forEach(this.itemListeners, function (callback, event) { - me.itemsData.on(event, callback, id); - }); + // order the translated points by depth + var sortDepth = function sortDepth(a, b) { + return b.dist - a.dist; + }; + this.dataPoints.sort(sortDepth); - // add all new items - ids = this.itemsData.getIds(); - this._onAdd(ids); + // draw the datapoints as bars + var xWidth = this.xBarWidth / 2; + var yWidth = this.yBarWidth / 2; + for (i = 0; i < this.dataPoints.length; i++) { + var point = this.dataPoints[i]; - // update the group holding all ungrouped items - this._updateUngrouped(); - } - }; + // determine color + var hue, color, borderColor; + if (this.style === Graph3d.STYLE.BARCOLOR) { + // calculate the color based on the value + hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; + color = this._hsv2rgb(hue, 1, 1); + borderColor = this._hsv2rgb(hue, 1, 0.8); + } else if (this.style === Graph3d.STYLE.BARSIZE) { + color = this.colorDot; + borderColor = this.colorDotBorder; + } else { + // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 + hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; + color = this._hsv2rgb(hue, 1, 1); + borderColor = this._hsv2rgb(hue, 1, 0.8); + } - /** - * Get the current items - * @returns {vis.DataSet | null} - */ - ItemSet.prototype.getItems = function () { - return this.itemsData; - }; + // calculate size for the bar + if (this.style === Graph3d.STYLE.BARSIZE) { + xWidth = this.xBarWidth / 2 * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); + yWidth = this.yBarWidth / 2 * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); + } - /** - * Set groups - * @param {vis.DataSet} groups - */ - ItemSet.prototype.setGroups = function (groups) { - var me = this, - ids; + // calculate all corner points + var me = this; + var point3d = point.point; + var top = [{ point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z) }, { point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z) }, { point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z) }, { point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z) }]; + var bottom = [{ point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin) }, { point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin) }, { point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin) }, { point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin) }]; - // unsubscribe from current dataset - if (this.groupsData) { - util.forEach(this.groupListeners, function (callback, event) { - me.groupsData.off(event, callback); + // calculate screen location of the points + top.forEach(function (obj) { + obj.screen = me._convert3Dto2D(obj.point); + }); + bottom.forEach(function (obj) { + obj.screen = me._convert3Dto2D(obj.point); }); - // 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'); - } + // create five sides, calculate both corner points and center points + var surfaces = [{ corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point) }, { corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point) }, { corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point) }, { corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point) }, { corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point) }]; + point.surfaces = surfaces; - if (this.groupsData) { - // subscribe to new dataset - var id = this.id; - util.forEach(this.groupListeners, function (callback, event) { - me.groupsData.on(event, callback, id); - }); + // calculate the distance of each of the surface centers to the camera + for (j = 0; j < surfaces.length; j++) { + surface = surfaces[j]; + var transCenter = this._convertPointToTranslation(surface.center); + surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z; + // TODO: this dept calculation doesn't work 100% of the cases due to perspective, + // but the current solution is fast/simple and works in 99.9% of all cases + // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9}) + } - // draw all ms - ids = this.groupsData.getIds(); - this._onAddGroups(ids); - } + // order the surfaces by their (translated) depth + surfaces.sort(function (a, b) { + var diff = b.dist - a.dist; + if (diff) return diff; - // update the group holding all ungrouped items - this._updateUngrouped(); + // if equal depth, sort the top surface last + if (a.corners === top) return 1; + if (b.corners === top) return -1; - // update the order of all items in each group - this._order(); + // both are equal + return 0; + }); - this.body.emitter.emit('change', { queue: true }); + // draw the ordered surfaces + ctx.lineWidth = 1; + ctx.strokeStyle = borderColor; + ctx.fillStyle = color; + // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside + for (j = 2; j < surfaces.length; j++) { + surface = surfaces[j]; + corners = surface.corners; + ctx.beginPath(); + ctx.moveTo(corners[3].screen.x, corners[3].screen.y); + ctx.lineTo(corners[0].screen.x, corners[0].screen.y); + ctx.lineTo(corners[1].screen.x, corners[1].screen.y); + ctx.lineTo(corners[2].screen.x, corners[2].screen.y); + ctx.lineTo(corners[3].screen.x, corners[3].screen.y); + ctx.fill(); + ctx.stroke(); + } + } }; /** - * Get the current groups - * @returns {vis.DataSet | null} groups + * Draw a line through all datapoints. + * This function can be used when the style is 'line' */ - ItemSet.prototype.getGroups = function () { - return this.groupsData; - }; + Graph3d.prototype._redrawDataLine = function () { + var canvas = this.frame.canvas, + ctx = canvas.getContext('2d'), + point, + i; - /** - * 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 (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? - 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); - } - }); + // calculate the translations of all points + for (i = 0; i < this.dataPoints.length; i++) { + var trans = this._convertPointToTranslation(this.dataPoints[i].point); + var screen = this._convertTranslationToScreen(trans); + + this.dataPoints[i].trans = trans; + this.dataPoints[i].screen = screen; } - }; - /** - * 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'); - }; + // start the line + if (this.dataPoints.length > 0) { + point = this.dataPoints[0]; - /** - * 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; + ctx.lineWidth = 1; // TODO: make customizable + ctx.strokeStyle = 'blue'; // TODO: make customizable + ctx.beginPath(); + ctx.moveTo(point.screen.x, point.screen.y); + } + + // draw the datapoints as colored circles + for (i = 1; i < this.dataPoints.length; i++) { + point = this.dataPoints[i]; + ctx.lineTo(point.screen.x, point.screen.y); + } + + // finish the line + if (this.dataPoints.length > 0) { + ctx.stroke(); } }; /** - * Handle updated items - * @param {Number[]} ids - * @protected + * Start a moving operation inside the provided parent element + * @param {Event} event The event that occurred (required for + * retrieving the mouse position) */ - ItemSet.prototype._onUpdate = function (ids) { - var me = this; + Graph3d.prototype._onMouseDown = function (event) { + event = event || window.event; - ids.forEach((function (id) { - var itemData = me.itemsData.get(id, me.itemOptions); - var item = me.items[id]; - var type = me._getType(itemData); + // check if mouse is still down (may be up when focus is lost for example + // in an iframe) + if (this.leftButtonDown) { + this._onMouseUp(event); + } - var constructor = ItemSet.types[type]; - var selected; + // only react on left mouse button down + this.leftButtonDown = event.which ? event.which === 1 : event.button === 1; + if (!this.leftButtonDown && !this.touchDown) return; - 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); - } - } + // get mouse position (different code for IE and all other browsers) + this.startMouseX = getMouseX(event); + this.startMouseY = getMouseY(event); - if (!item) { - // 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.startStart = new Date(this.start); + this.startEnd = new Date(this.end); + this.startArmRotation = this.camera.getArmRotation(); - this._order(); - this.stackDirty = true; // force re-stacking of all items next redraw - this.body.emitter.emit('change', { queue: true }); + 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', me.onmousemove); + util.addEventListener(document, 'mouseup', me.onmouseup); + util.preventDefault(event); }; /** - * Handle added items - * @param {Number[]} ids - * @protected + * Perform moving operating. + * This function activated from within the funcion Graph.mouseDown(). + * @param {Event} event Well, eehh, the event */ - ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate; + Graph3d.prototype._onMouseMove = function (event) { + event = event || window.event; - /** - * 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); - } - }); + // calculate change in mouse position + var diffX = parseFloat(getMouseX(event)) - this.startMouseX; + var diffY = parseFloat(getMouseY(event)) - this.startMouseY; - if (count) { - // update order - this._order(); - this.stackDirty = true; // force re-stacking of all items next redraw - this.body.emitter.emit('change', { queue: true }); + var horizontalNew = this.startArmRotation.horizontal + diffX / 200; + var verticalNew = this.startArmRotation.vertical + diffY / 200; + + var snapAngle = 4; // degrees + var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI); + + // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc... + // the -0.001 is to take care that the vertical axis is always drawn at the left front corner + if (Math.abs(Math.sin(horizontalNew)) < snapValue) { + horizontalNew = Math.round(horizontalNew / Math.PI) * Math.PI - 0.001; + } + if (Math.abs(Math.cos(horizontalNew)) < snapValue) { + horizontalNew = (Math.round(horizontalNew / Math.PI - 0.5) + 0.5) * Math.PI - 0.001; } - }; - /** - * 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(); - }); + // snap vertically to nice angles + if (Math.abs(Math.sin(verticalNew)) < snapValue) { + verticalNew = Math.round(verticalNew / Math.PI) * Math.PI; + } + if (Math.abs(Math.cos(verticalNew)) < snapValue) { + verticalNew = (Math.round(verticalNew / Math.PI - 0.5) + 0.5) * Math.PI; + } + + this.camera.setArmRotation(horizontalNew, verticalNew); + this.redraw(); + + // fire a cameraPositionChange event + var parameters = this.getCameraPosition(); + this.emit('cameraPositionChange', parameters); + + util.preventDefault(event); }; /** - * Handle updated groups - * @param {Number[]} ids - * @private + * Stop moving operating. + * This function activated from within the funcion Graph.mouseDown(). + * @param {event} event The event */ - ItemSet.prototype._onUpdateGroups = function (ids) { - this._onAddGroups(ids); + Graph3d.prototype._onMouseUp = function (event) { + this.frame.style.cursor = 'auto'; + this.leftButtonDown = false; + + // remove event listeners here + util.removeEventListener(document, 'mousemove', this.onmousemove); + util.removeEventListener(document, 'mouseup', this.onmouseup); + util.preventDefault(event); }; /** - * Handle changed groups (added or updated) - * @param {Number[]} ids - * @private + * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point + * @param {Event} event A mouse move event */ - ItemSet.prototype._onAddGroups = function (ids) { - var me = this; - - ids.forEach(function (id) { - var groupData = me.groupsData.get(id); - var group = me.groups[id]; + Graph3d.prototype._onTooltip = function (event) { + var delay = 300; // ms + var boundingRect = this.frame.getBoundingClientRect(); + var mouseX = getMouseX(event) - boundingRect.left; + var mouseY = getMouseY(event) - boundingRect.top; - if (!group) { - // check for reserved ids - if (id == UNGROUPED || id == BACKGROUND) { - throw new Error('Illegal group id. ' + id + ' is a reserved id.'); - } + if (!this.showTooltip) { + return; + } - var groupOptions = Object.create(me.options); - util.extend(groupOptions, { - height: null - }); + if (this.tooltipTimeout) { + clearTimeout(this.tooltipTimeout); + } - group = new Group(id, groupData, me); - me.groups[id] = group; + // (delayed) display of a tooltip only if no mouse button is down + if (this.leftButtonDown) { + this._hideTooltip(); + return; + } - // 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); - } - } + if (this.tooltip && this.tooltip.dataPoint) { + // tooltip is currently visible + var dataPoint = this._dataPointFromXY(mouseX, mouseY); + if (dataPoint !== this.tooltip.dataPoint) { + // datapoint changed + if (dataPoint) { + this._showTooltip(dataPoint); + } else { + this._hideTooltip(); } - - group.order(); - group.show(); - } else { - // update group - group.setData(groupData); } - }); + } else { + // tooltip is currently not visible + var me = this; + this.tooltipTimeout = setTimeout(function () { + me.tooltipTimeout = null; - this.body.emitter.emit('change', { queue: true }); + // show a tooltip if we have a data point + var dataPoint = me._dataPointFromXY(mouseX, mouseY); + if (dataPoint) { + me._showTooltip(dataPoint); + } + }, delay); + } }; /** - * Handle removed groups - * @param {Number[]} ids - * @private + * Event handler for touchstart event on mobile devices */ - ItemSet.prototype._onRemoveGroups = function (ids) { - var groups = this.groups; - ids.forEach(function (id) { - var group = groups[id]; - - if (group) { - group.hide(); - delete groups[id]; - } - }); + Graph3d.prototype._onTouchStart = function (event) { + this.touchDown = true; - this.markDirty(); + var me = this; + this.ontouchmove = function (event) { + me._onTouchMove(event); + }; + this.ontouchend = function (event) { + me._onTouchEnd(event); + }; + util.addEventListener(document, 'touchmove', me.ontouchmove); + util.addEventListener(document, 'touchend', me.ontouchend); - this.body.emitter.emit('change', { queue: true }); + this._onMouseDown(event); }; /** - * Reorder the groups if needed - * @return {boolean} changed - * @private + * Event handler for touchmove event on mobile devices */ - ItemSet.prototype._orderGroups = function () { - if (this.groupsData) { - // reorder the groups - var groupIds = this.groupsData.getIds({ - order: this.options.groupOrder - }); - - 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; - } + Graph3d.prototype._onTouchMove = function (event) { + this._onMouseMove(event); }; /** - * Add a new item - * @param {Item} item - * @private + * Event handler for touchend event on mobile devices */ - ItemSet.prototype._addItem = function (item) { - this.items[item.id] = item; + Graph3d.prototype._onTouchEnd = function (event) { + this.touchDown = false; - // add to group - var groupId = this._getGroupId(item.data); - var group = this.groups[groupId]; - if (group) group.add(item); + util.removeEventListener(document, 'touchmove', this.ontouchmove); + util.removeEventListener(document, 'touchend', this.ontouchend); + + this._onMouseUp(event); }; /** - * Update an existing item - * @param {Item} item - * @param {Object} itemData - * @private + * Event handler for mouse wheel event, used to zoom the graph + * Code from http://adomas.org/javascript-mouse-wheel/ + * @param {event} event The event */ - ItemSet.prototype._updateItem = function (item, itemData) { - var oldGroupId = item.data.group; - var oldSubGroupId = item.data.subgroup; + Graph3d.prototype._onWheel = function (event) { + if (!event) /* For IE. */ + event = window.event; - // update the items data (will redraw the item when displayed) - item.setData(itemData); + // 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; + } - // update group - if (oldGroupId != item.data.group || oldSubGroupId != item.data.subgroup) { - var oldGroup = this.groups[oldGroupId]; - if (oldGroup) oldGroup.remove(item); + // 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) { + var oldLength = this.camera.getArmLength(); + var newLength = oldLength * (1 - delta / 10); - var groupId = this._getGroupId(item.data); - var group = this.groups[groupId]; - if (group) group.add(item); + this.camera.setArmLength(newLength); + this.redraw(); + + this._hideTooltip(); } + + // fire a cameraPositionChange event + var parameters = this.getCameraPosition(); + this.emit('cameraPositionChange', parameters); + + // Prevent default actions caused by mouse wheel. + // That might be ugly, but we handle scrolls somehow + // anyway, so don't bother here.. + util.preventDefault(event); }; /** - * 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 + * Test whether a point lies inside given 2D triangle + * @param {Point2d} point + * @param {Point2d[]} triangle + * @return {boolean} Returns true if given point lies inside or on the edge of the triangle * @private */ - ItemSet.prototype._removeItem = function (item) { - // remove from DOM - item.hide(); + Graph3d.prototype._insideTriangle = function (point, triangle) { + var a = triangle[0], + b = triangle[1], + c = triangle[2]; - // remove from items - delete this.items[item.id]; + function sign(x) { + return x > 0 ? 1 : x < 0 ? -1 : 0; + } - // remove from selection - var index = this.selection.indexOf(item.id); - if (index != -1) this.selection.splice(index, 1); + var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x)); + var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x)); + var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x)); - // remove from group - item.parent && item.parent.remove(item); + // each of the three signs must be either equal to each other or zero + return (as == 0 || bs == 0 || as == bs) && (bs == 0 || cs == 0 || bs == cs) && (as == 0 || cs == 0 || as == cs); }; /** - * Create an array containing all items being a range (having an end date) - * @param array - * @returns {Array} + * Find a data point close to given screen position (x, y) + * @param {Number} x + * @param {Number} y + * @return {Object | null} The closest data point or null if not close to any data point * @private */ - ItemSet.prototype._constructByEndArray = function (array) { - var endArray = []; + Graph3d.prototype._dataPointFromXY = function (x, y) { + var i, + distMax = 100, + // px + dataPoint = null, + closestDataPoint = null, + closestDist = null, + center = new Point2d(x, y); - for (var i = 0; i < array.length; i++) { - if (array[i] instanceof RangeItem) { - endArray.push(array[i]); + if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { + // the data points are ordered from far away to closest + for (i = this.dataPoints.length - 1; i >= 0; i--) { + dataPoint = this.dataPoints[i]; + var surfaces = dataPoint.surfaces; + if (surfaces) { + for (var s = surfaces.length - 1; s >= 0; s--) { + // split each surface in two triangles, and see if the center point is inside one of these + var surface = surfaces[s]; + var corners = surface.corners; + var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen]; + var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen]; + if (this._insideTriangle(center, triangle1) || this._insideTriangle(center, triangle2)) { + // return immediately at the first hit + return dataPoint; + } + } + } + } + } else { + // find the closest data point, using distance to the center of the point on 2d screen + for (i = 0; i < this.dataPoints.length; i++) { + dataPoint = this.dataPoints[i]; + var point = dataPoint.screen; + if (point) { + var distX = Math.abs(x - point.x); + var distY = Math.abs(y - point.y); + var dist = Math.sqrt(distX * distX + distY * distY); + + if ((closestDist === null || dist < closestDist) && dist < distMax) { + closestDist = dist; + closestDataPoint = dataPoint; + } + } } } - return endArray; - }; - /** - * Register the clicked item on touch, before dragStart is initiated. - * - * dragStart is initiated from a mousemove event, AFTER the mouse/touch is - * already moving. Therefore, the mouse/touch can sometimes be above an other - * DOM element than the item itself. - * - * @param {Event} event - * @private - */ - ItemSet.prototype._onTouch = function (event) { - // store the touched item, used in _onDragStart - this.touchParams.item = this.itemFromTarget(event); - this.touchParams.dragLeftItem = event.target.dragLeftItem || false; - this.touchParams.dragRightItem = event.target.dragRightItem || false; - this.touchParams.itemProps = null; + return closestDataPoint; }; /** - * Start dragging the selected events - * @param {Event} event + * Display a tooltip for given data point + * @param {Object} dataPoint * @private */ - ItemSet.prototype._onDragStart = function (event) { - if (!this.options.editable.updateTime && !this.options.editable.updateGroup) { - return; - } + Graph3d.prototype._showTooltip = function (dataPoint) { + var content, line, dot; - var item = this.touchParams.item || null; - var me = this; - var props; + if (!this.tooltip) { + content = document.createElement('div'); + content.style.position = 'absolute'; + content.style.padding = '10px'; + content.style.border = '1px solid #4d4d4d'; + content.style.color = '#1a1a1a'; + content.style.background = 'rgba(255,255,255,0.7)'; + content.style.borderRadius = '2px'; + content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)'; - if (item && item.selected) { - var dragLeftItem = this.touchParams.dragLeftItem; - var dragRightItem = this.touchParams.dragRightItem; + line = document.createElement('div'); + line.style.position = 'absolute'; + line.style.height = '40px'; + line.style.width = '0'; + line.style.borderLeft = '1px solid #4d4d4d'; - if (dragLeftItem) { - props = { - item: dragLeftItem, - initialX: event.center.x, - dragLeft: true, - data: util.extend({}, item.data) // clone the items data - }; + dot = document.createElement('div'); + dot.style.position = 'absolute'; + dot.style.height = '0'; + dot.style.width = '0'; + dot.style.border = '5px solid #4d4d4d'; + dot.style.borderRadius = '5px'; - this.touchParams.itemProps = [props]; - } else if (dragRightItem) { - props = { - item: dragRightItem, - initialX: event.center.x, - dragRight: true, - data: util.extend({}, item.data) // clone the items data - }; + this.tooltip = { + dataPoint: null, + dom: { + content: content, + line: line, + dot: dot + } + }; + } else { + content = this.tooltip.dom.content; + line = this.tooltip.dom.line; + dot = this.tooltip.dom.dot; + } - this.touchParams.itemProps = [props]; - } else { - this.touchParams.itemProps = this.getSelection().map(function (id) { - var item = me.items[id]; - var props = { - item: item, - initialX: event.center.x, - data: util.extend({}, item.data) // clone the items data - }; - - return props; - }); - } + this._hideTooltip(); - event.stopPropagation(); - } else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) { - // create a new range item when dragging with ctrl key down - this._onDragStartAddItem(event); + this.tooltip.dataPoint = dataPoint; + if (typeof this.showTooltip === 'function') { + content.innerHTML = this.showTooltip(dataPoint.point); + } else { + content.innerHTML = '' + '' + '' + '' + '
x:' + dataPoint.point.x + '
y:' + dataPoint.point.y + '
z:' + dataPoint.point.z + '
'; } + + content.style.left = '0'; + content.style.top = '0'; + this.frame.appendChild(content); + this.frame.appendChild(line); + this.frame.appendChild(dot); + + // calculate sizes + var contentWidth = content.offsetWidth; + var contentHeight = content.offsetHeight; + var lineHeight = line.offsetHeight; + var dotWidth = dot.offsetWidth; + var dotHeight = dot.offsetHeight; + + var left = dataPoint.screen.x - contentWidth / 2; + left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth); + + line.style.left = dataPoint.screen.x + 'px'; + line.style.top = dataPoint.screen.y - lineHeight + 'px'; + content.style.left = left + 'px'; + content.style.top = dataPoint.screen.y - lineHeight - contentHeight + 'px'; + dot.style.left = dataPoint.screen.x - dotWidth / 2 + 'px'; + dot.style.top = dataPoint.screen.y - dotHeight / 2 + 'px'; }; /** - * Start creating a new range item by dragging. - * @param {Event} event + * Hide the tooltip when displayed * @private */ - ItemSet.prototype._onDragStartAddItem = function (event) { - var snap = this.options.snap || null; - var xAbs = util.getAbsoluteLeft(this.dom.frame); - var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px - var time = this.body.util.toTime(x); - var scale = this.body.util.getScale(); - var step = this.body.util.getStep(); - var start = snap ? snap(time, scale, step) : start; - var end = start; - - var itemData = { - type: 'range', - start: start, - end: end, - content: 'new item' - }; - - var id = util.randomUUID(); - itemData[this.itemsData._fieldId] = id; + Graph3d.prototype._hideTooltip = function () { + if (this.tooltip) { + this.tooltip.dataPoint = null; - var group = this.groupFromTarget(event); - if (group) { - itemData.group = group.groupId; + for (var prop in this.tooltip.dom) { + if (this.tooltip.dom.hasOwnProperty(prop)) { + var elem = this.tooltip.dom[prop]; + if (elem && elem.parentNode) { + elem.parentNode.removeChild(elem); + } + } + } } + }; - var newItem = new RangeItem(itemData, this.conversion, this.options); - newItem.id = id; // TODO: not so nice setting id afterwards - newItem.data = itemData; - this._addItem(newItem); - - var props = { - item: newItem, - dragRight: true, - initialX: event.center.x, - data: util.extend({}, itemData) - }; - this.touchParams.itemProps = [props]; + /**--------------------------------------------------------------------------**/ - event.stopPropagation(); - }; + /** + * Get the horizontal mouse position from a mouse event + * @param {Event} event + * @return {Number} mouse x + */ + function getMouseX(event) { + if ('clientX' in event) return event.clientX; + return event.targetTouches[0] && event.targetTouches[0].clientX || 0; + } /** - * Drag selected items + * Get the vertical mouse position from a mouse event * @param {Event} event - * @private + * @return {Number} mouse y */ - ItemSet.prototype._onDrag = function (event) { - if (this.touchParams.itemProps) { - event.stopPropagation(); + function getMouseY(event) { + if ('clientY' in event) return event.clientY; + return event.targetTouches[0] && event.targetTouches[0].clientY || 0; + } - var me = this; - var snap = this.options.snap || null; - var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width; - var scale = this.body.util.getScale(); - var step = this.body.util.getStep(); + module.exports = Graph3d; - // move - this.touchParams.itemProps.forEach(function (props) { - var newProps = {}; - var current = me.body.util.toTime(event.center.x - xOffset); - var initial = me.body.util.toTime(props.initialX - xOffset); - var offset = current - initial; + // use use defaults - var itemData = util.extend({}, props.item.data); // clone the data +/***/ }, +/* 18 */ +/***/ function(module, exports, __webpack_require__) { - if (me.options.editable.updateTime) { - if (props.dragLeft) { - // drag left side of a range item - if (itemData.start != undefined) { - var initialStart = util.convert(props.data.start, 'Date'); - var start = new Date(initialStart.valueOf() + offset); - itemData.start = snap ? snap(start, scale, step) : start; - } - } else if (props.dragRight) { - // drag right side of a range item - if (itemData.end != undefined) { - var initialEnd = util.convert(props.data.end, 'Date'); - var end = new Date(initialEnd.valueOf() + offset); - itemData.end = snap ? snap(end, scale, step) : end; - } - } else { - // drag both start and end - if (itemData.start != undefined) { - var initialStart = util.convert(props.data.start, 'Date').valueOf(); - var start = new Date(initialStart + offset); + /** + * @prototype Point2d + * @param {Number} [x] + * @param {Number} [y] + */ + "use strict"; - if (itemData.end != undefined) { - var initialEnd = util.convert(props.data.end, 'Date'); - var duration = initialEnd.valueOf() - initialStart.valueOf(); + function Point2d(x, y) { + this.x = x !== undefined ? x : 0; + this.y = y !== undefined ? y : 0; + } - itemData.start = snap ? snap(start, scale, step) : start; - itemData.end = new Date(itemData.start.valueOf() + duration); - } else { - itemData.start = snap ? snap(start, scale, step) : start; - } - } - } - } + module.exports = Point2d; - if (me.options.editable.updateGroup && (!props.dragLeft && !props.dragRight)) { - if (itemData.group != undefined) { - // drag from one group to another - var group = me.groupFromTarget(event); - if (group) { - itemData.group = group.groupId; - } - } - } +/***/ }, +/* 19 */ +/***/ function(module, exports, __webpack_require__) { - // confirm moving the item - me.options.onMoving(itemData, function (itemData) { - if (itemData) { - props.item.setData(itemData); - } - }); - }); + + /** + * Expose `Emitter`. + */ - this.stackDirty = true; // force re-stacking of all items next redraw - this.body.emitter.emit('change'); - } - }; + module.exports = Emitter; /** - * Move an item to another group - * @param {Item} item - * @param {String | Number} groupId - * @private + * Initialize a new `Emitter`. + * + * @api public */ - ItemSet.prototype._moveToGroup = function (item, groupId) { - var group = this.groups[groupId]; - if (group && group.groupId != item.data.group) { - var oldGroup = item.parent; - oldGroup.remove(item); - oldGroup.order(); - group.add(item); - group.order(); - item.data.group = group.groupId; - } + function Emitter(obj) { + if (obj) return mixin(obj); }; /** - * End of dragging selected items - * @param {Event} event - * @private + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private */ - ItemSet.prototype._onDragEnd = function (event) { - if (this.touchParams.itemProps) { - event.stopPropagation(); - // prepare a change set for the changed items - var changes = []; - var me = this; - var dataset = this.itemsData.getDataSet(); + function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; + } - var itemProps = this.touchParams.itemProps; - this.touchParams.itemProps = null; - itemProps.forEach(function (props) { - var id = props.item.id; - var exists = me.itemsData.get(id, me.itemOptions) != null; + /** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ - if (!exists) { - // add a new item - me.options.onAdd(props.item.data, function (itemData) { - me._removeItem(props.item); // remove temporary item - if (itemData) { - me.itemsData.getDataSet().add(itemData); - } + Emitter.prototype.on = + Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks[event] = this._callbacks[event] || []) + .push(fn); + return this; + }; - // force re-stacking of all items next redraw - me.stackDirty = true; - me.body.emitter.emit('change'); - }); - } else { - // update existing item - var itemData = util.extend({}, props.item.data); // clone the data - me.options.onMove(itemData, function (itemData) { - if (itemData) { - // apply changes - itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined) - changes.push(itemData); - } else { - // restore original values - props.item.setData(props.data); + /** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ - me.stackDirty = true; // force re-stacking of all items next redraw - me.body.emitter.emit('change'); - } - }); - } - }); + Emitter.prototype.once = function(event, fn){ + var self = this; + this._callbacks = this._callbacks || {}; - // apply the changes to the data (if there are changes) - if (changes.length) { - dataset.update(changes); - } + function on() { + self.off(event, on); + fn.apply(this, arguments); } + + on.fn = fn; + this.on(event, on); + return this; }; /** - * Handle selecting/deselecting an item when tapping it - * @param {Event} event - * @private + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public */ - ItemSet.prototype._onSelectItem = function (event) { - if (!this.options.selectable) return; - var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey); - var shiftKey = event.srcEvent && event.srcEvent.shiftKey; - if (ctrlKey || shiftKey) { - this._onMultiSelectItem(event); - return; - } + Emitter.prototype.off = + Emitter.prototype.removeListener = + Emitter.prototype.removeAllListeners = + Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; - var oldSelection = this.getSelection(); + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } - var item = this.itemFromTarget(event); - var selection = item ? [item.id] : []; - this.setSelection(selection); + // specific event + var callbacks = this._callbacks[event]; + if (!callbacks) return this; - var newSelection = this.getSelection(); + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks[event]; + return this; + } - // emit a select event, - // except when old selection is empty and new selection is still empty - if (newSelection.length > 0 || oldSelection.length > 0) { - this.body.emitter.emit('select', { - items: newSelection - }); + // 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; }; /** - * Handle creation and updates of an item on double tap - * @param event - * @private + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} */ - ItemSet.prototype._onAddItem = function (event) { - if (!this.options.selectable) return; - if (!this.options.editable.add) return; - - var me = this; - var snap = this.options.snap || null; - var item = this.itemFromTarget(event); - - event.stopPropagation(); - - if (item) { - // update item - - // execute async handler to update the item (or cancel it) - var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset - this.options.onUpdate(itemData, function (itemData) { - if (itemData) { - me.itemsData.getDataSet().update(itemData); - } - }); - } else { - // add item - var xAbs = util.getAbsoluteLeft(this.dom.frame); - var x = event.center.x - xAbs; - var start = this.body.util.toTime(x); - var scale = this.body.util.getScale(); - var step = this.body.util.getStep(); - var newItem = { - start: snap ? snap(start, scale, step) : start, - content: 'new item' - }; + Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks[event]; - // when default type is a range, add a default end date to the new item - if (this.options.type === 'range') { - var end = this.body.util.toTime(x + this.props.width / 5); - newItem.end = snap ? snap(end, scale, step) : end; + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); } + } - newItem[this.itemsData._fieldId] = util.randomUUID(); + return this; + }; - var group = this.groupFromTarget(event); - if (group) { - newItem.group = group.groupId; - } + /** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ - // execute async handler to customize (or cancel) adding an item - this.options.onAdd(newItem, function (item) { - if (item) { - me.itemsData.getDataSet().add(item); - // TODO: need to trigger a redraw? - } - }); - } + Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks[event] || []; }; /** - * Handle selecting/deselecting multiple items when holding an item - * @param {Event} event - * @private + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public */ - ItemSet.prototype._onMultiSelectItem = function (event) { - if (!this.options.selectable) return; - - var item = this.itemFromTarget(event); - if (item) { - // multi select items (if allowed) + Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; + }; - var selection = this.options.multiselect ? this.getSelection() // take current selection - : []; // deselect current selection - var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false; +/***/ }, +/* 20 */ +/***/ function(module, exports, __webpack_require__) { - if (shiftKey && this.options.multiselect) { - // select all items between the old selection and the tapped item + /** + * @prototype Point3d + * @param {Number} [x] + * @param {Number} [y] + * @param {Number} [z] + */ + "use strict"; - // determine the selection range - selection.push(item.id); - var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions)); + function Point3d(x, y, z) { + this.x = x !== undefined ? x : 0; + this.y = y !== undefined ? y : 0; + this.z = z !== undefined ? z : 0; + }; - // select all items within the selection range - selection = []; - for (var id in this.items) { - if (this.items.hasOwnProperty(id)) { - var _item = this.items[id]; - var start = _item.data.start; - var end = _item.data.end !== undefined ? _item.data.end : start; - - if (start >= range.min && end <= range.max && !(_item instanceof BackgroundItem)) { - selection.push(_item.id); // do not use id but item.id, id itself is stringified - } - } - } - } else { - // add/remove this item from the current selection - var index = selection.indexOf(item.id); - if (index == -1) { - // item is not yet selected -> select it - selection.push(item.id); - } else { - // item is already selected -> deselect it - selection.splice(index, 1); - } - } - - this.setSelection(selection); - - this.body.emitter.emit('select', { - items: this.getSelection() - }); - } - }; + /** + * 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; + }; /** - * Calculate the time range of a list of items - * @param {Array.} itemsData - * @return {{min: Date, max: Date}} Returns the range of the provided items - * @private + * Add the two provided points, returns a+b + * @param {Point3d} a + * @param {Point3d} b + * @return {Point3d} a+b */ - ItemSet._getItemRange = function (itemsData) { - var max = null; - var min = null; - - itemsData.forEach(function (data) { - if (min == null || data.start < min) { - min = data.start; - } - - if (data.end != undefined) { - if (max == null || data.end > max) { - max = data.end; - } - } else { - if (max == null || data.start > max) { - max = data.start; - } - } - }); - - return { - min: min, - max: max - }; + 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; }; /** - * Find an item from an event target: - * searches for the attribute 'timeline-item' in the event target's element tree - * @param {Event} event - * @return {Item | null} item + * Calculate the average of two 3d points + * @param {Point3d} a + * @param {Point3d} b + * @return {Point3d} The average, (a+b)/2 */ - ItemSet.prototype.itemFromTarget = function (event) { - var target = event.target; - while (target) { - if (target.hasOwnProperty('timeline-item')) { - return target['timeline-item']; - } - target = target.parentNode; - } - - return null; + Point3d.avg = function (a, b) { + return new Point3d((a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2); }; /** - * Find the Group from an event target: - * searches for the attribute 'timeline-group' in the event target's element tree - * @param {Event} event - * @return {Group | null} group + * 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 */ - ItemSet.prototype.groupFromTarget = function (event) { - var clientY = event.center ? event.center.y : event.clientY; - for (var i = 0; i < this.groupIds.length; i++) { - var groupId = this.groupIds[i]; - var group = this.groups[groupId]; - var foreground = group.dom.foreground; - var top = util.getAbsoluteTop(foreground); - if (clientY > top && clientY < top + foreground.offsetHeight) { - return group; - } + Point3d.crossProduct = function (a, b) { + var crossproduct = new Point3d(); - if (this.options.orientation.item === 'top') { - if (i === this.groupIds.length - 1 && clientY > top) { - return group; - } - } else { - if (i === 0 && clientY < top + foreground.offset) { - return group; - } - } - } + 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 null; + return crossproduct; }; /** - * Find the ItemSet from an event target: - * searches for the attribute 'timeline-itemset' in the event target's element tree - * @param {Event} event - * @return {ItemSet | null} item + * Rtrieve the length of the vector (or the distance from this point to the origin + * @return {Number} length */ - ItemSet.itemSetFromTarget = function (event) { - var target = event.target; - while (target) { - if (target.hasOwnProperty('timeline-itemset')) { - return target['timeline-itemset']; - } - target = target.parentNode; - } - - return null; + Point3d.prototype.length = function () { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); }; - module.exports = ItemSet; + module.exports = Point3d; /***/ }, -/* 33 */ +/* 21 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var util = __webpack_require__(2); - var DOMutil = __webpack_require__(3); - var Component = __webpack_require__(25); + var Point3d = __webpack_require__(20); /** - * Legend for Graph2d + * @class Camera + * 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 */ - function Legend(body, options, side, linegraphOptions) { - this.body = body; - this.defaultOptions = { - enabled: true, - icons: true, - iconSize: 20, - iconSpacing: 6, - left: { - visible: true, - position: 'top-left' // top/bottom - left,center,right - }, - right: { - visible: true, - position: 'top-left' // top/bottom - left,center,right - } - }; - this.side = side; - this.options = util.extend({}, this.defaultOptions); - this.linegraphOptions = linegraphOptions; + function Camera() { + this.armLocation = new Point3d(); + this.armRotation = {}; + this.armRotation.horizontal = 0; + this.armRotation.vertical = 0; + this.armLength = 1.7; - this.svgElements = {}; - this.dom = {}; - this.groups = {}; - this.amountOfGroups = 0; - this._create(); + this.cameraLocation = new Point3d(); + this.cameraRotation = new Point3d(0.5 * Math.PI, 0, 0); - this.setOptions(options); + this.calculateCameraOrientation(); } - Legend.prototype = new Component(); + /** + * 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; - Legend.prototype.clear = function () { - this.groups = {}; - this.amountOfGroups = 0; + this.calculateCameraOrientation(); }; - Legend.prototype.addGroup = function (label, graphOptions) { + /** + * 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 (!this.groups.hasOwnProperty(label)) { - this.groups[label] = graphOptions; + 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; } - this.amountOfGroups += 1; - }; - Legend.prototype.updateGroup = function (label, graphOptions) { - this.groups[label] = graphOptions; + if (horizontal !== undefined || vertical !== undefined) { + this.calculateCameraOrientation(); + } }; - Legend.prototype.removeGroup = function (label) { - if (this.groups.hasOwnProperty(label)) { - delete this.groups[label]; - this.amountOfGroups -= 1; - } + /** + * 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; }; - Legend.prototype._create = function () { - this.dom.frame = document.createElement('div'); - this.dom.frame.className = 'vis-legend'; - this.dom.frame.style.position = 'absolute'; - this.dom.frame.style.top = '10px'; - this.dom.frame.style.display = 'block'; + /** + * 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.dom.textArea = document.createElement('div'); - this.dom.textArea.className = 'vis-legend-text'; - this.dom.textArea.style.position = 'relative'; - this.dom.textArea.style.top = '0px'; + this.armLength = length; - this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - this.svg.style.position = 'absolute'; - this.svg.style.top = 0 + 'px'; - this.svg.style.width = this.options.iconSize + 5 + 'px'; - this.svg.style.height = '100%'; + // 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) this.armLength = 5; - this.dom.frame.appendChild(this.svg); - this.dom.frame.appendChild(this.dom.textArea); + this.calculateCameraOrientation(); }; /** - * Hide the component from the DOM + * Retrieve the arm length + * @return {Number} length */ - Legend.prototype.hide = function () { - // remove the frame containing the items - if (this.dom.frame.parentNode) { - this.dom.frame.parentNode.removeChild(this.dom.frame); - } + Camera.prototype.getArmLength = function () { + return this.armLength; }; /** - * Show the component in the DOM (when not already visible). - * @return {Boolean} changed + * Retrieve the camera location + * @return {Point3d} cameraLocation */ - Legend.prototype.show = function () { - // show frame containing the items - if (!this.dom.frame.parentNode) { - this.body.dom.center.appendChild(this.dom.frame); - } + Camera.prototype.getCameraLocation = function () { + return this.cameraLocation; }; - Legend.prototype.setOptions = function (options) { - var fields = ['enabled', 'orientation', 'icons', 'left', 'right']; - util.selectiveDeepExtend(fields, this.options, options); + /** + * Retrieve the camera rotation + * @return {Point3d} cameraRotation + */ + Camera.prototype.getCameraRotation = function () { + return this.cameraRotation; }; - Legend.prototype.redraw = function () { - var activeGroups = 0; - var groupArray = Object.keys(this.groups); - groupArray.sort(function (a, b) { - return a < b ? -1 : 1; + /** + * 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; + }; + + module.exports = Camera; + +/***/ }, +/* 22 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var DataView = __webpack_require__(16); + + /** + * @class Filter + * + * @param {DataSet} data The google data table + * @param {Number} column The index of the column to be filtered + * @param {Graph} graph The graph + */ + function Filter(data, column, graph) { + this.data = data; + 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 = graph.getDistinctValues(data.get(), this.column); + + // sort both numeric and string values correctly + this.values.sort(function (a, b) { + return a > b ? 1 : a < b ? -1 : 0; }); - for (var i = 0; i < groupArray.length; i++) { - var groupId = groupArray[i]; - if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { - activeGroups++; - } + if (this.values.length > 0) { + this.selectValue(0); } - if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false || activeGroups == 0) { - this.hide(); - } else { - this.show(); - if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'bottom-left') { - this.dom.frame.style.left = '4px'; - this.dom.frame.style.textAlign = 'left'; - this.dom.textArea.style.textAlign = 'left'; - this.dom.textArea.style.left = this.options.iconSize + 15 + 'px'; - this.dom.textArea.style.right = ''; - this.svg.style.left = 0 + 'px'; - this.svg.style.right = ''; - } else { - this.dom.frame.style.right = '4px'; - this.dom.frame.style.textAlign = 'right'; - this.dom.textArea.style.textAlign = 'right'; - this.dom.textArea.style.right = this.options.iconSize + 15 + 'px'; - this.dom.textArea.style.left = ''; - this.svg.style.right = 0 + 'px'; - this.svg.style.left = ''; - } - - if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'top-right') { - this.dom.frame.style.top = 4 - Number(this.body.dom.center.style.top.replace('px', '')) + 'px'; - this.dom.frame.style.bottom = ''; - } else { - var scrollableHeight = this.body.domProps.center.height - this.body.domProps.centerContainer.height; - this.dom.frame.style.bottom = 4 + scrollableHeight + Number(this.body.dom.center.style.top.replace('px', '')) + 'px'; - this.dom.frame.style.top = ''; - } + // create an array with the filtered datapoints. this will be loaded afterwards + this.dataPoints = []; - if (this.options.icons == false) { - this.dom.frame.style.width = this.dom.textArea.offsetWidth + 10 + 'px'; - this.dom.textArea.style.right = ''; - this.dom.textArea.style.left = ''; - this.svg.style.width = '0px'; - } else { - this.dom.frame.style.width = this.options.iconSize + 15 + this.dom.textArea.offsetWidth + 10 + 'px'; - this.drawLegendIcons(); - } + this.loaded = false; + this.onLoadCallback = undefined; - var content = ''; - for (var i = 0; i < groupArray.length; i++) { - var groupId = groupArray[i]; - if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { - content += this.groups[groupId].content + '
'; - } - } - this.dom.textArea.innerHTML = content; - this.dom.textArea.style.lineHeight = 0.75 * this.options.iconSize + this.options.iconSpacing + 'px'; + if (graph.animationPreload) { + this.loaded = false; + this.loadInBackground(); + } else { + this.loaded = true; } }; - Legend.prototype.drawLegendIcons = function () { - if (this.dom.frame.parentNode) { - var groupArray = Object.keys(this.groups); - groupArray.sort(function (a, b) { - return a < b ? -1 : 1; - }); + /** + * Return the label + * @return {string} label + */ + Filter.prototype.isLoaded = function () { + return this.loaded; + }; - DOMutil.prepareElements(this.svgElements); - var padding = window.getComputedStyle(this.dom.frame).paddingTop; - var iconOffset = Number(padding.replace('px', '')); - var x = iconOffset; - var iconWidth = this.options.iconSize; - var iconHeight = 0.75 * this.options.iconSize; - var y = iconOffset + 0.5 * iconHeight + 3; + /** + * Return the loaded progress + * @return {Number} percentage between 0 and 100 + */ + Filter.prototype.getLoadedProgress = function () { + var len = this.values.length; - this.svg.style.width = iconWidth + 5 + iconOffset + 'px'; + var i = 0; + while (this.dataPoints[i]) { + i++; + } - for (var i = 0; i < groupArray.length; i++) { - var groupId = groupArray[i]; - if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { - this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight); - y += iconHeight + this.options.iconSpacing; - } - } + return Math.round(i / len * 100); + }; - DOMutil.cleanupElements(this.svgElements); - } + /** + * Return the label + * @return {string} label + */ + Filter.prototype.getLabel = function () { + return this.graph.filterLabel; }; - module.exports = Legend; + /** + * Return the columnIndex of the filter + * @return {Number} columnIndex + */ + Filter.prototype.getColumn = function () { + return this.column; + }; -/***/ }, -/* 34 */ -/***/ function(module, exports, __webpack_require__) { + /** + * Return the currently selected value. Returns undefined if there is no selection + * @return {*} value + */ + Filter.prototype.getSelectedValue = function () { + if (this.index === undefined) return undefined; - 'use strict'; + return this.values[this.index]; + }; + + /** + * Retrieve all values of the filter + * @return {Array} values + */ + Filter.prototype.getValues = function () { + return this.values; + }; - var util = __webpack_require__(2); - var DOMutil = __webpack_require__(3); - var DataSet = __webpack_require__(4); - var DataView = __webpack_require__(5); - var Component = __webpack_require__(25); - var DataAxis = __webpack_require__(28); - var GraphGroup = __webpack_require__(29); - var Legend = __webpack_require__(33); - var BarFunctions = __webpack_require__(52); - var LineFunctions = __webpack_require__(51); + /** + * Retrieve one value of the filter + * @param {Number} index + * @return {*} value + */ + Filter.prototype.getValue = function (index) { + if (index >= this.values.length) throw 'Error: index out of range'; - var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items + return this.values[index]; + }; /** - * This is the constructor of the LineGraph. It requires a Timeline body and options. - * - * @param body - * @param options - * @constructor + * Retrieve the (filtered) dataPoints for the currently selected filter index + * @param {Number} [index] (optional) + * @return {Array} dataPoints */ - function LineGraph(body, options) { - this.id = util.randomUUID(); - this.body = body; + Filter.prototype._getDataPoints = function (index) { + if (index === undefined) index = this.index; - this.defaultOptions = { - yAxisOrientation: 'left', - defaultGroup: 'default', - sort: true, - sampling: true, - stack: false, - graphHeight: '400px', - shaded: { - enabled: false, - orientation: 'bottom' // top, bottom - }, - style: 'line', // line, bar - barChart: { - width: 50, - sideBySide: false, - align: 'center' // left, center, right - }, - interpolation: { - enabled: true, - parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) - alpha: 0.5 - }, - drawPoints: { - enabled: true, - size: 6, - style: 'square' // square, circle - }, - dataAxis: { - showMinorLabels: true, - showMajorLabels: true, - icons: false, - width: '40px', - visible: true, - alignZeros: true, - left: { - range: { min: undefined, max: undefined }, - format: function format(value) { - return value; - }, - title: { text: undefined, style: undefined } - }, - right: { - range: { min: undefined, max: undefined }, - format: function format(value) { - return value; - }, - title: { text: undefined, style: undefined } - } - }, - legend: { - enabled: false, - icons: true, - left: { - visible: true, - position: 'top-left' // top/bottom - left,right - }, - right: { - visible: true, - position: 'top-right' // top/bottom - left,right - } - }, - groups: { - visibility: {} - } - }; - - // options is shared by this ItemSet and all its items - this.options = util.extend({}, this.defaultOptions); - this.dom = {}; - this.props = {}; - this.hammer = null; - this.groups = {}; - this.abortedGraphUpdate = false; - this.updateSVGheight = false; - this.updateSVGheightOnResize = false; + if (index === undefined) return []; - var me = this; - this.itemsData = null; // DataSet - this.groupsData = null; // DataSet + var dataPoints; + if (this.dataPoints[index]) { + dataPoints = this.dataPoints[index]; + } else { + var f = {}; + f.column = this.column; + f.value = this.values[index]; - // listeners for the DataSet of the items - this.itemListeners = { - 'add': function add(event, params, senderId) { - me._onAdd(params.items); - }, - 'update': function update(event, params, senderId) { - me._onUpdate(params.items); - }, - 'remove': function remove(event, params, senderId) { - me._onRemove(params.items); - } - }; + var dataView = new DataView(this.data, { filter: function filter(item) { + return item[f.column] == f.value; + } }).get(); + dataPoints = this.graph._getDataPoints(dataView); - // listeners for the DataSet of the groups - this.groupListeners = { - 'add': function add(event, params, senderId) { - me._onAddGroups(params.items); - }, - 'update': function update(event, params, senderId) { - me._onUpdateGroups(params.items); - }, - 'remove': function remove(event, params, senderId) { - me._onRemoveGroups(params.items); - } - }; + this.dataPoints[index] = dataPoints; + } - this.items = {}; // object with an Item for every data item - this.selection = []; // list with the ids of all selected nodes - this.lastStart = this.body.range.start; - this.touchParams = {}; // stores properties while dragging + return dataPoints; + }; - this.svgElements = {}; - this.setOptions(options); - this.groupsUsingDefaultStyles = [0]; - this.COUNTER = 0; - this.body.emitter.on('rangechanged', function () { - me.lastStart = me.body.range.start; - me.svg.style.left = util.option.asSize(-me.props.width); - me.redraw.call(me, true); - }); + /** + * Set a callback function when the filter is fully loaded. + */ + Filter.prototype.setOnLoadCallback = function (callback) { + this.onLoadCallback = callback; + }; - // create the HTML DOM - this._create(); - this.framework = { svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups }; - this.body.emitter.emit('change'); - } + /** + * 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 'Error: index out of range'; - LineGraph.prototype = new Component(); + this.index = index; + this.value = this.values[index]; + }; /** - * Create the HTML DOM for the ItemSet + * Load all filtered rows in the background one by one + * Start this method without providing an index! */ - LineGraph.prototype._create = function () { - var frame = document.createElement('div'); - frame.className = 'vis-line-graph'; - this.dom.frame = frame; + Filter.prototype.loadInBackground = function (index) { + if (index === undefined) index = 0; - // create svg element for graph drawing. - this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - this.svg.style.position = 'relative'; - this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px'; - this.svg.style.display = 'block'; - frame.appendChild(this.svg); + var frame = this.graph.frame; - // data axis - this.options.dataAxis.orientation = 'left'; - this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups); + if (index < this.values.length) { + var dataPointsTemp = this._getDataPoints(index); + //this.graph.redrawInfo(); // TODO: not neat - this.options.dataAxis.orientation = 'right'; - this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups); - delete this.options.dataAxis.orientation; + // 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'; - // legends - this.legendLeft = new Legend(this.body, this.options.legend, 'left', this.options.groups); - this.legendRight = new Legend(this.body, this.options.legend, 'right', this.options.groups); + var me = this; + setTimeout(function () { + me.loadInBackground(index + 1); + }, 10); + this.loaded = false; + } else { + this.loaded = true; - this.show(); + // remove the progress box + if (frame.progress !== undefined) { + frame.removeChild(frame.progress); + frame.progress = undefined; + } + + if (this.onLoadCallback) this.onLoadCallback(); + } }; + module.exports = Filter; + +/***/ }, +/* 23 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var util = __webpack_require__(7); + /** - * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element. - * @param {object} options + * @constructor Slider + * + * An html slider control with start/stop/prev/next buttons + * @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. */ - LineGraph.prototype.setOptions = function (options) { - if (options) { - var fields = ['sampling', 'defaultGroup', 'stack', 'height', 'graphHeight', 'yAxisOrientation', 'style', 'barChart', 'dataAxis', 'sort', 'groups']; - if (options.graphHeight === undefined && options.height !== undefined && this.body.domProps.centerContainer.height !== undefined) { - this.updateSVGheight = true; - this.updateSVGheightOnResize = true; - } else if (this.body.domProps.centerContainer.height !== undefined && options.graphHeight !== undefined) { - if (parseInt((options.graphHeight + '').replace('px', '')) < this.body.domProps.centerContainer.height) { - this.updateSVGheight = true; - } - } - util.selectiveDeepExtend(fields, this.options, options); - util.mergeOptions(this.options, options, 'interpolation'); - util.mergeOptions(this.options, options, 'drawPoints'); - util.mergeOptions(this.options, options, 'shaded'); - util.mergeOptions(this.options, options, 'legend'); + function Slider(container, options) { + if (container === undefined) { + throw 'Error: No container element defined'; + } + this.container = container; + this.visible = options && options.visible != undefined ? options.visible : true; - if (options.interpolation) { - if (typeof options.interpolation == 'object') { - if (options.interpolation.parametrization) { - if (options.interpolation.parametrization == 'uniform') { - this.options.interpolation.alpha = 0; - } else if (options.interpolation.parametrization == 'chordal') { - this.options.interpolation.alpha = 1; - } else { - this.options.interpolation.parametrization = 'centripetal'; - this.options.interpolation.alpha = 0.5; - } - } - } - } + 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); - if (this.yAxisLeft) { - if (options.dataAxis !== undefined) { - this.yAxisLeft.setOptions(this.options.dataAxis); - this.yAxisRight.setOptions(this.options.dataAxis); - } - } + this.frame.prev = document.createElement('INPUT'); + this.frame.prev.type = 'BUTTON'; + this.frame.prev.value = 'Prev'; + this.frame.appendChild(this.frame.prev); - if (this.legendLeft) { - if (options.legend !== undefined) { - this.legendLeft.setOptions(this.options.legend); - this.legendRight.setOptions(this.options.legend); - } - } + this.frame.play = document.createElement('INPUT'); + this.frame.play.type = 'BUTTON'; + this.frame.play.value = 'Play'; + this.frame.appendChild(this.frame.play); - if (this.groups.hasOwnProperty(UNGROUPED)) { - this.groups[UNGROUPED].setOptions(options); - } - } + this.frame.next = document.createElement('INPUT'); + this.frame.next.type = 'BUTTON'; + this.frame.next.value = 'Next'; + this.frame.appendChild(this.frame.next); - // this is used to redraw the graph if the visibility of the groups is changed. - if (this.dom.frame) { - this.redraw(true); + 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; + } /** - * Hide the component from the DOM + * Select the previous index */ - LineGraph.prototype.hide = function () { - // remove the frame containing the items - if (this.dom.frame.parentNode) { - this.dom.frame.parentNode.removeChild(this.dom.frame); + Slider.prototype.prev = function () { + var index = this.getIndex(); + if (index > 0) { + index--; + this.setIndex(index); } }; /** - * Show the component in the DOM (when not already visible). - * @return {Boolean} changed + * Select the next index */ - LineGraph.prototype.show = function () { - // show frame containing the items - if (!this.dom.frame.parentNode) { - this.body.dom.center.appendChild(this.dom.frame); + Slider.prototype.next = function () { + var index = this.getIndex(); + if (index < this.values.length - 1) { + index++; + this.setIndex(index); } }; /** - * Set items - * @param {vis.DataSet | null} items + * Select the next index */ - LineGraph.prototype.setItems = function (items) { - var me = this, - ids, - oldItemsData = this.itemsData; + Slider.prototype.playNext = function () { + var start = new Date(); - // 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'); + 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); } - if (oldItemsData) { - // unsubscribe from old dataset - util.forEach(this.itemListeners, function (callback, event) { - oldItemsData.off(event, callback); - }); + var end = new Date(); + var diff = end - start; - // remove all drawn items - ids = oldItemsData.getIds(); - this._onRemove(ids); - } + // 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 - if (this.itemsData) { - // subscribe to new dataset - var id = this.id; - util.forEach(this.itemListeners, function (callback, event) { - me.itemsData.on(event, callback, id); - }); + var me = this; + this.playTimeout = setTimeout(function () { + me.playNext(); + }, interval); + }; - // add all new items - ids = this.itemsData.getIds(); - this._onAdd(ids); + /** + * Toggle start or stop playing + */ + Slider.prototype.togglePlay = function () { + if (this.playTimeout === undefined) { + this.play(); + } else { + this.stop(); } - this._updateUngrouped(); - //this._updateGraph(); - this.redraw(true); }; /** - * Set groups - * @param {vis.DataSet} groups + * Start playing */ - LineGraph.prototype.setGroups = function (groups) { - var me = this; - var ids; - - // unsubscribe from current dataset - if (this.groupsData) { - util.forEach(this.groupListeners, function (callback, event) { - me.groupsData.off(event, callback); - }); + Slider.prototype.play = function () { + // Test whether already playing + if (this.playTimeout) return; - // remove all drawn groups - ids = this.groupsData.getIds(); - this.groupsData = null; - this._onRemoveGroups(ids); // note: this will cause a redraw - } + this.playNext(); - // 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.frame) { + this.frame.play.value = 'Stop'; } + }; - if (this.groupsData) { - // subscribe to new dataset - var id = this.id; - util.forEach(this.groupListeners, function (callback, event) { - me.groupsData.on(event, callback, id); - }); + /** + * Stop playing + */ + Slider.prototype.stop = function () { + clearInterval(this.playTimeout); + this.playTimeout = undefined; - // draw all ms - ids = this.groupsData.getIds(); - this._onAddGroups(ids); + if (this.frame) { + this.frame.play.value = 'Play'; } - this._onUpdate(); }; /** - * Update the data - * @param [ids] - * @private + * Set a callback function which will be triggered when the value of the + * slider bar has changed. */ - LineGraph.prototype._onUpdate = function (ids) { - this._updateUngrouped(); - this._updateAllGroupData(); - //this._updateGraph(); - this.redraw(true); - }; - LineGraph.prototype._onAdd = function (ids) { - this._onUpdate(ids); - }; - LineGraph.prototype._onRemove = function (ids) { - this._onUpdate(ids); - }; - LineGraph.prototype._onUpdateGroups = function (groupIds) { - for (var i = 0; i < groupIds.length; i++) { - var group = this.groupsData.get(groupIds[i]); - this._updateGroup(group, groupIds[i]); - } - - //this._updateGraph(); - this.redraw(true); - }; - LineGraph.prototype._onAddGroups = function (groupIds) { - this._onUpdateGroups(groupIds); + Slider.prototype.setOnChangeCallback = function (callback) { + this.onChangeCallback = callback; }; /** - * this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph - * @param {Array} groupIds - * @private + * Set the interval for playing the list + * @param {Number} interval The interval in milliseconds */ - LineGraph.prototype._onRemoveGroups = function (groupIds) { - for (var i = 0; i < groupIds.length; i++) { - if (this.groups.hasOwnProperty(groupIds[i])) { - if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') { - this.yAxisRight.removeGroup(groupIds[i]); - this.legendRight.removeGroup(groupIds[i]); - this.legendRight.redraw(); - } else { - this.yAxisLeft.removeGroup(groupIds[i]); - this.legendLeft.removeGroup(groupIds[i]); - this.legendLeft.redraw(); - } - delete this.groups[groupIds[i]]; - } - } - this._updateUngrouped(); - //this._updateGraph(); - this.redraw(true); + Slider.prototype.setPlayInterval = function (interval) { + this.playInterval = interval; }; /** - * update a group object with the group dataset entree - * - * @param group - * @param groupId - * @private + * Retrieve the current play interval + * @return {Number} interval The interval in milliseconds */ - LineGraph.prototype._updateGroup = function (group, groupId) { - if (!this.groups.hasOwnProperty(groupId)) { - this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles); - if (this.groups[groupId].options.yAxisOrientation == 'right') { - this.yAxisRight.addGroup(groupId, this.groups[groupId]); - this.legendRight.addGroup(groupId, this.groups[groupId]); - } else { - this.yAxisLeft.addGroup(groupId, this.groups[groupId]); - this.legendLeft.addGroup(groupId, this.groups[groupId]); - } - } else { - this.groups[groupId].update(group); - if (this.groups[groupId].options.yAxisOrientation == 'right') { - this.yAxisRight.updateGroup(groupId, this.groups[groupId]); - this.legendRight.updateGroup(groupId, this.groups[groupId]); - } else { - this.yAxisLeft.updateGroup(groupId, this.groups[groupId]); - this.legendLeft.updateGroup(groupId, this.groups[groupId]); - } + Slider.prototype.getPlayInterval = function (interval) { + return this.playInterval; + }; + + /** + * Set looping on or off + * @pararm {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(); } - this.legendLeft.redraw(); - this.legendRight.redraw(); }; /** - * this updates all groups, it is used when there is an update the the itemset. - * - * @private + * redraw the slider on the correct place */ - LineGraph.prototype._updateAllGroupData = function () { - if (this.itemsData != null) { - var groupsContent = {}; - var groupId; - for (groupId in this.groups) { - if (this.groups.hasOwnProperty(groupId)) { - groupsContent[groupId] = []; - } - } - for (var itemId in this.itemsData._data) { - if (this.itemsData._data.hasOwnProperty(itemId)) { - var item = this.itemsData._data[itemId]; - if (groupsContent[item.group] === undefined) { - throw new Error('Cannot find referenced group. Possible reason: items added before groups? Groups need to be added before items, as items refer to groups.'); - } - item.x = util.convert(item.x, 'Date'); - groupsContent[item.group].push(item); - } - } - for (groupId in this.groups) { - if (this.groups.hasOwnProperty(groupId)) { - this.groups[groupId].setItems(groupsContent[groupId]); - } - } + 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'; } }; /** - * Create or delete the group holding all ungrouped items. This group is used when - * there are no groups specified. This anonymous group is called 'graph'. - * @protected + * Set the list with values for the slider + * @param {Array} values A javascript array with values (any type) */ - LineGraph.prototype._updateUngrouped = function () { - if (this.itemsData && this.itemsData != null) { - var ungroupedCounter = 0; - for (var itemId in this.itemsData._data) { - if (this.itemsData._data.hasOwnProperty(itemId)) { - var item = this.itemsData._data[itemId]; - if (item != undefined) { - if (item.hasOwnProperty('group')) { - if (item.group === undefined) { - item.group = UNGROUPED; - } - } else { - item.group = UNGROUPED; - } - ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter; - } - } - } + Slider.prototype.setValues = function (values) { + this.values = values; - if (ungroupedCounter == 0) { - delete this.groups[UNGROUPED]; - this.legendLeft.removeGroup(UNGROUPED); - this.legendRight.removeGroup(UNGROUPED); - this.yAxisLeft.removeGroup(UNGROUPED); - this.yAxisRight.removeGroup(UNGROUPED); - } else { - var group = { id: UNGROUPED, content: this.options.defaultGroup }; - this._updateGroup(group, UNGROUPED); - } + 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 { - delete this.groups[UNGROUPED]; - this.legendLeft.removeGroup(UNGROUPED); - this.legendRight.removeGroup(UNGROUPED); - this.yAxisLeft.removeGroup(UNGROUPED); - this.yAxisRight.removeGroup(UNGROUPED); + throw 'Error: index out of range'; } + }; - this.legendLeft.redraw(); - this.legendRight.redraw(); + /** + * retrieve the index of the currently selected vaue + * @return {Number} index + */ + Slider.prototype.getIndex = function () { + return this.index; }; /** - * Redraw the component, mandatory function - * @return {boolean} Returns true if the component is resized + * retrieve the currently selected value + * @return {*} value */ - LineGraph.prototype.redraw = function (forceGraphUpdate) { - var resized = false; + Slider.prototype.get = function () { + return this.values[this.index]; + }; - // calculate actual size and position - this.props.width = this.dom.frame.offsetWidth; - this.props.height = this.body.domProps.centerContainer.height - this.body.domProps.border.top - this.body.domProps.border.bottom; + 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; - // update the graph if there is no lastWidth or with, used for the initial draw - if (this.lastWidth === undefined && this.props.width) { - forceGraphUpdate = true; - } + this.startClientX = event.clientX; + this.startSlideX = parseFloat(this.frame.slide.style.left); - // check if this component is resized - resized = this._isResized() || resized; + this.frame.style.cursor = 'move'; - // check whether zoomed (in that case we need to re-stack everything) - var visibleInterval = this.body.range.end - this.body.range.start; - var zoomed = visibleInterval != this.lastVisibleInterval; - this.lastVisibleInterval = visibleInterval; + // 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); + }; - // the svg element is three times as big as the width, this allows for fully dragging left and right - // without reloading the graph. the controls for this are bound to events in the constructor - if (resized == true) { - this.svg.style.width = util.option.asSize(3 * this.props.width); - this.svg.style.left = util.option.asSize(-this.props.width); + Slider.prototype.leftToIndex = function (left) { + var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10; + var x = left - 3; - // if the height of the graph is set as proportional, change the height of the svg - if ((this.options.height + '').indexOf('%') != -1 || this.updateSVGheightOnResize == true) { - this.updateSVGheight = true; - } - } + 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; - // update the height of the graph on each redraw of the graph. - if (this.updateSVGheight == true) { - if (this.options.graphHeight != this.props.height + 'px') { - this.options.graphHeight = this.props.height + 'px'; - this.svg.style.height = this.props.height + 'px'; - } - this.updateSVGheight = false; - } else { - this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px'; - } + return index; + }; - // zoomed is here to ensure that animations are shown correctly. - if (resized == true || zoomed == true || this.abortedGraphUpdate == true || forceGraphUpdate == true) { - resized = this._updateGraph() || resized; - } else { - // move the whole svg while dragging - if (this.lastStart != 0) { - var offset = this.body.range.start - this.lastStart; - var range = this.body.range.end - this.body.range.start; - if (this.props.width != 0) { - var rangePerPixelInv = this.props.width / range; - var xOffset = offset * rangePerPixelInv; - this.svg.style.left = -this.props.width - xOffset + 'px'; - } - } - } + Slider.prototype.indexToLeft = function (index) { + var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10; - this.legendLeft.redraw(); - this.legendRight.redraw(); - return resized; + var x = index / (this.values.length - 1) * width; + var left = x + 3; + + return left; }; - /** - * Update and redraw the graph. - * - */ - LineGraph.prototype._updateGraph = function () { - // reset the svg elements - DOMutil.prepareElements(this.svgElements); - if (this.props.width != 0 && this.itemsData != null) { - var group, i; - var preprocessedGroupData = {}; - var processedGroupData = {}; - var groupRanges = {}; - var changeCalled = false; + Slider.prototype._onMouseMove = function (event) { + var diff = event.clientX - this.startClientX; + var x = this.startSlideX + diff; - // getting group Ids - var groupIds = []; - for (var groupId in this.groups) { - if (this.groups.hasOwnProperty(groupId)) { - group = this.groups[groupId]; - if (group.visible == true && (this.options.groups.visibility[groupId] === undefined || this.options.groups.visibility[groupId] == true)) { - groupIds.push(groupId); - } - } - } - if (groupIds.length > 0) { - // this is the range of the SVG canvas - var minDate = this.body.util.toGlobalTime(-this.body.domProps.root.width); - var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width); - var groupsData = {}; - // fill groups data, this only loads the data we require based on the timewindow - this._getRelevantData(groupIds, groupsData, minDate, maxDate); + var index = this.leftToIndex(x); - // apply sampling, if disabled, it will pass through this function. - this._applySampling(groupIds, groupsData); + this.setIndex(index); - // we transform the X coordinates to detect collisions - for (i = 0; i < groupIds.length; i++) { - preprocessedGroupData[groupIds[i]] = this._convertXcoordinates(groupsData[groupIds[i]]); - } + util.preventDefault(); + }; - // now all needed data has been collected we start the processing. - this._getYRanges(groupIds, preprocessedGroupData, groupRanges); + Slider.prototype._onMouseUp = function (event) { + this.frame.style.cursor = 'auto'; - // update the Y axis first, we use this data to draw at the correct Y points - // changeCalled is required to clean the SVG on a change emit. - changeCalled = this._updateYAxis(groupIds, groupRanges); - var MAX_CYCLES = 5; - if (changeCalled == true && this.COUNTER < MAX_CYCLES) { - DOMutil.cleanupElements(this.svgElements); - this.abortedGraphUpdate = true; - this.COUNTER++; - this.body.emitter.emit('change'); - return true; - } else { - if (this.COUNTER > MAX_CYCLES) { - console.log('WARNING: there may be an infinite loop in the _updateGraph emitter cycle.'); - } - this.COUNTER = 0; - this.abortedGraphUpdate = false; + // remove event listeners + util.removeEventListener(document, 'mousemove', this.onmousemove); + util.removeEventListener(document, 'mouseup', this.onmouseup); - // With the yAxis scaled correctly, use this to get the Y values of the points. - for (i = 0; i < groupIds.length; i++) { - group = this.groups[groupIds[i]]; - processedGroupData[groupIds[i]] = this._convertYcoordinates(groupsData[groupIds[i]], group); - } + util.preventDefault(); + }; - // draw the groups - for (i = 0; i < groupIds.length; i++) { - group = this.groups[groupIds[i]]; - if (group.options.style != 'bar') { - // bar needs to be drawn enmasse - group.draw(processedGroupData[groupIds[i]], group, this.framework); - } - } - BarFunctions.draw(groupIds, processedGroupData, this.framework); - } - } - } + module.exports = Slider; - // cleanup unused svg elements - DOMutil.cleanupElements(this.svgElements); - return false; - }; +/***/ }, +/* 24 */ +/***/ function(module, exports, __webpack_require__) { /** - * first select and preprocess the data from the datasets. - * the groups have their preselection of data, we now loop over this data to see - * what data we need to draw. Sorted data is much faster. - * more optimization is possible by doing the sampling before and using the binary search - * to find the end date to determine the increment. + * @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. * - * @param {array} groupIds - * @param {object} groupsData - * @param {date} minDate - * @param {date} maxDate - * @private - */ - LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) { - var group, i, j, item; - if (groupIds.length > 0) { - for (i = 0; i < groupIds.length; i++) { - group = this.groups[groupIds[i]]; - groupsData[groupIds[i]] = []; - var dataContainer = groupsData[groupIds[i]]; - // optimization for sorted data - if (group.options.sort == true) { - var guess = Math.max(0, util.binarySearchValue(group.itemsData, minDate, 'x', 'before')); - for (j = guess; j < group.itemsData.length; j++) { - item = group.itemsData[j]; - if (item !== undefined) { - if (item.x > maxDate) { - dataContainer.push(item); - break; - } else { - dataContainer.push(item); - } - } - } - } else { - for (j = 0; j < group.itemsData.length; j++) { - item = group.itemsData[j]; - if (item !== undefined) { - if (item.x > minDate && item.x < maxDate) { - dataContainer.push(item); - } - } - } - } - } - } - }; - - /** + * 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, .... * - * @param groupIds - * @param groupsData - * @private + * 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, ...) */ - LineGraph.prototype._applySampling = function (groupIds, groupsData) { - var group; - if (groupIds.length > 0) { - for (var i = 0; i < groupIds.length; i++) { - group = this.groups[groupIds[i]]; - if (group.options.sampling == true) { - var dataContainer = groupsData[groupIds[i]]; - if (dataContainer.length > 0) { - var increment = 1; - var amountOfPoints = dataContainer.length; + "use strict"; - // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop - // of width changing of the yAxis. - var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x); - var pointsPerPixel = amountOfPoints / xDistance; - increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel))); + function StepNumber(start, end, step, prettyStep) { + // set default values + this._start = 0; + this._end = 0; + this._step = 1; + this.prettyStep = true; + this.precision = 5; - var sampledData = []; - for (var j = 0; j < amountOfPoints; j += increment) { - sampledData.push(dataContainer[j]); - } - groupsData[groupIds[i]] = sampledData; - } - } - } - } + this._current = 0; + this.setRange(start, end, step, prettyStep); }; /** + * Set a new range: start, end and step. * - * - * @param {array} groupIds - * @param {object} groupsData - * @param {object} groupRanges | this is being filled here - * @private + * @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, ...) */ - LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) { - var groupData, group, i; - var combinedDataLeft = []; - var combinedDataRight = []; - var options; - if (groupIds.length > 0) { - for (i = 0; i < groupIds.length; i++) { - groupData = groupsData[groupIds[i]]; - options = this.groups[groupIds[i]].options; - if (groupData.length > 0) { - group = this.groups[groupIds[i]]; - // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups. - if (options.stack === true) { - if (options.yAxisOrientation == 'left') { - combinedDataLeft = combinedDataLeft.concat(group.getData(groupData)); - } else { - combinedDataRight = combinedDataRight.concat(group.getData(groupData)); - } - } else { - groupRanges[groupIds[i]] = group.getYRange(groupData, groupIds[i]); - } - } - } + StepNumber.prototype.setRange = function (start, end, step, prettyStep) { + this._start = start ? start : 0; + this._end = end ? end : 0; - // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups. - BarFunctions.getStackedYRange(combinedDataLeft, groupRanges, groupIds, '__barStackLeft', 'left'); - BarFunctions.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__barStackRight', 'right'); - // if line graphs are stacked, their range need to be handled differently and accumulated over all groups. - LineFunctions.getStackedYRange(combinedDataLeft, groupRanges, groupIds, '__lineStackLeft', 'left'); - LineFunctions.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__lineStackRight', 'right'); - } + this.setStep(step, prettyStep); }; /** - * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden. - * @param {Array} groupIds - * @param {Object} groupRanges - * @private + * 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, ...) */ - LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) { - var resized = false; - var yAxisLeftUsed = false; - var yAxisRightUsed = false; - var minLeft = 1000000000, - minRight = 1000000000, - maxLeft = -1000000000, - maxRight = -1000000000, - minVal, - maxVal; - // if groups are present - if (groupIds.length > 0) { - // this is here to make sure that if there are no items in the axis but there are groups, that there is no infinite draw/redraw loop. - for (var i = 0; i < groupIds.length; i++) { - var group = this.groups[groupIds[i]]; - if (group && group.options.yAxisOrientation != 'right') { - yAxisLeftUsed = true; - minLeft = 0; - maxLeft = 0; - } else if (group && group.options.yAxisOrientation) { - yAxisRightUsed = true; - minRight = 0; - maxRight = 0; - } - } + StepNumber.prototype.setStep = function (step, prettyStep) { + if (step === undefined || step <= 0) return; - // if there are items: - for (var i = 0; i < groupIds.length; i++) { - if (groupRanges.hasOwnProperty(groupIds[i])) { - if (groupRanges[groupIds[i]].ignore !== true) { - minVal = groupRanges[groupIds[i]].min; - maxVal = groupRanges[groupIds[i]].max; + if (prettyStep !== undefined) this.prettyStep = prettyStep; - if (groupRanges[groupIds[i]].yAxisOrientation != 'right') { - yAxisLeftUsed = true; - minLeft = minLeft > minVal ? minVal : minLeft; - maxLeft = maxLeft < maxVal ? maxVal : maxLeft; - } else { - yAxisRightUsed = true; - minRight = minRight > minVal ? minVal : minRight; - maxRight = maxRight < maxVal ? maxVal : maxRight; - } - } - } - } + if (this.prettyStep === true) this._step = StepNumber.calculatePrettyStep(step);else this._step = step; + }; - if (yAxisLeftUsed == true) { - this.yAxisLeft.setRange(minLeft, maxLeft); - } - if (yAxisRightUsed == true) { - this.yAxisRight.setRange(minRight, maxRight); - } - } - resized = this._toggleAxisVisiblity(yAxisLeftUsed, this.yAxisLeft) || resized; - resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized; + /** + * 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; + }; - if (yAxisRightUsed == true && yAxisLeftUsed == true) { - this.yAxisLeft.drawIcons = true; - this.yAxisRight.drawIcons = true; - } else { - this.yAxisLeft.drawIcons = false; - this.yAxisRight.drawIcons = false; - } - this.yAxisRight.master = !yAxisLeftUsed; - if (this.yAxisRight.master == false) { - if (yAxisRightUsed == true) { - this.yAxisLeft.lineOffset = this.yAxisRight.width; - } else { - this.yAxisLeft.lineOffset = 0; - } + // 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))); - resized = this.yAxisLeft.redraw() || resized; - this.yAxisRight.stepPixels = this.yAxisLeft.stepPixels; - this.yAxisRight.zeroCrossing = this.yAxisLeft.zeroCrossing; - this.yAxisRight.amountOfSteps = this.yAxisLeft.amountOfSteps; - resized = this.yAxisRight.redraw() || resized; - } else { - resized = this.yAxisRight.redraw() || resized; - } + // 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; - // clean the accumulated lists - var tempGroups = ['__barStackLeft', '__barStackRight', '__lineStackLeft', '__lineStackRight']; - for (var i = 0; i < tempGroups.length; i++) { - if (groupIds.indexOf(tempGroups[i]) != -1) { - groupIds.splice(groupIds.indexOf(tempGroups[i]), 1); - } + // for safety + if (prettyStep <= 0) { + prettyStep = 1; } - return resized; + return prettyStep; }; /** - * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function - * - * @param {boolean} axisUsed - * @returns {boolean} - * @private - * @param axis + * returns the current value of the step + * @return {Number} current value */ - LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) { - var changed = false; - if (axisUsed == false) { - if (axis.dom.frame.parentNode && axis.hidden == false) { - axis.hide(); - changed = true; - } - } else { - if (!axis.dom.frame.parentNode && axis.hidden == true) { - axis.show(); - changed = true; - } - } - return changed; + StepNumber.prototype.getCurrent = function () { + return parseFloat(this._current.toPrecision(this.precision)); }; /** - * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the - * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for - * the yAxis. - * - * @param datapoints - * @returns {Array} - * @private + * returns the current step size + * @return {Number} current step size */ - LineGraph.prototype._convertXcoordinates = function (datapoints) { - var extractedData = []; - var xValue, yValue; - var toScreen = this.body.util.toScreen; - - for (var i = 0; i < datapoints.length; i++) { - xValue = toScreen(datapoints[i].x) + this.props.width; - yValue = datapoints[i].y; - extractedData.push({ x: xValue, y: yValue }); - } - - return extractedData; + StepNumber.prototype.getStep = function () { + return this._step; }; /** - * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the - * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for - * the yAxis. - * - * @param datapoints - * @param group - * @returns {Array} - * @private + * Set the current value to the largest value smaller than start, which + * is a multiple of the step size */ - LineGraph.prototype._convertYcoordinates = function (datapoints, group) { - var extractedData = []; - var xValue, yValue; - var toScreen = this.body.util.toScreen; - var axis = this.yAxisLeft; - var svgHeight = Number(this.svg.style.height.replace('px', '')); - if (group.options.yAxisOrientation == 'right') { - axis = this.yAxisRight; - } - - for (var i = 0; i < datapoints.length; i++) { - var labelValue = datapoints[i].label ? datapoints[i].label : null; - xValue = toScreen(datapoints[i].x) + this.props.width; - yValue = Math.round(axis.convertValue(datapoints[i].y)); - extractedData.push({ x: xValue, y: yValue, label: labelValue }); - } + StepNumber.prototype.start = function () { + this._current = this._start - this._start % this._step; + }; - group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0))); + /** + * Do a step, add the step size to the current value + */ + StepNumber.prototype.next = function () { + this._current += this._step; + }; - return extractedData; + /** + * 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 = LineGraph; + module.exports = StepNumber; /***/ }, -/* 35 */ +/* 25 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var util = __webpack_require__(2); - var Component = __webpack_require__(25); - var TimeStep = __webpack_require__(20); - var DateUtil = __webpack_require__(16); - var moment = __webpack_require__(40); + var Emitter = __webpack_require__(19); + var Hammer = __webpack_require__(3); + var util = __webpack_require__(7); + var DataSet = __webpack_require__(14); + var DataView = __webpack_require__(16); + var Range = __webpack_require__(29); + var Core = __webpack_require__(32); + var TimeAxis = __webpack_require__(41); + var CurrentTime = __webpack_require__(26); + var CustomTime = __webpack_require__(44); + var ItemSet = __webpack_require__(33); + + var Configurator = __webpack_require__(45); + var Validator = __webpack_require__(47)['default']; + var printStyle = __webpack_require__(47).printStyle; + var allOptions = __webpack_require__(48).allOptions; + var configureOptions = __webpack_require__(48).configureOptions; /** - * 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 + * Create a timeline visualization + * @param {HTMLElement} container + * @param {vis.DataSet | vis.DataView | Array} [items] + * @param {vis.DataSet | vis.DataView | Array} [groups] + * @param {Object} [options] See Timeline.setOptions for the available options. + * @constructor + * @extends Core */ - function TimeAxis(body, options) { - this.dom = { - foreground: null, - lines: [], - majorTexts: [], - minorTexts: [], - redundant: { - lines: [], - majorTexts: [], - minorTexts: [] - } + function Timeline(container, items, groups, options) { + if (!(this instanceof Timeline)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + // if the third element is options, the forth is groups (optionally); + if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) { + var forthArgument = options; + options = groups; + groups = forthArgument; + } + + var me = this; + this.defaultOptions = { + start: null, + end: null, + + autoResize: true, + + orientation: { + axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both' + item: 'bottom' // not relevant + }, + + width: null, + height: null, + maxHeight: null, + minHeight: null }; - this.props = { - range: { - start: 0, - end: 0, - minimumStep: 0 + this.options = util.deepExtend({}, this.defaultOptions); + + // Create the DOM, props, and emitter + this._create(container); + + // all components listed here will be repainted automatically + this.components = []; + + this.body = { + dom: this.dom, + domProps: this.props, + emitter: { + on: this.on.bind(this), + off: this.off.bind(this), + emit: this.emit.bind(this) }, - lineTop: 0 + hiddenDates: [], + util: { + getScale: function getScale() { + return me.timeAxis.step.scale; + }, + getStep: function getStep() { + return me.timeAxis.step.step; + }, + + toScreen: me._toScreen.bind(me), + toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width + toTime: me._toTime.bind(me), + toGlobalTime: me._toGlobalTime.bind(me) + } }; - this.defaultOptions = { - orientation: { - axis: 'bottom' - }, // axis orientation: 'top' or 'bottom' - showMinorLabels: true, - showMajorLabels: true, - format: TimeStep.FORMAT, - timeAxis: null + // range + this.range = new Range(this.body); + this.components.push(this.range); + this.body.range = this.range; + + // time axis + this.timeAxis = new TimeAxis(this.body); + this.timeAxis2 = null; // used in case of orientation option 'both' + this.components.push(this.timeAxis); + + // current time bar + this.currentTime = new CurrentTime(this.body); + this.components.push(this.currentTime); + + // item set + this.itemSet = new ItemSet(this.body); + this.components.push(this.itemSet); + + this.itemsData = null; // DataSet + this.groupsData = null; // DataSet + + this.on('tap', function (event) { + me.emit('click', me.getEventProperties(event)); + }); + this.on('doubletap', function (event) { + me.emit('doubleClick', me.getEventProperties(event)); + }); + this.dom.root.oncontextmenu = function (event) { + me.emit('contextmenu', me.getEventProperties(event)); }; - this.options = util.extend({}, this.defaultOptions); - this.body = body; + // setup configuration system + this.configurator = new Configurator(this, container, configureOptions); - // create the HTML DOM - this._create(); + // apply options + if (options) { + this.setOptions(options); + } - this.setOptions(options); + // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! + if (groups) { + this.setGroups(groups); + } + + // create itemset + if (items) { + this.setItems(items); + } else { + this._redraw(); + } } - TimeAxis.prototype = new Component(); + // Extend the functionality from Core + Timeline.prototype = new Core(); /** - * Set options for the TimeAxis. - * Parameters will be merged in current options. - * @param {Object} options Available options: - * {string} [orientation.axis] - * {boolean} [showMinorLabels] - * {boolean} [showMajorLabels] + * Force a redraw. The size of all items will be recalculated. + * Can be useful to manually redraw when option autoResize=false and the window + * has been resized, or when the items CSS has been changed. */ - TimeAxis.prototype.setOptions = function (options) { - if (options) { - // copy all options that we know - util.selectiveExtend(['showMinorLabels', 'showMajorLabels', 'hiddenDates', 'timeAxis'], this.options, options); + Timeline.prototype.redraw = function () { + this.itemSet && this.itemSet.markDirty({ refreshItems: true }); + this._redraw(); + }; - // deep copy the format options - util.selectiveDeepExtend(['format'], this.options, options); + Timeline.prototype.setOptions = function (options) { + // validate options + var errorFound = Validator.validate(options, allOptions); + if (errorFound === true) { + console.log('%cErrors have been found in the supplied options object.', printStyle); + } - if ('orientation' in options) { - if (typeof options.orientation === 'string') { - this.options.orientation.axis = options.orientation; - } else if (typeof options.orientation === 'object' && 'axis' in options.orientation) { - this.options.orientation.axis = options.orientation.axis; - } - } + Core.prototype.setOptions.call(this, options); - // 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); + if ('type' in options) { + if (options.type !== this.options.type) { + this.options.type = options.type; + + // force recreation of all items + var itemsData = this.itemsData; + if (itemsData) { + var selection = this.getSelection(); + this.setItems(null); // remove all + this.setItems(itemsData); // add all + this.setSelection(selection); // restore selection } } } }; /** - * Create the HTML DOM for the TimeAxis + * Set items + * @param {vis.DataSet | Array | null} items */ - TimeAxis.prototype._create = function () { - this.dom.foreground = document.createElement('div'); - this.dom.background = document.createElement('div'); + Timeline.prototype.setItems = function (items) { + var initialLoad = this.itemsData == null; - this.dom.foreground.className = 'vis-time-axis vis-foreground'; - this.dom.background.className = 'vis-time-axis vis-background'; + // convert to type DataSet when needed + var newDataSet; + if (!items) { + newDataSet = null; + } else if (items instanceof DataSet || items instanceof DataView) { + newDataSet = items; + } else { + // turn an array into a dataset + newDataSet = new DataSet(items, { + type: { + start: 'Date', + end: 'Date' + } + }); + } + + // set items + this.itemsData = newDataSet; + this.itemSet && this.itemSet.setItems(newDataSet); + + if (initialLoad) { + if (this.options.start != undefined || this.options.end != undefined) { + if (this.options.start == undefined || this.options.end == undefined) { + var dataRange = this._getDataRange(); + } + + var start = this.options.start != undefined ? this.options.start : dataRange.start; + var end = this.options.end != undefined ? this.options.end : dataRange.end; + + this.setWindow(start, end, { animation: false }); + } else { + this.fit({ animation: false }); + } + } }; /** - * Destroy the TimeAxis + * Set groups + * @param {vis.DataSet | Array} groups */ - 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); + Timeline.prototype.setGroups = function (groups) { + // convert to type DataSet when needed + var newDataSet; + if (!groups) { + newDataSet = null; + } else if (groups instanceof DataSet || groups instanceof DataView) { + newDataSet = groups; + } else { + // turn an array into a dataset + newDataSet = new DataSet(groups); } - this.body = null; + this.groupsData = newDataSet; + this.itemSet.setGroups(newDataSet); }; /** - * Repaint the component - * @return {boolean} Returns true if the component is resized + * Set both items and groups in one go + * @param {{items: Array | vis.DataSet, groups: Array | vis.DataSet}} data */ - TimeAxis.prototype.redraw = function () { - var options = this.options; - 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 = options.orientation.axis == 'top' ? this.body.dom.top : this.body.dom.bottom; - var parentChanged = foreground.parentNode !== parent; - - // calculate character width and height - this._calculateCharSize(); + Timeline.prototype.setData = function (data) { + if (data && data.groups) { + this.setGroups(data.groups); + } - // TODO: recalculate sizes only needed when parent is resized or options is changed - var showMinorLabels = this.options.showMinorLabels; - var showMajorLabels = this.options.showMajorLabels; + if (data && data.items) { + this.setItems(data.items); + } + }; - // 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 - (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(); + /** + * 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. If ids is an empty array, all items will be + * unselected. + * @param {Object} [options] Available options: + * `focus: boolean` + * If true, focus will be set to the selected item(s) + * `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'. + * Only applicable when option focus is true. + */ + Timeline.prototype.setSelection = function (ids, options) { + this.itemSet && this.itemSet.setSelection(ids); - // 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); + if (options && options.focus) { + this.focus(ids, options); } - - return this._isResized() || parentChanged; }; /** - * Repaint major and minor text labels and vertical grid lines - * @private + * Get the selected items by their id + * @return {Array} ids The ids of the selected items */ - 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) * 7).valueOf(); - var minimumStep = timeLabelsize - DateUtil.getHiddenDurationBefore(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); - if (this.options.format) { - step.setFormat(this.options.format); - } - if (this.options.timeAxis) { - step.setScale(this.options.timeAxis); - } - this.step = step; + Timeline.prototype.getSelection = function () { + return this.itemSet && this.itemSet.getSelection() || []; + }; - // 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 = []; + /** + * Adjust the visible window such that the selected item (or multiple items) + * are centered on screen. + * @param {String | String[]} id An item id or array with item ids + * @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'. + */ + Timeline.prototype.focus = function (id, options) { + if (!this.itemsData || id == undefined) return; - var cur; - var x = 0; - var isMajor; - var xPrev = 0; - var width = 0; - var prevLine; - var xFirstMajorLabel = undefined; - var max = 0; - var className; + var ids = Array.isArray(id) ? id : [id]; - step.first(); - while (step.hasNext() && max < 1000) { - max++; + // get the specified item(s) + var itemsData = this.itemsData.getDataSet().get(ids, { + type: { + start: 'Date', + end: 'Date' + } + }); - cur = step.getCurrent(); - isMajor = step.isMajor(); - className = step.getClassName(); + // calculate minimum start and maximum end of specified items + var start = null; + var end = null; + itemsData.forEach(function (itemData) { + var s = itemData.start.valueOf(); + var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf(); - xPrev = x; - x = this.body.util.toScreen(cur); - width = x - xPrev; - if (prevLine) { - prevLine.style.width = width + 'px'; + if (start === null || s < start) { + start = s; } - if (this.options.showMinorLabels) { - this._repaintMinorText(x, step.getLabelMinor(), orientation, className); + if (end === null || e > end) { + end = e; } + }); - if (isMajor && this.options.showMajorLabels) { - if (x > 0) { - if (xFirstMajorLabel == undefined) { - xFirstMajorLabel = x; - } - this._repaintMajorText(x, step.getLabelMajor(), orientation, className); - } - prevLine = this._repaintMajorLine(x, orientation, className); - } else { - prevLine = this._repaintMinorLine(x, orientation, className); - } + if (start !== null && end !== null) { + // calculate the new middle and interval for the window + var middle = (start + end) / 2; + var interval = Math.max(this.range.end - this.range.start, (end - start) * 1.1); - step.next(); + var animation = options && options.animation !== undefined ? options.animation : true; + this.range.setRange(middle - interval / 2, middle + interval / 2, animation); } + }; - // 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 + /** + * Get the data range of the item set. + * @returns {{min: Date, max: Date}} range A range with a start and end Date. + * When no minimum is found, min==null + * When no maximum is found, max==null + */ + Timeline.prototype.getItemRange = function () { + // calculate min from start filed + var dataset = this.itemsData && this.itemsData.getDataSet(); + var min = null; + var max = null; - if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) { - this._repaintMajorText(0, leftText, orientation, className); - } - } + if (dataset) { + // calculate the minimum value of the field 'start' + var minItem = dataset.min('start'); + min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null; + // Note: we convert first to Date and then to number because else + // a conversion from ISODate to Number will fail - // 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); + // calculate maximum value of fields 'start' and 'end' + var maxStartItem = dataset.max('start'); + if (maxStartItem) { + max = util.convert(maxStartItem.start, 'Date').valueOf(); + } + var maxEndItem = dataset.max('end'); + if (maxEndItem) { + if (max == null) { + max = util.convert(maxEndItem.end, 'Date').valueOf(); + } else { + max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf()); } } - }); + } + + return { + min: min != null ? new Date(min) : null, + max: max != null ? new Date(max) : null + }; }; /** - * 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 - * @private + * Generate Timeline related information from an event + * @param {Event} event + * @return {Object} An object with related information, like on which area + * The event happened, whether clicked on an item, etc. */ - TimeAxis.prototype._repaintMinorText = function (x, text, orientation, className) { - // reuse redundant label - var label = this.dom.redundant.minorTexts.shift(); + Timeline.prototype.getEventProperties = function (event) { + var clientX = event.center ? event.center.x : event.clientX; + var clientY = event.center ? event.center.y : event.clientY; + var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer); + var y = clientY - util.getAbsoluteTop(this.dom.centerContainer); - 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); + var item = this.itemSet.itemFromTarget(event); + var group = this.itemSet.groupFromTarget(event); + var customTime = CustomTime.customTimeFromTarget(event); - label.childNodes[0].nodeValue = text; + var snap = this.itemSet.options.snap || null; + var scale = this.body.util.getScale(); + var step = this.body.util.getStep(); + var time = this._toTime(x); + var snappedTime = snap ? snap(time, scale, step) : time; - label.style.top = orientation == 'top' ? this.props.majorLabelHeight + 'px' : '0'; - label.style.left = x + 'px'; - label.className = 'vis-text vis-minor ' + className; - //label.title = title; // TODO: this is a heavy operation + var element = util.getTarget(event); + var what = null; + if (item != null) { + what = 'item'; + } else if (customTime != null) { + what = 'custom-time'; + } else if (util.hasParent(element, this.timeAxis.dom.foreground)) { + what = 'axis'; + } else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) { + what = 'axis'; + } else if (util.hasParent(element, this.itemSet.dom.labelSet)) { + what = 'group-label'; + } else if (util.hasParent(element, this.currentTime.bar)) { + what = 'current-time'; + } else if (util.hasParent(element, this.dom.center)) { + what = 'background'; + } + + return { + event: event, + item: item ? item.id : null, + group: group ? group.groupId : null, + what: what, + pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX, + pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY, + x: x, + y: y, + time: time, + snappedTime: snappedTime + }; }; - /** - * 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 - * @private - */ - TimeAxis.prototype._repaintMajorText = function (x, text, orientation, className) { - // reuse redundant label - var label = this.dom.redundant.majorTexts.shift(); + module.exports = Timeline; - if (!label) { - // create label - var content = document.createTextNode(text); - label = document.createElement('div'); - label.appendChild(content); - this.dom.foreground.appendChild(label); - } - this.dom.majorTexts.push(label); +/***/ }, +/* 26 */ +/***/ function(module, exports, __webpack_require__) { - label.childNodes[0].nodeValue = text; - label.className = 'vis-text vis-major ' + className; - //label.title = title; // TODO: this is a heavy operation + 'use strict'; - label.style.top = orientation == 'top' ? '0' : this.props.minorLabelHeight + 'px'; - label.style.left = x + 'px'; - }; + var util = __webpack_require__(7); + var Component = __webpack_require__(27); + var moment = __webpack_require__(8); + var locales = __webpack_require__(28); /** - * Create a minor line for the axis at position x - * @param {Number} x - * @param {String} orientation "top" or "bottom" (default) - * @param {String} className - * @return {Element} Returns the created line - * @private + * A current time bar + * @param {{range: Range, dom: Object, domProps: Object}} body + * @param {Object} [options] Available parameters: + * {Boolean} [showCurrentTime] + * @constructor CurrentTime + * @extends Component */ - TimeAxis.prototype._repaintMinorLine = function (x, 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); + function CurrentTime(body, options) { + this.body = body; - 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'; - line.style.left = x - props.minorLineWidth / 2 + 'px'; + // default options + this.defaultOptions = { + showCurrentTime: true, - line.className = 'vis-grid vis-vertical vis-minor ' + className; + locales: locales, + locale: 'en' + }; + this.options = util.extend({}, this.defaultOptions); + this.offset = 0; - return line; - }; + this._create(); + + this.setOptions(options); + } + + CurrentTime.prototype = new Component(); /** - * Create a Major line for the axis at position x - * @param {Number} x - * @param {String} orientation "top" or "bottom" (default) - * @param {String} className - * @return {Element} Returns the created line + * Create the HTML DOM for the current time bar * @private */ - TimeAxis.prototype._repaintMajorLine = function (x, 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'; - } - line.style.left = x - props.majorLineWidth / 2 + 'px'; - line.style.height = props.majorLineHeight + 'px'; - - line.className = 'vis-grid vis-vertical vis-major ' + className; + 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%'; - return line; + this.bar = bar; }; /** - * 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 + * Destroy the CurrentTime bar */ - 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; + CurrentTime.prototype.destroy = function () { + this.options.showCurrentTime = false; + this.redraw(); // will remove the bar from the DOM and stop refreshing - // 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.body = null; + }; - this.dom.measureCharMajor.appendChild(document.createTextNode('0')); - this.dom.foreground.appendChild(this.dom.measureCharMajor); + /** + * 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(['showCurrentTime', 'locale', 'locales'], this.options, options); } - this.props.majorCharHeight = this.dom.measureCharMajor.clientHeight; - this.props.majorCharWidth = this.dom.measureCharMajor.clientWidth; }; - module.exports = TimeAxis; - -/***/ }, -/* 36 */ -/***/ function(module, exports, __webpack_require__) { - - // Load custom shapes into CanvasRenderingContext2D - 'use strict'; - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - - var _modulesGroups = __webpack_require__(54); + /** + * 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); - var _modulesGroups2 = _interopRequireDefault(_modulesGroups); + this.start(); + } - var _modulesNodesHandler = __webpack_require__(55); + var now = new Date(new Date().valueOf() + this.offset); + var x = this.body.util.toScreen(now); - var _modulesNodesHandler2 = _interopRequireDefault(_modulesNodesHandler); + 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.html#Localization'); + this.warned = true; + } + locale = this.options.locales['en']; // fall back on english when not available + } + var title = locale.current + ' ' + locale.time + ': ' + moment(now).format('dddd, MMMM Do YYYY, H:mm:ss'); + title = title.charAt(0).toUpperCase() + title.substring(1); - var _modulesEdgesHandler = __webpack_require__(56); + 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(); + } - var _modulesEdgesHandler2 = _interopRequireDefault(_modulesEdgesHandler); + return false; + }; - var _modulesPhysicsEngine = __webpack_require__(1); + /** + * Start auto refreshing the current time bar + */ + CurrentTime.prototype.start = function () { + var me = this; - var _modulesPhysicsEngine2 = _interopRequireDefault(_modulesPhysicsEngine); + function update() { + me.stop(); - var _modulesClustering = __webpack_require__(58); + // 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; - var _modulesClustering2 = _interopRequireDefault(_modulesClustering); + me.redraw(); - var _modulesCanvasRenderer = __webpack_require__(59); + // start a renderTimer to adjust for the new time + me.currentTimeTimer = setTimeout(update, interval); + } - var _modulesCanvasRenderer2 = _interopRequireDefault(_modulesCanvasRenderer); + update(); + }; - var _modulesCanvas = __webpack_require__(60); + /** + * Stop auto refreshing the current time bar + */ + CurrentTime.prototype.stop = function () { + if (this.currentTimeTimer !== undefined) { + clearTimeout(this.currentTimeTimer); + delete this.currentTimeTimer; + } + }; - var _modulesCanvas2 = _interopRequireDefault(_modulesCanvas); + /** + * 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(); + }; - var _modulesView = __webpack_require__(61); + /** + * Get the current time. + * @return {Date} Returns the current time. + */ + CurrentTime.prototype.getCurrentTime = function () { + return new Date(new Date().valueOf() + this.offset); + }; - var _modulesView2 = _interopRequireDefault(_modulesView); + module.exports = CurrentTime; - var _modulesInteractionHandler = __webpack_require__(62); +/***/ }, +/* 27 */ +/***/ function(module, exports, __webpack_require__) { - var _modulesInteractionHandler2 = _interopRequireDefault(_modulesInteractionHandler); + /** + * Prototype for visual components + * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body] + * @param {Object} [options] + */ + "use strict"; - var _modulesSelectionHandler = __webpack_require__(63); + function Component(body, options) { + this.options = null; + this.props = null; + } - var _modulesSelectionHandler2 = _interopRequireDefault(_modulesSelectionHandler); + /** + * 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; + }; - var _modulesLayoutEngine = __webpack_require__(64); + /** + * Destroy the component. Cleanup DOM and event listeners + */ + Component.prototype.destroy = function () {}; - var _modulesLayoutEngine2 = _interopRequireDefault(_modulesLayoutEngine); + /** + * 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; - var _modulesManipulationSystem = __webpack_require__(65); + this.props._previousWidth = this.props.width; + this.props._previousHeight = this.props.height; - var _modulesManipulationSystem2 = _interopRequireDefault(_modulesManipulationSystem); + return resized; + }; - var _sharedConfigurator = __webpack_require__(45); + module.exports = Component; - var _sharedConfigurator2 = _interopRequireDefault(_sharedConfigurator); + // should be implemented by the component + +/***/ }, +/* 28 */ +/***/ function(module, exports, __webpack_require__) { - var _sharedValidator = __webpack_require__(46); + // English + 'use strict'; - var _sharedValidator2 = _interopRequireDefault(_sharedValidator); + exports['en'] = { + current: 'current', + time: 'time' + }; + exports['en_EN'] = exports['en']; + exports['en_US'] = exports['en']; + + // Dutch + exports['nl'] = { + current: 'huidige', + time: 'tijd' + }; + exports['nl_NL'] = exports['nl']; + exports['nl_BE'] = exports['nl']; - var _optionsJs = __webpack_require__(66); +/***/ }, +/* 29 */ +/***/ function(module, exports, __webpack_require__) { - __webpack_require__(67); + 'use strict'; - var Emitter = __webpack_require__(43); - var Hammer = __webpack_require__(41); - var util = __webpack_require__(2); - var DataSet = __webpack_require__(4); - var DataView = __webpack_require__(5); - var dotparser = __webpack_require__(38); - var gephiParser = __webpack_require__(39); - var Images = __webpack_require__(37); - var Activator = __webpack_require__(68); - var locales = __webpack_require__(69); + var util = __webpack_require__(7); + var hammerUtil = __webpack_require__(30); + var moment = __webpack_require__(8); + var Component = __webpack_require__(27); + var DateUtil = __webpack_require__(31); /** - * @constructor Network - * Create a network visualization, displaying nodes and edges. - * - * @param {Element} container The DOM element in which the Network will - * be created. Normally a div element. - * @param {Object} data An object containing parameters - * {Array} nodes - * {Array} edges - * @param {Object} options Options + * @constructor Range + * 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 */ - function Network(container, data, options) { - var _this = this; + function Range(body, options) { + var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0); + this.start = now.clone().add(-3, 'days').valueOf(); // Number + this.end = now.clone().add(4, 'days').valueOf(); // Number - if (!(this instanceof Network)) { - throw new SyntaxError('Constructor must be called with the new operator'); - } + this.body = body; + this.deltaDifference = 0; + this.scaleOffset = 0; + this.startToFront = false; + this.endToFront = true; - // set constant values - this.options = {}; + // default options this.defaultOptions = { - locale: 'en', - locales: locales, - clickToUse: false + start: null, + end: null, + direction: 'horizontal', // 'horizontal' or 'vertical' + moveable: true, + zoomable: true, + min: null, + max: null, + zoomMin: 10, // milliseconds + zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds }; - util.extend(this.options, this.defaultOptions); + this.options = util.extend({}, this.defaultOptions); - // containers for nodes and edges - this.body = { - nodes: {}, - nodeIndices: [], - edges: {}, - edgeIndices: [], - data: { - nodes: null, // A DataSet or DataView - edges: null // A DataSet or DataView - }, - functions: { - createNode: function createNode() {}, - createEdge: function createEdge() {}, - getPointer: function getPointer() {} - }, - emitter: { - on: this.on.bind(this), - off: this.off.bind(this), - emit: this.emit.bind(this), - once: this.once.bind(this) - }, - eventListeners: { - onTap: function onTap() {}, - onTouch: function onTouch() {}, - onDoubleTap: function onDoubleTap() {}, - onHold: function onHold() {}, - onDragStart: function onDragStart() {}, - onDrag: function onDrag() {}, - onDragEnd: function onDragEnd() {}, - onMouseWheel: function onMouseWheel() {}, - onPinch: function onPinch() {}, - onMouseMove: function onMouseMove() {}, - onRelease: function onRelease() {}, - onContext: function onContext() {} - }, - container: container, - view: { - scale: 1, - translation: { x: 0, y: 0 } - } + this.props = { + touch: {} }; + this.animationTimer = null; - // bind the event listeners - this.bindEventListeners(); - - // setting up all modules - this.images = new Images(function () { - return _this.body.emitter.emit('_requestRedraw'); - }); // object with images - this.groups = new _modulesGroups2['default'](); // object with groups - this.canvas = new _modulesCanvas2['default'](this.body); // DOM handler - this.selectionHandler = new _modulesSelectionHandler2['default'](this.body, this.canvas); // Selection handler - this.interactionHandler = new _modulesInteractionHandler2['default'](this.body, this.canvas, this.selectionHandler); // Interaction handler handles all the hammer bindings (that are bound by canvas), key - this.view = new _modulesView2['default'](this.body, this.canvas); // camera handler, does animations and zooms - this.renderer = new _modulesCanvasRenderer2['default'](this.body, this.canvas); // renderer, starts renderloop, has events that modules can hook into - this.physics = new _modulesPhysicsEngine2['default'](this.body); // physics engine, does all the simulations - this.layoutEngine = new _modulesLayoutEngine2['default'](this.body); // layout engine for inital layout and hierarchical layout - this.clustering = new _modulesClustering2['default'](this.body); // clustering api - this.manipulation = new _modulesManipulationSystem2['default'](this.body, this.canvas, this.selectionHandler); // data manipulation system - - this.nodesHandler = new _modulesNodesHandler2['default'](this.body, this.images, this.groups, this.layoutEngine); // Handle adding, deleting and updating of nodes as well as global options - this.edgesHandler = new _modulesEdgesHandler2['default'](this.body, this.images, this.groups); // Handle adding, deleting and updating of edges as well as global options + // 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)); - // create the DOM elements - this.canvas._create(); + // mouse wheel for zooming + this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this)); - // setup configuration system - this.configurator = new _sharedConfigurator2['default'](this, this.body.container, _optionsJs.configureOptions, this.canvas.pixelRatio); + // pinch to zoom + this.body.emitter.on('touch', this._onTouch.bind(this)); + this.body.emitter.on('pinch', this._onPinch.bind(this)); - // apply options this.setOptions(options); - - // load data (the disable start variable will be the same as the enabled clustering) - this.setData(data); } - // Extend Network with an Emitter mixin - Emitter(Network.prototype); + Range.prototype = new Component(); /** - * Set options - * @param {Object} options + * 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 */ - Network.prototype.setOptions = function (options) { - var _this2 = this; - - if (options !== undefined) { + Range.prototype.setOptions = function (options) { + if (options) { + // copy the options that we know + var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable', 'activate', 'hiddenDates']; + util.selectiveExtend(fields, this.options, options); - var errorFound = _sharedValidator2['default'].validate(options, _optionsJs.allOptions); - if (errorFound === true) { - console.log('%cErrors have been found in the supplied options object.', _sharedValidator.printStyle); + if ('start' in options || 'end' in options) { + // apply a new range. both start and end are optional + this.setRange(options.start, options.end); } + } + }; - // copy the global fields over - var fields = ['locale', 'locales', 'clickToUse']; - util.selectiveDeepExtend(fields, this.options, options); - - // the hierarchical system can adapt the edges and the physics to it's own options because not all combinations work with the hierarichical system. - options = this.layoutEngine.setOptions(options.layout, options); - - this.canvas.setOptions(options); // options for canvas are in globals - - // pass the options to the modules - this.groups.setOptions(options.groups); - this.nodesHandler.setOptions(options.nodes); - this.edgesHandler.setOptions(options.edges); - this.physics.setOptions(options.physics); - this.manipulation.setOptions(options.manipulation, options, this.options); // manipulation uses the locales in the globals + /** + * 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".'); + } + } - this.interactionHandler.setOptions(options.interaction); - this.renderer.setOptions(options.interaction); // options for rendering are in interaction - this.selectionHandler.setOptions(options.interaction); // options for selection are in interaction + /** + * Set a new start and end range + * @param {Date | Number | String} [start] + * @param {Date | Number | String} [end] + * @param {boolean | {duration: number, easingFunction: string}} [animation=false] + * 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 {Boolean} [byUser=false] + * + */ + Range.prototype.setRange = function (start, end, animation, byUser) { + if (byUser !== true) { + byUser = false; + } + var finalStart = start != undefined ? util.convert(start, 'Date').valueOf() : null; + var finalEnd = end != undefined ? util.convert(end, 'Date').valueOf() : null; + this._cancelAnimation(); - // reload the settings of the nodes to apply changes in groups that are not referenced by pointer. - if (options.groups !== undefined) { - this.body.emitter.emit('refreshNodes'); + if (animation) { + // true or an Object + var me = this; + var initStart = this.start; + var initEnd = this.end; + var duration = typeof animation === 'object' && 'duration' in animation ? animation.duration : 500; + var easingName = typeof animation === 'object' && 'easingFunction' in animation ? animation.easingFunction : 'easeInOutQuad'; + var easingFunction = util.easingFunctions[easingName]; + if (!easingFunction) { + throw new Error('Unknown easing function ' + JSON.stringify(easingName) + '. ' + 'Choose from: ' + Object.keys(util.easingFunctions).join(', ')); } - // these two do not have options at the moment, here for completeness - //this.view.setOptions(options.view); - //this.clustering.setOptions(options.clustering); - - this.configurator.setOptions(options.configure); - - // if the configuration system is enabled, copy all options and put them into the config system - if (this.configurator.options.enabled === true) { - var networkOptions = { nodes: {}, edges: {}, layout: {}, interaction: {}, manipulation: {}, physics: {}, global: {} }; - util.deepExtend(networkOptions.nodes, this.nodesHandler.options); - util.deepExtend(networkOptions.edges, this.edgesHandler.options); - util.deepExtend(networkOptions.layout, this.layoutEngine.options); - // load the selectionHandler and rendere default options in to the interaction group - util.deepExtend(networkOptions.interaction, this.selectionHandler.options); - util.deepExtend(networkOptions.interaction, this.renderer.options); - - util.deepExtend(networkOptions.interaction, this.interactionHandler.options); - util.deepExtend(networkOptions.manipulation, this.manipulation.options); - util.deepExtend(networkOptions.physics, this.physics.options); - // load globals into the global object - util.deepExtend(networkOptions.global, this.canvas.options); - util.deepExtend(networkOptions.global, this.options); + var initTime = new Date().valueOf(); + var anyChanged = false; - this.configurator.setModuleOptions(networkOptions); - } + 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; - // handle network global options - if (options.clickToUse !== undefined) { - if (options.clickToUse === true) { - if (this.activator === undefined) { - this.activator = new Activator(this.canvas.frame); - this.activator.on('change', function () { - _this2.body.emitter.emit('activate'); - }); + changed = me._applyRange(s, e); + DateUtil.updateHiddenDates(me.body, me.options.hiddenDates); + anyChanged = anyChanged || changed; + if (changed) { + me.body.emitter.emit('rangechange', { start: new Date(me.start), end: new Date(me.end), byUser: byUser }); } - } else { - if (this.activator !== undefined) { - this.activator.destroy(); - delete this.activator; + + if (done) { + if (anyChanged) { + me.body.emitter.emit('rangechanged', { start: new Date(me.start), end: new Date(me.end), byUser: byUser }); + } + } 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); } - this.body.emitter.emit('activate'); } - } else { - this.body.emitter.emit('activate'); - } + }; - this.canvas.setSize(); + return next(); + } else { + var changed = this._applyRange(finalStart, finalEnd); + DateUtil.updateHiddenDates(this.body, this.options.hiddenDates); + if (changed) { + var params = { start: new Date(this.start), end: new Date(this.end), byUser: byUser }; + this.body.emitter.emit('rangechange', params); + this.body.emitter.emit('rangechanged', params); + } + } + }; - // start the physics simulation. Can be safely called multiple times. - this.body.emitter.emit('startSimulation'); + /** + * Stop an animation + * @private + */ + Range.prototype._cancelAnimation = function () { + if (this.animationTimer) { + clearTimeout(this.animationTimer); + this.animationTimer = null; } }; /** - * Update the this.body.nodeIndices with the most recent node index list + * 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 */ - Network.prototype._updateVisibleIndices = function () { - var nodes = this.body.nodes; - var edges = this.body.edges; - this.body.nodeIndices = []; - this.body.edgeIndices = []; + 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; - for (var nodeId in nodes) { - if (nodes.hasOwnProperty(nodeId)) { - if (nodes[nodeId].options.hidden === false) { - this.body.nodeIndices.push(nodeId); + // 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 start < end + 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; + } } } } - for (var edgeId in edges) { - if (edges.hasOwnProperty(edgeId)) { - if (edges[edgeId].options.hidden === false) { - this.body.edgeIndices.push(edgeId); + // 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; + } } } } - }; - /** - * Bind all events - */ - Network.prototype.bindEventListeners = function () { - var _this3 = this; + // prevent (end-start) < zoomMin + if (this.options.zoomMin !== null) { + var zoomMin = parseFloat(this.options.zoomMin); + if (zoomMin < 0) { + zoomMin = 0; + } + if (newEnd - newStart < zoomMin) { + if (this.end - this.start === zoomMin && newStart > this.start && 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; + } + } + } - // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed. - this.body.emitter.on('_dataChanged', function () { - // update shortcut lists - _this3._updateVisibleIndices(); - _this3.physics.updatePhysicsData(); + // prevent (end-start) > zoomMax + if (this.options.zoomMax !== null) { + var zoomMax = parseFloat(this.options.zoomMax); + if (zoomMax < 0) { + zoomMax = 0; + } - // call the dataUpdated event because the only difference between the two is the updating of the indices - _this3.body.emitter.emit('_dataUpdated'); - }); + 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; + } + } + } - // this is called when options of EXISTING nodes or edges have changed. - this.body.emitter.on('_dataUpdated', function () { - // update values - _this3._updateValueRange(_this3.body.nodes); - _this3._updateValueRange(_this3.body.edges); - // start simulation (can be called safely, even if already running) - _this3.body.emitter.emit('startSimulation'); - }); + 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; }; /** - * Set nodes and edges, and optionally options as well. - * - * @param {Object} data Object containing parameters: - * {Array | DataSet | DataView} [nodes] Array with nodes - * {Array | DataSet | DataView} [edges] Array with edges - * {String} [dot] String containing data in DOT format - * {String} [gephi] String containing data in gephi JSON format - * {Options} [options] Object with options + * Retrieve the current range. + * @return {Object} An object with start and end properties */ - Network.prototype.setData = function (data) { - // reset the physics engine. - this.body.emitter.emit('resetPhysics'); - this.body.emitter.emit('_resetData'); + Range.prototype.getRange = function () { + return { + start: this.start, + end: this.end + }; + }; - // unselect all to ensure no selections from old data are carried over. - this.selectionHandler.unselectAll(); + /** + * Calculate the conversion offset and scale for current range, based on + * the provided width + * @param {Number} width + * @returns {{offset: number, scale: number}} conversion + */ + Range.prototype.conversion = function (width, totalHidden) { + return Range.conversion(this.start, this.end, width, totalHidden); + }; - if (data && data.dot && (data.nodes || data.edges)) { - throw new SyntaxError('Data must contain either parameter "dot" or ' + ' parameter pair "nodes" and "edges", but not both.'); + /** + * 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 + * @returns {{offset: number, scale: number}} conversion + */ + Range.conversion = function (start, end, width, totalHidden) { + if (totalHidden === undefined) { + totalHidden = 0; } - - // set options - this.setOptions(data && data.options); - // set all data - if (data && data.dot) { - console.log('The dot property has been depricated. Please use the static convertDot method to convert DOT into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertDot(dotString);'); - // parse DOT file - var dotData = dotparser.DOTToGraph(data.dot); - this.setData(dotData); - return; - } else if (data && data.gephi) { - // parse DOT file - console.log('The gephi property has been depricated. Please use the static convertGephi method to convert gephi into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertGephi(gephiJson);'); - var gephiData = gephiParser.parseGephi(data.gephi); - this.setData(gephiData); - return; + if (width != 0 && end - start != 0) { + return { + offset: start, + scale: width / (end - start - totalHidden) + }; } else { - this.nodesHandler.setData(data && data.nodes, true); - this.edgesHandler.setData(data && data.edges, true); + return { + offset: 0, + scale: 1 + }; } + }; - // emit change in data - this.body.emitter.emit('_dataChanged'); + /** + * 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; - // find a stable position or start animating to a stable position - this.body.emitter.emit('initPhysics'); + // 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.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'; + } }; /** - * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function. - * var network = new vis.Network(..); - * network.destroy(); - * network = null; + * Perform dragging operation + * @param {Event} event + * @private */ - Network.prototype.destroy = function () { - this.body.emitter.emit('destroy'); - // clear events - this.body.emitter.off(); - this.off(); + Range.prototype._onDrag = function (event) { + // only allow dragging when configured as movable + if (!this.options.moveable) return; - // delete modules - delete this.groups; - delete this.canvas; - delete this.selectionHandler; - delete this.interactionHandler; - delete this.view; - delete this.renderer; - delete this.physics; - delete this.layoutEngine; - delete this.clustering; - delete this.manipulation; - delete this.nodesHandler; - delete this.edgesHandler; - delete this.configurator; - delete this.images; + // 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; - // delete emitter bindings - delete this.body.emitter.emit; - delete this.body.emitter.on; - delete this.body.emitter.off; - delete this.body.emitter.once; - delete this.body.emitter; + 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; - for (var nodeId in this.body.nodes) { - delete this.body.nodes[nodeId]; + // 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 = -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; } - for (var edgeId in this.body.edges) { - delete this.body.edges[edgeId]; + + this.previousDelta = delta; + this._applyRange(newStart, newEnd); + + // fire a rangechange event + this.body.emitter.emit('rangechange', { + start: new Date(this.start), + end: new Date(this.end), + byUser: true + }); + }; + + /** + * Stop dragging operation + * @param {event} event + * @private + */ + Range.prototype._onDragEnd = function (event) { + // 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'; } - // remove the container and everything inside it recursively - util.recursiveDOMDelete(this.body.container); + // fire a rangechanged event + this.body.emitter.emit('rangechanged', { + start: new Date(this.start), + end: new Date(this.end), + byUser: true + }); }; /** - * Update the values of all object in the given array according to the current - * value range of the objects in the array. - * @param {Object} obj An object containing a set of Edges or Nodes - * The objects must have a method getValue() and - * setValueRange(min, max). + * Event handler for mouse wheel event, used to zoom + * Code from http://adomas.org/javascript-mouse-wheel/ + * @param {Event} event * @private */ - Network.prototype._updateValueRange = function (obj) { - var id; + Range.prototype._onMouseWheel = function (event) { + // only allow zooming when configured as zoomable and moveable + if (!(this.options.zoomable && this.options.moveable)) return; - // determine the range of the objects - var valueMin = undefined; - var valueMax = undefined; - var valueTotal = 0; - for (id in obj) { - if (obj.hasOwnProperty(id)) { - var value = obj[id].getValue(); - if (value !== undefined) { - valueMin = valueMin === undefined ? value : Math.min(value, valueMin); - valueMax = valueMax === undefined ? value : Math.max(value, valueMax); - valueTotal += value; - } - } + // 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; } - // adjust the range of all objects - if (valueMin !== undefined && valueMax !== undefined) { - for (id in obj) { - if (obj.hasOwnProperty(id)) { - obj[id].setValueRange(valueMin, valueMax, valueTotal); - } + // 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 pointer = getPointer({ x: event.clientX, y: event.clientY }, this.body.dom.center); + var pointerDate = this._pointerToDate(pointer); + + this.zoom(scale, pointerDate, delta); } + + // Prevent default actions caused by mouse wheel + // (else the page and timeline both zoom and scroll) + event.preventDefault(); }; /** - * Returns true when the Network is active. - * @returns {boolean} + * Start of a touch gesture + * @private */ - Network.prototype.isActive = function () { - return !this.activator || this.activator.active; + Range.prototype._onTouch = function (event) { + 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; }; - Network.prototype.setSize = function () { - return this.canvas.setSize.apply(this.canvas, arguments); - }; - Network.prototype.canvasToDOM = function () { - return this.canvas.canvasToDOM.apply(this.canvas, arguments); - }; - Network.prototype.DOMtoCanvas = function () { - return this.canvas.setSize.DOMtoCanvas(this.canvas, arguments); - }; - Network.prototype.findNode = function () { - return this.clustering.findNode.apply(this.clustering, arguments); - }; - Network.prototype.isCluster = function () { - return this.clustering.isCluster.apply(this.clustering, arguments); - }; - Network.prototype.openCluster = function () { - return this.clustering.openCluster.apply(this.clustering, arguments); - }; - Network.prototype.cluster = function () { - return this.clustering.cluster.apply(this.clustering, arguments); - }; - Network.prototype.getNodesInCluster = function () { - return this.clustering.getNodesInCluster.apply(this.clustering, arguments); - }; - Network.prototype.clusterByConnection = function () { - return this.clustering.clusterByConnection.apply(this.clustering, arguments); - }; - Network.prototype.clusterByHubsize = function () { - return this.clustering.clusterByHubsize.apply(this.clustering, arguments); - }; - Network.prototype.clusterOutliers = function () { - return this.clustering.clusterOutliers.apply(this.clustering, arguments); - }; - Network.prototype.getSeed = function () { - return this.layoutEngine.getSeed.apply(this.layoutEngine, arguments); - }; - Network.prototype.enableEditMode = function () { - return this.manipulation.enableEditMode.apply(this.manipulation, arguments); - }; - Network.prototype.disableEditMode = function () { - return this.manipulation.disableEditMode.apply(this.manipulation, arguments); - }; - Network.prototype.addNodeMode = function () { - return this.manipulation.addNodeMode.apply(this.manipulation, arguments); - }; - Network.prototype.editNode = function () { - return this.manipulation.editNode.apply(this.manipulation, arguments); - }; - Network.prototype.editNodeMode = function () { - console.log('Depricated: Please use editNode instead of editNodeMode.');return this.manipulation.editNode.apply(this.manipulation, arguments); - }; - Network.prototype.addEdgeMode = function () { - return this.manipulation.addEdgeMode.apply(this.manipulation, arguments); - }; - Network.prototype.editEdgeMode = function () { - return this.manipulation.editEdgeMode.apply(this.manipulation, arguments); - }; - Network.prototype.deleteSelected = function () { - return this.manipulation.deleteSelected.apply(this.manipulation, arguments); - }; - Network.prototype.getPositions = function () { - return this.nodesHandler.getPositions.apply(this.nodesHandler, arguments); - }; - Network.prototype.storePositions = function () { - return this.nodesHandler.storePositions.apply(this.nodesHandler, arguments); - }; - Network.prototype.getBoundingBox = function () { - return this.nodesHandler.getBoundingBox.apply(this.nodesHandler, arguments); - }; - Network.prototype.getConnectedNodes = function (objectId) { - if (this.body.nodes[objectId] !== undefined) { - return this.nodesHandler.getConnectedNodes.apply(this.nodesHandler, arguments); - } else { - return this.edgesHandler.getConnectedNodes.apply(this.edgesHandler, arguments); - } - }; - Network.prototype.getConnectedEdges = function () { - return this.nodesHandler.getConnectedEdges.apply(this.nodesHandler, arguments); - }; - Network.prototype.startSimulation = function () { - return this.physics.startSimulation.apply(this.physics, arguments); - }; - Network.prototype.stopSimulation = function () { - return this.physics.stopSimulation.apply(this.physics, arguments); - }; - Network.prototype.stabilize = function () { - return this.physics.stabilize.apply(this.physics, arguments); - }; - Network.prototype.getSelection = function () { - return this.selectionHandler.getSelection.apply(this.selectionHandler, arguments); - }; - Network.prototype.getSelectedNodes = function () { - return this.selectionHandler.getSelectedNodes.apply(this.selectionHandler, arguments); - }; - Network.prototype.getSelectedEdges = function () { - return this.selectionHandler.getSelectedEdges.apply(this.selectionHandler, arguments); - }; - Network.prototype.getNodeAt = function () { - var node = this.selectionHandler.getNodeAt.apply(this.selectionHandler, arguments); - if (node !== undefined && node.id !== undefined) { - return node.id; + /** + * 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; + + this.props.touch.allowDragging = false; + + if (!this.props.touch.center) { + this.props.touch.center = getPointer(event.center, this.body.dom.center); } - return node; - }; - Network.prototype.getEdgeAt = function () { - var edge = this.selectionHandler.getEdgeAt.apply(this.selectionHandler, arguments); - if (edge !== undefined && edge.id !== undefined) { - return edge.id; + + 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.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; } - return edge; - }; - Network.prototype.selectNodes = function () { - return this.selectionHandler.selectNodes.apply(this.selectionHandler, arguments); - }; - Network.prototype.selectEdges = function () { - return this.selectionHandler.selectEdges.apply(this.selectionHandler, arguments); - }; - Network.prototype.unselectAll = function () { - return this.selectionHandler.unselectAll.apply(this.selectionHandler, arguments); - }; - Network.prototype.redraw = function () { - return this.renderer.redraw.apply(this.renderer, arguments); - }; - Network.prototype.getScale = function () { - return this.view.getScale.apply(this.view, arguments); - }; - Network.prototype.getViewPosition = function () { - return this.view.getViewPosition.apply(this.view, arguments); - }; - Network.prototype.fit = function () { - return this.view.fit.apply(this.view, arguments); - }; - Network.prototype.moveTo = function () { - return this.view.moveTo.apply(this.view, arguments); - }; - Network.prototype.focus = function () { - return this.view.focus.apply(this.view, arguments); - }; - Network.prototype.releaseNode = function () { - return this.view.releaseNode.apply(this.view, arguments); - }; - module.exports = Network; + this.setRange(newStart, newEnd, false, true); -/***/ }, -/* 37 */ -/***/ function(module, exports, __webpack_require__) { + this.startToFront = false; // revert to default + this.endToFront = true; // revert to default + }; /** - * @class Images - * This class loads images and keeps them stored. + * Helper function to calculate the center date for zooming + * @param {{x: Number, y: Number}} pointer + * @return {number} date + * @private */ - "use strict"; + Range.prototype._pointerToDate = function (pointer) { + var conversion; + var direction = this.options.direction; - function Images(callback) { - this.images = {}; - this.imageBroken = {}; - this.callback = callback; - } + 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; + } + }; /** - * - * @param {string} url Url of the image - * @param {string} url Url of an image to use if the url image is not found - * @return {Image} img The image object + * 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 */ - Images.prototype.load = function (url, brokenUrl, id) { - var img = this.images[url]; // make a pointer - if (img === undefined) { - // create the image - var me = this; - img = new Image(); - img.onload = function () { - // IE11 fix -- thanks dponch! - if (this.width === 0) { - document.body.appendChild(this); - this.width = this.offsetWidth; - this.height = this.offsetHeight; - document.body.removeChild(this); - } + function getPointer(touch, element) { + return { + x: touch.x - util.getAbsoluteLeft(element), + y: touch.y - util.getAbsoluteTop(element) + }; + } - if (me.callback) { - me.images[url] = img; - me.callback(this); - } - }; + /** + * 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. + */ + Range.prototype.zoom = function (scale, center, delta) { + // if centerDate is not provided, take it half between start Date and end Date + if (center == null) { + center = (this.start + this.end) / 2; + } - img.onerror = function () { - if (brokenUrl === undefined) { - console.error("Could not load image:", url); - delete this.src; - if (me.callback) { - me.callback(this); - } - } else { - if (me.imageBroken[id] && me.imageBroken[id][url] === true) { - console.error("Could not load brokenImage:", brokenUrl); - delete this.src; - if (me.callback) { - me.callback(this); - } - } else { - console.error("Could not load image:", url); - this.src = brokenUrl; - if (me.imageBroken[id] === undefined) { - me.imageBroken[id] = {}; - } - me.imageBroken[id][url] = true; - } - } - }; + var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end); + var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, center); + var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore; - img.src = url; + // 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; } - return img; + this.setRange(newStart, newEnd, false, true); + + this.startToFront = false; // revert to default + this.endToFront = true; // revert to default }; - module.exports = Images; + /** + * 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; -/***/ }, -/* 38 */ -/***/ function(module, exports, __webpack_require__) { + // 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; + }; /** - * Parse a text source containing data in DOT language into a JSON object. - * The object contains two lists: one with nodes and one with edges. - * - * DOT language reference: http://www.graphviz.org/doc/info/lang.html - * - * DOT language attributes: http://graphviz.org/content/attrs - * - * @param {String} data Text containing a graph in DOT-notation - * @return {Object} graph An object containing two parameters: - * {Object[]} nodes - * {Object[]} edges + * Move the range to a new center point + * @param {Number} moveTo New center point of the range */ - 'use strict'; + Range.prototype.moveTo = function (moveTo) { + var center = (this.start + this.end) / 2; - function parseDOT(data) { - dot = data; - return parseGraph(); - } + var diff = center - moveTo; - // mapping of attributes from DOT (the keys) to vis.js (the values) - var NODE_ATTR_MAPPING = { - 'fontsize': 'font.size', - 'fontcolor': 'font.color', - 'labelfontcolor': 'font.color', - 'fontname': 'font.face', - 'color': ['color.border', 'color.background'], - 'fillcolor': 'color.background', - 'tooltip': 'title', - 'labeltooltip': 'title' - }; - var EDGE_ATTR_MAPPING = Object.create(NODE_ATTR_MAPPING); - EDGE_ATTR_MAPPING.color = 'color.color'; + // calculate new start and end + var newStart = this.start - diff; + var newEnd = this.end - diff; - // token types enumeration - var TOKENTYPE = { - NULL: 0, - DELIMITER: 1, - IDENTIFIER: 2, - UNKNOWN: 3 + this.setRange(newStart, newEnd); }; - // map with all delimiters - var DELIMITERS = { - '{': true, - '}': true, - '[': true, - ']': true, - ';': true, - '=': true, - ',': true, + module.exports = Range; - '->': true, - '--': true - }; +/***/ }, +/* 30 */ +/***/ function(module, exports, __webpack_require__) { - var dot = ''; // current dot file - var index = 0; // current index in dot file - var c = ''; // current token character in expr - var token = ''; // current token - var tokenType = TOKENTYPE.NULL; // type of the token + 'use strict'; - /** - * Get the first character from the dot file. - * The character is stored into the char c. If the end of the dot file is - * reached, the function puts an empty string in c. - */ - function first() { - index = 0; - c = dot.charAt(0); - } + var Hammer = __webpack_require__(3); /** - * Get the next character from the dot file. - * The character is stored into the char c. If the end of the dot file is - * reached, the function puts an empty string in c. + * Register a touch event, taking place before a gesture + * @param {Hammer} hammer A hammer instance + * @param {function} callback Callback, called as callback(event) */ - function next() { - index++; - c = dot.charAt(index); - } + exports.onTouch = function (hammer, callback) { + callback.inputHandler = function (event) { + if (event.isFirst && !isTouching) { + callback(event); + + isTouching = true; + setTimeout(function () { + isTouching = false; + }, 0); + } + }; + + hammer.on('hammer.input', callback.inputHandler); + }; + + // isTouching is true while a touch action is being emitted + // this is a hack to prevent `touch` from being fired twice + var isTouching = false; /** - * Preview the next character from the dot file. - * @return {String} cNext + * Register a release event, taking place after a gesture + * @param {Hammer} hammer A hammer instance + * @param {function} callback Callback, called as callback(event) */ - function nextPreview() { - return dot.charAt(index + 1); - } + exports.onRelease = function (hammer, callback) { + callback.inputHandler = function (event) { + if (event.isFinal && !isReleasing) { + callback(event); + + isReleasing = true; + setTimeout(function () { + isReleasing = false; + }, 0); + } + }; + + return hammer.on('hammer.input', callback.inputHandler); + }; + + // isReleasing is true while a release action is being emitted + // this is a hack to prevent `release` from being fired twice + var isReleasing = false; /** - * Test whether given character is alphabetic or numeric - * @param {String} c - * @return {Boolean} isAlphaNumeric + * Unregister a touch event, taking place before a gesture + * @param {Hammer} hammer A hammer instance + * @param {function} callback Callback, called as callback(event) */ - var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/; - function isAlphaNumeric(c) { - return regexAlphaNumeric.test(c); - } + exports.offTouch = function (hammer, callback) { + hammer.off('hammer.input', callback.inputHandler); + }; /** - * Merge all options of object b into object b - * @param {Object} a - * @param {Object} b - * @return {Object} a + * Unregister a release event, taking place before a gesture + * @param {Hammer} hammer A hammer instance + * @param {function} callback Callback, called as callback(event) */ - function merge(a, b) { - if (!a) { - a = {}; - } + exports.offRelease = exports.offTouch; - if (b) { - for (var name in b) { - if (b.hasOwnProperty(name)) { - a[name] = b[name]; - } - } - } - return a; - } +/***/ }, +/* 31 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + + var moment = __webpack_require__(8); /** - * Set a value in an object, where the provided parameter name can be a - * path with nested parameters. For example: - * - * var obj = {a: 2}; - * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}} - * - * @param {Object} obj - * @param {String} path A parameter name or dot-separated parameter path, - * like "color.highlight.border". - * @param {*} value + * used in Core to convert the options into a volatile variable + * + * @param Core */ - function setValue(obj, path, value) { - var keys = path.split('.'); - var o = obj; - while (keys.length) { - var key = keys.shift(); - if (keys.length) { - // this isn't the end point - if (!o[key]) { - o[key] = {}; + exports.convertHiddenOptions = function (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); + } } - o = o[key]; - } else { - // this is the end point - o[key] = value; + body.hiddenDates.sort(function (a, b) { + return a.start - b.start; + }); // sort by start time } } - } + }; /** - * Add a node to a graph object. If there is already a node with - * the same id, their attributes will be merged. - * @param {Object} graph - * @param {Object} node + * create new entrees for the repeating hidden dates + * @param body + * @param hiddenDates */ - function addNode(graph, node) { - var i, len; - var current = null; + exports.updateHiddenDates = function (body, hiddenDates) { + if (hiddenDates && body.domProps.centerContainer.width !== undefined) { + exports.convertHiddenOptions(body, hiddenDates); - // find root graph (in case of subgraph) - var graphs = [graph]; // list with all graphs from current graph to root graph - var root = graph; - while (root.parent) { - graphs.push(root.parent); - root = root.parent; - } + var start = moment(body.range.start); + var end = moment(body.range.end); - // find existing node (at root level) by its id - if (root.nodes) { - for (i = 0, len = root.nodes.length; i < len; i++) { - if (node.id === root.nodes[i].id) { - current = root.nodes[i]; - break; - } - } - } + var totalRange = body.range.end - body.range.start; + var pixelTime = totalRange / body.domProps.centerContainer.width; - if (!current) { - // this is a new node - current = { - id: node.id - }; - if (graph.node) { - // clone default attributes - current.attr = merge(current.attr, graph.node); - } - } + 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); - // add node to this (sub)graph and all its parent graphs - for (i = graphs.length - 1; i >= 0; i--) { - var g = graphs[i]; + 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); + } - if (!g.nodes) { - g.nodes = []; - } - if (g.nodes.indexOf(current) === -1) { - g.nodes.push(current); - } - } + var duration = endDate - startDate; + if (duration >= 4 * pixelTime) { - // merge attributes - if (node.attr) { - current.attr = merge(current.attr, node.attr); - } - } + 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"); - /** - * Add an edge to a graph object - * @param {Object} graph - * @param {Object} edge - */ - function addEdge(graph, edge) { - if (!graph.edges) { - graph.edges = []; - } - graph.edges.push(edge); - if (graph.edge) { - var attr = merge({}, graph.edge); // clone default attributes - edge.attr = merge(attr, edge.attr); // merge attributes - } - } + endDate.dayOfYear(start.dayOfYear()); + endDate.year(start.year()); + endDate.subtract(7 - offset, "days"); - /** - * Create an edge to a graph object - * @param {Object} graph - * @param {String | Number | Object} from - * @param {String | Number | Object} to - * @param {String} type - * @param {Object | null} attr - * @return {Object} edge - */ - function createEdge(graph, from, to, type, attr) { - var edge = { - from: from, - to: to, - type: type - }; + runUntil.add(1, "weeks"); + break; + case "weekly": + var dayOffset = endDate.diff(startDate, "days"); + var day = startDate.day(); - if (graph.edge) { - edge.attr = merge({}, graph.edge); // clone default attributes - } - edge.attr = merge(edge.attr || {}, attr); // merge attributes + // set the start date to the range.start + startDate.date(start.date()); + startDate.month(start.month()); + startDate.year(start.year()); + endDate = startDate.clone(); - return edge; - } + // force + startDate.day(day); + endDate.day(day); + endDate.add(dayOffset, "days"); - /** - * Get next token in the current dot file. - * The token and token type are available as token and tokenType - */ - function getToken() { - tokenType = TOKENTYPE.NULL; - token = ''; + startDate.subtract(1, "weeks"); + endDate.subtract(1, "weeks"); - // skip over whitespaces - while (c === ' ' || c === '\t' || c === '\n' || c === '\r') { - // space, tab, enter - next(); - } + 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"); - do { - var isComment = false; + endDate.month(start.month()); + endDate.year(start.year()); + endDate.subtract(1, "months"); + endDate.add(offset, "months"); - // skip comment - if (c === '#') { - // find the previous non-space character - var i = index - 1; - while (dot.charAt(i) === ' ' || dot.charAt(i) === '\t') { - i--; - } - if (dot.charAt(i) === '\n' || dot.charAt(i) === '') { - // the # is at the start of a line, this is indeed a line comment - while (c != '' && c != '\n') { - next(); - } - isComment = true; - } - } - if (c === '/' && nextPreview() === '/') { - // skip line comment - while (c != '' && c != '\n') { - next(); - } - isComment = true; - } - if (c === '/' && nextPreview() === '*') { - // skip block comment - while (c != '') { - if (c === '*' && nextPreview() === '/') { - // end of block comment found. skip these last two characters - next(); - next(); - break; - } else { - next(); + 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() }); } } - isComment = true; } - - // skip over whitespaces - while (c === ' ' || c === '\t' || c === '\n' || c === '\r') { - // space, tab, enter - next(); + // 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; } - } while (isComment); - - // check for end of dot file - if (c === '') { - // token is still empty - tokenType = TOKENTYPE.DELIMITER; - return; - } - - // check for delimiters consisting of 2 characters - var c2 = c + nextPreview(); - if (DELIMITERS[c2]) { - tokenType = TOKENTYPE.DELIMITER; - token = c2; - next(); - next(); - return; - } - - // check for delimiters consisting of 1 character - if (DELIMITERS[c]) { - tokenType = TOKENTYPE.DELIMITER; - token = c; - next(); - return; - } - - // check for an identifier (number or string) - // TODO: more precise parsing of numbers/strings (and the port separator ':') - if (isAlphaNumeric(c) || c === '-') { - token += c; - next(); - - while (isAlphaNumeric(c)) { - token += c; - next(); + if (endHidden.hidden == true) { + rangeEnd = body.range.endToFront == true ? endHidden.startDate - 1 : endHidden.endDate + 1; } - if (token === 'false') { - token = false; // convert to boolean - } else if (token === 'true') { - token = true; // convert to boolean - } else if (!isNaN(Number(token))) { - token = Number(token); // convert to number + if (startHidden.hidden == true || endHidden.hidden == true) { + body.range._applyRange(rangeStart, rangeEnd); } - tokenType = TOKENTYPE.IDENTIFIER; - return; } + }; - // check for a string enclosed by double quotes - if (c === '"') { - next(); - while (c != '' && (c != '"' || c === '"' && nextPreview() === '"')) { - token += c; - if (c === '"') { - // skip the escape character - next(); + /** + * remove duplicates from the hidden dates list. Duplicates are evil. They mess everything up. + * Scales with N^2 + * @param 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; + } } - next(); } - if (c != '"') { - throw newSyntaxError('End of string " expected'); + } + + for (var i = 0; i < hiddenDates.length; i++) { + if (hiddenDates[i].remove !== true) { + safeDates.push(hiddenDates[i]); } - next(); - tokenType = TOKENTYPE.IDENTIFIER; - return; } - // something unknown is found, wrong characters, a syntax error - tokenType = TOKENTYPE.UNKNOWN; - while (c != '') { - token += c; - next(); + 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); } - throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"'); - } + }; /** - * Parse a graph. - * @returns {Object} graph + * Used in TimeStep to avoid the hidden times. + * @param timeStep + * @param previousTime */ - function parseGraph() { - var graph = {}; - - first(); - getToken(); - - // optional strict keyword - if (token === 'strict') { - graph.strict = true; - getToken(); + exports.stepOverHiddenDates = function (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; + } } - // graph or digraph keyword - if (token === 'graph' || token === 'digraph') { - graph.type = token; - getToken(); - } + 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; + } - // optional graph id - if (tokenType === TOKENTYPE.IDENTIFIER) { - graph.id = token; - getToken(); + timeStep.current = newValue.toDate(); } + }; - // open angle bracket - if (token != '{') { - throw newSyntaxError('Angle bracket { expected'); - } - getToken(); + ///** + // * 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(); + // } + //}; - // statements - parseStatements(graph); + /** + * replaces the Core toScreen methods + * @param Core + * @param time + * @param width + * @returns {number} + */ + exports.toScreen = function (Core, time, width) { + if (Core.body.hiddenDates.length == 0) { + var 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; + } - // close angle bracket - if (token != '}') { - throw newSyntaxError('Angle bracket } expected'); - } - getToken(); + var duration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end); + time = exports.correctTimeForHidden(Core.body.hiddenDates, Core.range, time); - // end of file - if (token !== '') { - throw newSyntaxError('End of file expected'); + var conversion = Core.range.conversion(width, duration); + return (time.valueOf() - conversion.offset) * conversion.scale; } - getToken(); + }; - // remove temporary default options - delete graph.node; - delete graph.edge; - delete graph.graph; + /** + * Replaces the core toTime methods + * @param body + * @param range + * @param x + * @param 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 graph; - } + var newTime = new Date(accumulatedHiddenDuration + partialDuration + Core.range.start); + return newTime; + } + }; /** - * Parse a list with statements. - * @param {Object} graph + * Support function + * + * @param hiddenDates + * @param range + * @returns {number} */ - function parseStatements(graph) { - while (token !== '' && token != '}') { - parseStatement(graph); - if (token === ';') { - getToken(); + 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; + }; /** - * Parse a single statement. Can be a an attribute statement, node - * statement, a series of node statements and edge statements, or a - * parameter. - * @param {Object} graph + * Support function + * @param hiddenDates + * @param range + * @param time + * @returns {{duration: number, time: *, offset: number}} */ - function parseStatement(graph) { - // parse subgraph - var subgraph = parseSubgraph(graph); - if (subgraph) { - // edge statements - parseEdge(graph, subgraph); + exports.correctTimeForHidden = function (hiddenDates, range, time) { + time = moment(time).toDate().valueOf(); + time -= exports.getHiddenDurationBefore(hiddenDates, range, time); + return time; + }; - return; - } + exports.getHiddenDurationBefore = function (hiddenDates, range, time) { + var timeOffset = 0; + time = moment(time).toDate().valueOf(); - // parse an attribute statement - var attr = parseAttributeStatement(graph); - if (attr) { - return; + 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; + }; - // parse node - if (tokenType != TOKENTYPE.IDENTIFIER) { - throw newSyntaxError('Identifier expected'); + /** + * sum the duration from start to finish, including the hidden duration, + * until the required amount has been reached, return the accumulated hidden duration + * @param hiddenDates + * @param range + * @param time + * @returns {{duration: number, time: *, offset: 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; + } + } } - var id = token; // id can be a string or a number - getToken(); - if (token === '=') { - // id statement - getToken(); - if (tokenType != TOKENTYPE.IDENTIFIER) { - throw newSyntaxError('Identifier expected'); + return hiddenDuration; + }; + + /** + * used to step over to either side of a hidden block. Correction is disabled on tablets, might be set to true + * @param hiddenDates + * @param time + * @param direction + * @param correctionEnabled + * @returns {*} + */ + 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; + } } - graph[id] = token; - getToken(); - // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] " } else { - parseNodeStatement(graph, id); + return time; } - } + }; /** - * Parse a subgraph - * @param {Object} graph parent graph object - * @return {Object | null} subgraph + * Check if a time is hidden + * + * @param time + * @param hiddenDates + * @returns {{hidden: boolean, startDate: Window.start, endDate: *}} */ - function parseSubgraph(graph) { - var subgraph = null; - - // optional subgraph keyword - if (token === 'subgraph') { - subgraph = {}; - subgraph.type = 'subgraph'; - getToken(); + exports.isHidden = function (time, hiddenDates) { + for (var i = 0; i < hiddenDates.length; i++) { + var startDate = hiddenDates[i].start; + var endDate = hiddenDates[i].end; - // optional graph id - if (tokenType === TOKENTYPE.IDENTIFIER) { - subgraph.id = token; - getToken(); + if (time >= startDate && time < endDate) { + // if the start is entering a hidden zone + return { hidden: true, startDate: startDate, endDate: endDate }; + break; } } + return { hidden: false, startDate: startDate, endDate: endDate }; + }; - // open angle bracket - if (token === '{') { - getToken(); +/***/ }, +/* 32 */ +/***/ function(module, exports, __webpack_require__) { - if (!subgraph) { - subgraph = {}; - } - subgraph.parent = graph; - subgraph.node = graph.node; - subgraph.edge = graph.edge; - subgraph.graph = graph.graph; + 'use strict'; - // statements - parseStatements(subgraph); + var Emitter = __webpack_require__(19); + var Hammer = __webpack_require__(3); + var hammerUtil = __webpack_require__(30); + var util = __webpack_require__(7); + var DataSet = __webpack_require__(14); + var DataView = __webpack_require__(16); + var Range = __webpack_require__(29); + var ItemSet = __webpack_require__(33); + var TimeAxis = __webpack_require__(41); + var Activator = __webpack_require__(42); + var DateUtil = __webpack_require__(31); + var CustomTime = __webpack_require__(44); - // close angle bracket - if (token != '}') { - throw newSyntaxError('Angle bracket } expected'); - } - getToken(); + /** + * Create a timeline visualization + * @constructor + */ + function Core() {} - // remove temporary default options - delete subgraph.node; - delete subgraph.edge; - delete subgraph.graph; - delete subgraph.parent; - - // register at the parent graph - if (!graph.subgraphs) { - graph.subgraphs = []; - } - graph.subgraphs.push(subgraph); - } - - return subgraph; - } + // turn Core into an event emitter + Emitter(Core.prototype); /** - * parse an attribute statement like "node [shape=circle fontSize=16]". - * Available keywords are 'node', 'edge', 'graph'. - * The previous list with default attributes will be replaced - * @param {Object} graph - * @returns {String | null} keyword Returns the name of the parsed attribute - * (node, edge, graph), or null if nothing - * is parsed. + * 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 */ - function parseAttributeStatement(graph) { - // attribute statements - if (token === 'node') { - getToken(); - - // node attributes - graph.node = parseAttributeList(); - return 'node'; - } else if (token === 'edge') { - getToken(); + Core.prototype._create = function (container) { + this.dom = {}; - // edge attributes - graph.edge = parseAttributeList(); - return 'edge'; - } else if (token === 'graph') { - getToken(); + 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'); - // graph attributes - graph.graph = parseAttributeList(); - return 'graph'; - } + 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'; - return null; - } + 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); - /** - * parse a node statement - * @param {Object} graph - * @param {String | Number} id - */ - function parseNodeStatement(graph, id) { - // node statement - var node = { - id: id - }; - var attr = parseAttributeList(); - if (attr) { - node.attr = attr; - } - addNode(graph, node); + this.dom.centerContainer.appendChild(this.dom.center); + this.dom.leftContainer.appendChild(this.dom.left); + this.dom.rightContainer.appendChild(this.dom.right); - // edge statements - parseEdge(graph, id); - } + 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); - /** - * Parse an edge or a series of edges - * @param {Object} graph - * @param {String | Number} from Id of the from node - */ - function parseEdge(graph, from) { - while (token === '->' || token === '--') { - var to; - var type = token; - getToken(); + this.on('rangechange', this.redraw.bind(this)); + this.on('touch', this._onTouch.bind(this)); + this.on('pan', this._onDrag.bind(this)); - var subgraph = parseSubgraph(graph); - if (subgraph) { - to = subgraph; - } else { - if (tokenType != TOKENTYPE.IDENTIFIER) { - throw newSyntaxError('Identifier or subgraph expected'); + var me = this; + this.on('change', function (properties) { + if (properties && properties.queue == true) { + // redraw once on next tick + if (!me._redrawTimer) { + me._redrawTimer = setTimeout(function () { + me._redrawTimer = null; + me._redraw(); + }, 0); } - to = token; - addNode(graph, { - id: to - }); - getToken(); + } else { + // redraw immediately + me._redraw(); } + }); - // parse edge attributes - var attr = parseAttributeList(); + // create event listeners for all interesting events, these events will be + // emitted via emitter + this.hammer = new Hammer(this.dom.root); + this.hammer.get('pinch').set({ enable: true }); + this.listeners = {}; - // create edge - var edge = createEdge(graph, from, to, type, attr); - addEdge(graph, edge); + 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; + }); - from = to; + // 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)); + + function onMouseWheel(event) { + if (me.isActive()) { + me.emit('mousewheel', event); + } } - } + this.dom.root.addEventListener('mousewheel', onMouseWheel); + this.dom.root.addEventListener('DOMMouseScroll', onMouseWheel); + + // 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.customTimes = []; + + // store state information needed for touch events + this.touch = {}; + + this.redrawCount = 0; + + // attach the root panel to the provided container + if (!container) throw new Error('No container provided'); + container.appendChild(this.dom.root); + }; /** - * Parse a set with attributes, - * for example [label="1.000", shape=solid] - * @return {Object | null} attr + * 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 */ - function parseAttributeList() { - var attr = null; + Core.prototype.setOptions = function (options) { + if (options) { + // copy the known options + var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'clickToUse', 'dataAttributes', 'hiddenDates']; + util.selectiveExtend(fields, this.options, options); - while (token === '[') { - getToken(); - attr = {}; - while (token !== '' && token != ']') { - if (tokenType != TOKENTYPE.IDENTIFIER) { - throw newSyntaxError('Attribute name expected'); + if ('orientation' in options) { + if (typeof options.orientation === 'string') { + this.options.orientation = { + item: options.orientation, + axis: options.orientation + }; + } else if (typeof 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; + } } - var name = token; + } - getToken(); - if (token != '=') { - throw newSyntaxError('Equal sign = expected'); + 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); } - getToken(); - - if (tokenType != TOKENTYPE.IDENTIFIER) { - throw newSyntaxError('Attribute value expected'); + } 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; } - var value = token; - setValue(attr, name, value); // name can be a path + } - getToken(); - if (token == ',') { - getToken(); + if ('hiddenDates' in this.options) { + DateUtil.convertHiddenOptions(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 (token != ']') { - throw newSyntaxError('Bracket ] expected'); + if ('showCustomTime' in options) { + throw new Error('Option `showCustomTime` is deprecated. Create a custom time bar via timeline.addCustomTime(time [, id])'); } - getToken(); + + // enable/disable autoResize + this._initAutoResize(); } - return attr; - } + // propagate options to all components + this.components.forEach(function (component) { + return component.setOptions(options); + }); - /** - * Create a syntax error with extra information on current token and index. - * @param {String} message - * @returns {SyntaxError} err - */ - function newSyntaxError(message) { - return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')'); - } + // enable/disable configure + if (this.configurator) { + 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 }); + } + + // redraw everything + this._redraw(); + }; /** - * Chop off text after a maximum length - * @param {String} text - * @param {Number} maxLength - * @returns {String} + * Returns true when the Timeline is active. + * @returns {boolean} */ - function chop(text, maxLength) { - return text.length <= maxLength ? text : text.substr(0, 27) + '...'; - } + Core.prototype.isActive = function () { + return !this.activator || this.activator.active; + }; /** - * Execute a function fn for each pair of elements in two arrays - * @param {Array | *} array1 - * @param {Array | *} array2 - * @param {function} fn + * Destroy the Core, clean up all DOM elements and event listeners. */ - function forEach2(array1, array2, fn) { - if (Array.isArray(array1)) { - array1.forEach(function (elem1) { - if (Array.isArray(array2)) { - array2.forEach(function (elem2) { - fn(elem1, elem2); - }); - } else { - fn(elem1, array2); - } - }); - } else { - if (Array.isArray(array2)) { - array2.forEach(function (elem2) { - fn(array1, elem2); - }); - } else { - fn(array1, array2); - } + 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; - /** - * Set a nested property on an object - * When nested objects are missing, they will be created. - * For example setProp({}, 'font.color', 'red') will return {font: {color: 'red'}} - * @param {Object} object - * @param {string} path A dot separated string like 'font.color' - * @param {*} value Value for the property - * @return {Object} Returns the original object, allows for chaining. - */ - function setProp(object, path, value) { - var names = path.split('.'); - var prop = names.pop(); + // remove Activator + if (this.activator) { + this.activator.destroy(); + delete this.activator; + } - // traverse over the nested objects - var obj = object; - for (var i = 0; i < names.length; i++) { - var name = names[i]; - if (!(name in obj)) { - obj[name] = {}; + // cleanup hammer touch events + for (var event in this.listeners) { + if (this.listeners.hasOwnProperty(event)) { + delete this.listeners[event]; } - obj = obj[name]; } + this.listeners = null; + this.hammer = null; - // set the property value - obj[prop] = value; + // give all components the opportunity to cleanup + this.components.forEach(function (component) { + return component.destroy(); + }); - return object; - } + this.body = null; + }; /** - * Convert an object with DOT attributes to their vis.js equivalents. - * @param {Object} attr Object with DOT attributes - * @param {Object} mapping - * @return {Object} Returns an object with vis.js attributes + * Set a custom time bar + * @param {Date} time + * @param {number} [id=undefined] Optional id of the custom time bar to be adjusted. */ - function convertAttr(attr, mapping) { - var converted = {}; + Core.prototype.setCustomTime = function (time, id) { + var customTimes = this.customTimes.filter(function (component) { + return id === component.options.id; + }); - for (var prop in attr) { - if (attr.hasOwnProperty(prop)) { - var visProp = mapping[prop]; - if (Array.isArray(visProp)) { - visProp.forEach(function (visPropI) { - setProp(converted, visPropI, attr[prop]); - }); - } else if (typeof visProp === 'string') { - setProp(converted, visProp, attr[prop]); - } else { - setProp(converted, prop, attr[prop]); - } - } + if (customTimes.length === 0) { + throw new Error('No custom time bar found with id ' + JSON.stringify(id)); } - return converted; - } + if (customTimes.length > 0) { + customTimes[0].setCustomTime(time); + } + }; /** - * Convert a string containing a graph in DOT language into a map containing - * with nodes and edges in the format of graph. - * @param {String} data Text containing a graph in DOT-notation - * @return {Object} graphData + * Retrieve the current custom time. + * @param {number} [id=undefined] Id of the custom time bar. + * @return {Date | undefined} customTime */ - function DOTToGraph(data) { - // parse the DOT file - var dotData = parseDOT(data); - var graphData = { - nodes: [], - edges: [], - options: {} - }; + Core.prototype.getCustomTime = function (id) { + var customTimes = this.customTimes.filter(function (component) { + return component.options.id === id; + }); - // copy the nodes - if (dotData.nodes) { - dotData.nodes.forEach(function (dotNode) { - var graphNode = { - id: dotNode.id, - label: String(dotNode.label || dotNode.id) - }; - merge(graphNode, convertAttr(dotNode.attr, NODE_ATTR_MAPPING)); - if (graphNode.image) { - graphNode.shape = 'image'; - } - graphData.nodes.push(graphNode); - }); + if (customTimes.length === 0) { + throw new Error('No custom time bar found with id ' + JSON.stringify(id)); } + return customTimes[0].getCustomTime(); + }; - // copy the edges - if (dotData.edges) { - /** - * Convert an edge in DOT format to an edge with VisGraph format - * @param {Object} dotEdge - * @returns {Object} graphEdge - */ - var convertEdge = function convertEdge(dotEdge) { - var graphEdge = { - from: dotEdge.from, - to: dotEdge.to - }; - merge(graphEdge, convertAttr(dotEdge.attr, EDGE_ATTR_MAPPING)); - graphEdge.arrows = dotEdge.type === '->' ? 'to' : undefined; - - return graphEdge; - }; + /** + * 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(); - dotData.edges.forEach(function (dotEdge) { - var from, to; - if (dotEdge.from instanceof Object) { - from = dotEdge.from.nodes; - } else { - from = { - id: dotEdge.from - }; - } + var exists = this.customTimes.some(function (customTime) { + return customTime.options.id === id; + }); + if (exists) { + throw new Error('A custom time with id ' + JSON.stringify(id) + ' already exists'); + } - // TODO: support of solid/dotted/dashed edges (attr = 'style') - // TODO: support for attributes 'dir' and 'arrowhead' (edge arrows) + var customTime = new CustomTime(this.body, { + time: timestamp, + id: id + }); - if (dotEdge.to instanceof Object) { - to = dotEdge.to.nodes; - } else { - to = { - id: dotEdge.to - }; - } + this.customTimes.push(customTime); + this.components.push(customTime); + this.redraw(); - if (dotEdge.from instanceof Object && dotEdge.from.edges) { - dotEdge.from.edges.forEach(function (subEdge) { - var graphEdge = convertEdge(subEdge); - graphData.edges.push(graphEdge); - }); - } + return id; + }; - forEach2(from, to, function (from, to) { - var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr); - var graphEdge = convertEdge(subEdge); - graphData.edges.push(graphEdge); - }); + /** + * Remove previously added custom bar + * @param {int} id ID of the custom bar to be removed + * @return {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 (dotEdge.to instanceof Object && dotEdge.to.edges) { - dotEdge.to.edges.forEach(function (subEdge) { - var graphEdge = convertEdge(subEdge); - graphData.edges.push(graphEdge); - }); - } - }); + if (customTimes.length === 0) { + throw new Error('No custom time bar found with id ' + JSON.stringify(id)); } - // copy the options - if (dotData.attr) { - graphData.options = dotData.attr; - } + customTimes.forEach((function (customTime) { + this.customTimes.splice(this.customTimes.indexOf(customTime), 1); + this.components.splice(this.components.indexOf(customTime), 1); + customTime.destroy(); + }).bind(this)); + }; - return graphData; - } + /** + * 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() || []; + }; - // exports - exports.parseDOT = parseDOT; - exports.DOTToGraph = DOTToGraph; + /** + * 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'. + */ + Core.prototype.fit = function (options) { + var range = this._getDataRange(); -/***/ }, -/* 39 */ -/***/ function(module, exports, __webpack_require__) { + // skip range set if there is no start and end date + if (range.start === null && range.end === null) { + return; + } - 'use strict'; + var animation = options && options.animation !== undefined ? options.animation : true; + this.range.setRange(range.start, range.end, animation); + }; - function parseGephi(gephiJSON, optionsObj) { - var edges = []; - var nodes = []; - var options = { - edges: { - inheritColor: false - }, - nodes: { - fixed: false, - parseColor: false - } - }; + /** + * Calculate the data range of the items and applies a 5% window around it. + * @returns {{start: Date | null, end: Date | null}} + * @protected + */ + Core.prototype._getDataRange = function () { + // apply the data range as range + var dataRange = this.getItemRange(); - if (optionsObj !== undefined) { - if (optionsObj.fixed !== undefined) { - options.nodes.fixed = optionsObj.fixed; - } - if (optionsObj.parseColor !== undefined) { - options.nodes.parseColor = optionsObj.parseColor; - } - if (optionsObj.inheritColor !== undefined) { - options.edges.inheritColor = optionsObj.inheritColor; + // add 5% space on both sides + var start = dataRange.min; + var end = dataRange.max; + if (start != null && end != null) { + var interval = end.valueOf() - start.valueOf(); + if (interval <= 0) { + // prevent an empty interval + interval = 24 * 60 * 60 * 1000; // 1 day } + start = new Date(start.valueOf() - interval * 0.05); + end = new Date(end.valueOf() + interval * 0.05); } - var gEdges = gephiJSON.edges; - var gNodes = gephiJSON.nodes; - for (var i = 0; i < gEdges.length; i++) { - var edge = {}; - var gEdge = gEdges[i]; - edge['id'] = gEdge.id; - edge['from'] = gEdge.source; - edge['to'] = gEdge.target; - edge['attributes'] = gEdge.attributes; - // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined; - // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size; - if (gEdge.color && options.inheritColor === false) { - edge['color'] = gEdge.color; - } - edges.push(edge); - } + return { + start: start, + end: end + }; + }; - for (var i = 0; i < gNodes.length; i++) { - var node = {}; - var gNode = gNodes[i]; - node['id'] = gNode.id; - node['attributes'] = gNode.attributes; - node['title'] = gNode.title; - node['x'] = gNode.x; - node['y'] = gNode.y; - node['label'] = gNode.label; - if (options.nodes.parseColor === true) { - node['color'] = gNode.color; - } else { - node['color'] = gNode.color !== undefined ? { background: gNode.color, border: gNode.color, highlight: { background: gNode.color, border: gNode.color }, hover: { background: gNode.color, border: gNode.color } } : undefined; - } - node['size'] = gNode.size; - node['fixed'] = options.nodes.fixed && gNode.x !== undefined && gNode.y !== undefined; - nodes.push(node); + /** + * 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'. + */ + Core.prototype.setWindow = function (start, end, options) { + var animation; + if (arguments.length == 1) { + var range = arguments[0]; + animation = range.animation !== undefined ? range.animation : true; + this.range.setRange(range.start, range.end, animation); + } else { + animation = options && options.animation !== undefined ? options.animation : true; + this.range.setRange(start, end, animation); } + }; - return { nodes: nodes, edges: edges }; - } + /** + * 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'. + */ + Core.prototype.moveTo = function (time, options) { + var interval = this.range.end - this.range.start; + var t = util.convert(time, 'Date').valueOf(); - exports.parseGephi = parseGephi; + var start = t - interval / 2; + var end = t + interval / 2; + var animation = options && options.animation !== undefined ? options.animation : true; -/***/ }, -/* 40 */ -/***/ function(module, exports, __webpack_require__) { + this.range.setRange(start, end, animation); + }; - // first check if moment.js is already loaded in the browser window, if so, - // use this instance. Else, load via commonjs. - 'use strict'; + /** + * 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) + }; + }; - module.exports = typeof window !== 'undefined' && window['moment'] || __webpack_require__(70); + /** + * Force a redraw. Can be overridden by implementations of Core + */ + Core.prototype.redraw = function () { + this._redraw(); + }; -/***/ }, -/* 41 */ -/***/ function(module, exports, __webpack_require__) { + /** + * Redraw for internal use. Redraws all components. See also the public + * method redraw. + * @protected + */ + Core.prototype._redraw = function () { + var resized = false; + var options = this.options; + var props = this.props; + var dom = this.dom; - // Only load hammer.js when in a browser environment - // (loading hammer.js in a node.js environment gives errors) - 'use strict'; + if (!dom) return; // when destroyed - if (typeof window !== 'undefined') { - var propagating = __webpack_require__(71); - var Hammer = window['Hammer'] || __webpack_require__(72); - module.exports = propagating(Hammer, { - preventDefault: 'mouse' - }); - } else { - module.exports = function () { - throw Error('hammer.js is only available in a browser, not in node.js.'); - }; - } + DateUtil.updateHiddenDates(this.body, this.options.hiddenDates); -/***/ }, -/* 42 */ -/***/ function(module, exports, __webpack_require__) { + // 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'); + } - /* WEBPACK VAR INJECTION */(function(global) {'use strict'; + // 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, ''); - var _rng; + // 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; + var borderRootHeight = dom.root.offsetHeight - dom.root.clientHeight; + var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth; - var globalVar = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : null; + // 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) { + borderRootWidth = borderRootHeight; + } - if (globalVar && globalVar.crypto && crypto.getRandomValues) { - // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto - // Moderately fast, high quality - var _rnds8 = new Uint8Array(16); - _rng = function whatwgRNG() { - crypto.getRandomValues(_rnds8); - return _rnds8; - }; - } + // 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; - if (!_rng) { - // Math.random()-based (RNG) - // - // If all else fails, use Math.random(). It's fast, but is of unspecified - // quality. - var _rnds = new Array(16); - _rng = function () { - for (var i = 0, r; i < 16; i++) { - if ((i & 3) === 0) r = Math.random() * 4294967296; - _rnds[i] = r >>> ((i & 3) << 3) & 255; - } + // TODO: compensate borders when any of the panels is empty. - return _rnds; - }; - } + // 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 + borderRootHeight + props.border.top + props.border.bottom; + dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px'); - // uuid.js - // - // Copyright (c) 2010-2012 Robert Kieffer - // MIT License - http://opensource.org/licenses/mit-license.php + // calculate heights of the content panels + props.root.height = dom.root.offsetHeight; + props.background.height = props.root.height - borderRootHeight; + var containerHeight = props.root.height - props.top.height - props.bottom.height - borderRootHeight; + props.centerContainer.height = containerHeight; + props.leftContainer.height = containerHeight; + props.rightContainer.height = props.leftContainer.height; - // Unique ID creation requires a high quality random # generator. We feature - // detect to determine the best RNG source, normalizing to a function that - // returns 128-bits of randomness, since that's what's usually required + // calculate the widths of the panels + props.root.width = dom.root.offsetWidth; + props.background.width = props.root.width - borderRootWidth; + props.left.width = dom.leftContainer.clientWidth || -props.border.left; + props.leftContainer.width = props.left.width; + props.right.width = dom.rightContainer.clientWidth || -props.border.right; + props.rightContainer.width = props.right.width; + var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth; + props.center.width = centerWidth; + props.centerContainer.width = centerWidth; + props.top.width = centerWidth; + props.bottom.width = centerWidth; - //var _rng = require('./rng'); + // 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'; - // Maps for number <-> hex string conversion - var _byteToHex = []; - var _hexToByte = {}; - for (var i = 0; i < 256; i++) { - _byteToHex[i] = (i + 256).toString(16).substr(1); - _hexToByte[_byteToHex[i]] = i; - } + 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'; - // **`parse()` - Parse a UUID into it's component bytes** - function parse(s, buf, offset) { - var i = buf && offset || 0, - ii = 0; + // 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'; - buf = buf || []; - s.toLowerCase().replace(/[0-9a-f]{2}/g, function (oct) { - if (ii < 16) { - // Don't overflow! - buf[i + ii++] = _hexToByte[oct]; - } - }); + // 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 + this._updateScrollTop(); - // Zero out remaining bytes if string was short - while (ii < 16) { - buf[i + ii++] = 0; + // reposition the scrollable contents + var offset = this.props.scrollTop; + if (options.orientation.item != 'top') { + offset += Math.max(this.props.centerContainer.height - this.props.center.height - this.props.border.top - this.props.border.bottom, 0); } + dom.center.style.left = '0'; + dom.center.style.top = offset + 'px'; + dom.left.style.left = '0'; + dom.left.style.top = offset + 'px'; + dom.right.style.left = '0'; + dom.right.style.top = offset + 'px'; - return buf; - } - - // **`unparse()` - Convert UUID byte array (ala parse()) into a string** - function unparse(buf, offset) { - var i = offset || 0, - bth = _byteToHex; - return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]]; - } + // show shadows when vertical scrolling is available + var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : ''; + var visibilityBottom = this.props.scrollTop == this.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; - // **`v1()` - Generate time-based UUID** - // - // Inspired by https://github.com/LiosK/UUID.js - // and http://docs.python.org/library/uuid.html - - // random #'s we need to init node and clockseq - var _seedBytes = _rng(); - - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - var _nodeId = [_seedBytes[0] | 1, _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]]; - - // Per 4.2.2, randomize (14 bit) clockseq - var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 16383; - - // Previous uuid creation time - var _lastMSecs = 0, - _lastNSecs = 0; - - // See https://github.com/broofa/node-uuid for API details - function v1(options, buf, offset) { - var i = buf && offset || 0; - var b = buf || []; - - options = options || {}; - - var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; - - // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); - - // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - - // Time since last uuid creation (in msecs) - var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; - - // Per 4.2.1.2, Bump clockseq on clock regression - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 16383; + // redraw all components + this.components.forEach(function (component) { + resized = component.redraw() || resized; + }); + if (resized) { + // keep repainting until all sizes are settled + var MAX_REDRAWS = 3; // maximum number of consecutive redraws + if (this.redrawCount < MAX_REDRAWS) { + this.redrawCount++; + this._redraw(); + } else { + console.log('WARNING: infinite loop in redraw?'); + } + this.redrawCount = 0; } + }; - // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 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.'); + }; - // Per 4.2.1.2 Throw error if too many uuids are requested - if (nsecs >= 10000) { - throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + /** + * 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'); } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; - - // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000; - - // `time_low` - var tl = ((msecs & 268435455) * 10000 + nsecs) % 4294967296; - b[i++] = tl >>> 24 & 255; - b[i++] = tl >>> 16 & 255; - b[i++] = tl >>> 8 & 255; - b[i++] = tl & 255; - - // `time_mid` - var tmh = msecs / 4294967296 * 10000 & 268435455; - b[i++] = tmh >>> 8 & 255; - b[i++] = tmh & 255; - - // `time_high_and_version` - b[i++] = tmh >>> 24 & 15 | 16; // include version - b[i++] = tmh >>> 16 & 255; + this.currentTime.setCurrentTime(time); + }; - // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - b[i++] = clockseq >>> 8 | 128; + /** + * 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'); + } - // `clock_seq_low` - b[i++] = clockseq & 255; + return this.currentTime.getCurrentTime(); + }; - // `node` - var node = options.node || _nodeId; - for (var n = 0; n < 6; n++) { - b[i + n] = node[n]; - } + /** + * 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); + }; - return buf ? buf : unparse(b); - } + /** + * 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); + }; - // **`v4()` - Generate random UUID** + /** + * 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); + }; - // See https://github.com/broofa/node-uuid for API details - function v4(options, buf, offset) { - // Deprecated - 'format' argument, as supported in v1.2 - var i = buf && offset || 0; + /** + * 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; + }; - if (typeof options == 'string') { - buf = options == 'binary' ? new Array(16) : null; - options = null; + /** + * Initialize watching when option autoResize is true + * @private + */ + Core.prototype._initAutoResize = function () { + if (this.options.autoResize == true) { + this._startAutoResize(); + } else { + this._stopAutoResize(); } - options = options || {}; + }; - var rnds = options.random || (options.rng || _rng)(); + /** + * 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; - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = rnds[6] & 15 | 64; - rnds[8] = rnds[8] & 63 | 128; + this._stopAutoResize(); - // Copy bytes to buffer, if provided - if (buf) { - for (var ii = 0; ii < 16; ii++) { - buf[i + ii] = rnds[ii]; + this._onResize = function () { + if (me.options.autoResize != true) { + // stop watching when the option autoResize is changed to false + me._stopAutoResize(); + return; } - } - - return buf || unparse(rnds); - } - - // Export public API - var uuid = v4; - uuid.v1 = v1; - uuid.v4 = v4; - uuid.parse = parse; - uuid.unparse = unparse; - module.exports = uuid; - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + 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; -/***/ }, -/* 43 */ -/***/ function(module, exports, __webpack_require__) { + me.emit('change'); + } + } + }; - - /** - * Expose `Emitter`. - */ + // add event listener to window resize + util.addEventListener(window, 'resize', this._onResize); - module.exports = Emitter; + this.watchTimer = setInterval(this._onResize, 1000); + }; /** - * Initialize a new `Emitter`. - * - * @api public + * Stop watching for a resize of the frame. + * @private */ + Core.prototype._stopAutoResize = function () { + if (this.watchTimer) { + clearInterval(this.watchTimer); + this.watchTimer = undefined; + } - function Emitter(obj) { - if (obj) return mixin(obj); + // remove event listener on window.resize + util.removeEventListener(window, 'resize', this._onResize); + this._onResize = null; }; /** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private + * Start moving the timeline vertically + * @param {Event} event + * @private */ - - function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - return obj; - } + Core.prototype._onTouch = function (event) { + this.touch.allowDragging = true; + this.touch.initialScrollTop = this.props.scrollTop; + }; /** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public + * Start moving the timeline vertically + * @param {Event} event + * @private */ - - Emitter.prototype.on = - Emitter.prototype.addEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - (this._callbacks[event] = this._callbacks[event] || []) - .push(fn); - return this; + Core.prototype._onPinch = function (event) { + this.touch.allowDragging = false; }; /** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public + * Move the timeline vertically + * @param {Event} event + * @private */ + Core.prototype._onDrag = function (event) { + // 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; - Emitter.prototype.once = function(event, fn){ - var self = this; - this._callbacks = this._callbacks || {}; + var delta = event.deltaY; - function on() { - self.off(event, on); - fn.apply(this, arguments); - } + var oldScrollTop = this._getScrollTop(); + var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta); - on.fn = fn; - this.on(event, on); - return this; + if (newScrollTop != oldScrollTop) { + this._redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already + this.emit('verticalDrag'); + } }; /** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public + * Apply a scrollTop + * @param {Number} scrollTop + * @returns {Number} scrollTop Returns the applied scrollTop + * @private */ - - 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; + Core.prototype._setScrollTop = function (scrollTop) { + this.props.scrollTop = scrollTop; + this._updateScrollTop(); + return this.props.scrollTop; }; /** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} + * Update the current scrollTop when the height of the containers has been changed + * @returns {Number} scrollTop Returns the applied scrollTop + * @private */ - - 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); + 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; } - return this; - }; - - /** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ + // 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; - Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks[event] || []; + return this.props.scrollTop; }; /** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public + * Get the current scrollTop + * @returns {number} scrollTop + * @private */ - - Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; + Core.prototype._getScrollTop = function () { + return this.props.scrollTop; }; + module.exports = Core; /***/ }, -/* 44 */ +/* 33 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Emitter = __webpack_require__(43); - var Hammer = __webpack_require__(41); - var hammerUtil = __webpack_require__(49); - var util = __webpack_require__(2); - var DataSet = __webpack_require__(4); - var DataView = __webpack_require__(5); - var Range = __webpack_require__(18); - var ItemSet = __webpack_require__(32); - var TimeAxis = __webpack_require__(35); - var Activator = __webpack_require__(68); - var DateUtil = __webpack_require__(16); - var CustomTime = __webpack_require__(27); - - /** - * Create a timeline visualization - * @constructor - */ - function Core() {} + var Hammer = __webpack_require__(3); + var util = __webpack_require__(7); + var DataSet = __webpack_require__(14); + var DataView = __webpack_require__(16); + var TimeStep = __webpack_require__(37); + var Component = __webpack_require__(27); + var Group = __webpack_require__(34); + var BackgroundGroup = __webpack_require__(38); + var BoxItem = __webpack_require__(1); + var PointItem = __webpack_require__(39); + var RangeItem = __webpack_require__(36); + var BackgroundItem = __webpack_require__(40); - // turn Core into an event emitter - Emitter(Core.prototype); + var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items + var BACKGROUND = '__background__'; // reserved group id for background items without group /** - * 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 + * 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 */ - Core.prototype._create = function (container) { - this.dom = {}; + function ItemSet(body, options) { + this.body = body; - 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.defaultOptions = { + type: null, // 'box', 'point', 'range', 'background' + orientation: { + item: 'bottom' // item orientation: 'top' or 'bottom' + }, + align: 'auto', // alignment of box items + stack: true, + groupOrder: null, - 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'; + selectable: true, + multiselect: false, - 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.centerContainer.appendChild(this.dom.center); - this.dom.leftContainer.appendChild(this.dom.left); - this.dom.rightContainer.appendChild(this.dom.right); + editable: { + updateTime: false, + updateGroup: false, + add: false, + remove: false + }, - 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); + snap: TimeStep.snap, - this.on('rangechange', this.redraw.bind(this)); - this.on('touch', this._onTouch.bind(this)); - this.on('pan', this._onDrag.bind(this)); + 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); + }, - var me = this; - this.on('change', function (properties) { - if (properties && properties.queue == true) { - // redraw once on next tick - if (!me._redrawTimer) { - me._redrawTimer = setTimeout(function () { - me._redrawTimer = null; - me._redraw(); - }, 0); - } - } else { - // redraw immediately - me._redraw(); + margin: { + item: { + horizontal: 10, + vertical: 10 + }, + axis: 20 } - }); + }; - // create event listeners for all interesting events, these events will be - // emitted via emitter - this.hammer = new Hammer(this.dom.root); - this.hammer.get('pinch').set({ enable: true }); - this.listeners = {}; + // options is shared by this ItemSet and all its items + this.options = util.extend({}, this.defaultOptions); - 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; - }); + // options for getting items from the DataSet with the correct type + this.itemOptions = { + type: { start: 'Date', end: 'Date' } + }; - // 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)); + this.conversion = { + toScreen: body.util.toScreen, + toTime: body.util.toTime + }; + this.dom = {}; + this.props = {}; + this.hammer = null; - // emulate a release event (emitted after a pan, pinch, tap, or press) - hammerUtil.onRelease(this.hammer, (function (event) { - me.emit('release', event); - }).bind(this)); + var me = this; + this.itemsData = null; // DataSet + this.groupsData = null; // DataSet - function onMouseWheel(event) { - if (me.isActive()) { - me.emit('mousewheel', event); + // listeners for the DataSet of the items + this.itemListeners = { + 'add': function add(event, params, senderId) { + me._onAdd(params.items); + }, + 'update': function update(event, params, senderId) { + me._onUpdate(params.items); + }, + 'remove': function remove(event, params, senderId) { + me._onRemove(params.items); } - } - this.dom.root.addEventListener('mousewheel', onMouseWheel); - this.dom.root.addEventListener('DOMMouseScroll', onMouseWheel); + }; - // size properties of each of the panels - this.props = { - root: {}, - background: {}, - centerContainer: {}, - leftContainer: {}, - rightContainer: {}, - center: {}, - left: {}, - right: {}, - top: {}, - bottom: {}, - border: {}, - scrollTop: 0, - scrollTopMin: 0 + // listeners for the DataSet of the groups + this.groupListeners = { + 'add': function add(event, params, senderId) { + me._onAddGroups(params.items); + }, + 'update': function update(event, params, senderId) { + me._onUpdateGroups(params.items); + }, + 'remove': function remove(event, params, senderId) { + me._onRemoveGroups(params.items); + } }; - this.customTimes = []; + this.items = {}; // object with an Item for every data item + this.groups = {}; // Group object for every group + this.groupIds = []; - // store state information needed for touch events - this.touch = {}; + this.selection = []; // list with the ids of all selected nodes + this.stackDirty = true; // if true, all items will be restacked on next redraw - this.redrawCount = 0; + this.touchParams = {}; // stores properties while dragging + // create the HTML DOM - // attach the root panel to the provided container - if (!container) throw new Error('No container provided'); - container.appendChild(this.dom.root); + 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 }; /** - * 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 + * Create the HTML DOM for the ItemSet */ - Core.prototype.setOptions = function (options) { + 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)); + + // 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)); + + // 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 the known options - var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'clickToUse', 'dataAttributes', 'hiddenDates']; + // copy all options that we know + var fields = ['type', 'align', 'order', 'stack', 'selectable', 'multiselect', 'groupOrder', 'dataAttributes', 'template', 'hide', 'snap']; util.selectiveExtend(fields, this.options, options); if ('orientation' in options) { if (typeof options.orientation === 'string') { - this.options.orientation = { - item: options.orientation, - axis: options.orientation - }; - } else if (typeof 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; - } + this.options.orientation.item = options.orientation === 'top' ? 'top' : 'bottom'; + } else if (typeof options.orientation === 'object' && 'item' in options.orientation) { + this.options.orientation.item = options.orientation.item; } } - 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); + 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 (typeof 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 (typeof options.margin.item === 'object') { + util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item); + } } - this.timeAxis2.destroy(); - this.timeAxis2 = null; } } - if ('hiddenDates' in this.options) { - DateUtil.convertHiddenOptions(this.body, this.options.hiddenDates); + 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; + } else if (typeof options.editable === 'object') { + util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable); + } } - 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; + // 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; } - } - - 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 (this.configurator) { - this.configurator.setOptions(options.configure); + }).bind(this); + ['onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving'].forEach(addCallback); - // 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 }); + // force the itemSet to refresh: options like orientation and margins may be changed + this.markDirty(); } - - // redraw everything - this._redraw(); }; /** - * Returns true when the Timeline is active. - * @returns {boolean} + * 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] */ - Core.prototype.isActive = function () { - return !this.activator || this.activator.active; + ItemSet.prototype.markDirty = function (options) { + this.groupIds = []; + this.stackDirty = true; + + if (options && options.refreshItems) { + util.forEach(this.items, function (item) { + item.dirty = true; + if (item.displayed) item.redraw(); + }); + } }; /** - * Destroy the Core, clean up all DOM elements and event listeners. + * Destroy the ItemSet */ - Core.prototype.destroy = function () { - // unbind datasets + ItemSet.prototype.destroy = function () { + this.hide(); this.setItems(null); this.setGroups(null); - // remove all event listeners - this.off(); + this.hammer = null; - // stop checking for changed size - this._stopAutoResize(); + this.body = null; + this.conversion = null; + }; - // remove from DOM - if (this.dom.root.parentNode) { - this.dom.root.parentNode.removeChild(this.dom.root); + /** + * 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); } - this.dom = null; - // remove Activator - if (this.activator) { - this.activator.destroy(); - delete this.activator; + // remove the axis with dots + if (this.dom.axis.parentNode) { + this.dom.axis.parentNode.removeChild(this.dom.axis); } - // cleanup hammer touch events - for (var event in this.listeners) { - if (this.listeners.hasOwnProperty(event)) { - delete this.listeners[event]; - } + // remove the labelset containing all group labels + if (this.dom.labelSet.parentNode) { + this.dom.labelSet.parentNode.removeChild(this.dom.labelSet); } - 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. + * Show the component in the DOM (when not already visible). + * @return {Boolean} changed */ - Core.prototype.setCustomTime = function (time, id) { - var customTimes = this.customTimes.filter(function (component) { - return id === component.options.id; - }); + ItemSet.prototype.show = function () { + // show frame containing the items + if (!this.dom.frame.parentNode) { + this.body.dom.center.appendChild(this.dom.frame); + } - if (customTimes.length === 0) { - throw new Error('No custom time bar found with id ' + JSON.stringify(id)); + // show axis with dots + if (!this.dom.axis.parentNode) { + this.body.dom.backgroundVertical.appendChild(this.dom.axis); } - if (customTimes.length > 0) { - customTimes[0].setCustomTime(time); + // show labelset containing labels + if (!this.dom.labelSet.parentNode) { + this.body.dom.left.appendChild(this.dom.labelSet); } }; /** - * Retrieve the current custom time. - * @param {number} [id=undefined] Id of the custom time bar. - * @return {Date | undefined} customTime + * 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. */ - Core.prototype.getCustomTime = function (id) { - var customTimes = this.customTimes.filter(function (component) { - return component.options.id === id; - }); + ItemSet.prototype.setSelection = function (ids) { + var i, ii, id, item; - if (customTimes.length === 0) { - throw new Error('No custom time bar found with id ' + JSON.stringify(id)); + 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(); + } } - return customTimes[0].getCustomTime(); }; /** - * 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 + * Get the selected items by their id + * @return {Array} ids The ids of the selected items */ - Core.prototype.addCustomTime = function (time, id) { - var timestamp = time !== undefined ? util.convert(time, 'Date').valueOf() : new Date(); + ItemSet.prototype.getSelection = function () { + return this.selection.concat([]); + }; - var exists = this.customTimes.some(function (customTime) { - return customTime.options.id === id; - }); - if (exists) { - throw new Error('A custom time with id ' + JSON.stringify(id) + ' already exists'); - } + /** + * 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 left = this.body.util.toScreen(range.start); + var right = this.body.util.toScreen(range.end); - var customTime = new CustomTime(this.body, { - time: timestamp, - id: id - }); + var ids = []; + for (var groupId in this.groups) { + if (this.groups.hasOwnProperty(groupId)) { + var group = this.groups[groupId]; + var rawVisibleItems = group.visibleItems; - this.customTimes.push(customTime); - this.components.push(customTime); - this.redraw(); + // 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 (item.left < right && item.left + item.width > left) { + ids.push(item.id); + } + } + } + } - return id; + return ids; }; /** - * Remove previously added custom bar - * @param {int} id ID of the custom bar to be removed - * @return {boolean} True if the bar exists and is removed, false otherwise + * Deselect a selected item + * @param {String | Number} id + * @private */ - 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 ' + JSON.stringify(id)); + 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; + } } - - 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 + * Repaint the component + * @return {boolean} Returns true if the component is resized */ - Core.prototype.getVisibleItems = function () { - return this.itemSet && this.itemSet.getVisibleItems() || []; + 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, + editable = options.editable.updateTime || options.editable.updateGroup; + + // recalculate absolute position (before redrawing groups) + this.props.top = this.body.domProps.top.height + this.body.domProps.border.top; + this.props.left = this.body.domProps.left.width + this.body.domProps.border.left; + + // update class name + frame.className = 'vis-itemset' + (editable ? ' vis-editable' : ''); + + // 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; + if (zoomed) this.stackDirty = true; + this.lastVisibleInterval = visibleInterval; + this.props.lastWidth = this.props.width; + + var restack = this.stackDirty; + 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, restack); + + // redraw all regular groups + util.forEach(this.groups, function (group) { + var groupMargin = group == firstGroup ? firstMargin : nonFirstMargin; + var groupResized = group.redraw(range, groupMargin, restack); + resized = groupResized || resized; + height += group.height; + }); + height = Math.max(height, minHeight); + this.stackDirty = false; + + // 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); + this.dom.axis.style.left = '0'; + + // check if this component is resized + resized = this._isResized() || resized; + + return resized; }; /** - * 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'. + * Get the first group, aligned with the axis + * @return {Group | null} firstGroup + * @private */ - Core.prototype.fit = function (options) { - var range = this._getDataRange(); - - // skip range set if there is no start and end date - if (range.start === null && range.end === null) { - return; - } + 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]; - var animation = options && options.animation !== undefined ? options.animation : true; - this.range.setRange(range.start, range.end, animation); + return firstGroup || null; }; /** - * Calculate the data range of the items and applies a 5% window around it. - * @returns {{start: Date | null, end: Date | null}} + * Create or delete the group holding all ungrouped items. This group is used when + * there are no groups specified. * @protected */ - Core.prototype._getDataRange = function () { - // apply the data range as range - var dataRange = this.getItemRange(); + ItemSet.prototype._updateUngrouped = function () { + var ungrouped = this.groups[UNGROUPED]; + var background = this.groups[BACKGROUND]; + var item, itemId; - // add 5% space on both sides - var start = dataRange.min; - var end = dataRange.max; - if (start != null && end != null) { - var interval = end.valueOf() - start.valueOf(); - if (interval <= 0) { - // prevent an empty interval - interval = 24 * 60 * 60 * 1000; // 1 day + 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(); + } + } } - start = new Date(start.valueOf() - interval * 0.05); - end = new Date(end.valueOf() + interval * 0.05); - } + } 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; - return { - start: start, - end: end - }; + for (itemId in this.items) { + if (this.items.hasOwnProperty(itemId)) { + item = this.items[itemId]; + ungrouped.add(item); + } + } + + ungrouped.show(); + } + } }; /** - * 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'. + * Get the element for the labelset + * @return {HTMLElement} labelSet */ - Core.prototype.setWindow = function (start, end, options) { - var animation; - if (arguments.length == 1) { - var range = arguments[0]; - animation = range.animation !== undefined ? range.animation : true; - this.range.setRange(range.start, range.end, animation); - } else { - animation = options && options.animation !== undefined ? options.animation : true; - this.range.setRange(start, end, animation); - } + ItemSet.prototype.getLabelSet = function () { + return this.dom.labelSet; }; /** - * 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'. + * Set items + * @param {vis.DataSet | null} items */ - Core.prototype.moveTo = function (time, options) { - var interval = this.range.end - this.range.start; - var t = util.convert(time, 'Date').valueOf(); + ItemSet.prototype.setItems = function (items) { + var me = this, + ids, + oldItemsData = this.itemsData; - var start = t - interval / 2; - var end = t + interval / 2; - var animation = options && options.animation !== undefined ? options.animation : true; + // 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'); + } - this.range.setRange(start, end, animation); - }; + if (oldItemsData) { + // unsubscribe from old dataset + util.forEach(this.itemListeners, function (callback, event) { + oldItemsData.off(event, 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) - }; + // 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(); + } }; /** - * Force a redraw. Can be overridden by implementations of Core + * Get the current items + * @returns {vis.DataSet | null} */ - Core.prototype.redraw = function () { - this._redraw(); + ItemSet.prototype.getItems = function () { + return this.itemsData; }; /** - * Redraw for internal use. Redraws all components. See also the public - * method redraw. - * @protected + * Set groups + * @param {vis.DataSet} groups */ - Core.prototype._redraw = function () { - var resized = false; - var options = this.options; - var props = this.props; - var dom = this.dom; + ItemSet.prototype.setGroups = function (groups) { + var me = this, + ids; - if (!dom) return; // when destroyed + // unsubscribe from current dataset + if (this.groupsData) { + util.forEach(this.groupListeners, function (callback, event) { + me.groupsData.off(event, callback); + }); - DateUtil.updateHiddenDates(this.body, this.options.hiddenDates); + // remove all drawn groups + ids = this.groupsData.getIds(); + this.groupsData = null; + this._onRemoveGroups(ids); // note: this will cause a redraw + } - // update class names - if (options.orientation == 'top') { - util.addClassName(dom.root, 'vis-top'); - util.removeClassName(dom.root, 'vis-bottom'); + // replace the dataset + if (!groups) { + this.groupsData = null; + } else if (groups instanceof DataSet || groups instanceof DataView) { + this.groupsData = groups; } else { - util.removeClassName(dom.root, 'vis-top'); - util.addClassName(dom.root, 'vis-bottom'); + throw new TypeError('Data must be an instance of DataSet or DataView'); } - // 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; - var borderRootHeight = dom.root.offsetHeight - dom.root.clientHeight; - var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth; + if (this.groupsData) { + // subscribe to new dataset + var id = this.id; + util.forEach(this.groupListeners, function (callback, event) { + me.groupsData.on(event, callback, id); + }); - // 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) { - borderRootWidth = borderRootHeight; + // draw all ms + ids = this.groupsData.getIds(); + this._onAddGroups(ids); } - // 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. + // update the group holding all ungrouped items + this._updateUngrouped(); - // 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 + borderRootHeight + props.border.top + props.border.bottom; - dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px'); + // update the order of all items in each group + this._order(); - // calculate heights of the content panels - props.root.height = dom.root.offsetHeight; - props.background.height = props.root.height - borderRootHeight; - var containerHeight = props.root.height - props.top.height - props.bottom.height - borderRootHeight; - props.centerContainer.height = containerHeight; - props.leftContainer.height = containerHeight; - props.rightContainer.height = props.leftContainer.height; + this.body.emitter.emit('change', { queue: true }); + }; - // calculate the widths of the panels - props.root.width = dom.root.offsetWidth; - props.background.width = props.root.width - borderRootWidth; - props.left.width = dom.leftContainer.clientWidth || -props.border.left; - props.leftContainer.width = props.left.width; - props.right.width = dom.rightContainer.clientWidth || -props.border.right; - props.rightContainer.width = props.right.width; - var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth; - props.center.width = centerWidth; - props.centerContainer.width = centerWidth; - props.top.width = centerWidth; - props.bottom.width = centerWidth; + /** + * Get the current groups + * @returns {vis.DataSet | null} groups + */ + ItemSet.prototype.getGroups = function () { + return this.groupsData; + }; - // 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'; - - // 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 - this._updateScrollTop(); - - // reposition the scrollable contents - var offset = this.props.scrollTop; - if (options.orientation.item != 'top') { - offset += Math.max(this.props.centerContainer.height - this.props.center.height - this.props.border.top - this.props.border.bottom, 0); - } - dom.center.style.left = '0'; - dom.center.style.top = offset + 'px'; - dom.left.style.left = '0'; - dom.left.style.top = offset + 'px'; - dom.right.style.left = '0'; - dom.right.style.top = offset + 'px'; - - // show shadows when vertical scrolling is available - var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : ''; - var visibilityBottom = this.props.scrollTop == this.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; + /** + * 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(); - // redraw all components - this.components.forEach(function (component) { - resized = component.redraw() || resized; - }); - if (resized) { - // keep repainting until all sizes are settled - var MAX_REDRAWS = 3; // maximum number of consecutive redraws - if (this.redrawCount < MAX_REDRAWS) { - this.redrawCount++; - this._redraw(); - } else { - console.log('WARNING: infinite loop in redraw?'); - } - this.redrawCount = 0; + 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); + } + }); } }; - // 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. + * Get the time of an item based on it's data and options.type + * @param {Object} itemData + * @returns {string} Returns the type + * @private */ - Core.prototype.setCurrentTime = function (time) { - if (!this.currentTime) { - throw new Error('Option showCurrentTime must be true'); - } - - this.currentTime.setCurrentTime(time); + ItemSet.prototype._getType = function (itemData) { + return itemData.type || this.options.type || (itemData.end ? 'range' : 'box'); }; /** - * Get the current time. - * Only applicable when option `showCurrentTime` is true. - * @return {Date} Returns the current time. + * Get the group id for an item + * @param {Object} itemData + * @returns {string} Returns the groupId + * @private */ - Core.prototype.getCurrentTime = function () { - if (!this.currentTime) { - throw new Error('Option showCurrentTime must be true'); + 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; } - - 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 + * Handle updated items + * @param {Number[]} ids * @protected */ - // TODO: move this function to Range - Core.prototype._toTime = function (x) { - return DateUtil.toTime(this, x, this.props.center.width); + 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 = me._getType(itemData); + + 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) { + // 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.stackDirty = true; // force re-stacking of all items next redraw + this.body.emitter.emit('change', { queue: true }); }; /** - * 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 + * Handle added items + * @param {Number[]} ids * @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); - }; + ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate; /** - * 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. + * Handle removed items + * @param {Number[]} ids * @protected */ - // TODO: move this function to Range - Core.prototype._toScreen = function (time) { - return DateUtil.toScreen(this, time, this.props.center.width); + 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.stackDirty = true; // force re-stacking of all items next redraw + this.body.emitter.emit('change', { queue: true }); + } }; /** - * 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 + * Update the order of item in all groups + * @private */ - // 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; + 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(); + }); }; /** - * Initialize watching when option autoResize is true + * Handle updated groups + * @param {Number[]} ids * @private */ - Core.prototype._initAutoResize = function () { - if (this.options.autoResize == true) { - this._startAutoResize(); - } else { - this._stopAutoResize(); - } + ItemSet.prototype._onUpdateGroups = function (ids) { + this._onAddGroups(ids); }; /** - * Watch for changes in the size of the container. On resize, the Panel will - * automatically redraw itself. + * Handle changed groups (added or updated) + * @param {Number[]} ids * @private */ - Core.prototype._startAutoResize = function () { + ItemSet.prototype._onAddGroups = function (ids) { var me = this; - this._stopAutoResize(); + ids.forEach(function (id) { + var groupData = me.groupsData.get(id); + var group = me.groups[id]; - this._onResize = function () { - if (me.options.autoResize != true) { - // stop watching when the option autoResize is changed to false - me._stopAutoResize(); - return; - } + if (!group) { + // check for reserved ids + if (id == UNGROUPED || id == BACKGROUND) { + throw new Error('Illegal group id. ' + id + ' is a reserved id.'); + } - 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; + var groupOptions = Object.create(me.options); + util.extend(groupOptions, { + height: null + }); - me.emit('change'); + 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); + } + } } - } - }; - // add event listener to window resize - util.addEventListener(window, 'resize', this._onResize); + group.order(); + group.show(); + } else { + // update group + group.setData(groupData); + } + }); - this.watchTimer = setInterval(this._onResize, 1000); + this.body.emitter.emit('change', { queue: true }); }; /** - * Stop watching for a resize of the frame. + * Handle removed groups + * @param {Number[]} ids * @private */ - Core.prototype._stopAutoResize = function () { - if (this.watchTimer) { - clearInterval(this.watchTimer); - this.watchTimer = undefined; - } + ItemSet.prototype._onRemoveGroups = function (ids) { + var groups = this.groups; + ids.forEach(function (id) { + var group = groups[id]; - // remove event listener on window.resize - util.removeEventListener(window, 'resize', this._onResize); - this._onResize = null; + if (group) { + group.hide(); + delete groups[id]; + } + }); + + this.markDirty(); + + this.body.emitter.emit('change', { queue: true }); }; /** - * Start moving the timeline vertically - * @param {Event} event + * Reorder the groups if needed + * @return {boolean} changed * @private */ - Core.prototype._onTouch = function (event) { - this.touch.allowDragging = true; - this.touch.initialScrollTop = this.props.scrollTop; + ItemSet.prototype._orderGroups = function () { + if (this.groupsData) { + // reorder the groups + var groupIds = this.groupsData.getIds({ + order: this.options.groupOrder + }); + + 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; + } }; /** - * Start moving the timeline vertically - * @param {Event} event + * Add a new item + * @param {Item} item * @private */ - Core.prototype._onPinch = function (event) { - this.touch.allowDragging = false; + 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) group.add(item); }; /** - * Move the timeline vertically - * @param {Event} event + * Update an existing item + * @param {Item} item + * @param {Object} itemData * @private */ - Core.prototype._onDrag = function (event) { - // 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; + ItemSet.prototype._updateItem = function (item, itemData) { + var oldGroupId = item.data.group; + var oldSubGroupId = item.data.subgroup; - var delta = event.deltaY; + // update the items data (will redraw the item when displayed) + item.setData(itemData); - var oldScrollTop = this._getScrollTop(); - var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta); + // update group + if (oldGroupId != item.data.group || oldSubGroupId != item.data.subgroup) { + var oldGroup = this.groups[oldGroupId]; + if (oldGroup) oldGroup.remove(item); - if (newScrollTop != oldScrollTop) { - this._redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already - this.emit('verticalDrag'); + var groupId = this._getGroupId(item.data); + var group = this.groups[groupId]; + if (group) group.add(item); } }; /** - * Apply a scrollTop - * @param {Number} scrollTop - * @returns {Number} scrollTop Returns the applied scrollTop + * 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 */ - Core.prototype._setScrollTop = function (scrollTop) { - this.props.scrollTop = scrollTop; - this._updateScrollTop(); - return this.props.scrollTop; + 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); }; /** - * Update the current scrollTop when the height of the containers has been changed - * @returns {Number} scrollTop Returns the applied scrollTop + * Create an array containing all items being a range (having an end date) + * @param array + * @returns {Array} * @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; + ItemSet.prototype._constructByEndArray = function (array) { + var endArray = []; + + for (var i = 0; i < array.length; i++) { + if (array[i] instanceof RangeItem) { + endArray.push(array[i]); } - 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; - - return this.props.scrollTop; + return endArray; }; /** - * Get the current scrollTop - * @returns {number} scrollTop + * Register the clicked item on touch, before dragStart is initiated. + * + * dragStart is initiated from a mousemove event, AFTER the mouse/touch is + * already moving. Therefore, the mouse/touch can sometimes be above an other + * DOM element than the item itself. + * + * @param {Event} event * @private */ - Core.prototype._getScrollTop = function () { - return this.props.scrollTop; + ItemSet.prototype._onTouch = function (event) { + // store the touched item, used in _onDragStart + this.touchParams.item = this.itemFromTarget(event); + this.touchParams.dragLeftItem = event.target.dragLeftItem || false; + this.touchParams.dragRightItem = event.target.dragRightItem || false; + this.touchParams.itemProps = null; }; - module.exports = Core; - -/***/ }, -/* 45 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; + /** + * Start dragging the selected events + * @param {Event} event + * @private + */ + ItemSet.prototype._onDragStart = function (event) { + if (!this.options.editable.updateTime && !this.options.editable.updateGroup) { + return; + } - Object.defineProperty(exports, '__esModule', { - value: true - }); + var item = this.touchParams.item || null; + var me = this; + var props; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + if (item && item.selected) { + var dragLeftItem = this.touchParams.dragLeftItem; + var dragRightItem = this.touchParams.dragRightItem; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + if (dragLeftItem) { + props = { + item: dragLeftItem, + initialX: event.center.x, + dragLeft: true, + data: util.extend({}, item.data) // clone the items data + }; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + this.touchParams.itemProps = [props]; + } else if (dragRightItem) { + props = { + item: dragRightItem, + initialX: event.center.x, + dragRight: true, + data: util.extend({}, item.data) // clone the items data + }; - var _ColorPicker = __webpack_require__(73); + this.touchParams.itemProps = [props]; + } else { + this.touchParams.itemProps = this.getSelection().map(function (id) { + var item = me.items[id]; + var props = { + item: item, + initialX: event.center.x, + data: util.extend({}, item.data) // clone the items data + }; - var _ColorPicker2 = _interopRequireDefault(_ColorPicker); + return props; + }); + } - var util = __webpack_require__(2); + event.stopPropagation(); + } else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) { + // create a new range item when dragging with ctrl key down + this._onDragStartAddItem(event); + } + }; /** - * 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 - * - * @param parentModule | the location where parentModule.setOptions() can be called - * @param defaultContainer | the default container of the module - * @param configureOptions | the fully configured and predefined options set found in allOptions.js - * @param pixelRatio | canvas pixel ratio + * Start creating a new range item by dragging. + * @param {Event} event + * @private */ + ItemSet.prototype._onDragStartAddItem = function (event) { + var snap = this.options.snap || null; + var xAbs = util.getAbsoluteLeft(this.dom.frame); + var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px + var time = this.body.util.toTime(x); + var scale = this.body.util.getScale(); + var step = this.body.util.getStep(); + var start = snap ? snap(time, scale, step) : start; + var end = start; - var Configurator = (function () { - function Configurator(parentModule, defaultContainer, configureOptions) { - var pixelRatio = arguments[3] === undefined ? 1 : arguments[3]; + var itemData = { + type: 'range', + start: start, + end: end, + content: 'new item' + }; - _classCallCheck(this, Configurator); + var id = util.randomUUID(); + itemData[this.itemsData._fieldId] = id; - this.parent = parentModule; - this.changedOptions = []; - this.container = defaultContainer; - this.allowCreation = false; + var group = this.groupFromTarget(event); + if (group) { + itemData.group = group.groupId; + } - this.options = {}; - this.defaultOptions = { - enabled: false, - filter: true, - container: undefined, - showButton: true - }; - util.extend(this.options, this.defaultOptions); + var newItem = new RangeItem(itemData, this.conversion, this.options); + newItem.id = id; // TODO: not so nice setting id afterwards + newItem.data = itemData; + this._addItem(newItem); - this.configureOptions = configureOptions; - this.moduleOptions = {}; - this.domElements = []; - this.colorPicker = new _ColorPicker2['default'](pixelRatio); - this.wrapper = undefined; - } + var props = { + item: newItem, + dragRight: true, + initialX: event.center.x, + data: util.extend({}, itemData) + }; + this.touchParams.itemProps = [props]; - _createClass(Configurator, [{ - key: 'setOptions', + event.stopPropagation(); + }; - /** - * refresh all options. - * Because all modules parse their options by themselves, we just use their options. We copy them here. - * - * @param options - */ - value: function setOptions(options) { - if (options !== undefined) { - 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 === 'object') { - if (options.container !== undefined) { - this.options.container = options.container; - } - if (options.filter !== undefined) { - this.options.filter = options.filter; + /** + * Drag selected items + * @param {Event} event + * @private + */ + ItemSet.prototype._onDrag = function (event) { + if (this.touchParams.itemProps) { + event.stopPropagation(); + + var me = this; + var snap = this.options.snap || null; + var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width; + var scale = this.body.util.getScale(); + var step = this.body.util.getStep(); + + // move + this.touchParams.itemProps.forEach(function (props) { + var newProps = {}; + var current = me.body.util.toTime(event.center.x - xOffset); + var initial = me.body.util.toTime(props.initialX - xOffset); + var offset = current - initial; + + var itemData = util.extend({}, props.item.data); // clone the data + + if (me.options.editable.updateTime) { + if (props.dragLeft) { + // drag left side of a range item + if (itemData.start != undefined) { + var initialStart = util.convert(props.data.start, 'Date'); + var start = new Date(initialStart.valueOf() + offset); + itemData.start = snap ? snap(start, scale, step) : start; } - if (options.showButton !== undefined) { - this.options.showButton = options.showButton; + } else if (props.dragRight) { + // drag right side of a range item + if (itemData.end != undefined) { + var initialEnd = util.convert(props.data.end, 'Date'); + var end = new Date(initialEnd.valueOf() + offset); + itemData.end = snap ? snap(end, scale, step) : end; } - if (options.enabled !== undefined) { - enabled = options.enabled; + } else { + // drag both start and end + if (itemData.start != undefined) { + var initialStart = util.convert(props.data.start, 'Date').valueOf(); + var start = new Date(initialStart + offset); + + if (itemData.end != undefined) { + var initialEnd = util.convert(props.data.end, 'Date'); + var duration = initialEnd.valueOf() - initialStart.valueOf(); + + itemData.start = snap ? snap(start, scale, step) : start; + itemData.end = new Date(itemData.start.valueOf() + duration); + } else { + itemData.start = snap ? snap(start, scale, step) : start; + } } - } else if (typeof options === 'boolean') { - this.options.filter = true; - enabled = options; - } else if (typeof options === 'function') { - this.options.filter = options; - enabled = true; } - this.options.enabled = enabled; } - this._clean(); - } - }, { - 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; + + if (me.options.editable.updateGroup && (!props.dragLeft && !props.dragRight)) { + if (itemData.group != undefined) { + // drag from one group to another + var group = me.groupFromTarget(event); + if (group) { + itemData.group = group.groupId; + } } - this._create(); } - } - }, { - key: '_create', - /** - * Create all DOM elements - * @private - */ - value: function _create() { - var _this = this; + // confirm moving the item + me.options.onMoving(itemData, function (itemData) { + if (itemData) { + props.item.setData(itemData); + } + }); + }); - this._clean(); - this.changedOptions = []; + this.stackDirty = true; // force re-stacking of all items next redraw + this.body.emitter.emit('change'); + } + }; - 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; - } + /** + * Move an item to another group + * @param {Item} item + * @param {String | Number} groupId + * @private + */ + ItemSet.prototype._moveToGroup = function (item, groupId) { + var group = this.groups[groupId]; + if (group && group.groupId != item.data.group) { + var oldGroup = item.parent; + oldGroup.remove(item); + oldGroup.order(); + group.add(item); + group.order(); - if (show !== false) { - this.allowCreation = true; + item.data.group = group.groupId; + } + }; - // linebreak between categories - if (counter > 0) { - this._makeItem([]); - } - // a header for the category - this._makeHeader(option); + /** + * End of dragging selected items + * @param {Event} event + * @private + */ + ItemSet.prototype._onDragEnd = function (event) { + if (this.touchParams.itemProps) { + event.stopPropagation(); - // get the suboptions - this._handleObject(this.configureOptions[option], [option]); - } - counter++; - } - } + // prepare a change set for the changed items + var changes = []; + var me = this; + var dataset = this.itemsData.getDataSet(); - if (this.options.showButton === true) { - (function () { - var generateButton = document.createElement('div'); - generateButton.className = 'vis-network-configuration button'; - generateButton.innerHTML = 'generate options'; - generateButton.onclick = function () { - _this._printOptions(); - }; - generateButton.onmouseover = function () { - generateButton.className = 'vis-network-configuration button hover'; - }; - generateButton.onmouseout = function () { - generateButton.className = 'vis-network-configuration button'; - }; + var itemProps = this.touchParams.itemProps; + this.touchParams.itemProps = null; + itemProps.forEach(function (props) { + var id = props.item.id; + var exists = me.itemsData.get(id, me.itemOptions) != null; - _this.optionsContainer = document.createElement('div'); - _this.optionsContainer.className = 'vis-network-configuration vis-option-container'; + if (!exists) { + // add a new item + me.options.onAdd(props.item.data, function (itemData) { + me._removeItem(props.item); // remove temporary item + if (itemData) { + me.itemsData.getDataSet().add(itemData); + } - _this.domElements.push(_this.optionsContainer); - _this.domElements.push(generateButton); - })(); + // force re-stacking of all items next redraw + me.stackDirty = true; + me.body.emitter.emit('change'); + }); + } else { + // update existing item + var itemData = util.extend({}, props.item.data); // clone the data + me.options.onMove(itemData, function (itemData) { + if (itemData) { + // apply changes + itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined) + changes.push(itemData); + } else { + // restore original values + props.item.setData(props.data); + + me.stackDirty = true; // force re-stacking of all items next redraw + me.body.emitter.emit('change'); + } + }); } + }); - this._push(); - this.colorPicker.insertTo(this.container); + // apply the changes to the data (if there are changes) + if (changes.length) { + dataset.update(changes); } - }, { - key: '_push', + } + }; - /** - * draw all DOM elements on the screen - * @private - */ - value: function _push() { - this.wrapper = document.createElement('div'); - this.wrapper.className = 'vis-network-configuration-wrapper'; - this.container.appendChild(this.wrapper); - for (var i = 0; i < this.domElements.length; i++) { - this.wrapper.appendChild(this.domElements[i]); - } - } - }, { - key: '_clean', + /** + * Handle selecting/deselecting an item when tapping it + * @param {Event} event + * @private + */ + ItemSet.prototype._onSelectItem = function (event) { + if (!this.options.selectable) return; - /** - * delete all DOM elements - * @private - */ - value: function _clean() { - for (var i = 0; i < this.domElements.length; i++) { - this.wrapper.removeChild(this.domElements[i]); - } + var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey); + var shiftKey = event.srcEvent && event.srcEvent.shiftKey; + if (ctrlKey || shiftKey) { + this._onMultiSelectItem(event); + return; + } - if (this.wrapper !== undefined) { - this.container.removeChild(this.wrapper); - this.wrapper = undefined; - } - this.domElements = []; - } - }, { - key: '_getValue', + var oldSelection = this.getSelection(); - /** - * get the value from the actualOptions if it exists - * @param {array} path | where to look for the actual option - * @returns {*} - * @private - */ - 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; - } - }, { - key: '_makeItem', + var item = this.itemFromTarget(event); + var selection = item ? [item.id] : []; + this.setSelection(selection); - /** - * all option elements are wrapped in an item - * @param path - * @param domElements - * @private - */ - value: function _makeItem(path) { - var _this2 = this; + var newSelection = this.getSelection(); - for (var _len = arguments.length, domElements = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - domElements[_key - 1] = arguments[_key]; - } + // emit a select event, + // except when old selection is empty and new selection is still empty + if (newSelection.length > 0 || oldSelection.length > 0) { + this.body.emitter.emit('select', { + items: newSelection + }); + } + }; - if (this.allowCreation === true) { - (function () { - var item = document.createElement('div'); - item.className = 'vis-network-configuration item s' + path.length; - domElements.forEach(function (element) { - item.appendChild(element); - }); - _this2.domElements.push(item); - })(); + /** + * Handle creation and updates of an item on double tap + * @param event + * @private + */ + ItemSet.prototype._onAddItem = function (event) { + if (!this.options.selectable) return; + if (!this.options.editable.add) return; + + var me = this; + var snap = this.options.snap || null; + var item = this.itemFromTarget(event); + + event.stopPropagation(); + + if (item) { + // update item + + // execute async handler to update the item (or cancel it) + var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset + this.options.onUpdate(itemData, function (itemData) { + if (itemData) { + me.itemsData.getDataSet().update(itemData); } - } - }, { - key: '_makeHeader', + }); + } else { + // add item + var xAbs = util.getAbsoluteLeft(this.dom.frame); + var x = event.center.x - xAbs; + var start = this.body.util.toTime(x); + var scale = this.body.util.getScale(); + var step = this.body.util.getStep(); - /** - * header for major subjects - * @param name - * @private - */ - value: function _makeHeader(name) { - var div = document.createElement('div'); - div.className = 'vis-network-configuration header'; - div.innerHTML = name; - this._makeItem([], div); + var newItem = { + start: snap ? snap(start, scale, step) : start, + content: 'new item' + }; + + // when default type is a range, add a default end date to the new item + if (this.options.type === 'range') { + var end = this.body.util.toTime(x + this.props.width / 5); + newItem.end = snap ? snap(end, scale, step) : end; } - }, { - key: '_makeLabel', - /** - * make a label, if it is an object label, it gets different styling. - * @param name - * @param path - * @param objectLabel - * @returns {HTMLElement} - * @private - */ - value: function _makeLabel(name, path) { - var objectLabel = arguments[2] === undefined ? false : arguments[2]; + newItem[this.itemsData._fieldId] = util.randomUUID(); - var div = document.createElement('div'); - div.className = 'vis-network-configuration label s' + path.length; - if (objectLabel === true) { - div.innerHTML = '' + name + ':'; - } else { - div.innerHTML = name + ':'; - } - return div; + var group = this.groupFromTarget(event); + if (group) { + newItem.group = group.groupId; } - }, { - key: '_makeDropdown', - /** - * make a dropdown list for multiple possible string optoins - * @param arr - * @param value - * @param path - * @private - */ - value: function _makeDropdown(arr, value, path) { - var select = document.createElement('select'); - select.className = 'vis-network-configuration select'; - var selectedValue = 0; - if (value !== undefined) { - if (arr.indexOf(value) !== -1) { - selectedValue = arr.indexOf(value); - } + // execute async handler to customize (or cancel) adding an item + this.options.onAdd(newItem, function (item) { + if (item) { + me.itemsData.getDataSet().add(item); + // TODO: need to trigger a redraw? } + }); + } + }; - 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); - } + /** + * Handle selecting/deselecting multiple items when holding an item + * @param {Event} event + * @private + */ + ItemSet.prototype._onMultiSelectItem = function (event) { + if (!this.options.selectable) return; - var me = this; - select.onchange = function () { - me._update(this.value, path); - }; + var item = this.itemFromTarget(event); - var label = this._makeLabel(path[path.length - 1], path); - this._makeItem(path, label, select); - } - }, { - key: '_makeRange', + if (item) { + // multi select items (if allowed) - /** - * make a range object for numeric options - * @param arr - * @param value - * @param path - * @private - */ - 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.type = 'range'; - range.className = 'vis-network-configuration range'; - range.min = min; - range.max = max; - range.step = step; + var selection = this.options.multiselect ? this.getSelection() // take current selection + : []; // deselect current selection - if (value !== undefined) { - if (value < 0 && value * 2 < min) { - range.min = value * 2; - } else if (value * 0.1 < min) { - range.min = value / 10; - } - if (value * 2 > max && max !== 1) { - range.max = value * 2; - } - range.value = value; - } else { - range.value = defaultValue; - } + var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false; - var input = document.createElement('input'); - input.className = 'vis-network-configuration rangeinput'; - input.value = range.value; + if (shiftKey && this.options.multiselect) { + // select all items between the old selection and the tapped item - var me = this; - range.onchange = function () { - input.value = this.value;me._update(Number(this.value), path); - }; - range.oninput = function () { - input.value = this.value; - }; + // determine the selection range + selection.push(item.id); + var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions)); - var label = this._makeLabel(path[path.length - 1], path); - this._makeItem(path, label, range, input); - } - }, { - key: '_makeCheckbox', + // select all items within the selection range + selection = []; + for (var id in this.items) { + if (this.items.hasOwnProperty(id)) { + var _item = this.items[id]; + var start = _item.data.start; + var end = _item.data.end !== undefined ? _item.data.end : start; - /** - * make a checkbox for boolean options. - * @param defaultValue - * @param value - * @param path - * @private - */ - value: function _makeCheckbox(defaultValue, value, path) { - var checkbox = document.createElement('input'); - checkbox.type = 'checkbox'; - checkbox.className = 'vis-network-configuration checkbox'; - checkbox.checked = defaultValue; - if (value !== undefined) { - checkbox.checked = value; - if (value !== defaultValue) { - if (typeof defaultValue === 'object') { - if (value !== defaultValue.enabled) { - this.changedOptions.push({ path: path, value: value }); - } - } else { - this.changedOptions.push({ path: path, value: value }); + if (start >= range.min && end <= range.max && !(_item instanceof BackgroundItem)) { + selection.push(_item.id); // do not use id but item.id, id itself is stringified } } } - - 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); - } - }, { - key: '_makeTextInput', - - /** - * make a text input field for string options. - * @param defaultValue - * @param value - * @param path - * @private - */ - value: function _makeTextInput(defaultValue, value, path) { - var checkbox = document.createElement('input'); - checkbox.type = 'text'; - checkbox.className = 'vis-network-configuration text'; - checkbox.value = value; - if (value !== defaultValue) { - this.changedOptions.push({ path: path, value: value }); + } else { + // add/remove this item from the current selection + var index = selection.indexOf(item.id); + if (index == -1) { + // item is not yet selected -> select it + selection.push(item.id); + } else { + // item is already selected -> deselect it + selection.splice(index, 1); } - - 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); } - }, { - key: '_makeColorField', - - /** - * make a color field with a color picker for color fields - * @param arr - * @param value - * @param path - * @private - */ - value: function _makeColorField(arr, value, path) { - var _this3 = this; - var defaultColor = arr[1]; - var div = document.createElement('div'); - value = value === undefined ? defaultColor : value; + this.setSelection(selection); - if (value !== 'none') { - div.className = 'vis-network-configuration colorBlock'; - div.style.backgroundColor = value; - } else { - div.className = 'vis-network-configuration colorBlock none'; - } + this.body.emitter.emit('select', { + items: this.getSelection() + }); + } + }; - value = value === undefined ? defaultColor : value; - div.onclick = function () { - _this3._showColorPicker(value, div, path); - }; + /** + * Calculate the time range of a list of items + * @param {Array.} itemsData + * @return {{min: Date, max: Date}} Returns the range of the provided items + * @private + */ + ItemSet._getItemRange = function (itemsData) { + var max = null; + var min = null; - var label = this._makeLabel(path[path.length - 1], path); - this._makeItem(path, label, div); + itemsData.forEach(function (data) { + if (min == null || data.start < min) { + min = data.start; } - }, { - key: '_showColorPicker', - - /** - * used by the color buttons to call the color picker. - * @param event - * @param value - * @param div - * @param path - * @private - */ - value: function _showColorPicker(value, div, path) { - var _this4 = this; - var rect = div.getBoundingClientRect(); - var bodyRect = document.body.getBoundingClientRect(); - var pickerX = rect.left + rect.width + 5; - var pickerY = rect.top - bodyRect.top + rect.height * 0.5; - this.colorPicker.show(pickerX, pickerY); - this.colorPicker.setColor(value); - this.colorPicker.setCallback(function (color) { - var colorString = 'rgba(' + color.r + ',' + color.g + ',' + color.b + ',' + color.a + ')'; - div.style.backgroundColor = colorString; - _this4._update(colorString, path); - }); + if (data.end != undefined) { + if (max == null || data.end > max) { + max = data.end; + } + } else { + if (max == null || data.start > max) { + max = data.start; + } } - }, { - key: '_handleObject', - - /** - * parse an object and draw the correct items - * @param obj - * @param path - * @private - */ - value: function _handleObject(obj) { - var path = arguments[1] === undefined ? [] : arguments[1]; - var checkOnly = arguments[2] === undefined ? false : arguments[2]; - - 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; - } - } - } + return { + min: min, + max: max + }; + }; - if (show !== false) { - visibleInSet = true; - var value = this._getValue(newPath); + /** + * Find an item from an event target: + * searches for the attribute 'timeline-item' in the event target's element tree + * @param {Event} event + * @return {Item | null} item + */ + ItemSet.prototype.itemFromTarget = function (event) { + var target = event.target; + while (target) { + if (target.hasOwnProperty('timeline-item')) { + return target['timeline-item']; + } + target = target.parentNode; + } - 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; - } - } + return null; + }; - 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; + /** + * Find the Group from an event target: + * searches for the attribute 'timeline-group' in the event target's element tree + * @param {Event} event + * @return {Group | null} group + */ + ItemSet.prototype.groupFromTarget = function (event) { + var clientY = event.center ? event.center.y : event.clientY; + for (var i = 0; i < this.groupIds.length; i++) { + var groupId = this.groupIds[i]; + var group = this.groups[groupId]; + var foreground = group.dom.foreground; + var top = util.getAbsoluteTop(foreground); + if (clientY > top && clientY < top + foreground.offsetHeight) { + return group; } - }, { - key: '_handleArray', - /** - * handle the array type of option - * @param optionName - * @param arr - * @param value - * @param path - * @private - */ - 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) }); - } + if (this.options.orientation.item === 'top') { + if (i === this.groupIds.length - 1 && clientY > top) { + return group; + } + } else { + if (i === 0 && clientY < top + foreground.offset) { + return group; } } - }, { - key: '_update', - - /** - * called to update the network with the new settings. - * @param value - * @param path - * @private - */ - value: function _update(value, path) { - var options = this._constructOptions(value, path); - this.parent.setOptions(options); - } - }, { - key: '_constructOptions', - value: function _constructOptions(value, path) { - var optionsObj = 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; + return null; + }; - 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; - } - }, { - key: '_printOptions', - value: function _printOptions() { - var options = {}; - for (var i = 0; i < this.changedOptions.length; i++) { - this._constructOptions(this.changedOptions[i].value, this.changedOptions[i].path, options); - } - this.optionsContainer.innerHTML = '
var options = ' + JSON.stringify(options, null, 2) + '
'; + /** + * Find the ItemSet from an event target: + * searches for the attribute 'timeline-itemset' in the event target's element tree + * @param {Event} event + * @return {ItemSet | null} item + */ + ItemSet.itemSetFromTarget = function (event) { + var target = event.target; + while (target) { + if (target.hasOwnProperty('timeline-itemset')) { + return target['timeline-itemset']; } - }]); + target = target.parentNode; + } - return Configurator; - })(); + return null; + }; - exports['default'] = Configurator; - module.exports = exports['default']; + module.exports = ItemSet; /***/ }, -/* 46 */ +/* 34 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - var util = __webpack_require__(2); + var util = __webpack_require__(7); + var stack = __webpack_require__(35); + var RangeItem = __webpack_require__(36); - var errorFound = false; - var allOptions = undefined; - var printStyle = 'background: #FFeeee; color: #dd0000'; /** - * Used to validate options. + * @constructor Group + * @param {Number | String} groupId + * @param {Object} data + * @param {ItemSet} itemSet */ + function Group(groupId, data, itemSet) { + this.groupId = groupId; + this.subgroups = {}; + this.subgroupIndex = 0; + this.subgroupOrderer = data && data.subgroupOrder; + this.itemSet = itemSet; - var Validator = (function () { - function Validator() { - _classCallCheck(this, Validator); - } + this.dom = {}; + this.props = { + label: { + width: 0, + height: 0 + } + }; + this.className = null; - _createClass(Validator, null, [{ - key: 'validate', + this.items = {}; // items filtered by groupId of this group + this.visibleItems = []; // items currently visible in window + 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; + }); - /** - * Main function to be called - * @param options - * @param subObject - * @returns {boolean} - */ - 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; - } - }, { - key: 'parse', + this._create(); - /** - * Will traverse an object recursively and check every value - * @param options - * @param referenceOptions - * @param path - */ - value: function parse(options, referenceOptions, path) { - for (var option in options) { - if (options.hasOwnProperty(option)) { - Validator.check(option, options, referenceOptions, path); - } - } - } - }, { - key: 'check', + this.setData(data); + } - /** - * Check every value. If the value is an object, call the parse function on that object. - * @param option - * @param options - * @param referenceOptions - * @param path - */ - value: function check(option, options, referenceOptions, path) { - if (referenceOptions[option] === undefined && referenceOptions.__any__ === undefined) { - Validator.getSuggestion(option, referenceOptions, path); - } else if (referenceOptions[option] === undefined && referenceOptions.__any__ !== undefined) { - // __any__ is a wildcard. Any value is accepted and will be further analysed by reference. - if (Validator.getType(options[option]) === 'object') { - Validator.checkFields(option, options, referenceOptions, '__any__', referenceOptions['__any__'].__type__, path); - } - } else { - // Since all options in the reference are objects, we can check whether they are supposed to be object to look for the __type__ field. - if (referenceOptions[option].__type__ !== undefined) { - // if this should be an object, we check if the correct type has been supplied to account for shorthand options. - Validator.checkFields(option, options, referenceOptions, option, referenceOptions[option].__type__, path); - } else { - Validator.checkFields(option, options, referenceOptions, option, referenceOptions[option], path); - } - } - } - }, { - key: 'checkFields', + /** + * Create DOM elements for the group + * @private + */ + Group.prototype._create = function () { + var label = document.createElement('div'); + label.className = 'vis-label'; + this.dom.label = label; - /** - * - * @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} refOptionType | This is the type object from the reference options - * @param {Array} path | where in the object is the option - */ - value: function checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path) { - 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') { - if (refOptionType.indexOf(options[option]) === -1) { - console.log('%cInvalid option detected in "' + option + '".' + ' Allowed values are:' + Validator.print(refOptionType) + ' not "' + options[option] + '". ' + Validator.printLocation(path, option), printStyle); - errorFound = true; - } else if (optionType === 'object') { - path = util.copyAndExtendArray(path, option); - Validator.parse(options[option], referenceOptions[referenceOption], path); - } - } else if (optionType === 'object') { - path = util.copyAndExtendArray(path, option); - Validator.parse(options[option], referenceOptions[referenceOption], path); - } - } else { - if (refOptionObj['undef'] !== undefined && optionType === 'undefined') {} else if (refOptionObj['fn'] !== undefined && optionType === 'function') {} else { - // type of the field is incorrect - console.log('%cInvalid type received for "' + option + '". Expected: ' + Validator.print(Object.keys(refOptionObj)) + '. Received [' + optionType + '] "' + options[option] + '"' + Validator.printLocation(path, option), printStyle); - errorFound = true; - } - } - } - }, { - key: 'getType', - value: function getType(object) { - var type = typeof object; + var inner = document.createElement('div'); + inner.className = 'vis-inner'; + label.appendChild(inner); + this.dom.inner = inner; - 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; - } - }, { - key: 'getSuggestion', - value: function getSuggestion(option, options, path) { - var localSearch = Validator.findInOptions(option, options, path, false); - var globalSearch = Validator.findInOptions(option, allOptions, [], true); + var foreground = document.createElement('div'); + foreground.className = 'vis-group'; + foreground['timeline-group'] = this; + this.dom.foreground = foreground; - var localSearchThreshold = 8; - var globalSearchThreshold = 4; + this.dom.background = document.createElement('div'); + this.dom.background.className = 'vis-group'; - if (localSearch.indexMatch !== undefined) { - console.log('%cUnknown option detected: "' + option + '" in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was incomplete? Did you mean: "' + localSearch.indexMatch + '"?\n\n', printStyle); - } else if (globalSearch.distance <= globalSearchThreshold && localSearch.distance > globalSearch.distance) { - console.log('%cUnknown option detected: "' + option + '" in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was misplaced? Matching option found at: ' + Validator.printLocation(globalSearch.path, globalSearch.closestMatch, ''), printStyle); - } else if (localSearch.distance <= localSearchThreshold) { - console.log('%cUnknown option detected: "' + option + '". Did you mean "' + localSearch.closestMatch + '"?' + Validator.printLocation(localSearch.path, option), printStyle); - } else { - console.log('%cUnknown option detected: "' + option + '". Did you mean one of these: ' + Validator.print(Object.keys(options)) + Validator.printLocation(path, option), printStyle); - } + this.dom.axis = document.createElement('div'); + this.dom.axis.className = 'vis-group'; - errorFound = true; - } - }, { - key: 'findInOptions', + // 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.innerHTML = '?'; + this.dom.background.appendChild(this.dom.marker); + }; - /** - * traverse the options in search for a match. - * @param option - * @param options - * @param path - * @param recursive - * @returns {{closestMatch: string, path: Array, distance: number}} - */ - value: function findInOptions(option, options, path) { - var recursive = arguments[3] === undefined ? false : arguments[3]; + /** + * 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 = data && data.content; + if (content instanceof Element) { + this.dom.inner.appendChild(content); + } else if (content !== undefined && content !== null) { + this.dom.inner.innerHTML = content; + } else { + this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null + } - var min = 1000000000; - var closestMatch = ''; - var closestMatchPath = []; - var lowerCaseOption = option.toLowerCase(); - var indexMatch = undefined; - for (var op in options) { - var distance = undefined; - 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 }; - } - }, { - key: 'printLocation', - value: function printLocation(path, option) { - var prefix = arguments[2] === undefined ? 'Problem value found at: \n' : arguments[2]; + // update title + this.dom.label.title = data && data.title || ''; - 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 j = 0; j < path.length - i; j++) { - str += ' '; - } - str += '}\n'; - } - return str + '\n\n'; - } - }, { - key: 'print', - value: function print(options) { - return JSON.stringify(options).replace(/(\")|(\[)|(\])|(,"__type__")/g, '').replace(/(\,)/g, ', '); + if (!this.dom.inner.firstChild) { + util.addClassName(this.dom.inner, 'vis-hidden'); + } else { + util.removeClassName(this.dom.inner, 'vis-hidden'); + } + + // 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); } - }, { - key: 'levenshteinDistance', + 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; + } - // 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. - */ - value: function levenshteinDistance(a, b) { - if (a.length === 0) return b.length; - if (b.length === 0) return a.length; + // update style + if (this.style) { + util.removeCssText(this.dom.label, 'vis-' + this.style); + this.style = null; + } + if (data && data.style) { + util.addCssText(this.dom.label, 'vis-' + data.style); + this.style = data.style; + } + }; - var matrix = []; + /** + * Get the width of the group label + * @return {number} width + */ + Group.prototype.getLabelWidth = function () { + return this.props.label.width; + }; - // increment along the first column of each row - var i; - for (i = 0; i <= b.length; i++) { - matrix[i] = [i]; - } + /** + * Repaint this group + * @param {{start: number, end: number}} range + * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin + * @param {boolean} [restack=false] Force restacking of all items + * @return {boolean} Returns true if the group is resized + */ + Group.prototype.redraw = function (range, margin, restack) { + var resized = false; - // increment each column in the first row - var j; - for (j = 0; j <= a.length; j++) { - matrix[0][j] = j; - } + // 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) + var markerHeight = this.dom.marker.clientHeight; + if (markerHeight != this.lastMarkerHeight) { + this.lastMarkerHeight = markerHeight; - // 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 - } + util.forEach(this.items, function (item) { + item.dirty = true; + if (item.displayed) item.redraw(); + }); + + restack = true; + } + + // reposition visible items vertically + if (typeof this.itemSet.options.order === 'function') { + // a custom order function + + if (restack) { + // brute force restack of all items + + // show all items + var me = this; + var limitSize = false; + util.forEach(this.items, function (item) { + if (!item.displayed) { + item.redraw(); + me.visibleItems.push(item); } - } + item.repositionX(limitSize); + }); - return matrix[b.length][a.length]; + // 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 */); } - }]); - return Validator; - })(); + this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); + } else { + // no custom order function, lazy stacking + this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); - exports['default'] = Validator; - exports.printStyle = printStyle; + if (this.itemSet.options.stack) { + // TODO: ugly way to access options... + stack.stack(this.visibleItems, margin, restack); + } else { + // no stacking + stack.nostack(this.visibleItems, margin, this.subgroups); + } + } - // item is undefined, which is allowed + // recalculate the height of the group + var height = this._calculateHeight(margin); - // item is a function, which is allowed + // calculate actual size and position + var foreground = this.dom.foreground; + this.top = foreground.offsetTop; + this.left = foreground.offsetLeft; + this.width = foreground.offsetWidth; + resized = util.updateProperty(this, 'height', height) || resized; -/***/ }, -/* 47 */ -/***/ function(module, exports, __webpack_require__) { + // recalculate size of label + resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized; + resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized; + + // apply new 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 + for (var i = 0, ii = this.visibleItems.length; i < ii; i++) { + var item = this.visibleItems[i]; + item.repositionY(margin); + } + + return resized; + }; /** - * This object contains all possible options. It will check if the types are correct, if required if the option is one - * of the allowed values. - * - * __any__ means that the name of the property does not matter. - * __type__ is a required field for all objects and contains the allowed types of all objects + * recalculate the height of the group + * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin + * @returns {number} Returns the height + * @private */ - 'use strict'; + Group.prototype._calculateHeight = function (margin) { + // recalculate the height of the group + var height; + var visibleItems = this.visibleItems; + //var visibleSubgroups = []; + //this.visibleSubgroups = 0; + this.resetSubgroups(); + var me = this; + if (visibleItems.length > 0) { + var min = visibleItems[0].top; + var max = visibleItems[0].top + visibleItems[0].height; + util.forEach(visibleItems, function (item) { + min = Math.min(min, item.top); + max = Math.max(max, item.top + item.height); + if (item.data.subgroup !== undefined) { + me.subgroups[item.data.subgroup].height = Math.max(me.subgroups[item.data.subgroup].height, item.height); + me.subgroups[item.data.subgroup].visible = true; + } + }); + 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(visibleItems, function (item) { + item.top -= offset; + }); + } + height = max + margin.item.vertical / 2; + } else { + height = 0; + } + height = Math.max(height, this.props.label.height); - Object.defineProperty(exports, '__esModule', { - value: true - }); - var string = 'string'; - var boolean = 'boolean'; - var number = 'number'; - var array = 'array'; - var date = 'date'; - var object = 'object'; // should only be in a __type__ property - var dom = 'dom'; - var moment = 'moment'; - var fn = 'function'; - var nada = 'null'; - var undef = 'undefined'; - var any = 'any'; + return height; + }; - var allOptions = { - configure: { - enabled: { boolean: boolean }, - filter: { boolean: boolean, fn: fn }, - container: { dom: dom }, - __type__: { object: object, boolean: boolean, fn: fn } - }, + /** + * Show this group: attach to the DOM + */ + Group.prototype.show = function () { + if (!this.dom.label.parentNode) { + this.itemSet.dom.labelSet.appendChild(this.dom.label); + } - //globals : - align: { string: string }, - autoResize: { boolean: boolean }, - clickToUse: { boolean: boolean }, - dataAttributes: { string: string, array: array }, - editable: { - add: { boolean: boolean, undef: undef }, - remove: { boolean: boolean, undef: undef }, - updateGroup: { boolean: boolean, undef: undef }, - updateTime: { boolean: boolean, undef: undef }, - __type__: { boolean: boolean, object: object } - }, - end: { number: number, date: date, string: string, moment: moment }, - format: { - minorLabels: { - millisecond: { string: string, undef: undef }, - second: { string: string, undef: undef }, - minute: { string: string, undef: undef }, - hour: { string: string, undef: undef }, - weekday: { string: string, undef: undef }, - day: { string: string, undef: undef }, - month: { string: string, undef: undef }, - year: { string: string, undef: undef }, - __type__: { object: object } - }, - majorLabels: { - millisecond: { string: string, undef: undef }, - second: { string: string, undef: undef }, - minute: { string: string, undef: undef }, - hour: { string: string, undef: undef }, - weekday: { string: string, undef: undef }, - day: { string: string, undef: undef }, - month: { string: string, undef: undef }, - year: { string: string, undef: undef }, - __type__: { object: object } - }, - __type__: { object: object } - }, - groupOrder: { string: string, fn: fn }, - height: { string: string, number: number }, - hiddenDates: { object: object, array: array }, - locale: { string: string }, - locales: { - __any__: { object: object }, - __type__: { object: object } - }, - margin: { - axis: { number: number }, - item: { - horizontal: { number: number, undef: undef }, - vertical: { number: number, undef: undef }, - __type__: { object: object, number: number } - }, - __type__: { object: object, number: number } - }, - max: { date: date, number: number, string: string, moment: moment }, - maxHeight: { number: number, string: string }, - min: { date: date, number: number, string: string, moment: moment }, - minHeight: { number: number, string: string }, - moveable: { boolean: boolean }, - multiselect: { boolean: boolean }, - onAdd: { fn: fn }, - onUpdate: { fn: fn }, - onMove: { fn: fn }, - onMoving: { fn: fn }, - onRemove: { fn: fn }, - order: { fn: fn }, - orientation: { - axis: { string: string, undef: undef }, - item: { string: string, undef: undef }, - __type__: { string: string, object: object } - }, - selectable: { boolean: boolean }, - showCurrentTime: { boolean: boolean }, - showMajorLabels: { boolean: boolean }, - showMinorLabels: { boolean: boolean }, - stack: { boolean: boolean }, - snap: { fn: fn, nada: nada }, - start: { date: date, number: number, string: string, moment: moment }, - template: { fn: fn }, - timeAxis: { - scale: { string: string, undef: undef }, - step: { number: number, undef: undef }, - __type__: { object: object } - }, - type: { string: string }, - width: { string: string, number: number }, - zoomable: { boolean: boolean }, - zoomMax: { number: number }, - zoomMin: { number: number }, + if (!this.dom.foreground.parentNode) { + this.itemSet.dom.foreground.appendChild(this.dom.foreground); + } - __type__: { object: object } + 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); + } }; - var configureOptions = { - global: { - align: ['center', 'left', 'right'], - autoResize: true, - clickToUse: false, - // dataAttributes: ['all'], // FIXME: can be 'all' or string[] - editable: { - add: false, - remove: false, - updateGroup: false, - updateTime: false - }, - end: '', - format: { - minorLabels: { - millisecond: 'SSS', - second: 's', - minute: 'HH:mm', - hour: 'HH:mm', - weekday: 'ddd D', - day: 'D', - 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', - month: 'YYYY', - year: '' - } - }, + /** + * Hide this group: remove from the DOM + */ + Group.prototype.hide = function () { + var label = this.dom.label; + if (label.parentNode) { + label.parentNode.removeChild(label); + } - //groupOrder: {string, fn}, - height: '', - //hiddenDates: {object, array}, - locale: '', - margin: { - axis: [20, 0, 100, 1], - item: { - horizontal: [10, 0, 100, 1], - vertical: [10, 0, 100, 1] - } - }, - max: '', - maxHeight: '', - min: '', - minHeight: '', - moveable: false, - multiselect: false, - //onAdd: {fn}, - //onUpdate: {fn}, - //onMove: {fn}, - //onMoving: {fn}, - //onRename: {fn}, - //order: {fn}, - orientation: { - axis: ['both', 'bottom', 'top'], - item: ['bottom', 'top'] - }, - selectable: true, - showCurrentTime: false, - showMajorLabels: true, - showMinorLabels: true, - stack: true, - //snap: {fn, nada}, - start: '', - //template: {fn}, - //timeAxis: { - // scale: ['millisecond', 'second', 'minute', 'hour', 'weekday', 'day', 'month', 'year'], - // step: [1, 1, 10, 1] - //}, - type: ['box', 'point', 'range', 'background'], - width: '100%', - zoomable: true, - zoomMax: [315360000000000, 10, 315360000000000, 1], - zoomMin: [10, 10, 315360000000000, 1] + var foreground = this.dom.foreground; + if (foreground.parentNode) { + foreground.parentNode.removeChild(foreground); } - }; - exports.allOptions = allOptions; - exports.configureOptions = configureOptions; + var background = this.dom.background; + if (background.parentNode) { + background.parentNode.removeChild(background); + } -/***/ }, -/* 48 */ -/***/ function(module, exports, __webpack_require__) { + var axis = this.dom.axis; + if (axis.parentNode) { + axis.parentNode.removeChild(axis); + } + }; /** - * This object contains all possible options. It will check if the types are correct, if required if the option is one - * of the allowed values. - * - * __any__ means that the name of the property does not matter. - * __type__ is a required field for all objects and contains the allowed types of all objects + * Add an item to the group + * @param {Item} item */ - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); - var string = 'string'; - var boolean = 'boolean'; - var number = 'number'; - var array = 'array'; - var date = 'date'; - var object = 'object'; // should only be in a __type__ property - var dom = 'dom'; - var moment = 'moment'; - var fn = 'function'; - var nada = 'null'; - var undef = 'undefined'; - var any = 'any'; - - var allOptions = { - configure: { - enabled: { boolean: boolean }, - filter: { boolean: boolean, fn: fn }, - container: { dom: dom }, - __type__: { object: object, boolean: boolean, fn: fn } - }, + Group.prototype.add = function (item) { + this.items[item.id] = item; + item.setParent(this); - //globals : - yAxisOrientation: { string: ['left', 'right'] }, - defaultGroup: { string: string }, - sort: { boolean: boolean }, - sampling: { boolean: boolean }, - stack: { boolean: boolean }, - graphHeight: { string: string, number: number }, - shaded: { - enabled: { boolean: boolean }, - orientation: { string: ['bottom', 'top'] }, // top, bottom - __type__: { boolean: boolean, object: object } - }, - style: { string: ['line', 'bar', 'points'] }, // line, bar - barChart: { - width: { number: number }, - sideBySide: { boolean: boolean }, - align: { string: ['left', 'center', 'right'] }, - __type__: { object: object } - }, - interpolation: { - enabled: { boolean: boolean }, - parametrization: { string: ['centripetal', 'chordal', 'uniform'] }, // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) - alpha: { number: number }, - __type__: { object: object, boolean: boolean } - }, - drawPoints: { - enabled: { boolean: boolean }, - size: { number: number }, - style: { string: ['square', 'circle'] }, // square, circle - __type__: { object: object, boolean: boolean } - }, - dataAxis: { - showMinorLabels: { boolean: boolean }, - showMajorLabels: { boolean: boolean }, - icons: { boolean: boolean }, - width: { string: string, number: number }, - visible: { boolean: boolean }, - alignZeros: { boolean: boolean }, - left: { - range: { min: { number: number }, max: { number: number }, __type__: { object: object } }, - format: { fn: fn }, - title: { text: { string: string, number: number }, style: { string: string }, __type__: { object: object } }, - __type__: { object: object } - }, - right: { - range: { min: { number: number }, max: { number: number }, __type__: { object: object } }, - format: { fn: fn }, - title: { text: { string: string, number: number }, style: { string: string }, __type__: { object: object } }, - __type__: { object: object } - }, - __type__: { object: object } - }, - legend: { - enabled: { boolean: boolean }, - icons: { boolean: boolean }, - left: { - visible: { boolean: boolean }, - position: { string: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] }, - __type__: { object: object } - }, - right: { - visible: { boolean: boolean }, - position: { string: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] }, - __type__: { object: object } - }, - __type__: { object: object, boolean: boolean } - }, - groups: { - visibility: { any: any }, - __type__: { object: object } - }, + // add to + if (item.data.subgroup !== undefined) { + if (this.subgroups[item.data.subgroup] === undefined) { + this.subgroups[item.data.subgroup] = { height: 0, visible: false, index: this.subgroupIndex, items: [] }; + this.subgroupIndex++; + } + this.subgroups[item.data.subgroup].items.push(item); + } + this.orderSubgroups(); - autoResize: { boolean: boolean }, - clickToUse: { boolean: boolean }, - end: { number: number, date: date, string: string, moment: moment }, - format: { - minorLabels: { - millisecond: { string: string, undef: undef }, - second: { string: string, undef: undef }, - minute: { string: string, undef: undef }, - hour: { string: string, undef: undef }, - weekday: { string: string, undef: undef }, - day: { string: string, undef: undef }, - month: { string: string, undef: undef }, - year: { string: string, undef: undef }, - __type__: { object: object } - }, - majorLabels: { - millisecond: { string: string, undef: undef }, - second: { string: string, undef: undef }, - minute: { string: string, undef: undef }, - hour: { string: string, undef: undef }, - weekday: { string: string, undef: undef }, - day: { string: string, undef: undef }, - month: { string: string, undef: undef }, - year: { string: string, undef: undef }, - __type__: { object: object } - }, - __type__: { object: object } - }, - height: { string: string, number: number }, - hiddenDates: { object: object, array: array }, - locale: { string: string }, - locales: { - __any__: { object: object }, - __type__: { object: object } - }, - max: { date: date, number: number, string: string, moment: moment }, - maxHeight: { number: number, string: string }, - min: { date: date, number: number, string: string, moment: moment }, - minHeight: { number: number, string: string }, - moveable: { boolean: boolean }, - multiselect: { boolean: boolean }, - orientation: { string: string }, - showCurrentTime: { boolean: boolean }, - showMajorLabels: { boolean: boolean }, - showMinorLabels: { boolean: boolean }, - start: { date: date, number: number, string: string, moment: moment }, - timeAxis: { - scale: { string: string, undef: undef }, - step: { number: number, undef: undef }, - __type__: { object: object } - }, - width: { string: string, number: number }, - zoomable: { boolean: boolean }, - zoomMax: { number: number }, - zoomMin: { number: number }, - __type__: { object: object } + 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); + } }; - var configureOptions = { - global: { - //yAxisOrientation: ['left','right'], // TDOO: enable as soon as Grahp2d doesn't crash when changing this on the fly - sort: true, - sampling: true, - stack: false, - shaded: { - enabled: false, - orientation: ['top', 'bottom'] // top, bottom - }, - style: ['line', 'bar', 'points'], // line, bar - barChart: { - width: [50, 5, 100, 5], - sideBySide: false, - align: ['left', 'center', 'right'] // left, center, right - }, - interpolation: { - enabled: true, - parametrization: ['centripetal', 'chordal', 'uniform'] // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) - }, - drawPoints: { - enabled: true, - size: [6, 2, 30, 1], - style: ['square', 'circle'] // square, circle - }, - dataAxis: { - showMinorLabels: true, - showMajorLabels: true, - icons: false, - width: [40, 0, 200, 1], - visible: true, - alignZeros: true, - left: { - //range: {min:undefined,max:undefined}, - //format: function (value) {return value;}, - title: { text: '', style: '' } - }, - right: { - //range: {min:undefined,max:undefined}, - //format: function (value) {return value;}, - title: { text: '', style: '' } + Group.prototype.orderSubgroups = function () { + if (this.subgroupOrderer !== undefined) { + var sortArray = []; + if (typeof this.subgroupOrderer == 'string') { + for (var subgroup in this.subgroups) { + sortArray.push({ subgroup: subgroup, sortField: this.subgroups[subgroup].items[0].data[this.subgroupOrderer] }); } - }, - legend: { - enabled: false, - icons: true, - left: { - visible: true, - position: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] // top/bottom - left,right - }, - right: { - visible: true, - position: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] // top/bottom - left,right + sortArray.sort(function (a, b) { + return a.sortField - b.sortField; + }); + } else if (typeof this.subgroupOrderer == 'function') { + for (var subgroup in this.subgroups) { + sortArray.push(this.subgroups[subgroup].items[0].data); } - }, + sortArray.sort(this.subgroupOrderer); + } - autoResize: true, - clickToUse: false, - end: '', - format: { - minorLabels: { - millisecond: 'SSS', - second: 's', - minute: 'HH:mm', - hour: 'HH:mm', - weekday: 'ddd D', - day: 'D', - 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', - month: 'YYYY', - year: '' + if (sortArray.length > 0) { + for (var i = 0; i < sortArray.length; i++) { + this.subgroups[sortArray[i].subgroup].index = i; } - }, - - height: '', - locale: '', - max: '', - maxHeight: '', - min: '', - minHeight: '', - moveable: true, - orientation: ['both', 'bottom', 'top'], - showCurrentTime: false, - showMajorLabels: true, - showMinorLabels: true, - start: '', - width: '100%', - zoomable: true, - zoomMax: [315360000000000, 10, 315360000000000, 1], - zoomMin: [10, 10, 315360000000000, 1] + } } }; - exports.allOptions = allOptions; - exports.configureOptions = configureOptions; + Group.prototype.resetSubgroups = function () { + for (var subgroup in this.subgroups) { + if (this.subgroups.hasOwnProperty(subgroup)) { + this.subgroups[subgroup].visible = false; + } + } + }; -/***/ }, -/* 49 */ -/***/ function(module, exports, __webpack_require__) { + /** + * Remove an item from the group + * @param {Item} item + */ + Group.prototype.remove = function (item) { + delete this.items[item.id]; + item.setParent(null); - 'use strict'; + // remove from visible items + var index = this.visibleItems.indexOf(item); + if (index != -1) this.visibleItems.splice(index, 1); - var Hammer = __webpack_require__(41); + // TODO: also remove from ordered items? + }; /** - * Register a touch event, taking place before a gesture - * @param {Hammer} hammer A hammer instance - * @param {function} callback Callback, called as callback(event) + * Remove an item from the corresponding DataSet + * @param {Item} item */ - exports.onTouch = function (hammer, callback) { - callback.inputHandler = function (event) { - if (event.isFirst && !isTouching) { - callback(event); - - isTouching = true; - setTimeout(function () { - isTouching = false; - }, 0); - } - }; - - hammer.on('hammer.input', callback.inputHandler); + Group.prototype.removeFromDataSet = function (item) { + this.itemSet.removeItem(item.id); }; - // isTouching is true while a touch action is being emitted - // this is a hack to prevent `touch` from being fired twice - var isTouching = false; - /** - * Register a release event, taking place after a gesture - * @param {Hammer} hammer A hammer instance - * @param {function} callback Callback, called as callback(event) + * Reorder the items */ - exports.onRelease = function (hammer, callback) { - callback.inputHandler = function (event) { - if (event.isFinal && !isReleasing) { - callback(event); + Group.prototype.order = function () { + var array = util.toArray(this.items); + var startArray = []; + var endArray = []; - isReleasing = true; - setTimeout(function () { - isReleasing = false; - }, 0); + 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 }; - return hammer.on('hammer.input', callback.inputHandler); - }; - - // isReleasing is true while a release action is being emitted - // this is a hack to prevent `release` from being fired twice - var isReleasing = false; - - /** - * 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); + stack.orderByStart(this.orderedItems.byStart); + stack.orderByEnd(this.orderedItems.byEnd); }; /** - * Unregister a release event, taking place before a gesture - * @param {Hammer} hammer A hammer instance - * @param {function} callback Callback, called as callback(event) + * Update the visible items + * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date + * @param {Item[]} visibleItems The previously visible items. + * @param {{start: number, end: number}} range Visible range + * @return {Item[]} visibleItems The new visible items. + * @private */ - exports.offRelease = exports.offTouch; - -/***/ }, -/* 50 */ -/***/ function(module, exports, __webpack_require__) { - - // English - 'use strict'; - - exports['en'] = { - current: 'current', - time: 'time' - }; - exports['en_EN'] = exports['en']; - exports['en_US'] = exports['en']; + Group.prototype._updateVisibleItems = 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; + var item, i; - // Dutch - exports['nl'] = { - current: 'huidige', - time: 'tijd' - }; - exports['nl_NL'] = exports['nl']; - exports['nl_BE'] = exports['nl']; + // 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; + } + }; -/***/ }, -/* 51 */ -/***/ function(module, exports, __webpack_require__) { + // 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 (i = 0; i < oldVisibleItems.length; i++) { + this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range); + } + } - 'use strict'; + // we do a binary search for the items that have only start values. + var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data', 'start'); - var DOMutil = __webpack_require__(3); - var Points = __webpack_require__(53); + // 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; + }); - function Line(groupId, options) { - this.groupId = groupId; - this.options = options; - } + // 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'); - Line.prototype.getData = function (groupData) { - var combinedData = []; - for (var j = 0; j < groupData.length; j++) { - combinedData.push({ - x: groupData[j].x, - y: groupData[j].y, - groupId: this.groupId + // 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; }); } - return combinedData; - }; - Line.prototype.getYRange = function (groupData) { - var yMin = groupData[0].y; - var yMax = groupData[0].y; - for (var j = 0; j < groupData.length; j++) { - yMin = yMin > groupData[j].y ? groupData[j].y : yMin; - yMax = yMax < groupData[j].y ? groupData[j].y : yMax; + // finally, we reposition all the visible items. + for (i = 0; i < visibleItems.length; i++) { + item = visibleItems[i]; + if (!item.displayed) item.show(); + // reposition item horizontally + item.repositionX(); } - return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation }; - }; - Line.getStackedYRange = function (combinedData, groupRanges, groupIds, groupLabel, orientation) { - if (combinedData.length > 0) { - // sort by time and by group - combinedData.sort(function (a, b) { - if (a.x === b.x) { - return a.groupId < b.groupId ? -1 : 1; - } else { - return a.x - b.x; - } - }); - var intersections = {}; + // debug + //console.log("new line") + //if (this.groupId == null) { + // for (i = 0; i < orderedItems.byStart.length; i++) { + // item = orderedItems.byStart[i].data; + // console.log('start',i,initialPosByStart, item.start.valueOf(), item.content, item.start >= lowerBound && item.start <= upperBound,i == initialPosByStart ? "<------------------- HEREEEE" : "") + // } + // for (i = 0; i < orderedItems.byEnd.length; i++) { + // item = orderedItems.byEnd[i].data; + // console.log('rangeEnd',i,initialPosByEnd, item.end.valueOf(), item.content, item.end >= range.start && item.end <= range.end,i == initialPosByEnd ? "<------------------- HEREEEE" : "") + // } + //} - Line._getDataIntersections(intersections, combinedData); - groupRanges[groupLabel] = Line._getStackedYRange(intersections, combinedData); - groupRanges[groupLabel].yAxisOrientation = orientation; - groupIds.push(groupLabel); - } + return visibleItems; }; - Line._getStackedYRange = function (intersections, combinedData) { - var key; - var yMin = combinedData[0].y; - var yMax = combinedData[0].y; - for (var i = 0; i < combinedData.length; i++) { - key = combinedData[i].x; - if (intersections[key] === undefined) { - yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin; - yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax; - } else { - if (combinedData[i].y < 0) { - intersections[key].accumulatedNegative += combinedData[i].y; + Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) { + var item; + var i; + + if (initialPos != -1) { + for (i = initialPos; i >= 0; i--) { + item = items[i]; + if (breakCondition(item)) { + break; } else { - intersections[key].accumulatedPositive += combinedData[i].y; + if (visibleItemsLookup[item.id] === undefined) { + visibleItemsLookup[item.id] = true; + visibleItems.push(item); + } } } - } - for (var xpos in intersections) { - if (intersections.hasOwnProperty(xpos)) { - yMin = yMin > intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMin; - yMin = yMin > intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMin; - yMax = yMax < intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMax; - yMax = yMax < intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMax; + + 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); + } + } } } - - return { min: yMin, max: yMax }; }; /** - * Fill the intersections object with counters of how many datapoints share the same x coordinates - * @param intersections - * @param combinedData + * 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 */ - Line._getDataIntersections = function (intersections, combinedData) { - // get intersections - var coreDistance; - for (var i = 0; i < combinedData.length; i++) { - if (i + 1 < combinedData.length) { - coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x); - } - if (i > 0) { - coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x)); - } - if (coreDistance === 0) { - if (intersections[combinedData[i].x] === undefined) { - intersections[combinedData[i].x] = { amount: 0, resolved: 0, accumulatedPositive: 0, accumulatedNegative: 0 }; - } - intersections[combinedData[i].x].amount += 1; - } + 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(); } }; /** - * draw a line graph + * 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 dataset - * @param group + * @param {Item} item + * @param {Array} visibleItems + * @param {{start:number, end:number}} range + * @private */ - Line.prototype.draw = function (dataset, group, framework) { - if (dataset != null) { - if (dataset.length > 0) { - var path, d; - var svgHeight = Number(framework.svg.style.height.replace('px', '')); - path = DOMutil.getSVGElement('path', framework.svgElements, framework.svg); - path.setAttributeNS(null, 'class', group.className); - if (group.style !== undefined) { - path.setAttributeNS(null, 'style', group.style); - } - - // construct path from dataset - if (group.options.interpolation.enabled == true) { - d = Line._catmullRom(dataset, group); - } else { - d = Line._linear(dataset); - } - - // append with points for fill and finalize the path - if (group.options.shaded.enabled == true) { - var fillPath = DOMutil.getSVGElement('path', framework.svgElements, framework.svg); - var dFill; - if (group.options.shaded.orientation == 'top') { - dFill = 'M' + dataset[0].x + ',' + 0 + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + 0; - } else { - dFill = 'M' + dataset[0].x + ',' + svgHeight + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + svgHeight; - } - fillPath.setAttributeNS(null, 'class', group.className + ' vis-fill'); - if (group.options.shaded.style !== undefined) { - fillPath.setAttributeNS(null, 'style', group.options.shaded.style); - } - fillPath.setAttributeNS(null, 'd', dFill); - } - // copy properties to path for drawing. - path.setAttributeNS(null, 'd', 'M' + d); - - // draw points - if (group.options.drawPoints.enabled == true) { - Points.draw(dataset, group, framework); - } + 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(); } }; - /** - * This uses an uniform parametrization of the interpolation algorithm: - * 'On the Parameterization of Catmull-Rom Curves' by Cem Yuksel et al. - * @param data - * @returns {string} - * @private - */ - Line._catmullRomUniform = function (data) { - // catmull rom - var p0, p1, p2, p3, bp1, bp2; - var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' '; - var normalization = 1 / 6; - var length = data.length; - for (var i = 0; i < length - 1; i++) { - - p0 = i == 0 ? data[0] : data[i - 1]; - p1 = data[i]; - p2 = data[i + 1]; - p3 = i + 2 < length ? data[i + 2] : p2; + module.exports = Group; - // Catmull-Rom to Cubic Bezier conversion matrix - // 0 1 0 0 - // -1/6 1 1/6 0 - // 0 1/6 1 -1/6 - // 0 0 1 0 +/***/ }, +/* 35 */ +/***/ function(module, exports, __webpack_require__) { - // bp0 = { x: p1.x, y: p1.y }; - bp1 = { x: (-p0.x + 6 * p1.x + p2.x) * normalization, y: (-p0.y + 6 * p1.y + p2.y) * normalization }; - bp2 = { x: (p1.x + 6 * p2.x - p3.x) * normalization, y: (p1.y + 6 * p2.y - p3.y) * normalization }; - // bp0 = { x: p2.x, y: p2.y }; + // Utility functions for ordering and stacking of items + 'use strict'; - d += 'C' + bp1.x + ',' + bp1.y + ' ' + bp2.x + ',' + bp2.y + ' ' + p2.x + ',' + p2.y + ' '; - } + var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors - return d; + /** + * Order items by their start data + * @param {Item[]} items + */ + exports.orderByStart = function (items) { + items.sort(function (a, b) { + return a.data.start - b.data.start; + }); }; /** - * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm. - * By default, the centripetal parameterization is used because this gives the nicest results. - * These parameterizations are relatively heavy because the distance between 4 points have to be calculated. - * - * One optimization can be used to reuse distances since this is a sliding window approach. - * @param data - * @param group - * @returns {string} - * @private + * Order items by their end date. If they have no end date, their start date + * is used. + * @param {Item[]} items */ - Line._catmullRom = function (data, group) { - var alpha = group.options.interpolation.alpha; - if (alpha == 0 || alpha === undefined) { - return this._catmullRomUniform(data); - } else { - var p0, p1, p2, p3, bp1, bp2, d1, d2, d3, A, B, N, M; - var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA; - var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' '; - var length = data.length; - for (var i = 0; i < length - 1; i++) { - - p0 = i == 0 ? data[0] : data[i - 1]; - p1 = data[i]; - p2 = data[i + 1]; - p3 = i + 2 < length ? data[i + 2] : p2; - - d1 = Math.sqrt(Math.pow(p0.x - p1.x, 2) + Math.pow(p0.y - p1.y, 2)); - d2 = Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2)); - d3 = Math.sqrt(Math.pow(p2.x - p3.x, 2) + Math.pow(p2.y - p3.y, 2)); - - // Catmull-Rom to Cubic Bezier conversion matrix - - // A = 2d1^2a + 3d1^a * d2^a + d3^2a - // B = 2d3^2a + 3d3^a * d2^a + d2^2a + exports.orderByEnd = function (items) { + items.sort(function (a, b) { + var aTime = 'end' in a.data ? a.data.end : a.data.start, + bTime = 'end' in b.data ? b.data.end : b.data.start; - // [ 0 1 0 0 ] - // [ -d2^2a /N A/N d1^2a /N 0 ] - // [ 0 d3^2a /M B/M -d2^2a /M ] - // [ 0 0 1 0 ] + return aTime - bTime; + }); + }; - d3powA = Math.pow(d3, alpha); - d3pow2A = Math.pow(d3, 2 * alpha); - d2powA = Math.pow(d2, alpha); - d2pow2A = Math.pow(d2, 2 * alpha); - d1powA = Math.pow(d1, alpha); - d1pow2A = Math.pow(d1, 2 * alpha); + /** + * Adjust vertical positions of the items such that they don't overlap each + * other. + * @param {Item[]} items + * All visible items + * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin + * Margins between items and between items and the axis. + * @param {boolean} [force=false] + * If true, all items will be repositioned. If false (default), only + * items having a top===null will be re-stacked + */ + exports.stack = function (items, margin, force) { + var i, iMax; - A = 2 * d1pow2A + 3 * d1powA * d2powA + d2pow2A; - B = 2 * d3pow2A + 3 * d3powA * d2powA + d2pow2A; - N = 3 * d1powA * (d1powA + d2powA); - if (N > 0) { - N = 1 / N; - } - M = 3 * d3powA * (d3powA + d2powA); - if (M > 0) { - M = 1 / M; - } + if (force) { + // reset top position of all items + for (i = 0, iMax = items.length; i < iMax; i++) { + items[i].top = null; + } + } - bp1 = { x: (-d2pow2A * p0.x + A * p1.x + d1pow2A * p2.x) * N, - y: (-d2pow2A * p0.y + A * p1.y + d1pow2A * p2.y) * N }; + // calculate new, non-overlapping positions + for (i = 0, iMax = items.length; i < iMax; i++) { + var item = items[i]; + if (item.stack && item.top === null) { + // initialize top position + item.top = margin.axis; - bp2 = { x: (d3pow2A * p1.x + B * p2.x - d2pow2A * p3.x) * M, - y: (d3pow2A * p1.y + B * p2.y - d2pow2A * p3.y) * M }; + do { + // TODO: optimize checking for overlap. when there is a gap without items, + // you only need to check for items from the next item on, not from zero + var collidingItem = null; + for (var j = 0, jj = items.length; j < jj; j++) { + var other = items[j]; + if (other.top !== null && other !== item && other.stack && exports.collision(item, other, margin.item)) { + collidingItem = other; + break; + } + } - if (bp1.x == 0 && bp1.y == 0) { - bp1 = p1; - } - if (bp2.x == 0 && bp2.y == 0) { - bp2 = p2; - } - d += 'C' + bp1.x + ',' + bp1.y + ' ' + bp2.x + ',' + bp2.y + ' ' + p2.x + ',' + p2.y + ' '; + if (collidingItem != null) { + // There is a collision. Reposition the items above the colliding element + item.top = collidingItem.top + collidingItem.height + margin.item.vertical; + } + } while (collidingItem); } - - return d; } }; /** - * this generates the SVG path for a linear drawing between datapoints. - * @param data - * @returns {string} - * @private + * Adjust vertical positions of the items without stacking them + * @param {Item[]} items + * All visible items + * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin + * Margins between items and between items and the axis. */ - Line._linear = function (data) { - // linear - var d = ''; - for (var i = 0; i < data.length; i++) { - if (i == 0) { - d += data[i].x + ',' + data[i].y; + exports.nostack = function (items, margin, subgroups) { + var i, iMax, newTop; + + // reset top position of all items + for (i = 0, iMax = items.length; i < iMax; i++) { + if (items[i].data.subgroup !== undefined) { + newTop = margin.axis; + for (var subgroup in subgroups) { + if (subgroups.hasOwnProperty(subgroup)) { + if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroups[items[i].data.subgroup].index) { + newTop += subgroups[subgroup].height + margin.item.vertical; + } + } + } + items[i].top = newTop; } else { - d += ' ' + data[i].x + ',' + data[i].y; + items[i].top = margin.axis; } } - return d; }; - module.exports = Line; + /** + * Test if the two provided items collide + * The items must have parameters left, width, top, and height. + * @param {Item} a The first item + * @param {Item} b The second item + * @param {{horizontal: number, vertical: number}} margin + * An object containing a horizontal and vertical + * minimum required margin. + * @return {boolean} true if a and b collide, else false + */ + exports.collision = function (a, b, margin) { + return a.left - margin.horizontal + EPSILON < b.left + b.width && a.left + a.width + margin.horizontal - EPSILON > b.left && a.top - margin.vertical + EPSILON < b.top + b.height && a.top + a.height + margin.vertical - EPSILON > b.top; + }; /***/ }, -/* 52 */ +/* 36 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var DOMutil = __webpack_require__(3); - var Points = __webpack_require__(53); + var Hammer = __webpack_require__(3); + var Item = __webpack_require__(2); - function Bargraph(groupId, options) { - this.groupId = groupId; - this.options = options; - } + /** + * @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 - Bargraph.prototype.getYRange = function (groupData) { - var yMin = groupData[0].y; - var yMax = groupData[0].y; - for (var j = 0; j < groupData.length; j++) { - yMin = yMin > groupData[j].y ? groupData[j].y : yMin; - yMax = yMax < groupData[j].y ? groupData[j].y : yMax; + // 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); + } } - return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation }; - }; - Bargraph.prototype.getData = function (groupData) { - var combinedData = []; - for (var j = 0; j < groupData.length; j++) { - combinedData.push({ - x: groupData[j].x, - y: groupData[j].y, - groupId: this.groupId - }); - } - return combinedData; + 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 + * @returns {{start: Number, end: Number}} 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; }; /** - * draw a bar graph - * - * @param groupIds - * @param processedGroupData + * Repaint the item */ - Bargraph.draw = function (groupIds, processedGroupData, framework) { - var combinedData = []; - var intersections = {}; - var coreDistance; - var key, drawData; - var group; - var i, j; - var barPoints = 0; + RangeItem.prototype.redraw = function () { + var dom = this.dom; + if (!dom) { + // create DOM + this.dom = {}; + dom = this.dom; - // combine all barchart data - for (i = 0; i < groupIds.length; i++) { - group = framework.groups[groupIds[i]]; - if (group.options.style === 'bar') { - if (group.visible === true && (framework.options.groups.visibility[groupIds[i]] === undefined || framework.options.groups.visibility[groupIds[i]] === true)) { - for (j = 0; j < processedGroupData[groupIds[i]].length; j++) { - combinedData.push({ - x: processedGroupData[groupIds[i]][j].x, - y: processedGroupData[groupIds[i]][j].y, - groupId: groupIds[i], - label: processedGroupData[groupIds[i]][j].label - }); - barPoints += 1; - } - } - } - } + // background box + dom.box = document.createElement('div'); + // className is updated in redraw() - if (barPoints === 0) { - return; + // frame box (to prevent the item contents from overflowing + dom.frame = document.createElement('div'); + dom.frame.className = 'vis-item-overflow'; + dom.box.appendChild(dom.frame); + + // contents box + dom.content = document.createElement('div'); + dom.content.className = 'vis-item-content'; + dom.frame.appendChild(dom.content); + + // attach this item as attribute + dom.box['timeline-item'] = this; + + this.dirty = true; } - // sort by time and by group - combinedData.sort(function (a, b) { - if (a.x === b.x) { - return a.groupId < b.groupId ? -1 : 1; - } else { - return a.x - b.x; + // append DOM to parent DOM + if (!this.parent) { + throw new Error('Cannot redraw item: no parent attached'); + } + if (!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(dom.box); + } + this.displayed = true; - // get intersections - Bargraph._getDataIntersections(intersections, combinedData); + // Update DOM when item is marked dirty. 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._updateTitle(this.dom.box); + this._updateDataAttributes(this.dom.box); + this._updateStyle(this.dom.box); - // plot barchart - for (i = 0; i < combinedData.length; i++) { - group = framework.groups[combinedData[i].groupId]; - var minWidth = 0.1 * group.options.barChart.width; + // update class + var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); + dom.box.className = this.baseClassName + className; - key = combinedData[i].x; - var heightOffset = 0; - if (intersections[key] === undefined) { - if (i + 1 < combinedData.length) { - coreDistance = Math.abs(combinedData[i + 1].x - key); - } - if (i > 0) { - coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - key)); - } - drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth); - } else { - var nextKey = i + (intersections[key].amount - intersections[key].resolved); - var prevKey = i - (intersections[key].resolved + 1); - if (nextKey < combinedData.length) { - coreDistance = Math.abs(combinedData[nextKey].x - key); - } - if (prevKey > 0) { - coreDistance = Math.min(coreDistance, Math.abs(combinedData[prevKey].x - key)); - } - drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth); - intersections[key].resolved += 1; + // determine from css whether this box has overflow + this.overflow = window.getComputedStyle(dom.frame).overflow !== 'hidden'; - if (group.options.stack === true) { - if (combinedData[i].y < group.zeroPosition) { - heightOffset = intersections[key].accumulatedNegative; - intersections[key].accumulatedNegative += group.zeroPosition - combinedData[i].y; - } else { - heightOffset = intersections[key].accumulatedPositive; - intersections[key].accumulatedPositive += group.zeroPosition - combinedData[i].y; - } - } else if (group.options.barChart.sideBySide === true) { - drawData.width = drawData.width / intersections[key].amount; - drawData.offset += intersections[key].resolved * drawData.width - 0.5 * drawData.width * (intersections[key].amount + 1); - if (group.options.barChart.align === 'left') { - drawData.offset -= 0.5 * drawData.width; - } else if (group.options.barChart.align === 'right') { - drawData.offset += 0.5 * drawData.width; - } - } - } - DOMutil.drawBar(combinedData[i].x + drawData.offset, combinedData[i].y - heightOffset, drawData.width, group.zeroPosition - combinedData[i].y, group.className + ' vis-bar', framework.svgElements, framework.svg, group.style); - // draw points - if (group.options.drawPoints.enabled === true) { - Points.draw([combinedData[i]], group, framework, drawData.offset); - //DOMutil.drawPoint(combinedData[i].x + drawData.offset, combinedData[i].y, group, framework.svgElements, framework.svg); - } + // recalculate size + // 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'; + this.props.content.width = this.dom.content.offsetWidth; + this.height = this.dom.box.offsetHeight; + this.dom.content.style.maxWidth = ''; + + this.dirty = false; } + + this._repaintDeleteButton(dom.box); + this._repaintDragLeft(); + this._repaintDragRight(); }; /** - * Fill the intersections object with counters of how many datapoints share the same x coordinates - * @param intersections - * @param combinedData - * @private + * Show the item in the DOM (when not already visible). The items DOM will + * be created when needed. */ - Bargraph._getDataIntersections = function (intersections, combinedData) { - // get intersections - var coreDistance; - for (var i = 0; i < combinedData.length; i++) { - if (i + 1 < combinedData.length) { - coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x); - } - if (i > 0) { - coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x)); - } - if (coreDistance === 0) { - if (intersections[combinedData[i].x] === undefined) { - intersections[combinedData[i].x] = { amount: 0, resolved: 0, accumulatedPositive: 0, accumulatedNegative: 0 }; - } - intersections[combinedData[i].x].amount += 1; - } + RangeItem.prototype.show = function () { + if (!this.displayed) { + this.redraw(); } }; /** - * Get the width and offset for bargraphs based on the coredistance between datapoints - * - * @param coreDistance - * @param group - * @param minWidth - * @returns {{width: Number, offset: Number}} - * @private + * Hide the item from the DOM (when visible) + * @return {Boolean} changed */ - Bargraph._getSafeDrawData = function (coreDistance, group, minWidth) { - var width, offset; - if (coreDistance < group.options.barChart.width && coreDistance > 0) { - width = coreDistance < minWidth ? minWidth : coreDistance; + RangeItem.prototype.hide = function () { + if (this.displayed) { + var box = this.dom.box; - offset = 0; // recalculate offset with the new width; - if (group.options.barChart.align === 'left') { - offset -= 0.5 * coreDistance; - } else if (group.options.barChart.align === 'right') { - offset += 0.5 * coreDistance; - } - } else { - // default settings - width = group.options.barChart.width; - offset = 0; - if (group.options.barChart.align === 'left') { - offset -= 0.5 * group.options.barChart.width; - } else if (group.options.barChart.align === 'right') { - offset += 0.5 * group.options.barChart.width; + if (box.parentNode) { + box.parentNode.removeChild(box); } - } - - return { width: width, offset: offset }; - }; - - Bargraph.getStackedYRange = function (combinedData, groupRanges, groupIds, groupLabel, orientation) { - if (combinedData.length > 0) { - // sort by time and by group - combinedData.sort(function (a, b) { - if (a.x === b.x) { - return a.groupId < b.groupId ? -1 : 1; - } else { - return a.x - b.x; - } - }); - var intersections = {}; - Bargraph._getDataIntersections(intersections, combinedData); - groupRanges[groupLabel] = Bargraph._getStackedYRange(intersections, combinedData); - groupRanges[groupLabel].yAxisOrientation = orientation; - groupIds.push(groupLabel); + this.displayed = false; } }; - Bargraph._getStackedYRange = function (intersections, combinedData) { - var key; - var yMin = combinedData[0].y; - var yMax = combinedData[0].y; - for (var i = 0; i < combinedData.length; i++) { - key = combinedData[i].x; - if (intersections[key] === undefined) { - yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin; - yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax; - } else { - if (combinedData[i].y < 0) { - intersections[key].accumulatedNegative += combinedData[i].y; - } else { - intersections[key].accumulatedPositive += combinedData[i].y; - } + /** + * 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 contentLeft; + var contentWidth; + + // limit the width of the range, as browsers cannot draw very wide divs + if (limitSize === undefined || limitSize === true) { + if (start < -parentWidth) { + start = -parentWidth; } - } - for (var xpos in intersections) { - if (intersections.hasOwnProperty(xpos)) { - yMin = yMin > intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMin; - yMin = yMin > intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMin; - yMax = yMax < intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMax; - yMax = yMax < intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMax; + if (end > 2 * parentWidth) { + end = 2 * parentWidth; } } + var boxWidth = Math.max(end - start, 1); - return { min: yMin, max: yMax }; - }; + if (this.overflow) { + this.left = start; + this.width = boxWidth + this.props.content.width; + contentWidth = this.props.content.width; - module.exports = Bargraph; + // 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 { + this.left = start; + this.width = boxWidth; + contentWidth = Math.min(end - start, this.props.content.width); + } -/***/ }, -/* 53 */ -/***/ function(module, exports, __webpack_require__) { + this.dom.box.style.left = this.left + 'px'; + this.dom.box.style.width = boxWidth + 'px'; - 'use strict'; + switch (this.options.align) { + case 'left': + this.dom.content.style.left = '0'; + break; - var DOMutil = __webpack_require__(3); + case 'right': + this.dom.content.style.left = Math.max(boxWidth - contentWidth, 0) + 'px'; + break; - function Points(groupId, options) { - this.groupId = groupId; - this.options = options; - } + case 'center': + this.dom.content.style.left = Math.max((boxWidth - contentWidth) / 2, 0) + 'px'; + break; - Points.prototype.getYRange = function (groupData) { - var yMin = groupData[0].y; - var yMax = groupData[0].y; - for (var j = 0; j < groupData.length; j++) { - yMin = yMin > groupData[j].y ? groupData[j].y : yMin; - yMax = yMax < groupData[j].y ? groupData[j].y : yMax; + 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) { + contentLeft = Math.max(-start, 0); + } else { + contentLeft = -contentWidth; // ensure it's not visible anymore + } + } else { + if (start < 0) { + contentLeft = -start; + } else { + contentLeft = 0; + } + } + this.dom.content.style.left = contentLeft + 'px'; } - return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation }; }; - Points.prototype.draw = function (dataset, group, framework, offset) { - Points.draw(dataset, group, framework, offset); + /** + * 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'; + } }; /** - * draw the data points - * - * @param {Array} dataset - * @param {Object} JSONcontainer - * @param {Object} svg | SVG DOM element - * @param {GraphGroup} group - * @param {Number} [offset] + * Repaint a drag area on the left side of the range when the range is selected + * @protected */ - Points.draw = function (dataset, group, framework, offset) { - if (offset === undefined) { - offset = 0; + RangeItem.prototype._repaintDragLeft = function () { + if (this.selected && 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.dom.dragLeft) { + // delete drag area + if (this.dom.dragLeft.parentNode) { + this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft); + } + this.dom.dragLeft = null; } - for (var i = 0; i < dataset.length; i++) { - DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, framework.svgElements, framework.svg, dataset[i].label); + }; + + /** + * 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.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.dom.dragRight) { + // delete drag area + if (this.dom.dragRight.parentNode) { + this.dom.dragRight.parentNode.removeChild(this.dom.dragRight); + } + this.dom.dragRight = null; } }; - module.exports = Points; + module.exports = RangeItem; /***/ }, -/* 54 */ +/* 37 */ /***/ function(module, exports, __webpack_require__) { - "use strict"; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + 'use strict'; - var util = __webpack_require__(2); + var moment = __webpack_require__(8); + var DateUtil = __webpack_require__(31); + var util = __webpack_require__(7); /** - * @class Groups - * This class can store groups and options specific for groups. - */ + * @constructor TimeStep + * 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 + */ + function TimeStep(start, end, minimumStep, hiddenDates) { + // variables + this.current = new Date(); + this._start = new Date(); + this._end = new Date(); - var Groups = (function () { - function Groups() { - _classCallCheck(this, Groups); + this.autoScale = true; + this.scale = 'day'; + this.step = 1; - this.clear(); - this.defaultIndex = 0; - this.groupsArray = []; - this.groupIndex = 0; + // initialize the range + this.setRange(start, end, minimumStep); - this.defaultGroups = [{ border: "#2B7CE9", background: "#97C2FC", highlight: { border: "#2B7CE9", background: "#D2E5FF" }, hover: { border: "#2B7CE9", background: "#D2E5FF" } }, // 0: blue - { border: "#FFA500", background: "#FFFF00", highlight: { border: "#FFA500", background: "#FFFFA3" }, hover: { border: "#FFA500", background: "#FFFFA3" } }, // 1: yellow - { border: "#FA0A10", background: "#FB7E81", highlight: { border: "#FA0A10", background: "#FFAFB1" }, hover: { border: "#FA0A10", background: "#FFAFB1" } }, // 2: red - { border: "#41A906", background: "#7BE141", highlight: { border: "#41A906", background: "#A1EC76" }, hover: { border: "#41A906", background: "#A1EC76" } }, // 3: green - { border: "#E129F0", background: "#EB7DF4", highlight: { border: "#E129F0", background: "#F0B3F5" }, hover: { border: "#E129F0", background: "#F0B3F5" } }, // 4: magenta - { border: "#7C29F0", background: "#AD85E4", highlight: { border: "#7C29F0", background: "#D3BDF0" }, hover: { border: "#7C29F0", background: "#D3BDF0" } }, // 5: purple - { border: "#C37F00", background: "#FFA807", highlight: { border: "#C37F00", background: "#FFCA66" }, hover: { border: "#C37F00", background: "#FFCA66" } }, // 6: orange - { border: "#4220FB", background: "#6E6EFD", highlight: { border: "#4220FB", background: "#9B9BFD" }, hover: { border: "#4220FB", background: "#9B9BFD" } }, // 7: darkblue - { border: "#FD5A77", background: "#FFC0CB", highlight: { border: "#FD5A77", background: "#FFD1D9" }, hover: { border: "#FD5A77", background: "#FFD1D9" } }, // 8: pink - { border: "#4AD63A", background: "#C2FABC", highlight: { border: "#4AD63A", background: "#E6FFE3" }, hover: { border: "#4AD63A", background: "#E6FFE3" } }, // 9: mint + // hidden Dates options + this.switchedDay = false; + this.switchedMonth = false; + this.switchedYear = false; + this.hiddenDates = hiddenDates; + if (hiddenDates === undefined) { + this.hiddenDates = []; + } - { border: "#990000", background: "#EE0000", highlight: { border: "#BB0000", background: "#FF3333" }, hover: { border: "#BB0000", background: "#FF3333" } }, // 10:bright red + this.format = TimeStep.FORMAT; // default formatting + } - { border: "#FF6000", background: "#FF6000", highlight: { border: "#FF6000", background: "#FF6000" }, hover: { border: "#FF6000", background: "#FF6000" } }, // 12: real orange - { border: "#97C2FC", background: "#2B7CE9", highlight: { border: "#D2E5FF", background: "#2B7CE9" }, hover: { border: "#D2E5FF", background: "#2B7CE9" } }, // 13: blue - { border: "#399605", background: "#255C03", highlight: { border: "#399605", background: "#255C03" }, hover: { border: "#399605", background: "#255C03" } }, // 14: green - { border: "#B70054", background: "#FF007E", highlight: { border: "#B70054", background: "#FF007E" }, hover: { border: "#B70054", background: "#FF007E" } }, // 15: magenta - { border: "#AD85E4", background: "#7C29F0", highlight: { border: "#D3BDF0", background: "#7C29F0" }, hover: { border: "#D3BDF0", background: "#7C29F0" } }, // 16: purple - { border: "#4557FA", background: "#000EA1", highlight: { border: "#6E6EFD", background: "#000EA1" }, hover: { border: "#6E6EFD", background: "#000EA1" } }, // 17: darkblue - { border: "#FFC0CB", background: "#FD5A77", highlight: { border: "#FFD1D9", background: "#FD5A77" }, hover: { border: "#FFD1D9", background: "#FD5A77" } }, // 18: pink - { border: "#C2FABC", background: "#74D66A", highlight: { border: "#E6FFE3", background: "#74D66A" }, hover: { border: "#E6FFE3", background: "#74D66A" } }, // 19: mint + // Time formatting + TimeStep.FORMAT = { + minorLabels: { + millisecond: 'SSS', + second: 's', + minute: 'HH:mm', + hour: 'HH:mm', + weekday: 'ddd D', + day: 'D', + 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', + month: 'YYYY', + year: '' + } + }; - { border: "#EE0000", background: "#990000", highlight: { border: "#FF3333", background: "#BB0000" }, hover: { border: "#FF3333", background: "#BB0000" } } // 20:bright red - ]; + /** + * 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', '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); + }; - this.options = {}; - this.defaultOptions = { - useDefaultGroups: true - }; - util.extend(this.options, this.defaultOptions); + /** + * 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'; } - _createClass(Groups, [{ - key: "setOptions", - value: function setOptions(options) { - var optionFields = ["useDefaultGroups"]; - - if (options !== undefined) { - for (var groupName in options) { - if (options.hasOwnProperty(groupName)) { - if (optionFields.indexOf(groupName) === -1) { - var group = options[groupName]; - this.add(groupName, group); - } - } - } - } - } - }, { - key: "clear", + this._start = start != undefined ? new Date(start.valueOf()) : new Date(); + this._end = end != undefined ? new Date(end.valueOf()) : new Date(); - /** - * Clear all groups - */ - value: function clear() { - this.groups = {}; - this.groupsArray = []; - } - }, { - key: "get", + if (this.autoScale) { + this.setMinimumStep(minimumStep); + } + }; - /** - * get group options of a groupname. If groupname is not found, a new group - * is added. - * @param {*} groupname Can be a number, string, Date, etc. - * @return {Object} group The created group, containing all group options - */ - value: function get(groupname) { - var group = this.groups[groupname]; - if (group === undefined) { - if (this.options.useDefaultGroups === false && this.groupsArray.length > 0) { - // create new group - var index = this.groupIndex % this.groupsArray.length; - this.groupIndex++; - group = {}; - group.color = this.groups[this.groupsArray[index]]; - this.groups[groupname] = group; - } else { - // create new group - var index = this.defaultIndex % this.defaultGroups.length; - this.defaultIndex++; - group = {}; - group.color = this.defaultGroups[index]; - this.groups[groupname] = group; - } - } + /** + * Set the range iterator to the start date. + */ + TimeStep.prototype.first = function () { + this.current = new Date(this._start.valueOf()); + this.roundToMinor(); + }; - return group; - } - }, { - key: "add", + /** + * 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 + // IMPORTANT: we have no breaks in this switch! (this is no bug) + // noinspection FallThroughInSwitchStatementJS + switch (this.scale) { + case 'year': + this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step)); + this.current.setMonth(0); + case 'month': + this.current.setDate(1); + case 'day': // intentional fall through + case 'weekday': + this.current.setHours(0); + case 'hour': + this.current.setMinutes(0); + case 'minute': + this.current.setSeconds(0); + case 'second': + this.current.setMilliseconds(0); + //case 'millisecond': // nothing to do for milliseconds + } - /** - * Add a custom group style - * @param {String} groupName - * @param {Object} style An object containing borderColor, - * backgroundColor, etc. - * @return {Object} group The created group object - */ - value: function add(groupName, style) { - this.groups[groupName] = style; - this.groupsArray.push(groupName); - return style; + 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.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step);break; + case 'second': + this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step);break; + case 'minute': + this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step);break; + case 'hour': + this.current.setHours(this.current.getHours() - this.current.getHours() % this.step);break; + case 'weekday': // intentional fall through + case 'day': + this.current.setDate(this.current.getDate() - 1 - (this.current.getDate() - 1) % this.step + 1);break; + case 'month': + this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step);break; + case 'year': + this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step);break; + default: + break; } - }]); + } + }; - return Groups; - })(); + /** + * 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(); + }; - exports["default"] = Groups; - module.exports = exports["default"]; + /** + * Do the next step + */ + TimeStep.prototype.next = function () { + var prev = this.current.valueOf(); -/***/ }, -/* 55 */ -/***/ function(module, exports, __webpack_require__) { + // Two cases, needed to prevent issues with switching daylight savings + // (end of March and end of October) + if (this.current.getMonth() < 6) { + switch (this.scale) { + case 'millisecond': - 'use strict'; + this.current = new Date(this.current.valueOf() + this.step);break; + case 'second': + this.current = new Date(this.current.valueOf() + this.step * 1000);break; + case 'minute': + this.current = new Date(this.current.valueOf() + this.step * 1000 * 60);break; + case 'hour': + this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60); + // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...) + var h = this.current.getHours(); + this.current.setHours(h - h % this.step); + break; + case 'weekday': // intentional fall through + case 'day': + this.current.setDate(this.current.getDate() + this.step);break; + case 'month': + this.current.setMonth(this.current.getMonth() + this.step);break; + case 'year': + this.current.setFullYear(this.current.getFullYear() + this.step);break; + default: + break; + } + } else { + switch (this.scale) { + case 'millisecond': + this.current = new Date(this.current.valueOf() + this.step);break; + case 'second': + this.current.setSeconds(this.current.getSeconds() + this.step);break; + case 'minute': + this.current.setMinutes(this.current.getMinutes() + this.step);break; + case 'hour': + this.current.setHours(this.current.getHours() + this.step);break; + case 'weekday': // intentional fall through + case 'day': + this.current.setDate(this.current.getDate() + this.step);break; + case 'month': + this.current.setMonth(this.current.getMonth() + this.step);break; + case 'year': + this.current.setFullYear(this.current.getFullYear() + this.step);break; + default: + break; + } + } - Object.defineProperty(exports, '__esModule', { - value: true - }); + if (this.step != 1) { + // round down to the correct major value + switch (this.scale) { + case 'millisecond': + if (this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0);break; + case 'second': + if (this.current.getSeconds() < this.step) this.current.setSeconds(0);break; + case 'minute': + if (this.current.getMinutes() < this.step) this.current.setMinutes(0);break; + case 'hour': + if (this.current.getHours() < this.step) this.current.setHours(0);break; + case 'weekday': // intentional fall through + case 'day': + if (this.current.getDate() < this.step + 1) this.current.setDate(1);break; + case 'month': + if (this.current.getMonth() < this.step) this.current.setMonth(0);break; + case 'year': + break; // nothing to do for year + default: + break; + } + } - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // safety mechanism: if current time is still unchanged, move to the end + if (this.current.valueOf() == prev) { + this.current = new Date(this._end.valueOf()); + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + DateUtil.stepOverHiddenDates(this, prev); + }; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * Get the current datetime + * @return {Date} current The current date + */ + TimeStep.prototype.getCurrent = function () { + return this.current; + }; - var _componentsNode = __webpack_require__(74); + /** + * 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', '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; + } + }; - var _componentsNode2 = _interopRequireDefault(_componentsNode); + /** + * Enable or disable autoscaling + * @param {boolean} enable If true, autoascaling is set true + */ + TimeStep.prototype.setAutoScale = function (enable) { + this.autoScale = enable; + }; - var _componentsSharedLabel = __webpack_require__(75); + /** + * 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 _componentsSharedLabel2 = _interopRequireDefault(_componentsSharedLabel); + //var b = asc + ds; - var util = __webpack_require__(2); - var DataSet = __webpack_require__(4); - var DataView = __webpack_require__(5); + 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; - var NodesHandler = (function () { - function NodesHandler(body, images, groups, layoutEngine) { - var _this = this; + // 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; + } + }; - _classCallCheck(this, NodesHandler); + /** + * 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', 'month', 'year'. + * @param {number} step Current step (1, 2, 4, 5, ... + * @return {Date} snappedDate + */ + TimeStep.snap = function (date, scale, step) { + var clone = new Date(date.valueOf()); - this.body = body; - this.images = images; - this.groups = groups; - this.layoutEngine = layoutEngine; - - // create the node API in the body container - this.body.functions.createNode = this.create.bind(this); + if (scale == 'year') { + var year = clone.getFullYear() + Math.round(clone.getMonth() / 12); + clone.setFullYear(Math.round(year / step) * step); + clone.setMonth(0); + clone.setDate(0); + clone.setHours(0); + clone.setMinutes(0); + clone.setSeconds(0); + clone.setMilliseconds(0); + } else if (scale == 'month') { + if (clone.getDate() > 15) { + clone.setDate(1); + clone.setMonth(clone.getMonth() + 1); + // important: first set Date to 1, after that change the month. + } else { + clone.setDate(1); + } - this.nodesListeners = { - add: function add(event, params) { - _this.add(params.items); - }, - update: function update(event, params) { - _this.update(params.items, params.data); - }, - remove: function remove(event, params) { - _this.remove(params.items); - } - }; + clone.setHours(0); + clone.setMinutes(0); + clone.setSeconds(0); + clone.setMilliseconds(0); + } else if (scale == 'day') { + //noinspection FallthroughInSwitchStatementJS + switch (step) { + case 5: + case 2: + clone.setHours(Math.round(clone.getHours() / 24) * 24);break; + default: + clone.setHours(Math.round(clone.getHours() / 12) * 12);break; + } + clone.setMinutes(0); + clone.setSeconds(0); + clone.setMilliseconds(0); + } else if (scale == 'weekday') { + //noinspection FallthroughInSwitchStatementJS + switch (step) { + case 5: + case 2: + clone.setHours(Math.round(clone.getHours() / 12) * 12);break; + default: + clone.setHours(Math.round(clone.getHours() / 6) * 6);break; + } + clone.setMinutes(0); + clone.setSeconds(0); + clone.setMilliseconds(0); + } else if (scale == 'hour') { + switch (step) { + case 4: + clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60);break; + default: + clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30);break; + } + clone.setSeconds(0); + clone.setMilliseconds(0); + } else if (scale == 'minute') { + //noinspection FallthroughInSwitchStatementJS + switch (step) { + case 15: + case 10: + clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5); + clone.setSeconds(0); + break; + case 5: + clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60);break; + default: + clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30);break; + } + clone.setMilliseconds(0); + } else if (scale == 'second') { + //noinspection FallthroughInSwitchStatementJS + switch (step) { + case 15: + case 10: + clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5); + clone.setMilliseconds(0); + break; + case 5: + clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000);break; + default: + clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500);break; + } + } else if (scale == 'millisecond') { + var _step = step > 5 ? step / 2 : 1; + clone.setMilliseconds(Math.round(clone.getMilliseconds() / _step) * _step); + } - this.options = {}; - this.defaultOptions = { - borderWidth: 1, - borderWidthSelected: 2, - brokenImage: undefined, - color: { - border: '#2B7CE9', - background: '#97C2FC', - highlight: { - border: '#2B7CE9', - background: '#D2E5FF' - }, - hover: { - border: '#2B7CE9', - background: '#D2E5FF' - } - }, - fixed: { - x: false, - y: false - }, - font: { - color: '#343434', - size: 14, // px - face: 'arial', - background: 'none', - strokeWidth: 0, // px - strokeColor: '#ffffff', - align: 'horizontal' - }, - group: undefined, - hidden: false, - icon: { - face: 'FontAwesome', //'FontAwesome', - code: undefined, //'\uf007', - size: 50, //50, - color: '#2B7CE9' //'#aa00ff' - }, - image: undefined, // --> URL - label: undefined, - level: undefined, - mass: 1, - physics: true, - scaling: { - min: 10, - max: 30, - label: { - enabled: false, - min: 14, - max: 30, - maxVisible: 30, - drawThreshold: 5 - }, - customScalingFunction: function customScalingFunction(min, max, total, value) { - if (max === min) { - return 0.5; - } else { - var scale = 1 / (max - min); - return Math.max(0, (value - min) * scale); - } - } - }, - shadow: { - enabled: false, - size: 10, - x: 5, - y: 5 - }, - shape: 'ellipse', - size: 25, - title: undefined, - value: undefined, - x: undefined, - y: undefined - }; - util.extend(this.options, this.defaultOptions); + return clone; + }; - this.bindEventListeners(); + /** + * 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) { + this.switchedYear = false; + switch (this.scale) { + case 'year': + case 'month': + case 'weekday': + case 'day': + case 'hour': + case 'minute': + case 'second': + case 'millisecond': + return true; + default: + return false; + } + } else if (this.switchedMonth == true) { + this.switchedMonth = false; + switch (this.scale) { + case 'weekday': + case 'day': + case 'hour': + case 'minute': + case 'second': + case 'millisecond': + return true; + default: + return false; + } + } else if (this.switchedDay == true) { + this.switchedDay = false; + switch (this.scale) { + case 'millisecond': + case 'second': + case 'minute': + case 'hour': + return true; + default: + return false; + } } - _createClass(NodesHandler, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this2 = this; + switch (this.scale) { + case 'millisecond': + return this.current.getMilliseconds() == 0; + case 'second': + return this.current.getSeconds() == 0; + case 'minute': + return this.current.getHours() == 0 && this.current.getMinutes() == 0; + case 'hour': + return this.current.getHours() == 0; + case 'weekday': // intentional fall through + case 'day': + return this.current.getDate() == 1; + case 'month': + return this.current.getMonth() == 0; + case 'year': + return false; + default: + return false; + } + }; - // refresh the nodes. Used when reverting from hierarchical layout - this.body.emitter.on('refreshNodes', this.refresh.bind(this)); - this.body.emitter.on('refresh', this.refresh.bind(this)); - this.body.emitter.on('destroy', function () { - delete _this2.body.functions.createNode; - delete _this2.nodesListeners.add; - delete _this2.nodesListeners.update; - delete _this2.nodesListeners.remove; - delete _this2.nodesListeners; - }); - } - }, { - key: 'setOptions', - value: function setOptions(options) { - if (options !== undefined) { - _componentsNode2['default'].parseOptions(this.options, options); + /** + * 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] custom date. if not provided, current date is taken + */ + TimeStep.prototype.getLabelMinor = function (date) { + if (date == undefined) { + date = this.current; + } - // update the shape in all nodes - if (options.shape !== undefined) { - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - this.body.nodes[nodeId].updateShape(); - } - } - } + var format = this.format.minorLabels[this.scale]; + return format && format.length > 0 ? moment(date).format(format) : ''; + }; - // update the shape size in all nodes - if (options.font !== undefined) { - _componentsSharedLabel2['default'].parseOptions(this.options.font, options); - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - this.body.nodes[nodeId].updateLabelModule(); - this.body.nodes[nodeId]._reset(); - } - } - } + /** + * 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] custom date. if not provided, current date is taken + */ + TimeStep.prototype.getLabelMajor = function (date) { + if (date == undefined) { + date = this.current; + } - // update the shape size in all nodes - if (options.size !== undefined) { - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - this.body.nodes[nodeId]._reset(); - } - } - } + var format = this.format.majorLabels[this.scale]; + return format && format.length > 0 ? moment(date).format(format) : ''; + }; - // update the state of the letiables if needed - if (options.hidden !== undefined || options.physics !== undefined) { - this.body.emitter.emit('_dataChanged'); - } - } - } - }, { - key: 'setData', + TimeStep.prototype.getClassName = function () { + var m = moment(this.current); + var date = m.locale ? m.locale('en') : m.lang('en'); // old versions of moment have .lang() function + var step = this.step; - /** - * Set a data set with nodes for the network - * @param {Array | DataSet | DataView} nodes The data containing the nodes. - * @private - */ - value: function setData(nodes) { - var _this3 = this; + function even(value) { + return value / step % 2 == 0 ? ' vis-even' : ' vis-odd'; + } - var doNotEmit = arguments[1] === undefined ? false : arguments[1]; + 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 ''; + } - var oldNodesData = this.body.data.nodes; + function currentWeek(date) { + return date.isSame(new Date(), 'week') ? ' vis-current-week' : ''; + } - if (nodes instanceof DataSet || nodes instanceof DataView) { - this.body.data.nodes = nodes; - } else if (Array.isArray(nodes)) { - this.body.data.nodes = new DataSet(); - this.body.data.nodes.add(nodes); - } else if (!nodes) { - this.body.data.nodes = new DataSet(); - } else { - throw new TypeError('Array or DataSet expected'); - } + function currentMonth(date) { + return date.isSame(new Date(), 'month') ? ' vis-current-month' : ''; + } - if (oldNodesData) { - // unsubscribe from old dataset - util.forEach(this.nodesListeners, function (callback, event) { - oldNodesData.off(event, callback); - }); - } + function currentYear(date) { + return date.isSame(new Date(), 'year') ? ' vis-current-year' : ''; + } - // remove drawn nodes - this.body.nodes = {}; + switch (this.scale) { + case 'millisecond': + return even(date.milliseconds()).trim(); - if (this.body.data.nodes) { - (function () { - // subscribe to new dataset - var me = _this3; - util.forEach(_this3.nodesListeners, function (callback, event) { - me.body.data.nodes.on(event, callback); - }); + case 'second': + return even(date.seconds()).trim(); - // draw all new nodes - var ids = _this3.body.data.nodes.getIds(); - _this3.add(ids, true); - })(); - } + case 'minute': + return even(date.minutes()).trim(); - if (doNotEmit === false) { - this.body.emitter.emit('_dataChanged'); + case 'hour': + var hours = date.hours(); + if (this.step == 4) { + hours = hours + '-h' + (hours + 4); } - } - }, { - key: 'add', + return 'vis-h' + hours + today(date) + even(date.hours()); - /** - * Add nodes - * @param {Number[] | String[]} ids - * @private - */ - value: function add(ids) { - var doNotEmit = arguments[1] === undefined ? false : arguments[1]; + case 'weekday': + return 'vis-' + date.format('dddd').toLowerCase() + today(date) + currentWeek(date) + even(date.date()); - var id = undefined; - var newNodes = []; - for (var i = 0; i < ids.length; i++) { - id = ids[i]; - var _properties = this.body.data.nodes.get(id); - var node = this.create(_properties); - newNodes.push(node); - this.body.nodes[id] = node; // note: this may replace an existing node - } + case 'day': + var day = date.date(); + var month = date.format('MMMM').toLowerCase(); + return 'vis-day' + day + ' vis-' + month + currentMonth(date) + even(day - 1); - this.layoutEngine.positionInitially(newNodes); + case 'month': + return 'vis-' + date.format('MMMM').toLowerCase() + currentMonth(date) + even(date.month()); - if (doNotEmit === false) { - this.body.emitter.emit('_dataChanged'); - } - } - }, { - key: 'update', + case 'year': + var year = date.year(); + return 'vis-year' + year + currentYear(date) + even(year); - /** - * Update existing nodes, or create them when not yet existing - * @param {Number[] | String[]} ids - * @private - */ - value: function update(ids, changedData) { - var nodes = this.body.nodes; - var dataChanged = false; - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; - var node = nodes[id]; - var data = changedData[i]; - if (node !== undefined) { - // update node - dataChanged = node.setOptions(data); - } else { - dataChanged = true; - // create node - node = this.create(properties); - nodes[id] = node; - } - } + default: + return ''; + } + }; - if (dataChanged === true) { - this.body.emitter.emit('_dataChanged'); - } else { - this.body.emitter.emit('_dataUpdated'); - } - } - }, { - key: 'remove', + module.exports = TimeStep; - /** - * Remove existing nodes. If nodes do not exist, the method will just ignore it. - * @param {Number[] | String[]} ids - * @private - */ - value: function remove(ids) { - var nodes = this.body.nodes; +/***/ }, +/* 38 */ +/***/ function(module, exports, __webpack_require__) { - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; - delete nodes[id]; - } + 'use strict'; - this.body.emitter.emit('_dataChanged'); - } - }, { - key: 'create', + var util = __webpack_require__(7); + var Group = __webpack_require__(34); - /** - * create a node - * @param properties - * @param constructorClass - */ - value: function create(properties) { - var constructorClass = arguments[1] === undefined ? _componentsNode2['default'] : arguments[1]; + /** + * @constructor BackgroundGroup + * @param {Number | String} groupId + * @param {Object} data + * @param {ItemSet} itemSet + */ + function BackgroundGroup(groupId, data, itemSet) { + Group.call(this, groupId, data, itemSet); - return new constructorClass(properties, this.body, this.images, this.groups, this.options); - } - }, { - key: 'refresh', - value: function refresh() { - var nodes = this.body.nodes; - for (var nodeId in nodes) { - var node = undefined; - if (nodes.hasOwnProperty(nodeId)) { - node = nodes[nodeId]; - } - var data = this.body.data.nodes._data[nodeId]; - if (node !== undefined && data !== undefined) { - node.setOptions({ fixed: false }); - node.setOptions(data); - } - } - } - }, { - key: 'getPositions', + this.width = 0; + this.height = 0; + this.top = 0; + this.left = 0; + } - /** - * Returns the positions of the nodes. - * @param ids --> optional, can be array of nodeIds, can be string - * @returns {{}} - */ - value: function getPositions(ids) { - var dataArray = {}; - if (ids !== undefined) { - if (Array.isArray(ids) === true) { - for (var i = 0; i < ids.length; i++) { - if (this.body.nodes[ids[i]] !== undefined) { - var node = this.body.nodes[ids[i]]; - dataArray[ids[i]] = { x: Math.round(node.x), y: Math.round(node.y) }; - } - } - } else { - if (this.body.nodes[ids] !== undefined) { - var node = this.body.nodes[ids]; - dataArray[ids] = { x: Math.round(node.x), y: Math.round(node.y) }; - } - } - } else { - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - var node = this.body.nodes[nodeId]; - dataArray[nodeId] = { x: Math.round(node.x), y: Math.round(node.y) }; - } - } - } - return dataArray; - } - }, { - key: 'storePositions', + BackgroundGroup.prototype = Object.create(Group.prototype); - /** - * Load the XY positions of the nodes into the dataset. - */ - value: function storePositions() { - // todo: add support for clusters and hierarchical. - var dataArray = []; - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - var node = this.body.nodes[nodeId]; - if (this.body.data.nodes._data[nodeId].x != Math.round(node.x) || this.body.data.nodes._data[nodeId].y != Math.round(node.y)) { - dataArray.push({ id: nodeId, x: Math.round(node.x), y: Math.round(node.y) }); - } - } - } - this.body.data.nodes.update(dataArray); - } - }, { - key: 'getBoundingBox', + /** + * Repaint this group + * @param {{start: number, end: number}} range + * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin + * @param {boolean} [restack=false] Force restacking of all items + * @return {boolean} Returns true if the group is resized + */ + BackgroundGroup.prototype.redraw = function (range, margin, restack) { + var resized = false; - /** - * get the bounding box of a node. - * @param nodeId - * @returns {j|*} - */ - value: function getBoundingBox(nodeId) { - if (this.body.nodes[nodeId] !== undefined) { - return this.body.nodes[nodeId].shape.boundingBox; - } - } - }, { - key: 'getConnectedNodes', + this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); - /** - * Get the Ids of nodes connected to this node. - * @param nodeId - * @returns {Array} - */ - value: function getConnectedNodes(nodeId) { - var nodeList = []; - if (this.body.nodes[nodeId] !== undefined) { - var node = this.body.nodes[nodeId]; - var nodeObj = {}; // used to quickly check if node already exists - for (var i = 0; i < node.edges.length; i++) { - var edge = node.edges[i]; - if (edge.toId == nodeId) { - // these are double equals since ids can be numeric or string - if (nodeObj[edge.fromId] === undefined) { - nodeList.push(edge.fromId); - nodeObj[edge.fromId] = true; - } - } else if (edge.fromId == nodeId) { - // these are double equals since ids can be numeric or string - if (nodeObj[edge.toId] === undefined) { - nodeList.push(edge.toId); - nodeObj[edge.toId] = true; - } - } - } - } - return nodeList; - } - }, { - key: 'getConnectedEdges', + // calculate actual size + this.width = this.dom.background.offsetWidth; - /** - * Get the ids of the edges connected to this node. - * @param nodeId - * @returns {*} - */ - value: function getConnectedEdges(nodeId) { - var edgeList = []; - if (this.body.nodes[nodeId] !== undefined) { - var node = this.body.nodes[nodeId]; - for (var i = 0; i < node.edges.length; i++) { - edgeList.push(node.edges[i].id); - } - } else { - console.log('NodeId provided for getConnectedEdges does not exist. Provided: ', nodeId); - } - return edgeList; - } - }]); + // apply new height (just always zero for BackgroundGroup + this.dom.background.style.height = '0'; - return NodesHandler; - })(); + // 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); + } - exports['default'] = NodesHandler; - module.exports = exports['default']; + 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; /***/ }, -/* 56 */ +/* 39 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); + var Item = __webpack_require__(2); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + /** + * @constructor PointItem + * @extends Item + * @param {Object} data Object containing parameters start + * content, 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 PointItem(data, conversion, options) { + this.props = { + dot: { + top: 0, + width: 0, + height: 0 + }, + content: { + height: 0, + marginLeft: 0 + } + }; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + // validate data + if (data) { + if (data.start == undefined) { + throw new Error('Property "start" missing in item ' + data); + } + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + Item.call(this, data, conversion, options); + } - var _componentsEdge = __webpack_require__(76); + PointItem.prototype = new Item(null, null, null); - var _componentsEdge2 = _interopRequireDefault(_componentsEdge); + /** + * Check whether this item is visible inside given range + * @returns {{start: Number, end: Number}} range with a timestamp for start and end + * @returns {boolean} True if visible + */ + PointItem.prototype.isVisible = function (range) { + // determine visibility + // TODO: account for the real width of the item. Right now we just add 1/4 to the window + var interval = (range.end - range.start) / 4; + return this.data.start > range.start - interval && this.data.start < range.end + interval; + }; - var _componentsSharedLabel = __webpack_require__(75); + /** + * Repaint the item + */ + PointItem.prototype.redraw = function () { + var dom = this.dom; + if (!dom) { + // create DOM + this.dom = {}; + dom = this.dom; - var _componentsSharedLabel2 = _interopRequireDefault(_componentsSharedLabel); + // background box + dom.point = document.createElement('div'); + // className is updated in redraw() - var util = __webpack_require__(2); - var DataSet = __webpack_require__(4); - var DataView = __webpack_require__(5); + // contents box, right from the dot + dom.content = document.createElement('div'); + dom.content.className = 'vis-item-content'; + dom.point.appendChild(dom.content); - var EdgesHandler = (function () { - function EdgesHandler(body, images, groups) { - var _this = this; + // dot at start + dom.dot = document.createElement('div'); + dom.point.appendChild(dom.dot); - _classCallCheck(this, EdgesHandler); + // attach this item as attribute + dom.point['timeline-item'] = this; - this.body = body; - this.images = images; - this.groups = groups; + this.dirty = true; + } - // create the edge API in the body container - this.body.functions.createEdge = this.create.bind(this); + // append DOM to parent DOM + if (!this.parent) { + throw new Error('Cannot redraw item: no parent attached'); + } + if (!dom.point.parentNode) { + var foreground = this.parent.dom.foreground; + if (!foreground) { + throw new Error('Cannot redraw item: parent has no foreground container element'); + } + foreground.appendChild(dom.point); + } + this.displayed = true; - this.edgesListeners = { - add: function add(event, params) { - _this.add(params.items); - }, - update: function update(event, params) { - _this.update(params.items); - }, - remove: function remove(event, params) { - _this.remove(params.items); - } - }; + // Update DOM when item is marked dirty. 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._updateTitle(this.dom.point); + this._updateDataAttributes(this.dom.point); + this._updateStyle(this.dom.point); - this.options = {}; - this.defaultOptions = { - arrows: { - to: { enabled: false, scaleFactor: 1 }, // boolean / {arrowScaleFactor:1} / {enabled: false, arrowScaleFactor:1} - middle: { enabled: false, scaleFactor: 1 }, - from: { enabled: false, scaleFactor: 1 } - }, - color: { - color: '#848484', - highlight: '#848484', - hover: '#848484', - inherit: 'from', - opacity: 1 - }, - dashes: false, - font: { - color: '#343434', - size: 14, // px - face: 'arial', - background: 'none', - strokeWidth: 2, // px - strokeColor: '#ffffff', - align: 'horizontal' - }, - hidden: false, - hoverWidth: 1.5, - label: undefined, - length: undefined, - physics: true, - scaling: { - min: 1, - max: 15, - label: { - enabled: true, - min: 14, - max: 30, - maxVisible: 30, - drawThreshold: 5 - }, - customScalingFunction: function customScalingFunction(min, max, total, value) { - if (max === min) { - return 0.5; - } else { - var scale = 1 / (max - min); - return Math.max(0, (value - min) * scale); - } - } - }, - selectionWidth: 1.5, - selfReferenceSize: 20, - shadow: { - enabled: false, - size: 10, - x: 5, - y: 5 - }, - smooth: { - enabled: true, - type: 'dynamic', - roundness: 0.5 - }, - title: undefined, - width: 1, - value: undefined - }; + // update class + var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); + dom.point.className = 'vis-item vis-point' + className; + dom.dot.className = 'vis-item vis-dot' + className; - util.extend(this.options, this.defaultOptions); + // recalculate size + this.width = dom.point.offsetWidth; + this.height = dom.point.offsetHeight; + this.props.dot.width = dom.dot.offsetWidth; + this.props.dot.height = dom.dot.offsetHeight; + this.props.content.height = dom.content.offsetHeight; - this.bindEventListeners(); - } + // resize contents + dom.content.style.marginLeft = 2 * this.props.dot.width + 'px'; + //dom.content.style.marginRight = ... + 'px'; // TODO: margin right - _createClass(EdgesHandler, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this2 = this; + dom.dot.style.top = (this.height - this.props.dot.height) / 2 + 'px'; + dom.dot.style.left = this.props.dot.width / 2 + 'px'; - // this allows external modules to force all dynamic curves to turn static. - this.body.emitter.on('_forceDisableDynamicCurves', function (type) { - if (type === 'dynamic') { - type = 'continuous'; - } - var emitChange = false; - for (var edgeId in _this2.body.edges) { - if (_this2.body.edges.hasOwnProperty(edgeId)) { - var edge = _this2.body.edges[edgeId]; - var edgeData = _this2.body.data.edges._data[edgeId]; + this.dirty = false; + } - // only forcilby remove the smooth curve if the data has been set of the edge has the smooth curves defined. - // this is because a change in the global would not affect these curves. - if (edgeData !== undefined) { - var edgeOptions = edgeData.smooth; - if (edgeOptions !== undefined) { - if (edgeOptions.enabled === true && edgeOptions.type === 'dynamic') { - if (type === undefined) { - edge.setOptions({ smooth: false }); - } else { - edge.setOptions({ smooth: { type: type } }); - } - emitChange = true; - } - } - } - } - } - if (emitChange === true) { - _this2.body.emitter.emit('_dataChanged'); - } - }); + this._repaintDeleteButton(dom.point); + }; - // this is called when options of EXISTING nodes or edges have changed. - this.body.emitter.on('_dataUpdated', function () { - _this2.reconnectEdges(); - _this2.markAllEdgesAsDirty(); - }); + /** + * Show the item in the DOM (when not already visible). The items DOM will + * be created when needed. + */ + PointItem.prototype.show = function () { + if (!this.displayed) { + this.redraw(); + } + }; - // refresh the edges. Used when reverting from hierarchical layout - this.body.emitter.on('refreshEdges', this.refresh.bind(this)); - this.body.emitter.on('refresh', this.refresh.bind(this)); - this.body.emitter.on('destroy', function () { - delete _this2.body.functions.createEdge; - delete _this2.edgesListeners.add; - delete _this2.edgesListeners.update; - delete _this2.edgesListeners.remove; - delete _this2.edgesListeners; - }); + /** + * Hide the item from the DOM (when visible) + */ + PointItem.prototype.hide = function () { + if (this.displayed) { + if (this.dom.point.parentNode) { + this.dom.point.parentNode.removeChild(this.dom.point); } - }, { - key: 'setOptions', - value: function setOptions(options) { - if (options !== undefined) { - // use the parser from the Edge class to fill in all shorthand notations - _componentsEdge2['default'].parseOptions(this.options, options); - // hanlde multiple input cases for color - if (options.color !== undefined) { - this.markAllEdgesAsDirty(); - } - - // update smooth settings in all edges - var dataChanged = false; - if (options.smooth !== undefined) { - for (var edgeId in this.body.edges) { - if (this.body.edges.hasOwnProperty(edgeId)) { - dataChanged = this.body.edges[edgeId].updateEdgeType() || dataChanged; - } - } - } - - // update fonts in all edges - if (options.font !== undefined) { - // use the parser from the Label class to fill in all shorthand notations - _componentsSharedLabel2['default'].parseOptions(this.options, options); - for (var edgeId in this.body.edges) { - if (this.body.edges.hasOwnProperty(edgeId)) { - this.body.edges[edgeId].updateLabelModule(); - } - } - } + this.displayed = false; + } + }; - // update the state of the variables if needed - if (options.hidden !== undefined || options.physics !== undefined || dataChanged === true) { - this.body.emitter.emit('_dataChanged'); - } - } - } - }, { - key: 'setData', + /** + * Reposition the item horizontally + * @Override + */ + PointItem.prototype.repositionX = function () { + var start = this.conversion.toScreen(this.data.start); - /** - * Load edges by reading the data table - * @param {Array | DataSet | DataView} edges The data containing the edges. - * @private - * @private - */ - value: function setData(edges) { - var _this3 = this; + this.left = start - this.props.dot.width; - var doNotEmit = arguments[1] === undefined ? false : arguments[1]; + // reposition point + this.dom.point.style.left = this.left + 'px'; + }; - var oldEdgesData = this.body.data.edges; + /** + * Reposition the item vertically + * @Override + */ + PointItem.prototype.repositionY = function () { + var orientation = this.options.orientation.item; + var point = this.dom.point; - if (edges instanceof DataSet || edges instanceof DataView) { - this.body.data.edges = edges; - } else if (Array.isArray(edges)) { - this.body.data.edges = new DataSet(); - this.body.data.edges.add(edges); - } else if (!edges) { - this.body.data.edges = new DataSet(); - } else { - throw new TypeError('Array or DataSet expected'); - } - - // TODO: is this null or undefined or false? - if (oldEdgesData) { - // unsubscribe from old dataset - util.forEach(this.edgesListeners, function (callback, event) { - oldEdgesData.off(event, callback); - }); - } - - // remove drawn edges - this.body.edges = {}; - - // TODO: is this null or undefined or false? - if (this.body.data.edges) { - // subscribe to new dataset - util.forEach(this.edgesListeners, function (callback, event) { - _this3.body.data.edges.on(event, callback); - }); - - // draw all new nodes - var ids = this.body.data.edges.getIds(); - this.add(ids, true); - } - - if (doNotEmit === false) { - this.body.emitter.emit('_dataChanged'); - } - } - }, { - key: 'add', - - /** - * Add edges - * @param {Number[] | String[]} ids - * @private - */ - value: function add(ids) { - var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - - var edges = this.body.edges; - var edgesData = this.body.data.edges; - - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; - - var oldEdge = edges[id]; - if (oldEdge) { - oldEdge.disconnect(); - } - - var data = edgesData.get(id, { 'showInternalIds': true }); - edges[id] = this.create(data); - } - - if (doNotEmit === false) { - this.body.emitter.emit('_dataChanged'); - } - } - }, { - key: 'update', - - /** - * Update existing edges, or create them when not yet existing - * @param {Number[] | String[]} ids - * @private - */ - value: function update(ids) { - var edges = this.body.edges; - var edgesData = this.body.data.edges; - var dataChanged = false; - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; - var data = edgesData.get(id); - var edge = edges[id]; - if (edge === null) { - // update edge - edge.disconnect(); - dataChanged = edge.setOptions(data) || dataChanged; // if a support node is added, data can be changed. - edge.connect(); - } else { - // create edge - this.body.edges[id] = this.create(data); - dataChanged = true; - } - } - - if (dataChanged === true) { - this.body.emitter.emit('_dataChanged'); - } else { - this.body.emitter.emit('_dataUpdated'); - } - } - }, { - key: 'remove', - - /** - * Remove existing edges. Non existing ids will be ignored - * @param {Number[] | String[]} ids - * @private - */ - value: function remove(ids) { - var edges = this.body.edges; - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; - var edge = edges[id]; - if (edge !== undefined) { - if (edge.via != null) { - delete this.body.supportNodes[edge.via.id]; - } - edge.disconnect(); - delete edges[id]; - } - } - - this.body.emitter.emit('_dataChanged'); - } - }, { - key: 'refresh', - value: function refresh() { - var edges = this.body.edges; - for (var edgeId in edges) { - var edge = undefined; - if (edges.hasOwnProperty(edgeId)) { - edge = edges[edgeId]; - } - var data = this.body.data.edges._data[edgeId]; - if (edge !== undefined && data !== undefined) { - edge.setOptions(data); - } - } - } - }, { - key: 'create', - value: function create(properties) { - return new _componentsEdge2['default'](properties, this.body, this.options); - } - }, { - key: 'markAllEdgesAsDirty', - value: function markAllEdgesAsDirty() { - for (var edgeId in this.body.edges) { - this.body.edges[edgeId].edgeType.colorDirty = true; - } - } - }, { - key: 'reconnectEdges', - - /** - * Reconnect all edges - * @private - */ - value: function reconnectEdges() { - var id; - var nodes = this.body.nodes; - var edges = this.body.edges; - - for (id in nodes) { - if (nodes.hasOwnProperty(id)) { - nodes[id].edges = []; - } - } - - for (id in edges) { - if (edges.hasOwnProperty(id)) { - var edge = edges[id]; - edge.from = null; - edge.to = null; - edge.connect(); - } - } - } - }, { - key: 'getConnectedNodes', - value: function getConnectedNodes(edgeId) { - var nodeList = []; - if (this.body.edges[edgeId] !== undefined) { - var edge = this.body.edges[edgeId]; - if (edge.fromId) { - nodeList.push(edge.fromId); - } - if (edge.toId) { - nodeList.push(edge.toId); - } - } - return nodeList; - } - }]); - - return EdgesHandler; - })(); + if (orientation == 'top') { + point.style.top = this.top + 'px'; + } else { + point.style.top = this.parent.height - this.top - this.height + 'px'; + } + }; - exports['default'] = EdgesHandler; - module.exports = exports['default']; + module.exports = PointItem; /***/ }, -/* 57 */ +/* 40 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Item = __webpack_require__(21); - var util = __webpack_require__(2); + var Hammer = __webpack_require__(3); + var Item = __webpack_require__(2); + var BackgroundGroup = __webpack_require__(38); + var RangeItem = __webpack_require__(36); /** - * @constructor BoxItem + * @constructor BackgroundItem * @extends Item - * @param {Object} data Object containing parameters start + * @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 available options + * // TODO: describe options */ - function BoxItem(data, conversion, options) { + // TODO: implement support for the BackgroundItem just having a start, then being displayed as a sort of an annotation + function BackgroundItem(data, conversion, options) { this.props = { - dot: { - width: 0, - height: 0 - }, - line: { - width: 0, - height: 0 + content: { + width: 0 } }; + this.overflow = false; // if contents can overflow (css styling), this flag is set to true // validate data if (data) { if (data.start == undefined) { - throw new Error('Property "start" missing in item ' + data); + 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); } - BoxItem.prototype = new Item(null, null, null); + BackgroundItem.prototype = new Item(null, null, null); + + BackgroundItem.prototype.baseClassName = 'vis-item vis-background'; + BackgroundItem.prototype.stack = false; /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ - BoxItem.prototype.isVisible = function (range) { + BackgroundItem.prototype.isVisible = function (range) { // determine visibility - // TODO: account for the real width of the item. Right now we just add 1/4 to the window - var interval = (range.end - range.start) / 4; - return this.data.start > range.start - interval && this.data.start < range.end + interval; + return this.data.start < range.end && this.data.end > range.start; }; /** * Repaint the item */ - BoxItem.prototype.redraw = function () { + BackgroundItem.prototype.redraw = function () { var dom = this.dom; if (!dom) { // create DOM this.dom = {}; dom = this.dom; - // create main box - dom.box = document.createElement('DIV'); - - // contents box (inside the background box). used for making margins - dom.content = document.createElement('DIV'); - dom.content.className = 'vis-item-content'; - dom.box.appendChild(dom.content); + // background box + dom.box = document.createElement('div'); + // className is updated in redraw() - // line to axis - dom.line = document.createElement('DIV'); - dom.line.className = 'vis-line'; + // frame box (to prevent the item contents from overflowing + dom.frame = document.createElement('div'); + dom.frame.className = 'vis-item-overflow'; + dom.box.appendChild(dom.frame); - // dot on axis - dom.dot = document.createElement('DIV'); - dom.dot.className = 'vis-dot'; + // contents box + dom.content = document.createElement('div'); + dom.content.className = 'vis-item-content'; + dom.frame.appendChild(dom.content); - // attach this item as attribute - dom.box['timeline-item'] = this; + // Note: we do NOT attach this item as attribute to the DOM, + // such that background items cannot be selected + //dom.box['timeline-item'] = this; this.dirty = true; } @@ -22386,19 +19603,11 @@ return /******/ (function(modules) { // webpackBootstrap throw new Error('Cannot redraw item: no parent attached'); } if (!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(dom.box); - } - if (!dom.line.parentNode) { var background = this.parent.dom.background; - if (!background) throw new Error('Cannot redraw item: parent has no background container element'); - background.appendChild(dom.line); - } - if (!dom.dot.parentNode) { - var axis = this.parent.dom.axis; - if (!background) throw new Error('Cannot redraw item: parent has no axis container element'); - axis.appendChild(dom.dot); + if (!background) { + throw new Error('Cannot redraw item: parent has no background container element'); + } + background.appendChild(dom.box); } this.displayed = true; @@ -22408,13372 +19617,14597 @@ return /******/ (function(modules) { // webpackBootstrap // - the item is selected/deselected if (this.dirty) { this._updateContents(this.dom.content); - this._updateTitle(this.dom.box); - this._updateDataAttributes(this.dom.box); + this._updateTitle(this.dom.content); + this._updateDataAttributes(this.dom.content); this._updateStyle(this.dom.box); // update class var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : ''); - dom.box.className = 'vis-item vis-box' + className; - dom.line.className = 'vis-item vis-line' + className; - dom.dot.className = 'vis-item vis-dot' + className; + dom.box.className = this.baseClassName + className; + + // determine from css whether this box has overflow + this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden'; // recalculate size - this.props.dot.height = dom.dot.offsetHeight; - this.props.dot.width = dom.dot.offsetWidth; - this.props.line.width = dom.line.offsetWidth; - this.width = dom.box.offsetWidth; - this.height = dom.box.offsetHeight; + this.props.content.width = this.dom.content.offsetWidth; + this.height = 0; // set height zero, so this item will be ignored when stacking items this.dirty = false; } - - this._repaintDeleteButton(dom.box); }; /** - * Show the item in the DOM (when not already displayed). The items DOM will + * Show the item in the DOM (when not already visible). The items DOM will * be created when needed. */ - BoxItem.prototype.show = function () { - if (!this.displayed) { - this.redraw(); - } - }; + BackgroundItem.prototype.show = RangeItem.prototype.show; /** * Hide the item from the DOM (when visible) + * @return {Boolean} changed */ - BoxItem.prototype.hide = function () { - if (this.displayed) { - var dom = this.dom; - - if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box); - if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line); - if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot); - - this.displayed = false; - } - }; + BackgroundItem.prototype.hide = RangeItem.prototype.hide; /** * Reposition the item horizontally * @Override */ - BoxItem.prototype.repositionX = function () { - var start = this.conversion.toScreen(this.data.start); - var align = this.options.align; - var left; - - // calculate left position of the box - if (align == 'right') { - this.left = start - this.width; - } else if (align == 'left') { - this.left = start; - } else { - // default or 'center' - this.left = start - this.width / 2; - } - - // reposition box - this.dom.box.style.left = this.left + 'px'; - - // reposition line - this.dom.line.style.left = start - this.props.line.width / 2 + 'px'; - - // reposition dot - this.dom.dot.style.left = start - this.props.dot.width / 2 + 'px'; - }; + BackgroundItem.prototype.repositionX = RangeItem.prototype.repositionX; /** * Reposition the item vertically * @Override */ - BoxItem.prototype.repositionY = function () { - var orientation = this.options.orientation.item; - var box = this.dom.box; - var line = this.dom.line; - var dot = this.dom.dot; + BackgroundItem.prototype.repositionY = function (margin) { + var onTop = this.options.orientation.item === 'top'; + this.dom.content.style.top = onTop ? '' : '0'; + this.dom.content.style.bottom = onTop ? '0' : ''; + var height; - if (orientation == 'top') { - box.style.top = (this.top || 0) + 'px'; + // special positioning for subgroups + if (this.data.subgroup !== undefined) { + // TODO: instead of calculating the top position of the subgroups here for every BackgroundItem, calculate the top of the subgroup once in Itemset - line.style.top = '0'; - line.style.height = this.parent.top + this.top + 1 + 'px'; - line.style.bottom = ''; - } else { - // orientation 'bottom' - var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty - var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top; + var itemSubgroup = this.data.subgroup; + var subgroups = this.parent.subgroups; + var subgroupIndex = subgroups[itemSubgroup].index; + // if the orientation is top, we need to take the difference in height into account. + if (onTop == true) { + // the first subgroup will have to account for the distance from the top to the first item. + height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical; + height += subgroupIndex == 0 ? margin.axis - 0.5 * margin.item.vertical : 0; + var newTop = this.parent.top; + for (var subgroup in subgroups) { + if (subgroups.hasOwnProperty(subgroup)) { + if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroupIndex) { + newTop += subgroups[subgroup].height + margin.item.vertical; + } + } + } - box.style.top = (this.parent.height - this.top - this.height || 0) + 'px'; - line.style.top = itemSetHeight - lineHeight + 'px'; - line.style.bottom = '0'; + // the others will have to be offset downwards with this same distance. + newTop += subgroupIndex != 0 ? margin.axis - 0.5 * margin.item.vertical : 0; + this.dom.box.style.top = newTop + 'px'; + this.dom.box.style.bottom = ''; + } + // and when the orientation is bottom: + else { + var newTop = this.parent.top; + var totalHeight = 0; + for (var subgroup in subgroups) { + if (subgroups.hasOwnProperty(subgroup)) { + if (subgroups[subgroup].visible == true) { + var newHeight = subgroups[subgroup].height + margin.item.vertical; + totalHeight += newHeight; + if (subgroups[subgroup].index > subgroupIndex) { + newTop += newHeight; + } + } + } + } + height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical; + this.dom.box.style.top = this.parent.height - totalHeight + newTop + 'px'; + this.dom.box.style.bottom = ''; + } } - - dot.style.top = -this.props.dot.height / 2 + 'px'; + // and in the case of no subgroups: + else { + // we want backgrounds with groups to only show in groups. + if (this.parent instanceof BackgroundGroup) { + // if the item is not in a group: + height = Math.max(this.parent.height, this.parent.itemSet.body.domProps.center.height, this.parent.itemSet.body.domProps.centerContainer.height); + this.dom.box.style.top = onTop ? '0' : ''; + this.dom.box.style.bottom = onTop ? '' : '0'; + } else { + height = this.parent.height; + // same alignment for items when orientation is top or bottom + this.dom.box.style.top = this.parent.top + 'px'; + this.dom.box.style.bottom = ''; + } + } + this.dom.box.style.height = height + 'px'; }; - module.exports = BoxItem; + module.exports = BackgroundItem; /***/ }, -/* 58 */ +/* 41 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var util = __webpack_require__(7); + var Component = __webpack_require__(27); + var TimeStep = __webpack_require__(37); + var DateUtil = __webpack_require__(31); + var moment = __webpack_require__(8); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + /** + * 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 + }; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + this.defaultOptions = { + orientation: { + axis: 'bottom' + }, // axis orientation: 'top' or 'bottom' + showMinorLabels: true, + showMajorLabels: true, + format: TimeStep.FORMAT, + timeAxis: null + }; + this.options = util.extend({}, this.defaultOptions); - var _componentsNodesCluster = __webpack_require__(85); + this.body = body; - var _componentsNodesCluster2 = _interopRequireDefault(_componentsNodesCluster); + // create the HTML DOM + this._create(); - var util = __webpack_require__(2); + this.setOptions(options); + } - var ClusterEngine = (function () { - function ClusterEngine(body) { - var _this = this; + TimeAxis.prototype = new Component(); - _classCallCheck(this, ClusterEngine); + /** + * 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', 'hiddenDates', 'timeAxis'], this.options, options); - this.body = body; - this.clusteredNodes = {}; - - this.options = {}; - this.defaultOptions = {}; - util.extend(this.options, this.defaultOptions); - - this.body.emitter.on('_resetData', function () { - _this.clusteredNodes = {}; - }); - } + // deep copy the format options + util.selectiveDeepExtend(['format'], this.options, options); - _createClass(ClusterEngine, [{ - key: 'setOptions', - value: function setOptions(options) { - if (options !== undefined) {} + if ('orientation' in options) { + if (typeof options.orientation === 'string') { + this.options.orientation.axis = options.orientation; + } else if (typeof options.orientation === 'object' && 'axis' in options.orientation) { + this.options.orientation.axis = options.orientation.axis; + } } - }, { - key: 'clusterByHubsize', - /** - * - * @param hubsize - * @param options - */ - value: function clusterByHubsize(hubsize, options) { - if (hubsize === undefined) { - hubsize = this._getHubSize(); - } else if (typeof hubsize === 'object') { - options = this._checkOptions(hubsize); - hubsize = this._getHubSize(); + // 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); } + } + } + }; - var nodesToCluster = []; - for (var i = 0; i < this.body.nodeIndices.length; i++) { - var node = this.body.nodes[this.body.nodeIndices[i]]; - if (node.edges.length >= hubsize) { - nodesToCluster.push(node.id); - } - } + /** + * Create the HTML DOM for the TimeAxis + */ + TimeAxis.prototype._create = function () { + this.dom.foreground = document.createElement('div'); + this.dom.background = document.createElement('div'); - for (var i = 0; i < nodesToCluster.length; i++) { - this.clusterByConnection(nodesToCluster[i], options, false); - } - this.body.emitter.emit('_dataChanged'); - } - }, { - key: 'cluster', + this.dom.foreground.className = 'vis-time-axis vis-foreground'; + this.dom.background.className = 'vis-time-axis vis-background'; + }; - /** - * loop over all nodes, check if they adhere to the condition and cluster if needed. - * @param options - * @param refreshData - */ - value: function cluster() { - var options = arguments[0] === undefined ? {} : arguments[0]; - var refreshData = arguments[1] === undefined ? true : arguments[1]; + /** + * 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); + } - if (options.joinCondition === undefined) { - throw new Error('Cannot call clusterByNodeData without a joinCondition function in the options.'); - } + this.body = null; + }; - // check if the options object is fine, append if needed - options = this._checkOptions(options); + /** + * Repaint the component + * @return {boolean} Returns true if the component is resized + */ + TimeAxis.prototype.redraw = function () { + var options = this.options; + var props = this.props; + var foreground = this.dom.foreground; + var background = this.dom.background; - var childNodesObj = {}; - var childEdgesObj = {}; + // determine the correct parent DOM element (depending on option orientation) + var parent = options.orientation.axis == 'top' ? this.body.dom.top : this.body.dom.bottom; + var parentChanged = foreground.parentNode !== parent; - // collect the nodes that will be in the cluster - for (var i = 0; i < this.body.nodeIndices.length; i++) { - var nodeId = this.body.nodeIndices[i]; - var node = this.body.nodes[nodeId]; - var clonedOptions = this._cloneOptions(node); - if (options.joinCondition(clonedOptions) === true) { - childNodesObj[nodeId] = this.body.nodes[nodeId]; + // calculate character width and height + this._calculateCharSize(); - // collect the nodes that will be in the cluster - for (var _i = 0; _i < node.edges.length; _i++) { - var edge = node.edges[_i]; - childEdgesObj[edge.id] = edge; - } - } - } + // TODO: recalculate sizes only needed when parent is resized or options is changed + var showMinorLabels = this.options.showMinorLabels; + var showMajorLabels = this.options.showMajorLabels; - this._cluster(childNodesObj, childEdgesObj, options, refreshData); - } - }, { - key: 'clusterOutliers', + // 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; - /** - * Cluster all nodes in the network that have only 1 edge - * @param options - * @param refreshData - */ - value: function clusterOutliers(options) { - var refreshData = arguments[1] === undefined ? true : arguments[1]; + props.minorLineHeight = this.body.domProps.root.height - props.majorLabelHeight - (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 - options = this._checkOptions(options); - var clusters = []; + // 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); - // collect the nodes that will be in the cluster - for (var i = 0; i < this.body.nodeIndices.length; i++) { - var childNodesObj = {}; - var childEdgesObj = {}; - var nodeId = this.body.nodeIndices[i]; - var visibleEdges = 0; - var edge = undefined; - for (var j = 0; j < this.body.nodes[nodeId].edges.length; j++) { - if (this.body.nodes[nodeId].edges[j].options.hidden === false) { - visibleEdges++; - edge = this.body.nodes[nodeId].edges[j]; - } - } + foreground.style.height = this.props.height + 'px'; - if (visibleEdges === 1) { - // this is an outlier - var childNodeId = this._getConnectedId(edge, nodeId); - if (childNodeId !== nodeId) { - if (options.joinCondition === undefined) { - if (this._checkIfUsed(clusters, nodeId, edge.id) === false && this._checkIfUsed(clusters, childNodeId, edge.id) === false) { - childEdgesObj[edge.id] = edge; - childNodesObj[nodeId] = this.body.nodes[nodeId]; - childNodesObj[childNodeId] = this.body.nodes[childNodeId]; - } - } else { - var clonedOptions = this._cloneOptions(this.body.nodes[nodeId]); - if (options.joinCondition(clonedOptions) === true && this._checkIfUsed(clusters, nodeId, edge.id) === false) { - childEdgesObj[edge.id] = edge; - childNodesObj[nodeId] = this.body.nodes[nodeId]; - } - clonedOptions = this._cloneOptions(this.body.nodes[childNodeId]); - if (options.joinCondition(clonedOptions) === true && this._checkIfUsed(clusters, nodeId, edge.id) === false) { - childEdgesObj[edge.id] = edge; - childNodesObj[childNodeId] = this.body.nodes[childNodeId]; - } - } + this._repaintLabels(); - if (Object.keys(childNodesObj).length > 0 && Object.keys(childEdgesObj).length > 0) { - clusters.push({ nodes: childNodesObj, edges: childEdgesObj }); - } - } - } - } + // 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); + } - for (var i = 0; i < clusters.length; i++) { - this._cluster(clusters[i].nodes, clusters[i].edges, options, false); - } + return this._isResized() || parentChanged; + }; - if (refreshData === true) { - this.body.emitter.emit('_dataChanged'); - } - } - }, { - key: '_checkIfUsed', - value: function _checkIfUsed(clusters, nodeId, edgeId) { - for (var i = 0; i < clusters.length; i++) { - var cluster = clusters[i]; - if (cluster.nodes[nodeId] !== undefined || cluster.edges[edgeId] !== undefined) { - return true; - } - } - return false; - } - }, { - key: 'clusterByConnection', + /** + * Repaint major and minor text labels and vertical grid lines + * @private + */ + TimeAxis.prototype._repaintLabels = function () { + var orientation = this.options.orientation.axis; - /** - * suck all connected nodes of a node into the node. - * @param nodeId - * @param options - * @param refreshData - */ - value: function clusterByConnection(nodeId, options) { - var refreshData = arguments[2] === undefined ? true : arguments[2]; + // 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) * 7).valueOf(); + var minimumStep = timeLabelsize - DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this.body.range, timeLabelsize); + minimumStep -= this.body.util.toTime(0).valueOf(); - // kill conditions - if (nodeId === undefined) { - throw new Error('No nodeId supplied to clusterByConnection!'); - } - if (this.body.nodes[nodeId] === undefined) { - throw new Error('The nodeId given to clusterByConnection does not exist!'); - } + var step = new TimeStep(new Date(start), new Date(end), minimumStep, this.body.hiddenDates); + if (this.options.format) { + step.setFormat(this.options.format); + } + if (this.options.timeAxis) { + step.setScale(this.options.timeAxis); + } + this.step = step; - var node = this.body.nodes[nodeId]; - options = this._checkOptions(options, node); - if (options.clusterNodeProperties.x === undefined) { - options.clusterNodeProperties.x = node.x; - } - if (options.clusterNodeProperties.y === undefined) { - options.clusterNodeProperties.y = node.y; - } - if (options.clusterNodeProperties.fixed === undefined) { - options.clusterNodeProperties.fixed = {}; - options.clusterNodeProperties.fixed.x = node.options.fixed.x; - options.clusterNodeProperties.fixed.y = node.options.fixed.y; - } + // 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 childNodesObj = {}; - var childEdgesObj = {}; - var parentNodeId = node.id; - var parentClonedOptions = this._cloneOptions(node); - childNodesObj[parentNodeId] = node; + var cur; + var x = 0; + var isMajor; + var xPrev = 0; + var width = 0; + var prevLine; + var xFirstMajorLabel = undefined; + var max = 0; + var className; - // collect the nodes that will be in the cluster - for (var i = 0; i < node.edges.length; i++) { - var edge = node.edges[i]; - var childNodeId = this._getConnectedId(edge, parentNodeId); + step.first(); + while (step.hasNext() && max < 1000) { + max++; - if (childNodeId !== parentNodeId) { - if (options.joinCondition === undefined) { - childEdgesObj[edge.id] = edge; - childNodesObj[childNodeId] = this.body.nodes[childNodeId]; - } else { - // clone the options and insert some additional parameters that could be interesting. - var childClonedOptions = this._cloneOptions(this.body.nodes[childNodeId]); - if (options.joinCondition(parentClonedOptions, childClonedOptions) === true) { - childEdgesObj[edge.id] = edge; - childNodesObj[childNodeId] = this.body.nodes[childNodeId]; - } - } - } else { - childEdgesObj[edge.id] = edge; - } - } + cur = step.getCurrent(); + isMajor = step.isMajor(); + className = step.getClassName(); - this._cluster(childNodesObj, childEdgesObj, options, refreshData); + xPrev = x; + x = this.body.util.toScreen(cur); + width = x - xPrev; + if (prevLine) { + prevLine.style.width = width + 'px'; } - }, { - key: '_cloneOptions', - /** - * 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 objId - * @param type - * @returns {{}} - * @private - */ - 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; + if (this.options.showMinorLabels) { + this._repaintMinorText(x, step.getLabelMinor(), orientation, className); } - }, { - key: '_createClusterEdges', - - /** - * This function creates the edges that will be attached to the cluster. - * - * @param childNodesObj - * @param childEdgesObj - * @param newEdges - * @param options - * @private - */ - value: function _createClusterEdges(childNodesObj, childEdgesObj, newEdges, clusterNodeProperties, clusterEdgeProperties) { - var edge = undefined, - childNodeId = undefined, - childNode = undefined, - toId = undefined, - fromId = undefined, - otherNodeId = undefined; - - var childKeys = Object.keys(childNodesObj); - for (var i = 0; i < childKeys.length; i++) { - childNodeId = childKeys[i]; - childNode = childNodesObj[childNodeId]; - - // construct new edges from the cluster to others - for (var j = 0; j < childNode.edges.length; j++) { - edge = childNode.edges[j]; - childEdgesObj[edge.id] = edge; - - // childNodeId position will be replaced by the cluster. - if (edge.toId == childNodeId) { - // this is a double equals because ints and strings can be interchanged here. - toId = clusterNodeProperties.id; - fromId = edge.fromId; - otherNodeId = fromId; - } else { - toId = edge.toId; - fromId = clusterNodeProperties.id; - otherNodeId = toId; - } - // if the node connected to the cluster is also in the cluster we do not need a new edge. - if (childNodesObj[otherNodeId] === undefined) { - var clonedOptions = this._cloneOptions(edge, 'edge'); - util.deepExtend(clonedOptions, clusterEdgeProperties); - clonedOptions.from = fromId; - clonedOptions.to = toId; - clonedOptions.id = 'clusterEdge:' + util.randomUUID(); - newEdges.push(this.body.functions.createEdge(clonedOptions)); - } + if (isMajor && this.options.showMajorLabels) { + if (x > 0) { + if (xFirstMajorLabel == undefined) { + xFirstMajorLabel = x; } + this._repaintMajorText(x, step.getLabelMajor(), orientation, className); } + prevLine = this._repaintMajorLine(x, orientation, className); + } else { + prevLine = this._repaintMinorLine(x, orientation, className); } - }, { - key: '_checkOptions', - /** - * This function checks the options that can be supplied to the different cluster functions - * for certain fields and inserts defaults if needed - * @param options - * @returns {*} - * @private - */ - value: function _checkOptions() { - var options = arguments[0] === undefined ? {} : arguments[0]; + step.next(); + } - if (options.clusterEdgeProperties === undefined) { - options.clusterEdgeProperties = {}; - } - if (options.clusterNodeProperties === undefined) { - options.clusterNodeProperties = {}; - } + // 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 - return options; + if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) { + this._repaintMajorText(0, leftText, orientation, className); } - }, { - key: '_cluster', - - /** - * - * @param {Object} childNodesObj | object with node objects, id as keys, same as childNodes except it also contains a source node - * @param {Object} childEdgesObj | object with edge objects, id as keys - * @param {Array} options | object with {clusterNodeProperties, clusterEdgeProperties, processProperties} - * @param {Boolean} refreshData | when true, do not wrap up - * @private - */ - value: function _cluster(childNodesObj, childEdgesObj, options) { - var refreshData = arguments[3] === undefined ? true : arguments[3]; + } - // kill condition: no children so cant cluster - if (Object.keys(childNodesObj).length === 0) { - return; + // 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); } + } + }); + }; - var clusterNodeProperties = util.deepExtend({}, options.clusterNodeProperties); - - // construct the clusterNodeProperties - if (options.processProperties !== undefined) { - // get the childNode options - var childNodesOptions = []; - for (var nodeId in childNodesObj) { - var clonedOptions = this._cloneOptions(childNodesObj[nodeId]); - childNodesOptions.push(clonedOptions); - } + /** + * 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 + * @private + */ + TimeAxis.prototype._repaintMinorText = function (x, text, orientation, className) { + // reuse redundant label + var label = this.dom.redundant.minorTexts.shift(); - // get clusterproperties based on childNodes - var childEdgesOptions = []; - for (var edgeId in childEdgesObj) { - var clonedOptions = this._cloneOptions(childEdgesObj[edgeId], 'edge'); - childEdgesOptions.push(clonedOptions); - } + 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); - clusterNodeProperties = options.processProperties(clusterNodeProperties, childNodesOptions, childEdgesOptions); - if (!clusterNodeProperties) { - throw new Error('The processProperties function does not return properties!'); - } - } + label.childNodes[0].nodeValue = text; - // check if we have an unique id; - if (clusterNodeProperties.id === undefined) { - clusterNodeProperties.id = 'cluster:' + util.randomUUID(); - } - var clusterId = clusterNodeProperties.id; + label.style.top = orientation == 'top' ? this.props.majorLabelHeight + 'px' : '0'; + label.style.left = x + 'px'; + label.className = 'vis-text vis-minor ' + className; + //label.title = title; // TODO: this is a heavy operation + }; - if (clusterNodeProperties.label === undefined) { - clusterNodeProperties.label = 'cluster'; - } + /** + * 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 + * @private + */ + TimeAxis.prototype._repaintMajorText = function (x, text, orientation, className) { + // reuse redundant label + var label = this.dom.redundant.majorTexts.shift(); - // give the clusterNode a postion if it does not have one. - var pos = undefined; - if (clusterNodeProperties.x === undefined) { - pos = this._getClusterPosition(childNodesObj); - clusterNodeProperties.x = pos.x; - } - if (clusterNodeProperties.y === undefined) { - if (pos === undefined) { - pos = this._getClusterPosition(childNodesObj); - } - clusterNodeProperties.y = pos.y; - } + if (!label) { + // create label + var content = document.createTextNode(text); + label = document.createElement('div'); + label.appendChild(content); + this.dom.foreground.appendChild(label); + } + this.dom.majorTexts.push(label); - // force the ID to remain the same - clusterNodeProperties.id = clusterId; + label.childNodes[0].nodeValue = text; + label.className = 'vis-text vis-major ' + className; + //label.title = title; // TODO: this is a heavy operation - // create the clusterNode - var clusterNode = this.body.functions.createNode(clusterNodeProperties, _componentsNodesCluster2['default']); - clusterNode.isCluster = true; - clusterNode.containedNodes = childNodesObj; - clusterNode.containedEdges = childEdgesObj; - // cache a copy from the cluster edge properties if we have to reconnect others later on - clusterNode.clusterEdgeProperties = options.clusterEdgeProperties; + label.style.top = orientation == 'top' ? '0' : this.props.minorLabelHeight + 'px'; + label.style.left = x + 'px'; + }; - // finally put the cluster node into global - this.body.nodes[clusterNodeProperties.id] = clusterNode; + /** + * Create a minor line for the axis at position x + * @param {Number} x + * @param {String} orientation "top" or "bottom" (default) + * @param {String} className + * @return {Element} Returns the created line + * @private + */ + TimeAxis.prototype._repaintMinorLine = function (x, 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); - // create the new edges that will connect to the cluster - var newEdges = []; - this._createClusterEdges(childNodesObj, childEdgesObj, newEdges, clusterNodeProperties, options.clusterEdgeProperties); + 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'; + line.style.left = x - props.minorLineWidth / 2 + 'px'; - // disable the childEdges - for (var edgeId in childEdgesObj) { - if (childEdgesObj.hasOwnProperty(edgeId)) { - if (this.body.edges[edgeId] !== undefined) { - var edge = this.body.edges[edgeId]; - edge.togglePhysics(false); - edge.options.hidden = true; - } - } - } + line.className = 'vis-grid vis-vertical vis-minor ' + className; - // disable the childNodes - for (var nodeId in childNodesObj) { - if (childNodesObj.hasOwnProperty(nodeId)) { - this.clusteredNodes[nodeId] = { clusterId: clusterNodeProperties.id, node: this.body.nodes[nodeId] }; - this.body.nodes[nodeId].togglePhysics(false); - this.body.nodes[nodeId].options.hidden = true; - } - } + return line; + }; - // push new edges to global - for (var i = 0; i < newEdges.length; i++) { - this.body.edges[newEdges[i].id] = newEdges[i]; - this.body.edges[newEdges[i].id].connect(); - } + /** + * Create a Major line for the axis at position x + * @param {Number} x + * @param {String} orientation "top" or "bottom" (default) + * @param {String} className + * @return {Element} Returns the created line + * @private + */ + TimeAxis.prototype._repaintMajorLine = function (x, 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); - // set ID to undefined so no duplicates arise - clusterNodeProperties.id = undefined; + var props = this.props; + if (orientation == 'top') { + line.style.top = '0'; + } else { + line.style.top = this.body.domProps.top.height + 'px'; + } + line.style.left = x - props.majorLineWidth / 2 + 'px'; + line.style.height = props.majorLineHeight + 'px'; - // wrap up - if (refreshData === true) { - this.body.emitter.emit('_dataChanged'); - } - } - }, { - key: 'isCluster', + line.className = 'vis-grid vis-vertical vis-major ' + className; - /** - * Check if a node is a cluster. - * @param nodeId - * @returns {*} - */ - value: function isCluster(nodeId) { - if (this.body.nodes[nodeId] !== undefined) { - return this.body.nodes[nodeId].isCluster === true; - } else { - console.log('Node does not exist.'); - return false; - } - } - }, { - key: '_getClusterPosition', + return line; + }; - /** - * get the position of the cluster node based on what's inside - * @param {object} childNodesObj | object with node objects, id as keys - * @returns {{x: number, y: number}} - * @private - */ - value: function _getClusterPosition(childNodesObj) { - var childKeys = Object.keys(childNodesObj); - var minX = childNodesObj[childKeys[0]].x; - var maxX = childNodesObj[childKeys[0]].x; - var minY = childNodesObj[childKeys[0]].y; - var maxY = childNodesObj[childKeys[0]].y; - var node = undefined; - for (var i = 1; i < childKeys.length; i++) { - node = childNodesObj[childKeys[i]]; - minX = node.x < minX ? node.x : minX; - maxX = node.x > maxX ? node.x : maxX; - minY = node.y < minY ? node.y : minY; - maxY = node.y > maxY ? node.y : maxY; - } + /** + * 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. - return { x: 0.5 * (minX + maxX), y: 0.5 * (minY + maxY) }; - } - }, { - key: 'openCluster', + // 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'; - /** - * Open a cluster by calling this function. - * @param {String} clusterNodeId | the ID of the cluster node - * @param {Boolean} refreshData | wrap up afterwards if not true - */ - value: function openCluster(clusterNodeId) { - var refreshData = arguments[1] === undefined ? true : arguments[1]; + 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; - // kill conditions - if (clusterNodeId === undefined) { - throw new Error('No clusterNodeId supplied to openCluster.'); - } - if (this.body.nodes[clusterNodeId] === undefined) { - throw new Error('The clusterNodeId supplied to openCluster does not exist.'); - } - if (this.body.nodes[clusterNodeId].containedNodes === undefined) { - console.log('The node:' + clusterNodeId + ' is not a cluster.'); - return; - } - var clusterNode = this.body.nodes[clusterNodeId]; - var containedNodes = clusterNode.containedNodes; - var containedEdges = clusterNode.containedEdges; + // 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'; - // release nodes - for (var nodeId in containedNodes) { - if (containedNodes.hasOwnProperty(nodeId)) { - var containedNode = this.body.nodes[nodeId]; - containedNode = containedNodes[nodeId]; - // inherit position - containedNode.x = clusterNode.x; - containedNode.y = clusterNode.y; + 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; + }; - // inherit speed - containedNode.vx = clusterNode.vx; - containedNode.vy = clusterNode.vy; + module.exports = TimeAxis; - containedNode.options.hidden = false; - containedNode.togglePhysics(true); +/***/ }, +/* 42 */ +/***/ function(module, exports, __webpack_require__) { - delete this.clusteredNodes[nodeId]; - } - } + 'use strict'; - // release edges - for (var edgeId in containedEdges) { - if (containedEdges.hasOwnProperty(edgeId)) { - var edge = containedEdges[edgeId]; - // if this edge was a temporary edge and it's connected nodes do not exist anymore, we remove it from the data - if (this.body.nodes[edge.fromId] === undefined || this.body.nodes[edge.toId] === undefined) { - edge.edgeType.cleanup(); - // this removes the edge from node.edges, which is why edgeIds is formed - edge.disconnect(); - delete this.body.edges[edgeId]; - } else { - // one of the nodes connected to this edge is in a cluster. We give the edge to that cluster so it will be released when that cluster is opened. - if (this.clusteredNodes[edge.fromId] !== undefined || this.clusteredNodes[edge.toId] !== undefined) { - var fromId = undefined, - toId = undefined; - var clusteredNode = this.clusteredNodes[edge.fromId] || this.clusteredNodes[edge.toId]; - var clusterId = clusteredNode.clusterId; - var _clusterNode = this.body.nodes[clusterId]; - _clusterNode.containedEdges[edgeId] = edge; + var keycharm = __webpack_require__(43); + var Emitter = __webpack_require__(19); + var Hammer = __webpack_require__(3); + var util = __webpack_require__(7); - if (this.clusteredNodes[edge.fromId] !== undefined) { - fromId = clusterId; - toId = edge.toId; - } else { - fromId = edge.fromId; - toId = clusterId; - } + /** + * 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 + */ + function Activator(container) { + this.active = false; - // if both from and to nodes are visible, we create a new temporary edge - if (this.body.nodes[fromId].options.hidden !== true && this.body.nodes[toId].options.hidden !== true) { - var clonedOptions = this._cloneOptions(edge, 'edge'); - var id = 'clusterEdge:' + util.randomUUID(); - util.deepExtend(clonedOptions, _clusterNode.clusterEdgeProperties); - util.deepExtend(clonedOptions, { from: fromId, to: toId, hidden: false, physics: true, id: id }); - var newEdge = this.body.functions.createEdge(clonedOptions); + this.dom = { + container: container + }; - this.body.edges[id] = newEdge; - this.body.edges[id].connect(); - } - } else { - edge.options.hidden = false; - edge.togglePhysics(true); - } - } - } - } + this.dom.overlay = document.createElement('div'); + this.dom.overlay.className = 'vis-overlay'; - // remove all temporary edges - for (var i = 0; i < clusterNode.edges.length; i++) { - var edgeId = clusterNode.edges[i].id; - this.body.edges[edgeId].edgeType.cleanup(); - // this removes the edge from node.edges, which is why edgeIds is formed - this.body.edges[edgeId].disconnect(); - delete this.body.edges[edgeId]; - } + this.dom.container.appendChild(this.dom.overlay); - // remove clusterNode - delete this.body.nodes[clusterNodeId]; + this.hammer = Hammer(this.dom.overlay); + this.hammer.on('tap', this._onTapOverlay.bind(this)); - if (refreshData === true) { - this.body.emitter.emit('_dataChanged'); - } - } - }, { - key: 'getNodesInCluster', - value: function getNodesInCluster(clusterId) { - var nodesArray = []; - if (this.isCluster(clusterId) === true) { - var containedNodes = this.body.nodes[clusterId].containedNodes; - for (var nodeId in containedNodes) { - if (containedNodes.hasOwnProperty(nodeId)) { - nodesArray.push(nodeId); - } - } - } + // 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(); + }); + }); - return nodesArray; + // attach a tap event to the window, in order to deactivate when clicking outside the timeline + this.bodyHammer = Hammer(document && document.body, { prevent_default: false }); + this.bodyHammer.on('tap', function (event) { + // deactivate when clicked outside the container + if (!_hasParent(event.target, container)) { + me.deactivate(); } - }, { - key: 'findNode', + }); - /** - * Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node - * @param nodeId - * @returns {Array} - * @private - */ - value: function findNode(nodeId) { - var stack = []; - var max = 100; - var counter = 0; + if (this.keycharm !== undefined) { + this.keycharm.destroy(); + } + this.keycharm = keycharm(); - while (this.clusteredNodes[nodeId] !== undefined && counter < max) { - stack.push(this.clusteredNodes[nodeId].node); - nodeId = this.clusteredNodes[nodeId].clusterId; - counter++; - } - stack.push(this.body.nodes[nodeId]); - return stack; - } - }, { - key: '_getConnectedId', + // keycharm listener only bounded when active) + this.escListener = this.deactivate.bind(this); + } - /** - * Get the Id the node is connected to - * @param edge - * @param nodeId - * @returns {*} - * @private - */ - value: function _getConnectedId(edge, nodeId) { - if (edge.toId != nodeId) { - return edge.toId; - } else if (edge.fromId != nodeId) { - return edge.fromId; - } else { - return edge.fromId; - } - } - }, { - key: '_getHubSize', + // turn into an event emitter + Emitter(Activator.prototype); - /** - * We determine how many connections denote an important hub. - * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%) - * - * @private - */ - value: function _getHubSize() { - var average = 0; - var averageSquared = 0; - var hubCounter = 0; - var largestHub = 0; + // The currently active activator + Activator.current = null; - for (var i = 0; i < this.body.nodeIndices.length; i++) { - var node = this.body.nodes[this.body.nodeIndices[i]]; - if (node.edges.length > largestHub) { - largestHub = node.edges.length; - } - average += node.edges.length; - averageSquared += Math.pow(node.edges.length, 2); - hubCounter += 1; - } - average = average / hubCounter; - averageSquared = averageSquared / hubCounter; + /** + * Destroy the activator. Cleans up all created DOM and event listeners + */ + Activator.prototype.destroy = function () { + this.deactivate(); - var letiance = averageSquared - Math.pow(average, 2); - var standardDeviation = Math.sqrt(letiance); + // remove dom + this.dom.overlay.parentNode.removeChild(this.dom.overlay); - var hubThreshold = Math.floor(average + 2 * standardDeviation); + // cleanup hammer instances + this.hammer = null; + this.bodyHammer = null; + // FIXME: cleaning up hammer instances doesn't work (Timeline not removed from memory) + }; - // always have at least one to cluster - if (hubThreshold > largestHub) { - hubThreshold = largestHub; - } + /** + * 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; - return hubThreshold; - } - }]); + this.active = true; + this.dom.overlay.style.display = 'none'; + util.addClassName(this.dom.container, 'vis-active'); - return ClusterEngine; - })(); + this.emit('change'); + this.emit('activate'); - exports['default'] = ClusterEngine; - module.exports = exports['default']; + // 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); + }; -/***/ }, -/* 59 */ -/***/ function(module, exports, __webpack_require__) { + /** + * 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); - 'use strict'; + this.emit('change'); + this.emit('deactivate'); + }; - Object.defineProperty(exports, '__esModule', { - value: true - }); + /** + * Handle a tap event: activate the container + * @param event + * @private + */ + Activator.prototype._onTapOverlay = function (event) { + // activate the container + this.activate(); + event.stopPropagation(); + }; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - if (typeof window !== 'undefined') { - window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; + /** + * 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; } - var util = __webpack_require__(2); - - var CanvasRenderer = (function () { - function CanvasRenderer(body, canvas) { - _classCallCheck(this, CanvasRenderer); - - this.body = body; - this.canvas = canvas; + module.exports = Activator; - this.redrawRequested = false; - this.renderTimer = undefined; - this.requiresTimeout = true; - this.renderingActive = false; - this.renderRequests = 0; - this.pixelRatio = undefined; - this.allowRedrawRequests = true; +/***/ }, +/* 43 */ +/***/ function(module, exports, __webpack_require__) { - this.dragging = false; - this.options = {}; - this.defaultOptions = { - hideEdgesOnDrag: false, - hideNodesOnDrag: false - }; - util.extend(this.options, this.defaultOptions); + var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict"; + /** + * Created by Alex on 11/6/2014. + */ - this._determineBrowserMethod(); - this.bindEventListeners(); + // 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 () { - _createClass(CanvasRenderer, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this = this; - - this.body.emitter.on('dragStart', function () { - _this.dragging = true; - }); - this.body.emitter.on('dragEnd', function () { - return _this.dragging = false; - }); - this.body.emitter.on('_resizeNodes', function () { - return _this._resizeNodes(); - }); - this.body.emitter.on('_redraw', function () { - if (_this.renderingActive === false) { - _this._redraw(); - } - }); - this.body.emitter.on('_blockRedrawRequests', function () { - _this.allowRedrawRequests = false; - }); - this.body.emitter.on('_allowRedrawRequests', function () { - _this.allowRedrawRequests = true; - }); - this.body.emitter.on('_requestRedraw', this._requestRedraw.bind(this)); - this.body.emitter.on('_startRendering', function () { - _this.renderRequests += 1; - _this.renderingActive = true; - _this._startRendering(); - }); - this.body.emitter.on('_stopRendering', function () { - _this.renderRequests -= 1; - _this.renderingActive = _this.renderRequests > 0; - _this.renderTimer = undefined; - }); - this.body.emitter.on('destroy', function () { - _this.renderRequests = 0; - _this.renderingActive = false; - if (_this.requiresTimeout === true) { - clearTimeout(_this.renderTimer); - } else { - cancelAnimationFrame(_this.renderTimer); - } - _this.body.emitter.off(); - }); - } - }, { - key: 'setOptions', - value: function setOptions(options) { - if (options !== undefined) { - var fields = ['hideEdgesOnDrag', 'hideNodesOnDrag']; - util.selectiveDeepExtend(fields, this.options, options); - } - } - }, { - key: '_startRendering', - value: function _startRendering() { - if (this.renderingActive === true) { - if (this.renderTimer === undefined) { - if (this.requiresTimeout === true) { - this.renderTimer = window.setTimeout(this._renderStep.bind(this), this.simulationInterval); // wait this.renderTimeStep milliseconds and perform the animation step function - } else { - this.renderTimer = window.requestAnimationFrame(this._renderStep.bind(this)); // wait this.renderTimeStep milliseconds and perform the animation step function - } - } - } - } - }, { - key: '_renderStep', - value: function _renderStep() { - if (this.renderingActive === true) { - // reset the renderTimer so a new scheduled animation step can be set - this.renderTimer = undefined; - - if (this.requiresTimeout === true) { - // this schedules a new simulation step - this._startRendering(); - } - - this._redraw(); - - if (this.requiresTimeout === false) { - // this schedules a new simulation step - this._startRendering(); - } - } - } - }, { - key: 'redraw', - - /** - * Redraw the network with the current data - * chart will be resized too. - */ - value: function redraw() { - this.body.emitter.emit('setSize'); - this._redraw(); - } - }, { - key: '_requestRedraw', - - /** - * Redraw the network with the current data - * @param hidden | used to get the first estimate of the node sizes. only the nodes are drawn after which they are quickly drawn over. - * @private - */ - value: function _requestRedraw() { - if (this.redrawRequested !== true && this.renderingActive === false && this.allowRedrawRequests === true) { - this.redrawRequested = true; - if (this.requiresTimeout === true) { - window.setTimeout(this._redraw.bind(this, false), 0); - } else { - window.requestAnimationFrame(this._redraw.bind(this, false)); - } - } - } - }, { - key: '_redraw', - value: function _redraw() { - var hidden = arguments[0] === undefined ? false : arguments[0]; + function keycharm(options) { + var preventDefault = options && options.preventDefault || false; - this.body.emitter.emit('initRedraw'); + var container = options && options.container || window; - this.redrawRequested = false; - var ctx = this.canvas.frame.canvas.getContext('2d'); + var _exportFunctions = {}; + var _bound = {keydown:{}, keyup:{}}; + var _keys = {}; + var i; - // when the container div was hidden, this fixes it back up! - if (this.canvas.frame.canvas.width === 0 || this.canvas.frame.canvas.height === 0) { - this.canvas.setSize(); - } + // 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};} - if (this.pixelRatio === undefined) { - this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); - } + // 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}; - ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); - // clear the canvas - var w = this.canvas.frame.canvas.clientWidth; - var h = this.canvas.frame.canvas.clientHeight; - ctx.clearRect(0, 0, w, h); - // set scaling and translation - ctx.save(); - ctx.translate(this.body.view.translation.x, this.body.view.translation.y); - ctx.scale(this.body.view.scale, this.body.view.scale); + var down = function(event) {handleEvent(event,'keydown');}; + var up = function(event) {handleEvent(event,'keyup');}; - ctx.beginPath(); - this.body.emitter.emit('beforeDrawing', ctx); - ctx.closePath(); + // 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 (hidden === false) { - if (this.dragging === false || this.dragging === true && this.options.hideEdgesOnDrag === false) { - this._drawEdges(ctx); + if (preventDefault == true) { + event.preventDefault(); } } + }; - if (this.dragging === false || this.dragging === true && this.options.hideNodesOnDrag === false) { - this._drawNodes(ctx, hidden); + // bind a key to a callback + _exportFunctions.bind = function(key, callback, type) { + if (type === undefined) { + type = 'keydown'; } - - if (this.controlNodesActive === true) { - this._drawControlNodes(ctx); + 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}); + }; - ctx.beginPath(); - //this.physics.nodesSolver._debug(ctx,"#F00F0F"); - this.body.emitter.emit('afterDrawing', ctx); - ctx.closePath(); - // restore original scaling and translation - ctx.restore(); - if (hidden === true) { - ctx.clearRect(0, 0, w, h); + // bind all keys to a call back (demo purposes) + _exportFunctions.bindAll = function(callback, type) { + if (type === undefined) { + type = 'keydown'; } - } - }, { - key: '_resizeNodes', - - /** - * Redraw all nodes - * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); - * @param {CanvasRenderingContext2D} ctx - * @param {Boolean} [alwaysShow] - * @private - */ - value: function _resizeNodes() { - var ctx = this.canvas.frame.canvas.getContext('2d'); - if (this.pixelRatio === undefined) { - this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + for (var key in _keys) { + if (_keys.hasOwnProperty(key)) { + _exportFunctions.bind(key,callback,type); + } } - ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); - ctx.save(); - ctx.translate(this.body.view.translation.x, this.body.view.translation.y); - ctx.scale(this.body.view.scale, this.body.view.scale); - - var nodes = this.body.nodes; - var node = undefined; + }; - // resize all nodes - for (var nodeId in nodes) { - if (nodes.hasOwnProperty(nodeId)) { - node = nodes[nodeId]; - node.resize(ctx); - node.updateBoundingBox(ctx); + // 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"; + }; - // restore original scaling and translation - ctx.restore(); - } - }, { - key: '_drawNodes', - - /** - * Redraw all nodes - * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); - * @param {CanvasRenderingContext2D} ctx - * @param {Boolean} [alwaysShow] - * @private - */ - value: function _drawNodes(ctx) { - var alwaysShow = arguments[1] === undefined ? false : arguments[1]; - - var nodes = this.body.nodes; - var nodeIndices = this.body.nodeIndices; - var node = undefined; - var selected = []; - var margin = 20; - var topLeft = this.canvas.DOMtoCanvas({ x: -margin, y: -margin }); - var bottomRight = this.canvas.DOMtoCanvas({ - x: this.canvas.frame.canvas.clientWidth + margin, - y: this.canvas.frame.canvas.clientHeight + margin - }); - var viewableArea = { top: topLeft.y, left: topLeft.x, bottom: bottomRight.y, right: bottomRight.x }; - - // draw unselected nodes; - for (var i = 0; i < nodeIndices.length; i++) { - node = nodes[nodeIndices[i]]; - // set selected nodes aside - if (node.isSelected()) { - selected.push(nodeIndices[i]); - } else { - if (alwaysShow === true) { - node.draw(ctx); - } else if (node.isBoundingBoxOverlappingWith(viewableArea) === true) { - node.draw(ctx); - } else { - node.updateBoundingBox(ctx); + // 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; } - - // draw the selected nodes on top - for (var i = 0; i < selected.length; i++) { - node = nodes[selected[i]]; - node.draw(ctx); + else { + _bound[type][_keys[key].code] = []; } - } - }, { - key: '_drawEdges', + }; - /** - * Redraw all edges - * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); - * @param {CanvasRenderingContext2D} ctx - * @private - */ - value: function _drawEdges(ctx) { - var edges = this.body.edges; - var edgeIndices = this.body.edgeIndices; - var edge = undefined; + // reset all bound variables. + _exportFunctions.reset = function() { + _bound = {keydown:{}, keyup:{}}; + }; - for (var i = 0; i < edgeIndices.length; i++) { - edge = edges[edgeIndices[i]]; - if (edge.connected === true) { - edge.draw(ctx); - } - } - } - }, { - key: '_drawControlNodes', + // unbind all listeners and reset all variables. + _exportFunctions.destroy = function() { + _bound = {keydown:{}, keyup:{}}; + container.removeEventListener('keydown', down, true); + container.removeEventListener('keyup', up, true); + }; - /** - * Redraw all edges - * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); - * @param {CanvasRenderingContext2D} ctx - * @private - */ - value: function _drawControlNodes(ctx) { - var edges = this.body.edges; - var edgeIndices = this.body.edgeIndices; - var edge = undefined; + // create listeners. + container.addEventListener('keydown',down,true); + container.addEventListener('keyup',up,true); - for (var i = 0; i < edgeIndices.length; i++) { - edge = edges[edgeIndices[i]]; - edge._drawControlNodes(ctx); - } - } - }, { - key: '_determineBrowserMethod', + // return the public functions. + return _exportFunctions; + } + + return keycharm; + })); - /** - * Determine if the browser requires a setTimeout or a requestAnimationFrame. This was required because - * some implementations (safari and IE9) did not support requestAnimationFrame - * @private - */ - value: function _determineBrowserMethod() { - if (typeof window !== 'undefined') { - var browserType = navigator.userAgent.toLowerCase(); - this.requiresTimeout = false; - if (browserType.indexOf('msie 9.0') != -1) { - // IE 9 - this.requiresTimeout = true; - } else if (browserType.indexOf('safari') != -1) { - // safari - if (browserType.indexOf('chrome') <= -1) { - this.requiresTimeout = true; - } - } - } else { - this.requiresTimeout = true; - } - } - }]); - return CanvasRenderer; - })(); - exports['default'] = CanvasRenderer; - module.exports = exports['default']; /***/ }, -/* 60 */ +/* 44 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - var Hammer = __webpack_require__(41); - var hammerUtil = __webpack_require__(49); - - var util = __webpack_require__(2); + var Hammer = __webpack_require__(3); + var util = __webpack_require__(7); + var Component = __webpack_require__(27); + var moment = __webpack_require__(8); + var locales = __webpack_require__(28); /** - * Create the main frame for the Network. - * This function is executed once when a Network object is created. The frame - * contains a canvas, and this canvas contains all objects like the axis and - * nodes. - * @private + * 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 */ - var Canvas = (function () { - function Canvas(body) { - _classCallCheck(this, Canvas); - - this.body = body; - this.pixelRatio = 1; - this.resizeTimer = undefined; - this.resizeFunction = this._onResize.bind(this); + function CustomTime(body, options) { + this.body = body; - this.options = {}; - this.defaultOptions = { - autoResize: true, - height: '100%', - width: '100%' - }; - util.extend(this.options, this.defaultOptions); + // default options + this.defaultOptions = { + locales: locales, + locale: 'en', + id: undefined + }; + this.options = util.extend({}, this.defaultOptions); - this.bindEventListeners(); + if (options && options.time) { + this.customTime = options.time; + } else { + this.customTime = new Date(); } - _createClass(Canvas, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this = this; - - // bind the events - this.body.emitter.once('resize', function (obj) { - if (obj.width !== 0) { - _this.body.view.translation.x = obj.width * 0.5; - } - if (obj.height !== 0) { - _this.body.view.translation.y = obj.height * 0.5; - } - }); - this.body.emitter.on('setSize', this.setSize.bind(this)); - this.body.emitter.on('destroy', function () { - _this.hammerFrame.destroy(); - _this.hammer.destroy(); - _this._cleanUp(); - }); - } - }, { - key: 'setOptions', - value: function setOptions(options) { - var _this2 = this; + this.eventParams = {}; // stores state parameters while dragging the bar - if (options !== undefined) { - var fields = ['width', 'height', 'autoResize']; - util.selectiveDeepExtend(fields, this.options, options); - } + this.setOptions(options); - if (this.options.autoResize === true) { - // automatically adapt to a changing size of the browser. - this._cleanUp(); - this.resizeTimer = setInterval(function () { - _this2.setSize();_this2.body.emitter.emit('_requestRedraw'); - }, 1000); - this.resizeFunction = this._onResize.bind(this); - util.addEventListener(window, 'resize', this.resizeFunction); - } - } - }, { - key: '_cleanUp', - value: function _cleanUp() { - // automatically adapt to a changing size of the browser. - if (this.resizeTimer !== undefined) { - clearInterval(this.resizeTimer); - } - util.removeEventListener(window, 'resize', this.resizeFunction); - this.resizeFunction = undefined; - } - }, { - key: '_onResize', - value: function _onResize() { - this.setSize(); - this.body.emitter.emit('_redraw'); - } - }, { - key: '_prepareValue', - value: function _prepareValue(value) { - if (typeof value === 'number') { - return value + 'px'; - } else if (typeof value === 'string') { - if (value.indexOf('%') !== -1 || value.indexOf('px') !== -1) { - return value; - } else if (value.indexOf('%') === -1) { - return value + 'px'; - } - } - throw new Error('Could not use the value supplie for width or height:' + value); - } - }, { - key: '_create', + // create the DOM + this._create(); + } - /** - * Create the HTML - */ - value: function _create() { - // remove all elements from the container element. - while (this.body.container.hasChildNodes()) { - this.body.container.removeChild(this.body.container.firstChild); - } + CustomTime.prototype = new Component(); - this.frame = document.createElement('div'); - this.frame.className = 'vis-network'; - this.frame.style.position = 'relative'; - this.frame.style.overflow = 'hidden'; - this.frame.tabIndex = 900; // tab index is required for keycharm to bind keystrokes to the div instead of the window + /** + * 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(['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; - this.frame.canvas = document.createElement('canvas'); - this.frame.canvas.style.position = 'relative'; - this.frame.appendChild(this.frame.canvas); + 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'; + bar.appendChild(drag); - if (!this.frame.canvas.getContext) { - var noCanvas = document.createElement('DIV'); - noCanvas.style.color = 'red'; - noCanvas.style.fontWeight = 'bold'; - noCanvas.style.padding = '10px'; - noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; - this.frame.canvas.appendChild(noCanvas); - } else { - var ctx = this.frame.canvas.getContext('2d'); - this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + // 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)); + // TODO: cleanup + //this.hammer.on('pan', function (event) { + // event.preventDefault(); + //}); + }; - this.frame.canvas.getContext('2d').setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); - } + /** + * Destroy the CustomTime bar + */ + CustomTime.prototype.destroy = function () { + this.hide(); - // add the frame to the container element - this.body.container.appendChild(this.frame); + this.hammer.destroy(); + this.hammer = null; - this.body.view.scale = 1; - this.body.view.translation = { x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight }; + this.body = null; + }; - this._bindHammer(); + /** + * 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); } - }, { - key: '_bindHammer', - - /** - * This function binds hammer, it can be repeated over and over due to the uniqueness check. - * @private - */ - value: function _bindHammer() { - var _this3 = this; - - if (this.hammer !== undefined) { - this.hammer.destroy(); - } - this.drag = {}; - this.pinch = {}; - - // init hammer - this.hammer = new Hammer(this.frame.canvas); - this.hammer.get('pinch').set({ enable: true }); - // enable to get better response, todo: test on mobile. - //this.hammer.get('pan').set({threshold:2}); - - hammerUtil.onTouch(this.hammer, function (event) { - _this3.body.eventListeners.onTouch(event); - }); - this.hammer.on('tap', function (event) { - _this3.body.eventListeners.onTap(event); - }); - this.hammer.on('doubletap', function (event) { - _this3.body.eventListeners.onDoubleTap(event); - }); - this.hammer.on('press', function (event) { - _this3.body.eventListeners.onHold(event); - }); - this.hammer.on('panstart', function (event) { - _this3.body.eventListeners.onDragStart(event); - }); - this.hammer.on('panmove', function (event) { - _this3.body.eventListeners.onDrag(event); - }); - this.hammer.on('panend', function (event) { - _this3.body.eventListeners.onDragEnd(event); - }); - this.hammer.on('pinch', function (event) { - _this3.body.eventListeners.onPinch(event); - }); - - // TODO: neatly cleanup these handlers when re-creating the Canvas, IF these are done with hammer, event.stopPropagation will not work? - this.frame.canvas.addEventListener('mousewheel', function (event) { - _this3.body.eventListeners.onMouseWheel(event); - }); - this.frame.canvas.addEventListener('DOMMouseScroll', function (event) { - _this3.body.eventListeners.onMouseWheel(event); - }); + parent.appendChild(this.bar); + } - this.frame.canvas.addEventListener('mousemove', function (event) { - _this3.body.eventListeners.onMouseMove(event); - }); - this.frame.canvas.addEventListener('contextmenu', function (event) { - _this3.body.eventListeners.onContext(event); - }); + var x = this.body.util.toScreen(this.customTime); - this.hammerFrame = new Hammer(this.frame); - hammerUtil.onRelease(this.hammerFrame, function (event) { - _this3.body.eventListeners.onRelease(event); - }); + 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.html#Localization'); + this.warned = true; } - }, { - key: 'setSize', + locale = this.options.locales['en']; // fall back on english when not available + } + var title = locale.time + ': ' + moment(this.customTime).format('dddd, MMMM Do YYYY, H:mm:ss'); + title = title.charAt(0).toUpperCase() + title.substring(1); - /** - * Set a new size for the network - * @param {string} width Width in pixels or percentage (for example '800px' - * or '50%') - * @param {string} height Height in pixels or percentage (for example '400px' - * or '30%') - */ - value: function setSize() { - var width = arguments[0] === undefined ? this.options.width : arguments[0]; - var height = arguments[1] === undefined ? this.options.height : arguments[1]; + this.bar.style.left = x + 'px'; + this.bar.title = title; - width = this._prepareValue(width); - height = this._prepareValue(height); + return false; + }; - var emitEvent = false; - var oldWidth = this.frame.canvas.width; - var oldHeight = this.frame.canvas.height; + /** + * 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); + } + }; - if (width != this.options.width || height != this.options.height || this.frame.style.width != width || this.frame.style.height != height) { - this.frame.style.width = width; - this.frame.style.height = height; + /** + * Set custom time. + * @param {Date | number | string} time + */ + CustomTime.prototype.setCustomTime = function (time) { + this.customTime = util.convert(time, 'Date'); + this.redraw(); + }; - this.frame.canvas.style.width = '100%'; - this.frame.canvas.style.height = '100%'; + /** + * Retrieve the current custom time. + * @return {Date} customTime + */ + CustomTime.prototype.getCustomTime = function () { + return new Date(this.customTime.valueOf()); + }; - this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio; - this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio; + /** + * Start moving horizontally + * @param {Event} event + * @private + */ + CustomTime.prototype._onDragStart = function (event) { + this.eventParams.dragging = true; + this.eventParams.customTime = this.customTime; - this.options.width = width; - this.options.height = height; + event.stopPropagation(); + }; - emitEvent = true; - } else { - // this would adapt the width of the canvas to the width from 100% if and only if - // there is a change. + /** + * Perform moving operating. + * @param {Event} event + * @private + */ + CustomTime.prototype._onDrag = function (event) { + if (!this.eventParams.dragging) return; - if (this.frame.canvas.width != this.frame.canvas.clientWidth * this.pixelRatio) { - this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio; - emitEvent = true; - } - if (this.frame.canvas.height != this.frame.canvas.clientHeight * this.pixelRatio) { - this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio; - emitEvent = true; - } - } + var x = this.body.util.toScreen(this.eventParams.customTime) + event.deltaX; + var time = this.body.util.toTime(x); - if (emitEvent === true) { - this.body.emitter.emit('resize', { width: this.frame.canvas.width / this.pixelRatio, height: this.frame.canvas.height / this.pixelRatio, oldWidth: oldWidth / this.pixelRatio, oldHeight: oldHeight / this.pixelRatio }); - } - } - }, { - key: '_XconvertDOMtoCanvas', + this.setCustomTime(time); - /** - * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to - * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) - * @param {number} x - * @returns {number} - * @private - */ - value: function _XconvertDOMtoCanvas(x) { - return (x - this.body.view.translation.x) / this.body.view.scale; - } - }, { - key: '_XconvertCanvasToDOM', + // fire a timechange event + this.body.emitter.emit('timechange', { + id: this.options.id, + time: new Date(this.customTime.valueOf()) + }); - /** - * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to - * the X coordinate in DOM-space (coordinate point in browser relative to the container div) - * @param {number} x - * @returns {number} - * @private - */ - value: function _XconvertCanvasToDOM(x) { - return x * this.body.view.scale + this.body.view.translation.x; - } - }, { - key: '_YconvertDOMtoCanvas', + event.stopPropagation(); + }; - /** - * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to - * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) - * @param {number} y - * @returns {number} - * @private - */ - value: function _YconvertDOMtoCanvas(y) { - return (y - this.body.view.translation.y) / this.body.view.scale; - } - }, { - key: '_YconvertCanvasToDOM', + /** + * Stop moving operating. + * @param {Event} event + * @private + */ + CustomTime.prototype._onDragEnd = function (event) { + if (!this.eventParams.dragging) return; - /** - * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to - * the Y coordinate in DOM-space (coordinate point in browser relative to the container div) - * @param {number} y - * @returns {number} - * @private - */ - value: function _YconvertCanvasToDOM(y) { - return y * this.body.view.scale + this.body.view.translation.y; - } - }, { - key: 'canvasToDOM', + // fire a timechanged event + this.body.emitter.emit('timechanged', { + id: this.options.id, + time: new Date(this.customTime.valueOf()) + }); - /** - * - * @param {object} pos = {x: number, y: number} - * @returns {{x: number, y: number}} - * @constructor - */ - value: function canvasToDOM(pos) { - return { x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y) }; - } - }, { - key: 'DOMtoCanvas', + event.stopPropagation(); + }; - /** - * - * @param {object} pos = {x: number, y: number} - * @returns {{x: number, y: number}} - * @constructor - */ - value: function DOMtoCanvas(pos) { - return { x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y) }; + /** + * 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 Canvas; - })(); + return null; + }; - exports['default'] = Canvas; - module.exports = exports['default']; + module.exports = CustomTime; /***/ }, -/* 61 */ +/* 45 */ /***/ function(module, exports, __webpack_require__) { - "use strict"; + 'use strict'; - Object.defineProperty(exports, "__esModule", { + Object.defineProperty(exports, '__esModule', { value: true }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - var util = __webpack_require__(2); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var View = (function () { - function View(body, canvas) { - var _this = this; + var _ColorPicker = __webpack_require__(46); - _classCallCheck(this, View); + var _ColorPicker2 = _interopRequireDefault(_ColorPicker); - this.body = body; - this.canvas = canvas; + var util = __webpack_require__(7); - this.animationSpeed = 1 / this.renderRefreshRate; - this.animationEasingFunction = "easeInOutQuint"; - this.easingTime = 0; - this.sourceScale = 0; - this.targetScale = 0; - this.sourceTranslation = 0; - this.targetTranslation = 0; - this.lockedOnNodeId = undefined; - this.lockedOnNodeOffset = undefined; - this.touchTime = 0; + /** + * 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 + * + * @param parentModule | the location where parentModule.setOptions() can be called + * @param defaultContainer | the default container of the module + * @param configureOptions | the fully configured and predefined options set found in allOptions.js + * @param pixelRatio | canvas pixel ratio + */ - this.viewFunction = undefined; + var Configurator = (function () { + function Configurator(parentModule, defaultContainer, configureOptions) { + var pixelRatio = arguments[3] === undefined ? 1 : arguments[3]; - this.body.emitter.on("fit", this.fit.bind(this)); - this.body.emitter.on("animationFinished", function () { - _this.body.emitter.emit("_stopRendering"); - }); - this.body.emitter.on("unlockNode", this.releaseNode.bind(this)); - } + _classCallCheck(this, Configurator); - _createClass(View, [{ - key: "setOptions", - value: function setOptions() { - var options = arguments[0] === undefined ? {} : arguments[0]; + this.parent = parentModule; + this.changedOptions = []; + this.container = defaultContainer; + this.allowCreation = false; - this.options = options; - } - }, { - key: "_getRange", + this.options = {}; + this.defaultOptions = { + enabled: false, + filter: true, + container: undefined, + showButton: true + }; + util.extend(this.options, this.defaultOptions); + + this.configureOptions = configureOptions; + this.moduleOptions = {}; + this.domElements = []; + this.colorPicker = new _ColorPicker2['default'](pixelRatio); + this.wrapper = undefined; + } + + _createClass(Configurator, [{ + key: 'setOptions', /** - * Find the center position of the network - * @private + * refresh all options. + * Because all modules parse their options by themselves, we just use their options. We copy them here. + * + * @param options */ - value: function _getRange() { - var specificNodes = arguments[0] === undefined ? [] : arguments[0]; - - var minY = 1000000000, - maxY = -1000000000, - minX = 1000000000, - maxX = -1000000000, - node; - if (specificNodes.length > 0) { - for (var i = 0; i < specificNodes.length; i++) { - node = this.body.nodes[specificNodes[i]]; - if (minX > node.shape.boundingBox.left) { - minX = node.shape.boundingBox.left; + value: function setOptions(options) { + if (options !== undefined) { + 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 === 'object') { + if (options.container !== undefined) { + this.options.container = options.container; } - if (maxX < node.shape.boundingBox.right) { - maxX = node.shape.boundingBox.right; + if (options.filter !== undefined) { + this.options.filter = options.filter; } - 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 - } - } else { - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - node = this.body.nodes[nodeId]; - 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 (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; } + this.options.enabled = enabled; } - - if (minX === 1000000000 && maxX === -1000000000 && minY === 1000000000 && maxY === -1000000000) { - minY = 0, maxY = 0, minX = 0, maxX = 0; - } - return { minX: minX, maxX: maxX, minY: minY, maxY: maxY }; + this._clean(); } }, { - key: "_findCenter", - - /** - * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; - * @returns {{x: number, y: number}} - * @private - */ - value: function _findCenter(range) { - return { x: 0.5 * (range.maxX + range.minX), - y: 0.5 * (range.maxY + range.minY) }; + 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(); + } } }, { - key: "fit", + key: '_create', /** - * This function zooms out to fit all data on screen based on amount of nodes - * @param {Object} Options - * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false; + * Create all DOM elements + * @private */ - value: function fit() { - var options = arguments[0] === undefined ? { nodes: [] } : arguments[0]; - var initialZoom = arguments[1] === undefined ? false : arguments[1]; + value: function _create() { + var _this = this; - var range; - var zoomLevel; + this._clean(); + this.changedOptions = []; - if (initialZoom === true) { - // check if more than half of the nodes have a predefined position. If so, we use the range, not the approximation. - var positionDefined = 0; - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - var node = this.body.nodes[nodeId]; - if (node.predefinedPosition === true) { - positionDefined += 1; - } + 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 (positionDefined > 0.5 * this.body.nodeIndices.length) { - this.fit(options, false); - return; - } - range = this._getRange(options.nodes); + if (show !== false) { + this.allowCreation = true; - var numberOfNodes = this.body.nodeIndices.length; - zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. + // linebreak between categories + if (counter > 0) { + this._makeItem([]); + } + // a header for the category + this._makeHeader(option); - // correct for larger canvasses. - var factor = Math.min(this.canvas.frame.canvas.clientWidth / 600, this.canvas.frame.canvas.clientHeight / 600); - zoomLevel *= factor; - } else { - this.body.emitter.emit("_resizeNodes"); - range = this._getRange(options.nodes); - var xDistance = Math.abs(range.maxX - range.minX) * 1.1; - var yDistance = Math.abs(range.maxY - range.minY) * 1.1; + // get the suboptions + this._handleObject(this.configureOptions[option], [option]); + } + counter++; + } + } - var xZoomLevel = this.canvas.frame.canvas.clientWidth / xDistance; - var yZoomLevel = this.canvas.frame.canvas.clientHeight / yDistance; + if (this.options.showButton === true) { + (function () { + var generateButton = document.createElement('div'); + generateButton.className = 'vis-network-configuration button'; + generateButton.innerHTML = 'generate options'; + generateButton.onclick = function () { + _this._printOptions(); + }; + generateButton.onmouseover = function () { + generateButton.className = 'vis-network-configuration button hover'; + }; + generateButton.onmouseout = function () { + generateButton.className = 'vis-network-configuration button'; + }; - zoomLevel = xZoomLevel <= yZoomLevel ? xZoomLevel : yZoomLevel; - } + _this.optionsContainer = document.createElement('div'); + _this.optionsContainer.className = 'vis-network-configuration vis-option-container'; - if (zoomLevel > 1) { - zoomLevel = 1; - } else if (zoomLevel === 0) { - zoomLevel = 1; + _this.domElements.push(_this.optionsContainer); + _this.domElements.push(generateButton); + })(); } - var center = this._findCenter(range); - var animationOptions = { position: center, scale: zoomLevel, animation: options.animation }; - this.moveTo(animationOptions); + this._push(); + this.colorPicker.insertTo(this.container); } }, { - key: "focus", - - // animation + key: '_push', /** - * Center a node in view. - * - * @param {Number} nodeId - * @param {Number} [options] + * draw all DOM elements on the screen + * @private */ - value: function focus(nodeId) { - var options = arguments[1] === undefined ? {} : arguments[1]; - - if (this.body.nodes[nodeId] !== undefined) { - var nodePosition = { x: this.body.nodes[nodeId].x, y: this.body.nodes[nodeId].y }; - options.position = nodePosition; - options.lockedOnNode = nodeId; - - this.moveTo(options); - } else { - console.log("Node: " + nodeId + " cannot be found."); + value: function _push() { + this.wrapper = document.createElement('div'); + this.wrapper.className = 'vis-network-configuration-wrapper'; + this.container.appendChild(this.wrapper); + for (var i = 0; i < this.domElements.length; i++) { + this.wrapper.appendChild(this.domElements[i]); } } }, { - key: "moveTo", + key: '_clean', /** - * - * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels - * | options.scale = Number // scale to move to - * | options.position = {x:Number, y:Number} // position to move to - * | options.animation = {duration:Number, easingFunction:String} || Boolean // position to move to + * delete all DOM elements + * @private */ - value: function moveTo(options) { - if (options === undefined) { - options = {}; - return; - } - if (options.offset === undefined) { - options.offset = { x: 0, y: 0 }; - } - if (options.offset.x === undefined) { - options.offset.x = 0; - } - if (options.offset.y === undefined) { - options.offset.y = 0; - } - if (options.scale === undefined) { - options.scale = this.body.view.scale; - } - if (options.position === undefined) { - options.position = this.getViewPosition(); - } - if (options.animation === undefined) { - options.animation = { duration: 0 }; - } - if (options.animation === false) { - options.animation = { duration: 0 }; - } - if (options.animation === true) { - options.animation = {}; + value: function _clean() { + for (var i = 0; i < this.domElements.length; i++) { + this.wrapper.removeChild(this.domElements[i]); } - if (options.animation.duration === undefined) { - options.animation.duration = 1000; - } // default duration - if (options.animation.easingFunction === undefined) { - options.animation.easingFunction = "easeInOutQuad"; - } // default easing function - this.animateView(options); + if (this.wrapper !== undefined) { + this.container.removeChild(this.wrapper); + this.wrapper = undefined; + } + this.domElements = []; } }, { - key: "animateView", + key: '_getValue', /** - * - * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels - * | options.time = Number // animation time in milliseconds - * | options.scale = Number // scale to animate to - * | options.position = {x:Number, y:Number} // position to animate to - * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad, - * // easeInCubic, easeOutCubic, easeInOutCubic, - * // easeInQuart, easeOutQuart, easeInOutQuart, - * // easeInQuint, easeOutQuint, easeInOutQuint + * get the value from the actualOptions if it exists + * @param {array} path | where to look for the actual option + * @returns {*} + * @private */ - value: function animateView(options) { - if (options === undefined) { - return; - } - this.animationEasingFunction = options.animation.easingFunction; - // release if something focussed on the node - this.releaseNode(); - if (options.locked === true) { - this.lockedOnNodeId = options.lockedOnNode; - this.lockedOnNodeOffset = options.offset; - } - - // forcefully complete the old animation if it was still running - if (this.easingTime != 0) { - this._transitionRedraw(true); // by setting easingtime to 1, we finish the animation. - } - - this.sourceScale = this.body.view.scale; - this.sourceTranslation = this.body.view.translation; - this.targetScale = options.scale; - - // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw - // but at least then we'll have the target transition - this.body.view.scale = this.targetScale; - var viewCenter = this.canvas.DOMtoCanvas({ x: 0.5 * this.canvas.frame.canvas.clientWidth, y: 0.5 * this.canvas.frame.canvas.clientHeight }); - - var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node - x: viewCenter.x - options.position.x, - y: viewCenter.y - options.position.y - }; - this.targetTranslation = { - x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x, - y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y - }; - - // if the time is set to 0, don't do an animation - if (options.animation.duration === 0) { - if (this.lockedOnNodeId != undefined) { - this.viewFunction = this._lockedRedraw.bind(this); - this.body.emitter.on("initRedraw", this.viewFunction); + 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 { - this.body.view.scale = this.targetScale; - this.body.view.translation = this.targetTranslation; - this.body.emitter.emit("_requestRedraw"); + base = undefined; + break; } - } else { - this.animationSpeed = 1 / (60 * options.animation.duration * 0.001) || 1 / 60; // 60 for 60 seconds, 0.001 for milli's - this.animationEasingFunction = options.animation.easingFunction; - - this.viewFunction = this._transitionRedraw.bind(this); - this.body.emitter.on("initRedraw", this.viewFunction); - this.body.emitter.emit("_startRendering"); } + return base; } }, { - key: "_lockedRedraw", + key: '_makeItem', /** - * used to animate smoothly by hijacking the redraw function. + * all option elements are wrapped in an item + * @param path + * @param domElements * @private */ - value: function _lockedRedraw() { - var nodePosition = { x: this.body.nodes[this.lockedOnNodeId].x, y: this.body.nodes[this.lockedOnNodeId].y }; - var viewCenter = this.DOMtoCanvas({ x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight }); - var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node - x: viewCenter.x - nodePosition.x, - y: viewCenter.y - nodePosition.y - }; - var sourceTranslation = this.body.view.translation; - var targetTranslation = { - x: sourceTranslation.x + distanceFromCenter.x * this.body.view.scale + this.lockedOnNodeOffset.x, - y: sourceTranslation.y + distanceFromCenter.y * this.body.view.scale + this.lockedOnNodeOffset.y - }; + value: function _makeItem(path) { + var _this2 = this; - this.body.view.translation = targetTranslation; - } - }, { - key: "releaseNode", - value: function releaseNode() { - if (this.lockedOnNodeId !== undefined && this.viewFunction !== undefined) { - this.body.emitter.off("initRedraw", this.viewFunction); - this.lockedOnNodeId = undefined; - this.lockedOnNodeOffset = undefined; + for (var _len = arguments.length, domElements = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + domElements[_key - 1] = arguments[_key]; + } + + if (this.allowCreation === true) { + (function () { + var item = document.createElement('div'); + item.className = 'vis-network-configuration item s' + path.length; + domElements.forEach(function (element) { + item.appendChild(element); + }); + _this2.domElements.push(item); + })(); } } }, { - key: "_transitionRedraw", + key: '_makeHeader', /** - * - * @param easingTime + * header for major subjects + * @param name * @private */ - value: function _transitionRedraw() { - var finished = arguments[0] === undefined ? false : arguments[0]; - - this.easingTime += this.animationSpeed; - this.easingTime = finished === true ? 1 : this.easingTime; - - var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime); + value: function _makeHeader(name) { + var div = document.createElement('div'); + div.className = 'vis-network-configuration header'; + div.innerHTML = name; + this._makeItem([], div); + } + }, { + key: '_makeLabel', - this.body.view.scale = this.sourceScale + (this.targetScale - this.sourceScale) * progress; - this.body.view.translation = { - x: this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress, - y: this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress - }; + /** + * make a label, if it is an object label, it gets different styling. + * @param name + * @param path + * @param objectLabel + * @returns {HTMLElement} + * @private + */ + value: function _makeLabel(name, path) { + var objectLabel = arguments[2] === undefined ? false : arguments[2]; - // cleanup - if (this.easingTime >= 1) { - this.body.emitter.off("initRedraw", this.viewFunction); - this.easingTime = 0; - if (this.lockedOnNodeId != undefined) { - this.viewFunction = this._lockedRedraw.bind(this); - this.body.emitter.on("initRedraw", this.viewFunction); - } - this.body.emitter.emit("animationFinished"); + var div = document.createElement('div'); + div.className = 'vis-network-configuration label s' + path.length; + if (objectLabel === true) { + div.innerHTML = '' + name + ':'; + } else { + div.innerHTML = name + ':'; } + return div; } }, { - key: "getScale", - value: function getScale() { - return this.body.view.scale; - } - }, { - key: "getViewPosition", - value: function getViewPosition() { - return this.canvas.DOMtoCanvas({ x: 0.5 * this.canvas.frame.canvas.clientWidth, y: 0.5 * this.canvas.frame.canvas.clientHeight }); - } - }]); - - return View; - })(); - - exports["default"] = View; - module.exports = exports["default"]; - -/***/ }, -/* 62 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - var _componentsNavigationHandler = __webpack_require__(86); - - var _componentsNavigationHandler2 = _interopRequireDefault(_componentsNavigationHandler); - - var _componentsPopup = __webpack_require__(87); - - var _componentsPopup2 = _interopRequireDefault(_componentsPopup); - - var util = __webpack_require__(2); - - var InteractionHandler = (function () { - function InteractionHandler(body, canvas, selectionHandler) { - _classCallCheck(this, InteractionHandler); - - this.body = body; - this.canvas = canvas; - this.selectionHandler = selectionHandler; - this.navigationHandler = new _componentsNavigationHandler2['default'](body, canvas); - - // bind the events from hammer to functions in this object - this.body.eventListeners.onTap = this.onTap.bind(this); - this.body.eventListeners.onTouch = this.onTouch.bind(this); - this.body.eventListeners.onDoubleTap = this.onDoubleTap.bind(this); - this.body.eventListeners.onHold = this.onHold.bind(this); - this.body.eventListeners.onDragStart = this.onDragStart.bind(this); - this.body.eventListeners.onDrag = this.onDrag.bind(this); - this.body.eventListeners.onDragEnd = this.onDragEnd.bind(this); - this.body.eventListeners.onMouseWheel = this.onMouseWheel.bind(this); - this.body.eventListeners.onPinch = this.onPinch.bind(this); - this.body.eventListeners.onMouseMove = this.onMouseMove.bind(this); - this.body.eventListeners.onRelease = this.onRelease.bind(this); - this.body.eventListeners.onContext = this.onContext.bind(this); - - this.touchTime = 0; - this.drag = {}; - this.pinch = {}; - this.popup = undefined; - this.popupObj = undefined; - this.popupTimer = undefined; - - this.body.functions.getPointer = this.getPointer.bind(this); + key: '_makeDropdown', - this.options = {}; - this.defaultOptions = { - dragNodes: true, - dragView: true, - hover: false, - keyboard: { - enabled: false, - speed: { x: 10, y: 10, zoom: 0.02 }, - bindToWindow: true - }, - navigationButtons: false, - tooltipDelay: 300, - zoomView: true - }; - util.extend(this.options, this.defaultOptions); + /** + * make a dropdown list for multiple possible string optoins + * @param arr + * @param value + * @param path + * @private + */ + value: function _makeDropdown(arr, value, path) { + var select = document.createElement('select'); + select.className = 'vis-network-configuration select'; + var selectedValue = 0; + if (value !== undefined) { + if (arr.indexOf(value) !== -1) { + selectedValue = arr.indexOf(value); + } + } - this.bindEventListeners(); - } + 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); + } - _createClass(InteractionHandler, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this = this; + var me = this; + select.onchange = function () { + me._update(this.value, path); + }; - this.body.emitter.on('destroy', function () { - clearTimeout(_this.popupTimer); - delete _this.body.functions.getPointer; - }); + var label = this._makeLabel(path[path.length - 1], path); + this._makeItem(path, label, select); } }, { - key: 'setOptions', - value: function setOptions(options) { - if (options !== undefined) { - // extend all but the values in fields - var fields = ['hideEdgesOnDrag', 'hideNodesOnDrag', 'keyboard', 'multiselect', 'selectable', 'selectConnectedEdges']; - util.selectiveNotDeepExtend(fields, this.options, options); + key: '_makeRange', - // merge the keyboard options in. - util.mergeOptions(this.options, options, 'keyboard'); + /** + * make a range object for numeric options + * @param arr + * @param value + * @param path + * @private + */ + 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.type = 'range'; + range.className = 'vis-network-configuration range'; + range.min = min; + range.max = max; + range.step = step; - if (options.tooltip) { - util.extend(this.options.tooltip, options.tooltip); - if (options.tooltip.color) { - this.options.tooltip.color = util.parseColor(options.tooltip.color); - } + if (value !== undefined) { + if (value < 0 && value * 2 < min) { + range.min = value * 2; + } else if (value * 0.1 < min) { + range.min = value / 10; + } + if (value * 2 > max && max !== 1) { + range.max = value * 2; } + range.value = value; + } else { + range.value = defaultValue; } - this.navigationHandler.setOptions(this.options); - } - }, { - key: 'getPointer', + var input = document.createElement('input'); + input.className = 'vis-network-configuration rangeinput'; + input.value = range.value; - /** - * Get the pointer location from a touch location - * @param {{x: Number, y: Number}} touch - * @return {{x: Number, y: Number}} pointer - * @private - */ - value: function getPointer(touch) { - return { - x: touch.x - util.getAbsoluteLeft(this.canvas.frame.canvas), - y: touch.y - util.getAbsoluteTop(this.canvas.frame.canvas) + 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); + this._makeItem(path, label, range, input); } }, { - key: 'onTouch', + key: '_makeCheckbox', /** - * On start of a touch gesture, store the pointer - * @param event + * make a checkbox for boolean options. + * @param defaultValue + * @param value + * @param path * @private */ - value: function onTouch(event) { - if (new Date().valueOf() - this.touchTime > 50) { - this.drag.pointer = this.getPointer(event.center); - this.drag.pinched = false; - this.pinch.scale = this.body.view.scale; - // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame) - this.touchTime = new Date().valueOf(); + value: function _makeCheckbox(defaultValue, value, path) { + var checkbox = document.createElement('input'); + checkbox.type = 'checkbox'; + checkbox.className = 'vis-network-configuration checkbox'; + checkbox.checked = defaultValue; + if (value !== undefined) { + checkbox.checked = value; + if (value !== defaultValue) { + if (typeof defaultValue === 'object') { + if (value !== defaultValue.enabled) { + this.changedOptions.push({ path: path, value: value }); + } + } else { + this.changedOptions.push({ path: path, value: value }); + } + } } - } - }, { - key: 'onTap', - /** - * handle tap/click event: select/unselect a node - * @private - */ - value: function onTap(event) { - var pointer = this.getPointer(event.center); - var multiselect = this.selectionHandler.options.multiselect && (event.changedPointers[0].ctrlKey || event.changedPointers[0].metaKey); + var me = this; + checkbox.onchange = function () { + me._update(this.checked, path); + }; - this.checkSelectionChanges(pointer, event, multiselect); - this.selectionHandler._generateClickEvent('click', event, pointer); + var label = this._makeLabel(path[path.length - 1], path); + this._makeItem(path, label, checkbox); } }, { - key: 'onDoubleTap', + key: '_makeTextInput', /** - * handle doubletap event + * make a text input field for string options. + * @param defaultValue + * @param value + * @param path * @private */ - value: function onDoubleTap(event) { - var pointer = this.getPointer(event.center); - this.selectionHandler._generateClickEvent('doubleClick', event, pointer); + value: function _makeTextInput(defaultValue, value, path) { + var checkbox = document.createElement('input'); + checkbox.type = 'text'; + checkbox.className = 'vis-network-configuration 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); } }, { - key: 'onHold', + key: '_makeColorField', /** - * handle long tap event: multi select nodes + * make a color field with a color picker for color fields + * @param arr + * @param value + * @param path * @private */ - value: function onHold(event) { - var pointer = this.getPointer(event.center); - var multiselect = this.selectionHandler.options.multiselect; + value: function _makeColorField(arr, value, path) { + var _this3 = this; - this.checkSelectionChanges(pointer, event, multiselect); + var defaultColor = arr[1]; + var div = document.createElement('div'); + value = value === undefined ? defaultColor : value; - this.selectionHandler._generateClickEvent('click', event, pointer); - this.selectionHandler._generateClickEvent('hold', event, pointer); + if (value !== 'none') { + div.className = 'vis-network-configuration colorBlock'; + div.style.backgroundColor = value; + } else { + div.className = 'vis-network-configuration colorBlock none'; + } + + value = value === undefined ? defaultColor : value; + div.onclick = function () { + _this3._showColorPicker(value, div, path); + }; + + var label = this._makeLabel(path[path.length - 1], path); + this._makeItem(path, label, div); } }, { - key: 'onRelease', + key: '_showColorPicker', /** - * handle the release of the screen - * + * used by the color buttons to call the color picker. + * @param event + * @param value + * @param div + * @param path * @private */ - value: function onRelease(event) { - if (new Date().valueOf() - this.touchTime > 10) { - var pointer = this.getPointer(event.center); - this.selectionHandler._generateClickEvent('release', event, pointer); - // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame) - this.touchTime = new Date().valueOf(); - } - } - }, { - key: 'onContext', - value: function onContext(event) { - var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); - this.selectionHandler._generateClickEvent('oncontext', event, pointer); + value: function _showColorPicker(value, div, path) { + var _this4 = this; + + var rect = div.getBoundingClientRect(); + var bodyRect = document.body.getBoundingClientRect(); + var pickerX = rect.left + rect.width + 5; + var pickerY = rect.top - bodyRect.top + rect.height * 0.5; + this.colorPicker.show(pickerX, pickerY); + this.colorPicker.setColor(value); + this.colorPicker.setCallback(function (color) { + var colorString = 'rgba(' + color.r + ',' + color.g + ',' + color.b + ',' + color.a + ')'; + div.style.backgroundColor = colorString; + _this4._update(colorString, path); + }); } }, { - key: 'checkSelectionChanges', + key: '_handleObject', /** - * - * @param pointer - * @param add + * parse an object and draw the correct items + * @param obj + * @param path + * @private */ - value: function checkSelectionChanges(pointer, event) { - var add = arguments[2] === undefined ? false : arguments[2]; - - var previouslySelectedEdgeCount = this.selectionHandler._getSelectedEdgeCount(); - var previouslySelectedNodeCount = this.selectionHandler._getSelectedNodeCount(); - var previousSelection = this.selectionHandler.getSelection(); - var selected = undefined; - if (add === true) { - selected = this.selectionHandler.selectAdditionalOnPoint(pointer); - } else { - selected = this.selectionHandler.selectOnPoint(pointer); - } - var selectedEdgesCount = this.selectionHandler._getSelectedEdgeCount(); - var selectedNodesCount = this.selectionHandler._getSelectedNodeCount(); - var currentSelection = this.selectionHandler.getSelection(); + value: function _handleObject(obj) { + var path = arguments[1] === undefined ? [] : arguments[1]; + var checkOnly = arguments[2] === undefined ? false : arguments[2]; - var _determineIfDifferent = this._determineIfDifferent(previousSelection, currentSelection); + 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); - var nodesChanges = _determineIfDifferent.nodesChanges; - var edgesChanges = _determineIfDifferent.edgesChanges; + // 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 (selectedNodesCount - previouslySelectedNodeCount > 0) { - // node was selected - this.selectionHandler._generateClickEvent('selectNode', event, pointer); - selected = true; - } else if (selectedNodesCount - previouslySelectedNodeCount < 0) { - // node was deselected - this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection); - selected = true; - } else if (selectedNodesCount === previouslySelectedNodeCount && nodesChanges === true) { - this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection); - this.selectionHandler._generateClickEvent('selectNode', event, pointer); - selected = true; - } + if (show !== false) { + visibleInSet = true; + var value = this._getValue(newPath); - if (selectedEdgesCount - previouslySelectedEdgeCount > 0) { - // edge was selected - this.selectionHandler._generateClickEvent('selectEdge', event, pointer); - selected = true; - } else if (selectedEdgesCount - previouslySelectedEdgeCount < 0) { - // edge was deselected - this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection); - selected = true; - } else if (selectedEdgesCount === previouslySelectedEdgeCount && edgesChanges === true) { - this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection); - this.selectionHandler._generateClickEvent('selectEdge', event, pointer); - selected = true; - } + 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 (selected === true) { - // select or unselect - this.selectionHandler._generateClickEvent('select', event, pointer); + 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; } }, { - key: '_determineIfDifferent', + key: '_handleArray', /** - * This function checks if the nodes and edges previously selected have changed. - * @param previousSelection - * @param currentSelection - * @returns {{nodesChanges: boolean, edgesChanges: boolean}} + * handle the array type of option + * @param optionName + * @param arr + * @param value + * @param path * @private */ - value: function _determineIfDifferent(previousSelection, currentSelection) { - var nodesChanges = false; - var edgesChanges = false; - - for (var i = 0; i < previousSelection.nodes.length; i++) { - if (currentSelection.nodes.indexOf(previousSelection.nodes[i]) === -1) { - nodesChanges = true; - } - } - for (var i = 0; i < currentSelection.nodes.length; i++) { - if (previousSelection.nodes.indexOf(previousSelection.nodes[i]) === -1) { - nodesChanges = true; + 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 }); } - } - for (var i = 0; i < previousSelection.edges.length; i++) { - if (currentSelection.edges.indexOf(previousSelection.edges[i]) === -1) { - edgesChanges = true; + } else if (typeof arr[0] === 'string') { + this._makeDropdown(arr, value, path); + if (arr[0] !== value) { + this.changedOptions.push({ path: path, value: value }); } - } - for (var i = 0; i < currentSelection.edges.length; i++) { - if (previousSelection.edges.indexOf(previousSelection.edges[i]) === -1) { - edgesChanges = true; + } else if (typeof arr[0] === 'number') { + this._makeRange(arr, value, path); + if (arr[0] !== value) { + this.changedOptions.push({ path: path, value: Number(value) }); } } - - return { nodesChanges: nodesChanges, edgesChanges: edgesChanges }; } }, { - key: 'onDragStart', + key: '_update', /** - * This function is called by onDragStart. - * It is separated out because we can then overload it for the datamanipulation system. - * + * called to update the network with the new settings. + * @param value + * @param path * @private */ - value: function onDragStart(event) { - //in case the touch event was triggered on an external div, do the initial touch now. - if (this.drag.pointer === undefined) { - this.onTouch(event); + value: function _update(value, path) { + var options = this._constructOptions(value, path); + this.parent.setOptions(options); + } + }, { + key: '_constructOptions', + value: function _constructOptions(value, path) { + var optionsObj = 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; + } + }, { + key: '_printOptions', + value: function _printOptions() { + var options = {}; + for (var i = 0; i < this.changedOptions.length; i++) { + this._constructOptions(this.changedOptions[i].value, this.changedOptions[i].path, options); } + this.optionsContainer.innerHTML = '
var options = ' + JSON.stringify(options, null, 2) + '
'; + } + }]); - // note: drag.pointer is set in onTouch to get the initial touch location - var node = this.selectionHandler.getNodeAt(this.drag.pointer); + return Configurator; + })(); - this.drag.dragging = true; - this.drag.selection = []; - this.drag.translation = util.extend({}, this.body.view.translation); // copy the object - this.drag.nodeId = undefined; + exports['default'] = Configurator; + module.exports = exports['default']; - this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer); +/***/ }, +/* 46 */ +/***/ function(module, exports, __webpack_require__) { - if (node !== undefined && this.options.dragNodes === true) { - this.drag.nodeId = node.id; - // select the clicked node if not yet selected - if (node.isSelected() === false) { - this.selectionHandler.unselectAll(); - this.selectionHandler.selectObject(node); - } + 'use strict'; - var selection = this.selectionHandler.selectionObj.nodes; - // create an array with the selected nodes and their original location and status - for (var nodeId in selection) { - if (selection.hasOwnProperty(nodeId)) { - var object = selection[nodeId]; - var s = { - id: object.id, - node: object, + Object.defineProperty(exports, '__esModule', { + value: true + }); - // store original x, y, xFixed and yFixed, make the node temporarily Fixed - x: object.x, - y: object.y, - xFixed: object.options.fixed.x, - yFixed: object.options.fixed.y - }; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - object.options.fixed.x = true; - object.options.fixed.y = true; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - this.drag.selection.push(s); - } - } + var Hammer = __webpack_require__(3); + var hammerUtil = __webpack_require__(30); + var util = __webpack_require__(7); + + var ColorPicker = (function () { + function ColorPicker() { + var pixelRatio = arguments[0] === undefined ? 1 : arguments[0]; + + _classCallCheck(this, ColorPicker); + + this.pixelRatio = pixelRatio; + this.generated = false; + this.centerCoordinates = { x: 289 / 2, y: 289 / 2 }; + this.r = 289 * 0.49; + this.color = { r: 255, g: 255, b: 255, a: 1 }; + this.hueCircle = undefined; + this.initialColor = { r: 255, g: 255, b: 255, a: 1 }; + this.previousColor = undefined; + this.applied = false; + + // bound by + this.updateCallback = function () {}; + + // create all DOM elements + this._create(); + } + + _createClass(ColorPicker, [{ + key: 'insertTo', + + /** + * this inserts the colorPicker into a div from the DOM + * @param container + */ + value: function insertTo(container) { + if (this.hammer !== undefined) { + this.hammer.destroy(); + this.hammer = undefined; } + this.container = container; + this.container.appendChild(this.frame); + this._bindHammer(); + + this._setSize(); } }, { - key: 'onDrag', + key: 'setCallback', /** - * handle drag event - * @private + * the callback is executed on apply and save. Bind it to the application + * @param callback */ - value: function onDrag(event) { - var _this2 = this; - - if (this.drag.pinched === true) { - return; + value: function setCallback(callback) { + if (typeof callback === 'function') { + this.updateCallback = callback; + } else { + throw new Error('Function attempted to set as colorPicker callback is not a function.'); } + } + }, { + key: '_isColorString', + value: function _isColorString(color) { + var htmlColors = { black: '#000000', navy: '#000080', darkblue: '#00008B', mediumblue: '#0000CD', blue: '#0000FF', darkgreen: '#006400', green: '#008000', teal: '#008080', darkcyan: '#008B8B', deepskyblue: '#00BFFF', darkturquoise: '#00CED1', mediumspringgreen: '#00FA9A', lime: '#00FF00', springgreen: '#00FF7F', aqua: '#00FFFF', cyan: '#00FFFF', midnightblue: '#191970', dodgerblue: '#1E90FF', lightseagreen: '#20B2AA', forestgreen: '#228B22', seagreen: '#2E8B57', darkslategray: '#2F4F4F', limegreen: '#32CD32', mediumseagreen: '#3CB371', turquoise: '#40E0D0', royalblue: '#4169E1', steelblue: '#4682B4', darkslateblue: '#483D8B', mediumturquoise: '#48D1CC', indigo: '#4B0082', darkolivegreen: '#556B2F', cadetblue: '#5F9EA0', cornflowerblue: '#6495ED', mediumaquamarine: '#66CDAA', dimgray: '#696969', slateblue: '#6A5ACD', olivedrab: '#6B8E23', slategray: '#708090', lightslategray: '#778899', mediumslateblue: '#7B68EE', lawngreen: '#7CFC00', chartreuse: '#7FFF00', aquamarine: '#7FFFD4', maroon: '#800000', purple: '#800080', olive: '#808000', gray: '#808080', skyblue: '#87CEEB', lightskyblue: '#87CEFA', blueviolet: '#8A2BE2', darkred: '#8B0000', darkmagenta: '#8B008B', saddlebrown: '#8B4513', darkseagreen: '#8FBC8F', lightgreen: '#90EE90', mediumpurple: '#9370D8', darkviolet: '#9400D3', palegreen: '#98FB98', darkorchid: '#9932CC', yellowgreen: '#9ACD32', sienna: '#A0522D', brown: '#A52A2A', darkgray: '#A9A9A9', lightblue: '#ADD8E6', greenyellow: '#ADFF2F', paleturquoise: '#AFEEEE', lightsteelblue: '#B0C4DE', powderblue: '#B0E0E6', firebrick: '#B22222', darkgoldenrod: '#B8860B', mediumorchid: '#BA55D3', rosybrown: '#BC8F8F', darkkhaki: '#BDB76B', silver: '#C0C0C0', mediumvioletred: '#C71585', indianred: '#CD5C5C', peru: '#CD853F', chocolate: '#D2691E', tan: '#D2B48C', lightgrey: '#D3D3D3', palevioletred: '#D87093', thistle: '#D8BFD8', orchid: '#DA70D6', goldenrod: '#DAA520', crimson: '#DC143C', gainsboro: '#DCDCDC', plum: '#DDA0DD', burlywood: '#DEB887', lightcyan: '#E0FFFF', lavender: '#E6E6FA', darksalmon: '#E9967A', violet: '#EE82EE', palegoldenrod: '#EEE8AA', lightcoral: '#F08080', khaki: '#F0E68C', aliceblue: '#F0F8FF', honeydew: '#F0FFF0', azure: '#F0FFFF', sandybrown: '#F4A460', wheat: '#F5DEB3', beige: '#F5F5DC', whitesmoke: '#F5F5F5', mintcream: '#F5FFFA', ghostwhite: '#F8F8FF', salmon: '#FA8072', antiquewhite: '#FAEBD7', linen: '#FAF0E6', lightgoldenrodyellow: '#FAFAD2', oldlace: '#FDF5E6', red: '#FF0000', fuchsia: '#FF00FF', magenta: '#FF00FF', deeppink: '#FF1493', orangered: '#FF4500', tomato: '#FF6347', hotpink: '#FF69B4', coral: '#FF7F50', darkorange: '#FF8C00', lightsalmon: '#FFA07A', orange: '#FFA500', lightpink: '#FFB6C1', pink: '#FFC0CB', gold: '#FFD700', peachpuff: '#FFDAB9', navajowhite: '#FFDEAD', moccasin: '#FFE4B5', bisque: '#FFE4C4', mistyrose: '#FFE4E1', blanchedalmond: '#FFEBCD', papayawhip: '#FFEFD5', lavenderblush: '#FFF0F5', seashell: '#FFF5EE', cornsilk: '#FFF8DC', lemonchiffon: '#FFFACD', floralwhite: '#FFFAF0', snow: '#FFFAFA', yellow: '#FFFF00', lightyellow: '#FFFFE0', ivory: '#FFFFF0', white: '#FFFFFF' }; + if (typeof color === 'string') { + return htmlColors[color]; + } + } + }, { + key: 'setColor', - // remove the focus on node if it is focussed on by the focusOnNode - this.body.emitter.emit('unlockNode'); - - var pointer = this.getPointer(event.center); + /** + * Set the color of the colorPicker + * Supported formats: + * 'red' --> HTML color string + * '#ffffff' --> hex string + * 'rbg(255,255,255)' --> rgb string + * 'rgba(255,255,255,1.0)' --> rgba string + * {r:255,g:255,b:255} --> rgb object + * {r:255,g:255,b:255,a:1.0} --> rgba object + * @param color + * @param setInitial + */ + value: function setColor(color) { + var setInitial = arguments[1] === undefined ? true : arguments[1]; - this.selectionHandler._generateClickEvent('dragging', event, pointer); + if (color === 'none') { + return; + } - var selection = this.drag.selection; - if (selection && selection.length && this.options.dragNodes === true) { - (function () { - // calculate delta's and new location - var deltaX = pointer.x - _this2.drag.pointer.x; - var deltaY = pointer.y - _this2.drag.pointer.y; + var rgba = undefined; - // update position of all selected nodes - selection.forEach(function (selection) { - var node = selection.node; - // only move the node if it was not fixed initially - if (selection.xFixed === false) { - node.x = _this2.canvas._XconvertDOMtoCanvas(_this2.canvas._XconvertCanvasToDOM(selection.x) + deltaX); - } - // only move the node if it was not fixed initially - if (selection.yFixed === false) { - node.y = _this2.canvas._YconvertDOMtoCanvas(_this2.canvas._YconvertCanvasToDOM(selection.y) + deltaY); - } - }); + // if a html color shorthand is used, convert to hex + var htmlColor = this._isColorString(color); + if (htmlColor !== undefined) { + color = htmlColor; + } - // start the simulation of the physics - _this2.body.emitter.emit('startSimulation'); - })(); + // check format + if (util.isString(color) === true) { + if (util.isValidRGB(color) === true) { + var rgbaArray = color.substr(4).substr(0, color.length - 5).split(','); + rgba = { r: rgbaArray[0], g: rgbaArray[1], b: rgbaArray[2], a: 1 }; + } else if (util.isValidRGBA(color) === true) { + var rgbaArray = color.substr(5).substr(0, color.length - 6).split(','); + rgba = { r: rgbaArray[0], g: rgbaArray[1], b: rgbaArray[2], a: rgbaArray[3] }; + } else if (util.isValidHex(color) === true) { + var rgbObj = util.hexToRGB(color); + rgba = { r: rgbObj.r, g: rgbObj.g, b: rgbObj.b, a: 1 }; + } } else { - // move the network - if (this.options.dragView === true) { - // if the drag was not started properly because the click started outside the network div, start it now. - if (this.drag.pointer === undefined) { - this._handleDragStart(event); - return; + if (color instanceof Object) { + if (color.r !== undefined && color.g !== undefined && color.b !== undefined) { + var alpha = color.a !== undefined ? color.a : '1.0'; + rgba = { r: color.r, g: color.g, b: color.b, a: alpha }; } - var diffX = pointer.x - this.drag.pointer.x; - var diffY = pointer.y - this.drag.pointer.y; - - this.body.view.translation = { x: this.drag.translation.x + diffX, y: this.drag.translation.y + diffY }; - this.body.emitter.emit('_redraw'); } } + + // set color + if (rgba === undefined) { + throw new Error('Unknown color passed to the colorPicker. Supported are strings: rgb, hex, rgba. Object: rgb ({r:r,g:g,b:b,[a:a]}). Supplied: ' + JSON.stringify(color)); + } else { + this._setColor(rgba, setInitial); + } } }, { - key: 'onDragEnd', + key: 'show', /** - * handle drag start event - * @private + * this shows the color picker at a location. The hue circle is constructed once and stored. + * @param x + * @param y */ - value: function onDragEnd(event) { - this.drag.dragging = false; - var selection = this.drag.selection; - if (selection && selection.length) { - selection.forEach(function (s) { - // restore original xFixed and yFixed - s.node.options.fixed.x = s.xFixed; - s.node.options.fixed.y = s.yFixed; - }); - this.body.emitter.emit('startSimulation'); - } else { - this.body.emitter.emit('_requestRedraw'); - } - this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center)); + value: function show(x, y) { + this.applied = false; + this.frame.style.display = 'block'; + this.frame.style.top = y + 'px'; + this.frame.style.left = x + 'px'; + this._generateHueCircle(); } }, { - key: 'onPinch', + key: '_hide', + + // ------------------------------------------ PRIVATE ----------------------------- // /** - * Handle pinch event - * @param event + * Hide the picker. Is called by the cancel button. + * Optional boolean to store the previous color for easy access later on. + * @param storePrevious * @private */ - value: function onPinch(event) { - var pointer = this.getPointer(event.center); + value: function _hide() { + var storePrevious = arguments[0] === undefined ? true : arguments[0]; - this.drag.pinched = true; - if (this.pinch['scale'] === undefined) { - this.pinch.scale = 1; + // store the previous color for next time; + if (storePrevious === true) { + this.previousColor = util.extend({}, this.color); } - // TODO: enabled moving while pinching? - var scale = this.pinch.scale * event.scale; - this.zoom(scale, pointer); + if (this.applied === true) { + this.updateCallback(this.initialColor); + } + + this.frame.style.display = 'none'; } }, { - key: 'zoom', + key: '_save', /** - * Zoom the network in or out - * @param {Number} scale a number around 1, and between 0.01 and 10 - * @param {{x: Number, y: Number}} pointer Position on screen - * @return {Number} appliedScale scale is limited within the boundaries + * bound to the save button. Saves and hides. * @private */ - value: function zoom(scale, pointer) { - if (this.options.zoomView === true) { - var scaleOld = this.body.view.scale; - if (scale < 0.00001) { - scale = 0.00001; - } - if (scale > 10) { - scale = 10; - } - - var preScaleDragPointer = undefined; - if (this.drag !== undefined) { - if (this.drag.dragging === true) { - preScaleDragPointer = this.canvas.DOMtoCanvas(this.drag.pointer); - } - } - // + this.canvas.frame.canvas.clientHeight / 2 - var translation = this.body.view.translation; - - var scaleFrac = scale / scaleOld; - var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac; - var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac; - - this.body.view.scale = scale; - this.body.view.translation = { x: tx, y: ty }; - - if (preScaleDragPointer != undefined) { - var postScaleDragPointer = this.canvas.canvasToDOM(preScaleDragPointer); - this.drag.pointer.x = postScaleDragPointer.x; - this.drag.pointer.y = postScaleDragPointer.y; - } + value: function _save() { + this.updateCallback(this.color); + this.applied = false; + this._hide(); + } + }, { + key: '_apply', - this.body.emitter.emit('_requestRedraw'); + /** + * Bound to apply button. Saves but does not close. Is undone by the cancel button. + * @private + */ + value: function _apply() { + this.applied = true; + this.updateCallback(this.color); + this._updatePicker(this.color); + } + }, { + key: '_loadLast', - if (scaleOld < scale) { - this.body.emitter.emit('zoom', { direction: '+', scale: this.body.view.scale }); - } else { - this.body.emitter.emit('zoom', { direction: '-', scale: this.body.view.scale }); - } + /** + * load the color from the previous session. + * @private + */ + value: function _loadLast() { + if (this.previousColor !== undefined) { + this.setColor(this.previousColor, false); + } else { + alert('There is no last color to load...'); } } }, { - key: 'onMouseWheel', + key: '_setColor', /** - * Event handler for mouse wheel event, used to zoom the timeline - * See http://adomas.org/javascript-mouse-wheel/ - * https://github.com/EightMedia/hammer.js/issues/256 - * @param {MouseEvent} event + * set the color, place the picker + * @param rgba + * @param setInitial * @private */ - value: function onMouseWheel(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; - } + value: function _setColor(rgba) { + var setInitial = arguments[1] === undefined ? true : arguments[1]; - // 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 !== 0) { + // store the initial color + if (setInitial === true) { + this.initialColor = util.extend({}, rgba); + } - // calculate the new scale - var scale = this.body.view.scale; - var zoom = delta / 10; - if (delta < 0) { - zoom = zoom / (1 - zoom); - } - scale *= 1 + zoom; + this.color = rgba; + var hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b); - // calculate the pointer location - var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); + var angleConvert = 2 * Math.PI; + var radius = this.r * hsv.s; + var x = this.centerCoordinates.x + radius * Math.sin(angleConvert * hsv.h); + var y = this.centerCoordinates.y + radius * Math.cos(angleConvert * hsv.h); - // apply the new scale - this.zoom(scale, pointer); - } + this.colorPickerSelector.style.left = x - 0.5 * this.colorPickerSelector.clientWidth + 'px'; + this.colorPickerSelector.style.top = y - 0.5 * this.colorPickerSelector.clientHeight + 'px'; - // Prevent default actions caused by mouse wheel. - event.preventDefault(); + this._updatePicker(rgba); } }, { - key: 'onMouseMove', + key: '_setOpacity', /** - * Mouse move handler for checking whether the title moves over a node with a title. - * @param {Event} event + * bound to opacity control + * @param value * @private */ - value: function onMouseMove(event) { - var _this3 = this; + value: function _setOpacity(value) { + this.color.a = value / 100; + this._updatePicker(this.color); + } + }, { + key: '_setBrightness', - var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); - var popupVisible = false; + /** + * bound to brightness control + * @param value + * @private + */ + value: function _setBrightness(value) { + var hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b); + hsv.v = value / 100; + var rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v); + rgba['a'] = this.color.a; + this.color = rgba; + this._updatePicker(); + } + }, { + key: '_updatePicker', - // check if the previously selected node is still selected - if (this.popup !== undefined) { - if (this.popup.hidden === false) { - this._checkHidePopup(pointer); - } + /** + * update the colorpicker. A black circle overlays the hue circle to mimic the brightness decreasing. + * @param rgba + * @private + */ + value: function _updatePicker() { + var rgba = arguments[0] === undefined ? this.color : arguments[0]; - // if the popup was not hidden above - if (this.popup.hidden === false) { - popupVisible = true; - this.popup.setPosition(pointer.x + 3, pointer.y - 5); - this.popup.show(); - } + var hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b); + var ctx = this.colorPickerCanvas.getContext('2d'); + if (this.pixelRation === undefined) { + this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); } + ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); - // if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over. - if (this.options.keyboard.bindToWindow === false && this.options.keyboard.enabled === true) { - this.canvas.frame.focus(); - } + // clear the canvas + var w = this.colorPickerCanvas.clientWidth; + var h = this.colorPickerCanvas.clientHeight; + ctx.clearRect(0, 0, w, h); - // start a timeout that will check if the mouse is positioned above an element - if (popupVisible === false) { - if (this.popupTimer !== undefined) { - clearInterval(this.popupTimer); // stop any running calculationTimer - this.popupTimer = undefined; - } - if (!this.drag.dragging) { - this.popupTimer = setTimeout(function () { - return _this3._checkShowPopup(pointer); - }, this.options.tooltipDelay); - } - } + ctx.putImageData(this.hueCircle, 0, 0); + ctx.fillStyle = 'rgba(0,0,0,' + (1 - hsv.v) + ')'; + ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r); + ctx.fill(); - /** - * Adding hover highlights - */ - if (this.options.hover === true) { - // adding hover highlights - var obj = this.selectionHandler.getNodeAt(pointer); - if (obj === undefined) { - obj = this.selectionHandler.getEdgeAt(pointer); - } - this.selectionHandler.hoverObject(obj); - } + this.brightnessRange.value = 100 * hsv.v; + this.opacityRange.value = 100 * rgba.a; + + this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')'; + this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')'; } }, { - key: '_checkShowPopup', + key: '_setSize', /** - * Check if there is an element on the given position in the network - * (a node or edge). If so, and if this element has a title, - * show a popup window with its title. - * - * @param {{x:Number, y:Number}} pointer + * used by create to set the size of the canvas. * @private */ - value: function _checkShowPopup(pointer) { - var x = this.canvas._XconvertDOMtoCanvas(pointer.x); - var y = this.canvas._YconvertDOMtoCanvas(pointer.y); - var pointerObj = { - left: x, - top: y, - right: x, - bottom: y - }; + value: function _setSize() { + this.colorPickerCanvas.style.width = '100%'; + this.colorPickerCanvas.style.height = '100%'; - var previousPopupObjId = this.popupObj === undefined ? undefined : this.popupObj.id; - var nodeUnderCursor = false; - var popupType = 'node'; + this.colorPickerCanvas.width = 289 * this.pixelRatio; + this.colorPickerCanvas.height = 289 * this.pixelRatio; + } + }, { + key: '_create', - // check if a node is under the cursor. - if (this.popupObj === undefined) { - // search the nodes for overlap, select the top one in case of multiple nodes - var nodeIndices = this.body.nodeIndices; - var nodes = this.body.nodes; - var node = undefined; - var overlappingNodes = []; - for (var i = 0; i < nodeIndices.length; i++) { - node = nodes[nodeIndices[i]]; - if (node.isOverlappingWith(pointerObj) === true) { - if (node.getTitle() !== undefined) { - overlappingNodes.push(nodeIndices[i]); - } - } - } + /** + * create all dom elements + * TODO: cleanup, lots of similar dom elements + * @private + */ + value: function _create() { + this.frame = document.createElement('div'); + this.frame.className = 'vis-color-picker'; - if (overlappingNodes.length > 0) { - // if there are overlapping nodes, select the last one, this is the one which is drawn on top of the others - this.popupObj = nodes[overlappingNodes[overlappingNodes.length - 1]]; - // if you hover over a node, the title of the edge is not supposed to be shown. - nodeUnderCursor = true; - } - } + this.colorPickerDiv = document.createElement('div'); + this.colorPickerSelector = document.createElement('div'); + this.colorPickerSelector.className = 'vis-selector'; + this.colorPickerDiv.appendChild(this.colorPickerSelector); - if (this.popupObj === undefined && nodeUnderCursor === false) { - // search the edges for overlap - var edgeIndices = this.body.edgeIndices; - var edges = this.body.edges; - var edge = undefined; - var overlappingEdges = []; - for (var i = 0; i < edgeIndices.length; i++) { - edge = edges[edgeIndices[i]]; - if (edge.isOverlappingWith(pointerObj) === true) { - if (edge.connected === true && edge.getTitle() !== undefined) { - overlappingEdges.push(edgeIndices[i]); - } - } - } + this.colorPickerCanvas = document.createElement('canvas'); + this.colorPickerDiv.appendChild(this.colorPickerCanvas); - if (overlappingEdges.length > 0) { - this.popupObj = edges[overlappingEdges[overlappingEdges.length - 1]]; - popupType = 'edge'; - } + if (!this.colorPickerCanvas.getContext) { + var noCanvas = document.createElement('DIV'); + noCanvas.style.color = 'red'; + noCanvas.style.fontWeight = 'bold'; + noCanvas.style.padding = '10px'; + noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; + this.colorPickerCanvas.appendChild(noCanvas); + } else { + var ctx = this.colorPickerCanvas.getContext('2d'); + this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + + this.colorPickerCanvas.getContext('2d').setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); } - if (this.popupObj !== undefined) { - // show popup message window - if (this.popupObj.id !== previousPopupObjId) { - if (this.popup === undefined) { - this.popup = new _componentsPopup2['default'](this.canvas.frame); - } + this.colorPickerDiv.className = 'vis-color'; - this.popup.popupTargetType = popupType; - this.popup.popupTargetId = this.popupObj.id; + this.opacityDiv = document.createElement('div'); + this.opacityDiv.className = 'vis-opacity'; - // adjust a small offset such that the mouse cursor is located in the - // bottom left location of the popup, and you can easily move over the - // popup area - this.popup.setPosition(pointer.x + 3, pointer.y - 5); - this.popup.setText(this.popupObj.getTitle()); - this.popup.show(); - this.body.emitter.emit('showPopup', this.popupObj.id); - } - } else { - if (this.popup !== undefined) { - this.popup.hide(); - this.body.emitter.emit('hidePopup'); - } - } + this.brightnessDiv = document.createElement('div'); + this.brightnessDiv.className = 'vis-brightness'; + + this.arrowDiv = document.createElement('div'); + this.arrowDiv.className = 'vis-arrow'; + + this.opacityRange = document.createElement('input'); + this.opacityRange.type = 'range'; + this.opacityRange.min = '0'; + this.opacityRange.max = '100'; + this.opacityRange.value = '100'; + this.opacityRange.className = 'vis-range'; + + this.brightnessRange = document.createElement('input'); + this.brightnessRange.type = 'range'; + this.brightnessRange.min = '0'; + this.brightnessRange.max = '100'; + this.brightnessRange.value = '100'; + this.brightnessRange.className = 'vis-range'; + + this.opacityDiv.appendChild(this.opacityRange); + this.brightnessDiv.appendChild(this.brightnessRange); + + var me = this; + this.opacityRange.onchange = function () { + me._setOpacity(this.value); + }; + this.opacityRange.oninput = function () { + me._setOpacity(this.value); + }; + this.brightnessRange.onchange = function () { + me._setBrightness(this.value); + }; + this.brightnessRange.oninput = function () { + me._setBrightness(this.value); + }; + + this.brightnessLabel = document.createElement('div'); + this.brightnessLabel.className = 'vis-label vis-brightness'; + this.brightnessLabel.innerHTML = 'brightness:'; + + this.opacityLabel = document.createElement('div'); + this.opacityLabel.className = 'vis-label vis-opacity'; + this.opacityLabel.innerHTML = 'opacity:'; + + this.newColorDiv = document.createElement('div'); + this.newColorDiv.className = 'vis-new-color'; + this.newColorDiv.innerHTML = 'new'; + + this.initialColorDiv = document.createElement('div'); + this.initialColorDiv.className = 'vis-initial-color'; + this.initialColorDiv.innerHTML = 'initial'; + + this.cancelButton = document.createElement('div'); + this.cancelButton.className = 'vis-button vis-cancel'; + this.cancelButton.innerHTML = 'cancel'; + this.cancelButton.onclick = this._hide.bind(this, false); + + this.applyButton = document.createElement('div'); + this.applyButton.className = 'vis-button vis-apply'; + this.applyButton.innerHTML = 'apply'; + this.applyButton.onclick = this._apply.bind(this); + + this.saveButton = document.createElement('div'); + this.saveButton.className = 'vis-button vis-save'; + this.saveButton.innerHTML = 'save'; + this.saveButton.onclick = this._save.bind(this); + + this.loadButton = document.createElement('div'); + this.loadButton.className = 'vis-button vis-load'; + this.loadButton.innerHTML = 'load last'; + this.loadButton.onclick = this._loadLast.bind(this); + + this.frame.appendChild(this.colorPickerDiv); + this.frame.appendChild(this.arrowDiv); + this.frame.appendChild(this.brightnessLabel); + this.frame.appendChild(this.brightnessDiv); + this.frame.appendChild(this.opacityLabel); + this.frame.appendChild(this.opacityDiv); + this.frame.appendChild(this.newColorDiv); + this.frame.appendChild(this.initialColorDiv); + + this.frame.appendChild(this.cancelButton); + this.frame.appendChild(this.applyButton); + this.frame.appendChild(this.saveButton); + this.frame.appendChild(this.loadButton); } }, { - key: '_checkHidePopup', + key: '_bindHammer', /** - * Check if the popup must be hidden, which is the case when the mouse is no - * longer hovering on the object - * @param {{x:Number, y:Number}} pointer + * bind hammer to the color picker * @private */ - value: function _checkHidePopup(pointer) { - var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); + value: function _bindHammer() { + var _this = this; - var stillOnObj = false; - if (this.popup.popupTargetType === 'node') { - if (this.body.nodes[this.popup.popupTargetId] !== undefined) { - stillOnObj = this.body.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj); + this.drag = {}; + this.pinch = {}; + this.hammer = new Hammer(this.colorPickerCanvas); + this.hammer.get('pinch').set({ enable: true }); - // if the mouse is still one the node, we have to check if it is not also on one that is drawn on top of it. - // we initially only check stillOnObj because this is much faster. - if (stillOnObj === true) { - var overNode = this.selectionHandler.getNodeAt(pointer); - stillOnObj = overNode.id === this.popup.popupTargetId; - } + hammerUtil.onTouch(this.hammer, function (event) { + _this._moveSelector(event); + }); + this.hammer.on('tap', function (event) { + _this._moveSelector(event); + }); + this.hammer.on('panstart', function (event) { + _this._moveSelector(event); + }); + this.hammer.on('panmove', function (event) { + _this._moveSelector(event); + }); + this.hammer.on('panend', function (event) { + _this._moveSelector(event); + }); + } + }, { + key: '_generateHueCircle', + + /** + * generate the hue circle. This is relatively heavy (200ms) and is done only once on the first time it is shown. + * @private + */ + value: function _generateHueCircle() { + if (this.generated === false) { + var ctx = this.colorPickerCanvas.getContext('2d'); + if (this.pixelRation === undefined) { + this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); } - } else { - if (this.selectionHandler.getNodeAt(pointer) === undefined) { - if (this.body.edges[this.popup.popupTargetId] !== undefined) { - stillOnObj = this.body.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj); + ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); + + // clear the canvas + var w = this.colorPickerCanvas.clientWidth; + var h = this.colorPickerCanvas.clientHeight; + ctx.clearRect(0, 0, w, h); + + // draw hue circle + var x = undefined, + y = undefined, + hue = undefined, + sat = undefined; + this.centerCoordinates = { x: w * 0.5, y: h * 0.5 }; + this.r = 0.49 * w; + var angleConvert = 2 * Math.PI / 360; + var hfac = 1 / 360; + var sfac = 1 / this.r; + var rgb = undefined; + for (hue = 0; hue < 360; hue++) { + for (sat = 0; sat < this.r; sat++) { + x = this.centerCoordinates.x + sat * Math.sin(angleConvert * hue); + y = this.centerCoordinates.y + sat * Math.cos(angleConvert * hue); + rgb = util.HSVToRGB(hue * hfac, sat * sfac, 1); + ctx.fillStyle = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')'; + ctx.fillRect(x - 0.5, y - 0.5, 2, 2); } } - } + ctx.strokeStyle = 'rgba(0,0,0,1)'; + ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r); + ctx.stroke(); - if (stillOnObj === false) { - this.popupObj = undefined; - this.popup.hide(); - this.body.emitter.emit('hidePopup'); + this.hueCircle = ctx.getImageData(0, 0, w, h); } + this.generated = true; + } + }, { + key: '_moveSelector', + + /** + * move the selector. This is called by hammer functions. + * + * @param event + * @private + */ + value: function _moveSelector(event) { + var rect = this.colorPickerDiv.getBoundingClientRect(); + var left = event.center.x - rect.left; + var top = event.center.y - rect.top; + + var centerY = 0.5 * this.colorPickerDiv.clientHeight; + var centerX = 0.5 * this.colorPickerDiv.clientWidth; + + var x = left - centerX; + var y = top - centerY; + + var angle = Math.atan2(x, y); + var radius = 0.98 * Math.min(Math.sqrt(x * x + y * y), centerX); + + var newTop = Math.cos(angle) * radius + centerY; + var newLeft = Math.sin(angle) * radius + centerX; + + this.colorPickerSelector.style.top = newTop - 0.5 * this.colorPickerSelector.clientHeight + 'px'; + this.colorPickerSelector.style.left = newLeft - 0.5 * this.colorPickerSelector.clientWidth + 'px'; + + // set color + var h = angle / (2 * Math.PI); + h = h < 0 ? h + 1 : h; + var s = radius / this.r; + var hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b); + hsv.h = h; + hsv.s = s; + var rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v); + rgba['a'] = this.color.a; + this.color = rgba; + + // update previews + this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')'; + this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')'; } }]); - return InteractionHandler; + return ColorPicker; })(); - exports['default'] = InteractionHandler; + exports['default'] = ColorPicker; module.exports = exports['default']; /***/ }, -/* 63 */ +/* 47 */ /***/ function(module, exports, __webpack_require__) { - "use strict"; + 'use strict'; - Object.defineProperty(exports, "__esModule", { + Object.defineProperty(exports, '__esModule', { value: true }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - var Node = __webpack_require__(74); - var Edge = __webpack_require__(76); - var util = __webpack_require__(2); - - var SelectionHandler = (function () { - function SelectionHandler(body, canvas) { - var _this = this; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - _classCallCheck(this, SelectionHandler); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - this.body = body; - this.canvas = canvas; - this.selectionObj = { nodes: [], edges: [] }; - this.hoverObj = { nodes: {}, edges: {} }; + var util = __webpack_require__(7); - this.options = {}; - this.defaultOptions = { - multiselect: false, - selectable: true, - selectConnectedEdges: true, - hoverConnectedEdges: true - }; - util.extend(this.options, this.defaultOptions); + var errorFound = false; + var allOptions = undefined; + var printStyle = 'background: #FFeeee; color: #dd0000'; + /** + * Used to validate options. + */ - this.body.emitter.on("_dataChanged", function () { - _this.updateSelection(); - }); + var Validator = (function () { + function Validator() { + _classCallCheck(this, Validator); } - _createClass(SelectionHandler, [{ - key: "setOptions", - value: function setOptions(options) { - if (options !== undefined) { - var fields = ["multiselect", "hoverConnectedEdges", "selectable", "selectConnectedEdges"]; - util.selectiveDeepExtend(fields, this.options, options); + _createClass(Validator, null, [{ + key: 'validate', + + /** + * Main function to be called + * @param options + * @param subObject + * @returns {boolean} + */ + 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; } }, { - key: "selectOnPoint", + key: 'parse', /** - * handles the selection part of the tap; - * - * @param {Object} pointer - * @private + * Will traverse an object recursively and check every value + * @param options + * @param referenceOptions + * @param path */ - value: function selectOnPoint(pointer) { - var selected = false; - if (this.options.selectable === true) { - this.unselectAll(); - var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer); - if (obj !== undefined) { - selected = this.selectObject(obj); + value: function parse(options, referenceOptions, path) { + for (var option in options) { + if (options.hasOwnProperty(option)) { + Validator.check(option, options, referenceOptions, path); } - this.body.emitter.emit("_requestRedraw"); } - return selected; } }, { - key: "selectAdditionalOnPoint", - value: function selectAdditionalOnPoint(pointer) { - var selectionChanged = false; - if (this.options.selectable === true) { - var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer); - - if (obj !== undefined) { - selectionChanged = true; - if (obj.isSelected() === true) { - this.deselectObject(obj); - } else { - this.selectObject(obj); - } + key: 'check', - this.body.emitter.emit("_requestRedraw"); + /** + * Check every value. If the value is an object, call the parse function on that object. + * @param option + * @param options + * @param referenceOptions + * @param path + */ + value: function check(option, options, referenceOptions, path) { + if (referenceOptions[option] === undefined && referenceOptions.__any__ === undefined) { + Validator.getSuggestion(option, referenceOptions, path); + } else if (referenceOptions[option] === undefined && referenceOptions.__any__ !== undefined) { + // __any__ is a wildcard. Any value is accepted and will be further analysed by reference. + if (Validator.getType(options[option]) === 'object') { + Validator.checkFields(option, options, referenceOptions, '__any__', referenceOptions['__any__'].__type__, path); + } + } else { + // Since all options in the reference are objects, we can check whether they are supposed to be object to look for the __type__ field. + if (referenceOptions[option].__type__ !== undefined) { + // if this should be an object, we check if the correct type has been supplied to account for shorthand options. + Validator.checkFields(option, options, referenceOptions, option, referenceOptions[option].__type__, path); + } else { + Validator.checkFields(option, options, referenceOptions, option, referenceOptions[option], path); } } - return selectionChanged; } }, { - key: "_generateClickEvent", - value: function _generateClickEvent(eventType, event, pointer, oldSelection) { - var properties = this.getSelection(); - properties["pointer"] = { - DOM: { x: pointer.x, y: pointer.y }, - canvas: this.canvas.DOMtoCanvas(pointer) - }; - properties["event"] = event; + key: 'checkFields', - if (oldSelection !== undefined) { - properties["previousSelection"] = oldSelection; + /** + * + * @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} refOptionType | This is the type object from the reference options + * @param {Array} path | where in the object is the option + */ + value: function checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path) { + 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') { + if (refOptionType.indexOf(options[option]) === -1) { + console.log('%cInvalid option detected in "' + option + '".' + ' Allowed values are:' + Validator.print(refOptionType) + ' not "' + options[option] + '". ' + Validator.printLocation(path, option), printStyle); + errorFound = true; + } else if (optionType === 'object') { + path = util.copyAndExtendArray(path, option); + Validator.parse(options[option], referenceOptions[referenceOption], path); + } + } else if (optionType === 'object') { + path = util.copyAndExtendArray(path, option); + Validator.parse(options[option], referenceOptions[referenceOption], path); + } + } else { + if (refOptionObj['undef'] !== undefined && optionType === 'undefined') {} else if (refOptionObj['fn'] !== undefined && optionType === 'function') {} else { + // type of the field is incorrect + console.log('%cInvalid type received for "' + option + '". Expected: ' + Validator.print(Object.keys(refOptionObj)) + '. Received [' + optionType + '] "' + options[option] + '"' + Validator.printLocation(path, option), printStyle); + errorFound = true; + } } - this.body.emitter.emit(eventType, properties); } }, { - key: "selectObject", - value: function selectObject(obj) { - var highlightEdges = arguments[1] === undefined ? this.options.selectConnectedEdges : arguments[1]; + key: 'getType', + value: function getType(object) { + var type = typeof object; - if (obj !== undefined) { - if (obj instanceof Node) { - if (highlightEdges === true) { - this._selectConnectedEdges(obj); - } + if (type === 'object') { + if (object === null) { + return 'null'; } - obj.select(); - this._addToSelection(obj); - return true; - } - return false; - } - }, { - key: "deselectObject", - value: function deselectObject(obj) { - if (obj.isSelected() === true) { - obj.selected = false; - this._removeFromSelection(obj); - } - } - }, { - key: "_getAllNodesOverlappingWith", - - /** - * retrieve all nodes overlapping with given object - * @param {Object} object An object with parameters left, top, right, bottom - * @return {Number[]} An array with id's of the overlapping nodes - * @private - */ - value: function _getAllNodesOverlappingWith(object) { - var overlappingNodes = []; - var nodes = this.body.nodes; - for (var i = 0; i < this.body.nodeIndices.length; i++) { - var nodeId = this.body.nodeIndices[i]; - if (nodes[nodeId].isOverlappingWith(object)) { - overlappingNodes.push(nodeId); + if (object instanceof Boolean) { + return 'boolean'; } - } - return overlappingNodes; - } - }, { - key: "_pointerToPositionObject", - - /** - * Return a position object in canvasspace from a single point in screenspace - * - * @param pointer - * @returns {{left: number, top: number, right: number, bottom: number}} - * @private - */ - value: function _pointerToPositionObject(pointer) { - var canvasPos = this.canvas.DOMtoCanvas(pointer); - return { - left: canvasPos.x - 1, - top: canvasPos.y + 1, - right: canvasPos.x + 1, - bottom: canvasPos.y - 1 - }; - } - }, { - key: "getNodeAt", - - /** - * Get the top node at the a specific point (like a click) - * - * @param {{x: Number, y: Number}} pointer - * @return {Node | undefined} node - * @private - */ - value: function getNodeAt(pointer) { - var returnNode = arguments[1] === undefined ? true : arguments[1]; - - // we first check if this is an navigation controls element - var positionObject = this._pointerToPositionObject(pointer); - var overlappingNodes = this._getAllNodesOverlappingWith(positionObject); - // if there are overlapping nodes, select the last one, this is the - // one which is drawn on top of the others - if (overlappingNodes.length > 0) { - if (returnNode === true) { - return this.body.nodes[overlappingNodes[overlappingNodes.length - 1]]; - } else { - return overlappingNodes[overlappingNodes.length - 1]; + if (object instanceof Number) { + return 'number'; } - } else { - return undefined; - } - } - }, { - key: "_getEdgesOverlappingWith", - - /** - * retrieve all edges overlapping with given object, selector is around center - * @param {Object} object An object with parameters left, top, right, bottom - * @return {Number[]} An array with id's of the overlapping nodes - * @private - */ - value: function _getEdgesOverlappingWith(object, overlappingEdges) { - var edges = this.body.edges; - for (var i = 0; i < this.body.edgeIndices.length; i++) { - var edgeId = this.body.edgeIndices[i]; - if (edges[edgeId].isOverlappingWith(object)) { - overlappingEdges.push(edgeId); + 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; } }, { - key: "_getAllEdgesOverlappingWith", - - /** - * retrieve all nodes overlapping with given object - * @param {Object} object An object with parameters left, top, right, bottom - * @return {Number[]} An array with id's of the overlapping nodes - * @private - */ - value: function _getAllEdgesOverlappingWith(object) { - var overlappingEdges = []; - this._getEdgesOverlappingWith(object, overlappingEdges); - return overlappingEdges; - } - }, { - key: "getEdgeAt", - - /** - * Place holder. To implement change the getNodeAt to a _getObjectAt. Have the _getObjectAt call - * getNodeAt and _getEdgesAt, then priortize the selection to user preferences. - * - * @param pointer - * @returns {undefined} - * @private - */ - value: function getEdgeAt(pointer) { - var returnEdge = arguments[1] === undefined ? true : arguments[1]; + key: 'getSuggestion', + value: function getSuggestion(option, options, path) { + var localSearch = Validator.findInOptions(option, options, path, false); + var globalSearch = Validator.findInOptions(option, allOptions, [], true); - var positionObject = this._pointerToPositionObject(pointer); - var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject); + var localSearchThreshold = 8; + var globalSearchThreshold = 4; - if (overlappingEdges.length > 0) { - if (returnEdge === true) { - return this.body.edges[overlappingEdges[overlappingEdges.length - 1]]; - } else { - return overlappingEdges[overlappingEdges.length - 1]; - } + if (localSearch.indexMatch !== undefined) { + console.log('%cUnknown option detected: "' + option + '" in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was incomplete? Did you mean: "' + localSearch.indexMatch + '"?\n\n', printStyle); + } else if (globalSearch.distance <= globalSearchThreshold && localSearch.distance > globalSearch.distance) { + console.log('%cUnknown option detected: "' + option + '" in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was misplaced? Matching option found at: ' + Validator.printLocation(globalSearch.path, globalSearch.closestMatch, ''), printStyle); + } else if (localSearch.distance <= localSearchThreshold) { + console.log('%cUnknown option detected: "' + option + '". Did you mean "' + localSearch.closestMatch + '"?' + Validator.printLocation(localSearch.path, option), printStyle); } else { - return undefined; + console.log('%cUnknown option detected: "' + option + '". Did you mean one of these: ' + Validator.print(Object.keys(options)) + Validator.printLocation(path, option), printStyle); } - } - }, { - key: "_addToSelection", - /** - * Add object to the selection array. - * - * @param obj - * @private - */ - value: function _addToSelection(obj) { - if (obj instanceof Node) { - this.selectionObj.nodes[obj.id] = obj; - } else { - this.selectionObj.edges[obj.id] = obj; - } + errorFound = true; } }, { - key: "_addToHover", + key: 'findInOptions', /** - * Add object to the selection array. - * - * @param obj - * @private + * traverse the options in search for a match. + * @param option + * @param options + * @param path + * @param recursive + * @returns {{closestMatch: string, path: Array, distance: number}} */ - value: function _addToHover(obj) { - if (obj instanceof Node) { - this.hoverObj.nodes[obj.id] = obj; - } else { - this.hoverObj.edges[obj.id] = obj; - } - } - }, { - key: "_removeFromSelection", + value: function findInOptions(option, options, path) { + var recursive = arguments[3] === undefined ? false : arguments[3]; - /** - * Remove a single option from selection. - * - * @param {Object} obj - * @private - */ - value: function _removeFromSelection(obj) { - if (obj instanceof Node) { - delete this.selectionObj.nodes[obj.id]; - } else { - delete this.selectionObj.edges[obj.id]; + var min = 1000000000; + var closestMatch = ''; + var closestMatchPath = []; + var lowerCaseOption = option.toLowerCase(); + var indexMatch = undefined; + for (var op in options) { + var distance = undefined; + 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 }; } }, { - key: "unselectAll", + key: 'printLocation', + value: function printLocation(path, option) { + var prefix = arguments[2] === undefined ? 'Problem value found at: \n' : arguments[2]; - /** - * Unselect all. The selectionObj is useful for this. - * - * @private - */ - value: function unselectAll() { - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - this.selectionObj.nodes[nodeId].unselect(); + 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 edgeId in this.selectionObj.edges) { - if (this.selectionObj.edges.hasOwnProperty(edgeId)) { - this.selectionObj.edges[edgeId].unselect(); - } + for (var j = 0; j < path.length + 1; j++) { + str += ' '; } - - this.selectionObj = { nodes: {}, edges: {} }; - } - }, { - key: "_getSelectedNodeCount", - - /** - * return the number of selected nodes - * - * @returns {number} - * @private - */ - value: function _getSelectedNodeCount() { - var count = 0; - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - count += 1; + str += option + '\n'; + for (var i = 0; i < path.length + 1; i++) { + for (var j = 0; j < path.length - i; j++) { + str += ' '; } + str += '}\n'; } - return count; + return str + '\n\n'; } }, { - key: "_getSelectedNode", - - /** - * return the selected node - * - * @returns {number} - * @private - */ - value: function _getSelectedNode() { - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - return this.selectionObj.nodes[nodeId]; - } - } - return undefined; + key: 'print', + value: function print(options) { + return JSON.stringify(options).replace(/(\")|(\[)|(\])|(,"__type__")/g, '').replace(/(\,)/g, ', '); } }, { - key: "_getSelectedEdge", + key: 'levenshteinDistance', - /** - * return the selected edge - * - * @returns {number} - * @private + // 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. */ - value: function _getSelectedEdge() { - for (var edgeId in this.selectionObj.edges) { - if (this.selectionObj.edges.hasOwnProperty(edgeId)) { - return this.selectionObj.edges[edgeId]; - } - } - return undefined; - } - }, { - key: "_getSelectedEdgeCount", + value: function levenshteinDistance(a, b) { + if (a.length === 0) return b.length; + if (b.length === 0) return a.length; - /** - * return the number of selected edges - * - * @returns {number} - * @private - */ - value: function _getSelectedEdgeCount() { - var count = 0; - for (var edgeId in this.selectionObj.edges) { - if (this.selectionObj.edges.hasOwnProperty(edgeId)) { - count += 1; - } - } - return count; - } - }, { - key: "_getSelectedObjectCount", + var matrix = []; - /** - * return the number of selected objects. - * - * @returns {number} - * @private - */ - value: function _getSelectedObjectCount() { - var count = 0; - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - count += 1; - } - } - for (var edgeId in this.selectionObj.edges) { - if (this.selectionObj.edges.hasOwnProperty(edgeId)) { - count += 1; - } + // increment along the first column of each row + var i; + for (i = 0; i <= b.length; i++) { + matrix[i] = [i]; } - return count; - } - }, { - key: "_selectionIsEmpty", - /** - * Check if anything is selected - * - * @returns {boolean} - * @private - */ - value: function _selectionIsEmpty() { - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - return false; - } - } - for (var edgeId in this.selectionObj.edges) { - if (this.selectionObj.edges.hasOwnProperty(edgeId)) { - return false; - } + // increment each column in the first row + var j; + for (j = 0; j <= a.length; j++) { + matrix[0][j] = j; } - return true; - } - }, { - key: "_clusterInSelection", - /** - * check if one of the selected nodes is a cluster. - * - * @returns {boolean} - * @private - */ - value: function _clusterInSelection() { - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - if (this.selectionObj.nodes[nodeId].clusterSize > 1) { - return true; + // 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 false; - } - }, { - key: "_selectConnectedEdges", - /** - * select the edges connected to the node that is being selected - * - * @param {Node} node - * @private - */ - value: function _selectConnectedEdges(node) { - for (var i = 0; i < node.edges.length; i++) { - var edge = node.edges[i]; - edge.select(); - this._addToSelection(edge); - } + return matrix[b.length][a.length]; } - }, { - key: "_hoverConnectedEdges", + }]); - /** - * select the edges connected to the node that is being selected - * - * @param {Node} node - * @private - */ - value: function _hoverConnectedEdges(node) { - for (var i = 0; i < node.edges.length; i++) { - var edge = node.edges[i]; - edge.hover = true; - this._addToHover(edge); - } - } - }, { - key: "_unselectConnectedEdges", + return Validator; + })(); - /** - * unselect the edges connected to the node that is being selected - * - * @param {Node} node - * @private - */ - value: function _unselectConnectedEdges(node) { - for (var i = 0; i < node.edges.length; i++) { - var edge = node.edges[i]; - edge.unselect(); - this._removeFromSelection(edge); - } - } - }, { - key: "blurObject", + exports['default'] = Validator; + exports.printStyle = printStyle; - /** - * This is called when someone clicks on a node. either select or deselect it. - * If there is an existing selection and we don't want to append to it, clear the existing selection - * - * @param {Node || Edge} object - * @private - */ - value: function blurObject(object) { - if (object.hover === true) { - object.hover = false; - this.body.emitter.emit("blurNode", { node: object.id }); - } - } - }, { - key: "hoverObject", + // item is undefined, which is allowed - /** - * This is called when someone clicks on a node. either select or deselect it. - * If there is an existing selection and we don't want to append to it, clear the existing selection - * - * @param {Node || Edge} object - * @private - */ - value: function hoverObject(object) { - var hoverChanged = false; - // remove all node hover highlights - for (var nodeId in this.hoverObj.nodes) { - if (this.hoverObj.nodes.hasOwnProperty(nodeId)) { - if (object === undefined) { - this.blurObject(this.hoverObj.nodes[nodeId]); - hoverChanged = true; - } else if (object instanceof Node && object.id != nodeId || object instanceof Edge || object === undefined) { - this.blurObject(this.hoverObj.nodes[nodeId]); - hoverChanged = true; - delete this.hoverObj.nodes[nodeId]; - } - } - } + // item is a function, which is allowed - // removing all edge hover highlights - for (var edgeId in this.hoverObj.edges) { - if (this.hoverObj.edges.hasOwnProperty(edgeId)) { - this.hoverObj.edges[edgeId].hover = false; - delete this.hoverObj.edges[edgeId]; - } - } +/***/ }, +/* 48 */ +/***/ function(module, exports, __webpack_require__) { - if (object !== undefined) { - if (object.hover === false) { - object.hover = true; - this._addToHover(object); - hoverChanged = true; - if (object instanceof Node) { - this.body.emitter.emit("hoverNode", { node: object.id }); - } - } - if (object instanceof Node && this.options.hoverConnectedEdges === true) { - this._hoverConnectedEdges(object); - } - } + /** + * This object contains all possible options. It will check if the types are correct, if required if the option is one + * of the allowed values. + * + * __any__ means that the name of the property does not matter. + * __type__ is a required field for all objects and contains the allowed types of all objects + */ + 'use strict'; - if (hoverChanged === true) { - this.body.emitter.emit("_requestRedraw"); - } - } - }, { - key: "getSelection", + Object.defineProperty(exports, '__esModule', { + value: true + }); + var string = 'string'; + var boolean = 'boolean'; + var number = 'number'; + var array = 'array'; + var date = 'date'; + var object = 'object'; // should only be in a __type__ property + var dom = 'dom'; + var moment = 'moment'; + var fn = 'function'; + var nada = 'null'; + var undef = 'undefined'; + var any = 'any'; - /** - * - * retrieve the currently selected objects - * @return {{nodes: Array., edges: Array.}} selection - */ - value: function getSelection() { - var nodeIds = this.getSelectedNodes(); - var edgeIds = this.getSelectedEdges(); - return { nodes: nodeIds, edges: edgeIds }; - } - }, { - key: "getSelectedNodes", + var allOptions = { + configure: { + enabled: { boolean: boolean }, + filter: { boolean: boolean, fn: fn }, + container: { dom: dom }, + __type__: { object: object, boolean: boolean, fn: fn } + }, - /** - * - * retrieve the currently selected nodes - * @return {String[]} selection An array with the ids of the - * selected nodes. - */ - value: function getSelectedNodes() { - var idArray = []; - if (this.options.selectable === true) { - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - idArray.push(nodeId); - } - } - } - return idArray; - } - }, { - key: "getSelectedEdges", + //globals : + align: { string: string }, + autoResize: { boolean: boolean }, + clickToUse: { boolean: boolean }, + dataAttributes: { string: string, array: array }, + editable: { + add: { boolean: boolean, undef: undef }, + remove: { boolean: boolean, undef: undef }, + updateGroup: { boolean: boolean, undef: undef }, + updateTime: { boolean: boolean, undef: undef }, + __type__: { boolean: boolean, object: object } + }, + end: { number: number, date: date, string: string, moment: moment }, + format: { + minorLabels: { + millisecond: { string: string, undef: undef }, + second: { string: string, undef: undef }, + minute: { string: string, undef: undef }, + hour: { string: string, undef: undef }, + weekday: { string: string, undef: undef }, + day: { string: string, undef: undef }, + month: { string: string, undef: undef }, + year: { string: string, undef: undef }, + __type__: { object: object } + }, + majorLabels: { + millisecond: { string: string, undef: undef }, + second: { string: string, undef: undef }, + minute: { string: string, undef: undef }, + hour: { string: string, undef: undef }, + weekday: { string: string, undef: undef }, + day: { string: string, undef: undef }, + month: { string: string, undef: undef }, + year: { string: string, undef: undef }, + __type__: { object: object } + }, + __type__: { object: object } + }, + groupOrder: { string: string, fn: fn }, + height: { string: string, number: number }, + hiddenDates: { object: object, array: array }, + locale: { string: string }, + locales: { + __any__: { object: object }, + __type__: { object: object } + }, + margin: { + axis: { number: number }, + item: { + horizontal: { number: number, undef: undef }, + vertical: { number: number, undef: undef }, + __type__: { object: object, number: number } + }, + __type__: { object: object, number: number } + }, + max: { date: date, number: number, string: string, moment: moment }, + maxHeight: { number: number, string: string }, + min: { date: date, number: number, string: string, moment: moment }, + minHeight: { number: number, string: string }, + moveable: { boolean: boolean }, + multiselect: { boolean: boolean }, + onAdd: { fn: fn }, + onUpdate: { fn: fn }, + onMove: { fn: fn }, + onMoving: { fn: fn }, + onRemove: { fn: fn }, + order: { fn: fn }, + orientation: { + axis: { string: string, undef: undef }, + item: { string: string, undef: undef }, + __type__: { string: string, object: object } + }, + selectable: { boolean: boolean }, + showCurrentTime: { boolean: boolean }, + showMajorLabels: { boolean: boolean }, + showMinorLabels: { boolean: boolean }, + stack: { boolean: boolean }, + snap: { fn: fn, nada: nada }, + start: { date: date, number: number, string: string, moment: moment }, + template: { fn: fn }, + timeAxis: { + scale: { string: string, undef: undef }, + step: { number: number, undef: undef }, + __type__: { object: object } + }, + type: { string: string }, + width: { string: string, number: number }, + zoomable: { boolean: boolean }, + zoomMax: { number: number }, + zoomMin: { number: number }, - /** - * - * retrieve the currently selected edges - * @return {Array} selection An array with the ids of the - * selected nodes. - */ - value: function getSelectedEdges() { - var idArray = []; - if (this.options.selectable === true) { - for (var edgeId in this.selectionObj.edges) { - if (this.selectionObj.edges.hasOwnProperty(edgeId)) { - idArray.push(edgeId); - } - } + __type__: { object: object } + }; + + var configureOptions = { + global: { + align: ['center', 'left', 'right'], + autoResize: true, + clickToUse: false, + // dataAttributes: ['all'], // FIXME: can be 'all' or string[] + editable: { + add: false, + remove: false, + updateGroup: false, + updateTime: false + }, + end: '', + format: { + minorLabels: { + millisecond: 'SSS', + second: 's', + minute: 'HH:mm', + hour: 'HH:mm', + weekday: 'ddd D', + day: 'D', + 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', + month: 'YYYY', + year: '' } - return idArray; - } - }, { - key: "selectNodes", + }, - /** - * select zero or more nodes with the option to highlight edges - * @param {Number[] | String[]} selection An array with the ids of the - * selected nodes. - * @param {boolean} [highlightEdges] - */ - value: function selectNodes(selection) { - var highlightEdges = arguments[1] === undefined ? true : arguments[1]; + //groupOrder: {string, fn}, + height: '', + //hiddenDates: {object, array}, + locale: '', + margin: { + axis: [20, 0, 100, 1], + item: { + horizontal: [10, 0, 100, 1], + vertical: [10, 0, 100, 1] + } + }, + max: '', + maxHeight: '', + min: '', + minHeight: '', + moveable: false, + multiselect: false, + //onAdd: {fn}, + //onUpdate: {fn}, + //onMove: {fn}, + //onMoving: {fn}, + //onRename: {fn}, + //order: {fn}, + orientation: { + axis: ['both', 'bottom', 'top'], + item: ['bottom', 'top'] + }, + selectable: true, + showCurrentTime: false, + showMajorLabels: true, + showMinorLabels: true, + stack: true, + //snap: {fn, nada}, + start: '', + //template: {fn}, + //timeAxis: { + // scale: ['millisecond', 'second', 'minute', 'hour', 'weekday', 'day', 'month', 'year'], + // step: [1, 1, 10, 1] + //}, + type: ['box', 'point', 'range', 'background'], + width: '100%', + zoomable: true, + zoomMax: [315360000000000, 10, 315360000000000, 1], + zoomMin: [10, 10, 315360000000000, 1] + } + }; - var i = undefined, - id = undefined; + exports.allOptions = allOptions; + exports.configureOptions = configureOptions; - if (!selection || selection.length === undefined) throw "Selection must be an array with ids"; +/***/ }, +/* 49 */ +/***/ function(module, exports, __webpack_require__) { - // first unselect any selected node - this.unselectAll(); + 'use strict'; - for (i = 0; i < selection.length; i++) { - id = selection[i]; + var Emitter = __webpack_require__(19); + var Hammer = __webpack_require__(3); + var util = __webpack_require__(7); + var DataSet = __webpack_require__(14); + var DataView = __webpack_require__(16); + var Range = __webpack_require__(29); + var Core = __webpack_require__(32); + var TimeAxis = __webpack_require__(41); + var CurrentTime = __webpack_require__(26); + var CustomTime = __webpack_require__(44); + var LineGraph = __webpack_require__(50); - var node = this.body.nodes[id]; - if (!node) { - throw new RangeError("Node with id \"" + id + "\" not found"); - } - this.selectObject(node, highlightEdges); - } - this.body.emitter.emit("_requestRedraw"); - } - }, { - key: "selectEdges", + var Configurator = __webpack_require__(45); + var Validator = __webpack_require__(47)['default']; + var printStyle = __webpack_require__(47).printStyle; + var allOptions = __webpack_require__(58).allOptions; + var configureOptions = __webpack_require__(58).configureOptions; - /** - * select zero or more edges - * @param {Number[] | String[]} selection An array with the ids of the - * selected nodes. - */ - value: function selectEdges(selection) { - var i = undefined, - id = undefined; + /** + * Create a timeline visualization + * @param {HTMLElement} container + * @param {vis.DataSet | Array} [items] + * @param {Object} [options] See Graph2d.setOptions for the available options. + * @constructor + * @extends Core + */ + function Graph2d(container, items, groups, options) { + // if the third element is options, the forth is groups (optionally); + if (!(Array.isArray(groups) || groups instanceof DataSet) && groups instanceof Object) { + var forthArgument = options; + options = groups; + groups = forthArgument; + } - if (!selection || selection.length === undefined) throw "Selection must be an array with ids"; + var me = this; + this.defaultOptions = { + start: null, + end: null, - // first unselect any selected objects - this.unselectAll(); + autoResize: true, - for (i = 0; i < selection.length; i++) { - id = selection[i]; + orientation: { + axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both' + item: 'bottom' // not relevant for Graph2d + }, - var edge = this.body.edges[id]; - if (!edge) { - throw new RangeError("Edge with id \"" + id + "\" not found"); - } - this.selectObject(edge); - } - this.body.emitter.emit("_requestRedraw"); - } - }, { - key: "updateSelection", + width: null, + height: null, + maxHeight: null, + minHeight: null + }; + this.options = util.deepExtend({}, this.defaultOptions); - /** - * Validate the selection: remove ids of nodes which no longer exist - * @private - */ - value: function updateSelection() { - for (var nodeId in this.selectionObj.nodes) { - if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { - if (!this.body.nodes.hasOwnProperty(nodeId)) { - delete this.selectionObj.nodes[nodeId]; - } - } - } - for (var edgeId in this.selectionObj.edges) { - if (this.selectionObj.edges.hasOwnProperty(edgeId)) { - if (!this.body.edges.hasOwnProperty(edgeId)) { - delete this.selectionObj.edges[edgeId]; - } - } - } - } - }]); + // Create the DOM, props, and emitter + this._create(container); - return SelectionHandler; - })(); + // all components listed here will be repainted automatically + this.components = []; - exports["default"] = SelectionHandler; - module.exports = exports["default"]; + this.body = { + dom: this.dom, + domProps: this.props, + emitter: { + on: this.on.bind(this), + off: this.off.bind(this), + emit: this.emit.bind(this) + }, + hiddenDates: [], + util: { + toScreen: me._toScreen.bind(me), + toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width + toTime: me._toTime.bind(me), + toGlobalTime: me._toGlobalTime.bind(me) + } + }; -/***/ }, -/* 64 */ -/***/ function(module, exports, __webpack_require__) { + // range + this.range = new Range(this.body); + this.components.push(this.range); + this.body.range = this.range; - 'use strict'; + // time axis + this.timeAxis = new TimeAxis(this.body); + this.components.push(this.timeAxis); + //this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); - Object.defineProperty(exports, '__esModule', { - value: true - }); + // current time bar + this.currentTime = new CurrentTime(this.body); + this.components.push(this.currentTime); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // item set + this.linegraph = new LineGraph(this.body); + this.components.push(this.linegraph); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + this.itemsData = null; // DataSet + this.groupsData = null; // DataSet - var util = __webpack_require__(2); + this.on('tap', function (event) { + me.emit('click', me.getEventProperties(event)); + }); + this.on('doubletap', function (event) { + me.emit('doubleClick', me.getEventProperties(event)); + }); + this.dom.root.oncontextmenu = function (event) { + me.emit('contextmenu', me.getEventProperties(event)); + }; - var LayoutEngine = (function () { - function LayoutEngine(body) { - _classCallCheck(this, LayoutEngine); + // setup configuration system + this.configurator = new Configurator(this, container, configureOptions); - this.body = body; + // apply options + if (options) { + this.setOptions(options); + } - this.initialRandomSeed = Math.round(Math.random() * 1000000); - this.randomSeed = this.initialRandomSeed; - this.options = {}; - this.optionsBackup = {}; + // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! + if (groups) { + this.setGroups(groups); + } - this.defaultOptions = { - randomSeed: undefined, - hierarchical: { - enabled: false, - levelSeparation: 150, - direction: 'UD', // UD, DU, LR, RL - sortMethod: 'hubsize' // hubsize, directed - } - }; - util.extend(this.options, this.defaultOptions); + // create itemset + if (items) { + this.setItems(items); + } else { + this._redraw(); + } + } - this.hierarchicalLevels = {}; + // Extend the functionality from Core + Graph2d.prototype = new Core(); - this.bindEventListeners(); + Graph2d.prototype.setOptions = function (options) { + // validate options + var errorFound = Validator.validate(options, allOptions); + if (errorFound === true) { + console.log('%cErrors have been found in the supplied options object.', printStyle); } - _createClass(LayoutEngine, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this = this; - - this.body.emitter.on('_dataChanged', function () { - _this.setupHierarchicalLayout(); - }); - this.body.emitter.on('_resetHierarchicalLayout', function () { - _this.setupHierarchicalLayout(); - }); - } - }, { - key: 'setOptions', - value: function setOptions(options, allOptions) { - if (options !== undefined) { - var prevHierarchicalState = this.options.hierarchical.enabled; - - util.mergeOptions(this.options, options, 'hierarchical'); - if (options.randomSeed !== undefined) { - this.initialRandomSeed = options.randomSeed; - } + Core.prototype.setOptions.call(this, options); + }; - if (this.options.hierarchical.enabled === true) { - // make sure the level seperation is the right way up - if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'DU') { - if (this.options.hierarchical.levelSeparation > 0) { - this.options.hierarchical.levelSeparation *= -1; - } - } else { - if (this.options.hierarchical.levelSeparation < 0) { - this.options.hierarchical.levelSeparation *= -1; - } - } + /** + * Set items + * @param {vis.DataSet | Array | null} items + */ + Graph2d.prototype.setItems = function (items) { + var initialLoad = this.itemsData == null; - this.body.emitter.emit('_resetHierarchicalLayout'); - // because the hierarchical system needs it's own physics and smooth curve settings, we adapt the other options if needed. - return this.adaptAllOptions(allOptions); - } else { - if (prevHierarchicalState === true) { - // refresh the overridden options for nodes and edges. - this.body.emitter.emit('refresh'); - return util.deepExtend(allOptions, this.optionsBackup); - } - } + // convert to type DataSet when needed + var newDataSet; + if (!items) { + newDataSet = null; + } else if (items instanceof DataSet || items instanceof DataView) { + newDataSet = items; + } else { + // turn an array into a dataset + newDataSet = new DataSet(items, { + type: { + start: 'Date', + end: 'Date' } - return allOptions; - } - }, { - key: 'adaptAllOptions', - value: function adaptAllOptions(allOptions) { - if (this.options.hierarchical.enabled === true) { - // set the physics - if (allOptions.physics === undefined || allOptions.physics === true) { - allOptions.physics = { solver: 'hierarchicalRepulsion' }; - this.optionsBackup.physics = { solver: 'barnesHut' }; - } else if (typeof allOptions.physics === 'object') { - this.optionsBackup.physics = { solver: 'barnesHut' }; - if (allOptions.physics.solver !== undefined) { - this.optionsBackup.physics = { solver: allOptions.physics.solver }; - } - allOptions.physics['solver'] = 'hierarchicalRepulsion'; - } else if (allOptions.physics !== false) { - this.optionsBackup.physics = { solver: 'barnesHut' }; - allOptions.physics['solver'] = 'hierarchicalRepulsion'; - } - - // get the type of static smooth curve in case it is required - var type = 'horizontal'; - if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'LR') { - type = 'vertical'; - } + }); + } - // disable smooth curves if nothing is defined. If smooth curves have been turned on, turn them into static smooth curves. - if (allOptions.edges === undefined) { - this.optionsBackup.edges = { smooth: { enabled: true, type: 'dynamic' } }; - allOptions.edges = { smooth: false }; - } else if (allOptions.edges.smooth === undefined) { - this.optionsBackup.edges = { smooth: { enabled: true, type: 'dynamic' } }; - allOptions.edges.smooth = false; - } else { - if (typeof allOptions.edges.smooth === 'boolean') { - this.optionsBackup.edges = { smooth: allOptions.edges.smooth }; - allOptions.edges.smooth = { enabled: allOptions.edges.smooth, type: type }; - } else { - // allow custom types except for dynamic - if (allOptions.edges.smooth.type !== undefined && allOptions.edges.smooth.type !== 'dynamic') { - type = allOptions.edges.smooth.type; - } + // set items + this.itemsData = newDataSet; + this.linegraph && this.linegraph.setItems(newDataSet); - this.optionsBackup.edges = { - smooth: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled, - type: allOptions.edges.smooth.type === undefined ? 'dynamic' : allOptions.edges.smooth.type, - roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness - }; - allOptions.edges.smooth = { - enabled: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled, - type: type, - roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness - }; - } - } + if (initialLoad) { + if (this.options.start != undefined || this.options.end != undefined) { + var start = this.options.start != undefined ? this.options.start : null; + var end = this.options.end != undefined ? this.options.end : null; - // force all edges into static smooth curves. Only applies to edges that do not use the global options for smooth. - this.body.emitter.emit('_forceDisableDynamicCurves', type); - } - return allOptions; - } - }, { - key: 'seededRandom', - value: function seededRandom() { - var x = Math.sin(this.randomSeed++) * 10000; - return x - Math.floor(x); - } - }, { - key: 'positionInitially', - value: function positionInitially(nodesArray) { - if (this.options.hierarchical.enabled !== true) { - this.randomSeed = this.initialRandomSeed; - for (var i = 0; i < nodesArray.length; i++) { - var node = nodesArray[i]; - if (!node.isFixed() && (node.x === undefined || node.y === undefined)) { - var radius = 10 * 0.1 * nodesArray.length + 10; - var angle = 2 * Math.PI * this.seededRandom(); - if (node.options.fixed.x === false) { - node.x = radius * Math.cos(angle); - } - if (node.options.fixed.x === false) { - node.y = radius * Math.sin(angle); - } - } - } - } - } - }, { - key: 'getSeed', - value: function getSeed() { - return this.initialRandomSeed; + this.setWindow(start, end, { animation: false }); + } else { + this.fit({ animation: false }); } - }, { - key: 'setupHierarchicalLayout', + } + }; - /** - * This is the main function to layout the nodes in a hierarchical way. - * It checks if the node details are supplied correctly - * - * @private - */ - value: function setupHierarchicalLayout() { - if (this.options.hierarchical.enabled === true && this.body.nodeIndices.length > 0) { - // get the size of the largest hubs and check if the user has defined a level for a node. - var node = undefined, - nodeId = undefined; - var definedLevel = false; - var undefinedLevel = false; - this.hierarchicalLevels = {}; - this.nodeSpacing = 100; + /** + * Set groups + * @param {vis.DataSet | Array} groups + */ + Graph2d.prototype.setGroups = function (groups) { + // convert to type DataSet when needed + var newDataSet; + if (!groups) { + newDataSet = null; + } else if (groups instanceof DataSet || groups instanceof DataView) { + newDataSet = groups; + } else { + // turn an array into a dataset + newDataSet = new DataSet(groups); + } - for (nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - node = this.body.nodes[nodeId]; - if (node.options.level !== undefined) { - definedLevel = true; - this.hierarchicalLevels[nodeId] = node.options.level; - } else { - undefinedLevel = true; - } - } - } + this.groupsData = newDataSet; + this.linegraph.setGroups(newDataSet); + }; - // if the user defined some levels but not all, alert and run without hierarchical layout - if (undefinedLevel === true && definedLevel === true) { - throw new Error('To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.'); - return; - } else { - // setup the system to use hierarchical method. - //this._changeConstants(); + /** + * Returns an object containing an SVG element with the icon of the group (size determined by iconWidth and iconHeight), the label of the group (content) and the yAxisOrientation of the group (left or right). + * @param groupId + * @param width + * @param height + */ + Graph2d.prototype.getLegend = function (groupId, width, height) { + if (width === undefined) { + width = 15; + } + if (height === undefined) { + height = 15; + } + if (this.linegraph.groups[groupId] !== undefined) { + return this.linegraph.groups[groupId].getLegend(width, height); + } else { + return 'cannot find group:' + groupId; + } + }; - // define levels if undefined by the users. Based on hubsize - if (undefinedLevel === true) { - if (this.options.hierarchical.sortMethod === 'hubsize') { - this._determineLevelsByHubsize(); - } else if (this.options.hierarchical.sortMethod === 'directed' || 'direction') { - this._determineLevelsDirected(); - } - } + /** + * This checks if the visible option of the supplied group (by ID) is true or false. + * @param groupId + * @returns {*} + */ + Graph2d.prototype.isGroupVisible = function (groupId) { + if (this.linegraph.groups[groupId] !== undefined) { + return this.linegraph.groups[groupId].visible && (this.linegraph.options.groups.visibility[groupId] === undefined || this.linegraph.options.groups.visibility[groupId] == true); + } else { + return false; + } + }; - // check the distribution of the nodes per level. - var distribution = this._getDistribution(); + /** + * Get the data range of the item set. + * @returns {{min: Date, max: Date}} range A range with a start and end Date. + * When no minimum is found, min==null + * When no maximum is found, max==null + */ + Graph2d.prototype.getItemRange = function () { + var min = null; + var max = null; - // place the nodes on the canvas. - this._placeNodesByHierarchy(distribution); + // calculate min from start filed + for (var groupId in this.linegraph.groups) { + if (this.linegraph.groups.hasOwnProperty(groupId)) { + if (this.linegraph.groups[groupId].visible == true) { + for (var i = 0; i < this.linegraph.groups[groupId].itemsData.length; i++) { + var item = this.linegraph.groups[groupId].itemsData[i]; + var value = util.convert(item.x, 'Date').valueOf(); + min = min == null ? value : min > value ? value : min; + max = max == null ? value : max < value ? value : max; } } } - }, { - key: '_placeNodesByHierarchy', - - /** - * This function places the nodes on the canvas based on the hierarchial distribution. - * - * @param {Object} distribution | obtained by the function this._getDistribution() - * @private - */ - value: function _placeNodesByHierarchy(distribution) { - var nodeId = undefined, - node = undefined; - this.positionedNodes = {}; - // start placing all the level 0 nodes first. Then recursively position their branches. - for (var level in distribution) { - if (distribution.hasOwnProperty(level)) { - for (nodeId in distribution[level].nodes) { - if (distribution[level].nodes.hasOwnProperty(nodeId)) { + } - node = distribution[level].nodes[nodeId]; + return { + min: min != null ? new Date(min) : null, + max: max != null ? new Date(max) : null + }; + }; - if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') { - if (node.x === undefined) { - node.x = distribution[level].distance; - } - distribution[level].distance = node.x + this.nodeSpacing; - } else { - if (node.y === undefined) { - node.y = distribution[level].distance; - } - distribution[level].distance = node.y + this.nodeSpacing; - } + /** + * Generate Timeline related information from an event + * @param {Event} event + * @return {Object} An object with related information, like on which area + * The event happened, whether clicked on an item, etc. + */ + Graph2d.prototype.getEventProperties = function (event) { + var clientX = event.center ? event.center.x : event.clientX; + var clientY = event.center ? event.center.y : event.clientY; + var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer); + var y = clientY - util.getAbsoluteTop(this.dom.centerContainer); + var time = this._toTime(x); - this.positionedNodes[nodeId] = true; - this._placeBranchNodes(node.edges, node.id, distribution, level); - } - } - } - } - } - }, { - key: '_getDistribution', + var customTime = CustomTime.customTimeFromTarget(event); - /** - * This function get the distribution of levels based on hubsize - * - * @returns {Object} - * @private - */ - value: function _getDistribution() { - var distribution = {}; - var nodeId = undefined, - node = undefined; + var element = util.getTarget(event); + var what = null; + if (util.hasParent(element, this.timeAxis.dom.foreground)) { + what = 'axis'; + } else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) { + what = 'axis'; + } else if (util.hasParent(element, this.linegraph.yAxisLeft.dom.frame)) { + what = 'data-axis'; + } else if (util.hasParent(element, this.linegraph.yAxisRight.dom.frame)) { + what = 'data-axis'; + } else if (util.hasParent(element, this.linegraph.legendLeft.dom.frame)) { + what = 'legend'; + } else if (util.hasParent(element, this.linegraph.legendRight.dom.frame)) { + what = 'legend'; + } else if (customTime != null) { + what = 'custom-time'; + } else if (util.hasParent(element, this.currentTime.bar)) { + what = 'current-time'; + } else if (util.hasParent(element, this.dom.center)) { + what = 'background'; + } - // we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time. - // the fix of X is removed after the x value has been set. - for (nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - node = this.body.nodes[nodeId]; - var level = this.hierarchicalLevels[nodeId] === undefined ? 0 : this.hierarchicalLevels[nodeId]; - if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') { - node.y = this.options.hierarchical.levelSeparation * level; - node.options.fixed.y = true; - } else { - node.x = this.options.hierarchical.levelSeparation * level; - node.options.fixed.x = true; - } - if (distribution[level] === undefined) { - distribution[level] = { amount: 0, nodes: {}, distance: 0 }; - } - distribution[level].amount += 1; - distribution[level].nodes[nodeId] = node; - } - } - return distribution; - } - }, { - key: '_getHubSize', + var value = []; + var yAxisLeft = this.linegraph.yAxisLeft; + var yAxisRight = this.linegraph.yAxisRight; + if (!yAxisLeft.hidden) { + value.push(yAxisLeft.screenToValue(y)); + } + if (!yAxisRight.hidden) { + value.push(yAxisRight.screenToValue(y)); + } - /** - * Get the hubsize from all remaining unlevelled nodes. - * - * @returns {number} - * @private - */ - value: function _getHubSize() { - var hubSize = 0; - for (var nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - var node = this.body.nodes[nodeId]; - if (this.hierarchicalLevels[nodeId] === undefined) { - hubSize = node.edges.length < hubSize ? hubSize : node.edges.length; - } - } - } - return hubSize; - } - }, { - key: '_determineLevelsByHubsize', + return { + event: event, + what: what, + pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX, + pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY, + x: x, + y: y, + time: time, + value: value + }; + }; - /** - * this function allocates nodes in levels based on the recursive branching from the largest hubs. - * - * @param hubsize - * @private - */ - value: function _determineLevelsByHubsize() { - var nodeId = undefined, - node = undefined; - var hubSize = 1; + module.exports = Graph2d; - while (hubSize > 0) { - // determine hubs - hubSize = this._getHubSize(); - if (hubSize === 0) break; +/***/ }, +/* 50 */ +/***/ function(module, exports, __webpack_require__) { - for (nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - node = this.body.nodes[nodeId]; - if (node.edges.length === hubSize) { - this._setLevelByHubsize(0, node); - } - } - } - } - } - }, { - key: '_setLevelByHubsize', + 'use strict'; - /** - * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level. - * - * @param level - * @param edges - * @param parentId - * @private - */ - value: function _setLevelByHubsize(level, node) { - if (this.hierarchicalLevels[node.id] !== undefined) return; + var util = __webpack_require__(7); + var DOMutil = __webpack_require__(13); + var DataSet = __webpack_require__(14); + var DataView = __webpack_require__(16); + var Component = __webpack_require__(27); + var DataAxis = __webpack_require__(51); + var GraphGroup = __webpack_require__(53); + var Legend = __webpack_require__(57); + var BarFunctions = __webpack_require__(56); + var LineFunctions = __webpack_require__(54); - var childNode = undefined; - this.hierarchicalLevels[node.id] = level; - for (var i = 0; i < node.edges.length; i++) { - if (node.edges[i].toId === node.id) { - childNode = node.edges[i].from; - } else { - childNode = node.edges[i].to; - } - this._setLevelByHubsize(level + 1, childNode); - } - } - }, { - key: '_determineLevelsDirected', + var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items - /** - * this function allocates nodes in levels based on the direction of the edges - * - * @param hubsize - * @private - */ - value: function _determineLevelsDirected() { - var nodeId = undefined, - node = undefined; - var minLevel = 10000; + /** + * This is the constructor of the LineGraph. It requires a Timeline body and options. + * + * @param body + * @param options + * @constructor + */ + function LineGraph(body, options) { + this.id = util.randomUUID(); + this.body = body; - // set first node to source - for (nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - node = this.body.nodes[nodeId]; - this._setLevelDirected(minLevel, node); - } - } - - // get the minimum level - for (nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - minLevel = this.hierarchicalLevels[nodeId] < minLevel ? this.hierarchicalLevels[nodeId] : minLevel; - } + this.defaultOptions = { + yAxisOrientation: 'left', + defaultGroup: 'default', + sort: true, + sampling: true, + stack: false, + graphHeight: '400px', + shaded: { + enabled: false, + orientation: 'bottom' // top, bottom + }, + style: 'line', // line, bar + barChart: { + width: 50, + sideBySide: false, + align: 'center' // left, center, right + }, + interpolation: { + enabled: true, + parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) + alpha: 0.5 + }, + drawPoints: { + enabled: true, + size: 6, + style: 'square' // square, circle + }, + dataAxis: { + showMinorLabels: true, + showMajorLabels: true, + icons: false, + width: '40px', + visible: true, + alignZeros: true, + left: { + range: { min: undefined, max: undefined }, + format: function format(value) { + return value; + }, + title: { text: undefined, style: undefined } + }, + right: { + range: { min: undefined, max: undefined }, + format: function format(value) { + return value; + }, + title: { text: undefined, style: undefined } } - - // subtract the minimum from the set so we have a range starting from 0 - for (nodeId in this.body.nodes) { - if (this.body.nodes.hasOwnProperty(nodeId)) { - this.hierarchicalLevels[nodeId] -= minLevel; - } + }, + legend: { + enabled: false, + icons: true, + left: { + visible: true, + position: 'top-left' // top/bottom - left,right + }, + right: { + visible: true, + position: 'top-right' // top/bottom - left,right } + }, + groups: { + visibility: {} } - }, { - key: '_setLevelDirected', + }; - /** - * this function is called recursively to enumerate the branched of the first node and give each node a level based on edge direction - * - * @param level - * @param edges - * @param parentId - * @private - */ - value: function _setLevelDirected(level, node) { - if (this.hierarchicalLevels[node.id] !== undefined) return; + // options is shared by this ItemSet and all its items + this.options = util.extend({}, this.defaultOptions); + this.dom = {}; + this.props = {}; + this.hammer = null; + this.groups = {}; + this.abortedGraphUpdate = false; + this.updateSVGheight = false; + this.updateSVGheightOnResize = false; - var childNode = undefined; - this.hierarchicalLevels[node.id] = level; + var me = this; + this.itemsData = null; // DataSet + this.groupsData = null; // DataSet - for (var i = 0; i < node.edges.length; i++) { - if (node.edges[i].toId === node.id) { - childNode = node.edges[i].from; - this._setLevelDirected(level - 1, childNode); - } else { - childNode = node.edges[i].to; - this._setLevelDirected(level + 1, childNode); - } - } + // listeners for the DataSet of the items + this.itemListeners = { + 'add': function add(event, params, senderId) { + me._onAdd(params.items); + }, + 'update': function update(event, params, senderId) { + me._onUpdate(params.items); + }, + 'remove': function remove(event, params, senderId) { + me._onRemove(params.items); } - }, { - key: '_placeBranchNodes', - - /** - * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes - * on a X position that ensures there will be no overlap. - * - * @param edges - * @param parentId - * @param distribution - * @param parentLevel - * @private - */ - value: function _placeBranchNodes(edges, parentId, distribution, parentLevel) { - for (var i = 0; i < edges.length; i++) { - var childNode = undefined; - var parentNode = undefined; - if (edges[i].toId === parentId) { - childNode = edges[i].from; - parentNode = edges[i].to; - } else { - childNode = edges[i].to; - parentNode = edges[i].from; - } - var childNodeLevel = this.hierarchicalLevels[childNode.id]; - - if (this.positionedNodes[childNode.id] === undefined) { - // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here. - if (childNodeLevel > parentLevel) { - if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') { - if (childNode.x === undefined) { - childNode.x = Math.max(distribution[childNodeLevel].distance, parentNode.x); - } - distribution[childNodeLevel].distance = childNode.x + this.nodeSpacing; - this.positionedNodes[childNode.id] = true; - } else { - if (childNode.y === undefined) { - childNode.y = Math.max(distribution[childNodeLevel].distance, parentNode.y); - } - distribution[childNodeLevel].distance = childNode.y + this.nodeSpacing; - } - this.positionedNodes[childNode.id] = true; + }; - if (childNode.edges.length > 1) { - this._placeBranchNodes(childNode.edges, childNode.id, distribution, childNodeLevel); - } - } - } - } + // listeners for the DataSet of the groups + this.groupListeners = { + 'add': function add(event, params, senderId) { + me._onAddGroups(params.items); + }, + 'update': function update(event, params, senderId) { + me._onUpdateGroups(params.items); + }, + 'remove': function remove(event, params, senderId) { + me._onRemoveGroups(params.items); } - }]); - - return LayoutEngine; - })(); - - exports['default'] = LayoutEngine; - module.exports = exports['default']; - -/***/ }, -/* 65 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; + }; - Object.defineProperty(exports, '__esModule', { - value: true - }); + this.items = {}; // object with an Item for every data item + this.selection = []; // list with the ids of all selected nodes + this.lastStart = this.body.range.start; + this.touchParams = {}; // stores properties while dragging - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + this.svgElements = {}; + this.setOptions(options); + this.groupsUsingDefaultStyles = [0]; + this.COUNTER = 0; + this.body.emitter.on('rangechanged', function () { + me.lastStart = me.body.range.start; + me.svg.style.left = util.option.asSize(-me.props.width); + me.redraw.call(me, true); + }); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + // create the HTML DOM + this._create(); + this.framework = { svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups }; + this.body.emitter.emit('change'); + } - var util = __webpack_require__(2); - var Hammer = __webpack_require__(41); - var hammerUtil = __webpack_require__(49); + LineGraph.prototype = new Component(); /** - * clears the toolbar div element of children - * - * @private + * Create the HTML DOM for the ItemSet */ + LineGraph.prototype._create = function () { + var frame = document.createElement('div'); + frame.className = 'vis-line-graph'; + this.dom.frame = frame; - var ManipulationSystem = (function () { - function ManipulationSystem(body, canvas, selectionHandler) { - var _this = this; - - _classCallCheck(this, ManipulationSystem); - - this.body = body; - this.canvas = canvas; - this.selectionHandler = selectionHandler; - - this.editMode = false; - this.manipulationDiv = undefined; - this.editModeDiv = undefined; - this.closeDiv = undefined; - - this.manipulationHammers = []; - this.temporaryUIFunctions = {}; - this.temporaryEventFunctions = []; + // create svg element for graph drawing. + this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + this.svg.style.position = 'relative'; + this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px'; + this.svg.style.display = 'block'; + frame.appendChild(this.svg); - this.touchTime = 0; - this.temporaryIds = { nodes: [], edges: [] }; - this.guiEnabled = false; - this.inMode = false; - this.selectedControlNode = undefined; + // data axis + this.options.dataAxis.orientation = 'left'; + this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups); - this.options = {}; - this.defaultOptions = { - enabled: false, - initiallyActive: false, - addNode: true, - addEdge: true, - editNode: undefined, - editEdge: true, - deleteNode: true, - deleteEdge: true, - controlNodeStyle: { - shape: 'dot', - size: 6, - color: { background: '#ff0000', border: '#3c3c3c', highlight: { background: '#07f968', border: '#3c3c3c' } }, - borderWidth: 2, - borderWidthSelected: 2 - } - }; - util.extend(this.options, this.defaultOptions); + this.options.dataAxis.orientation = 'right'; + this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups); + delete this.options.dataAxis.orientation; - this.body.emitter.on('destroy', function () { - _this._clean(); - }); - this.body.emitter.on('_dataChanged', this._restore.bind(this)); - this.body.emitter.on('_resetData', this._restore.bind(this)); - } + // legends + this.legendLeft = new Legend(this.body, this.options.legend, 'left', this.options.groups); + this.legendRight = new Legend(this.body, this.options.legend, 'right', this.options.groups); - _createClass(ManipulationSystem, [{ - key: '_restore', + this.show(); + }; - /** - * If something changes in the data during editing, switch back to the initial datamanipulation state and close all edit modes. - * @private - */ - value: function _restore() { - if (this.inMode !== false) { - if (this.options.initiallyActive === true) { - this.enableEditMode(); - } else { - this.disableEditMode(); - } + /** + * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element. + * @param {object} options + */ + LineGraph.prototype.setOptions = function (options) { + if (options) { + var fields = ['sampling', 'defaultGroup', 'stack', 'height', 'graphHeight', 'yAxisOrientation', 'style', 'barChart', 'dataAxis', 'sort', 'groups']; + if (options.graphHeight === undefined && options.height !== undefined && this.body.domProps.centerContainer.height !== undefined) { + this.updateSVGheight = true; + this.updateSVGheightOnResize = true; + } else if (this.body.domProps.centerContainer.height !== undefined && options.graphHeight !== undefined) { + if (parseInt((options.graphHeight + '').replace('px', '')) < this.body.domProps.centerContainer.height) { + this.updateSVGheight = true; } } - }, { - key: 'setOptions', - - /** - * Set the Options - * @param options - */ - value: function setOptions(options, allOptions, globalOptions) { - if (allOptions !== undefined) { - if (allOptions.locale !== undefined) { - this.options.locale = allOptions.locale; - } else { - this.options.locale = globalOptions.locale; - } - if (allOptions.locales !== undefined) { - this.options.locales = allOptions.locales; - } else { - this.options.locales = globalOptions.locales; - } - } + util.selectiveDeepExtend(fields, this.options, options); + util.mergeOptions(this.options, options, 'interpolation'); + util.mergeOptions(this.options, options, 'drawPoints'); + util.mergeOptions(this.options, options, 'shaded'); + util.mergeOptions(this.options, options, 'legend'); - if (options !== undefined) { - if (typeof options === 'boolean') { - this.options.enabled = options; - } else { - this.options.enabled = true; - util.deepExtend(this.options, options); - } - if (this.options.initiallyActive === true) { - this.editMode = true; + if (options.interpolation) { + if (typeof options.interpolation == 'object') { + if (options.interpolation.parametrization) { + if (options.interpolation.parametrization == 'uniform') { + this.options.interpolation.alpha = 0; + } else if (options.interpolation.parametrization == 'chordal') { + this.options.interpolation.alpha = 1; + } else { + this.options.interpolation.parametrization = 'centripetal'; + this.options.interpolation.alpha = 0.5; + } } - this._setup(); } } - }, { - key: 'toggleEditMode', - /** - * Enable or disable edit-mode. Draws the DOM required and cleans up after itself. - * - * @private - */ - value: function toggleEditMode() { - if (this.editMode === true) { - this.disableEditMode(); - } else { - this.enableEditMode(); + if (this.yAxisLeft) { + if (options.dataAxis !== undefined) { + this.yAxisLeft.setOptions(this.options.dataAxis); + this.yAxisRight.setOptions(this.options.dataAxis); } } - }, { - key: 'enableEditMode', - value: function enableEditMode() { - this.editMode = true; - this._clean(); - if (this.guiEnabled === true) { - this.manipulationDiv.style.display = 'block'; - this.closeDiv.style.display = 'block'; - this.editModeDiv.style.display = 'none'; - this.showManipulatorToolbar(); + if (this.legendLeft) { + if (options.legend !== undefined) { + this.legendLeft.setOptions(this.options.legend); + this.legendRight.setOptions(this.options.legend); } } - }, { - key: 'disableEditMode', - value: function disableEditMode() { - this.editMode = false; - this._clean(); - if (this.guiEnabled === true) { - this.manipulationDiv.style.display = 'none'; - this.closeDiv.style.display = 'none'; - this.editModeDiv.style.display = 'block'; - this._createEditButton(); - } + if (this.groups.hasOwnProperty(UNGROUPED)) { + this.groups[UNGROUPED].setOptions(options); } - }, { - key: 'showManipulatorToolbar', + } - /** - * Creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar. - * - * @private - */ - value: function showManipulatorToolbar() { - // restore the state of any bound functions or events, remove control nodes, restore physics - this._clean(); + // this is used to redraw the graph if the visibility of the groups is changed. + if (this.dom.frame) { + this.redraw(true); + } + }; - // reset global letiables - this.manipulationDOM = {}; + /** + * Hide the component from the DOM + */ + LineGraph.prototype.hide = function () { + // remove the frame containing the items + if (this.dom.frame.parentNode) { + this.dom.frame.parentNode.removeChild(this.dom.frame); + } + }; - // if the gui is enabled, draw all elements. - if (this.guiEnabled === true) { - // a _restore will hide these menus - this.editMode = true; - this.manipulationDiv.style.display = 'block'; - this.closeDiv.style.display = 'block'; + /** + * Show the component in the DOM (when not already visible). + * @return {Boolean} changed + */ + LineGraph.prototype.show = function () { + // show frame containing the items + if (!this.dom.frame.parentNode) { + this.body.dom.center.appendChild(this.dom.frame); + } + }; - var selectedNodeCount = this.selectionHandler._getSelectedNodeCount(); - var selectedEdgeCount = this.selectionHandler._getSelectedEdgeCount(); - var selectedTotalCount = selectedNodeCount + selectedEdgeCount; - var locale = this.options.locales[this.options.locale]; - var needSeperator = false; + /** + * Set items + * @param {vis.DataSet | null} items + */ + LineGraph.prototype.setItems = function (items) { + var me = this, + ids, + oldItemsData = this.itemsData; - if (this.options.addNode !== false) { - this._createAddNodeButton(locale); - needSeperator = true; - } - if (this.options.addEdge !== false) { - if (needSeperator === true) { - this._createSeperator(1); - } else { - needSeperator = true; - } - this._createAddEdgeButton(locale); - } + // 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 (selectedNodeCount === 1 && typeof this.options.editNode === 'function') { - if (needSeperator === true) { - this._createSeperator(2); - } else { - needSeperator = true; - } - this._createEditNodeButton(locale); - } else if (selectedEdgeCount === 1 && selectedNodeCount === 0 && this.options.editEdge !== false) { - if (needSeperator === true) { - this._createSeperator(3); - } else { - needSeperator = true; - } - this._createEditEdgeButton(locale); - } + if (oldItemsData) { + // unsubscribe from old dataset + util.forEach(this.itemListeners, function (callback, event) { + oldItemsData.off(event, callback); + }); - // remove buttons - if (selectedTotalCount !== 0) { - if (selectedNodeCount === 1 && this.options.deleteNode !== false) { - if (needSeperator === true) { - this._createSeperator(4); - } - this._createDeleteButton(locale); - } else if (selectedNodeCount === 0 && this.options.deleteEdge !== false) { - if (needSeperator === true) { - this._createSeperator(4); - } - this._createDeleteButton(locale); - } - } + // remove all drawn items + ids = oldItemsData.getIds(); + this._onRemove(ids); + } - // bind the close button - this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); + if (this.itemsData) { + // subscribe to new dataset + var id = this.id; + util.forEach(this.itemListeners, function (callback, event) { + me.itemsData.on(event, callback, id); + }); - // refresh this bar based on what has been selected - this._temporaryBindEvent('select', this.showManipulatorToolbar.bind(this)); - } + // add all new items + ids = this.itemsData.getIds(); + this._onAdd(ids); + } + this._updateUngrouped(); + //this._updateGraph(); + this.redraw(true); + }; - // redraw to show any possible changes - this.body.emitter.emit('_redraw'); - } - }, { - key: 'addNodeMode', + /** + * Set groups + * @param {vis.DataSet} groups + */ + LineGraph.prototype.setGroups = function (groups) { + var me = this; + var ids; - /** - * Create the toolbar for adding Nodes - * - * @private - */ - value: function addNodeMode() { - // when using the gui, enable edit mode if it wasnt already. - if (this.editMode !== true) { - this.enableEditMode(); - } + // unsubscribe from current dataset + if (this.groupsData) { + util.forEach(this.groupListeners, function (callback, event) { + me.groupsData.off(event, callback); + }); - // restore the state of any bound functions or events, remove control nodes, restore physics - this._clean(); + // remove all drawn groups + ids = this.groupsData.getIds(); + this.groupsData = null; + this._onRemoveGroups(ids); // note: this will cause a redraw + } - this.inMode = 'addNode'; - if (this.guiEnabled === true) { - var locale = this.options.locales[this.options.locale]; - this.manipulationDOM = {}; - this._createBackButton(locale); - this._createSeperator(); - this._createDescription(locale['addDescription'] || this.options.locales['en']['addDescription']); + // 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'); + } - // bind the close button - this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); - } + if (this.groupsData) { + // subscribe to new dataset + var id = this.id; + util.forEach(this.groupListeners, function (callback, event) { + me.groupsData.on(event, callback, id); + }); - this._temporaryBindEvent('click', this._performAddNode.bind(this)); - } - }, { - key: 'editNode', + // draw all ms + ids = this.groupsData.getIds(); + this._onAddGroups(ids); + } + this._onUpdate(); + }; - /** - * call the bound function to handle the editing of the node. The node has to be selected. - * - * @private - */ - value: function editNode() { - var _this2 = this; + /** + * Update the data + * @param [ids] + * @private + */ + LineGraph.prototype._onUpdate = function (ids) { + this._updateUngrouped(); + this._updateAllGroupData(); + //this._updateGraph(); + this.redraw(true); + }; + LineGraph.prototype._onAdd = function (ids) { + this._onUpdate(ids); + }; + LineGraph.prototype._onRemove = function (ids) { + this._onUpdate(ids); + }; + LineGraph.prototype._onUpdateGroups = function (groupIds) { + for (var i = 0; i < groupIds.length; i++) { + var group = this.groupsData.get(groupIds[i]); + this._updateGroup(group, groupIds[i]); + } - // when using the gui, enable edit mode if it wasnt already. - if (this.editMode !== true) { - this.enableEditMode(); + //this._updateGraph(); + this.redraw(true); + }; + LineGraph.prototype._onAddGroups = function (groupIds) { + this._onUpdateGroups(groupIds); + }; + + /** + * this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph + * @param {Array} groupIds + * @private + */ + LineGraph.prototype._onRemoveGroups = function (groupIds) { + for (var i = 0; i < groupIds.length; i++) { + if (this.groups.hasOwnProperty(groupIds[i])) { + if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') { + this.yAxisRight.removeGroup(groupIds[i]); + this.legendRight.removeGroup(groupIds[i]); + this.legendRight.redraw(); + } else { + this.yAxisLeft.removeGroup(groupIds[i]); + this.legendLeft.removeGroup(groupIds[i]); + this.legendLeft.redraw(); } + delete this.groups[groupIds[i]]; + } + } + this._updateUngrouped(); + //this._updateGraph(); + this.redraw(true); + }; - // restore the state of any bound functions or events, remove control nodes, restore physics - this._clean(); + /** + * update a group object with the group dataset entree + * + * @param group + * @param groupId + * @private + */ + LineGraph.prototype._updateGroup = function (group, groupId) { + if (!this.groups.hasOwnProperty(groupId)) { + this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles); + if (this.groups[groupId].options.yAxisOrientation == 'right') { + this.yAxisRight.addGroup(groupId, this.groups[groupId]); + this.legendRight.addGroup(groupId, this.groups[groupId]); + } else { + this.yAxisLeft.addGroup(groupId, this.groups[groupId]); + this.legendLeft.addGroup(groupId, this.groups[groupId]); + } + } else { + this.groups[groupId].update(group); + if (this.groups[groupId].options.yAxisOrientation == 'right') { + this.yAxisRight.updateGroup(groupId, this.groups[groupId]); + this.legendRight.updateGroup(groupId, this.groups[groupId]); + } else { + this.yAxisLeft.updateGroup(groupId, this.groups[groupId]); + this.legendLeft.updateGroup(groupId, this.groups[groupId]); + } + } + this.legendLeft.redraw(); + this.legendRight.redraw(); + }; - this.inMode = 'editNode'; - if (typeof this.options.editNode === 'function') { - var node = this.selectionHandler._getSelectedNode(); - if (node.isCluster !== true) { - var data = util.deepExtend({}, node.options, true); - data.x = node.x; - data.y = node.y; + /** + * this updates all groups, it is used when there is an update the the itemset. + * + * @private + */ + LineGraph.prototype._updateAllGroupData = function () { + if (this.itemsData != null) { + var groupsContent = {}; + var groupId; + for (groupId in this.groups) { + if (this.groups.hasOwnProperty(groupId)) { + groupsContent[groupId] = []; + } + } + for (var itemId in this.itemsData._data) { + if (this.itemsData._data.hasOwnProperty(itemId)) { + var item = this.itemsData._data[itemId]; + if (groupsContent[item.group] === undefined) { + throw new Error('Cannot find referenced group. Possible reason: items added before groups? Groups need to be added before items, as items refer to groups.'); + } + item.x = util.convert(item.x, 'Date'); + groupsContent[item.group].push(item); + } + } + for (groupId in this.groups) { + if (this.groups.hasOwnProperty(groupId)) { + this.groups[groupId].setItems(groupsContent[groupId]); + } + } + } + }; - if (this.options.editNode.length === 2) { - this.options.editNode(data, function (finalizedData) { - if (finalizedData !== null && finalizedData !== undefined && _this2.inMode === 'editNode') { - // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { - _this2.body.data.nodes.update(finalizedData); - } - _this2.showManipulatorToolbar(); - }); + /** + * Create or delete the group holding all ungrouped items. This group is used when + * there are no groups specified. This anonymous group is called 'graph'. + * @protected + */ + LineGraph.prototype._updateUngrouped = function () { + if (this.itemsData && this.itemsData != null) { + var ungroupedCounter = 0; + for (var itemId in this.itemsData._data) { + if (this.itemsData._data.hasOwnProperty(itemId)) { + var item = this.itemsData._data[itemId]; + if (item != undefined) { + if (item.hasOwnProperty('group')) { + if (item.group === undefined) { + item.group = UNGROUPED; + } } else { - throw new Error('The function for edit does not support two arguments (data, callback)'); + item.group = UNGROUPED; } - } else { - alert(this.options.locales[this.options.locale]['editClusterError'] || this.options.locales['en']['editClusterError']); + ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter; } - } else { - throw new Error('No function has been configured to handle the editing of nodes.'); } } - }, { - key: 'addEdgeMode', - - /** - * create the toolbar to connect nodes - * - * @private - */ - value: function addEdgeMode() { - // when using the gui, enable edit mode if it wasnt already. - if (this.editMode !== true) { - this.enableEditMode(); - } - - // restore the state of any bound functions or events, remove control nodes, restore physics - this._clean(); - this.inMode = 'addEdge'; - if (this.guiEnabled === true) { - var locale = this.options.locales[this.options.locale]; - this.manipulationDOM = {}; - this._createBackButton(locale); - this._createSeperator(); - this._createDescription(locale['edgeDescription'] || this.options.locales['en']['edgeDescription']); + if (ungroupedCounter == 0) { + delete this.groups[UNGROUPED]; + this.legendLeft.removeGroup(UNGROUPED); + this.legendRight.removeGroup(UNGROUPED); + this.yAxisLeft.removeGroup(UNGROUPED); + this.yAxisRight.removeGroup(UNGROUPED); + } else { + var group = { id: UNGROUPED, content: this.options.defaultGroup }; + this._updateGroup(group, UNGROUPED); + } + } else { + delete this.groups[UNGROUPED]; + this.legendLeft.removeGroup(UNGROUPED); + this.legendRight.removeGroup(UNGROUPED); + this.yAxisLeft.removeGroup(UNGROUPED); + this.yAxisRight.removeGroup(UNGROUPED); + } - // bind the close button - this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); - } + this.legendLeft.redraw(); + this.legendRight.redraw(); + }; - // temporarily overload functions - this._temporaryBindUI('onTouch', this._handleConnect.bind(this)); - this._temporaryBindUI('onDragEnd', this._finishConnect.bind(this)); - this._temporaryBindUI('onDrag', this._dragControlNode.bind(this)); - this._temporaryBindUI('onRelease', this._finishConnect.bind(this)); + /** + * Redraw the component, mandatory function + * @return {boolean} Returns true if the component is resized + */ + LineGraph.prototype.redraw = function (forceGraphUpdate) { + var resized = false; - this._temporaryBindUI('onDragStart', function () {}); - this._temporaryBindUI('onHold', function () {}); - } - }, { - key: 'editEdgeMode', + // calculate actual size and position + this.props.width = this.dom.frame.offsetWidth; + this.props.height = this.body.domProps.centerContainer.height - this.body.domProps.border.top - this.body.domProps.border.bottom; - /** - * create the toolbar to edit edges - * - * @private - */ - value: function editEdgeMode() { - // when using the gui, enable edit mode if it wasnt already. - if (this.editMode !== true) { - this.enableEditMode(); - } + // update the graph if there is no lastWidth or with, used for the initial draw + if (this.lastWidth === undefined && this.props.width) { + forceGraphUpdate = true; + } - // restore the state of any bound functions or events, remove control nodes, restore physics - this._clean(); + // check if this component is resized + resized = this._isResized() || resized; - this.inMode = 'editEdge'; - if (this.guiEnabled === true) { - var locale = this.options.locales[this.options.locale]; - this.manipulationDOM = {}; - this._createBackButton(locale); - this._createSeperator(); - this._createDescription(locale['editEdgeDescription'] || this.options.locales['en']['editEdgeDescription']); + // check whether zoomed (in that case we need to re-stack everything) + var visibleInterval = this.body.range.end - this.body.range.start; + var zoomed = visibleInterval != this.lastVisibleInterval; + this.lastVisibleInterval = visibleInterval; - // bind the close button - this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); - } + // the svg element is three times as big as the width, this allows for fully dragging left and right + // without reloading the graph. the controls for this are bound to events in the constructor + if (resized == true) { + this.svg.style.width = util.option.asSize(3 * this.props.width); + this.svg.style.left = util.option.asSize(-this.props.width); - this.edgeBeingEditedId = this.selectionHandler.getSelectedEdges()[0]; - var edge = this.body.edges[this.edgeBeingEditedId]; + // if the height of the graph is set as proportional, change the height of the svg + if ((this.options.height + '').indexOf('%') != -1 || this.updateSVGheightOnResize == true) { + this.updateSVGheight = true; + } + } - // create control nodes - var controlNodeFrom = this._getNewTargetNode(edge.from.x, edge.from.y); - var controlNodeTo = this._getNewTargetNode(edge.to.x, edge.to.y); + // update the height of the graph on each redraw of the graph. + if (this.updateSVGheight == true) { + if (this.options.graphHeight != this.props.height + 'px') { + this.options.graphHeight = this.props.height + 'px'; + this.svg.style.height = this.props.height + 'px'; + } + this.updateSVGheight = false; + } else { + this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px'; + } - this.temporaryIds.nodes.push(controlNodeFrom.id); - this.temporaryIds.nodes.push(controlNodeTo.id); + // zoomed is here to ensure that animations are shown correctly. + if (resized == true || zoomed == true || this.abortedGraphUpdate == true || forceGraphUpdate == true) { + resized = this._updateGraph() || resized; + } else { + // move the whole svg while dragging + if (this.lastStart != 0) { + var offset = this.body.range.start - this.lastStart; + var range = this.body.range.end - this.body.range.start; + if (this.props.width != 0) { + var rangePerPixelInv = this.props.width / range; + var xOffset = offset * rangePerPixelInv; + this.svg.style.left = -this.props.width - xOffset + 'px'; + } + } + } - this.body.nodes[controlNodeFrom.id] = controlNodeFrom; - this.body.nodeIndices.push(controlNodeFrom.id); - this.body.nodes[controlNodeTo.id] = controlNodeTo; - this.body.nodeIndices.push(controlNodeTo.id); + this.legendLeft.redraw(); + this.legendRight.redraw(); + return resized; + }; - // temporarily overload UI functions, cleaned up automatically because of _temporaryBindUI - this._temporaryBindUI('onTouch', this._controlNodeTouch.bind(this)); // used to get the position - this._temporaryBindUI('onTap', function () {}); // disabled - this._temporaryBindUI('onHold', function () {}); // disabled - this._temporaryBindUI('onDragStart', this._controlNodeDragStart.bind(this)); // used to select control node - this._temporaryBindUI('onDrag', this._controlNodeDrag.bind(this)); // used to drag control node - this._temporaryBindUI('onDragEnd', this._controlNodeDragEnd.bind(this)); // used to connect or revert control nodes - this._temporaryBindUI('onMouseMove', function () {}); // disabled + /** + * Update and redraw the graph. + * + */ + LineGraph.prototype._updateGraph = function () { + // reset the svg elements + DOMutil.prepareElements(this.svgElements); + if (this.props.width != 0 && this.itemsData != null) { + var group, i; + var preprocessedGroupData = {}; + var processedGroupData = {}; + var groupRanges = {}; + var changeCalled = false; - // create function to position control nodes correctly on movement - // automatically cleaned up because we use the temporary bind - this._temporaryBindEvent('beforeDrawing', function (ctx) { - var positions = edge.edgeType.findBorderPositions(ctx); - if (controlNodeFrom.selected === false) { - controlNodeFrom.x = positions.from.x; - controlNodeFrom.y = positions.from.y; - } - if (controlNodeTo.selected === false) { - controlNodeTo.x = positions.to.x; - controlNodeTo.y = positions.to.y; + // getting group Ids + var groupIds = []; + for (var groupId in this.groups) { + if (this.groups.hasOwnProperty(groupId)) { + group = this.groups[groupId]; + if (group.visible == true && (this.options.groups.visibility[groupId] === undefined || this.options.groups.visibility[groupId] == true)) { + groupIds.push(groupId); } - }); - - this.body.emitter.emit('_redraw'); + } } - }, { - key: 'deleteSelected', + if (groupIds.length > 0) { + // this is the range of the SVG canvas + var minDate = this.body.util.toGlobalTime(-this.body.domProps.root.width); + var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width); + var groupsData = {}; + // fill groups data, this only loads the data we require based on the timewindow + this._getRelevantData(groupIds, groupsData, minDate, maxDate); - /** - * delete everything in the selection - * - * @private - */ - value: function deleteSelected() { - var _this3 = this; + // apply sampling, if disabled, it will pass through this function. + this._applySampling(groupIds, groupsData); - // when using the gui, enable edit mode if it wasnt already. - if (this.editMode !== true) { - this.enableEditMode(); + // we transform the X coordinates to detect collisions + for (i = 0; i < groupIds.length; i++) { + preprocessedGroupData[groupIds[i]] = this._convertXcoordinates(groupsData[groupIds[i]]); } - // restore the state of any bound functions or events, remove control nodes, restore physics - this._clean(); + // now all needed data has been collected we start the processing. + this._getYRanges(groupIds, preprocessedGroupData, groupRanges); - this.inMode = 'delete'; - var selectedNodes = this.selectionHandler.getSelectedNodes(); - var selectedEdges = this.selectionHandler.getSelectedEdges(); - var deleteFunction = undefined; - if (selectedNodes.length > 0) { - for (var i = 0; i < selectedNodes.length; i++) { - if (this.body.nodes[selectedNodes[i]].isCluster === true) { - alert(this.options.locales[this.options.locale]['deleteClusterError'] || this.options.locales['en']['deleteClusterError']); - return; - } + // update the Y axis first, we use this data to draw at the correct Y points + // changeCalled is required to clean the SVG on a change emit. + changeCalled = this._updateYAxis(groupIds, groupRanges); + var MAX_CYCLES = 5; + if (changeCalled == true && this.COUNTER < MAX_CYCLES) { + DOMutil.cleanupElements(this.svgElements); + this.abortedGraphUpdate = true; + this.COUNTER++; + this.body.emitter.emit('change'); + return true; + } else { + if (this.COUNTER > MAX_CYCLES) { + console.log('WARNING: there may be an infinite loop in the _updateGraph emitter cycle.'); } + this.COUNTER = 0; + this.abortedGraphUpdate = false; - if (typeof this.options.deleteNode === 'function') { - deleteFunction = this.options.deleteNode; - } - } else if (selectedEdges.length > 0) { - if (typeof this.options.deleteEdge === 'function') { - deleteFunction = this.options.deleteEdge; + // With the yAxis scaled correctly, use this to get the Y values of the points. + for (i = 0; i < groupIds.length; i++) { + group = this.groups[groupIds[i]]; + processedGroupData[groupIds[i]] = this._convertYcoordinates(groupsData[groupIds[i]], group); } - } - if (typeof deleteFunction === 'function') { - var data = { nodes: selectedNodes, edges: selectedEdges }; - if (deleteFunction.length === 2) { - deleteFunction(data, function (finalizedData) { - if (finalizedData !== null && finalizedData !== undefined && _this3.inMode === 'delete') { - // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { - _this3.body.data.edges.remove(finalizedData.edges); - _this3.body.data.nodes.remove(finalizedData.nodes); - _this3.body.emitter.emit('startSimulation'); - _this3.showManipulatorToolbar(); - } - }); - } else { - throw new Error('The function for delete does not support two arguments (data, callback)'); + // draw the groups + for (i = 0; i < groupIds.length; i++) { + group = this.groups[groupIds[i]]; + if (group.options.style != 'bar') { + // bar needs to be drawn enmasse + group.draw(processedGroupData[groupIds[i]], group, this.framework); + } } - } else { - this.body.data.edges.remove(selectedEdges); - this.body.data.nodes.remove(selectedNodes); - this.body.emitter.emit('startSimulation'); - this.showManipulatorToolbar(); + BarFunctions.draw(groupIds, processedGroupData, this.framework); } } - }, { - key: '_setup', - - //********************************************** PRIVATE ***************************************// + } - /** - * draw or remove the DOM - * @private - */ - value: function _setup() { - if (this.options.enabled === true) { - // Enable the GUI - this.guiEnabled = true; + // cleanup unused svg elements + DOMutil.cleanupElements(this.svgElements); + return false; + }; - this._createWrappers(); - if (this.editMode === false) { - this._createEditButton(); - } else { - this.showManipulatorToolbar(); + /** + * first select and preprocess the data from the datasets. + * the groups have their preselection of data, we now loop over this data to see + * what data we need to draw. Sorted data is much faster. + * more optimization is possible by doing the sampling before and using the binary search + * to find the end date to determine the increment. + * + * @param {array} groupIds + * @param {object} groupsData + * @param {date} minDate + * @param {date} maxDate + * @private + */ + LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) { + var group, i, j, item; + if (groupIds.length > 0) { + for (i = 0; i < groupIds.length; i++) { + group = this.groups[groupIds[i]]; + groupsData[groupIds[i]] = []; + var dataContainer = groupsData[groupIds[i]]; + // optimization for sorted data + if (group.options.sort == true) { + var guess = Math.max(0, util.binarySearchValue(group.itemsData, minDate, 'x', 'before')); + for (j = guess; j < group.itemsData.length; j++) { + item = group.itemsData[j]; + if (item !== undefined) { + if (item.x > maxDate) { + dataContainer.push(item); + break; + } else { + dataContainer.push(item); + } + } } } else { - this._removeManipulationDOM(); - - // disable the gui - this.guiEnabled = false; + for (j = 0; j < group.itemsData.length; j++) { + item = group.itemsData[j]; + if (item !== undefined) { + if (item.x > minDate && item.x < maxDate) { + dataContainer.push(item); + } + } + } } } - }, { - key: '_createWrappers', + } + }; - /** - * create the div overlays that contain the DOM - * @private - */ - value: function _createWrappers() { - // load the manipulator HTML elements. All styling done in css. - if (this.manipulationDiv === undefined) { - this.manipulationDiv = document.createElement('div'); - this.manipulationDiv.className = 'vis-manipulation'; - if (this.editMode === true) { - this.manipulationDiv.style.display = 'block'; - } else { - this.manipulationDiv.style.display = 'none'; + /** + * + * @param groupIds + * @param groupsData + * @private + */ + LineGraph.prototype._applySampling = function (groupIds, groupsData) { + var group; + if (groupIds.length > 0) { + for (var i = 0; i < groupIds.length; i++) { + group = this.groups[groupIds[i]]; + if (group.options.sampling == true) { + var dataContainer = groupsData[groupIds[i]]; + if (dataContainer.length > 0) { + var increment = 1; + var amountOfPoints = dataContainer.length; + + // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop + // of width changing of the yAxis. + var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x); + var pointsPerPixel = amountOfPoints / xDistance; + increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel))); + + var sampledData = []; + for (var j = 0; j < amountOfPoints; j += increment) { + sampledData.push(dataContainer[j]); + } + groupsData[groupIds[i]] = sampledData; } - this.canvas.frame.appendChild(this.manipulationDiv); } + } + } + }; - // container for the edit button. - if (this.editModeDiv === undefined) { - this.editModeDiv = document.createElement('div'); - this.editModeDiv.className = 'vis-edit-mode'; - if (this.editMode === true) { - this.editModeDiv.style.display = 'none'; + /** + * + * + * @param {array} groupIds + * @param {object} groupsData + * @param {object} groupRanges | this is being filled here + * @private + */ + LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) { + var groupData, group, i; + var combinedDataLeft = []; + var combinedDataRight = []; + var options; + if (groupIds.length > 0) { + for (i = 0; i < groupIds.length; i++) { + groupData = groupsData[groupIds[i]]; + options = this.groups[groupIds[i]].options; + if (groupData.length > 0) { + group = this.groups[groupIds[i]]; + // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups. + if (options.stack === true) { + if (options.yAxisOrientation == 'left') { + combinedDataLeft = combinedDataLeft.concat(group.getData(groupData)); + } else { + combinedDataRight = combinedDataRight.concat(group.getData(groupData)); + } } else { - this.editModeDiv.style.display = 'block'; + groupRanges[groupIds[i]] = group.getYRange(groupData, groupIds[i]); } - this.canvas.frame.appendChild(this.editModeDiv); } + } - // container for the close div button - if (this.closeDiv === undefined) { - this.closeDiv = document.createElement('div'); - this.closeDiv.className = 'vis-close'; - this.closeDiv.style.display = this.manipulationDiv.style.display; - this.canvas.frame.appendChild(this.closeDiv); + // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups. + BarFunctions.getStackedYRange(combinedDataLeft, groupRanges, groupIds, '__barStackLeft', 'left'); + BarFunctions.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__barStackRight', 'right'); + // if line graphs are stacked, their range need to be handled differently and accumulated over all groups. + LineFunctions.getStackedYRange(combinedDataLeft, groupRanges, groupIds, '__lineStackLeft', 'left'); + LineFunctions.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__lineStackRight', 'right'); + } + }; + + /** + * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden. + * @param {Array} groupIds + * @param {Object} groupRanges + * @private + */ + LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) { + var resized = false; + var yAxisLeftUsed = false; + var yAxisRightUsed = false; + var minLeft = 1000000000, + minRight = 1000000000, + maxLeft = -1000000000, + maxRight = -1000000000, + minVal, + maxVal; + // if groups are present + if (groupIds.length > 0) { + // this is here to make sure that if there are no items in the axis but there are groups, that there is no infinite draw/redraw loop. + for (var i = 0; i < groupIds.length; i++) { + var group = this.groups[groupIds[i]]; + if (group && group.options.yAxisOrientation != 'right') { + yAxisLeftUsed = true; + minLeft = 0; + maxLeft = 0; + } else if (group && group.options.yAxisOrientation) { + yAxisRightUsed = true; + minRight = 0; + maxRight = 0; } } - }, { - key: '_getNewTargetNode', - /** - * generate a new target node. Used for creating new edges and editing edges - * @param x - * @param y - * @returns {*} - * @private - */ - value: function _getNewTargetNode(x, y) { - var controlNodeStyle = util.deepExtend({}, this.options.controlNodeStyle); + // if there are items: + for (var i = 0; i < groupIds.length; i++) { + if (groupRanges.hasOwnProperty(groupIds[i])) { + if (groupRanges[groupIds[i]].ignore !== true) { + minVal = groupRanges[groupIds[i]].min; + maxVal = groupRanges[groupIds[i]].max; - controlNodeStyle.id = 'targetNode' + util.randomUUID(); - controlNodeStyle.hidden = false; - controlNodeStyle.physics = false; - controlNodeStyle.x = x; - controlNodeStyle.y = y; + if (groupRanges[groupIds[i]].yAxisOrientation != 'right') { + yAxisLeftUsed = true; + minLeft = minLeft > minVal ? minVal : minLeft; + maxLeft = maxLeft < maxVal ? maxVal : maxLeft; + } else { + yAxisRightUsed = true; + minRight = minRight > minVal ? minVal : minRight; + maxRight = maxRight < maxVal ? maxVal : maxRight; + } + } + } + } - return this.body.functions.createNode(controlNodeStyle); + if (yAxisLeftUsed == true) { + this.yAxisLeft.setRange(minLeft, maxLeft); } - }, { - key: '_createEditButton', + if (yAxisRightUsed == true) { + this.yAxisRight.setRange(minRight, maxRight); + } + } + resized = this._toggleAxisVisiblity(yAxisLeftUsed, this.yAxisLeft) || resized; + resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized; - /** - * Create the edit button - */ - value: function _createEditButton() { - // restore everything to it's original state (if applicable) - this._clean(); + if (yAxisRightUsed == true && yAxisLeftUsed == true) { + this.yAxisLeft.drawIcons = true; + this.yAxisRight.drawIcons = true; + } else { + this.yAxisLeft.drawIcons = false; + this.yAxisRight.drawIcons = false; + } + this.yAxisRight.master = !yAxisLeftUsed; + if (this.yAxisRight.master == false) { + if (yAxisRightUsed == true) { + this.yAxisLeft.lineOffset = this.yAxisRight.width; + } else { + this.yAxisLeft.lineOffset = 0; + } - // reset the manipulationDOM - this.manipulationDOM = {}; + resized = this.yAxisLeft.redraw() || resized; + this.yAxisRight.stepPixels = this.yAxisLeft.stepPixels; + this.yAxisRight.zeroCrossing = this.yAxisLeft.zeroCrossing; + this.yAxisRight.amountOfSteps = this.yAxisLeft.amountOfSteps; + resized = this.yAxisRight.redraw() || resized; + } else { + resized = this.yAxisRight.redraw() || resized; + } - // empty the editModeDiv - util.recursiveDOMDelete(this.editModeDiv); + // clean the accumulated lists + var tempGroups = ['__barStackLeft', '__barStackRight', '__lineStackLeft', '__lineStackRight']; + for (var i = 0; i < tempGroups.length; i++) { + if (groupIds.indexOf(tempGroups[i]) != -1) { + groupIds.splice(groupIds.indexOf(tempGroups[i]), 1); + } + } - // create the contents for the editMode button - var locale = this.options.locales[this.options.locale]; - var button = this._createButton('editMode', 'vis-button vis-edit vis-edit-mode', locale['edit'] || this.options.locales['en']['edit']); - this.editModeDiv.appendChild(button); + return resized; + }; - // bind a hammer listener to the button, calling the function toggleEditMode. - this._bindHammerToDiv(button, this.toggleEditMode.bind(this)); + /** + * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function + * + * @param {boolean} axisUsed + * @returns {boolean} + * @private + * @param axis + */ + LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) { + var changed = false; + if (axisUsed == false) { + if (axis.dom.frame.parentNode && axis.hidden == false) { + axis.hide(); + changed = true; } - }, { - key: '_clean', - - /** - * this function cleans up after everything this module does. Temporary elements, functions and events are removed, physics restored, hammers removed. - * @private - */ - value: function _clean() { - // not in mode - this.inMode = false; + } else { + if (!axis.dom.frame.parentNode && axis.hidden == true) { + axis.show(); + changed = true; + } + } + return changed; + }; - // _clean the divs - if (this.guiEnabled === true) { - util.recursiveDOMDelete(this.editModeDiv); - util.recursiveDOMDelete(this.manipulationDiv); + /** + * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the + * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for + * the yAxis. + * + * @param datapoints + * @returns {Array} + * @private + */ + LineGraph.prototype._convertXcoordinates = function (datapoints) { + var extractedData = []; + var xValue, yValue; + var toScreen = this.body.util.toScreen; - // removes all the bindings and overloads - this._cleanManipulatorHammers(); - } + for (var i = 0; i < datapoints.length; i++) { + xValue = toScreen(datapoints[i].x) + this.props.width; + yValue = datapoints[i].y; + extractedData.push({ x: xValue, y: yValue }); + } - // remove temporary nodes and edges - this._cleanupTemporaryNodesAndEdges(); + return extractedData; + }; - // restore overloaded UI functions - this._unbindTemporaryUIs(); + /** + * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the + * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for + * the yAxis. + * + * @param datapoints + * @param group + * @returns {Array} + * @private + */ + LineGraph.prototype._convertYcoordinates = function (datapoints, group) { + var extractedData = []; + var xValue, yValue; + var toScreen = this.body.util.toScreen; + var axis = this.yAxisLeft; + var svgHeight = Number(this.svg.style.height.replace('px', '')); + if (group.options.yAxisOrientation == 'right') { + axis = this.yAxisRight; + } - // remove the temporaryEventFunctions - this._unbindTemporaryEvents(); + for (var i = 0; i < datapoints.length; i++) { + var labelValue = datapoints[i].label ? datapoints[i].label : null; + xValue = toScreen(datapoints[i].x) + this.props.width; + yValue = Math.round(axis.convertValue(datapoints[i].y)); + extractedData.push({ x: xValue, y: yValue, label: labelValue }); + } - // restore the physics if required - this.body.emitter.emit('restorePhysics'); - } - }, { - key: '_cleanManipulatorHammers', + group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0))); - /** - * Each dom element has it's own hammer. They are stored in this.manipulationHammers. This cleans them up. - * @private - */ - value: function _cleanManipulatorHammers() { - // _clean hammer bindings - if (this.manipulationHammers.length != 0) { - for (var i = 0; i < this.manipulationHammers.length; i++) { - this.manipulationHammers[i].destroy(); - } - this.manipulationHammers = []; - } - } - }, { - key: '_removeManipulationDOM', + return extractedData; + }; - /** - * Remove all DOM elements created by this module. - * @private - */ - value: function _removeManipulationDOM() { - // removes all the bindings and overloads - this._clean(); + module.exports = LineGraph; - // empty the manipulation divs - util.recursiveDOMDelete(this.manipulationDiv); - util.recursiveDOMDelete(this.editModeDiv); - util.recursiveDOMDelete(this.closeDiv); +/***/ }, +/* 51 */ +/***/ function(module, exports, __webpack_require__) { - // remove the manipulation divs - if (this.manipulationDiv) { - this.canvas.frame.removeChild(this.manipulationDiv); - } - if (this.editModeDiv) { - this.canvas.frame.removeChild(this.editModeDiv); - } - if (this.closeDiv) { - this.canvas.frame.removeChild(this.manipulationDiv); - } + 'use strict'; - // set the references to undefined - this.manipulationDiv = undefined; - this.editModeDiv = undefined; - this.closeDiv = undefined; - } - }, { - key: '_createSeperator', + var util = __webpack_require__(7); + var DOMutil = __webpack_require__(13); + var Component = __webpack_require__(27); + var DataStep = __webpack_require__(52); - /** - * create a seperator line. the index is to differentiate in the manipulation dom - * @param index - * @private - */ - value: function _createSeperator() { - var index = arguments[0] === undefined ? 1 : arguments[0]; + /** + * A horizontal time axis + * @param {Object} [options] See DataAxis.setOptions for the available + * options. + * @constructor DataAxis + * @extends Component + * @param body + */ + function DataAxis(body, options, svg, linegraphOptions) { + this.id = util.randomUUID(); + this.body = body; - this.manipulationDOM['seperatorLineDiv' + index] = document.createElement('div'); - this.manipulationDOM['seperatorLineDiv' + index].className = 'vis-separator-line'; - this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv' + index]); + this.defaultOptions = { + orientation: 'left', // supported: 'left', 'right' + showMinorLabels: true, + showMajorLabels: true, + icons: true, + majorLinesOffset: 7, + minorLinesOffset: 4, + labelOffsetX: 10, + labelOffsetY: 2, + iconWidth: 20, + width: '40px', + visible: true, + alignZeros: true, + left: { + range: { min: undefined, max: undefined }, + format: function format(value) { + return value; + }, + title: { text: undefined, style: undefined } + }, + right: { + range: { min: undefined, max: undefined }, + format: function format(value) { + return value; + }, + title: { text: undefined, style: undefined } } - }, { - key: '_createAddNodeButton', - - // ---------------------- DOM functions for buttons --------------------------// + }; - value: function _createAddNodeButton(locale) { - var button = this._createButton('addNode', 'vis-button vis-add', locale['addNode'] || this.options.locales['en']['addNode']); - this.manipulationDiv.appendChild(button); - this._bindHammerToDiv(button, this.addNodeMode.bind(this)); - } - }, { - key: '_createAddEdgeButton', - value: function _createAddEdgeButton(locale) { - var button = this._createButton('addEdge', 'vis-button vis-connect', locale['addEdge'] || this.options.locales['en']['addEdge']); - this.manipulationDiv.appendChild(button); - this._bindHammerToDiv(button, this.addEdgeMode.bind(this)); - } - }, { - key: '_createEditNodeButton', - value: function _createEditNodeButton(locale) { - var button = this._createButton('editNode', 'vis-button vis-edit', locale['editNode'] || this.options.locales['en']['editNode']); - this.manipulationDiv.appendChild(button); - this._bindHammerToDiv(button, this.editNode.bind(this)); - } - }, { - key: '_createEditEdgeButton', - value: function _createEditEdgeButton(locale) { - var button = this._createButton('editEdge', 'vis-button vis-edit', locale['editEdge'] || this.options.locales['en']['editEdge']); - this.manipulationDiv.appendChild(button); - this._bindHammerToDiv(button, this.editEdgeMode.bind(this)); - } - }, { - key: '_createDeleteButton', - value: function _createDeleteButton(locale) { - var button = this._createButton('delete', 'vis-button vis-delete', locale['del'] || this.options.locales['en']['del']); - this.manipulationDiv.appendChild(button); - this._bindHammerToDiv(button, this.deleteSelected.bind(this)); - } - }, { - key: '_createBackButton', - value: function _createBackButton(locale) { - var button = this._createButton('back', 'vis-button vis-back', locale['back'] || this.options.locales['en']['back']); - this.manipulationDiv.appendChild(button); - this._bindHammerToDiv(button, this.showManipulatorToolbar.bind(this)); - } - }, { - key: '_createButton', - value: function _createButton(id, className, label) { - var labelClassName = arguments[3] === undefined ? 'vis-label' : arguments[3]; + this.linegraphOptions = linegraphOptions; + this.linegraphSVG = svg; + this.props = {}; + this.DOMelements = { // dynamic elements + lines: {}, + labels: {}, + title: {} + }; - this.manipulationDOM[id + 'Div'] = document.createElement('div'); - this.manipulationDOM[id + 'Div'].className = className; - this.manipulationDOM[id + 'Label'] = document.createElement('div'); - this.manipulationDOM[id + 'Label'].className = labelClassName; - this.manipulationDOM[id + 'Label'].innerHTML = label; - this.manipulationDOM[id + 'Div'].appendChild(this.manipulationDOM[id + 'Label']); - return this.manipulationDOM[id + 'Div']; - } - }, { - key: '_createDescription', - value: function _createDescription(label) { - this.manipulationDiv.appendChild(this._createButton('description', 'vis-button vis-none', label)); - } - }, { - key: '_temporaryBindEvent', + this.dom = {}; - // -------------------------- End of DOM functions for buttons ------------------------------// + this.range = { start: 0, end: 0 }; - /** - * this binds an event until cleanup by the clean functions. - * @param event - * @param newFunction - * @private - */ - value: function _temporaryBindEvent(event, newFunction) { - this.temporaryEventFunctions.push({ event: event, boundFunction: newFunction }); - this.body.emitter.on(event, newFunction); - } - }, { - key: '_temporaryBindUI', + this.options = util.extend({}, this.defaultOptions); + this.conversionFactor = 1; - /** - * this overrides an UI function until cleanup by the clean function - * @param UIfunctionName - * @param newFunction - * @private - */ - value: function _temporaryBindUI(UIfunctionName, newFunction) { - if (this.body.eventListeners[UIfunctionName] !== undefined) { - this.temporaryUIFunctions[UIfunctionName] = this.body.eventListeners[UIfunctionName]; - this.body.eventListeners[UIfunctionName] = newFunction; - } else { - throw new Error('This UI function does not exist. Typo? You tried: ' + UIfunctionName + ' possible are: ' + JSON.stringify(Object.keys(this.body.eventListeners))); - } - } - }, { - key: '_unbindTemporaryUIs', + this.setOptions(options); + this.width = Number(('' + this.options.width).replace('px', '')); + this.minWidth = this.width; + this.height = this.linegraphSVG.offsetHeight; + this.hidden = false; - /** - * Restore the overridden UI functions to their original state. - * - * @private - */ - value: function _unbindTemporaryUIs() { - for (var functionName in this.temporaryUIFunctions) { - if (this.temporaryUIFunctions.hasOwnProperty(functionName)) { - this.body.eventListeners[functionName] = this.temporaryUIFunctions[functionName]; - delete this.temporaryUIFunctions[functionName]; - } - } - this.temporaryUIFunctions = {}; - } - }, { - key: '_unbindTemporaryEvents', + this.stepPixels = 25; + this.zeroCrossing = -1; + this.amountOfSteps = -1; - /** - * Unbind the events created by _temporaryBindEvent - * @private - */ - value: function _unbindTemporaryEvents() { - for (var i = 0; i < this.temporaryEventFunctions.length; i++) { - var eventName = this.temporaryEventFunctions[i].event; - var boundFunction = this.temporaryEventFunctions[i].boundFunction; - this.body.emitter.off(eventName, boundFunction); - } - this.temporaryEventFunctions = []; - } - }, { - key: '_bindHammerToDiv', + this.lineOffset = 0; + this.master = true; + this.svgElements = {}; + this.iconsRemoved = false; - /** - * Bind an hammer instance to a DOM element. - * @param domElement - * @param funct - */ - value: function _bindHammerToDiv(domElement, boundFunction) { - var hammer = new Hammer(domElement, {}); - hammerUtil.onTouch(hammer, boundFunction); - this.manipulationHammers.push(hammer); - } - }, { - key: '_cleanupTemporaryNodesAndEdges', + this.groups = {}; + this.amountOfGroups = 0; - /** - * Neatly clean up temporary edges and nodes - * @private - */ - value: function _cleanupTemporaryNodesAndEdges() { - // _clean temporary edges - for (var i = 0; i < this.temporaryIds.edges.length; i++) { - this.body.edges[this.temporaryIds.edges[i]].disconnect(); - delete this.body.edges[this.temporaryIds.edges[i]]; - var indexTempEdge = this.body.edgeIndices.indexOf(this.temporaryIds.edges[i]); - if (indexTempEdge !== -1) { - this.body.edgeIndices.splice(indexTempEdge, 1); - } - } + // create the HTML DOM + this._create(); - // _clean temporary nodes - for (var i = 0; i < this.temporaryIds.nodes.length; i++) { - delete this.body.nodes[this.temporaryIds.nodes[i]]; - var indexTempNode = this.body.nodeIndices.indexOf(this.temporaryIds.nodes[i]); - if (indexTempNode !== -1) { - this.body.nodeIndices.splice(indexTempNode, 1); - } - } + var me = this; + this.body.emitter.on('verticalDrag', function () { + me.dom.lineContainer.style.top = me.body.domProps.scrollTop + 'px'; + }); + } - this.temporaryIds = { nodes: [], edges: [] }; + DataAxis.prototype = new Component(); + + DataAxis.prototype.addGroup = function (label, graphOptions) { + if (!this.groups.hasOwnProperty(label)) { + this.groups[label] = graphOptions; + } + this.amountOfGroups += 1; + }; + + DataAxis.prototype.updateGroup = function (label, graphOptions) { + this.groups[label] = graphOptions; + }; + + DataAxis.prototype.removeGroup = function (label) { + if (this.groups.hasOwnProperty(label)) { + delete this.groups[label]; + this.amountOfGroups -= 1; + } + }; + + DataAxis.prototype.setOptions = function (options) { + if (options) { + var redraw = false; + if (this.options.orientation != options.orientation && options.orientation !== undefined) { + redraw = true; } - }, { - key: '_controlNodeTouch', + var fields = ['orientation', 'showMinorLabels', 'showMajorLabels', 'icons', 'majorLinesOffset', 'minorLinesOffset', 'labelOffsetX', 'labelOffsetY', 'iconWidth', 'width', 'visible', 'left', 'right', 'alignZeros']; + util.selectiveExtend(fields, this.options, options); - // ------------------------------------------ EDIT EDGE FUNCTIONS -----------------------------------------// + this.minWidth = Number(('' + this.options.width).replace('px', '')); - /** - * the touch is used to get the position of the initial click - * @param event - * @private - */ - value: function _controlNodeTouch(event) { - this.selectionHandler.unselectAll(); - this.lastTouch = this.body.functions.getPointer(event.center); - this.lastTouch.translation = util.extend({}, this.body.view.translation); // copy the object + if (redraw === true && this.dom.frame) { + this.hide(); + this.show(); } - }, { - key: '_controlNodeDragStart', + } + }; - /** - * the drag start is used to mark one of the control nodes as selected. - * @param event - * @private - */ - value: function _controlNodeDragStart(event) { - var pointer = this.lastTouch; - var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); - var from = this.body.nodes[this.temporaryIds.nodes[0]]; - var to = this.body.nodes[this.temporaryIds.nodes[1]]; - var edge = this.body.edges[this.edgeBeingEditedId]; - this.selectedControlNode = undefined; + /** + * Create the HTML DOM for the DataAxis + */ + DataAxis.prototype._create = function () { + this.dom.frame = document.createElement('div'); + this.dom.frame.style.width = this.options.width; + this.dom.frame.style.height = this.height; - var fromSelect = from.isOverlappingWith(pointerObj); - var toSelect = to.isOverlappingWith(pointerObj); + this.dom.lineContainer = document.createElement('div'); + this.dom.lineContainer.style.width = '100%'; + this.dom.lineContainer.style.height = this.height; + this.dom.lineContainer.style.position = 'relative'; - if (fromSelect === true) { - this.selectedControlNode = from; - edge.edgeType.from = from; - } else if (toSelect === true) { - this.selectedControlNode = to; - edge.edgeType.to = to; - } + // create svg element for graph drawing. + this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + this.svg.style.position = 'absolute'; + this.svg.style.top = '0px'; + this.svg.style.height = '100%'; + this.svg.style.width = '100%'; + this.svg.style.display = 'block'; + this.dom.frame.appendChild(this.svg); + }; - this.body.emitter.emit('_redraw'); - } - }, { - key: '_controlNodeDrag', + DataAxis.prototype._redrawGroupIcons = function () { + DOMutil.prepareElements(this.svgElements); - /** - * dragging the control nodes or the canvas - * @param event - * @private - */ - value: function _controlNodeDrag(event) { - this.body.emitter.emit('disablePhysics'); - var pointer = this.body.functions.getPointer(event.center); - var pos = this.canvas.DOMtoCanvas(pointer); + var x; + var iconWidth = this.options.iconWidth; + var iconHeight = 15; + var iconOffset = 4; + var y = iconOffset + 0.5 * iconHeight; - if (this.selectedControlNode !== undefined) { - this.selectedControlNode.x = pos.x; - this.selectedControlNode.y = pos.y; - } else { - // if the drag was not started properly because the click started outside the network div, start it now. - var diffX = pointer.x - this.lastTouch.x; - var diffY = pointer.y - this.lastTouch.y; - this.body.view.translation = { x: this.lastTouch.translation.x + diffX, y: this.lastTouch.translation.y + diffY }; - } - this.body.emitter.emit('_redraw'); + if (this.options.orientation === 'left') { + x = iconOffset; + } else { + x = this.width - iconWidth - iconOffset; + } + + var groupArray = Object.keys(this.groups); + groupArray.sort(function (a, b) { + return a < b ? -1 : 1; + }); + + for (var i = 0; i < groupArray.length; i++) { + var groupId = groupArray[i]; + if (this.groups[groupId].visible === true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] === true)) { + this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight); + y += iconHeight + iconOffset; } - }, { - key: '_controlNodeDragEnd', + } - /** - * connecting or restoring the control nodes. - * @param event - * @private - */ - value: function _controlNodeDragEnd(event) { - var pointer = this.body.functions.getPointer(event.center); - var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); - var edge = this.body.edges[this.edgeBeingEditedId]; + DOMutil.cleanupElements(this.svgElements); + this.iconsRemoved = false; + }; - var overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj); - var node = undefined; - for (var i = overlappingNodeIds.length - 1; i >= 0; i--) { - if (overlappingNodeIds[i] !== this.selectedControlNode.id) { - node = this.body.nodes[overlappingNodeIds[i]]; - break; - } - } + DataAxis.prototype._cleanupIcons = function () { + if (this.iconsRemoved === false) { + DOMutil.prepareElements(this.svgElements); + DOMutil.cleanupElements(this.svgElements); + this.iconsRemoved = true; + } + }; - // perform the connection - if (node !== undefined && this.selectedControlNode !== undefined) { - if (node.isCluster === true) { - alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']); - } else { - var from = this.body.nodes[this.temporaryIds.nodes[0]]; - if (this.selectedControlNode.id === from.id) { - this._performEditEdge(node.id, edge.to.id); - } else { - this._performEditEdge(edge.from.id, node.id); - } - } - } else { - edge.updateEdgeType(); - this.body.emitter.emit('restorePhysics'); - } - this.body.emitter.emit('_redraw'); + /** + * Create the HTML DOM for the DataAxis + */ + DataAxis.prototype.show = function () { + this.hidden = false; + if (!this.dom.frame.parentNode) { + if (this.options.orientation === 'left') { + this.body.dom.left.appendChild(this.dom.frame); + } else { + this.body.dom.right.appendChild(this.dom.frame); } - }, { - key: '_handleConnect', + } - // ------------------------------------ END OF EDIT EDGE FUNCTIONS -----------------------------------------// + if (!this.dom.lineContainer.parentNode) { + this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer); + } + }; - // ------------------------------------------- ADD EDGE FUNCTIONS -----------------------------------------// - /** - * the function bound to the selection event. It checks if you want to connect a cluster and changes the description - * to walk the user through the process. - * - * @private - */ - value: function _handleConnect(event) { - // check to avoid double fireing of this function. - if (new Date().valueOf() - this.touchTime > 100) { - this.lastTouch = this.body.functions.getPointer(event.center); - this.lastTouch.translation = util.extend({}, this.body.view.translation); // copy the object + /** + * Create the HTML DOM for the DataAxis + */ + DataAxis.prototype.hide = function () { + this.hidden = true; + if (this.dom.frame.parentNode) { + this.dom.frame.parentNode.removeChild(this.dom.frame); + } - var pointer = this.lastTouch; - var node = this.selectionHandler.getNodeAt(pointer); + if (this.dom.lineContainer.parentNode) { + this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer); + } + }; - if (node !== undefined) { - if (node.isCluster === true) { - alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']); - } else { - // create a node the temporary line can look at - var targetNode = this._getNewTargetNode(node.x, node.y); - this.body.nodes[targetNode.id] = targetNode; - this.body.nodeIndices.push(targetNode.id); + /** + * Set a range (start and end) + * @param end + * @param start + * @param end + */ + DataAxis.prototype.setRange = function (start, end) { + if (this.master === false && this.options.alignZeros === true && this.zeroCrossing != -1) { + if (start > 0) { + start = 0; + } + } + this.range.start = start; + this.range.end = end; + }; - // create a temporary edge - var connectionEdge = this.body.functions.createEdge({ - id: 'connectionEdge' + util.randomUUID(), - from: node.id, - to: targetNode.id, - physics: false, - smooth: { - enabled: true, - type: 'continuous', - roundness: 0.5 - } - }); - this.body.edges[connectionEdge.id] = connectionEdge; - this.body.edgeIndices.push(connectionEdge.id); + /** + * Repaint the component + * @return {boolean} Returns true if the component is resized + */ + DataAxis.prototype.redraw = function () { + var resized = false; + var activeGroups = 0; - this.temporaryIds.nodes.push(targetNode.id); - this.temporaryIds.edges.push(connectionEdge.id); - } - } - this.touchTime = new Date().valueOf(); - } - } - }, { - key: '_dragControlNode', - value: function _dragControlNode(event) { - var pointer = this.body.functions.getPointer(event.center); - if (this.temporaryIds.nodes[0] !== undefined) { - var targetNode = this.body.nodes[this.temporaryIds.nodes[0]]; // there is only one temp node in the add edge mode. - targetNode.x = this.canvas._XconvertDOMtoCanvas(pointer.x); - targetNode.y = this.canvas._YconvertDOMtoCanvas(pointer.y); - this.body.emitter.emit('_redraw'); - } else { - var diffX = pointer.x - this.lastTouch.x; - var diffY = pointer.y - this.lastTouch.y; - this.body.view.translation = { x: this.lastTouch.translation.x + diffX, y: this.lastTouch.translation.y + diffY }; + // Make sure the line container adheres to the vertical scrolling. + this.dom.lineContainer.style.top = this.body.domProps.scrollTop + 'px'; + + for (var groupId in this.groups) { + if (this.groups.hasOwnProperty(groupId)) { + if (this.groups[groupId].visible === true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] === true)) { + activeGroups++; } } - }, { - key: '_finishConnect', + } + if (this.amountOfGroups === 0 || activeGroups === 0) { + this.hide(); + } else { + this.show(); + this.height = Number(this.linegraphSVG.style.height.replace('px', '')); - /** - * Connect the new edge to the target if one exists, otherwise remove temp line - * @param event - * @private - */ - value: function _finishConnect(event) { - var pointer = this.body.functions.getPointer(event.center); - var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); + // svg offsetheight did not work in firefox and explorer... + this.dom.lineContainer.style.height = this.height + 'px'; + this.width = this.options.visible === true ? Number(('' + this.options.width).replace('px', '')) : 0; - // remember the edge id - var connectFromId = undefined; - if (this.temporaryIds.edges[0] !== undefined) { - connectFromId = this.body.edges[this.temporaryIds.edges[0]].fromId; - } + var props = this.props; + var frame = this.dom.frame; - // get the overlapping node but NOT the temporary node; - var overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj); - var node = undefined; - for (var i = overlappingNodeIds.length - 1; i >= 0; i--) { - // if the node id is NOT a temporary node, accept the node. - if (this.temporaryIds.nodes.indexOf(overlappingNodeIds[i]) === -1) { - node = this.body.nodes[overlappingNodeIds[i]]; - break; - } - } + // update classname + frame.className = 'vis-data-axis'; - // clean temporary nodes and edges. - this._cleanupTemporaryNodesAndEdges(); + // calculate character width and height + this._calculateCharSize(); - // perform the connection - if (node !== undefined) { - if (node.isCluster === true) { - alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']); - } else { - if (this.body.nodes[connectFromId] !== undefined && this.body.nodes[node.id] !== undefined) { - this._performAddEdge(connectFromId, node.id); - } - } - } - this.body.emitter.emit('_redraw'); + var orientation = this.options.orientation; + var showMinorLabels = this.options.showMinorLabels; + var showMajorLabels = this.options.showMajorLabels; + + // determine the width and height of the elements for the axis + props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0; + props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0; + + props.minorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.minorLinesOffset; + props.minorLineHeight = 1; + props.majorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.majorLinesOffset; + props.majorLineHeight = 1; + + // take frame offline while updating (is almost twice as fast) + if (orientation === 'left') { + frame.style.top = '0'; + frame.style.left = '0'; + frame.style.bottom = ''; + frame.style.width = this.width + 'px'; + frame.style.height = this.height + 'px'; + this.props.width = this.body.domProps.left.width; + this.props.height = this.body.domProps.left.height; + } else { + // right + frame.style.top = ''; + frame.style.bottom = '0'; + frame.style.left = '0'; + frame.style.width = this.width + 'px'; + frame.style.height = this.height + 'px'; + this.props.width = this.body.domProps.right.width; + this.props.height = this.body.domProps.right.height; } - }, { - key: '_performAddNode', - // --------------------------------------- END OF ADD EDGE FUNCTIONS -------------------------------------// + resized = this._redrawLabels(); + resized = this._isResized() || resized; - // ------------------------------ Performing all the actual data manipulation ------------------------// + if (this.options.icons === true) { + this._redrawGroupIcons(); + } else { + this._cleanupIcons(); + } - /** - * Adds a node on the specified location - */ - value: function _performAddNode(clickData) { - var _this4 = this; + this._redrawTitle(orientation); + } + return resized; + }; - var defaultData = { - id: util.randomUUID(), - x: clickData.pointer.canvas.x, - y: clickData.pointer.canvas.y, - label: 'new' - }; + /** + * Repaint major and minor text labels and vertical grid lines + * @private + */ + DataAxis.prototype._redrawLabels = function () { + var resized = false; + DOMutil.prepareElements(this.DOMelements.lines); + DOMutil.prepareElements(this.DOMelements.labels); + var orientation = this.options['orientation']; - if (typeof this.options.addNode === 'function') { - if (this.options.addNode.length === 2) { - this.options.addNode(defaultData, function (finalizedData) { - if (finalizedData !== null && finalizedData !== undefined && _this4.inMode === 'addNode') { - // if for whatever reason the mode has changes (due to dataset change) disregard the callback - _this4.body.data.nodes.add(finalizedData); - _this4.showManipulatorToolbar(); - } - }); - } else { - throw new Error('The function for add does not support two arguments (data,callback)'); - this.showManipulatorToolbar(); - } + // get the range for the slaved axis + var step; + if (this.master === false) { + var stepSize, rangeStart, rangeEnd, minimumStep; + if (this.zeroCrossing !== -1 && this.options.alignZeros === true) { + if (this.range.end > 0) { + stepSize = this.range.end / this.zeroCrossing; // size of one step + rangeStart = this.range.end - this.amountOfSteps * stepSize; + rangeEnd = this.range.end; } else { - this.body.data.nodes.add(defaultData); - this.showManipulatorToolbar(); + // all of the range (including start) has to be done before the zero crossing. + stepSize = -1 * this.range.start / (this.amountOfSteps - this.zeroCrossing); // absolute size of a step + rangeStart = this.range.start; + rangeEnd = this.range.start + stepSize * this.amountOfSteps; } + } else { + rangeStart = this.range.start; + rangeEnd = this.range.end; } - }, { - key: '_performAddEdge', + minimumStep = this.stepPixels; + } else { + // calculate range and step (step such that we have space for 7 characters per label) + minimumStep = this.props.majorCharHeight; + rangeStart = this.range.start; + rangeEnd = this.range.end; + } - /** - * connect two nodes with a new edge. - * - * @private - */ - value: function _performAddEdge(sourceNodeId, targetNodeId) { - var _this5 = this; + this.step = step = new DataStep(rangeStart, rangeEnd, minimumStep, this.dom.frame.offsetHeight, this.options[this.options.orientation].range, this.options[this.options.orientation].format, this.master === false && this.options.alignZeros // does the step have to align zeros? only if not master and the options is on + ); - var defaultData = { from: sourceNodeId, to: targetNodeId }; - if (typeof this.options.addEdge === 'function') { - if (this.options.addEdge.length === 2) { - this.options.addEdge(defaultData, function (finalizedData) { - if (finalizedData !== null && finalizedData !== undefined && _this5.inMode === 'addEdge') { - // if for whatever reason the mode has changes (due to dataset change) disregard the callback - _this5.body.data.edges.add(finalizedData); - _this5.selectionHandler.unselectAll(); - _this5.showManipulatorToolbar(); - } - }); - } else { - throw new Error('The function for connect does not support two arguments (data,callback)'); - } - } else { - this.body.data.edges.add(defaultData); - this.selectionHandler.unselectAll(); - this.showManipulatorToolbar(); - } + // the slave axis needs to use the same horizontal lines as the master axis. + if (this.master === true) { + this.stepPixels = this.dom.frame.offsetHeight / step.marginRange * step.step; + this.amountOfSteps = Math.ceil(this.dom.frame.offsetHeight / this.stepPixels); + } else { + // align with zero + if (this.options.alignZeros === true && this.zeroCrossing !== -1) { + // distance is the amount of steps away from the zero crossing we are. + var distance = (step.current - this.zeroCrossing * step.step) / step.step; + this.step.shift(distance); } - }, { - key: '_performEditEdge', + } - /** - * connect two nodes with a new edge. - * - * @private - */ - value: function _performEditEdge(sourceNodeId, targetNodeId) { - var _this6 = this; + // value at the bottom of the SVG + this.valueAtBottom = step.marginEnd; - var defaultData = { id: this.edgeBeingEditedId, from: sourceNodeId, to: targetNodeId }; - if (typeof this.options.editEdge === 'function') { - if (this.options.editEdge.length === 2) { - this.options.editEdge(defaultData, function (finalizedData) { - if (finalizedData === null || finalizedData === undefined || _this6.inMode !== 'editEdge') { - // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { - _this6.body.edges[defaultData.id].updateEdgeType(); - _this6.body.emitter.emit('_redraw'); - } else { - _this6.body.data.edges.update(finalizedData); - _this6.selectionHandler.unselectAll(); - _this6.showManipulatorToolbar(); - } - }); - } else { - throw new Error('The function for edit does not support two arguments (data, callback)'); + this.maxLabelSize = 0; + var y = 0; // init value + var stepIndex = 0; // init value + var isMajor = false; // init value + while (stepIndex < this.amountOfSteps) { + y = Math.round(stepIndex * this.stepPixels); + isMajor = step.isMajor(); + + if (stepIndex > 0 && stepIndex !== this.amountOfSteps) { + if (this.options['showMinorLabels'] && isMajor === false || this.master === false && this.options['showMinorLabels'] === true) { + this._redrawLabel(y - 2, step.getCurrent(), orientation, 'vis-y-axis vis-minor', this.props.minorCharHeight); + } + + if (isMajor && this.options['showMajorLabels'] && this.master === true || this.options['showMinorLabels'] === false && this.master === false && isMajor === true) { + if (y >= 0) { + this._redrawLabel(y - 2, step.getCurrent(), orientation, 'vis-y-axis vis-major', this.props.majorCharHeight); } + this._redrawLine(y, orientation, 'vis-grid vis-horizontal vis-major', this.options.majorLinesOffset, this.props.majorLineWidth); } else { - this.body.data.edges.update(defaultData); - this.selectionHandler.unselectAll(); - this.showManipulatorToolbar(); + this._redrawLine(y, orientation, 'vis-grid vis-horizontal vis-minor', this.options.minorLinesOffset, this.props.minorLineWidth); } } - }]); - return ManipulationSystem; - })(); + // get zero crossing + if (this.master === true && step.current === 0) { + this.zeroCrossing = stepIndex; + } - exports['default'] = ManipulationSystem; - module.exports = exports['default']; + step.next(); + stepIndex += 1; + } + + // get zero crossing if it's the last step + if (this.master === true && step.current === 0) { + this.zeroCrossing = stepIndex; + } + + this.conversionFactor = this.stepPixels / step.step; + + // Note that title is rotated, so we're using the height, not width! + var titleWidth = 0; + if (this.options[orientation].title !== undefined && this.options[orientation].title.text !== undefined) { + titleWidth = this.props.titleCharHeight; + } + var offset = this.options.icons === true ? Math.max(this.options.iconWidth, titleWidth) + this.options.labelOffsetX + 15 : titleWidth + this.options.labelOffsetX + 15; + + // this will resize the yAxis to accommodate the labels. + if (this.maxLabelSize > this.width - offset && this.options.visible === true) { + this.width = this.maxLabelSize + offset; + this.options.width = this.width + 'px'; + DOMutil.cleanupElements(this.DOMelements.lines); + DOMutil.cleanupElements(this.DOMelements.labels); + this.redraw(); + resized = true; + } + // this will resize the yAxis if it is too big for the labels. + else if (this.maxLabelSize < this.width - offset && this.options.visible === true && this.width > this.minWidth) { + this.width = Math.max(this.minWidth, this.maxLabelSize + offset); + this.options.width = this.width + 'px'; + DOMutil.cleanupElements(this.DOMelements.lines); + DOMutil.cleanupElements(this.DOMelements.labels); + this.redraw(); + resized = true; + } else { + DOMutil.cleanupElements(this.DOMelements.lines); + DOMutil.cleanupElements(this.DOMelements.labels); + resized = false; + } + + return resized; + }; + + DataAxis.prototype.convertValue = function (value) { + var invertedValue = this.valueAtBottom - value; + var convertedValue = invertedValue * this.conversionFactor; + return convertedValue; + }; + + DataAxis.prototype.screenToValue = function (x) { + return this.valueAtBottom - x / this.conversionFactor; + }; + + /** + * Create a label for the axis at position x + * @private + * @param y + * @param text + * @param orientation + * @param className + * @param characterHeight + */ + DataAxis.prototype._redrawLabel = function (y, text, orientation, className, characterHeight) { + // reuse redundant label + var label = DOMutil.getDOMElement('div', this.DOMelements.labels, this.dom.frame); //this.dom.redundant.labels.shift(); + label.className = className; + label.innerHTML = text; + if (orientation === 'left') { + label.style.left = '-' + this.options.labelOffsetX + 'px'; + label.style.textAlign = 'right'; + } else { + label.style.right = '-' + this.options.labelOffsetX + 'px'; + label.style.textAlign = 'left'; + } + + label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px'; + + text += ''; + + var largestWidth = Math.max(this.props.majorCharWidth, this.props.minorCharWidth); + if (this.maxLabelSize < text.length * largestWidth) { + this.maxLabelSize = text.length * largestWidth; + } + }; + + /** + * Create a minor line for the axis at position y + * @param y + * @param orientation + * @param className + * @param offset + * @param width + */ + DataAxis.prototype._redrawLine = function (y, orientation, className, offset, width) { + if (this.master === true) { + var line = DOMutil.getDOMElement('div', this.DOMelements.lines, this.dom.lineContainer); //this.dom.redundant.lines.shift(); + line.className = className; + line.innerHTML = ''; + + if (orientation === 'left') { + line.style.left = this.width - offset + 'px'; + } else { + line.style.right = this.width - offset + 'px'; + } + + line.style.width = width + 'px'; + line.style.top = y + 'px'; + } + }; + + /** + * Create a title for the axis + * @private + * @param orientation + */ + DataAxis.prototype._redrawTitle = function (orientation) { + DOMutil.prepareElements(this.DOMelements.title); + + // Check if the title is defined for this axes + if (this.options[orientation].title !== undefined && this.options[orientation].title.text !== undefined) { + var title = DOMutil.getDOMElement('div', this.DOMelements.title, this.dom.frame); + title.className = 'vis-y-axis vis-title vis-' + orientation; + title.innerHTML = this.options[orientation].title.text; + + // Add style - if provided + if (this.options[orientation].title.style !== undefined) { + util.addCssText(title, this.options[orientation].title.style); + } + + if (orientation === 'left') { + title.style.left = this.props.titleCharHeight + 'px'; + } else { + title.style.right = this.props.titleCharHeight + 'px'; + } + + title.style.width = this.height + 'px'; + } + + // we need to clean up in case we did not use all elements. + DOMutil.cleanupElements(this.DOMelements.title); + }; + + /** + * 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 + */ + DataAxis.prototype._calculateCharSize = function () { + // determine the char width and height on the minor axis + if (!('minorCharHeight' in this.props)) { + var textMinor = document.createTextNode('0'); + var measureCharMinor = document.createElement('div'); + measureCharMinor.className = 'vis-y-axis vis-minor vis-measure'; + measureCharMinor.appendChild(textMinor); + this.dom.frame.appendChild(measureCharMinor); + + this.props.minorCharHeight = measureCharMinor.clientHeight; + this.props.minorCharWidth = measureCharMinor.clientWidth; + + this.dom.frame.removeChild(measureCharMinor); + } + + if (!('majorCharHeight' in this.props)) { + var textMajor = document.createTextNode('0'); + var measureCharMajor = document.createElement('div'); + measureCharMajor.className = 'vis-y-axis vis-major vis-measure'; + measureCharMajor.appendChild(textMajor); + this.dom.frame.appendChild(measureCharMajor); + + this.props.majorCharHeight = measureCharMajor.clientHeight; + this.props.majorCharWidth = measureCharMajor.clientWidth; + + this.dom.frame.removeChild(measureCharMajor); + } + + if (!('titleCharHeight' in this.props)) { + var textTitle = document.createTextNode('0'); + var measureCharTitle = document.createElement('div'); + measureCharTitle.className = 'vis-y-axis vis-title vis-measure'; + measureCharTitle.appendChild(textTitle); + this.dom.frame.appendChild(measureCharTitle); + + this.props.titleCharHeight = measureCharTitle.clientHeight; + this.props.titleCharWidth = measureCharTitle.clientWidth; + + this.dom.frame.removeChild(measureCharTitle); + } + }; + + module.exports = DataAxis; /***/ }, -/* 66 */ +/* 52 */ /***/ function(module, exports, __webpack_require__) { /** - * This object contains all possible options. It will check if the types are correct, if required if the option is one - * of the allowed values. + * @constructor DataStep + * The class DataStep is an iterator for data for the lineGraph. You provide a start data point and an + * end data point. The class itself determines the best scale (step size) based on the + * provided start Date, end Date, and minimumStep. * - * __any__ means that the name of the property does not matter. - * __type__ is a required field for all objects and contains the allowed types of all objects + * 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 DataStep 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 */ 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); - var string = 'string'; - var boolean = 'boolean'; - var number = 'number'; - var array = 'array'; - var object = 'object'; // should only be in a __type__ property - var dom = 'dom'; - var fn = 'function'; - var undef = 'undefined'; - var any = 'any'; + function DataStep(start, end, minimumStep, containerHeight, customRange, formattingFunction, alignZeros) { + // variables + this.current = 0; - var allOptions = { - configure: { - enabled: { boolean: boolean }, - filter: { boolean: boolean, string: string, array: array, fn: fn }, - container: { dom: dom }, - showButton: { boolean: boolean }, - __type__: { object: object, boolean: boolean, string: string, array: array, fn: fn } - }, - edges: { - arrows: { - to: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } }, - middle: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } }, - from: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } }, - __type__: { string: ['from', 'to', 'middle'], object: object } - }, - color: { - color: { string: string }, - highlight: { string: string }, - hover: { string: string }, - inherit: { string: ['from', 'to', 'both'], boolean: boolean }, - opacity: { number: number }, - __type__: { object: object, string: string } - }, - dashes: { boolean: boolean, array: array }, - font: { - color: { string: string }, - size: { number: number }, // px - face: { string: string }, - background: { string: string }, - strokeWidth: { number: number }, // px - strokeColor: { string: string }, - align: { string: ['horizontal', 'top', 'middle', 'bottom'] }, - __type__: { object: object, string: string } - }, - hidden: { boolean: boolean }, - hoverWidth: { fn: fn, number: number }, - label: { string: string, undef: undef }, - length: { number: number, undef: undef }, - physics: { boolean: boolean }, - scaling: { - min: { number: number }, - max: { number: number }, - label: { - enabled: { boolean: boolean }, - min: { number: number }, - max: { number: number }, - maxVisible: { number: number }, - drawThreshold: { number: number }, - __type__: { object: object, boolean: boolean } - }, - customScalingFunction: { fn: fn }, - __type__: { object: object } - }, - selectionWidth: { fn: fn, number: number }, - selfReferenceSize: { number: number }, - shadow: { - enabled: { boolean: boolean }, - size: { number: number }, - x: { number: number }, - y: { number: number }, - __type__: { object: object, boolean: boolean } - }, - smooth: { - enabled: { boolean: boolean }, - type: { string: ['dynamic', 'continuous', 'discrete', 'diagonalCross', 'straightCross', 'horizontal', 'vertical', 'curvedCW', 'curvedCCW'] }, - roundness: { number: number }, - __type__: { object: object, boolean: boolean } + this.autoScale = true; + this.stepIndex = 0; + this.step = 1; + this.scale = 1; + this.formattingFunction = formattingFunction; + + this.marginStart; + this.marginEnd; + this.deadSpace = 0; + + this.majorSteps = [1, 2, 5, 10]; + this.minorSteps = [0.25, 0.5, 1, 2]; + + this.alignZeros = alignZeros; + + this.setRange(start, end, minimumStep, containerHeight, customRange); + } + + /** + * 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 {Number} [start] The start date and time. + * @param {Number} [end] The end date and time. + * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds + */ + DataStep.prototype.setRange = function (start, end, minimumStep, containerHeight, customRange) { + this._start = customRange.min === undefined ? start : customRange.min; + this._end = customRange.max === undefined ? end : customRange.max; + if (this._start === this._end) { + this._start = customRange.min === undefined ? this._start - 0.75 : this._start; + this._end = customRange.max === undefined ? this._end + 1 : this._end;; + } + + if (this.autoScale === true) { + this.setMinimumStep(minimumStep, containerHeight); + } + + this.setFirst(customRange); + }; + + /** + * Automatically determine the scale that bests fits the provided minimum step + * @param {Number} [minimumStep] The minimum step size in pixels + */ + DataStep.prototype.setMinimumStep = function (minimumStep, containerHeight) { + // round to floor + var range = this._end - this._start; + var safeRange = range * 1.2; + var minimumStepValue = minimumStep * (safeRange / containerHeight); + var orderOfMagnitude = Math.round(Math.log(safeRange) / Math.LN10); + + var minorStepIdx = -1; + var magnitudefactor = Math.pow(10, orderOfMagnitude); + + var start = 0; + if (orderOfMagnitude < 0) { + start = orderOfMagnitude; + } + + var solutionFound = false; + for (var i = start; Math.abs(i) <= Math.abs(orderOfMagnitude); i++) { + magnitudefactor = Math.pow(10, i); + for (var j = 0; j < this.minorSteps.length; j++) { + var stepSize = magnitudefactor * this.minorSteps[j]; + if (stepSize >= minimumStepValue) { + solutionFound = true; + minorStepIdx = j; + break; + } + } + if (solutionFound === true) { + break; + } + } + this.stepIndex = minorStepIdx; + this.scale = magnitudefactor; + this.step = magnitudefactor * this.minorSteps[minorStepIdx]; + }; + + /** + * Round the current date to the first minor date value + * This must be executed once when the current date is set to start Date + */ + DataStep.prototype.setFirst = function (customRange) { + if (customRange === undefined) { + customRange = {}; + } + + var niceStart = customRange.min === undefined ? this._start - this.scale * 2 * this.minorSteps[this.stepIndex] : customRange.min; + var niceEnd = customRange.max === undefined ? this._end + this.scale * this.minorSteps[this.stepIndex] : customRange.max; + + this.marginEnd = customRange.max === undefined ? this.roundToMinor(niceEnd) : customRange.max; + this.marginStart = customRange.min === undefined ? this.roundToMinor(niceStart) : customRange.min; + + // if we need to align the zero's we need to make sure that there is a zero to use. + if (this.alignZeros === true && (this.marginEnd - this.marginStart) % this.step != 0) { + this.marginEnd += this.marginEnd % this.step; + } + + this.deadSpace = this.roundToMinor(niceEnd) - niceEnd + this.roundToMinor(niceStart) - niceStart; + this.marginRange = this.marginEnd - this.marginStart; + + this.current = this.marginEnd; + }; + + DataStep.prototype.roundToMinor = function (value) { + var rounded = value - value % (this.scale * this.minorSteps[this.stepIndex]); + if (value % (this.scale * this.minorSteps[this.stepIndex]) > 0.5 * (this.scale * this.minorSteps[this.stepIndex])) { + return rounded + this.scale * this.minorSteps[this.stepIndex]; + } else { + return rounded; + } + }; + + /** + * Check if the there is a next step + * @return {boolean} true if the current date has not passed the end date + */ + DataStep.prototype.hasNext = function () { + return this.current >= this.marginStart; + }; + + /** + * Do the next step + */ + DataStep.prototype.next = function () { + var prev = this.current; + this.current -= this.step; + + // safety mechanism: if current time is still unchanged, move to the end + if (this.current === prev) { + this.current = this._end; + } + }; + + /** + * Do the next step + */ + DataStep.prototype.previous = function () { + this.current += this.step; + this.marginEnd += this.step; + this.marginRange = this.marginEnd - this.marginStart; + }; + + /** + * Get the current datetime + * @return {String} current The current date + */ + DataStep.prototype.getCurrent = function () { + // prevent round-off errors when close to zero + var current = Math.abs(this.current) < this.step / 2 ? 0 : this.current; + var returnValue = current.toPrecision(5); + if (typeof this.formattingFunction === 'function') { + returnValue = this.formattingFunction(current); + } + + if (typeof returnValue === 'number') { + return '' + returnValue; + } else if (typeof returnValue === 'string') { + return returnValue; + } else { + return current.toPrecision(5); + } + }; + + /** + * 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. + */ + DataStep.prototype.isMajor = function () { + return this.current % (this.scale * this.majorSteps[this.stepIndex]) === 0; + }; + + DataStep.prototype.shift = function (steps) { + if (steps < 0) { + for (var i = 0; i < -steps; i++) { + this.previous(); + } + } else if (steps > 0) { + for (var i = 0; i < steps; i++) { + this.next(); + } + } + }; + + module.exports = DataStep; + +/***/ }, +/* 53 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var util = __webpack_require__(7); + var DOMutil = __webpack_require__(13); + var Line = __webpack_require__(54); + var Bar = __webpack_require__(56); + var Points = __webpack_require__(55); + + /** + * /** + * @param {object} group | the object of the group from the dataset + * @param {string} groupId | ID of the group + * @param {object} options | the default options + * @param {array} groupsUsingDefaultStyles | this array has one entree. + * It is passed as an array so it is passed by reference. + * It enumerates through the default styles + * @constructor + */ + function GraphGroup(group, groupId, options, groupsUsingDefaultStyles) { + this.id = groupId; + var fields = ['sampling', 'style', 'sort', 'yAxisOrientation', 'barChart', 'drawPoints', 'shaded', 'interpolation']; + this.options = util.selectiveBridgeObject(fields, options); + this.usingDefaultStyle = group.className === undefined; + this.groupsUsingDefaultStyles = groupsUsingDefaultStyles; + this.zeroPosition = 0; + this.update(group); + if (this.usingDefaultStyle == true) { + this.groupsUsingDefaultStyles[0] += 1; + } + this.itemsData = []; + this.visible = group.visible === undefined ? true : group.visible; + } + + /** + * this loads a reference to all items in this group into this group. + * @param {array} items + */ + GraphGroup.prototype.setItems = function (items) { + if (items != null) { + this.itemsData = items; + if (this.options.sort == true) { + this.itemsData.sort(function (a, b) { + return a.x - b.x; + }); + } + } else { + this.itemsData = []; + } + }; + + /** + * this is used for plotting barcharts, this way, we only have to calculate it once. + * @param pos + */ + GraphGroup.prototype.setZeroPosition = function (pos) { + this.zeroPosition = pos; + }; + + /** + * set the options of the graph group over the default options. + * @param options + */ + GraphGroup.prototype.setOptions = function (options) { + if (options !== undefined) { + var fields = ['sampling', 'style', 'sort', 'yAxisOrientation', 'barChart']; + util.selectiveDeepExtend(fields, this.options, options); + + util.mergeOptions(this.options, options, 'interpolation'); + util.mergeOptions(this.options, options, 'drawPoints'); + util.mergeOptions(this.options, options, 'shaded'); + + if (options.interpolation) { + if (typeof options.interpolation == 'object') { + if (options.interpolation.parametrization) { + if (options.interpolation.parametrization == 'uniform') { + this.options.interpolation.alpha = 0; + } else if (options.interpolation.parametrization == 'chordal') { + this.options.interpolation.alpha = 1; + } else { + this.options.interpolation.parametrization = 'centripetal'; + this.options.interpolation.alpha = 0.5; + } + } + } + } + } + + if (this.options.style == 'line') { + this.type = new Line(this.id, this.options); + } else if (this.options.style == 'bar') { + this.type = new Bar(this.id, this.options); + } else if (this.options.style == 'points') { + this.type = new Points(this.id, this.options); + } + }; + + /** + * this updates the current group class with the latest group dataset entree, used in _updateGroup in linegraph + * @param group + */ + GraphGroup.prototype.update = function (group) { + this.group = group; + this.content = group.content || 'graph'; + this.className = group.className || this.className || 'vis-graph-group' + this.groupsUsingDefaultStyles[0] % 10; + this.visible = group.visible === undefined ? true : group.visible; + this.style = group.style; + this.setOptions(group.options); + }; + + /** + * draw the icon for the legend. + * + * @param x + * @param y + * @param JSONcontainer + * @param SVGcontainer + * @param iconWidth + * @param iconHeight + */ + GraphGroup.prototype.drawIcon = function (x, y, JSONcontainer, SVGcontainer, iconWidth, iconHeight) { + var fillHeight = iconHeight * 0.5; + var path, fillPath; + + var outline = DOMutil.getSVGElement('rect', JSONcontainer, SVGcontainer); + 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'); + + if (this.options.style == 'line') { + path = DOMutil.getSVGElement('path', JSONcontainer, SVGcontainer); + path.setAttributeNS(null, 'class', this.className); + if (this.style !== undefined) { + path.setAttributeNS(null, 'style', this.style); + } + + path.setAttributeNS(null, 'd', 'M' + x + ',' + y + ' L' + (x + iconWidth) + ',' + y + ''); + if (this.options.shaded.enabled == true) { + fillPath = DOMutil.getSVGElement('path', JSONcontainer, SVGcontainer); + if (this.options.shaded.orientation == 'top') { + fillPath.setAttributeNS(null, 'd', 'M' + x + ', ' + (y - fillHeight) + 'L' + x + ',' + y + ' L' + (x + iconWidth) + ',' + y + ' L' + (x + iconWidth) + ',' + (y - fillHeight)); + } else { + fillPath.setAttributeNS(null, 'd', 'M' + x + ',' + y + ' ' + 'L' + x + ',' + (y + fillHeight) + ' ' + 'L' + (x + iconWidth) + ',' + (y + fillHeight) + 'L' + (x + iconWidth) + ',' + y); + } + fillPath.setAttributeNS(null, 'class', this.className + ' vis-icon-fill'); + } + + if (this.options.drawPoints.enabled == true) { + DOMutil.drawPoint(x + 0.5 * iconWidth, y, this, JSONcontainer, SVGcontainer); + } + } else { + var barWidth = Math.round(0.3 * iconWidth); + var bar1Height = Math.round(0.4 * iconHeight); + var bar2Height = Math.round(0.75 * iconHeight); + + var offset = Math.round((iconWidth - 2 * barWidth) / 3); + + DOMutil.drawBar(x + 0.5 * barWidth + offset, y + fillHeight - bar1Height - 1, barWidth, bar1Height, this.className + ' vis-bar', JSONcontainer, SVGcontainer, this.style); + DOMutil.drawBar(x + 1.5 * barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, this.className + ' vis-bar', JSONcontainer, SVGcontainer, this.style); + } + }; + + /** + * return the legend entree for this group. + * + * @param iconWidth + * @param iconHeight + * @returns {{icon: HTMLElement, label: (group.content|*|string), orientation: (.options.yAxisOrientation|*)}} + */ + GraphGroup.prototype.getLegend = function (iconWidth, iconHeight) { + var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + this.drawIcon(0, 0.5 * iconHeight, [], svg, iconWidth, iconHeight); + return { icon: svg, label: this.content, orientation: this.options.yAxisOrientation }; + }; + + GraphGroup.prototype.getYRange = function (groupData) { + return this.type.getYRange(groupData); + }; + + GraphGroup.prototype.getData = function (groupData) { + return this.type.getData(groupData); + }; + + GraphGroup.prototype.draw = function (dataset, group, framework) { + this.type.draw(dataset, group, framework); + }; + + module.exports = GraphGroup; + +/***/ }, +/* 54 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var DOMutil = __webpack_require__(13); + var Points = __webpack_require__(55); + + function Line(groupId, options) { + this.groupId = groupId; + this.options = options; + } + + Line.prototype.getData = function (groupData) { + var combinedData = []; + for (var j = 0; j < groupData.length; j++) { + combinedData.push({ + x: groupData[j].x, + y: groupData[j].y, + groupId: this.groupId + }); + } + return combinedData; + }; + + Line.prototype.getYRange = function (groupData) { + var yMin = groupData[0].y; + var yMax = groupData[0].y; + for (var j = 0; j < groupData.length; j++) { + yMin = yMin > groupData[j].y ? groupData[j].y : yMin; + yMax = yMax < groupData[j].y ? groupData[j].y : yMax; + } + return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation }; + }; + + Line.getStackedYRange = function (combinedData, groupRanges, groupIds, groupLabel, orientation) { + if (combinedData.length > 0) { + // sort by time and by group + combinedData.sort(function (a, b) { + if (a.x === b.x) { + return a.groupId < b.groupId ? -1 : 1; + } else { + return a.x - b.x; + } + }); + var intersections = {}; + + Line._getDataIntersections(intersections, combinedData); + groupRanges[groupLabel] = Line._getStackedYRange(intersections, combinedData); + groupRanges[groupLabel].yAxisOrientation = orientation; + groupIds.push(groupLabel); + } + }; + + Line._getStackedYRange = function (intersections, combinedData) { + var key; + var yMin = combinedData[0].y; + var yMax = combinedData[0].y; + for (var i = 0; i < combinedData.length; i++) { + key = combinedData[i].x; + if (intersections[key] === undefined) { + yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin; + yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax; + } else { + if (combinedData[i].y < 0) { + intersections[key].accumulatedNegative += combinedData[i].y; + } else { + intersections[key].accumulatedPositive += combinedData[i].y; + } + } + } + for (var xpos in intersections) { + if (intersections.hasOwnProperty(xpos)) { + yMin = yMin > intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMin; + yMin = yMin > intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMin; + yMax = yMax < intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMax; + yMax = yMax < intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMax; + } + } + + return { min: yMin, max: yMax }; + }; + + /** + * Fill the intersections object with counters of how many datapoints share the same x coordinates + * @param intersections + * @param combinedData + * @private + */ + Line._getDataIntersections = function (intersections, combinedData) { + // get intersections + var coreDistance; + for (var i = 0; i < combinedData.length; i++) { + if (i + 1 < combinedData.length) { + coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x); + } + if (i > 0) { + coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x)); + } + if (coreDistance === 0) { + if (intersections[combinedData[i].x] === undefined) { + intersections[combinedData[i].x] = { amount: 0, resolved: 0, accumulatedPositive: 0, accumulatedNegative: 0 }; + } + intersections[combinedData[i].x].amount += 1; + } + } + }; + + /** + * draw a line graph + * + * @param dataset + * @param group + */ + Line.prototype.draw = function (dataset, group, framework) { + if (dataset != null) { + if (dataset.length > 0) { + var path, d; + var svgHeight = Number(framework.svg.style.height.replace('px', '')); + path = DOMutil.getSVGElement('path', framework.svgElements, framework.svg); + path.setAttributeNS(null, 'class', group.className); + if (group.style !== undefined) { + path.setAttributeNS(null, 'style', group.style); + } + + // construct path from dataset + if (group.options.interpolation.enabled == true) { + d = Line._catmullRom(dataset, group); + } else { + d = Line._linear(dataset); + } + + // append with points for fill and finalize the path + if (group.options.shaded.enabled == true) { + var fillPath = DOMutil.getSVGElement('path', framework.svgElements, framework.svg); + var dFill; + if (group.options.shaded.orientation == 'top') { + dFill = 'M' + dataset[0].x + ',' + 0 + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + 0; + } else { + dFill = 'M' + dataset[0].x + ',' + svgHeight + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + svgHeight; + } + fillPath.setAttributeNS(null, 'class', group.className + ' vis-fill'); + if (group.options.shaded.style !== undefined) { + fillPath.setAttributeNS(null, 'style', group.options.shaded.style); + } + fillPath.setAttributeNS(null, 'd', dFill); + } + // copy properties to path for drawing. + path.setAttributeNS(null, 'd', 'M' + d); + + // draw points + if (group.options.drawPoints.enabled == true) { + Points.draw(dataset, group, framework); + } + } + } + }; + + /** + * This uses an uniform parametrization of the interpolation algorithm: + * 'On the Parameterization of Catmull-Rom Curves' by Cem Yuksel et al. + * @param data + * @returns {string} + * @private + */ + Line._catmullRomUniform = function (data) { + // catmull rom + var p0, p1, p2, p3, bp1, bp2; + var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' '; + var normalization = 1 / 6; + var length = data.length; + for (var i = 0; i < length - 1; i++) { + + p0 = i == 0 ? data[0] : data[i - 1]; + p1 = data[i]; + p2 = data[i + 1]; + p3 = i + 2 < length ? data[i + 2] : p2; + + // Catmull-Rom to Cubic Bezier conversion matrix + // 0 1 0 0 + // -1/6 1 1/6 0 + // 0 1/6 1 -1/6 + // 0 0 1 0 + + // bp0 = { x: p1.x, y: p1.y }; + bp1 = { x: (-p0.x + 6 * p1.x + p2.x) * normalization, y: (-p0.y + 6 * p1.y + p2.y) * normalization }; + bp2 = { x: (p1.x + 6 * p2.x - p3.x) * normalization, y: (p1.y + 6 * p2.y - p3.y) * normalization }; + // bp0 = { x: p2.x, y: p2.y }; + + d += 'C' + bp1.x + ',' + bp1.y + ' ' + bp2.x + ',' + bp2.y + ' ' + p2.x + ',' + p2.y + ' '; + } + + return d; + }; + + /** + * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm. + * By default, the centripetal parameterization is used because this gives the nicest results. + * These parameterizations are relatively heavy because the distance between 4 points have to be calculated. + * + * One optimization can be used to reuse distances since this is a sliding window approach. + * @param data + * @param group + * @returns {string} + * @private + */ + Line._catmullRom = function (data, group) { + var alpha = group.options.interpolation.alpha; + if (alpha == 0 || alpha === undefined) { + return this._catmullRomUniform(data); + } else { + var p0, p1, p2, p3, bp1, bp2, d1, d2, d3, A, B, N, M; + var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA; + var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' '; + var length = data.length; + for (var i = 0; i < length - 1; i++) { + + p0 = i == 0 ? data[0] : data[i - 1]; + p1 = data[i]; + p2 = data[i + 1]; + p3 = i + 2 < length ? data[i + 2] : p2; + + d1 = Math.sqrt(Math.pow(p0.x - p1.x, 2) + Math.pow(p0.y - p1.y, 2)); + d2 = Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2)); + d3 = Math.sqrt(Math.pow(p2.x - p3.x, 2) + Math.pow(p2.y - p3.y, 2)); + + // Catmull-Rom to Cubic Bezier conversion matrix + + // A = 2d1^2a + 3d1^a * d2^a + d3^2a + // B = 2d3^2a + 3d3^a * d2^a + d2^2a + + // [ 0 1 0 0 ] + // [ -d2^2a /N A/N d1^2a /N 0 ] + // [ 0 d3^2a /M B/M -d2^2a /M ] + // [ 0 0 1 0 ] + + d3powA = Math.pow(d3, alpha); + d3pow2A = Math.pow(d3, 2 * alpha); + d2powA = Math.pow(d2, alpha); + d2pow2A = Math.pow(d2, 2 * alpha); + d1powA = Math.pow(d1, alpha); + d1pow2A = Math.pow(d1, 2 * alpha); + + A = 2 * d1pow2A + 3 * d1powA * d2powA + d2pow2A; + B = 2 * d3pow2A + 3 * d3powA * d2powA + d2pow2A; + N = 3 * d1powA * (d1powA + d2powA); + if (N > 0) { + N = 1 / N; + } + M = 3 * d3powA * (d3powA + d2powA); + if (M > 0) { + M = 1 / M; + } + + bp1 = { x: (-d2pow2A * p0.x + A * p1.x + d1pow2A * p2.x) * N, + y: (-d2pow2A * p0.y + A * p1.y + d1pow2A * p2.y) * N }; + + bp2 = { x: (d3pow2A * p1.x + B * p2.x - d2pow2A * p3.x) * M, + y: (d3pow2A * p1.y + B * p2.y - d2pow2A * p3.y) * M }; + + if (bp1.x == 0 && bp1.y == 0) { + bp1 = p1; + } + if (bp2.x == 0 && bp2.y == 0) { + bp2 = p2; + } + d += 'C' + bp1.x + ',' + bp1.y + ' ' + bp2.x + ',' + bp2.y + ' ' + p2.x + ',' + p2.y + ' '; + } + + return d; + } + }; + + /** + * this generates the SVG path for a linear drawing between datapoints. + * @param data + * @returns {string} + * @private + */ + Line._linear = function (data) { + // linear + var d = ''; + for (var i = 0; i < data.length; i++) { + if (i == 0) { + d += data[i].x + ',' + data[i].y; + } else { + d += ' ' + data[i].x + ',' + data[i].y; + } + } + return d; + }; + + module.exports = Line; + +/***/ }, +/* 55 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var DOMutil = __webpack_require__(13); + + function Points(groupId, options) { + this.groupId = groupId; + this.options = options; + } + + Points.prototype.getYRange = function (groupData) { + var yMin = groupData[0].y; + var yMax = groupData[0].y; + for (var j = 0; j < groupData.length; j++) { + yMin = yMin > groupData[j].y ? groupData[j].y : yMin; + yMax = yMax < groupData[j].y ? groupData[j].y : yMax; + } + return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation }; + }; + + Points.prototype.draw = function (dataset, group, framework, offset) { + Points.draw(dataset, group, framework, offset); + }; + + /** + * draw the data points + * + * @param {Array} dataset + * @param {Object} JSONcontainer + * @param {Object} svg | SVG DOM element + * @param {GraphGroup} group + * @param {Number} [offset] + */ + Points.draw = function (dataset, group, framework, offset) { + if (offset === undefined) { + offset = 0; + } + for (var i = 0; i < dataset.length; i++) { + DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, framework.svgElements, framework.svg, dataset[i].label); + } + }; + + module.exports = Points; + +/***/ }, +/* 56 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var DOMutil = __webpack_require__(13); + var Points = __webpack_require__(55); + + function Bargraph(groupId, options) { + this.groupId = groupId; + this.options = options; + } + + Bargraph.prototype.getYRange = function (groupData) { + var yMin = groupData[0].y; + var yMax = groupData[0].y; + for (var j = 0; j < groupData.length; j++) { + yMin = yMin > groupData[j].y ? groupData[j].y : yMin; + yMax = yMax < groupData[j].y ? groupData[j].y : yMax; + } + return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation }; + }; + + Bargraph.prototype.getData = function (groupData) { + var combinedData = []; + for (var j = 0; j < groupData.length; j++) { + combinedData.push({ + x: groupData[j].x, + y: groupData[j].y, + groupId: this.groupId + }); + } + return combinedData; + }; + + /** + * draw a bar graph + * + * @param groupIds + * @param processedGroupData + */ + Bargraph.draw = function (groupIds, processedGroupData, framework) { + var combinedData = []; + var intersections = {}; + var coreDistance; + var key, drawData; + var group; + var i, j; + var barPoints = 0; + + // combine all barchart data + for (i = 0; i < groupIds.length; i++) { + group = framework.groups[groupIds[i]]; + if (group.options.style === 'bar') { + if (group.visible === true && (framework.options.groups.visibility[groupIds[i]] === undefined || framework.options.groups.visibility[groupIds[i]] === true)) { + for (j = 0; j < processedGroupData[groupIds[i]].length; j++) { + combinedData.push({ + x: processedGroupData[groupIds[i]][j].x, + y: processedGroupData[groupIds[i]][j].y, + groupId: groupIds[i], + label: processedGroupData[groupIds[i]][j].label + }); + barPoints += 1; + } + } + } + } + + if (barPoints === 0) { + return; + } + + // sort by time and by group + combinedData.sort(function (a, b) { + if (a.x === b.x) { + return a.groupId < b.groupId ? -1 : 1; + } else { + return a.x - b.x; + } + }); + + // get intersections + Bargraph._getDataIntersections(intersections, combinedData); + + // plot barchart + for (i = 0; i < combinedData.length; i++) { + group = framework.groups[combinedData[i].groupId]; + var minWidth = 0.1 * group.options.barChart.width; + + key = combinedData[i].x; + var heightOffset = 0; + if (intersections[key] === undefined) { + if (i + 1 < combinedData.length) { + coreDistance = Math.abs(combinedData[i + 1].x - key); + } + if (i > 0) { + coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - key)); + } + drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth); + } else { + var nextKey = i + (intersections[key].amount - intersections[key].resolved); + var prevKey = i - (intersections[key].resolved + 1); + if (nextKey < combinedData.length) { + coreDistance = Math.abs(combinedData[nextKey].x - key); + } + if (prevKey > 0) { + coreDistance = Math.min(coreDistance, Math.abs(combinedData[prevKey].x - key)); + } + drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth); + intersections[key].resolved += 1; + + if (group.options.stack === true) { + if (combinedData[i].y < group.zeroPosition) { + heightOffset = intersections[key].accumulatedNegative; + intersections[key].accumulatedNegative += group.zeroPosition - combinedData[i].y; + } else { + heightOffset = intersections[key].accumulatedPositive; + intersections[key].accumulatedPositive += group.zeroPosition - combinedData[i].y; + } + } else if (group.options.barChart.sideBySide === true) { + drawData.width = drawData.width / intersections[key].amount; + drawData.offset += intersections[key].resolved * drawData.width - 0.5 * drawData.width * (intersections[key].amount + 1); + if (group.options.barChart.align === 'left') { + drawData.offset -= 0.5 * drawData.width; + } else if (group.options.barChart.align === 'right') { + drawData.offset += 0.5 * drawData.width; + } + } + } + DOMutil.drawBar(combinedData[i].x + drawData.offset, combinedData[i].y - heightOffset, drawData.width, group.zeroPosition - combinedData[i].y, group.className + ' vis-bar', framework.svgElements, framework.svg, group.style); + // draw points + if (group.options.drawPoints.enabled === true) { + Points.draw([combinedData[i]], group, framework, drawData.offset); + //DOMutil.drawPoint(combinedData[i].x + drawData.offset, combinedData[i].y, group, framework.svgElements, framework.svg); + } + } + }; + + /** + * Fill the intersections object with counters of how many datapoints share the same x coordinates + * @param intersections + * @param combinedData + * @private + */ + Bargraph._getDataIntersections = function (intersections, combinedData) { + // get intersections + var coreDistance; + for (var i = 0; i < combinedData.length; i++) { + if (i + 1 < combinedData.length) { + coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x); + } + if (i > 0) { + coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x)); + } + if (coreDistance === 0) { + if (intersections[combinedData[i].x] === undefined) { + intersections[combinedData[i].x] = { amount: 0, resolved: 0, accumulatedPositive: 0, accumulatedNegative: 0 }; + } + intersections[combinedData[i].x].amount += 1; + } + } + }; + + /** + * Get the width and offset for bargraphs based on the coredistance between datapoints + * + * @param coreDistance + * @param group + * @param minWidth + * @returns {{width: Number, offset: Number}} + * @private + */ + Bargraph._getSafeDrawData = function (coreDistance, group, minWidth) { + var width, offset; + if (coreDistance < group.options.barChart.width && coreDistance > 0) { + width = coreDistance < minWidth ? minWidth : coreDistance; + + offset = 0; // recalculate offset with the new width; + if (group.options.barChart.align === 'left') { + offset -= 0.5 * coreDistance; + } else if (group.options.barChart.align === 'right') { + offset += 0.5 * coreDistance; + } + } else { + // default settings + width = group.options.barChart.width; + offset = 0; + if (group.options.barChart.align === 'left') { + offset -= 0.5 * group.options.barChart.width; + } else if (group.options.barChart.align === 'right') { + offset += 0.5 * group.options.barChart.width; + } + } + + return { width: width, offset: offset }; + }; + + Bargraph.getStackedYRange = function (combinedData, groupRanges, groupIds, groupLabel, orientation) { + if (combinedData.length > 0) { + // sort by time and by group + combinedData.sort(function (a, b) { + if (a.x === b.x) { + return a.groupId < b.groupId ? -1 : 1; + } else { + return a.x - b.x; + } + }); + var intersections = {}; + + Bargraph._getDataIntersections(intersections, combinedData); + groupRanges[groupLabel] = Bargraph._getStackedYRange(intersections, combinedData); + groupRanges[groupLabel].yAxisOrientation = orientation; + groupIds.push(groupLabel); + } + }; + + Bargraph._getStackedYRange = function (intersections, combinedData) { + var key; + var yMin = combinedData[0].y; + var yMax = combinedData[0].y; + for (var i = 0; i < combinedData.length; i++) { + key = combinedData[i].x; + if (intersections[key] === undefined) { + yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin; + yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax; + } else { + if (combinedData[i].y < 0) { + intersections[key].accumulatedNegative += combinedData[i].y; + } else { + intersections[key].accumulatedPositive += combinedData[i].y; + } + } + } + for (var xpos in intersections) { + if (intersections.hasOwnProperty(xpos)) { + yMin = yMin > intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMin; + yMin = yMin > intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMin; + yMax = yMax < intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMax; + yMax = yMax < intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMax; + } + } + + return { min: yMin, max: yMax }; + }; + + module.exports = Bargraph; + +/***/ }, +/* 57 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var util = __webpack_require__(7); + var DOMutil = __webpack_require__(13); + var Component = __webpack_require__(27); + + /** + * Legend for Graph2d + */ + function Legend(body, options, side, linegraphOptions) { + this.body = body; + this.defaultOptions = { + enabled: true, + icons: true, + iconSize: 20, + iconSpacing: 6, + left: { + visible: true, + position: 'top-left' // top/bottom - left,center,right }, - title: { string: string, undef: undef }, + right: { + visible: true, + position: 'top-left' // top/bottom - left,center,right + } + }; + this.side = side; + this.options = util.extend({}, this.defaultOptions); + this.linegraphOptions = linegraphOptions; + + this.svgElements = {}; + this.dom = {}; + this.groups = {}; + this.amountOfGroups = 0; + this._create(); + + this.setOptions(options); + } + + Legend.prototype = new Component(); + + Legend.prototype.clear = function () { + this.groups = {}; + this.amountOfGroups = 0; + }; + + Legend.prototype.addGroup = function (label, graphOptions) { + + if (!this.groups.hasOwnProperty(label)) { + this.groups[label] = graphOptions; + } + this.amountOfGroups += 1; + }; + + Legend.prototype.updateGroup = function (label, graphOptions) { + this.groups[label] = graphOptions; + }; + + Legend.prototype.removeGroup = function (label) { + if (this.groups.hasOwnProperty(label)) { + delete this.groups[label]; + this.amountOfGroups -= 1; + } + }; + + Legend.prototype._create = function () { + this.dom.frame = document.createElement('div'); + this.dom.frame.className = 'vis-legend'; + this.dom.frame.style.position = 'absolute'; + this.dom.frame.style.top = '10px'; + this.dom.frame.style.display = 'block'; + + this.dom.textArea = document.createElement('div'); + this.dom.textArea.className = 'vis-legend-text'; + this.dom.textArea.style.position = 'relative'; + this.dom.textArea.style.top = '0px'; + + this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + this.svg.style.position = 'absolute'; + this.svg.style.top = 0 + 'px'; + this.svg.style.width = this.options.iconSize + 5 + 'px'; + this.svg.style.height = '100%'; + + this.dom.frame.appendChild(this.svg); + this.dom.frame.appendChild(this.dom.textArea); + }; + + /** + * Hide the component from the DOM + */ + Legend.prototype.hide = function () { + // remove the frame containing the items + if (this.dom.frame.parentNode) { + this.dom.frame.parentNode.removeChild(this.dom.frame); + } + }; + + /** + * Show the component in the DOM (when not already visible). + * @return {Boolean} changed + */ + Legend.prototype.show = function () { + // show frame containing the items + if (!this.dom.frame.parentNode) { + this.body.dom.center.appendChild(this.dom.frame); + } + }; + + Legend.prototype.setOptions = function (options) { + var fields = ['enabled', 'orientation', 'icons', 'left', 'right']; + util.selectiveDeepExtend(fields, this.options, options); + }; + + Legend.prototype.redraw = function () { + var activeGroups = 0; + var groupArray = Object.keys(this.groups); + groupArray.sort(function (a, b) { + return a < b ? -1 : 1; + }); + + for (var i = 0; i < groupArray.length; i++) { + var groupId = groupArray[i]; + if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { + activeGroups++; + } + } + + if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false || activeGroups == 0) { + this.hide(); + } else { + this.show(); + if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'bottom-left') { + this.dom.frame.style.left = '4px'; + this.dom.frame.style.textAlign = 'left'; + this.dom.textArea.style.textAlign = 'left'; + this.dom.textArea.style.left = this.options.iconSize + 15 + 'px'; + this.dom.textArea.style.right = ''; + this.svg.style.left = 0 + 'px'; + this.svg.style.right = ''; + } else { + this.dom.frame.style.right = '4px'; + this.dom.frame.style.textAlign = 'right'; + this.dom.textArea.style.textAlign = 'right'; + this.dom.textArea.style.right = this.options.iconSize + 15 + 'px'; + this.dom.textArea.style.left = ''; + this.svg.style.right = 0 + 'px'; + this.svg.style.left = ''; + } + + if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'top-right') { + this.dom.frame.style.top = 4 - Number(this.body.dom.center.style.top.replace('px', '')) + 'px'; + this.dom.frame.style.bottom = ''; + } else { + var scrollableHeight = this.body.domProps.center.height - this.body.domProps.centerContainer.height; + this.dom.frame.style.bottom = 4 + scrollableHeight + Number(this.body.dom.center.style.top.replace('px', '')) + 'px'; + this.dom.frame.style.top = ''; + } + + if (this.options.icons == false) { + this.dom.frame.style.width = this.dom.textArea.offsetWidth + 10 + 'px'; + this.dom.textArea.style.right = ''; + this.dom.textArea.style.left = ''; + this.svg.style.width = '0px'; + } else { + this.dom.frame.style.width = this.options.iconSize + 15 + this.dom.textArea.offsetWidth + 10 + 'px'; + this.drawLegendIcons(); + } + + var content = ''; + for (var i = 0; i < groupArray.length; i++) { + var groupId = groupArray[i]; + if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { + content += this.groups[groupId].content + '
'; + } + } + this.dom.textArea.innerHTML = content; + this.dom.textArea.style.lineHeight = 0.75 * this.options.iconSize + this.options.iconSpacing + 'px'; + } + }; + + Legend.prototype.drawLegendIcons = function () { + if (this.dom.frame.parentNode) { + var groupArray = Object.keys(this.groups); + groupArray.sort(function (a, b) { + return a < b ? -1 : 1; + }); + + DOMutil.prepareElements(this.svgElements); + var padding = window.getComputedStyle(this.dom.frame).paddingTop; + var iconOffset = Number(padding.replace('px', '')); + var x = iconOffset; + var iconWidth = this.options.iconSize; + var iconHeight = 0.75 * this.options.iconSize; + var y = iconOffset + 0.5 * iconHeight + 3; + + this.svg.style.width = iconWidth + 5 + iconOffset + 'px'; + + for (var i = 0; i < groupArray.length; i++) { + var groupId = groupArray[i]; + if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { + this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight); + y += iconHeight + this.options.iconSpacing; + } + } + + DOMutil.cleanupElements(this.svgElements); + } + }; + + module.exports = Legend; + +/***/ }, +/* 58 */ +/***/ function(module, exports, __webpack_require__) { + + /** + * This object contains all possible options. It will check if the types are correct, if required if the option is one + * of the allowed values. + * + * __any__ means that the name of the property does not matter. + * __type__ is a required field for all objects and contains the allowed types of all objects + */ + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + var string = 'string'; + var boolean = 'boolean'; + var number = 'number'; + var array = 'array'; + var date = 'date'; + var object = 'object'; // should only be in a __type__ property + var dom = 'dom'; + var moment = 'moment'; + var fn = 'function'; + var nada = 'null'; + var undef = 'undefined'; + var any = 'any'; + + var allOptions = { + configure: { + enabled: { boolean: boolean }, + filter: { boolean: boolean, fn: fn }, + container: { dom: dom }, + __type__: { object: object, boolean: boolean, fn: fn } + }, + + //globals : + yAxisOrientation: { string: ['left', 'right'] }, + defaultGroup: { string: string }, + sort: { boolean: boolean }, + sampling: { boolean: boolean }, + stack: { boolean: boolean }, + graphHeight: { string: string, number: number }, + shaded: { + enabled: { boolean: boolean }, + orientation: { string: ['bottom', 'top'] }, // top, bottom + __type__: { boolean: boolean, object: object } + }, + style: { string: ['line', 'bar', 'points'] }, // line, bar + barChart: { width: { number: number }, - value: { number: number, undef: undef }, + sideBySide: { boolean: boolean }, + align: { string: ['left', 'center', 'right'] }, __type__: { object: object } }, - groups: { - useDefaultGroups: { boolean: boolean }, - __any__: 'get from nodes, will be overwritten below', + interpolation: { + enabled: { boolean: boolean }, + parametrization: { string: ['centripetal', 'chordal', 'uniform'] }, // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) + alpha: { number: number }, + __type__: { object: object, boolean: boolean } + }, + drawPoints: { + enabled: { boolean: boolean }, + size: { number: number }, + style: { string: ['square', 'circle'] }, // square, circle + __type__: { object: object, boolean: boolean } + }, + dataAxis: { + showMinorLabels: { boolean: boolean }, + showMajorLabels: { boolean: boolean }, + icons: { boolean: boolean }, + width: { string: string, number: number }, + visible: { boolean: boolean }, + alignZeros: { boolean: boolean }, + left: { + range: { min: { number: number }, max: { number: number }, __type__: { object: object } }, + format: { fn: fn }, + title: { text: { string: string, number: number }, style: { string: string }, __type__: { object: object } }, + __type__: { object: object } + }, + right: { + range: { min: { number: number }, max: { number: number }, __type__: { object: object } }, + format: { fn: fn }, + title: { text: { string: string, number: number }, style: { string: string }, __type__: { object: object } }, + __type__: { object: object } + }, __type__: { object: object } }, - interaction: { - dragNodes: { boolean: boolean }, - dragView: { boolean: boolean }, - hideEdgesOnDrag: { boolean: boolean }, - hideNodesOnDrag: { boolean: boolean }, - hover: { boolean: boolean }, - keyboard: { - enabled: { boolean: boolean }, - speed: { x: { number: number }, y: { number: number }, zoom: { number: number }, __type__: { object: object } }, - bindToWindow: { boolean: boolean }, - __type__: { object: object, boolean: boolean } + legend: { + enabled: { boolean: boolean }, + icons: { boolean: boolean }, + left: { + visible: { boolean: boolean }, + position: { string: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] }, + __type__: { object: object } + }, + right: { + visible: { boolean: boolean }, + position: { string: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] }, + __type__: { object: object } }, - multiselect: { boolean: boolean }, - navigationButtons: { boolean: boolean }, - selectable: { boolean: boolean }, - selectConnectedEdges: { boolean: boolean }, - hoverConnectedEdges: { boolean: boolean }, - tooltipDelay: { number: number }, - zoomView: { boolean: boolean }, + __type__: { object: object, boolean: boolean } + }, + groups: { + visibility: { any: any }, __type__: { object: object } }, - layout: { - randomSeed: { undef: undef, number: number }, - hierarchical: { - enabled: { boolean: boolean }, - levelSeparation: { number: number }, - direction: { string: ['UD', 'DU', 'LR', 'RL'] }, // UD, DU, LR, RL - sortMethod: { string: ['hubsize', 'directed'] }, // hubsize, directed - __type__: { object: object, boolean: boolean } + + autoResize: { boolean: boolean }, + clickToUse: { boolean: boolean }, + end: { number: number, date: date, string: string, moment: moment }, + format: { + minorLabels: { + millisecond: { string: string, undef: undef }, + second: { string: string, undef: undef }, + minute: { string: string, undef: undef }, + hour: { string: string, undef: undef }, + weekday: { string: string, undef: undef }, + day: { string: string, undef: undef }, + month: { string: string, undef: undef }, + year: { string: string, undef: undef }, + __type__: { object: object } + }, + majorLabels: { + millisecond: { string: string, undef: undef }, + second: { string: string, undef: undef }, + minute: { string: string, undef: undef }, + hour: { string: string, undef: undef }, + weekday: { string: string, undef: undef }, + day: { string: string, undef: undef }, + month: { string: string, undef: undef }, + year: { string: string, undef: undef }, + __type__: { object: object } }, __type__: { object: object } }, - manipulation: { - enabled: { boolean: boolean }, - initiallyActive: { boolean: boolean }, - addNode: { boolean: boolean, fn: fn }, - addEdge: { boolean: boolean, fn: fn }, - editNode: { fn: fn }, - editEdge: { boolean: boolean, fn: fn }, - deleteNode: { boolean: boolean, fn: fn }, - deleteEdge: { boolean: boolean, fn: fn }, - controlNodeStyle: 'get from nodes, will be overwritten below', - __type__: { object: object, boolean: boolean } + height: { string: string, number: number }, + hiddenDates: { object: object, array: array }, + locale: { string: string }, + locales: { + __any__: { object: object }, + __type__: { object: object } }, - nodes: { - borderWidth: { number: number }, - borderWidthSelected: { number: number, undef: undef }, - brokenImage: { string: string, undef: undef }, - color: { - border: { string: string }, - background: { string: string }, - highlight: { - border: { string: string }, - background: { string: string }, - __type__: { object: object, string: string } - }, - hover: { - border: { string: string }, - background: { string: string }, - __type__: { object: object, string: string } - }, - __type__: { object: object, string: string } + max: { date: date, number: number, string: string, moment: moment }, + maxHeight: { number: number, string: string }, + min: { date: date, number: number, string: string, moment: moment }, + minHeight: { number: number, string: string }, + moveable: { boolean: boolean }, + multiselect: { boolean: boolean }, + orientation: { string: string }, + showCurrentTime: { boolean: boolean }, + showMajorLabels: { boolean: boolean }, + showMinorLabels: { boolean: boolean }, + start: { date: date, number: number, string: string, moment: moment }, + timeAxis: { + scale: { string: string, undef: undef }, + step: { number: number, undef: undef }, + __type__: { object: object } + }, + width: { string: string, number: number }, + zoomable: { boolean: boolean }, + zoomMax: { number: number }, + zoomMin: { number: number }, + __type__: { object: object } + }; + + var configureOptions = { + global: { + //yAxisOrientation: ['left','right'], // TDOO: enable as soon as Grahp2d doesn't crash when changing this on the fly + sort: true, + sampling: true, + stack: false, + shaded: { + enabled: false, + orientation: ['top', 'bottom'] // top, bottom }, - fixed: { - x: { boolean: boolean }, - y: { boolean: boolean }, - __type__: { object: object, boolean: boolean } + style: ['line', 'bar', 'points'], // line, bar + barChart: { + width: [50, 5, 100, 5], + sideBySide: false, + align: ['left', 'center', 'right'] // left, center, right }, - font: { - color: { string: string }, - size: { number: number }, // px - face: { string: string }, - background: { string: string }, - strokeWidth: { number: number }, // px - strokeColor: { string: string }, - __type__: { object: object, string: string } + interpolation: { + enabled: true, + parametrization: ['centripetal', 'chordal', 'uniform'] // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) }, - group: { string: string, number: number, undef: undef }, - hidden: { boolean: boolean }, - icon: { - face: { string: string }, - code: { string: string }, //'\uf007', - size: { number: number }, //50, - color: { string: string }, - __type__: { object: object } + drawPoints: { + enabled: true, + size: [6, 2, 30, 1], + style: ['square', 'circle'] // square, circle }, - id: { string: string, number: number }, - image: { string: string, undef: undef }, // --> URL - label: { string: string, undef: undef }, - level: { number: number, undef: undef }, - mass: { number: number }, - physics: { boolean: boolean }, - scaling: { - min: { number: number }, - max: { number: number }, - label: { - enabled: { boolean: boolean }, - min: { number: number }, - max: { number: number }, - maxVisible: { number: number }, - drawThreshold: { number: number }, - __type__: { object: object, boolean: boolean } + dataAxis: { + showMinorLabels: true, + showMajorLabels: true, + icons: false, + width: [40, 0, 200, 1], + visible: true, + alignZeros: true, + left: { + //range: {min:undefined,max:undefined}, + //format: function (value) {return value;}, + title: { text: '', style: '' } }, - customScalingFunction: { fn: fn }, - __type__: { object: object } + right: { + //range: {min:undefined,max:undefined}, + //format: function (value) {return value;}, + title: { text: '', style: '' } + } }, - shadow: { - enabled: { boolean: boolean }, - size: { number: number }, - x: { number: number }, - y: { number: number }, - __type__: { object: object, boolean: boolean } + legend: { + enabled: false, + icons: true, + left: { + visible: true, + position: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] // top/bottom - left,right + }, + right: { + visible: true, + position: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] // top/bottom - left,right + } }, - shape: { string: ['ellipse', 'circle', 'database', 'box', 'text', 'image', 'circularImage', 'diamond', 'dot', 'star', 'triangle', 'triangleDown', 'square', 'icon'] }, - size: { number: number }, - title: { string: string, undef: undef }, - value: { number: number, undef: undef }, - x: { number: number }, - y: { number: number }, - __type__: { object: object } - }, - physics: { - barnesHut: { - gravitationalConstant: { number: number }, - centralGravity: { number: number }, - springLength: { number: number }, - springConstant: { number: number }, - damping: { number: number }, - avoidOverlap: { number: number }, - __type__: { object: object } + + autoResize: true, + clickToUse: false, + end: '', + format: { + minorLabels: { + millisecond: 'SSS', + second: 's', + minute: 'HH:mm', + hour: 'HH:mm', + weekday: 'ddd D', + day: 'D', + 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', + month: 'YYYY', + year: '' + } }, - forceAtlas2Based: { - gravitationalConstant: { number: number }, - centralGravity: { number: number }, - springLength: { number: number }, - springConstant: { number: number }, - damping: { number: number }, - avoidOverlap: { number: number }, - __type__: { object: object } + + height: '', + locale: '', + max: '', + maxHeight: '', + min: '', + minHeight: '', + moveable: true, + orientation: ['both', 'bottom', 'top'], + showCurrentTime: false, + showMajorLabels: true, + showMinorLabels: true, + start: '', + width: '100%', + zoomable: true, + zoomMax: [315360000000000, 10, 315360000000000, 1], + zoomMin: [10, 10, 315360000000000, 1] + } + }; + + exports.allOptions = allOptions; + exports.configureOptions = configureOptions; + +/***/ }, +/* 59 */ +/***/ function(module, exports, __webpack_require__) { + + // Load custom shapes into CanvasRenderingContext2D + 'use strict'; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + var _modulesGroups = __webpack_require__(60); + + var _modulesGroups2 = _interopRequireDefault(_modulesGroups); + + var _modulesNodesHandler = __webpack_require__(61); + + var _modulesNodesHandler2 = _interopRequireDefault(_modulesNodesHandler); + + var _modulesEdgesHandler = __webpack_require__(81); + + var _modulesEdgesHandler2 = _interopRequireDefault(_modulesEdgesHandler); + + var _modulesPhysicsEngine = __webpack_require__(88); + + var _modulesPhysicsEngine2 = _interopRequireDefault(_modulesPhysicsEngine); + + var _modulesClustering = __webpack_require__(97); + + var _modulesClustering2 = _interopRequireDefault(_modulesClustering); + + var _modulesCanvasRenderer = __webpack_require__(99); + + var _modulesCanvasRenderer2 = _interopRequireDefault(_modulesCanvasRenderer); + + var _modulesCanvas = __webpack_require__(100); + + var _modulesCanvas2 = _interopRequireDefault(_modulesCanvas); + + var _modulesView = __webpack_require__(101); + + var _modulesView2 = _interopRequireDefault(_modulesView); + + var _modulesInteractionHandler = __webpack_require__(102); + + var _modulesInteractionHandler2 = _interopRequireDefault(_modulesInteractionHandler); + + var _modulesSelectionHandler = __webpack_require__(105); + + var _modulesSelectionHandler2 = _interopRequireDefault(_modulesSelectionHandler); + + var _modulesLayoutEngine = __webpack_require__(106); + + var _modulesLayoutEngine2 = _interopRequireDefault(_modulesLayoutEngine); + + var _modulesManipulationSystem = __webpack_require__(107); + + var _modulesManipulationSystem2 = _interopRequireDefault(_modulesManipulationSystem); + + var _sharedConfigurator = __webpack_require__(45); + + var _sharedConfigurator2 = _interopRequireDefault(_sharedConfigurator); + + var _sharedValidator = __webpack_require__(47); + + var _sharedValidator2 = _interopRequireDefault(_sharedValidator); + + var _optionsJs = __webpack_require__(108); + + __webpack_require__(109); + + var Emitter = __webpack_require__(19); + var Hammer = __webpack_require__(3); + var util = __webpack_require__(7); + var DataSet = __webpack_require__(14); + var DataView = __webpack_require__(16); + var dotparser = __webpack_require__(110); + var gephiParser = __webpack_require__(111); + var Images = __webpack_require__(112); + var Activator = __webpack_require__(42); + var locales = __webpack_require__(113); + + /** + * @constructor Network + * Create a network visualization, displaying nodes and edges. + * + * @param {Element} container The DOM element in which the Network will + * be created. Normally a div element. + * @param {Object} data An object containing parameters + * {Array} nodes + * {Array} edges + * @param {Object} options Options + */ + function Network(container, data, options) { + var _this = this; + + if (!(this instanceof Network)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + // set constant values + this.options = {}; + this.defaultOptions = { + locale: 'en', + locales: locales, + clickToUse: false + }; + util.extend(this.options, this.defaultOptions); + + // containers for nodes and edges + this.body = { + nodes: {}, + nodeIndices: [], + edges: {}, + edgeIndices: [], + data: { + nodes: null, // A DataSet or DataView + edges: null // A DataSet or DataView }, - repulsion: { - centralGravity: { number: number }, - springLength: { number: number }, - springConstant: { number: number }, - nodeDistance: { number: number }, - damping: { number: number }, - __type__: { object: object } + functions: { + createNode: function createNode() {}, + createEdge: function createEdge() {}, + getPointer: function getPointer() {} }, - hierarchicalRepulsion: { - centralGravity: { number: number }, - springLength: { number: number }, - springConstant: { number: number }, - nodeDistance: { number: number }, - damping: { number: number }, - __type__: { object: object } + emitter: { + on: this.on.bind(this), + off: this.off.bind(this), + emit: this.emit.bind(this), + once: this.once.bind(this) }, - maxVelocity: { number: number }, - minVelocity: { number: number }, // px/s - solver: { string: ['barnesHut', 'repulsion', 'hierarchicalRepulsion', 'forceAtlas2Based'] }, - stabilization: { - enabled: { boolean: boolean }, - iterations: { number: number }, // maximum number of iteration to stabilize - updateInterval: { number: number }, - onlyDynamicEdges: { boolean: boolean }, - fit: { boolean: boolean }, - __type__: { object: object, boolean: boolean } + eventListeners: { + onTap: function onTap() {}, + onTouch: function onTouch() {}, + onDoubleTap: function onDoubleTap() {}, + onHold: function onHold() {}, + onDragStart: function onDragStart() {}, + onDrag: function onDrag() {}, + onDragEnd: function onDragEnd() {}, + onMouseWheel: function onMouseWheel() {}, + onPinch: function onPinch() {}, + onMouseMove: function onMouseMove() {}, + onRelease: function onRelease() {}, + onContext: function onContext() {} }, - timestep: { number: number }, - __type__: { object: object, boolean: boolean } - }, + container: container, + view: { + scale: 1, + translation: { x: 0, y: 0 } + } + }; + + // bind the event listeners + this.bindEventListeners(); + + // setting up all modules + this.images = new Images(function () { + return _this.body.emitter.emit('_requestRedraw'); + }); // object with images + this.groups = new _modulesGroups2['default'](); // object with groups + this.canvas = new _modulesCanvas2['default'](this.body); // DOM handler + this.selectionHandler = new _modulesSelectionHandler2['default'](this.body, this.canvas); // Selection handler + this.interactionHandler = new _modulesInteractionHandler2['default'](this.body, this.canvas, this.selectionHandler); // Interaction handler handles all the hammer bindings (that are bound by canvas), key + this.view = new _modulesView2['default'](this.body, this.canvas); // camera handler, does animations and zooms + this.renderer = new _modulesCanvasRenderer2['default'](this.body, this.canvas); // renderer, starts renderloop, has events that modules can hook into + this.physics = new _modulesPhysicsEngine2['default'](this.body); // physics engine, does all the simulations + this.layoutEngine = new _modulesLayoutEngine2['default'](this.body); // layout engine for inital layout and hierarchical layout + this.clustering = new _modulesClustering2['default'](this.body); // clustering api + this.manipulation = new _modulesManipulationSystem2['default'](this.body, this.canvas, this.selectionHandler); // data manipulation system + + this.nodesHandler = new _modulesNodesHandler2['default'](this.body, this.images, this.groups, this.layoutEngine); // Handle adding, deleting and updating of nodes as well as global options + this.edgesHandler = new _modulesEdgesHandler2['default'](this.body, this.images, this.groups); // Handle adding, deleting and updating of edges as well as global options + + // create the DOM elements + this.canvas._create(); + + // setup configuration system + this.configurator = new _sharedConfigurator2['default'](this, this.body.container, _optionsJs.configureOptions, this.canvas.pixelRatio); + + // apply options + this.setOptions(options); + + // load data (the disable start variable will be the same as the enabled clustering) + this.setData(data); + } + + // Extend Network with an Emitter mixin + Emitter(Network.prototype); + + /** + * Set options + * @param {Object} options + */ + Network.prototype.setOptions = function (options) { + var _this2 = this; + + if (options !== undefined) { + + var errorFound = _sharedValidator2['default'].validate(options, _optionsJs.allOptions); + if (errorFound === true) { + console.log('%cErrors have been found in the supplied options object.', _sharedValidator.printStyle); + } + + // copy the global fields over + var fields = ['locale', 'locales', 'clickToUse']; + util.selectiveDeepExtend(fields, this.options, options); + + // the hierarchical system can adapt the edges and the physics to it's own options because not all combinations work with the hierarichical system. + options = this.layoutEngine.setOptions(options.layout, options); + + this.canvas.setOptions(options); // options for canvas are in globals + + // pass the options to the modules + this.groups.setOptions(options.groups); + this.nodesHandler.setOptions(options.nodes); + this.edgesHandler.setOptions(options.edges); + this.physics.setOptions(options.physics); + this.manipulation.setOptions(options.manipulation, options, this.options); // manipulation uses the locales in the globals + + this.interactionHandler.setOptions(options.interaction); + this.renderer.setOptions(options.interaction); // options for rendering are in interaction + this.selectionHandler.setOptions(options.interaction); // options for selection are in interaction + + // reload the settings of the nodes to apply changes in groups that are not referenced by pointer. + if (options.groups !== undefined) { + this.body.emitter.emit('refreshNodes'); + } + // these two do not have options at the moment, here for completeness + //this.view.setOptions(options.view); + //this.clustering.setOptions(options.clustering); + + this.configurator.setOptions(options.configure); + + // if the configuration system is enabled, copy all options and put them into the config system + if (this.configurator.options.enabled === true) { + var networkOptions = { nodes: {}, edges: {}, layout: {}, interaction: {}, manipulation: {}, physics: {}, global: {} }; + util.deepExtend(networkOptions.nodes, this.nodesHandler.options); + util.deepExtend(networkOptions.edges, this.edgesHandler.options); + util.deepExtend(networkOptions.layout, this.layoutEngine.options); + // load the selectionHandler and rendere default options in to the interaction group + util.deepExtend(networkOptions.interaction, this.selectionHandler.options); + util.deepExtend(networkOptions.interaction, this.renderer.options); + + util.deepExtend(networkOptions.interaction, this.interactionHandler.options); + util.deepExtend(networkOptions.manipulation, this.manipulation.options); + util.deepExtend(networkOptions.physics, this.physics.options); + + // load globals into the global object + util.deepExtend(networkOptions.global, this.canvas.options); + util.deepExtend(networkOptions.global, this.options); - //globals : - autoResize: { boolean: boolean }, - clickToUse: { boolean: boolean }, - locale: { string: string }, - locales: { - __any__: { object: object }, - __type__: { object: object } - }, - height: { string: string }, - width: { string: string }, - __type__: { object: object } + this.configurator.setModuleOptions(networkOptions); + } + + // handle network global options + if (options.clickToUse !== undefined) { + if (options.clickToUse === true) { + if (this.activator === undefined) { + this.activator = new Activator(this.canvas.frame); + this.activator.on('change', function () { + _this2.body.emitter.emit('activate'); + }); + } + } else { + if (this.activator !== undefined) { + this.activator.destroy(); + delete this.activator; + } + this.body.emitter.emit('activate'); + } + } else { + this.body.emitter.emit('activate'); + } + + this.canvas.setSize(); + + // start the physics simulation. Can be safely called multiple times. + this.body.emitter.emit('startSimulation'); + } }; - allOptions.groups.__any__ = allOptions.nodes; - allOptions.manipulation.controlNodeStyle = allOptions.nodes; + /** + * Update the this.body.nodeIndices with the most recent node index list + * @private + */ + Network.prototype._updateVisibleIndices = function () { + var nodes = this.body.nodes; + var edges = this.body.edges; + this.body.nodeIndices = []; + this.body.edgeIndices = []; - var configureOptions = { - nodes: { - borderWidth: [1, 0, 10, 1], - borderWidthSelected: [2, 0, 10, 1], - color: { - border: ['color', '#2B7CE9'], - background: ['color', '#97C2FC'], - highlight: { - border: ['color', '#2B7CE9'], - background: ['color', '#D2E5FF'] - }, - hover: { - border: ['color', '#2B7CE9'], - background: ['color', '#D2E5FF'] + for (var nodeId in nodes) { + if (nodes.hasOwnProperty(nodeId)) { + if (nodes[nodeId].options.hidden === false) { + this.body.nodeIndices.push(nodeId); } - }, - fixed: { - x: false, - y: false - }, - font: { - color: ['color', '#343434'], - size: [14, 0, 100, 1], // px - face: ['arial', 'verdana', 'tahoma'], - background: ['color', 'none'], - strokeWidth: [0, 0, 50, 1], // px - strokeColor: ['color', '#ffffff'] - }, - //group: 'string', - hidden: false, - //icon: { - // face: 'string', //'FontAwesome', - // code: 'string', //'\uf007', - // size: [50, 0, 200, 1], //50, - // color: ['color','#2B7CE9'] //'#aa00ff' - //}, - //image: 'string', // --> URL - physics: true, - scaling: { - min: [10, 0, 200, 1], - max: [30, 0, 200, 1], - label: { - enabled: false, - min: [14, 0, 200, 1], - max: [30, 0, 200, 1], - maxVisible: [30, 0, 200, 1], - drawThreshold: [5, 0, 20, 1] + } + } + + for (var edgeId in edges) { + if (edges.hasOwnProperty(edgeId)) { + if (edges[edgeId].options.hidden === false) { + this.body.edgeIndices.push(edgeId); } - }, - shadow: { - enabled: false, - size: [10, 0, 20, 1], - x: [5, -30, 30, 1], - y: [5, -30, 30, 1] - }, - shape: ['ellipse', 'box', 'circle', 'database', 'diamond', 'dot', 'square', 'star', 'text', 'triangle', 'triangleDown'], - size: [25, 0, 200, 1] - }, - edges: { - arrows: { - to: { enabled: false, scaleFactor: [1, 0, 3, 0.05] }, // boolean / {arrowScaleFactor:1} / {enabled: false, arrowScaleFactor:1} - middle: { enabled: false, scaleFactor: [1, 0, 3, 0.05] }, - from: { enabled: false, scaleFactor: [1, 0, 3, 0.05] } - }, - color: { - color: ['color', '#848484'], - highlight: ['color', '#848484'], - hover: ['color', '#848484'], - inherit: ['from', 'to', 'both', true, false], - opacity: [1, 0, 1, 0.05] - }, - dashes: false, - font: { - color: ['color', '#343434'], - size: [14, 0, 100, 1], // px - face: ['arial', 'verdana', 'tahoma'], - background: ['color', 'none'], - strokeWidth: [2, 0, 50, 1], // px - strokeColor: ['color', '#ffffff'], - align: ['horizontal', 'top', 'middle', 'bottom'] - }, - hidden: false, - hoverWidth: [1.5, 0, 5, 0.1], - physics: true, - scaling: { - min: [1, 0, 100, 1], - max: [15, 0, 100, 1], - label: { - enabled: true, - min: [14, 0, 200, 1], - max: [30, 0, 200, 1], - maxVisible: [30, 0, 200, 1], - drawThreshold: [5, 0, 20, 1] + } + } + }; + + /** + * Bind all events + */ + Network.prototype.bindEventListeners = function () { + var _this3 = this; + + // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed. + this.body.emitter.on('_dataChanged', function () { + // update shortcut lists + _this3._updateVisibleIndices(); + _this3.physics.updatePhysicsData(); + + // call the dataUpdated event because the only difference between the two is the updating of the indices + _this3.body.emitter.emit('_dataUpdated'); + }); + + // this is called when options of EXISTING nodes or edges have changed. + this.body.emitter.on('_dataUpdated', function () { + // update values + _this3._updateValueRange(_this3.body.nodes); + _this3._updateValueRange(_this3.body.edges); + // start simulation (can be called safely, even if already running) + _this3.body.emitter.emit('startSimulation'); + }); + }; + + /** + * Set nodes and edges, and optionally options as well. + * + * @param {Object} data Object containing parameters: + * {Array | DataSet | DataView} [nodes] Array with nodes + * {Array | DataSet | DataView} [edges] Array with edges + * {String} [dot] String containing data in DOT format + * {String} [gephi] String containing data in gephi JSON format + * {Options} [options] Object with options + */ + Network.prototype.setData = function (data) { + // reset the physics engine. + this.body.emitter.emit('resetPhysics'); + this.body.emitter.emit('_resetData'); + + // unselect all to ensure no selections from old data are carried over. + this.selectionHandler.unselectAll(); + + if (data && data.dot && (data.nodes || data.edges)) { + throw new SyntaxError('Data must contain either parameter "dot" or ' + ' parameter pair "nodes" and "edges", but not both.'); + } + + // set options + this.setOptions(data && data.options); + // set all data + if (data && data.dot) { + console.log('The dot property has been depricated. Please use the static convertDot method to convert DOT into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertDot(dotString);'); + // parse DOT file + var dotData = dotparser.DOTToGraph(data.dot); + this.setData(dotData); + return; + } else if (data && data.gephi) { + // parse DOT file + console.log('The gephi property has been depricated. Please use the static convertGephi method to convert gephi into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertGephi(gephiJson);'); + var gephiData = gephiParser.parseGephi(data.gephi); + this.setData(gephiData); + return; + } else { + this.nodesHandler.setData(data && data.nodes, true); + this.edgesHandler.setData(data && data.edges, true); + } + + // emit change in data + this.body.emitter.emit('_dataChanged'); + + // find a stable position or start animating to a stable position + this.body.emitter.emit('initPhysics'); + }; + + /** + * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function. + * var network = new vis.Network(..); + * network.destroy(); + * network = null; + */ + Network.prototype.destroy = function () { + this.body.emitter.emit('destroy'); + // clear events + this.body.emitter.off(); + this.off(); + + // delete modules + delete this.groups; + delete this.canvas; + delete this.selectionHandler; + delete this.interactionHandler; + delete this.view; + delete this.renderer; + delete this.physics; + delete this.layoutEngine; + delete this.clustering; + delete this.manipulation; + delete this.nodesHandler; + delete this.edgesHandler; + delete this.configurator; + delete this.images; + + // delete emitter bindings + delete this.body.emitter.emit; + delete this.body.emitter.on; + delete this.body.emitter.off; + delete this.body.emitter.once; + delete this.body.emitter; + + for (var nodeId in this.body.nodes) { + delete this.body.nodes[nodeId]; + } + for (var edgeId in this.body.edges) { + delete this.body.edges[edgeId]; + } + + // remove the container and everything inside it recursively + util.recursiveDOMDelete(this.body.container); + }; + + /** + * Update the values of all object in the given array according to the current + * value range of the objects in the array. + * @param {Object} obj An object containing a set of Edges or Nodes + * The objects must have a method getValue() and + * setValueRange(min, max). + * @private + */ + Network.prototype._updateValueRange = function (obj) { + var id; + + // determine the range of the objects + var valueMin = undefined; + var valueMax = undefined; + var valueTotal = 0; + for (id in obj) { + if (obj.hasOwnProperty(id)) { + var value = obj[id].getValue(); + if (value !== undefined) { + valueMin = valueMin === undefined ? value : Math.min(value, valueMin); + valueMax = valueMax === undefined ? value : Math.max(value, valueMax); + valueTotal += value; } - }, - selectionWidth: [1.5, 0, 5, 0.1], - selfReferenceSize: [20, 0, 200, 1], - shadow: { - enabled: false, - size: [10, 0, 20, 1], - x: [5, -30, 30, 1], - y: [5, -30, 30, 1] - }, - smooth: { - enabled: true, - type: ['dynamic', 'continuous', 'discrete', 'diagonalCross', 'straightCross', 'horizontal', 'vertical', 'curvedCW', 'curvedCCW'], - roundness: [0.5, 0, 1, 0.05] - }, - width: [1, 0, 30, 1] - }, - layout: { - //randomSeed: [0, 0, 500, 1], - hierarchical: { - enabled: false, - levelSeparation: [150, 20, 500, 5], - direction: ['UD', 'DU', 'LR', 'RL'], // UD, DU, LR, RL - sortMethod: ['hubsize', 'directed'] // hubsize, directed } - }, - interaction: { - dragNodes: true, - dragView: true, - hideEdgesOnDrag: false, - hideNodesOnDrag: false, - hover: false, - keyboard: { - enabled: false, - speed: { x: [10, 0, 40, 1], y: [10, 0, 40, 1], zoom: [0.02, 0, 0.1, 0.005] }, - bindToWindow: true - }, - multiselect: false, - navigationButtons: false, - selectable: true, - selectConnectedEdges: true, - hoverConnectedEdges: true, - tooltipDelay: [300, 0, 1000, 25], - zoomView: true - }, - manipulation: { - enabled: false, - initiallyActive: false - }, - physics: { - barnesHut: { - //theta: [0.5, 0.1, 1, 0.05], - gravitationalConstant: [-2000, -30000, 0, 50], - centralGravity: [0.3, 0, 10, 0.05], - springLength: [95, 0, 500, 5], - springConstant: [0.04, 0, 1.2, 0.005], - damping: [0.09, 0, 1, 0.01], - avoidOverlap: [0, 0, 1, 0.01] - }, - forceAtlas2Based: { - //theta: [0.5, 0.1, 1, 0.05], - gravitationalConstant: [-50, -500, 0, 1], - centralGravity: [0.01, 0, 1, 0.005], - springLength: [95, 0, 500, 5], - springConstant: [0.08, 0, 1.2, 0.005], - damping: [0.4, 0, 1, 0.01], - avoidOverlap: [0, 0, 1, 0.01] - }, - repulsion: { - centralGravity: [0.2, 0, 10, 0.05], - springLength: [200, 0, 500, 5], - springConstant: [0.05, 0, 1.2, 0.005], - nodeDistance: [100, 0, 500, 5], - damping: [0.09, 0, 1, 0.01] - }, - hierarchicalRepulsion: { - centralGravity: [0.2, 0, 10, 0.05], - springLength: [100, 0, 500, 5], - springConstant: [0.01, 0, 1.2, 0.005], - nodeDistance: [120, 0, 500, 5], - damping: [0.09, 0, 1, 0.01] - }, - maxVelocity: [50, 0, 150, 1], - minVelocity: [0.1, 0.01, 0.5, 0.01], - solver: ['barnesHut', 'forceAtlas2Based', 'repulsion', 'hierarchicalRepulsion'], - timestep: [0.5, 0.01, 1, 0.01] - }, - global: { - locale: ['en', 'nl'] } + + // adjust the range of all objects + if (valueMin !== undefined && valueMax !== undefined) { + for (id in obj) { + if (obj.hasOwnProperty(id)) { + obj[id].setValueRange(valueMin, valueMax, valueTotal); + } + } + } + }; + + /** + * Returns true when the Network is active. + * @returns {boolean} + */ + Network.prototype.isActive = function () { + return !this.activator || this.activator.active; + }; + + Network.prototype.setSize = function () { + return this.canvas.setSize.apply(this.canvas, arguments); + }; + Network.prototype.canvasToDOM = function () { + return this.canvas.canvasToDOM.apply(this.canvas, arguments); + }; + Network.prototype.DOMtoCanvas = function () { + return this.canvas.setSize.DOMtoCanvas(this.canvas, arguments); + }; + Network.prototype.findNode = function () { + return this.clustering.findNode.apply(this.clustering, arguments); + }; + Network.prototype.isCluster = function () { + return this.clustering.isCluster.apply(this.clustering, arguments); + }; + Network.prototype.openCluster = function () { + return this.clustering.openCluster.apply(this.clustering, arguments); + }; + Network.prototype.cluster = function () { + return this.clustering.cluster.apply(this.clustering, arguments); + }; + Network.prototype.getNodesInCluster = function () { + return this.clustering.getNodesInCluster.apply(this.clustering, arguments); + }; + Network.prototype.clusterByConnection = function () { + return this.clustering.clusterByConnection.apply(this.clustering, arguments); + }; + Network.prototype.clusterByHubsize = function () { + return this.clustering.clusterByHubsize.apply(this.clustering, arguments); + }; + Network.prototype.clusterOutliers = function () { + return this.clustering.clusterOutliers.apply(this.clustering, arguments); + }; + Network.prototype.getSeed = function () { + return this.layoutEngine.getSeed.apply(this.layoutEngine, arguments); + }; + Network.prototype.enableEditMode = function () { + return this.manipulation.enableEditMode.apply(this.manipulation, arguments); + }; + Network.prototype.disableEditMode = function () { + return this.manipulation.disableEditMode.apply(this.manipulation, arguments); + }; + Network.prototype.addNodeMode = function () { + return this.manipulation.addNodeMode.apply(this.manipulation, arguments); + }; + Network.prototype.editNode = function () { + return this.manipulation.editNode.apply(this.manipulation, arguments); + }; + Network.prototype.editNodeMode = function () { + console.log('Depricated: Please use editNode instead of editNodeMode.');return this.manipulation.editNode.apply(this.manipulation, arguments); + }; + Network.prototype.addEdgeMode = function () { + return this.manipulation.addEdgeMode.apply(this.manipulation, arguments); + }; + Network.prototype.editEdgeMode = function () { + return this.manipulation.editEdgeMode.apply(this.manipulation, arguments); + }; + Network.prototype.deleteSelected = function () { + return this.manipulation.deleteSelected.apply(this.manipulation, arguments); + }; + Network.prototype.getPositions = function () { + return this.nodesHandler.getPositions.apply(this.nodesHandler, arguments); + }; + Network.prototype.storePositions = function () { + return this.nodesHandler.storePositions.apply(this.nodesHandler, arguments); + }; + Network.prototype.getBoundingBox = function () { + return this.nodesHandler.getBoundingBox.apply(this.nodesHandler, arguments); + }; + Network.prototype.getConnectedNodes = function (objectId) { + if (this.body.nodes[objectId] !== undefined) { + return this.nodesHandler.getConnectedNodes.apply(this.nodesHandler, arguments); + } else { + return this.edgesHandler.getConnectedNodes.apply(this.edgesHandler, arguments); + } + }; + Network.prototype.getConnectedEdges = function () { + return this.nodesHandler.getConnectedEdges.apply(this.nodesHandler, arguments); + }; + Network.prototype.startSimulation = function () { + return this.physics.startSimulation.apply(this.physics, arguments); + }; + Network.prototype.stopSimulation = function () { + return this.physics.stopSimulation.apply(this.physics, arguments); + }; + Network.prototype.stabilize = function () { + return this.physics.stabilize.apply(this.physics, arguments); + }; + Network.prototype.getSelection = function () { + return this.selectionHandler.getSelection.apply(this.selectionHandler, arguments); + }; + Network.prototype.getSelectedNodes = function () { + return this.selectionHandler.getSelectedNodes.apply(this.selectionHandler, arguments); + }; + Network.prototype.getSelectedEdges = function () { + return this.selectionHandler.getSelectedEdges.apply(this.selectionHandler, arguments); + }; + Network.prototype.getNodeAt = function () { + var node = this.selectionHandler.getNodeAt.apply(this.selectionHandler, arguments); + if (node !== undefined && node.id !== undefined) { + return node.id; + } + return node; + }; + Network.prototype.getEdgeAt = function () { + var edge = this.selectionHandler.getEdgeAt.apply(this.selectionHandler, arguments); + if (edge !== undefined && edge.id !== undefined) { + return edge.id; + } + return edge; + }; + Network.prototype.selectNodes = function () { + return this.selectionHandler.selectNodes.apply(this.selectionHandler, arguments); + }; + Network.prototype.selectEdges = function () { + return this.selectionHandler.selectEdges.apply(this.selectionHandler, arguments); + }; + Network.prototype.unselectAll = function () { + return this.selectionHandler.unselectAll.apply(this.selectionHandler, arguments); + }; + Network.prototype.redraw = function () { + return this.renderer.redraw.apply(this.renderer, arguments); + }; + Network.prototype.getScale = function () { + return this.view.getScale.apply(this.view, arguments); + }; + Network.prototype.getViewPosition = function () { + return this.view.getViewPosition.apply(this.view, arguments); + }; + Network.prototype.fit = function () { + return this.view.fit.apply(this.view, arguments); + }; + Network.prototype.moveTo = function () { + return this.view.moveTo.apply(this.view, arguments); + }; + Network.prototype.focus = function () { + return this.view.focus.apply(this.view, arguments); + }; + Network.prototype.releaseNode = function () { + return this.view.releaseNode.apply(this.view, arguments); }; - exports.allOptions = allOptions; - exports.configureOptions = configureOptions; + module.exports = Network; /***/ }, -/* 67 */ +/* 60 */ /***/ function(module, exports, __webpack_require__) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var util = __webpack_require__(7); + /** - * Canvas shapes used by Network + * @class Groups + * This class can store groups and options specific for groups. */ + + var Groups = (function () { + function Groups() { + _classCallCheck(this, Groups); + + this.clear(); + this.defaultIndex = 0; + this.groupsArray = []; + this.groupIndex = 0; + + this.defaultGroups = [{ border: "#2B7CE9", background: "#97C2FC", highlight: { border: "#2B7CE9", background: "#D2E5FF" }, hover: { border: "#2B7CE9", background: "#D2E5FF" } }, // 0: blue + { border: "#FFA500", background: "#FFFF00", highlight: { border: "#FFA500", background: "#FFFFA3" }, hover: { border: "#FFA500", background: "#FFFFA3" } }, // 1: yellow + { border: "#FA0A10", background: "#FB7E81", highlight: { border: "#FA0A10", background: "#FFAFB1" }, hover: { border: "#FA0A10", background: "#FFAFB1" } }, // 2: red + { border: "#41A906", background: "#7BE141", highlight: { border: "#41A906", background: "#A1EC76" }, hover: { border: "#41A906", background: "#A1EC76" } }, // 3: green + { border: "#E129F0", background: "#EB7DF4", highlight: { border: "#E129F0", background: "#F0B3F5" }, hover: { border: "#E129F0", background: "#F0B3F5" } }, // 4: magenta + { border: "#7C29F0", background: "#AD85E4", highlight: { border: "#7C29F0", background: "#D3BDF0" }, hover: { border: "#7C29F0", background: "#D3BDF0" } }, // 5: purple + { border: "#C37F00", background: "#FFA807", highlight: { border: "#C37F00", background: "#FFCA66" }, hover: { border: "#C37F00", background: "#FFCA66" } }, // 6: orange + { border: "#4220FB", background: "#6E6EFD", highlight: { border: "#4220FB", background: "#9B9BFD" }, hover: { border: "#4220FB", background: "#9B9BFD" } }, // 7: darkblue + { border: "#FD5A77", background: "#FFC0CB", highlight: { border: "#FD5A77", background: "#FFD1D9" }, hover: { border: "#FD5A77", background: "#FFD1D9" } }, // 8: pink + { border: "#4AD63A", background: "#C2FABC", highlight: { border: "#4AD63A", background: "#E6FFE3" }, hover: { border: "#4AD63A", background: "#E6FFE3" } }, // 9: mint + + { border: "#990000", background: "#EE0000", highlight: { border: "#BB0000", background: "#FF3333" }, hover: { border: "#BB0000", background: "#FF3333" } }, // 10:bright red + + { border: "#FF6000", background: "#FF6000", highlight: { border: "#FF6000", background: "#FF6000" }, hover: { border: "#FF6000", background: "#FF6000" } }, // 12: real orange + { border: "#97C2FC", background: "#2B7CE9", highlight: { border: "#D2E5FF", background: "#2B7CE9" }, hover: { border: "#D2E5FF", background: "#2B7CE9" } }, // 13: blue + { border: "#399605", background: "#255C03", highlight: { border: "#399605", background: "#255C03" }, hover: { border: "#399605", background: "#255C03" } }, // 14: green + { border: "#B70054", background: "#FF007E", highlight: { border: "#B70054", background: "#FF007E" }, hover: { border: "#B70054", background: "#FF007E" } }, // 15: magenta + { border: "#AD85E4", background: "#7C29F0", highlight: { border: "#D3BDF0", background: "#7C29F0" }, hover: { border: "#D3BDF0", background: "#7C29F0" } }, // 16: purple + { border: "#4557FA", background: "#000EA1", highlight: { border: "#6E6EFD", background: "#000EA1" }, hover: { border: "#6E6EFD", background: "#000EA1" } }, // 17: darkblue + { border: "#FFC0CB", background: "#FD5A77", highlight: { border: "#FFD1D9", background: "#FD5A77" }, hover: { border: "#FFD1D9", background: "#FD5A77" } }, // 18: pink + { border: "#C2FABC", background: "#74D66A", highlight: { border: "#E6FFE3", background: "#74D66A" }, hover: { border: "#E6FFE3", background: "#74D66A" } }, // 19: mint + + { border: "#EE0000", background: "#990000", highlight: { border: "#FF3333", background: "#BB0000" }, hover: { border: "#FF3333", background: "#BB0000" } } // 20:bright red + ]; + + this.options = {}; + this.defaultOptions = { + useDefaultGroups: true + }; + util.extend(this.options, this.defaultOptions); + } + + _createClass(Groups, [{ + key: "setOptions", + value: function setOptions(options) { + var optionFields = ["useDefaultGroups"]; + + if (options !== undefined) { + for (var groupName in options) { + if (options.hasOwnProperty(groupName)) { + if (optionFields.indexOf(groupName) === -1) { + var group = options[groupName]; + this.add(groupName, group); + } + } + } + } + } + }, { + key: "clear", + + /** + * Clear all groups + */ + value: function clear() { + this.groups = {}; + this.groupsArray = []; + } + }, { + key: "get", + + /** + * get group options of a groupname. If groupname is not found, a new group + * is added. + * @param {*} groupname Can be a number, string, Date, etc. + * @return {Object} group The created group, containing all group options + */ + value: function get(groupname) { + var group = this.groups[groupname]; + if (group === undefined) { + if (this.options.useDefaultGroups === false && this.groupsArray.length > 0) { + // create new group + var index = this.groupIndex % this.groupsArray.length; + this.groupIndex++; + group = {}; + group.color = this.groups[this.groupsArray[index]]; + this.groups[groupname] = group; + } else { + // create new group + var index = this.defaultIndex % this.defaultGroups.length; + this.defaultIndex++; + group = {}; + group.color = this.defaultGroups[index]; + this.groups[groupname] = group; + } + } + + return group; + } + }, { + key: "add", + + /** + * Add a custom group style + * @param {String} groupName + * @param {Object} style An object containing borderColor, + * backgroundColor, etc. + * @return {Object} group The created group object + */ + value: function add(groupName, style) { + this.groups[groupName] = style; + this.groupsArray.push(groupName); + return style; + } + }]); + + return Groups; + })(); + + exports["default"] = Groups; + module.exports = exports["default"]; + +/***/ }, +/* 61 */ +/***/ function(module, exports, __webpack_require__) { + 'use strict'; - if (typeof CanvasRenderingContext2D !== 'undefined') { + Object.defineProperty(exports, '__esModule', { + value: true + }); - /** - * Draw a circle shape - */ - CanvasRenderingContext2D.prototype.circle = function (x, y, r) { - this.beginPath(); - this.arc(x, y, r, 0, 2 * Math.PI, false); - this.closePath(); - }; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /** - * Draw a square shape - * @param {Number} x horizontal center - * @param {Number} y vertical center - * @param {Number} r size, width and height of the square - */ - CanvasRenderingContext2D.prototype.square = function (x, y, r) { - this.beginPath(); - this.rect(x - r, y - r, r * 2, r * 2); - this.closePath(); - }; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - /** - * Draw a triangle shape - * @param {Number} x horizontal center - * @param {Number} y vertical center - * @param {Number} r radius, half the length of the sides of the triangle - */ - CanvasRenderingContext2D.prototype.triangle = function (x, y, r) { - // http://en.wikipedia.org/wiki/Equilateral_triangle - this.beginPath(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - // the change in radius and the offset is here to center the shape - r *= 1.15; - y += 0.275 * r; + var _componentsNode = __webpack_require__(62); - var s = r * 2; - var s2 = s / 2; - var ir = Math.sqrt(3) / 6 * s; // radius of inner circle - var h = Math.sqrt(s * s - s2 * s2); // height + var _componentsNode2 = _interopRequireDefault(_componentsNode); - this.moveTo(x, y - (h - ir)); - this.lineTo(x + s2, y + ir); - this.lineTo(x - s2, y + ir); - this.lineTo(x, y - (h - ir)); - this.closePath(); - }; + var _componentsSharedLabel = __webpack_require__(63); - /** - * Draw a triangle shape in downward orientation - * @param {Number} x horizontal center - * @param {Number} y vertical center - * @param {Number} r radius - */ - CanvasRenderingContext2D.prototype.triangleDown = function (x, y, r) { - // http://en.wikipedia.org/wiki/Equilateral_triangle - this.beginPath(); + var _componentsSharedLabel2 = _interopRequireDefault(_componentsSharedLabel); - // the change in radius and the offset is here to center the shape - r *= 1.15; - y -= 0.275 * r; + var util = __webpack_require__(7); + var DataSet = __webpack_require__(14); + var DataView = __webpack_require__(16); - var s = r * 2; - var s2 = s / 2; - var ir = Math.sqrt(3) / 6 * s; // radius of inner circle - var h = Math.sqrt(s * s - s2 * s2); // height + var NodesHandler = (function () { + function NodesHandler(body, images, groups, layoutEngine) { + var _this = this; - this.moveTo(x, y + (h - ir)); - this.lineTo(x + s2, y - ir); - this.lineTo(x - s2, y - ir); - this.lineTo(x, y + (h - ir)); - this.closePath(); - }; + _classCallCheck(this, NodesHandler); - /** - * Draw a star shape, a star with 5 points - * @param {Number} x horizontal center - * @param {Number} y vertical center - * @param {Number} r radius, half the length of the sides of the triangle - */ - CanvasRenderingContext2D.prototype.star = function (x, y, r) { - // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/ - this.beginPath(); + this.body = body; + this.images = images; + this.groups = groups; + this.layoutEngine = layoutEngine; - // the change in radius and the offset is here to center the shape - r *= 0.82; - y += 0.1 * r; + // create the node API in the body container + this.body.functions.createNode = this.create.bind(this); - for (var n = 0; n < 10; n++) { - var radius = n % 2 === 0 ? r * 1.3 : r * 0.5; - this.lineTo(x + radius * Math.sin(n * 2 * Math.PI / 10), y - radius * Math.cos(n * 2 * Math.PI / 10)); + this.nodesListeners = { + add: function add(event, params) { + _this.add(params.items); + }, + update: function update(event, params) { + _this.update(params.items, params.data); + }, + remove: function remove(event, params) { + _this.remove(params.items); + } + }; + + this.options = {}; + this.defaultOptions = { + borderWidth: 1, + borderWidthSelected: 2, + brokenImage: undefined, + color: { + border: '#2B7CE9', + background: '#97C2FC', + highlight: { + border: '#2B7CE9', + background: '#D2E5FF' + }, + hover: { + border: '#2B7CE9', + background: '#D2E5FF' + } + }, + fixed: { + x: false, + y: false + }, + font: { + color: '#343434', + size: 14, // px + face: 'arial', + background: 'none', + strokeWidth: 0, // px + strokeColor: '#ffffff', + align: 'horizontal' + }, + group: undefined, + hidden: false, + icon: { + face: 'FontAwesome', //'FontAwesome', + code: undefined, //'\uf007', + size: 50, //50, + color: '#2B7CE9' //'#aa00ff' + }, + image: undefined, // --> URL + label: undefined, + level: undefined, + mass: 1, + physics: true, + scaling: { + min: 10, + max: 30, + label: { + enabled: false, + min: 14, + max: 30, + maxVisible: 30, + drawThreshold: 5 + }, + customScalingFunction: function customScalingFunction(min, max, total, value) { + if (max === min) { + return 0.5; + } else { + var scale = 1 / (max - min); + return Math.max(0, (value - min) * scale); + } + } + }, + shadow: { + enabled: false, + size: 10, + x: 5, + y: 5 + }, + shape: 'ellipse', + size: 25, + title: undefined, + value: undefined, + x: undefined, + y: undefined + }; + util.extend(this.options, this.defaultOptions); + + this.bindEventListeners(); + } + + _createClass(NodesHandler, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this2 = this; + + // refresh the nodes. Used when reverting from hierarchical layout + this.body.emitter.on('refreshNodes', this.refresh.bind(this)); + this.body.emitter.on('refresh', this.refresh.bind(this)); + this.body.emitter.on('destroy', function () { + delete _this2.body.functions.createNode; + delete _this2.nodesListeners.add; + delete _this2.nodesListeners.update; + delete _this2.nodesListeners.remove; + delete _this2.nodesListeners; + }); } + }, { + key: 'setOptions', + value: function setOptions(options) { + if (options !== undefined) { + _componentsNode2['default'].parseOptions(this.options, options); - this.closePath(); - }; + // update the shape in all nodes + if (options.shape !== undefined) { + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + this.body.nodes[nodeId].updateShape(); + } + } + } - /** - * Draw a Diamond shape - * @param {Number} x horizontal center - * @param {Number} y vertical center - * @param {Number} r radius, half the length of the sides of the triangle - */ - CanvasRenderingContext2D.prototype.diamond = function (x, y, r) { - // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/ - this.beginPath(); + // update the shape size in all nodes + if (options.font !== undefined) { + _componentsSharedLabel2['default'].parseOptions(this.options.font, options); + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + this.body.nodes[nodeId].updateLabelModule(); + this.body.nodes[nodeId]._reset(); + } + } + } - this.lineTo(x, y + r); - this.lineTo(x + r, y); - this.lineTo(x, y - r); - this.lineTo(x - r, y); + // update the shape size in all nodes + if (options.size !== undefined) { + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + this.body.nodes[nodeId]._reset(); + } + } + } - this.closePath(); - }; + // update the state of the letiables if needed + if (options.hidden !== undefined || options.physics !== undefined) { + this.body.emitter.emit('_dataChanged'); + } + } + } + }, { + key: 'setData', - /** - * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas - */ - CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) { - var r2d = Math.PI / 180; - if (w - 2 * r < 0) { - r = w / 2; - } //ensure that the radius isn't too large for x - if (h - 2 * r < 0) { - r = h / 2; - } //ensure that the radius isn't too large for y - this.beginPath(); - this.moveTo(x + r, y); - this.lineTo(x + w - r, y); - this.arc(x + w - r, y + r, r, r2d * 270, r2d * 360, false); - this.lineTo(x + w, y + h - r); - this.arc(x + w - r, y + h - r, r, 0, r2d * 90, false); - this.lineTo(x + r, y + h); - this.arc(x + r, y + h - r, r, r2d * 90, r2d * 180, false); - this.lineTo(x, y + r); - this.arc(x + r, y + r, r, r2d * 180, r2d * 270, false); - this.closePath(); - }; + /** + * Set a data set with nodes for the network + * @param {Array | DataSet | DataView} nodes The data containing the nodes. + * @private + */ + value: function setData(nodes) { + var _this3 = this; - /** - * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas - */ - CanvasRenderingContext2D.prototype.ellipse = function (x, y, w, h) { - var kappa = 0.5522848, - ox = w / 2 * kappa, - // control point offset horizontal - oy = h / 2 * kappa, - // control point offset vertical - xe = x + w, - // x-end - ye = y + h, - // y-end - xm = x + w / 2, - // x-middle - ym = y + h / 2; // y-middle + var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - this.beginPath(); - this.moveTo(x, ym); - this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); - this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); - this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); - this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); - this.closePath(); - }; + var oldNodesData = this.body.data.nodes; + + if (nodes instanceof DataSet || nodes instanceof DataView) { + this.body.data.nodes = nodes; + } else if (Array.isArray(nodes)) { + this.body.data.nodes = new DataSet(); + this.body.data.nodes.add(nodes); + } else if (!nodes) { + this.body.data.nodes = new DataSet(); + } else { + throw new TypeError('Array or DataSet expected'); + } + + if (oldNodesData) { + // unsubscribe from old dataset + util.forEach(this.nodesListeners, function (callback, event) { + oldNodesData.off(event, callback); + }); + } - /** - * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas - */ - CanvasRenderingContext2D.prototype.database = function (x, y, w, h) { - var f = 1 / 3; - var wEllipse = w; - var hEllipse = h * f; + // remove drawn nodes + this.body.nodes = {}; - var kappa = 0.5522848, - ox = wEllipse / 2 * kappa, - // control point offset horizontal - oy = hEllipse / 2 * kappa, - // control point offset vertical - xe = x + wEllipse, - // x-end - ye = y + hEllipse, - // y-end - xm = x + wEllipse / 2, - // x-middle - ym = y + hEllipse / 2, - // y-middle - ymb = y + (h - hEllipse / 2), - // y-midlle, bottom ellipse - yeb = y + h; // y-end, bottom ellipse + if (this.body.data.nodes) { + (function () { + // subscribe to new dataset + var me = _this3; + util.forEach(_this3.nodesListeners, function (callback, event) { + me.body.data.nodes.on(event, callback); + }); - this.beginPath(); - this.moveTo(xe, ym); + // draw all new nodes + var ids = _this3.body.data.nodes.getIds(); + _this3.add(ids, true); + })(); + } - this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); - this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + if (doNotEmit === false) { + this.body.emitter.emit('_dataChanged'); + } + } + }, { + key: 'add', - this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); - this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + /** + * Add nodes + * @param {Number[] | String[]} ids + * @private + */ + value: function add(ids) { + var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - this.lineTo(xe, ymb); + var id = undefined; + var newNodes = []; + for (var i = 0; i < ids.length; i++) { + id = ids[i]; + var _properties = this.body.data.nodes.get(id); + var node = this.create(_properties); + newNodes.push(node); + this.body.nodes[id] = node; // note: this may replace an existing node + } - this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb); - this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb); + this.layoutEngine.positionInitially(newNodes); - this.lineTo(x, ym); - }; + if (doNotEmit === false) { + this.body.emitter.emit('_dataChanged'); + } + } + }, { + key: 'update', - /** - * Draw an arrow point (no line) - */ - CanvasRenderingContext2D.prototype.arrow = function (x, y, angle, length) { - // tail - var xt = x - length * Math.cos(angle); - var yt = y - length * Math.sin(angle); + /** + * Update existing nodes, or create them when not yet existing + * @param {Number[] | String[]} ids + * @private + */ + value: function update(ids, changedData) { + var nodes = this.body.nodes; + var dataChanged = false; + for (var i = 0; i < ids.length; i++) { + var id = ids[i]; + var node = nodes[id]; + var data = changedData[i]; + if (node !== undefined) { + // update node + dataChanged = node.setOptions(data); + } else { + dataChanged = true; + // create node + node = this.create(properties); + nodes[id] = node; + } + } - // inner tail - var xi = x - length * 0.9 * Math.cos(angle); - var yi = y - length * 0.9 * Math.sin(angle); + if (dataChanged === true) { + this.body.emitter.emit('_dataChanged'); + } else { + this.body.emitter.emit('_dataUpdated'); + } + } + }, { + key: 'remove', - // left - var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI); - var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI); + /** + * Remove existing nodes. If nodes do not exist, the method will just ignore it. + * @param {Number[] | String[]} ids + * @private + */ + value: function remove(ids) { + var nodes = this.body.nodes; - // right - var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI); - var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI); + for (var i = 0; i < ids.length; i++) { + var id = ids[i]; + delete nodes[id]; + } - this.beginPath(); - this.moveTo(x, y); - this.lineTo(xl, yl); - this.lineTo(xi, yi); - this.lineTo(xr, yr); - this.closePath(); - }; + this.body.emitter.emit('_dataChanged'); + } + }, { + key: 'create', - /** - * Sets up the dashedLine functionality for drawing - * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas - * @author David Jordan - * @date 2012-08-08 - */ - CanvasRenderingContext2D.prototype.dashedLine = function (x, y, x2, y2, pattern) { - this.beginPath(); - this.moveTo(x, y); + /** + * create a node + * @param properties + * @param constructorClass + */ + value: function create(properties) { + var constructorClass = arguments[1] === undefined ? _componentsNode2['default'] : arguments[1]; - var patternLength = pattern.length; - var dx = x2 - x; - var dy = y2 - y; - var slope = dy / dx; - var distRemaining = Math.sqrt(dx * dx + dy * dy); - var patternIndex = 0; - var draw = true; - var xStep = 0; - var dashLength = pattern[0]; + return new constructorClass(properties, this.body, this.images, this.groups, this.options); + } + }, { + key: 'refresh', + value: function refresh() { + var nodes = this.body.nodes; + for (var nodeId in nodes) { + var node = undefined; + if (nodes.hasOwnProperty(nodeId)) { + node = nodes[nodeId]; + } + var data = this.body.data.nodes._data[nodeId]; + if (node !== undefined && data !== undefined) { + node.setOptions({ fixed: false }); + node.setOptions(data); + } + } + } + }, { + key: 'getPositions', - while (distRemaining >= 0.1) { - dashLength = pattern[patternIndex++ % patternLength]; - if (dashLength > distRemaining) { - dashLength = distRemaining; + /** + * Returns the positions of the nodes. + * @param ids --> optional, can be array of nodeIds, can be string + * @returns {{}} + */ + value: function getPositions(ids) { + var dataArray = {}; + if (ids !== undefined) { + if (Array.isArray(ids) === true) { + for (var i = 0; i < ids.length; i++) { + if (this.body.nodes[ids[i]] !== undefined) { + var node = this.body.nodes[ids[i]]; + dataArray[ids[i]] = { x: Math.round(node.x), y: Math.round(node.y) }; + } + } + } else { + if (this.body.nodes[ids] !== undefined) { + var node = this.body.nodes[ids]; + dataArray[ids] = { x: Math.round(node.x), y: Math.round(node.y) }; + } + } + } else { + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + var node = this.body.nodes[nodeId]; + dataArray[nodeId] = { x: Math.round(node.x), y: Math.round(node.y) }; + } + } } + return dataArray; + } + }, { + key: 'storePositions', - xStep = Math.sqrt(dashLength * dashLength / (1 + slope * slope)); - xStep = dx < 0 ? -xStep : xStep; - x += xStep; - y += slope * xStep; + /** + * Load the XY positions of the nodes into the dataset. + */ + value: function storePositions() { + // todo: add support for clusters and hierarchical. + var dataArray = []; + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + var node = this.body.nodes[nodeId]; + if (this.body.data.nodes._data[nodeId].x != Math.round(node.x) || this.body.data.nodes._data[nodeId].y != Math.round(node.y)) { + dataArray.push({ id: nodeId, x: Math.round(node.x), y: Math.round(node.y) }); + } + } + } + this.body.data.nodes.update(dataArray); + } + }, { + key: 'getBoundingBox', - if (draw === true) { - this.lineTo(x, y); - } else { - this.moveTo(x, y); + /** + * get the bounding box of a node. + * @param nodeId + * @returns {j|*} + */ + value: function getBoundingBox(nodeId) { + if (this.body.nodes[nodeId] !== undefined) { + return this.body.nodes[nodeId].shape.boundingBox; } + } + }, { + key: 'getConnectedNodes', - distRemaining -= dashLength; - draw = !draw; + /** + * Get the Ids of nodes connected to this node. + * @param nodeId + * @returns {Array} + */ + value: function getConnectedNodes(nodeId) { + var nodeList = []; + if (this.body.nodes[nodeId] !== undefined) { + var node = this.body.nodes[nodeId]; + var nodeObj = {}; // used to quickly check if node already exists + for (var i = 0; i < node.edges.length; i++) { + var edge = node.edges[i]; + if (edge.toId == nodeId) { + // these are double equals since ids can be numeric or string + if (nodeObj[edge.fromId] === undefined) { + nodeList.push(edge.fromId); + nodeObj[edge.fromId] = true; + } + } else if (edge.fromId == nodeId) { + // these are double equals since ids can be numeric or string + if (nodeObj[edge.toId] === undefined) { + nodeList.push(edge.toId); + nodeObj[edge.toId] = true; + } + } + } + } + return nodeList; } - }; - } + }, { + key: 'getConnectedEdges', + + /** + * Get the ids of the edges connected to this node. + * @param nodeId + * @returns {*} + */ + value: function getConnectedEdges(nodeId) { + var edgeList = []; + if (this.body.nodes[nodeId] !== undefined) { + var node = this.body.nodes[nodeId]; + for (var i = 0; i < node.edges.length; i++) { + edgeList.push(node.edges[i].id); + } + } else { + console.log('NodeId provided for getConnectedEdges does not exist. Provided: ', nodeId); + } + return edgeList; + } + }]); + + return NodesHandler; + })(); + + exports['default'] = NodesHandler; + module.exports = exports['default']; /***/ }, -/* 68 */ +/* 62 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var keycharm = __webpack_require__(88); - var Emitter = __webpack_require__(43); - var Hammer = __webpack_require__(41); - var util = __webpack_require__(2); + Object.defineProperty(exports, '__esModule', { + value: true + }); - /** - * 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 - */ - function Activator(container) { - this.active = false; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - this.dom = { - container: container - }; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - this.dom.overlay = document.createElement('div'); - this.dom.overlay.className = 'vis-overlay'; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - this.dom.container.appendChild(this.dom.overlay); + var _sharedLabel = __webpack_require__(63); - this.hammer = Hammer(this.dom.overlay); - this.hammer.on('tap', this._onTapOverlay.bind(this)); + var _sharedLabel2 = _interopRequireDefault(_sharedLabel); - // 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(); - }); - }); + var _nodesShapesBox = __webpack_require__(64); - // attach a tap event to the window, in order to deactivate when clicking outside the timeline - this.bodyHammer = Hammer(document && document.body, { prevent_default: false }); - this.bodyHammer.on('tap', function (event) { - // deactivate when clicked outside the container - if (!_hasParent(event.target, container)) { - me.deactivate(); - } - }); + var _nodesShapesBox2 = _interopRequireDefault(_nodesShapesBox); - if (this.keycharm !== undefined) { - this.keycharm.destroy(); - } - this.keycharm = keycharm(); + var _nodesShapesCircle = __webpack_require__(66); - // keycharm listener only bounded when active) - this.escListener = this.deactivate.bind(this); - } + var _nodesShapesCircle2 = _interopRequireDefault(_nodesShapesCircle); - // turn into an event emitter - Emitter(Activator.prototype); + var _nodesShapesCircularImage = __webpack_require__(68); - // The currently active activator - Activator.current = null; + var _nodesShapesCircularImage2 = _interopRequireDefault(_nodesShapesCircularImage); - /** - * Destroy the activator. Cleans up all created DOM and event listeners - */ - Activator.prototype.destroy = function () { - this.deactivate(); + var _nodesShapesDatabase = __webpack_require__(69); - // remove dom - this.dom.overlay.parentNode.removeChild(this.dom.overlay); + var _nodesShapesDatabase2 = _interopRequireDefault(_nodesShapesDatabase); - // cleanup hammer instances - this.hammer = null; - this.bodyHammer = null; - // FIXME: cleaning up hammer instances doesn't work (Timeline not removed from memory) - }; + var _nodesShapesDiamond = __webpack_require__(70); - /** - * 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; + var _nodesShapesDiamond2 = _interopRequireDefault(_nodesShapesDiamond); - this.active = true; - this.dom.overlay.style.display = 'none'; - util.addClassName(this.dom.container, 'vis-active'); + var _nodesShapesDot = __webpack_require__(72); - this.emit('change'); - this.emit('activate'); + var _nodesShapesDot2 = _interopRequireDefault(_nodesShapesDot); - // 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); - }; + var _nodesShapesEllipse = __webpack_require__(73); - /** - * 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); + var _nodesShapesEllipse2 = _interopRequireDefault(_nodesShapesEllipse); - this.emit('change'); - this.emit('deactivate'); - }; + var _nodesShapesIcon = __webpack_require__(74); - /** - * Handle a tap event: activate the container - * @param event - * @private - */ - Activator.prototype._onTapOverlay = function (event) { - // activate the container - this.activate(); - event.stopPropagation(); - }; + var _nodesShapesIcon2 = _interopRequireDefault(_nodesShapesIcon); - /** - * 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; - } + var _nodesShapesImage = __webpack_require__(75); - module.exports = Activator; + var _nodesShapesImage2 = _interopRequireDefault(_nodesShapesImage); -/***/ }, -/* 69 */ -/***/ function(module, exports, __webpack_require__) { + var _nodesShapesSquare = __webpack_require__(76); - // English - 'use strict'; + var _nodesShapesSquare2 = _interopRequireDefault(_nodesShapesSquare); - exports['en'] = { - edit: 'Edit', - del: 'Delete selected', - back: 'Back', - addNode: 'Add Node', - addEdge: 'Add Edge', - editNode: 'Edit Node', - editEdge: 'Edit Edge', - addDescription: 'Click in an empty space to place a new node.', - edgeDescription: 'Click on a node and drag the edge to another node to connect them.', - editEdgeDescription: 'Click on the control points and drag them to a node to connect to it.', - createEdgeError: 'Cannot link edges to a cluster.', - deleteClusterError: 'Clusters cannot be deleted.', - editClusterError: 'Clusters cannot be edited.' - }; - exports['en_EN'] = exports['en']; - exports['en_US'] = exports['en']; + var _nodesShapesStar = __webpack_require__(77); - // Dutch - exports['nl'] = { - edit: 'Wijzigen', - del: 'Selectie verwijderen', - back: 'Terug', - addNode: 'Node toevoegen', - addEdge: 'Link toevoegen', - editNode: 'Node wijzigen', - editEdge: 'Link wijzigen', - addDescription: 'Klik op een leeg gebied om een nieuwe node te maken.', - edgeDescription: 'Klik op een node en sleep de link naar een andere node om ze te verbinden.', - editEdgeDescription: 'Klik op de verbindingspunten en sleep ze naar een node om daarmee te verbinden.', - createEdgeError: 'Kan geen link maken naar een cluster.', - deleteClusterError: 'Clusters kunnen niet worden verwijderd.', - editClusterError: 'Clusters kunnen niet worden aangepast.' - }; - exports['nl_NL'] = exports['nl']; - exports['nl_BE'] = exports['nl']; + var _nodesShapesStar2 = _interopRequireDefault(_nodesShapesStar); -/***/ }, -/* 70 */ -/***/ function(module, exports, __webpack_require__) { + var _nodesShapesText = __webpack_require__(78); - /* WEBPACK VAR INJECTION */(function(module) {//! moment.js - //! version : 2.10.3 - //! authors : Tim Wood, Iskren Chernev, Moment.js contributors - //! license : MIT - //! momentjs.com + var _nodesShapesText2 = _interopRequireDefault(_nodesShapesText); - (function (global, factory) { - true ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - global.moment = factory() - }(this, function () { 'use strict'; + var _nodesShapesTriangle = __webpack_require__(79); - var hookCallback; + var _nodesShapesTriangle2 = _interopRequireDefault(_nodesShapesTriangle); - function utils_hooks__hooks () { - return hookCallback.apply(null, arguments); - } + var _nodesShapesTriangleDown = __webpack_require__(80); - // This is done to register the method called with moment() - // without creating circular dependencies. - function setHookCallback (callback) { - hookCallback = callback; - } + var _nodesShapesTriangleDown2 = _interopRequireDefault(_nodesShapesTriangleDown); - function isArray(input) { - return Object.prototype.toString.call(input) === '[object Array]'; - } + var _sharedValidator = __webpack_require__(47); - function isDate(input) { - return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; - } + var _sharedValidator2 = _interopRequireDefault(_sharedValidator); - function map(arr, fn) { - var res = [], i; - for (i = 0; i < arr.length; ++i) { - res.push(fn(arr[i], i)); - } - return res; - } + var util = __webpack_require__(7); - function hasOwnProp(a, b) { - return Object.prototype.hasOwnProperty.call(a, b); - } + /** + * @class Node + * A node. A node can be connected to other nodes via one or multiple edges. + * @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, available: + * "database", "circle", "ellipse", + * "box", "image", "text", "dot", + * "star", "triangle", "triangleDown", + * "square", "icon" + * {string} image An image url + * {string} title An title text, can be HTML + * {anytype} group A group name or number + * @param {Network.Images} imagelist A list with images. Only needed + * when the node has an image + * @param {Network.Groups} grouplist A list with groups. Needed for + * retrieving group options + * @param {Object} constants An object with default values for + * example for the color + * + */ - function extend(a, b) { - for (var i in b) { - if (hasOwnProp(b, i)) { - a[i] = b[i]; - } - } + var Node = (function () { + function Node(options, body, imagelist, grouplist, globalOptions) { + _classCallCheck(this, Node); - if (hasOwnProp(b, 'toString')) { - a.toString = b.toString; - } + this.options = util.bridgeObject(globalOptions); + this.body = body; - if (hasOwnProp(b, 'valueOf')) { - a.valueOf = b.valueOf; - } + this.edges = []; // all edges connected to this node - return a; - } + // set defaults for the options + this.id = undefined; + this.imagelist = imagelist; + this.grouplist = grouplist; - function create_utc__createUTC (input, format, locale, strict) { - return createLocalOrUTC(input, format, locale, strict, true).utc(); - } + // 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; - function defaultParsingFlags() { - // We need to deep clone this object. - return { - empty : false, - unusedTokens : [], - unusedInput : [], - overflow : -2, - charsLeftOver : 0, - nullInput : false, - invalidMonth : null, - invalidFormat : false, - userInvalidated : false, - iso : false - }; - } + this.labelModule = new _sharedLabel2['default'](this.body, this.options); + this.setOptions(options); + } - function getParsingFlags(m) { - if (m._pf == null) { - m._pf = defaultParsingFlags(); - } - return m._pf; + _createClass(Node, [{ + key: 'attachEdge', + + /** + * Attach a edge to the node + * @param {Edge} edge + */ + value: function attachEdge(edge) { + if (this.edges.indexOf(edge) === -1) { + this.edges.push(edge); + } } + }, { + key: 'detachEdge', - function valid__isValid(m) { - if (m._isValid == null) { - var flags = getParsingFlags(m); - m._isValid = !isNaN(m._d.getTime()) && - flags.overflow < 0 && - !flags.empty && - !flags.invalidMonth && - !flags.nullInput && - !flags.invalidFormat && - !flags.userInvalidated; + /** + * Detach a edge from the node + * @param {Edge} edge + */ + value: function detachEdge(edge) { + var index = this.edges.indexOf(edge); + if (index != -1) { + this.edges.splice(index, 1); + } + } + }, { + key: 'togglePhysics', - if (m._strict) { - m._isValid = m._isValid && - flags.charsLeftOver === 0 && - flags.unusedTokens.length === 0 && - flags.bigHour === undefined; - } - } - return m._isValid; + /** + * Enable or disable the physics. + * @param status + */ + value: function togglePhysics(status) { + this.options.physics = status; } + }, { + key: 'setOptions', - function valid__createInvalid (flags) { - var m = create_utc__createUTC(NaN); - if (flags != null) { - extend(getParsingFlags(m), flags); - } - else { - getParsingFlags(m).userInvalidated = true; - } + /** + * Set or overwrite options for the node + * @param {Object} options an object with options + * @param {Object} constants and object with default, global options + */ + value: function setOptions(options) { + if (!options) { + return; + } + // basic options + if (options.id !== undefined) { + this.id = options.id; + } - return m; - } + if (this.id === undefined) { + throw 'Node must have an id'; + } - var momentProperties = utils_hooks__hooks.momentProperties = []; + // set these options locally + if (options.x !== undefined) { + this.x = parseInt(options.x);this.predefinedPosition = true; + } + if (options.y !== undefined) { + this.y = parseInt(options.y);this.predefinedPosition = true; + } + if (options.size !== undefined) { + this.baseSize = options.size; + } + if (options.value !== undefined) { + options.value = parseInt(options.value); + } - function copyConfig(to, from) { - var i, prop, val; + // copy group options + if (typeof options.group === 'number' || typeof options.group === 'string' && options.group != '') { + var groupObj = this.grouplist.get(options.group); + util.deepExtend(this.options, groupObj); + // the color object needs to be completely defined. Since groups can partially overwrite the colors, we parse it again, just in case. + this.options.color = util.parseColor(this.options.color); + } - if (typeof from._isAMomentObject !== 'undefined') { - to._isAMomentObject = from._isAMomentObject; - } - if (typeof from._i !== 'undefined') { - to._i = from._i; - } - if (typeof from._f !== 'undefined') { - to._f = from._f; - } - if (typeof from._l !== 'undefined') { - to._l = from._l; - } - if (typeof from._strict !== 'undefined') { - to._strict = from._strict; - } - if (typeof from._tzm !== 'undefined') { - to._tzm = from._tzm; - } - if (typeof from._isUTC !== 'undefined') { - to._isUTC = from._isUTC; - } - if (typeof from._offset !== 'undefined') { - to._offset = from._offset; - } - if (typeof from._pf !== 'undefined') { - to._pf = getParsingFlags(from); - } - if (typeof from._locale !== 'undefined') { - to._locale = from._locale; - } + // this transforms all shorthands into fully defined options + Node.parseOptions(this.options, options, true); - if (momentProperties.length > 0) { - for (i in momentProperties) { - prop = momentProperties[i]; - val = from[prop]; - if (typeof val !== 'undefined') { - to[prop] = val; - } - } + // load the images + if (this.options.image !== undefined && this.options.image != '') { + if (this.imagelist) { + this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage, this.id); + } else { + throw 'No imagelist provided'; } + } - return to; - } + this.updateShape(); + this.updateLabelModule(); - var updateInProgress = false; + // reset the size of the node, this can be changed + this._reset(); - // Moment prototype object - function Moment(config) { - copyConfig(this, config); - this._d = new Date(+config._d); - // Prevent infinite loop in case updateOffset creates new moment - // objects. - if (updateInProgress === false) { - updateInProgress = true; - utils_hooks__hooks.updateOffset(this); - updateInProgress = false; - } + if (options.hidden !== undefined || options.physics !== undefined) { + return true; + } + return false; } - - function isMoment (obj) { - return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); + }, { + key: 'updateLabelModule', + value: function updateLabelModule() { + if (this.options.label === undefined || this.options.label === null) { + this.options.label = ''; + } + this.labelModule.setOptions(this.options, true); + if (this.labelModule.baseSize !== undefined) { + this.baseFontSize = this.labelModule.baseSize; + } } - - function toInt(argumentForCoercion) { - var coercedNumber = +argumentForCoercion, - value = 0; - - if (coercedNumber !== 0 && isFinite(coercedNumber)) { - if (coercedNumber >= 0) { - value = Math.floor(coercedNumber); - } else { - value = Math.ceil(coercedNumber); - } - } - - return value; + }, { + key: 'updateShape', + value: function updateShape() { + // choose draw method depending on the shape + switch (this.options.shape) { + case 'box': + this.shape = new _nodesShapesBox2['default'](this.options, this.body, this.labelModule); + break; + case 'circle': + this.shape = new _nodesShapesCircle2['default'](this.options, this.body, this.labelModule); + break; + case 'circularImage': + this.shape = new _nodesShapesCircularImage2['default'](this.options, this.body, this.labelModule, this.imageObj); + break; + case 'database': + this.shape = new _nodesShapesDatabase2['default'](this.options, this.body, this.labelModule); + break; + case 'diamond': + this.shape = new _nodesShapesDiamond2['default'](this.options, this.body, this.labelModule); + break; + case 'dot': + this.shape = new _nodesShapesDot2['default'](this.options, this.body, this.labelModule); + break; + case 'ellipse': + this.shape = new _nodesShapesEllipse2['default'](this.options, this.body, this.labelModule); + break; + case 'icon': + this.shape = new _nodesShapesIcon2['default'](this.options, this.body, this.labelModule); + break; + case 'image': + this.shape = new _nodesShapesImage2['default'](this.options, this.body, this.labelModule, this.imageObj); + break; + case 'square': + this.shape = new _nodesShapesSquare2['default'](this.options, this.body, this.labelModule); + break; + case 'star': + this.shape = new _nodesShapesStar2['default'](this.options, this.body, this.labelModule); + break; + case 'text': + this.shape = new _nodesShapesText2['default'](this.options, this.body, this.labelModule); + break; + case 'triangle': + this.shape = new _nodesShapesTriangle2['default'](this.options, this.body, this.labelModule); + break; + case 'triangleDown': + this.shape = new _nodesShapesTriangleDown2['default'](this.options, this.body, this.labelModule); + break; + default: + this.shape = new _nodesShapesEllipse2['default'](this.options, this.body, this.labelModule); + break; + } + this._reset(); } + }, { + key: 'select', - function compareArrays(array1, array2, dontConvert) { - var len = Math.min(array1.length, array2.length), - lengthDiff = Math.abs(array1.length - array2.length), - diffs = 0, - i; - for (i = 0; i < len; i++) { - if ((dontConvert && array1[i] !== array2[i]) || - (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { - diffs++; - } - } - return diffs + lengthDiff; + /** + * select this node + */ + value: function select() { + this.selected = true; + this._reset(); } + }, { + key: 'unselect', - function Locale() { + /** + * unselect this node + */ + value: function unselect() { + this.selected = false; + this._reset(); } + }, { + key: '_reset', - var locales = {}; - var globalLocale; + /** + * Reset the calculated size of the node, forces it to recalculate its size + * @private + */ + value: function _reset() { + this.shape.width = undefined; + this.shape.height = undefined; + } + }, { + key: 'getTitle', - function normalizeLocale(key) { - return key ? key.toLowerCase().replace('_', '-') : key; + /** + * get the title of this node. + * @return {string} title The title of the node, or undefined when no title + * has been set. + */ + value: function getTitle() { + return this.options.title; } + }, { + key: 'distanceToBorder', - // pick the locale from the array - // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each - // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root - function chooseLocale(names) { - var i = 0, j, next, locale, split; + /** + * 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 + */ + value: function distanceToBorder(ctx, angle) { + return this.shape.distanceToBorder(ctx, angle); + } + }, { + key: 'isFixed', - while (i < names.length) { - split = normalizeLocale(names[i]).split('-'); - j = split.length; - next = normalizeLocale(names[i + 1]); - next = next ? next.split('-') : null; - while (j > 0) { - locale = loadLocale(split.slice(0, j).join('-')); - if (locale) { - return locale; - } - if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { - //the next array item is better than a shallower substring of this one - break; - } - j--; - } - i++; - } - return null; + /** + * Check if this node has a fixed x and y position + * @return {boolean} true if fixed, false if not + */ + value: function isFixed() { + return this.options.fixed.x && this.options.fixed.y; } + }, { + key: 'isSelected', - function loadLocale(name) { - var oldLocale = null; - // TODO: Find a better way to register and load all the locales in Node - if (!locales[name] && typeof module !== 'undefined' && - module && module.exports) { - try { - oldLocale = globalLocale._abbr; - !(function webpackMissingModule() { var e = new Error("Cannot find module \"./locale\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()); - // because defineLocale currently also sets the global locale, we - // want to undo that for lazy loaded locales - locale_locales__getSetGlobalLocale(oldLocale); - } catch (e) { } - } - return locales[name]; + /** + * check if this node is selecte + * @return {boolean} selected True if node is selected, else false + */ + value: function isSelected() { + return this.selected; } + }, { + key: 'getValue', - // This function will load locale and then set the global locale. If - // no arguments are passed in, it will simply return the current global - // locale key. - function locale_locales__getSetGlobalLocale (key, values) { - var data; - if (key) { - if (typeof values === 'undefined') { - data = locale_locales__getLocale(key); - } - else { - data = defineLocale(key, values); - } + /** + * Retrieve the value of the node. Can be undefined + * @return {Number} value + */ + value: function getValue() { + return this.options.value; + } + }, { + key: 'setValueRange', - if (data) { - // moment.duration._locale = moment._locale = data; - globalLocale = data; - } + /** + * Adjust the value range of the node. The node will adjust it's size + * based on its value. + * @param {Number} min + * @param {Number} max + */ + 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; + } + } + }, { + key: 'draw', - return globalLocale._abbr; + /** + * Draw this node in the given canvas + * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); + * @param {CanvasRenderingContext2D} ctx + */ + value: function draw(ctx) { + this.shape.draw(ctx, this.x, this.y, this.selected, this.hover); } + }, { + key: 'updateBoundingBox', - function defineLocale (name, values) { - if (values !== null) { - values.abbr = name; - if (!locales[name]) { - locales[name] = new Locale(); - } - locales[name].set(values); + /** + * Update the bounding box of the shape + */ + value: function updateBoundingBox() { + this.shape.updateBoundingBox(this.x, this.y); + } + }, { + key: 'resize', - // backwards compat for now: also set the locale - locale_locales__getSetGlobalLocale(name); + /** + * 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 + */ + value: function resize(ctx) { + this.shape.resize(ctx); + } + }, { + key: 'isOverlappingWith', - return locales[name]; - } else { - // useful for testing - delete locales[name]; - return null; - } + /** + * 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 + */ + 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; } + }, { + key: 'isBoundingBoxOverlappingWith', - // returns locale data - function locale_locales__getLocale (key) { - var locale; + /** + * 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 + */ + 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; + } + }], [{ + key: 'parseOptions', - if (key && key._locale && key._locale._abbr) { - key = key._locale._abbr; - } + /** + * 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 parentOptions + * @param newOptions + */ + value: function parseOptions(parentOptions, newOptions) { + var allowDeletion = arguments[2] === undefined ? false : arguments[2]; - if (!key) { - return globalLocale; - } + var fields = ['color', 'font', 'fixed', 'shadow']; + util.selectiveNotDeepExtend(fields, parentOptions, newOptions, allowDeletion); - if (!isArray(key)) { - //short-circuit everything else - locale = loadLocale(key); - if (locale) { - return locale; - } - key = [key]; - } + // merge the shadow options into the parent. + util.mergeOptions(parentOptions, newOptions, 'shadow'); - return chooseLocale(key); - } + // 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 = undefined; + delete parentOptions.color; + } - var aliases = {}; + // 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; + } + } + } - function addUnitAlias (unit, shorthand) { - var lowerCase = unit.toLowerCase(); - aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; - } + // handle the font options + if (newOptions.font !== undefined) { + _sharedLabel2['default'].parseOptions(parentOptions.font, newOptions); + } - function normalizeUnits(units) { - return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; + // handle the scaling options, specifically the label part + if (newOptions.scaling !== undefined) { + util.mergeOptions(parentOptions.scaling, newOptions.scaling, 'label'); + } } + }]); - function normalizeObjectUnits(inputObject) { - var normalizedInput = {}, - normalizedProp, - prop; + return Node; + })(); - for (prop in inputObject) { - if (hasOwnProp(inputObject, prop)) { - normalizedProp = normalizeUnits(prop); - if (normalizedProp) { - normalizedInput[normalizedProp] = inputObject[prop]; - } - } - } + exports['default'] = Node; + module.exports = exports['default']; - return normalizedInput; - } +/***/ }, +/* 63 */ +/***/ function(module, exports, __webpack_require__) { - function makeGetSet (unit, keepTime) { - return function (value) { - if (value != null) { - get_set__set(this, unit, value); - utils_hooks__hooks.updateOffset(this, keepTime); - return this; - } else { - return get_set__get(this, unit); - } - }; - } + 'use strict'; - function get_set__get (mom, unit) { - return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); - } + Object.defineProperty(exports, '__esModule', { + value: true + }); - function get_set__set (mom, unit, value) { - return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // MOMENTS + function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _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; } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } } - function getSet (units, value) { - var unit; - if (typeof units === 'object') { - for (unit in units) { - this.set(unit, units[unit]); - } - } else { - units = normalizeUnits(units); - if (typeof this[units] === 'function') { - return this[units](value); - } - } - return this; - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - function zeroFill(number, targetLength, forceSign) { - var output = '' + Math.abs(number), - sign = number >= 0; + var util = __webpack_require__(7); - while (output.length < targetLength) { - output = '0' + output; - } - return (sign ? (forceSign ? '+' : '') : '-') + output; - } + var Label = (function () { + function Label(body, options) { + _classCallCheck(this, Label); - var formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g; + this.body = body; - var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; + this.baseSize = undefined; + this.setOptions(options); + this.size = { top: 0, left: 0, width: 0, height: 0, yLine: 0 }; // could be cached + } - var formatFunctions = {}; + _createClass(Label, [{ + key: 'setOptions', + value: function setOptions(options) { + var allowDeletion = arguments[1] === undefined ? false : arguments[1]; - var formatTokenFunctions = {}; + this.options = options; - // token: 'M' - // padded: ['MM', 2] - // ordinal: 'Mo' - // callback: function () { this.month() + 1 } - function addFormatToken (token, padded, ordinal, callback) { - var func = callback; - if (typeof callback === 'string') { - func = function () { - return this[callback](); - }; - } - if (token) { - formatTokenFunctions[token] = func; - } - if (padded) { - formatTokenFunctions[padded[0]] = function () { - return zeroFill(func.apply(this, arguments), padded[1], padded[2]); - }; - } - if (ordinal) { - formatTokenFunctions[ordinal] = function () { - return this.localeData().ordinal(func.apply(this, arguments), token); - }; - } - } + if (options.label !== undefined) { + this.labelDirty = true; + } - function removeFormattingTokens(input) { - if (input.match(/\[[\s\S]/)) { - return input.replace(/^\[|\]$/g, ''); + if (options.font !== undefined) { + Label.parseOptions(this.options.font, options, allowDeletion); + if (typeof options.font === 'string') { + this.baseSize = this.options.font.size; + } else if (typeof options.font === 'object') { + if (options.font.size !== undefined) { + this.baseSize = options.font.size; + } } - return input.replace(/\\/g, ''); + } } + }, { + key: 'draw', - function makeFormatFunction(format) { - var array = format.match(formattingTokens), i, length; + /** + * Main function. This is called from anything that wants to draw a label. + * @param ctx + * @param x + * @param y + * @param selected + * @param baseline + */ + value: function draw(ctx, x, y, selected) { + var baseline = arguments[4] === undefined ? 'middle' : arguments[4]; - for (i = 0, length = array.length; i < length; i++) { - if (formatTokenFunctions[array[i]]) { - array[i] = formatTokenFunctions[array[i]]; - } else { - array[i] = removeFormattingTokens(array[i]); - } - } + // if no label, return + if (this.options.label === undefined) return; - return function (mom) { - var output = ''; - for (i = 0; i < length; i++) { - output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; - } - return output; - }; + // check if we have to render the label + var viewFontSize = this.options.font.size * this.body.view.scale; + if (this.options.label && viewFontSize < this.options.scaling.label.drawThreshold - 1) return; + + // update the size cache if required + this.calculateLabelSize(ctx, selected, x, y, baseline); + + // create the fontfill background + this._drawBackground(ctx); + // draw text + this._drawText(ctx, selected, x, y, baseline); } + }, { + key: '_drawBackground', - // format date using native date object - function formatMoment(m, format) { - if (!m.isValid()) { - return m.localeData().invalidDate(); - } + /** + * Draws the label background + * @param {CanvasRenderingContext2D} ctx + * @private + */ + value: function _drawBackground(ctx) { + if (this.options.font.background !== undefined && this.options.font.background !== 'none') { + ctx.fillStyle = this.options.font.background; - format = expandFormat(format, m.localeData()); + var lineMargin = 2; - if (!formatFunctions[format]) { - formatFunctions[format] = makeFormatFunction(format); + switch (this.options.font.align) { + case 'middle': + ctx.fillRect(-this.size.width * 0.5, -this.size.height * 0.5, this.size.width, this.size.height); + break; + case 'top': + ctx.fillRect(-this.size.width * 0.5, -(this.size.height + lineMargin), this.size.width, this.size.height); + break; + case 'bottom': + ctx.fillRect(-this.size.width * 0.5, lineMargin, this.size.width, this.size.height); + break; + default: + ctx.fillRect(this.size.left, this.size.top - 0.5 * lineMargin, this.size.width, this.size.height); + break; } - - return formatFunctions[format](m); + } } + }, { + key: '_drawText', - function expandFormat(format, locale) { - var i = 5; + /** + * + * @param ctx + * @param x + * @param baseline + * @private + */ + value: function _drawText(ctx, selected, x, y) { + var baseline = arguments[4] === undefined ? 'middle' : arguments[4]; - function replaceLongDateFormatTokens(input) { - return locale.longDateFormat(input) || input; - } + var fontSize = this.options.font.size; + var viewFontSize = fontSize * this.body.view.scale; + // this ensures that there will not be HUGE letters on screen by setting an upper limit on the visible text size (regardless of zoomLevel) + if (viewFontSize >= this.options.scaling.label.maxVisible) { + fontSize = Number(this.options.scaling.label.maxVisible) / this.body.view.scale; + } - localFormattingTokens.lastIndex = 0; - while (i >= 0 && localFormattingTokens.test(format)) { - format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); - localFormattingTokens.lastIndex = 0; - i -= 1; - } + var yLine = this.size.yLine; - return format; - } + var _getColor = this._getColor(viewFontSize); - var match1 = /\d/; // 0 - 9 - var match2 = /\d\d/; // 00 - 99 - var match3 = /\d{3}/; // 000 - 999 - var match4 = /\d{4}/; // 0000 - 9999 - var match6 = /[+-]?\d{6}/; // -999999 - 999999 - var match1to2 = /\d\d?/; // 0 - 99 - var match1to3 = /\d{1,3}/; // 0 - 999 - var match1to4 = /\d{1,4}/; // 0 - 9999 - var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 + var _getColor2 = _slicedToArray(_getColor, 2); - var matchUnsigned = /\d+/; // 0 - inf - var matchSigned = /[+-]?\d+/; // -inf - inf + var fontColor = _getColor2[0]; + var strokeColor = _getColor2[1]; - var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z + var _setAlignment = this._setAlignment(ctx, x, yLine, baseline); - var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 + var _setAlignment2 = _slicedToArray(_setAlignment, 2); - // any word (or two) characters or numbers including two/three word month in arabic. - var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i; + x = _setAlignment2[0]; + yLine = _setAlignment2[1]; - var regexes = {}; + // configure context for drawing the text + ctx.font = (selected ? 'bold ' : '') + fontSize + 'px ' + this.options.font.face; + ctx.fillStyle = fontColor; + ctx.textAlign = 'center'; - function addRegexToken (token, regex, strictRegex) { - regexes[token] = typeof regex === 'function' ? regex : function (isStrict) { - return (isStrict && strictRegex) ? strictRegex : regex; - }; + // set the strokeWidth + if (this.options.font.strokeWidth > 0) { + ctx.lineWidth = this.options.font.strokeWidth; + ctx.strokeStyle = strokeColor; + ctx.lineJoin = 'round'; + } + + // draw the text + for (var i = 0; i < this.lineCount; i++) { + if (this.options.font.strokeWidth > 0) { + ctx.strokeText(this.lines[i], x, yLine); + } + ctx.fillText(this.lines[i], x, yLine); + yLine += fontSize; + } } + }, { + key: '_setAlignment', + value: function _setAlignment(ctx, x, yLine, baseline) { + // check for label alignment (for edges) + // TODO: make alignment for nodes + if (this.options.font.align !== 'horizontal') { + x = 0; + yLine = 0; - function getParseRegexForToken (token, config) { - if (!hasOwnProp(regexes, token)) { - return new RegExp(unescapeFormat(token)); + var lineMargin = 2; + if (this.options.font.align === 'top') { + ctx.textBaseline = 'alphabetic'; + yLine -= 2 * lineMargin; // distance from edge, required because we use alphabetic. Alphabetic has less difference between browsers + } else if (this.options.font.align === 'bottom') { + ctx.textBaseline = 'hanging'; + yLine += 2 * lineMargin; // distance from edge, required because we use hanging. Hanging has less difference between browsers + } else { + ctx.textBaseline = 'middle'; } + } else { + ctx.textBaseline = baseline; + } - return regexes[token](config._strict, config._locale); + return [x, yLine]; } + }, { + key: '_getColor', - // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript - function unescapeFormat(s) { - return s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { - return p1 || p2 || p3 || p4; - }).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); + /** + * fade in when relative scale is between threshold and threshold - 1. + * If the relative scale would be smaller than threshold -1 the draw function would have returned before coming here. + * + * @param viewFontSize + * @returns {*[]} + * @private + */ + value: function _getColor(viewFontSize) { + var fontColor = this.options.font.color || '#000000'; + var strokeColor = this.options.font.strokeColor || '#ffffff'; + if (viewFontSize <= this.options.scaling.label.drawThreshold) { + var opacity = Math.max(0, Math.min(1, 1 - (this.options.scaling.label.drawThreshold - viewFontSize))); + fontColor = util.overrideOpacity(fontColor, opacity); + strokeColor = util.overrideOpacity(strokeColor, opacity); + } + return [fontColor, strokeColor]; } + }, { + key: 'getTextSize', - var tokens = {}; - - function addParseToken (token, callback) { - var i, func = callback; - if (typeof token === 'string') { - token = [token]; - } - if (typeof callback === 'number') { - func = function (input, array) { - array[callback] = toInt(input); - }; - } - for (i = 0; i < token.length; i++) { - tokens[token[i]] = func; - } - } + /** + * + * @param ctx + * @param selected + * @returns {{width: number, height: number}} + */ + value: function getTextSize(ctx) { + var selected = arguments[1] === undefined ? false : arguments[1]; - function addWeekParseToken (token, callback) { - addParseToken(token, function (input, array, config, token) { - config._w = config._w || {}; - callback(input, config._w, config, token); - }); + var size = { + width: this._processLabel(ctx, selected), + height: this.options.font.size * this.lineCount, + lineCount: this.lineCount + }; + return size; } + }, { + key: 'calculateLabelSize', - function addTimeToArrayFromToken(token, input, config) { - if (input != null && hasOwnProp(tokens, token)) { - tokens[token](input, config._a, config, token); - } - } + /** + * + * @param ctx + * @param selected + * @param x + * @param y + * @param baseline + */ + value: function calculateLabelSize(ctx, selected) { + var x = arguments[2] === undefined ? 0 : arguments[2]; + var y = arguments[3] === undefined ? 0 : arguments[3]; + var baseline = arguments[4] === undefined ? 'middle' : arguments[4]; - var YEAR = 0; - var MONTH = 1; - var DATE = 2; - var HOUR = 3; - var MINUTE = 4; - var SECOND = 5; - var MILLISECOND = 6; + if (this.labelDirty === true) { + this.size.width = this._processLabel(ctx, selected); + } + this.size.height = this.options.font.size * this.lineCount; + this.size.left = x - this.size.width * 0.5; + this.size.top = y - this.size.height * 0.5; + this.size.yLine = y + (1 - this.lineCount) * 0.5 * this.options.font.size; + if (baseline === 'hanging') { + this.size.top += 0.5 * this.options.font.size; + this.size.top += 4; // distance from node, required because we use hanging. Hanging has less difference between browsers + this.size.yLine += 4; // distance from node + } - function daysInMonth(year, month) { - return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); + this.labelDirty = false; } + }, { + key: '_processLabel', - // FORMATTING - - addFormatToken('M', ['MM', 2], 'Mo', function () { - return this.month() + 1; - }); + /** + * This calculates the width as well as explodes the label string and calculates the amount of lines. + * @param ctx + * @param selected + * @returns {number} + * @private + */ + value: function _processLabel(ctx, selected) { + var width = 0; + var lines = ['']; + var lineCount = 0; + if (this.options.label !== undefined) { + lines = String(this.options.label).split('\n'); + lineCount = lines.length; + ctx.font = (selected ? 'bold ' : '') + this.options.font.size + 'px ' + this.options.font.face; + width = ctx.measureText(lines[0]).width; + for (var i = 1; i < lineCount; i++) { + var lineWidth = ctx.measureText(lines[i]).width; + width = lineWidth > width ? lineWidth : width; + } + } + this.lines = lines; + this.lineCount = lineCount; - addFormatToken('MMM', 0, 0, function (format) { - return this.localeData().monthsShort(this, format); - }); + return width; + } + }], [{ + key: 'parseOptions', + value: function parseOptions(parentOptions, newOptions) { + var allowDeletion = arguments[2] === undefined ? false : arguments[2]; - addFormatToken('MMMM', 0, 0, function (format) { - return this.localeData().months(this, format); - }); + if (typeof newOptions.font === 'string') { + var newOptionsArray = newOptions.font.split(' '); + parentOptions.size = newOptionsArray[0].replace('px', ''); + parentOptions.face = newOptionsArray[1]; + parentOptions.color = newOptionsArray[2]; + } else if (typeof newOptions.font === 'object') { + util.fillIfDefined(parentOptions, newOptions.font, allowDeletion); + } + parentOptions.size = Number(parentOptions.size); + } + }]); - // ALIASES + return Label; + })(); - addUnitAlias('month', 'M'); + exports['default'] = Label; + module.exports = exports['default']; - // PARSING +/***/ }, +/* 64 */ +/***/ function(module, exports, __webpack_require__) { - addRegexToken('M', match1to2); - addRegexToken('MM', match1to2, match2); - addRegexToken('MMM', matchWord); - addRegexToken('MMMM', matchWord); + 'use strict'; - addParseToken(['M', 'MM'], function (input, array) { - array[MONTH] = toInt(input) - 1; - }); + Object.defineProperty(exports, '__esModule', { + value: true + }); - addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { - var month = config._locale.monthsParse(input, token, config._strict); - // if we didn't find a month name, mark the date as invalid. - if (month != null) { - array[MONTH] = month; - } else { - getParsingFlags(config).invalidMonth = input; - } - }); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // LOCALES + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); - function localeMonths (m) { - return this._months[m.month()]; - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); - function localeMonthsShort (m) { - return this._monthsShort[m.month()]; - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - function localeMonthsParse (monthName, format, strict) { - var i, mom, regex; + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - if (!this._monthsParse) { - this._monthsParse = []; - this._longMonthsParse = []; - this._shortMonthsParse = []; - } + var _utilNodeBase = __webpack_require__(65); - for (i = 0; i < 12; i++) { - // make the regex if we don't have it already - mom = create_utc__createUTC([2000, i]); - if (strict && !this._longMonthsParse[i]) { - this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); - this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); - } - if (!strict && !this._monthsParse[i]) { - regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); - this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); - } - // test the regex - if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { - return i; - } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { - return i; - } else if (!strict && this._monthsParse[i].test(monthName)) { - return i; - } - } - } + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - // MOMENTS + var Box = (function (_NodeBase) { + function Box(options, body, labelModule) { + _classCallCheck(this, Box); - function setMonth (mom, value) { - var dayOfMonth; + _get(Object.getPrototypeOf(Box.prototype), 'constructor', this).call(this, options, body, labelModule); + } - // TODO: Move this out of here! - if (typeof value === 'string') { - value = mom.localeData().monthsParse(value); - // TODO: Another silent failure? - if (typeof value !== 'number') { - return mom; - } - } + _inherits(Box, _NodeBase); - dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); - mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); - return mom; + _createClass(Box, [{ + key: 'resize', + value: function resize(ctx, selected) { + if (this.width === undefined) { + var margin = 5; + var textSize = this.labelModule.getTextSize(ctx, selected); + this.width = textSize.width + 2 * margin; + this.height = textSize.height + 2 * margin; + this.radius = 0.5 * this.width; + } } + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(ctx, selected); + this.left = x - this.width / 2; + this.top = y - this.height / 2; - function getSetMonth (value) { - if (value != null) { - setMonth(this, value); - utils_hooks__hooks.updateOffset(this, true); - return this; - } else { - return get_set__get(this, 'Month'); - } - } + var borderWidth = this.options.borderWidth; + var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - function getDaysInMonth () { - return daysInMonth(this.year(), this.month()); - } + ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; + ctx.lineWidth = selected ? selectionLineWidth : borderWidth; + ctx.lineWidth /= this.body.view.scale; + ctx.lineWidth = Math.min(this.width, ctx.lineWidth); - function checkOverflow (m) { - var overflow; - var a = m._a; + ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; - if (a && getParsingFlags(m).overflow === -2) { - overflow = - a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : - a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : - a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : - a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : - a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : - a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : - -1; + var borderRadius = 6; + ctx.roundRect(this.left, this.top, this.width, this.height, borderRadius); - if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { - overflow = DATE; - } + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); - getParsingFlags(m).overflow = overflow; - } + // disable shadows for other elements. + this.disableShadow(ctx); - return m; - } + ctx.stroke(); - function warn(msg) { - if (utils_hooks__hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { - console.warn('Deprecation warning: ' + msg); - } + this.updateBoundingBox(x, y); + this.labelModule.draw(ctx, x, y, selected); } + }, { + key: 'updateBoundingBox', + value: function updateBoundingBox(x, y) { + this.left = x - this.width * 0.5; + this.top = y - this.height * 0.5; - function deprecate(msg, fn) { - var firstTime = true, - msgWithStack = msg + '\n' + (new Error()).stack; - - return extend(function () { - if (firstTime) { - warn(msgWithStack); - firstTime = false; - } - return fn.apply(this, arguments); - }, fn); + this.boundingBox.left = this.left; + this.boundingBox.top = this.top; + this.boundingBox.bottom = this.top + this.height; + this.boundingBox.right = this.left + this.width; } - - var deprecations = {}; - - function deprecateSimple(name, msg) { - if (!deprecations[name]) { - warn(msg); - deprecations[name] = true; - } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + var a = this.width / 2; + var b = this.height / 2; + var w = Math.sin(angle) * a; + var h = Math.cos(angle) * b; + return a * b / Math.sqrt(w * w + h * h); } + }]); - utils_hooks__hooks.suppressDeprecationWarnings = false; + return Box; + })(_utilNodeBase2['default']); - var from_string__isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; + exports['default'] = Box; + module.exports = exports['default']; - var isoDates = [ - ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], - ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], - ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], - ['GGGG-[W]WW', /\d{4}-W\d{2}/], - ['YYYY-DDD', /\d{4}-\d{3}/] - ]; +/***/ }, +/* 65 */ +/***/ function(module, exports, __webpack_require__) { - // iso time formats and regexes - var isoTimes = [ - ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], - ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], - ['HH:mm', /(T| )\d\d:\d\d/], - ['HH', /(T| )\d\d/] - ]; + 'use strict'; - var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; + Object.defineProperty(exports, '__esModule', { + value: true + }); - // date from iso format - function configFromISO(config) { - var i, l, - string = config._i, - match = from_string__isoRegex.exec(string); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - if (match) { - getParsingFlags(config).iso = true; - for (i = 0, l = isoDates.length; i < l; i++) { - if (isoDates[i][1].exec(string)) { - // match[5] should be 'T' or undefined - config._f = isoDates[i][0] + (match[6] || ' '); - break; - } - } - for (i = 0, l = isoTimes.length; i < l; i++) { - if (isoTimes[i][1].exec(string)) { - config._f += isoTimes[i][0]; - break; - } - } - if (string.match(matchOffset)) { - config._f += 'Z'; - } - configFromStringAndFormat(config); - } else { - config._isValid = false; - } - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - // date from iso format or fallback - function configFromString(config) { - var matched = aspNetJsonRegex.exec(config._i); + var NodeBase = (function () { + function NodeBase(options, body, labelModule) { + _classCallCheck(this, NodeBase); - if (matched !== null) { - config._d = new Date(+matched[1]); - return; - } + 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.boundingBox = { top: 0, left: 0, right: 0, bottom: 0 }; + } - configFromISO(config); - if (config._isValid === false) { - delete config._isValid; - utils_hooks__hooks.createFromInputFallback(config); - } + _createClass(NodeBase, [{ + key: 'setOptions', + value: function setOptions(options) { + this.options = options; } - - utils_hooks__hooks.createFromInputFallback = deprecate( - 'moment construction falls back to js Date. This is ' + - 'discouraged and will be removed in upcoming major ' + - 'release. Please refer to ' + - 'https://github.com/moment/moment/issues/1407 for more info.', - function (config) { - config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); - } - ); - - function createDate (y, m, d, h, M, s, ms) { - //can't just apply() to create a date: - //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply - var date = new Date(y, m, d, h, M, s, ms); - - //the date constructor doesn't accept years < 1970 - if (y < 1970) { - date.setFullYear(y); - } - return date; + }, { + key: '_distanceToBorder', + value: function _distanceToBorder(angle) { + var borderWidth = 1; + return Math.min(Math.abs(this.width / 2 / Math.cos(angle)), Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth; } - - function createUTCDate (y) { - var date = new Date(Date.UTC.apply(null, arguments)); - if (y < 1970) { - date.setUTCFullYear(y); - } - return date; + }, { + key: 'enableShadow', + value: function enableShadow(ctx) { + if (this.options.shadow.enabled === true) { + ctx.shadowColor = 'rgba(0,0,0,0.5)'; + ctx.shadowBlur = this.options.shadow.size; + ctx.shadowOffsetX = this.options.shadow.x; + ctx.shadowOffsetY = this.options.shadow.y; + } + } + }, { + key: 'disableShadow', + value: function disableShadow(ctx) { + if (this.options.shadow.enabled === true) { + ctx.shadowColor = 'rgba(0,0,0,0)'; + ctx.shadowBlur = 0; + ctx.shadowOffsetX = 0; + ctx.shadowOffsetY = 0; + } } + }]); - addFormatToken(0, ['YY', 2], 0, function () { - return this.year() % 100; - }); + return NodeBase; + })(); - addFormatToken(0, ['YYYY', 4], 0, 'year'); - addFormatToken(0, ['YYYYY', 5], 0, 'year'); - addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); + exports['default'] = NodeBase; + module.exports = exports['default']; - // ALIASES +/***/ }, +/* 66 */ +/***/ function(module, exports, __webpack_require__) { - addUnitAlias('year', 'y'); + 'use strict'; - // PARSING + Object.defineProperty(exports, '__esModule', { + value: true + }); - addRegexToken('Y', matchSigned); - addRegexToken('YY', match1to2, match2); - addRegexToken('YYYY', match1to4, match4); - addRegexToken('YYYYY', match1to6, match6); - addRegexToken('YYYYYY', match1to6, match6); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - addParseToken(['YYYY', 'YYYYY', 'YYYYYY'], YEAR); - addParseToken('YY', function (input, array) { - array[YEAR] = utils_hooks__hooks.parseTwoDigitYear(input); - }); + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - // HELPERS + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - function daysInYear(year) { - return isLeapYear(year) ? 366 : 365; - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - function isLeapYear(year) { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; - } + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - // HOOKS + var _utilCircleImageBase = __webpack_require__(67); - utils_hooks__hooks.parseTwoDigitYear = function (input) { - return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); - }; + var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); - // MOMENTS + var Circle = (function (_CircleImageBase) { + function Circle(options, body, labelModule) { + _classCallCheck(this, Circle); - var getSetYear = makeGetSet('FullYear', false); + _get(Object.getPrototypeOf(Circle.prototype), 'constructor', this).call(this, options, body, labelModule); + } - function getIsLeapYear () { - return isLeapYear(this.year()); - } + _inherits(Circle, _CircleImageBase); - addFormatToken('w', ['ww', 2], 'wo', 'week'); - addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); + _createClass(Circle, [{ + key: 'resize', + value: function resize(ctx, selected) { + if (this.width === undefined) { + var margin = 5; + var textSize = this.labelModule.getTextSize(ctx, selected); + var diameter = Math.max(textSize.width, textSize.height) + 2 * margin; + this.options.size = diameter / 2; - // ALIASES + this.width = diameter; + this.height = diameter; + this.radius = 0.5 * this.width; + } + } + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(ctx, selected); + this.left = x - this.width / 2; + this.top = y - this.height / 2; - addUnitAlias('week', 'w'); - addUnitAlias('isoWeek', 'W'); + this._drawRawCircle(ctx, x, y, selected, hover, this.options.size); - // PARSING + 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; - addRegexToken('w', match1to2); - addRegexToken('ww', match1to2, match2); - addRegexToken('W', match1to2); - addRegexToken('WW', match1to2, match2); + this.updateBoundingBox(x, y); + this.labelModule.draw(ctx, x, y, selected); + } + }, { + 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; + } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + var a = this.width / 2; + var b = this.height / 2; + var w = Math.sin(angle) * a; + var h = Math.cos(angle) * b; + return a * b / Math.sqrt(w * w + h * h); + } + }]); - addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { - week[token.substr(0, 1)] = toInt(input); - }); + return Circle; + })(_utilCircleImageBase2['default']); - // HELPERS + exports['default'] = Circle; + module.exports = exports['default']; - // firstDayOfWeek 0 = sun, 6 = sat - // the day of the week that starts the week - // (usually sunday or monday) - // firstDayOfWeekOfYear 0 = sun, 6 = sat - // the first week is the week that contains the first - // of this day of the week - // (eg. ISO weeks use thursday (4)) - function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { - var end = firstDayOfWeekOfYear - firstDayOfWeek, - daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), - adjustedMoment; +/***/ }, +/* 67 */ +/***/ function(module, exports, __webpack_require__) { + 'use strict'; - if (daysToDayOfWeek > end) { - daysToDayOfWeek -= 7; - } + Object.defineProperty(exports, '__esModule', { + value: true + }); - if (daysToDayOfWeek < end - 7) { - daysToDayOfWeek += 7; - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - adjustedMoment = local__createLocal(mom).add(daysToDayOfWeek, 'd'); - return { - week: Math.ceil(adjustedMoment.dayOfYear() / 7), - year: adjustedMoment.year() - }; - } + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - // LOCALES + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - function localeWeek (mom) { - return weekOfYear(mom, this._week.dow, this._week.doy).week; - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var defaultLocaleWeek = { - dow : 0, // Sunday is the first day of the week. - doy : 6 // The week that contains Jan 1st is the first week of the year. - }; + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - function localeFirstDayOfWeek () { - return this._week.dow; - } + var _utilNodeBase = __webpack_require__(65); - function localeFirstDayOfYear () { - return this._week.doy; - } + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - // MOMENTS + var CircleImageBase = (function (_NodeBase) { + function CircleImageBase(options, body, labelModule) { + _classCallCheck(this, CircleImageBase); - function getSetWeek (input) { - var week = this.localeData().week(this); - return input == null ? week : this.add((input - week) * 7, 'd'); - } + _get(Object.getPrototypeOf(CircleImageBase.prototype), 'constructor', this).call(this, options, body, labelModule); + this.labelOffset = 0; + this.imageLoaded = false; + } - function getSetISOWeek (input) { - var week = weekOfYear(this, 1, 4).week; - return input == null ? week : this.add((input - week) * 7, 'd'); - } + _inherits(CircleImageBase, _NodeBase); - addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); + _createClass(CircleImageBase, [{ + key: '_resizeImage', - // ALIASES + /** + * This function resizes the image by the options size when the image has not yet loaded. If the image has loaded, we + * force the update of the size again. + * + * @private + */ + value: function _resizeImage() { + var force = false; + if (!this.imageObj.width || !this.imageObj.height) { + // undefined or 0 + this.imageLoaded = false; + } else if (this.imageLoaded === false) { + this.imageLoaded = true; + force = true; + } - addUnitAlias('dayOfYear', 'DDD'); + if (!this.width || !this.height || force === true) { + // undefined or 0 + var width, height, ratio; + if (this.imageObj.width && this.imageObj.height) { + // not undefined or 0 + width = 0; + height = 0; + } + if (this.imageObj.width > this.imageObj.height) { + ratio = this.imageObj.width / this.imageObj.height; + width = this.options.size * 2 * ratio || this.imageObj.width; + height = this.options.size * 2 || this.imageObj.height; + } else { + if (this.imageObj.width && this.imageObj.height) { + // not undefined or 0 + ratio = this.imageObj.height / this.imageObj.width; + } else { + ratio = 1; + } + width = this.options.size * 2 || this.imageObj.width; + height = this.options.size * 2 * ratio || this.imageObj.height; + } + this.width = width; + this.height = height; + this.radius = 0.5 * this.width; + } + } + }, { + key: '_drawRawCircle', + value: function _drawRawCircle(ctx, x, y, selected, hover, size) { + var borderWidth = this.options.borderWidth; + var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - // PARSING + ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; - addRegexToken('DDD', match1to3); - addRegexToken('DDDD', match3); - addParseToken(['DDD', 'DDDD'], function (input, array, config) { - config._dayOfYear = toInt(input); - }); + ctx.lineWidth = selected ? selectionLineWidth : borderWidth; + ctx.lineWidth *= this.networkScaleInv; + ctx.lineWidth = Math.min(this.width, ctx.lineWidth); - // HELPERS + ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; + ctx.circle(x, y, size); - //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday - function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { - var d = createUTCDate(year, 0, 1).getUTCDay(); - var daysToAdd; - var dayOfYear; + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); - d = d === 0 ? 7 : d; - weekday = weekday != null ? weekday : firstDayOfWeek; - daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); - dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; + // disable shadows for other elements. + this.disableShadow(ctx); - return { - year : dayOfYear > 0 ? year : year - 1, - dayOfYear : dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear - }; + ctx.stroke(); } + }, { + key: '_drawImageAtPosition', + value: function _drawImageAtPosition(ctx) { + if (this.imageObj.width != 0) { + // draw the image + ctx.globalAlpha = 1; - // MOMENTS + // draw shadow if enabled + this.enableShadow(ctx); + ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height); - function getSetDayOfYear (input) { - var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; - return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); + // disable shadows for other elements. + this.disableShadow(ctx); + } } + }, { + key: '_drawImageLabel', + value: function _drawImageLabel(ctx, x, y, selected) { + var yLabel; + var offset = 0; - // Pick the first defined of two or three arguments. - function defaults(a, b, c) { - if (a != null) { - return a; - } - if (b != null) { - return b; + if (this.height !== undefined) { + offset = this.height * 0.5; + var labelDimensions = this.labelModule.getTextSize(ctx); + if (labelDimensions.lineCount >= 1) { + offset += labelDimensions.height / 2; } - return c; - } + } - function currentDateArray(config) { - var now = new Date(); - if (config._useUTC) { - return [now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()]; - } - return [now.getFullYear(), now.getMonth(), now.getDate()]; - } + yLabel = y + offset; - // convert an array to a date. - // the array should mirror the parameters below - // note: all values past the year are optional and will default to the lowest possible value. - // [year, month, day , hour, minute, second, millisecond] - function configFromArray (config) { - var i, date, input = [], currentDate, yearToUse; + if (this.options.label) { + this.labelOffset = offset; + } + this.labelModule.draw(ctx, x, yLabel, selected, 'hanging'); + } + }]); - if (config._d) { - return; - } + return CircleImageBase; + })(_utilNodeBase2['default']); - currentDate = currentDateArray(config); + exports['default'] = CircleImageBase; + module.exports = exports['default']; - //compute day of the year from weeks and weekdays - if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { - dayOfYearFromWeekInfo(config); - } +/***/ }, +/* 68 */ +/***/ function(module, exports, __webpack_require__) { - //if the day of the year is set, figure out what it is - if (config._dayOfYear) { - yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); + 'use strict'; - if (config._dayOfYear > daysInYear(yearToUse)) { - getParsingFlags(config)._overflowDayOfYear = true; - } + Object.defineProperty(exports, '__esModule', { + value: true + }); - date = createUTCDate(yearToUse, 0, config._dayOfYear); - config._a[MONTH] = date.getUTCMonth(); - config._a[DATE] = date.getUTCDate(); - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // Default to current date. - // * if no year, month, day of month are given, default to today - // * if day of month is given, default month and year - // * if month is given, default only year - // * if year is given, don't default anything - for (i = 0; i < 3 && config._a[i] == null; ++i) { - config._a[i] = input[i] = currentDate[i]; - } + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - // Zero out whatever was not defaulted, including time - for (; i < 7; i++) { - config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - // Check for 24:00:00.000 - if (config._a[HOUR] === 24 && - config._a[MINUTE] === 0 && - config._a[SECOND] === 0 && - config._a[MILLISECOND] === 0) { - config._nextDay = true; - config._a[HOUR] = 0; - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); - // Apply timezone offset from input. The actual utcOffset can be changed - // with parseZone. - if (config._tzm != null) { - config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); - } + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - if (config._nextDay) { - config._a[HOUR] = 24; - } - } + var _utilCircleImageBase = __webpack_require__(67); - function dayOfYearFromWeekInfo(config) { - var w, weekYear, week, weekday, dow, doy, temp; + var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); - w = config._w; - if (w.GG != null || w.W != null || w.E != null) { - dow = 1; - doy = 4; + var CircularImage = (function (_CircleImageBase) { + function CircularImage(options, body, labelModule, imageObj) { + _classCallCheck(this, CircularImage); - // TODO: We need to take the current isoWeekYear, but that depends on - // how we interpret now (local, utc, fixed offset). So create - // a now version of current config (take local/utc/offset flags, and - // create now). - weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(local__createLocal(), 1, 4).year); - week = defaults(w.W, 1); - weekday = defaults(w.E, 1); - } else { - dow = config._locale._week.dow; - doy = config._locale._week.doy; + _get(Object.getPrototypeOf(CircularImage.prototype), 'constructor', this).call(this, options, body, labelModule); + this.imageObj = imageObj; + this._swapToImageResizeWhenImageLoaded = true; + } - weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(local__createLocal(), dow, doy).year); - week = defaults(w.w, 1); + _inherits(CircularImage, _CircleImageBase); - if (w.d != null) { - // weekday -- low day numbers are considered next week - weekday = w.d; - if (weekday < dow) { - ++week; - } - } else if (w.e != null) { - // local weekday -- counting starts from begining of week - weekday = w.e + dow; - } else { - // default to begining of week - weekday = dow; - } + _createClass(CircularImage, [{ + key: 'resize', + value: function resize() { + if (this.imageObj.src === undefined || this.imageObj.width === undefined || this.imageObj.height === undefined) { + if (!this.width) { + var diameter = this.options.size * 2; + this.width = diameter; + this.height = diameter; + this._swapToImageResizeWhenImageLoaded = true; + this.radius = 0.5 * this.width; } - temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); - - config._a[YEAR] = temp.year; - config._dayOfYear = temp.dayOfYear; + } else { + if (this._swapToImageResizeWhenImageLoaded) { + this.width = undefined; + this.height = undefined; + this._swapToImageResizeWhenImageLoaded = false; + } + this._resizeImage(); + } } + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(); - utils_hooks__hooks.ISO_8601 = function () {}; - - // date from string and format string - function configFromStringAndFormat(config) { - // TODO: Move this to another part of the creation flow to prevent circular deps - if (config._f === utils_hooks__hooks.ISO_8601) { - configFromISO(config); - return; - } + this.left = x - this.width / 2; + this.top = y - this.height / 2; - config._a = []; - getParsingFlags(config).empty = true; + var size = Math.min(0.5 * this.height, 0.5 * this.width); - // This array is used to make a Date, either with `new Date` or `Date.UTC` - var string = '' + config._i, - i, parsedInput, tokens, token, skipped, - stringLength = string.length, - totalParsedInputLength = 0; + this._drawRawCircle(ctx, x, y, selected, hover, size); - tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; + ctx.save(); + ctx.circle(x, y, size); + ctx.stroke(); + ctx.clip(); - for (i = 0; i < tokens.length; i++) { - token = tokens[i]; - parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; - if (parsedInput) { - skipped = string.substr(0, string.indexOf(parsedInput)); - if (skipped.length > 0) { - getParsingFlags(config).unusedInput.push(skipped); - } - string = string.slice(string.indexOf(parsedInput) + parsedInput.length); - totalParsedInputLength += parsedInput.length; - } - // don't parse if it's not a known token - if (formatTokenFunctions[token]) { - if (parsedInput) { - getParsingFlags(config).empty = false; - } - else { - getParsingFlags(config).unusedTokens.push(token); - } - addTimeToArrayFromToken(token, parsedInput, config); - } - else if (config._strict && !parsedInput) { - getParsingFlags(config).unusedTokens.push(token); - } - } + this._drawImageAtPosition(ctx); - // add remaining unparsed input length to the string - getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; - if (string.length > 0) { - getParsingFlags(config).unusedInput.push(string); - } + ctx.restore(); - // clear _12h flag if hour is <= 12 - if (getParsingFlags(config).bigHour === true && - config._a[HOUR] <= 12 && - config._a[HOUR] > 0) { - getParsingFlags(config).bigHour = undefined; - } - // handle meridiem - config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); + this._drawImageLabel(ctx, x, y, selected); - configFromArray(config); - checkOverflow(config); + this.updateBoundingBox(x, 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; + 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.labelOffset); + } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + return this._distanceToBorder(angle); + } + }]); + return CircularImage; + })(_utilCircleImageBase2['default']); - function meridiemFixWrap (locale, hour, meridiem) { - var isPm; - - if (meridiem == null) { - // nothing to do - return hour; - } - if (locale.meridiemHour != null) { - return locale.meridiemHour(hour, meridiem); - } else if (locale.isPM != null) { - // Fallback - isPm = locale.isPM(meridiem); - if (isPm && hour < 12) { - hour += 12; - } - if (!isPm && hour === 12) { - hour = 0; - } - return hour; - } else { - // this is not supposed to happen - return hour; - } - } + exports['default'] = CircularImage; + module.exports = exports['default']; - function configFromStringAndArray(config) { - var tempConfig, - bestMoment, +/***/ }, +/* 69 */ +/***/ function(module, exports, __webpack_require__) { - scoreToBeat, - i, - currentScore; + 'use strict'; - if (config._f.length === 0) { - getParsingFlags(config).invalidFormat = true; - config._d = new Date(NaN); - return; - } + Object.defineProperty(exports, '__esModule', { + value: true + }); - for (i = 0; i < config._f.length; i++) { - currentScore = 0; - tempConfig = copyConfig({}, config); - if (config._useUTC != null) { - tempConfig._useUTC = config._useUTC; - } - tempConfig._f = config._f[i]; - configFromStringAndFormat(tempConfig); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - if (!valid__isValid(tempConfig)) { - continue; - } + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - // if there is any input that was not parsed add a penalty for that format - currentScore += getParsingFlags(tempConfig).charsLeftOver; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - //or tokens - currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - getParsingFlags(tempConfig).score = currentScore; + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - if (scoreToBeat == null || currentScore < scoreToBeat) { - scoreToBeat = currentScore; - bestMoment = tempConfig; - } - } + var _utilNodeBase = __webpack_require__(65); - extend(config, bestMoment || tempConfig); - } + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - function configFromObject(config) { - if (config._d) { - return; - } + var Database = (function (_NodeBase) { + function Database(options, body, labelModule) { + _classCallCheck(this, Database); - var i = normalizeObjectUnits(config._i); - config._a = [i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond]; + _get(Object.getPrototypeOf(Database.prototype), 'constructor', this).call(this, options, body, labelModule); + } - configFromArray(config); + _inherits(Database, _NodeBase); + + _createClass(Database, [{ + key: 'resize', + value: function resize(ctx, selected) { + if (this.width === undefined) { + var margin = 5; + var textSize = this.labelModule.getTextSize(ctx, selected); + var size = textSize.width + 2 * margin; + this.width = size; + this.height = size; + this.radius = 0.5 * this.width; + } } + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(ctx, selected); + this.left = x - this.width / 2; + this.top = y - this.height / 2; - function createFromConfig (config) { - var input = config._i, - format = config._f, - res; + var borderWidth = this.options.borderWidth; + var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - config._locale = config._locale || locale_locales__getLocale(config._l); + ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; + ctx.lineWidth = this.selected ? selectionLineWidth : borderWidth; + ctx.lineWidth *= this.networkScaleInv; + ctx.lineWidth = Math.min(this.width, ctx.lineWidth); - if (input === null || (format === undefined && input === '')) { - return valid__createInvalid({nullInput: true}); - } + ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; + ctx.database(x - this.width / 2, y - this.height * 0.5, this.width, this.height); - if (typeof input === 'string') { - config._i = input = config._locale.preparse(input); - } + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); - if (isMoment(input)) { - return new Moment(checkOverflow(input)); - } else if (isArray(format)) { - configFromStringAndArray(config); - } else if (format) { - configFromStringAndFormat(config); - } else if (isDate(input)) { - config._d = input; - } else { - configFromInput(config); - } + // disable shadows for other elements. + this.disableShadow(ctx); - res = new Moment(checkOverflow(config)); - if (res._nextDay) { - // Adding is smart enough around DST - res.add(1, 'd'); - res._nextDay = undefined; - } + ctx.stroke(); - return res; + this.updateBoundingBox(x, y); + + this.labelModule.draw(ctx, x, y, selected); } + }, { + key: 'updateBoundingBox', + value: function updateBoundingBox(x, y) { + this.left = x - this.width * 0.5; + this.top = y - this.height * 0.5; - function configFromInput(config) { - var input = config._i; - if (input === undefined) { - config._d = new Date(); - } else if (isDate(input)) { - config._d = new Date(+input); - } else if (typeof input === 'string') { - configFromString(config); - } else if (isArray(input)) { - config._a = map(input.slice(0), function (obj) { - return parseInt(obj, 10); - }); - configFromArray(config); - } else if (typeof(input) === 'object') { - configFromObject(config); - } else if (typeof(input) === 'number') { - // from milliseconds - config._d = new Date(input); - } else { - utils_hooks__hooks.createFromInputFallback(config); - } + this.boundingBox.left = this.left; + this.boundingBox.top = this.top; + this.boundingBox.bottom = this.top + this.height; + this.boundingBox.right = this.left + this.width; + } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + var a = this.width / 2; + var b = this.height / 2; + var w = Math.sin(angle) * a; + var h = Math.cos(angle) * b; + return a * b / Math.sqrt(w * w + h * h); } + }]); - function createLocalOrUTC (input, format, locale, strict, isUTC) { - var c = {}; + return Database; + })(_utilNodeBase2['default']); - if (typeof(locale) === 'boolean') { - strict = locale; - locale = undefined; - } - // object construction must be done this way. - // https://github.com/moment/moment/issues/1423 - c._isAMomentObject = true; - c._useUTC = c._isUTC = isUTC; - c._l = locale; - c._i = input; - c._f = format; - c._strict = strict; + exports['default'] = Database; + module.exports = exports['default']; - return createFromConfig(c); - } +/***/ }, +/* 70 */ +/***/ function(module, exports, __webpack_require__) { - function local__createLocal (input, format, locale, strict) { - return createLocalOrUTC(input, format, locale, strict, false); - } + 'use strict'; - var prototypeMin = deprecate( - 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548', - function () { - var other = local__createLocal.apply(null, arguments); - return other < this ? this : other; - } - ); + Object.defineProperty(exports, '__esModule', { + value: true + }); - var prototypeMax = deprecate( - 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548', - function () { - var other = local__createLocal.apply(null, arguments); - return other > this ? this : other; - } - ); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // Pick a moment m from moments so that m[fn](other) is true for all - // other. This relies on the function fn to be transitive. - // - // moments should either be an array of moment objects or an array, whose - // first element is an array of moment objects. - function pickBy(fn, moments) { - var res, i; - if (moments.length === 1 && isArray(moments[0])) { - moments = moments[0]; - } - if (!moments.length) { - return local__createLocal(); - } - res = moments[0]; - for (i = 1; i < moments.length; ++i) { - if (moments[i][fn](res)) { - res = moments[i]; - } - } - return res; - } + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - // TODO: Use [].sort instead? - function min () { - var args = [].slice.call(arguments, 0); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - return pickBy('isBefore', args); - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - function max () { - var args = [].slice.call(arguments, 0); + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - return pickBy('isAfter', args); - } + var _utilShapeBase = __webpack_require__(71); - function Duration (duration) { - var normalizedInput = normalizeObjectUnits(duration), - years = normalizedInput.year || 0, - quarters = normalizedInput.quarter || 0, - months = normalizedInput.month || 0, - weeks = normalizedInput.week || 0, - days = normalizedInput.day || 0, - hours = normalizedInput.hour || 0, - minutes = normalizedInput.minute || 0, - seconds = normalizedInput.second || 0, - milliseconds = normalizedInput.millisecond || 0; + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); - // representation for dateAddRemove - this._milliseconds = +milliseconds + - seconds * 1e3 + // 1000 - minutes * 6e4 + // 1000 * 60 - hours * 36e5; // 1000 * 60 * 60 - // Because of dateAddRemove treats 24 hours as different from a - // day when working around DST, we need to store them separately - this._days = +days + - weeks * 7; - // It is impossible translate months into days without knowing - // which months you are are talking about, so we have to store - // it separately. - this._months = +months + - quarters * 3 + - years * 12; + var Diamond = (function (_ShapeBase) { + function Diamond(options, body, labelModule) { + _classCallCheck(this, Diamond); - this._data = {}; + _get(Object.getPrototypeOf(Diamond.prototype), 'constructor', this).call(this, options, body, labelModule); + } - this._locale = locale_locales__getLocale(); + _inherits(Diamond, _ShapeBase); - this._bubble(); + _createClass(Diamond, [{ + key: 'resize', + value: function resize(ctx) { + this._resizeShape(); } - - function isDuration (obj) { - return obj instanceof Duration; + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this._drawShape(ctx, 'diamond', 4, x, y, selected, hover); } - - function offset (token, separator) { - addFormatToken(token, 0, 0, function () { - var offset = this.utcOffset(); - var sign = '+'; - if (offset < 0) { - offset = -offset; - sign = '-'; - } - return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); - }); + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + return this._distanceToBorder(angle); } + }]); - offset('Z', ':'); - offset('ZZ', ''); - - // PARSING + return Diamond; + })(_utilShapeBase2['default']); - addRegexToken('Z', matchOffset); - addRegexToken('ZZ', matchOffset); - addParseToken(['Z', 'ZZ'], function (input, array, config) { - config._useUTC = true; - config._tzm = offsetFromString(input); - }); + exports['default'] = Diamond; + module.exports = exports['default']; - // HELPERS +/***/ }, +/* 71 */ +/***/ function(module, exports, __webpack_require__) { - // timezone chunker - // '+10:00' > ['10', '00'] - // '-1530' > ['-15', '30'] - var chunkOffset = /([\+\-]|\d\d)/gi; + 'use strict'; - function offsetFromString(string) { - var matches = ((string || '').match(matchOffset) || []); - var chunk = matches[matches.length - 1] || []; - var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; - var minutes = +(parts[1] * 60) + toInt(parts[2]); + Object.defineProperty(exports, '__esModule', { + value: true + }); - return parts[0] === '+' ? minutes : -minutes; - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // Return a moment from input, that is local/utc/zone equivalent to model. - function cloneWithOffset(input, model) { - var res, diff; - if (model._isUTC) { - res = model.clone(); - diff = (isMoment(input) || isDate(input) ? +input : +local__createLocal(input)) - (+res); - // Use low-level api, because this fn is low-level api. - res._d.setTime(+res._d + diff); - utils_hooks__hooks.updateOffset(res, false); - return res; - } else { - return local__createLocal(input).local(); - } - return model._isUTC ? local__createLocal(input).zone(model._offset || 0) : local__createLocal(input).local(); - } + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - function getDateOffset (m) { - // On Firefox.24 Date#getTimezoneOffset returns a floating point. - // https://github.com/moment/moment/pull/1871 - return -Math.round(m._d.getTimezoneOffset() / 15) * 15; - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - // HOOKS + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - // This function will be called whenever a moment is mutated. - // It is intended to keep the offset in sync with the timezone. - utils_hooks__hooks.updateOffset = function () {}; + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - // MOMENTS + var _utilNodeBase = __webpack_require__(65); - // keepLocalTime = true means only change the timezone, without - // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> - // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset - // +0200, so we adjust the time as needed, to be valid. - // - // Keeping the time actually adds/subtracts (one hour) - // from the actual represented time. That is why we call updateOffset - // a second time. In case it wants us to change the offset again - // _changeInProgress == true case, then we have to adjust, because - // there is no such time in the given timezone. - function getSetOffset (input, keepLocalTime) { - var offset = this._offset || 0, - localAdjust; - if (input != null) { - if (typeof input === 'string') { - input = offsetFromString(input); - } - if (Math.abs(input) < 16) { - input = input * 60; - } - if (!this._isUTC && keepLocalTime) { - localAdjust = getDateOffset(this); - } - this._offset = input; - this._isUTC = true; - if (localAdjust != null) { - this.add(localAdjust, 'm'); - } - if (offset !== input) { - if (!keepLocalTime || this._changeInProgress) { - add_subtract__addSubtract(this, create__createDuration(input - offset, 'm'), 1, false); - } else if (!this._changeInProgress) { - this._changeInProgress = true; - utils_hooks__hooks.updateOffset(this, true); - this._changeInProgress = null; - } - } - return this; - } else { - return this._isUTC ? offset : getDateOffset(this); - } - } + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - function getSetZone (input, keepLocalTime) { - if (input != null) { - if (typeof input !== 'string') { - input = -input; - } + var ShapeBase = (function (_NodeBase) { + function ShapeBase(options, body, labelModule) { + _classCallCheck(this, ShapeBase); - this.utcOffset(input, keepLocalTime); + _get(Object.getPrototypeOf(ShapeBase.prototype), 'constructor', this).call(this, options, body, labelModule); + } - return this; - } else { - return -this.utcOffset(); - } - } + _inherits(ShapeBase, _NodeBase); - function setOffsetToUTC (keepLocalTime) { - return this.utcOffset(0, keepLocalTime); + _createClass(ShapeBase, [{ + key: '_resizeShape', + value: function _resizeShape() { + if (this.width === undefined) { + var size = 2 * this.options.size; + this.width = size; + this.height = size; + this.radius = 0.5 * this.width; + } } + }, { + key: '_drawShape', + value: function _drawShape(ctx, shape, sizeMultiplier, x, y, selected, hover) { + this._resizeShape(); - function setOffsetToLocal (keepLocalTime) { - if (this._isUTC) { - this.utcOffset(0, keepLocalTime); - this._isUTC = false; + this.left = x - this.width / 2; + this.top = y - this.height / 2; - if (keepLocalTime) { - this.subtract(getDateOffset(this), 'm'); - } - } - return this; - } + var borderWidth = this.options.borderWidth; + var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - function setOffsetToParsedOffset () { - if (this._tzm) { - this.utcOffset(this._tzm); - } else if (typeof this._i === 'string') { - this.utcOffset(offsetFromString(this._i)); - } - return this; - } + ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; + ctx.lineWidth = selected ? selectionLineWidth : borderWidth; + ctx.lineWidth /= this.body.view.scale; + ctx.lineWidth = Math.min(this.width, ctx.lineWidth); + ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; + ctx[shape](x, y, this.options.size); - function hasAlignedHourOffset (input) { - if (!input) { - input = 0; - } - else { - input = local__createLocal(input).utcOffset(); - } + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); - return (this.utcOffset() - input) % 60 === 0; - } + // disable shadows for other elements. + this.disableShadow(ctx); - function isDaylightSavingTime () { - return ( - this.utcOffset() > this.clone().month(0).utcOffset() || - this.utcOffset() > this.clone().month(5).utcOffset() - ); - } + ctx.stroke(); - function isDaylightSavingTimeShifted () { - if (this._a) { - var other = this._isUTC ? create_utc__createUTC(this._a) : local__createLocal(this._a); - return this.isValid() && compareArrays(this._a, other.toArray()) > 0; - } + if (this.options.label !== undefined) { + var yLabel = y + 0.5 * this.height + 3; // the + 3 is to offset it a bit below the node. + this.labelModule.draw(ctx, x, yLabel, selected, 'hanging'); + } - return false; + this.updateBoundingBox(x, 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; - function isLocal () { - return !this._isUTC; + if (this.options.label !== undefined) { + 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 + 3); + } } + }]); - function isUtcOffset () { - return this._isUTC; - } + return ShapeBase; + })(_utilNodeBase2['default']); - function isUtc () { - return this._isUTC && this._offset === 0; - } + exports['default'] = ShapeBase; + module.exports = exports['default']; - var aspNetRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/; +/***/ }, +/* 72 */ +/***/ function(module, exports, __webpack_require__) { - // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html - // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere - var create__isoRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/; + 'use strict'; - function create__createDuration (input, key) { - var duration = input, - // matching against regexp is expensive, do it on demand - match = null, - sign, - ret, - diffRes; + Object.defineProperty(exports, '__esModule', { + value: true + }); - if (isDuration(input)) { - duration = { - ms : input._milliseconds, - d : input._days, - M : input._months - }; - } else if (typeof input === 'number') { - duration = {}; - if (key) { - duration[key] = input; - } else { - duration.milliseconds = input; - } - } else if (!!(match = aspNetRegex.exec(input))) { - sign = (match[1] === '-') ? -1 : 1; - duration = { - y : 0, - d : toInt(match[DATE]) * sign, - h : toInt(match[HOUR]) * sign, - m : toInt(match[MINUTE]) * sign, - s : toInt(match[SECOND]) * sign, - ms : toInt(match[MILLISECOND]) * sign - }; - } else if (!!(match = create__isoRegex.exec(input))) { - sign = (match[1] === '-') ? -1 : 1; - duration = { - y : parseIso(match[2], sign), - M : parseIso(match[3], sign), - d : parseIso(match[4], sign), - h : parseIso(match[5], sign), - m : parseIso(match[6], sign), - s : parseIso(match[7], sign), - w : parseIso(match[8], sign) - }; - } else if (duration == null) {// checks for null or undefined - duration = {}; - } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { - diffRes = momentsDifference(local__createLocal(duration.from), local__createLocal(duration.to)); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - duration = {}; - duration.ms = diffRes.milliseconds; - duration.M = diffRes.months; - } + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - ret = new Duration(duration); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - if (isDuration(input) && hasOwnProp(input, '_locale')) { - ret._locale = input._locale; - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - return ret; - } + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - create__createDuration.fn = Duration.prototype; + var _utilShapeBase = __webpack_require__(71); - function parseIso (inp, sign) { - // We'd normally use ~~inp for this, but unfortunately it also - // converts floats to ints. - // inp may be undefined, so careful calling replace on it. - var res = inp && parseFloat(inp.replace(',', '.')); - // apply sign while we're at it - return (isNaN(res) ? 0 : res) * sign; - } + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); - function positiveMomentsDifference(base, other) { - var res = {milliseconds: 0, months: 0}; + var Dot = (function (_ShapeBase) { + function Dot(options, body, labelModule) { + _classCallCheck(this, Dot); - res.months = other.month() - base.month() + - (other.year() - base.year()) * 12; - if (base.clone().add(res.months, 'M').isAfter(other)) { - --res.months; - } + _get(Object.getPrototypeOf(Dot.prototype), 'constructor', this).call(this, options, body, labelModule); + } - res.milliseconds = +other - +(base.clone().add(res.months, 'M')); + _inherits(Dot, _ShapeBase); - return res; + _createClass(Dot, [{ + key: 'resize', + value: function resize(ctx) { + this._resizeShape(); + } + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this._drawShape(ctx, 'circle', 2, x, y, selected, hover); + } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + return this.options.size + this.options.borderWidth; } + }]); - function momentsDifference(base, other) { - var res; - other = cloneWithOffset(other, base); - if (base.isBefore(other)) { - res = positiveMomentsDifference(base, other); - } else { - res = positiveMomentsDifference(other, base); - res.milliseconds = -res.milliseconds; - res.months = -res.months; - } + return Dot; + })(_utilShapeBase2['default']); - return res; - } + exports['default'] = Dot; + module.exports = exports['default']; - function createAdder(direction, name) { - return function (val, period) { - var dur, tmp; - //invert the arguments, but complain about it - if (period !== null && !isNaN(+period)) { - deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).'); - tmp = val; val = period; period = tmp; - } +/***/ }, +/* 73 */ +/***/ function(module, exports, __webpack_require__) { - val = typeof val === 'string' ? +val : val; - dur = create__createDuration(val, period); - add_subtract__addSubtract(this, dur, direction); - return this; - }; - } + 'use strict'; - function add_subtract__addSubtract (mom, duration, isAdding, updateOffset) { - var milliseconds = duration._milliseconds, - days = duration._days, - months = duration._months; - updateOffset = updateOffset == null ? true : updateOffset; + Object.defineProperty(exports, '__esModule', { + value: true + }); - if (milliseconds) { - mom._d.setTime(+mom._d + milliseconds * isAdding); - } - if (days) { - get_set__set(mom, 'Date', get_set__get(mom, 'Date') + days * isAdding); - } - if (months) { - setMonth(mom, get_set__get(mom, 'Month') + months * isAdding); - } - if (updateOffset) { - utils_hooks__hooks.updateOffset(mom, days || months); - } - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var add_subtract__add = createAdder(1, 'add'); - var add_subtract__subtract = createAdder(-1, 'subtract'); + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - function moment_calendar__calendar (time) { - // We want to compare the start of today, vs this. - // Getting start-of-today depends on whether we're local/utc/offset or not. - var now = time || local__createLocal(), - sod = cloneWithOffset(now, this).startOf('day'), - diff = this.diff(sod, 'days', true), - format = diff < -6 ? 'sameElse' : - diff < -1 ? 'lastWeek' : - diff < 0 ? 'lastDay' : - diff < 1 ? 'sameDay' : - diff < 2 ? 'nextDay' : - diff < 7 ? 'nextWeek' : 'sameElse'; - return this.format(this.localeData().calendar(format, this, local__createLocal(now))); - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - function clone () { - return new Moment(this); - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - function isAfter (input, units) { - var inputMs; - units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); - if (units === 'millisecond') { - input = isMoment(input) ? input : local__createLocal(input); - return +this > +input; - } else { - inputMs = isMoment(input) ? +input : +local__createLocal(input); - return inputMs < +this.clone().startOf(units); - } - } + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - function isBefore (input, units) { - var inputMs; - units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); - if (units === 'millisecond') { - input = isMoment(input) ? input : local__createLocal(input); - return +this < +input; - } else { - inputMs = isMoment(input) ? +input : +local__createLocal(input); - return +this.clone().endOf(units) < inputMs; - } - } + var _utilNodeBase = __webpack_require__(65); - function isBetween (from, to, units) { - return this.isAfter(from, units) && this.isBefore(to, units); - } + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - function isSame (input, units) { - var inputMs; - units = normalizeUnits(units || 'millisecond'); - if (units === 'millisecond') { - input = isMoment(input) ? input : local__createLocal(input); - return +this === +input; - } else { - inputMs = +local__createLocal(input); - return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units)); - } - } + var Ellipse = (function (_NodeBase) { + function Ellipse(options, body, labelModule) { + _classCallCheck(this, Ellipse); - function absFloor (number) { - if (number < 0) { - return Math.ceil(number); - } else { - return Math.floor(number); - } - } + _get(Object.getPrototypeOf(Ellipse.prototype), 'constructor', this).call(this, options, body, labelModule); + } - function diff (input, units, asFloat) { - var that = cloneWithOffset(input, this), - zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4, - delta, output; + _inherits(Ellipse, _NodeBase); - units = normalizeUnits(units); + _createClass(Ellipse, [{ + key: 'resize', + value: function resize(ctx, selected) { + if (this.width === undefined) { + var textSize = this.labelModule.getTextSize(ctx, selected); - if (units === 'year' || units === 'month' || units === 'quarter') { - output = monthDiff(this, that); - if (units === 'quarter') { - output = output / 3; - } else if (units === 'year') { - output = output / 12; - } - } else { - delta = this - that; - output = units === 'second' ? delta / 1e3 : // 1000 - units === 'minute' ? delta / 6e4 : // 1000 * 60 - units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60 - units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst - units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst - delta; + this.width = textSize.width * 1.5; + this.height = textSize.height * 2; + if (this.width < this.height) { + this.width = this.height; } - return asFloat ? output : absFloor(output); + this.radius = 0.5 * this.width; + } } + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(ctx, selected); + this.left = x - this.width * 0.5; + this.top = y - this.height * 0.5; - function monthDiff (a, b) { - // difference in months - var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), - // b is in (anchor - 1 month, anchor + 1 month) - anchor = a.clone().add(wholeMonthDiff, 'months'), - anchor2, adjust; - - if (b - anchor < 0) { - anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); - // linear across the month - adjust = (b - anchor) / (anchor - anchor2); - } else { - anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); - // linear across the month - adjust = (b - anchor) / (anchor2 - anchor); - } + var borderWidth = this.options.borderWidth; + var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - return -(wholeMonthDiff + adjust); - } + ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; - utils_hooks__hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; + ctx.lineWidth = selected ? selectionLineWidth : borderWidth; + ctx.lineWidth /= this.body.view.scale; + ctx.lineWidth = Math.min(this.width, ctx.lineWidth); - function toString () { - return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); - } + ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; + ctx.ellipse(this.left, this.top, this.width, this.height); - function moment_format__toISOString () { - var m = this.clone().utc(); - if (0 < m.year() && m.year() <= 9999) { - if ('function' === typeof Date.prototype.toISOString) { - // native implementation is ~50x faster, use it when we can - return this.toDate().toISOString(); - } else { - return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); - } - } else { - return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); - } - } + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); - function format (inputString) { - var output = formatMoment(this, inputString || utils_hooks__hooks.defaultFormat); - return this.localeData().postformat(output); - } + // disable shadows for other elements. + this.disableShadow(ctx); - function from (time, withoutSuffix) { - if (!this.isValid()) { - return this.localeData().invalidDate(); - } - return create__createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); - } + ctx.stroke(); - function fromNow (withoutSuffix) { - return this.from(local__createLocal(), withoutSuffix); + this.updateBoundingBox(x, y); + this.labelModule.draw(ctx, x, y, selected); } + }, { + key: 'updateBoundingBox', + value: function updateBoundingBox(x, y) { + this.left = x - this.width * 0.5; + this.top = y - this.height * 0.5; - function to (time, withoutSuffix) { - if (!this.isValid()) { - return this.localeData().invalidDate(); - } - return create__createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix); + this.boundingBox.left = this.left; + this.boundingBox.top = this.top; + this.boundingBox.bottom = this.top + this.height; + this.boundingBox.right = this.left + this.width; } - - function toNow (withoutSuffix) { - return this.to(local__createLocal(), withoutSuffix); + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + var a = this.width * 0.5; + var b = this.height * 0.5; + var w = Math.sin(angle) * a; + var h = Math.cos(angle) * b; + return a * b / Math.sqrt(w * w + h * h); } + }]); - function locale (key) { - var newLocaleData; + return Ellipse; + })(_utilNodeBase2['default']); - if (key === undefined) { - return this._locale._abbr; - } else { - newLocaleData = locale_locales__getLocale(key); - if (newLocaleData != null) { - this._locale = newLocaleData; - } - return this; - } - } + exports['default'] = Ellipse; + module.exports = exports['default']; - var lang = deprecate( - 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', - function (key) { - if (key === undefined) { - return this.localeData(); - } else { - return this.locale(key); - } - } - ); +/***/ }, +/* 74 */ +/***/ function(module, exports, __webpack_require__) { - function localeData () { - return this._locale; - } + 'use strict'; - function startOf (units) { - units = normalizeUnits(units); - // the following switch intentionally omits break keywords - // to utilize falling through the cases. - switch (units) { - case 'year': - this.month(0); - /* falls through */ - case 'quarter': - case 'month': - this.date(1); - /* falls through */ - case 'week': - case 'isoWeek': - case 'day': - this.hours(0); - /* falls through */ - case 'hour': - this.minutes(0); - /* falls through */ - case 'minute': - this.seconds(0); - /* falls through */ - case 'second': - this.milliseconds(0); - } + Object.defineProperty(exports, '__esModule', { + value: true + }); - // weeks are a special case - if (units === 'week') { - this.weekday(0); - } - if (units === 'isoWeek') { - this.isoWeekday(1); - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // quarters are also special - if (units === 'quarter') { - this.month(Math.floor(this.month() / 3) * 3); - } + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - return this; - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - function endOf (units) { - units = normalizeUnits(units); - if (units === undefined || units === 'millisecond') { - return this; - } - return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - function to_type__valueOf () { - return +this._d - ((this._offset || 0) * 60000); - } + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - function unix () { - return Math.floor(+this / 1000); - } + var _utilNodeBase = __webpack_require__(65); - function toDate () { - return this._offset ? new Date(+this) : this._d; - } + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - function toArray () { - var m = this; - return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; - } + var Icon = (function (_NodeBase) { + function Icon(options, body, labelModule) { + _classCallCheck(this, Icon); - function moment_valid__isValid () { - return valid__isValid(this); - } + _get(Object.getPrototypeOf(Icon.prototype), 'constructor', this).call(this, options, body, labelModule); + } - function parsingFlags () { - return extend({}, getParsingFlags(this)); - } + _inherits(Icon, _NodeBase); - function invalidAt () { - return getParsingFlags(this).overflow; + _createClass(Icon, [{ + key: 'resize', + value: function resize(ctx) { + if (this.width === undefined) { + var margin = 5; + var iconSize = { + width: Number(this.options.icon.size), + height: Number(this.options.icon.size) + }; + this.width = iconSize.width + 2 * margin; + this.height = iconSize.height + 2 * margin; + this.radius = 0.5 * this.width; + } } + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(ctx); + this.options.icon.size = this.options.icon.size || 50; - addFormatToken(0, ['gg', 2], 0, function () { - return this.weekYear() % 100; - }); + this.left = x - this.width * 0.5; + this.top = y - this.height * 0.5; + this._icon(ctx, x, y, selected); - addFormatToken(0, ['GG', 2], 0, function () { - return this.isoWeekYear() % 100; - }); + if (this.options.label !== undefined) { + var iconTextSpacing = 5; + this.labelModule.draw(ctx, x, y + this.height * 0.5 + iconTextSpacing, selected); + } - function addWeekYearFormatToken (token, getter) { - addFormatToken(0, [token, token.length], 0, getter); + this.updateBoundingBox(x, y); } + }, { + key: 'updateBoundingBox', + value: function updateBoundingBox(x, y) { + this.boundingBox.top = y - this.options.icon.size * 0.5; + this.boundingBox.left = x - this.options.icon.size * 0.5; + this.boundingBox.right = x + this.options.icon.size * 0.5; + this.boundingBox.bottom = y + this.options.icon.size * 0.5; - addWeekYearFormatToken('gggg', 'weekYear'); - addWeekYearFormatToken('ggggg', 'weekYear'); - addWeekYearFormatToken('GGGG', 'isoWeekYear'); - addWeekYearFormatToken('GGGGG', 'isoWeekYear'); + if (this.options.label !== undefined) { + var iconTextSpacing = 5; + 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 + iconTextSpacing); + } + } + }, { + key: '_icon', + value: function _icon(ctx, x, y, selected) { + var iconSize = Number(this.options.icon.size); - // ALIASES + if (this.options.icon.code !== undefined) { + ctx.font = (selected ? 'bold ' : '') + iconSize + 'px ' + this.options.icon.face; - addUnitAlias('weekYear', 'gg'); - addUnitAlias('isoWeekYear', 'GG'); + // draw icon + ctx.fillStyle = this.options.icon.color || 'black'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; - // PARSING + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fillText(this.options.icon.code, x, y); - addRegexToken('G', matchSigned); - addRegexToken('g', matchSigned); - addRegexToken('GG', match1to2, match2); - addRegexToken('gg', match1to2, match2); - addRegexToken('GGGG', match1to4, match4); - addRegexToken('gggg', match1to4, match4); - addRegexToken('GGGGG', match1to6, match6); - addRegexToken('ggggg', match1to6, match6); + // disable shadows for other elements. + this.disableShadow(ctx); + } else { + console.error('When using the icon shape, you need to define the code in the icon options object. This can be done per node or globally.'); + } + } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + this._distanceToBorder(angle); + } + }]); - addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { - week[token.substr(0, 2)] = toInt(input); - }); + return Icon; + })(_utilNodeBase2['default']); - addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { - week[token] = utils_hooks__hooks.parseTwoDigitYear(input); - }); + exports['default'] = Icon; + module.exports = exports['default']; - // HELPERS +/***/ }, +/* 75 */ +/***/ function(module, exports, __webpack_require__) { - function weeksInYear(year, dow, doy) { - return weekOfYear(local__createLocal([year, 11, 31 + dow - doy]), dow, doy).week; - } + 'use strict'; - // MOMENTS + Object.defineProperty(exports, '__esModule', { + value: true + }); - function getSetWeekYear (input) { - var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year; - return input == null ? year : this.add((input - year), 'y'); - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - function getSetISOWeekYear (input) { - var year = weekOfYear(this, 1, 4).year; - return input == null ? year : this.add((input - year), 'y'); - } + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - function getISOWeeksInYear () { - return weeksInYear(this.year(), 1, 4); - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - function getWeeksInYear () { - var weekInfo = this.localeData()._week; - return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - addFormatToken('Q', 0, 0, 'quarter'); + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - // ALIASES + var _utilCircleImageBase = __webpack_require__(67); - addUnitAlias('quarter', 'Q'); + var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); - // PARSING + var Image = (function (_CircleImageBase) { + function Image(options, body, labelModule, imageObj) { + _classCallCheck(this, Image); - addRegexToken('Q', match1); - addParseToken('Q', function (input, array) { - array[MONTH] = (toInt(input) - 1) * 3; - }); + _get(Object.getPrototypeOf(Image.prototype), 'constructor', this).call(this, options, body, labelModule); + this.imageObj = imageObj; + } - // MOMENTS + _inherits(Image, _CircleImageBase); - function getSetQuarter (input) { - return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); + _createClass(Image, [{ + key: 'resize', + value: function resize() { + this._resizeImage(); } + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(); + this.left = x - this.width / 2; + this.top = y - this.height / 2; - addFormatToken('D', ['DD', 2], 'Do', 'date'); + this._drawImageAtPosition(ctx); - // ALIASES + this._drawImageLabel(ctx, x, y, selected || hover); - addUnitAlias('date', 'D'); + this.updateBoundingBox(x, y); + } + }, { + key: 'updateBoundingBox', + value: function updateBoundingBox(x, y) { + this.left = x - this.width / 2; + this.top = y - this.height / 2; - // PARSING + this.boundingBox.top = this.top; + this.boundingBox.left = this.left; + this.boundingBox.right = this.left + this.width; + this.boundingBox.bottom = this.top + this.height; - addRegexToken('D', match1to2); - addRegexToken('DD', match1to2, match2); - addRegexToken('Do', function (isStrict, locale) { - return isStrict ? locale._ordinalParse : locale._ordinalParseLenient; - }); + if (this.options.label !== undefined) { + 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.labelOffset); + } + } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + var a = this.width / 2; + var b = this.height / 2; + var w = Math.sin(angle) * a; + var h = Math.cos(angle) * b; + return a * b / Math.sqrt(w * w + h * h); + } + }]); - addParseToken(['D', 'DD'], DATE); - addParseToken('Do', function (input, array) { - array[DATE] = toInt(input.match(match1to2)[0], 10); - }); + return Image; + })(_utilCircleImageBase2['default']); - // MOMENTS + exports['default'] = Image; + module.exports = exports['default']; - var getSetDayOfMonth = makeGetSet('Date', true); +/***/ }, +/* 76 */ +/***/ function(module, exports, __webpack_require__) { - addFormatToken('d', 0, 'do', 'day'); + 'use strict'; - addFormatToken('dd', 0, 0, function (format) { - return this.localeData().weekdaysMin(this, format); - }); + Object.defineProperty(exports, '__esModule', { + value: true + }); - addFormatToken('ddd', 0, 0, function (format) { - return this.localeData().weekdaysShort(this, format); - }); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - addFormatToken('dddd', 0, 0, function (format) { - return this.localeData().weekdays(this, format); - }); + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - addFormatToken('e', 0, 0, 'weekday'); - addFormatToken('E', 0, 0, 'isoWeekday'); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - // ALIASES + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - addUnitAlias('day', 'd'); - addUnitAlias('weekday', 'e'); - addUnitAlias('isoWeekday', 'E'); + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - // PARSING + var _utilShapeBase = __webpack_require__(71); - addRegexToken('d', match1to2); - addRegexToken('e', match1to2); - addRegexToken('E', match1to2); - addRegexToken('dd', matchWord); - addRegexToken('ddd', matchWord); - addRegexToken('dddd', matchWord); + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); - addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config) { - var weekday = config._locale.weekdaysParse(input); - // if we didn't get a weekday name, mark the date as invalid - if (weekday != null) { - week.d = weekday; - } else { - getParsingFlags(config).invalidWeekday = input; - } - }); + var Square = (function (_ShapeBase) { + function Square(options, body, labelModule) { + _classCallCheck(this, Square); - addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { - week[token] = toInt(input); - }); + _get(Object.getPrototypeOf(Square.prototype), 'constructor', this).call(this, options, body, labelModule); + } - // HELPERS + _inherits(Square, _ShapeBase); - function parseWeekday(input, locale) { - if (typeof input === 'string') { - if (!isNaN(input)) { - input = parseInt(input, 10); - } - else { - input = locale.weekdaysParse(input); - if (typeof input !== 'number') { - return null; - } - } - } - return input; + _createClass(Square, [{ + key: 'resize', + value: function resize() { + this._resizeShape(); } - - // LOCALES - - var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); - function localeWeekdays (m) { - return this._weekdays[m.day()]; + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this._drawShape(ctx, 'square', 2, x, y, selected, hover); } - - var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); - function localeWeekdaysShort (m) { - return this._weekdaysShort[m.day()]; + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + return this._distanceToBorder(angle); } + }]); - var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); - function localeWeekdaysMin (m) { - return this._weekdaysMin[m.day()]; - } + return Square; + })(_utilShapeBase2['default']); - function localeWeekdaysParse (weekdayName) { - var i, mom, regex; + exports['default'] = Square; + module.exports = exports['default']; - if (!this._weekdaysParse) { - this._weekdaysParse = []; - } +/***/ }, +/* 77 */ +/***/ function(module, exports, __webpack_require__) { - for (i = 0; i < 7; i++) { - // make the regex if we don't have it already - if (!this._weekdaysParse[i]) { - mom = local__createLocal([2000, 1]).day(i); - regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); - this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); - } - // test the regex - if (this._weekdaysParse[i].test(weekdayName)) { - return i; - } - } - } + 'use strict'; - // MOMENTS + Object.defineProperty(exports, '__esModule', { + value: true + }); - function getSetDayOfWeek (input) { - var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); - if (input != null) { - input = parseWeekday(input, this.localeData()); - return this.add(input - day, 'd'); - } else { - return day; - } - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - function getSetLocaleDayOfWeek (input) { - var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; - return input == null ? weekday : this.add(input - weekday, 'd'); - } + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - function getSetISODayOfWeek (input) { - // behaves the same as moment#day except - // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) - // as a setter, sunday should belong to the previous week. - return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - addFormatToken('H', ['HH', 2], 0, 'hour'); - addFormatToken('h', ['hh', 2], 0, function () { - return this.hours() % 12 || 12; - }); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - function meridiem (token, lowercase) { - addFormatToken(token, 0, 0, function () { - return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); - }); - } + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - meridiem('a', true); - meridiem('A', false); + var _utilShapeBase = __webpack_require__(71); - // ALIASES + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); - addUnitAlias('hour', 'h'); + var Star = (function (_ShapeBase) { + function Star(options, body, labelModule) { + _classCallCheck(this, Star); - // PARSING + _get(Object.getPrototypeOf(Star.prototype), 'constructor', this).call(this, options, body, labelModule); + } - function matchMeridiem (isStrict, locale) { - return locale._meridiemParse; + _inherits(Star, _ShapeBase); + + _createClass(Star, [{ + key: 'resize', + value: function resize(ctx) { + this._resizeShape(); + } + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this._drawShape(ctx, 'star', 4, x, y, selected, hover); + } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + return this._distanceToBorder(angle); } + }]); - addRegexToken('a', matchMeridiem); - addRegexToken('A', matchMeridiem); - addRegexToken('H', match1to2); - addRegexToken('h', match1to2); - addRegexToken('HH', match1to2, match2); - addRegexToken('hh', match1to2, match2); + return Star; + })(_utilShapeBase2['default']); - addParseToken(['H', 'HH'], HOUR); - addParseToken(['a', 'A'], function (input, array, config) { - config._isPm = config._locale.isPM(input); - config._meridiem = input; - }); - addParseToken(['h', 'hh'], function (input, array, config) { - array[HOUR] = toInt(input); - getParsingFlags(config).bigHour = true; - }); + exports['default'] = Star; + module.exports = exports['default']; - // LOCALES +/***/ }, +/* 78 */ +/***/ function(module, exports, __webpack_require__) { - function localeIsPM (input) { - // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays - // Using charAt should be more compatible. - return ((input + '').toLowerCase().charAt(0) === 'p'); - } + 'use strict'; - var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; - function localeMeridiem (hours, minutes, isLower) { - if (hours > 11) { - return isLower ? 'pm' : 'PM'; - } else { - return isLower ? 'am' : 'AM'; - } - } + Object.defineProperty(exports, '__esModule', { + value: true + }); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // MOMENTS + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - // Setting the hour should keep the time, because the user explicitly - // specified which hour he wants. So trying to maintain the same hour (in - // a new timezone) makes sense. Adding/subtracting hours does not follow - // this rule. - var getSetHour = makeGetSet('Hours', true); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - addFormatToken('m', ['mm', 2], 0, 'minute'); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - // ALIASES + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - addUnitAlias('minute', 'm'); + var _utilNodeBase = __webpack_require__(65); - // PARSING + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - addRegexToken('m', match1to2); - addRegexToken('mm', match1to2, match2); - addParseToken(['m', 'mm'], MINUTE); + var Text = (function (_NodeBase) { + function Text(options, body, labelModule) { + _classCallCheck(this, Text); - // MOMENTS + _get(Object.getPrototypeOf(Text.prototype), 'constructor', this).call(this, options, body, labelModule); + } - var getSetMinute = makeGetSet('Minutes', false); + _inherits(Text, _NodeBase); - addFormatToken('s', ['ss', 2], 0, 'second'); + _createClass(Text, [{ + key: 'resize', + value: function resize(ctx, selected) { + if (this.width === undefined) { + var margin = 5; + var textSize = this.labelModule.getTextSize(ctx, selected); + this.width = textSize.width + 2 * margin; + this.height = textSize.height + 2 * margin; + this.radius = 0.5 * this.width; + } + } + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(ctx, selected || hover); + this.left = x - this.width / 2; + this.top = y - this.height / 2; - // ALIASES + // draw shadow if enabled + this.enableShadow(ctx); + this.labelModule.draw(ctx, x, y, selected || hover); - addUnitAlias('second', 's'); + // disable shadows for other elements. + this.disableShadow(ctx); - // PARSING + this.updateBoundingBox(x, y); + } + }, { + key: 'updateBoundingBox', + value: function updateBoundingBox(x, y) { + this.left = x - this.width / 2; + this.top = y - this.height / 2; - addRegexToken('s', match1to2); - addRegexToken('ss', match1to2, match2); - addParseToken(['s', 'ss'], SECOND); + this.boundingBox.top = this.top; + this.boundingBox.left = this.left; + this.boundingBox.right = this.left + this.width; + this.boundingBox.bottom = this.top + this.height; + } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + return this._distanceToBorder(angle); + } + }]); - // MOMENTS + return Text; + })(_utilNodeBase2['default']); - var getSetSecond = makeGetSet('Seconds', false); + exports['default'] = Text; + module.exports = exports['default']; - addFormatToken('S', 0, 0, function () { - return ~~(this.millisecond() / 100); - }); +/***/ }, +/* 79 */ +/***/ function(module, exports, __webpack_require__) { - addFormatToken(0, ['SS', 2], 0, function () { - return ~~(this.millisecond() / 10); - }); + 'use strict'; - function millisecond__milliseconds (token) { - addFormatToken(0, [token, 3], 0, 'millisecond'); - } + Object.defineProperty(exports, '__esModule', { + value: true + }); - millisecond__milliseconds('SSS'); - millisecond__milliseconds('SSSS'); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // ALIASES + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - addUnitAlias('millisecond', 'ms'); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - // PARSING + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - addRegexToken('S', match1to3, match1); - addRegexToken('SS', match1to3, match2); - addRegexToken('SSS', match1to3, match3); - addRegexToken('SSSS', matchUnsigned); - addParseToken(['S', 'SS', 'SSS', 'SSSS'], function (input, array) { - array[MILLISECOND] = toInt(('0.' + input) * 1000); - }); + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - // MOMENTS + var _utilShapeBase = __webpack_require__(71); - var getSetMillisecond = makeGetSet('Milliseconds', false); + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); - addFormatToken('z', 0, 0, 'zoneAbbr'); - addFormatToken('zz', 0, 0, 'zoneName'); + var Triangle = (function (_ShapeBase) { + function Triangle(options, body, labelModule) { + _classCallCheck(this, Triangle); - // MOMENTS + _get(Object.getPrototypeOf(Triangle.prototype), 'constructor', this).call(this, options, body, labelModule); + } - function getZoneAbbr () { - return this._isUTC ? 'UTC' : ''; - } + _inherits(Triangle, _ShapeBase); - function getZoneName () { - return this._isUTC ? 'Coordinated Universal Time' : ''; + _createClass(Triangle, [{ + key: 'resize', + value: function resize(ctx) { + this._resizeShape(); } + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this._drawShape(ctx, 'triangle', 3, x, y, selected, hover); + } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + return this._distanceToBorder(angle); + } + }]); - var momentPrototype__proto = Moment.prototype; - - momentPrototype__proto.add = add_subtract__add; - momentPrototype__proto.calendar = moment_calendar__calendar; - momentPrototype__proto.clone = clone; - momentPrototype__proto.diff = diff; - momentPrototype__proto.endOf = endOf; - momentPrototype__proto.format = format; - momentPrototype__proto.from = from; - momentPrototype__proto.fromNow = fromNow; - momentPrototype__proto.to = to; - momentPrototype__proto.toNow = toNow; - momentPrototype__proto.get = getSet; - momentPrototype__proto.invalidAt = invalidAt; - momentPrototype__proto.isAfter = isAfter; - momentPrototype__proto.isBefore = isBefore; - momentPrototype__proto.isBetween = isBetween; - momentPrototype__proto.isSame = isSame; - momentPrototype__proto.isValid = moment_valid__isValid; - momentPrototype__proto.lang = lang; - momentPrototype__proto.locale = locale; - momentPrototype__proto.localeData = localeData; - momentPrototype__proto.max = prototypeMax; - momentPrototype__proto.min = prototypeMin; - momentPrototype__proto.parsingFlags = parsingFlags; - momentPrototype__proto.set = getSet; - momentPrototype__proto.startOf = startOf; - momentPrototype__proto.subtract = add_subtract__subtract; - momentPrototype__proto.toArray = toArray; - momentPrototype__proto.toDate = toDate; - momentPrototype__proto.toISOString = moment_format__toISOString; - momentPrototype__proto.toJSON = moment_format__toISOString; - momentPrototype__proto.toString = toString; - momentPrototype__proto.unix = unix; - momentPrototype__proto.valueOf = to_type__valueOf; + return Triangle; + })(_utilShapeBase2['default']); - // Year - momentPrototype__proto.year = getSetYear; - momentPrototype__proto.isLeapYear = getIsLeapYear; + exports['default'] = Triangle; + module.exports = exports['default']; - // Week Year - momentPrototype__proto.weekYear = getSetWeekYear; - momentPrototype__proto.isoWeekYear = getSetISOWeekYear; +/***/ }, +/* 80 */ +/***/ function(module, exports, __webpack_require__) { - // Quarter - momentPrototype__proto.quarter = momentPrototype__proto.quarters = getSetQuarter; + 'use strict'; - // Month - momentPrototype__proto.month = getSetMonth; - momentPrototype__proto.daysInMonth = getDaysInMonth; + Object.defineProperty(exports, '__esModule', { + value: true + }); - // Week - momentPrototype__proto.week = momentPrototype__proto.weeks = getSetWeek; - momentPrototype__proto.isoWeek = momentPrototype__proto.isoWeeks = getSetISOWeek; - momentPrototype__proto.weeksInYear = getWeeksInYear; - momentPrototype__proto.isoWeeksInYear = getISOWeeksInYear; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // Day - momentPrototype__proto.date = getSetDayOfMonth; - momentPrototype__proto.day = momentPrototype__proto.days = getSetDayOfWeek; - momentPrototype__proto.weekday = getSetLocaleDayOfWeek; - momentPrototype__proto.isoWeekday = getSetISODayOfWeek; - momentPrototype__proto.dayOfYear = getSetDayOfYear; + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - // Hour - momentPrototype__proto.hour = momentPrototype__proto.hours = getSetHour; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - // Minute - momentPrototype__proto.minute = momentPrototype__proto.minutes = getSetMinute; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - // Second - momentPrototype__proto.second = momentPrototype__proto.seconds = getSetSecond; + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - // Millisecond - momentPrototype__proto.millisecond = momentPrototype__proto.milliseconds = getSetMillisecond; + var _utilShapeBase = __webpack_require__(71); - // Offset - momentPrototype__proto.utcOffset = getSetOffset; - momentPrototype__proto.utc = setOffsetToUTC; - momentPrototype__proto.local = setOffsetToLocal; - momentPrototype__proto.parseZone = setOffsetToParsedOffset; - momentPrototype__proto.hasAlignedHourOffset = hasAlignedHourOffset; - momentPrototype__proto.isDST = isDaylightSavingTime; - momentPrototype__proto.isDSTShifted = isDaylightSavingTimeShifted; - momentPrototype__proto.isLocal = isLocal; - momentPrototype__proto.isUtcOffset = isUtcOffset; - momentPrototype__proto.isUtc = isUtc; - momentPrototype__proto.isUTC = isUtc; + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); - // Timezone - momentPrototype__proto.zoneAbbr = getZoneAbbr; - momentPrototype__proto.zoneName = getZoneName; + var TriangleDown = (function (_ShapeBase) { + function TriangleDown(options, body, labelModule) { + _classCallCheck(this, TriangleDown); - // Deprecations - momentPrototype__proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); - momentPrototype__proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); - momentPrototype__proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); - momentPrototype__proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779', getSetZone); + _get(Object.getPrototypeOf(TriangleDown.prototype), 'constructor', this).call(this, options, body, labelModule); + } - var momentPrototype = momentPrototype__proto; + _inherits(TriangleDown, _ShapeBase); - function moment__createUnix (input) { - return local__createLocal(input * 1000); + _createClass(TriangleDown, [{ + key: 'resize', + value: function resize(ctx) { + this._resizeShape(); } - - function moment__createInZone () { - return local__createLocal.apply(null, arguments).parseZone(); + }, { + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this._drawShape(ctx, 'triangleDown', 3, x, y, selected, hover); } - - var defaultCalendar = { - sameDay : '[Today at] LT', - nextDay : '[Tomorrow at] LT', - nextWeek : 'dddd [at] LT', - lastDay : '[Yesterday at] LT', - lastWeek : '[Last] dddd [at] LT', - sameElse : 'L' - }; - - function locale_calendar__calendar (key, mom, now) { - var output = this._calendar[key]; - return typeof output === 'function' ? output.call(mom, now) : output; + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + return this._distanceToBorder(angle); } + }]); - var defaultLongDateFormat = { - LTS : 'h:mm:ss A', - LT : 'h:mm A', - L : 'MM/DD/YYYY', - LL : 'MMMM D, YYYY', - LLL : 'MMMM D, YYYY LT', - LLLL : 'dddd, MMMM D, YYYY LT' - }; + return TriangleDown; + })(_utilShapeBase2['default']); - function longDateFormat (key) { - var output = this._longDateFormat[key]; - if (!output && this._longDateFormat[key.toUpperCase()]) { - output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { - return val.slice(1); - }); - this._longDateFormat[key] = output; - } - return output; - } + exports['default'] = TriangleDown; + module.exports = exports['default']; - var defaultInvalidDate = 'Invalid date'; +/***/ }, +/* 81 */ +/***/ function(module, exports, __webpack_require__) { - function invalidDate () { - return this._invalidDate; - } + 'use strict'; - var defaultOrdinal = '%d'; - var defaultOrdinalParse = /\d{1,2}/; + Object.defineProperty(exports, '__esModule', { + value: true + }); - function ordinal (number) { - return this._ordinal.replace('%d', number); - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - function preParsePostFormat (string) { - return string; - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - var defaultRelativeTime = { - future : 'in %s', - past : '%s ago', - s : 'a few seconds', - m : 'a minute', - mm : '%d minutes', - h : 'an hour', - hh : '%d hours', - d : 'a day', - dd : '%d days', - M : 'a month', - MM : '%d months', - y : 'a year', - yy : '%d years' - }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - function relative__relativeTime (number, withoutSuffix, string, isFuture) { - var output = this._relativeTime[string]; - return (typeof output === 'function') ? - output(number, withoutSuffix, string, isFuture) : - output.replace(/%d/i, number); - } + var _componentsEdge = __webpack_require__(82); - function pastFuture (diff, output) { - var format = this._relativeTime[diff > 0 ? 'future' : 'past']; - return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); - } + var _componentsEdge2 = _interopRequireDefault(_componentsEdge); - function locale_set__set (config) { - var prop, i; - for (i in config) { - prop = config[i]; - if (typeof prop === 'function') { - this[i] = prop; - } else { - this['_' + i] = prop; - } - } - // Lenient ordinal parsing accepts just a number in addition to - // number + (possibly) stuff coming from _ordinalParseLenient. - this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + (/\d{1,2}/).source); - } + var _componentsSharedLabel = __webpack_require__(63); - var prototype__proto = Locale.prototype; + var _componentsSharedLabel2 = _interopRequireDefault(_componentsSharedLabel); - prototype__proto._calendar = defaultCalendar; - prototype__proto.calendar = locale_calendar__calendar; - prototype__proto._longDateFormat = defaultLongDateFormat; - prototype__proto.longDateFormat = longDateFormat; - prototype__proto._invalidDate = defaultInvalidDate; - prototype__proto.invalidDate = invalidDate; - prototype__proto._ordinal = defaultOrdinal; - prototype__proto.ordinal = ordinal; - prototype__proto._ordinalParse = defaultOrdinalParse; - prototype__proto.preparse = preParsePostFormat; - prototype__proto.postformat = preParsePostFormat; - prototype__proto._relativeTime = defaultRelativeTime; - prototype__proto.relativeTime = relative__relativeTime; - prototype__proto.pastFuture = pastFuture; - prototype__proto.set = locale_set__set; + var util = __webpack_require__(7); + var DataSet = __webpack_require__(14); + var DataView = __webpack_require__(16); - // Month - prototype__proto.months = localeMonths; - prototype__proto._months = defaultLocaleMonths; - prototype__proto.monthsShort = localeMonthsShort; - prototype__proto._monthsShort = defaultLocaleMonthsShort; - prototype__proto.monthsParse = localeMonthsParse; + var EdgesHandler = (function () { + function EdgesHandler(body, images, groups) { + var _this = this; - // Week - prototype__proto.week = localeWeek; - prototype__proto._week = defaultLocaleWeek; - prototype__proto.firstDayOfYear = localeFirstDayOfYear; - prototype__proto.firstDayOfWeek = localeFirstDayOfWeek; + _classCallCheck(this, EdgesHandler); - // Day of Week - prototype__proto.weekdays = localeWeekdays; - prototype__proto._weekdays = defaultLocaleWeekdays; - prototype__proto.weekdaysMin = localeWeekdaysMin; - prototype__proto._weekdaysMin = defaultLocaleWeekdaysMin; - prototype__proto.weekdaysShort = localeWeekdaysShort; - prototype__proto._weekdaysShort = defaultLocaleWeekdaysShort; - prototype__proto.weekdaysParse = localeWeekdaysParse; + this.body = body; + this.images = images; + this.groups = groups; - // Hours - prototype__proto.isPM = localeIsPM; - prototype__proto._meridiemParse = defaultLocaleMeridiemParse; - prototype__proto.meridiem = localeMeridiem; + // create the edge API in the body container + this.body.functions.createEdge = this.create.bind(this); - function lists__get (format, index, field, setter) { - var locale = locale_locales__getLocale(); - var utc = create_utc__createUTC().set(setter, index); - return locale[field](utc, format); - } + this.edgesListeners = { + add: function add(event, params) { + _this.add(params.items); + }, + update: function update(event, params) { + _this.update(params.items); + }, + remove: function remove(event, params) { + _this.remove(params.items); + } + }; - function list (format, index, field, count, setter) { - if (typeof format === 'number') { - index = format; - format = undefined; + this.options = {}; + this.defaultOptions = { + arrows: { + to: { enabled: false, scaleFactor: 1 }, // boolean / {arrowScaleFactor:1} / {enabled: false, arrowScaleFactor:1} + middle: { enabled: false, scaleFactor: 1 }, + from: { enabled: false, scaleFactor: 1 } + }, + color: { + color: '#848484', + highlight: '#848484', + hover: '#848484', + inherit: 'from', + opacity: 1 + }, + dashes: false, + font: { + color: '#343434', + size: 14, // px + face: 'arial', + background: 'none', + strokeWidth: 2, // px + strokeColor: '#ffffff', + align: 'horizontal' + }, + hidden: false, + hoverWidth: 1.5, + label: undefined, + length: undefined, + physics: true, + scaling: { + min: 1, + max: 15, + label: { + enabled: true, + min: 14, + max: 30, + maxVisible: 30, + drawThreshold: 5 + }, + customScalingFunction: function customScalingFunction(min, max, total, value) { + if (max === min) { + return 0.5; + } else { + var scale = 1 / (max - min); + return Math.max(0, (value - min) * scale); + } } + }, + selectionWidth: 1.5, + selfReferenceSize: 20, + shadow: { + enabled: false, + size: 10, + x: 5, + y: 5 + }, + smooth: { + enabled: true, + type: 'dynamic', + roundness: 0.5 + }, + title: undefined, + width: 1, + value: undefined + }; - format = format || ''; + util.extend(this.options, this.defaultOptions); - if (index != null) { - return lists__get(format, index, field, setter); - } + this.bindEventListeners(); + } - var i; - var out = []; - for (i = 0; i < count; i++) { - out[i] = lists__get(format, i, field, setter); + _createClass(EdgesHandler, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this2 = this; + + // this allows external modules to force all dynamic curves to turn static. + this.body.emitter.on('_forceDisableDynamicCurves', function (type) { + if (type === 'dynamic') { + type = 'continuous'; } - return out; - } + var emitChange = false; + for (var edgeId in _this2.body.edges) { + if (_this2.body.edges.hasOwnProperty(edgeId)) { + var edge = _this2.body.edges[edgeId]; + var edgeData = _this2.body.data.edges._data[edgeId]; - function lists__listMonths (format, index) { - return list(format, index, 'months', 12, 'month'); - } + // only forcilby remove the smooth curve if the data has been set of the edge has the smooth curves defined. + // this is because a change in the global would not affect these curves. + if (edgeData !== undefined) { + var edgeOptions = edgeData.smooth; + if (edgeOptions !== undefined) { + if (edgeOptions.enabled === true && edgeOptions.type === 'dynamic') { + if (type === undefined) { + edge.setOptions({ smooth: false }); + } else { + edge.setOptions({ smooth: { type: type } }); + } + emitChange = true; + } + } + } + } + } + if (emitChange === true) { + _this2.body.emitter.emit('_dataChanged'); + } + }); - function lists__listMonthsShort (format, index) { - return list(format, index, 'monthsShort', 12, 'month'); - } + // this is called when options of EXISTING nodes or edges have changed. + this.body.emitter.on('_dataUpdated', function () { + _this2.reconnectEdges(); + _this2.markAllEdgesAsDirty(); + }); - function lists__listWeekdays (format, index) { - return list(format, index, 'weekdays', 7, 'day'); + // refresh the edges. Used when reverting from hierarchical layout + this.body.emitter.on('refreshEdges', this.refresh.bind(this)); + this.body.emitter.on('refresh', this.refresh.bind(this)); + this.body.emitter.on('destroy', function () { + delete _this2.body.functions.createEdge; + delete _this2.edgesListeners.add; + delete _this2.edgesListeners.update; + delete _this2.edgesListeners.remove; + delete _this2.edgesListeners; + }); } + }, { + key: 'setOptions', + value: function setOptions(options) { + if (options !== undefined) { + // use the parser from the Edge class to fill in all shorthand notations + _componentsEdge2['default'].parseOptions(this.options, options); - function lists__listWeekdaysShort (format, index) { - return list(format, index, 'weekdaysShort', 7, 'day'); - } + // hanlde multiple input cases for color + if (options.color !== undefined) { + this.markAllEdgesAsDirty(); + } - function lists__listWeekdaysMin (format, index) { - return list(format, index, 'weekdaysMin', 7, 'day'); - } + // update smooth settings in all edges + var dataChanged = false; + if (options.smooth !== undefined) { + for (var edgeId in this.body.edges) { + if (this.body.edges.hasOwnProperty(edgeId)) { + dataChanged = this.body.edges[edgeId].updateEdgeType() || dataChanged; + } + } + } - locale_locales__getSetGlobalLocale('en', { - ordinalParse: /\d{1,2}(th|st|nd|rd)/, - ordinal : function (number) { - var b = number % 10, - output = (toInt(number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - return number + output; + // update fonts in all edges + if (options.font !== undefined) { + // use the parser from the Label class to fill in all shorthand notations + _componentsSharedLabel2['default'].parseOptions(this.options, options); + for (var edgeId in this.body.edges) { + if (this.body.edges.hasOwnProperty(edgeId)) { + this.body.edges[edgeId].updateLabelModule(); + } + } } - }); - - // Side effect imports - utils_hooks__hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', locale_locales__getSetGlobalLocale); - utils_hooks__hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', locale_locales__getLocale); - var mathAbs = Math.abs; + // update the state of the variables if needed + if (options.hidden !== undefined || options.physics !== undefined || dataChanged === true) { + this.body.emitter.emit('_dataChanged'); + } + } + } + }, { + key: 'setData', - function duration_abs__abs () { - var data = this._data; + /** + * Load edges by reading the data table + * @param {Array | DataSet | DataView} edges The data containing the edges. + * @private + * @private + */ + value: function setData(edges) { + var _this3 = this; - this._milliseconds = mathAbs(this._milliseconds); - this._days = mathAbs(this._days); - this._months = mathAbs(this._months); + var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - data.milliseconds = mathAbs(data.milliseconds); - data.seconds = mathAbs(data.seconds); - data.minutes = mathAbs(data.minutes); - data.hours = mathAbs(data.hours); - data.months = mathAbs(data.months); - data.years = mathAbs(data.years); + var oldEdgesData = this.body.data.edges; - return this; - } + if (edges instanceof DataSet || edges instanceof DataView) { + this.body.data.edges = edges; + } else if (Array.isArray(edges)) { + this.body.data.edges = new DataSet(); + this.body.data.edges.add(edges); + } else if (!edges) { + this.body.data.edges = new DataSet(); + } else { + throw new TypeError('Array or DataSet expected'); + } - function duration_add_subtract__addSubtract (duration, input, value, direction) { - var other = create__createDuration(input, value); + // TODO: is this null or undefined or false? + if (oldEdgesData) { + // unsubscribe from old dataset + util.forEach(this.edgesListeners, function (callback, event) { + oldEdgesData.off(event, callback); + }); + } - duration._milliseconds += direction * other._milliseconds; - duration._days += direction * other._days; - duration._months += direction * other._months; + // remove drawn edges + this.body.edges = {}; - return duration._bubble(); - } + // TODO: is this null or undefined or false? + if (this.body.data.edges) { + // subscribe to new dataset + util.forEach(this.edgesListeners, function (callback, event) { + _this3.body.data.edges.on(event, callback); + }); - // supports only 2.0-style add(1, 's') or add(duration) - function duration_add_subtract__add (input, value) { - return duration_add_subtract__addSubtract(this, input, value, 1); - } + // draw all new nodes + var ids = this.body.data.edges.getIds(); + this.add(ids, true); + } - // supports only 2.0-style subtract(1, 's') or subtract(duration) - function duration_add_subtract__subtract (input, value) { - return duration_add_subtract__addSubtract(this, input, value, -1); + if (doNotEmit === false) { + this.body.emitter.emit('_dataChanged'); + } } + }, { + key: 'add', - function bubble () { - var milliseconds = this._milliseconds; - var days = this._days; - var months = this._months; - var data = this._data; - var seconds, minutes, hours, years = 0; - - // The following code bubbles up values, see the tests for - // examples of what that means. - data.milliseconds = milliseconds % 1000; + /** + * Add edges + * @param {Number[] | String[]} ids + * @private + */ + value: function add(ids) { + var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - seconds = absFloor(milliseconds / 1000); - data.seconds = seconds % 60; + var edges = this.body.edges; + var edgesData = this.body.data.edges; - minutes = absFloor(seconds / 60); - data.minutes = minutes % 60; + for (var i = 0; i < ids.length; i++) { + var id = ids[i]; - hours = absFloor(minutes / 60); - data.hours = hours % 24; + var oldEdge = edges[id]; + if (oldEdge) { + oldEdge.disconnect(); + } - days += absFloor(hours / 24); + var data = edgesData.get(id, { 'showInternalIds': true }); + edges[id] = this.create(data); + } - // Accurately convert days to years, assume start from year 0. - years = absFloor(daysToYears(days)); - days -= absFloor(yearsToDays(years)); + if (doNotEmit === false) { + this.body.emitter.emit('_dataChanged'); + } + } + }, { + key: 'update', - // 30 days to a month - // TODO (iskren): Use anchor date (like 1st Jan) to compute this. - months += absFloor(days / 30); - days %= 30; + /** + * Update existing edges, or create them when not yet existing + * @param {Number[] | String[]} ids + * @private + */ + value: function update(ids) { + var edges = this.body.edges; + var edgesData = this.body.data.edges; + var dataChanged = false; + for (var i = 0; i < ids.length; i++) { + var id = ids[i]; + var data = edgesData.get(id); + var edge = edges[id]; + if (edge === null) { + // update edge + edge.disconnect(); + dataChanged = edge.setOptions(data) || dataChanged; // if a support node is added, data can be changed. + edge.connect(); + } else { + // create edge + this.body.edges[id] = this.create(data); + dataChanged = true; + } + } - // 12 months -> 1 year - years += absFloor(months / 12); - months %= 12; + if (dataChanged === true) { + this.body.emitter.emit('_dataChanged'); + } else { + this.body.emitter.emit('_dataUpdated'); + } + } + }, { + key: 'remove', - data.days = days; - data.months = months; - data.years = years; + /** + * Remove existing edges. Non existing ids will be ignored + * @param {Number[] | String[]} ids + * @private + */ + value: function remove(ids) { + var edges = this.body.edges; + for (var i = 0; i < ids.length; i++) { + var id = ids[i]; + var edge = edges[id]; + if (edge !== undefined) { + if (edge.via != null) { + delete this.body.supportNodes[edge.via.id]; + } + edge.disconnect(); + delete edges[id]; + } + } - return this; + this.body.emitter.emit('_dataChanged'); } - - function daysToYears (days) { - // 400 years have 146097 days (taking into account leap year rules) - return days * 400 / 146097; + }, { + key: 'refresh', + value: function refresh() { + var edges = this.body.edges; + for (var edgeId in edges) { + var edge = undefined; + if (edges.hasOwnProperty(edgeId)) { + edge = edges[edgeId]; + } + var data = this.body.data.edges._data[edgeId]; + if (edge !== undefined && data !== undefined) { + edge.setOptions(data); + } + } } - - function yearsToDays (years) { - // years * 365 + absFloor(years / 4) - - // absFloor(years / 100) + absFloor(years / 400); - return years * 146097 / 400; + }, { + key: 'create', + value: function create(properties) { + return new _componentsEdge2['default'](properties, this.body, this.options); + } + }, { + key: 'markAllEdgesAsDirty', + value: function markAllEdgesAsDirty() { + for (var edgeId in this.body.edges) { + this.body.edges[edgeId].edgeType.colorDirty = true; + } } + }, { + key: 'reconnectEdges', - function as (units) { - var days; - var months; - var milliseconds = this._milliseconds; + /** + * Reconnect all edges + * @private + */ + value: function reconnectEdges() { + var id; + var nodes = this.body.nodes; + var edges = this.body.edges; - units = normalizeUnits(units); + for (id in nodes) { + if (nodes.hasOwnProperty(id)) { + nodes[id].edges = []; + } + } - if (units === 'month' || units === 'year') { - days = this._days + milliseconds / 864e5; - months = this._months + daysToYears(days) * 12; - return units === 'month' ? months : months / 12; - } else { - // handle milliseconds separately because of floating point math errors (issue #1867) - days = this._days + Math.round(yearsToDays(this._months / 12)); - switch (units) { - case 'week' : return days / 7 + milliseconds / 6048e5; - case 'day' : return days + milliseconds / 864e5; - case 'hour' : return days * 24 + milliseconds / 36e5; - case 'minute' : return days * 1440 + milliseconds / 6e4; - case 'second' : return days * 86400 + milliseconds / 1000; - // Math.floor prevents floating point math errors here - case 'millisecond': return Math.floor(days * 864e5) + milliseconds; - default: throw new Error('Unknown unit ' + units); - } + for (id in edges) { + if (edges.hasOwnProperty(id)) { + var edge = edges[id]; + edge.from = null; + edge.to = null; + edge.connect(); } + } } - - // TODO: Use this.as('ms')? - function duration_as__valueOf () { - return ( - this._milliseconds + - this._days * 864e5 + - (this._months % 12) * 2592e6 + - toInt(this._months / 12) * 31536e6 - ); + }, { + key: 'getConnectedNodes', + value: function getConnectedNodes(edgeId) { + var nodeList = []; + if (this.body.edges[edgeId] !== undefined) { + var edge = this.body.edges[edgeId]; + if (edge.fromId) { + nodeList.push(edge.fromId); + } + if (edge.toId) { + nodeList.push(edge.toId); + } + } + return nodeList; } + }]); - function makeAs (alias) { - return function () { - return this.as(alias); - }; - } + return EdgesHandler; + })(); - var asMilliseconds = makeAs('ms'); - var asSeconds = makeAs('s'); - var asMinutes = makeAs('m'); - var asHours = makeAs('h'); - var asDays = makeAs('d'); - var asWeeks = makeAs('w'); - var asMonths = makeAs('M'); - var asYears = makeAs('y'); + exports['default'] = EdgesHandler; + module.exports = exports['default']; - function duration_get__get (units) { - units = normalizeUnits(units); - return this[units + 's'](); - } +/***/ }, +/* 82 */ +/***/ function(module, exports, __webpack_require__) { - function makeGetter(name) { - return function () { - return this._data[name]; - }; - } + 'use strict'; - var duration_get__milliseconds = makeGetter('milliseconds'); - var seconds = makeGetter('seconds'); - var minutes = makeGetter('minutes'); - var hours = makeGetter('hours'); - var days = makeGetter('days'); - var months = makeGetter('months'); - var years = makeGetter('years'); + Object.defineProperty(exports, '__esModule', { + value: true + }); - function weeks () { - return absFloor(this.days() / 7); - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var round = Math.round; - var thresholds = { - s: 45, // seconds to minute - m: 45, // minutes to hour - h: 22, // hours to day - d: 26, // days to month - M: 11 // months to year - }; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize - function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { - return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - function duration_humanize__relativeTime (posNegDuration, withoutSuffix, locale) { - var duration = create__createDuration(posNegDuration).abs(); - var seconds = round(duration.as('s')); - var minutes = round(duration.as('m')); - var hours = round(duration.as('h')); - var days = round(duration.as('d')); - var months = round(duration.as('M')); - var years = round(duration.as('y')); + var _sharedLabel = __webpack_require__(63); - var a = seconds < thresholds.s && ['s', seconds] || - minutes === 1 && ['m'] || - minutes < thresholds.m && ['mm', minutes] || - hours === 1 && ['h'] || - hours < thresholds.h && ['hh', hours] || - days === 1 && ['d'] || - days < thresholds.d && ['dd', days] || - months === 1 && ['M'] || - months < thresholds.M && ['MM', months] || - years === 1 && ['y'] || ['yy', years]; + var _sharedLabel2 = _interopRequireDefault(_sharedLabel); - a[2] = withoutSuffix; - a[3] = +posNegDuration > 0; - a[4] = locale; - return substituteTimeAgo.apply(null, a); - } + var _edgesBezierEdgeDynamic = __webpack_require__(83); - // This function allows you to set a threshold for relative time strings - function duration_humanize__getSetRelativeTimeThreshold (threshold, limit) { - if (thresholds[threshold] === undefined) { - return false; - } - if (limit === undefined) { - return thresholds[threshold]; - } - thresholds[threshold] = limit; - return true; - } + var _edgesBezierEdgeDynamic2 = _interopRequireDefault(_edgesBezierEdgeDynamic); - function humanize (withSuffix) { - var locale = this.localeData(); - var output = duration_humanize__relativeTime(this, !withSuffix, locale); + var _edgesBezierEdgeStatic = __webpack_require__(86); - if (withSuffix) { - output = locale.pastFuture(+this, output); - } + var _edgesBezierEdgeStatic2 = _interopRequireDefault(_edgesBezierEdgeStatic); - return locale.postformat(output); - } + var _edgesStraightEdge = __webpack_require__(87); - var iso_string__abs = Math.abs; + var _edgesStraightEdge2 = _interopRequireDefault(_edgesStraightEdge); - function iso_string__toISOString() { - // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js - var Y = iso_string__abs(this.years()); - var M = iso_string__abs(this.months()); - var D = iso_string__abs(this.days()); - var h = iso_string__abs(this.hours()); - var m = iso_string__abs(this.minutes()); - var s = iso_string__abs(this.seconds() + this.milliseconds() / 1000); - var total = this.asSeconds(); + var util = __webpack_require__(7); - if (!total) { - // this is the same as C#'s (Noda) and python (isodate)... - // but not other JS (goog.date) - return 'P0D'; - } + /** + * @class Edge + * + * A edge connects two nodes + * @param {Object} properties Object with options. Must contain + * At least options from and to. + * Available options: from (number), + * to (number), label (string, color (string), + * width (number), style (string), + * length (number), title (string) + * @param {Network} network A Network object, used to find and edge to + * nodes. + * @param {Object} constants An object with default values for + * example for the color + */ - return (total < 0 ? '-' : '') + - 'P' + - (Y ? Y + 'Y' : '') + - (M ? M + 'M' : '') + - (D ? D + 'D' : '') + - ((h || m || s) ? 'T' : '') + - (h ? h + 'H' : '') + - (m ? m + 'M' : '') + - (s ? s + 'S' : ''); - } + var Edge = (function () { + function Edge(options, body, globalOptions) { + _classCallCheck(this, Edge); - var duration_prototype__proto = Duration.prototype; + if (body === undefined) { + throw 'No body provided'; + } + this.options = util.bridgeObject(globalOptions); + this.body = body; - duration_prototype__proto.abs = duration_abs__abs; - duration_prototype__proto.add = duration_add_subtract__add; - duration_prototype__proto.subtract = duration_add_subtract__subtract; - duration_prototype__proto.as = as; - duration_prototype__proto.asMilliseconds = asMilliseconds; - duration_prototype__proto.asSeconds = asSeconds; - duration_prototype__proto.asMinutes = asMinutes; - duration_prototype__proto.asHours = asHours; - duration_prototype__proto.asDays = asDays; - duration_prototype__proto.asWeeks = asWeeks; - duration_prototype__proto.asMonths = asMonths; - duration_prototype__proto.asYears = asYears; - duration_prototype__proto.valueOf = duration_as__valueOf; - duration_prototype__proto._bubble = bubble; - duration_prototype__proto.get = duration_get__get; - duration_prototype__proto.milliseconds = duration_get__milliseconds; - duration_prototype__proto.seconds = seconds; - duration_prototype__proto.minutes = minutes; - duration_prototype__proto.hours = hours; - duration_prototype__proto.days = days; - duration_prototype__proto.weeks = weeks; - duration_prototype__proto.months = months; - duration_prototype__proto.years = years; - duration_prototype__proto.humanize = humanize; - duration_prototype__proto.toISOString = iso_string__toISOString; - duration_prototype__proto.toString = iso_string__toISOString; - duration_prototype__proto.toJSON = iso_string__toISOString; - duration_prototype__proto.locale = locale; - duration_prototype__proto.localeData = localeData; + // initialize variables + this.id = undefined; + this.fromId = undefined; + this.toId = undefined; + this.selected = false; + this.hover = false; + this.labelDirty = true; + this.colorDirty = true; - // Deprecations - duration_prototype__proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', iso_string__toISOString); - duration_prototype__proto.lang = lang; + this.baseWidth = this.options.width; + this.baseFontSize = this.options.font.size; - // Side effect imports + this.from = undefined; // a node + this.to = undefined; // a node - addFormatToken('X', 0, 0, 'unix'); - addFormatToken('x', 0, 0, 'valueOf'); + this.edgeType = undefined; - // PARSING + this.connected = false; - addRegexToken('x', matchSigned); - addRegexToken('X', matchTimestamp); - addParseToken('X', function (input, array, config) { - config._d = new Date(parseFloat(input, 10) * 1000); - }); - addParseToken('x', function (input, array, config) { - config._d = new Date(toInt(input)); - }); + this.labelModule = new _sharedLabel2['default'](this.body, this.options); - // Side effect imports + this.setOptions(options); + } + _createClass(Edge, [{ + key: 'setOptions', - utils_hooks__hooks.version = '2.10.3'; + /** + * Set or overwrite options for the edge + * @param {Object} options an object with options + * @param doNotEmit + */ + value: function setOptions(options) { + if (!options) { + return; + } + this.colorDirty = true; - setHookCallback(local__createLocal); + Edge.parseOptions(this.options, options, true); - utils_hooks__hooks.fn = momentPrototype; - utils_hooks__hooks.min = min; - utils_hooks__hooks.max = max; - utils_hooks__hooks.utc = create_utc__createUTC; - utils_hooks__hooks.unix = moment__createUnix; - utils_hooks__hooks.months = lists__listMonths; - utils_hooks__hooks.isDate = isDate; - utils_hooks__hooks.locale = locale_locales__getSetGlobalLocale; - utils_hooks__hooks.invalid = valid__createInvalid; - utils_hooks__hooks.duration = create__createDuration; - utils_hooks__hooks.isMoment = isMoment; - utils_hooks__hooks.weekdays = lists__listWeekdays; - utils_hooks__hooks.parseZone = moment__createInZone; - utils_hooks__hooks.localeData = locale_locales__getLocale; - utils_hooks__hooks.isDuration = isDuration; - utils_hooks__hooks.monthsShort = lists__listMonthsShort; - utils_hooks__hooks.weekdaysMin = lists__listWeekdaysMin; - utils_hooks__hooks.defineLocale = defineLocale; - utils_hooks__hooks.weekdaysShort = lists__listWeekdaysShort; - utils_hooks__hooks.normalizeUnits = normalizeUnits; - utils_hooks__hooks.relativeTimeThreshold = duration_humanize__getSetRelativeTimeThreshold; + 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 = parseInt(options.value); + } - var _moment = utils_hooks__hooks; + // update label Module + this.updateLabelModule(); - return _moment; + var dataChanged = this.updateEdgeType(); - })); - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(90)(module))) + // if anything has been updates, reset the selection width and the hover width + this._setInteractionWidths(); -/***/ }, -/* 71 */ -/***/ function(module, exports, __webpack_require__) { + // A node is connected when it has a from and to node that both exist in the network.body.nodes. + this.connect(); - var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; + if (options.hidden !== undefined || options.physics !== undefined) { + dataChanged = true; + } - (function (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) - window.propagating = factory(); - } - }(function () { - var _firstTarget = null; // singleton, will contain the target element where the touch event started - var _processing = false; // singleton, true when a touch event is being handled + return dataChanged; + } + }, { + key: 'updateLabelModule', - /** - * Extend an Hammer.js instance with event propagation. - * - * Features: - * - Events emitted by hammer will propagate in order from child to parent - * elements. - * - Events are extended with a function `event.stopPropagation()` to stop - * propagation to parent elements. - * - An option `preventDefault` to stop all default browser behavior. - * - * Usage: - * var hammer = propagatingHammer(new Hammer(element)); - * var hammer = propagatingHammer(new Hammer(element), {preventDefault: true}); - * - * @param {Hammer.Manager} hammer An hammer instance. - * @param {Object} [options] Available options: - * - `preventDefault: true | 'mouse' | 'touch' | 'pen'`. - * Enforce preventing the default browser behavior. - * Cannot be set to `false`. - * @return {Hammer.Manager} Returns the same hammer instance with extended - * functionality - */ - return function propagating(hammer, options) { - if (options && options.preventDefault === false) { - throw new Error('Only supports preventDefault == true'); + /** + * update the options in the label module + */ + value: function updateLabelModule() { + this.labelModule.setOptions(this.options, true); + if (this.labelModule.baseSize !== undefined) { + this.baseFontSize = this.labelModule.baseSize; + } } - var _options = options || { - preventDefault: false - }; + }, { + key: 'updateEdgeType', - if (hammer.Manager) { - // This looks like the Hammer constructor. - // Overload the constructors with our own. - var Hammer = hammer; + /** + * update the edge type, set the options + * @returns {boolean} + */ + value: function updateEdgeType() { + var dataChanged = false; + var changeInType = true; + if (this.edgeType !== undefined) { + if (this.edgeType instanceof _edgesBezierEdgeDynamic2['default'] && this.options.smooth.enabled === true && this.options.smooth.type === 'dynamic') { + changeInType = false; + } + if (this.edgeType instanceof _edgesBezierEdgeStatic2['default'] && this.options.smooth.enabled === true && this.options.smooth.type !== 'dynamic') { + changeInType = false; + } + if (this.edgeType instanceof _edgesStraightEdge2['default'] && this.options.smooth.enabled === false) { + changeInType = false; + } - var PropagatingHammer = function(element, options) { - return propagating(new Hammer(element, options), _options); - }; - Hammer.extend(PropagatingHammer, Hammer); - PropagatingHammer.Manager = function (element, options) { - return propagating(new Hammer.Manager(element, options), _options); - }; + if (changeInType === true) { + dataChanged = this.edgeType.cleanup(); + } + } - return PropagatingHammer; + if (changeInType === true) { + if (this.options.smooth.enabled === true) { + if (this.options.smooth.type === 'dynamic') { + dataChanged = true; + this.edgeType = new _edgesBezierEdgeDynamic2['default'](this.options, this.body, this.labelModule); + } else { + this.edgeType = new _edgesBezierEdgeStatic2['default'](this.options, this.body, this.labelModule); + } + } else { + this.edgeType = new _edgesStraightEdge2['default'](this.options, this.body, this.labelModule); + } + } else { + // if nothing changes, we just set the options. + this.edgeType.setOptions(this.options); + } + + return dataChanged; } + }, { + key: 'togglePhysics', - // attach to DOM element - var element = hammer.element; - element.hammer = hammer; + /** + * Enable or disable the physics. + * @param status + */ + value: function togglePhysics(status) { + this.options.physics = status; + this.edgeType.togglePhysics(status); + } + }, { + key: 'connect', - // move the original functions that we will wrap - hammer._on = hammer.on; - hammer._off = hammer.off; - hammer._emit = hammer.emit; - hammer._destroy = hammer.destroy; + /** + * Connect an edge to its nodes + */ + value: function connect() { + this.disconnect(); - /** @type {Object.>} */ - hammer._handlers = {}; + this.from = this.body.nodes[this.fromId] || undefined; + this.to = this.body.nodes[this.toId] || undefined; + this.connected = this.from !== undefined && this.to !== undefined; - // register an event to catch the start of a gesture and store the - // target in a singleton - hammer._on('hammer.input', function (event) { - if (_options.preventDefault === true || (_options.preventDefault === event.pointerType)) { - event.preventDefault(); + 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); + } } - if (event.isFirst) { - _firstTarget = event.target; - _processing = true; + + this.edgeType.connect(); + } + }, { + key: 'disconnect', + + /** + * Disconnect an edge from its nodes + */ + value: function disconnect() { + if (this.from) { + this.from.detachEdge(this); + this.from = undefined; } - if (event.isFinal) { - _processing = false; + if (this.to) { + this.to.detachEdge(this); + this.to = undefined; } - }); + + this.connected = false; + } + }, { + key: 'getTitle', /** - * Register a handler for one or multiple events - * @param {String} events A space separated string with events - * @param {function} handler A callback function, called as handler(event) - * @returns {Hammer.Manager} Returns the hammer instance + * get the title of this edge. + * @return {string} title The title of the edge, or undefined when no title + * has been set. */ - hammer.on = function (events, handler) { - // register the handler - split(events).forEach(function (event) { - var _handlers = hammer._handlers[event]; - if (!_handlers) { - hammer._handlers[event] = _handlers = []; + value: function getTitle() { + return this.title; + } + }, { + key: 'isSelected', - // register the static, propagated handler - hammer._on(event, propagatedHandler); + /** + * check if this node is selecte + * @return {boolean} selected True if node is selected, else false + */ + value: function isSelected() { + return this.selected; + } + }, { + key: 'getValue', + + /** + * Retrieve the value of the edge. Can be undefined + * @return {Number} value + */ + value: function getValue() { + return this.options.value; + } + }, { + key: 'setValueRange', + + /** + * 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 total + */ + 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; } - _handlers.push(handler); - }); + this.options.width = this.options.scaling.min + scale * widthDiff; + } else { + this.options.width = this.baseWidth; + this.options.font.size = this.baseFontSize; + } - return hammer; - }; + this._setInteractionWidths(); + } + }, { + 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; + } + } + }, { + key: 'draw', /** - * Unregister a handler for one or multiple events - * @param {String} events A space separated string with events - * @param {function} [handler] Optional. The registered handler. If not - * provided, all handlers for given events - * are removed. - * @returns {Hammer.Manager} Returns the hammer instance + * 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 */ - hammer.off = function (events, handler) { - // unregister the handler - split(events).forEach(function (event) { - var _handlers = hammer._handlers[event]; - if (_handlers) { - _handlers = handler ? _handlers.filter(function (h) { - return h !== handler; - }) : []; + value: function draw(ctx) { + var via = this.edgeType.drawLine(ctx, this.selected, this.hover); + this.drawArrows(ctx, via); + this.drawLabel(ctx, via); + } + }, { + key: 'drawArrows', + value: function drawArrows(ctx, viaNode) { + if (this.options.arrows.from.enabled === true) { + this.edgeType.drawArrowHead(ctx, 'from', viaNode, this.selected, this.hover); + } + if (this.options.arrows.middle.enabled === true) { + this.edgeType.drawArrowHead(ctx, 'middle', viaNode, this.selected, this.hover); + } + if (this.options.arrows.to.enabled === true) { + this.edgeType.drawArrowHead(ctx, 'to', viaNode, this.selected, this.hover); + } + } + }, { + key: 'drawLabel', + value: function drawLabel(ctx, viaNode) { + if (this.options.label !== undefined) { + // set style + var node1 = this.from; + var node2 = this.to; + var selected = this.from.selected || this.to.selected || this.selected; + if (node1.id != node2.id) { + var point = this.edgeType.getPoint(0.5, viaNode); + ctx.save(); - if (_handlers.length > 0) { - hammer._handlers[event] = _handlers; + // if the label has to be rotated: + if (this.options.font.align !== 'horizontal') { + this.labelModule.calculateLabelSize(ctx, selected, point.x, point.y); + ctx.translate(point.x, this.labelModule.size.yLine); + this._rotateForLabelAlignment(ctx); } - else { - // remove static, propagated handler - hammer._off(event, propagatedHandler); - delete hammer._handlers[event]; + + // draw the label + this.labelModule.draw(ctx, point.x, point.y, selected); + ctx.restore(); + } else { + 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, selected); } - }); - - return hammer; - }; + } + } + }, { + key: 'isOverlappingWith', /** - * Emit to the event listeners - * @param {string} eventType - * @param {Event} event + * 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 */ - hammer.emit = function(eventType, event) { - if (!_processing) { - _firstTarget = event.target; - } - hammer._emit(eventType, event); - }; + 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; - hammer.destroy = function () { - // Detach from DOM element - var element = hammer.element; - delete element.hammer; + var dist = this.edgeType.getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj); - // clear all handlers - hammer._handlers = {}; + return dist < distMax; + } else { + return false; + } + } + }, { + key: '_rotateForLabelAlignment', - // call original hammer destroy - hammer._destroy(); - }; + /** + * Rotates the canvas so the text is most readable + * @param {CanvasRenderingContext2D} ctx + * @private + */ + value: function _rotateForLabelAlignment(ctx) { + var dy = this.from.y - this.to.y; + var dx = this.from.x - this.to.x; + var angleInDegrees = Math.atan2(dy, dx); - // split a string with space separated words - function split(events) { - return events.match(/[^ ]+/g); + // rotate so label it is readable + if (angleInDegrees < -1 && dx < 0 || angleInDegrees > 0 && dx < 0) { + angleInDegrees = angleInDegrees + Math.PI; + } + + ctx.rotate(angleInDegrees); } + }, { + key: '_pointOnCircle', /** - * A static event handler, applying event propagation. - * @param {Object} event + * 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 */ - function propagatedHandler(event) { - // let only a single hammer instance handle this event - if (event.type !== 'hammer.input') { - // it is possible that the same srcEvent is used with multiple hammer events, - // we keep track on which events are handled in an object _handled - if (!event.srcEvent._handled) { - event.srcEvent._handled = {}; - } + 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) + }; + } + }, { + key: 'select', + value: function select() { + this.selected = true; + } + }, { + key: 'unselect', + value: function unselect() { + this.selected = false; + } + }], [{ + key: 'parseOptions', + value: function parseOptions(parentOptions, newOptions) { + var allowDeletion = arguments[2] === undefined ? false : arguments[2]; + + var fields = ['id', 'from', 'hidden', 'hoverWidth', 'label', 'length', 'line', 'opacity', 'physics', 'selectionWidth', 'selfReferenceSize', 'to', 'title', 'value', 'width']; + + // only deep extend the items in the field array. These do not have shorthand. + util.selectiveDeepExtend(fields, parentOptions, newOptions, allowDeletion); - if (event.srcEvent._handled[event.type]) { - return; + util.mergeOptions(parentOptions, newOptions, 'smooth'); + util.mergeOptions(parentOptions, newOptions, 'shadow'); + + if (newOptions.dashes !== undefined && newOptions.dashes !== null) { + parentOptions.dashes = newOptions.dashes; + } else if (allowDeletion === true && newOptions.dashes === null) { + parentOptions.dashes = undefined; + delete parentOptions.dashes; + } + + // set the scaling newOptions + if (newOptions.scaling !== undefined && newOptions.scaling !== null) { + if (newOptions.scaling.min !== undefined) { + parentOptions.scaling.min = newOptions.scaling.min; } - else { - event.srcEvent._handled[event.type] = true; + if (newOptions.scaling.max !== undefined) { + parentOptions.scaling.max = newOptions.scaling.max; } + util.mergeOptions(parentOptions.scaling, newOptions.scaling, 'label'); + } else if (allowDeletion === true && newOptions.scaling === null) { + parentOptions.scaling = undefined; + delete parentOptions.scaling; } - // attach a stopPropagation function to the event - var stopped = false; - event.stopPropagation = function () { - stopped = true; - }; + // hanlde multiple input cases for arrows + if (newOptions.arrows !== undefined && newOptions.arrows !== null) { + if (typeof newOptions.arrows === 'string') { + var arrows = newOptions.arrows.toLowerCase(); + if (arrows.indexOf('to') != -1) { + parentOptions.arrows.to.enabled = true; + } + if (arrows.indexOf('middle') != -1) { + parentOptions.arrows.middle.enabled = true; + } + if (arrows.indexOf('from') != -1) { + parentOptions.arrows.from.enabled = true; + } + } else if (typeof newOptions.arrows === 'object') { + util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'to'); + util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'middle'); + util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'from'); + } else { + throw new Error('The arrow newOptions can only be an object or a string. Refer to the documentation. You used:' + JSON.stringify(newOptions.arrows)); + } + } else if (allowDeletion === true && newOptions.arrows === null) { + parentOptions.arrows = undefined; + delete parentOptions.arrows; + } - // attach firstTarget property to the event - event.firstTarget = _firstTarget; + // hanlde multiple input cases for color + if (newOptions.color !== undefined && newOptions.color !== null) { + if (util.isString(newOptions.color)) { + parentOptions.color.color = newOptions.color; + parentOptions.color.highlight = newOptions.color; + parentOptions.color.hover = newOptions.color; + parentOptions.color.inherit = false; + } else { + var colorsDefined = false; + if (newOptions.color.color !== undefined) { + parentOptions.color.color = newOptions.color.color;colorsDefined = true; + } + if (newOptions.color.highlight !== undefined) { + parentOptions.color.highlight = newOptions.color.highlight;colorsDefined = true; + } + if (newOptions.color.hover !== undefined) { + parentOptions.color.hover = newOptions.color.hover;colorsDefined = true; + } + if (newOptions.color.inherit !== undefined) { + parentOptions.color.inherit = newOptions.color.inherit; + } + if (newOptions.color.opacity !== undefined) { + parentOptions.color.opacity = Math.min(1, Math.max(0, newOptions.color.opacity)); + } - // propagate over all elements (until stopped) - var elem = _firstTarget; - while (elem && !stopped) { - var _handlers = elem.hammer && elem.hammer._handlers[event.type]; - if (_handlers) { - for (var i = 0; i < _handlers.length && !stopped; i++) { - _handlers[i](event); + if (newOptions.color.inherit === undefined && colorsDefined === true) { + parentOptions.color.inherit = false; } } + } else if (allowDeletion === true && newOptions.color === null) { + parentOptions.color = undefined; + delete parentOptions.color; + } - elem = elem.parentNode; + // handle the font settings + if (newOptions.font !== undefined) { + _sharedLabel2['default'].parseOptions(parentOptions.font, newOptions); } } + }]); - return hammer; - }; - })); + return Edge; + })(); + exports['default'] = Edge; + module.exports = exports['default']; /***/ }, -/* 72 */ +/* 83 */ /***/ function(module, exports, __webpack_require__) { - var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v2.0.4 - 2014-09-28 - * http://hammerjs.github.io/ - * - * Copyright (c) 2014 Jorik Tangelder; - * Licensed under the MIT license */ - (function(window, document, exportName, undefined) { - 'use strict'; - - var VENDOR_PREFIXES = ['', 'webkit', 'moz', 'MS', 'ms', 'o']; - var TEST_ELEMENT = document.createElement('div'); - - var TYPE_FUNCTION = 'function'; - - var round = Math.round; - var abs = Math.abs; - var now = Date.now; + 'use strict'; - /** - * set a timeout with a given scope - * @param {Function} fn - * @param {Number} timeout - * @param {Object} context - * @returns {number} - */ - function setTimeoutContext(fn, timeout, context) { - return setTimeout(bindFn(fn, context), timeout); - } + Object.defineProperty(exports, '__esModule', { + value: true + }); - /** - * if the argument is an array, we want to execute the fn on each entry - * if it aint an array we don't want to do a thing. - * this is used by all the methods that accept a single and array argument. - * @param {*|Array} arg - * @param {String} fn - * @param {Object} [context] - * @returns {Boolean} - */ - function invokeArrayArg(arg, fn, context) { - if (Array.isArray(arg)) { - each(arg, context[fn], context); - return true; - } - return false; - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /** - * walk objects and arrays - * @param {Object} obj - * @param {Function} iterator - * @param {Object} context - */ - function each(obj, iterator, context) { - var i; + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - if (!obj) { - return; - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - if (obj.forEach) { - obj.forEach(iterator, context); - } else if (obj.length !== undefined) { - i = 0; - while (i < obj.length) { - iterator.call(context, obj[i], i, obj); - i++; - } - } else { - for (i in obj) { - obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj); - } - } - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - /** - * extend object. - * means that properties in dest will be overwritten by the ones in src. - * @param {Object} dest - * @param {Object} src - * @param {Boolean} [merge] - * @returns {Object} dest - */ - function extend(dest, src, merge) { - var keys = Object.keys(src); - var i = 0; - while (i < keys.length) { - if (!merge || (merge && dest[keys[i]] === undefined)) { - dest[keys[i]] = src[keys[i]]; - } - i++; - } - return dest; - } + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - /** - * merge the values from src in the dest. - * means that properties that exist in dest will not be overwritten by src - * @param {Object} dest - * @param {Object} src - * @returns {Object} dest - */ - function merge(dest, src) { - return extend(dest, src, true); - } + var _utilBezierEdgeBase = __webpack_require__(84); - /** - * simple class inheritance - * @param {Function} child - * @param {Function} base - * @param {Object} [properties] - */ - function inherit(child, base, properties) { - var baseP = base.prototype, - childP; + var _utilBezierEdgeBase2 = _interopRequireDefault(_utilBezierEdgeBase); - childP = child.prototype = Object.create(baseP); - childP.constructor = child; - childP._super = baseP; + var BezierEdgeDynamic = (function (_BezierEdgeBase) { + function BezierEdgeDynamic(options, body, labelModule) { + _classCallCheck(this, BezierEdgeDynamic); - if (properties) { - extend(childP, properties); - } - } + //this.via = undefined; // Here for completeness but not allowed to defined before super() is invoked. + _get(Object.getPrototypeOf(BezierEdgeDynamic.prototype), 'constructor', this).call(this, options, body, labelModule); // --> this calls the setOptions below + } - /** - * simple function bind - * @param {Function} fn - * @param {Object} context - * @returns {Function} - */ - function bindFn(fn, context) { - return function boundFn() { - return fn.apply(context, arguments); - }; - } + _inherits(BezierEdgeDynamic, _BezierEdgeBase); - /** - * let a boolean value also be a function that must return a boolean - * this first item in args will be used as the context - * @param {Boolean|Function} val - * @param {Array} [args] - * @returns {Boolean} - */ - function boolOrFn(val, args) { - if (typeof val == TYPE_FUNCTION) { - return val.apply(args ? args[0] || undefined : undefined, args); + _createClass(BezierEdgeDynamic, [{ + key: 'setOptions', + value: function setOptions(options) { + this.options = options; + this.id = this.options.id; + this.setupSupportNode(); + this.connect(); } - return val; - } - - /** - * use the val2 when val1 is undefined - * @param {*} val1 - * @param {*} val2 - * @returns {*} - */ - function ifUndefined(val1, val2) { - return (val1 === undefined) ? val2 : val1; - } - - /** - * addEventListener with multiple events at once - * @param {EventTarget} target - * @param {String} types - * @param {Function} handler - */ - function addEventListeners(target, types, handler) { - each(splitStr(types), function(type) { - target.addEventListener(type, handler, false); - }); - } - - /** - * removeEventListener with multiple events at once - * @param {EventTarget} target - * @param {String} types - * @param {Function} handler - */ - function removeEventListeners(target, types, handler) { - each(splitStr(types), function(type) { - target.removeEventListener(type, handler, false); - }); - } - - /** - * find if a node is in the given parent - * @method hasParent - * @param {HTMLElement} node - * @param {HTMLElement} parent - * @return {Boolean} found - */ - function hasParent(node, parent) { - while (node) { - if (node == parent) { - return true; + }, { + key: 'connect', + value: function connect() { + this.from = this.body.nodes[this.options.from]; + this.to = this.body.nodes[this.options.to]; + if (this.from === undefined || this.to === undefined) { + this.via.setOptions({ physics: false }); + } else { + // fix weird behaviour where a selfreferencing node has physics enabled + if (this.from.id === this.to.id) { + this.via.setOptions({ physics: false }); + } else { + this.via.setOptions({ physics: true }); } - node = node.parentNode; + } } - return false; - } - - /** - * small indexOf wrapper - * @param {String} str - * @param {String} find - * @returns {Boolean} found - */ - function inStr(str, find) { - return str.indexOf(find) > -1; - } - - /** - * split string on whitespace - * @param {String} str - * @returns {Array} words - */ - function splitStr(str) { - return str.trim().split(/\s+/g); - } - - /** - * find if a array contains the object using indexOf or a simple polyFill - * @param {Array} src - * @param {String} find - * @param {String} [findByKey] - * @return {Boolean|Number} false when not found, or the index - */ - function inArray(src, find, findByKey) { - if (src.indexOf && !findByKey) { - return src.indexOf(find); - } else { - var i = 0; - while (i < src.length) { - if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) { - return i; - } - i++; - } - return -1; + }, { + key: 'cleanup', + value: function cleanup() { + if (this.via !== undefined) { + delete this.body.nodes[this.via.id]; + this.via = undefined; + return true; + } + return false; } - } - - /** - * convert array-like objects to real arrays - * @param {Object} obj - * @returns {Array} - */ - function toArray(obj) { - return Array.prototype.slice.call(obj, 0); - } - - /** - * unique array with objects based on a key (like 'id') or just by the array's value - * @param {Array} src [{id:1},{id:2},{id:1}] - * @param {String} [key] - * @param {Boolean} [sort=False] - * @returns {Array} [{id:1},{id:2}] - */ - function uniqueArray(src, key, sort) { - var results = []; - var values = []; - var i = 0; - - while (i < src.length) { - var val = key ? src[i][key] : src[i]; - if (inArray(values, val) < 0) { - results.push(src[i]); - } - values[i] = val; - i++; + }, { + key: 'togglePhysics', + value: function togglePhysics(status) { + this.via.setOptions({ physics: status }); } + }, { + key: 'setupSupportNode', - if (sort) { - if (!key) { - results = results.sort(); - } else { - results = results.sort(function sortUniqueArray(a, b) { - return a[key] > b[key]; - }); - } + /** + * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but + * are used for the force calculation. + * + * The changed data is not called, if needed, it is returned by the main edge constructor. + * @private + */ + value: function setupSupportNode() { + if (this.via === undefined) { + var nodeId = 'edgeId:' + this.id; + var node = this.body.functions.createNode({ + id: nodeId, + shape: 'circle', + physics: true, + hidden: true + }); + this.body.nodes[nodeId] = node; + this.via = node; + this.via.parentEdgeId = this.id; + this.positionBezierNode(); + } } + }, { + key: 'positionBezierNode', + value: function positionBezierNode() { + if (this.via !== undefined && this.from !== undefined && this.to !== undefined) { + this.via.x = 0.5 * (this.from.x + this.to.x); + this.via.y = 0.5 * (this.from.y + this.to.y); + } else if (this.via !== undefined) { + this.via.x = 0; + this.via.y = 0; + } + } + }, { + key: '_line', - return results; - } - - /** - * get the prefixed property - * @param {Object} obj - * @param {String} property - * @returns {String|Undefined} prefixed - */ - function prefixed(obj, property) { - var prefix, prop; - var camelProp = property[0].toUpperCase() + property.slice(1); + /** + * Draw a line between two nodes + * @param {CanvasRenderingContext2D} ctx + * @private + */ + value: function _line(ctx) { + // draw a straight line + ctx.beginPath(); + ctx.moveTo(this.from.x, this.from.y); + ctx.quadraticCurveTo(this.via.x, this.via.y, this.to.x, this.to.y); + // draw shadow if enabled + this.enableShadow(ctx); + ctx.stroke(); + this.disableShadow(ctx); + return this.via; + } + }, { + key: 'getPoint', - var i = 0; - while (i < VENDOR_PREFIXES.length) { - prefix = VENDOR_PREFIXES[i]; - prop = (prefix) ? prefix + camelProp : property; + /** + * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way + * @param percentage + * @param via + * @returns {{x: number, y: number}} + * @private + */ + value: function getPoint(percentage) { + var t = percentage; + var x = Math.pow(1 - t, 2) * this.from.x + 2 * t * (1 - t) * this.via.x + Math.pow(t, 2) * this.to.x; + var y = Math.pow(1 - t, 2) * this.from.y + 2 * t * (1 - t) * this.via.y + Math.pow(t, 2) * this.to.y; - if (prop in obj) { - return prop; - } - i++; + return { x: x, y: y }; + } + }, { + key: '_findBorderPosition', + value: function _findBorderPosition(nearNode, ctx) { + return this._findBorderPositionBezier(nearNode, ctx, this.via); + } + }, { + key: '_getDistanceToEdge', + value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) { + // x3,y3 is the point + return this._getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, this.via); } - return undefined; - } + }]); - /** - * get a unique id - * @returns {number} uniqueId - */ - var _uniqueId = 1; - function uniqueId() { - return _uniqueId++; - } + return BezierEdgeDynamic; + })(_utilBezierEdgeBase2['default']); - /** - * get the window object of an element - * @param {HTMLElement} element - * @returns {DocumentView|Window} - */ - function getWindowForElement(element) { - var doc = element.ownerDocument; - return (doc.defaultView || doc.parentWindow); - } + exports['default'] = BezierEdgeDynamic; + module.exports = exports['default']; - var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i; +/***/ }, +/* 84 */ +/***/ function(module, exports, __webpack_require__) { - var SUPPORT_TOUCH = ('ontouchstart' in window); - var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined; - var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent); + 'use strict'; - var INPUT_TYPE_TOUCH = 'touch'; - var INPUT_TYPE_PEN = 'pen'; - var INPUT_TYPE_MOUSE = 'mouse'; - var INPUT_TYPE_KINECT = 'kinect'; + Object.defineProperty(exports, '__esModule', { + value: true + }); - var COMPUTE_INTERVAL = 25; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var INPUT_START = 1; - var INPUT_MOVE = 2; - var INPUT_END = 4; - var INPUT_CANCEL = 8; + var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - var DIRECTION_NONE = 1; - var DIRECTION_LEFT = 2; - var DIRECTION_RIGHT = 4; - var DIRECTION_UP = 8; - var DIRECTION_DOWN = 16; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT; - var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN; - var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var PROPS_XY = ['x', 'y']; - var PROPS_CLIENT_XY = ['clientX', 'clientY']; + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - /** - * create new input type manager - * @param {Manager} manager - * @param {Function} callback - * @returns {Input} - * @constructor - */ - function Input(manager, callback) { - var self = this; - this.manager = manager; - this.callback = callback; - this.element = manager.element; - this.target = manager.options.inputTarget; + var _EdgeBase2 = __webpack_require__(85); - // smaller wrapper around the handler, for the scope and the enabled state of the manager, - // so when disabled the input events are completely bypassed. - this.domHandler = function(ev) { - if (boolOrFn(manager.options.enable, [manager])) { - self.handler(ev); - } - }; + var _EdgeBase3 = _interopRequireDefault(_EdgeBase2); - this.init(); + var BezierEdgeBase = (function (_EdgeBase) { + function BezierEdgeBase(options, body, labelModule) { + _classCallCheck(this, BezierEdgeBase); - } + _get(Object.getPrototypeOf(BezierEdgeBase.prototype), 'constructor', this).call(this, options, body, labelModule); + } - Input.prototype = { - /** - * should handle the inputEvent data and trigger the callback - * @virtual - */ - handler: function() { }, + _inherits(BezierEdgeBase, _EdgeBase); - /** - * bind the events - */ - init: function() { - this.evEl && addEventListeners(this.element, this.evEl, this.domHandler); - this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler); - this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); - }, + _createClass(BezierEdgeBase, [{ + key: '_findBorderPositionBezier', /** - * unbind the events + * This function uses binary search to look for the point where the bezier curve crosses the border of the node. + * + * @param nearNode + * @param ctx + * @param viaNode + * @param nearNode + * @param ctx + * @param viaNode + * @param nearNode + * @param ctx + * @param viaNode */ - destroy: function() { - this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler); - this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler); - this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); - } - }; + value: function _findBorderPositionBezier(nearNode, ctx) { + var viaNode = arguments[2] === undefined ? this._getViaCoordinates() : arguments[2]; - /** - * create new input type manager - * called by the Manager constructor - * @param {Hammer} manager - * @returns {Input} - */ - function createInputInstance(manager) { - var Type; - var inputClass = manager.options.inputClass; + 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; + } - if (inputClass) { - Type = inputClass; - } else if (SUPPORT_POINTER_EVENTS) { - Type = PointerEventInput; - } else if (SUPPORT_ONLY_TOUCH) { - Type = TouchInput; - } else if (!SUPPORT_TOUCH) { - Type = MouseInput; - } else { - Type = TouchMouseInput; - } - return new (Type)(manager, inputHandler); - } + while (low <= high && iteration < maxIterations) { + var middle = (low + high) * 0.5; - /** - * handle input events - * @param {Manager} manager - * @param {String} eventType - * @param {Object} input - */ - function inputHandler(manager, eventType, input) { - var pointersLen = input.pointers.length; - var changedPointersLen = input.changedPointers.length; - var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0)); - var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0)); + 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; + } + } - input.isFirst = !!isFirst; - input.isFinal = !!isFinal; + iteration++; + } + pos.t = middle; - if (isFirst) { - manager.session = {}; + return pos; } + }, { + key: '_getDistanceToBezierEdge', - // source event is the normalized value of the domEvents - // like 'touchstart, mouseup, pointerdown' - input.eventType = eventType; + /** + * 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 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {number} x3 + * @param {number} y3 + * @private + */ + value: function _getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via) { + // x3,y3 is the point + var xVia = undefined, + yVia = undefined; + xVia = via.x; + yVia = via.y; + var minDistance = 1000000000; + var distance = undefined; + var i = undefined, + t = undefined, + x = undefined, + y = undefined; + 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) * xVia + Math.pow(t, 2) * x2; + y = Math.pow(1 - t, 2) * y1 + 2 * t * (1 - t) * yVia + 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; + } - // compute scale, rotation etc - computeInputData(manager, input); + return minDistance; + } + }]); - // emit secret event - manager.emit('hammer.input', input); + return BezierEdgeBase; + })(_EdgeBase3['default']); - manager.recognize(input); - manager.session.prevInput = input; - } + exports['default'] = BezierEdgeBase; + module.exports = exports['default']; - /** - * extend the data with some usable properties like scale, rotate, velocity etc - * @param {Object} manager - * @param {Object} input - */ - function computeInputData(manager, input) { - var session = manager.session; - var pointers = input.pointers; - var pointersLength = pointers.length; +/***/ }, +/* 85 */ +/***/ function(module, exports, __webpack_require__) { - // store the first input to calculate the distance and direction - if (!session.firstInput) { - session.firstInput = simpleCloneInputData(input); - } + 'use strict'; - // to compute scale and rotation we need to store the multiple touches - if (pointersLength > 1 && !session.firstMultiple) { - session.firstMultiple = simpleCloneInputData(input); - } else if (pointersLength === 1) { - session.firstMultiple = false; - } + Object.defineProperty(exports, '__esModule', { + value: true + }); - var firstInput = session.firstInput; - var firstMultiple = session.firstMultiple; - var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var center = input.center = getCenter(pointers); - input.timeStamp = now(); - input.deltaTime = input.timeStamp - firstInput.timeStamp; + function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _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; } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } } - input.angle = getAngle(offsetCenter, center); - input.distance = getDistance(offsetCenter, center); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - computeDeltaXY(session, input); - input.offsetDirection = getDirection(input.deltaX, input.deltaY); + var util = __webpack_require__(7); - input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1; - input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0; + var EdgeBase = (function () { + function EdgeBase(options, body, labelModule) { + _classCallCheck(this, EdgeBase); - computeIntervalInputData(session, input); + this.body = body; + this.labelModule = labelModule; + this.setOptions(options); + this.colorDirty = true; + this.color = {}; + this.selectionWidth = 2; + this.hoverWidth = 1.5; + } - // find the correct target - var target = manager.element; - if (hasParent(input.srcEvent.target, target)) { - target = input.srcEvent.target; + _createClass(EdgeBase, [{ + key: 'connect', + value: function connect() {} + }, { + key: 'cleanup', + value: function cleanup() { + return false; } - input.target = target; - } - - function computeDeltaXY(session, input) { - var center = input.center; - var offset = session.offsetDelta || {}; - var prevDelta = session.prevDelta || {}; - var prevInput = session.prevInput || {}; + }, { + key: 'setOptions', + value: function setOptions(options) { + this.options = options; + this.from = this.body.nodes[this.options.from]; + this.to = this.body.nodes[this.options.to]; + this.id = this.options.id; + } + }, { + key: 'togglePhysics', - if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) { - prevDelta = session.prevDelta = { - x: prevInput.deltaX || 0, - y: prevInput.deltaY || 0 - }; + /** + * overloadable if the shape has to toggle the via node to disabled + * @param status + */ + value: function togglePhysics(status) {} + }, { + key: 'drawLine', - offset = session.offsetDelta = { - x: center.x, - y: center.y - }; + /** + * Redraw a edge as a line + * Draw this edge in the given canvas + * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); + * @param {CanvasRenderingContext2D} ctx + * @private + */ + value: function drawLine(ctx, selected, hover) { + // set style + ctx.strokeStyle = this.getColor(ctx, selected, hover); + ctx.lineWidth = this.getLineWidth(selected, hover); + var via = undefined; + if (this.options.dashes !== false) { + via = this._drawDashedLine(ctx); + } else { + via = this._drawLine(ctx); + } + return via; } + }, { + key: '_drawLine', + value: function _drawLine(ctx) { + var via = undefined; + if (this.from != this.to) { + // draw line + via = this._line(ctx); + } else { + var _getCircleData = this._getCircleData(ctx); - input.deltaX = prevDelta.x + (center.x - offset.x); - input.deltaY = prevDelta.y + (center.y - offset.y); - } + var _getCircleData2 = _slicedToArray(_getCircleData, 3); - /** - * velocity is calculated every x ms - * @param {Object} session - * @param {Object} input - */ - function computeIntervalInputData(session, input) { - var last = session.lastInterval || input, - deltaTime = input.timeStamp - last.timeStamp, - velocity, velocityX, velocityY, direction; + var x = _getCircleData2[0]; + var y = _getCircleData2[1]; + var radius = _getCircleData2[2]; - if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) { - var deltaX = last.deltaX - input.deltaX; - var deltaY = last.deltaY - input.deltaY; + this._circle(ctx, x, y, radius); + } + return via; + } + }, { + key: '_drawDashedLine', + value: function _drawDashedLine(ctx) { + var via = undefined; + ctx.lineCap = 'round'; + var pattern = [5, 5]; + if (Array.isArray(this.options.dashes) === true) { + pattern = this.options.dashes; + } - var v = getVelocity(deltaTime, deltaX, deltaY); - velocityX = v.x; - velocityY = v.y; - velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y; - direction = getDirection(deltaX, deltaY); + // only firefox and chrome support this method, else we use the legacy one. + if (ctx.setLineDash !== undefined) { + ctx.save(); - session.lastInterval = input; - } else { - // use latest velocity info if it doesn't overtake a minimum period - velocity = last.velocity; - velocityX = last.velocityX; - velocityY = last.velocityY; - direction = last.direction; - } + // set dash settings for chrome or firefox + ctx.setLineDash(pattern); + ctx.lineDashOffset = 0; - input.velocity = velocity; - input.velocityX = velocityX; - input.velocityY = velocityY; - input.direction = direction; - } + // draw the line + if (this.from != this.to) { + // draw line + via = this._line(ctx); + } else { + var _getCircleData3 = this._getCircleData(ctx); - /** - * create a simple clone from the input used for storage of firstInput and firstMultiple - * @param {Object} input - * @returns {Object} clonedInputData - */ - function simpleCloneInputData(input) { - // make a simple copy of the pointers because we will get a reference if we don't - // we only need clientXY for the calculations - var pointers = []; - var i = 0; - while (i < input.pointers.length) { - pointers[i] = { - clientX: round(input.pointers[i].clientX), - clientY: round(input.pointers[i].clientY) - }; - i++; - } + var _getCircleData32 = _slicedToArray(_getCircleData3, 3); - return { - timeStamp: now(), - pointers: pointers, - center: getCenter(pointers), - deltaX: input.deltaX, - deltaY: input.deltaY - }; - } + var x = _getCircleData32[0]; + var y = _getCircleData32[1]; + var radius = _getCircleData32[2]; - /** - * get the center of all the pointers - * @param {Array} pointers - * @return {Object} center contains `x` and `y` properties - */ - function getCenter(pointers) { - var pointersLength = pointers.length; + this._circle(ctx, x, y, radius); + } - // no need to loop when only one touch - if (pointersLength === 1) { - return { - x: round(pointers[0].clientX), - y: round(pointers[0].clientY) - }; - } + // restore the dash settings. + ctx.setLineDash([0]); + ctx.lineDashOffset = 0; + ctx.restore(); + } else { + // unsupporting smooth lines - var x = 0, y = 0, i = 0; - while (i < pointersLength) { - x += pointers[i].clientX; - y += pointers[i].clientY; - i++; - } + if (this.from != this.to) { + // draw line + ctx.dashedLine(this.from.x, this.from.y, this.to.x, this.to.y, pattern); + } else { + var _getCircleData4 = this._getCircleData(ctx); + + var _getCircleData42 = _slicedToArray(_getCircleData4, 3); + + var x = _getCircleData42[0]; + var y = _getCircleData42[1]; + var radius = _getCircleData42[2]; - return { - x: round(x / pointersLength), - y: round(y / pointersLength) - }; - } + this._circle(ctx, x, y, radius); + } + // draw shadow if enabled + this.enableShadow(ctx); - /** - * calculate the velocity between two points. unit is in px per ms. - * @param {Number} deltaTime - * @param {Number} x - * @param {Number} y - * @return {Object} velocity `x` and `y` - */ - function getVelocity(deltaTime, x, y) { - return { - x: x / deltaTime || 0, - y: y / deltaTime || 0 - }; - } + ctx.stroke(); - /** - * get the direction between two points - * @param {Number} x - * @param {Number} y - * @return {Number} direction - */ - function getDirection(x, y) { - if (x === y) { - return DIRECTION_NONE; + // disable shadows for other elements. + this.disableShadow(ctx); + } + return via; } - - if (abs(x) >= abs(y)) { - return x > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; + }, { + key: 'findBorderPosition', + value: function findBorderPosition(nearNode, ctx, options) { + if (this.from != this.to) { + return this._findBorderPosition(nearNode, ctx, options); + } else { + return this._findBorderPositionCircle(nearNode, ctx, options); + } } - return y > 0 ? DIRECTION_UP : DIRECTION_DOWN; - } + }, { + key: 'findBorderPositions', + value: function findBorderPositions(ctx) { + var from = {}; + var to = {}; + if (this.from != this.to) { + from = this._findBorderPosition(this.from, ctx); + to = this._findBorderPosition(this.to, ctx); + } else { + var _getCircleData5 = this._getCircleData(ctx); - /** - * calculate the absolute distance between two points - * @param {Object} p1 {x, y} - * @param {Object} p2 {x, y} - * @param {Array} [props] containing x and y keys - * @return {Number} distance - */ - function getDistance(p1, p2, props) { - if (!props) { - props = PROPS_XY; - } - var x = p2[props[0]] - p1[props[0]], - y = p2[props[1]] - p1[props[1]]; + var _getCircleData52 = _slicedToArray(_getCircleData5, 3); - return Math.sqrt((x * x) + (y * y)); - } + var x = _getCircleData52[0]; + var y = _getCircleData52[1]; + var radius = _getCircleData52[2]; - /** - * calculate the angle between two coordinates - * @param {Object} p1 - * @param {Object} p2 - * @param {Array} [props] containing x and y keys - * @return {Number} angle - */ - function getAngle(p1, p2, props) { - if (!props) { - props = PROPS_XY; + from = this._findBorderPositionCircle(this.from, ctx, { x: x, y: y, low: 0.25, high: 0.6, direction: -1 }); + to = this._findBorderPositionCircle(this.from, ctx, { x: x, y: y, low: 0.6, high: 0.8, direction: 1 }); + } + return { from: from, to: to }; } - var x = p2[props[0]] - p1[props[0]], - y = p2[props[1]] - p1[props[1]]; - return Math.atan2(y, x) * 180 / Math.PI; - } + }, { + key: '_getCircleData', + value: function _getCircleData(ctx) { + var x = undefined, + y = undefined; + var node = this.from; + var radius = this.options.selfReferenceSize; - /** - * calculate the rotation degrees between two pointersets - * @param {Array} start array of pointers - * @param {Array} end array of pointers - * @return {Number} rotation - */ - function getRotation(start, end) { - return getAngle(end[1], end[0], PROPS_CLIENT_XY) - getAngle(start[1], start[0], PROPS_CLIENT_XY); - } + if (ctx !== undefined) { + if (node.shape.width === undefined) { + node.shape.resize(ctx); + } + } - /** - * calculate the scale factor between two pointersets - * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out - * @param {Array} start array of pointers - * @param {Array} end array of pointers - * @return {Number} scale - */ - function getScale(start, end) { - return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY); - } + // get circle coordinates + if (node.shape.width > node.shape.height) { + x = node.x + node.shape.width * 0.5; + y = node.y - radius; + } else { + x = node.x + radius; + y = node.y - node.shape.height * 0.5; + } + return [x, y, radius]; + } + }, { + key: '_pointOnCircle', - var MOUSE_INPUT_MAP = { - mousedown: INPUT_START, - mousemove: INPUT_MOVE, - mouseup: INPUT_END - }; + /** + * 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 + */ + 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) + }; + } + }, { + key: '_findBorderPositionCircle', - var MOUSE_ELEMENT_EVENTS = 'mousedown'; - var MOUSE_WINDOW_EVENTS = 'mousemove mouseup'; + /** + * This function uses binary search to look for the point where the circle crosses the border of the node. + * @param node + * @param ctx + * @param options + * @returns {*} + * @private + */ + value: function _findBorderPositionCircle(node, ctx, options) { + var x = options.x; + var y = options.y; + var low = options.low; + var high = options.high; + var direction = options.direction; - /** - * Mouse events input - * @constructor - * @extends Input - */ - function MouseInput() { - this.evEl = MOUSE_ELEMENT_EVENTS; - this.evWin = MOUSE_WINDOW_EVENTS; + var maxIterations = 10; + var iteration = 0; + var radius = this.options.selfReferenceSize; + var pos = undefined, + angle = undefined, + distanceToBorder = undefined, + distanceToPoint = undefined, + difference = undefined; + var threshold = 0.05; + var middle = (low + high) * 0.5; - this.allow = true; // used by Input.TouchMouse to disable mouse events - this.pressed = false; // mousedown state + while (low <= high && iteration < maxIterations) { + middle = (low + high) * 0.5; - Input.apply(this, arguments); - } + pos = this._pointOnCircle(x, y, radius, middle); + 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 (direction > 0) { + low = middle; + } else { + high = middle; + } + } else { + if (direction > 0) { + high = middle; + } else { + low = middle; + } + } + iteration++; + } + pos.t = middle; + + return pos; + } + }, { + key: 'getLineWidth', - inherit(MouseInput, Input, { /** - * handle mouse events - * @param {Object} ev + * Get the line width of the edge. Depends on width and whether one of the + * connected nodes is selected. + * @return {Number} width + * @private */ - handler: function MEhandler(ev) { - var eventType = MOUSE_INPUT_MAP[ev.type]; - - // on start we want to have the left mouse button down - if (eventType & INPUT_START && ev.button === 0) { - this.pressed = true; + value: function getLineWidth(selected, hover) { + if (selected === true) { + return Math.max(this.selectionWidth, 0.3 / this.body.view.scale); + } else { + if (hover === true) { + return Math.max(this.hoverWidth, 0.3 / this.body.view.scale); + } else { + return Math.max(this.options.width, 0.3 / this.body.view.scale); } + } + } + }, { + key: 'getColor', + value: function getColor(ctx, selected, hover) { + var colorOptions = this.options.color; + if (colorOptions.inherit !== false) { + // when this is a loop edge, just use the 'from' method + if (colorOptions.inherit === 'both' && this.from.id !== this.to.id) { + var grd = ctx.createLinearGradient(this.from.x, this.from.y, this.to.x, this.to.y); + var fromColor = undefined, + toColor = undefined; + fromColor = this.from.options.color.highlight.border; + toColor = this.to.options.color.highlight.border; - if (eventType & INPUT_MOVE && ev.which !== 1) { - eventType = INPUT_END; - } + if (this.from.selected === false && this.to.selected === false) { + fromColor = util.overrideOpacity(this.from.options.color.border, this.options.color.opacity); + toColor = util.overrideOpacity(this.to.options.color.border, this.options.color.opacity); + } else if (this.from.selected === true && this.to.selected === false) { + toColor = this.to.options.color.border; + } else if (this.from.selected === false && this.to.selected === true) { + fromColor = this.from.options.color.border; + } + grd.addColorStop(0, fromColor); + grd.addColorStop(1, toColor); - // mouse must be down, and mouse events are allowed (see the TouchMouse input) - if (!this.pressed || !this.allow) { - return; + // -------------------- this returns -------------------- // + return grd; } - if (eventType & INPUT_END) { - this.pressed = false; + if (this.colorDirty === true) { + if (colorOptions.inherit === 'to') { + this.color.highlight = this.to.options.color.highlight.border; + this.color.hover = this.to.options.color.hover.border; + this.color.color = util.overrideOpacity(this.to.options.color.border, colorOptions.opacity); + } else { + // (this.options.color.inherit.source === "from") { + this.color.highlight = this.from.options.color.highlight.border; + this.color.hover = this.from.options.color.hover.border; + this.color.color = util.overrideOpacity(this.from.options.color.border, colorOptions.opacity); + } } + } else if (this.colorDirty === true) { + this.color.highlight = colorOptions.highlight; + this.color.hover = colorOptions.hover; + this.color.color = util.overrideOpacity(colorOptions.color, colorOptions.opacity); + } - this.callback(this.manager, eventType, { - pointers: [ev], - changedPointers: [ev], - pointerType: INPUT_TYPE_MOUSE, - srcEvent: ev - }); + // if color inherit is on and gradients are used, the function has already returned by now. + this.colorDirty = false; + + if (selected === true) { + return this.color.highlight; + } else if (hover === true) { + return this.color.hover; + } else { + return this.color.color; + } } - }); + }, { + key: '_circle', - var POINTER_INPUT_MAP = { - pointerdown: INPUT_START, - pointermove: INPUT_MOVE, - pointerup: INPUT_END, - pointercancel: INPUT_CANCEL, - pointerout: INPUT_CANCEL - }; + /** + * Draw a line from a node to itself, a circle + * @param {CanvasRenderingContext2D} ctx + * @param {Number} x + * @param {Number} y + * @param {Number} radius + * @private + */ + value: function _circle(ctx, x, y, radius) { + // draw shadow if enabled + this.enableShadow(ctx); - // in IE10 the pointer types is defined as an enum - var IE10_POINTER_TYPE_ENUM = { - 2: INPUT_TYPE_TOUCH, - 3: INPUT_TYPE_PEN, - 4: INPUT_TYPE_MOUSE, - 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816 - }; + // draw a circle + ctx.beginPath(); + ctx.arc(x, y, radius, 0, 2 * Math.PI, false); + ctx.stroke(); - var POINTER_ELEMENT_EVENTS = 'pointerdown'; - var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel'; + // disable shadows for other elements. + this.disableShadow(ctx); + } + }, { + key: 'getDistanceToEdge', - // IE10 has prefixed support, and case-sensitive - if (window.MSPointerEvent) { - POINTER_ELEMENT_EVENTS = 'MSPointerDown'; - POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel'; - } + /** + * 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 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {number} x3 + * @param {number} y3 + * @private + */ + value: function getDistanceToEdge(x1, y1, x2, y2, x3, y3, via) { + // x3,y3 is the point + var returnValue = 0; + if (this.from != this.to) { + returnValue = this._getDistanceToEdge(x1, y1, x2, y2, x3, y3, via); + } else { + var _getCircleData6 = this._getCircleData(); - /** - * Pointer events input - * @constructor - * @extends Input - */ - function PointerEventInput() { - this.evEl = POINTER_ELEMENT_EVENTS; - this.evWin = POINTER_WINDOW_EVENTS; + var _getCircleData62 = _slicedToArray(_getCircleData6, 3); - Input.apply(this, arguments); + var x = _getCircleData62[0]; + var y = _getCircleData62[1]; + var radius = _getCircleData62[2]; - this.store = (this.manager.session.pointerEvents = []); - } + var dx = x - x3; + var dy = y - y3; + returnValue = Math.abs(Math.sqrt(dx * dx + dy * dy) - radius); + } - inherit(PointerEventInput, Input, { - /** - * handle mouse events - * @param {Object} ev - */ - handler: function PEhandler(ev) { - var store = this.store; - var removePointer = false; + if (this.labelModule.size.left < x3 && this.labelModule.size.left + this.labelModule.size.width > x3 && this.labelModule.size.top < y3 && this.labelModule.size.top + this.labelModule.size.height > y3) { + return 0; + } else { + return returnValue; + } + } + }, { + key: '_getDistanceToLine', + value: function _getDistanceToLine(x1, y1, x2, y2, x3, y3) { + var px = x2 - x1; + var py = y2 - y1; + var something = px * px + py * py; + var u = ((x3 - x1) * px + (y3 - y1) * py) / something; - var eventTypeNormalized = ev.type.toLowerCase().replace('ms', ''); - var eventType = POINTER_INPUT_MAP[eventTypeNormalized]; - var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType; + if (u > 1) { + u = 1; + } else if (u < 0) { + u = 0; + } - var isTouch = (pointerType == INPUT_TYPE_TOUCH); + var x = x1 + u * px; + var y = y1 + u * py; + var dx = x - x3; + var dy = y - y3; - // get index of the event in the store - var storeIndex = inArray(store, ev.pointerId, 'pointerId'); + //# Note: If the actual distance does not matter, + //# if you only want to compare what this function + //# returns to other results of this function, you + //# can just return the squared distance instead + //# (i.e. remove the sqrt) to gain a little performance - // start and mouse must be down - if (eventType & INPUT_START && (ev.button === 0 || isTouch)) { - if (storeIndex < 0) { - store.push(ev); - storeIndex = store.length - 1; - } - } else if (eventType & (INPUT_END | INPUT_CANCEL)) { - removePointer = true; - } + return Math.sqrt(dx * dx + dy * dy); + } + }, { + key: 'drawArrowHead', - // it not found, so the pointer hasn't been down (so it's probably a hover) - if (storeIndex < 0) { - return; - } + /** + * + * @param ctx + * @param position + * @param viaNode + */ + value: function drawArrowHead(ctx, position, viaNode, selected, hover) { + // set style + ctx.strokeStyle = this.getColor(ctx, selected, hover); + ctx.fillStyle = ctx.strokeStyle; + ctx.lineWidth = this.getLineWidth(selected, hover); - // update the event in the store - store[storeIndex] = ev; + // set lets + var angle = undefined; + var length = undefined; + var arrowPos = undefined; + var node1 = undefined; + var node2 = undefined; + var guideOffset = undefined; + var scaleFactor = undefined; - this.callback(this.manager, eventType, { - pointers: store, - changedPointers: [ev], - pointerType: pointerType, - srcEvent: ev - }); + if (position === 'from') { + node1 = this.from; + node2 = this.to; + guideOffset = 0.1; + scaleFactor = this.options.arrows.from.scaleFactor; + } else if (position === 'to') { + node1 = this.to; + node2 = this.from; + guideOffset = -0.1; + scaleFactor = this.options.arrows.to.scaleFactor; + } else { + node1 = this.to; + node2 = this.from; + scaleFactor = this.options.arrows.middle.scaleFactor; + } - if (removePointer) { - // remove from the store - store.splice(storeIndex, 1); + // if not connected to itself + if (node1 != node2) { + if (position !== 'middle') { + // draw arrow head + if (this.options.smooth.enabled === true) { + arrowPos = this.findBorderPosition(node1, ctx, { via: viaNode }); + var guidePos = this.getPoint(Math.max(0, Math.min(1, arrowPos.t + guideOffset)), viaNode); + angle = Math.atan2(arrowPos.y - guidePos.y, arrowPos.x - guidePos.x); + } else { + angle = Math.atan2(node1.y - node2.y, node1.x - node2.x); + arrowPos = this.findBorderPosition(node1, ctx); + } + } else { + angle = Math.atan2(node1.y - node2.y, node1.x - node2.x); + arrowPos = this.getPoint(0.6, viaNode); // this is 0.6 to account for the size of the arrow. } - } - }); - - var SINGLE_TOUCH_INPUT_MAP = { - touchstart: INPUT_START, - touchmove: INPUT_MOVE, - touchend: INPUT_END, - touchcancel: INPUT_CANCEL - }; + // draw arrow at the end of the line + length = (10 + 5 * this.options.width) * scaleFactor; + ctx.arrow(arrowPos.x, arrowPos.y, angle, length); - var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart'; - var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel'; + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); - /** - * Touch events input - * @constructor - * @extends Input - */ - function SingleTouchInput() { - this.evTarget = SINGLE_TOUCH_TARGET_EVENTS; - this.evWin = SINGLE_TOUCH_WINDOW_EVENTS; - this.started = false; + // disable shadows for other elements. + this.disableShadow(ctx); + ctx.stroke(); + } else { + // draw circle + var _angle = undefined, + point = undefined; - Input.apply(this, arguments); - } + var _getCircleData7 = this._getCircleData(ctx); - inherit(SingleTouchInput, Input, { - handler: function TEhandler(ev) { - var type = SINGLE_TOUCH_INPUT_MAP[ev.type]; + var _getCircleData72 = _slicedToArray(_getCircleData7, 3); - // should we handle the touch events? - if (type === INPUT_START) { - this.started = true; - } + var x = _getCircleData72[0]; + var y = _getCircleData72[1]; + var radius = _getCircleData72[2]; - if (!this.started) { - return; + if (position === 'from') { + point = this.findBorderPosition(this.from, ctx, { x: x, y: y, low: 0.25, high: 0.6, direction: -1 }); + _angle = point.t * -2 * Math.PI + 1.5 * Math.PI + 0.1 * Math.PI; + } else if (position === 'to') { + point = this.findBorderPosition(this.from, ctx, { x: x, y: y, low: 0.6, high: 1, direction: 1 }); + _angle = point.t * -2 * Math.PI + 1.5 * Math.PI - 1.1 * Math.PI; + } else { + point = this._pointOnCircle(x, y, radius, 0.175); + _angle = 3.9269908169872414; // === 0.175 * -2 * Math.PI + 1.5 * Math.PI + 0.1 * Math.PI; } - var touches = normalizeSingleTouches.call(this, ev, type); + // draw the arrowhead + var _length = (10 + 5 * this.options.width) * scaleFactor; + ctx.arrow(point.x, point.y, _angle, _length); - // when done, reset the started state - if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) { - this.started = false; - } + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); - this.callback(this.manager, type, { - pointers: touches[0], - changedPointers: touches[1], - pointerType: INPUT_TYPE_TOUCH, - srcEvent: ev - }); + // disable shadows for other elements. + this.disableShadow(ctx); + ctx.stroke(); + } } - }); - - /** - * @this {TouchInput} - * @param {Object} ev - * @param {Number} type flag - * @returns {undefined|Array} [all, changed] - */ - function normalizeSingleTouches(ev, type) { - var all = toArray(ev.touches); - var changed = toArray(ev.changedTouches); - - if (type & (INPUT_END | INPUT_CANCEL)) { - all = uniqueArray(all.concat(changed), 'identifier', true); + }, { + key: 'enableShadow', + value: function enableShadow(ctx) { + if (this.options.shadow.enabled === true) { + ctx.shadowColor = 'rgba(0,0,0,0.5)'; + ctx.shadowBlur = this.options.shadow.size; + ctx.shadowOffsetX = this.options.shadow.x; + ctx.shadowOffsetY = this.options.shadow.y; + } } + }, { + key: 'disableShadow', + value: function disableShadow(ctx) { + if (this.options.shadow.enabled === true) { + ctx.shadowColor = 'rgba(0,0,0,0)'; + ctx.shadowBlur = 0; + ctx.shadowOffsetX = 0; + ctx.shadowOffsetY = 0; + } + } + }]); - return [all, changed]; - } - - var TOUCH_INPUT_MAP = { - touchstart: INPUT_START, - touchmove: INPUT_MOVE, - touchend: INPUT_END, - touchcancel: INPUT_CANCEL - }; - - var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel'; + return EdgeBase; + })(); - /** - * Multi-user touch events input - * @constructor - * @extends Input - */ - function TouchInput() { - this.evTarget = TOUCH_TARGET_EVENTS; - this.targetIds = {}; + exports['default'] = EdgeBase; + module.exports = exports['default']; - Input.apply(this, arguments); - } +/***/ }, +/* 86 */ +/***/ function(module, exports, __webpack_require__) { - inherit(TouchInput, Input, { - handler: function MTEhandler(ev) { - var type = TOUCH_INPUT_MAP[ev.type]; - var touches = getTouches.call(this, ev, type); - if (!touches) { - return; - } + 'use strict'; - this.callback(this.manager, type, { - pointers: touches[0], - changedPointers: touches[1], - pointerType: INPUT_TYPE_TOUCH, - srcEvent: ev - }); - } + Object.defineProperty(exports, '__esModule', { + value: true }); - /** - * @this {TouchInput} - * @param {Object} ev - * @param {Number} type flag - * @returns {undefined|Array} [all, changed] - */ - function getTouches(ev, type) { - var allTouches = toArray(ev.touches); - var targetIds = this.targetIds; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - // when there is only one touch, the process can be simplified - if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) { - targetIds[allTouches[0].identifier] = true; - return [allTouches, allTouches]; - } + var _get = function get(_x4, _x5, _x6) { var _again = true; _function: while (_again) { var object = _x4, property = _x5, receiver = _x6; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x4 = parent; _x5 = property; _x6 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - var i, - targetTouches, - changedTouches = toArray(ev.changedTouches), - changedTargetTouches = [], - target = this.target; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - // get target touches from touches - targetTouches = allTouches.filter(function(touch) { - return hasParent(touch.target, target); - }); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - // collect touches - if (type === INPUT_START) { - i = 0; - while (i < targetTouches.length) { - targetIds[targetTouches[i].identifier] = true; - i++; - } - } + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - // filter changed touches to only contain touches that exist in the collected target ids - i = 0; - while (i < changedTouches.length) { - if (targetIds[changedTouches[i].identifier]) { - changedTargetTouches.push(changedTouches[i]); - } + var _utilBezierEdgeBase = __webpack_require__(84); - // cleanup removed touches - if (type & (INPUT_END | INPUT_CANCEL)) { - delete targetIds[changedTouches[i].identifier]; - } - i++; - } + var _utilBezierEdgeBase2 = _interopRequireDefault(_utilBezierEdgeBase); - if (!changedTargetTouches.length) { - return; - } + var BezierEdgeStatic = (function (_BezierEdgeBase) { + function BezierEdgeStatic(options, body, labelModule) { + _classCallCheck(this, BezierEdgeStatic); - return [ - // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel' - uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true), - changedTargetTouches - ]; - } + _get(Object.getPrototypeOf(BezierEdgeStatic.prototype), 'constructor', this).call(this, options, body, labelModule); + } - /** - * Combined touch and mouse input - * - * Touch has a higher priority then mouse, and while touching no mouse events are allowed. - * This because touch devices also emit mouse events while doing a touch. - * - * @constructor - * @extends Input - */ - function TouchMouseInput() { - Input.apply(this, arguments); + _inherits(BezierEdgeStatic, _BezierEdgeBase); - var handler = bindFn(this.handler, this); - this.touch = new TouchInput(this.manager, handler); - this.mouse = new MouseInput(this.manager, handler); - } + _createClass(BezierEdgeStatic, [{ + key: '_line', - inherit(TouchMouseInput, Input, { /** - * handle mouse and touch events - * @param {Hammer} manager - * @param {String} inputEvent - * @param {Object} inputData + * Draw a line between two nodes + * @param {CanvasRenderingContext2D} ctx + * @private */ - handler: function TMEhandler(manager, inputEvent, inputData) { - var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH), - isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE); + value: function _line(ctx) { + // draw a straight line + ctx.beginPath(); + ctx.moveTo(this.from.x, this.from.y); + var via = this._getViaCoordinates(); + var returnValue = via; - // when we're in a touch event, so block all upcoming mouse events - // most mobile browser also emit mouseevents, right after touchstart - if (isTouch) { - this.mouse.allow = false; - } else if (isMouse && !this.mouse.allow) { - return; + // fallback to normal straight edges + if (via.x === undefined) { + ctx.lineTo(this.to.x, this.to.y); + returnValue = undefined; + } else { + ctx.quadraticCurveTo(via.x, via.y, this.to.x, this.to.y); + } + // draw shadow if enabled + this.enableShadow(ctx); + ctx.stroke(); + this.disableShadow(ctx); + return returnValue; + } + }, { + key: '_getViaCoordinates', + value: function _getViaCoordinates() { + var xVia = undefined; + var yVia = undefined; + var factor = this.options.smooth.roundness; + var type = this.options.smooth.type; + var dx = Math.abs(this.from.x - this.to.x); + var dy = Math.abs(this.from.y - this.to.y); + if (type === 'discrete' || type === 'diagonalCross') { + if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { + if (this.from.y > this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dy; + yVia = this.from.y - factor * dy; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dy; + yVia = this.from.y - factor * dy; + } + } else if (this.from.y < this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dy; + yVia = this.from.y + factor * dy; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dy; + yVia = this.from.y + factor * dy; + } + } + if (type === 'discrete') { + xVia = dx < factor * dy ? this.from.x : xVia; + } + } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { + if (this.from.y > this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dx; + yVia = this.from.y - factor * dx; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dx; + yVia = this.from.y - factor * dx; + } + } else if (this.from.y < this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dx; + yVia = this.from.y + factor * dx; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dx; + yVia = this.from.y + factor * dx; + } + } + if (type === 'discrete') { + yVia = dy < factor * dx ? this.from.y : yVia; + } + } + } else if (type === 'straightCross') { + if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { + // up - down + xVia = this.from.x; + if (this.from.y < this.to.y) { + yVia = this.to.y - (1 - factor) * dy; + } else { + yVia = this.to.y + (1 - factor) * dy; + } + } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { + // left - right + if (this.from.x < this.to.x) { + xVia = this.to.x - (1 - factor) * dx; + } else { + xVia = this.to.x + (1 - factor) * dx; + } + yVia = this.from.y; + } + } else if (type === 'horizontal') { + if (this.from.x < this.to.x) { + xVia = this.to.x - (1 - factor) * dx; + } else { + xVia = this.to.x + (1 - factor) * dx; + } + yVia = this.from.y; + } else if (type === 'vertical') { + xVia = this.from.x; + if (this.from.y < this.to.y) { + yVia = this.to.y - (1 - factor) * dy; + } else { + yVia = this.to.y + (1 - factor) * dy; } + } else if (type === 'curvedCW') { + dx = this.to.x - this.from.x; + dy = this.from.y - this.to.y; + var radius = Math.sqrt(dx * dx + dy * dy); + var pi = Math.PI; - // reset the allowMouse when we're done - if (inputEvent & (INPUT_END | INPUT_CANCEL)) { - this.mouse.allow = true; + var originalAngle = Math.atan2(dy, dx); + var myAngle = (originalAngle + (factor * 0.5 + 0.5) * pi) % (2 * pi); + + xVia = this.from.x + (factor * 0.5 + 0.5) * radius * Math.sin(myAngle); + yVia = this.from.y + (factor * 0.5 + 0.5) * radius * Math.cos(myAngle); + } else if (type === 'curvedCCW') { + dx = this.to.x - this.from.x; + dy = this.from.y - this.to.y; + var radius = Math.sqrt(dx * dx + dy * dy); + var pi = Math.PI; + + var originalAngle = Math.atan2(dy, dx); + var myAngle = (originalAngle + (-factor * 0.5 + 0.5) * pi) % (2 * pi); + + xVia = this.from.x + (factor * 0.5 + 0.5) * radius * Math.sin(myAngle); + yVia = this.from.y + (factor * 0.5 + 0.5) * radius * Math.cos(myAngle); + } else { + // continuous + if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { + if (this.from.y > this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dy; + yVia = this.from.y - factor * dy; + xVia = this.to.x < xVia ? this.to.x : xVia; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dy; + yVia = this.from.y - factor * dy; + xVia = this.to.x > xVia ? this.to.x : xVia; + } + } else if (this.from.y < this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dy; + yVia = this.from.y + factor * dy; + xVia = this.to.x < xVia ? this.to.x : xVia; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dy; + yVia = this.from.y + factor * dy; + xVia = this.to.x > xVia ? this.to.x : xVia; + } + } + } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { + if (this.from.y > this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dx; + yVia = this.from.y - factor * dx; + yVia = this.to.y > yVia ? this.to.y : yVia; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dx; + yVia = this.from.y - factor * dx; + yVia = this.to.y > yVia ? this.to.y : yVia; + } + } else if (this.from.y < this.to.y) { + if (this.from.x < this.to.x) { + xVia = this.from.x + factor * dx; + yVia = this.from.y + factor * dx; + yVia = this.to.y < yVia ? this.to.y : yVia; + } else if (this.from.x > this.to.x) { + xVia = this.from.x - factor * dx; + yVia = this.from.y + factor * dx; + yVia = this.to.y < yVia ? this.to.y : yVia; + } + } } + } + return { x: xVia, y: yVia }; + } + }, { + key: '_findBorderPosition', + value: function _findBorderPosition(nearNode, ctx) { + var options = arguments[2] === undefined ? {} : arguments[2]; - this.callback(manager, inputEvent, inputData); - }, + return this._findBorderPositionBezier(nearNode, ctx, options.via); + } + }, { + key: '_getDistanceToEdge', + value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) { + var via = arguments[6] === undefined ? this._getViaCoordinates() : arguments[6]; + // x3,y3 is the point + return this._getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via); + } + }, { + key: 'getPoint', /** - * remove the event listeners + * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way + * @param percentage + * @param via + * @returns {{x: number, y: number}} + * @private */ - destroy: function destroy() { - this.touch.destroy(); - this.mouse.destroy(); + value: function getPoint(percentage) { + var via = arguments[1] === undefined ? this._getViaCoordinates() : arguments[1]; + + var t = percentage; + var x = Math.pow(1 - t, 2) * this.from.x + 2 * t * (1 - t) * via.x + Math.pow(t, 2) * this.to.x; + var y = Math.pow(1 - t, 2) * this.from.y + 2 * t * (1 - t) * via.y + Math.pow(t, 2) * this.to.y; + + return { x: x, y: y }; } - }); + }]); - var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction'); - var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined; + return BezierEdgeStatic; + })(_utilBezierEdgeBase2['default']); - // magical touchAction value - var TOUCH_ACTION_COMPUTE = 'compute'; - var TOUCH_ACTION_AUTO = 'auto'; - var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented - var TOUCH_ACTION_NONE = 'none'; - var TOUCH_ACTION_PAN_X = 'pan-x'; - var TOUCH_ACTION_PAN_Y = 'pan-y'; + exports['default'] = BezierEdgeStatic; + module.exports = exports['default']; - /** - * Touch Action - * sets the touchAction property or uses the js alternative - * @param {Manager} manager - * @param {String} value - * @constructor - */ - function TouchAction(manager, value) { - this.manager = manager; - this.set(value); - } +/***/ }, +/* 87 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - TouchAction.prototype = { - /** - * set the touchAction value on the element or enable the polyfill - * @param {String} value - */ - set: function(value) { - // find out the touch-action by the event handlers - if (value == TOUCH_ACTION_COMPUTE) { - value = this.compute(); - } + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - if (NATIVE_TOUCH_ACTION) { - this.manager.element.style[PREFIXED_TOUCH_ACTION] = value; - } - this.actions = value.toLowerCase().trim(); - }, + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - /** - * just re-set the touchAction value - */ - update: function() { - this.set(this.manager.options.touchAction); - }, + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - /** - * compute the value for the touchAction property based on the recognizer's settings - * @returns {String} value - */ - compute: function() { - var actions = []; - each(this.manager.recognizers, function(recognizer) { - if (boolOrFn(recognizer.options.enable, [recognizer])) { - actions = actions.concat(recognizer.getTouchAction()); - } - }); - return cleanTouchActions(actions.join(' ')); - }, + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - /** - * this method is called on each input cycle and provides the preventing of the browser behavior - * @param {Object} input - */ - preventDefaults: function(input) { - // not needed with native support for the touchAction property - if (NATIVE_TOUCH_ACTION) { - return; - } + var _utilEdgeBase = __webpack_require__(85); - var srcEvent = input.srcEvent; - var direction = input.offsetDirection; + var _utilEdgeBase2 = _interopRequireDefault(_utilEdgeBase); - // if the touch action did prevented once this session - if (this.manager.session.prevented) { - srcEvent.preventDefault(); - return; - } + var StraightEdge = (function (_EdgeBase) { + function StraightEdge(options, body, labelModule) { + _classCallCheck(this, StraightEdge); - var actions = this.actions; - var hasNone = inStr(actions, TOUCH_ACTION_NONE); - var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); - var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); + _get(Object.getPrototypeOf(StraightEdge.prototype), 'constructor', this).call(this, options, body, labelModule); + } - if (hasNone || - (hasPanY && direction & DIRECTION_HORIZONTAL) || - (hasPanX && direction & DIRECTION_VERTICAL)) { - return this.preventSrc(srcEvent); - } - }, + _inherits(StraightEdge, _EdgeBase); + + _createClass(StraightEdge, [{ + key: '_line', /** - * call preventDefault to prevent the browser's default behavior (scrolling in most cases) - * @param {Object} srcEvent + * Draw a line between two nodes + * @param {CanvasRenderingContext2D} ctx + * @private */ - preventSrc: function(srcEvent) { - this.manager.session.prevented = true; - srcEvent.preventDefault(); + value: function _line(ctx) { + // draw a straight line + ctx.beginPath(); + ctx.moveTo(this.from.x, this.from.y); + ctx.lineTo(this.to.x, this.to.y); + // draw shadow if enabled + this.enableShadow(ctx); + ctx.stroke(); + this.disableShadow(ctx); + return undefined; } - }; + }, { + key: 'getPoint', - /** - * when the touchActions are collected they are not a valid value, so we need to clean things up. * - * @param {String} actions - * @returns {*} - */ - function cleanTouchActions(actions) { - // none - if (inStr(actions, TOUCH_ACTION_NONE)) { - return TOUCH_ACTION_NONE; + /** + * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way + * @param percentage + * @param via + * @returns {{x: number, y: number}} + * @private + */ + value: function getPoint(percentage) { + return { + x: (1 - percentage) * this.from.x + percentage * this.to.x, + y: (1 - percentage) * this.from.y + percentage * this.to.y + }; } + }, { + key: '_findBorderPosition', + value: function _findBorderPosition(nearNode, ctx) { + var node1 = this.to; + var node2 = this.from; + if (nearNode.id === this.from.id) { + node1 = this.from; + node2 = this.to; + } - var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); - var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); + var angle = Math.atan2(node1.y - node2.y, node1.x - node2.x); + var dx = node1.x - node2.x; + var dy = node1.y - node2.y; + var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); + var toBorderDist = nearNode.distanceToBorder(ctx, angle); + var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength; - // pan-x and pan-y can be combined - if (hasPanX && hasPanY) { - return TOUCH_ACTION_PAN_X + ' ' + TOUCH_ACTION_PAN_Y; - } + var borderPos = {}; + borderPos.x = (1 - toBorderPoint) * node2.x + toBorderPoint * node1.x; + borderPos.y = (1 - toBorderPoint) * node2.y + toBorderPoint * node1.y; - // pan-x OR pan-y - if (hasPanX || hasPanY) { - return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y; + return borderPos; } - - // manipulation - if (inStr(actions, TOUCH_ACTION_MANIPULATION)) { - return TOUCH_ACTION_MANIPULATION; + }, { + key: '_getDistanceToEdge', + value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) { + // x3,y3 is the point + return this._getDistanceToLine(x1, y1, x2, y2, x3, y3); } + }]); - return TOUCH_ACTION_AUTO; - } + return StraightEdge; + })(_utilEdgeBase2['default']); - /** - * Recognizer flow explained; * - * All recognizers have the initial state of POSSIBLE when a input session starts. - * The definition of a input session is from the first input until the last input, with all it's movement in it. * - * Example session for mouse-input: mousedown -> mousemove -> mouseup - * - * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed - * which determines with state it should be. - * - * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to - * POSSIBLE to give it another change on the next cycle. - * - * Possible - * | - * +-----+---------------+ - * | | - * +-----+-----+ | - * | | | - * Failed Cancelled | - * +-------+------+ - * | | - * Recognized Began - * | - * Changed - * | - * Ended/Recognized - */ - var STATE_POSSIBLE = 1; - var STATE_BEGAN = 2; - var STATE_CHANGED = 4; - var STATE_ENDED = 8; - var STATE_RECOGNIZED = STATE_ENDED; - var STATE_CANCELLED = 16; - var STATE_FAILED = 32; + exports['default'] = StraightEdge; + module.exports = exports['default']; - /** - * Recognizer - * Every recognizer needs to extend from this class. - * @constructor - * @param {Object} options - */ - function Recognizer(options) { - this.id = uniqueId(); +/***/ }, +/* 88 */ +/***/ function(module, exports, __webpack_require__) { - this.manager = null; - this.options = merge(options || {}, this.defaults); + 'use strict'; - // default is enable true - this.options.enable = ifUndefined(this.options.enable, true); + Object.defineProperty(exports, '__esModule', { + value: true + }); - this.state = STATE_POSSIBLE; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - this.simultaneous = {}; - this.requireFail = []; - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - Recognizer.prototype = { - /** - * @virtual - * @type {Object} - */ - defaults: {}, + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - /** - * set options - * @param {Object} options - * @return {Recognizer} - */ - set: function(options) { - extend(this.options, options); + var _componentsPhysicsBarnesHutSolver = __webpack_require__(89); - // also update the touchAction, in case something changed about the directions/enabled state - this.manager && this.manager.touchAction.update(); - return this; - }, + var _componentsPhysicsBarnesHutSolver2 = _interopRequireDefault(_componentsPhysicsBarnesHutSolver); - /** - * recognize simultaneous with an other recognizer. - * @param {Recognizer} otherRecognizer - * @returns {Recognizer} this - */ - recognizeWith: function(otherRecognizer) { - if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) { - return this; - } + var _componentsPhysicsRepulsionSolver = __webpack_require__(90); - var simultaneous = this.simultaneous; - otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); - if (!simultaneous[otherRecognizer.id]) { - simultaneous[otherRecognizer.id] = otherRecognizer; - otherRecognizer.recognizeWith(this); - } - return this; - }, + var _componentsPhysicsRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsRepulsionSolver); - /** - * drop the simultaneous link. it doesnt remove the link on the other recognizer. - * @param {Recognizer} otherRecognizer - * @returns {Recognizer} this - */ - dropRecognizeWith: function(otherRecognizer) { - if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) { - return this; - } + var _componentsPhysicsHierarchicalRepulsionSolver = __webpack_require__(91); - otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); - delete this.simultaneous[otherRecognizer.id]; - return this; - }, + var _componentsPhysicsHierarchicalRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsHierarchicalRepulsionSolver); - /** - * recognizer can only run when an other is failing - * @param {Recognizer} otherRecognizer - * @returns {Recognizer} this - */ - requireFailure: function(otherRecognizer) { - if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) { - return this; - } + var _componentsPhysicsSpringSolver = __webpack_require__(92); - var requireFail = this.requireFail; - otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); - if (inArray(requireFail, otherRecognizer) === -1) { - requireFail.push(otherRecognizer); - otherRecognizer.requireFailure(this); - } - return this; - }, + var _componentsPhysicsSpringSolver2 = _interopRequireDefault(_componentsPhysicsSpringSolver); - /** - * drop the requireFailure link. it does not remove the link on the other recognizer. - * @param {Recognizer} otherRecognizer - * @returns {Recognizer} this - */ - dropRequireFailure: function(otherRecognizer) { - if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) { - return this; - } + var _componentsPhysicsHierarchicalSpringSolver = __webpack_require__(93); - otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); - var index = inArray(this.requireFail, otherRecognizer); - if (index > -1) { - this.requireFail.splice(index, 1); - } - return this; - }, + var _componentsPhysicsHierarchicalSpringSolver2 = _interopRequireDefault(_componentsPhysicsHierarchicalSpringSolver); - /** - * has require failures boolean - * @returns {boolean} - */ - hasRequireFailures: function() { - return this.requireFail.length > 0; - }, + var _componentsPhysicsCentralGravitySolver = __webpack_require__(94); - /** - * if the recognizer can recognize simultaneous with an other recognizer - * @param {Recognizer} otherRecognizer - * @returns {Boolean} - */ - canRecognizeWith: function(otherRecognizer) { - return !!this.simultaneous[otherRecognizer.id]; - }, + var _componentsPhysicsCentralGravitySolver2 = _interopRequireDefault(_componentsPhysicsCentralGravitySolver); - /** - * You should use `tryEmit` instead of `emit` directly to check - * that all the needed recognizers has failed before emitting. - * @param {Object} input - */ - emit: function(input) { - var self = this; - var state = this.state; + var _componentsPhysicsFA2BasedRepulsionSolver = __webpack_require__(95); - function emit(withState) { - self.manager.emit(self.options.event + (withState ? stateStr(state) : ''), input); - } + var _componentsPhysicsFA2BasedRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsFA2BasedRepulsionSolver); - // 'panstart' and 'panmove' - if (state < STATE_ENDED) { - emit(true); - } + var _componentsPhysicsFA2BasedCentralGravitySolver = __webpack_require__(96); - emit(); // simple 'eventName' events + var _componentsPhysicsFA2BasedCentralGravitySolver2 = _interopRequireDefault(_componentsPhysicsFA2BasedCentralGravitySolver); - // panend and pancancel - if (state >= STATE_ENDED) { - emit(true); - } - }, + var util = __webpack_require__(7); - /** - * Check that all the require failure recognizers has failed, - * if true, it emits a gesture event, - * otherwise, setup the state to FAILED. - * @param {Object} input - */ - tryEmit: function(input) { - if (this.canEmit()) { - return this.emit(input); - } - // it's failing anyway - this.state = STATE_FAILED; - }, + var PhysicsEngine = (function () { + function PhysicsEngine(body) { + _classCallCheck(this, PhysicsEngine); - /** - * can we emit? - * @returns {boolean} - */ - canEmit: function() { - var i = 0; - while (i < this.requireFail.length) { - if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) { - return false; - } - i++; + this.body = body; + this.physicsBody = { physicsNodeIndices: [], physicsEdgeIndices: [], forces: {}, velocities: {} }; + + this.physicsEnabled = true; + this.simulationInterval = 1000 / 60; + this.requiresTimeout = true; + this.previousStates = {}; + this.freezeCache = {}; + this.renderTimer = undefined; + + this.stabilized = false; + this.startedStabilization = false; + this.stabilizationIterations = 0; + this.ready = false; // will be set to true if the stabilize + + // default options + this.options = {}; + this.defaultOptions = { + barnesHut: { + theta: 0.5, + gravitationalConstant: -2000, + centralGravity: 0.3, + springLength: 95, + springConstant: 0.04, + damping: 0.09, + avoidOverlap: 0 + }, + forceAtlas2Based: { + theta: 0.5, + gravitationalConstant: -50, + centralGravity: 0.01, + springConstant: 0.08, + springLength: 100, + damping: 0.4, + avoidOverlap: 0 + }, + repulsion: { + centralGravity: 0.2, + springLength: 200, + springConstant: 0.05, + nodeDistance: 100, + damping: 0.09, + avoidOverlap: 0 + }, + hierarchicalRepulsion: { + centralGravity: 0, + springLength: 100, + springConstant: 0.01, + nodeDistance: 120, + damping: 0.09 + }, + maxVelocity: 50, + minVelocity: 0.1, // px/s + solver: 'barnesHut', + stabilization: { + enabled: true, + iterations: 1000, // maximum number of iteration to stabilize + updateInterval: 50, + onlyDynamicEdges: false, + fit: true + }, + timestep: 0.5 + }; + util.extend(this.options, this.defaultOptions); + + this.bindEventListeners(); + } + + _createClass(PhysicsEngine, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this = this; + + this.body.emitter.on('initPhysics', function () { + _this.initPhysics(); + }); + this.body.emitter.on('resetPhysics', function () { + _this.stopSimulation();_this.ready = false; + }); + this.body.emitter.on('disablePhysics', function () { + _this.physicsEnabled = false;_this.stopSimulation(); + }); + this.body.emitter.on('restorePhysics', function () { + _this.setOptions(_this.options); + if (_this.ready === true) { + _this.startSimulation(); + } + }); + this.body.emitter.on('startSimulation', function () { + if (_this.ready === true) { + _this.startSimulation(); + } + }); + this.body.emitter.on('stopSimulation', function () { + _this.stopSimulation(); + }); + this.body.emitter.on('destroy', function () { + _this.stopSimulation(false); + _this.body.emitter.off(); + }); + } + }, { + key: 'setOptions', + value: function setOptions(options) { + if (options !== undefined) { + if (options === false) { + this.physicsEnabled = false; + this.stopSimulation(); + } else { + this.physicsEnabled = true; + util.selectiveNotDeepExtend(['stabilization'], this.options, options); + util.mergeOptions(this.options, options, 'stabilization'); + } + } + this.init(); + } + }, { + key: 'init', + value: function init() { + var options; + if (this.options.solver === 'forceAtlas2Based') { + options = this.options.forceAtlas2Based; + this.nodesSolver = new _componentsPhysicsFA2BasedRepulsionSolver2['default'](this.body, this.physicsBody, options); + this.edgesSolver = new _componentsPhysicsSpringSolver2['default'](this.body, this.physicsBody, options); + this.gravitySolver = new _componentsPhysicsFA2BasedCentralGravitySolver2['default'](this.body, this.physicsBody, options); + } else if (this.options.solver === 'repulsion') { + options = this.options.repulsion; + this.nodesSolver = new _componentsPhysicsRepulsionSolver2['default'](this.body, this.physicsBody, options); + this.edgesSolver = new _componentsPhysicsSpringSolver2['default'](this.body, this.physicsBody, options); + this.gravitySolver = new _componentsPhysicsCentralGravitySolver2['default'](this.body, this.physicsBody, options); + } else if (this.options.solver === 'hierarchicalRepulsion') { + options = this.options.hierarchicalRepulsion; + this.nodesSolver = new _componentsPhysicsHierarchicalRepulsionSolver2['default'](this.body, this.physicsBody, options); + this.edgesSolver = new _componentsPhysicsHierarchicalSpringSolver2['default'](this.body, this.physicsBody, options); + this.gravitySolver = new _componentsPhysicsCentralGravitySolver2['default'](this.body, this.physicsBody, options); + } else { + // barnesHut + options = this.options.barnesHut; + this.nodesSolver = new _componentsPhysicsBarnesHutSolver2['default'](this.body, this.physicsBody, options); + this.edgesSolver = new _componentsPhysicsSpringSolver2['default'](this.body, this.physicsBody, options); + this.gravitySolver = new _componentsPhysicsCentralGravitySolver2['default'](this.body, this.physicsBody, options); + } + + this.modelOptions = options; + } + }, { + key: 'initPhysics', + value: function initPhysics() { + if (this.physicsEnabled === true) { + if (this.options.stabilization.enabled === true) { + this.stabilize(); + } else { + this.stabilized = false; + this.ready = true; + this.body.emitter.emit('fit', {}, true); + this.startSimulation(); } - return true; - }, + } else { + this.ready = true; + this.body.emitter.emit('fit'); + } + } + }, { + key: 'startSimulation', /** - * update the recognizer - * @param {Object} inputData + * Start the simulation */ - recognize: function(inputData) { - // make a new copy of the inputData - // so we can change the inputData without messing up the other recognizers - var inputDataClone = extend({}, inputData); - - // is is enabled and allow recognizing? - if (!boolOrFn(this.options.enable, [this, inputDataClone])) { - this.reset(); - this.state = STATE_FAILED; - return; - } - - // reset when we've reached the end - if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) { - this.state = STATE_POSSIBLE; - } + value: function startSimulation() { + if (this.physicsEnabled === true) { + this.stabilized = false; - this.state = this.process(inputDataClone); + // this sets the width of all nodes initially which could be required for the avoidOverlap + this.body.emitter.emit('_resizeNodes'); - // the recognizer has recognized a gesture - // so trigger an event - if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) { - this.tryEmit(inputDataClone); + if (this.viewFunction === undefined) { + this.viewFunction = this.simulationStep.bind(this); + this.body.emitter.on('initRedraw', this.viewFunction); + this.body.emitter.emit('_startRendering'); } - }, + } else { + this.body.emitter.emit('_redraw'); + } + } + }, { + key: 'stopSimulation', /** - * return the state of the recognizer - * the actual recognizing happens in this method - * @virtual - * @param {Object} inputData - * @returns {Const} STATE + * Stop the simulation, force stabilization. */ - process: function(inputData) { }, // jshint ignore:line + value: function stopSimulation() { + var emit = arguments[0] === undefined ? true : arguments[0]; - /** - * return the preferred touch-action - * @virtual - * @returns {Array} - */ - getTouchAction: function() { }, + this.stabilized = true; + if (emit === true) { + this._emitStabilized(); + } + if (this.viewFunction !== undefined) { + this.body.emitter.off('initRedraw', this.viewFunction); + this.viewFunction = undefined; + if (emit === true) { + this.body.emitter.emit('_stopRendering'); + } + } + } + }, { + key: 'simulationStep', /** - * called when the gesture isn't allowed to recognize - * like when another is being recognized or it is disabled - * @virtual + * The viewFunction inserts this step into each renderloop. It calls the physics tick and handles the cleanup at stabilized. + * */ - reset: function() { } - }; + value: function simulationStep() { + // check if the physics have settled + var startTime = Date.now(); + this.physicsTick(); + var physicsTime = Date.now() - startTime; - /** - * get a usable string, used as event postfix - * @param {Const} state - * @returns {String} state - */ - function stateStr(state) { - if (state & STATE_CANCELLED) { - return 'cancel'; - } else if (state & STATE_ENDED) { - return 'end'; - } else if (state & STATE_CHANGED) { - return 'move'; - } else if (state & STATE_BEGAN) { - return 'start'; - } - return ''; - } + // run double speed if it is a little graph + if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) { + this.physicsTick(); - /** - * direction cons to string - * @param {Const} direction - * @returns {String} - */ - function directionStr(direction) { - if (direction == DIRECTION_DOWN) { - return 'down'; - } else if (direction == DIRECTION_UP) { - return 'up'; - } else if (direction == DIRECTION_LEFT) { - return 'left'; - } else if (direction == DIRECTION_RIGHT) { - return 'right'; - } - return ''; - } + // this makes sure there is no jitter. The decision is taken once to run it at double speed. + this.runDoubleSpeed = true; + } - /** - * get a recognizer by name if it is bound to a manager - * @param {Recognizer|String} otherRecognizer - * @param {Recognizer} recognizer - * @returns {Recognizer} - */ - function getRecognizerByNameIfManager(otherRecognizer, recognizer) { - var manager = recognizer.manager; - if (manager) { - return manager.get(otherRecognizer); + if (this.stabilized === true) { + if (this.stabilizationIterations > 1) { + // trigger the 'stabilized' event. + // The event is triggered on the next tick, to prevent the case that + // it is fired while initializing the Network, in which case you would not + // be able to catch it + this.startedStabilization = false; + //this._emitStabilized(); + } + this.stopSimulation(); + } } - return otherRecognizer; - } - - /** - * This recognizer is just used as a base for the simple attribute recognizers. - * @constructor - * @extends Recognizer - */ - function AttrRecognizer() { - Recognizer.apply(this, arguments); - } - - inherit(AttrRecognizer, Recognizer, { - /** - * @namespace - * @memberof AttrRecognizer - */ - defaults: { - /** - * @type {Number} - * @default 1 - */ - pointers: 1 - }, + }, { + key: '_emitStabilized', + value: function _emitStabilized() { + var _this2 = this; - /** - * Used to check if it the recognizer receives valid input, like input.distance > 10. - * @memberof AttrRecognizer - * @param {Object} input - * @returns {Boolean} recognized - */ - attrTest: function(input) { - var optionPointers = this.options.pointers; - return optionPointers === 0 || input.pointers.length === optionPointers; - }, + if (this.stabilizationIterations > 1) { + setTimeout(function () { + _this2.body.emitter.emit('stabilized', { iterations: _this2.stabilizationIterations }); + _this2.stabilizationIterations = 0; + }, 0); + } + } + }, { + key: 'physicsTick', /** - * Process the input and return the state for the recognizer - * @memberof AttrRecognizer - * @param {Object} input - * @returns {*} State + * A single simulation step (or 'tick') in the physics simulation + * + * @private */ - process: function(input) { - var state = this.state; - var eventType = input.eventType; - - var isRecognized = state & (STATE_BEGAN | STATE_CHANGED); - var isValid = this.attrTest(input); + value: function physicsTick() { + if (this.stabilized === false) { + this.calculateForces(); + this.stabilized = this.moveNodes(); - // on cancel input and we've recognized before, return STATE_CANCELLED - if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) { - return state | STATE_CANCELLED; - } else if (isRecognized || isValid) { - if (eventType & INPUT_END) { - return state | STATE_ENDED; - } else if (!(state & STATE_BEGAN)) { - return STATE_BEGAN; - } - return state | STATE_CHANGED; + // determine if the network has stabilzied + if (this.stabilized === true) { + this.revert(); + } else { + // this is here to ensure that there is no start event when the network is already stable. + if (this.startedStabilization === false) { + this.body.emitter.emit('startStabilizing'); + this.startedStabilization = true; + } } - return STATE_FAILED; - } - }); - - /** - * Pan - * Recognized when the pointer is down and moved in the allowed direction. - * @constructor - * @extends AttrRecognizer - */ - function PanRecognizer() { - AttrRecognizer.apply(this, arguments); - this.pX = null; - this.pY = null; - } + this.stabilizationIterations++; + } + } + }, { + key: 'updatePhysicsData', - inherit(PanRecognizer, AttrRecognizer, { /** - * @namespace - * @memberof PanRecognizer + * Nodes and edges can have the physics toggles on or off. A collection of indices is created here so we can skip the check all the time. + * + * @private */ - defaults: { - event: 'pan', - threshold: 10, - pointers: 1, - direction: DIRECTION_ALL - }, + value: function updatePhysicsData() { + this.physicsBody.forces = {}; + this.physicsBody.physicsNodeIndices = []; + this.physicsBody.physicsEdgeIndices = []; + var nodes = this.body.nodes; + var edges = this.body.edges; - getTouchAction: function() { - var direction = this.options.direction; - var actions = []; - if (direction & DIRECTION_HORIZONTAL) { - actions.push(TOUCH_ACTION_PAN_Y); - } - if (direction & DIRECTION_VERTICAL) { - actions.push(TOUCH_ACTION_PAN_X); + // get node indices for physics + for (var nodeId in nodes) { + if (nodes.hasOwnProperty(nodeId)) { + if (nodes[nodeId].options.physics === true) { + this.physicsBody.physicsNodeIndices.push(nodeId); + } } - return actions; - }, - - directionTest: function(input) { - var options = this.options; - var hasMoved = true; - var distance = input.distance; - var direction = input.direction; - var x = input.deltaX; - var y = input.deltaY; + } - // lock to axis? - if (!(direction & options.direction)) { - if (options.direction & DIRECTION_HORIZONTAL) { - direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; - hasMoved = x != this.pX; - distance = Math.abs(input.deltaX); - } else { - direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN; - hasMoved = y != this.pY; - distance = Math.abs(input.deltaY); - } + // get edge indices for physics + for (var edgeId in edges) { + if (edges.hasOwnProperty(edgeId)) { + if (edges[edgeId].options.physics === true) { + this.physicsBody.physicsEdgeIndices.push(edgeId); + } } - input.direction = direction; - return hasMoved && distance > options.threshold && direction & options.direction; - }, - - attrTest: function(input) { - return AttrRecognizer.prototype.attrTest.call(this, input) && - (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input))); - }, + } - emit: function(input) { - this.pX = input.deltaX; - this.pY = input.deltaY; + // get the velocity and the forces vector + for (var i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) { + var nodeId = this.physicsBody.physicsNodeIndices[i]; + this.physicsBody.forces[nodeId] = { x: 0, y: 0 }; - var direction = directionStr(input.direction); - if (direction) { - this.manager.emit(this.options.event + direction, input); + // forces can be reset because they are recalculated. Velocities have to persist. + if (this.physicsBody.velocities[nodeId] === undefined) { + this.physicsBody.velocities[nodeId] = { x: 0, y: 0 }; } + } - this._super.emit.call(this, input); + // clean deleted nodes from the velocity vector + for (var nodeId in this.physicsBody.velocities) { + if (nodes[nodeId] === undefined) { + delete this.physicsBody.velocities[nodeId]; + } + } } - }); - - /** - * Pinch - * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out). - * @constructor - * @extends AttrRecognizer - */ - function PinchRecognizer() { - AttrRecognizer.apply(this, arguments); - } + }, { + key: 'revert', - inherit(PinchRecognizer, AttrRecognizer, { /** - * @namespace - * @memberof PinchRecognizer + * Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized. */ - defaults: { - event: 'pinch', - threshold: 0, - pointers: 2 - }, - - getTouchAction: function() { - return [TOUCH_ACTION_NONE]; - }, - - attrTest: function(input) { - return this._super.attrTest.call(this, input) && - (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN); - }, + value: function revert() { + var nodeIds = Object.keys(this.previousStates); + var nodes = this.body.nodes; + var velocities = this.physicsBody.velocities; - emit: function(input) { - this._super.emit.call(this, input); - if (input.scale !== 1) { - var inOut = input.scale < 1 ? 'in' : 'out'; - this.manager.emit(this.options.event + inOut, input); + for (var i = 0; i < nodeIds.length; i++) { + var nodeId = nodeIds[i]; + if (nodes[nodeId] !== undefined) { + if (nodes[nodeId].options.physics === true) { + velocities[nodeId].x = this.previousStates[nodeId].vx; + velocities[nodeId].y = this.previousStates[nodeId].vy; + nodes[nodeId].x = this.previousStates[nodeId].x; + nodes[nodeId].y = this.previousStates[nodeId].y; + } + } else { + delete this.previousStates[nodeId]; } + } } - }); - - /** - * Press - * Recognized when the pointer is down for x ms without any movement. - * @constructor - * @extends Recognizer - */ - function PressRecognizer() { - Recognizer.apply(this, arguments); - - this._timer = null; - this._input = null; - } + }, { + key: 'moveNodes', - inherit(PressRecognizer, Recognizer, { /** - * @namespace - * @memberof PressRecognizer + * move the nodes one timestap and check if they are stabilized + * @returns {boolean} */ - defaults: { - event: 'press', - pointers: 1, - time: 500, // minimal time of the pointer to be pressed - threshold: 5 // a minimal movement is ok, but keep it low - }, + value: function moveNodes() { + var nodesPresent = false; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var maxVelocity = this.options.maxVelocity ? this.options.maxVelocity : 1000000000; + var stabilized = true; + var vminCorrected = this.options.minVelocity / Math.max(this.body.view.scale, 0.05); - getTouchAction: function() { - return [TOUCH_ACTION_AUTO]; - }, + for (var i = 0; i < nodeIndices.length; i++) { + var nodeId = nodeIndices[i]; + var nodeVelocity = this._performStep(nodeId, maxVelocity); + // stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized + stabilized = nodeVelocity < vminCorrected && stabilized === true; + nodesPresent = true; + } - process: function(input) { - var options = this.options; - var validPointers = input.pointers.length === options.pointers; - var validMovement = input.distance < options.threshold; - var validTime = input.deltaTime > options.time; + if (nodesPresent === true) { + if (vminCorrected > 0.5 * this.options.maxVelocity) { + return false; + } else { + return stabilized; + } + } + return true; + } + }, { + key: '_performStep', - this._input = input; + /** + * Perform the actual step + * + * @param nodeId + * @param maxVelocity + * @returns {number} + * @private + */ + value: function _performStep(nodeId, maxVelocity) { + var node = this.body.nodes[nodeId]; + var timestep = this.options.timestep; + var forces = this.physicsBody.forces; + var velocities = this.physicsBody.velocities; - // we only allow little movement - // and we've reached an end event, so a tap is possible - if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) { - this.reset(); - } else if (input.eventType & INPUT_START) { - this.reset(); - this._timer = setTimeoutContext(function() { - this.state = STATE_RECOGNIZED; - this.tryEmit(); - }, options.time, this); - } else if (input.eventType & INPUT_END) { - return STATE_RECOGNIZED; - } - return STATE_FAILED; - }, + // store the state so we can revert + this.previousStates[nodeId] = { x: node.x, y: node.y, vx: velocities[nodeId].x, vy: velocities[nodeId].y }; - reset: function() { - clearTimeout(this._timer); - }, + if (node.options.fixed.x === false) { + var dx = this.modelOptions.damping * velocities[nodeId].x; // damping force + var ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration + velocities[nodeId].x += ax * timestep; // velocity + velocities[nodeId].x = Math.abs(velocities[nodeId].x) > maxVelocity ? velocities[nodeId].x > 0 ? maxVelocity : -maxVelocity : velocities[nodeId].x; + node.x += velocities[nodeId].x * timestep; // position + } else { + forces[nodeId].x = 0; + velocities[nodeId].x = 0; + } - emit: function(input) { - if (this.state !== STATE_RECOGNIZED) { - return; - } + if (node.options.fixed.y === false) { + var dy = this.modelOptions.damping * velocities[nodeId].y; // damping force + var ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration + velocities[nodeId].y += ay * timestep; // velocity + velocities[nodeId].y = Math.abs(velocities[nodeId].y) > maxVelocity ? velocities[nodeId].y > 0 ? maxVelocity : -maxVelocity : velocities[nodeId].y; + node.y += velocities[nodeId].y * timestep; // position + } else { + forces[nodeId].y = 0; + velocities[nodeId].y = 0; + } - if (input && (input.eventType & INPUT_END)) { - this.manager.emit(this.options.event + 'up', input); - } else { - this._input.timeStamp = now(); - this.manager.emit(this.options.event, this._input); - } + var totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x, 2) + Math.pow(velocities[nodeId].y, 2)); + return totalVelocity; } - }); - - /** - * Rotate - * Recognized when two or more pointer are moving in a circular motion. - * @constructor - * @extends AttrRecognizer - */ - function RotateRecognizer() { - AttrRecognizer.apply(this, arguments); - } + }, { + key: 'calculateForces', - inherit(RotateRecognizer, AttrRecognizer, { /** - * @namespace - * @memberof RotateRecognizer + * calculate the forces for one physics iteration. */ - defaults: { - event: 'rotate', - threshold: 0, - pointers: 2 - }, - - getTouchAction: function() { - return [TOUCH_ACTION_NONE]; - }, - - attrTest: function(input) { - return this._super.attrTest.call(this, input) && - (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN); + value: function calculateForces() { + this.gravitySolver.solve(); + this.nodesSolver.solve(); + this.edgesSolver.solve(); } - }); - - /** - * Swipe - * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction. - * @constructor - * @extends AttrRecognizer - */ - function SwipeRecognizer() { - AttrRecognizer.apply(this, arguments); - } + }, { + key: '_freezeNodes', - inherit(SwipeRecognizer, AttrRecognizer, { /** - * @namespace - * @memberof SwipeRecognizer + * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization + * because only the supportnodes for the smoothCurves have to settle. + * + * @private */ - defaults: { - event: 'swipe', - threshold: 10, - velocity: 0.65, - direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL, - pointers: 1 - }, - - getTouchAction: function() { - return PanRecognizer.prototype.getTouchAction.call(this); - }, - - attrTest: function(input) { - var direction = this.options.direction; - var velocity; - - if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) { - velocity = input.velocity; - } else if (direction & DIRECTION_HORIZONTAL) { - velocity = input.velocityX; - } else if (direction & DIRECTION_VERTICAL) { - velocity = input.velocityY; + value: function _freezeNodes() { + var nodes = this.body.nodes; + for (var id in nodes) { + if (nodes.hasOwnProperty(id)) { + if (nodes[id].x && nodes[id].y) { + this.freezeCache[id] = { x: nodes[id].options.fixed.x, y: nodes[id].options.fixed.y }; + nodes[id].options.fixed.x = true; + nodes[id].options.fixed.y = true; + } } + } + } + }, { + key: '_restoreFrozenNodes', - return this._super.attrTest.call(this, input) && - direction & input.direction && - input.distance > this.options.threshold && - abs(velocity) > this.options.velocity && input.eventType & INPUT_END; - }, - - emit: function(input) { - var direction = directionStr(input.direction); - if (direction) { - this.manager.emit(this.options.event + direction, input); + /** + * Unfreezes the nodes that have been frozen by _freezeDefinedNodes. + * + * @private + */ + value: function _restoreFrozenNodes() { + var nodes = this.body.nodes; + for (var id in nodes) { + if (nodes.hasOwnProperty(id)) { + if (this.freezeCache[id] !== undefined) { + nodes[id].options.fixed.x = this.freezeCache[id].x; + nodes[id].options.fixed.y = this.freezeCache[id].y; + } } - - this.manager.emit(this.options.event, input); + } + this.freezeCache = {}; } - }); + }, { + key: 'stabilize', - /** - * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur - * between the given interval and position. The delay option can be used to recognize multi-taps without firing - * a single tap. - * - * The eventData from the emitted event contains the property `tapCount`, which contains the amount of - * multi-taps being recognized. - * @constructor - * @extends Recognizer - */ - function TapRecognizer() { - Recognizer.apply(this, arguments); + /** + * Find a stable position for all nodes + * @private + */ + value: function stabilize() { + var _this3 = this; - // previous time and center, - // used for tap counting - this.pTime = false; - this.pCenter = false; + var iterations = arguments[0] === undefined ? this.options.stabilization.iterations : arguments[0]; - this._timer = null; - this._input = null; - this.count = 0; - } + if (typeof iterations !== 'number') { + console.log('The stabilize method needs a numeric amount of iterations. Switching to default: ', this.options.stabilization.iterations); + iterations = this.options.stabilization.iterations; + } - inherit(TapRecognizer, Recognizer, { - /** - * @namespace - * @memberof PinchRecognizer - */ - defaults: { - event: 'tap', - pointers: 1, - taps: 1, - interval: 300, // max time between the multi-tap taps - time: 250, // max time of the pointer to be down (like finger on the screen) - threshold: 2, // a minimal movement is ok, but keep it low - posThreshold: 10 // a multi-tap can be a bit off the initial position - }, + // this sets the width of all nodes initially which could be required for the avoidOverlap + this.body.emitter.emit('_resizeNodes'); - getTouchAction: function() { - return [TOUCH_ACTION_MANIPULATION]; - }, + // stop the render loop + this.stopSimulation(); - process: function(input) { - var options = this.options; + // set stabilze to false + this.stabilized = false; - var validPointers = input.pointers.length === options.pointers; - var validMovement = input.distance < options.threshold; - var validTouchTime = input.deltaTime < options.time; + // block redraw requests + this.body.emitter.emit('_blockRedrawRequests'); + this.targetIterations = iterations; - this.reset(); + // start the stabilization + if (this.options.stabilization.onlyDynamicEdges === true) { + this._freezeNodes(); + } + this.stabilizationIterations = 0; - if ((input.eventType & INPUT_START) && (this.count === 0)) { - return this.failTimeout(); - } + setTimeout(function () { + return _this3._stabilizationBatch(); + }, 0); + } + }, { + key: '_stabilizationBatch', + value: function _stabilizationBatch() { + var count = 0; + while (this.stabilized === false && count < this.options.stabilization.updateInterval && this.stabilizationIterations < this.targetIterations) { + this.physicsTick(); + this.stabilizationIterations++; + count++; + } - // we only allow little movement - // and we've reached an end event, so a tap is possible - if (validMovement && validTouchTime && validPointers) { - if (input.eventType != INPUT_END) { - return this.failTimeout(); - } + if (this.stabilized === false && this.stabilizationIterations < this.targetIterations) { + this.body.emitter.emit('stabilizationProgress', { iterations: this.stabilizationIterations, total: this.targetIterations }); + setTimeout(this._stabilizationBatch.bind(this), 0); + } else { + this._finalizeStabilization(); + } + } + }, { + key: '_finalizeStabilization', + value: function _finalizeStabilization() { + this.body.emitter.emit('_allowRedrawRequests'); + if (this.options.stabilization.fit === true) { + this.body.emitter.emit('fit'); + } - var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true; - var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold; + if (this.options.stabilization.onlyDynamicEdges === true) { + this._restoreFrozenNodes(); + } - this.pTime = input.timeStamp; - this.pCenter = input.center; + this.body.emitter.emit('stabilizationIterationsDone'); + this.body.emitter.emit('_requestRedraw'); - if (!validMultiTap || !validInterval) { - this.count = 1; - } else { - this.count += 1; - } + if (this.stabilized === true) { + this._emitStabilized(); + } else { + this.startSimulation(); + } - this._input = input; + this.ready = true; + } + }]); - // if tap count matches we have recognized it, - // else it has began recognizing... - var tapCount = this.count % options.taps; - if (tapCount === 0) { - // no failing requirements, immediately trigger the tap event - // or wait as long as the multitap interval to trigger - if (!this.hasRequireFailures()) { - return STATE_RECOGNIZED; - } else { - this._timer = setTimeoutContext(function() { - this.state = STATE_RECOGNIZED; - this.tryEmit(); - }, options.interval, this); - return STATE_BEGAN; - } - } - } - return STATE_FAILED; - }, + return PhysicsEngine; + })(); - failTimeout: function() { - this._timer = setTimeoutContext(function() { - this.state = STATE_FAILED; - }, this.options.interval, this); - return STATE_FAILED; - }, + exports['default'] = PhysicsEngine; + module.exports = exports['default']; - reset: function() { - clearTimeout(this._timer); - }, +/***/ }, +/* 89 */ +/***/ function(module, exports, __webpack_require__) { - emit: function() { - if (this.state == STATE_RECOGNIZED ) { - this._input.tapCount = this.count; - this.manager.emit(this.options.event, this._input); - } - } + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true }); - /** - * Simple way to create an manager with a default set of recognizers. - * @param {HTMLElement} element - * @param {Object} [options] - * @constructor - */ - function Hammer(element, options) { - options = options || {}; - options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset); - return new Manager(element, options); - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /** - * @const {string} - */ - Hammer.VERSION = '2.0.4'; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - /** - * default settings - * @namespace - */ - Hammer.defaults = { - /** - * set if DOM events are being triggered. - * But this is slower and unused by simple implementations, so disabled by default. - * @type {Boolean} - * @default false - */ - domEvents: false, + var BarnesHutSolver = (function () { + function BarnesHutSolver(body, physicsBody, options) { + _classCallCheck(this, BarnesHutSolver); - /** - * The value for the touchAction property/fallback. - * When set to `compute` it will magically set the correct value based on the added recognizers. - * @type {String} - * @default compute - */ - touchAction: TOUCH_ACTION_COMPUTE, + this.body = body; + this.physicsBody = physicsBody; + this.barnesHutTree; + this.setOptions(options); + } - /** - * @type {Boolean} - * @default true - */ - enable: true, + _createClass(BarnesHutSolver, [{ + key: "setOptions", + value: function setOptions(options) { + this.options = options; + this.thetaInversed = 1 / this.options.theta; + this.overlapAvoidanceFactor = 1 - Math.max(0, Math.min(1, this.options.avoidOverlap)); // if 1 then min distance = 0.5, if 0.5 then min distance = 0.5 + 0.5*node.shape.radius + } + }, { + key: "solve", /** - * EXPERIMENTAL FEATURE -- can be removed/changed - * Change the parent input target element. - * If Null, then it is being set the to main element. - * @type {Null|EventTarget} - * @default null + * This function calculates the forces the nodes apply on eachother based on a gravitational model. + * The Barnes Hut method is used to speed up this N-body simulation. + * + * @private */ - inputTarget: null, + value: function solve() { + if (this.options.gravitationalConstant !== 0 && this.physicsBody.physicsNodeIndices.length > 0) { + var node = undefined; + var nodes = this.body.nodes; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var nodeCount = nodeIndices.length; - /** - * force an input class - * @type {Null|Function} - * @default null - */ - inputClass: null, + // create the tree + var barnesHutTree = this._formBarnesHutTree(nodes, nodeIndices); - /** - * Default recognizer setup when calling `Hammer()` - * When creating a new Manager these will be skipped. - * @type {Array} - */ - preset: [ - // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...] - [RotateRecognizer, { enable: false }], - [PinchRecognizer, { enable: false }, ['rotate']], - [SwipeRecognizer,{ direction: DIRECTION_HORIZONTAL }], - [PanRecognizer, { direction: DIRECTION_HORIZONTAL }, ['swipe']], - [TapRecognizer], - [TapRecognizer, { event: 'doubletap', taps: 2 }, ['tap']], - [PressRecognizer] - ], + // for debugging + this.barnesHutTree = barnesHutTree; + + // place the nodes one by one recursively + for (var i = 0; i < nodeCount; i++) { + node = nodes[nodeIndices[i]]; + if (node.options.mass > 0) { + // starting with root is irrelevant, it never passes the BarnesHutSolver condition + this._getForceContribution(barnesHutTree.root.children.NW, node); + this._getForceContribution(barnesHutTree.root.children.NE, node); + this._getForceContribution(barnesHutTree.root.children.SW, node); + this._getForceContribution(barnesHutTree.root.children.SE, node); + } + } + } + } + }, { + key: "_getForceContribution", /** - * Some CSS properties can be used to improve the working of Hammer. - * Add them to this method and they will be set when creating a new Manager. - * @namespace + * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass. + * If a region contains a single node, we check if it is not itself, then we apply the force. + * + * @param parentBranch + * @param node + * @private */ - cssProps: { - /** - * Disables text selection to improve the dragging gesture. Mainly for desktop browsers. - * @type {String} - * @default 'none' - */ - userSelect: 'none', - - /** - * Disable the Windows Phone grippers when pressing an element. - * @type {String} - * @default 'none' - */ - touchSelect: 'none', - - /** - * Disables the default callout shown when you touch and hold a touch target. - * On iOS, when you touch and hold a touch target such as a link, Safari displays - * a callout containing information about the link. This property allows you to disable that callout. - * @type {String} - * @default 'none' - */ - touchCallout: 'none', - - /** - * Specifies whether zooming is enabled. Used by IE10> - * @type {String} - * @default 'none' - */ - contentZooming: 'none', + value: function _getForceContribution(parentBranch, node) { + // we get no force contribution from an empty region + if (parentBranch.childrenCount > 0) { + var dx = undefined, + dy = undefined, + distance = undefined; - /** - * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers. - * @type {String} - * @default 'none' - */ - userDrag: 'none', + // get the distance from the center of mass to the node. + dx = parentBranch.centerOfMass.x - node.x; + dy = parentBranch.centerOfMass.y - node.y; + distance = Math.sqrt(dx * dx + dy * dy); - /** - * Overrides the highlight color shown when the user taps a link or a JavaScript - * clickable element in iOS. This property obeys the alpha value, if specified. - * @type {String} - * @default 'rgba(0,0,0,0)' - */ - tapHighlightColor: 'rgba(0,0,0,0)' + // BarnesHutSolver condition + // original condition : s/d < theta = passed === d/s > 1/theta = passed + // calcSize = 1/s --> d * 1/s > 1/theta = passed + if (distance * parentBranch.calcSize > this.thetaInversed) { + this._calculateForces(distance, dx, dy, node, parentBranch); + } else { + // Did not pass the condition, go into children if available + if (parentBranch.childrenCount === 4) { + this._getForceContribution(parentBranch.children.NW, node); + this._getForceContribution(parentBranch.children.NE, node); + this._getForceContribution(parentBranch.children.SW, node); + this._getForceContribution(parentBranch.children.SE, node); + } else { + // parentBranch must have only one node, if it was empty we wouldnt be here + if (parentBranch.children.data.id != node.id) { + // if it is not self + this._calculateForces(distance, dx, dy, node, parentBranch); + } + } + } + } } - }; - - var STOP = 1; - var FORCED_STOP = 2; - - /** - * Manager - * @param {HTMLElement} element - * @param {Object} [options] - * @constructor - */ - function Manager(element, options) { - options = options || {}; - - this.options = merge(options, Hammer.defaults); - this.options.inputTarget = this.options.inputTarget || element; + }, { + key: "_calculateForces", - this.handlers = {}; - this.session = {}; - this.recognizers = []; + /** + * Calculate the forces based on the distance. + * + * @param distance + * @param dx + * @param dy + * @param node + * @param parentBranch + * @private + */ + value: function _calculateForces(distance, dx, dy, node, parentBranch) { + if (distance === 0) { + distance = 0.1; + dx = distance; + } - this.element = element; - this.input = createInputInstance(this); - this.touchAction = new TouchAction(this, this.options.touchAction); + if (this.overlapAvoidanceFactor < 1) { + distance = Math.max(0.1 + this.overlapAvoidanceFactor * node.shape.radius, distance - node.shape.radius); + } - toggleCssProps(this, true); + // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines + // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce + var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass / Math.pow(distance, 3); + var fx = dx * gravityForce; + var fy = dy * gravityForce; - each(options.recognizers, function(item) { - var recognizer = this.add(new (item[0])(item[1])); - item[2] && recognizer.recognizeWith(item[2]); - item[3] && recognizer.requireFailure(item[3]); - }, this); - } + this.physicsBody.forces[node.id].x += fx; + this.physicsBody.forces[node.id].y += fy; + } + }, { + key: "_formBarnesHutTree", - Manager.prototype = { /** - * set options - * @param {Object} options - * @returns {Manager} + * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes. + * + * @param nodes + * @param nodeIndices + * @private */ - set: function(options) { - extend(this.options, options); + value: function _formBarnesHutTree(nodes, nodeIndices) { + var node = undefined; + var nodeCount = nodeIndices.length; - // Options that need a little more setup - if (options.touchAction) { - this.touchAction.update(); - } - if (options.inputTarget) { - // Clean up existing event listeners and reinitialize - this.input.destroy(); - this.input.target = options.inputTarget; - this.input.init(); + var minX = nodes[nodeIndices[0]].x; + var minY = nodes[nodeIndices[0]].y; + var maxX = nodes[nodeIndices[0]].x; + var maxY = nodes[nodeIndices[0]].y; + + // get the range of the nodes + for (var i = 1; i < nodeCount; i++) { + var x = nodes[nodeIndices[i]].x; + var y = nodes[nodeIndices[i]].y; + if (nodes[nodeIndices[i]].options.mass > 0) { + if (x < minX) { + minX = x; + } + if (x > maxX) { + maxX = x; + } + if (y < minY) { + minY = y; + } + if (y > maxY) { + maxY = y; + } } - return this; - }, + } + // make the range a square + var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y + if (sizeDiff > 0) { + minY -= 0.5 * sizeDiff; + maxY += 0.5 * sizeDiff; + } // xSize > ySize + else { + minX += 0.5 * sizeDiff; + maxX -= 0.5 * sizeDiff; + } // xSize < ySize - /** - * stop recognizing for this session. - * This session will be discarded, when a new [input]start event is fired. - * When forced, the recognizer cycle is stopped immediately. - * @param {Boolean} [force] - */ - stop: function(force) { - this.session.stopped = force ? FORCED_STOP : STOP; - }, + var minimumTreeSize = 0.00001; + var rootSize = Math.max(minimumTreeSize, Math.abs(maxX - minX)); + var halfRootSize = 0.5 * rootSize; + var centerX = 0.5 * (minX + maxX), + centerY = 0.5 * (minY + maxY); - /** - * run the recognizers! - * called by the inputHandler function on every movement of the pointers (touches) - * it walks through all the recognizers and tries to detect the gesture that is being made - * @param {Object} inputData - */ - recognize: function(inputData) { - var session = this.session; - if (session.stopped) { - return; + // construct the barnesHutTree + var barnesHutTree = { + root: { + centerOfMass: { x: 0, y: 0 }, + mass: 0, + range: { + minX: centerX - halfRootSize, maxX: centerX + halfRootSize, + minY: centerY - halfRootSize, maxY: centerY + halfRootSize + }, + size: rootSize, + calcSize: 1 / rootSize, + children: { data: null }, + maxWidth: 0, + level: 0, + childrenCount: 4 } + }; + this._splitBranch(barnesHutTree.root); - // run the touch-action polyfill - this.touchAction.preventDefaults(inputData); - - var recognizer; - var recognizers = this.recognizers; + // place the nodes one by one recursively + for (var i = 0; i < nodeCount; i++) { + node = nodes[nodeIndices[i]]; + if (node.options.mass > 0) { + this._placeInTree(barnesHutTree.root, node); + } + } - // this holds the recognizer that is being recognized. - // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED - // if no recognizer is detecting a thing, it is set to `null` - var curRecognizer = session.curRecognizer; + // make global + return barnesHutTree; + } + }, { + key: "_updateBranchMass", - // reset when the last recognizer is recognized - // or when we're in a new session - if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) { - curRecognizer = session.curRecognizer = null; - } + /** + * this updates the mass of a branch. this is increased by adding a node. + * + * @param parentBranch + * @param node + * @private + */ + value: function _updateBranchMass(parentBranch, node) { + var totalMass = parentBranch.mass + node.options.mass; + var totalMassInv = 1 / totalMass; - var i = 0; - while (i < recognizers.length) { - recognizer = recognizers[i]; + parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass; + parentBranch.centerOfMass.x *= totalMassInv; - // find out if we are allowed try to recognize the input for this one. - // 1. allow if the session is NOT forced stopped (see the .stop() method) - // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one - // that is being recognized. - // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer. - // this can be setup with the `recognizeWith()` method on the recognizer. - if (session.stopped !== FORCED_STOP && ( // 1 - !curRecognizer || recognizer == curRecognizer || // 2 - recognizer.canRecognizeWith(curRecognizer))) { // 3 - recognizer.recognize(inputData); - } else { - recognizer.reset(); - } + parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass; + parentBranch.centerOfMass.y *= totalMassInv; - // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the - // current active recognizer. but only if we don't already have an active recognizer - if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) { - curRecognizer = session.curRecognizer = recognizer; - } - i++; - } - }, + parentBranch.mass = totalMass; + var biggestSize = Math.max(Math.max(node.height, node.radius), node.width); + parentBranch.maxWidth = parentBranch.maxWidth < biggestSize ? biggestSize : parentBranch.maxWidth; + } + }, { + key: "_placeInTree", /** - * get a recognizer by its event name. - * @param {Recognizer|String} recognizer - * @returns {Recognizer|Null} + * determine in which branch the node will be placed. + * + * @param parentBranch + * @param node + * @param skipMassUpdate + * @private */ - get: function(recognizer) { - if (recognizer instanceof Recognizer) { - return recognizer; - } + value: function _placeInTree(parentBranch, node, skipMassUpdate) { + if (skipMassUpdate != true || skipMassUpdate === undefined) { + // update the mass of the branch. + this._updateBranchMass(parentBranch, node); + } - var recognizers = this.recognizers; - for (var i = 0; i < recognizers.length; i++) { - if (recognizers[i].options.event == recognizer) { - return recognizers[i]; - } + if (parentBranch.children.NW.range.maxX > node.x) { + // in NW or SW + if (parentBranch.children.NW.range.maxY > node.y) { + // in NW + this._placeInRegion(parentBranch, node, "NW"); + } else { + // in SW + this._placeInRegion(parentBranch, node, "SW"); } - return null; - }, + } else { + // in NE or SE + if (parentBranch.children.NW.range.maxY > node.y) { + // in NE + this._placeInRegion(parentBranch, node, "NE"); + } else { + // in SE + this._placeInRegion(parentBranch, node, "SE"); + } + } + } + }, { + key: "_placeInRegion", /** - * add a recognizer to the manager - * existing recognizers with the same event name will be removed - * @param {Recognizer} recognizer - * @returns {Recognizer|Manager} + * actually place the node in a region (or branch) + * + * @param parentBranch + * @param node + * @param region + * @private */ - add: function(recognizer) { - if (invokeArrayArg(recognizer, 'add', this)) { - return this; - } - - // remove existing - var existing = this.get(recognizer.options.event); - if (existing) { - this.remove(existing); - } + value: function _placeInRegion(parentBranch, node, region) { + switch (parentBranch.children[region].childrenCount) { + case 0: + // place node here + parentBranch.children[region].children.data = node; + parentBranch.children[region].childrenCount = 1; + this._updateBranchMass(parentBranch.children[region], node); + break; + case 1: + // convert into children + // if there are two nodes exactly overlapping (on init, on opening of cluster etc.) + // we move one node a pixel and we do not put it in the tree. + if (parentBranch.children[region].children.data.x === node.x && parentBranch.children[region].children.data.y === node.y) { + //node.x += Math.random(); + //node.y += Math.random(); + node.x += 0.1; + node.y += 0.1; + } else { + this._splitBranch(parentBranch.children[region]); + this._placeInTree(parentBranch.children[region], node); + } + break; + case 4: + // place in branch + this._placeInTree(parentBranch.children[region], node); + break; + } + } + }, { + key: "_splitBranch", - this.recognizers.push(recognizer); - recognizer.manager = this; + /** + * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch + * after the split is complete. + * + * @param parentBranch + * @private + */ + value: function _splitBranch(parentBranch) { + // if the branch is shaded with a node, replace the node in the new subset. + var containedNode = null; + if (parentBranch.childrenCount === 1) { + containedNode = parentBranch.children.data; + parentBranch.mass = 0; + parentBranch.centerOfMass.x = 0; + parentBranch.centerOfMass.y = 0; + } + parentBranch.childrenCount = 4; + parentBranch.children.data = null; + this._insertRegion(parentBranch, "NW"); + this._insertRegion(parentBranch, "NE"); + this._insertRegion(parentBranch, "SW"); + this._insertRegion(parentBranch, "SE"); - this.touchAction.update(); - return recognizer; - }, + if (containedNode != null) { + this._placeInTree(parentBranch, containedNode); + } + } + }, { + key: "_insertRegion", /** - * remove a recognizer by name or instance - * @param {Recognizer|String} recognizer - * @returns {Manager} + * This function subdivides the region into four new segments. + * Specifically, this inserts a single new segment. + * It fills the children section of the parentBranch + * + * @param parentBranch + * @param region + * @param parentRange + * @private */ - remove: function(recognizer) { - if (invokeArrayArg(recognizer, 'remove', this)) { - return this; - } + value: function _insertRegion(parentBranch, region) { + var minX = undefined, + maxX = undefined, + minY = undefined, + maxY = undefined; + var childSize = 0.5 * parentBranch.size; + switch (region) { + case "NW": + minX = parentBranch.range.minX; + maxX = parentBranch.range.minX + childSize; + minY = parentBranch.range.minY; + maxY = parentBranch.range.minY + childSize; + break; + case "NE": + minX = parentBranch.range.minX + childSize; + maxX = parentBranch.range.maxX; + minY = parentBranch.range.minY; + maxY = parentBranch.range.minY + childSize; + break; + case "SW": + minX = parentBranch.range.minX; + maxX = parentBranch.range.minX + childSize; + minY = parentBranch.range.minY + childSize; + maxY = parentBranch.range.maxY; + break; + case "SE": + minX = parentBranch.range.minX + childSize; + maxX = parentBranch.range.maxX; + minY = parentBranch.range.minY + childSize; + maxY = parentBranch.range.maxY; + break; + } - var recognizers = this.recognizers; - recognizer = this.get(recognizer); - recognizers.splice(inArray(recognizers, recognizer), 1); + parentBranch.children[region] = { + centerOfMass: { x: 0, y: 0 }, + mass: 0, + range: { minX: minX, maxX: maxX, minY: minY, maxY: maxY }, + size: 0.5 * parentBranch.size, + calcSize: 2 * parentBranch.calcSize, + children: { data: null }, + maxWidth: 0, + level: parentBranch.level + 1, + childrenCount: 0 + }; + } + }, { + key: "_debug", - this.touchAction.update(); - return this; - }, + //--------------------------- DEBUGGING BELOW ---------------------------// /** - * bind event - * @param {String} events - * @param {Function} handler - * @returns {EventEmitter} this + * This function is for debugging purposed, it draws the tree. + * + * @param ctx + * @param color + * @private */ - on: function(events, handler) { - var handlers = this.handlers; - each(splitStr(events), function(event) { - handlers[event] = handlers[event] || []; - handlers[event].push(handler); - }); - return this; - }, + value: function _debug(ctx, color) { + if (this.barnesHutTree !== undefined) { + + ctx.lineWidth = 1; + + this._drawBranch(this.barnesHutTree.root, ctx, color); + } + } + }, { + key: "_drawBranch", /** - * unbind event, leave emit blank to remove all handlers - * @param {String} events - * @param {Function} [handler] - * @returns {EventEmitter} this + * This function is for debugging purposes. It draws the branches recursively. + * + * @param branch + * @param ctx + * @param color + * @private */ - off: function(events, handler) { - var handlers = this.handlers; - each(splitStr(events), function(event) { - if (!handler) { - delete handlers[event]; - } else { - handlers[event].splice(inArray(handlers[event], handler), 1); - } - }); - return this; - }, + value: function _drawBranch(branch, ctx, color) { + if (color === undefined) { + color = "#FF0000"; + } + + if (branch.childrenCount === 4) { + this._drawBranch(branch.children.NW, ctx); + this._drawBranch(branch.children.NE, ctx); + this._drawBranch(branch.children.SE, ctx); + this._drawBranch(branch.children.SW, ctx); + } + ctx.strokeStyle = color; + ctx.beginPath(); + ctx.moveTo(branch.range.minX, branch.range.minY); + ctx.lineTo(branch.range.maxX, branch.range.minY); + ctx.stroke(); + + ctx.beginPath(); + ctx.moveTo(branch.range.maxX, branch.range.minY); + ctx.lineTo(branch.range.maxX, branch.range.maxY); + ctx.stroke(); + + ctx.beginPath(); + ctx.moveTo(branch.range.maxX, branch.range.maxY); + ctx.lineTo(branch.range.minX, branch.range.maxY); + ctx.stroke(); + + ctx.beginPath(); + ctx.moveTo(branch.range.minX, branch.range.maxY); + ctx.lineTo(branch.range.minX, branch.range.minY); + ctx.stroke(); + + /* + if (branch.mass > 0) { + ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass); + ctx.stroke(); + } + */ + } + }]); - /** - * emit event to the listeners - * @param {String} event - * @param {Object} data - */ - emit: function(event, data) { - // we also want to trigger dom events - if (this.options.domEvents) { - triggerDomEvent(event, data); - } + return BarnesHutSolver; + })(); - // no handlers, so skip it all - var handlers = this.handlers[event] && this.handlers[event].slice(); - if (!handlers || !handlers.length) { - return; - } + exports["default"] = BarnesHutSolver; + module.exports = exports["default"]; - data.type = event; - data.preventDefault = function() { - data.srcEvent.preventDefault(); - }; +/***/ }, +/* 90 */ +/***/ function(module, exports, __webpack_require__) { - var i = 0; - while (i < handlers.length) { - handlers[i](data); - i++; - } - }, + "use strict"; - /** - * destroy the manager and unbinds all events - * it doesn't unbind dom events, that is the user own responsibility - */ - destroy: function() { - this.element && toggleCssProps(this, false); + Object.defineProperty(exports, "__esModule", { + value: true + }); - this.handlers = {}; - this.session = {}; - this.input.destroy(); - this.element = null; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var RepulsionSolver = (function () { + function RepulsionSolver(body, physicsBody, options) { + _classCallCheck(this, RepulsionSolver); + + this.body = body; + this.physicsBody = physicsBody; + this.setOptions(options); + } + + _createClass(RepulsionSolver, [{ + key: "setOptions", + value: function setOptions(options) { + this.options = options; } - }; + }, { + key: "solve", - /** - * add/remove the css properties as defined in manager.options.cssProps - * @param {Manager} manager - * @param {Boolean} add - */ - function toggleCssProps(manager, add) { - var element = manager.element; - each(manager.options.cssProps, function(value, name) { - element.style[prefixed(element.style, name)] = add ? value : ''; - }); - } + /** + * Calculate the forces the nodes apply on each other based on a repulsion field. + * This field is linearly approximated. + * + * @private + */ + value: function solve() { + var dx, dy, distance, fx, fy, repulsingForce, node1, node2; - /** - * trigger dom event - * @param {String} event - * @param {Object} data - */ - function triggerDomEvent(event, data) { - var gestureEvent = document.createEvent('Event'); - gestureEvent.initEvent(event, true, true); - gestureEvent.gesture = data; - data.target.dispatchEvent(gestureEvent); - } + var nodes = this.body.nodes; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var forces = this.physicsBody.forces; - extend(Hammer, { - INPUT_START: INPUT_START, - INPUT_MOVE: INPUT_MOVE, - INPUT_END: INPUT_END, - INPUT_CANCEL: INPUT_CANCEL, + // repulsing forces between nodes + var nodeDistance = this.options.nodeDistance; - STATE_POSSIBLE: STATE_POSSIBLE, - STATE_BEGAN: STATE_BEGAN, - STATE_CHANGED: STATE_CHANGED, - STATE_ENDED: STATE_ENDED, - STATE_RECOGNIZED: STATE_RECOGNIZED, - STATE_CANCELLED: STATE_CANCELLED, - STATE_FAILED: STATE_FAILED, + // approximation constants + var a = -2 / 3 / nodeDistance; + var b = 4 / 3; - DIRECTION_NONE: DIRECTION_NONE, - DIRECTION_LEFT: DIRECTION_LEFT, - DIRECTION_RIGHT: DIRECTION_RIGHT, - DIRECTION_UP: DIRECTION_UP, - DIRECTION_DOWN: DIRECTION_DOWN, - DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL, - DIRECTION_VERTICAL: DIRECTION_VERTICAL, - DIRECTION_ALL: DIRECTION_ALL, + // we loop from i over all but the last entree in the array + // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j + for (var i = 0; i < nodeIndices.length - 1; i++) { + node1 = nodes[nodeIndices[i]]; + for (var j = i + 1; j < nodeIndices.length; j++) { + node2 = nodes[nodeIndices[j]]; - Manager: Manager, - Input: Input, - TouchAction: TouchAction, + dx = node2.x - node1.x; + dy = node2.y - node1.y; + distance = Math.sqrt(dx * dx + dy * dy); - TouchInput: TouchInput, - MouseInput: MouseInput, - PointerEventInput: PointerEventInput, - TouchMouseInput: TouchMouseInput, - SingleTouchInput: SingleTouchInput, + // same condition as BarnesHutSolver, making sure nodes are never 100% overlapping. + if (distance === 0) { + distance = 0.1 * Math.random(); + dx = distance; + } - Recognizer: Recognizer, - AttrRecognizer: AttrRecognizer, - Tap: TapRecognizer, - Pan: PanRecognizer, - Swipe: SwipeRecognizer, - Pinch: PinchRecognizer, - Rotate: RotateRecognizer, - Press: PressRecognizer, + if (distance < 2 * nodeDistance) { + if (distance < 0.5 * nodeDistance) { + repulsingForce = 1; + } else { + repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / nodeDistance - 1) * steepness)) + } + repulsingForce = repulsingForce / distance; - on: addEventListeners, - off: removeEventListeners, - each: each, - merge: merge, - extend: extend, - inherit: inherit, - bindFn: bindFn, - prefixed: prefixed - }); + fx = dx * repulsingForce; + fy = dy * repulsingForce; - if ("function" == TYPE_FUNCTION && __webpack_require__(91)) { - !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { - return Hammer; - }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else if (typeof module != 'undefined' && module.exports) { - module.exports = Hammer; - } else { - window[exportName] = Hammer; - } + forces[node1.id].x -= fx; + forces[node1.id].y -= fy; + forces[node2.id].x += fx; + forces[node2.id].y += fy; + } + } + } + } + }]); - })(window, document, 'Hammer'); + return RepulsionSolver; + })(); + exports["default"] = RepulsionSolver; + module.exports = exports["default"]; /***/ }, -/* 73 */ +/* 91 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; + "use strict"; - Object.defineProperty(exports, '__esModule', { + Object.defineProperty(exports, "__esModule", { value: true }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - var Hammer = __webpack_require__(41); - var hammerUtil = __webpack_require__(49); - var util = __webpack_require__(2); - - var ColorPicker = (function () { - function ColorPicker() { - var pixelRatio = arguments[0] === undefined ? 1 : arguments[0]; - - _classCallCheck(this, ColorPicker); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - this.pixelRatio = pixelRatio; - this.generated = false; - this.centerCoordinates = { x: 289 / 2, y: 289 / 2 }; - this.r = 289 * 0.49; - this.color = { r: 255, g: 255, b: 255, a: 1 }; - this.hueCircle = undefined; - this.initialColor = { r: 255, g: 255, b: 255, a: 1 }; - this.previousColor = undefined; - this.applied = false; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - // bound by - this.updateCallback = function () {}; + var HierarchicalRepulsionSolver = (function () { + function HierarchicalRepulsionSolver(body, physicsBody, options) { + _classCallCheck(this, HierarchicalRepulsionSolver); - // create all DOM elements - this._create(); + this.body = body; + this.physicsBody = physicsBody; + this.setOptions(options); } - _createClass(ColorPicker, [{ - key: 'insertTo', - - /** - * this inserts the colorPicker into a div from the DOM - * @param container - */ - value: function insertTo(container) { - if (this.hammer !== undefined) { - this.hammer.destroy(); - this.hammer = undefined; - } - this.container = container; - this.container.appendChild(this.frame); - this._bindHammer(); - - this._setSize(); + _createClass(HierarchicalRepulsionSolver, [{ + key: "setOptions", + value: function setOptions(options) { + this.options = options; } }, { - key: 'setCallback', + key: "solve", /** - * the callback is executed on apply and save. Bind it to the application - * @param callback + * Calculate the forces the nodes apply on each other based on a repulsion field. + * This field is linearly approximated. + * + * @private */ - value: function setCallback(callback) { - if (typeof callback === 'function') { - this.updateCallback = callback; - } else { - throw new Error('Function attempted to set as colorPicker callback is not a function.'); - } - } - }, { - key: '_isColorString', - value: function _isColorString(color) { - var htmlColors = { black: '#000000', navy: '#000080', darkblue: '#00008B', mediumblue: '#0000CD', blue: '#0000FF', darkgreen: '#006400', green: '#008000', teal: '#008080', darkcyan: '#008B8B', deepskyblue: '#00BFFF', darkturquoise: '#00CED1', mediumspringgreen: '#00FA9A', lime: '#00FF00', springgreen: '#00FF7F', aqua: '#00FFFF', cyan: '#00FFFF', midnightblue: '#191970', dodgerblue: '#1E90FF', lightseagreen: '#20B2AA', forestgreen: '#228B22', seagreen: '#2E8B57', darkslategray: '#2F4F4F', limegreen: '#32CD32', mediumseagreen: '#3CB371', turquoise: '#40E0D0', royalblue: '#4169E1', steelblue: '#4682B4', darkslateblue: '#483D8B', mediumturquoise: '#48D1CC', indigo: '#4B0082', darkolivegreen: '#556B2F', cadetblue: '#5F9EA0', cornflowerblue: '#6495ED', mediumaquamarine: '#66CDAA', dimgray: '#696969', slateblue: '#6A5ACD', olivedrab: '#6B8E23', slategray: '#708090', lightslategray: '#778899', mediumslateblue: '#7B68EE', lawngreen: '#7CFC00', chartreuse: '#7FFF00', aquamarine: '#7FFFD4', maroon: '#800000', purple: '#800080', olive: '#808000', gray: '#808080', skyblue: '#87CEEB', lightskyblue: '#87CEFA', blueviolet: '#8A2BE2', darkred: '#8B0000', darkmagenta: '#8B008B', saddlebrown: '#8B4513', darkseagreen: '#8FBC8F', lightgreen: '#90EE90', mediumpurple: '#9370D8', darkviolet: '#9400D3', palegreen: '#98FB98', darkorchid: '#9932CC', yellowgreen: '#9ACD32', sienna: '#A0522D', brown: '#A52A2A', darkgray: '#A9A9A9', lightblue: '#ADD8E6', greenyellow: '#ADFF2F', paleturquoise: '#AFEEEE', lightsteelblue: '#B0C4DE', powderblue: '#B0E0E6', firebrick: '#B22222', darkgoldenrod: '#B8860B', mediumorchid: '#BA55D3', rosybrown: '#BC8F8F', darkkhaki: '#BDB76B', silver: '#C0C0C0', mediumvioletred: '#C71585', indianred: '#CD5C5C', peru: '#CD853F', chocolate: '#D2691E', tan: '#D2B48C', lightgrey: '#D3D3D3', palevioletred: '#D87093', thistle: '#D8BFD8', orchid: '#DA70D6', goldenrod: '#DAA520', crimson: '#DC143C', gainsboro: '#DCDCDC', plum: '#DDA0DD', burlywood: '#DEB887', lightcyan: '#E0FFFF', lavender: '#E6E6FA', darksalmon: '#E9967A', violet: '#EE82EE', palegoldenrod: '#EEE8AA', lightcoral: '#F08080', khaki: '#F0E68C', aliceblue: '#F0F8FF', honeydew: '#F0FFF0', azure: '#F0FFFF', sandybrown: '#F4A460', wheat: '#F5DEB3', beige: '#F5F5DC', whitesmoke: '#F5F5F5', mintcream: '#F5FFFA', ghostwhite: '#F8F8FF', salmon: '#FA8072', antiquewhite: '#FAEBD7', linen: '#FAF0E6', lightgoldenrodyellow: '#FAFAD2', oldlace: '#FDF5E6', red: '#FF0000', fuchsia: '#FF00FF', magenta: '#FF00FF', deeppink: '#FF1493', orangered: '#FF4500', tomato: '#FF6347', hotpink: '#FF69B4', coral: '#FF7F50', darkorange: '#FF8C00', lightsalmon: '#FFA07A', orange: '#FFA500', lightpink: '#FFB6C1', pink: '#FFC0CB', gold: '#FFD700', peachpuff: '#FFDAB9', navajowhite: '#FFDEAD', moccasin: '#FFE4B5', bisque: '#FFE4C4', mistyrose: '#FFE4E1', blanchedalmond: '#FFEBCD', papayawhip: '#FFEFD5', lavenderblush: '#FFF0F5', seashell: '#FFF5EE', cornsilk: '#FFF8DC', lemonchiffon: '#FFFACD', floralwhite: '#FFFAF0', snow: '#FFFAFA', yellow: '#FFFF00', lightyellow: '#FFFFE0', ivory: '#FFFFF0', white: '#FFFFFF' }; - if (typeof color === 'string') { - return htmlColors[color]; - } - } - }, { - key: 'setColor', + value: function solve() { + var dx, dy, distance, fx, fy, repulsingForce, node1, node2, i, j; - /** - * Set the color of the colorPicker - * Supported formats: - * 'red' --> HTML color string - * '#ffffff' --> hex string - * 'rbg(255,255,255)' --> rgb string - * 'rgba(255,255,255,1.0)' --> rgba string - * {r:255,g:255,b:255} --> rgb object - * {r:255,g:255,b:255,a:1.0} --> rgba object - * @param color - * @param setInitial - */ - value: function setColor(color) { - var setInitial = arguments[1] === undefined ? true : arguments[1]; + var nodes = this.body.nodes; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var forces = this.physicsBody.forces; - if (color === 'none') { - return; - } + // repulsing forces between nodes + var nodeDistance = this.options.nodeDistance; - var rgba = undefined; + // we loop from i over all but the last entree in the array + // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j + for (i = 0; i < nodeIndices.length - 1; i++) { + node1 = nodes[nodeIndices[i]]; + for (j = i + 1; j < nodeIndices.length; j++) { + node2 = nodes[nodeIndices[j]]; - // if a html color shorthand is used, convert to hex - var htmlColor = this._isColorString(color); - if (htmlColor !== undefined) { - color = htmlColor; - } + // nodes only affect nodes on their level + if (node1.level === node2.level) { + dx = node2.x - node1.x; + dy = node2.y - node1.y; + distance = Math.sqrt(dx * dx + dy * dy); - // check format - if (util.isString(color) === true) { - if (util.isValidRGB(color) === true) { - var rgbaArray = color.substr(4).substr(0, color.length - 5).split(','); - rgba = { r: rgbaArray[0], g: rgbaArray[1], b: rgbaArray[2], a: 1 }; - } else if (util.isValidRGBA(color) === true) { - var rgbaArray = color.substr(5).substr(0, color.length - 6).split(','); - rgba = { r: rgbaArray[0], g: rgbaArray[1], b: rgbaArray[2], a: rgbaArray[3] }; - } else if (util.isValidHex(color) === true) { - var rgbObj = util.hexToRGB(color); - rgba = { r: rgbObj.r, g: rgbObj.g, b: rgbObj.b, a: 1 }; - } - } else { - if (color instanceof Object) { - if (color.r !== undefined && color.g !== undefined && color.b !== undefined) { - var alpha = color.a !== undefined ? color.a : '1.0'; - rgba = { r: color.r, g: color.g, b: color.b, a: alpha }; + var steepness = 0.05; + if (distance < nodeDistance) { + repulsingForce = -Math.pow(steepness * distance, 2) + Math.pow(steepness * nodeDistance, 2); + } else { + repulsingForce = 0; + } + // normalize force with + if (distance === 0) { + distance = 0.01; + } else { + repulsingForce = repulsingForce / distance; + } + fx = dx * repulsingForce; + fy = dy * repulsingForce; + + forces[node1.id].x -= fx; + forces[node1.id].y -= fy; + forces[node2.id].x += fx; + forces[node2.id].y += fy; } } } - - // set color - if (rgba === undefined) { - throw new Error('Unknown color passed to the colorPicker. Supported are strings: rgb, hex, rgba. Object: rgb ({r:r,g:g,b:b,[a:a]}). Supplied: ' + JSON.stringify(color)); - } else { - this._setColor(rgba, setInitial); - } } - }, { - key: 'show', + }]); - /** - * this shows the color picker at a location. The hue circle is constructed once and stored. - * @param x - * @param y - */ - value: function show(x, y) { - this.applied = false; - this.frame.style.display = 'block'; - this.frame.style.top = y + 'px'; - this.frame.style.left = x + 'px'; - this._generateHueCircle(); - } - }, { - key: '_hide', + return HierarchicalRepulsionSolver; + })(); - // ------------------------------------------ PRIVATE ----------------------------- // + exports["default"] = HierarchicalRepulsionSolver; + module.exports = exports["default"]; - /** - * Hide the picker. Is called by the cancel button. - * Optional boolean to store the previous color for easy access later on. - * @param storePrevious - * @private - */ - value: function _hide() { - var storePrevious = arguments[0] === undefined ? true : arguments[0]; +/***/ }, +/* 92 */ +/***/ function(module, exports, __webpack_require__) { - // store the previous color for next time; - if (storePrevious === true) { - this.previousColor = util.extend({}, this.color); - } + "use strict"; - if (this.applied === true) { - this.updateCallback(this.initialColor); - } + Object.defineProperty(exports, "__esModule", { + value: true + }); - this.frame.style.display = 'none'; - } - }, { - key: '_save', + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /** - * bound to the save button. Saves and hides. - * @private - */ - value: function _save() { - this.updateCallback(this.color); - this.applied = false; - this._hide(); - } - }, { - key: '_apply', + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - /** - * Bound to apply button. Saves but does not close. Is undone by the cancel button. - * @private - */ - value: function _apply() { - this.applied = true; - this.updateCallback(this.color); - this._updatePicker(this.color); - } - }, { - key: '_loadLast', + var SpringSolver = (function () { + function SpringSolver(body, physicsBody, options) { + _classCallCheck(this, SpringSolver); - /** - * load the color from the previous session. - * @private - */ - value: function _loadLast() { - if (this.previousColor !== undefined) { - this.setColor(this.previousColor, false); - } else { - alert('There is no last color to load...'); - } + this.body = body; + this.physicsBody = physicsBody; + this.setOptions(options); + } + + _createClass(SpringSolver, [{ + key: "setOptions", + value: function setOptions(options) { + this.options = options; } }, { - key: '_setColor', + key: "solve", /** - * set the color, place the picker - * @param rgba - * @param setInitial + * This function calculates the springforces on the nodes, accounting for the support nodes. + * * @private */ - value: function _setColor(rgba) { - var setInitial = arguments[1] === undefined ? true : arguments[1]; - - // store the initial color - if (setInitial === true) { - this.initialColor = util.extend({}, rgba); - } - - this.color = rgba; - var hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b); - - var angleConvert = 2 * Math.PI; - var radius = this.r * hsv.s; - var x = this.centerCoordinates.x + radius * Math.sin(angleConvert * hsv.h); - var y = this.centerCoordinates.y + radius * Math.cos(angleConvert * hsv.h); + value: function solve() { + var edgeLength = undefined, + edge = undefined; + var edgeIndices = this.physicsBody.physicsEdgeIndices; + var edges = this.body.edges; + var node1 = undefined, + node2 = undefined, + node3 = undefined; - this.colorPickerSelector.style.left = x - 0.5 * this.colorPickerSelector.clientWidth + 'px'; - this.colorPickerSelector.style.top = y - 0.5 * this.colorPickerSelector.clientHeight + 'px'; + // forces caused by the edges, modelled as springs + for (var i = 0; i < edgeIndices.length; i++) { + edge = edges[edgeIndices[i]]; + if (edge.connected === true && edge.toId !== edge.fromId) { + // only calculate forces if nodes are in the same sector + if (this.body.nodes[edge.toId] !== undefined && this.body.nodes[edge.fromId] !== undefined) { + if (edge.edgeType.via !== undefined) { + edgeLength = edge.options.length === undefined ? this.options.springLength : edge.options.length; + node1 = edge.to; + node2 = edge.edgeType.via; + node3 = edge.from; - this._updatePicker(rgba); + this._calculateSpringForce(node1, node2, 0.5 * edgeLength); + this._calculateSpringForce(node2, node3, 0.5 * edgeLength); + } else { + // the * 1.5 is here so the edge looks as large as a smooth edge. It does not initially because the smooth edges use + // the support nodes which exert a repulsive force on the to and from nodes, making the edge appear larger. + edgeLength = edge.options.length === undefined ? this.options.springLength * 1.5 : edge.options.length; + this._calculateSpringForce(edge.from, edge.to, edgeLength); + } + } + } + } } }, { - key: '_setOpacity', + key: "_calculateSpringForce", /** - * bound to opacity control - * @param value + * This is the code actually performing the calculation for the function above. + * + * @param node1 + * @param node2 + * @param edgeLength * @private */ - value: function _setOpacity(value) { - this.color.a = value / 100; - this._updatePicker(this.color); - } - }, { - key: '_setBrightness', + value: function _calculateSpringForce(node1, node2, edgeLength) { + var dx = node1.x - node2.x; + var dy = node1.y - node2.y; + var distance = Math.max(Math.sqrt(dx * dx + dy * dy), 0.01); - /** - * bound to brightness control - * @param value - * @private - */ - value: function _setBrightness(value) { - var hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b); - hsv.v = value / 100; - var rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v); - rgba['a'] = this.color.a; - this.color = rgba; - this._updatePicker(); - } - }, { - key: '_updatePicker', + // the 1/distance is so the fx and fy can be calculated without sine or cosine. + var springForce = this.options.springConstant * (edgeLength - distance) / distance; - /** - * update the colorpicker. A black circle overlays the hue circle to mimic the brightness decreasing. - * @param rgba - * @private - */ - value: function _updatePicker() { - var rgba = arguments[0] === undefined ? this.color : arguments[0]; + var fx = dx * springForce; + var fy = dy * springForce; - var hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b); - var ctx = this.colorPickerCanvas.getContext('2d'); - if (this.pixelRation === undefined) { - this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + // handle the case where one node is not part of the physcis + if (this.physicsBody.forces[node1.id] !== undefined) { + this.physicsBody.forces[node1.id].x += fx; + this.physicsBody.forces[node1.id].y += fy; } - ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); - // clear the canvas - var w = this.colorPickerCanvas.clientWidth; - var h = this.colorPickerCanvas.clientHeight; - ctx.clearRect(0, 0, w, h); + if (this.physicsBody.forces[node2.id] !== undefined) { + this.physicsBody.forces[node2.id].x -= fx; + this.physicsBody.forces[node2.id].y -= fy; + } + } + }]); - ctx.putImageData(this.hueCircle, 0, 0); - ctx.fillStyle = 'rgba(0,0,0,' + (1 - hsv.v) + ')'; - ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r); - ctx.fill(); + return SpringSolver; + })(); - this.brightnessRange.value = 100 * hsv.v; - this.opacityRange.value = 100 * rgba.a; + exports["default"] = SpringSolver; + module.exports = exports["default"]; - this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')'; - this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')'; - } - }, { - key: '_setSize', +/***/ }, +/* 93 */ +/***/ function(module, exports, __webpack_require__) { - /** - * used by create to set the size of the canvas. - * @private - */ - value: function _setSize() { - this.colorPickerCanvas.style.width = '100%'; - this.colorPickerCanvas.style.height = '100%'; + "use strict"; - this.colorPickerCanvas.width = 289 * this.pixelRatio; - this.colorPickerCanvas.height = 289 * this.pixelRatio; + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var HierarchicalSpringSolver = (function () { + function HierarchicalSpringSolver(body, physicsBody, options) { + _classCallCheck(this, HierarchicalSpringSolver); + + this.body = body; + this.physicsBody = physicsBody; + this.setOptions(options); + } + + _createClass(HierarchicalSpringSolver, [{ + key: "setOptions", + value: function setOptions(options) { + this.options = options; } }, { - key: '_create', + key: "solve", /** - * create all dom elements - * TODO: cleanup, lots of similar dom elements + * This function calculates the springforces on the nodes, accounting for the support nodes. + * * @private */ - value: function _create() { - this.frame = document.createElement('div'); - this.frame.className = 'vis-color-picker'; - - this.colorPickerDiv = document.createElement('div'); - this.colorPickerSelector = document.createElement('div'); - this.colorPickerSelector.className = 'vis-selector'; - this.colorPickerDiv.appendChild(this.colorPickerSelector); - - this.colorPickerCanvas = document.createElement('canvas'); - this.colorPickerDiv.appendChild(this.colorPickerCanvas); + value: function solve() { + var edgeLength, edge; + var dx, dy, fx, fy, springForce, distance; + var edges = this.body.edges; + var factor = 0.5; - if (!this.colorPickerCanvas.getContext) { - var noCanvas = document.createElement('DIV'); - noCanvas.style.color = 'red'; - noCanvas.style.fontWeight = 'bold'; - noCanvas.style.padding = '10px'; - noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; - this.colorPickerCanvas.appendChild(noCanvas); - } else { - var ctx = this.colorPickerCanvas.getContext('2d'); - this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + var edgeIndices = this.physicsBody.physicsEdgeIndices; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var forces = this.physicsBody.forces; - this.colorPickerCanvas.getContext('2d').setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); + // initialize the spring force counters + for (var i = 0; i < nodeIndices.length; i++) { + var nodeId = nodeIndices[i]; + forces[nodeId].springFx = 0; + forces[nodeId].springFy = 0; } - this.colorPickerDiv.className = 'vis-color'; - - this.opacityDiv = document.createElement('div'); - this.opacityDiv.className = 'vis-opacity'; - - this.brightnessDiv = document.createElement('div'); - this.brightnessDiv.className = 'vis-brightness'; + // forces caused by the edges, modelled as springs + for (var i = 0; i < edgeIndices.length; i++) { + edge = edges[edgeIndices[i]]; + if (edge.connected === true) { + edgeLength = edge.options.length === undefined ? this.options.springLength : edge.options.length; - this.arrowDiv = document.createElement('div'); - this.arrowDiv.className = 'vis-arrow'; + dx = edge.from.x - edge.to.x; + dy = edge.from.y - edge.to.y; + distance = Math.sqrt(dx * dx + dy * dy); + distance = distance === 0 ? 0.01 : distance; - this.opacityRange = document.createElement('input'); - this.opacityRange.type = 'range'; - this.opacityRange.min = '0'; - this.opacityRange.max = '100'; - this.opacityRange.value = '100'; - this.opacityRange.className = 'vis-range'; + // the 1/distance is so the fx and fy can be calculated without sine or cosine. + springForce = this.options.springConstant * (edgeLength - distance) / distance; - this.brightnessRange = document.createElement('input'); - this.brightnessRange.type = 'range'; - this.brightnessRange.min = '0'; - this.brightnessRange.max = '100'; - this.brightnessRange.value = '100'; - this.brightnessRange.className = 'vis-range'; + fx = dx * springForce; + fy = dy * springForce; - this.opacityDiv.appendChild(this.opacityRange); - this.brightnessDiv.appendChild(this.brightnessRange); + if (edge.to.level != edge.from.level) { + forces[edge.toId].springFx -= fx; + forces[edge.toId].springFy -= fy; + forces[edge.fromId].springFx += fx; + forces[edge.fromId].springFy += fy; + } else { + forces[edge.toId].x -= factor * fx; + forces[edge.toId].y -= factor * fy; + forces[edge.fromId].x += factor * fx; + forces[edge.fromId].y += factor * fy; + } + } + } - var me = this; - this.opacityRange.onchange = function () { - me._setOpacity(this.value); - }; - this.opacityRange.oninput = function () { - me._setOpacity(this.value); - }; - this.brightnessRange.onchange = function () { - me._setBrightness(this.value); - }; - this.brightnessRange.oninput = function () { - me._setBrightness(this.value); - }; + // normalize spring forces + var springForce = 1; + var springFx, springFy; + for (var i = 0; i < nodeIndices.length; i++) { + var nodeId = nodeIndices[i]; + springFx = Math.min(springForce, Math.max(-springForce, forces[nodeId].springFx)); + springFy = Math.min(springForce, Math.max(-springForce, forces[nodeId].springFy)); - this.brightnessLabel = document.createElement('div'); - this.brightnessLabel.className = 'vis-label vis-brightness'; - this.brightnessLabel.innerHTML = 'brightness:'; + forces[nodeId].x += springFx; + forces[nodeId].y += springFy; + } - this.opacityLabel = document.createElement('div'); - this.opacityLabel.className = 'vis-label vis-opacity'; - this.opacityLabel.innerHTML = 'opacity:'; + // retain energy balance + var totalFx = 0; + var totalFy = 0; + for (var i = 0; i < nodeIndices.length; i++) { + var nodeId = nodeIndices[i]; + totalFx += forces[nodeId].x; + totalFy += forces[nodeId].y; + } + var correctionFx = totalFx / nodeIndices.length; + var correctionFy = totalFy / nodeIndices.length; - this.newColorDiv = document.createElement('div'); - this.newColorDiv.className = 'vis-new-color'; - this.newColorDiv.innerHTML = 'new'; + for (var i = 0; i < nodeIndices.length; i++) { + var nodeId = nodeIndices[i]; + forces[nodeId].x -= correctionFx; + forces[nodeId].y -= correctionFy; + } + } + }]); - this.initialColorDiv = document.createElement('div'); - this.initialColorDiv.className = 'vis-initial-color'; - this.initialColorDiv.innerHTML = 'initial'; + return HierarchicalSpringSolver; + })(); - this.cancelButton = document.createElement('div'); - this.cancelButton.className = 'vis-button vis-cancel'; - this.cancelButton.innerHTML = 'cancel'; - this.cancelButton.onclick = this._hide.bind(this, false); + exports["default"] = HierarchicalSpringSolver; + module.exports = exports["default"]; - this.applyButton = document.createElement('div'); - this.applyButton.className = 'vis-button vis-apply'; - this.applyButton.innerHTML = 'apply'; - this.applyButton.onclick = this._apply.bind(this); +/***/ }, +/* 94 */ +/***/ function(module, exports, __webpack_require__) { - this.saveButton = document.createElement('div'); - this.saveButton.className = 'vis-button vis-save'; - this.saveButton.innerHTML = 'save'; - this.saveButton.onclick = this._save.bind(this); + "use strict"; - this.loadButton = document.createElement('div'); - this.loadButton.className = 'vis-button vis-load'; - this.loadButton.innerHTML = 'load last'; - this.loadButton.onclick = this._loadLast.bind(this); + Object.defineProperty(exports, "__esModule", { + value: true + }); - this.frame.appendChild(this.colorPickerDiv); - this.frame.appendChild(this.arrowDiv); - this.frame.appendChild(this.brightnessLabel); - this.frame.appendChild(this.brightnessDiv); - this.frame.appendChild(this.opacityLabel); - this.frame.appendChild(this.opacityDiv); - this.frame.appendChild(this.newColorDiv); - this.frame.appendChild(this.initialColorDiv); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - this.frame.appendChild(this.cancelButton); - this.frame.appendChild(this.applyButton); - this.frame.appendChild(this.saveButton); - this.frame.appendChild(this.loadButton); - } - }, { - key: '_bindHammer', + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - /** - * bind hammer to the color picker - * @private - */ - value: function _bindHammer() { - var _this = this; + var CentralGravitySolver = (function () { + function CentralGravitySolver(body, physicsBody, options) { + _classCallCheck(this, CentralGravitySolver); - this.drag = {}; - this.pinch = {}; - this.hammer = new Hammer(this.colorPickerCanvas); - this.hammer.get('pinch').set({ enable: true }); + this.body = body; + this.physicsBody = physicsBody; + this.setOptions(options); + } - hammerUtil.onTouch(this.hammer, function (event) { - _this._moveSelector(event); - }); - this.hammer.on('tap', function (event) { - _this._moveSelector(event); - }); - this.hammer.on('panstart', function (event) { - _this._moveSelector(event); - }); - this.hammer.on('panmove', function (event) { - _this._moveSelector(event); - }); - this.hammer.on('panend', function (event) { - _this._moveSelector(event); - }); + _createClass(CentralGravitySolver, [{ + key: "setOptions", + value: function setOptions(options) { + this.options = options; } }, { - key: '_generateHueCircle', - - /** - * generate the hue circle. This is relatively heavy (200ms) and is done only once on the first time it is shown. - * @private - */ - value: function _generateHueCircle() { - if (this.generated === false) { - var ctx = this.colorPickerCanvas.getContext('2d'); - if (this.pixelRation === undefined) { - this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); - } - ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); - - // clear the canvas - var w = this.colorPickerCanvas.clientWidth; - var h = this.colorPickerCanvas.clientHeight; - ctx.clearRect(0, 0, w, h); + key: "solve", + value: function solve() { + var dx = undefined, + dy = undefined, + distance = undefined, + node = undefined; + var nodes = this.body.nodes; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var forces = this.physicsBody.forces; - // draw hue circle - var x = undefined, - y = undefined, - hue = undefined, - sat = undefined; - this.centerCoordinates = { x: w * 0.5, y: h * 0.5 }; - this.r = 0.49 * w; - var angleConvert = 2 * Math.PI / 360; - var hfac = 1 / 360; - var sfac = 1 / this.r; - var rgb = undefined; - for (hue = 0; hue < 360; hue++) { - for (sat = 0; sat < this.r; sat++) { - x = this.centerCoordinates.x + sat * Math.sin(angleConvert * hue); - y = this.centerCoordinates.y + sat * Math.cos(angleConvert * hue); - rgb = util.HSVToRGB(hue * hfac, sat * sfac, 1); - ctx.fillStyle = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')'; - ctx.fillRect(x - 0.5, y - 0.5, 2, 2); - } - } - ctx.strokeStyle = 'rgba(0,0,0,1)'; - ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r); - ctx.stroke(); + for (var i = 0; i < nodeIndices.length; i++) { + var nodeId = nodeIndices[i]; + node = nodes[nodeId]; + dx = -node.x; + dy = -node.y; + distance = Math.sqrt(dx * dx + dy * dy); - this.hueCircle = ctx.getImageData(0, 0, w, h); + this._calculateForces(distance, dx, dy, forces, node); } - this.generated = true; } }, { - key: '_moveSelector', + key: "_calculateForces", /** - * move the selector. This is called by hammer functions. - * - * @param event + * Calculate the forces based on the distance. * @private */ - value: function _moveSelector(event) { - var rect = this.colorPickerDiv.getBoundingClientRect(); - var left = event.center.x - rect.left; - var top = event.center.y - rect.top; - - var centerY = 0.5 * this.colorPickerDiv.clientHeight; - var centerX = 0.5 * this.colorPickerDiv.clientWidth; - - var x = left - centerX; - var y = top - centerY; - - var angle = Math.atan2(x, y); - var radius = 0.98 * Math.min(Math.sqrt(x * x + y * y), centerX); - - var newTop = Math.cos(angle) * radius + centerY; - var newLeft = Math.sin(angle) * radius + centerX; - - this.colorPickerSelector.style.top = newTop - 0.5 * this.colorPickerSelector.clientHeight + 'px'; - this.colorPickerSelector.style.left = newLeft - 0.5 * this.colorPickerSelector.clientWidth + 'px'; - - // set color - var h = angle / (2 * Math.PI); - h = h < 0 ? h + 1 : h; - var s = radius / this.r; - var hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b); - hsv.h = h; - hsv.s = s; - var rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v); - rgba['a'] = this.color.a; - this.color = rgba; - - // update previews - this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')'; - this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')'; + value: function _calculateForces(distance, dx, dy, forces, node) { + var gravityForce = distance === 0 ? 0 : this.options.centralGravity / distance; + forces[node.id].x = dx * gravityForce; + forces[node.id].y = dy * gravityForce; } }]); - return ColorPicker; + return CentralGravitySolver; })(); - exports['default'] = ColorPicker; - module.exports = exports['default']; + exports["default"] = CentralGravitySolver; + module.exports = exports["default"]; /***/ }, -/* 74 */ +/* 95 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; + "use strict"; - Object.defineProperty(exports, '__esModule', { + Object.defineProperty(exports, "__esModule", { value: true }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - var _sharedLabel = __webpack_require__(75); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var _sharedLabel2 = _interopRequireDefault(_sharedLabel); + function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - var _nodesShapesBox = __webpack_require__(92); + var _BarnesHutSolver2 = __webpack_require__(89); - var _nodesShapesBox2 = _interopRequireDefault(_nodesShapesBox); + var _BarnesHutSolver3 = _interopRequireDefault(_BarnesHutSolver2); + + var ForceAtlas2BasedRepulsionSolver = (function (_BarnesHutSolver) { + function ForceAtlas2BasedRepulsionSolver(body, physicsBody, options) { + _classCallCheck(this, ForceAtlas2BasedRepulsionSolver); - var _nodesShapesCircle = __webpack_require__(93); + _get(Object.getPrototypeOf(ForceAtlas2BasedRepulsionSolver.prototype), "constructor", this).call(this, body, physicsBody, options); + } - var _nodesShapesCircle2 = _interopRequireDefault(_nodesShapesCircle); + _inherits(ForceAtlas2BasedRepulsionSolver, _BarnesHutSolver); - var _nodesShapesCircularImage = __webpack_require__(94); + _createClass(ForceAtlas2BasedRepulsionSolver, [{ + key: "_calculateForces", - var _nodesShapesCircularImage2 = _interopRequireDefault(_nodesShapesCircularImage); + /** + * Calculate the forces based on the distance. + * + * @param distance + * @param dx + * @param dy + * @param node + * @param parentBranch + * @private + */ + value: function _calculateForces(distance, dx, dy, node, parentBranch) { + if (distance === 0) { + distance = 0.1 * Math.random(); + dx = distance; + } - var _nodesShapesDatabase = __webpack_require__(95); + if (this.overlapAvoidanceFactor < 1) { + distance = Math.max(0.1 + this.overlapAvoidanceFactor * node.shape.radius, distance - node.shape.radius); + } - var _nodesShapesDatabase2 = _interopRequireDefault(_nodesShapesDatabase); + var degree = node.edges.length + 1; + // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines + // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce + var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass * degree / Math.pow(distance, 2); + var fx = dx * gravityForce; + var fy = dy * gravityForce; + + this.physicsBody.forces[node.id].x += fx; + this.physicsBody.forces[node.id].y += fy; + } + }]); + + return ForceAtlas2BasedRepulsionSolver; + })(_BarnesHutSolver3["default"]); + + exports["default"] = ForceAtlas2BasedRepulsionSolver; + module.exports = exports["default"]; + +/***/ }, +/* 96 */ +/***/ function(module, exports, __webpack_require__) { - var _nodesShapesDiamond = __webpack_require__(96); + "use strict"; - var _nodesShapesDiamond2 = _interopRequireDefault(_nodesShapesDiamond); + Object.defineProperty(exports, "__esModule", { + value: true + }); - var _nodesShapesDot = __webpack_require__(97); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var _nodesShapesDot2 = _interopRequireDefault(_nodesShapesDot); + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - var _nodesShapesEllipse = __webpack_require__(98); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - var _nodesShapesEllipse2 = _interopRequireDefault(_nodesShapesEllipse); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var _nodesShapesIcon = __webpack_require__(99); + function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - var _nodesShapesIcon2 = _interopRequireDefault(_nodesShapesIcon); + var _CentralGravitySolver2 = __webpack_require__(94); - var _nodesShapesImage = __webpack_require__(100); + var _CentralGravitySolver3 = _interopRequireDefault(_CentralGravitySolver2); - var _nodesShapesImage2 = _interopRequireDefault(_nodesShapesImage); + var ForceAtlas2BasedCentralGravitySolver = (function (_CentralGravitySolver) { + function ForceAtlas2BasedCentralGravitySolver(body, physicsBody, options) { + _classCallCheck(this, ForceAtlas2BasedCentralGravitySolver); - var _nodesShapesSquare = __webpack_require__(101); + _get(Object.getPrototypeOf(ForceAtlas2BasedCentralGravitySolver.prototype), "constructor", this).call(this, body, physicsBody, options); + } - var _nodesShapesSquare2 = _interopRequireDefault(_nodesShapesSquare); + _inherits(ForceAtlas2BasedCentralGravitySolver, _CentralGravitySolver); - var _nodesShapesStar = __webpack_require__(102); + _createClass(ForceAtlas2BasedCentralGravitySolver, [{ + key: "_calculateForces", - var _nodesShapesStar2 = _interopRequireDefault(_nodesShapesStar); + /** + * Calculate the forces based on the distance. + * @private + */ + value: function _calculateForces(distance, dx, dy, forces, node) { + if (distance > 0) { + var degree = node.edges.length + 1; + var gravityForce = this.options.centralGravity * degree * node.options.mass; + forces[node.id].x = dx * gravityForce; + forces[node.id].y = dy * gravityForce; + } + } + }]); - var _nodesShapesText = __webpack_require__(103); + return ForceAtlas2BasedCentralGravitySolver; + })(_CentralGravitySolver3["default"]); - var _nodesShapesText2 = _interopRequireDefault(_nodesShapesText); + exports["default"] = ForceAtlas2BasedCentralGravitySolver; + module.exports = exports["default"]; - var _nodesShapesTriangle = __webpack_require__(104); +/***/ }, +/* 97 */ +/***/ function(module, exports, __webpack_require__) { - var _nodesShapesTriangle2 = _interopRequireDefault(_nodesShapesTriangle); + 'use strict'; - var _nodesShapesTriangleDown = __webpack_require__(105); + Object.defineProperty(exports, '__esModule', { + value: true + }); - var _nodesShapesTriangleDown2 = _interopRequireDefault(_nodesShapesTriangleDown); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var _sharedValidator = __webpack_require__(46); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - var _sharedValidator2 = _interopRequireDefault(_sharedValidator); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var util = __webpack_require__(2); + var _componentsNodesCluster = __webpack_require__(98); - /** - * @class Node - * A node. A node can be connected to other nodes via one or multiple edges. - * @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, available: - * "database", "circle", "ellipse", - * "box", "image", "text", "dot", - * "star", "triangle", "triangleDown", - * "square", "icon" - * {string} image An image url - * {string} title An title text, can be HTML - * {anytype} group A group name or number - * @param {Network.Images} imagelist A list with images. Only needed - * when the node has an image - * @param {Network.Groups} grouplist A list with groups. Needed for - * retrieving group options - * @param {Object} constants An object with default values for - * example for the color - * - */ + var _componentsNodesCluster2 = _interopRequireDefault(_componentsNodesCluster); - var Node = (function () { - function Node(options, body, imagelist, grouplist, globalOptions) { - _classCallCheck(this, Node); + var util = __webpack_require__(7); - this.options = util.bridgeObject(globalOptions); - this.body = body; + var ClusterEngine = (function () { + function ClusterEngine(body) { + var _this = this; - this.edges = []; // all edges connected to this node + _classCallCheck(this, ClusterEngine); - // set defaults for the options - this.id = undefined; - this.imagelist = imagelist; - this.grouplist = grouplist; + this.body = body; + this.clusteredNodes = {}; - // 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.options = {}; + this.defaultOptions = {}; + util.extend(this.options, this.defaultOptions); - this.labelModule = new _sharedLabel2['default'](this.body, this.options); - this.setOptions(options); + this.body.emitter.on('_resetData', function () { + _this.clusteredNodes = {}; + }); } - _createClass(Node, [{ - key: 'attachEdge', - - /** - * Attach a edge to the node - * @param {Edge} edge - */ - value: function attachEdge(edge) { - if (this.edges.indexOf(edge) === -1) { - this.edges.push(edge); - } + _createClass(ClusterEngine, [{ + key: 'setOptions', + value: function setOptions(options) { + if (options !== undefined) {} } }, { - key: 'detachEdge', + key: 'clusterByHubsize', /** - * Detach a edge from the node - * @param {Edge} edge - */ - value: function detachEdge(edge) { - var index = this.edges.indexOf(edge); - if (index != -1) { - this.edges.splice(index, 1); + * + * @param hubsize + * @param options + */ + value: function clusterByHubsize(hubsize, options) { + if (hubsize === undefined) { + hubsize = this._getHubSize(); + } else if (typeof hubsize === 'object') { + options = this._checkOptions(hubsize); + hubsize = this._getHubSize(); } - } - }, { - key: 'togglePhysics', - /** - * Enable or disable the physics. - * @param status - */ - value: function togglePhysics(status) { - this.options.physics = status; + var nodesToCluster = []; + for (var i = 0; i < this.body.nodeIndices.length; i++) { + var node = this.body.nodes[this.body.nodeIndices[i]]; + if (node.edges.length >= hubsize) { + nodesToCluster.push(node.id); + } + } + + for (var i = 0; i < nodesToCluster.length; i++) { + this.clusterByConnection(nodesToCluster[i], options, false); + } + this.body.emitter.emit('_dataChanged'); } }, { - key: 'setOptions', + key: 'cluster', /** - * Set or overwrite options for the node - * @param {Object} options an object with options - * @param {Object} constants and object with default, global options - */ - value: function setOptions(options) { - if (!options) { - return; - } - // basic options - if (options.id !== undefined) { - this.id = options.id; - } + * loop over all nodes, check if they adhere to the condition and cluster if needed. + * @param options + * @param refreshData + */ + value: function cluster() { + var options = arguments[0] === undefined ? {} : arguments[0]; + var refreshData = arguments[1] === undefined ? true : arguments[1]; - if (this.id === undefined) { - throw 'Node must have an id'; + if (options.joinCondition === undefined) { + throw new Error('Cannot call clusterByNodeData without a joinCondition function in the options.'); } - // set these options locally - if (options.x !== undefined) { - this.x = parseInt(options.x);this.predefinedPosition = true; - } - if (options.y !== undefined) { - this.y = parseInt(options.y);this.predefinedPosition = true; - } - if (options.size !== undefined) { - this.baseSize = options.size; - } - if (options.value !== undefined) { - options.value = parseInt(options.value); - } + // check if the options object is fine, append if needed + options = this._checkOptions(options); - // copy group options - if (typeof options.group === 'number' || typeof options.group === 'string' && options.group != '') { - var groupObj = this.grouplist.get(options.group); - util.deepExtend(this.options, groupObj); - // the color object needs to be completely defined. Since groups can partially overwrite the colors, we parse it again, just in case. - this.options.color = util.parseColor(this.options.color); - } + var childNodesObj = {}; + var childEdgesObj = {}; - // this transforms all shorthands into fully defined options - Node.parseOptions(this.options, options, true); + // collect the nodes that will be in the cluster + for (var i = 0; i < this.body.nodeIndices.length; i++) { + var nodeId = this.body.nodeIndices[i]; + var node = this.body.nodes[nodeId]; + var clonedOptions = this._cloneOptions(node); + if (options.joinCondition(clonedOptions) === true) { + childNodesObj[nodeId] = this.body.nodes[nodeId]; - // load the images - if (this.options.image !== undefined && this.options.image != '') { - if (this.imagelist) { - this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage, this.id); - } else { - throw 'No imagelist provided'; + // collect the nodes that will be in the cluster + for (var _i = 0; _i < node.edges.length; _i++) { + var edge = node.edges[_i]; + childEdgesObj[edge.id] = edge; + } } } - this.updateShape(); - this.updateLabelModule(); + this._cluster(childNodesObj, childEdgesObj, options, refreshData); + } + }, { + key: 'clusterOutliers', - // reset the size of the node, this can be changed - this._reset(); + /** + * Cluster all nodes in the network that have only 1 edge + * @param options + * @param refreshData + */ + value: function clusterOutliers(options) { + var refreshData = arguments[1] === undefined ? true : arguments[1]; - if (options.hidden !== undefined || options.physics !== undefined) { - return true; + options = this._checkOptions(options); + var clusters = []; + + // collect the nodes that will be in the cluster + for (var i = 0; i < this.body.nodeIndices.length; i++) { + var childNodesObj = {}; + var childEdgesObj = {}; + var nodeId = this.body.nodeIndices[i]; + var visibleEdges = 0; + var edge = undefined; + for (var j = 0; j < this.body.nodes[nodeId].edges.length; j++) { + if (this.body.nodes[nodeId].edges[j].options.hidden === false) { + visibleEdges++; + edge = this.body.nodes[nodeId].edges[j]; + } + } + + if (visibleEdges === 1) { + // this is an outlier + var childNodeId = this._getConnectedId(edge, nodeId); + if (childNodeId !== nodeId) { + if (options.joinCondition === undefined) { + if (this._checkIfUsed(clusters, nodeId, edge.id) === false && this._checkIfUsed(clusters, childNodeId, edge.id) === false) { + childEdgesObj[edge.id] = edge; + childNodesObj[nodeId] = this.body.nodes[nodeId]; + childNodesObj[childNodeId] = this.body.nodes[childNodeId]; + } + } else { + var clonedOptions = this._cloneOptions(this.body.nodes[nodeId]); + if (options.joinCondition(clonedOptions) === true && this._checkIfUsed(clusters, nodeId, edge.id) === false) { + childEdgesObj[edge.id] = edge; + childNodesObj[nodeId] = this.body.nodes[nodeId]; + } + clonedOptions = this._cloneOptions(this.body.nodes[childNodeId]); + if (options.joinCondition(clonedOptions) === true && this._checkIfUsed(clusters, nodeId, edge.id) === false) { + childEdgesObj[edge.id] = edge; + childNodesObj[childNodeId] = this.body.nodes[childNodeId]; + } + } + + if (Object.keys(childNodesObj).length > 0 && Object.keys(childEdgesObj).length > 0) { + clusters.push({ nodes: childNodesObj, edges: childEdgesObj }); + } + } + } } - return false; - } - }, { - key: 'updateLabelModule', - value: function updateLabelModule() { - if (this.options.label === undefined || this.options.label === null) { - this.options.label = ''; + + for (var i = 0; i < clusters.length; i++) { + this._cluster(clusters[i].nodes, clusters[i].edges, options, false); } - this.labelModule.setOptions(this.options, true); - if (this.labelModule.baseSize !== undefined) { - this.baseFontSize = this.labelModule.baseSize; + + if (refreshData === true) { + this.body.emitter.emit('_dataChanged'); } } }, { - key: 'updateShape', - value: function updateShape() { - // choose draw method depending on the shape - switch (this.options.shape) { - case 'box': - this.shape = new _nodesShapesBox2['default'](this.options, this.body, this.labelModule); - break; - case 'circle': - this.shape = new _nodesShapesCircle2['default'](this.options, this.body, this.labelModule); - break; - case 'circularImage': - this.shape = new _nodesShapesCircularImage2['default'](this.options, this.body, this.labelModule, this.imageObj); - break; - case 'database': - this.shape = new _nodesShapesDatabase2['default'](this.options, this.body, this.labelModule); - break; - case 'diamond': - this.shape = new _nodesShapesDiamond2['default'](this.options, this.body, this.labelModule); - break; - case 'dot': - this.shape = new _nodesShapesDot2['default'](this.options, this.body, this.labelModule); - break; - case 'ellipse': - this.shape = new _nodesShapesEllipse2['default'](this.options, this.body, this.labelModule); - break; - case 'icon': - this.shape = new _nodesShapesIcon2['default'](this.options, this.body, this.labelModule); - break; - case 'image': - this.shape = new _nodesShapesImage2['default'](this.options, this.body, this.labelModule, this.imageObj); - break; - case 'square': - this.shape = new _nodesShapesSquare2['default'](this.options, this.body, this.labelModule); - break; - case 'star': - this.shape = new _nodesShapesStar2['default'](this.options, this.body, this.labelModule); - break; - case 'text': - this.shape = new _nodesShapesText2['default'](this.options, this.body, this.labelModule); - break; - case 'triangle': - this.shape = new _nodesShapesTriangle2['default'](this.options, this.body, this.labelModule); - break; - case 'triangleDown': - this.shape = new _nodesShapesTriangleDown2['default'](this.options, this.body, this.labelModule); - break; - default: - this.shape = new _nodesShapesEllipse2['default'](this.options, this.body, this.labelModule); - break; + key: '_checkIfUsed', + value: function _checkIfUsed(clusters, nodeId, edgeId) { + for (var i = 0; i < clusters.length; i++) { + var cluster = clusters[i]; + if (cluster.nodes[nodeId] !== undefined || cluster.edges[edgeId] !== undefined) { + return true; + } } - this._reset(); - } - }, { - key: 'select', - - /** - * select this node - */ - value: function select() { - this.selected = true; - this._reset(); - } - }, { - key: 'unselect', - - /** - * unselect this node - */ - value: function unselect() { - this.selected = false; - this._reset(); - } - }, { - key: '_reset', - - /** - * Reset the calculated size of the node, forces it to recalculate its size - * @private - */ - value: function _reset() { - this.shape.width = undefined; - this.shape.height = undefined; + return false; } }, { - key: 'getTitle', + key: 'clusterByConnection', /** - * get the title of this node. - * @return {string} title The title of the node, or undefined when no title - * has been set. - */ - value: function getTitle() { - return this.options.title; - } - }, { - key: 'distanceToBorder', + * suck all connected nodes of a node into the node. + * @param nodeId + * @param options + * @param refreshData + */ + value: function clusterByConnection(nodeId, options) { + var refreshData = arguments[2] === undefined ? true : arguments[2]; - /** - * 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 - */ - value: function distanceToBorder(ctx, angle) { - return this.shape.distanceToBorder(ctx, angle); - } - }, { - key: 'isFixed', + // kill conditions + if (nodeId === undefined) { + throw new Error('No nodeId supplied to clusterByConnection!'); + } + if (this.body.nodes[nodeId] === undefined) { + throw new Error('The nodeId given to clusterByConnection does not exist!'); + } - /** - * Check if this node has a fixed x and y position - * @return {boolean} true if fixed, false if not - */ - value: function isFixed() { - return this.options.fixed.x && this.options.fixed.y; - } - }, { - key: 'isSelected', + var node = this.body.nodes[nodeId]; + options = this._checkOptions(options, node); + if (options.clusterNodeProperties.x === undefined) { + options.clusterNodeProperties.x = node.x; + } + if (options.clusterNodeProperties.y === undefined) { + options.clusterNodeProperties.y = node.y; + } + if (options.clusterNodeProperties.fixed === undefined) { + options.clusterNodeProperties.fixed = {}; + options.clusterNodeProperties.fixed.x = node.options.fixed.x; + options.clusterNodeProperties.fixed.y = node.options.fixed.y; + } - /** - * check if this node is selecte - * @return {boolean} selected True if node is selected, else false - */ - value: function isSelected() { - return this.selected; - } - }, { - key: 'getValue', + var childNodesObj = {}; + var childEdgesObj = {}; + var parentNodeId = node.id; + var parentClonedOptions = this._cloneOptions(node); + childNodesObj[parentNodeId] = node; - /** - * Retrieve the value of the node. Can be undefined - * @return {Number} value - */ - value: function getValue() { - return this.options.value; - } - }, { - key: 'setValueRange', + // collect the nodes that will be in the cluster + for (var i = 0; i < node.edges.length; i++) { + var edge = node.edges[i]; + var childNodeId = this._getConnectedId(edge, parentNodeId); - /** - * Adjust the value range of the node. The node will adjust it's size - * based on its value. - * @param {Number} min - * @param {Number} max - */ - 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; + if (childNodeId !== parentNodeId) { + if (options.joinCondition === undefined) { + childEdgesObj[edge.id] = edge; + childNodesObj[childNodeId] = this.body.nodes[childNodeId]; + } else { + // clone the options and insert some additional parameters that could be interesting. + var childClonedOptions = this._cloneOptions(this.body.nodes[childNodeId]); + if (options.joinCondition(parentClonedOptions, childClonedOptions) === true) { + childEdgesObj[edge.id] = edge; + childNodesObj[childNodeId] = this.body.nodes[childNodeId]; + } + } + } else { + childEdgesObj[edge.id] = edge; } - this.options.size = this.options.scaling.min + scale * sizeDiff; - } else { - this.options.size = this.baseSize; - this.options.font.size = this.baseFontSize; } - } - }, { - key: 'draw', - /** - * Draw this node in the given canvas - * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); - * @param {CanvasRenderingContext2D} ctx - */ - value: function draw(ctx) { - this.shape.draw(ctx, this.x, this.y, this.selected, this.hover); + this._cluster(childNodesObj, childEdgesObj, options, refreshData); } }, { - key: 'updateBoundingBox', + key: '_cloneOptions', /** - * Update the bounding box of the shape - */ - value: function updateBoundingBox() { - this.shape.updateBoundingBox(this.x, this.y); + * 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 objId + * @param type + * @returns {{}} + * @private + */ + 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; } }, { - key: 'resize', + key: '_createClusterEdges', /** - * 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 - */ - value: function resize(ctx) { - this.shape.resize(ctx); + * This function creates the edges that will be attached to the cluster. + * + * @param childNodesObj + * @param childEdgesObj + * @param newEdges + * @param options + * @private + */ + value: function _createClusterEdges(childNodesObj, childEdgesObj, newEdges, clusterNodeProperties, clusterEdgeProperties) { + var edge = undefined, + childNodeId = undefined, + childNode = undefined, + toId = undefined, + fromId = undefined, + otherNodeId = undefined; + + var childKeys = Object.keys(childNodesObj); + for (var i = 0; i < childKeys.length; i++) { + childNodeId = childKeys[i]; + childNode = childNodesObj[childNodeId]; + + // construct new edges from the cluster to others + for (var j = 0; j < childNode.edges.length; j++) { + edge = childNode.edges[j]; + childEdgesObj[edge.id] = edge; + + // childNodeId position will be replaced by the cluster. + if (edge.toId == childNodeId) { + // this is a double equals because ints and strings can be interchanged here. + toId = clusterNodeProperties.id; + fromId = edge.fromId; + otherNodeId = fromId; + } else { + toId = edge.toId; + fromId = clusterNodeProperties.id; + otherNodeId = toId; + } + + // if the node connected to the cluster is also in the cluster we do not need a new edge. + if (childNodesObj[otherNodeId] === undefined) { + var clonedOptions = this._cloneOptions(edge, 'edge'); + util.deepExtend(clonedOptions, clusterEdgeProperties); + clonedOptions.from = fromId; + clonedOptions.to = toId; + clonedOptions.id = 'clusterEdge:' + util.randomUUID(); + newEdges.push(this.body.functions.createEdge(clonedOptions)); + } + } + } } }, { - key: 'isOverlappingWith', + key: '_checkOptions', /** - * 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 - */ - 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; + * This function checks the options that can be supplied to the different cluster functions + * for certain fields and inserts defaults if needed + * @param options + * @returns {*} + * @private + */ + value: function _checkOptions() { + var options = arguments[0] === undefined ? {} : arguments[0]; + + if (options.clusterEdgeProperties === undefined) { + options.clusterEdgeProperties = {}; + } + if (options.clusterNodeProperties === undefined) { + options.clusterNodeProperties = {}; + } + + return options; } }, { - key: 'isBoundingBoxOverlappingWith', + key: '_cluster', /** - * 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 - */ - 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; - } - }], [{ - key: 'parseOptions', + * + * @param {Object} childNodesObj | object with node objects, id as keys, same as childNodes except it also contains a source node + * @param {Object} childEdgesObj | object with edge objects, id as keys + * @param {Array} options | object with {clusterNodeProperties, clusterEdgeProperties, processProperties} + * @param {Boolean} refreshData | when true, do not wrap up + * @private + */ + value: function _cluster(childNodesObj, childEdgesObj, options) { + var refreshData = arguments[3] === undefined ? true : arguments[3]; - /** - * 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 parentOptions - * @param newOptions - */ - value: function parseOptions(parentOptions, newOptions) { - var allowDeletion = arguments[2] === undefined ? false : arguments[2]; + // kill condition: no children so cant cluster + if (Object.keys(childNodesObj).length === 0) { + return; + } - var fields = ['color', 'font', 'fixed', 'shadow']; - util.selectiveNotDeepExtend(fields, parentOptions, newOptions, allowDeletion); + var clusterNodeProperties = util.deepExtend({}, options.clusterNodeProperties); - // merge the shadow options into the parent. - util.mergeOptions(parentOptions, newOptions, 'shadow'); + // construct the clusterNodeProperties + if (options.processProperties !== undefined) { + // get the childNode options + var childNodesOptions = []; + for (var nodeId in childNodesObj) { + var clonedOptions = this._cloneOptions(childNodesObj[nodeId]); + childNodesOptions.push(clonedOptions); + } - // 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 = undefined; - delete parentOptions.color; - } + // get clusterproperties based on childNodes + var childEdgesOptions = []; + for (var edgeId in childEdgesObj) { + var clonedOptions = this._cloneOptions(childEdgesObj[edgeId], 'edge'); + childEdgesOptions.push(clonedOptions); + } - // 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; - } + clusterNodeProperties = options.processProperties(clusterNodeProperties, childNodesOptions, childEdgesOptions); + if (!clusterNodeProperties) { + throw new Error('The processProperties function does not return properties!'); } } - // handle the font options - if (newOptions.font !== undefined) { - _sharedLabel2['default'].parseOptions(parentOptions.font, newOptions); + // check if we have an unique id; + if (clusterNodeProperties.id === undefined) { + clusterNodeProperties.id = 'cluster:' + util.randomUUID(); } + var clusterId = clusterNodeProperties.id; - // handle the scaling options, specifically the label part - if (newOptions.scaling !== undefined) { - util.mergeOptions(parentOptions.scaling, newOptions.scaling, 'label'); + if (clusterNodeProperties.label === undefined) { + clusterNodeProperties.label = 'cluster'; } - } - }]); - - return Node; - })(); - - exports['default'] = Node; - module.exports = exports['default']; - -/***/ }, -/* 75 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _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; } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + // give the clusterNode a postion if it does not have one. + var pos = undefined; + if (clusterNodeProperties.x === undefined) { + pos = this._getClusterPosition(childNodesObj); + clusterNodeProperties.x = pos.x; + } + if (clusterNodeProperties.y === undefined) { + if (pos === undefined) { + pos = this._getClusterPosition(childNodesObj); + } + clusterNodeProperties.y = pos.y; + } - var util = __webpack_require__(2); + // force the ID to remain the same + clusterNodeProperties.id = clusterId; - var Label = (function () { - function Label(body, options) { - _classCallCheck(this, Label); + // create the clusterNode + var clusterNode = this.body.functions.createNode(clusterNodeProperties, _componentsNodesCluster2['default']); + clusterNode.isCluster = true; + clusterNode.containedNodes = childNodesObj; + clusterNode.containedEdges = childEdgesObj; + // cache a copy from the cluster edge properties if we have to reconnect others later on + clusterNode.clusterEdgeProperties = options.clusterEdgeProperties; - this.body = body; + // finally put the cluster node into global + this.body.nodes[clusterNodeProperties.id] = clusterNode; - this.baseSize = undefined; - this.setOptions(options); - this.size = { top: 0, left: 0, width: 0, height: 0, yLine: 0 }; // could be cached - } + // create the new edges that will connect to the cluster + var newEdges = []; + this._createClusterEdges(childNodesObj, childEdgesObj, newEdges, clusterNodeProperties, options.clusterEdgeProperties); - _createClass(Label, [{ - key: 'setOptions', - value: function setOptions(options) { - var allowDeletion = arguments[1] === undefined ? false : arguments[1]; + // disable the childEdges + for (var edgeId in childEdgesObj) { + if (childEdgesObj.hasOwnProperty(edgeId)) { + if (this.body.edges[edgeId] !== undefined) { + var edge = this.body.edges[edgeId]; + edge.togglePhysics(false); + edge.options.hidden = true; + } + } + } - this.options = options; + // disable the childNodes + for (var nodeId in childNodesObj) { + if (childNodesObj.hasOwnProperty(nodeId)) { + this.clusteredNodes[nodeId] = { clusterId: clusterNodeProperties.id, node: this.body.nodes[nodeId] }; + this.body.nodes[nodeId].togglePhysics(false); + this.body.nodes[nodeId].options.hidden = true; + } + } - if (options.label !== undefined) { - this.labelDirty = true; + // push new edges to global + for (var i = 0; i < newEdges.length; i++) { + this.body.edges[newEdges[i].id] = newEdges[i]; + this.body.edges[newEdges[i].id].connect(); } - if (options.font !== undefined) { - Label.parseOptions(this.options.font, options, allowDeletion); - if (typeof options.font === 'string') { - this.baseSize = this.options.font.size; - } else if (typeof options.font === 'object') { - if (options.font.size !== undefined) { - this.baseSize = options.font.size; - } - } + // set ID to undefined so no duplicates arise + clusterNodeProperties.id = undefined; + + // wrap up + if (refreshData === true) { + this.body.emitter.emit('_dataChanged'); } } }, { - key: 'draw', + key: 'isCluster', /** - * Main function. This is called from anything that wants to draw a label. - * @param ctx - * @param x - * @param y - * @param selected - * @param baseline - */ - value: function draw(ctx, x, y, selected) { - var baseline = arguments[4] === undefined ? 'middle' : arguments[4]; - - // if no label, return - if (this.options.label === undefined) return; - - // check if we have to render the label - var viewFontSize = this.options.font.size * this.body.view.scale; - if (this.options.label && viewFontSize < this.options.scaling.label.drawThreshold - 1) return; - - // update the size cache if required - this.calculateLabelSize(ctx, selected, x, y, baseline); - - // create the fontfill background - this._drawBackground(ctx); - // draw text - this._drawText(ctx, selected, x, y, baseline); + * Check if a node is a cluster. + * @param nodeId + * @returns {*} + */ + value: function isCluster(nodeId) { + if (this.body.nodes[nodeId] !== undefined) { + return this.body.nodes[nodeId].isCluster === true; + } else { + console.log('Node does not exist.'); + return false; + } } }, { - key: '_drawBackground', + key: '_getClusterPosition', /** - * Draws the label background - * @param {CanvasRenderingContext2D} ctx - * @private - */ - value: function _drawBackground(ctx) { - if (this.options.font.background !== undefined && this.options.font.background !== 'none') { - ctx.fillStyle = this.options.font.background; - - var lineMargin = 2; - - switch (this.options.font.align) { - case 'middle': - ctx.fillRect(-this.size.width * 0.5, -this.size.height * 0.5, this.size.width, this.size.height); - break; - case 'top': - ctx.fillRect(-this.size.width * 0.5, -(this.size.height + lineMargin), this.size.width, this.size.height); - break; - case 'bottom': - ctx.fillRect(-this.size.width * 0.5, lineMargin, this.size.width, this.size.height); - break; - default: - ctx.fillRect(this.size.left, this.size.top - 0.5 * lineMargin, this.size.width, this.size.height); - break; - } + * get the position of the cluster node based on what's inside + * @param {object} childNodesObj | object with node objects, id as keys + * @returns {{x: number, y: number}} + * @private + */ + value: function _getClusterPosition(childNodesObj) { + var childKeys = Object.keys(childNodesObj); + var minX = childNodesObj[childKeys[0]].x; + var maxX = childNodesObj[childKeys[0]].x; + var minY = childNodesObj[childKeys[0]].y; + var maxY = childNodesObj[childKeys[0]].y; + var node = undefined; + for (var i = 1; i < childKeys.length; i++) { + node = childNodesObj[childKeys[i]]; + minX = node.x < minX ? node.x : minX; + maxX = node.x > maxX ? node.x : maxX; + minY = node.y < minY ? node.y : minY; + maxY = node.y > maxY ? node.y : maxY; } + + return { x: 0.5 * (minX + maxX), y: 0.5 * (minY + maxY) }; } }, { - key: '_drawText', + key: 'openCluster', /** - * - * @param ctx - * @param x - * @param baseline - * @private - */ - value: function _drawText(ctx, selected, x, y) { - var baseline = arguments[4] === undefined ? 'middle' : arguments[4]; + * Open a cluster by calling this function. + * @param {String} clusterNodeId | the ID of the cluster node + * @param {Boolean} refreshData | wrap up afterwards if not true + */ + value: function openCluster(clusterNodeId) { + var refreshData = arguments[1] === undefined ? true : arguments[1]; - var fontSize = this.options.font.size; - var viewFontSize = fontSize * this.body.view.scale; - // this ensures that there will not be HUGE letters on screen by setting an upper limit on the visible text size (regardless of zoomLevel) - if (viewFontSize >= this.options.scaling.label.maxVisible) { - fontSize = Number(this.options.scaling.label.maxVisible) / this.body.view.scale; + // kill conditions + if (clusterNodeId === undefined) { + throw new Error('No clusterNodeId supplied to openCluster.'); + } + if (this.body.nodes[clusterNodeId] === undefined) { + throw new Error('The clusterNodeId supplied to openCluster does not exist.'); + } + if (this.body.nodes[clusterNodeId].containedNodes === undefined) { + console.log('The node:' + clusterNodeId + ' is not a cluster.'); + return; } + var clusterNode = this.body.nodes[clusterNodeId]; + var containedNodes = clusterNode.containedNodes; + var containedEdges = clusterNode.containedEdges; - var yLine = this.size.yLine; + // release nodes + for (var nodeId in containedNodes) { + if (containedNodes.hasOwnProperty(nodeId)) { + var containedNode = this.body.nodes[nodeId]; + containedNode = containedNodes[nodeId]; + // inherit position + containedNode.x = clusterNode.x; + containedNode.y = clusterNode.y; - var _getColor = this._getColor(viewFontSize); + // inherit speed + containedNode.vx = clusterNode.vx; + containedNode.vy = clusterNode.vy; - var _getColor2 = _slicedToArray(_getColor, 2); + containedNode.options.hidden = false; + containedNode.togglePhysics(true); - var fontColor = _getColor2[0]; - var strokeColor = _getColor2[1]; + delete this.clusteredNodes[nodeId]; + } + } - var _setAlignment = this._setAlignment(ctx, x, yLine, baseline); + // release edges + for (var edgeId in containedEdges) { + if (containedEdges.hasOwnProperty(edgeId)) { + var edge = containedEdges[edgeId]; + // if this edge was a temporary edge and it's connected nodes do not exist anymore, we remove it from the data + if (this.body.nodes[edge.fromId] === undefined || this.body.nodes[edge.toId] === undefined) { + edge.edgeType.cleanup(); + // this removes the edge from node.edges, which is why edgeIds is formed + edge.disconnect(); + delete this.body.edges[edgeId]; + } else { + // one of the nodes connected to this edge is in a cluster. We give the edge to that cluster so it will be released when that cluster is opened. + if (this.clusteredNodes[edge.fromId] !== undefined || this.clusteredNodes[edge.toId] !== undefined) { + var fromId = undefined, + toId = undefined; + var clusteredNode = this.clusteredNodes[edge.fromId] || this.clusteredNodes[edge.toId]; + var clusterId = clusteredNode.clusterId; + var _clusterNode = this.body.nodes[clusterId]; + _clusterNode.containedEdges[edgeId] = edge; - var _setAlignment2 = _slicedToArray(_setAlignment, 2); + if (this.clusteredNodes[edge.fromId] !== undefined) { + fromId = clusterId; + toId = edge.toId; + } else { + fromId = edge.fromId; + toId = clusterId; + } - x = _setAlignment2[0]; - yLine = _setAlignment2[1]; + // if both from and to nodes are visible, we create a new temporary edge + if (this.body.nodes[fromId].options.hidden !== true && this.body.nodes[toId].options.hidden !== true) { + var clonedOptions = this._cloneOptions(edge, 'edge'); + var id = 'clusterEdge:' + util.randomUUID(); + util.deepExtend(clonedOptions, _clusterNode.clusterEdgeProperties); + util.deepExtend(clonedOptions, { from: fromId, to: toId, hidden: false, physics: true, id: id }); + var newEdge = this.body.functions.createEdge(clonedOptions); - // configure context for drawing the text - ctx.font = (selected ? 'bold ' : '') + fontSize + 'px ' + this.options.font.face; - ctx.fillStyle = fontColor; - ctx.textAlign = 'center'; + this.body.edges[id] = newEdge; + this.body.edges[id].connect(); + } + } else { + edge.options.hidden = false; + edge.togglePhysics(true); + } + } + } + } - // set the strokeWidth - if (this.options.font.strokeWidth > 0) { - ctx.lineWidth = this.options.font.strokeWidth; - ctx.strokeStyle = strokeColor; - ctx.lineJoin = 'round'; + // remove all temporary edges + for (var i = 0; i < clusterNode.edges.length; i++) { + var edgeId = clusterNode.edges[i].id; + this.body.edges[edgeId].edgeType.cleanup(); + // this removes the edge from node.edges, which is why edgeIds is formed + this.body.edges[edgeId].disconnect(); + delete this.body.edges[edgeId]; } - // draw the text - for (var i = 0; i < this.lineCount; i++) { - if (this.options.font.strokeWidth > 0) { - ctx.strokeText(this.lines[i], x, yLine); - } - ctx.fillText(this.lines[i], x, yLine); - yLine += fontSize; + // remove clusterNode + delete this.body.nodes[clusterNodeId]; + + if (refreshData === true) { + this.body.emitter.emit('_dataChanged'); } } }, { - key: '_setAlignment', - value: function _setAlignment(ctx, x, yLine, baseline) { - // check for label alignment (for edges) - // TODO: make alignment for nodes - if (this.options.font.align !== 'horizontal') { - x = 0; - yLine = 0; - - var lineMargin = 2; - if (this.options.font.align === 'top') { - ctx.textBaseline = 'alphabetic'; - yLine -= 2 * lineMargin; // distance from edge, required because we use alphabetic. Alphabetic has less difference between browsers - } else if (this.options.font.align === 'bottom') { - ctx.textBaseline = 'hanging'; - yLine += 2 * lineMargin; // distance from edge, required because we use hanging. Hanging has less difference between browsers - } else { - ctx.textBaseline = 'middle'; + key: 'getNodesInCluster', + value: function getNodesInCluster(clusterId) { + var nodesArray = []; + if (this.isCluster(clusterId) === true) { + var containedNodes = this.body.nodes[clusterId].containedNodes; + for (var nodeId in containedNodes) { + if (containedNodes.hasOwnProperty(nodeId)) { + nodesArray.push(nodeId); + } } - } else { - ctx.textBaseline = baseline; } - return [x, yLine]; - } - }, { - key: '_getColor', - - /** - * fade in when relative scale is between threshold and threshold - 1. - * If the relative scale would be smaller than threshold -1 the draw function would have returned before coming here. - * - * @param viewFontSize - * @returns {*[]} - * @private - */ - value: function _getColor(viewFontSize) { - var fontColor = this.options.font.color || '#000000'; - var strokeColor = this.options.font.strokeColor || '#ffffff'; - if (viewFontSize <= this.options.scaling.label.drawThreshold) { - var opacity = Math.max(0, Math.min(1, 1 - (this.options.scaling.label.drawThreshold - viewFontSize))); - fontColor = util.overrideOpacity(fontColor, opacity); - strokeColor = util.overrideOpacity(strokeColor, opacity); - } - return [fontColor, strokeColor]; + return nodesArray; } }, { - key: 'getTextSize', + key: 'findNode', /** - * - * @param ctx - * @param selected - * @returns {{width: number, height: number}} - */ - value: function getTextSize(ctx) { - var selected = arguments[1] === undefined ? false : arguments[1]; + * Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node + * @param nodeId + * @returns {Array} + * @private + */ + value: function findNode(nodeId) { + var stack = []; + var max = 100; + var counter = 0; - var size = { - width: this._processLabel(ctx, selected), - height: this.options.font.size * this.lineCount, - lineCount: this.lineCount - }; - return size; + while (this.clusteredNodes[nodeId] !== undefined && counter < max) { + stack.push(this.clusteredNodes[nodeId].node); + nodeId = this.clusteredNodes[nodeId].clusterId; + counter++; + } + stack.push(this.body.nodes[nodeId]); + return stack; } }, { - key: 'calculateLabelSize', + key: '_getConnectedId', /** - * - * @param ctx - * @param selected - * @param x - * @param y - * @param baseline - */ - value: function calculateLabelSize(ctx, selected) { - var x = arguments[2] === undefined ? 0 : arguments[2]; - var y = arguments[3] === undefined ? 0 : arguments[3]; - var baseline = arguments[4] === undefined ? 'middle' : arguments[4]; - - if (this.labelDirty === true) { - this.size.width = this._processLabel(ctx, selected); - } - this.size.height = this.options.font.size * this.lineCount; - this.size.left = x - this.size.width * 0.5; - this.size.top = y - this.size.height * 0.5; - this.size.yLine = y + (1 - this.lineCount) * 0.5 * this.options.font.size; - if (baseline === 'hanging') { - this.size.top += 0.5 * this.options.font.size; - this.size.top += 4; // distance from node, required because we use hanging. Hanging has less difference between browsers - this.size.yLine += 4; // distance from node + * Get the Id the node is connected to + * @param edge + * @param nodeId + * @returns {*} + * @private + */ + value: function _getConnectedId(edge, nodeId) { + if (edge.toId != nodeId) { + return edge.toId; + } else if (edge.fromId != nodeId) { + return edge.fromId; + } else { + return edge.fromId; } - - this.labelDirty = false; } }, { - key: '_processLabel', + key: '_getHubSize', /** - * This calculates the width as well as explodes the label string and calculates the amount of lines. - * @param ctx - * @param selected - * @returns {number} - * @private - */ - value: function _processLabel(ctx, selected) { - var width = 0; - var lines = ['']; - var lineCount = 0; - if (this.options.label !== undefined) { - lines = String(this.options.label).split('\n'); - lineCount = lines.length; - ctx.font = (selected ? 'bold ' : '') + this.options.font.size + 'px ' + this.options.font.face; - width = ctx.measureText(lines[0]).width; - for (var i = 1; i < lineCount; i++) { - var lineWidth = ctx.measureText(lines[i]).width; - width = lineWidth > width ? lineWidth : width; + * We determine how many connections denote an important hub. + * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%) + * + * @private + */ + value: function _getHubSize() { + var average = 0; + var averageSquared = 0; + var hubCounter = 0; + var largestHub = 0; + + for (var i = 0; i < this.body.nodeIndices.length; i++) { + var node = this.body.nodes[this.body.nodeIndices[i]]; + if (node.edges.length > largestHub) { + largestHub = node.edges.length; } + average += node.edges.length; + averageSquared += Math.pow(node.edges.length, 2); + hubCounter += 1; } - this.lines = lines; - this.lineCount = lineCount; + average = average / hubCounter; + averageSquared = averageSquared / hubCounter; - return width; - } - }], [{ - key: 'parseOptions', - value: function parseOptions(parentOptions, newOptions) { - var allowDeletion = arguments[2] === undefined ? false : arguments[2]; + var letiance = averageSquared - Math.pow(average, 2); + var standardDeviation = Math.sqrt(letiance); - if (typeof newOptions.font === 'string') { - var newOptionsArray = newOptions.font.split(' '); - parentOptions.size = newOptionsArray[0].replace('px', ''); - parentOptions.face = newOptionsArray[1]; - parentOptions.color = newOptionsArray[2]; - } else if (typeof newOptions.font === 'object') { - util.fillIfDefined(parentOptions, newOptions.font, allowDeletion); + var hubThreshold = Math.floor(average + 2 * standardDeviation); + + // always have at least one to cluster + if (hubThreshold > largestHub) { + hubThreshold = largestHub; } - parentOptions.size = Number(parentOptions.size); + + return hubThreshold; } }]); - return Label; + return ClusterEngine; })(); - exports['default'] = Label; + exports['default'] = ClusterEngine; module.exports = exports['default']; /***/ }, -/* 76 */ +/* 98 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -35782,1053 +34216,791 @@ return /******/ (function(modules) { // webpackBootstrap value: true }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var _sharedLabel = __webpack_require__(75); - - var _sharedLabel2 = _interopRequireDefault(_sharedLabel); - - var _edgesBezierEdgeDynamic = __webpack_require__(106); - - var _edgesBezierEdgeDynamic2 = _interopRequireDefault(_edgesBezierEdgeDynamic); - - var _edgesBezierEdgeStatic = __webpack_require__(107); - - var _edgesBezierEdgeStatic2 = _interopRequireDefault(_edgesBezierEdgeStatic); - - var _edgesStraightEdge = __webpack_require__(108); + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - var _edgesStraightEdge2 = _interopRequireDefault(_edgesStraightEdge); + var _Node2 = __webpack_require__(62); - var util = __webpack_require__(2); + var _Node3 = _interopRequireDefault(_Node2); /** - * @class Edge * - * A edge connects two nodes - * @param {Object} properties Object with options. Must contain - * At least options from and to. - * Available options: from (number), - * to (number), label (string, color (string), - * width (number), style (string), - * length (number), title (string) - * @param {Network} network A Network object, used to find and edge to - * nodes. - * @param {Object} constants An object with default values for - * example for the color */ - var Edge = (function () { - function Edge(options, body, globalOptions) { - _classCallCheck(this, Edge); - - if (body === undefined) { - throw 'No body provided'; - } - this.options = util.bridgeObject(globalOptions); - this.body = body; - - // initialize variables - this.id = undefined; - this.fromId = undefined; - this.toId = undefined; - this.selected = false; - this.hover = false; - this.labelDirty = true; - this.colorDirty = 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; + var Cluster = (function (_Node) { + function Cluster(options, body, imagelist, grouplist, globalOptions) { + _classCallCheck(this, Cluster); - this.labelModule = new _sharedLabel2['default'](this.body, this.options); + _get(Object.getPrototypeOf(Cluster.prototype), 'constructor', this).call(this, options, body, imagelist, grouplist, globalOptions); - this.setOptions(options); + this.isCluster = true; + this.containedNodes = {}; + this.containedEdges = {}; } - _createClass(Edge, [{ - key: 'setOptions', - - /** - * Set or overwrite options for the edge - * @param {Object} options an object with options - * @param doNotEmit - */ - value: function setOptions(options) { - if (!options) { - return; - } - this.colorDirty = true; - - Edge.parseOptions(this.options, options, true); - - 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 = parseInt(options.value); - } - - // update label Module - this.updateLabelModule(); - - 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; - } - }, { - key: 'updateLabelModule', - - /** - * update the options in the label module - */ - value: function updateLabelModule() { - this.labelModule.setOptions(this.options, true); - if (this.labelModule.baseSize !== undefined) { - this.baseFontSize = this.labelModule.baseSize; - } - } - }, { - key: 'updateEdgeType', - - /** - * update the edge type, set the options - * @returns {boolean} - */ - value: function updateEdgeType() { - var dataChanged = false; - var changeInType = true; - if (this.edgeType !== undefined) { - if (this.edgeType instanceof _edgesBezierEdgeDynamic2['default'] && this.options.smooth.enabled === true && this.options.smooth.type === 'dynamic') { - changeInType = false; - } - if (this.edgeType instanceof _edgesBezierEdgeStatic2['default'] && this.options.smooth.enabled === true && this.options.smooth.type !== 'dynamic') { - changeInType = false; - } - if (this.edgeType instanceof _edgesStraightEdge2['default'] && this.options.smooth.enabled === false) { - changeInType = false; - } - - if (changeInType === true) { - dataChanged = this.edgeType.cleanup(); - } - } - - if (changeInType === true) { - if (this.options.smooth.enabled === true) { - if (this.options.smooth.type === 'dynamic') { - dataChanged = true; - this.edgeType = new _edgesBezierEdgeDynamic2['default'](this.options, this.body, this.labelModule); - } else { - this.edgeType = new _edgesBezierEdgeStatic2['default'](this.options, this.body, this.labelModule); - } - } else { - this.edgeType = new _edgesStraightEdge2['default'](this.options, this.body, this.labelModule); - } - } else { - // if nothing changes, we just set the options. - this.edgeType.setOptions(this.options); - } - - return dataChanged; - } - }, { - key: 'togglePhysics', + _inherits(Cluster, _Node); - /** - * Enable or disable the physics. - * @param status - */ - value: function togglePhysics(status) { - this.options.physics = status; - this.edgeType.togglePhysics(status); - } - }, { - key: 'connect', + return Cluster; + })(_Node3['default']); - /** - * Connect an edge to its nodes - */ - value: function connect() { - this.disconnect(); + exports['default'] = Cluster; + module.exports = exports['default']; - this.from = this.body.nodes[this.fromId] || undefined; - this.to = this.body.nodes[this.toId] || undefined; - this.connected = this.from !== undefined && this.to !== undefined; +/***/ }, +/* 99 */ +/***/ function(module, exports, __webpack_require__) { - 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); - } - } + 'use strict'; - this.edgeType.connect(); - } - }, { - key: 'disconnect', + Object.defineProperty(exports, '__esModule', { + value: true + }); - /** - * Disconnect an edge from its nodes - */ - value: function disconnect() { - if (this.from) { - this.from.detachEdge(this); - this.from = undefined; - } - if (this.to) { - this.to.detachEdge(this); - this.to = undefined; - } + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - this.connected = false; - } - }, { - key: 'getTitle', + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - /** - * get the title of this edge. - * @return {string} title The title of the edge, or undefined when no title - * has been set. - */ - value: function getTitle() { - return this.title; - } - }, { - key: 'isSelected', + if (typeof window !== 'undefined') { + window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; + } - /** - * check if this node is selecte - * @return {boolean} selected True if node is selected, else false - */ - value: function isSelected() { - return this.selected; - } - }, { - key: 'getValue', + var util = __webpack_require__(7); - /** - * Retrieve the value of the edge. Can be undefined - * @return {Number} value - */ - value: function getValue() { - return this.options.value; - } - }, { - key: 'setValueRange', + var CanvasRenderer = (function () { + function CanvasRenderer(body, canvas) { + _classCallCheck(this, CanvasRenderer); - /** - * 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 total - */ - 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.body = body; + this.canvas = canvas; - this._setInteractionWidths(); - } - }, { - 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; - } + this.redrawRequested = false; + this.renderTimer = undefined; + this.requiresTimeout = true; + this.renderingActive = false; + this.renderRequests = 0; + this.pixelRatio = undefined; + this.allowRedrawRequests = true; - 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; - } - } - }, { - key: 'draw', + this.dragging = false; + this.options = {}; + this.defaultOptions = { + hideEdgesOnDrag: false, + hideNodesOnDrag: false + }; + util.extend(this.options, this.defaultOptions); - /** - * 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 - */ - value: function draw(ctx) { - var via = this.edgeType.drawLine(ctx, this.selected, this.hover); - this.drawArrows(ctx, via); - this.drawLabel(ctx, via); + this._determineBrowserMethod(); + this.bindEventListeners(); + } + + _createClass(CanvasRenderer, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this = this; + + this.body.emitter.on('dragStart', function () { + _this.dragging = true; + }); + this.body.emitter.on('dragEnd', function () { + return _this.dragging = false; + }); + this.body.emitter.on('_resizeNodes', function () { + return _this._resizeNodes(); + }); + this.body.emitter.on('_redraw', function () { + if (_this.renderingActive === false) { + _this._redraw(); + } + }); + this.body.emitter.on('_blockRedrawRequests', function () { + _this.allowRedrawRequests = false; + }); + this.body.emitter.on('_allowRedrawRequests', function () { + _this.allowRedrawRequests = true; + }); + this.body.emitter.on('_requestRedraw', this._requestRedraw.bind(this)); + this.body.emitter.on('_startRendering', function () { + _this.renderRequests += 1; + _this.renderingActive = true; + _this._startRendering(); + }); + this.body.emitter.on('_stopRendering', function () { + _this.renderRequests -= 1; + _this.renderingActive = _this.renderRequests > 0; + _this.renderTimer = undefined; + }); + this.body.emitter.on('destroy', function () { + _this.renderRequests = 0; + _this.renderingActive = false; + if (_this.requiresTimeout === true) { + clearTimeout(_this.renderTimer); + } else { + cancelAnimationFrame(_this.renderTimer); + } + _this.body.emitter.off(); + }); } }, { - key: 'drawArrows', - value: function drawArrows(ctx, viaNode) { - if (this.options.arrows.from.enabled === true) { - this.edgeType.drawArrowHead(ctx, 'from', viaNode, this.selected, this.hover); - } - if (this.options.arrows.middle.enabled === true) { - this.edgeType.drawArrowHead(ctx, 'middle', viaNode, this.selected, this.hover); - } - if (this.options.arrows.to.enabled === true) { - this.edgeType.drawArrowHead(ctx, 'to', viaNode, this.selected, this.hover); + key: 'setOptions', + value: function setOptions(options) { + if (options !== undefined) { + var fields = ['hideEdgesOnDrag', 'hideNodesOnDrag']; + util.selectiveDeepExtend(fields, this.options, options); } } }, { - key: 'drawLabel', - value: function drawLabel(ctx, viaNode) { - if (this.options.label !== undefined) { - // set style - var node1 = this.from; - var node2 = this.to; - var selected = this.from.selected || this.to.selected || this.selected; - if (node1.id != node2.id) { - var point = this.edgeType.getPoint(0.5, viaNode); - ctx.save(); - - // if the label has to be rotated: - if (this.options.font.align !== 'horizontal') { - this.labelModule.calculateLabelSize(ctx, selected, point.x, point.y); - ctx.translate(point.x, this.labelModule.size.yLine); - this._rotateForLabelAlignment(ctx); - } - - // draw the label - this.labelModule.draw(ctx, point.x, point.y, selected); - ctx.restore(); - } else { - 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; + key: '_startRendering', + value: function _startRendering() { + if (this.renderingActive === true) { + if (this.renderTimer === undefined) { + if (this.requiresTimeout === true) { + this.renderTimer = window.setTimeout(this._renderStep.bind(this), this.simulationInterval); // wait this.renderTimeStep milliseconds and perform the animation step function } else { - x = node1.x + radius; - y = node1.y - node1.shape.height * 0.5; + this.renderTimer = window.requestAnimationFrame(this._renderStep.bind(this)); // wait this.renderTimeStep milliseconds and perform the animation step function } - point = this._pointOnCircle(x, y, radius, 0.125); - this.labelModule.draw(ctx, point.x, point.y, selected); } } } }, { - key: 'isOverlappingWith', + key: '_renderStep', + value: function _renderStep() { + if (this.renderingActive === true) { + // reset the renderTimer so a new scheduled animation step can be set + this.renderTimer = undefined; - /** - * 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 - */ - 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; + if (this.requiresTimeout === true) { + // this schedules a new simulation step + this._startRendering(); + } - var dist = this.edgeType.getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj); + this._redraw(); - return dist < distMax; - } else { - return false; + if (this.requiresTimeout === false) { + // this schedules a new simulation step + this._startRendering(); + } } } }, { - key: '_rotateForLabelAlignment', + key: 'redraw', /** - * Rotates the canvas so the text is most readable - * @param {CanvasRenderingContext2D} ctx - * @private + * Redraw the network with the current data + * chart will be resized too. */ - value: function _rotateForLabelAlignment(ctx) { - var dy = this.from.y - this.to.y; - var dx = this.from.x - this.to.x; - var angleInDegrees = Math.atan2(dy, dx); - - // rotate so label it is readable - if (angleInDegrees < -1 && dx < 0 || angleInDegrees > 0 && dx < 0) { - angleInDegrees = angleInDegrees + Math.PI; - } - - ctx.rotate(angleInDegrees); + value: function redraw() { + this.body.emitter.emit('setSize'); + this._redraw(); } }, { - key: '_pointOnCircle', + key: '_requestRedraw', /** - * 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 + * Redraw the network with the current data + * @param hidden | used to get the first estimate of the node sizes. only the nodes are drawn after which they are quickly drawn over. * @private */ - 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) - }; - } - }, { - key: 'select', - value: function select() { - this.selected = true; + value: function _requestRedraw() { + if (this.redrawRequested !== true && this.renderingActive === false && this.allowRedrawRequests === true) { + this.redrawRequested = true; + if (this.requiresTimeout === true) { + window.setTimeout(this._redraw.bind(this, false), 0); + } else { + window.requestAnimationFrame(this._redraw.bind(this, false)); + } + } } }, { - key: 'unselect', - value: function unselect() { - this.selected = false; - } - }], [{ - key: 'parseOptions', - value: function parseOptions(parentOptions, newOptions) { - var allowDeletion = arguments[2] === undefined ? false : arguments[2]; - - var fields = ['id', 'from', 'hidden', 'hoverWidth', 'label', 'length', 'line', 'opacity', 'physics', 'selectionWidth', 'selfReferenceSize', 'to', 'title', 'value', 'width']; + key: '_redraw', + value: function _redraw() { + var hidden = arguments[0] === undefined ? false : arguments[0]; - // only deep extend the items in the field array. These do not have shorthand. - util.selectiveDeepExtend(fields, parentOptions, newOptions, allowDeletion); + this.body.emitter.emit('initRedraw'); - util.mergeOptions(parentOptions, newOptions, 'smooth'); - util.mergeOptions(parentOptions, newOptions, 'shadow'); + this.redrawRequested = false; + var ctx = this.canvas.frame.canvas.getContext('2d'); - if (newOptions.dashes !== undefined && newOptions.dashes !== null) { - parentOptions.dashes = newOptions.dashes; - } else if (allowDeletion === true && newOptions.dashes === null) { - parentOptions.dashes = undefined; - delete parentOptions.dashes; + // when the container div was hidden, this fixes it back up! + if (this.canvas.frame.canvas.width === 0 || this.canvas.frame.canvas.height === 0) { + this.canvas.setSize(); } - // 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'); - } else if (allowDeletion === true && newOptions.scaling === null) { - parentOptions.scaling = undefined; - delete parentOptions.scaling; + if (this.pixelRatio === undefined) { + this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); } - // hanlde multiple input cases for arrows - if (newOptions.arrows !== undefined && newOptions.arrows !== null) { - if (typeof newOptions.arrows === 'string') { - var arrows = newOptions.arrows.toLowerCase(); - if (arrows.indexOf('to') != -1) { - parentOptions.arrows.to.enabled = true; - } - if (arrows.indexOf('middle') != -1) { - parentOptions.arrows.middle.enabled = true; - } - if (arrows.indexOf('from') != -1) { - parentOptions.arrows.from.enabled = true; - } - } else if (typeof newOptions.arrows === 'object') { - util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'to'); - util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'middle'); - util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'from'); - } else { - throw new Error('The arrow newOptions can only be an object or a string. Refer to the documentation. You used:' + JSON.stringify(newOptions.arrows)); - } - } else if (allowDeletion === true && newOptions.arrows === null) { - parentOptions.arrows = undefined; - delete parentOptions.arrows; - } + ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); - // hanlde multiple input cases for color - if (newOptions.color !== undefined && newOptions.color !== null) { - if (util.isString(newOptions.color)) { - parentOptions.color.color = newOptions.color; - parentOptions.color.highlight = newOptions.color; - parentOptions.color.hover = newOptions.color; - parentOptions.color.inherit = false; - } else { - var colorsDefined = false; - if (newOptions.color.color !== undefined) { - parentOptions.color.color = newOptions.color.color;colorsDefined = true; - } - if (newOptions.color.highlight !== undefined) { - parentOptions.color.highlight = newOptions.color.highlight;colorsDefined = true; - } - if (newOptions.color.hover !== undefined) { - parentOptions.color.hover = newOptions.color.hover;colorsDefined = true; - } - if (newOptions.color.inherit !== undefined) { - parentOptions.color.inherit = newOptions.color.inherit; - } - if (newOptions.color.opacity !== undefined) { - parentOptions.color.opacity = Math.min(1, Math.max(0, newOptions.color.opacity)); - } + // clear the canvas + var w = this.canvas.frame.canvas.clientWidth; + var h = this.canvas.frame.canvas.clientHeight; + ctx.clearRect(0, 0, w, h); - if (newOptions.color.inherit === undefined && colorsDefined === true) { - parentOptions.color.inherit = false; - } + // set scaling and translation + ctx.save(); + ctx.translate(this.body.view.translation.x, this.body.view.translation.y); + ctx.scale(this.body.view.scale, this.body.view.scale); + + ctx.beginPath(); + this.body.emitter.emit('beforeDrawing', ctx); + ctx.closePath(); + + if (hidden === false) { + if (this.dragging === false || this.dragging === true && this.options.hideEdgesOnDrag === false) { + this._drawEdges(ctx); } - } else if (allowDeletion === true && newOptions.color === null) { - parentOptions.color = undefined; - delete parentOptions.color; } - // handle the font settings - if (newOptions.font !== undefined) { - _sharedLabel2['default'].parseOptions(parentOptions.font, newOptions); + if (this.dragging === false || this.dragging === true && this.options.hideNodesOnDrag === false) { + this._drawNodes(ctx, hidden); } - } - }]); - - return Edge; - })(); - - exports['default'] = Edge; - module.exports = exports['default']; - -/***/ }, -/* 77 */ -/***/ function(module, exports, __webpack_require__) { - "use strict"; + if (this.controlNodesActive === true) { + this._drawControlNodes(ctx); + } - Object.defineProperty(exports, "__esModule", { - value: true - }); + ctx.beginPath(); + //this.physics.nodesSolver._debug(ctx,"#F00F0F"); + this.body.emitter.emit('afterDrawing', ctx); + ctx.closePath(); + // restore original scaling and translation + ctx.restore(); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + if (hidden === true) { + ctx.clearRect(0, 0, w, h); + } + } + }, { + key: '_resizeNodes', - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** + * Redraw all nodes + * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); + * @param {CanvasRenderingContext2D} ctx + * @param {Boolean} [alwaysShow] + * @private + */ + value: function _resizeNodes() { + var ctx = this.canvas.frame.canvas.getContext('2d'); + if (this.pixelRatio === undefined) { + this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + } + ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); + ctx.save(); + ctx.translate(this.body.view.translation.x, this.body.view.translation.y); + ctx.scale(this.body.view.scale, this.body.view.scale); - var BarnesHutSolver = (function () { - function BarnesHutSolver(body, physicsBody, options) { - _classCallCheck(this, BarnesHutSolver); + var nodes = this.body.nodes; + var node = undefined; - this.body = body; - this.physicsBody = physicsBody; - this.barnesHutTree; - this.setOptions(options); - } + // resize all nodes + for (var nodeId in nodes) { + if (nodes.hasOwnProperty(nodeId)) { + node = nodes[nodeId]; + node.resize(ctx); + node.updateBoundingBox(ctx); + } + } - _createClass(BarnesHutSolver, [{ - key: "setOptions", - value: function setOptions(options) { - this.options = options; - this.thetaInversed = 1 / this.options.theta; - this.overlapAvoidanceFactor = 1 - Math.max(0, Math.min(1, this.options.avoidOverlap)); // if 1 then min distance = 0.5, if 0.5 then min distance = 0.5 + 0.5*node.shape.radius + // restore original scaling and translation + ctx.restore(); } }, { - key: "solve", + key: '_drawNodes', /** - * This function calculates the forces the nodes apply on eachother based on a gravitational model. - * The Barnes Hut method is used to speed up this N-body simulation. - * + * Redraw all nodes + * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); + * @param {CanvasRenderingContext2D} ctx + * @param {Boolean} [alwaysShow] * @private */ - value: function solve() { - if (this.options.gravitationalConstant !== 0 && this.physicsBody.physicsNodeIndices.length > 0) { - var node = undefined; - var nodes = this.body.nodes; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var nodeCount = nodeIndices.length; - - // create the tree - var barnesHutTree = this._formBarnesHutTree(nodes, nodeIndices); + value: function _drawNodes(ctx) { + var alwaysShow = arguments[1] === undefined ? false : arguments[1]; - // for debugging - this.barnesHutTree = barnesHutTree; + var nodes = this.body.nodes; + var nodeIndices = this.body.nodeIndices; + var node = undefined; + var selected = []; + var margin = 20; + var topLeft = this.canvas.DOMtoCanvas({ x: -margin, y: -margin }); + var bottomRight = this.canvas.DOMtoCanvas({ + x: this.canvas.frame.canvas.clientWidth + margin, + y: this.canvas.frame.canvas.clientHeight + margin + }); + var viewableArea = { top: topLeft.y, left: topLeft.x, bottom: bottomRight.y, right: bottomRight.x }; - // place the nodes one by one recursively - for (var i = 0; i < nodeCount; i++) { - node = nodes[nodeIndices[i]]; - if (node.options.mass > 0) { - // starting with root is irrelevant, it never passes the BarnesHutSolver condition - this._getForceContribution(barnesHutTree.root.children.NW, node); - this._getForceContribution(barnesHutTree.root.children.NE, node); - this._getForceContribution(barnesHutTree.root.children.SW, node); - this._getForceContribution(barnesHutTree.root.children.SE, node); + // draw unselected nodes; + for (var i = 0; i < nodeIndices.length; i++) { + node = nodes[nodeIndices[i]]; + // set selected nodes aside + if (node.isSelected()) { + selected.push(nodeIndices[i]); + } else { + if (alwaysShow === true) { + node.draw(ctx); + } else if (node.isBoundingBoxOverlappingWith(viewableArea) === true) { + node.draw(ctx); + } else { + node.updateBoundingBox(ctx); } } } + + // draw the selected nodes on top + for (var i = 0; i < selected.length; i++) { + node = nodes[selected[i]]; + node.draw(ctx); + } } }, { - key: "_getForceContribution", + key: '_drawEdges', /** - * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass. - * If a region contains a single node, we check if it is not itself, then we apply the force. - * - * @param parentBranch - * @param node + * Redraw all edges + * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); + * @param {CanvasRenderingContext2D} ctx * @private */ - value: function _getForceContribution(parentBranch, node) { - // we get no force contribution from an empty region - if (parentBranch.childrenCount > 0) { - var dx = undefined, - dy = undefined, - distance = undefined; - - // get the distance from the center of mass to the node. - dx = parentBranch.centerOfMass.x - node.x; - dy = parentBranch.centerOfMass.y - node.y; - distance = Math.sqrt(dx * dx + dy * dy); + value: function _drawEdges(ctx) { + var edges = this.body.edges; + var edgeIndices = this.body.edgeIndices; + var edge = undefined; - // BarnesHutSolver condition - // original condition : s/d < theta = passed === d/s > 1/theta = passed - // calcSize = 1/s --> d * 1/s > 1/theta = passed - if (distance * parentBranch.calcSize > this.thetaInversed) { - this._calculateForces(distance, dx, dy, node, parentBranch); - } else { - // Did not pass the condition, go into children if available - if (parentBranch.childrenCount === 4) { - this._getForceContribution(parentBranch.children.NW, node); - this._getForceContribution(parentBranch.children.NE, node); - this._getForceContribution(parentBranch.children.SW, node); - this._getForceContribution(parentBranch.children.SE, node); - } else { - // parentBranch must have only one node, if it was empty we wouldnt be here - if (parentBranch.children.data.id != node.id) { - // if it is not self - this._calculateForces(distance, dx, dy, node, parentBranch); - } - } + for (var i = 0; i < edgeIndices.length; i++) { + edge = edges[edgeIndices[i]]; + if (edge.connected === true) { + edge.draw(ctx); } } } }, { - key: "_calculateForces", + key: '_drawControlNodes', /** - * Calculate the forces based on the distance. - * - * @param distance - * @param dx - * @param dy - * @param node - * @param parentBranch + * Redraw all edges + * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); + * @param {CanvasRenderingContext2D} ctx * @private */ - value: function _calculateForces(distance, dx, dy, node, parentBranch) { - if (distance === 0) { - distance = 0.1; - dx = distance; - } + value: function _drawControlNodes(ctx) { + var edges = this.body.edges; + var edgeIndices = this.body.edgeIndices; + var edge = undefined; - if (this.overlapAvoidanceFactor < 1) { - distance = Math.max(0.1 + this.overlapAvoidanceFactor * node.shape.radius, distance - node.shape.radius); + for (var i = 0; i < edgeIndices.length; i++) { + edge = edges[edgeIndices[i]]; + edge._drawControlNodes(ctx); } - - // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines - // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce - var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass / Math.pow(distance, 3); - var fx = dx * gravityForce; - var fy = dy * gravityForce; - - this.physicsBody.forces[node.id].x += fx; - this.physicsBody.forces[node.id].y += fy; } }, { - key: "_formBarnesHutTree", + key: '_determineBrowserMethod', /** - * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes. - * - * @param nodes - * @param nodeIndices + * Determine if the browser requires a setTimeout or a requestAnimationFrame. This was required because + * some implementations (safari and IE9) did not support requestAnimationFrame * @private */ - value: function _formBarnesHutTree(nodes, nodeIndices) { - var node = undefined; - var nodeCount = nodeIndices.length; - - var minX = nodes[nodeIndices[0]].x; - var minY = nodes[nodeIndices[0]].y; - var maxX = nodes[nodeIndices[0]].x; - var maxY = nodes[nodeIndices[0]].y; - - // get the range of the nodes - for (var i = 1; i < nodeCount; i++) { - var x = nodes[nodeIndices[i]].x; - var y = nodes[nodeIndices[i]].y; - if (nodes[nodeIndices[i]].options.mass > 0) { - if (x < minX) { - minX = x; - } - if (x > maxX) { - maxX = x; - } - if (y < minY) { - minY = y; - } - if (y > maxY) { - maxY = y; + value: function _determineBrowserMethod() { + if (typeof window !== 'undefined') { + var browserType = navigator.userAgent.toLowerCase(); + this.requiresTimeout = false; + if (browserType.indexOf('msie 9.0') != -1) { + // IE 9 + this.requiresTimeout = true; + } else if (browserType.indexOf('safari') != -1) { + // safari + if (browserType.indexOf('chrome') <= -1) { + this.requiresTimeout = true; } } + } else { + this.requiresTimeout = true; } - // make the range a square - var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y - if (sizeDiff > 0) { - minY -= 0.5 * sizeDiff; - maxY += 0.5 * sizeDiff; - } // xSize > ySize - else { - minX += 0.5 * sizeDiff; - maxX -= 0.5 * sizeDiff; - } // xSize < ySize + } + }]); - var minimumTreeSize = 0.00001; - var rootSize = Math.max(minimumTreeSize, Math.abs(maxX - minX)); - var halfRootSize = 0.5 * rootSize; - var centerX = 0.5 * (minX + maxX), - centerY = 0.5 * (minY + maxY); + return CanvasRenderer; + })(); - // construct the barnesHutTree - var barnesHutTree = { - root: { - centerOfMass: { x: 0, y: 0 }, - mass: 0, - range: { - minX: centerX - halfRootSize, maxX: centerX + halfRootSize, - minY: centerY - halfRootSize, maxY: centerY + halfRootSize - }, - size: rootSize, - calcSize: 1 / rootSize, - children: { data: null }, - maxWidth: 0, - level: 0, - childrenCount: 4 - } - }; - this._splitBranch(barnesHutTree.root); + exports['default'] = CanvasRenderer; + module.exports = exports['default']; - // place the nodes one by one recursively - for (var i = 0; i < nodeCount; i++) { - node = nodes[nodeIndices[i]]; - if (node.options.mass > 0) { - this._placeInTree(barnesHutTree.root, node); - } - } +/***/ }, +/* 100 */ +/***/ function(module, exports, __webpack_require__) { - // make global - return barnesHutTree; - } - }, { - key: "_updateBranchMass", + 'use strict'; - /** - * this updates the mass of a branch. this is increased by adding a node. - * - * @param parentBranch - * @param node - * @private - */ - value: function _updateBranchMass(parentBranch, node) { - var totalMass = parentBranch.mass + node.options.mass; - var totalMassInv = 1 / totalMass; + Object.defineProperty(exports, '__esModule', { + value: true + }); - parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass; - parentBranch.centerOfMass.x *= totalMassInv; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass; - parentBranch.centerOfMass.y *= totalMassInv; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - parentBranch.mass = totalMass; - var biggestSize = Math.max(Math.max(node.height, node.radius), node.width); - parentBranch.maxWidth = parentBranch.maxWidth < biggestSize ? biggestSize : parentBranch.maxWidth; + var Hammer = __webpack_require__(3); + var hammerUtil = __webpack_require__(30); + + var util = __webpack_require__(7); + + /** + * Create the main frame for the Network. + * This function is executed once when a Network object is created. The frame + * contains a canvas, and this canvas contains all objects like the axis and + * nodes. + * @private + */ + + var Canvas = (function () { + function Canvas(body) { + _classCallCheck(this, Canvas); + + this.body = body; + this.pixelRatio = 1; + this.resizeTimer = undefined; + this.resizeFunction = this._onResize.bind(this); + + this.options = {}; + this.defaultOptions = { + autoResize: true, + height: '100%', + width: '100%' + }; + util.extend(this.options, this.defaultOptions); + + this.bindEventListeners(); + } + + _createClass(Canvas, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this = this; + + // bind the events + this.body.emitter.once('resize', function (obj) { + if (obj.width !== 0) { + _this.body.view.translation.x = obj.width * 0.5; + } + if (obj.height !== 0) { + _this.body.view.translation.y = obj.height * 0.5; + } + }); + this.body.emitter.on('setSize', this.setSize.bind(this)); + this.body.emitter.on('destroy', function () { + _this.hammerFrame.destroy(); + _this.hammer.destroy(); + _this._cleanUp(); + }); } }, { - key: "_placeInTree", + key: 'setOptions', + value: function setOptions(options) { + var _this2 = this; - /** - * determine in which branch the node will be placed. - * - * @param parentBranch - * @param node - * @param skipMassUpdate - * @private - */ - value: function _placeInTree(parentBranch, node, skipMassUpdate) { - if (skipMassUpdate != true || skipMassUpdate === undefined) { - // update the mass of the branch. - this._updateBranchMass(parentBranch, node); + if (options !== undefined) { + var fields = ['width', 'height', 'autoResize']; + util.selectiveDeepExtend(fields, this.options, options); } - if (parentBranch.children.NW.range.maxX > node.x) { - // in NW or SW - if (parentBranch.children.NW.range.maxY > node.y) { - // in NW - this._placeInRegion(parentBranch, node, "NW"); - } else { - // in SW - this._placeInRegion(parentBranch, node, "SW"); - } - } else { - // in NE or SE - if (parentBranch.children.NW.range.maxY > node.y) { - // in NE - this._placeInRegion(parentBranch, node, "NE"); - } else { - // in SE - this._placeInRegion(parentBranch, node, "SE"); + if (this.options.autoResize === true) { + // automatically adapt to a changing size of the browser. + this._cleanUp(); + this.resizeTimer = setInterval(function () { + _this2.setSize();_this2.body.emitter.emit('_requestRedraw'); + }, 1000); + this.resizeFunction = this._onResize.bind(this); + util.addEventListener(window, 'resize', this.resizeFunction); + } + } + }, { + key: '_cleanUp', + value: function _cleanUp() { + // automatically adapt to a changing size of the browser. + if (this.resizeTimer !== undefined) { + clearInterval(this.resizeTimer); + } + util.removeEventListener(window, 'resize', this.resizeFunction); + this.resizeFunction = undefined; + } + }, { + key: '_onResize', + value: function _onResize() { + this.setSize(); + this.body.emitter.emit('_redraw'); + } + }, { + key: '_prepareValue', + value: function _prepareValue(value) { + if (typeof value === 'number') { + return value + 'px'; + } else if (typeof value === 'string') { + if (value.indexOf('%') !== -1 || value.indexOf('px') !== -1) { + return value; + } else if (value.indexOf('%') === -1) { + return value + 'px'; } } + throw new Error('Could not use the value supplie for width or height:' + value); } }, { - key: "_placeInRegion", + key: '_create', /** - * actually place the node in a region (or branch) - * - * @param parentBranch - * @param node - * @param region - * @private + * Create the HTML */ - value: function _placeInRegion(parentBranch, node, region) { - switch (parentBranch.children[region].childrenCount) { - case 0: - // place node here - parentBranch.children[region].children.data = node; - parentBranch.children[region].childrenCount = 1; - this._updateBranchMass(parentBranch.children[region], node); - break; - case 1: - // convert into children - // if there are two nodes exactly overlapping (on init, on opening of cluster etc.) - // we move one node a pixel and we do not put it in the tree. - if (parentBranch.children[region].children.data.x === node.x && parentBranch.children[region].children.data.y === node.y) { - //node.x += Math.random(); - //node.y += Math.random(); - node.x += 0.1; - node.y += 0.1; - } else { - this._splitBranch(parentBranch.children[region]); - this._placeInTree(parentBranch.children[region], node); - } - break; - case 4: - // place in branch - this._placeInTree(parentBranch.children[region], node); - break; + value: function _create() { + // remove all elements from the container element. + while (this.body.container.hasChildNodes()) { + this.body.container.removeChild(this.body.container.firstChild); + } + + this.frame = document.createElement('div'); + this.frame.className = 'vis-network'; + this.frame.style.position = 'relative'; + this.frame.style.overflow = 'hidden'; + this.frame.tabIndex = 900; // tab index is required for keycharm to bind keystrokes to the div instead of the window + + ////////////////////////////////////////////////////////////////// + + this.frame.canvas = document.createElement('canvas'); + this.frame.canvas.style.position = 'relative'; + this.frame.appendChild(this.frame.canvas); + + if (!this.frame.canvas.getContext) { + var noCanvas = document.createElement('DIV'); + noCanvas.style.color = 'red'; + noCanvas.style.fontWeight = 'bold'; + noCanvas.style.padding = '10px'; + noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; + this.frame.canvas.appendChild(noCanvas); + } else { + var ctx = this.frame.canvas.getContext('2d'); + this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + + this.frame.canvas.getContext('2d').setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); } + + // add the frame to the container element + this.body.container.appendChild(this.frame); + + this.body.view.scale = 1; + this.body.view.translation = { x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight }; + + this._bindHammer(); } }, { - key: "_splitBranch", + key: '_bindHammer', /** - * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch - * after the split is complete. - * - * @param parentBranch + * This function binds hammer, it can be repeated over and over due to the uniqueness check. * @private */ - value: function _splitBranch(parentBranch) { - // if the branch is shaded with a node, replace the node in the new subset. - var containedNode = null; - if (parentBranch.childrenCount === 1) { - containedNode = parentBranch.children.data; - parentBranch.mass = 0; - parentBranch.centerOfMass.x = 0; - parentBranch.centerOfMass.y = 0; - } - parentBranch.childrenCount = 4; - parentBranch.children.data = null; - this._insertRegion(parentBranch, "NW"); - this._insertRegion(parentBranch, "NE"); - this._insertRegion(parentBranch, "SW"); - this._insertRegion(parentBranch, "SE"); + value: function _bindHammer() { + var _this3 = this; - if (containedNode != null) { - this._placeInTree(parentBranch, containedNode); + if (this.hammer !== undefined) { + this.hammer.destroy(); } + this.drag = {}; + this.pinch = {}; + + // init hammer + this.hammer = new Hammer(this.frame.canvas); + this.hammer.get('pinch').set({ enable: true }); + // enable to get better response, todo: test on mobile. + //this.hammer.get('pan').set({threshold:2}); + + hammerUtil.onTouch(this.hammer, function (event) { + _this3.body.eventListeners.onTouch(event); + }); + this.hammer.on('tap', function (event) { + _this3.body.eventListeners.onTap(event); + }); + this.hammer.on('doubletap', function (event) { + _this3.body.eventListeners.onDoubleTap(event); + }); + this.hammer.on('press', function (event) { + _this3.body.eventListeners.onHold(event); + }); + this.hammer.on('panstart', function (event) { + _this3.body.eventListeners.onDragStart(event); + }); + this.hammer.on('panmove', function (event) { + _this3.body.eventListeners.onDrag(event); + }); + this.hammer.on('panend', function (event) { + _this3.body.eventListeners.onDragEnd(event); + }); + this.hammer.on('pinch', function (event) { + _this3.body.eventListeners.onPinch(event); + }); + + // TODO: neatly cleanup these handlers when re-creating the Canvas, IF these are done with hammer, event.stopPropagation will not work? + this.frame.canvas.addEventListener('mousewheel', function (event) { + _this3.body.eventListeners.onMouseWheel(event); + }); + this.frame.canvas.addEventListener('DOMMouseScroll', function (event) { + _this3.body.eventListeners.onMouseWheel(event); + }); + + this.frame.canvas.addEventListener('mousemove', function (event) { + _this3.body.eventListeners.onMouseMove(event); + }); + this.frame.canvas.addEventListener('contextmenu', function (event) { + _this3.body.eventListeners.onContext(event); + }); + + this.hammerFrame = new Hammer(this.frame); + hammerUtil.onRelease(this.hammerFrame, function (event) { + _this3.body.eventListeners.onRelease(event); + }); } }, { - key: "_insertRegion", + key: 'setSize', /** - * This function subdivides the region into four new segments. - * Specifically, this inserts a single new segment. - * It fills the children section of the parentBranch - * - * @param parentBranch - * @param region - * @param parentRange - * @private + * Set a new size for the network + * @param {string} width Width in pixels or percentage (for example '800px' + * or '50%') + * @param {string} height Height in pixels or percentage (for example '400px' + * or '30%') */ - value: function _insertRegion(parentBranch, region) { - var minX = undefined, - maxX = undefined, - minY = undefined, - maxY = undefined; - var childSize = 0.5 * parentBranch.size; - switch (region) { - case "NW": - minX = parentBranch.range.minX; - maxX = parentBranch.range.minX + childSize; - minY = parentBranch.range.minY; - maxY = parentBranch.range.minY + childSize; - break; - case "NE": - minX = parentBranch.range.minX + childSize; - maxX = parentBranch.range.maxX; - minY = parentBranch.range.minY; - maxY = parentBranch.range.minY + childSize; - break; - case "SW": - minX = parentBranch.range.minX; - maxX = parentBranch.range.minX + childSize; - minY = parentBranch.range.minY + childSize; - maxY = parentBranch.range.maxY; - break; - case "SE": - minX = parentBranch.range.minX + childSize; - maxX = parentBranch.range.maxX; - minY = parentBranch.range.minY + childSize; - maxY = parentBranch.range.maxY; - break; + value: function setSize() { + var width = arguments[0] === undefined ? this.options.width : arguments[0]; + var height = arguments[1] === undefined ? this.options.height : arguments[1]; + + width = this._prepareValue(width); + height = this._prepareValue(height); + + var emitEvent = false; + var oldWidth = this.frame.canvas.width; + var oldHeight = this.frame.canvas.height; + + if (width != this.options.width || height != this.options.height || this.frame.style.width != width || this.frame.style.height != height) { + this.frame.style.width = width; + this.frame.style.height = height; + + this.frame.canvas.style.width = '100%'; + this.frame.canvas.style.height = '100%'; + + this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio; + this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio; + + this.options.width = width; + this.options.height = height; + + emitEvent = true; + } else { + // this would adapt the width of the canvas to the width from 100% if and only if + // there is a change. + + if (this.frame.canvas.width != this.frame.canvas.clientWidth * this.pixelRatio) { + this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio; + emitEvent = true; + } + if (this.frame.canvas.height != this.frame.canvas.clientHeight * this.pixelRatio) { + this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio; + emitEvent = true; + } } - parentBranch.children[region] = { - centerOfMass: { x: 0, y: 0 }, - mass: 0, - range: { minX: minX, maxX: maxX, minY: minY, maxY: maxY }, - size: 0.5 * parentBranch.size, - calcSize: 2 * parentBranch.calcSize, - children: { data: null }, - maxWidth: 0, - level: parentBranch.level + 1, - childrenCount: 0 - }; + if (emitEvent === true) { + this.body.emitter.emit('resize', { width: this.frame.canvas.width / this.pixelRatio, height: this.frame.canvas.height / this.pixelRatio, oldWidth: oldWidth / this.pixelRatio, oldHeight: oldHeight / this.pixelRatio }); + } } }, { - key: "_debug", - - //--------------------------- DEBUGGING BELOW ---------------------------// + key: '_XconvertDOMtoCanvas', /** - * This function is for debugging purposed, it draws the tree. - * - * @param ctx - * @param color + * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to + * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) + * @param {number} x + * @returns {number} * @private */ - value: function _debug(ctx, color) { - if (this.barnesHutTree !== undefined) { - - ctx.lineWidth = 1; - - this._drawBranch(this.barnesHutTree.root, ctx, color); - } + value: function _XconvertDOMtoCanvas(x) { + return (x - this.body.view.translation.x) / this.body.view.scale; } }, { - key: "_drawBranch", + key: '_XconvertCanvasToDOM', /** - * This function is for debugging purposes. It draws the branches recursively. - * - * @param branch - * @param ctx - * @param color + * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to + * the X coordinate in DOM-space (coordinate point in browser relative to the container div) + * @param {number} x + * @returns {number} * @private */ - value: function _drawBranch(branch, ctx, color) { - if (color === undefined) { - color = "#FF0000"; - } - - if (branch.childrenCount === 4) { - this._drawBranch(branch.children.NW, ctx); - this._drawBranch(branch.children.NE, ctx); - this._drawBranch(branch.children.SE, ctx); - this._drawBranch(branch.children.SW, ctx); - } - ctx.strokeStyle = color; - ctx.beginPath(); - ctx.moveTo(branch.range.minX, branch.range.minY); - ctx.lineTo(branch.range.maxX, branch.range.minY); - ctx.stroke(); + value: function _XconvertCanvasToDOM(x) { + return x * this.body.view.scale + this.body.view.translation.x; + } + }, { + key: '_YconvertDOMtoCanvas', - ctx.beginPath(); - ctx.moveTo(branch.range.maxX, branch.range.minY); - ctx.lineTo(branch.range.maxX, branch.range.maxY); - ctx.stroke(); + /** + * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to + * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) + * @param {number} y + * @returns {number} + * @private + */ + value: function _YconvertDOMtoCanvas(y) { + return (y - this.body.view.translation.y) / this.body.view.scale; + } + }, { + key: '_YconvertCanvasToDOM', - ctx.beginPath(); - ctx.moveTo(branch.range.maxX, branch.range.maxY); - ctx.lineTo(branch.range.minX, branch.range.maxY); - ctx.stroke(); + /** + * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to + * the Y coordinate in DOM-space (coordinate point in browser relative to the container div) + * @param {number} y + * @returns {number} + * @private + */ + value: function _YconvertCanvasToDOM(y) { + return y * this.body.view.scale + this.body.view.translation.y; + } + }, { + key: 'canvasToDOM', - ctx.beginPath(); - ctx.moveTo(branch.range.minX, branch.range.maxY); - ctx.lineTo(branch.range.minX, branch.range.minY); - ctx.stroke(); + /** + * + * @param {object} pos = {x: number, y: number} + * @returns {{x: number, y: number}} + * @constructor + */ + value: function canvasToDOM(pos) { + return { x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y) }; + } + }, { + key: 'DOMtoCanvas', - /* - if (branch.mass > 0) { - ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass); - ctx.stroke(); - } - */ + /** + * + * @param {object} pos = {x: number, y: number} + * @returns {{x: number, y: number}} + * @constructor + */ + value: function DOMtoCanvas(pos) { + return { x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y) }; } }]); - return BarnesHutSolver; + return Canvas; })(); - exports["default"] = BarnesHutSolver; - module.exports = exports["default"]; + exports['default'] = Canvas; + module.exports = exports['default']; /***/ }, -/* 78 */ +/* 101 */ /***/ function(module, exports, __webpack_require__) { "use strict"; @@ -36841,655 +35013,1154 @@ return /******/ (function(modules) { // webpackBootstrap function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var RepulsionSolver = (function () { - function RepulsionSolver(body, physicsBody, options) { - _classCallCheck(this, RepulsionSolver); + var util = __webpack_require__(7); + + var View = (function () { + function View(body, canvas) { + var _this = this; + + _classCallCheck(this, View); this.body = body; - this.physicsBody = physicsBody; - this.setOptions(options); + this.canvas = canvas; + + this.animationSpeed = 1 / this.renderRefreshRate; + this.animationEasingFunction = "easeInOutQuint"; + this.easingTime = 0; + this.sourceScale = 0; + this.targetScale = 0; + this.sourceTranslation = 0; + this.targetTranslation = 0; + this.lockedOnNodeId = undefined; + this.lockedOnNodeOffset = undefined; + this.touchTime = 0; + + this.viewFunction = undefined; + + this.body.emitter.on("fit", this.fit.bind(this)); + this.body.emitter.on("animationFinished", function () { + _this.body.emitter.emit("_stopRendering"); + }); + this.body.emitter.on("unlockNode", this.releaseNode.bind(this)); } - _createClass(RepulsionSolver, [{ + _createClass(View, [{ key: "setOptions", - value: function setOptions(options) { + value: function setOptions() { + var options = arguments[0] === undefined ? {} : arguments[0]; + this.options = options; } }, { - key: "solve", + key: "_getRange", /** - * Calculate the forces the nodes apply on each other based on a repulsion field. - * This field is linearly approximated. - * + * Find the center position of the network * @private */ - value: function solve() { - var dx, dy, distance, fx, fy, repulsingForce, node1, node2; - - var nodes = this.body.nodes; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var forces = this.physicsBody.forces; - - // repulsing forces between nodes - var nodeDistance = this.options.nodeDistance; - - // approximation constants - var a = -2 / 3 / nodeDistance; - var b = 4 / 3; - - // we loop from i over all but the last entree in the array - // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j - for (var i = 0; i < nodeIndices.length - 1; i++) { - node1 = nodes[nodeIndices[i]]; - for (var j = i + 1; j < nodeIndices.length; j++) { - node2 = nodes[nodeIndices[j]]; - - dx = node2.x - node1.x; - dy = node2.y - node1.y; - distance = Math.sqrt(dx * dx + dy * dy); + value: function _getRange() { + var specificNodes = arguments[0] === undefined ? [] : arguments[0]; - // same condition as BarnesHutSolver, making sure nodes are never 100% overlapping. - if (distance === 0) { - distance = 0.1 * Math.random(); - dx = distance; + var minY = 1000000000, + maxY = -1000000000, + minX = 1000000000, + maxX = -1000000000, + node; + if (specificNodes.length > 0) { + for (var i = 0; i < specificNodes.length; i++) { + node = this.body.nodes[specificNodes[i]]; + if (minX > node.shape.boundingBox.left) { + minX = node.shape.boundingBox.left; } - - if (distance < 2 * nodeDistance) { - if (distance < 0.5 * nodeDistance) { - repulsingForce = 1; - } else { - repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / nodeDistance - 1) * steepness)) + 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 + } + } else { + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + node = this.body.nodes[nodeId]; + if (minX > node.shape.boundingBox.left) { + minX = node.shape.boundingBox.left; } - repulsingForce = repulsingForce / distance; - - fx = dx * repulsingForce; - fy = dy * repulsingForce; - - forces[node1.id].x -= fx; - forces[node1.id].y -= fy; - forces[node2.id].x += fx; - forces[node2.id].y += fy; + 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 === 1000000000 && maxX === -1000000000 && minY === 1000000000 && maxY === -1000000000) { + minY = 0, maxY = 0, minX = 0, maxX = 0; + } + return { minX: minX, maxX: maxX, minY: minY, maxY: maxY }; } - }]); + }, { + key: "_findCenter", - return RepulsionSolver; - })(); + /** + * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; + * @returns {{x: number, y: number}} + * @private + */ + value: function _findCenter(range) { + return { x: 0.5 * (range.maxX + range.minX), + y: 0.5 * (range.maxY + range.minY) }; + } + }, { + key: "fit", - exports["default"] = RepulsionSolver; - module.exports = exports["default"]; + /** + * This function zooms out to fit all data on screen based on amount of nodes + * @param {Object} Options + * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false; + */ + value: function fit() { + var options = arguments[0] === undefined ? { nodes: [] } : arguments[0]; + var initialZoom = arguments[1] === undefined ? false : arguments[1]; -/***/ }, -/* 79 */ -/***/ function(module, exports, __webpack_require__) { + var range; + var zoomLevel; - "use strict"; + if (initialZoom === true) { + // check if more than half of the nodes have a predefined position. If so, we use the range, not the approximation. + var positionDefined = 0; + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + var node = this.body.nodes[nodeId]; + if (node.predefinedPosition === true) { + positionDefined += 1; + } + } + } + if (positionDefined > 0.5 * this.body.nodeIndices.length) { + this.fit(options, false); + return; + } - Object.defineProperty(exports, "__esModule", { - value: true - }); + range = this._getRange(options.nodes); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var numberOfNodes = this.body.nodeIndices.length; + zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + // correct for larger canvasses. + var factor = Math.min(this.canvas.frame.canvas.clientWidth / 600, this.canvas.frame.canvas.clientHeight / 600); + zoomLevel *= factor; + } else { + this.body.emitter.emit("_resizeNodes"); + range = this._getRange(options.nodes); + var xDistance = Math.abs(range.maxX - range.minX) * 1.1; + var yDistance = Math.abs(range.maxY - range.minY) * 1.1; - var HierarchicalRepulsionSolver = (function () { - function HierarchicalRepulsionSolver(body, physicsBody, options) { - _classCallCheck(this, HierarchicalRepulsionSolver); + var xZoomLevel = this.canvas.frame.canvas.clientWidth / xDistance; + var yZoomLevel = this.canvas.frame.canvas.clientHeight / yDistance; - this.body = body; - this.physicsBody = physicsBody; - this.setOptions(options); - } + zoomLevel = xZoomLevel <= yZoomLevel ? xZoomLevel : yZoomLevel; + } - _createClass(HierarchicalRepulsionSolver, [{ - key: "setOptions", - value: function setOptions(options) { - this.options = options; + if (zoomLevel > 1) { + zoomLevel = 1; + } else if (zoomLevel === 0) { + zoomLevel = 1; + } + + var center = this._findCenter(range); + var animationOptions = { position: center, scale: zoomLevel, animation: options.animation }; + this.moveTo(animationOptions); } }, { - key: "solve", + key: "focus", + + // animation /** - * Calculate the forces the nodes apply on each other based on a repulsion field. - * This field is linearly approximated. + * Center a node in view. * - * @private + * @param {Number} nodeId + * @param {Number} [options] */ - value: function solve() { - var dx, dy, distance, fx, fy, repulsingForce, node1, node2, i, j; - - var nodes = this.body.nodes; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var forces = this.physicsBody.forces; - - // repulsing forces between nodes - var nodeDistance = this.options.nodeDistance; - - // we loop from i over all but the last entree in the array - // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j - for (i = 0; i < nodeIndices.length - 1; i++) { - node1 = nodes[nodeIndices[i]]; - for (j = i + 1; j < nodeIndices.length; j++) { - node2 = nodes[nodeIndices[j]]; - - // nodes only affect nodes on their level - if (node1.level === node2.level) { - dx = node2.x - node1.x; - dy = node2.y - node1.y; - distance = Math.sqrt(dx * dx + dy * dy); + value: function focus(nodeId) { + var options = arguments[1] === undefined ? {} : arguments[1]; - var steepness = 0.05; - if (distance < nodeDistance) { - repulsingForce = -Math.pow(steepness * distance, 2) + Math.pow(steepness * nodeDistance, 2); - } else { - repulsingForce = 0; - } - // normalize force with - if (distance === 0) { - distance = 0.01; - } else { - repulsingForce = repulsingForce / distance; - } - fx = dx * repulsingForce; - fy = dy * repulsingForce; + if (this.body.nodes[nodeId] !== undefined) { + var nodePosition = { x: this.body.nodes[nodeId].x, y: this.body.nodes[nodeId].y }; + options.position = nodePosition; + options.lockedOnNode = nodeId; - forces[node1.id].x -= fx; - forces[node1.id].y -= fy; - forces[node2.id].x += fx; - forces[node2.id].y += fy; - } - } + this.moveTo(options); + } else { + console.log("Node: " + nodeId + " cannot be found."); } } - }]); - - return HierarchicalRepulsionSolver; - })(); + }, { + key: "moveTo", - exports["default"] = HierarchicalRepulsionSolver; - module.exports = exports["default"]; + /** + * + * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels + * | options.scale = Number // scale to move to + * | options.position = {x:Number, y:Number} // position to move to + * | options.animation = {duration:Number, easingFunction:String} || Boolean // position to move to + */ + value: function moveTo(options) { + if (options === undefined) { + options = {}; + return; + } + if (options.offset === undefined) { + options.offset = { x: 0, y: 0 }; + } + if (options.offset.x === undefined) { + options.offset.x = 0; + } + if (options.offset.y === undefined) { + options.offset.y = 0; + } + if (options.scale === undefined) { + options.scale = this.body.view.scale; + } + if (options.position === undefined) { + options.position = this.getViewPosition(); + } + if (options.animation === undefined) { + options.animation = { duration: 0 }; + } + if (options.animation === false) { + options.animation = { duration: 0 }; + } + if (options.animation === true) { + options.animation = {}; + } + if (options.animation.duration === undefined) { + options.animation.duration = 1000; + } // default duration + if (options.animation.easingFunction === undefined) { + options.animation.easingFunction = "easeInOutQuad"; + } // default easing function -/***/ }, -/* 80 */ -/***/ function(module, exports, __webpack_require__) { + this.animateView(options); + } + }, { + key: "animateView", - "use strict"; + /** + * + * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels + * | options.time = Number // animation time in milliseconds + * | options.scale = Number // scale to animate to + * | options.position = {x:Number, y:Number} // position to animate to + * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad, + * // easeInCubic, easeOutCubic, easeInOutCubic, + * // easeInQuart, easeOutQuart, easeInOutQuart, + * // easeInQuint, easeOutQuint, easeInOutQuint + */ + value: function animateView(options) { + if (options === undefined) { + return; + } + this.animationEasingFunction = options.animation.easingFunction; + // release if something focussed on the node + this.releaseNode(); + if (options.locked === true) { + this.lockedOnNodeId = options.lockedOnNode; + this.lockedOnNodeOffset = options.offset; + } - Object.defineProperty(exports, "__esModule", { - value: true - }); + // forcefully complete the old animation if it was still running + if (this.easingTime != 0) { + this._transitionRedraw(true); // by setting easingtime to 1, we finish the animation. + } - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + this.sourceScale = this.body.view.scale; + this.sourceTranslation = this.body.view.translation; + this.targetScale = options.scale; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw + // but at least then we'll have the target transition + this.body.view.scale = this.targetScale; + var viewCenter = this.canvas.DOMtoCanvas({ x: 0.5 * this.canvas.frame.canvas.clientWidth, y: 0.5 * this.canvas.frame.canvas.clientHeight }); - var SpringSolver = (function () { - function SpringSolver(body, physicsBody, options) { - _classCallCheck(this, SpringSolver); + var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node + x: viewCenter.x - options.position.x, + y: viewCenter.y - options.position.y + }; + this.targetTranslation = { + x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x, + y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y + }; - this.body = body; - this.physicsBody = physicsBody; - this.setOptions(options); - } + // if the time is set to 0, don't do an animation + if (options.animation.duration === 0) { + if (this.lockedOnNodeId != undefined) { + this.viewFunction = this._lockedRedraw.bind(this); + this.body.emitter.on("initRedraw", this.viewFunction); + } else { + this.body.view.scale = this.targetScale; + this.body.view.translation = this.targetTranslation; + this.body.emitter.emit("_requestRedraw"); + } + } else { + this.animationSpeed = 1 / (60 * options.animation.duration * 0.001) || 1 / 60; // 60 for 60 seconds, 0.001 for milli's + this.animationEasingFunction = options.animation.easingFunction; - _createClass(SpringSolver, [{ - key: "setOptions", - value: function setOptions(options) { - this.options = options; + this.viewFunction = this._transitionRedraw.bind(this); + this.body.emitter.on("initRedraw", this.viewFunction); + this.body.emitter.emit("_startRendering"); + } } }, { - key: "solve", + key: "_lockedRedraw", /** - * This function calculates the springforces on the nodes, accounting for the support nodes. - * + * used to animate smoothly by hijacking the redraw function. * @private */ - value: function solve() { - var edgeLength = undefined, - edge = undefined; - var edgeIndices = this.physicsBody.physicsEdgeIndices; - var edges = this.body.edges; - var node1 = undefined, - node2 = undefined, - node3 = undefined; - - // forces caused by the edges, modelled as springs - for (var i = 0; i < edgeIndices.length; i++) { - edge = edges[edgeIndices[i]]; - if (edge.connected === true && edge.toId !== edge.fromId) { - // only calculate forces if nodes are in the same sector - if (this.body.nodes[edge.toId] !== undefined && this.body.nodes[edge.fromId] !== undefined) { - if (edge.edgeType.via !== undefined) { - edgeLength = edge.options.length === undefined ? this.options.springLength : edge.options.length; - node1 = edge.to; - node2 = edge.edgeType.via; - node3 = edge.from; + value: function _lockedRedraw() { + var nodePosition = { x: this.body.nodes[this.lockedOnNodeId].x, y: this.body.nodes[this.lockedOnNodeId].y }; + var viewCenter = this.DOMtoCanvas({ x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight }); + var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node + x: viewCenter.x - nodePosition.x, + y: viewCenter.y - nodePosition.y + }; + var sourceTranslation = this.body.view.translation; + var targetTranslation = { + x: sourceTranslation.x + distanceFromCenter.x * this.body.view.scale + this.lockedOnNodeOffset.x, + y: sourceTranslation.y + distanceFromCenter.y * this.body.view.scale + this.lockedOnNodeOffset.y + }; - this._calculateSpringForce(node1, node2, 0.5 * edgeLength); - this._calculateSpringForce(node2, node3, 0.5 * edgeLength); - } else { - // the * 1.5 is here so the edge looks as large as a smooth edge. It does not initially because the smooth edges use - // the support nodes which exert a repulsive force on the to and from nodes, making the edge appear larger. - edgeLength = edge.options.length === undefined ? this.options.springLength * 1.5 : edge.options.length; - this._calculateSpringForce(edge.from, edge.to, edgeLength); - } - } - } + this.body.view.translation = targetTranslation; + } + }, { + key: "releaseNode", + value: function releaseNode() { + if (this.lockedOnNodeId !== undefined && this.viewFunction !== undefined) { + this.body.emitter.off("initRedraw", this.viewFunction); + this.lockedOnNodeId = undefined; + this.lockedOnNodeOffset = undefined; } } }, { - key: "_calculateSpringForce", + key: "_transitionRedraw", /** - * This is the code actually performing the calculation for the function above. * - * @param node1 - * @param node2 - * @param edgeLength + * @param easingTime * @private */ - value: function _calculateSpringForce(node1, node2, edgeLength) { - var dx = node1.x - node2.x; - var dy = node1.y - node2.y; - var distance = Math.max(Math.sqrt(dx * dx + dy * dy), 0.01); + value: function _transitionRedraw() { + var finished = arguments[0] === undefined ? false : arguments[0]; - // the 1/distance is so the fx and fy can be calculated without sine or cosine. - var springForce = this.options.springConstant * (edgeLength - distance) / distance; + this.easingTime += this.animationSpeed; + this.easingTime = finished === true ? 1 : this.easingTime; - var fx = dx * springForce; - var fy = dy * springForce; + var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime); - // handle the case where one node is not part of the physcis - if (this.physicsBody.forces[node1.id] !== undefined) { - this.physicsBody.forces[node1.id].x += fx; - this.physicsBody.forces[node1.id].y += fy; - } + this.body.view.scale = this.sourceScale + (this.targetScale - this.sourceScale) * progress; + this.body.view.translation = { + x: this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress, + y: this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress + }; - if (this.physicsBody.forces[node2.id] !== undefined) { - this.physicsBody.forces[node2.id].x -= fx; - this.physicsBody.forces[node2.id].y -= fy; + // cleanup + if (this.easingTime >= 1) { + this.body.emitter.off("initRedraw", this.viewFunction); + this.easingTime = 0; + if (this.lockedOnNodeId != undefined) { + this.viewFunction = this._lockedRedraw.bind(this); + this.body.emitter.on("initRedraw", this.viewFunction); + } + this.body.emitter.emit("animationFinished"); } } + }, { + key: "getScale", + value: function getScale() { + return this.body.view.scale; + } + }, { + key: "getViewPosition", + value: function getViewPosition() { + return this.canvas.DOMtoCanvas({ x: 0.5 * this.canvas.frame.canvas.clientWidth, y: 0.5 * this.canvas.frame.canvas.clientHeight }); + } }]); - return SpringSolver; + return View; })(); - exports["default"] = SpringSolver; + exports["default"] = View; module.exports = exports["default"]; /***/ }, -/* 81 */ +/* 102 */ /***/ function(module, exports, __webpack_require__) { - "use strict"; + 'use strict'; - Object.defineProperty(exports, "__esModule", { + Object.defineProperty(exports, '__esModule', { value: true }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - var HierarchicalSpringSolver = (function () { - function HierarchicalSpringSolver(body, physicsBody, options) { - _classCallCheck(this, HierarchicalSpringSolver); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + var _componentsNavigationHandler = __webpack_require__(103); + + var _componentsNavigationHandler2 = _interopRequireDefault(_componentsNavigationHandler); + + var _componentsPopup = __webpack_require__(104); + + var _componentsPopup2 = _interopRequireDefault(_componentsPopup); + + var util = __webpack_require__(7); + + var InteractionHandler = (function () { + function InteractionHandler(body, canvas, selectionHandler) { + _classCallCheck(this, InteractionHandler); this.body = body; - this.physicsBody = physicsBody; - this.setOptions(options); - } + this.canvas = canvas; + this.selectionHandler = selectionHandler; + this.navigationHandler = new _componentsNavigationHandler2['default'](body, canvas); - _createClass(HierarchicalSpringSolver, [{ - key: "setOptions", - value: function setOptions(options) { - this.options = options; - } - }, { - key: "solve", + // bind the events from hammer to functions in this object + this.body.eventListeners.onTap = this.onTap.bind(this); + this.body.eventListeners.onTouch = this.onTouch.bind(this); + this.body.eventListeners.onDoubleTap = this.onDoubleTap.bind(this); + this.body.eventListeners.onHold = this.onHold.bind(this); + this.body.eventListeners.onDragStart = this.onDragStart.bind(this); + this.body.eventListeners.onDrag = this.onDrag.bind(this); + this.body.eventListeners.onDragEnd = this.onDragEnd.bind(this); + this.body.eventListeners.onMouseWheel = this.onMouseWheel.bind(this); + this.body.eventListeners.onPinch = this.onPinch.bind(this); + this.body.eventListeners.onMouseMove = this.onMouseMove.bind(this); + this.body.eventListeners.onRelease = this.onRelease.bind(this); + this.body.eventListeners.onContext = this.onContext.bind(this); - /** - * This function calculates the springforces on the nodes, accounting for the support nodes. - * - * @private - */ - value: function solve() { - var edgeLength, edge; - var dx, dy, fx, fy, springForce, distance; - var edges = this.body.edges; - var factor = 0.5; + this.touchTime = 0; + this.drag = {}; + this.pinch = {}; + this.popup = undefined; + this.popupObj = undefined; + this.popupTimer = undefined; - var edgeIndices = this.physicsBody.physicsEdgeIndices; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var forces = this.physicsBody.forces; + this.body.functions.getPointer = this.getPointer.bind(this); - // initialize the spring force counters - for (var i = 0; i < nodeIndices.length; i++) { - var nodeId = nodeIndices[i]; - forces[nodeId].springFx = 0; - forces[nodeId].springFy = 0; - } + this.options = {}; + this.defaultOptions = { + dragNodes: true, + dragView: true, + hover: false, + keyboard: { + enabled: false, + speed: { x: 10, y: 10, zoom: 0.02 }, + bindToWindow: true + }, + navigationButtons: false, + tooltipDelay: 300, + zoomView: true + }; + util.extend(this.options, this.defaultOptions); - // forces caused by the edges, modelled as springs - for (var i = 0; i < edgeIndices.length; i++) { - edge = edges[edgeIndices[i]]; - if (edge.connected === true) { - edgeLength = edge.options.length === undefined ? this.options.springLength : edge.options.length; + this.bindEventListeners(); + } - dx = edge.from.x - edge.to.x; - dy = edge.from.y - edge.to.y; - distance = Math.sqrt(dx * dx + dy * dy); - distance = distance === 0 ? 0.01 : distance; + _createClass(InteractionHandler, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this = this; - // the 1/distance is so the fx and fy can be calculated without sine or cosine. - springForce = this.options.springConstant * (edgeLength - distance) / distance; + this.body.emitter.on('destroy', function () { + clearTimeout(_this.popupTimer); + delete _this.body.functions.getPointer; + }); + } + }, { + key: 'setOptions', + value: function setOptions(options) { + if (options !== undefined) { + // extend all but the values in fields + var fields = ['hideEdgesOnDrag', 'hideNodesOnDrag', 'keyboard', 'multiselect', 'selectable', 'selectConnectedEdges']; + util.selectiveNotDeepExtend(fields, this.options, options); - fx = dx * springForce; - fy = dy * springForce; + // merge the keyboard options in. + util.mergeOptions(this.options, options, 'keyboard'); - if (edge.to.level != edge.from.level) { - forces[edge.toId].springFx -= fx; - forces[edge.toId].springFy -= fy; - forces[edge.fromId].springFx += fx; - forces[edge.fromId].springFy += fy; - } else { - forces[edge.toId].x -= factor * fx; - forces[edge.toId].y -= factor * fy; - forces[edge.fromId].x += factor * fx; - forces[edge.fromId].y += factor * fy; + if (options.tooltip) { + util.extend(this.options.tooltip, options.tooltip); + if (options.tooltip.color) { + this.options.tooltip.color = util.parseColor(options.tooltip.color); } } } - // normalize spring forces - var springForce = 1; - var springFx, springFy; - for (var i = 0; i < nodeIndices.length; i++) { - var nodeId = nodeIndices[i]; - springFx = Math.min(springForce, Math.max(-springForce, forces[nodeId].springFx)); - springFy = Math.min(springForce, Math.max(-springForce, forces[nodeId].springFy)); + this.navigationHandler.setOptions(this.options); + } + }, { + key: 'getPointer', - forces[nodeId].x += springFx; - forces[nodeId].y += springFy; - } + /** + * Get the pointer location from a touch location + * @param {{x: Number, y: Number}} touch + * @return {{x: Number, y: Number}} pointer + * @private + */ + value: function getPointer(touch) { + return { + x: touch.x - util.getAbsoluteLeft(this.canvas.frame.canvas), + y: touch.y - util.getAbsoluteTop(this.canvas.frame.canvas) + }; + } + }, { + key: 'onTouch', - // retain energy balance - var totalFx = 0; - var totalFy = 0; - for (var i = 0; i < nodeIndices.length; i++) { - var nodeId = nodeIndices[i]; - totalFx += forces[nodeId].x; - totalFy += forces[nodeId].y; + /** + * On start of a touch gesture, store the pointer + * @param event + * @private + */ + value: function onTouch(event) { + if (new Date().valueOf() - this.touchTime > 50) { + this.drag.pointer = this.getPointer(event.center); + this.drag.pinched = false; + this.pinch.scale = this.body.view.scale; + // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame) + this.touchTime = new Date().valueOf(); } - var correctionFx = totalFx / nodeIndices.length; - var correctionFy = totalFy / nodeIndices.length; + } + }, { + key: 'onTap', - for (var i = 0; i < nodeIndices.length; i++) { - var nodeId = nodeIndices[i]; - forces[nodeId].x -= correctionFx; - forces[nodeId].y -= correctionFy; - } + /** + * handle tap/click event: select/unselect a node + * @private + */ + value: function onTap(event) { + var pointer = this.getPointer(event.center); + var multiselect = this.selectionHandler.options.multiselect && (event.changedPointers[0].ctrlKey || event.changedPointers[0].metaKey); + + this.checkSelectionChanges(pointer, event, multiselect); + this.selectionHandler._generateClickEvent('click', event, pointer); } - }]); + }, { + key: 'onDoubleTap', - return HierarchicalSpringSolver; - })(); + /** + * handle doubletap event + * @private + */ + value: function onDoubleTap(event) { + var pointer = this.getPointer(event.center); + this.selectionHandler._generateClickEvent('doubleClick', event, pointer); + } + }, { + key: 'onHold', - exports["default"] = HierarchicalSpringSolver; - module.exports = exports["default"]; + /** + * handle long tap event: multi select nodes + * @private + */ + value: function onHold(event) { + var pointer = this.getPointer(event.center); + var multiselect = this.selectionHandler.options.multiselect; -/***/ }, -/* 82 */ -/***/ function(module, exports, __webpack_require__) { + this.checkSelectionChanges(pointer, event, multiselect); - "use strict"; + this.selectionHandler._generateClickEvent('click', event, pointer); + this.selectionHandler._generateClickEvent('hold', event, pointer); + } + }, { + key: 'onRelease', - Object.defineProperty(exports, "__esModule", { - value: true - }); + /** + * handle the release of the screen + * + * @private + */ + value: function onRelease(event) { + if (new Date().valueOf() - this.touchTime > 10) { + var pointer = this.getPointer(event.center); + this.selectionHandler._generateClickEvent('release', event, pointer); + // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame) + this.touchTime = new Date().valueOf(); + } + } + }, { + key: 'onContext', + value: function onContext(event) { + var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); + this.selectionHandler._generateClickEvent('oncontext', event, pointer); + } + }, { + key: 'checkSelectionChanges', - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + /** + * + * @param pointer + * @param add + */ + value: function checkSelectionChanges(pointer, event) { + var add = arguments[2] === undefined ? false : arguments[2]; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var previouslySelectedEdgeCount = this.selectionHandler._getSelectedEdgeCount(); + var previouslySelectedNodeCount = this.selectionHandler._getSelectedNodeCount(); + var previousSelection = this.selectionHandler.getSelection(); + var selected = undefined; + if (add === true) { + selected = this.selectionHandler.selectAdditionalOnPoint(pointer); + } else { + selected = this.selectionHandler.selectOnPoint(pointer); + } + var selectedEdgesCount = this.selectionHandler._getSelectedEdgeCount(); + var selectedNodesCount = this.selectionHandler._getSelectedNodeCount(); + var currentSelection = this.selectionHandler.getSelection(); - var CentralGravitySolver = (function () { - function CentralGravitySolver(body, physicsBody, options) { - _classCallCheck(this, CentralGravitySolver); + var _determineIfDifferent = this._determineIfDifferent(previousSelection, currentSelection); - this.body = body; - this.physicsBody = physicsBody; - this.setOptions(options); - } + var nodesChanges = _determineIfDifferent.nodesChanges; + var edgesChanges = _determineIfDifferent.edgesChanges; - _createClass(CentralGravitySolver, [{ - key: "setOptions", - value: function setOptions(options) { - this.options = options; + if (selectedNodesCount - previouslySelectedNodeCount > 0) { + // node was selected + this.selectionHandler._generateClickEvent('selectNode', event, pointer); + selected = true; + } else if (selectedNodesCount - previouslySelectedNodeCount < 0) { + // node was deselected + this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection); + selected = true; + } else if (selectedNodesCount === previouslySelectedNodeCount && nodesChanges === true) { + this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection); + this.selectionHandler._generateClickEvent('selectNode', event, pointer); + selected = true; + } + + if (selectedEdgesCount - previouslySelectedEdgeCount > 0) { + // edge was selected + this.selectionHandler._generateClickEvent('selectEdge', event, pointer); + selected = true; + } else if (selectedEdgesCount - previouslySelectedEdgeCount < 0) { + // edge was deselected + this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection); + selected = true; + } else if (selectedEdgesCount === previouslySelectedEdgeCount && edgesChanges === true) { + this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection); + this.selectionHandler._generateClickEvent('selectEdge', event, pointer); + selected = true; + } + + if (selected === true) { + // select or unselect + this.selectionHandler._generateClickEvent('select', event, pointer); + } } }, { - key: "solve", - value: function solve() { - var dx = undefined, - dy = undefined, - distance = undefined, - node = undefined; - var nodes = this.body.nodes; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var forces = this.physicsBody.forces; + key: '_determineIfDifferent', - for (var i = 0; i < nodeIndices.length; i++) { - var nodeId = nodeIndices[i]; - node = nodes[nodeId]; - dx = -node.x; - dy = -node.y; - distance = Math.sqrt(dx * dx + dy * dy); + /** + * This function checks if the nodes and edges previously selected have changed. + * @param previousSelection + * @param currentSelection + * @returns {{nodesChanges: boolean, edgesChanges: boolean}} + * @private + */ + value: function _determineIfDifferent(previousSelection, currentSelection) { + var nodesChanges = false; + var edgesChanges = false; - this._calculateForces(distance, dx, dy, forces, node); + for (var i = 0; i < previousSelection.nodes.length; i++) { + if (currentSelection.nodes.indexOf(previousSelection.nodes[i]) === -1) { + nodesChanges = true; + } + } + for (var i = 0; i < currentSelection.nodes.length; i++) { + if (previousSelection.nodes.indexOf(previousSelection.nodes[i]) === -1) { + nodesChanges = true; + } + } + for (var i = 0; i < previousSelection.edges.length; i++) { + if (currentSelection.edges.indexOf(previousSelection.edges[i]) === -1) { + edgesChanges = true; + } + } + for (var i = 0; i < currentSelection.edges.length; i++) { + if (previousSelection.edges.indexOf(previousSelection.edges[i]) === -1) { + edgesChanges = true; + } } + + return { nodesChanges: nodesChanges, edgesChanges: edgesChanges }; } }, { - key: "_calculateForces", + key: 'onDragStart', /** - * Calculate the forces based on the distance. + * This function is called by onDragStart. + * It is separated out because we can then overload it for the datamanipulation system. + * * @private */ - value: function _calculateForces(distance, dx, dy, forces, node) { - var gravityForce = distance === 0 ? 0 : this.options.centralGravity / distance; - forces[node.id].x = dx * gravityForce; - forces[node.id].y = dy * gravityForce; - } - }]); + value: function onDragStart(event) { + //in case the touch event was triggered on an external div, do the initial touch now. + if (this.drag.pointer === undefined) { + this.onTouch(event); + } - return CentralGravitySolver; - })(); + // note: drag.pointer is set in onTouch to get the initial touch location + var node = this.selectionHandler.getNodeAt(this.drag.pointer); - exports["default"] = CentralGravitySolver; - module.exports = exports["default"]; + this.drag.dragging = true; + this.drag.selection = []; + this.drag.translation = util.extend({}, this.body.view.translation); // copy the object + this.drag.nodeId = undefined; -/***/ }, -/* 83 */ -/***/ function(module, exports, __webpack_require__) { + this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer); - "use strict"; + if (node !== undefined && this.options.dragNodes === true) { + this.drag.nodeId = node.id; + // select the clicked node if not yet selected + if (node.isSelected() === false) { + this.selectionHandler.unselectAll(); + this.selectionHandler.selectObject(node); + } - Object.defineProperty(exports, "__esModule", { - value: true - }); + var selection = this.selectionHandler.selectionObj.nodes; + // create an array with the selected nodes and their original location and status + for (var nodeId in selection) { + if (selection.hasOwnProperty(nodeId)) { + var object = selection[nodeId]; + var s = { + id: object.id, + node: object, - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // store original x, y, xFixed and yFixed, make the node temporarily Fixed + x: object.x, + y: object.y, + xFixed: object.options.fixed.x, + yFixed: object.options.fixed.y + }; - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + object.options.fixed.x = true; + object.options.fixed.y = true; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + this.drag.selection.push(s); + } + } + } + } + }, { + key: 'onDrag', - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** + * handle drag event + * @private + */ + value: function onDrag(event) { + var _this2 = this; - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + if (this.drag.pinched === true) { + return; + } - var _BarnesHutSolver2 = __webpack_require__(77); + // remove the focus on node if it is focussed on by the focusOnNode + this.body.emitter.emit('unlockNode'); - var _BarnesHutSolver3 = _interopRequireDefault(_BarnesHutSolver2); + var pointer = this.getPointer(event.center); - var ForceAtlas2BasedRepulsionSolver = (function (_BarnesHutSolver) { - function ForceAtlas2BasedRepulsionSolver(body, physicsBody, options) { - _classCallCheck(this, ForceAtlas2BasedRepulsionSolver); + this.selectionHandler._generateClickEvent('dragging', event, pointer); - _get(Object.getPrototypeOf(ForceAtlas2BasedRepulsionSolver.prototype), "constructor", this).call(this, body, physicsBody, options); - } + var selection = this.drag.selection; + if (selection && selection.length && this.options.dragNodes === true) { + (function () { + // calculate delta's and new location + var deltaX = pointer.x - _this2.drag.pointer.x; + var deltaY = pointer.y - _this2.drag.pointer.y; - _inherits(ForceAtlas2BasedRepulsionSolver, _BarnesHutSolver); + // update position of all selected nodes + selection.forEach(function (selection) { + var node = selection.node; + // only move the node if it was not fixed initially + if (selection.xFixed === false) { + node.x = _this2.canvas._XconvertDOMtoCanvas(_this2.canvas._XconvertCanvasToDOM(selection.x) + deltaX); + } + // only move the node if it was not fixed initially + if (selection.yFixed === false) { + node.y = _this2.canvas._YconvertDOMtoCanvas(_this2.canvas._YconvertCanvasToDOM(selection.y) + deltaY); + } + }); - _createClass(ForceAtlas2BasedRepulsionSolver, [{ - key: "_calculateForces", + // start the simulation of the physics + _this2.body.emitter.emit('startSimulation'); + })(); + } else { + // move the network + if (this.options.dragView === true) { + // if the drag was not started properly because the click started outside the network div, start it now. + if (this.drag.pointer === undefined) { + this._handleDragStart(event); + return; + } + var diffX = pointer.x - this.drag.pointer.x; + var diffY = pointer.y - this.drag.pointer.y; + + this.body.view.translation = { x: this.drag.translation.x + diffX, y: this.drag.translation.y + diffY }; + this.body.emitter.emit('_redraw'); + } + } + } + }, { + key: 'onDragEnd', /** - * Calculate the forces based on the distance. - * - * @param distance - * @param dx - * @param dy - * @param node - * @param parentBranch + * handle drag start event * @private */ - value: function _calculateForces(distance, dx, dy, node, parentBranch) { - if (distance === 0) { - distance = 0.1 * Math.random(); - dx = distance; - } - - if (this.overlapAvoidanceFactor < 1) { - distance = Math.max(0.1 + this.overlapAvoidanceFactor * node.shape.radius, distance - node.shape.radius); + value: function onDragEnd(event) { + this.drag.dragging = false; + var selection = this.drag.selection; + if (selection && selection.length) { + selection.forEach(function (s) { + // restore original xFixed and yFixed + s.node.options.fixed.x = s.xFixed; + s.node.options.fixed.y = s.yFixed; + }); + this.body.emitter.emit('startSimulation'); + } else { + this.body.emitter.emit('_requestRedraw'); } - - var degree = node.edges.length + 1; - // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines - // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce - var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass * degree / Math.pow(distance, 2); - var fx = dx * gravityForce; - var fy = dy * gravityForce; - - this.physicsBody.forces[node.id].x += fx; - this.physicsBody.forces[node.id].y += fy; + this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center)); } - }]); + }, { + key: 'onPinch', - return ForceAtlas2BasedRepulsionSolver; - })(_BarnesHutSolver3["default"]); + /** + * Handle pinch event + * @param event + * @private + */ + value: function onPinch(event) { + var pointer = this.getPointer(event.center); - exports["default"] = ForceAtlas2BasedRepulsionSolver; - module.exports = exports["default"]; + this.drag.pinched = true; + if (this.pinch['scale'] === undefined) { + this.pinch.scale = 1; + } -/***/ }, -/* 84 */ -/***/ function(module, exports, __webpack_require__) { + // TODO: enabled moving while pinching? + var scale = this.pinch.scale * event.scale; + this.zoom(scale, pointer); + } + }, { + key: 'zoom', - "use strict"; + /** + * Zoom the network in or out + * @param {Number} scale a number around 1, and between 0.01 and 10 + * @param {{x: Number, y: Number}} pointer Position on screen + * @return {Number} appliedScale scale is limited within the boundaries + * @private + */ + value: function zoom(scale, pointer) { + if (this.options.zoomView === true) { + var scaleOld = this.body.view.scale; + if (scale < 0.00001) { + scale = 0.00001; + } + if (scale > 10) { + scale = 10; + } - Object.defineProperty(exports, "__esModule", { - value: true - }); + var preScaleDragPointer = undefined; + if (this.drag !== undefined) { + if (this.drag.dragging === true) { + preScaleDragPointer = this.canvas.DOMtoCanvas(this.drag.pointer); + } + } + // + this.canvas.frame.canvas.clientHeight / 2 + var translation = this.body.view.translation; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var scaleFrac = scale / scaleOld; + var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac; + var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac; - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + this.body.view.scale = scale; + this.body.view.translation = { x: tx, y: ty }; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + if (preScaleDragPointer != undefined) { + var postScaleDragPointer = this.canvas.canvasToDOM(preScaleDragPointer); + this.drag.pointer.x = postScaleDragPointer.x; + this.drag.pointer.y = postScaleDragPointer.y; + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + this.body.emitter.emit('_requestRedraw'); - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + if (scaleOld < scale) { + this.body.emitter.emit('zoom', { direction: '+', scale: this.body.view.scale }); + } else { + this.body.emitter.emit('zoom', { direction: '-', scale: this.body.view.scale }); + } + } + } + }, { + key: 'onMouseWheel', - var _CentralGravitySolver2 = __webpack_require__(82); + /** + * Event handler for mouse wheel event, used to zoom the timeline + * See http://adomas.org/javascript-mouse-wheel/ + * https://github.com/EightMedia/hammer.js/issues/256 + * @param {MouseEvent} event + * @private + */ + value: function onMouseWheel(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; + } - var _CentralGravitySolver3 = _interopRequireDefault(_CentralGravitySolver2); + // 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 !== 0) { - var ForceAtlas2BasedCentralGravitySolver = (function (_CentralGravitySolver) { - function ForceAtlas2BasedCentralGravitySolver(body, physicsBody, options) { - _classCallCheck(this, ForceAtlas2BasedCentralGravitySolver); + // calculate the new scale + var scale = this.body.view.scale; + var zoom = delta / 10; + if (delta < 0) { + zoom = zoom / (1 - zoom); + } + scale *= 1 + zoom; - _get(Object.getPrototypeOf(ForceAtlas2BasedCentralGravitySolver.prototype), "constructor", this).call(this, body, physicsBody, options); - } + // calculate the pointer location + var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); - _inherits(ForceAtlas2BasedCentralGravitySolver, _CentralGravitySolver); + // apply the new scale + this.zoom(scale, pointer); + } - _createClass(ForceAtlas2BasedCentralGravitySolver, [{ - key: "_calculateForces", + // Prevent default actions caused by mouse wheel. + event.preventDefault(); + } + }, { + key: 'onMouseMove', /** - * Calculate the forces based on the distance. + * Mouse move handler for checking whether the title moves over a node with a title. + * @param {Event} event * @private */ - value: function _calculateForces(distance, dx, dy, forces, node) { - if (distance > 0) { - var degree = node.edges.length + 1; - var gravityForce = this.options.centralGravity * degree * node.options.mass; - forces[node.id].x = dx * gravityForce; - forces[node.id].y = dy * gravityForce; + value: function onMouseMove(event) { + var _this3 = this; + + var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); + var popupVisible = false; + + // check if the previously selected node is still selected + if (this.popup !== undefined) { + if (this.popup.hidden === false) { + this._checkHidePopup(pointer); + } + + // if the popup was not hidden above + if (this.popup.hidden === false) { + popupVisible = true; + this.popup.setPosition(pointer.x + 3, pointer.y - 5); + this.popup.show(); + } } - } - }]); - return ForceAtlas2BasedCentralGravitySolver; - })(_CentralGravitySolver3["default"]); + // if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over. + if (this.options.keyboard.bindToWindow === false && this.options.keyboard.enabled === true) { + this.canvas.frame.focus(); + } - exports["default"] = ForceAtlas2BasedCentralGravitySolver; - module.exports = exports["default"]; + // start a timeout that will check if the mouse is positioned above an element + if (popupVisible === false) { + if (this.popupTimer !== undefined) { + clearInterval(this.popupTimer); // stop any running calculationTimer + this.popupTimer = undefined; + } + if (!this.drag.dragging) { + this.popupTimer = setTimeout(function () { + return _this3._checkShowPopup(pointer); + }, this.options.tooltipDelay); + } + } -/***/ }, -/* 85 */ -/***/ function(module, exports, __webpack_require__) { + /** + * Adding hover highlights + */ + if (this.options.hover === true) { + // adding hover highlights + var obj = this.selectionHandler.getNodeAt(pointer); + if (obj === undefined) { + obj = this.selectionHandler.getEdgeAt(pointer); + } + this.selectionHandler.hoverObject(obj); + } + } + }, { + key: '_checkShowPopup', - 'use strict'; + /** + * Check if there is an element on the given position in the network + * (a node or edge). If so, and if this element has a title, + * show a popup window with its title. + * + * @param {{x:Number, y:Number}} pointer + * @private + */ + value: function _checkShowPopup(pointer) { + var x = this.canvas._XconvertDOMtoCanvas(pointer.x); + var y = this.canvas._YconvertDOMtoCanvas(pointer.y); + var pointerObj = { + left: x, + top: y, + right: x, + bottom: y + }; - Object.defineProperty(exports, '__esModule', { - value: true - }); + var previousPopupObjId = this.popupObj === undefined ? undefined : this.popupObj.id; + var nodeUnderCursor = false; + var popupType = 'node'; - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + // check if a node is under the cursor. + if (this.popupObj === undefined) { + // search the nodes for overlap, select the top one in case of multiple nodes + var nodeIndices = this.body.nodeIndices; + var nodes = this.body.nodes; + var node = undefined; + var overlappingNodes = []; + for (var i = 0; i < nodeIndices.length; i++) { + node = nodes[nodeIndices[i]]; + if (node.isOverlappingWith(pointerObj) === true) { + if (node.getTitle() !== undefined) { + overlappingNodes.push(nodeIndices[i]); + } + } + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + if (overlappingNodes.length > 0) { + // if there are overlapping nodes, select the last one, this is the one which is drawn on top of the others + this.popupObj = nodes[overlappingNodes[overlappingNodes.length - 1]]; + // if you hover over a node, the title of the edge is not supposed to be shown. + nodeUnderCursor = true; + } + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + if (this.popupObj === undefined && nodeUnderCursor === false) { + // search the edges for overlap + var edgeIndices = this.body.edgeIndices; + var edges = this.body.edges; + var edge = undefined; + var overlappingEdges = []; + for (var i = 0; i < edgeIndices.length; i++) { + edge = edges[edgeIndices[i]]; + if (edge.isOverlappingWith(pointerObj) === true) { + if (edge.connected === true && edge.getTitle() !== undefined) { + overlappingEdges.push(edgeIndices[i]); + } + } + } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + if (overlappingEdges.length > 0) { + this.popupObj = edges[overlappingEdges[overlappingEdges.length - 1]]; + popupType = 'edge'; + } + } - var _Node2 = __webpack_require__(74); + if (this.popupObj !== undefined) { + // show popup message window + if (this.popupObj.id !== previousPopupObjId) { + if (this.popup === undefined) { + this.popup = new _componentsPopup2['default'](this.canvas.frame); + } - var _Node3 = _interopRequireDefault(_Node2); + this.popup.popupTargetType = popupType; + this.popup.popupTargetId = this.popupObj.id; - /** - * - */ + // adjust a small offset such that the mouse cursor is located in the + // bottom left location of the popup, and you can easily move over the + // popup area + this.popup.setPosition(pointer.x + 3, pointer.y - 5); + this.popup.setText(this.popupObj.getTitle()); + this.popup.show(); + this.body.emitter.emit('showPopup', this.popupObj.id); + } + } else { + if (this.popup !== undefined) { + this.popup.hide(); + this.body.emitter.emit('hidePopup'); + } + } + } + }, { + key: '_checkHidePopup', - var Cluster = (function (_Node) { - function Cluster(options, body, imagelist, grouplist, globalOptions) { - _classCallCheck(this, Cluster); + /** + * Check if the popup must be hidden, which is the case when the mouse is no + * longer hovering on the object + * @param {{x:Number, y:Number}} pointer + * @private + */ + value: function _checkHidePopup(pointer) { + var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); - _get(Object.getPrototypeOf(Cluster.prototype), 'constructor', this).call(this, options, body, imagelist, grouplist, globalOptions); + var stillOnObj = false; + if (this.popup.popupTargetType === 'node') { + if (this.body.nodes[this.popup.popupTargetId] !== undefined) { + stillOnObj = this.body.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj); - this.isCluster = true; - this.containedNodes = {}; - this.containedEdges = {}; - } + // if the mouse is still one the node, we have to check if it is not also on one that is drawn on top of it. + // we initially only check stillOnObj because this is much faster. + if (stillOnObj === true) { + var overNode = this.selectionHandler.getNodeAt(pointer); + stillOnObj = overNode.id === this.popup.popupTargetId; + } + } + } else { + if (this.selectionHandler.getNodeAt(pointer) === undefined) { + if (this.body.edges[this.popup.popupTargetId] !== undefined) { + stillOnObj = this.body.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj); + } + } + } - _inherits(Cluster, _Node); + if (stillOnObj === false) { + this.popupObj = undefined; + this.popup.hide(); + this.body.emitter.emit('hidePopup'); + } + } + }]); - return Cluster; - })(_Node3['default']); + return InteractionHandler; + })(); - exports['default'] = Cluster; + exports['default'] = InteractionHandler; module.exports = exports['default']; /***/ }, -/* 86 */ +/* 103 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -37502,10 +36173,10 @@ return /******/ (function(modules) { // webpackBootstrap function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var util = __webpack_require__(2); - var Hammer = __webpack_require__(41); - var hammerUtil = __webpack_require__(49); - var keycharm = __webpack_require__(88); + var util = __webpack_require__(7); + var Hammer = __webpack_require__(3); + var hammerUtil = __webpack_require__(30); + var keycharm = __webpack_require__(43); var NavigationHandler = (function () { function NavigationHandler(body, canvas) { @@ -37756,7 +36427,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = exports['default']; /***/ }, -/* 87 */ +/* 104 */ /***/ function(module, exports, __webpack_require__) { /** @@ -37882,438 +36553,728 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = exports['default']; /***/ }, -/* 88 */ +/* 105 */ /***/ function(module, exports, __webpack_require__) { - var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict"; - /** - * Created by Alex on 11/6/2014. - */ + "use strict"; - // 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 () { + Object.defineProperty(exports, "__esModule", { + value: true + }); - function keycharm(options) { - var preventDefault = options && options.preventDefault || false; + var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var container = options && options.container || window; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var _exportFunctions = {}; - var _bound = {keydown:{}, keyup:{}}; - var _keys = {}; - var i; + var Node = __webpack_require__(62); + var Edge = __webpack_require__(82); + var util = __webpack_require__(7); - // 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};} + var SelectionHandler = (function () { + function SelectionHandler(body, canvas) { + var _this = this; - // 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}; + _classCallCheck(this, SelectionHandler); + this.body = body; + this.canvas = canvas; + this.selectionObj = { nodes: [], edges: [] }; + this.hoverObj = { nodes: {}, edges: {} }; + this.options = {}; + this.defaultOptions = { + multiselect: false, + selectable: true, + selectConnectedEdges: true, + hoverConnectedEdges: true + }; + util.extend(this.options, this.defaultOptions); - var down = function(event) {handleEvent(event,'keydown');}; - var up = function(event) {handleEvent(event,'keyup');}; + this.body.emitter.on("_dataChanged", function () { + _this.updateSelection(); + }); + } - // 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); + _createClass(SelectionHandler, [{ + key: "setOptions", + value: function setOptions(options) { + if (options !== undefined) { + var fields = ["multiselect", "hoverConnectedEdges", "selectable", "selectConnectedEdges"]; + util.selectiveDeepExtend(fields, this.options, options); + } + } + }, { + key: "selectOnPoint", + + /** + * handles the selection part of the tap; + * + * @param {Object} pointer + * @private + */ + value: function selectOnPoint(pointer) { + var selected = false; + if (this.options.selectable === true) { + this.unselectAll(); + var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer); + if (obj !== undefined) { + selected = this.selectObject(obj); + } + this.body.emitter.emit("_requestRedraw"); + } + return selected; + } + }, { + key: "selectAdditionalOnPoint", + value: function selectAdditionalOnPoint(pointer) { + var selectionChanged = false; + if (this.options.selectable === true) { + var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer); + + if (obj !== undefined) { + selectionChanged = true; + if (obj.isSelected() === true) { + this.deselectObject(obj); + } else { + this.selectObject(obj); } - else if (bound[i].shift == false && event.shiftKey == false) { - bound[i].fn(event); + + this.body.emitter.emit("_requestRedraw"); + } + } + return selectionChanged; + } + }, { + key: "_generateClickEvent", + value: function _generateClickEvent(eventType, event, pointer, oldSelection) { + var properties = this.getSelection(); + properties["pointer"] = { + DOM: { x: pointer.x, y: pointer.y }, + canvas: this.canvas.DOMtoCanvas(pointer) + }; + properties["event"] = event; + + if (oldSelection !== undefined) { + properties["previousSelection"] = oldSelection; + } + this.body.emitter.emit(eventType, properties); + } + }, { + key: "selectObject", + value: function selectObject(obj) { + var highlightEdges = arguments[1] === undefined ? this.options.selectConnectedEdges : arguments[1]; + + if (obj !== undefined) { + if (obj instanceof Node) { + if (highlightEdges === true) { + this._selectConnectedEdges(obj); } } - - if (preventDefault == true) { - event.preventDefault(); + obj.select(); + this._addToSelection(obj); + return true; + } + return false; + } + }, { + key: "deselectObject", + value: function deselectObject(obj) { + if (obj.isSelected() === true) { + obj.selected = false; + this._removeFromSelection(obj); + } + } + }, { + key: "_getAllNodesOverlappingWith", + + /** + * retrieve all nodes overlapping with given object + * @param {Object} object An object with parameters left, top, right, bottom + * @return {Number[]} An array with id's of the overlapping nodes + * @private + */ + value: function _getAllNodesOverlappingWith(object) { + var overlappingNodes = []; + var nodes = this.body.nodes; + for (var i = 0; i < this.body.nodeIndices.length; i++) { + var nodeId = this.body.nodeIndices[i]; + if (nodes[nodeId].isOverlappingWith(object)) { + overlappingNodes.push(nodeId); + } + } + return overlappingNodes; + } + }, { + key: "_pointerToPositionObject", + + /** + * Return a position object in canvasspace from a single point in screenspace + * + * @param pointer + * @returns {{left: number, top: number, right: number, bottom: number}} + * @private + */ + value: function _pointerToPositionObject(pointer) { + var canvasPos = this.canvas.DOMtoCanvas(pointer); + return { + left: canvasPos.x - 1, + top: canvasPos.y + 1, + right: canvasPos.x + 1, + bottom: canvasPos.y - 1 + }; + } + }, { + key: "getNodeAt", + + /** + * Get the top node at the a specific point (like a click) + * + * @param {{x: Number, y: Number}} pointer + * @return {Node | undefined} node + * @private + */ + value: function getNodeAt(pointer) { + var returnNode = arguments[1] === undefined ? true : arguments[1]; + + // we first check if this is an navigation controls element + var positionObject = this._pointerToPositionObject(pointer); + var overlappingNodes = this._getAllNodesOverlappingWith(positionObject); + // if there are overlapping nodes, select the last one, this is the + // one which is drawn on top of the others + if (overlappingNodes.length > 0) { + if (returnNode === true) { + return this.body.nodes[overlappingNodes[overlappingNodes.length - 1]]; + } else { + return overlappingNodes[overlappingNodes.length - 1]; + } + } else { + return undefined; + } + } + }, { + key: "_getEdgesOverlappingWith", + + /** + * retrieve all edges overlapping with given object, selector is around center + * @param {Object} object An object with parameters left, top, right, bottom + * @return {Number[]} An array with id's of the overlapping nodes + * @private + */ + value: function _getEdgesOverlappingWith(object, overlappingEdges) { + var edges = this.body.edges; + for (var i = 0; i < this.body.edgeIndices.length; i++) { + var edgeId = this.body.edgeIndices[i]; + if (edges[edgeId].isOverlappingWith(object)) { + overlappingEdges.push(edgeId); + } + } + } + }, { + key: "_getAllEdgesOverlappingWith", + + /** + * retrieve all nodes overlapping with given object + * @param {Object} object An object with parameters left, top, right, bottom + * @return {Number[]} An array with id's of the overlapping nodes + * @private + */ + value: function _getAllEdgesOverlappingWith(object) { + var overlappingEdges = []; + this._getEdgesOverlappingWith(object, overlappingEdges); + return overlappingEdges; + } + }, { + key: "getEdgeAt", + + /** + * Place holder. To implement change the getNodeAt to a _getObjectAt. Have the _getObjectAt call + * getNodeAt and _getEdgesAt, then priortize the selection to user preferences. + * + * @param pointer + * @returns {undefined} + * @private + */ + value: function getEdgeAt(pointer) { + var returnEdge = arguments[1] === undefined ? true : arguments[1]; + + var positionObject = this._pointerToPositionObject(pointer); + var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject); + + if (overlappingEdges.length > 0) { + if (returnEdge === true) { + return this.body.edges[overlappingEdges[overlappingEdges.length - 1]]; + } else { + return overlappingEdges[overlappingEdges.length - 1]; + } + } else { + return undefined; + } + } + }, { + key: "_addToSelection", + + /** + * Add object to the selection array. + * + * @param obj + * @private + */ + value: function _addToSelection(obj) { + if (obj instanceof Node) { + this.selectionObj.nodes[obj.id] = obj; + } else { + this.selectionObj.edges[obj.id] = obj; + } + } + }, { + key: "_addToHover", + + /** + * Add object to the selection array. + * + * @param obj + * @private + */ + value: function _addToHover(obj) { + if (obj instanceof Node) { + this.hoverObj.nodes[obj.id] = obj; + } else { + this.hoverObj.edges[obj.id] = obj; + } + } + }, { + key: "_removeFromSelection", + + /** + * Remove a single option from selection. + * + * @param {Object} obj + * @private + */ + value: function _removeFromSelection(obj) { + if (obj instanceof Node) { + delete this.selectionObj.nodes[obj.id]; + } else { + delete this.selectionObj.edges[obj.id]; + } + } + }, { + key: "unselectAll", + + /** + * Unselect all. The selectionObj is useful for this. + * + * @private + */ + value: function unselectAll() { + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + this.selectionObj.nodes[nodeId].unselect(); + } + } + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + this.selectionObj.edges[edgeId].unselect(); + } + } + + this.selectionObj = { nodes: {}, edges: {} }; + } + }, { + key: "_getSelectedNodeCount", + + /** + * return the number of selected nodes + * + * @returns {number} + * @private + */ + value: function _getSelectedNodeCount() { + var count = 0; + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + count += 1; + } + } + return count; + } + }, { + key: "_getSelectedNode", + + /** + * return the selected node + * + * @returns {number} + * @private + */ + value: function _getSelectedNode() { + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + return this.selectionObj.nodes[nodeId]; + } + } + return undefined; + } + }, { + key: "_getSelectedEdge", + + /** + * return the selected edge + * + * @returns {number} + * @private + */ + value: function _getSelectedEdge() { + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + return this.selectionObj.edges[edgeId]; + } + } + return undefined; + } + }, { + key: "_getSelectedEdgeCount", + + /** + * return the number of selected edges + * + * @returns {number} + * @private + */ + value: function _getSelectedEdgeCount() { + var count = 0; + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + count += 1; + } + } + return count; + } + }, { + key: "_getSelectedObjectCount", + + /** + * return the number of selected objects. + * + * @returns {number} + * @private + */ + value: function _getSelectedObjectCount() { + var count = 0; + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + count += 1; + } + } + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + count += 1; + } + } + return count; + } + }, { + key: "_selectionIsEmpty", + + /** + * Check if anything is selected + * + * @returns {boolean} + * @private + */ + value: function _selectionIsEmpty() { + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + return false; + } + } + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + return false; } } - }; + return true; + } + }, { + key: "_clusterInSelection", - // 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); + /** + * check if one of the selected nodes is a cluster. + * + * @returns {boolean} + * @private + */ + value: function _clusterInSelection() { + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + if (this.selectionObj.nodes[nodeId].clusterSize > 1) { + return true; + } + } } - if (_bound[type][_keys[key].code] === undefined) { - _bound[type][_keys[key].code] = []; + return false; + } + }, { + key: "_selectConnectedEdges", + + /** + * select the edges connected to the node that is being selected + * + * @param {Node} node + * @private + */ + value: function _selectConnectedEdges(node) { + for (var i = 0; i < node.edges.length; i++) { + var edge = node.edges[i]; + edge.select(); + this._addToSelection(edge); } - _bound[type][_keys[key].code].push({fn:callback, shift:_keys[key].shift}); - }; + } + }, { + key: "_hoverConnectedEdges", + /** + * select the edges connected to the node that is being selected + * + * @param {Node} node + * @private + */ + value: function _hoverConnectedEdges(node) { + for (var i = 0; i < node.edges.length; i++) { + var edge = node.edges[i]; + edge.hover = true; + this._addToHover(edge); + } + } + }, { + key: "_unselectConnectedEdges", - // bind all keys to a call back (demo purposes) - _exportFunctions.bindAll = function(callback, type) { - if (type === undefined) { - type = 'keydown'; + /** + * unselect the edges connected to the node that is being selected + * + * @param {Node} node + * @private + */ + value: function _unselectConnectedEdges(node) { + for (var i = 0; i < node.edges.length; i++) { + var edge = node.edges[i]; + edge.unselect(); + this._removeFromSelection(edge); } - for (var key in _keys) { - if (_keys.hasOwnProperty(key)) { - _exportFunctions.bind(key,callback,type); - } + } + }, { + key: "blurObject", + + /** + * This is called when someone clicks on a node. either select or deselect it. + * If there is an existing selection and we don't want to append to it, clear the existing selection + * + * @param {Node || Edge} object + * @private + */ + value: function blurObject(object) { + if (object.hover === true) { + object.hover = false; + this.body.emitter.emit("blurNode", { node: object.id }); } - }; + } + }, { + key: "hoverObject", - // 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; + /** + * This is called when someone clicks on a node. either select or deselect it. + * If there is an existing selection and we don't want to append to it, clear the existing selection + * + * @param {Node || Edge} object + * @private + */ + value: function hoverObject(object) { + var hoverChanged = false; + // remove all node hover highlights + for (var nodeId in this.hoverObj.nodes) { + if (this.hoverObj.nodes.hasOwnProperty(nodeId)) { + if (object === undefined) { + this.blurObject(this.hoverObj.nodes[nodeId]); + hoverChanged = true; + } else if (object instanceof Node && object.id != nodeId || object instanceof Edge || object === undefined) { + this.blurObject(this.hoverObj.nodes[nodeId]); + hoverChanged = true; + delete this.hoverObj.nodes[nodeId]; } } } - 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); + // removing all edge hover highlights + for (var edgeId in this.hoverObj.edges) { + if (this.hoverObj.edges.hasOwnProperty(edgeId)) { + this.hoverObj.edges[edgeId].hover = false; + delete this.hoverObj.edges[edgeId]; + } } - 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]); - } + + if (object !== undefined) { + if (object.hover === false) { + object.hover = true; + this._addToHover(object); + hoverChanged = true; + if (object instanceof Node) { + this.body.emitter.emit("hoverNode", { node: object.id }); } } - _bound[type][_keys[key].code] = newBindings; - } - else { - _bound[type][_keys[key].code] = []; + if (object instanceof Node && this.options.hoverConnectedEdges === true) { + this._hoverConnectedEdges(object); + } } - }; - - // 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; - })); - - - - -/***/ }, -/* 89 */ -/***/ function(module, exports, __webpack_require__) { - - function webpackContext(req) { - throw new Error("Cannot find module '" + req + "'."); - } - webpackContext.keys = function() { return []; }; - webpackContext.resolve = webpackContext; - module.exports = webpackContext; - webpackContext.id = 89; - - -/***/ }, -/* 90 */ -/***/ function(module, exports, __webpack_require__) { - - module.exports = function(module) { - if(!module.webpackPolyfill) { - module.deprecate = function() {}; - module.paths = []; - // module.parent = undefined by default - module.children = []; - module.webpackPolyfill = 1; - } - return module; - } - - -/***/ }, -/* 91 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__; - - /* WEBPACK VAR INJECTION */}.call(exports, {})) - -/***/ }, -/* 92 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - - var _utilNodeBase = __webpack_require__(109); - - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - - var Box = (function (_NodeBase) { - function Box(options, body, labelModule) { - _classCallCheck(this, Box); - - _get(Object.getPrototypeOf(Box.prototype), 'constructor', this).call(this, options, body, labelModule); - } - - _inherits(Box, _NodeBase); - - _createClass(Box, [{ - key: 'resize', - value: function resize(ctx, selected) { - if (this.width === undefined) { - var margin = 5; - var textSize = this.labelModule.getTextSize(ctx, selected); - this.width = textSize.width + 2 * margin; - this.height = textSize.height + 2 * margin; - this.radius = 0.5 * this.width; + if (hoverChanged === true) { + this.body.emitter.emit("_requestRedraw"); } } }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(ctx, selected); - this.left = x - this.width / 2; - this.top = y - this.height / 2; - - var borderWidth = this.options.borderWidth; - var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - - ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; - ctx.lineWidth = selected ? selectionLineWidth : borderWidth; - ctx.lineWidth /= this.body.view.scale; - ctx.lineWidth = Math.min(this.width, ctx.lineWidth); - - ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; - - var borderRadius = 6; - ctx.roundRect(this.left, this.top, this.width, this.height, borderRadius); - - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); - - // disable shadows for other elements. - this.disableShadow(ctx); - - ctx.stroke(); + key: "getSelection", - this.updateBoundingBox(x, y); - this.labelModule.draw(ctx, x, y, selected); + /** + * + * retrieve the currently selected objects + * @return {{nodes: Array., edges: Array.}} selection + */ + value: function getSelection() { + var nodeIds = this.getSelectedNodes(); + var edgeIds = this.getSelectedEdges(); + return { nodes: nodeIds, edges: edgeIds }; } }, { - key: 'updateBoundingBox', - value: function updateBoundingBox(x, y) { - this.left = x - this.width * 0.5; - this.top = y - this.height * 0.5; + key: "getSelectedNodes", - this.boundingBox.left = this.left; - this.boundingBox.top = this.top; - this.boundingBox.bottom = this.top + this.height; - this.boundingBox.right = this.left + this.width; + /** + * + * retrieve the currently selected nodes + * @return {String[]} selection An array with the ids of the + * selected nodes. + */ + value: function getSelectedNodes() { + var idArray = []; + if (this.options.selectable === true) { + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + idArray.push(nodeId); + } + } + } + return idArray; } }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - var a = this.width / 2; - var b = this.height / 2; - var w = Math.sin(angle) * a; - var h = Math.cos(angle) * b; - return a * b / Math.sqrt(w * w + h * h); - } - }]); - - return Box; - })(_utilNodeBase2['default']); - - exports['default'] = Box; - module.exports = exports['default']; - -/***/ }, -/* 93 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); + key: "getSelectedEdges", - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + /** + * + * retrieve the currently selected edges + * @return {Array} selection An array with the ids of the + * selected nodes. + */ + value: function getSelectedEdges() { + var idArray = []; + if (this.options.selectable === true) { + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + idArray.push(edgeId); + } + } + } + return idArray; + } + }, { + key: "selectNodes", - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + /** + * select zero or more nodes with the option to highlight edges + * @param {Number[] | String[]} selection An array with the ids of the + * selected nodes. + * @param {boolean} [highlightEdges] + */ + value: function selectNodes(selection) { + var highlightEdges = arguments[1] === undefined ? true : arguments[1]; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var i = undefined, + id = undefined; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + if (!selection || selection.length === undefined) throw "Selection must be an array with ids"; - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + // first unselect any selected node + this.unselectAll(); - var _utilCircleImageBase = __webpack_require__(110); + for (i = 0; i < selection.length; i++) { + id = selection[i]; - var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); + var node = this.body.nodes[id]; + if (!node) { + throw new RangeError("Node with id \"" + id + "\" not found"); + } + this.selectObject(node, highlightEdges); + } + this.body.emitter.emit("_requestRedraw"); + } + }, { + key: "selectEdges", - var Circle = (function (_CircleImageBase) { - function Circle(options, body, labelModule) { - _classCallCheck(this, Circle); + /** + * select zero or more edges + * @param {Number[] | String[]} selection An array with the ids of the + * selected nodes. + */ + value: function selectEdges(selection) { + var i = undefined, + id = undefined; - _get(Object.getPrototypeOf(Circle.prototype), 'constructor', this).call(this, options, body, labelModule); - } + if (!selection || selection.length === undefined) throw "Selection must be an array with ids"; - _inherits(Circle, _CircleImageBase); + // first unselect any selected objects + this.unselectAll(); - _createClass(Circle, [{ - key: 'resize', - value: function resize(ctx, selected) { - if (this.width === undefined) { - var margin = 5; - var textSize = this.labelModule.getTextSize(ctx, selected); - var diameter = Math.max(textSize.width, textSize.height) + 2 * margin; - this.options.size = diameter / 2; + for (i = 0; i < selection.length; i++) { + id = selection[i]; - this.width = diameter; - this.height = diameter; - this.radius = 0.5 * this.width; + var edge = this.body.edges[id]; + if (!edge) { + throw new RangeError("Edge with id \"" + id + "\" not found"); + } + this.selectObject(edge); } + this.body.emitter.emit("_requestRedraw"); } }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(ctx, selected); - this.left = x - this.width / 2; - this.top = y - this.height / 2; - - this._drawRawCircle(ctx, x, y, selected, hover, this.options.size); - - 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; + key: "updateSelection", - this.updateBoundingBox(x, y); - this.labelModule.draw(ctx, x, y, selected); - } - }, { - 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; - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - var a = this.width / 2; - var b = this.height / 2; - var w = Math.sin(angle) * a; - var h = Math.cos(angle) * b; - return a * b / Math.sqrt(w * w + h * h); + /** + * Validate the selection: remove ids of nodes which no longer exist + * @private + */ + value: function updateSelection() { + for (var nodeId in this.selectionObj.nodes) { + if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { + if (!this.body.nodes.hasOwnProperty(nodeId)) { + delete this.selectionObj.nodes[nodeId]; + } + } + } + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + if (!this.body.edges.hasOwnProperty(edgeId)) { + delete this.selectionObj.edges[edgeId]; + } + } + } } }]); - return Circle; - })(_utilCircleImageBase2['default']); + return SelectionHandler; + })(); - exports['default'] = Circle; - module.exports = exports['default']; + exports["default"] = SelectionHandler; + module.exports = exports["default"]; /***/ }, -/* 94 */ +/* 106 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -38324,262 +37285,506 @@ return /******/ (function(modules) { // webpackBootstrap var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var util = __webpack_require__(7); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + var LayoutEngine = (function () { + function LayoutEngine(body) { + _classCallCheck(this, LayoutEngine); - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + this.body = body; - var _utilCircleImageBase = __webpack_require__(110); + this.initialRandomSeed = Math.round(Math.random() * 1000000); + this.randomSeed = this.initialRandomSeed; + this.options = {}; + this.optionsBackup = {}; - var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); + this.defaultOptions = { + randomSeed: undefined, + hierarchical: { + enabled: false, + levelSeparation: 150, + direction: 'UD', // UD, DU, LR, RL + sortMethod: 'hubsize' // hubsize, directed + } + }; + util.extend(this.options, this.defaultOptions); - var CircularImage = (function (_CircleImageBase) { - function CircularImage(options, body, labelModule, imageObj) { - _classCallCheck(this, CircularImage); + this.hierarchicalLevels = {}; - _get(Object.getPrototypeOf(CircularImage.prototype), 'constructor', this).call(this, options, body, labelModule); - this.imageObj = imageObj; - this._swapToImageResizeWhenImageLoaded = true; + this.bindEventListeners(); } - _inherits(CircularImage, _CircleImageBase); + _createClass(LayoutEngine, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this = this; - _createClass(CircularImage, [{ - key: 'resize', - value: function resize() { - if (this.imageObj.src === undefined || this.imageObj.width === undefined || this.imageObj.height === undefined) { - if (!this.width) { - var diameter = this.options.size * 2; - this.width = diameter; - this.height = diameter; - this._swapToImageResizeWhenImageLoaded = true; - this.radius = 0.5 * this.width; - } - } else { - if (this._swapToImageResizeWhenImageLoaded) { - this.width = undefined; - this.height = undefined; - this._swapToImageResizeWhenImageLoaded = false; - } - this._resizeImage(); - } + this.body.emitter.on('_dataChanged', function () { + _this.setupHierarchicalLayout(); + }); + this.body.emitter.on('_resetHierarchicalLayout', function () { + _this.setupHierarchicalLayout(); + }); } }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(); - - this.left = x - this.width / 2; - this.top = y - this.height / 2; + key: 'setOptions', + value: function setOptions(options, allOptions) { + if (options !== undefined) { + var prevHierarchicalState = this.options.hierarchical.enabled; - var size = Math.min(0.5 * this.height, 0.5 * this.width); + util.mergeOptions(this.options, options, 'hierarchical'); + if (options.randomSeed !== undefined) { + this.initialRandomSeed = options.randomSeed; + } - this._drawRawCircle(ctx, x, y, selected, hover, size); + if (this.options.hierarchical.enabled === true) { + // make sure the level seperation is the right way up + if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'DU') { + if (this.options.hierarchical.levelSeparation > 0) { + this.options.hierarchical.levelSeparation *= -1; + } + } else { + if (this.options.hierarchical.levelSeparation < 0) { + this.options.hierarchical.levelSeparation *= -1; + } + } - ctx.save(); - ctx.circle(x, y, size); - ctx.stroke(); - ctx.clip(); + this.body.emitter.emit('_resetHierarchicalLayout'); + // because the hierarchical system needs it's own physics and smooth curve settings, we adapt the other options if needed. + return this.adaptAllOptions(allOptions); + } else { + if (prevHierarchicalState === true) { + // refresh the overridden options for nodes and edges. + this.body.emitter.emit('refresh'); + return util.deepExtend(allOptions, this.optionsBackup); + } + } + } + return allOptions; + } + }, { + key: 'adaptAllOptions', + value: function adaptAllOptions(allOptions) { + if (this.options.hierarchical.enabled === true) { + // set the physics + if (allOptions.physics === undefined || allOptions.physics === true) { + allOptions.physics = { solver: 'hierarchicalRepulsion' }; + this.optionsBackup.physics = { solver: 'barnesHut' }; + } else if (typeof allOptions.physics === 'object') { + this.optionsBackup.physics = { solver: 'barnesHut' }; + if (allOptions.physics.solver !== undefined) { + this.optionsBackup.physics = { solver: allOptions.physics.solver }; + } + allOptions.physics['solver'] = 'hierarchicalRepulsion'; + } else if (allOptions.physics !== false) { + this.optionsBackup.physics = { solver: 'barnesHut' }; + allOptions.physics['solver'] = 'hierarchicalRepulsion'; + } - this._drawImageAtPosition(ctx); + // get the type of static smooth curve in case it is required + var type = 'horizontal'; + if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'LR') { + type = 'vertical'; + } - ctx.restore(); + // disable smooth curves if nothing is defined. If smooth curves have been turned on, turn them into static smooth curves. + if (allOptions.edges === undefined) { + this.optionsBackup.edges = { smooth: { enabled: true, type: 'dynamic' } }; + allOptions.edges = { smooth: false }; + } else if (allOptions.edges.smooth === undefined) { + this.optionsBackup.edges = { smooth: { enabled: true, type: 'dynamic' } }; + allOptions.edges.smooth = false; + } else { + if (typeof allOptions.edges.smooth === 'boolean') { + this.optionsBackup.edges = { smooth: allOptions.edges.smooth }; + allOptions.edges.smooth = { enabled: allOptions.edges.smooth, type: type }; + } else { + // allow custom types except for dynamic + if (allOptions.edges.smooth.type !== undefined && allOptions.edges.smooth.type !== 'dynamic') { + type = allOptions.edges.smooth.type; + } - this._drawImageLabel(ctx, x, y, selected); + this.optionsBackup.edges = { + smooth: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled, + type: allOptions.edges.smooth.type === undefined ? 'dynamic' : allOptions.edges.smooth.type, + roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness + }; + allOptions.edges.smooth = { + enabled: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled, + type: type, + roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness + }; + } + } - this.updateBoundingBox(x, y); + // force all edges into static smooth curves. Only applies to edges that do not use the global options for smooth. + this.body.emitter.emit('_forceDisableDynamicCurves', type); + } + return allOptions; } }, { - 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; - 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.labelOffset); + key: 'seededRandom', + value: function seededRandom() { + var x = Math.sin(this.randomSeed++) * 10000; + return x - Math.floor(x); } }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - return this._distanceToBorder(angle); + key: 'positionInitially', + value: function positionInitially(nodesArray) { + if (this.options.hierarchical.enabled !== true) { + this.randomSeed = this.initialRandomSeed; + for (var i = 0; i < nodesArray.length; i++) { + var node = nodesArray[i]; + if (!node.isFixed() && (node.x === undefined || node.y === undefined)) { + var radius = 10 * 0.1 * nodesArray.length + 10; + var angle = 2 * Math.PI * this.seededRandom(); + if (node.options.fixed.x === false) { + node.x = radius * Math.cos(angle); + } + if (node.options.fixed.x === false) { + node.y = radius * Math.sin(angle); + } + } + } + } } - }]); - - return CircularImage; - })(_utilCircleImageBase2['default']); - - exports['default'] = CircularImage; - module.exports = exports['default']; - -/***/ }, -/* 95 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + }, { + key: 'getSeed', + value: function getSeed() { + return this.initialRandomSeed; + } + }, { + key: 'setupHierarchicalLayout', - var _utilNodeBase = __webpack_require__(109); + /** + * This is the main function to layout the nodes in a hierarchical way. + * It checks if the node details are supplied correctly + * + * @private + */ + value: function setupHierarchicalLayout() { + if (this.options.hierarchical.enabled === true && this.body.nodeIndices.length > 0) { + // get the size of the largest hubs and check if the user has defined a level for a node. + var node = undefined, + nodeId = undefined; + var definedLevel = false; + var undefinedLevel = false; + this.hierarchicalLevels = {}; + this.nodeSpacing = 100; - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + for (nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + node = this.body.nodes[nodeId]; + if (node.options.level !== undefined) { + definedLevel = true; + this.hierarchicalLevels[nodeId] = node.options.level; + } else { + undefinedLevel = true; + } + } + } - var Database = (function (_NodeBase) { - function Database(options, body, labelModule) { - _classCallCheck(this, Database); + // if the user defined some levels but not all, alert and run without hierarchical layout + if (undefinedLevel === true && definedLevel === true) { + throw new Error('To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.'); + return; + } else { + // setup the system to use hierarchical method. + //this._changeConstants(); - _get(Object.getPrototypeOf(Database.prototype), 'constructor', this).call(this, options, body, labelModule); - } + // define levels if undefined by the users. Based on hubsize + if (undefinedLevel === true) { + if (this.options.hierarchical.sortMethod === 'hubsize') { + this._determineLevelsByHubsize(); + } else if (this.options.hierarchical.sortMethod === 'directed' || 'direction') { + this._determineLevelsDirected(); + } + } - _inherits(Database, _NodeBase); + // check the distribution of the nodes per level. + var distribution = this._getDistribution(); - _createClass(Database, [{ - key: 'resize', - value: function resize(ctx, selected) { - if (this.width === undefined) { - var margin = 5; - var textSize = this.labelModule.getTextSize(ctx, selected); - var size = textSize.width + 2 * margin; - this.width = size; - this.height = size; - this.radius = 0.5 * this.width; + // place the nodes on the canvas. + this._placeNodesByHierarchy(distribution); + } } } }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(ctx, selected); - this.left = x - this.width / 2; - this.top = y - this.height / 2; - - var borderWidth = this.options.borderWidth; - var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - - ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; - ctx.lineWidth = this.selected ? selectionLineWidth : borderWidth; - ctx.lineWidth *= this.networkScaleInv; - ctx.lineWidth = Math.min(this.width, ctx.lineWidth); + key: '_placeNodesByHierarchy', - ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; - ctx.database(x - this.width / 2, y - this.height * 0.5, this.width, this.height); + /** + * This function places the nodes on the canvas based on the hierarchial distribution. + * + * @param {Object} distribution | obtained by the function this._getDistribution() + * @private + */ + value: function _placeNodesByHierarchy(distribution) { + var nodeId = undefined, + node = undefined; + this.positionedNodes = {}; + // start placing all the level 0 nodes first. Then recursively position their branches. + for (var level in distribution) { + if (distribution.hasOwnProperty(level)) { + for (nodeId in distribution[level].nodes) { + if (distribution[level].nodes.hasOwnProperty(nodeId)) { - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); + node = distribution[level].nodes[nodeId]; - // disable shadows for other elements. - this.disableShadow(ctx); + if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') { + if (node.x === undefined) { + node.x = distribution[level].distance; + } + distribution[level].distance = node.x + this.nodeSpacing; + } else { + if (node.y === undefined) { + node.y = distribution[level].distance; + } + distribution[level].distance = node.y + this.nodeSpacing; + } - ctx.stroke(); + this.positionedNodes[nodeId] = true; + this._placeBranchNodes(node.edges, node.id, distribution, level); + } + } + } + } + } + }, { + key: '_getDistribution', - this.updateBoundingBox(x, y); + /** + * This function get the distribution of levels based on hubsize + * + * @returns {Object} + * @private + */ + value: function _getDistribution() { + var distribution = {}; + var nodeId = undefined, + node = undefined; - this.labelModule.draw(ctx, x, y, selected); + // we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time. + // the fix of X is removed after the x value has been set. + for (nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + node = this.body.nodes[nodeId]; + var level = this.hierarchicalLevels[nodeId] === undefined ? 0 : this.hierarchicalLevels[nodeId]; + if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') { + node.y = this.options.hierarchical.levelSeparation * level; + node.options.fixed.y = true; + } else { + node.x = this.options.hierarchical.levelSeparation * level; + node.options.fixed.x = true; + } + if (distribution[level] === undefined) { + distribution[level] = { amount: 0, nodes: {}, distance: 0 }; + } + distribution[level].amount += 1; + distribution[level].nodes[nodeId] = node; + } + } + return distribution; } }, { - key: 'updateBoundingBox', - value: function updateBoundingBox(x, y) { - this.left = x - this.width * 0.5; - this.top = y - this.height * 0.5; + key: '_getHubSize', - this.boundingBox.left = this.left; - this.boundingBox.top = this.top; - this.boundingBox.bottom = this.top + this.height; - this.boundingBox.right = this.left + this.width; + /** + * Get the hubsize from all remaining unlevelled nodes. + * + * @returns {number} + * @private + */ + value: function _getHubSize() { + var hubSize = 0; + for (var nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + var node = this.body.nodes[nodeId]; + if (this.hierarchicalLevels[nodeId] === undefined) { + hubSize = node.edges.length < hubSize ? hubSize : node.edges.length; + } + } + } + return hubSize; } }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - var a = this.width / 2; - var b = this.height / 2; - var w = Math.sin(angle) * a; - var h = Math.cos(angle) * b; - return a * b / Math.sqrt(w * w + h * h); - } - }]); - - return Database; - })(_utilNodeBase2['default']); + key: '_determineLevelsByHubsize', - exports['default'] = Database; - module.exports = exports['default']; + /** + * this function allocates nodes in levels based on the recursive branching from the largest hubs. + * + * @param hubsize + * @private + */ + value: function _determineLevelsByHubsize() { + var nodeId = undefined, + node = undefined; + var hubSize = 1; -/***/ }, -/* 96 */ -/***/ function(module, exports, __webpack_require__) { + while (hubSize > 0) { + // determine hubs + hubSize = this._getHubSize(); + if (hubSize === 0) break; - 'use strict'; + for (nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + node = this.body.nodes[nodeId]; + if (node.edges.length === hubSize) { + this._setLevelByHubsize(0, node); + } + } + } + } + } + }, { + key: '_setLevelByHubsize', - Object.defineProperty(exports, '__esModule', { - value: true - }); + /** + * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level. + * + * @param level + * @param edges + * @param parentId + * @private + */ + value: function _setLevelByHubsize(level, node) { + if (this.hierarchicalLevels[node.id] !== undefined) return; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + var childNode = undefined; + this.hierarchicalLevels[node.id] = level; + for (var i = 0; i < node.edges.length; i++) { + if (node.edges[i].toId === node.id) { + childNode = node.edges[i].from; + } else { + childNode = node.edges[i].to; + } + this._setLevelByHubsize(level + 1, childNode); + } + } + }, { + key: '_determineLevelsDirected', - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + /** + * this function allocates nodes in levels based on the direction of the edges + * + * @param hubsize + * @private + */ + value: function _determineLevelsDirected() { + var nodeId = undefined, + node = undefined; + var minLevel = 10000; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + // set first node to source + for (nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + node = this.body.nodes[nodeId]; + this._setLevelDirected(minLevel, node); + } + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + // get the minimum level + for (nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + minLevel = this.hierarchicalLevels[nodeId] < minLevel ? this.hierarchicalLevels[nodeId] : minLevel; + } + } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + // subtract the minimum from the set so we have a range starting from 0 + for (nodeId in this.body.nodes) { + if (this.body.nodes.hasOwnProperty(nodeId)) { + this.hierarchicalLevels[nodeId] -= minLevel; + } + } + } + }, { + key: '_setLevelDirected', - var _utilShapeBase = __webpack_require__(111); + /** + * this function is called recursively to enumerate the branched of the first node and give each node a level based on edge direction + * + * @param level + * @param edges + * @param parentId + * @private + */ + value: function _setLevelDirected(level, node) { + if (this.hierarchicalLevels[node.id] !== undefined) return; - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + var childNode = undefined; + this.hierarchicalLevels[node.id] = level; - var Diamond = (function (_ShapeBase) { - function Diamond(options, body, labelModule) { - _classCallCheck(this, Diamond); + for (var i = 0; i < node.edges.length; i++) { + if (node.edges[i].toId === node.id) { + childNode = node.edges[i].from; + this._setLevelDirected(level - 1, childNode); + } else { + childNode = node.edges[i].to; + this._setLevelDirected(level + 1, childNode); + } + } + } + }, { + key: '_placeBranchNodes', - _get(Object.getPrototypeOf(Diamond.prototype), 'constructor', this).call(this, options, body, labelModule); - } + /** + * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes + * on a X position that ensures there will be no overlap. + * + * @param edges + * @param parentId + * @param distribution + * @param parentLevel + * @private + */ + value: function _placeBranchNodes(edges, parentId, distribution, parentLevel) { + for (var i = 0; i < edges.length; i++) { + var childNode = undefined; + var parentNode = undefined; + if (edges[i].toId === parentId) { + childNode = edges[i].from; + parentNode = edges[i].to; + } else { + childNode = edges[i].to; + parentNode = edges[i].from; + } + var childNodeLevel = this.hierarchicalLevels[childNode.id]; - _inherits(Diamond, _ShapeBase); + if (this.positionedNodes[childNode.id] === undefined) { + // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here. + if (childNodeLevel > parentLevel) { + if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') { + if (childNode.x === undefined) { + childNode.x = Math.max(distribution[childNodeLevel].distance, parentNode.x); + } + distribution[childNodeLevel].distance = childNode.x + this.nodeSpacing; + this.positionedNodes[childNode.id] = true; + } else { + if (childNode.y === undefined) { + childNode.y = Math.max(distribution[childNodeLevel].distance, parentNode.y); + } + distribution[childNodeLevel].distance = childNode.y + this.nodeSpacing; + } + this.positionedNodes[childNode.id] = true; - _createClass(Diamond, [{ - key: 'resize', - value: function resize(ctx) { - this._resizeShape(); - } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'diamond', 4, x, y, selected, hover); - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - return this._distanceToBorder(angle); + if (childNode.edges.length > 1) { + this._placeBranchNodes(childNode.edges, childNode.id, distribution, childNodeLevel); + } + } + } + } } }]); - return Diamond; - })(_utilShapeBase2['default']); + return LayoutEngine; + })(); - exports['default'] = Diamond; + exports['default'] = LayoutEngine; module.exports = exports['default']; /***/ }, -/* 97 */ +/* 107 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -38590,2254 +37795,3049 @@ return /******/ (function(modules) { // webpackBootstrap var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - - var _utilShapeBase = __webpack_require__(111); - - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); - - var Dot = (function (_ShapeBase) { - function Dot(options, body, labelModule) { - _classCallCheck(this, Dot); - - _get(Object.getPrototypeOf(Dot.prototype), 'constructor', this).call(this, options, body, labelModule); - } - - _inherits(Dot, _ShapeBase); - - _createClass(Dot, [{ - key: 'resize', - value: function resize(ctx) { - this._resizeShape(); - } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'circle', 2, x, y, selected, hover); - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - return this.options.size + this.options.borderWidth; - } - }]); - - return Dot; - })(_utilShapeBase2['default']); - - exports['default'] = Dot; - module.exports = exports['default']; - -/***/ }, -/* 98 */ -/***/ function(module, exports, __webpack_require__) { + var util = __webpack_require__(7); + var Hammer = __webpack_require__(3); + var hammerUtil = __webpack_require__(30); - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + /** + * clears the toolbar div element of children + * + * @private + */ - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + var ManipulationSystem = (function () { + function ManipulationSystem(body, canvas, selectionHandler) { + var _this = this; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + _classCallCheck(this, ManipulationSystem); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + this.body = body; + this.canvas = canvas; + this.selectionHandler = selectionHandler; - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + this.editMode = false; + this.manipulationDiv = undefined; + this.editModeDiv = undefined; + this.closeDiv = undefined; - var _utilNodeBase = __webpack_require__(109); + this.manipulationHammers = []; + this.temporaryUIFunctions = {}; + this.temporaryEventFunctions = []; - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + this.touchTime = 0; + this.temporaryIds = { nodes: [], edges: [] }; + this.guiEnabled = false; + this.inMode = false; + this.selectedControlNode = undefined; - var Ellipse = (function (_NodeBase) { - function Ellipse(options, body, labelModule) { - _classCallCheck(this, Ellipse); + this.options = {}; + this.defaultOptions = { + enabled: false, + initiallyActive: false, + addNode: true, + addEdge: true, + editNode: undefined, + editEdge: true, + deleteNode: true, + deleteEdge: true, + controlNodeStyle: { + shape: 'dot', + size: 6, + color: { background: '#ff0000', border: '#3c3c3c', highlight: { background: '#07f968', border: '#3c3c3c' } }, + borderWidth: 2, + borderWidthSelected: 2 + } + }; + util.extend(this.options, this.defaultOptions); - _get(Object.getPrototypeOf(Ellipse.prototype), 'constructor', this).call(this, options, body, labelModule); + this.body.emitter.on('destroy', function () { + _this._clean(); + }); + this.body.emitter.on('_dataChanged', this._restore.bind(this)); + this.body.emitter.on('_resetData', this._restore.bind(this)); } - _inherits(Ellipse, _NodeBase); - - _createClass(Ellipse, [{ - key: 'resize', - value: function resize(ctx, selected) { - if (this.width === undefined) { - var textSize = this.labelModule.getTextSize(ctx, selected); + _createClass(ManipulationSystem, [{ + key: '_restore', - this.width = textSize.width * 1.5; - this.height = textSize.height * 2; - if (this.width < this.height) { - this.width = this.height; + /** + * If something changes in the data during editing, switch back to the initial datamanipulation state and close all edit modes. + * @private + */ + value: function _restore() { + if (this.inMode !== false) { + if (this.options.initiallyActive === true) { + this.enableEditMode(); + } else { + this.disableEditMode(); } - this.radius = 0.5 * this.width; } } }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(ctx, selected); - this.left = x - this.width * 0.5; - this.top = y - this.height * 0.5; - - var borderWidth = this.options.borderWidth; - var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - - ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; - - ctx.lineWidth = selected ? selectionLineWidth : borderWidth; - ctx.lineWidth /= this.body.view.scale; - ctx.lineWidth = Math.min(this.width, ctx.lineWidth); - - ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; - ctx.ellipse(this.left, this.top, this.width, this.height); - - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); - - // disable shadows for other elements. - this.disableShadow(ctx); + key: 'setOptions', - ctx.stroke(); + /** + * Set the Options + * @param options + */ + value: function setOptions(options, allOptions, globalOptions) { + if (allOptions !== undefined) { + if (allOptions.locale !== undefined) { + this.options.locale = allOptions.locale; + } else { + this.options.locale = globalOptions.locale; + } + if (allOptions.locales !== undefined) { + this.options.locales = allOptions.locales; + } else { + this.options.locales = globalOptions.locales; + } + } - this.updateBoundingBox(x, y); - this.labelModule.draw(ctx, x, y, selected); + if (options !== undefined) { + if (typeof options === 'boolean') { + this.options.enabled = options; + } else { + this.options.enabled = true; + util.deepExtend(this.options, options); + } + if (this.options.initiallyActive === true) { + this.editMode = true; + } + this._setup(); + } } }, { - key: 'updateBoundingBox', - value: function updateBoundingBox(x, y) { - this.left = x - this.width * 0.5; - this.top = y - this.height * 0.5; + key: 'toggleEditMode', - this.boundingBox.left = this.left; - this.boundingBox.top = this.top; - this.boundingBox.bottom = this.top + this.height; - this.boundingBox.right = this.left + this.width; + /** + * Enable or disable edit-mode. Draws the DOM required and cleans up after itself. + * + * @private + */ + value: function toggleEditMode() { + if (this.editMode === true) { + this.disableEditMode(); + } else { + this.enableEditMode(); + } } }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - var a = this.width * 0.5; - var b = this.height * 0.5; - var w = Math.sin(angle) * a; - var h = Math.cos(angle) * b; - return a * b / Math.sqrt(w * w + h * h); - } - }]); - - return Ellipse; - })(_utilNodeBase2['default']); - - exports['default'] = Ellipse; - module.exports = exports['default']; - -/***/ }, -/* 99 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); + key: 'enableEditMode', + value: function enableEditMode() { + this.editMode = true; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + this._clean(); + if (this.guiEnabled === true) { + this.manipulationDiv.style.display = 'block'; + this.closeDiv.style.display = 'block'; + this.editModeDiv.style.display = 'none'; + this.showManipulatorToolbar(); + } + } + }, { + key: 'disableEditMode', + value: function disableEditMode() { + this.editMode = false; - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + this._clean(); + if (this.guiEnabled === true) { + this.manipulationDiv.style.display = 'none'; + this.closeDiv.style.display = 'none'; + this.editModeDiv.style.display = 'block'; + this._createEditButton(); + } + } + }, { + key: 'showManipulatorToolbar', - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + /** + * Creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar. + * + * @private + */ + value: function showManipulatorToolbar() { + // restore the state of any bound functions or events, remove control nodes, restore physics + this._clean(); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + // reset global letiables + this.manipulationDOM = {}; - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + // if the gui is enabled, draw all elements. + if (this.guiEnabled === true) { + // a _restore will hide these menus + this.editMode = true; + this.manipulationDiv.style.display = 'block'; + this.closeDiv.style.display = 'block'; - var _utilNodeBase = __webpack_require__(109); + var selectedNodeCount = this.selectionHandler._getSelectedNodeCount(); + var selectedEdgeCount = this.selectionHandler._getSelectedEdgeCount(); + var selectedTotalCount = selectedNodeCount + selectedEdgeCount; + var locale = this.options.locales[this.options.locale]; + var needSeperator = false; - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + if (this.options.addNode !== false) { + this._createAddNodeButton(locale); + needSeperator = true; + } + if (this.options.addEdge !== false) { + if (needSeperator === true) { + this._createSeperator(1); + } else { + needSeperator = true; + } + this._createAddEdgeButton(locale); + } - var Icon = (function (_NodeBase) { - function Icon(options, body, labelModule) { - _classCallCheck(this, Icon); + if (selectedNodeCount === 1 && typeof this.options.editNode === 'function') { + if (needSeperator === true) { + this._createSeperator(2); + } else { + needSeperator = true; + } + this._createEditNodeButton(locale); + } else if (selectedEdgeCount === 1 && selectedNodeCount === 0 && this.options.editEdge !== false) { + if (needSeperator === true) { + this._createSeperator(3); + } else { + needSeperator = true; + } + this._createEditEdgeButton(locale); + } - _get(Object.getPrototypeOf(Icon.prototype), 'constructor', this).call(this, options, body, labelModule); - } + // remove buttons + if (selectedTotalCount !== 0) { + if (selectedNodeCount === 1 && this.options.deleteNode !== false) { + if (needSeperator === true) { + this._createSeperator(4); + } + this._createDeleteButton(locale); + } else if (selectedNodeCount === 0 && this.options.deleteEdge !== false) { + if (needSeperator === true) { + this._createSeperator(4); + } + this._createDeleteButton(locale); + } + } - _inherits(Icon, _NodeBase); + // bind the close button + this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); - _createClass(Icon, [{ - key: 'resize', - value: function resize(ctx) { - if (this.width === undefined) { - var margin = 5; - var iconSize = { - width: Number(this.options.icon.size), - height: Number(this.options.icon.size) - }; - this.width = iconSize.width + 2 * margin; - this.height = iconSize.height + 2 * margin; - this.radius = 0.5 * this.width; + // refresh this bar based on what has been selected + this._temporaryBindEvent('select', this.showManipulatorToolbar.bind(this)); } + + // redraw to show any possible changes + this.body.emitter.emit('_redraw'); } }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(ctx); - this.options.icon.size = this.options.icon.size || 50; - - this.left = x - this.width * 0.5; - this.top = y - this.height * 0.5; - this._icon(ctx, x, y, selected); + key: 'addNodeMode', - if (this.options.label !== undefined) { - var iconTextSpacing = 5; - this.labelModule.draw(ctx, x, y + this.height * 0.5 + iconTextSpacing, selected); + /** + * Create the toolbar for adding Nodes + * + * @private + */ + value: function addNodeMode() { + // when using the gui, enable edit mode if it wasnt already. + if (this.editMode !== true) { + this.enableEditMode(); } - this.updateBoundingBox(x, y); - } - }, { - key: 'updateBoundingBox', - value: function updateBoundingBox(x, y) { - this.boundingBox.top = y - this.options.icon.size * 0.5; - this.boundingBox.left = x - this.options.icon.size * 0.5; - this.boundingBox.right = x + this.options.icon.size * 0.5; - this.boundingBox.bottom = y + this.options.icon.size * 0.5; + // restore the state of any bound functions or events, remove control nodes, restore physics + this._clean(); + + this.inMode = 'addNode'; + if (this.guiEnabled === true) { + var locale = this.options.locales[this.options.locale]; + this.manipulationDOM = {}; + this._createBackButton(locale); + this._createSeperator(); + this._createDescription(locale['addDescription'] || this.options.locales['en']['addDescription']); - if (this.options.label !== undefined) { - var iconTextSpacing = 5; - 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 + iconTextSpacing); + // bind the close button + this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); } + + this._temporaryBindEvent('click', this._performAddNode.bind(this)); } }, { - key: '_icon', - value: function _icon(ctx, x, y, selected) { - var iconSize = Number(this.options.icon.size); + key: 'editNode', - if (this.options.icon.code !== undefined) { - ctx.font = (selected ? 'bold ' : '') + iconSize + 'px ' + this.options.icon.face; + /** + * call the bound function to handle the editing of the node. The node has to be selected. + * + * @private + */ + value: function editNode() { + var _this2 = this; - // draw icon - ctx.fillStyle = this.options.icon.color || 'black'; - ctx.textAlign = 'center'; - ctx.textBaseline = 'middle'; + // when using the gui, enable edit mode if it wasnt already. + if (this.editMode !== true) { + this.enableEditMode(); + } - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fillText(this.options.icon.code, x, y); + // restore the state of any bound functions or events, remove control nodes, restore physics + this._clean(); - // disable shadows for other elements. - this.disableShadow(ctx); + this.inMode = 'editNode'; + if (typeof this.options.editNode === 'function') { + var node = this.selectionHandler._getSelectedNode(); + if (node.isCluster !== true) { + var data = util.deepExtend({}, node.options, true); + data.x = node.x; + data.y = node.y; + + if (this.options.editNode.length === 2) { + this.options.editNode(data, function (finalizedData) { + if (finalizedData !== null && finalizedData !== undefined && _this2.inMode === 'editNode') { + // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { + _this2.body.data.nodes.update(finalizedData); + } + _this2.showManipulatorToolbar(); + }); + } else { + throw new Error('The function for edit does not support two arguments (data, callback)'); + } + } else { + alert(this.options.locales[this.options.locale]['editClusterError'] || this.options.locales['en']['editClusterError']); + } } else { - console.error('When using the icon shape, you need to define the code in the icon options object. This can be done per node or globally.'); + throw new Error('No function has been configured to handle the editing of nodes.'); } } }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - this._distanceToBorder(angle); - } - }]); - - return Icon; - })(_utilNodeBase2['default']); - - exports['default'] = Icon; - module.exports = exports['default']; + key: 'addEdgeMode', -/***/ }, -/* 100 */ -/***/ function(module, exports, __webpack_require__) { + /** + * create the toolbar to connect nodes + * + * @private + */ + value: function addEdgeMode() { + // when using the gui, enable edit mode if it wasnt already. + if (this.editMode !== true) { + this.enableEditMode(); + } - 'use strict'; + // restore the state of any bound functions or events, remove control nodes, restore physics + this._clean(); - Object.defineProperty(exports, '__esModule', { - value: true - }); + this.inMode = 'addEdge'; + if (this.guiEnabled === true) { + var locale = this.options.locales[this.options.locale]; + this.manipulationDOM = {}; + this._createBackButton(locale); + this._createSeperator(); + this._createDescription(locale['edgeDescription'] || this.options.locales['en']['edgeDescription']); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // bind the close button + this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); + } - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + // temporarily overload functions + this._temporaryBindUI('onTouch', this._handleConnect.bind(this)); + this._temporaryBindUI('onDragEnd', this._finishConnect.bind(this)); + this._temporaryBindUI('onDrag', this._dragControlNode.bind(this)); + this._temporaryBindUI('onRelease', this._finishConnect.bind(this)); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + this._temporaryBindUI('onDragStart', function () {}); + this._temporaryBindUI('onHold', function () {}); + } + }, { + key: 'editEdgeMode', - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * create the toolbar to edit edges + * + * @private + */ + value: function editEdgeMode() { + // when using the gui, enable edit mode if it wasnt already. + if (this.editMode !== true) { + this.enableEditMode(); + } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + // restore the state of any bound functions or events, remove control nodes, restore physics + this._clean(); - var _utilCircleImageBase = __webpack_require__(110); + this.inMode = 'editEdge'; + if (this.guiEnabled === true) { + var locale = this.options.locales[this.options.locale]; + this.manipulationDOM = {}; + this._createBackButton(locale); + this._createSeperator(); + this._createDescription(locale['editEdgeDescription'] || this.options.locales['en']['editEdgeDescription']); - var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); + // bind the close button + this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); + } - var Image = (function (_CircleImageBase) { - function Image(options, body, labelModule, imageObj) { - _classCallCheck(this, Image); + this.edgeBeingEditedId = this.selectionHandler.getSelectedEdges()[0]; + var edge = this.body.edges[this.edgeBeingEditedId]; - _get(Object.getPrototypeOf(Image.prototype), 'constructor', this).call(this, options, body, labelModule); - this.imageObj = imageObj; - } + // create control nodes + var controlNodeFrom = this._getNewTargetNode(edge.from.x, edge.from.y); + var controlNodeTo = this._getNewTargetNode(edge.to.x, edge.to.y); - _inherits(Image, _CircleImageBase); + this.temporaryIds.nodes.push(controlNodeFrom.id); + this.temporaryIds.nodes.push(controlNodeTo.id); - _createClass(Image, [{ - key: 'resize', - value: function resize() { - this._resizeImage(); - } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(); - this.left = x - this.width / 2; - this.top = y - this.height / 2; + this.body.nodes[controlNodeFrom.id] = controlNodeFrom; + this.body.nodeIndices.push(controlNodeFrom.id); + this.body.nodes[controlNodeTo.id] = controlNodeTo; + this.body.nodeIndices.push(controlNodeTo.id); - this._drawImageAtPosition(ctx); + // temporarily overload UI functions, cleaned up automatically because of _temporaryBindUI + this._temporaryBindUI('onTouch', this._controlNodeTouch.bind(this)); // used to get the position + this._temporaryBindUI('onTap', function () {}); // disabled + this._temporaryBindUI('onHold', function () {}); // disabled + this._temporaryBindUI('onDragStart', this._controlNodeDragStart.bind(this)); // used to select control node + this._temporaryBindUI('onDrag', this._controlNodeDrag.bind(this)); // used to drag control node + this._temporaryBindUI('onDragEnd', this._controlNodeDragEnd.bind(this)); // used to connect or revert control nodes + this._temporaryBindUI('onMouseMove', function () {}); // disabled - this._drawImageLabel(ctx, x, y, selected || hover); + // create function to position control nodes correctly on movement + // automatically cleaned up because we use the temporary bind + this._temporaryBindEvent('beforeDrawing', function (ctx) { + var positions = edge.edgeType.findBorderPositions(ctx); + if (controlNodeFrom.selected === false) { + controlNodeFrom.x = positions.from.x; + controlNodeFrom.y = positions.from.y; + } + if (controlNodeTo.selected === false) { + controlNodeTo.x = positions.to.x; + controlNodeTo.y = positions.to.y; + } + }); - this.updateBoundingBox(x, y); + this.body.emitter.emit('_redraw'); } }, { - key: 'updateBoundingBox', - value: function updateBoundingBox(x, y) { - this.left = x - this.width / 2; - this.top = y - this.height / 2; + key: 'deleteSelected', - this.boundingBox.top = this.top; - this.boundingBox.left = this.left; - this.boundingBox.right = this.left + this.width; - this.boundingBox.bottom = this.top + this.height; + /** + * delete everything in the selection + * + * @private + */ + value: function deleteSelected() { + var _this3 = this; - if (this.options.label !== undefined) { - 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.labelOffset); + // when using the gui, enable edit mode if it wasnt already. + if (this.editMode !== true) { + this.enableEditMode(); } - } - }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - var a = this.width / 2; - var b = this.height / 2; - var w = Math.sin(angle) * a; - var h = Math.cos(angle) * b; - return a * b / Math.sqrt(w * w + h * h); - } - }]); - - return Image; - })(_utilCircleImageBase2['default']); - - exports['default'] = Image; - module.exports = exports['default']; - -/***/ }, -/* 101 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // restore the state of any bound functions or events, remove control nodes, restore physics + this._clean(); - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + this.inMode = 'delete'; + var selectedNodes = this.selectionHandler.getSelectedNodes(); + var selectedEdges = this.selectionHandler.getSelectedEdges(); + var deleteFunction = undefined; + if (selectedNodes.length > 0) { + for (var i = 0; i < selectedNodes.length; i++) { + if (this.body.nodes[selectedNodes[i]].isCluster === true) { + alert(this.options.locales[this.options.locale]['deleteClusterError'] || this.options.locales['en']['deleteClusterError']); + return; + } + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + if (typeof this.options.deleteNode === 'function') { + deleteFunction = this.options.deleteNode; + } + } else if (selectedEdges.length > 0) { + if (typeof this.options.deleteEdge === 'function') { + deleteFunction = this.options.deleteEdge; + } + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + if (typeof deleteFunction === 'function') { + var data = { nodes: selectedNodes, edges: selectedEdges }; + if (deleteFunction.length === 2) { + deleteFunction(data, function (finalizedData) { + if (finalizedData !== null && finalizedData !== undefined && _this3.inMode === 'delete') { + // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { + _this3.body.data.edges.remove(finalizedData.edges); + _this3.body.data.nodes.remove(finalizedData.nodes); + _this3.body.emitter.emit('startSimulation'); + _this3.showManipulatorToolbar(); + } + }); + } else { + throw new Error('The function for delete does not support two arguments (data, callback)'); + } + } else { + this.body.data.edges.remove(selectedEdges); + this.body.data.nodes.remove(selectedNodes); + this.body.emitter.emit('startSimulation'); + this.showManipulatorToolbar(); + } + } + }, { + key: '_setup', - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + //********************************************** PRIVATE ***************************************// - var _utilShapeBase = __webpack_require__(111); + /** + * draw or remove the DOM + * @private + */ + value: function _setup() { + if (this.options.enabled === true) { + // Enable the GUI + this.guiEnabled = true; - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + this._createWrappers(); + if (this.editMode === false) { + this._createEditButton(); + } else { + this.showManipulatorToolbar(); + } + } else { + this._removeManipulationDOM(); - var Square = (function (_ShapeBase) { - function Square(options, body, labelModule) { - _classCallCheck(this, Square); + // disable the gui + this.guiEnabled = false; + } + } + }, { + key: '_createWrappers', - _get(Object.getPrototypeOf(Square.prototype), 'constructor', this).call(this, options, body, labelModule); - } + /** + * create the div overlays that contain the DOM + * @private + */ + value: function _createWrappers() { + // load the manipulator HTML elements. All styling done in css. + if (this.manipulationDiv === undefined) { + this.manipulationDiv = document.createElement('div'); + this.manipulationDiv.className = 'vis-manipulation'; + if (this.editMode === true) { + this.manipulationDiv.style.display = 'block'; + } else { + this.manipulationDiv.style.display = 'none'; + } + this.canvas.frame.appendChild(this.manipulationDiv); + } - _inherits(Square, _ShapeBase); + // container for the edit button. + if (this.editModeDiv === undefined) { + this.editModeDiv = document.createElement('div'); + this.editModeDiv.className = 'vis-edit-mode'; + if (this.editMode === true) { + this.editModeDiv.style.display = 'none'; + } else { + this.editModeDiv.style.display = 'block'; + } + this.canvas.frame.appendChild(this.editModeDiv); + } - _createClass(Square, [{ - key: 'resize', - value: function resize() { - this._resizeShape(); - } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'square', 2, x, y, selected, hover); + // container for the close div button + if (this.closeDiv === undefined) { + this.closeDiv = document.createElement('div'); + this.closeDiv.className = 'vis-close'; + this.closeDiv.style.display = this.manipulationDiv.style.display; + this.canvas.frame.appendChild(this.closeDiv); + } } }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - return this._distanceToBorder(angle); - } - }]); - - return Square; - })(_utilShapeBase2['default']); + key: '_getNewTargetNode', - exports['default'] = Square; - module.exports = exports['default']; + /** + * generate a new target node. Used for creating new edges and editing edges + * @param x + * @param y + * @returns {*} + * @private + */ + value: function _getNewTargetNode(x, y) { + var controlNodeStyle = util.deepExtend({}, this.options.controlNodeStyle); -/***/ }, -/* 102 */ -/***/ function(module, exports, __webpack_require__) { + controlNodeStyle.id = 'targetNode' + util.randomUUID(); + controlNodeStyle.hidden = false; + controlNodeStyle.physics = false; + controlNodeStyle.x = x; + controlNodeStyle.y = y; - 'use strict'; + return this.body.functions.createNode(controlNodeStyle); + } + }, { + key: '_createEditButton', - Object.defineProperty(exports, '__esModule', { - value: true - }); + /** + * Create the edit button + */ + value: function _createEditButton() { + // restore everything to it's original state (if applicable) + this._clean(); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // reset the manipulationDOM + this.manipulationDOM = {}; - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + // empty the editModeDiv + util.recursiveDOMDelete(this.editModeDiv); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + // create the contents for the editMode button + var locale = this.options.locales[this.options.locale]; + var button = this._createButton('editMode', 'vis-button vis-edit vis-edit-mode', locale['edit'] || this.options.locales['en']['edit']); + this.editModeDiv.appendChild(button); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + // bind a hammer listener to the button, calling the function toggleEditMode. + this._bindHammerToDiv(button, this.toggleEditMode.bind(this)); + } + }, { + key: '_clean', - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + /** + * this function cleans up after everything this module does. Temporary elements, functions and events are removed, physics restored, hammers removed. + * @private + */ + value: function _clean() { + // not in mode + this.inMode = false; - var _utilShapeBase = __webpack_require__(111); + // _clean the divs + if (this.guiEnabled === true) { + util.recursiveDOMDelete(this.editModeDiv); + util.recursiveDOMDelete(this.manipulationDiv); - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + // removes all the bindings and overloads + this._cleanManipulatorHammers(); + } - var Star = (function (_ShapeBase) { - function Star(options, body, labelModule) { - _classCallCheck(this, Star); + // remove temporary nodes and edges + this._cleanupTemporaryNodesAndEdges(); - _get(Object.getPrototypeOf(Star.prototype), 'constructor', this).call(this, options, body, labelModule); - } + // restore overloaded UI functions + this._unbindTemporaryUIs(); - _inherits(Star, _ShapeBase); + // remove the temporaryEventFunctions + this._unbindTemporaryEvents(); - _createClass(Star, [{ - key: 'resize', - value: function resize(ctx) { - this._resizeShape(); + // restore the physics if required + this.body.emitter.emit('restorePhysics'); } }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'star', 4, x, y, selected, hover); + key: '_cleanManipulatorHammers', + + /** + * Each dom element has it's own hammer. They are stored in this.manipulationHammers. This cleans them up. + * @private + */ + value: function _cleanManipulatorHammers() { + // _clean hammer bindings + if (this.manipulationHammers.length != 0) { + for (var i = 0; i < this.manipulationHammers.length; i++) { + this.manipulationHammers[i].destroy(); + } + this.manipulationHammers = []; + } } }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - return this._distanceToBorder(angle); - } - }]); - - return Star; - })(_utilShapeBase2['default']); - - exports['default'] = Star; - module.exports = exports['default']; - -/***/ }, -/* 103 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; + key: '_removeManipulationDOM', - Object.defineProperty(exports, '__esModule', { - value: true - }); + /** + * Remove all DOM elements created by this module. + * @private + */ + value: function _removeManipulationDOM() { + // removes all the bindings and overloads + this._clean(); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // empty the manipulation divs + util.recursiveDOMDelete(this.manipulationDiv); + util.recursiveDOMDelete(this.editModeDiv); + util.recursiveDOMDelete(this.closeDiv); - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + // remove the manipulation divs + if (this.manipulationDiv) { + this.canvas.frame.removeChild(this.manipulationDiv); + } + if (this.editModeDiv) { + this.canvas.frame.removeChild(this.editModeDiv); + } + if (this.closeDiv) { + this.canvas.frame.removeChild(this.manipulationDiv); + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + // set the references to undefined + this.manipulationDiv = undefined; + this.editModeDiv = undefined; + this.closeDiv = undefined; + } + }, { + key: '_createSeperator', - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * create a seperator line. the index is to differentiate in the manipulation dom + * @param index + * @private + */ + value: function _createSeperator() { + var index = arguments[0] === undefined ? 1 : arguments[0]; - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + this.manipulationDOM['seperatorLineDiv' + index] = document.createElement('div'); + this.manipulationDOM['seperatorLineDiv' + index].className = 'vis-separator-line'; + this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv' + index]); + } + }, { + key: '_createAddNodeButton', - var _utilNodeBase = __webpack_require__(109); + // ---------------------- DOM functions for buttons --------------------------// - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + value: function _createAddNodeButton(locale) { + var button = this._createButton('addNode', 'vis-button vis-add', locale['addNode'] || this.options.locales['en']['addNode']); + this.manipulationDiv.appendChild(button); + this._bindHammerToDiv(button, this.addNodeMode.bind(this)); + } + }, { + key: '_createAddEdgeButton', + value: function _createAddEdgeButton(locale) { + var button = this._createButton('addEdge', 'vis-button vis-connect', locale['addEdge'] || this.options.locales['en']['addEdge']); + this.manipulationDiv.appendChild(button); + this._bindHammerToDiv(button, this.addEdgeMode.bind(this)); + } + }, { + key: '_createEditNodeButton', + value: function _createEditNodeButton(locale) { + var button = this._createButton('editNode', 'vis-button vis-edit', locale['editNode'] || this.options.locales['en']['editNode']); + this.manipulationDiv.appendChild(button); + this._bindHammerToDiv(button, this.editNode.bind(this)); + } + }, { + key: '_createEditEdgeButton', + value: function _createEditEdgeButton(locale) { + var button = this._createButton('editEdge', 'vis-button vis-edit', locale['editEdge'] || this.options.locales['en']['editEdge']); + this.manipulationDiv.appendChild(button); + this._bindHammerToDiv(button, this.editEdgeMode.bind(this)); + } + }, { + key: '_createDeleteButton', + value: function _createDeleteButton(locale) { + var button = this._createButton('delete', 'vis-button vis-delete', locale['del'] || this.options.locales['en']['del']); + this.manipulationDiv.appendChild(button); + this._bindHammerToDiv(button, this.deleteSelected.bind(this)); + } + }, { + key: '_createBackButton', + value: function _createBackButton(locale) { + var button = this._createButton('back', 'vis-button vis-back', locale['back'] || this.options.locales['en']['back']); + this.manipulationDiv.appendChild(button); + this._bindHammerToDiv(button, this.showManipulatorToolbar.bind(this)); + } + }, { + key: '_createButton', + value: function _createButton(id, className, label) { + var labelClassName = arguments[3] === undefined ? 'vis-label' : arguments[3]; - var Text = (function (_NodeBase) { - function Text(options, body, labelModule) { - _classCallCheck(this, Text); + this.manipulationDOM[id + 'Div'] = document.createElement('div'); + this.manipulationDOM[id + 'Div'].className = className; + this.manipulationDOM[id + 'Label'] = document.createElement('div'); + this.manipulationDOM[id + 'Label'].className = labelClassName; + this.manipulationDOM[id + 'Label'].innerHTML = label; + this.manipulationDOM[id + 'Div'].appendChild(this.manipulationDOM[id + 'Label']); + return this.manipulationDOM[id + 'Div']; + } + }, { + key: '_createDescription', + value: function _createDescription(label) { + this.manipulationDiv.appendChild(this._createButton('description', 'vis-button vis-none', label)); + } + }, { + key: '_temporaryBindEvent', - _get(Object.getPrototypeOf(Text.prototype), 'constructor', this).call(this, options, body, labelModule); - } + // -------------------------- End of DOM functions for buttons ------------------------------// - _inherits(Text, _NodeBase); + /** + * this binds an event until cleanup by the clean functions. + * @param event + * @param newFunction + * @private + */ + value: function _temporaryBindEvent(event, newFunction) { + this.temporaryEventFunctions.push({ event: event, boundFunction: newFunction }); + this.body.emitter.on(event, newFunction); + } + }, { + key: '_temporaryBindUI', - _createClass(Text, [{ - key: 'resize', - value: function resize(ctx, selected) { - if (this.width === undefined) { - var margin = 5; - var textSize = this.labelModule.getTextSize(ctx, selected); - this.width = textSize.width + 2 * margin; - this.height = textSize.height + 2 * margin; - this.radius = 0.5 * this.width; + /** + * this overrides an UI function until cleanup by the clean function + * @param UIfunctionName + * @param newFunction + * @private + */ + value: function _temporaryBindUI(UIfunctionName, newFunction) { + if (this.body.eventListeners[UIfunctionName] !== undefined) { + this.temporaryUIFunctions[UIfunctionName] = this.body.eventListeners[UIfunctionName]; + this.body.eventListeners[UIfunctionName] = newFunction; + } else { + throw new Error('This UI function does not exist. Typo? You tried: ' + UIfunctionName + ' possible are: ' + JSON.stringify(Object.keys(this.body.eventListeners))); } } }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this.resize(ctx, selected || hover); - this.left = x - this.width / 2; - this.top = y - this.height / 2; - - // draw shadow if enabled - this.enableShadow(ctx); - this.labelModule.draw(ctx, x, y, selected || hover); - - // disable shadows for other elements. - this.disableShadow(ctx); + key: '_unbindTemporaryUIs', - this.updateBoundingBox(x, y); + /** + * Restore the overridden UI functions to their original state. + * + * @private + */ + value: function _unbindTemporaryUIs() { + for (var functionName in this.temporaryUIFunctions) { + if (this.temporaryUIFunctions.hasOwnProperty(functionName)) { + this.body.eventListeners[functionName] = this.temporaryUIFunctions[functionName]; + delete this.temporaryUIFunctions[functionName]; + } + } + this.temporaryUIFunctions = {}; } }, { - key: 'updateBoundingBox', - value: function updateBoundingBox(x, y) { - this.left = x - this.width / 2; - this.top = y - this.height / 2; + key: '_unbindTemporaryEvents', - this.boundingBox.top = this.top; - this.boundingBox.left = this.left; - this.boundingBox.right = this.left + this.width; - this.boundingBox.bottom = this.top + this.height; + /** + * Unbind the events created by _temporaryBindEvent + * @private + */ + value: function _unbindTemporaryEvents() { + for (var i = 0; i < this.temporaryEventFunctions.length; i++) { + var eventName = this.temporaryEventFunctions[i].event; + var boundFunction = this.temporaryEventFunctions[i].boundFunction; + this.body.emitter.off(eventName, boundFunction); + } + this.temporaryEventFunctions = []; } }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - return this._distanceToBorder(angle); - } - }]); - - return Text; - })(_utilNodeBase2['default']); + key: '_bindHammerToDiv', - exports['default'] = Text; - module.exports = exports['default']; + /** + * Bind an hammer instance to a DOM element. + * @param domElement + * @param funct + */ + value: function _bindHammerToDiv(domElement, boundFunction) { + var hammer = new Hammer(domElement, {}); + hammerUtil.onTouch(hammer, boundFunction); + this.manipulationHammers.push(hammer); + } + }, { + key: '_cleanupTemporaryNodesAndEdges', -/***/ }, -/* 104 */ -/***/ function(module, exports, __webpack_require__) { + /** + * Neatly clean up temporary edges and nodes + * @private + */ + value: function _cleanupTemporaryNodesAndEdges() { + // _clean temporary edges + for (var i = 0; i < this.temporaryIds.edges.length; i++) { + this.body.edges[this.temporaryIds.edges[i]].disconnect(); + delete this.body.edges[this.temporaryIds.edges[i]]; + var indexTempEdge = this.body.edgeIndices.indexOf(this.temporaryIds.edges[i]); + if (indexTempEdge !== -1) { + this.body.edgeIndices.splice(indexTempEdge, 1); + } + } - 'use strict'; + // _clean temporary nodes + for (var i = 0; i < this.temporaryIds.nodes.length; i++) { + delete this.body.nodes[this.temporaryIds.nodes[i]]; + var indexTempNode = this.body.nodeIndices.indexOf(this.temporaryIds.nodes[i]); + if (indexTempNode !== -1) { + this.body.nodeIndices.splice(indexTempNode, 1); + } + } - Object.defineProperty(exports, '__esModule', { - value: true - }); + this.temporaryIds = { nodes: [], edges: [] }; + } + }, { + key: '_controlNodeTouch', - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // ------------------------------------------ EDIT EDGE FUNCTIONS -----------------------------------------// - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + /** + * the touch is used to get the position of the initial click + * @param event + * @private + */ + value: function _controlNodeTouch(event) { + this.selectionHandler.unselectAll(); + this.lastTouch = this.body.functions.getPointer(event.center); + this.lastTouch.translation = util.extend({}, this.body.view.translation); // copy the object + } + }, { + key: '_controlNodeDragStart', - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + /** + * the drag start is used to mark one of the control nodes as selected. + * @param event + * @private + */ + value: function _controlNodeDragStart(event) { + var pointer = this.lastTouch; + var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); + var from = this.body.nodes[this.temporaryIds.nodes[0]]; + var to = this.body.nodes[this.temporaryIds.nodes[1]]; + var edge = this.body.edges[this.edgeBeingEditedId]; + this.selectedControlNode = undefined; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + var fromSelect = from.isOverlappingWith(pointerObj); + var toSelect = to.isOverlappingWith(pointerObj); - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + if (fromSelect === true) { + this.selectedControlNode = from; + edge.edgeType.from = from; + } else if (toSelect === true) { + this.selectedControlNode = to; + edge.edgeType.to = to; + } - var _utilShapeBase = __webpack_require__(111); + this.body.emitter.emit('_redraw'); + } + }, { + key: '_controlNodeDrag', - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + /** + * dragging the control nodes or the canvas + * @param event + * @private + */ + value: function _controlNodeDrag(event) { + this.body.emitter.emit('disablePhysics'); + var pointer = this.body.functions.getPointer(event.center); + var pos = this.canvas.DOMtoCanvas(pointer); - var Triangle = (function (_ShapeBase) { - function Triangle(options, body, labelModule) { - _classCallCheck(this, Triangle); + if (this.selectedControlNode !== undefined) { + this.selectedControlNode.x = pos.x; + this.selectedControlNode.y = pos.y; + } else { + // if the drag was not started properly because the click started outside the network div, start it now. + var diffX = pointer.x - this.lastTouch.x; + var diffY = pointer.y - this.lastTouch.y; + this.body.view.translation = { x: this.lastTouch.translation.x + diffX, y: this.lastTouch.translation.y + diffY }; + } + this.body.emitter.emit('_redraw'); + } + }, { + key: '_controlNodeDragEnd', - _get(Object.getPrototypeOf(Triangle.prototype), 'constructor', this).call(this, options, body, labelModule); - } + /** + * connecting or restoring the control nodes. + * @param event + * @private + */ + value: function _controlNodeDragEnd(event) { + var pointer = this.body.functions.getPointer(event.center); + var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); + var edge = this.body.edges[this.edgeBeingEditedId]; - _inherits(Triangle, _ShapeBase); + var overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj); + var node = undefined; + for (var i = overlappingNodeIds.length - 1; i >= 0; i--) { + if (overlappingNodeIds[i] !== this.selectedControlNode.id) { + node = this.body.nodes[overlappingNodeIds[i]]; + break; + } + } - _createClass(Triangle, [{ - key: 'resize', - value: function resize(ctx) { - this._resizeShape(); - } - }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'triangle', 3, x, y, selected, hover); + // perform the connection + if (node !== undefined && this.selectedControlNode !== undefined) { + if (node.isCluster === true) { + alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']); + } else { + var from = this.body.nodes[this.temporaryIds.nodes[0]]; + if (this.selectedControlNode.id === from.id) { + this._performEditEdge(node.id, edge.to.id); + } else { + this._performEditEdge(edge.from.id, node.id); + } + } + } else { + edge.updateEdgeType(); + this.body.emitter.emit('restorePhysics'); + } + this.body.emitter.emit('_redraw'); } }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - return this._distanceToBorder(angle); - } - }]); + key: '_handleConnect', - return Triangle; - })(_utilShapeBase2['default']); + // ------------------------------------ END OF EDIT EDGE FUNCTIONS -----------------------------------------// - exports['default'] = Triangle; - module.exports = exports['default']; + // ------------------------------------------- ADD EDGE FUNCTIONS -----------------------------------------// + /** + * the function bound to the selection event. It checks if you want to connect a cluster and changes the description + * to walk the user through the process. + * + * @private + */ + value: function _handleConnect(event) { + // check to avoid double fireing of this function. + if (new Date().valueOf() - this.touchTime > 100) { + this.lastTouch = this.body.functions.getPointer(event.center); + this.lastTouch.translation = util.extend({}, this.body.view.translation); // copy the object -/***/ }, -/* 105 */ -/***/ function(module, exports, __webpack_require__) { + var pointer = this.lastTouch; + var node = this.selectionHandler.getNodeAt(pointer); - 'use strict'; + if (node !== undefined) { + if (node.isCluster === true) { + alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']); + } else { + // create a node the temporary line can look at + var targetNode = this._getNewTargetNode(node.x, node.y); + this.body.nodes[targetNode.id] = targetNode; + this.body.nodeIndices.push(targetNode.id); - Object.defineProperty(exports, '__esModule', { - value: true - }); + // create a temporary edge + var connectionEdge = this.body.functions.createEdge({ + id: 'connectionEdge' + util.randomUUID(), + from: node.id, + to: targetNode.id, + physics: false, + smooth: { + enabled: true, + type: 'continuous', + roundness: 0.5 + } + }); + this.body.edges[connectionEdge.id] = connectionEdge; + this.body.edgeIndices.push(connectionEdge.id); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + this.temporaryIds.nodes.push(targetNode.id); + this.temporaryIds.edges.push(connectionEdge.id); + } + } + this.touchTime = new Date().valueOf(); + } + } + }, { + key: '_dragControlNode', + value: function _dragControlNode(event) { + var pointer = this.body.functions.getPointer(event.center); + if (this.temporaryIds.nodes[0] !== undefined) { + var targetNode = this.body.nodes[this.temporaryIds.nodes[0]]; // there is only one temp node in the add edge mode. + targetNode.x = this.canvas._XconvertDOMtoCanvas(pointer.x); + targetNode.y = this.canvas._YconvertDOMtoCanvas(pointer.y); + this.body.emitter.emit('_redraw'); + } else { + var diffX = pointer.x - this.lastTouch.x; + var diffY = pointer.y - this.lastTouch.y; + this.body.view.translation = { x: this.lastTouch.translation.x + diffX, y: this.lastTouch.translation.y + diffY }; + } + } + }, { + key: '_finishConnect', - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + /** + * Connect the new edge to the target if one exists, otherwise remove temp line + * @param event + * @private + */ + value: function _finishConnect(event) { + var pointer = this.body.functions.getPointer(event.center); + var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + // remember the edge id + var connectFromId = undefined; + if (this.temporaryIds.edges[0] !== undefined) { + connectFromId = this.body.edges[this.temporaryIds.edges[0]].fromId; + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + // get the overlapping node but NOT the temporary node; + var overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj); + var node = undefined; + for (var i = overlappingNodeIds.length - 1; i >= 0; i--) { + // if the node id is NOT a temporary node, accept the node. + if (this.temporaryIds.nodes.indexOf(overlappingNodeIds[i]) === -1) { + node = this.body.nodes[overlappingNodeIds[i]]; + break; + } + } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + // clean temporary nodes and edges. + this._cleanupTemporaryNodesAndEdges(); - var _utilShapeBase = __webpack_require__(111); + // perform the connection + if (node !== undefined) { + if (node.isCluster === true) { + alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']); + } else { + if (this.body.nodes[connectFromId] !== undefined && this.body.nodes[node.id] !== undefined) { + this._performAddEdge(connectFromId, node.id); + } + } + } + this.body.emitter.emit('_redraw'); + } + }, { + key: '_performAddNode', - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + // --------------------------------------- END OF ADD EDGE FUNCTIONS -------------------------------------// - var TriangleDown = (function (_ShapeBase) { - function TriangleDown(options, body, labelModule) { - _classCallCheck(this, TriangleDown); + // ------------------------------ Performing all the actual data manipulation ------------------------// - _get(Object.getPrototypeOf(TriangleDown.prototype), 'constructor', this).call(this, options, body, labelModule); - } + /** + * Adds a node on the specified location + */ + value: function _performAddNode(clickData) { + var _this4 = this; - _inherits(TriangleDown, _ShapeBase); + var defaultData = { + id: util.randomUUID(), + x: clickData.pointer.canvas.x, + y: clickData.pointer.canvas.y, + label: 'new' + }; - _createClass(TriangleDown, [{ - key: 'resize', - value: function resize(ctx) { - this._resizeShape(); + if (typeof this.options.addNode === 'function') { + if (this.options.addNode.length === 2) { + this.options.addNode(defaultData, function (finalizedData) { + if (finalizedData !== null && finalizedData !== undefined && _this4.inMode === 'addNode') { + // if for whatever reason the mode has changes (due to dataset change) disregard the callback + _this4.body.data.nodes.add(finalizedData); + _this4.showManipulatorToolbar(); + } + }); + } else { + throw new Error('The function for add does not support two arguments (data,callback)'); + this.showManipulatorToolbar(); + } + } else { + this.body.data.nodes.add(defaultData); + this.showManipulatorToolbar(); + } } }, { - key: 'draw', - value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'triangleDown', 3, x, y, selected, hover); + key: '_performAddEdge', + + /** + * connect two nodes with a new edge. + * + * @private + */ + value: function _performAddEdge(sourceNodeId, targetNodeId) { + var _this5 = this; + + var defaultData = { from: sourceNodeId, to: targetNodeId }; + if (typeof this.options.addEdge === 'function') { + if (this.options.addEdge.length === 2) { + this.options.addEdge(defaultData, function (finalizedData) { + if (finalizedData !== null && finalizedData !== undefined && _this5.inMode === 'addEdge') { + // if for whatever reason the mode has changes (due to dataset change) disregard the callback + _this5.body.data.edges.add(finalizedData); + _this5.selectionHandler.unselectAll(); + _this5.showManipulatorToolbar(); + } + }); + } else { + throw new Error('The function for connect does not support two arguments (data,callback)'); + } + } else { + this.body.data.edges.add(defaultData); + this.selectionHandler.unselectAll(); + this.showManipulatorToolbar(); + } } }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - return this._distanceToBorder(angle); + key: '_performEditEdge', + + /** + * connect two nodes with a new edge. + * + * @private + */ + value: function _performEditEdge(sourceNodeId, targetNodeId) { + var _this6 = this; + + var defaultData = { id: this.edgeBeingEditedId, from: sourceNodeId, to: targetNodeId }; + if (typeof this.options.editEdge === 'function') { + if (this.options.editEdge.length === 2) { + this.options.editEdge(defaultData, function (finalizedData) { + if (finalizedData === null || finalizedData === undefined || _this6.inMode !== 'editEdge') { + // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { + _this6.body.edges[defaultData.id].updateEdgeType(); + _this6.body.emitter.emit('_redraw'); + } else { + _this6.body.data.edges.update(finalizedData); + _this6.selectionHandler.unselectAll(); + _this6.showManipulatorToolbar(); + } + }); + } else { + throw new Error('The function for edit does not support two arguments (data, callback)'); + } + } else { + this.body.data.edges.update(defaultData); + this.selectionHandler.unselectAll(); + this.showManipulatorToolbar(); + } } }]); - return TriangleDown; - })(_utilShapeBase2['default']); + return ManipulationSystem; + })(); - exports['default'] = TriangleDown; + exports['default'] = ManipulationSystem; module.exports = exports['default']; /***/ }, -/* 106 */ +/* 108 */ /***/ function(module, exports, __webpack_require__) { + /** + * This object contains all possible options. It will check if the types are correct, if required if the option is one + * of the allowed values. + * + * __any__ means that the name of the property does not matter. + * __type__ is a required field for all objects and contains the allowed types of all objects + */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); + var string = 'string'; + var boolean = 'boolean'; + var number = 'number'; + var array = 'array'; + var object = 'object'; // should only be in a __type__ property + var dom = 'dom'; + var fn = 'function'; + var undef = 'undefined'; + var any = 'any'; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - - var _utilBezierEdgeBase = __webpack_require__(112); - - var _utilBezierEdgeBase2 = _interopRequireDefault(_utilBezierEdgeBase); - - var BezierEdgeDynamic = (function (_BezierEdgeBase) { - function BezierEdgeDynamic(options, body, labelModule) { - _classCallCheck(this, BezierEdgeDynamic); + var allOptions = { + configure: { + enabled: { boolean: boolean }, + filter: { boolean: boolean, string: string, array: array, fn: fn }, + container: { dom: dom }, + showButton: { boolean: boolean }, + __type__: { object: object, boolean: boolean, string: string, array: array, fn: fn } + }, + edges: { + arrows: { + to: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } }, + middle: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } }, + from: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } }, + __type__: { string: ['from', 'to', 'middle'], object: object } + }, + color: { + color: { string: string }, + highlight: { string: string }, + hover: { string: string }, + inherit: { string: ['from', 'to', 'both'], boolean: boolean }, + opacity: { number: number }, + __type__: { object: object, string: string } + }, + dashes: { boolean: boolean, array: array }, + font: { + color: { string: string }, + size: { number: number }, // px + face: { string: string }, + background: { string: string }, + strokeWidth: { number: number }, // px + strokeColor: { string: string }, + align: { string: ['horizontal', 'top', 'middle', 'bottom'] }, + __type__: { object: object, string: string } + }, + hidden: { boolean: boolean }, + hoverWidth: { fn: fn, number: number }, + label: { string: string, undef: undef }, + length: { number: number, undef: undef }, + physics: { boolean: boolean }, + scaling: { + min: { number: number }, + max: { number: number }, + label: { + enabled: { boolean: boolean }, + min: { number: number }, + max: { number: number }, + maxVisible: { number: number }, + drawThreshold: { number: number }, + __type__: { object: object, boolean: boolean } + }, + customScalingFunction: { fn: fn }, + __type__: { object: object } + }, + selectionWidth: { fn: fn, number: number }, + selfReferenceSize: { number: number }, + shadow: { + enabled: { boolean: boolean }, + size: { number: number }, + x: { number: number }, + y: { number: number }, + __type__: { object: object, boolean: boolean } + }, + smooth: { + enabled: { boolean: boolean }, + type: { string: ['dynamic', 'continuous', 'discrete', 'diagonalCross', 'straightCross', 'horizontal', 'vertical', 'curvedCW', 'curvedCCW'] }, + roundness: { number: number }, + __type__: { object: object, boolean: boolean } + }, + title: { string: string, undef: undef }, + width: { number: number }, + value: { number: number, undef: undef }, + __type__: { object: object } + }, + groups: { + useDefaultGroups: { boolean: boolean }, + __any__: 'get from nodes, will be overwritten below', + __type__: { object: object } + }, + interaction: { + dragNodes: { boolean: boolean }, + dragView: { boolean: boolean }, + hideEdgesOnDrag: { boolean: boolean }, + hideNodesOnDrag: { boolean: boolean }, + hover: { boolean: boolean }, + keyboard: { + enabled: { boolean: boolean }, + speed: { x: { number: number }, y: { number: number }, zoom: { number: number }, __type__: { object: object } }, + bindToWindow: { boolean: boolean }, + __type__: { object: object, boolean: boolean } + }, + multiselect: { boolean: boolean }, + navigationButtons: { boolean: boolean }, + selectable: { boolean: boolean }, + selectConnectedEdges: { boolean: boolean }, + hoverConnectedEdges: { boolean: boolean }, + tooltipDelay: { number: number }, + zoomView: { boolean: boolean }, + __type__: { object: object } + }, + layout: { + randomSeed: { undef: undef, number: number }, + hierarchical: { + enabled: { boolean: boolean }, + levelSeparation: { number: number }, + direction: { string: ['UD', 'DU', 'LR', 'RL'] }, // UD, DU, LR, RL + sortMethod: { string: ['hubsize', 'directed'] }, // hubsize, directed + __type__: { object: object, boolean: boolean } + }, + __type__: { object: object } + }, + manipulation: { + enabled: { boolean: boolean }, + initiallyActive: { boolean: boolean }, + addNode: { boolean: boolean, fn: fn }, + addEdge: { boolean: boolean, fn: fn }, + editNode: { fn: fn }, + editEdge: { boolean: boolean, fn: fn }, + deleteNode: { boolean: boolean, fn: fn }, + deleteEdge: { boolean: boolean, fn: fn }, + controlNodeStyle: 'get from nodes, will be overwritten below', + __type__: { object: object, boolean: boolean } + }, + nodes: { + borderWidth: { number: number }, + borderWidthSelected: { number: number, undef: undef }, + brokenImage: { string: string, undef: undef }, + color: { + border: { string: string }, + background: { string: string }, + highlight: { + border: { string: string }, + background: { string: string }, + __type__: { object: object, string: string } + }, + hover: { + border: { string: string }, + background: { string: string }, + __type__: { object: object, string: string } + }, + __type__: { object: object, string: string } + }, + fixed: { + x: { boolean: boolean }, + y: { boolean: boolean }, + __type__: { object: object, boolean: boolean } + }, + font: { + color: { string: string }, + size: { number: number }, // px + face: { string: string }, + background: { string: string }, + strokeWidth: { number: number }, // px + strokeColor: { string: string }, + __type__: { object: object, string: string } + }, + group: { string: string, number: number, undef: undef }, + hidden: { boolean: boolean }, + icon: { + face: { string: string }, + code: { string: string }, //'\uf007', + size: { number: number }, //50, + color: { string: string }, + __type__: { object: object } + }, + id: { string: string, number: number }, + image: { string: string, undef: undef }, // --> URL + label: { string: string, undef: undef }, + level: { number: number, undef: undef }, + mass: { number: number }, + physics: { boolean: boolean }, + scaling: { + min: { number: number }, + max: { number: number }, + label: { + enabled: { boolean: boolean }, + min: { number: number }, + max: { number: number }, + maxVisible: { number: number }, + drawThreshold: { number: number }, + __type__: { object: object, boolean: boolean } + }, + customScalingFunction: { fn: fn }, + __type__: { object: object } + }, + shadow: { + enabled: { boolean: boolean }, + size: { number: number }, + x: { number: number }, + y: { number: number }, + __type__: { object: object, boolean: boolean } + }, + shape: { string: ['ellipse', 'circle', 'database', 'box', 'text', 'image', 'circularImage', 'diamond', 'dot', 'star', 'triangle', 'triangleDown', 'square', 'icon'] }, + size: { number: number }, + title: { string: string, undef: undef }, + value: { number: number, undef: undef }, + x: { number: number }, + y: { number: number }, + __type__: { object: object } + }, + physics: { + barnesHut: { + gravitationalConstant: { number: number }, + centralGravity: { number: number }, + springLength: { number: number }, + springConstant: { number: number }, + damping: { number: number }, + avoidOverlap: { number: number }, + __type__: { object: object } + }, + forceAtlas2Based: { + gravitationalConstant: { number: number }, + centralGravity: { number: number }, + springLength: { number: number }, + springConstant: { number: number }, + damping: { number: number }, + avoidOverlap: { number: number }, + __type__: { object: object } + }, + repulsion: { + centralGravity: { number: number }, + springLength: { number: number }, + springConstant: { number: number }, + nodeDistance: { number: number }, + damping: { number: number }, + __type__: { object: object } + }, + hierarchicalRepulsion: { + centralGravity: { number: number }, + springLength: { number: number }, + springConstant: { number: number }, + nodeDistance: { number: number }, + damping: { number: number }, + __type__: { object: object } + }, + maxVelocity: { number: number }, + minVelocity: { number: number }, // px/s + solver: { string: ['barnesHut', 'repulsion', 'hierarchicalRepulsion', 'forceAtlas2Based'] }, + stabilization: { + enabled: { boolean: boolean }, + iterations: { number: number }, // maximum number of iteration to stabilize + updateInterval: { number: number }, + onlyDynamicEdges: { boolean: boolean }, + fit: { boolean: boolean }, + __type__: { object: object, boolean: boolean } + }, + timestep: { number: number }, + __type__: { object: object, boolean: boolean } + }, - //this.via = undefined; // Here for completeness but not allowed to defined before super() is invoked. - _get(Object.getPrototypeOf(BezierEdgeDynamic.prototype), 'constructor', this).call(this, options, body, labelModule); // --> this calls the setOptions below - } + //globals : + autoResize: { boolean: boolean }, + clickToUse: { boolean: boolean }, + locale: { string: string }, + locales: { + __any__: { object: object }, + __type__: { object: object } + }, + height: { string: string }, + width: { string: string }, + __type__: { object: object } + }; - _inherits(BezierEdgeDynamic, _BezierEdgeBase); + allOptions.groups.__any__ = allOptions.nodes; + allOptions.manipulation.controlNodeStyle = allOptions.nodes; - _createClass(BezierEdgeDynamic, [{ - key: 'setOptions', - value: function setOptions(options) { - this.options = options; - this.id = this.options.id; - this.setupSupportNode(); - this.connect(); - } - }, { - key: 'connect', - value: function connect() { - this.from = this.body.nodes[this.options.from]; - this.to = this.body.nodes[this.options.to]; - if (this.from === undefined || this.to === undefined) { - this.via.setOptions({ physics: false }); - } else { - // fix weird behaviour where a selfreferencing node has physics enabled - if (this.from.id === this.to.id) { - this.via.setOptions({ physics: false }); - } else { - this.via.setOptions({ physics: true }); - } - } - } - }, { - key: 'cleanup', - value: function cleanup() { - if (this.via !== undefined) { - delete this.body.nodes[this.via.id]; - this.via = undefined; - return true; + var configureOptions = { + nodes: { + borderWidth: [1, 0, 10, 1], + borderWidthSelected: [2, 0, 10, 1], + color: { + border: ['color', '#2B7CE9'], + background: ['color', '#97C2FC'], + highlight: { + border: ['color', '#2B7CE9'], + background: ['color', '#D2E5FF'] + }, + hover: { + border: ['color', '#2B7CE9'], + background: ['color', '#D2E5FF'] } - return false; - } - }, { - key: 'togglePhysics', - value: function togglePhysics(status) { - this.via.setOptions({ physics: status }); - } - }, { - key: 'setupSupportNode', - - /** - * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but - * are used for the force calculation. - * - * The changed data is not called, if needed, it is returned by the main edge constructor. - * @private - */ - value: function setupSupportNode() { - if (this.via === undefined) { - var nodeId = 'edgeId:' + this.id; - var node = this.body.functions.createNode({ - id: nodeId, - shape: 'circle', - physics: true, - hidden: true - }); - this.body.nodes[nodeId] = node; - this.via = node; - this.via.parentEdgeId = this.id; - this.positionBezierNode(); + }, + fixed: { + x: false, + y: false + }, + font: { + color: ['color', '#343434'], + size: [14, 0, 100, 1], // px + face: ['arial', 'verdana', 'tahoma'], + background: ['color', 'none'], + strokeWidth: [0, 0, 50, 1], // px + strokeColor: ['color', '#ffffff'] + }, + //group: 'string', + hidden: false, + //icon: { + // face: 'string', //'FontAwesome', + // code: 'string', //'\uf007', + // size: [50, 0, 200, 1], //50, + // color: ['color','#2B7CE9'] //'#aa00ff' + //}, + //image: 'string', // --> URL + physics: true, + scaling: { + min: [10, 0, 200, 1], + max: [30, 0, 200, 1], + label: { + enabled: false, + min: [14, 0, 200, 1], + max: [30, 0, 200, 1], + maxVisible: [30, 0, 200, 1], + drawThreshold: [5, 0, 20, 1] } - } - }, { - key: 'positionBezierNode', - value: function positionBezierNode() { - if (this.via !== undefined && this.from !== undefined && this.to !== undefined) { - this.via.x = 0.5 * (this.from.x + this.to.x); - this.via.y = 0.5 * (this.from.y + this.to.y); - } else if (this.via !== undefined) { - this.via.x = 0; - this.via.y = 0; + }, + shadow: { + enabled: false, + size: [10, 0, 20, 1], + x: [5, -30, 30, 1], + y: [5, -30, 30, 1] + }, + shape: ['ellipse', 'box', 'circle', 'database', 'diamond', 'dot', 'square', 'star', 'text', 'triangle', 'triangleDown'], + size: [25, 0, 200, 1] + }, + edges: { + arrows: { + to: { enabled: false, scaleFactor: [1, 0, 3, 0.05] }, // boolean / {arrowScaleFactor:1} / {enabled: false, arrowScaleFactor:1} + middle: { enabled: false, scaleFactor: [1, 0, 3, 0.05] }, + from: { enabled: false, scaleFactor: [1, 0, 3, 0.05] } + }, + color: { + color: ['color', '#848484'], + highlight: ['color', '#848484'], + hover: ['color', '#848484'], + inherit: ['from', 'to', 'both', true, false], + opacity: [1, 0, 1, 0.05] + }, + dashes: false, + font: { + color: ['color', '#343434'], + size: [14, 0, 100, 1], // px + face: ['arial', 'verdana', 'tahoma'], + background: ['color', 'none'], + strokeWidth: [2, 0, 50, 1], // px + strokeColor: ['color', '#ffffff'], + align: ['horizontal', 'top', 'middle', 'bottom'] + }, + hidden: false, + hoverWidth: [1.5, 0, 5, 0.1], + physics: true, + scaling: { + min: [1, 0, 100, 1], + max: [15, 0, 100, 1], + label: { + enabled: true, + min: [14, 0, 200, 1], + max: [30, 0, 200, 1], + maxVisible: [30, 0, 200, 1], + drawThreshold: [5, 0, 20, 1] } + }, + selectionWidth: [1.5, 0, 5, 0.1], + selfReferenceSize: [20, 0, 200, 1], + shadow: { + enabled: false, + size: [10, 0, 20, 1], + x: [5, -30, 30, 1], + y: [5, -30, 30, 1] + }, + smooth: { + enabled: true, + type: ['dynamic', 'continuous', 'discrete', 'diagonalCross', 'straightCross', 'horizontal', 'vertical', 'curvedCW', 'curvedCCW'], + roundness: [0.5, 0, 1, 0.05] + }, + width: [1, 0, 30, 1] + }, + layout: { + //randomSeed: [0, 0, 500, 1], + hierarchical: { + enabled: false, + levelSeparation: [150, 20, 500, 5], + direction: ['UD', 'DU', 'LR', 'RL'], // UD, DU, LR, RL + sortMethod: ['hubsize', 'directed'] // hubsize, directed } - }, { - key: '_line', - - /** - * Draw a line between two nodes - * @param {CanvasRenderingContext2D} ctx - * @private - */ - value: function _line(ctx) { - // draw a straight line - ctx.beginPath(); - ctx.moveTo(this.from.x, this.from.y); - ctx.quadraticCurveTo(this.via.x, this.via.y, this.to.x, this.to.y); - // draw shadow if enabled - this.enableShadow(ctx); - ctx.stroke(); - this.disableShadow(ctx); - return this.via; - } - }, { - key: 'getPoint', - - /** - * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way - * @param percentage - * @param via - * @returns {{x: number, y: number}} - * @private - */ - value: function getPoint(percentage) { - var t = percentage; - var x = Math.pow(1 - t, 2) * this.from.x + 2 * t * (1 - t) * this.via.x + Math.pow(t, 2) * this.to.x; - var y = Math.pow(1 - t, 2) * this.from.y + 2 * t * (1 - t) * this.via.y + Math.pow(t, 2) * this.to.y; - - return { x: x, y: y }; - } - }, { - key: '_findBorderPosition', - value: function _findBorderPosition(nearNode, ctx) { - return this._findBorderPositionBezier(nearNode, ctx, this.via); - } - }, { - key: '_getDistanceToEdge', - value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) { - // x3,y3 is the point - return this._getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, this.via); - } - }]); - - return BezierEdgeDynamic; - })(_utilBezierEdgeBase2['default']); + }, + interaction: { + dragNodes: true, + dragView: true, + hideEdgesOnDrag: false, + hideNodesOnDrag: false, + hover: false, + keyboard: { + enabled: false, + speed: { x: [10, 0, 40, 1], y: [10, 0, 40, 1], zoom: [0.02, 0, 0.1, 0.005] }, + bindToWindow: true + }, + multiselect: false, + navigationButtons: false, + selectable: true, + selectConnectedEdges: true, + hoverConnectedEdges: true, + tooltipDelay: [300, 0, 1000, 25], + zoomView: true + }, + manipulation: { + enabled: false, + initiallyActive: false + }, + physics: { + barnesHut: { + //theta: [0.5, 0.1, 1, 0.05], + gravitationalConstant: [-2000, -30000, 0, 50], + centralGravity: [0.3, 0, 10, 0.05], + springLength: [95, 0, 500, 5], + springConstant: [0.04, 0, 1.2, 0.005], + damping: [0.09, 0, 1, 0.01], + avoidOverlap: [0, 0, 1, 0.01] + }, + forceAtlas2Based: { + //theta: [0.5, 0.1, 1, 0.05], + gravitationalConstant: [-50, -500, 0, 1], + centralGravity: [0.01, 0, 1, 0.005], + springLength: [95, 0, 500, 5], + springConstant: [0.08, 0, 1.2, 0.005], + damping: [0.4, 0, 1, 0.01], + avoidOverlap: [0, 0, 1, 0.01] + }, + repulsion: { + centralGravity: [0.2, 0, 10, 0.05], + springLength: [200, 0, 500, 5], + springConstant: [0.05, 0, 1.2, 0.005], + nodeDistance: [100, 0, 500, 5], + damping: [0.09, 0, 1, 0.01] + }, + hierarchicalRepulsion: { + centralGravity: [0.2, 0, 10, 0.05], + springLength: [100, 0, 500, 5], + springConstant: [0.01, 0, 1.2, 0.005], + nodeDistance: [120, 0, 500, 5], + damping: [0.09, 0, 1, 0.01] + }, + maxVelocity: [50, 0, 150, 1], + minVelocity: [0.1, 0.01, 0.5, 0.01], + solver: ['barnesHut', 'forceAtlas2Based', 'repulsion', 'hierarchicalRepulsion'], + timestep: [0.5, 0.01, 1, 0.01] + }, + global: { + locale: ['en', 'nl'] + } + }; - exports['default'] = BezierEdgeDynamic; - module.exports = exports['default']; + exports.allOptions = allOptions; + exports.configureOptions = configureOptions; /***/ }, -/* 107 */ +/* 109 */ /***/ function(module, exports, __webpack_require__) { + /** + * Canvas shapes used by Network + */ 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - var _get = function get(_x4, _x5, _x6) { var _again = true; _function: while (_again) { var object = _x4, property = _x5, receiver = _x6; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x4 = parent; _x5 = property; _x6 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } - - var _utilBezierEdgeBase = __webpack_require__(112); - - var _utilBezierEdgeBase2 = _interopRequireDefault(_utilBezierEdgeBase); - - var BezierEdgeStatic = (function (_BezierEdgeBase) { - function BezierEdgeStatic(options, body, labelModule) { - _classCallCheck(this, BezierEdgeStatic); - - _get(Object.getPrototypeOf(BezierEdgeStatic.prototype), 'constructor', this).call(this, options, body, labelModule); - } - - _inherits(BezierEdgeStatic, _BezierEdgeBase); - - _createClass(BezierEdgeStatic, [{ - key: '_line', - - /** - * Draw a line between two nodes - * @param {CanvasRenderingContext2D} ctx - * @private - */ - value: function _line(ctx) { - // draw a straight line - ctx.beginPath(); - ctx.moveTo(this.from.x, this.from.y); - var via = this._getViaCoordinates(); - var returnValue = via; - - // fallback to normal straight edges - if (via.x === undefined) { - ctx.lineTo(this.to.x, this.to.y); - returnValue = undefined; - } else { - ctx.quadraticCurveTo(via.x, via.y, this.to.x, this.to.y); - } - // draw shadow if enabled - this.enableShadow(ctx); - ctx.stroke(); - this.disableShadow(ctx); - return returnValue; - } - }, { - key: '_getViaCoordinates', - value: function _getViaCoordinates() { - var xVia = undefined; - var yVia = undefined; - var factor = this.options.smooth.roundness; - var type = this.options.smooth.type; - var dx = Math.abs(this.from.x - this.to.x); - var dy = Math.abs(this.from.y - this.to.y); - if (type === 'discrete' || type === 'diagonalCross') { - if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { - if (this.from.y > this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dy; - yVia = this.from.y - factor * dy; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dy; - yVia = this.from.y - factor * dy; - } - } else if (this.from.y < this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dy; - yVia = this.from.y + factor * dy; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dy; - yVia = this.from.y + factor * dy; - } - } - if (type === 'discrete') { - xVia = dx < factor * dy ? this.from.x : xVia; - } - } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { - if (this.from.y > this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dx; - yVia = this.from.y - factor * dx; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dx; - yVia = this.from.y - factor * dx; - } - } else if (this.from.y < this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dx; - yVia = this.from.y + factor * dx; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dx; - yVia = this.from.y + factor * dx; - } - } - if (type === 'discrete') { - yVia = dy < factor * dx ? this.from.y : yVia; - } - } - } else if (type === 'straightCross') { - if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { - // up - down - xVia = this.from.x; - if (this.from.y < this.to.y) { - yVia = this.to.y - (1 - factor) * dy; - } else { - yVia = this.to.y + (1 - factor) * dy; - } - } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { - // left - right - if (this.from.x < this.to.x) { - xVia = this.to.x - (1 - factor) * dx; - } else { - xVia = this.to.x + (1 - factor) * dx; - } - yVia = this.from.y; - } - } else if (type === 'horizontal') { - if (this.from.x < this.to.x) { - xVia = this.to.x - (1 - factor) * dx; - } else { - xVia = this.to.x + (1 - factor) * dx; - } - yVia = this.from.y; - } else if (type === 'vertical') { - xVia = this.from.x; - if (this.from.y < this.to.y) { - yVia = this.to.y - (1 - factor) * dy; - } else { - yVia = this.to.y + (1 - factor) * dy; - } - } else if (type === 'curvedCW') { - dx = this.to.x - this.from.x; - dy = this.from.y - this.to.y; - var radius = Math.sqrt(dx * dx + dy * dy); - var pi = Math.PI; - - var originalAngle = Math.atan2(dy, dx); - var myAngle = (originalAngle + (factor * 0.5 + 0.5) * pi) % (2 * pi); - - xVia = this.from.x + (factor * 0.5 + 0.5) * radius * Math.sin(myAngle); - yVia = this.from.y + (factor * 0.5 + 0.5) * radius * Math.cos(myAngle); - } else if (type === 'curvedCCW') { - dx = this.to.x - this.from.x; - dy = this.from.y - this.to.y; - var radius = Math.sqrt(dx * dx + dy * dy); - var pi = Math.PI; - - var originalAngle = Math.atan2(dy, dx); - var myAngle = (originalAngle + (-factor * 0.5 + 0.5) * pi) % (2 * pi); + if (typeof CanvasRenderingContext2D !== 'undefined') { - xVia = this.from.x + (factor * 0.5 + 0.5) * radius * Math.sin(myAngle); - yVia = this.from.y + (factor * 0.5 + 0.5) * radius * Math.cos(myAngle); - } else { - // continuous - if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { - if (this.from.y > this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dy; - yVia = this.from.y - factor * dy; - xVia = this.to.x < xVia ? this.to.x : xVia; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dy; - yVia = this.from.y - factor * dy; - xVia = this.to.x > xVia ? this.to.x : xVia; - } - } else if (this.from.y < this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dy; - yVia = this.from.y + factor * dy; - xVia = this.to.x < xVia ? this.to.x : xVia; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dy; - yVia = this.from.y + factor * dy; - xVia = this.to.x > xVia ? this.to.x : xVia; - } - } - } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { - if (this.from.y > this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dx; - yVia = this.from.y - factor * dx; - yVia = this.to.y > yVia ? this.to.y : yVia; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dx; - yVia = this.from.y - factor * dx; - yVia = this.to.y > yVia ? this.to.y : yVia; - } - } else if (this.from.y < this.to.y) { - if (this.from.x < this.to.x) { - xVia = this.from.x + factor * dx; - yVia = this.from.y + factor * dx; - yVia = this.to.y < yVia ? this.to.y : yVia; - } else if (this.from.x > this.to.x) { - xVia = this.from.x - factor * dx; - yVia = this.from.y + factor * dx; - yVia = this.to.y < yVia ? this.to.y : yVia; - } - } - } - } - return { x: xVia, y: yVia }; - } - }, { - key: '_findBorderPosition', - value: function _findBorderPosition(nearNode, ctx) { - var options = arguments[2] === undefined ? {} : arguments[2]; + /** + * Draw a circle shape + */ + CanvasRenderingContext2D.prototype.circle = function (x, y, r) { + this.beginPath(); + this.arc(x, y, r, 0, 2 * Math.PI, false); + this.closePath(); + }; - return this._findBorderPositionBezier(nearNode, ctx, options.via); - } - }, { - key: '_getDistanceToEdge', - value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) { - var via = arguments[6] === undefined ? this._getViaCoordinates() : arguments[6]; - // x3,y3 is the point - return this._getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via); - } - }, { - key: 'getPoint', + /** + * Draw a square shape + * @param {Number} x horizontal center + * @param {Number} y vertical center + * @param {Number} r size, width and height of the square + */ + CanvasRenderingContext2D.prototype.square = function (x, y, r) { + this.beginPath(); + this.rect(x - r, y - r, r * 2, r * 2); + this.closePath(); + }; - /** - * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way - * @param percentage - * @param via - * @returns {{x: number, y: number}} - * @private - */ - value: function getPoint(percentage) { - var via = arguments[1] === undefined ? this._getViaCoordinates() : arguments[1]; + /** + * Draw a triangle shape + * @param {Number} x horizontal center + * @param {Number} y vertical center + * @param {Number} r radius, half the length of the sides of the triangle + */ + CanvasRenderingContext2D.prototype.triangle = function (x, y, r) { + // http://en.wikipedia.org/wiki/Equilateral_triangle + this.beginPath(); - var t = percentage; - var x = Math.pow(1 - t, 2) * this.from.x + 2 * t * (1 - t) * via.x + Math.pow(t, 2) * this.to.x; - var y = Math.pow(1 - t, 2) * this.from.y + 2 * t * (1 - t) * via.y + Math.pow(t, 2) * this.to.y; + // the change in radius and the offset is here to center the shape + r *= 1.15; + y += 0.275 * r; - return { x: x, y: y }; - } - }]); + var s = r * 2; + var s2 = s / 2; + var ir = Math.sqrt(3) / 6 * s; // radius of inner circle + var h = Math.sqrt(s * s - s2 * s2); // height - return BezierEdgeStatic; - })(_utilBezierEdgeBase2['default']); + this.moveTo(x, y - (h - ir)); + this.lineTo(x + s2, y + ir); + this.lineTo(x - s2, y + ir); + this.lineTo(x, y - (h - ir)); + this.closePath(); + }; - exports['default'] = BezierEdgeStatic; - module.exports = exports['default']; + /** + * Draw a triangle shape in downward orientation + * @param {Number} x horizontal center + * @param {Number} y vertical center + * @param {Number} r radius + */ + CanvasRenderingContext2D.prototype.triangleDown = function (x, y, r) { + // http://en.wikipedia.org/wiki/Equilateral_triangle + this.beginPath(); -/***/ }, -/* 108 */ -/***/ function(module, exports, __webpack_require__) { + // the change in radius and the offset is here to center the shape + r *= 1.15; + y -= 0.275 * r; - 'use strict'; + var s = r * 2; + var s2 = s / 2; + var ir = Math.sqrt(3) / 6 * s; // radius of inner circle + var h = Math.sqrt(s * s - s2 * s2); // height - Object.defineProperty(exports, '__esModule', { - value: true - }); + this.moveTo(x, y + (h - ir)); + this.lineTo(x + s2, y - ir); + this.lineTo(x - s2, y - ir); + this.lineTo(x, y + (h - ir)); + this.closePath(); + }; - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + /** + * Draw a star shape, a star with 5 points + * @param {Number} x horizontal center + * @param {Number} y vertical center + * @param {Number} r radius, half the length of the sides of the triangle + */ + CanvasRenderingContext2D.prototype.star = function (x, y, r) { + // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/ + this.beginPath(); - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + // the change in radius and the offset is here to center the shape + r *= 0.82; + y += 0.1 * r; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + for (var n = 0; n < 10; n++) { + var radius = n % 2 === 0 ? r * 1.3 : r * 0.5; + this.lineTo(x + radius * Math.sin(n * 2 * Math.PI / 10), y - radius * Math.cos(n * 2 * Math.PI / 10)); + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + this.closePath(); + }; - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + /** + * Draw a Diamond shape + * @param {Number} x horizontal center + * @param {Number} y vertical center + * @param {Number} r radius, half the length of the sides of the triangle + */ + CanvasRenderingContext2D.prototype.diamond = function (x, y, r) { + // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/ + this.beginPath(); - var _utilEdgeBase = __webpack_require__(113); + this.lineTo(x, y + r); + this.lineTo(x + r, y); + this.lineTo(x, y - r); + this.lineTo(x - r, y); - var _utilEdgeBase2 = _interopRequireDefault(_utilEdgeBase); + this.closePath(); + }; - var StraightEdge = (function (_EdgeBase) { - function StraightEdge(options, body, labelModule) { - _classCallCheck(this, StraightEdge); + /** + * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas + */ + CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) { + var r2d = Math.PI / 180; + if (w - 2 * r < 0) { + r = w / 2; + } //ensure that the radius isn't too large for x + if (h - 2 * r < 0) { + r = h / 2; + } //ensure that the radius isn't too large for y + this.beginPath(); + this.moveTo(x + r, y); + this.lineTo(x + w - r, y); + this.arc(x + w - r, y + r, r, r2d * 270, r2d * 360, false); + this.lineTo(x + w, y + h - r); + this.arc(x + w - r, y + h - r, r, 0, r2d * 90, false); + this.lineTo(x + r, y + h); + this.arc(x + r, y + h - r, r, r2d * 90, r2d * 180, false); + this.lineTo(x, y + r); + this.arc(x + r, y + r, r, r2d * 180, r2d * 270, false); + this.closePath(); + }; - _get(Object.getPrototypeOf(StraightEdge.prototype), 'constructor', this).call(this, options, body, labelModule); - } + /** + * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + */ + CanvasRenderingContext2D.prototype.ellipse = function (x, y, w, h) { + var kappa = 0.5522848, + ox = w / 2 * kappa, + // control point offset horizontal + oy = h / 2 * kappa, + // control point offset vertical + xe = x + w, + // x-end + ye = y + h, + // y-end + xm = x + w / 2, + // x-middle + ym = y + h / 2; // y-middle - _inherits(StraightEdge, _EdgeBase); + this.beginPath(); + this.moveTo(x, ym); + this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + this.closePath(); + }; - _createClass(StraightEdge, [{ - key: '_line', + /** + * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + */ + CanvasRenderingContext2D.prototype.database = function (x, y, w, h) { + var f = 1 / 3; + var wEllipse = w; + var hEllipse = h * f; - /** - * Draw a line between two nodes - * @param {CanvasRenderingContext2D} ctx - * @private - */ - value: function _line(ctx) { - // draw a straight line - ctx.beginPath(); - ctx.moveTo(this.from.x, this.from.y); - ctx.lineTo(this.to.x, this.to.y); - // draw shadow if enabled - this.enableShadow(ctx); - ctx.stroke(); - this.disableShadow(ctx); - return undefined; - } - }, { - key: 'getPoint', + var kappa = 0.5522848, + ox = wEllipse / 2 * kappa, + // control point offset horizontal + oy = hEllipse / 2 * kappa, + // control point offset vertical + xe = x + wEllipse, + // x-end + ye = y + hEllipse, + // y-end + xm = x + wEllipse / 2, + // x-middle + ym = y + hEllipse / 2, + // y-middle + ymb = y + (h - hEllipse / 2), + // y-midlle, bottom ellipse + yeb = y + h; // y-end, bottom ellipse - /** - * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way - * @param percentage - * @param via - * @returns {{x: number, y: number}} - * @private - */ - value: function getPoint(percentage) { - return { - x: (1 - percentage) * this.from.x + percentage * this.to.x, - y: (1 - percentage) * this.from.y + percentage * this.to.y - }; - } - }, { - key: '_findBorderPosition', - value: function _findBorderPosition(nearNode, ctx) { - var node1 = this.to; - var node2 = this.from; - if (nearNode.id === this.from.id) { - node1 = this.from; - node2 = this.to; - } + this.beginPath(); + this.moveTo(xe, ym); - var angle = Math.atan2(node1.y - node2.y, node1.x - node2.x); - var dx = node1.x - node2.x; - var dy = node1.y - node2.y; - var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); - var toBorderDist = nearNode.distanceToBorder(ctx, angle); - var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength; + this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); - var borderPos = {}; - borderPos.x = (1 - toBorderPoint) * node2.x + toBorderPoint * node1.x; - borderPos.y = (1 - toBorderPoint) * node2.y + toBorderPoint * node1.y; + this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); - return borderPos; - } - }, { - key: '_getDistanceToEdge', - value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) { - // x3,y3 is the point - return this._getDistanceToLine(x1, y1, x2, y2, x3, y3); - } - }]); + this.lineTo(xe, ymb); - return StraightEdge; - })(_utilEdgeBase2['default']); + this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb); + this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb); - exports['default'] = StraightEdge; - module.exports = exports['default']; + this.lineTo(x, ym); + }; -/***/ }, -/* 109 */ -/***/ function(module, exports, __webpack_require__) { + /** + * Draw an arrow point (no line) + */ + CanvasRenderingContext2D.prototype.arrow = function (x, y, angle, length) { + // tail + var xt = x - length * Math.cos(angle); + var yt = y - length * Math.sin(angle); - 'use strict'; + // inner tail + var xi = x - length * 0.9 * Math.cos(angle); + var yi = y - length * 0.9 * Math.sin(angle); - Object.defineProperty(exports, '__esModule', { - value: true - }); + // left + var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI); + var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI); - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // right + var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI); + var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + this.beginPath(); + this.moveTo(x, y); + this.lineTo(xl, yl); + this.lineTo(xi, yi); + this.lineTo(xr, yr); + this.closePath(); + }; - var NodeBase = (function () { - function NodeBase(options, body, labelModule) { - _classCallCheck(this, NodeBase); + /** + * Sets up the dashedLine functionality for drawing + * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas + * @author David Jordan + * @date 2012-08-08 + */ + CanvasRenderingContext2D.prototype.dashedLine = function (x, y, x2, y2, pattern) { + this.beginPath(); + this.moveTo(x, y); - 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.boundingBox = { top: 0, left: 0, right: 0, bottom: 0 }; - } + var patternLength = pattern.length; + var dx = x2 - x; + var dy = y2 - y; + var slope = dy / dx; + var distRemaining = Math.sqrt(dx * dx + dy * dy); + var patternIndex = 0; + var draw = true; + var xStep = 0; + var dashLength = pattern[0]; - _createClass(NodeBase, [{ - key: 'setOptions', - value: function setOptions(options) { - this.options = options; - } - }, { - key: '_distanceToBorder', - value: function _distanceToBorder(angle) { - var borderWidth = 1; - return Math.min(Math.abs(this.width / 2 / Math.cos(angle)), Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth; - } - }, { - key: 'enableShadow', - value: function enableShadow(ctx) { - if (this.options.shadow.enabled === true) { - ctx.shadowColor = 'rgba(0,0,0,0.5)'; - ctx.shadowBlur = this.options.shadow.size; - ctx.shadowOffsetX = this.options.shadow.x; - ctx.shadowOffsetY = this.options.shadow.y; - } - } - }, { - key: 'disableShadow', - value: function disableShadow(ctx) { - if (this.options.shadow.enabled === true) { - ctx.shadowColor = 'rgba(0,0,0,0)'; - ctx.shadowBlur = 0; - ctx.shadowOffsetX = 0; - ctx.shadowOffsetY = 0; + while (distRemaining >= 0.1) { + dashLength = pattern[patternIndex++ % patternLength]; + if (dashLength > distRemaining) { + dashLength = distRemaining; } - } - }]); - return NodeBase; - })(); + xStep = Math.sqrt(dashLength * dashLength / (1 + slope * slope)); + xStep = dx < 0 ? -xStep : xStep; + x += xStep; + y += slope * xStep; - exports['default'] = NodeBase; - module.exports = exports['default']; + if (draw === true) { + this.lineTo(x, y); + } else { + this.moveTo(x, y); + } + + distRemaining -= dashLength; + draw = !draw; + } + }; + } /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { + /** + * Parse a text source containing data in DOT language into a JSON object. + * The object contains two lists: one with nodes and one with edges. + * + * DOT language reference: http://www.graphviz.org/doc/info/lang.html + * + * DOT language attributes: http://graphviz.org/content/attrs + * + * @param {String} data Text containing a graph in DOT-notation + * @return {Object} graph An object containing two parameters: + * {Object[]} nodes + * {Object[]} edges + */ 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + function parseDOT(data) { + dot = data; + return parseGraph(); + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + // mapping of attributes from DOT (the keys) to vis.js (the values) + var NODE_ATTR_MAPPING = { + 'fontsize': 'font.size', + 'fontcolor': 'font.color', + 'labelfontcolor': 'font.color', + 'fontname': 'font.face', + 'color': ['color.border', 'color.background'], + 'fillcolor': 'color.background', + 'tooltip': 'title', + 'labeltooltip': 'title' + }; + var EDGE_ATTR_MAPPING = Object.create(NODE_ATTR_MAPPING); + EDGE_ATTR_MAPPING.color = 'color.color'; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + // token types enumeration + var TOKENTYPE = { + NULL: 0, + DELIMITER: 1, + IDENTIFIER: 2, + UNKNOWN: 3 + }; - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + // map with all delimiters + var DELIMITERS = { + '{': true, + '}': true, + '[': true, + ']': true, + ';': true, + '=': true, + ',': true, - var _utilNodeBase = __webpack_require__(109); + '->': true, + '--': true + }; - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + var dot = ''; // current dot file + var index = 0; // current index in dot file + var c = ''; // current token character in expr + var token = ''; // current token + var tokenType = TOKENTYPE.NULL; // type of the token - var CircleImageBase = (function (_NodeBase) { - function CircleImageBase(options, body, labelModule) { - _classCallCheck(this, CircleImageBase); + /** + * Get the first character from the dot file. + * The character is stored into the char c. If the end of the dot file is + * reached, the function puts an empty string in c. + */ + function first() { + index = 0; + c = dot.charAt(0); + } - _get(Object.getPrototypeOf(CircleImageBase.prototype), 'constructor', this).call(this, options, body, labelModule); - this.labelOffset = 0; - this.imageLoaded = false; - } + /** + * Get the next character from the dot file. + * The character is stored into the char c. If the end of the dot file is + * reached, the function puts an empty string in c. + */ + function next() { + index++; + c = dot.charAt(index); + } - _inherits(CircleImageBase, _NodeBase); + /** + * Preview the next character from the dot file. + * @return {String} cNext + */ + function nextPreview() { + return dot.charAt(index + 1); + } - _createClass(CircleImageBase, [{ - key: '_resizeImage', + /** + * Test whether given character is alphabetic or numeric + * @param {String} c + * @return {Boolean} isAlphaNumeric + */ + var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/; + function isAlphaNumeric(c) { + return regexAlphaNumeric.test(c); + } - /** - * This function resizes the image by the options size when the image has not yet loaded. If the image has loaded, we - * force the update of the size again. - * - * @private - */ - value: function _resizeImage() { - var force = false; - if (!this.imageObj.width || !this.imageObj.height) { - // undefined or 0 - this.imageLoaded = false; - } else if (this.imageLoaded === false) { - this.imageLoaded = true; - force = true; - } + /** + * Merge all options of object b into object b + * @param {Object} a + * @param {Object} b + * @return {Object} a + */ + function merge(a, b) { + if (!a) { + a = {}; + } - if (!this.width || !this.height || force === true) { - // undefined or 0 - var width, height, ratio; - if (this.imageObj.width && this.imageObj.height) { - // not undefined or 0 - width = 0; - height = 0; - } - if (this.imageObj.width > this.imageObj.height) { - ratio = this.imageObj.width / this.imageObj.height; - width = this.options.size * 2 * ratio || this.imageObj.width; - height = this.options.size * 2 || this.imageObj.height; - } else { - if (this.imageObj.width && this.imageObj.height) { - // not undefined or 0 - ratio = this.imageObj.height / this.imageObj.width; - } else { - ratio = 1; - } - width = this.options.size * 2 || this.imageObj.width; - height = this.options.size * 2 * ratio || this.imageObj.height; - } - this.width = width; - this.height = height; - this.radius = 0.5 * this.width; + if (b) { + for (var name in b) { + if (b.hasOwnProperty(name)) { + a[name] = b[name]; } } - }, { - key: '_drawRawCircle', - value: function _drawRawCircle(ctx, x, y, selected, hover, size) { - var borderWidth = this.options.borderWidth; - var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - - ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; - - ctx.lineWidth = selected ? selectionLineWidth : borderWidth; - ctx.lineWidth *= this.networkScaleInv; - ctx.lineWidth = Math.min(this.width, ctx.lineWidth); - - ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; - ctx.circle(x, y, size); - - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); - - // disable shadows for other elements. - this.disableShadow(ctx); - - ctx.stroke(); - } - }, { - key: '_drawImageAtPosition', - value: function _drawImageAtPosition(ctx) { - if (this.imageObj.width != 0) { - // draw the image - ctx.globalAlpha = 1; - - // draw shadow if enabled - this.enableShadow(ctx); - ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height); + } + return a; + } - // disable shadows for other elements. - this.disableShadow(ctx); + /** + * Set a value in an object, where the provided parameter name can be a + * path with nested parameters. For example: + * + * var obj = {a: 2}; + * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}} + * + * @param {Object} obj + * @param {String} path A parameter name or dot-separated parameter path, + * like "color.highlight.border". + * @param {*} value + */ + function setValue(obj, path, value) { + var keys = path.split('.'); + var o = obj; + while (keys.length) { + var key = keys.shift(); + if (keys.length) { + // this isn't the end point + if (!o[key]) { + o[key] = {}; } + o = o[key]; + } else { + // this is the end point + o[key] = value; } - }, { - key: '_drawImageLabel', - value: function _drawImageLabel(ctx, x, y, selected) { - var yLabel; - var offset = 0; + } + } - if (this.height !== undefined) { - offset = this.height * 0.5; - var labelDimensions = this.labelModule.getTextSize(ctx); - if (labelDimensions.lineCount >= 1) { - offset += labelDimensions.height / 2; - } - } + /** + * Add a node to a graph object. If there is already a node with + * the same id, their attributes will be merged. + * @param {Object} graph + * @param {Object} node + */ + function addNode(graph, node) { + var i, len; + var current = null; - yLabel = y + offset; + // find root graph (in case of subgraph) + var graphs = [graph]; // list with all graphs from current graph to root graph + var root = graph; + while (root.parent) { + graphs.push(root.parent); + root = root.parent; + } - if (this.options.label) { - this.labelOffset = offset; + // find existing node (at root level) by its id + if (root.nodes) { + for (i = 0, len = root.nodes.length; i < len; i++) { + if (node.id === root.nodes[i].id) { + current = root.nodes[i]; + break; } - this.labelModule.draw(ctx, x, yLabel, selected, 'hanging'); } - }]); - - return CircleImageBase; - })(_utilNodeBase2['default']); - - exports['default'] = CircleImageBase; - module.exports = exports['default']; - -/***/ }, -/* 111 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; + } - Object.defineProperty(exports, '__esModule', { - value: true - }); + if (!current) { + // this is a new node + current = { + id: node.id + }; + if (graph.node) { + // clone default attributes + current.attr = merge(current.attr, graph.node); + } + } - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // add node to this (sub)graph and all its parent graphs + for (i = graphs.length - 1; i >= 0; i--) { + var g = graphs[i]; - var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + if (!g.nodes) { + g.nodes = []; + } + if (g.nodes.indexOf(current) === -1) { + g.nodes.push(current); + } + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + // merge attributes + if (node.attr) { + current.attr = merge(current.attr, node.attr); + } + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * Add an edge to a graph object + * @param {Object} graph + * @param {Object} edge + */ + function addEdge(graph, edge) { + if (!graph.edges) { + graph.edges = []; + } + graph.edges.push(edge); + if (graph.edge) { + var attr = merge({}, graph.edge); // clone default attributes + edge.attr = merge(attr, edge.attr); // merge attributes + } + } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + /** + * Create an edge to a graph object + * @param {Object} graph + * @param {String | Number | Object} from + * @param {String | Number | Object} to + * @param {String} type + * @param {Object | null} attr + * @return {Object} edge + */ + function createEdge(graph, from, to, type, attr) { + var edge = { + from: from, + to: to, + type: type + }; - var _utilNodeBase = __webpack_require__(109); + if (graph.edge) { + edge.attr = merge({}, graph.edge); // clone default attributes + } + edge.attr = merge(edge.attr || {}, attr); // merge attributes - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + return edge; + } - var ShapeBase = (function (_NodeBase) { - function ShapeBase(options, body, labelModule) { - _classCallCheck(this, ShapeBase); + /** + * Get next token in the current dot file. + * The token and token type are available as token and tokenType + */ + function getToken() { + tokenType = TOKENTYPE.NULL; + token = ''; - _get(Object.getPrototypeOf(ShapeBase.prototype), 'constructor', this).call(this, options, body, labelModule); + // skip over whitespaces + while (c === ' ' || c === '\t' || c === '\n' || c === '\r') { + // space, tab, enter + next(); } - _inherits(ShapeBase, _NodeBase); + do { + var isComment = false; - _createClass(ShapeBase, [{ - key: '_resizeShape', - value: function _resizeShape() { - if (this.width === undefined) { - var size = 2 * this.options.size; - this.width = size; - this.height = size; - this.radius = 0.5 * this.width; + // skip comment + if (c === '#') { + // find the previous non-space character + var i = index - 1; + while (dot.charAt(i) === ' ' || dot.charAt(i) === '\t') { + i--; + } + if (dot.charAt(i) === '\n' || dot.charAt(i) === '') { + // the # is at the start of a line, this is indeed a line comment + while (c != '' && c != '\n') { + next(); + } + isComment = true; } } - }, { - key: '_drawShape', - value: function _drawShape(ctx, shape, sizeMultiplier, x, y, selected, hover) { - this._resizeShape(); - - this.left = x - this.width / 2; - this.top = y - this.height / 2; - - var borderWidth = this.options.borderWidth; - var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - - ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; - ctx.lineWidth = selected ? selectionLineWidth : borderWidth; - ctx.lineWidth /= this.body.view.scale; - ctx.lineWidth = Math.min(this.width, ctx.lineWidth); - ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; - ctx[shape](x, y, this.options.size); - - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); - - // disable shadows for other elements. - this.disableShadow(ctx); - - ctx.stroke(); - - if (this.options.label !== undefined) { - var yLabel = y + 0.5 * this.height + 3; // the + 3 is to offset it a bit below the node. - this.labelModule.draw(ctx, x, yLabel, selected, 'hanging'); + if (c === '/' && nextPreview() === '/') { + // skip line comment + while (c != '' && c != '\n') { + next(); } - - this.updateBoundingBox(x, y); + isComment = true; } - }, { - 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.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 + 3); + if (c === '/' && nextPreview() === '*') { + // skip block comment + while (c != '') { + if (c === '*' && nextPreview() === '/') { + // end of block comment found. skip these last two characters + next(); + next(); + break; + } else { + next(); + } } + isComment = true; } - }]); - - return ShapeBase; - })(_utilNodeBase2['default']); - - exports['default'] = ShapeBase; - module.exports = exports['default']; - -/***/ }, -/* 112 */ -/***/ function(module, exports, __webpack_require__) { - 'use strict'; + // skip over whitespaces + while (c === ' ' || c === '\t' || c === '\n' || c === '\r') { + // space, tab, enter + next(); + } + } while (isComment); - Object.defineProperty(exports, '__esModule', { - value: true - }); + // check for end of dot file + if (c === '') { + // token is still empty + tokenType = TOKENTYPE.DELIMITER; + return; + } - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // check for delimiters consisting of 2 characters + var c2 = c + nextPreview(); + if (DELIMITERS[c2]) { + tokenType = TOKENTYPE.DELIMITER; + token = c2; + next(); + next(); + return; + } - var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + // check for delimiters consisting of 1 character + if (DELIMITERS[c]) { + tokenType = TOKENTYPE.DELIMITER; + token = c; + next(); + return; + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + // check for an identifier (number or string) + // TODO: more precise parsing of numbers/strings (and the port separator ':') + if (isAlphaNumeric(c) || c === '-') { + token += c; + next(); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + while (isAlphaNumeric(c)) { + token += c; + next(); + } + if (token === 'false') { + token = false; // convert to boolean + } else if (token === 'true') { + token = true; // convert to boolean + } else if (!isNaN(Number(token))) { + token = Number(token); // convert to number + } + tokenType = TOKENTYPE.IDENTIFIER; + return; + } - function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } + // check for a string enclosed by double quotes + if (c === '"') { + next(); + while (c != '' && (c != '"' || c === '"' && nextPreview() === '"')) { + token += c; + if (c === '"') { + // skip the escape character + next(); + } + next(); + } + if (c != '"') { + throw newSyntaxError('End of string " expected'); + } + next(); + tokenType = TOKENTYPE.IDENTIFIER; + return; + } - var _EdgeBase2 = __webpack_require__(113); + // something unknown is found, wrong characters, a syntax error + tokenType = TOKENTYPE.UNKNOWN; + while (c != '') { + token += c; + next(); + } + throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"'); + } - var _EdgeBase3 = _interopRequireDefault(_EdgeBase2); + /** + * Parse a graph. + * @returns {Object} graph + */ + function parseGraph() { + var graph = {}; - var BezierEdgeBase = (function (_EdgeBase) { - function BezierEdgeBase(options, body, labelModule) { - _classCallCheck(this, BezierEdgeBase); + first(); + getToken(); - _get(Object.getPrototypeOf(BezierEdgeBase.prototype), 'constructor', this).call(this, options, body, labelModule); + // optional strict keyword + if (token === 'strict') { + graph.strict = true; + getToken(); } - _inherits(BezierEdgeBase, _EdgeBase); - - _createClass(BezierEdgeBase, [{ - key: '_findBorderPositionBezier', + // graph or digraph keyword + if (token === 'graph' || token === 'digraph') { + graph.type = token; + getToken(); + } - /** - * This function uses binary search to look for the point where the bezier curve crosses the border of the node. - * - * @param nearNode - * @param ctx - * @param viaNode - * @param nearNode - * @param ctx - * @param viaNode - * @param nearNode - * @param ctx - * @param viaNode - */ - value: function _findBorderPositionBezier(nearNode, ctx) { - var viaNode = arguments[2] === undefined ? this._getViaCoordinates() : arguments[2]; + // optional graph id + if (tokenType === TOKENTYPE.IDENTIFIER) { + graph.id = token; + getToken(); + } - 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; - } + // open angle bracket + if (token != '{') { + throw newSyntaxError('Angle bracket { expected'); + } + getToken(); - while (low <= high && iteration < maxIterations) { - var middle = (low + high) * 0.5; + // statements + parseStatements(graph); - 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; - } - } + // close angle bracket + if (token != '}') { + throw newSyntaxError('Angle bracket } expected'); + } + getToken(); - iteration++; - } - pos.t = middle; + // end of file + if (token !== '') { + throw newSyntaxError('End of file expected'); + } + getToken(); - return pos; - } - }, { - key: '_getDistanceToBezierEdge', + // remove temporary default options + delete graph.node; + delete graph.edge; + delete graph.graph; - /** - * 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 - * @param {number} y1 - * @param {number} x2 - * @param {number} y2 - * @param {number} x3 - * @param {number} y3 - * @private - */ - value: function _getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via) { - // x3,y3 is the point - var xVia = undefined, - yVia = undefined; - xVia = via.x; - yVia = via.y; - var minDistance = 1000000000; - var distance = undefined; - var i = undefined, - t = undefined, - x = undefined, - y = undefined; - 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) * xVia + Math.pow(t, 2) * x2; - y = Math.pow(1 - t, 2) * y1 + 2 * t * (1 - t) * yVia + 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 graph; + } - return minDistance; + /** + * Parse a list with statements. + * @param {Object} graph + */ + function parseStatements(graph) { + while (token !== '' && token != '}') { + parseStatement(graph); + if (token === ';') { + getToken(); } - }]); - - return BezierEdgeBase; - })(_EdgeBase3['default']); - - exports['default'] = BezierEdgeBase; - module.exports = exports['default']; - -/***/ }, -/* 113 */ -/***/ function(module, exports, __webpack_require__) { + } + } - 'use strict'; + /** + * Parse a single statement. Can be a an attribute statement, node + * statement, a series of node statements and edge statements, or a + * parameter. + * @param {Object} graph + */ + function parseStatement(graph) { + // parse subgraph + var subgraph = parseSubgraph(graph); + if (subgraph) { + // edge statements + parseEdge(graph, subgraph); - Object.defineProperty(exports, '__esModule', { - value: true - }); + return; + } - var _createClass = (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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + // parse an attribute statement + var attr = parseAttributeStatement(graph); + if (attr) { + return; + } - function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _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; } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } } + // parse node + if (tokenType != TOKENTYPE.IDENTIFIER) { + throw newSyntaxError('Identifier expected'); + } + var id = token; // id can be a string or a number + getToken(); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + if (token === '=') { + // id statement + getToken(); + if (tokenType != TOKENTYPE.IDENTIFIER) { + throw newSyntaxError('Identifier expected'); + } + graph[id] = token; + getToken(); + // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] " + } else { + parseNodeStatement(graph, id); + } + } - var util = __webpack_require__(2); + /** + * Parse a subgraph + * @param {Object} graph parent graph object + * @return {Object | null} subgraph + */ + function parseSubgraph(graph) { + var subgraph = null; - var EdgeBase = (function () { - function EdgeBase(options, body, labelModule) { - _classCallCheck(this, EdgeBase); + // optional subgraph keyword + if (token === 'subgraph') { + subgraph = {}; + subgraph.type = 'subgraph'; + getToken(); - this.body = body; - this.labelModule = labelModule; - this.setOptions(options); - this.colorDirty = true; - this.color = {}; - this.selectionWidth = 2; - this.hoverWidth = 1.5; + // optional graph id + if (tokenType === TOKENTYPE.IDENTIFIER) { + subgraph.id = token; + getToken(); + } } - _createClass(EdgeBase, [{ - key: 'connect', - value: function connect() {} - }, { - key: 'cleanup', - value: function cleanup() { - return false; - } - }, { - key: 'setOptions', - value: function setOptions(options) { - this.options = options; - this.from = this.body.nodes[this.options.from]; - this.to = this.body.nodes[this.options.to]; - this.id = this.options.id; + // open angle bracket + if (token === '{') { + getToken(); + + if (!subgraph) { + subgraph = {}; } - }, { - key: 'togglePhysics', + subgraph.parent = graph; + subgraph.node = graph.node; + subgraph.edge = graph.edge; + subgraph.graph = graph.graph; - /** - * overloadable if the shape has to toggle the via node to disabled - * @param status - */ - value: function togglePhysics(status) {} - }, { - key: 'drawLine', + // statements + parseStatements(subgraph); - /** - * Redraw a edge as a line - * Draw this edge in the given canvas - * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); - * @param {CanvasRenderingContext2D} ctx - * @private - */ - value: function drawLine(ctx, selected, hover) { - // set style - ctx.strokeStyle = this.getColor(ctx, selected, hover); - ctx.lineWidth = this.getLineWidth(selected, hover); - var via = undefined; - if (this.options.dashes !== false) { - via = this._drawDashedLine(ctx); - } else { - via = this._drawLine(ctx); - } - return via; + // close angle bracket + if (token != '}') { + throw newSyntaxError('Angle bracket } expected'); } - }, { - key: '_drawLine', - value: function _drawLine(ctx) { - var via = undefined; - if (this.from != this.to) { - // draw line - via = this._line(ctx); - } else { - var _getCircleData = this._getCircleData(ctx); - - var _getCircleData2 = _slicedToArray(_getCircleData, 3); + getToken(); - var x = _getCircleData2[0]; - var y = _getCircleData2[1]; - var radius = _getCircleData2[2]; + // remove temporary default options + delete subgraph.node; + delete subgraph.edge; + delete subgraph.graph; + delete subgraph.parent; - this._circle(ctx, x, y, radius); - } - return via; + // register at the parent graph + if (!graph.subgraphs) { + graph.subgraphs = []; } - }, { - key: '_drawDashedLine', - value: function _drawDashedLine(ctx) { - var via = undefined; - ctx.lineCap = 'round'; - var pattern = [5, 5]; - if (Array.isArray(this.options.dashes) === true) { - pattern = this.options.dashes; - } + graph.subgraphs.push(subgraph); + } - // only firefox and chrome support this method, else we use the legacy one. - if (ctx.setLineDash !== undefined) { - ctx.save(); + return subgraph; + } - // set dash settings for chrome or firefox - ctx.setLineDash(pattern); - ctx.lineDashOffset = 0; + /** + * parse an attribute statement like "node [shape=circle fontSize=16]". + * Available keywords are 'node', 'edge', 'graph'. + * The previous list with default attributes will be replaced + * @param {Object} graph + * @returns {String | null} keyword Returns the name of the parsed attribute + * (node, edge, graph), or null if nothing + * is parsed. + */ + function parseAttributeStatement(graph) { + // attribute statements + if (token === 'node') { + getToken(); - // draw the line - if (this.from != this.to) { - // draw line - via = this._line(ctx); - } else { - var _getCircleData3 = this._getCircleData(ctx); + // node attributes + graph.node = parseAttributeList(); + return 'node'; + } else if (token === 'edge') { + getToken(); - var _getCircleData32 = _slicedToArray(_getCircleData3, 3); + // edge attributes + graph.edge = parseAttributeList(); + return 'edge'; + } else if (token === 'graph') { + getToken(); - var x = _getCircleData32[0]; - var y = _getCircleData32[1]; - var radius = _getCircleData32[2]; + // graph attributes + graph.graph = parseAttributeList(); + return 'graph'; + } - this._circle(ctx, x, y, radius); - } + return null; + } - // restore the dash settings. - ctx.setLineDash([0]); - ctx.lineDashOffset = 0; - ctx.restore(); - } else { - // unsupporting smooth lines + /** + * parse a node statement + * @param {Object} graph + * @param {String | Number} id + */ + function parseNodeStatement(graph, id) { + // node statement + var node = { + id: id + }; + var attr = parseAttributeList(); + if (attr) { + node.attr = attr; + } + addNode(graph, node); - if (this.from != this.to) { - // draw line - ctx.dashedLine(this.from.x, this.from.y, this.to.x, this.to.y, pattern); - } else { - var _getCircleData4 = this._getCircleData(ctx); + // edge statements + parseEdge(graph, id); + } - var _getCircleData42 = _slicedToArray(_getCircleData4, 3); + /** + * Parse an edge or a series of edges + * @param {Object} graph + * @param {String | Number} from Id of the from node + */ + function parseEdge(graph, from) { + while (token === '->' || token === '--') { + var to; + var type = token; + getToken(); - var x = _getCircleData42[0]; - var y = _getCircleData42[1]; - var radius = _getCircleData42[2]; + var subgraph = parseSubgraph(graph); + if (subgraph) { + to = subgraph; + } else { + if (tokenType != TOKENTYPE.IDENTIFIER) { + throw newSyntaxError('Identifier or subgraph expected'); + } + to = token; + addNode(graph, { + id: to + }); + getToken(); + } - this._circle(ctx, x, y, radius); - } - // draw shadow if enabled - this.enableShadow(ctx); + // parse edge attributes + var attr = parseAttributeList(); - ctx.stroke(); + // create edge + var edge = createEdge(graph, from, to, type, attr); + addEdge(graph, edge); - // disable shadows for other elements. - this.disableShadow(ctx); - } - return via; - } - }, { - key: 'findBorderPosition', - value: function findBorderPosition(nearNode, ctx, options) { - if (this.from != this.to) { - return this._findBorderPosition(nearNode, ctx, options); - } else { - return this._findBorderPositionCircle(nearNode, ctx, options); - } - } - }, { - key: 'findBorderPositions', - value: function findBorderPositions(ctx) { - var from = {}; - var to = {}; - if (this.from != this.to) { - from = this._findBorderPosition(this.from, ctx); - to = this._findBorderPosition(this.to, ctx); - } else { - var _getCircleData5 = this._getCircleData(ctx); + from = to; + } + } - var _getCircleData52 = _slicedToArray(_getCircleData5, 3); + /** + * Parse a set with attributes, + * for example [label="1.000", shape=solid] + * @return {Object | null} attr + */ + function parseAttributeList() { + var attr = null; - var x = _getCircleData52[0]; - var y = _getCircleData52[1]; - var radius = _getCircleData52[2]; + while (token === '[') { + getToken(); + attr = {}; + while (token !== '' && token != ']') { + if (tokenType != TOKENTYPE.IDENTIFIER) { + throw newSyntaxError('Attribute name expected'); + } + var name = token; - from = this._findBorderPositionCircle(this.from, ctx, { x: x, y: y, low: 0.25, high: 0.6, direction: -1 }); - to = this._findBorderPositionCircle(this.from, ctx, { x: x, y: y, low: 0.6, high: 0.8, direction: 1 }); + getToken(); + if (token != '=') { + throw newSyntaxError('Equal sign = expected'); } - return { from: from, to: to }; - } - }, { - key: '_getCircleData', - value: function _getCircleData(ctx) { - var x = undefined, - y = undefined; - var node = this.from; - var radius = this.options.selfReferenceSize; + getToken(); - if (ctx !== undefined) { - if (node.shape.width === undefined) { - node.shape.resize(ctx); - } + if (tokenType != TOKENTYPE.IDENTIFIER) { + throw newSyntaxError('Attribute value expected'); } + var value = token; + setValue(attr, name, value); // name can be a path - // get circle coordinates - if (node.shape.width > node.shape.height) { - x = node.x + node.shape.width * 0.5; - y = node.y - radius; - } else { - x = node.x + radius; - y = node.y - node.shape.height * 0.5; + getToken(); + if (token == ',') { + getToken(); } - return [x, y, radius]; } - }, { - key: '_pointOnCircle', - /** - * 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 - */ - 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) - }; + if (token != ']') { + throw newSyntaxError('Bracket ] expected'); } - }, { - key: '_findBorderPositionCircle', - - /** - * This function uses binary search to look for the point where the circle crosses the border of the node. - * @param node - * @param ctx - * @param options - * @returns {*} - * @private - */ - value: function _findBorderPositionCircle(node, ctx, options) { - var x = options.x; - var y = options.y; - var low = options.low; - var high = options.high; - var direction = options.direction; - - var maxIterations = 10; - var iteration = 0; - var radius = this.options.selfReferenceSize; - var pos = undefined, - angle = undefined, - distanceToBorder = undefined, - distanceToPoint = undefined, - difference = undefined; - var threshold = 0.05; - var middle = (low + high) * 0.5; + getToken(); + } - while (low <= high && iteration < maxIterations) { - middle = (low + high) * 0.5; + return attr; + } - pos = this._pointOnCircle(x, y, radius, middle); - 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 (direction > 0) { - low = middle; - } else { - high = middle; - } - } else { - if (direction > 0) { - high = middle; - } else { - low = middle; - } - } - iteration++; - } - pos.t = middle; + /** + * Create a syntax error with extra information on current token and index. + * @param {String} message + * @returns {SyntaxError} err + */ + function newSyntaxError(message) { + return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')'); + } - return pos; - } - }, { - key: 'getLineWidth', + /** + * Chop off text after a maximum length + * @param {String} text + * @param {Number} maxLength + * @returns {String} + */ + function chop(text, maxLength) { + return text.length <= maxLength ? text : text.substr(0, 27) + '...'; + } - /** - * Get the line width of the edge. Depends on width and whether one of the - * connected nodes is selected. - * @return {Number} width - * @private - */ - value: function getLineWidth(selected, hover) { - if (selected === true) { - return Math.max(this.selectionWidth, 0.3 / this.body.view.scale); + /** + * Execute a function fn for each pair of elements in two arrays + * @param {Array | *} array1 + * @param {Array | *} array2 + * @param {function} fn + */ + function forEach2(array1, array2, fn) { + if (Array.isArray(array1)) { + array1.forEach(function (elem1) { + if (Array.isArray(array2)) { + array2.forEach(function (elem2) { + fn(elem1, elem2); + }); } else { - if (hover === true) { - return Math.max(this.hoverWidth, 0.3 / this.body.view.scale); - } else { - return Math.max(this.options.width, 0.3 / this.body.view.scale); - } + fn(elem1, array2); } + }); + } else { + if (Array.isArray(array2)) { + array2.forEach(function (elem2) { + fn(array1, elem2); + }); + } else { + fn(array1, array2); } - }, { - key: 'getColor', - value: function getColor(ctx, selected, hover) { - var colorOptions = this.options.color; - if (colorOptions.inherit !== false) { - // when this is a loop edge, just use the 'from' method - if (colorOptions.inherit === 'both' && this.from.id !== this.to.id) { - var grd = ctx.createLinearGradient(this.from.x, this.from.y, this.to.x, this.to.y); - var fromColor = undefined, - toColor = undefined; - fromColor = this.from.options.color.highlight.border; - toColor = this.to.options.color.highlight.border; + } + } - if (this.from.selected === false && this.to.selected === false) { - fromColor = util.overrideOpacity(this.from.options.color.border, this.options.color.opacity); - toColor = util.overrideOpacity(this.to.options.color.border, this.options.color.opacity); - } else if (this.from.selected === true && this.to.selected === false) { - toColor = this.to.options.color.border; - } else if (this.from.selected === false && this.to.selected === true) { - fromColor = this.from.options.color.border; - } - grd.addColorStop(0, fromColor); - grd.addColorStop(1, toColor); + /** + * Set a nested property on an object + * When nested objects are missing, they will be created. + * For example setProp({}, 'font.color', 'red') will return {font: {color: 'red'}} + * @param {Object} object + * @param {string} path A dot separated string like 'font.color' + * @param {*} value Value for the property + * @return {Object} Returns the original object, allows for chaining. + */ + function setProp(object, path, value) { + var names = path.split('.'); + var prop = names.pop(); - // -------------------- this returns -------------------- // - return grd; - } + // traverse over the nested objects + var obj = object; + for (var i = 0; i < names.length; i++) { + var name = names[i]; + if (!(name in obj)) { + obj[name] = {}; + } + obj = obj[name]; + } - if (this.colorDirty === true) { - if (colorOptions.inherit === 'to') { - this.color.highlight = this.to.options.color.highlight.border; - this.color.hover = this.to.options.color.hover.border; - this.color.color = util.overrideOpacity(this.to.options.color.border, colorOptions.opacity); - } else { - // (this.options.color.inherit.source === "from") { - this.color.highlight = this.from.options.color.highlight.border; - this.color.hover = this.from.options.color.hover.border; - this.color.color = util.overrideOpacity(this.from.options.color.border, colorOptions.opacity); - } - } - } else if (this.colorDirty === true) { - this.color.highlight = colorOptions.highlight; - this.color.hover = colorOptions.hover; - this.color.color = util.overrideOpacity(colorOptions.color, colorOptions.opacity); - } + // set the property value + obj[prop] = value; - // if color inherit is on and gradients are used, the function has already returned by now. - this.colorDirty = false; + return object; + } - if (selected === true) { - return this.color.highlight; - } else if (hover === true) { - return this.color.hover; + /** + * Convert an object with DOT attributes to their vis.js equivalents. + * @param {Object} attr Object with DOT attributes + * @param {Object} mapping + * @return {Object} Returns an object with vis.js attributes + */ + function convertAttr(attr, mapping) { + var converted = {}; + + for (var prop in attr) { + if (attr.hasOwnProperty(prop)) { + var visProp = mapping[prop]; + if (Array.isArray(visProp)) { + visProp.forEach(function (visPropI) { + setProp(converted, visPropI, attr[prop]); + }); + } else if (typeof visProp === 'string') { + setProp(converted, visProp, attr[prop]); } else { - return this.color.color; + setProp(converted, prop, attr[prop]); } } - }, { - key: '_circle', + } - /** - * Draw a line from a node to itself, a circle - * @param {CanvasRenderingContext2D} ctx - * @param {Number} x - * @param {Number} y - * @param {Number} radius - * @private - */ - value: function _circle(ctx, x, y, radius) { - // draw shadow if enabled - this.enableShadow(ctx); + return converted; + } - // draw a circle - ctx.beginPath(); - ctx.arc(x, y, radius, 0, 2 * Math.PI, false); - ctx.stroke(); + /** + * Convert a string containing a graph in DOT language into a map containing + * with nodes and edges in the format of graph. + * @param {String} data Text containing a graph in DOT-notation + * @return {Object} graphData + */ + function DOTToGraph(data) { + // parse the DOT file + var dotData = parseDOT(data); + var graphData = { + nodes: [], + edges: [], + options: {} + }; - // disable shadows for other elements. - this.disableShadow(ctx); - } - }, { - key: 'getDistanceToEdge', + // copy the nodes + if (dotData.nodes) { + dotData.nodes.forEach(function (dotNode) { + var graphNode = { + id: dotNode.id, + label: String(dotNode.label || dotNode.id) + }; + merge(graphNode, convertAttr(dotNode.attr, NODE_ATTR_MAPPING)); + if (graphNode.image) { + graphNode.shape = 'image'; + } + graphData.nodes.push(graphNode); + }); + } + // copy the edges + if (dotData.edges) { /** - * 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 - * @param {number} y1 - * @param {number} x2 - * @param {number} y2 - * @param {number} x3 - * @param {number} y3 - * @private + * Convert an edge in DOT format to an edge with VisGraph format + * @param {Object} dotEdge + * @returns {Object} graphEdge */ - value: function getDistanceToEdge(x1, y1, x2, y2, x3, y3, via) { - // x3,y3 is the point - var returnValue = 0; - if (this.from != this.to) { - returnValue = this._getDistanceToEdge(x1, y1, x2, y2, x3, y3, via); - } else { - var _getCircleData6 = this._getCircleData(); - - var _getCircleData62 = _slicedToArray(_getCircleData6, 3); + var convertEdge = function convertEdge(dotEdge) { + var graphEdge = { + from: dotEdge.from, + to: dotEdge.to + }; + merge(graphEdge, convertAttr(dotEdge.attr, EDGE_ATTR_MAPPING)); + graphEdge.arrows = dotEdge.type === '->' ? 'to' : undefined; - var x = _getCircleData62[0]; - var y = _getCircleData62[1]; - var radius = _getCircleData62[2]; + return graphEdge; + }; - var dx = x - x3; - var dy = y - y3; - returnValue = Math.abs(Math.sqrt(dx * dx + dy * dy) - radius); + dotData.edges.forEach(function (dotEdge) { + var from, to; + if (dotEdge.from instanceof Object) { + from = dotEdge.from.nodes; + } else { + from = { + id: dotEdge.from + }; } - if (this.labelModule.size.left < x3 && this.labelModule.size.left + this.labelModule.size.width > x3 && this.labelModule.size.top < y3 && this.labelModule.size.top + this.labelModule.size.height > y3) { - return 0; + // TODO: support of solid/dotted/dashed edges (attr = 'style') + // TODO: support for attributes 'dir' and 'arrowhead' (edge arrows) + + if (dotEdge.to instanceof Object) { + to = dotEdge.to.nodes; } else { - return returnValue; + to = { + id: dotEdge.to + }; } - } - }, { - key: '_getDistanceToLine', - value: function _getDistanceToLine(x1, y1, x2, y2, x3, y3) { - var px = x2 - x1; - var py = y2 - y1; - var something = px * px + py * py; - var u = ((x3 - x1) * px + (y3 - y1) * py) / something; - if (u > 1) { - u = 1; - } else if (u < 0) { - u = 0; + if (dotEdge.from instanceof Object && dotEdge.from.edges) { + dotEdge.from.edges.forEach(function (subEdge) { + var graphEdge = convertEdge(subEdge); + graphData.edges.push(graphEdge); + }); } - var x = x1 + u * px; - var y = y1 + u * py; - var dx = x - x3; - var dy = y - y3; + forEach2(from, to, function (from, to) { + var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr); + var graphEdge = convertEdge(subEdge); + graphData.edges.push(graphEdge); + }); - //# Note: If the actual distance does not matter, - //# if you only want to compare what this function - //# returns to other results of this function, you - //# can just return the squared distance instead - //# (i.e. remove the sqrt) to gain a little performance + if (dotEdge.to instanceof Object && dotEdge.to.edges) { + dotEdge.to.edges.forEach(function (subEdge) { + var graphEdge = convertEdge(subEdge); + graphData.edges.push(graphEdge); + }); + } + }); + } - return Math.sqrt(dx * dx + dy * dy); - } - }, { - key: 'drawArrowHead', + // copy the options + if (dotData.attr) { + graphData.options = dotData.attr; + } - /** - * - * @param ctx - * @param position - * @param viaNode - */ - value: function drawArrowHead(ctx, position, viaNode, selected, hover) { - // set style - ctx.strokeStyle = this.getColor(ctx, selected, hover); - ctx.fillStyle = ctx.strokeStyle; - ctx.lineWidth = this.getLineWidth(selected, hover); + return graphData; + } - // set lets - var angle = undefined; - var length = undefined; - var arrowPos = undefined; - var node1 = undefined; - var node2 = undefined; - var guideOffset = undefined; - var scaleFactor = undefined; + // exports + exports.parseDOT = parseDOT; + exports.DOTToGraph = DOTToGraph; - if (position === 'from') { - node1 = this.from; - node2 = this.to; - guideOffset = 0.1; - scaleFactor = this.options.arrows.from.scaleFactor; - } else if (position === 'to') { - node1 = this.to; - node2 = this.from; - guideOffset = -0.1; - scaleFactor = this.options.arrows.to.scaleFactor; - } else { - node1 = this.to; - node2 = this.from; - scaleFactor = this.options.arrows.middle.scaleFactor; - } +/***/ }, +/* 111 */ +/***/ function(module, exports, __webpack_require__) { - // if not connected to itself - if (node1 != node2) { - if (position !== 'middle') { - // draw arrow head - if (this.options.smooth.enabled === true) { - arrowPos = this.findBorderPosition(node1, ctx, { via: viaNode }); - var guidePos = this.getPoint(Math.max(0, Math.min(1, arrowPos.t + guideOffset)), viaNode); - angle = Math.atan2(arrowPos.y - guidePos.y, arrowPos.x - guidePos.x); - } else { - angle = Math.atan2(node1.y - node2.y, node1.x - node2.x); - arrowPos = this.findBorderPosition(node1, ctx); - } - } else { - angle = Math.atan2(node1.y - node2.y, node1.x - node2.x); - arrowPos = this.getPoint(0.6, viaNode); // this is 0.6 to account for the size of the arrow. - } - // draw arrow at the end of the line - length = (10 + 5 * this.options.width) * scaleFactor; - ctx.arrow(arrowPos.x, arrowPos.y, angle, length); + 'use strict'; - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); + function parseGephi(gephiJSON, optionsObj) { + var edges = []; + var nodes = []; + var options = { + edges: { + inheritColor: false + }, + nodes: { + fixed: false, + parseColor: false + } + }; - // disable shadows for other elements. - this.disableShadow(ctx); - ctx.stroke(); - } else { - // draw circle - var _angle = undefined, - point = undefined; + if (optionsObj !== undefined) { + if (optionsObj.fixed !== undefined) { + options.nodes.fixed = optionsObj.fixed; + } + if (optionsObj.parseColor !== undefined) { + options.nodes.parseColor = optionsObj.parseColor; + } + if (optionsObj.inheritColor !== undefined) { + options.edges.inheritColor = optionsObj.inheritColor; + } + } - var _getCircleData7 = this._getCircleData(ctx); + var gEdges = gephiJSON.edges; + var gNodes = gephiJSON.nodes; + for (var i = 0; i < gEdges.length; i++) { + var edge = {}; + var gEdge = gEdges[i]; + edge['id'] = gEdge.id; + edge['from'] = gEdge.source; + edge['to'] = gEdge.target; + edge['attributes'] = gEdge.attributes; + // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined; + // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size; + if (gEdge.color && options.inheritColor === false) { + edge['color'] = gEdge.color; + } + edges.push(edge); + } - var _getCircleData72 = _slicedToArray(_getCircleData7, 3); + for (var i = 0; i < gNodes.length; i++) { + var node = {}; + var gNode = gNodes[i]; + node['id'] = gNode.id; + node['attributes'] = gNode.attributes; + node['title'] = gNode.title; + node['x'] = gNode.x; + node['y'] = gNode.y; + node['label'] = gNode.label; + if (options.nodes.parseColor === true) { + node['color'] = gNode.color; + } else { + node['color'] = gNode.color !== undefined ? { background: gNode.color, border: gNode.color, highlight: { background: gNode.color, border: gNode.color }, hover: { background: gNode.color, border: gNode.color } } : undefined; + } + node['size'] = gNode.size; + node['fixed'] = options.nodes.fixed && gNode.x !== undefined && gNode.y !== undefined; + nodes.push(node); + } - var x = _getCircleData72[0]; - var y = _getCircleData72[1]; - var radius = _getCircleData72[2]; + return { nodes: nodes, edges: edges }; + } - if (position === 'from') { - point = this.findBorderPosition(this.from, ctx, { x: x, y: y, low: 0.25, high: 0.6, direction: -1 }); - _angle = point.t * -2 * Math.PI + 1.5 * Math.PI + 0.1 * Math.PI; - } else if (position === 'to') { - point = this.findBorderPosition(this.from, ctx, { x: x, y: y, low: 0.6, high: 1, direction: 1 }); - _angle = point.t * -2 * Math.PI + 1.5 * Math.PI - 1.1 * Math.PI; - } else { - point = this._pointOnCircle(x, y, radius, 0.175); - _angle = 3.9269908169872414; // === 0.175 * -2 * Math.PI + 1.5 * Math.PI + 0.1 * Math.PI; - } + exports.parseGephi = parseGephi; - // draw the arrowhead - var _length = (10 + 5 * this.options.width) * scaleFactor; - ctx.arrow(point.x, point.y, _angle, _length); +/***/ }, +/* 112 */ +/***/ function(module, exports, __webpack_require__) { - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); + /** + * @class Images + * This class loads images and keeps them stored. + */ + "use strict"; - // disable shadows for other elements. - this.disableShadow(ctx); - ctx.stroke(); + function Images(callback) { + this.images = {}; + this.imageBroken = {}; + this.callback = callback; + } + + /** + * + * @param {string} url Url of the image + * @param {string} url Url of an image to use if the url image is not found + * @return {Image} img The image object + */ + Images.prototype.load = function (url, brokenUrl, id) { + var img = this.images[url]; // make a pointer + if (img === undefined) { + // create the image + var me = this; + img = new Image(); + img.onload = function () { + // IE11 fix -- thanks dponch! + if (this.width === 0) { + document.body.appendChild(this); + this.width = this.offsetWidth; + this.height = this.offsetHeight; + document.body.removeChild(this); } - } - }, { - key: 'enableShadow', - value: function enableShadow(ctx) { - if (this.options.shadow.enabled === true) { - ctx.shadowColor = 'rgba(0,0,0,0.5)'; - ctx.shadowBlur = this.options.shadow.size; - ctx.shadowOffsetX = this.options.shadow.x; - ctx.shadowOffsetY = this.options.shadow.y; + + if (me.callback) { + me.images[url] = img; + me.callback(this); } - } - }, { - key: 'disableShadow', - value: function disableShadow(ctx) { - if (this.options.shadow.enabled === true) { - ctx.shadowColor = 'rgba(0,0,0,0)'; - ctx.shadowBlur = 0; - ctx.shadowOffsetX = 0; - ctx.shadowOffsetY = 0; + }; + + img.onerror = function () { + if (brokenUrl === undefined) { + console.error("Could not load image:", url); + delete this.src; + if (me.callback) { + me.callback(this); + } + } else { + if (me.imageBroken[id] && me.imageBroken[id][url] === true) { + console.error("Could not load brokenImage:", brokenUrl); + delete this.src; + if (me.callback) { + me.callback(this); + } + } else { + console.error("Could not load image:", url); + this.src = brokenUrl; + if (me.imageBroken[id] === undefined) { + me.imageBroken[id] = {}; + } + me.imageBroken[id][url] = true; + } } - } - }]); + }; - return EdgeBase; - })(); + img.src = url; + } - exports['default'] = EdgeBase; - module.exports = exports['default']; + return img; + }; + + module.exports = Images; + +/***/ }, +/* 113 */ +/***/ function(module, exports, __webpack_require__) { + + // English + 'use strict'; + + exports['en'] = { + edit: 'Edit', + del: 'Delete selected', + back: 'Back', + addNode: 'Add Node', + addEdge: 'Add Edge', + editNode: 'Edit Node', + editEdge: 'Edit Edge', + addDescription: 'Click in an empty space to place a new node.', + edgeDescription: 'Click on a node and drag the edge to another node to connect them.', + editEdgeDescription: 'Click on the control points and drag them to a node to connect to it.', + createEdgeError: 'Cannot link edges to a cluster.', + deleteClusterError: 'Clusters cannot be deleted.', + editClusterError: 'Clusters cannot be edited.' + }; + exports['en_EN'] = exports['en']; + exports['en_US'] = exports['en']; + + // Dutch + exports['nl'] = { + edit: 'Wijzigen', + del: 'Selectie verwijderen', + back: 'Terug', + addNode: 'Node toevoegen', + addEdge: 'Link toevoegen', + editNode: 'Node wijzigen', + editEdge: 'Link wijzigen', + addDescription: 'Klik op een leeg gebied om een nieuwe node te maken.', + edgeDescription: 'Klik op een node en sleep de link naar een andere node om ze te verbinden.', + editEdgeDescription: 'Klik op de verbindingspunten en sleep ze naar een node om daarmee te verbinden.', + createEdgeError: 'Kan geen link maken naar een cluster.', + deleteClusterError: 'Clusters kunnen niet worden verwijderd.', + editClusterError: 'Clusters kunnen niet worden aangepast.' + }; + exports['nl_NL'] = exports['nl']; + exports['nl_BE'] = exports['nl']; /***/ } /******/ ]) diff --git a/dist/vis.map b/dist/vis.map index 944ffd9e..1a0868f3 100644 --- a/dist/vis.map +++ b/dist/vis.map @@ -1 +1 @@ -{"version":3,"file":"vis.map","sources":["./dist/vis.js"],"names":["root","factory","exports","module","define","amd","this","modules","__webpack_require__","moduleId","installedModules","id","loaded","call","m","c","p","util","DOMutil","DataSet","DataView","Queue","Graph3d","graph3d","Camera","Filter","Point2d","Point3d","Slider","StepNumber","Timeline","Graph2d","timeline","DateUtil","DataStep","Range","stack","TimeStep","components","items","Item","BackgroundItem","BoxItem","PointItem","RangeItem","Component","CurrentTime","CustomTime","DataAxis","GraphGroup","Group","BackgroundGroup","ItemSet","Legend","LineGraph","TimeAxis","Network","network","Images","dotparser","gephiParser","convertDot","input","DOTToGraph","convertGephi","options","parseGephi","Graph","Error","moment","hammer","Hammer","_interopRequireDefault","obj","__esModule","default","_classCallCheck","instance","Constructor","TypeError","Object","defineProperty","value","_createClass","defineProperties","target","props","i","length","descriptor","enumerable","configurable","writable","key","protoProps","staticProps","prototype","_componentsNodesCluster","_componentsNodesCluster2","ClusterEngine","body","_this","clusteredNodes","defaultOptions","extend","emitter","on","hubsize","undefined","_getHubSize","tyepof","_checkOptions","nodesToCluster","nodeIndices","node","nodes","edges","push","clusterByConnection","emit","arguments","refreshData","joinCondition","childNodesObj","childEdgesObj","nodeId","clonedOptions","_cloneOptions","_i","edge","_cluster","clusters","visibleEdges","j","hidden","childNodeId","_getConnectedId","_checkIfUsed","keys","edgeId","cluster","clusterNodeProperties","x","y","fixed","parentNodeId","parentClonedOptions","childClonedOptions","item","type","deepExtend","amountOfConnections","newEdges","clusterEdgeProperties","childNode","toId","fromId","otherNodeId","childKeys","from","to","randomUUID","functions","createEdge","processProperties","childNodesOptions","childEdgesOptions","clusterId","label","pos","_getClusterPosition","clusterNode","createNode","isCluster","containedNodes","containedEdges","_createClusterEdges","hasOwnProperty","togglePhysics","connect","console","log","minX","maxX","minY","maxY","clusterNodeId","containedNode","vx","vy","edgeType","cleanup","disconnect","clusteredNode","_clusterNode","physics","newEdge","clusterStack","findNode","pop","fromArray","toArray","max","counter","average","averageSquared","hubCounter","largestHub","Math","pow","letiance","standardDeviation","sqrt","hubThreshold","floor","prepareElements","JSONcontainer","elementType","redundant","used","cleanupElements","parentNode","removeChild","getSVGElement","svgContainer","element","shift","document","createElementNS","appendChild","getDOMElement","DOMContainer","insertBefore","createElement","drawPoint","group","labelObj","point","drawPoints","style","setAttributeNS","size","styles","className","xOffset","yOffset","content","textContent","drawBar","width","height","rect","data","Array","isArray","_options","_data","_fieldId","fieldId","_type","field","convert","_subscribers","add","setOptions","queue","_queue","destroy","replace","event","callback","subscribers","subscribe","off","filter","listener","unsubscribe","_trigger","params","senderId","concat","subscriber","addedIds","me","len","_addItem","update","updatedIds","updatedData","addOrUpdate","_updateItem","get","args","ids","firstType","getType","returnType","allowedValues","indexOf","itemId","_getItem","order","_sort","fields","_filterFields","result","getIds","getDataSet","forEach","map","mappedItems","filteredItem","isString","name","sort","a","b","av","bv","remove","removedId","removedIds","_remove","isNumber","clear","maxField","itemField","min","minField","distinct","values","fieldType","count","prop","exists","d","types","raw","converted","JSON","stringify","_ids","_onEvent","apply","setData","refresh","newIds","added","removed","viewOptions","getArguments","defaultFilter","dataSet","updated","delay","Infinity","_timeout","_extended","_flushIfNeeded","object","flush","methods","original","method","fn","context","entry","clearTimeout","setTimeout","container","SyntaxError","containerElement","margin","defaultXCenter","defaultYCenter","xLabel","yLabel","zLabel","passValueFn","v","xValueLabel","yValueLabel","zValueLabel","filterLabel","legendLabel","STYLE","DOT","showPerspective","showGrid","keepAspectRatio","showShadow","showGrayBottom","showTooltip","verticalRatio","animationInterval","animationPreload","camera","eye","dataTable","dataPoints","colX","colY","colZ","colValue","colFilter","xMin","xStep","xMax","yMin","yStep","yMax","zMin","zStep","zMax","valueMin","valueMax","xBarWidth","yBarWidth","colorAxis","colorGrid","colorDot","colorDotBorder","create","getMouseX","clientX","targetTouches","getMouseY","clientY","Emitter","_setScale","scale","z","xCenter","yCenter","zCenter","setArmLocation","_convert3Dto2D","point3d","translation","_convertPointToTranslation","_convertTranslationToScreen","ax","ay","az","cx","getCameraLocation","cy","cz","sinTx","sin","getCameraRotation","cosTx","cos","sinTy","cosTy","sinTz","cosTz","dx","dy","dz","bx","by","ex","ey","ez","getArmLength","xcenter","frame","canvas","clientWidth","ycenter","_setBackgroundColor","backgroundColor","fill","stroke","strokeWidth","borderColor","borderWidth","borderStyle","BAR","BARCOLOR","BARSIZE","DOTLINE","DOTCOLOR","DOTSIZE","GRID","LINE","SURFACE","_getStyleNumber","styleName","_determineColumnIndexes","getNumberOfColumns","getNumberOfRows","column","getDistinctValues","distinctValues","getColumnRange","minMax","_dataInitialize","rawData","_onChange","dataFilter","setOnLoadCallback","redraw","withBars","defaultXBarWidth","dataX","defaultYBarWidth","dataY","xRange","defaultXMin","defaultXMax","defaultXStep","yRange","defaultYMin","defaultYMax","defaultYStep","zRange","defaultZMin","defaultZMax","defaultZStep","valueRange","defaultValueMin","defaultValueMax","_getDataPoints","sortNumber","dataMatrix","xIndex","yIndex","trans","screen","bottom","pointRight","pointTop","pointCross","hasChildNodes","firstChild","position","overflow","noCanvas","color","fontWeight","padding","innerHTML","left","onmousedown","_onMouseDown","ontouchstart","_onTouchStart","onmousewheel","_onWheel","ontooltip","_onTooltip","addEventListener","onkeydown","setSize","_resizeCanvas","clientHeight","animationStart","slider","play","animationStop","stop","_resizeCenter","charAt","parseFloat","setCameraPosition","horizontal","vertical","setArmRotation","distance","setArmLength","getCameraPosition","getArmRotation","_readData","_redrawFilter","animationAutoStart","cameraPosition","styleNumber","tooltip","showAnimationControls","_redrawSlider","_redrawClear","_redrawAxis","_redrawDataGrid","_redrawDataLine","_redrawDataBar","_redrawDataDot","_redrawInfo","_redrawLegend","ctx","getContext","clearRect","widthMin","widthMax","dotSize","top","right","lineWidth","font","ymin","ymax","f","hue","_hsv2rgb","strokeStyle","beginPath","moveTo","lineTo","strokeRect","fillStyle","closePath","gridLineLen","step","start","getCurrent","next","end","textAlign","textBaseline","fillText","visible","setValues","setPlayInterval","onchange","index","getIndex","selectValue","setOnChangeCallback","lineStyle","getLabel","getSelectedValue","prettyStep","text","xText","yText","zText","offset","xMin2d","xMax2d","gridLenX","gridLenY","textMargin","armAngle","H","S","V","R","G","B","C","Hi","X","abs","parseInt","cross","topSideVisible","h","s","zAvg","transBottom","dist","sortDepth","aDiff","subtract","bDiff","crossproduct","crossProduct","radius","arc","PI","surface","corners","xWidth","yWidth","surfaces","center","avg","transCenter","diff","window","leftButtonDown","_onMouseUp","which","button","touchDown","startMouseX","startMouseY","startStart","Date","startEnd","startArmRotation","cursor","onmousemove","_onMouseMove","onmouseup","preventDefault","diffX","diffY","horizontalNew","verticalNew","snapAngle","snapValue","round","parameters","removeEventListener","boundingRect","getBoundingClientRect","mouseX","mouseY","tooltipTimeout","_hideTooltip","dataPoint","_dataPointFromXY","_showTooltip","ontouchmove","_onTouchMove","ontouchend","_onTouchEnd","delta","wheelDelta","detail","oldLength","newLength","_insideTriangle","triangle","sign","as","bs","cs","distMax","closestDataPoint","closestDist","triangle1","triangle2","distX","distY","line","dot","dom","border","background","borderRadius","boxShadow","borderLeft","contentWidth","offsetWidth","contentHeight","offsetHeight","lineHeight","dotWidth","dotHeight","elem","armLocation","armRotation","armLength","cameraLocation","cameraRotation","calculateCameraOrientation","rot","graph","onLoadCallback","loadInBackground","isLoaded","getLoadedProgress","getColumn","getValues","getValue","dataView","progress","sub","sum","prev","bar","MozBorderRadius","slide","onclick","togglePlay","onChangeCallback","playTimeout","playInterval","playLoop","setIndex","playNext","interval","clearInterval","getPlayInterval","setPlayLoop","doLoop","onChange","indexToLeft","startClientX","startSlideX","leftToIndex","_start","_end","_step","precision","_current","setRange","setStep","calculatePrettyStep","log10","LN10","step1","step2","step5","toPrecision","getStep","groups","forthArgument","autoResize","orientation","axis","maxHeight","minHeight","_create","domProps","bind","hiddenDates","getScale","timeAxis","toScreen","_toScreen","toGlobalScreen","_toGlobalScreen","toTime","_toTime","toGlobalTime","_toGlobalTime","range","timeAxis2","currentTime","itemSet","itemsData","groupsData","getEventProperties","oncontextmenu","configurator","Configurator","configureOptions","setGroups","setItems","_redraw","Core","Validator","printStyle","allOptions","markDirty","refreshItems","errorFound","validate","selection","getSelection","setSelection","newDataSet","initialLoad","dataRange","_getDataRange","setWindow","animation","fit","focus","itemData","valueOf","e","middle","getItemRange","dataset","minItem","maxStartItem","maxEndItem","getAbsoluteLeft","centerContainer","getAbsoluteTop","itemFromTarget","groupFromTarget","customTime","customTimeFromTarget","snap","time","snappedTime","getTarget","what","hasParent","foreground","labelSet","groupId","pageX","srcEvent","pageY","linegraph","getLegend","isGroupVisible","visibility","yAxisLeft","yAxisRight","legendLeft","legendRight","screenToValue","convertHiddenOptions","repeat","dateItem","toDate","updateHiddenDates","totalRange","pixelTime","startDate","endDate","_d","duration","runUntil","clone","day","dayOfYear","year","dayOffset","date","month","removeDuplicates","startHidden","isHidden","endHidden","rangeStart","rangeEnd","startToFront","endToFront","_applyRange","safeDates","printDates","dates","stepOverHiddenDates","timeStep","previousTime","stepInHidden","currentValue","current","prevValue","newValue","switchedYear","switchedMonth","switchedDay","conversion","getHiddenDurationBetween","correctTimeForHidden","hiddenDuration","totalDuration","partialDuration","accumulatedHiddenDuration","getAccumulatedHiddenDuration","newTime","getHiddenDurationBefore","timeOffset","requiredDuration","previousPoint","snapAwayFromHidden","direction","correctionEnabled","minimumStep","containerHeight","customRange","formattingFunction","alignZeros","autoScale","stepIndex","marginStart","marginEnd","deadSpace","majorSteps","minorSteps","setMinimumStep","setFirst","safeRange","minimumStepValue","orderOfMagnitude","minorStepIdx","magnitudefactor","solutionFound","stepSize","niceStart","niceEnd","roundToMinor","marginRange","rounded","hasNext","previous","returnValue","isMajor","steps","now","hours","minutes","seconds","milliseconds","deltaDifference","scaleOffset","moveable","zoomable","zoomMin","zoomMax","touch","animationTimer","_onDragStart","_onDrag","_onDragEnd","_onMouseWheel","_onTouch","_onPinch","validateDirection","getPointer","selectiveExtend","byUser","finalStart","finalEnd","_cancelAnimation","initStart","initEnd","easingName","easingFunction","easingFunctions","join","initTime","anyChanged","dragging","ease","done","changed","newStart","newEnd","isNaN","getRange","totalHidden","previousDelta","allowDragging","deltaX","deltaY","diffRange","safeStart","safeEnd","pointer","pointerDate","_pointerToDate","zoom","centerDate","hiddenDurationBefore","hiddenDurationAfter","move","EPSILON","orderByStart","orderByEnd","aTime","bTime","force","iMax","collidingItem","jj","other","collision","nostack","subgroups","newTop","subgroup","format","FORMAT","minorLabels","millisecond","second","minute","hour","weekday","majorLabels","setFormat","defaultFormat","first","setFullYear","getFullYear","setMonth","setDate","setHours","setMinutes","setSeconds","setMilliseconds","getMilliseconds","getSeconds","getMinutes","getHours","getDate","getMonth","setScale","setAutoScale","enable","stepYear","stepMonth","stepDay","stepHour","stepMinute","stepSecond","stepMillisecond","getLabelMinor","getLabelMajor","getClassName","even","today","isSame","currentWeek","currentMonth","currentYear","locale","lang","trim","toLowerCase","isVisible","box","dirty","parent","displayed","_updateContents","_updateTitle","_updateDataAttributes","_updateStyle","selected","_repaintDeleteButton","show","hide","repositionX","align","repositionY","itemSetHeight","select","unselect","groupChanged","_moveToGroup","setParent","anchor","editable","deleteButton","title","removeFromDataSet","stopPropagation","template","_contentToString","Element","removeAttribute","dataAttributes","attributes","setAttribute","removeCssText","addCssText","outerHTML","baseClassName","getComputedStyle","onTop","itemSubgroup","subgroupIndex","totalHeight","newHeight","marginLeft","maxWidth","_repaintDragLeft","_repaintDragRight","limitSize","contentLeft","parentWidth","boxWidth","updateTime","dragLeft","dragLeftItem","dragRight","dragRightItem","_isResized","resized","_previousWidth","_previousHeight","showCurrentTime","locales","backgroundVertical","warned","toUpperCase","substring","currentTimeTimer","setCurrentTime","t","getCurrentTime","eventParams","drag","setCustomTime","getCustomTime","svg","linegraphOptions","showMinorLabels","showMajorLabels","icons","majorLinesOffset","minorLinesOffset","labelOffsetX","labelOffsetY","iconWidth","linegraphSVG","DOMelements","lines","labels","conversionFactor","Number","minWidth","stepPixels","zeroCrossing","amountOfSteps","lineOffset","master","svgElements","iconsRemoved","amountOfGroups","lineContainer","scrollTop","addGroup","graphOptions","updateGroup","removeGroup","display","_redrawGroupIcons","iconHeight","iconOffset","groupArray","drawIcon","_cleanupIcons","backgroundHorizontal","activeGroups","_calculateCharSize","minorLabelHeight","minorCharHeight","majorLabelHeight","majorCharHeight","minorLineWidth","minorLineHeight","majorLineWidth","majorLineHeight","_redrawLabels","_redrawTitle","ceil","valueAtBottom","maxLabelSize","_redrawLabel","_redrawLine","titleWidth","titleCharHeight","convertValue","invertedValue","convertedValue","characterHeight","largestWidth","majorCharWidth","minorCharWidth","textMinor","createTextNode","measureCharMinor","textMajor","measureCharMajor","textTitle","measureCharTitle","titleCharWidth","groupsUsingDefaultStyles","selectiveBridgeObject","usingDefaultStyle","zeroPosition","Line","Bar","Points","setZeroPosition","selectiveDeepExtend","mergeOptions","interpolation","parametrization","alpha","SVGcontainer","path","fillPath","fillHeight","outline","shaded","enabled","barWidth","bar1Height","bar2Height","icon","yAxisOrientation","getYRange","groupData","getData","draw","framework","subgroupOrderer","subgroupOrder","visibleItems","orderedItems","byStart","byEnd","checkRangedItems","inner","marker","removeClassName","addClassName","getLabelWidth","restack","markerHeight","lastMarkerHeight","customOrderedItems","slice","_updateVisibleItems","_calculateHeight","offsetTop","offsetLeft","updateProperty","ii","resetSubgroups","orderSubgroups","_checkIfVisible","sortArray","sortField","splice","removeItem","array","startArray","endArray","oldVisibleItems","visibleItemsLookup","lowerBound","upperBound","searchFunction","_checkIfVisibleWithReference","initialPosByStart","binarySearchCustom","_traceVisible","initialPosByEnd","initialPos","breakCondition","groupOrder","selectable","multiselect","onAdd","onUpdate","onMove","onRemove","onMoving","itemOptions","itemListeners","_onAdd","_onUpdate","_onRemove","groupListeners","_onAddGroups","_onUpdateGroups","_onRemoveGroups","groupIds","stackDirty","touchParams","UNGROUPED","BACKGROUND","_updateUngrouped","backgroundGroup","isFirst","_onSelectItem","_onMultiSelectItem","_onAddItem","addCallback","Function","getVisibleItems","rawVisibleItems","_deselect","asSize","option","_orderGroups","visibleInterval","zoomed","lastVisibleInterval","lastWidth","firstGroup","_firstGroup","firstMargin","nonFirstMargin","groupMargin","groupResized","firstGroupIndex","firstGroupId","ungrouped","_getGroupId","getLabelSet","oldItemsData","getItems","_order","getGroups","_getType","constructor","_removeItem","groupOptions","equalArray","oldGroupId","oldSubGroupId","oldGroup","_constructByEndArray","itemProps","initialX","ctrlKey","_onDragStartAddItem","xAbs","newItem","initial","initialStart","initialEnd","changes","shiftKey","oldSelection","newSelection","_getItemRange","_item","itemSetFromTarget","side","iconSize","iconSpacing","textArea","scrollableHeight","drawLegendIcons","paddingTop","defaultGroup","sampling","graphHeight","barChart","sideBySide","dataAxis","legend","abortedGraphUpdate","updateSVGheight","updateSVGheightOnResize","lastStart","COUNTER","BarFunctions","LineFunctions","_updateAllGroupData","_updateGroup","groupsContent","ungroupedCounter","forceGraphUpdate","_updateGraph","rangePerPixelInv","preprocessedGroupData","processedGroupData","groupRanges","changeCalled","minDate","maxDate","_getRelevantData","_applySampling","_convertXcoordinates","_getYRanges","_updateYAxis","MAX_CYCLES","_convertYcoordinates","dataContainer","guess","binarySearchValue","increment","amountOfPoints","xDistance","pointsPerPixel","sampledData","combinedDataLeft","combinedDataRight","getStackedYRange","minVal","maxVal","yAxisLeftUsed","yAxisRightUsed","minLeft","minRight","maxLeft","maxRight","ignore","_toggleAxisVisiblity","drawIcons","tempGroups","axisUsed","datapoints","xValue","yValue","extractedData","svgHeight","labelValue","majorTexts","minorTexts","lineTop","parentChanged","foregroundNextSibling","nextSibling","backgroundNextSibling","_repaintLabels","timeLabelsize","cur","prevLine","xPrev","xFirstMajorLabel","_repaintMinorText","_repaintMajorText","_repaintMajorLine","_repaintMinorLine","leftTime","leftText","widthText","arr","childNodes","nodeValue","clickToUse","edgeIndices","once","eventListeners","onTap","onTouch","onDoubleTap","onHold","onDragStart","onDrag","onDragEnd","onMouseWheel","onPinch","onMouseMove","onRelease","onContext","view","bindEventListeners","images","_modulesGroups2","_modulesCanvas2","selectionHandler","_modulesSelectionHandler2","interactionHandler","_modulesInteractionHandler2","_modulesView2","renderer","_modulesCanvasRenderer2","_modulesPhysicsEngine2","layoutEngine","_modulesLayoutEngine2","clustering","_modulesClustering2","manipulation","_modulesManipulationSystem2","nodesHandler","_modulesNodesHandler2","edgesHandler","_modulesEdgesHandler2","_sharedConfigurator2","_optionsJs","pixelRatio","_modulesGroups","_modulesNodesHandler","_modulesEdgesHandler","_modulesPhysicsEngine","_modulesClustering","_modulesCanvasRenderer","_modulesCanvas","_modulesView","_modulesInteractionHandler","_modulesSelectionHandler","_modulesLayoutEngine","_modulesManipulationSystem","_sharedConfigurator","_sharedValidator","_sharedValidator2","Activator","layout","interaction","configure","networkOptions","global","setModuleOptions","activator","_createKeyBinds","_updateVisibleIndices","_this2","updatePhysicsData","_updateValueRange","unselectAll","dotData","gephi","gephiData","recursiveDOMDelete","valueTotal","setValueRange","isActive","active","canvasToDOM","DOMtoCanvas","openCluster","clusterByHubsize","clusterOutliers","getSeed","enableEditMode","disableEditMode","addNodeMode","editNodeMode","addEdgeMode","editEdgeMode","deleteSelected","getPositions","storePositions","getBoundingBox","getConnectedNodes","objectId","getEdges","startSimulation","stopSimulation","stabilize","getSelectedNodes","getSelectedEdges","getNodeAt","getEdgeAt","selectNodes","selectEdges","getViewPosition","releaseNode","imageBroken","load","url","brokenUrl","img","Image","onload","onerror","error","src","parseDOT","parseGraph","nextPreview","isAlphaNumeric","regexAlphaNumeric","test","merge","setValue","split","o","addNode","graphs","attr","g","addEdge","getToken","tokenType","TOKENTYPE","NULL","token","isComment","DELIMITER","c2","DELIMITERS","IDENTIFIER","newSyntaxError","UNKNOWN","chop","strict","parseStatements","parseStatement","subgraph","parseSubgraph","parseEdge","parseAttributeStatement","parseNodeStatement","subgraphs","parseAttributeList","message","maxLength","substr","forEach2","array1","array2","elem1","elem2","setProp","names","convertAttr","mapping","visProp","visPropI","graphData","dotNode","graphNode","String","NODE_ATTR_MAPPING","image","shape","convertEdge","dotEdge","graphEdge","EDGE_ATTR_MAPPING","arrows","subEdge","fontsize","fontcolor","labelfontcolor","fontname","fillcolor","labeltooltip","{","}","[","]",";","=",",","->","--","gephiJSON","optionsObj","inheritColor","parseColor","gEdges","gNodes","gEdge","source","gNode","highlight","hover","propagating","parse","buf","oct","_hexToByte","unparse","bth","_byteToHex","v1","clockseq","_clockseq","msecs","getTime","nsecs","_lastNSecs","dt","_lastMSecs","tl","tmh","_nodeId","n","v4","rnds","random","rng","_rng","globalVar","crypto","getRandomValues","_rnds8","Uint8Array","_rnds","r","toString","_seedBytes","uuid","hammerUtil","leftContainer","rightContainer","shadowTop","shadowBottom","shadowTopLeft","shadowBottomLeft","shadowTopRight","shadowBottomRight","properties","_redrawTimer","set","listeners","events","scrollTopMin","customTimes","redrawCount","_initAutoResize","component","appliedOptions","_stopAutoResize","addCustomTime","timestamp","some","removeCustomTime","getWindow","borderRootHeight","borderRootWidth","autoHeight","centerWidth","_updateScrollTop","visibilityTop","visibilityBottom","MAX_REDRAWS","repaint","_startAutoResize","_onResize","lastHeight","watchTimer","setInterval","initialScrollTop","oldScrollTop","_getScrollTop","newScrollTop","_setScrollTop","_ColorPicker","_ColorPicker2","parentModule","defaultContainer","changedOptions","allowCreation","showButton","moduleOptions","domElements","colorPicker","wrapper","_clean","_handleObject","_makeItem","_makeHeader","generateButton","_printOptions","onmouseover","onmouseout","optionsContainer","_push","insertTo","base","_len","_key","div","objectLabel","selectedValue","_update","_makeLabel","defaultValue","oninput","checkbox","checked","_this3","defaultColor","_showColorPicker","_this4","bodyRect","pickerX","pickerY","setColor","setCallback","colorString","checkOnly","visibleInSet","subObj","newPath","copyAndExtendArray","_getValue","_handleArray","_makeTextInput","_makeCheckbox","solver","enabledPath","enabledValue","_makeColorField","_makeDropdown","_makeRange","_constructOptions","referenceOptions","subObject","usedOptions","check","__any__","getSuggestion","checkFields","__type__","referenceOption","refOptionObj","optionType","refOptionType","print","printLocation","Boolean","nodeType","_isAMomentObject","localSearch","findInOptions","globalSearch","localSearchThreshold","globalSearchThreshold","indexMatch","closestMatch","recursive","closestMatchPath","lowerCaseOption","op","levenshteinDistance","copyArray","prefix","str","matrix","string","boolean","number","nada","undef","any","inputHandler","isTouching","isFinal","isReleasing","offTouch","offRelease","combinedData","groupLabel","intersections","_getDataIntersections","_getStackedYRange","accumulatedNegative","accumulatedPositive","xpos","coreDistance","amount","resolved","_catmullRom","_linear","dFill","_catmullRomUniform","p0","p1","p2","p3","bp1","bp2","normalization","d1","d2","d3","A","N","M","d3powA","d2powA","d3pow2A","d2pow2A","d1pow2A","d1powA","Bargraph","drawData","barPoints","heightOffset","_getSafeDrawData","nextKey","prevKey","Groups","defaultIndex","groupsArray","groupIndex","defaultGroups","useDefaultGroups","optionFields","groupName","groupname","_componentsNode","_componentsNode2","_componentsSharedLabel","_componentsSharedLabel2","NodesHandler","nodesListeners","borderWidthSelected","brokenImage","face","strokeColor","code","level","mass","scaling","maxVisible","drawThreshold","customScalingFunction","total","shadow","parseOptions","updateShape","updateLabelModule","_reset","doNotEmit","oldNodesData","newNodes","_properties","positionInitially","changedData","dataChanged","constructorClass","dataArray","boundingBox","nodeList","nodeObj","edgeList","_componentsEdge","_componentsEdge2","EdgesHandler","edgesListeners","scaleFactor","inherit","opacity","dashes","hoverWidth","selectionWidth","selfReferenceSize","smooth","roundness","emitChange","edgeData","edgeOptions","dynamic","reconnectEdges","markAllEdgesAsDirty","updateEdgeType","oldEdgesData","edgesData","oldEdge","showInternalIds","via","supportNodes","colorDirty","_componentsPhysicsBarnesHutSolver","_componentsPhysicsBarnesHutSolver2","_componentsPhysicsRepulsionSolver","_componentsPhysicsRepulsionSolver2","_componentsPhysicsHierarchicalRepulsionSolver","_componentsPhysicsHierarchicalRepulsionSolver2","_componentsPhysicsSpringSolver","_componentsPhysicsSpringSolver2","_componentsPhysicsHierarchicalSpringSolver","_componentsPhysicsHierarchicalSpringSolver2","_componentsPhysicsCentralGravitySolver","_componentsPhysicsCentralGravitySolver2","_componentsPhysicsFA2BasedRepulsionSolver","_componentsPhysicsFA2BasedRepulsionSolver2","_componentsPhysicsFA2BasedCentralGravitySolver","_componentsPhysicsFA2BasedCentralGravitySolver2","PhysicsEngine","physicsBody","physicsNodeIndices","physicsEdgeIndices","forces","velocities","physicsEnabled","simulationInterval","requiresTimeout","previousStates","freezeCache","renderTimer","stabilized","startedStabilization","stabilizationIterations","ready","barnesHut","theta","gravitationalConstant","centralGravity","springLength","springConstant","damping","avoidOverlap","forceAtlas2Based","repulsion","nodeDistance","hierarchicalRepulsion","maxVelocity","minVelocity","stabilization","iterations","updateInterval","onlyDynamicEdges","timestep","initPhysics","selectiveNotDeepExtend","init","nodesSolver","edgesSolver","gravitySolver","modelOptions","viewFunction","simulationStep","_emitStabilized","startTime","physicsTick","physicsTime","runDoubleSpeed","calculateForces","moveNodes","revert","nodeIds","nodesPresent","vminCorrected","nodeVelocity","_performStep","totalVelocity","solve","targetIterations","_freezeNodes","_stabilizationBatch","_finalizeStabilization","_restoreFrozenNodes","DOMobject","giveRange","isDate","match","ASPDateRegex","exec","assignAllKeys","fillIfDefined","allowDeletion","protoExtend","isMoment","toISOString","newArr","classes","action","useCapture","navigator","userAgent","attachEvent","detachEvent","srcElement","asBoolean","asNumber","asString","asElement","hexToRGB","hex","shorthandRegex","overrideOpacity","rgb","RGBToHex","red","green","blue","isValidRGB","isValidHex","hsv","hexToHSV","lighterColorHSV","darkerColorHSV","darkerColorHex","HSVToHex","lighterColorHex","RGBToHSV","minRGB","maxRGB","saturation","cssUtil","cssText","parts","currentStyles","newStyles","removeStyles","HSVToRGB","q","isOk","isValidRGBA","rgba","referenceObject","objectTo","bridgeObject","mergeTarget","field2","maxIterations","iteration","low","high","searchResult","sidePreference","nextValue","linear","easeInQuad","easeOutQuad","easeInOutQuad","easeInCubic","easeOutCubic","easeInOutCubic","easeInQuart","easeOutQuart","easeInOutQuart","easeInQuint","easeOutQuint","easeInOutQuint","requestAnimationFrame","mozRequestAnimationFrame","webkitRequestAnimationFrame","msRequestAnimationFrame","CanvasRenderer","redrawRequested","renderingActive","renderRequests","allowRedrawRequests","hideEdgesOnDrag","hideNodesOnDrag","_determineBrowserMethod","_resizeNodes","_requestRedraw","_startRendering","cancelAnimationFrame","_renderStep","devicePixelRatio","webkitBackingStorePixelRatio","mozBackingStorePixelRatio","msBackingStorePixelRatio","oBackingStorePixelRatio","backingStorePixelRatio","setTransform","w","save","translate","_drawEdges","_drawNodes","controlNodesActive","_drawControlNodes","restore","resize","updateBoundingBox","alwaysShow","topLeft","bottomRight","viewableArea","isSelected","isBoundingBoxOverlappingWith","connected","browserType","Canvas","resizeTimer","resizeFunction","hammerFrame","_cleanUp","tabIndex","_bindHammer","pinch","_prepareValue","emitEvent","oldWidth","oldHeight","_XconvertCanvasToDOM","_YconvertCanvasToDOM","_XconvertDOMtoCanvas","_YconvertDOMtoCanvas","View","animationSpeed","renderRefreshRate","animationEasingFunction","easingTime","sourceScale","targetScale","sourceTranslation","targetTranslation","lockedOnNodeId","lockedOnNodeOffset","touchTime","specificNodes","zoomLevel","initialZoom","positionDefined","predefinedPosition","_getRange","numberOfNodes","factor","yDistance","xZoomLevel","yZoomLevel","_findCenter","animationOptions","nodePosition","lockedOnNode","animateView","locked","_transitionRedraw","viewCenter","distanceFromCenter","_lockedRedraw","finished","_componentsNavigationHandler","_componentsNavigationHandler2","_componentsPopup","_componentsPopup2","InteractionHandler","navigationHandler","popup","popupObj","popupTimer","dragNodes","dragView","keyboard","speed","bindToWindow","navigationButtons","tooltipDelay","zoomView","pinched","changedPointers","checkSelectionChanges","_generateClickEvent","previouslySelectedEdgeCount","_getSelectedEdgeCount","previouslySelectedNodeCount","_getSelectedNodeCount","previousSelection","selectAdditionalOnPoint","selectOnPoint","selectedEdges","selectedNodes","selectObject","selectionObj","xFixed","yFixed","_handleDragStart","scaleOld","preScaleDragPointer","scaleFrac","tx","ty","postScaleDragPointer","popupVisible","_checkHidePopup","setPosition","_checkShowPopup","hoverObject","pointerObj","previousPopupObjId","nodeUnderCursor","popupType","overlappingNodes","isOverlappingWith","getTitle","overlappingEdges","popupTargetType","popupTargetId","setText","_pointerToPositionObject","stillOnObj","overNode","Node","Edge","SelectionHandler","hoverObj","selectConnectedEdges","updateSelection","selectionChanged","deselectObject","eventType","DOM","highlightEdges","_selectConnectedEdges","_addToSelection","_removeFromSelection","canvasPos","returnNode","positionObject","_getAllNodesOverlappingWith","_getEdgesOverlappingWith","returnEdge","_getAllEdgesOverlappingWith","clusterSize","_addToHover","hoverChanged","blurObject","_hoverConnectedEdges","edgeIds","idArray","RangeError","LayoutEngine","initialRandomSeed","randomSeed","optionsBackup","hierarchical","levelSeparation","sortMethod","hierarchicalLevels","setupHierarchicalLayout","prevHierarchicalState","adaptAllOptions","nodesArray","isFixed","angle","seededRandom","definedLevel","undefinedLevel","nodeSpacing","_determineLevelsByHubsize","_determineLevelsDirected","distribution","_getDistribution","_placeNodesByHierarchy","positionedNodes","_placeBranchNodes","hubSize","_setLevel","minLevel","_setLevelDirected","parentId","parentLevel","childNodeLevel","ManipulationSystem","editMode","manipulationDiv","editModeDiv","closeDiv","manipulationHammers","temporaryUIFunctions","temporaryEventFunctions","temporaryIds","guiEnabled","inMode","selectedControlNode","initiallyActive","editNode","editEdge","deleteNode","deleteEdge","controlNodeStyle","_restore","globalOptions","_setup","showManipulatorToolbar","_createEditButton","manipulationDOM","selectedNodeCount","selectedEdgeCount","selectedTotalCount","needSeperator","_createAddNodeButton","_createSeperator","_createAddEdgeButton","_createEditNodeButton","_createEditEdgeButton","_createDeleteButton","_bindHammerToDiv","toggleEditMode","_temporaryBindEvent","_createBackButton","_createDescription","_performAddNode","_getSelectedNode","finalizedData","alert","_temporaryBindUI","_handleConnect","_finishConnect","_dragControlNode","edgeBeingEditedId","controlNodeFrom","_getNewTargetNode","controlNodeTo","_controlNodeTouch","_controlNodeDragStart","_controlNodeDrag","_controlNodeDragEnd","positions","findBorderPositions","deleteFunction","_createWrappers","_removeManipulationDOM","_createButton","_cleanManipulatorHammers","_cleanupTemporaryNodesAndEdges","_unbindTemporaryUIs","_unbindTemporaryEvents","labelClassName","newFunction","boundFunction","UIfunctionName","functionName","eventName","domElement","indexTempEdge","indexTempNode","lastTouch","fromSelect","toSelect","overlappingNodeIds","_performEditEdge","targetNode","connectionEdge","connectFromId","_performAddEdge","clickData","defaultData","sourceNodeId","targetNodeId","_this5","_this6","CanvasRenderingContext2D","circle","square","s2","ir","triangleDown","star","diamond","roundRect","r2d","ellipse","kappa","ox","oy","xe","ye","xm","ym","bezierCurveTo","database","wEllipse","hEllipse","ymb","yeb","arrow","xt","yt","xi","yi","xl","yl","xr","yr","dashedLine","x2","y2","pattern","patternLength","slope","distRemaining","patternIndex","dashLength","overlay","_onTapOverlay","bodyHammer","prevent_default","_hasParent","deactivate","keycharm","escListener","activate","unbind","edit","del","back","addDescription","edgeDescription","editEdgeDescription","createEdgeError","deleteClusterError","editClusterError","mixin","_callbacks","self","removeListener","removeAllListeners","callbacks","cb","hasListeners","utils_hooks__hooks","hookCallback","setHookCallback","res","hasOwnProp","create_utc__createUTC","createLocalOrUTC","utc","defaultParsingFlags","empty","unusedTokens","unusedInput","charsLeftOver","nullInput","invalidMonth","invalidFormat","userInvalidated","iso","getParsingFlags","_pf","valid__isValid","_isValid","flags","_strict","bigHour","valid__createInvalid","NaN","copyConfig","val","_f","_l","_tzm","_isUTC","_offset","_locale","momentProperties","Moment","config","updateInProgress","updateOffset","toInt","argumentForCoercion","coercedNumber","isFinite","compareArrays","dontConvert","lengthDiff","diffs","Locale","normalizeLocale","chooseLocale","loadLocale","oldLocale","globalLocale","_abbr","locale_locales__getSetGlobalLocale","locale_locales__getLocale","defineLocale","abbr","addUnitAlias","unit","shorthand","lowerCase","aliases","normalizeUnits","units","normalizeObjectUnits","inputObject","normalizedProp","normalizedInput","makeGetSet","keepTime","get_set__set","get_set__get","mom","getSet","zeroFill","targetLength","forceSign","output","addFormatToken","padded","ordinal","func","formatTokenFunctions","localeData","removeFormattingTokens","makeFormatFunction","formattingTokens","formatMoment","isValid","expandFormat","formatFunctions","invalidDate","replaceLongDateFormatTokens","longDateFormat","localFormattingTokens","lastIndex","addRegexToken","regex","strictRegex","regexes","isStrict","getParseRegexForToken","RegExp","unescapeFormat","matched","p4","addParseToken","tokens","addWeekParseToken","_w","addTimeToArrayFromToken","_a","daysInMonth","UTC","getUTCDate","localeMonths","_months","localeMonthsShort","_monthsShort","localeMonthsParse","monthName","_monthsParse","_longMonthsParse","_shortMonthsParse","months","monthsShort","dayOfMonth","monthsParse","getSetMonth","getDaysInMonth","checkOverflow","MONTH","DATE","YEAR","HOUR","MINUTE","SECOND","MILLISECOND","_overflowDayOfYear","warn","msg","suppressDeprecationWarnings","deprecate","firstTime","msgWithStack","deprecateSimple","deprecations","configFromISO","l","from_string__isoRegex","isoDates","isoTimes","matchOffset","configFromStringAndFormat","configFromString","aspNetJsonRegex","createFromInputFallback","createDate","ms","createUTCDate","setUTCFullYear","daysInYear","isLeapYear","getIsLeapYear","weekOfYear","firstDayOfWeek","firstDayOfWeekOfYear","adjustedMoment","daysToDayOfWeek","local__createLocal","week","localeWeek","_week","dow","doy","localeFirstDayOfWeek","localeFirstDayOfYear","getSetWeek","getSetISOWeek","dayOfYearFromWeeks","daysToAdd","getUTCDay","getSetDayOfYear","startOf","defaults","currentDateArray","_useUTC","getUTCFullYear","getUTCMonth","configFromArray","currentDate","yearToUse","dayOfYearFromWeekInfo","_dayOfYear","_nextDay","setUTCMinutes","getUTCMinutes","weekYear","temp","GG","W","E","gg","ISO_8601","parsedInput","skipped","stringLength","totalParsedInputLength","meridiemFixWrap","_meridiem","meridiem","isPm","meridiemHour","isPM","configFromStringAndArray","tempConfig","bestMoment","scoreToBeat","currentScore","score","configFromObject","createFromConfig","preparse","configFromInput","isUTC","pickBy","moments","Duration","years","quarters","quarter","weeks","days","_milliseconds","_days","_bubble","isDuration","separator","utcOffset","offsetFromString","matches","chunk","chunkOffset","cloneWithOffset","model","setTime","local","getDateOffset","getTimezoneOffset","getSetOffset","keepLocalTime","localAdjust","_changeInProgress","add_subtract__addSubtract","create__createDuration","getSetZone","setOffsetToUTC","setOffsetToLocal","setOffsetToParsedOffset","hasAlignedHourOffset","isDaylightSavingTime","isDaylightSavingTimeShifted","isLocal","isUtcOffset","isUtc","ret","diffRes","aspNetRegex","create__isoRegex","parseIso","momentsDifference","inp","positiveMomentsDifference","isAfter","isBefore","createAdder","period","dur","tmp","isAdding","moment_calendar__calendar","sod","calendar","inputMs","endOf","isBetween","absFloor","asFloat","that","zoneDelta","monthDiff","anchor2","adjust","wholeMonthDiff","moment_format__toISOString","inputString","postformat","withoutSuffix","humanize","fromNow","toNow","newLocaleData","isoWeekday","to_type__valueOf","unix","moment_valid__isValid","parsingFlags","invalidAt","addWeekYearFormatToken","getter","weeksInYear","getSetWeekYear","getSetISOWeekYear","getISOWeeksInYear","getWeeksInYear","weekInfo","getSetQuarter","parseWeekday","weekdaysParse","localeWeekdays","_weekdays","localeWeekdaysShort","_weekdaysShort","localeWeekdaysMin","_weekdaysMin","localeWeekdaysParse","weekdayName","_weekdaysParse","weekdays","weekdaysShort","weekdaysMin","getSetDayOfWeek","getDay","getSetLocaleDayOfWeek","getSetISODayOfWeek","lowercase","matchMeridiem","_meridiemParse","localeIsPM","localeMeridiem","isLower","millisecond__milliseconds","getZoneAbbr","getZoneName","moment__createUnix","moment__createInZone","parseZone","locale_calendar__calendar","_calendar","_longDateFormat","_invalidDate","_ordinal","preParsePostFormat","relative__relativeTime","isFuture","_relativeTime","pastFuture","locale_set__set","_ordinalParseLenient","_ordinalParse","lists__get","setter","list","out","lists__listMonths","lists__listMonthsShort","lists__listWeekdays","lists__listWeekdaysShort","lists__listWeekdaysMin","duration_abs__abs","mathAbs","duration_add_subtract__addSubtract","duration_add_subtract__add","duration_add_subtract__subtract","bubble","daysToYears","yearsToDays","duration_as__valueOf","makeAs","alias","duration_get__get","makeGetter","substituteTimeAgo","relativeTime","duration_humanize__relativeTime","posNegDuration","thresholds","duration_humanize__getSetRelativeTimeThreshold","threshold","limit","withSuffix","iso_string__toISOString","Y","iso_string__abs","D","asSeconds","match1","match2","match3","match4","match6","match1to2","match1to3","match1to4","match1to6","matchUnsigned","matchSigned","matchTimestamp","matchWord","defaultLocaleMonths","defaultLocaleMonthsShort","parseTwoDigitYear","getSetYear","defaultLocaleWeek","prototypeMin","prototypeMax","add_subtract__add","add_subtract__subtract","isoWeekYear","getSetDayOfMonth","invalidWeekday","defaultLocaleWeekdays","defaultLocaleWeekdaysShort","defaultLocaleWeekdaysMin","_isPm","defaultLocaleMeridiemParse","getSetHour","getSetMinute","getSetSecond","getSetMillisecond","momentPrototype__proto","toJSON","isoWeek","isoWeeks","isoWeeksInYear","isDST","isDSTShifted","zoneAbbr","zoneName","zone","momentPrototype","defaultCalendar","sameDay","nextDay","nextWeek","lastDay","lastWeek","sameElse","defaultLongDateFormat","LTS","LT","L","LL","LLL","LLLL","defaultInvalidDate","defaultOrdinal","defaultOrdinalParse","defaultRelativeTime","future","past","mm","hh","dd","MM","yy","prototype__proto","firstDayOfYear","ordinalParse","langData","asMilliseconds","asMinutes","asHours","asDays","asWeeks","asMonths","asYears","duration_get__milliseconds","duration_prototype__proto","toIsoString","version","invalid","relativeTimeThreshold","_moment","__WEBPACK_AMD_DEFINE_FACTORY__","__WEBPACK_AMD_DEFINE_ARRAY__","__WEBPACK_AMD_DEFINE_RESULT__","_firstTarget","_processing","propagatedHandler","_handled","stopped","firstTarget","_handlers","Manager","PropagatingHammer","_on","_off","_emit","_destroy","pointerType","handler","exportName","setTimeoutContext","timeout","bindFn","invokeArrayArg","arg","each","iterator","dest","child","childP","baseP","_super","boolOrFn","TYPE_FUNCTION","ifUndefined","val1","val2","addEventListeners","splitStr","removeEventListeners","inStr","find","inArray","findByKey","uniqueArray","results","prefixed","property","camelProp","VENDOR_PREFIXES","uniqueId","_uniqueId","getWindowForElement","doc","ownerDocument","defaultView","parentWindow","Input","manager","inputTarget","domHandler","ev","createInputInstance","Type","inputClass","SUPPORT_POINTER_EVENTS","PointerEventInput","SUPPORT_ONLY_TOUCH","TouchInput","SUPPORT_TOUCH","TouchMouseInput","MouseInput","pointersLen","pointers","changedPointersLen","INPUT_START","INPUT_END","INPUT_CANCEL","session","computeInputData","recognize","prevInput","pointersLength","firstInput","simpleCloneInputData","firstMultiple","offsetCenter","getCenter","timeStamp","deltaTime","getAngle","getDistance","computeDeltaXY","offsetDirection","getDirection","rotation","getRotation","computeIntervalInputData","offsetDelta","prevDelta","velocity","velocityX","velocityY","last","lastInterval","COMPUTE_INTERVAL","getVelocity","DIRECTION_NONE","DIRECTION_LEFT","DIRECTION_RIGHT","DIRECTION_UP","DIRECTION_DOWN","PROPS_XY","atan2","PROPS_CLIENT_XY","evEl","MOUSE_ELEMENT_EVENTS","evWin","MOUSE_WINDOW_EVENTS","allow","pressed","POINTER_ELEMENT_EVENTS","POINTER_WINDOW_EVENTS","store","pointerEvents","SingleTouchInput","evTarget","SINGLE_TOUCH_TARGET_EVENTS","SINGLE_TOUCH_WINDOW_EVENTS","started","normalizeSingleTouches","all","touches","changedTouches","TOUCH_TARGET_EVENTS","targetIds","getTouches","allTouches","INPUT_MOVE","identifier","changedTargetTouches","mouse","TouchAction","cleanTouchActions","actions","TOUCH_ACTION_NONE","hasPanX","TOUCH_ACTION_PAN_X","hasPanY","TOUCH_ACTION_PAN_Y","TOUCH_ACTION_MANIPULATION","TOUCH_ACTION_AUTO","Recognizer","state","STATE_POSSIBLE","simultaneous","requireFail","stateStr","STATE_CANCELLED","STATE_ENDED","STATE_CHANGED","STATE_BEGAN","directionStr","getRecognizerByNameIfManager","otherRecognizer","recognizer","AttrRecognizer","PanRecognizer","pX","pY","PinchRecognizer","PressRecognizer","_timer","_input","RotateRecognizer","SwipeRecognizer","TapRecognizer","pTime","pCenter","recognizers","preset","handlers","touchAction","toggleCssProps","recognizeWith","requireFailure","cssProps","triggerDomEvent","gestureEvent","createEvent","initEvent","gesture","dispatchEvent","TEST_ELEMENT","MOBILE_REGEX","INPUT_TYPE_TOUCH","INPUT_TYPE_PEN","INPUT_TYPE_MOUSE","INPUT_TYPE_KINECT","DIRECTION_HORIZONTAL","DIRECTION_VERTICAL","DIRECTION_ALL","MOUSE_INPUT_MAP","mousedown","mousemove","mouseup","POINTER_INPUT_MAP","pointerdown","pointermove","pointerup","pointercancel","pointerout","IE10_POINTER_TYPE_ENUM",2,3,4,5,"MSPointerEvent","removePointer","eventTypeNormalized","isTouch","storeIndex","pointerId","SINGLE_TOUCH_INPUT_MAP","touchstart","touchmove","touchend","touchcancel","TOUCH_INPUT_MAP","inputEvent","inputData","isMouse","PREFIXED_TOUCH_ACTION","NATIVE_TOUCH_ACTION","TOUCH_ACTION_COMPUTE","compute","getTouchAction","preventDefaults","prevented","hasNone","preventSrc","STATE_RECOGNIZED","STATE_FAILED","dropRecognizeWith","dropRequireFailure","hasRequireFailures","canRecognizeWith","withState","tryEmit","canEmit","inputDataClone","process","reset","attrTest","optionPointers","isRecognized","directionTest","hasMoved","inOut","validPointers","validMovement","validTime","taps","posThreshold","validTouchTime","failTimeout","validInterval","validMultiTap","tapCount","VERSION","domEvents","userSelect","touchSelect","touchCallout","contentZooming","userDrag","tapHighlightColor","STOP","FORCED_STOP","curRecognizer","existing","Tap","Pan","Swipe","Pinch","Rotate","Press","ColorPicker","generated","centerCoordinates","hueCircle","initialColor","previousColor","applied","updateCallback","_setSize","htmlColors","black","navy","darkblue","mediumblue","darkgreen","teal","darkcyan","deepskyblue","darkturquoise","mediumspringgreen","lime","springgreen","aqua","cyan","midnightblue","dodgerblue","lightseagreen","forestgreen","seagreen","darkslategray","limegreen","mediumseagreen","turquoise","royalblue","steelblue","darkslateblue","mediumturquoise","indigo","darkolivegreen","cadetblue","cornflowerblue","mediumaquamarine","dimgray","slateblue","olivedrab","slategray","lightslategray","mediumslateblue","lawngreen","chartreuse","aquamarine","maroon","purple","olive","gray","skyblue","lightskyblue","blueviolet","darkred","darkmagenta","saddlebrown","darkseagreen","lightgreen","mediumpurple","darkviolet","palegreen","darkorchid","yellowgreen","sienna","brown","darkgray","lightblue","greenyellow","paleturquoise","lightsteelblue","powderblue","firebrick","darkgoldenrod","mediumorchid","rosybrown","darkkhaki","silver","mediumvioletred","indianred","peru","chocolate","tan","lightgrey","palevioletred","thistle","orchid","goldenrod","crimson","gainsboro","plum","burlywood","lightcyan","lavender","darksalmon","violet","palegoldenrod","lightcoral","khaki","aliceblue","honeydew","azure","sandybrown","wheat","beige","whitesmoke","mintcream","ghostwhite","salmon","antiquewhite","linen","lightgoldenrodyellow","oldlace","fuchsia","magenta","deeppink","orangered","tomato","hotpink","coral","darkorange","lightsalmon","orange","lightpink","pink","gold","peachpuff","navajowhite","moccasin","bisque","mistyrose","blanchedalmond","papayawhip","lavenderblush","seashell","cornsilk","lemonchiffon","floralwhite","snow","yellow","lightyellow","ivory","white","setInitial","htmlColor","_isColorString","rgbaArray","rgbObj","_setColor","_generateHueCircle","storePrevious","_hide","_updatePicker","angleConvert","colorPickerSelector","colorPickerCanvas","pixelRation","putImageData","brightnessRange","opacityRange","initialColorDiv","newColorDiv","colorPickerDiv","opacityDiv","brightnessDiv","arrowDiv","_setOpacity","_setBrightness","brightnessLabel","opacityLabel","cancelButton","applyButton","_apply","saveButton","_save","loadButton","_loadLast","_moveSelector","sat","hfac","sfac","fillRect","getImageData","centerY","centerX","newLeft","_sharedLabel","_sharedLabel2","_nodesShapesBox","_nodesShapesBox2","_nodesShapesCircle","_nodesShapesCircle2","_nodesShapesCircularImage","_nodesShapesCircularImage2","_nodesShapesDatabase","_nodesShapesDatabase2","_nodesShapesDiamond","_nodesShapesDiamond2","_nodesShapesDot","_nodesShapesDot2","_nodesShapesEllipse","_nodesShapesEllipse2","_nodesShapesIcon","_nodesShapesIcon2","_nodesShapesImage","_nodesShapesImage2","_nodesShapesSquare","_nodesShapesSquare2","_nodesShapesStar","_nodesShapesStar2","_nodesShapesText","_nodesShapesText2","_nodesShapesTriangle","_nodesShapesTriangle2","_nodesShapesTriangleDown","_nodesShapesTriangleDown2","imagelist","grouplist","baseSize","baseFontSize","labelModule","status","groupObj","imageObj","distanceToBorder","sizeDiff","fontDiff","parentOptions","newOptions","parsedColor","_slicedToArray","Symbol","_arr","_n","_e","_s","err","Label","yLine","labelDirty","baseline","viewFontSize","calculateLabelSize","_drawBackground","_drawText","lineMargin","fontSize","_getColor","_getColor2","fontColor","_setAlignment","_setAlignment2","lineJoin","lineCount","strokeText","_processLabel","measureText","newOptionsArray","_edgesBezierEdgeDynamic","_edgesBezierEdgeDynamic2","_edgesBezierEdgeStatic","_edgesBezierEdgeStatic2","_edgesStraightEdge","_edgesStraightEdge2","baseWidth","_setInteractionWidths","changeInType","attachEdge","detachEdge","widthDiff","drawLine","drawArrows","drawLabel","viaNode","drawArrowHead","node1","node2","getPoint","_rotateForLabelAlignment","_pointOnCircle","xFrom","yFrom","xTo","yTo","xObj","yObj","getDistanceToEdge","angleInDegrees","rotate","percentage","colorsDefined","BarnesHutSolver","barnesHutTree","thetaInversed","overlapAvoidanceFactor","nodeCount","_formBarnesHutTree","_getForceContribution","children","NW","NE","SW","SE","parentBranch","childrenCount","centerOfMass","calcSize","_calculateForces","gravityForce","fx","fy","minimumTreeSize","rootSize","halfRootSize","_splitBranch","_placeInTree","totalMass","totalMassInv","biggestSize","skipMassUpdate","_updateBranchMass","_placeInRegion","region","_insertRegion","childSize","_drawBranch","branch","RepulsionSolver","repulsingForce","HierarchicalRepulsionSolver","steepness","SpringSolver","edgeLength","node3","_calculateSpringForce","springForce","HierarchicalSpringSolver","springFx","springFy","totalFx","totalFy","correctionFx","correctionFy","CentralGravitySolver","_inherits","subClass","superClass","__proto__","_get","_x","_x2","_x3","_again","receiver","desc","getOwnPropertyDescriptor","getPrototypeOf","_BarnesHutSolver2","_BarnesHutSolver3","ForceAtlas2BasedRepulsionSolver","_BarnesHutSolver","degree","_CentralGravitySolver2","_CentralGravitySolver3","ForceAtlas2BasedCentralGravitySolver","_CentralGravitySolver","_Node2","_Node3","Cluster","_Node","NavigationHandler","iconsCreated","navigationHammers","boundFunctions","activated","_stopMovement","configureKeyboardBindings","loadNavigationElements","cleanNavigation","_navigationReleaseOverload","navigationDOM","navigationDivs","navigationDivActions","_fit","bindToRedraw","boundAction","unbindFromRedraw","Popup","doShow","_exportFunctions","_bound","keydown","keyup","_keys","fromCharCode","down","handleEvent","up","keyCode","bound","bindAll","getKey","newBindings","webpackContext","req","resolve","_utilNodeBase","_utilNodeBase2","Box","_NodeBase","textSize","getTextSize","selectionLineWidth","enableShadow","disableShadow","_utilCircleImageBase","_utilCircleImageBase2","Circle","_CircleImageBase","diameter","_drawRawCircle","CircularImage","_swapToImageResizeWhenImageLoaded","_resizeImage","clip","_drawImageAtPosition","_drawImageLabel","labelOffset","_distanceToBorder","Database","networkScaleInv","_utilShapeBase","_utilShapeBase2","Diamond","_ShapeBase","_resizeShape","_drawShape","Dot","Ellipse","Icon","_icon","iconTextSpacing","Square","Star","Text","Triangle","TriangleDown","_utilBezierEdgeBase","_utilBezierEdgeBase2","BezierEdgeDynamic","_BezierEdgeBase","setupSupportNode","parentEdgeId","positionBezierNode","quadraticCurveTo","nearNode","_findBorderPositionBezier","x1","y1","x3","y3","_getDistanceToBezierEdge","_x4","_x5","_x6","BezierEdgeStatic","_getViaCoordinates","xVia","yVia","pi","originalAngle","myAngle","_utilEdgeBase","_utilEdgeBase2","StraightEdge","_EdgeBase","edgeSegmentLength","toBorderDist","toBorderPoint","borderPos","_getDistanceToLine","webpackPolyfill","paths","__webpack_amd_options__","CircleImageBase","ratio","globalAlpha","drawImage","labelDimensions","NodeBase","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","ShapeBase","sizeMultiplier","_EdgeBase2","_EdgeBase3","BezierEdgeBase","distanceToPoint","difference","minDistance","lastX","lastY","EdgeBase","getColor","getLineWidth","_drawDashedLine","_drawLine","_line","_getCircleData","_getCircleData2","_circle","lineCap","setLineDash","lineDashOffset","_getCircleData3","_getCircleData32","_getCircleData4","_getCircleData42","_findBorderPosition","_findBorderPositionCircle","_getCircleData5","_getCircleData52","colorOptions","grd","createLinearGradient","fromColor","toColor","addColorStop","_getDistanceToEdge","_getCircleData6","_getCircleData62","px","py","something","u","arrowPos","guideOffset","findBorderPosition","guidePos","_angle","_getCircleData7","_getCircleData72","_length"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,cAEA,SAA2CA,EAAMC,GAC1B,gBAAZC,UAA0C,gBAAXC,QACxCA,OAAOD,QAAUD,IACQ,kBAAXG,SAAyBA,OAAOC,IAC9CD,OAAOH,GACmB,gBAAZC,SACdA,QAAa,IAAID,IAEjBD,EAAU,IAAIC,KACbK,KAAM,WACT,MAAgB,UAAUC,GAKhB,QAASC,GAAoBC,GAG5B,GAAGC,EAAiBD,GACnB,MAAOC,GAAiBD,GAAUP,OAGnC,IAAIC,GAASO,EAA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D,QAAQwL,OAASktD,CAC9C73C,GAAI63D,MAAM9tE,EAAM/F,EAAG+F,EAAM9F,EAAG8oH,EAAQG,GAGpC1xH,KAAKupH,aAAa/kG,GAClBA,EAAIrH,OAGJnd,KAAKwpH,cAAchlG,GACnBA,EAAIpH,aAIR7X,IAAK,eACLX,MAAO,SAAsB4f,GACvBxkB,KAAK2D,QAAQo3D,OAAOtrB,WAAY,IAClCjrB,EAAI4pG,YAAc,kBAClB5pG,EAAI6pG,WAAaruH,KAAK2D,QAAQo3D,OAAOpsD,KACrC6V,EAAI8pG,cAAgBtuH,KAAK2D,QAAQo3D,OAAOvyD,EACxCgc,EAAI+pG,cAAgBvuH,KAAK2D,QAAQo3D,OAAOtyD,MAI5ClD,IAAK,gBACLX,MAAO,SAAuB4f,GACxBxkB,KAAK2D,QAAQo3D,OAAOtrB,WAAY,IAClCjrB,EAAI4pG,YAAc,gBAClB5pG,EAAI6pG,WAAa,EACjB7pG,EAAI8pG,cAAgB,EACpB9pG,EAAI+pG,cAAgB,OAKnBW,IAGTtvH,GAAQ,WAAasvH,EACrBrvH,EAAOD,QAAUA,EAAQ"} \ No newline at end of file +{"version":3,"file":"vis.map","sources":["./dist/vis.js"],"names":["root","factory","exports","module","define","amd","this","modules","__webpack_require__","moduleId","installedModules","id","loaded","call","m","c","p","util","DOMutil","DataSet","DataView","Queue","Graph3d","graph3d","Camera","Filter","Point2d","Point3d","Slider","StepNumber","Timeline","Graph2d","timeline","DateUtil","DataStep","Range","stack","TimeStep","components","items","Item","BackgroundItem","BoxItem","PointItem","RangeItem","Component","CurrentTime","CustomTime","DataAxis","GraphGroup","Group","BackgroundGroup","ItemSet","Legend","LineGraph","TimeAxis","Network","network","Images","dotparser","gephiParser","convertDot","input","DOTToGraph","convertGephi","options","parseGephi","Graph","Error","moment","hammer","Hammer","data","conversion","props","dot","width","height","line","undefined","start","prototype","isVisible","range","interval","end","redraw","dom","box","document","createElement","content","className","appendChild","dirty","parent","parentNode","foreground","background","axis","displayed","_updateContents","_updateTitle","_updateDataAttributes","_updateStyle","selected","offsetHeight","offsetWidth","_repaintDeleteButton","show","hide","removeChild","repositionX","toScreen","align","left","style","repositionY","orientation","item","top","bottom","itemSetHeight","itemSet","lineHeight","select","unselect","setData","groupChanged","group","_moveToGroup","setParent","anchor","editable","remove","deleteButton","me","title","on","event","stopPropagation","removeFromDataSet","element","template","itemData","itemsData","get","changed","_contentToString","Element","innerHTML","type","removeAttribute","dataAttributes","length","attributes","Array","isArray","Object","keys","i","name","value","setAttribute","removeCssText","addCssText","outerHTML","window","propagating","preventDefault","__WEBPACK_AMD_DEFINE_FACTORY__","__WEBPACK_AMD_DEFINE_ARRAY__","__WEBPACK_AMD_DEFINE_RESULT__","apply","_firstTarget","_processing","split","events","match","propagatedHandler","srcEvent","_handled","stopped","firstTarget","elem","_handlers","_options","Manager","PropagatingHammer","extend","_on","_off","off","_emit","emit","_destroy","destroy","pointerType","isFirst","target","isFinal","handler","forEach","push","filter","h","eventType","exportName","setTimeoutContext","fn","timeout","context","setTimeout","bindFn","invokeArrayArg","arg","each","obj","iterator","hasOwnProperty","dest","src","merge","inherit","child","base","properties","childP","baseP","create","constructor","_super","arguments","boolOrFn","val","args","TYPE_FUNCTION","ifUndefined","val1","val2","addEventListeners","types","splitStr","addEventListener","removeEventListeners","removeEventListener","hasParent","node","inStr","str","find","indexOf","trim","inArray","findByKey","toArray","slice","uniqueArray","key","sort","results","values","a","b","prefixed","property","prefix","prop","camelProp","toUpperCase","VENDOR_PREFIXES","uniqueId","_uniqueId","getWindowForElement","doc","ownerDocument","defaultView","parentWindow","Input","manager","callback","self","inputTarget","domHandler","ev","enable","init","createInputInstance","Type","inputClass","SUPPORT_POINTER_EVENTS","PointerEventInput","SUPPORT_ONLY_TOUCH","TouchInput","SUPPORT_TOUCH","TouchMouseInput","MouseInput","inputHandler","pointersLen","pointers","changedPointersLen","changedPointers","INPUT_START","INPUT_END","INPUT_CANCEL","session","computeInputData","recognize","prevInput","pointersLength","firstInput","simpleCloneInputData","firstMultiple","offsetCenter","center","getCenter","timeStamp","now","deltaTime","angle","getAngle","distance","getDistance","computeDeltaXY","offsetDirection","getDirection","deltaX","deltaY","scale","getScale","rotation","getRotation","computeIntervalInputData","offset","offsetDelta","prevDelta","x","y","velocity","velocityX","velocityY","direction","last","lastInterval","COMPUTE_INTERVAL","v","getVelocity","abs","clientX","round","clientY","DIRECTION_NONE","DIRECTION_LEFT","DIRECTION_RIGHT","DIRECTION_UP","DIRECTION_DOWN","p1","p2","PROPS_XY","Math","sqrt","atan2","PI","PROPS_CLIENT_XY","evEl","MOUSE_ELEMENT_EVENTS","evWin","MOUSE_WINDOW_EVENTS","allow","pressed","POINTER_ELEMENT_EVENTS","POINTER_WINDOW_EVENTS","store","pointerEvents","SingleTouchInput","evTarget","SINGLE_TOUCH_TARGET_EVENTS","SINGLE_TOUCH_WINDOW_EVENTS","started","normalizeSingleTouches","all","touches","changedTouches","concat","TOUCH_TARGET_EVENTS","targetIds","getTouches","allTouches","INPUT_MOVE","identifier","targetTouches","changedTargetTouches","touch","mouse","TouchAction","set","cleanTouchActions","actions","TOUCH_ACTION_NONE","hasPanX","TOUCH_ACTION_PAN_X","hasPanY","TOUCH_ACTION_PAN_Y","TOUCH_ACTION_MANIPULATION","TOUCH_ACTION_AUTO","Recognizer","defaults","state","STATE_POSSIBLE","simultaneous","requireFail","stateStr","STATE_CANCELLED","STATE_ENDED","STATE_CHANGED","STATE_BEGAN","directionStr","getRecognizerByNameIfManager","otherRecognizer","recognizer","AttrRecognizer","PanRecognizer","pX","pY","PinchRecognizer","PressRecognizer","_timer","_input","RotateRecognizer","SwipeRecognizer","TapRecognizer","pTime","pCenter","count","recognizers","preset","handlers","touchAction","toggleCssProps","add","recognizeWith","requireFailure","cssProps","triggerDomEvent","gestureEvent","createEvent","initEvent","gesture","dispatchEvent","TEST_ELEMENT","Date","MOBILE_REGEX","test","navigator","userAgent","INPUT_TYPE_TOUCH","INPUT_TYPE_PEN","INPUT_TYPE_MOUSE","INPUT_TYPE_KINECT","DIRECTION_HORIZONTAL","DIRECTION_VERTICAL","DIRECTION_ALL","MOUSE_INPUT_MAP","mousedown","mousemove","mouseup","button","which","POINTER_INPUT_MAP","pointerdown","pointermove","pointerup","pointercancel","pointerout","IE10_POINTER_TYPE_ENUM",2,3,4,5,"MSPointerEvent","removePointer","eventTypeNormalized","toLowerCase","replace","isTouch","storeIndex","pointerId","splice","SINGLE_TOUCH_INPUT_MAP","touchstart","touchmove","touchend","touchcancel","TOUCH_INPUT_MAP","inputEvent","inputData","isMouse","PREFIXED_TOUCH_ACTION","NATIVE_TOUCH_ACTION","TOUCH_ACTION_COMPUTE","compute","update","getTouchAction","join","preventDefaults","prevented","hasNone","preventSrc","STATE_RECOGNIZED","STATE_FAILED","dropRecognizeWith","dropRequireFailure","index","hasRequireFailures","canRecognizeWith","withState","tryEmit","canEmit","inputDataClone","process","reset","attrTest","optionPointers","isRecognized","isValid","threshold","directionTest","hasMoved","inOut","time","validPointers","validMovement","validTime","clearTimeout","taps","posThreshold","validTouchTime","failTimeout","validInterval","validMultiTap","tapCount","VERSION","domEvents","userSelect","touchSelect","touchCallout","contentZooming","userDrag","tapHighlightColor","STOP","FORCED_STOP","stop","force","curRecognizer","existing","Tap","Pan","Swipe","Pinch","Rotate","Press","__webpack_amd_options__","uuid","isNumber","object","Number","recursiveDOMDelete","DOMobject","hasChildNodes","firstChild","giveRange","min","max","total","isString","String","isDate","ASPDateRegex","exec","isNaN","parse","randomUUID","v4","assignAllKeys","fillIfDefined","allowDeletion","protoExtend","other","selectiveExtend","selectiveDeepExtend","TypeError","deepExtend","selectiveNotDeepExtend","equalArray","len","convert","Boolean","valueOf","isMoment","toDate","getType","toISOString","copyAndExtendArray","arr","newValue","newArr","copyArray","getAbsoluteLeft","getBoundingClientRect","getAbsoluteTop","addClassName","classes","removeClassName","array","updateProperty","action","listener","useCapture","attachEvent","detachEvent","returnValue","getTarget","srcElement","nodeType","e","option","asBoolean","defaultValue","asNumber","asString","asSize","asElement","hexToRGB","hex","shorthandRegex","r","g","result","parseInt","overrideOpacity","color","opacity","rgb","substr","RGBToHex","red","green","blue","toString","parseColor","isValidRGB","map","isValidHex","hsv","hexToHSV","lighterColorHSV","s","darkerColorHSV","darkerColorHex","HSVToHex","lighterColorHex","border","highlight","hover","RGBToHSV","minRGB","maxRGB","d","hue","saturation","cssUtil","cssText","styles","parts","currentStyles","newStyles","removeStyles","HSVToRGB","floor","f","q","t","isOk","isValidRGBA","rgba","selectiveBridgeObject","fields","referenceObject","objectTo","bridgeObject","mergeOptions","mergeTarget","enabled","binarySearchCustom","orderedItems","searchFunction","field","field2","maxIterations","iteration","low","high","middle","searchResult","binarySearchValue","sidePreference","prevValue","nextValue","easingFunctions","linear","easeInQuad","easeOutQuad","easeInOutQuad","easeInCubic","easeOutCubic","easeInOutCubic","easeInQuart","easeOutQuart","easeInOutQuart","easeInQuint","easeOutQuint","easeInOutQuint","global","utils_hooks__hooks","hookCallback","setHookCallback","res","hasOwnProp","create_utc__createUTC","format","locale","strict","createLocalOrUTC","utc","defaultParsingFlags","empty","unusedTokens","unusedInput","overflow","charsLeftOver","nullInput","invalidMonth","invalidFormat","userInvalidated","iso","getParsingFlags","_pf","valid__isValid","_isValid","flags","_d","getTime","_strict","bigHour","valid__createInvalid","NaN","copyConfig","to","from","_isAMomentObject","_i","_f","_l","_tzm","_isUTC","_offset","_locale","momentProperties","Moment","config","updateInProgress","updateOffset","toInt","argumentForCoercion","coercedNumber","isFinite","ceil","compareArrays","array1","array2","dontConvert","lengthDiff","diffs","Locale","normalizeLocale","chooseLocale","names","j","next","loadLocale","oldLocale","locales","globalLocale","_abbr","code","locale_locales__getSetGlobalLocale","locale_locales__getLocale","defineLocale","abbr","addUnitAlias","unit","shorthand","lowerCase","aliases","normalizeUnits","units","normalizeObjectUnits","inputObject","normalizedProp","normalizedInput","makeGetSet","keepTime","get_set__set","get_set__get","mom","getSet","zeroFill","number","targetLength","forceSign","output","sign","addFormatToken","token","padded","ordinal","func","formatTokenFunctions","localeData","removeFormattingTokens","makeFormatFunction","formattingTokens","Function","formatMoment","expandFormat","formatFunctions","invalidDate","replaceLongDateFormatTokens","longDateFormat","localFormattingTokens","lastIndex","addRegexToken","regex","strictRegex","regexes","isStrict","getParseRegexForToken","RegExp","unescapeFormat","matched","p3","p4","addParseToken","tokens","addWeekParseToken","_w","addTimeToArrayFromToken","_a","daysInMonth","year","month","UTC","getUTCDate","localeMonths","_months","localeMonthsShort","_monthsShort","localeMonthsParse","monthName","_monthsParse","_longMonthsParse","_shortMonthsParse","months","monthsShort","setMonth","dayOfMonth","monthsParse","date","getSetMonth","getDaysInMonth","checkOverflow","MONTH","DATE","YEAR","HOUR","MINUTE","SECOND","MILLISECOND","_overflowDayOfYear","warn","msg","suppressDeprecationWarnings","console","deprecate","firstTime","msgWithStack","deprecateSimple","deprecations","configFromISO","l","string","from_string__isoRegex","isoDates","isoTimes","matchOffset","configFromStringAndFormat","configFromString","aspNetJsonRegex","createFromInputFallback","createDate","M","ms","setFullYear","createUTCDate","setUTCFullYear","daysInYear","isLeapYear","getIsLeapYear","weekOfYear","firstDayOfWeek","firstDayOfWeekOfYear","adjustedMoment","daysToDayOfWeek","day","local__createLocal","week","dayOfYear","localeWeek","_week","dow","doy","localeFirstDayOfWeek","localeFirstDayOfYear","getSetWeek","getSetISOWeek","dayOfYearFromWeeks","weekday","daysToAdd","getUTCDay","getSetDayOfYear","clone","startOf","currentDateArray","_useUTC","getUTCFullYear","getUTCMonth","getFullYear","getMonth","getDate","configFromArray","currentDate","yearToUse","dayOfYearFromWeekInfo","_dayOfYear","_nextDay","setUTCMinutes","getUTCMinutes","w","weekYear","temp","GG","W","E","gg","ISO_8601","parsedInput","skipped","stringLength","totalParsedInputLength","meridiemFixWrap","_meridiem","hour","meridiem","isPm","meridiemHour","isPM","configFromStringAndArray","tempConfig","bestMoment","scoreToBeat","currentScore","score","configFromObject","minute","second","millisecond","createFromConfig","preparse","configFromInput","isUTC","pickBy","moments","Duration","duration","years","quarters","quarter","weeks","days","hours","minutes","seconds","milliseconds","_milliseconds","_days","_data","_bubble","isDuration","separator","utcOffset","offsetFromString","matches","chunk","chunkOffset","cloneWithOffset","model","diff","setTime","local","getDateOffset","getTimezoneOffset","getSetOffset","keepLocalTime","localAdjust","_changeInProgress","add_subtract__addSubtract","create__createDuration","getSetZone","setOffsetToUTC","setOffsetToLocal","subtract","setOffsetToParsedOffset","hasAlignedHourOffset","isDaylightSavingTime","isDaylightSavingTimeShifted","isLocal","isUtcOffset","isUtc","ret","diffRes","aspNetRegex","create__isoRegex","parseIso","momentsDifference","inp","parseFloat","positiveMomentsDifference","isAfter","isBefore","createAdder","period","dur","tmp","isAdding","moment_calendar__calendar","sod","calendar","inputMs","endOf","isBetween","isSame","absFloor","asFloat","delta","that","zoneDelta","monthDiff","anchor2","adjust","wholeMonthDiff","moment_format__toISOString","inputString","defaultFormat","postformat","withoutSuffix","humanize","fromNow","toNow","newLocaleData","isoWeekday","to_type__valueOf","unix","moment_valid__isValid","parsingFlags","invalidAt","addWeekYearFormatToken","getter","weeksInYear","getSetWeekYear","getSetISOWeekYear","getISOWeeksInYear","getWeeksInYear","weekInfo","getSetQuarter","parseWeekday","weekdaysParse","localeWeekdays","_weekdays","localeWeekdaysShort","_weekdaysShort","localeWeekdaysMin","_weekdaysMin","localeWeekdaysParse","weekdayName","_weekdaysParse","weekdays","weekdaysShort","weekdaysMin","getSetDayOfWeek","getDay","getSetLocaleDayOfWeek","getSetISODayOfWeek","lowercase","matchMeridiem","_meridiemParse","localeIsPM","charAt","localeMeridiem","isLower","millisecond__milliseconds","getZoneAbbr","getZoneName","moment__createUnix","moment__createInZone","parseZone","locale_calendar__calendar","_calendar","_longDateFormat","_invalidDate","_ordinal","preParsePostFormat","relative__relativeTime","isFuture","_relativeTime","pastFuture","locale_set__set","_ordinalParseLenient","_ordinalParse","source","lists__get","setter","list","out","lists__listMonths","lists__listMonthsShort","lists__listWeekdays","lists__listWeekdaysShort","lists__listWeekdaysMin","duration_abs__abs","mathAbs","duration_add_subtract__addSubtract","duration_add_subtract__add","duration_add_subtract__subtract","bubble","daysToYears","yearsToDays","as","duration_as__valueOf","makeAs","alias","duration_get__get","makeGetter","substituteTimeAgo","relativeTime","duration_humanize__relativeTime","posNegDuration","thresholds","duration_humanize__getSetRelativeTimeThreshold","limit","withSuffix","iso_string__toISOString","Y","iso_string__abs","D","asSeconds","match1","match2","match3","match4","match6","match1to2","match1to3","match1to4","match1to6","matchUnsigned","matchSigned","matchTimestamp","matchWord","defaultLocaleMonths","defaultLocaleMonthsShort","parseTwoDigitYear","getSetYear","defaultLocaleWeek","prototypeMin","prototypeMax","add_subtract__add","add_subtract__subtract","lang","isoWeekYear","getSetDayOfMonth","invalidWeekday","defaultLocaleWeekdays","defaultLocaleWeekdaysShort","defaultLocaleWeekdaysMin","_isPm","defaultLocaleMeridiemParse","getSetHour","getSetMinute","getSetSecond","getSetMillisecond","momentPrototype__proto","toJSON","isoWeek","isoWeeks","isoWeeksInYear","isDST","isDSTShifted","zoneAbbr","zoneName","dates","zone","momentPrototype","defaultCalendar","sameDay","nextDay","nextWeek","lastDay","lastWeek","sameElse","defaultLongDateFormat","LTS","LT","L","LL","LLL","LLLL","defaultInvalidDate","defaultOrdinal","defaultOrdinalParse","defaultRelativeTime","future","past","mm","hh","dd","MM","yy","prototype__proto","firstDayOfYear","ordinalParse","langData","asMilliseconds","asMinutes","asHours","asDays","asWeeks","asMonths","asYears","duration_get__milliseconds","duration_prototype__proto","toIsoString","version","invalid","relativeTimeThreshold","_moment","webpackPolyfill","paths","children","webpackContext","req","resolve","buf","ii","oct","_hexToByte","unparse","bth","_byteToHex","v1","clockseq","_clockseq","msecs","nsecs","_lastNSecs","dt","_lastMSecs","tl","tmh","_nodeId","n","rnds","random","rng","_rng","globalVar","crypto","getRandomValues","_rnds8","Uint8Array","_rnds","_seedBytes","prepareElements","JSONcontainer","elementType","redundant","used","cleanupElements","getSVGElement","svgContainer","shift","createElementNS","getDOMElement","DOMContainer","insertBefore","drawPoint","labelObj","point","drawPoints","setAttributeNS","size","label","xOffset","yOffset","textContent","drawBar","rect","_fieldId","fieldId","_type","_subscribers","setOptions","queue","_queue","subscribers","subscribe","unsubscribe","_trigger","params","senderId","subscriber","addedIds","_addItem","updatedIds","updatedData","addOrUpdate","_updateItem","ids","firstType","returnType","allowedValues","itemId","_getItem","order","_sort","_filterFields","getIds","getDataSet","mappedItems","filteredItem","av","bv","removedId","removedIds","_remove","clear","maxField","itemField","minField","distinct","fieldType","exists","raw","converted","JSON","stringify","delay","Infinity","_timeout","_extended","_flushIfNeeded","flush","methods","original","method","entry","_ids","_onEvent","refresh","newIds","added","removed","viewOptions","getArguments","defaultFilter","dataSet","updated","container","SyntaxError","containerElement","margin","defaultXCenter","defaultYCenter","xLabel","yLabel","zLabel","passValueFn","xValueLabel","yValueLabel","zValueLabel","filterLabel","legendLabel","STYLE","DOT","showPerspective","showGrid","keepAspectRatio","showShadow","showGrayBottom","showTooltip","verticalRatio","animationInterval","animationPreload","camera","eye","dataTable","dataPoints","colX","colY","colZ","colValue","colFilter","xMin","xStep","xMax","yMin","yStep","yMax","zMin","zStep","zMax","valueMin","valueMax","xBarWidth","yBarWidth","colorAxis","colorGrid","colorDot","colorDotBorder","getMouseX","getMouseY","Emitter","_setScale","z","xCenter","yCenter","zCenter","setArmLocation","_convert3Dto2D","point3d","translation","_convertPointToTranslation","_convertTranslationToScreen","ax","ay","az","cx","getCameraLocation","cy","cz","sinTx","sin","getCameraRotation","cosTx","cos","sinTy","cosTy","sinTz","cosTz","dx","dy","dz","bx","by","ex","ey","ez","getArmLength","xcenter","frame","canvas","clientWidth","ycenter","_setBackgroundColor","backgroundColor","fill","stroke","strokeWidth","borderColor","borderWidth","borderStyle","BAR","BARCOLOR","BARSIZE","DOTLINE","DOTCOLOR","DOTSIZE","GRID","LINE","SURFACE","_getStyleNumber","styleName","_determineColumnIndexes","getNumberOfColumns","getNumberOfRows","counter","column","getDistinctValues","distinctValues","getColumnRange","minMax","_dataInitialize","rawData","_onChange","dataFilter","setOnLoadCallback","withBars","defaultXBarWidth","dataX","defaultYBarWidth","dataY","xRange","defaultXMin","defaultXMax","defaultXStep","yRange","defaultYMin","defaultYMax","defaultYStep","zRange","defaultZMin","defaultZMax","defaultZStep","valueRange","defaultValueMin","defaultValueMax","_getDataPoints","sortNumber","dataMatrix","xIndex","yIndex","trans","screen","pointRight","pointTop","pointCross","position","noCanvas","fontWeight","padding","onmousedown","_onMouseDown","ontouchstart","_onTouchStart","onmousewheel","_onWheel","ontooltip","_onTooltip","onkeydown","setSize","_resizeCanvas","clientHeight","animationStart","slider","play","animationStop","_resizeCenter","setCameraPosition","pos","horizontal","vertical","setArmRotation","setArmLength","getCameraPosition","getArmRotation","_readData","_redrawFilter","animationAutoStart","cameraPosition","styleNumber","tooltip","showAnimationControls","_redrawSlider","_redrawClear","_redrawAxis","_redrawDataGrid","_redrawDataLine","_redrawDataBar","_redrawDataDot","_redrawInfo","_redrawLegend","ctx","getContext","clearRect","widthMin","widthMax","dotSize","right","lineWidth","font","ymin","ymax","_hsv2rgb","strokeStyle","beginPath","moveTo","lineTo","strokeRect","fillStyle","closePath","gridLineLen","step","getCurrent","textAlign","textBaseline","fillText","visible","setValues","setPlayInterval","onchange","getIndex","selectValue","setOnChangeCallback","lineStyle","getLabel","getSelectedValue","prettyStep","text","xText","yText","zText","xMin2d","xMax2d","gridLenX","gridLenY","textMargin","armAngle","H","S","V","R","G","B","C","Hi","X","cross","topSideVisible","zAvg","transBottom","dist","sortDepth","aDiff","bDiff","crossproduct","crossProduct","radius","arc","surface","corners","xWidth","yWidth","surfaces","avg","transCenter","leftButtonDown","_onMouseUp","touchDown","startMouseX","startMouseY","startStart","startEnd","startArmRotation","cursor","onmousemove","_onMouseMove","onmouseup","diffX","diffY","horizontalNew","verticalNew","snapAngle","snapValue","parameters","boundingRect","mouseX","mouseY","tooltipTimeout","_hideTooltip","dataPoint","_dataPointFromXY","_showTooltip","ontouchmove","_onTouchMove","ontouchend","_onTouchEnd","wheelDelta","detail","oldLength","newLength","_insideTriangle","triangle","bs","cs","distMax","closestDataPoint","closestDist","triangle1","triangle2","distX","distY","borderRadius","boxShadow","borderLeft","contentWidth","contentHeight","dotWidth","dotHeight","mixin","_callbacks","once","removeListener","removeAllListeners","callbacks","cb","listeners","hasListeners","sub","sum","armLocation","armRotation","armLength","cameraLocation","cameraRotation","calculateCameraOrientation","rot","graph","onLoadCallback","loadInBackground","isLoaded","getLoadedProgress","getColumn","getValues","getValue","dataView","progress","prev","bar","MozBorderRadius","slide","onclick","togglePlay","onChangeCallback","playTimeout","playInterval","playLoop","setIndex","playNext","clearInterval","getPlayInterval","setPlayLoop","doLoop","onChange","indexToLeft","startClientX","startSlideX","leftToIndex","_start","_end","_step","precision","_current","setRange","setStep","calculatePrettyStep","log10","log","LN10","step1","pow","step2","step5","toPrecision","getStep","groups","forthArgument","defaultOptions","autoResize","maxHeight","minHeight","_create","body","domProps","emitter","bind","hiddenDates","timeAxis","_toScreen","toGlobalScreen","_toGlobalScreen","toTime","_toTime","toGlobalTime","_toGlobalTime","timeAxis2","currentTime","groupsData","getEventProperties","oncontextmenu","configurator","Configurator","configureOptions","setGroups","setItems","_redraw","Core","Validator","printStyle","allOptions","markDirty","refreshItems","errorFound","validate","selection","getSelection","setSelection","newDataSet","initialLoad","dataRange","_getDataRange","setWindow","animation","fit","focus","getItemRange","dataset","minItem","maxStartItem","maxEndItem","centerContainer","itemFromTarget","groupFromTarget","customTime","customTimeFromTarget","snap","snappedTime","what","labelSet","groupId","pageX","pageY","showCurrentTime","backgroundVertical","warned","current","substring","currentTimeTimer","setCurrentTime","getCurrentTime","_isResized","resized","_previousWidth","_previousHeight","deltaDifference","scaleOffset","startToFront","endToFront","moveable","zoomable","zoomMin","zoomMax","animationTimer","_onDragStart","_onDrag","_onDragEnd","_onMouseWheel","_onTouch","_onPinch","validateDirection","getPointer","byUser","finalStart","finalEnd","_cancelAnimation","initStart","initEnd","easingName","easingFunction","initTime","anyChanged","dragging","ease","done","_applyRange","updateHiddenDates","newStart","newEnd","getRange","totalHidden","previousDelta","allowDragging","getHiddenDurationBetween","diffRange","safeStart","snapAwayFromHidden","safeEnd","pointer","pointerDate","_pointerToDate","zoom","centerDate","hiddenDuration","hiddenDurationBefore","getHiddenDurationBefore","hiddenDurationAfter","move","onTouch","isTouching","onRelease","isReleasing","offTouch","offRelease","convertHiddenOptions","repeat","dateItem","totalRange","pixelTime","startDate","endDate","runUntil","dayOffset","removeDuplicates","startHidden","isHidden","endHidden","rangeStart","rangeEnd","hidden","safeDates","printDates","stepOverHiddenDates","timeStep","previousTime","stepInHidden","currentValue","switchedYear","switchedMonth","switchedDay","correctTimeForHidden","totalDuration","partialDuration","accumulatedHiddenDuration","getAccumulatedHiddenDuration","newTime","timeOffset","requiredDuration","previousPoint","correctionEnabled","hammerUtil","Activator","onMouseWheel","isActive","backgroundHorizontal","leftContainer","rightContainer","shadowTop","shadowBottom","shadowTopLeft","shadowBottomLeft","shadowTopRight","shadowBottomRight","_redrawTimer","scrollTop","scrollTopMin","customTimes","redrawCount","clickToUse","activator","_initAutoResize","component","configure","appliedOptions","setModuleOptions","active","_stopAutoResize","setCustomTime","getCustomTime","addCustomTime","timestamp","some","removeCustomTime","getVisibleItems","getWindow","borderRootHeight","borderRootWidth","autoHeight","containerHeight","centerWidth","_updateScrollTop","visibilityTop","visibilityBottom","visibility","MAX_REDRAWS","repaint","_startAutoResize","_onResize","lastWidth","lastHeight","watchTimer","setInterval","initialScrollTop","oldScrollTop","_getScrollTop","newScrollTop","_setScrollTop","groupOrder","selectable","multiselect","updateTime","updateGroup","onAdd","onUpdate","onMove","onRemove","onMoving","itemOptions","itemListeners","_onAdd","_onUpdate","_onRemove","groupListeners","_onAddGroups","_onUpdateGroups","_onRemoveGroups","groupIds","stackDirty","touchParams","UNGROUPED","BACKGROUND","_updateUngrouped","backgroundGroup","_onSelectItem","_onMultiSelectItem","_onAddItem","addCallback","rawVisibleItems","visibleItems","_deselect","_orderGroups","visibleInterval","zoomed","lastVisibleInterval","restack","firstGroup","_firstGroup","firstMargin","nonFirstMargin","groupMargin","groupResized","firstGroupIndex","firstGroupId","ungrouped","_getGroupId","getLabelSet","oldItemsData","getItems","_order","getGroups","removeItem","_getType","_removeItem","groupData","groupOptions","oldGroupId","oldSubGroupId","subgroup","oldGroup","_constructByEndArray","endArray","dragLeftItem","dragRightItem","itemProps","initialX","dragLeft","dragRight","ctrlKey","metaKey","_onDragStartAddItem","xAbs","newItem","offsetLeft","initial","initialStart","initialEnd","changes","shiftKey","oldSelection","newSelection","_getItemRange","_item","itemSetFromTarget","subgroups","subgroupIndex","subgroupOrderer","subgroupOrder","byStart","byEnd","checkRangedItems","inner","marker","getLabelWidth","markerHeight","lastMarkerHeight","limitSize","customOrderedItems","_updateVisibleItems","nostack","_calculateHeight","offsetTop","resetSubgroups","orderSubgroups","_checkIfVisible","sortArray","sortField","startArray","orderByStart","orderByEnd","oldVisibleItems","visibleItemsLookup","lowerBound","upperBound","_checkIfVisibleWithReference","initialPosByStart","_traceVisible","initialPosByEnd","initialPos","breakCondition","EPSILON","aTime","bTime","iMax","collidingItem","jj","collision","newTop","baseClassName","getComputedStyle","maxWidth","_repaintDragLeft","_repaintDragRight","contentLeft","parentWidth","boxWidth","minimumStep","autoScale","FORMAT","minorLabels","majorLabels","setFormat","setMinimumStep","first","roundToMinor","setDate","setHours","setMinutes","setSeconds","setMilliseconds","getMilliseconds","getSeconds","getMinutes","getHours","hasNext","setScale","setAutoScale","stepYear","stepMonth","stepDay","stepHour","stepMinute","stepSecond","stepMillisecond","isMajor","getLabelMinor","getLabelMajor","getClassName","even","today","currentWeek","currentMonth","currentYear","marginLeft","onTop","itemSubgroup","totalHeight","newHeight","lines","majorTexts","minorTexts","lineTop","showMinorLabels","showMajorLabels","parentChanged","_calculateCharSize","minorLabelHeight","minorCharHeight","majorLabelHeight","majorCharHeight","minorLineHeight","minorLineWidth","majorLineHeight","majorLineWidth","foregroundNextSibling","nextSibling","backgroundNextSibling","_repaintLabels","timeLabelsize","minorCharWidth","cur","prevLine","xPrev","xFirstMajorLabel","_repaintMinorText","_repaintMajorText","_repaintMajorLine","_repaintMinorLine","leftTime","leftText","widthText","majorCharWidth","pop","createTextNode","childNodes","nodeValue","measureCharMinor","measureCharMajor","overlay","_onTapOverlay","bodyHammer","prevent_default","_hasParent","deactivate","keycharm","escListener","activate","display","unbind","_exportFunctions","_bound","keydown","keyup","_keys","fromCharCode","down","handleEvent","up","keyCode","bound","bindAll","getKey","newBindings","eventParams","drag","_interopRequireDefault","__esModule","default","_classCallCheck","instance","Constructor","defineProperty","_createClass","defineProperties","descriptor","enumerable","configurable","writable","protoProps","staticProps","_ColorPicker","_ColorPicker2","parentModule","defaultContainer","pixelRatio","changedOptions","allowCreation","showButton","moduleOptions","domElements","colorPicker","wrapper","_clean","_this","_handleObject","_makeItem","_makeHeader","generateButton","_printOptions","onmouseover","onmouseout","optionsContainer","_push","insertTo","path","_this2","_len","_key","div","objectLabel","selectedValue","_update","_makeLabel","oninput","checkbox","checked","_this3","defaultColor","_showColorPicker","_this4","bodyRect","pickerX","pickerY","setColor","setCallback","colorString","checkOnly","visibleInSet","subObj","newPath","_getValue","_handleArray","_makeTextInput","_makeCheckbox","draw","physics","solver","enabledPath","enabledValue","error","_makeColorField","_makeDropdown","_makeRange","_constructOptions","optionsObj","ColorPicker","generated","centerCoordinates","hueCircle","initialColor","previousColor","applied","updateCallback","_bindHammer","_setSize","htmlColors","black","navy","darkblue","mediumblue","darkgreen","teal","darkcyan","deepskyblue","darkturquoise","mediumspringgreen","lime","springgreen","aqua","cyan","midnightblue","dodgerblue","lightseagreen","forestgreen","seagreen","darkslategray","limegreen","mediumseagreen","turquoise","royalblue","steelblue","darkslateblue","mediumturquoise","indigo","darkolivegreen","cadetblue","cornflowerblue","mediumaquamarine","dimgray","slateblue","olivedrab","slategray","lightslategray","mediumslateblue","lawngreen","chartreuse","aquamarine","maroon","purple","olive","gray","skyblue","lightskyblue","blueviolet","darkred","darkmagenta","saddlebrown","darkseagreen","lightgreen","mediumpurple","darkviolet","palegreen","darkorchid","yellowgreen","sienna","brown","darkgray","lightblue","greenyellow","paleturquoise","lightsteelblue","powderblue","firebrick","darkgoldenrod","mediumorchid","rosybrown","darkkhaki","silver","mediumvioletred","indianred","peru","chocolate","tan","lightgrey","palevioletred","thistle","orchid","goldenrod","crimson","gainsboro","plum","burlywood","lightcyan","lavender","darksalmon","violet","palegoldenrod","lightcoral","khaki","aliceblue","honeydew","azure","sandybrown","wheat","beige","whitesmoke","mintcream","ghostwhite","salmon","antiquewhite","linen","lightgoldenrodyellow","oldlace","fuchsia","magenta","deeppink","orangered","tomato","hotpink","coral","darkorange","lightsalmon","orange","lightpink","pink","gold","peachpuff","navajowhite","moccasin","bisque","mistyrose","blanchedalmond","papayawhip","lavenderblush","seashell","cornsilk","lemonchiffon","floralwhite","snow","yellow","lightyellow","ivory","white","setInitial","htmlColor","_isColorString","rgbaArray","rgbObj","alpha","_setColor","_generateHueCircle","storePrevious","_hide","_updatePicker","alert","angleConvert","colorPickerSelector","colorPickerCanvas","pixelRation","devicePixelRatio","webkitBackingStorePixelRatio","mozBackingStorePixelRatio","msBackingStorePixelRatio","oBackingStorePixelRatio","backingStorePixelRatio","setTransform","putImageData","circle","brightnessRange","opacityRange","initialColorDiv","newColorDiv","colorPickerDiv","opacityDiv","brightnessDiv","arrowDiv","_setOpacity","_setBrightness","brightnessLabel","opacityLabel","cancelButton","applyButton","_apply","saveButton","_save","loadButton","_loadLast","pinch","_moveSelector","sat","hfac","sfac","fillRect","getImageData","centerY","centerX","newLeft","referenceOptions","subObject","usedOptions","check","__any__","getSuggestion","checkFields","__type__","referenceOption","refOptionObj","optionType","refOptionType","print","printLocation","localSearch","findInOptions","globalSearch","localSearchThreshold","globalSearchThreshold","indexMatch","closestMatch","recursive","closestMatchPath","lowerCaseOption","op","levenshteinDistance","matrix","boolean","nada","undef","linegraph","getLegend","isGroupVisible","yAxisLeft","yAxisRight","legendLeft","legendRight","screenToValue","yAxisOrientation","defaultGroup","sampling","graphHeight","shaded","barChart","sideBySide","interpolation","parametrization","dataAxis","icons","alignZeros","legend","abortedGraphUpdate","updateSVGheight","updateSVGheightOnResize","lastStart","svgElements","groupsUsingDefaultStyles","COUNTER","svg","framework","BarFunctions","LineFunctions","_updateAllGroupData","_updateGroup","removeGroup","addGroup","groupsContent","ungroupedCounter","forceGraphUpdate","_updateGraph","rangePerPixelInv","preprocessedGroupData","processedGroupData","groupRanges","changeCalled","minDate","maxDate","_getRelevantData","_applySampling","_convertXcoordinates","_getYRanges","_updateYAxis","MAX_CYCLES","_convertYcoordinates","dataContainer","guess","increment","amountOfPoints","xDistance","pointsPerPixel","sampledData","combinedDataLeft","combinedDataRight","getData","getYRange","getStackedYRange","minVal","maxVal","yAxisLeftUsed","yAxisRightUsed","minLeft","minRight","maxLeft","maxRight","ignore","_toggleAxisVisiblity","drawIcons","master","lineOffset","stepPixels","zeroCrossing","amountOfSteps","tempGroups","axisUsed","datapoints","xValue","yValue","extractedData","svgHeight","labelValue","convertValue","setZeroPosition","linegraphOptions","majorLinesOffset","minorLinesOffset","labelOffsetX","labelOffsetY","iconWidth","linegraphSVG","DOMelements","labels","conversionFactor","minWidth","iconsRemoved","amountOfGroups","lineContainer","graphOptions","_redrawGroupIcons","iconHeight","iconOffset","groupArray","drawIcon","_cleanupIcons","activeGroups","_redrawLabels","_redrawTitle","stepSize","marginRange","valueAtBottom","marginEnd","maxLabelSize","stepIndex","_redrawLabel","_redrawLine","titleWidth","titleCharHeight","invertedValue","convertedValue","characterHeight","largestWidth","textMinor","textMajor","textTitle","measureCharTitle","titleCharWidth","customRange","formattingFunction","marginStart","deadSpace","majorSteps","minorSteps","setFirst","safeRange","minimumStepValue","orderOfMagnitude","minorStepIdx","magnitudefactor","solutionFound","niceStart","niceEnd","rounded","previous","steps","usingDefaultStyle","zeroPosition","Line","Bar","Points","SVGcontainer","fillPath","fillHeight","outline","barWidth","bar1Height","bar2Height","icon","combinedData","groupLabel","intersections","_getDataIntersections","_getStackedYRange","accumulatedNegative","accumulatedPositive","xpos","coreDistance","amount","resolved","_catmullRom","_linear","dFill","_catmullRomUniform","p0","bp1","bp2","normalization","d1","d2","d3","A","N","d3powA","d2powA","d3pow2A","d2pow2A","d1pow2A","d1powA","Bargraph","drawData","barPoints","heightOffset","_getSafeDrawData","nextKey","prevKey","side","iconSize","iconSpacing","textArea","scrollableHeight","drawLegendIcons","paddingTop","any","nodes","nodeIndices","edges","edgeIndices","functions","createNode","createEdge","eventListeners","onTap","onDoubleTap","onHold","onDragStart","onDrag","onDragEnd","onPinch","onMouseMove","onContext","view","bindEventListeners","images","_modulesGroups2","_modulesCanvas2","selectionHandler","_modulesSelectionHandler2","interactionHandler","_modulesInteractionHandler2","_modulesView2","renderer","_modulesCanvasRenderer2","_modulesPhysicsEngine2","layoutEngine","_modulesLayoutEngine2","clustering","_modulesClustering2","manipulation","_modulesManipulationSystem2","nodesHandler","_modulesNodesHandler2","edgesHandler","_modulesEdgesHandler2","_sharedConfigurator2","_optionsJs","_modulesGroups","_modulesNodesHandler","_modulesEdgesHandler","_modulesPhysicsEngine","_modulesClustering","_modulesCanvasRenderer","_modulesCanvas","_modulesView","_modulesInteractionHandler","_modulesSelectionHandler","_modulesLayoutEngine","_modulesManipulationSystem","_sharedConfigurator","_sharedValidator","_sharedValidator2","layout","interaction","networkOptions","_updateVisibleIndices","nodeId","edgeId","updatePhysicsData","_updateValueRange","unselectAll","dotData","gephi","gephiData","valueTotal","setValueRange","canvasToDOM","DOMtoCanvas","findNode","isCluster","openCluster","cluster","getNodesInCluster","clusterByConnection","clusterByHubsize","clusterOutliers","getSeed","enableEditMode","disableEditMode","addNodeMode","editNode","editNodeMode","addEdgeMode","editEdgeMode","deleteSelected","getPositions","storePositions","getBoundingBox","getConnectedNodes","objectId","getConnectedEdges","startSimulation","stopSimulation","stabilize","getSelectedNodes","getSelectedEdges","getNodeAt","getEdgeAt","edge","selectNodes","selectEdges","getViewPosition","releaseNode","Groups","defaultIndex","groupsArray","groupIndex","defaultGroups","useDefaultGroups","optionFields","groupName","groupname","_componentsNode","_componentsNode2","_componentsSharedLabel","_componentsSharedLabel2","NodesHandler","nodesListeners","borderWidthSelected","brokenImage","fixed","face","strokeColor","image","level","mass","scaling","maxVisible","drawThreshold","customScalingFunction","shadow","shape","parseOptions","updateShape","updateLabelModule","_reset","doNotEmit","oldNodesData","newNodes","_properties","positionInitially","changedData","dataChanged","constructorClass","dataArray","boundingBox","nodeList","nodeObj","toId","fromId","edgeList","_sharedLabel","_sharedLabel2","_nodesShapesBox","_nodesShapesBox2","_nodesShapesCircle","_nodesShapesCircle2","_nodesShapesCircularImage","_nodesShapesCircularImage2","_nodesShapesDatabase","_nodesShapesDatabase2","_nodesShapesDiamond","_nodesShapesDiamond2","_nodesShapesDot","_nodesShapesDot2","_nodesShapesEllipse","_nodesShapesEllipse2","_nodesShapesIcon","_nodesShapesIcon2","_nodesShapesImage","_nodesShapesImage2","_nodesShapesSquare","_nodesShapesSquare2","_nodesShapesStar","_nodesShapesStar2","_nodesShapesText","_nodesShapesText2","_nodesShapesTriangle","_nodesShapesTriangle2","_nodesShapesTriangleDown","_nodesShapesTriangleDown2","Node","imagelist","grouplist","globalOptions","baseSize","baseFontSize","predefinedPosition","labelModule","status","groupObj","imageObj","load","distanceToBorder","sizeDiff","fontDiff","updateBoundingBox","resize","parentOptions","newOptions","parsedColor","_slicedToArray","Symbol","_arr","_n","_e","_s","err","Label","yLine","labelDirty","baseline","viewFontSize","calculateLabelSize","_drawBackground","_drawText","lineMargin","fontSize","_getColor","_getColor2","fontColor","_setAlignment","_setAlignment2","lineJoin","lineCount","strokeText","_processLabel","measureText","newOptionsArray","_inherits","subClass","superClass","__proto__","_get","_x","_x2","_x3","_again","receiver","desc","getOwnPropertyDescriptor","getPrototypeOf","_utilNodeBase","_utilNodeBase2","Box","_NodeBase","textSize","getTextSize","selectionLineWidth","roundRect","enableShadow","disableShadow","NodeBase","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","_utilCircleImageBase","_utilCircleImageBase2","Circle","_CircleImageBase","diameter","_drawRawCircle","CircleImageBase","labelOffset","imageLoaded","ratio","networkScaleInv","globalAlpha","drawImage","labelDimensions","CircularImage","_swapToImageResizeWhenImageLoaded","_resizeImage","save","clip","_drawImageAtPosition","restore","_drawImageLabel","_distanceToBorder","Database","database","_utilShapeBase","_utilShapeBase2","Diamond","_ShapeBase","_resizeShape","_drawShape","ShapeBase","sizeMultiplier","Dot","Ellipse","ellipse","Icon","_icon","iconTextSpacing","Image","Square","Star","Text","Triangle","TriangleDown","_componentsEdge","_componentsEdge2","EdgesHandler","edgesListeners","arrows","scaleFactor","dashes","hoverWidth","selectionWidth","selfReferenceSize","smooth","roundness","emitChange","edgeData","edgeOptions","reconnectEdges","markAllEdgesAsDirty","updateEdgeType","oldEdgesData","edgesData","oldEdge","disconnect","showInternalIds","connect","via","supportNodes","edgeType","colorDirty","_edgesBezierEdgeDynamic","_edgesBezierEdgeDynamic2","_edgesBezierEdgeStatic","_edgesBezierEdgeStatic2","_edgesStraightEdge","_edgesStraightEdge2","Edge","baseWidth","connected","_setInteractionWidths","changeInType","cleanup","togglePhysics","attachEdge","detachEdge","widthDiff","drawLine","drawArrows","drawLabel","viaNode","drawArrowHead","node1","node2","getPoint","translate","_rotateForLabelAlignment","_pointOnCircle","xFrom","yFrom","xTo","yTo","xObj","yObj","getDistanceToEdge","angleInDegrees","rotate","percentage","colorsDefined","_utilBezierEdgeBase","_utilBezierEdgeBase2","BezierEdgeDynamic","_BezierEdgeBase","setupSupportNode","parentEdgeId","positionBezierNode","quadraticCurveTo","nearNode","_findBorderPositionBezier","x1","y1","x2","y2","x3","y3","_getDistanceToBezierEdge","_x4","_EdgeBase2","_EdgeBase3","BezierEdgeBase","_EdgeBase","distanceToPoint","difference","_getViaCoordinates","xVia","yVia","minDistance","lastX","lastY","_getDistanceToLine","EdgeBase","getColor","getLineWidth","_drawDashedLine","_drawLine","_line","_getCircleData","_getCircleData2","_circle","lineCap","pattern","setLineDash","lineDashOffset","_getCircleData3","_getCircleData32","dashedLine","_getCircleData4","_getCircleData42","_findBorderPosition","_findBorderPositionCircle","_getCircleData5","_getCircleData52","colorOptions","grd","createLinearGradient","fromColor","toColor","addColorStop","_getDistanceToEdge","_getCircleData6","_getCircleData62","px","py","something","u","arrowPos","guideOffset","findBorderPosition","guidePos","arrow","_angle","_getCircleData7","_getCircleData72","_length","_x5","_x6","BezierEdgeStatic","factor","pi","originalAngle","myAngle","_utilEdgeBase","_utilEdgeBase2","StraightEdge","edgeSegmentLength","toBorderDist","toBorderPoint","borderPos","_componentsPhysicsBarnesHutSolver","_componentsPhysicsBarnesHutSolver2","_componentsPhysicsRepulsionSolver","_componentsPhysicsRepulsionSolver2","_componentsPhysicsHierarchicalRepulsionSolver","_componentsPhysicsHierarchicalRepulsionSolver2","_componentsPhysicsSpringSolver","_componentsPhysicsSpringSolver2","_componentsPhysicsHierarchicalSpringSolver","_componentsPhysicsHierarchicalSpringSolver2","_componentsPhysicsCentralGravitySolver","_componentsPhysicsCentralGravitySolver2","_componentsPhysicsFA2BasedRepulsionSolver","_componentsPhysicsFA2BasedRepulsionSolver2","_componentsPhysicsFA2BasedCentralGravitySolver","_componentsPhysicsFA2BasedCentralGravitySolver2","PhysicsEngine","physicsBody","physicsNodeIndices","physicsEdgeIndices","forces","velocities","physicsEnabled","simulationInterval","requiresTimeout","previousStates","freezeCache","renderTimer","stabilized","startedStabilization","stabilizationIterations","ready","barnesHut","theta","gravitationalConstant","centralGravity","springLength","springConstant","damping","avoidOverlap","forceAtlas2Based","repulsion","nodeDistance","hierarchicalRepulsion","maxVelocity","minVelocity","stabilization","iterations","updateInterval","onlyDynamicEdges","timestep","initPhysics","nodesSolver","edgesSolver","gravitySolver","modelOptions","viewFunction","simulationStep","_emitStabilized","startTime","physicsTick","physicsTime","runDoubleSpeed","calculateForces","moveNodes","revert","nodeIds","vx","vy","nodesPresent","vminCorrected","nodeVelocity","_performStep","totalVelocity","solve","targetIterations","_freezeNodes","_stabilizationBatch","_finalizeStabilization","_restoreFrozenNodes","BarnesHutSolver","barnesHutTree","thetaInversed","overlapAvoidanceFactor","nodeCount","_formBarnesHutTree","_getForceContribution","NW","NE","SW","SE","parentBranch","childrenCount","centerOfMass","calcSize","_calculateForces","gravityForce","fx","fy","minX","minY","maxX","maxY","minimumTreeSize","rootSize","halfRootSize","_splitBranch","_placeInTree","totalMass","totalMassInv","biggestSize","skipMassUpdate","_updateBranchMass","_placeInRegion","region","containedNode","_insertRegion","childSize","_drawBranch","branch","RepulsionSolver","repulsingForce","HierarchicalRepulsionSolver","steepness","SpringSolver","edgeLength","node3","_calculateSpringForce","springForce","HierarchicalSpringSolver","springFx","springFy","totalFx","totalFy","correctionFx","correctionFy","CentralGravitySolver","_BarnesHutSolver2","_BarnesHutSolver3","ForceAtlas2BasedRepulsionSolver","_BarnesHutSolver","degree","_CentralGravitySolver2","_CentralGravitySolver3","ForceAtlas2BasedCentralGravitySolver","_CentralGravitySolver","_componentsNodesCluster","_componentsNodesCluster2","ClusterEngine","clusteredNodes","hubsize","_getHubSize","_checkOptions","nodesToCluster","refreshData","joinCondition","childNodesObj","childEdgesObj","clonedOptions","_cloneOptions","_cluster","clusters","visibleEdges","childNodeId","_getConnectedId","_checkIfUsed","clusterNodeProperties","parentNodeId","parentClonedOptions","childClonedOptions","amountOfConnections","newEdges","clusterEdgeProperties","childNode","otherNodeId","childKeys","processProperties","childNodesOptions","childEdgesOptions","clusterId","_getClusterPosition","clusterNode","containedNodes","containedEdges","_createClusterEdges","clusterNodeId","clusteredNode","_clusterNode","newEdge","nodesArray","average","averageSquared","hubCounter","largestHub","letiance","standardDeviation","hubThreshold","_Node2","_Node3","Cluster","_Node","requestAnimationFrame","mozRequestAnimationFrame","webkitRequestAnimationFrame","msRequestAnimationFrame","CanvasRenderer","redrawRequested","renderingActive","renderRequests","allowRedrawRequests","hideEdgesOnDrag","hideNodesOnDrag","_determineBrowserMethod","_resizeNodes","_requestRedraw","_startRendering","cancelAnimationFrame","_renderStep","_drawEdges","_drawNodes","controlNodesActive","_drawControlNodes","alwaysShow","topLeft","bottomRight","viewableArea","isSelected","isBoundingBoxOverlappingWith","browserType","Canvas","resizeTimer","resizeFunction","hammerFrame","_cleanUp","tabIndex","_prepareValue","emitEvent","oldWidth","oldHeight","_XconvertCanvasToDOM","_YconvertCanvasToDOM","_XconvertDOMtoCanvas","_YconvertDOMtoCanvas","View","animationSpeed","renderRefreshRate","animationEasingFunction","easingTime","sourceScale","targetScale","sourceTranslation","targetTranslation","lockedOnNodeId","lockedOnNodeOffset","touchTime","specificNodes","zoomLevel","initialZoom","positionDefined","_getRange","numberOfNodes","yDistance","xZoomLevel","yZoomLevel","_findCenter","animationOptions","nodePosition","lockedOnNode","animateView","locked","_transitionRedraw","viewCenter","distanceFromCenter","_lockedRedraw","finished","_componentsNavigationHandler","_componentsNavigationHandler2","_componentsPopup","_componentsPopup2","InteractionHandler","navigationHandler","popup","popupObj","popupTimer","dragNodes","dragView","keyboard","speed","bindToWindow","navigationButtons","tooltipDelay","zoomView","pinched","checkSelectionChanges","_generateClickEvent","previouslySelectedEdgeCount","_getSelectedEdgeCount","previouslySelectedNodeCount","_getSelectedNodeCount","previousSelection","selectAdditionalOnPoint","selectOnPoint","selectedEdgesCount","selectedNodesCount","currentSelection","_determineIfDifferent","nodesChanges","edgesChanges","selectObject","selectionObj","xFixed","yFixed","_handleDragStart","scaleOld","preScaleDragPointer","scaleFrac","tx","ty","postScaleDragPointer","popupVisible","_checkHidePopup","setPosition","_checkShowPopup","hoverObject","pointerObj","previousPopupObjId","nodeUnderCursor","popupType","overlappingNodes","isOverlappingWith","getTitle","overlappingEdges","popupTargetType","popupTargetId","setText","_pointerToPositionObject","stillOnObj","overNode","NavigationHandler","iconsCreated","navigationHammers","boundFunctions","activated","_stopMovement","configureKeyboardBindings","loadNavigationElements","cleanNavigation","navigationDOM","navigationDivs","navigationDivActions","_fit","bindToRedraw","boundAction","unbindFromRedraw","Popup","doShow","SelectionHandler","hoverObj","selectConnectedEdges","hoverConnectedEdges","updateSelection","selectionChanged","deselectObject","DOM","highlightEdges","_selectConnectedEdges","_addToSelection","_removeFromSelection","canvasPos","returnNode","positionObject","_getAllNodesOverlappingWith","_getEdgesOverlappingWith","returnEdge","_getAllEdgesOverlappingWith","clusterSize","_addToHover","hoverChanged","blurObject","_hoverConnectedEdges","edgeIds","idArray","RangeError","LayoutEngine","initialRandomSeed","randomSeed","optionsBackup","hierarchical","levelSeparation","sortMethod","hierarchicalLevels","setupHierarchicalLayout","prevHierarchicalState","adaptAllOptions","isFixed","seededRandom","definedLevel","undefinedLevel","nodeSpacing","_determineLevelsByHubsize","_determineLevelsDirected","distribution","_getDistribution","_placeNodesByHierarchy","positionedNodes","_placeBranchNodes","hubSize","_setLevelByHubsize","minLevel","_setLevelDirected","parentId","parentLevel","childNodeLevel","ManipulationSystem","editMode","manipulationDiv","editModeDiv","closeDiv","manipulationHammers","temporaryUIFunctions","temporaryEventFunctions","temporaryIds","guiEnabled","inMode","selectedControlNode","initiallyActive","addNode","addEdge","editEdge","deleteNode","deleteEdge","controlNodeStyle","_restore","_setup","showManipulatorToolbar","_createEditButton","manipulationDOM","selectedNodeCount","selectedEdgeCount","selectedTotalCount","needSeperator","_createAddNodeButton","_createSeperator","_createAddEdgeButton","_createEditNodeButton","_createEditEdgeButton","_createDeleteButton","_bindHammerToDiv","toggleEditMode","_temporaryBindEvent","_createBackButton","_createDescription","_performAddNode","_getSelectedNode","finalizedData","_temporaryBindUI","_handleConnect","_finishConnect","_dragControlNode","edgeBeingEditedId","controlNodeFrom","_getNewTargetNode","controlNodeTo","_controlNodeTouch","_controlNodeDragStart","_controlNodeDrag","_controlNodeDragEnd","positions","findBorderPositions","selectedNodes","selectedEdges","deleteFunction","_createWrappers","_removeManipulationDOM","_createButton","_cleanManipulatorHammers","_cleanupTemporaryNodesAndEdges","_unbindTemporaryUIs","_unbindTemporaryEvents","labelClassName","newFunction","boundFunction","UIfunctionName","functionName","eventName","domElement","indexTempEdge","indexTempNode","lastTouch","fromSelect","toSelect","overlappingNodeIds","_performEditEdge","targetNode","connectionEdge","connectFromId","_performAddEdge","clickData","defaultData","sourceNodeId","targetNodeId","_this5","_this6","CanvasRenderingContext2D","square","s2","ir","triangleDown","star","diamond","r2d","kappa","ox","oy","xe","ye","xm","ym","bezierCurveTo","wEllipse","hEllipse","ymb","yeb","xt","yt","xi","yi","xl","yl","xr","yr","patternLength","slope","distRemaining","patternIndex","dashLength","parseDOT","parseGraph","nextPreview","isAlphaNumeric","regexAlphaNumeric","setValue","o","graphs","attr","getToken","tokenType","TOKENTYPE","NULL","isComment","DELIMITER","c2","DELIMITERS","IDENTIFIER","newSyntaxError","UNKNOWN","chop","parseStatements","parseStatement","subgraph","parseSubgraph","parseEdge","parseAttributeStatement","parseNodeStatement","subgraphs","parseAttributeList","message","maxLength","forEach2","elem1","elem2","setProp","convertAttr","mapping","visProp","visPropI","graphData","dotNode","graphNode","NODE_ATTR_MAPPING","convertEdge","dotEdge","graphEdge","EDGE_ATTR_MAPPING","subEdge","fontsize","fontcolor","labelfontcolor","fontname","fillcolor","labeltooltip","{","}","[","]",";","=",",","->","--","gephiJSON","inheritColor","gEdges","gNodes","gEdge","gNode","imageBroken","url","brokenUrl","img","onload","onerror","edit","del","back","addDescription","edgeDescription","editEdgeDescription","createEdgeError","deleteClusterError","editClusterError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,cAEA,SAA2CA,EAAMC,GAC1B,gBAAZC,UAA0C,gBAAXC,QACxCA,OAAOD,QAAUD,IACQ,kBAAXG,SAAyBA,OAAOC,IAC9CD,OAAOH,GACmB,gBAAZC,SACdA,QAAa,IAAID,IAEjBD,EAAU,IAAIC,KACbK,KAAM,WACT,MAAgB,UAAUC,GAKhB,QAASC,GAAoBC,GAG5B,GAAGC,EAAiBD,GACnB,MA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hJ,EAAGgJ,SAASlR,QAGds3B,QAAQ66C,MAAM,wBAAyB8+C,GACvCjxH,KAAKuN,IAAM2jH,EACgBzsH,SAAvByD,EAAG8oH,YAAY3wH,KACjB6H,EAAG8oH,YAAY3wH,OAEjB6H,EAAG8oH,YAAY3wH,GAAI4wH,IAAO,IAKhCE,EAAI5jH,IAAM0jH,EAGZ,MAAOE,IAGTtxH,EAAOD,QAAUwD,GAIb,SAASvD,EAAQD,EAASM,GAK9BN,EAAY,IACV0xH,KAAM,OACNC,IAAK,kBACLC,KAAM,OACN5L,QAAS,WACTC,QAAS,WACTpyB,SAAU,YACVqyB,SAAU,YACV2L,eAAgB,+CAChBC,gBAAiB,qEACjBC,oBAAqB,wEACrBC,gBAAiB,kCACjBC,mBAAoB,8BACpBC,iBAAkB,8BAEpBlyH,EAAe,MAAIA,EAAY,GAC/BA,EAAe,MAAIA,EAAY,GAG/BA,EAAY,IACV0xH,KAAM,WACNC,IAAK,uBACLC,KAAM,QACN5L,QAAS,iBACTC,QAAS,iBACTpyB,SAAU,gBACVqyB,SAAU,gBACV2L,eAAgB,uDAChBC,gBAAiB,6EACjBC,oBAAqB,kFACrBC,gBAAiB,wCACjBC,mBAAoB,0CACpBC,iBAAkB,0CAEpBlyH,EAAe,MAAIA,EAAY,GAC/BA,EAAe,MAAIA,EAAY"} \ No newline at end of file diff --git a/dist/vis.min.js b/dist/vis.min.js index eee8e80d..ff384416 100644 --- a/dist/vis.min.js +++ b/dist/vis.min.js @@ -4,8 +4,8 @@ * * A dynamic, browser-based visualization library. * - * @version 4.0.1-SNAPSHOT - * @date 2015-05-22 + * @version 4.1.0 + * @date 2015-05-28 * * @license * Copyright (C) 2011-2014 Almende B.V, http://almende.com @@ -22,21 +22,21 @@ * * Vis.js may be distributed under either license. */ -"use strict";!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):"object"==typeof exports?exports.vis=e():t.vis=e()}(this,function(){return function(t){function e(o){if(i[o])return i[o].exports;var n=i[o]={exports:{},id:o,loaded:!1};return t[o].call(n.exports,n,n.exports,e),n.loaded=!0,n.exports}var i={};return e.m=t,e.c=i,e.p="",e(0)}([function(t,e,i){e.util=i(57),e.DOMutil=i(2),e.DataSet=i(3),e.DataView=i(4),e.Queue=i(5),e.Graph3d=i(6),e.graph3d={Camera:i(7),Filter:i(8),Point2d:i(9),Point3d:i(10),Slider:i(11),StepNumber:i(12)},e.Timeline=i(13),e.Graph2d=i(14),e.timeline={DateUtil:i(15),DataStep:i(16),Range:i(17),stack:i(18),TimeStep:i(19),components:{items:{Item:i(21),BackgroundItem:i(22),BoxItem:i(20),PointItem:i(23),RangeItem:i(24)},Component:i(25),CurrentTime:i(26),CustomTime:i(27),DataAxis:i(28),GraphGroup:i(29),Group:i(30),BackgroundGroup:i(31),ItemSet:i(32),Legend:i(33),LineGraph:i(34),TimeAxis:i(35)}},e.Network=i(36),e.network={Images:i(37),dotparser:i(38),gephiParser:i(39)},e.network.convertDot=function(t){return e.network.dotparser.DOTToGraph(t)},e.network.convertGephi=function(t,i){return e.network.gephiParser.parseGephi(t,i)},e.Graph=function(){throw new Error("Graph is renamed to Network. Please create a graph as new vis.Network(...)")},e.moment=i(40),e.hammer=i(41),e.Hammer=i(41)},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function t(t,e){for(var i=0;i=t&&i.push(n.id)}for(var o=0;o0&&Object.keys(s).length>0&&i.push({nodes:n,edges:s})}}}for(var o=0;oo?r.x:o,n=r.ys?r.y:s;return{x:.5*(i+o),y:.5*(n+s)}}},{key:"openCluster",value:function(t){var e=void 0===arguments[1]?!0:arguments[1];if(void 0===t)throw new Error("No clusterNodeId supplied to openCluster.");if(void 0===this.body.nodes[t])throw new Error("The clusterNodeId supplied to openCluster does not exist.");if(void 0===this.body.nodes[t].containedNodes)return void console.log("The node:"+t+" is not a cluster.");var i=this.body.nodes[t],o=i.containedNodes,n=i.containedEdges;for(var s in o)if(o.hasOwnProperty(s)){var r=this.body.nodes[s];r=o[s],r.x=i.x,r.y=i.y,r.vx=i.vx,r.vy=i.vy,r.options.hidden=!1,r.togglePhysics(!0),delete this.clusteredNodes[s]}for(var a in n)if(n.hasOwnProperty(a)){var d=n[a];if(void 0===this.body.nodes[d.fromId]||void 0===this.body.nodes[d.toId])d.edgeType.cleanup(),d.disconnect(),delete this.body.edges[a];else if(void 0!==this.clusteredNodes[d.fromId]||void 0!==this.clusteredNodes[d.toId]){var l=void 0,u=void 0,c=this.clusteredNodes[d.fromId]||this.clusteredNodes[d.toId],p=c.clusterId,f=this.body.nodes[p];if(f.containedEdges[a]=d,d.from.options.hidden!==!0&&d.to.options.hidden!==!0){void 0!==this.clusteredNodes[d.fromId]?(l=p,u=d.toId):(l=d.fromId,u=p);var m=this._cloneOptions(d,"edge"),v="clusterEdge:"+h.randomUUID();h.deepExtend(m,f.clusterEdgeProperties),h.deepExtend(m,{from:l,to:u,hidden:!1,physics:!0,id:v});var g=this.body.functions.createEdge(m);this.body.edges[v]=g,this.body.edges[v].connect()}}else d.options.hidden=!1,d.togglePhysics(!0)}for(var y=0;yo;)e.push(this.clusteredNodes[t].node),t=this.clusteredNodes[t].clusterId,o++;return e.push(this.body.nodes[t]),e}},{key:"_getConnectedId",value:function(t,e){return t.toId!=e?t.toId:t.fromId!=e?t.fromId:t.fromId}},{key:"_getHubSize",value:function(){for(var t=0,e=0,i=0,o=0,n=0;no&&(o=s.edges.length),t+=s.edges.length,e+=Math.pow(s.edges.length,2),i+=1}t/=i,e/=i;var r=e-Math.pow(t,2),a=Math.sqrt(r),h=Math.floor(t+2*a);return h>o&&(h=o),h}}]),t}();e["default"]=d,t.exports=e["default"]},function(t,e,i){e.prepareElements=function(t){for(var e in t)t.hasOwnProperty(e)&&(t[e].redundant=t[e].used,t[e].used=[])},e.cleanupElements=function(t){for(var e in t)if(t.hasOwnProperty(e)&&t[e].redundant){for(var i=0;i0?(o=e[t].redundant[0],e[t].redundant.shift()):(o=document.createElementNS("http://www.w3.org/2000/svg",t),i.appendChild(o)):(o=document.createElementNS("http://www.w3.org/2000/svg",t),e[t]={used:[],redundant:[]},i.appendChild(o)),e[t].used.push(o),o},e.getDOMElement=function(t,e,i,o){var n;return e.hasOwnProperty(t)?e[t].redundant.length>0?(n=e[t].redundant[0],e[t].redundant.shift()):(n=document.createElement(t),void 0!==o?i.insertBefore(n,o):i.appendChild(n)):(n=document.createElement(t),e[t]={used:[],redundant:[]},void 0!==o?i.insertBefore(n,o):i.appendChild(n)),e[t].used.push(n),n},e.drawPoint=function(t,i,o,n,s,r){var a;if("circle"==o.options.drawPoints.style?(a=e.getSVGElement("circle",n,s),a.setAttributeNS(null,"cx",t),a.setAttributeNS(null,"cy",i),a.setAttributeNS(null,"r",.5*o.options.drawPoints.size)):(a=e.getSVGElement("rect",n,s),a.setAttributeNS(null,"x",t-.5*o.options.drawPoints.size),a.setAttributeNS(null,"y",i-.5*o.options.drawPoints.size),a.setAttributeNS(null,"width",o.options.drawPoints.size),a.setAttributeNS(null,"height",o.options.drawPoints.size)),void 0!==o.options.drawPoints.styles&&a.setAttributeNS(null,"style",o.group.options.drawPoints.styles),a.setAttributeNS(null,"class",o.className+" vis-point"),r){var h=e.getSVGElement("text",n,s);r.xOffset&&(t+=r.xOffset),r.yOffset&&(i+=r.yOffset),r.content&&(h.textContent=r.content),r.className&&h.setAttributeNS(null,"class",r.className+" vis-label"),h.setAttributeNS(null,"x",t),h.setAttributeNS(null,"y",i)}return a},e.drawBar=function(t,i,o,n,s,r,a,h){if(0!=n){0>n&&(n*=-1,i-=n);var d=e.getSVGElement("rect",r,a);d.setAttributeNS(null,"x",t-.5*o),d.setAttributeNS(null,"y",i),d.setAttributeNS(null,"width",o),d.setAttributeNS(null,"height",n),d.setAttributeNS(null,"class",s),h&&d.setAttributeNS(null,"style",h)}}},function(t,e,i){function o(t,e){if(t&&!Array.isArray(t)&&(e=t,t=null),this._options=e||{},this._data={},this.length=0,this._fieldId=this._options.fieldId||"id",this._type={},this._options.type)for(var i in this._options.type)if(this._options.type.hasOwnProperty(i)){var o=this._options.type[i];"Date"==o||"ISODate"==o||"ASPDate"==o?this._type[i]="Date":this._type[i]=o}if(this._options.convert)throw new Error('Option "convert" is deprecated. Use "type" instead.');this._subscribers={},t&&this.add(t),this.setOptions(e)}var n=i(57),s=i(5);o.prototype.setOptions=function(t){t&&void 0!==t.queue&&(t.queue===!1?this._queue&&(this._queue.destroy(),delete this._queue):(this._queue||(this._queue=s.extend(this,{replace:["add","update","remove"]})),"object"==typeof t.queue&&this._queue.setOptions(t.queue)))},o.prototype.on=function(t,e){var i=this._subscribers[t];i||(i=[],this._subscribers[t]=i),i.push({callback:e})},o.prototype.subscribe=function(){throw new Error("DataSet.subscribe is deprecated. Use DataSet.on instead.")},o.prototype.off=function(t,e){var i=this._subscribers[t];i&&(this._subscribers[t]=i.filter(function(t){return t.callback!=e}))},o.prototype.unsubscribe=function(){throw new Error("DataSet.unsubscribe is deprecated. Use DataSet.off instead.")},o.prototype._trigger=function(t,e,i){if("*"==t)throw new Error("Cannot trigger event *");var o=[];t in this._subscribers&&(o=o.concat(this._subscribers[t])),"*"in this._subscribers&&(o=o.concat(this._subscribers["*"]));for(var n=0;ns;s++)i=n._addItem(t[s]),o.push(i);else{if(!(t instanceof Object))throw new Error("Unknown dataType");i=n._addItem(t),o.push(i)}return o.length&&this._trigger("add",{items:o},e),o},o.prototype.update=function(t,e){var i=[],o=[],n=[],s=this,r=s._fieldId,a=function(t){var e=t[r];s._data[e]?(e=s._updateItem(t),o.push(e),n.push(t)):(e=s._addItem(t),i.push(e))};if(Array.isArray(t))for(var h=0,d=t.length;d>h;h++)a(t[h]);else{if(!(t instanceof Object))throw new Error("Unknown dataType");a(t)}return i.length&&this._trigger("add",{items:i},e),o.length&&this._trigger("update",{items:o,data:n},e),i.concat(o)},o.prototype.get=function(t){var e,i,o,s=this,r=n.getType(arguments[0]);"String"==r||"Number"==r?(e=arguments[0],o=arguments[1]):"Array"==r?(i=arguments[0],o=arguments[1]):o=arguments[0];var a;if(o&&o.returnType){var h=["Array","Object"];a=-1==h.indexOf(o.returnType)?"Array":o.returnType}else a="Array";var d,l,u,c,p=o&&o.type||this._options.type,f=o&&o.filter,m=[];if(void 0!=e)d=s._getItem(e,p),f&&!f(d)&&(d=null);else if(void 0!=i)for(u=0,c=i.length;c>u;u++)d=s._getItem(i[u],p),(!f||f(d))&&m.push(d);else for(l in this._data)this._data.hasOwnProperty(l)&&(d=s._getItem(l,p),(!f||f(d))&&m.push(d));if(o&&o.order&&void 0==e&&this._sort(m,o.order),o&&o.fields){var v=o.fields;if(void 0!=e)d=this._filterFields(d,v);else for(u=0,c=m.length;c>u;u++)m[u]=this._filterFields(m[u],v)}if("Object"==a){var g={};for(u=0;ue;e++)l[e]=s[e][this._fieldId]}else for(o in r)r.hasOwnProperty(o)&&(n=this._getItem(o,d),a(n)&&l.push(n[this._fieldId]));else if(h){s=[];for(o in r)r.hasOwnProperty(o)&&s.push(r[o]);for(this._sort(s,h),e=0,i=s.length;i>e;e++)l[e]=s[e][this._fieldId]}else for(o in r)r.hasOwnProperty(o)&&(n=r[o],l.push(n[this._fieldId]));return l},o.prototype.getDataSet=function(){return this},o.prototype.forEach=function(t,e){var i,o,n=e&&e.filter,s=e&&e.type||this._options.type,r=this._data;if(e&&e.order)for(var a=this.get(e),h=0,d=a.length;d>h;h++)i=a[h],o=i[this._fieldId],t(i,o);else for(o in r)r.hasOwnProperty(o)&&(i=this._getItem(o,s),(!n||n(i))&&t(i,o))},o.prototype.map=function(t,e){var i,o=e&&e.filter,n=e&&e.type||this._options.type,s=[],r=this._data;for(var a in r)r.hasOwnProperty(a)&&(i=this._getItem(a,n),(!o||o(i))&&s.push(t(i,a)));return e&&e.order&&this._sort(s,e.order),s},o.prototype._filterFields=function(t,e){if(!t)return t;var i={};if(Array.isArray(e))for(var o in t)t.hasOwnProperty(o)&&-1!=e.indexOf(o)&&(i[o]=t[o]);else for(var o in t)t.hasOwnProperty(o)&&e.hasOwnProperty(o)&&(i[e[o]]=t[o]);return i},o.prototype._sort=function(t,e){if(n.isString(e)){var i=e;t.sort(function(t,e){var o=t[i],n=e[i];return o>n?1:n>o?-1:0})}else{if("function"!=typeof e)throw new TypeError("Order must be a function or a string");t.sort(e)}},o.prototype.remove=function(t,e){var i,o,n,s=[];if(Array.isArray(t))for(i=0,o=t.length;o>i;i++)n=this._remove(t[i]),null!=n&&s.push(n);else n=this._remove(t),null!=n&&s.push(n);return s.length&&this._trigger("remove",{items:s},e),s},o.prototype._remove=function(t){if(n.isNumber(t)||n.isString(t)){if(this._data[t])return delete this._data[t],this.length--,t}else if(t instanceof Object){var e=t[this._fieldId];if(e&&this._data[e])return delete this._data[e],this.length--,e}return null},o.prototype.clear=function(t){var e=Object.keys(this._data);return this._data={},this.length=0,this._trigger("remove",{items:e},t),e},o.prototype.max=function(t){var e=this._data,i=null,o=null;for(var n in e)if(e.hasOwnProperty(n)){var s=e[n],r=s[t];null!=r&&(!i||r>o)&&(i=s,o=r)}return i},o.prototype.min=function(t){var e=this._data,i=null,o=null;for(var n in e)if(e.hasOwnProperty(n)){var s=e[n],r=s[t];null!=r&&(!i||o>r)&&(i=s,o=r)}return i},o.prototype.distinct=function(t){var e,i=this._data,o=[],s=this._options.type&&this._options.type[t]||null,r=0;for(var a in i)if(i.hasOwnProperty(a)){var h=i[a],d=h[t],l=!1;for(e=0;r>e;e++)if(o[e]==d){l=!0;break}l||void 0===d||(o[r]=d,r++)}if(s)for(e=0;ei;i++)n=e[i],this._ids[n]=!0;this.length=e.length,this._trigger("add",{items:e}),this._data.on&&this._data.on("*",this.listener)}},o.prototype.refresh=function(){for(var t,e=this._data.getIds({filter:this._options&&this._options.filter}),i={},o=[],n=[],s=0;so;o++)s=a[o],r=this.get(s),r&&(this._ids[s]=!0,l.push(s));break;case"update":for(o=0,n=a.length;n>o;o++)s=a[o],r=this.get(s),r?this._ids[s]?(u.push(s),d.push(e.data[o])):(this._ids[s]=!0,l.push(s)):this._ids[s]&&(delete this._ids[s],c.push(s));break;case"remove":for(o=0,n=a.length;n>o;o++)s=a[o],this._ids[s]&&(delete this._ids[s],c.push(s))}this.length+=l.length-c.length,l.length&&this._trigger("add",{items:l},i),u.length&&this._trigger("update",{items:u,data:d},i),c.length&&this._trigger("remove",{items:c},i)}},o.prototype.on=s.prototype.on,o.prototype.off=s.prototype.off,o.prototype._trigger=s.prototype._trigger,o.prototype.subscribe=o.prototype.on,o.prototype.unsubscribe=o.prototype.off,t.exports=o},function(t,e,i){function o(t){this.delay=null,this.max=1/0,this._queue=[],this._timeout=null,this._extended=null,this.setOptions(t)}o.prototype.setOptions=function(t){t&&"undefined"!=typeof t.delay&&(this.delay=t.delay),t&&"undefined"!=typeof t.max&&(this.max=t.max),this._flushIfNeeded()},o.extend=function(t,e){var i=new o(e);if(void 0!==t.flush)throw new Error("Target object already has a property flush");t.flush=function(){i.flush()};var n=[{name:"flush",original:void 0}];if(e&&e.replace)for(var s=0;sthis.max&&this.flush(),clearTimeout(this._timeout),this.queue.length>0&&"number"==typeof this.delay){var t=this;this._timeout=setTimeout(function(){t.flush()},this.delay)}},o.prototype.flush=function(){for(;this._queue.length>0;){var t=this._queue.shift();t.fn.apply(t.context||t.fn,t.args||[])}},t.exports=o},function(t,e,i){function o(t,e,i){if(!(this instanceof o))throw new SyntaxError("Constructor must be called with the new operator");this.containerElement=t,this.width="400px",this.height="400px",this.margin=10,this.defaultXCenter="55%",this.defaultYCenter="50%",this.xLabel="x",this.yLabel="y",this.zLabel="z";var n=function(t){return t};this.xValueLabel=n,this.yValueLabel=n,this.zValueLabel=n,this.filterLabel="time",this.legendLabel="value",this.style=o.STYLE.DOT,this.showPerspective=!0,this.showGrid=!0,this.keepAspectRatio=!0,this.showShadow=!1,this.showGrayBottom=!1,this.showTooltip=!1,this.verticalRatio=.5,this.animationInterval=1e3,this.animationPreload=!1,this.camera=new c,this.eye=new l(0,0,-1),this.dataTable=null,this.dataPoints=null,this.colX=void 0,this.colY=void 0,this.colZ=void 0,this.colValue=void 0,this.colFilter=void 0,this.xMin=0,this.xStep=void 0,this.xMax=1,this.yMin=0,this.yStep=void 0,this.yMax=1,this.zMin=0,this.zStep=void 0,this.zMax=1,this.valueMin=0,this.valueMax=1,this.xBarWidth=1,this.yBarWidth=1,this.colorAxis="#4D4D4D",this.colorGrid="#D3D3D3",this.colorDot="#7DC1FF",this.colorDotBorder="#3267D2",this.create(),this.setOptions(i),e&&this.setData(e)}function n(t){return"clientX"in t?t.clientX:t.targetTouches[0]&&t.targetTouches[0].clientX||0}function s(t){return"clientY"in t?t.clientY:t.targetTouches[0]&&t.targetTouches[0].clientY||0}var r=i(69),a=i(3),h=i(4),d=i(57),l=i(10),u=i(9),c=i(7),p=i(8),f=i(11),m=i(12);r(o.prototype),o.prototype._setScale=function(){this.scale=new l(1/(this.xMax-this.xMin),1/(this.yMax-this.yMin),1/(this.zMax-this.zMin)),this.keepAspectRatio&&(this.scale.x3&&(this.colFilter=3);else{if(this.style!==o.STYLE.DOTCOLOR&&this.style!==o.STYLE.DOTSIZE&&this.style!==o.STYLE.BARCOLOR&&this.style!==o.STYLE.BARSIZE)throw'Unknown style "'+this.style+'"';this.colX=0,this.colY=1,this.colZ=2,this.colValue=3,t.getNumberOfColumns()>4&&(this.colFilter=4)}},o.prototype.getNumberOfRows=function(t){return t.length},o.prototype.getNumberOfColumns=function(t){var e=0;for(var i in t[0])t[0].hasOwnProperty(i)&&e++;return e},o.prototype.getDistinctValues=function(t,e){for(var i=[],o=0;ot[o][e]&&(i.min=t[o][e]),i.maxt;t++){var f=(t-c)/(p-c),v=240*f,g=this._hsv2rgb(v,1,1);u.strokeStyle=g,u.beginPath(),u.moveTo(h,r+t),u.lineTo(a,r+t),u.stroke()}u.strokeStyle=this.colorAxis,u.strokeRect(h,r,i,s)}if(this.style===o.STYLE.DOTSIZE&&(u.strokeStyle=this.colorAxis,u.fillStyle=this.colorDot,u.beginPath(),u.moveTo(h,r),u.lineTo(a,r),u.lineTo(a-i+e,d),u.lineTo(h,d),u.closePath(),u.fill(),u.stroke()),this.style===o.STYLE.DOTCOLOR||this.style===o.STYLE.DOTSIZE){var y=5,b=new m(this.valueMin,this.valueMax,(this.valueMax-this.valueMin)/5,!0);for(b.start(),b.getCurrent()0?this.yMin:this.yMax,n=this._convert3Dto2D(new l(_,r,this.zMin)),Math.cos(2*w)>0?(v.textAlign="center",v.textBaseline="top",n.y+=b):Math.sin(2*w)<0?(v.textAlign="right",v.textBaseline="middle"):(v.textAlign="left",v.textBaseline="middle"),v.fillStyle=this.colorAxis,v.fillText(" "+this.xValueLabel(i.getCurrent())+" ",n.x,n.y),i.next()}for(v.lineWidth=1,o=void 0===this.defaultYStep,i=new m(this.yMin,this.yMax,this.yStep,o),i.start(),i.getCurrent()0?this.xMin:this.xMax,n=this._convert3Dto2D(new l(s,i.getCurrent(),this.zMin)),Math.cos(2*w)<0?(v.textAlign="center",v.textBaseline="top",n.y+=b):Math.sin(2*w)>0?(v.textAlign="right",v.textBaseline="middle"):(v.textAlign="left",v.textBaseline="middle"),v.fillStyle=this.colorAxis,v.fillText(" "+this.yValueLabel(i.getCurrent())+" ",n.x,n.y),i.next();for(v.lineWidth=1,o=void 0===this.defaultZStep,i=new m(this.zMin,this.zMax,this.zStep,o),i.start(),i.getCurrent()0?this.xMin:this.xMax,r=Math.sin(w)<0?this.yMin:this.yMax;!i.end();)t=this._convert3Dto2D(new l(s,r,i.getCurrent())),v.strokeStyle=this.colorAxis,v.beginPath(),v.moveTo(t.x,t.y),v.lineTo(t.x-b,t.y),v.stroke(),v.textAlign="right",v.textBaseline="middle",v.fillStyle=this.colorAxis,v.fillText(this.zValueLabel(i.getCurrent())+" ",t.x-5,t.y),i.next();v.lineWidth=1,t=this._convert3Dto2D(new l(s,r,this.zMin)),e=this._convert3Dto2D(new l(s,r,this.zMax)),v.strokeStyle=this.colorAxis,v.beginPath(),v.moveTo(t.x,t.y),v.lineTo(e.x,e.y),v.stroke(),v.lineWidth=1,c=this._convert3Dto2D(new l(this.xMin,this.yMin,this.zMin)),p=this._convert3Dto2D(new l(this.xMax,this.yMin,this.zMin)),v.strokeStyle=this.colorAxis,v.beginPath(),v.moveTo(c.x,c.y),v.lineTo(p.x,p.y),v.stroke(),c=this._convert3Dto2D(new l(this.xMin,this.yMax,this.zMin)),p=this._convert3Dto2D(new l(this.xMax,this.yMax,this.zMin)),v.strokeStyle=this.colorAxis,v.beginPath(),v.moveTo(c.x,c.y),v.lineTo(p.x,p.y),v.stroke(),v.lineWidth=1,t=this._convert3Dto2D(new l(this.xMin,this.yMin,this.zMin)),e=this._convert3Dto2D(new l(this.xMin,this.yMax,this.zMin)),v.strokeStyle=this.colorAxis,v.beginPath(),v.moveTo(t.x,t.y),v.lineTo(e.x,e.y),v.stroke(),t=this._convert3Dto2D(new l(this.xMax,this.yMin,this.zMin)),e=this._convert3Dto2D(new l(this.xMax,this.yMax,this.zMin)),v.strokeStyle=this.colorAxis,v.beginPath(),v.moveTo(t.x,t.y),v.lineTo(e.x,e.y),v.stroke();var x=this.xLabel;x.length>0&&(u=.1/this.scale.y,s=(this.xMin+this.xMax)/2,r=Math.cos(w)>0?this.yMin-u:this.yMax+u,n=this._convert3Dto2D(new l(s,r,this.zMin)),Math.cos(2*w)>0?(v.textAlign="center",v.textBaseline="top"):Math.sin(2*w)<0?(v.textAlign="right",v.textBaseline="middle"):(v.textAlign="left",v.textBaseline="middle"),v.fillStyle=this.colorAxis,v.fillText(x,n.x,n.y));var k=this.yLabel;k.length>0&&(d=.1/this.scale.x,s=Math.sin(w)>0?this.xMin-d:this.xMax+d,r=(this.yMin+this.yMax)/2,n=this._convert3Dto2D(new l(s,r,this.zMin)),Math.cos(2*w)<0?(v.textAlign="center",v.textBaseline="top"):Math.sin(2*w)>0?(v.textAlign="right",v.textBaseline="middle"):(v.textAlign="left",v.textBaseline="middle"),v.fillStyle=this.colorAxis,v.fillText(k,n.x,n.y));var M=this.zLabel;M.length>0&&(h=30,s=Math.cos(w)>0?this.xMin:this.xMax,r=Math.sin(w)<0?this.yMin:this.yMax,a=(this.zMin+this.zMax)/2,n=this._convert3Dto2D(new l(s,r,a)),v.textAlign="right",v.textBaseline="middle",v.fillStyle=this.colorAxis,v.fillText(M,n.x-h,n.y))},o.prototype._hsv2rgb=function(t,e,i){var o,n,s,r,a,h;switch(r=i*e,a=Math.floor(t/60),h=r*(1-Math.abs(t/60%2-1)),a){case 0:o=r,n=h,s=0;break;case 1:o=h,n=r,s=0;break;case 2:o=0,n=r,s=h;break;case 3:o=0,n=h,s=r;break;case 4:o=h,n=0,s=r;break;case 5:o=r,n=0,s=h;break;default:o=0,n=0,s=0}return"RGB("+parseInt(255*o)+","+parseInt(255*n)+","+parseInt(255*s)+")"},o.prototype._redrawDataGrid=function(){var t,e,i,n,s,r,a,h,d,u,c,p,f,m=this.frame.canvas,v=m.getContext("2d");if(!(void 0===this.dataPoints||this.dataPoints.length<=0)){for(s=0;s0}else r=!0;r?(f=(t.point.z+e.point.z+i.point.z+n.point.z)/4,u=240*(1-(f-this.zMin)*this.scale.z/this.verticalRatio),c=1,this.showShadow?(p=Math.min(1+k.x/M/2,1),a=this._hsv2rgb(u,c,p),h=a):(p=1,a=this._hsv2rgb(u,c,p),h=this.colorAxis)):(a="gray",h=this.colorAxis),d=.5,v.lineWidth=d,v.fillStyle=a,v.strokeStyle=h,v.beginPath(),v.moveTo(t.screen.x,t.screen.y),v.lineTo(e.screen.x,e.screen.y),v.lineTo(n.screen.x,n.screen.y),v.lineTo(i.screen.x,i.screen.y),v.closePath(),v.fill(),v.stroke()}}else for(s=0;sc&&(c=0);var p,f,m;this.style===o.STYLE.DOTCOLOR?(p=240*(1-(d.point.value-this.valueMin)*this.scale.value),f=this._hsv2rgb(p,1,1),m=this._hsv2rgb(p,1,.8)):this.style===o.STYLE.DOTSIZE?(f=this.colorDot,m=this.colorDotBorder):(p=240*(1-(d.point.z-this.zMin)*this.scale.z/this.verticalRatio),f=this._hsv2rgb(p,1,1),m=this._hsv2rgb(p,1,.8)),i.lineWidth=1,i.strokeStyle=m,i.fillStyle=f,i.beginPath(),i.arc(d.screen.x,d.screen.y,c,0,2*Math.PI,!0),i.fill(),i.stroke()}}},o.prototype._redrawDataBar=function(){var t,e,i,n,s=this.frame.canvas,r=s.getContext("2d");if(!(void 0===this.dataPoints||this.dataPoints.length<=0)){for(t=0;t0&&(t=this.dataPoints[0],o.lineWidth=1,o.strokeStyle="blue",o.beginPath(),o.moveTo(t.screen.x,t.screen.y)),e=1;e0&&o.stroke()}},o.prototype._onMouseDown=function(t){if(t=t||window.event,this.leftButtonDown&&this._onMouseUp(t),this.leftButtonDown=t.which?1===t.which:1===t.button,this.leftButtonDown||this.touchDown){this.startMouseX=n(t),this.startMouseY=s(t),this.startStart=new Date(this.start),this.startEnd=new Date(this.end),this.startArmRotation=this.camera.getArmRotation(),this.frame.style.cursor="move";var e=this;this.onmousemove=function(t){e._onMouseMove(t)},this.onmouseup=function(t){e._onMouseUp(t)},d.addEventListener(document,"mousemove",e.onmousemove),d.addEventListener(document,"mouseup",e.onmouseup),d.preventDefault(t)}},o.prototype._onMouseMove=function(t){t=t||window.event;var e=parseFloat(n(t))-this.startMouseX,i=parseFloat(s(t))-this.startMouseY,o=this.startArmRotation.horizontal+e/200,r=this.startArmRotation.vertical+i/200,a=4,h=Math.sin(a/360*2*Math.PI);Math.abs(Math.sin(o))0?1:0>t?-1:0}var o=e[0],n=e[1],s=e[2],r=i((n.x-o.x)*(t.y-o.y)-(n.y-o.y)*(t.x-o.x)),a=i((s.x-n.x)*(t.y-n.y)-(s.y-n.y)*(t.x-n.x)),h=i((o.x-s.x)*(t.y-s.y)-(o.y-s.y)*(t.x-s.x));return!(0!=r&&0!=a&&r!=a||0!=a&&0!=h&&a!=h||0!=r&&0!=h&&r!=h)},o.prototype._dataPointFromXY=function(t,e){var i,n=100,s=null,r=null,a=null,h=new u(t,e);if(this.style===o.STYLE.BAR||this.style===o.STYLE.BARCOLOR||this.style===o.STYLE.BARSIZE)for(i=this.dataPoints.length-1;i>=0;i--){s=this.dataPoints[i];var d=s.surfaces;if(d)for(var l=d.length-1;l>=0;l--){var c=d[l],p=c.corners,f=[p[0].screen,p[1].screen,p[2].screen],m=[p[2].screen,p[3].screen,p[0].screen];if(this._insideTriangle(h,f)||this._insideTriangle(h,m))return s}}else for(i=0;ib)&&n>b&&(a=b,r=s)}}return r},o.prototype._showTooltip=function(t){var e,i,o;this.tooltip?(e=this.tooltip.dom.content,i=this.tooltip.dom.line,o=this.tooltip.dom.dot):(e=document.createElement("div"),e.style.position="absolute",e.style.padding="10px",e.style.border="1px solid #4d4d4d",e.style.color="#1a1a1a",e.style.background="rgba(255,255,255,0.7)",e.style.borderRadius="2px",e.style.boxShadow="5px 5px 10px rgba(128,128,128,0.5)",i=document.createElement("div"),i.style.position="absolute",i.style.height="40px",i.style.width="0",i.style.borderLeft="1px solid #4d4d4d",o=document.createElement("div"),o.style.position="absolute",o.style.height="0",o.style.width="0",o.style.border="5px solid #4d4d4d",o.style.borderRadius="5px",this.tooltip={dataPoint:null,dom:{content:e,line:i,dot:o}}),this._hideTooltip(),this.tooltip.dataPoint=t,"function"==typeof this.showTooltip?e.innerHTML=this.showTooltip(t.point):e.innerHTML="
x:"+t.point.x+"
y:"+t.point.y+"
z:"+t.point.z+"
",e.style.left="0",e.style.top="0",this.frame.appendChild(e),this.frame.appendChild(i),this.frame.appendChild(o);var n=e.offsetWidth,s=e.offsetHeight,r=i.offsetHeight,a=o.offsetWidth,h=o.offsetHeight,d=t.screen.x-n/2;d=Math.min(Math.max(d,10),this.frame.clientWidth-10-n),i.style.left=t.screen.x+"px",i.style.top=t.screen.y-r+"px",e.style.left=d+"px",e.style.top=t.screen.y-r-s+"px",o.style.left=t.screen.x-a/2+"px",o.style.top=t.screen.y-h/2+"px"},o.prototype._hideTooltip=function(){if(this.tooltip){this.tooltip.dataPoint=null;for(var t in this.tooltip.dom)if(this.tooltip.dom.hasOwnProperty(t)){var e=this.tooltip.dom[t];e&&e.parentNode&&e.parentNode.removeChild(e)}}},t.exports=o},function(t,e,i){function o(){this.armLocation=new n,this.armRotation={},this.armRotation.horizontal=0,this.armRotation.vertical=0,this.armLength=1.7,this.cameraLocation=new n,this.cameraRotation=new n(.5*Math.PI,0,0),this.calculateCameraOrientation()}var n=i(10);o.prototype.setArmLocation=function(t,e,i){this.armLocation.x=t,this.armLocation.y=e,this.armLocation.z=i,this.calculateCameraOrientation()},o.prototype.setArmRotation=function(t,e){void 0!==t&&(this.armRotation.horizontal=t),void 0!==e&&(this.armRotation.vertical=e,this.armRotation.vertical<0&&(this.armRotation.vertical=0),this.armRotation.vertical>.5*Math.PI&&(this.armRotation.vertical=.5*Math.PI)),(void 0!==t||void 0!==e)&&this.calculateCameraOrientation()},o.prototype.getArmRotation=function(){var t={};return t.horizontal=this.armRotation.horizontal,t.vertical=this.armRotation.vertical,t},o.prototype.setArmLength=function(t){void 0!==t&&(this.armLength=t,this.armLength<.71&&(this.armLength=.71),this.armLength>5&&(this.armLength=5),this.calculateCameraOrientation())},o.prototype.getArmLength=function(){return this.armLength},o.prototype.getCameraLocation=function(){return this.cameraLocation},o.prototype.getCameraRotation=function(){return this.cameraRotation},o.prototype.calculateCameraOrientation=function(){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),this.cameraRotation.x=Math.PI/2-this.armRotation.vertical,this.cameraRotation.y=0,this.cameraRotation.z=-this.armRotation.horizontal},t.exports=o},function(t,e,i){function o(t,e,i){this.data=t,this.column=e,this.graph=i,this.index=void 0,this.value=void 0,this.values=i.getDistinctValues(t.get(),this.column),this.values.sort(function(t,e){return t>e?1:e>t?-1:0}),this.values.length>0&&this.selectValue(0),this.dataPoints=[],this.loaded=!1,this.onLoadCallback=void 0,i.animationPreload?(this.loaded=!1,this.loadInBackground()):this.loaded=!0}var n=i(4);o.prototype.isLoaded=function(){return this.loaded},o.prototype.getLoadedProgress=function(){for(var t=this.values.length,e=0;this.dataPoints[e];)e++;return Math.round(e/t*100)},o.prototype.getLabel=function(){return this.graph.filterLabel},o.prototype.getColumn=function(){return this.column},o.prototype.getSelectedValue=function(){return void 0===this.index?void 0:this.values[this.index]},o.prototype.getValues=function(){return this.values},o.prototype.getValue=function(t){if(t>=this.values.length)throw"Error: index out of range";return this.values[t]},o.prototype._getDataPoints=function(t){if(void 0===t&&(t=this.index),void 0===t)return[];var e;if(this.dataPoints[t])e=this.dataPoints[t];else{var i={};i.column=this.column,i.value=this.values[t];var o=new n(this.data,{filter:function(t){return t[i.column]==i.value}}).get();e=this.graph._getDataPoints(o),this.dataPoints[t]=e}return e},o.prototype.setOnLoadCallback=function(t){this.onLoadCallback=t},o.prototype.selectValue=function(t){if(t>=this.values.length)throw"Error: index out of range";this.index=t,this.value=this.values[t]},o.prototype.loadInBackground=function(t){void 0===t&&(t=0);var e=this.graph.frame;if(t0&&(t--,this.setIndex(t))},o.prototype.next=function(){var t=this.getIndex();t0?this.setIndex(0):this.index=void 0},o.prototype.setIndex=function(t){if(!(to&&(o=0),o>this.values.length-1&&(o=this.values.length-1),o},o.prototype.indexToLeft=function(t){var e=parseFloat(this.frame.bar.style.width)-this.frame.slide.clientWidth-10,i=t/(this.values.length-1)*e,o=i+3;return o},o.prototype._onMouseMove=function(t){var e=t.clientX-this.startClientX,i=this.startSlideX+e,o=this.leftToIndex(i);this.setIndex(o),n.preventDefault()},o.prototype._onMouseUp=function(t){this.frame.style.cursor="auto",n.removeEventListener(document,"mousemove",this.onmousemove),n.removeEventListener(document,"mouseup",this.onmouseup),n.preventDefault()},t.exports=o},function(t,e,i){function o(t,e,i,o){this._start=0,this._end=0,this._step=1,this.prettyStep=!0,this.precision=5,this._current=0,this.setRange(t,e,i,o)}o.prototype.setRange=function(t,e,i,o){this._start=t?t:0,this._end=e?e:0,this.setStep(i,o)},o.prototype.setStep=function(t,e){void 0===t||0>=t||(void 0!==e&&(this.prettyStep=e),this.prettyStep===!0?this._step=o.calculatePrettyStep(t):this._step=t)},o.calculatePrettyStep=function(t){var e=function(t){return Math.log(t)/Math.LN10},i=Math.pow(10,Math.round(e(t))),o=2*Math.pow(10,Math.round(e(t/2))),n=5*Math.pow(10,Math.round(e(t/5))),s=i;return Math.abs(o-t)<=Math.abs(s-t)&&(s=o),Math.abs(n-t)<=Math.abs(s-t)&&(s=n),0>=s&&(s=1),s},o.prototype.getCurrent=function(){return parseFloat(this._current.toPrecision(this.precision))},o.prototype.getStep=function(){return this._step},o.prototype.start=function(){this._current=this._start-this._start%this._step},o.prototype.next=function(){this._current+=this._step},o.prototype.end=function(){return this._current>this._end},t.exports=o},function(t,e,i){function o(t,e,i,h){if(!(this instanceof o))throw new SyntaxError("Constructor must be called with the new operator");if(!(Array.isArray(i)||i instanceof s||i instanceof r)&&i instanceof Object){var u=h;h=i,i=u}var f=this;this.defaultOptions={start:null,end:null,autoResize:!0,orientation:{axis:"bottom",item:"bottom"},width:null,height:null,maxHeight:null,minHeight:null},this.options=n.deepExtend({},this.defaultOptions),this._create(t),this.components=[],this.body={dom:this.dom,domProps:this.props,emitter:{on:this.on.bind(this),off:this.off.bind(this),emit:this.emit.bind(this)},hiddenDates:[],util:{getScale:function(){return f.timeAxis.step.scale},getStep:function(){return f.timeAxis.step.step},toScreen:f._toScreen.bind(f),toGlobalScreen:f._toGlobalScreen.bind(f),toTime:f._toTime.bind(f),toGlobalTime:f._toGlobalTime.bind(f)}},this.range=new a(this.body),this.components.push(this.range),this.body.range=this.range,this.timeAxis=new d(this.body),this.timeAxis2=null,this.components.push(this.timeAxis),this.currentTime=new l(this.body),this.components.push(this.currentTime),this.itemSet=new c(this.body),this.components.push(this.itemSet),this.itemsData=null,this.groupsData=null,this.on("tap",function(t){f.emit("click",f.getEventProperties(t))}),this.on("doubletap",function(t){f.emit("doubleClick",f.getEventProperties(t))}),this.dom.root.oncontextmenu=function(t){f.emit("contextmenu",f.getEventProperties(t))},this.configurator=new p(this,t,g),h&&this.setOptions(h),i&&this.setGroups(i),e?this.setItems(e):this._redraw()}var n=(i(69),i(41),i(57)),s=i(3),r=i(4),a=i(17),h=i(43),d=i(35),l=i(26),u=i(27),c=i(32),p=i(44),f=i(45)["default"],m=i(45).printStyle,v=i(46).allOptions,g=i(46).configureOptions;o.prototype=new h,o.prototype.redraw=function(){this.itemSet&&this.itemSet.markDirty({refreshItems:!0}),this._redraw()},o.prototype.setOptions=function(t){var e=f.validate(t,v);if(e===!0&&console.log("%cErrors have been found in the supplied options object.",m),h.prototype.setOptions.call(this,t),"type"in t&&t.type!==this.options.type){this.options.type=t.type;var i=this.itemsData;if(i){var o=this.getSelection();this.setItems(null),this.setItems(i),this.setSelection(o)}}},o.prototype.setItems=function(t){var e,i=null==this.itemsData;if(e=t?t instanceof s||t instanceof r?t:new s(t,{type:{start:"Date",end:"Date"}}):null,this.itemsData=e,this.itemSet&&this.itemSet.setItems(e),i)if(void 0!=this.options.start||void 0!=this.options.end){if(void 0==this.options.start||void 0==this.options.end)var o=this._getDataRange();var n=void 0!=this.options.start?this.options.start:o.start,a=void 0!=this.options.end?this.options.end:o.end;this.setWindow(n,a,{animation:!1})}else this.fit({animation:!1})},o.prototype.setGroups=function(t){var e;e=t?t instanceof s||t instanceof r?t:new s(t):null,this.groupsData=e,this.itemSet.setGroups(e)},o.prototype.setData=function(t){t&&t.groups&&this.setGroups(t.groups),t&&t.items&&this.setItems(t.items)},o.prototype.setSelection=function(t,e){this.itemSet&&this.itemSet.setSelection(t),e&&e.focus&&this.focus(t,e)},o.prototype.getSelection=function(){return this.itemSet&&this.itemSet.getSelection()||[]},o.prototype.focus=function(t,e){if(this.itemsData&&void 0!=t){var i=Array.isArray(t)?t:[t],o=this.itemsData.getDataSet().get(i,{type:{start:"Date",end:"Date"}}),n=null,s=null;if(o.forEach(function(t){var e=t.start.valueOf(),i="end"in t?t.end.valueOf():t.start.valueOf();(null===n||n>e)&&(n=e),(null===s||i>s)&&(s=i)}),null!==n&&null!==s){var r=(n+s)/2,a=Math.max(this.range.end-this.range.start,1.1*(s-n)),h=e&&void 0!==e.animation?e.animation:!0;this.range.setRange(r-a/2,r+a/2,h)}}},o.prototype.getItemRange=function(){var t=this.itemsData&&this.itemsData.getDataSet(),e=null,i=null;if(t){var o=t.min("start");e=o?n.convert(o.start,"Date").valueOf():null;var s=t.max("start");s&&(i=n.convert(s.start,"Date").valueOf());var r=t.max("end");r&&(i=null==i?n.convert(r.end,"Date").valueOf():Math.max(i,n.convert(r.end,"Date").valueOf()))}return{min:null!=e?new Date(e):null,max:null!=i?new Date(i):null}},o.prototype.getEventProperties=function(t){var e=t.center?t.center.x:t.clientX,i=t.center?t.center.y:t.clientY,o=e-n.getAbsoluteLeft(this.dom.centerContainer),s=i-n.getAbsoluteTop(this.dom.centerContainer),r=this.itemSet.itemFromTarget(t),a=this.itemSet.groupFromTarget(t),h=u.customTimeFromTarget(t),d=this.itemSet.options.snap||null,l=this.body.util.getScale(),c=this.body.util.getStep(),p=this._toTime(o),f=d?d(p,l,c):p,m=n.getTarget(t),v=null;return null!=r?v="item":null!=h?v="custom-time":n.hasParent(m,this.timeAxis.dom.foreground)?v="axis":this.timeAxis2&&n.hasParent(m,this.timeAxis2.dom.foreground)?v="axis":n.hasParent(m,this.itemSet.dom.labelSet)?v="group-label":n.hasParent(m,this.currentTime.bar)?v="current-time":n.hasParent(m,this.dom.center)&&(v="background"),{event:t,item:r?r.id:null,group:a?a.groupId:null,what:v,pageX:t.srcEvent?t.srcEvent.pageX:t.pageX,pageY:t.srcEvent?t.srcEvent.pageY:t.pageY,x:o,y:s,time:p,snappedTime:f}},t.exports=o},function(t,e,i){function o(t,e,i,o){if(!(Array.isArray(i)||i instanceof s)&&i instanceof Object){var r=o;o=i,i=r}var h=this;this.defaultOptions={start:null,end:null,autoResize:!0,orientation:{axis:"bottom",item:"bottom"},width:null,height:null,maxHeight:null,minHeight:null},this.options=n.deepExtend({},this.defaultOptions),this._create(t),this.components=[],this.body={dom:this.dom,domProps:this.props,emitter:{on:this.on.bind(this),off:this.off.bind(this),emit:this.emit.bind(this)},hiddenDates:[],util:{toScreen:h._toScreen.bind(h),toGlobalScreen:h._toGlobalScreen.bind(h),toTime:h._toTime.bind(h),toGlobalTime:h._toGlobalTime.bind(h)}},this.range=new a(this.body),this.components.push(this.range),this.body.range=this.range,this.timeAxis=new d(this.body),this.components.push(this.timeAxis),this.currentTime=new l(this.body),this.components.push(this.currentTime),this.linegraph=new c(this.body),this.components.push(this.linegraph),this.itemsData=null,this.groupsData=null,this.on("tap",function(t){h.emit("click",h.getEventProperties(t))}),this.on("doubletap",function(t){h.emit("doubleClick",h.getEventProperties(t))}),this.dom.root.oncontextmenu=function(t){h.emit("contextmenu",h.getEventProperties(t))},this.configurator=new p(this,t,g),o&&this.setOptions(o),i&&this.setGroups(i),e?this.setItems(e):this._redraw()}var n=(i(69),i(41),i(57)),s=i(3),r=i(4),a=i(17),h=i(43),d=i(35),l=i(26),u=i(27),c=i(34),p=i(44),f=i(45)["default"],m=i(45).printStyle,v=i(47).allOptions,g=i(47).configureOptions;o.prototype=new h,o.prototype.setOptions=function(t){var e=f.validate(t,v);e===!0&&console.log("%cErrors have been found in the supplied options object.",m),h.prototype.setOptions.call(this,t)},o.prototype.setItems=function(t){var e,i=null==this.itemsData;if(e=t?t instanceof s||t instanceof r?t:new s(t,{type:{start:"Date",end:"Date"}}):null,this.itemsData=e,this.linegraph&&this.linegraph.setItems(e),i)if(void 0!=this.options.start||void 0!=this.options.end){var o=void 0!=this.options.start?this.options.start:null,n=void 0!=this.options.end?this.options.end:null;this.setWindow(o,n,{animation:!1})}else this.fit({animation:!1})},o.prototype.setGroups=function(t){var e;e=t?t instanceof s||t instanceof r?t:new s(t):null,this.groupsData=e,this.linegraph.setGroups(e)},o.prototype.getLegend=function(t,e,i){return void 0===e&&(e=15),void 0===i&&(i=15),void 0!==this.linegraph.groups[t]?this.linegraph.groups[t].getLegend(e,i):"cannot find group:"+t},o.prototype.isGroupVisible=function(t){return void 0!==this.linegraph.groups[t]?this.linegraph.groups[t].visible&&(void 0===this.linegraph.options.groups.visibility[t]||1==this.linegraph.options.groups.visibility[t]):!1},o.prototype.getItemRange=function(){var t=null,e=null;for(var i in this.linegraph.groups)if(this.linegraph.groups.hasOwnProperty(i)&&1==this.linegraph.groups[i].visible)for(var o=0;or?r:t,e=null==e?r:r>e?r:e}return{min:null!=t?new Date(t):null,max:null!=e?new Date(e):null}},o.prototype.getEventProperties=function(t){var e=t.center?t.center.x:t.clientX,i=t.center?t.center.y:t.clientY,o=e-n.getAbsoluteLeft(this.dom.centerContainer),s=i-n.getAbsoluteTop(this.dom.centerContainer),r=this._toTime(o),a=u.customTimeFromTarget(t),h=n.getTarget(t),d=null;n.hasParent(h,this.timeAxis.dom.foreground)?d="axis":this.timeAxis2&&n.hasParent(h,this.timeAxis2.dom.foreground)?d="axis":n.hasParent(h,this.linegraph.yAxisLeft.dom.frame)?d="data-axis":n.hasParent(h,this.linegraph.yAxisRight.dom.frame)?d="data-axis":n.hasParent(h,this.linegraph.legendLeft.dom.frame)?d="legend":n.hasParent(h,this.linegraph.legendRight.dom.frame)?d="legend":null!=a?d="custom-time":n.hasParent(h,this.currentTime.bar)?d="current-time":n.hasParent(h,this.dom.center)&&(d="background");var l=[],c=this.linegraph.yAxisLeft,p=this.linegraph.yAxisRight;return c.hidden||l.push(c.screenToValue(s)),p.hidden||l.push(p.screenToValue(s)),{event:t,what:d,pageX:t.srcEvent?t.srcEvent.pageX:t.pageX,pageY:t.srcEvent?t.srcEvent.pageY:t.pageY,x:o,y:s,time:r,value:l}},t.exports=o},function(t,e,i){var o=i(40);e.convertHiddenOptions=function(t,e){if(t.hiddenDates=[],e&&1==Array.isArray(e)){for(var i=0;i=4*a){var c=0,p=s.clone();switch(i[h].repeat){case"daily":d.day()!=l.day()&&(c=1),d.dayOfYear(n.dayOfYear()),d.year(n.year()),d.subtract(7,"days"),l.dayOfYear(n.dayOfYear()),l.year(n.year()),l.subtract(7-c,"days"),p.add(1,"weeks");break;case"weekly":var f=l.diff(d,"days"),m=d.day();d.date(n.date()),d.month(n.month()),d.year(n.year()),l=d.clone(),d.day(m),l.day(m),l.add(f,"days"),d.subtract(1,"weeks"),l.subtract(1,"weeks"),p.add(1,"weeks");break;case"monthly":d.month()!=l.month()&&(c=1),d.month(n.month()),d.year(n.year()),d.subtract(1,"months"),l.month(n.month()),l.year(n.year()),l.subtract(1,"months"),l.add(c,"months"),p.add(1,"months");break;case"yearly":d.year()!=l.year()&&(c=1),d.year(n.year()),d.subtract(1,"years"),l.year(n.year()),l.subtract(1,"years"),l.add(c,"years"),p.add(1,"years");break;default:return void console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:",i[h].repeat)}for(;p>d;)switch(t.hiddenDates.push({start:d.valueOf(),end:l.valueOf()}),i[h].repeat){case"daily":d.add(1,"days"),l.add(1,"days");break;case"weekly":d.add(1,"weeks"),l.add(1,"weeks");break;case"monthly":d.add(1,"months"),l.add(1,"months");break;case"yearly":d.add(1,"y"),l.add(1,"y");break;default:return void console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:",i[h].repeat)}t.hiddenDates.push({start:d.valueOf(),end:l.valueOf()})}}e.removeDuplicates(t);var v=e.isHidden(t.range.start,t.hiddenDates),g=e.isHidden(t.range.end,t.hiddenDates),y=t.range.start,b=t.range.end;1==v.hidden&&(y=1==t.range.startToFront?v.startDate-1:v.endDate+1),1==g.hidden&&(b=1==t.range.endToFront?g.startDate-1:g.endDate+1),(1==v.hidden||1==g.hidden)&&t.range._applyRange(y,b)}},e.removeDuplicates=function(t){for(var e=t.hiddenDates,i=[],o=0;o=e[o].start&&e[n].end<=e[o].end?e[n].remove=!0:e[n].start>=e[o].start&&e[n].start<=e[o].end?(e[o].end=e[n].end,e[n].remove=!0):e[n].end>=e[o].start&&e[n].end<=e[o].end&&(e[o].start=e[n].start,e[n].remove=!0));for(var o=0;o=r&&a>n){i=!0;break}}if(1==i&&n=e&&i>r&&(o+=r-s)}return o},e.correctTimeForHidden=function(t,i,n){return n=o(n).toDate().valueOf(),n-=e.getHiddenDurationBefore(t,i,n)},e.getHiddenDurationBefore=function(t,e,i){var n=0;i=o(i).toDate().valueOf();for(var s=0;s=e.start&&a=a&&(n+=a-r)}return n},e.getAccumulatedHiddenDuration=function(t,e,i){for(var o=0,n=0,s=e.start,r=0;r=e.start&&h=i)break;o+=h-a}}return o},e.snapAwayFromHidden=function(t,i,o,n){var s=e.isHidden(i,t);return 1==s.hidden?0>o?1==n?s.startDate-(s.endDate-i)-1:s.startDate-1:1==n?s.endDate+(i-s.startDate)+1:s.endDate+1:i},e.isHidden=function(t,e){for(var i=0;i=o&&n>t)return{hidden:!0,startDate:o,endDate:n}}return{hidden:!1,startDate:o,endDate:n}}},function(t,e,i){function o(t,e,i,o,n,s,r){this.current=0,this.autoScale=!0,this.stepIndex=0,this.step=1,this.scale=1,this.formattingFunction=s,this.marginStart,this.marginEnd,this.deadSpace=0,this.majorSteps=[1,2,5,10],this.minorSteps=[.25,.5,1,2],this.alignZeros=r,this.setRange(t,e,i,o,n)}o.prototype.setRange=function(t,e,i,o,n){this._start=void 0===n.min?t:n.min,this._end=void 0===n.max?e:n.max,this._start===this._end&&(this._start=void 0===n.min?this._start-.75:this._start,this._end=void 0===n.max?this._end+1:this._end),this.autoScale===!0&&this.setMinimumStep(i,o),this.setFirst(n)},o.prototype.setMinimumStep=function(t,e){var i=this._end-this._start,o=1.2*i,n=t*(o/e),s=Math.round(Math.log(o)/Math.LN10),r=-1,a=Math.pow(10,s),h=0;0>s&&(h=s);for(var d=!1,l=h;Math.abs(l)<=Math.abs(s);l++){a=Math.pow(10,l);for(var u=0;u=n){d=!0,r=u;break}}if(d===!0)break}this.stepIndex=r,this.scale=a,this.step=a*this.minorSteps[r]},o.prototype.setFirst=function(t){void 0===t&&(t={});var e=void 0===t.min?this._start-2*this.scale*this.minorSteps[this.stepIndex]:t.min,i=void 0===t.max?this._end+this.scale*this.minorSteps[this.stepIndex]:t.max;this.marginEnd=void 0===t.max?this.roundToMinor(i):t.max,this.marginStart=void 0===t.min?this.roundToMinor(e):t.min,this.alignZeros===!0&&(this.marginEnd-this.marginStart)%this.step!=0&&(this.marginEnd+=this.marginEnd%this.step),this.deadSpace=this.roundToMinor(i)-i+this.roundToMinor(e)-e,this.marginRange=this.marginEnd-this.marginStart,this.current=this.marginEnd},o.prototype.roundToMinor=function(t){var e=t-t%(this.scale*this.minorSteps[this.stepIndex]);return t%(this.scale*this.minorSteps[this.stepIndex])>.5*this.scale*this.minorSteps[this.stepIndex]?e+this.scale*this.minorSteps[this.stepIndex]:e},o.prototype.hasNext=function(){return this.current>=this.marginStart},o.prototype.next=function(){var t=this.current;this.current-=this.step,this.current===t&&(this.current=this._end)},o.prototype.previous=function(){this.current+=this.step,this.marginEnd+=this.step,this.marginRange=this.marginEnd-this.marginStart},o.prototype.getCurrent=function(){var t=Math.abs(this.current)t)for(var e=0;-t>e;e++)this.previous();else if(t>0)for(var e=0;t>e;e++)this.next()},t.exports=o},function(t,e,i){function o(t,e){var i=a().hours(0).minutes(0).seconds(0).milliseconds(0);this.start=i.clone().add(-3,"days").valueOf(),this.end=i.clone().add(4,"days").valueOf(),this.body=t,this.deltaDifference=0,this.scaleOffset=0,this.startToFront=!1,this.endToFront=!0,this.defaultOptions={start:null,end:null,direction:"horizontal",moveable:!0,zoomable:!0,min:null,max:null,zoomMin:10,zoomMax:31536e10},this.options=r.extend({},this.defaultOptions),this.props={touch:{}},this.animationTimer=null,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)),this.body.emitter.on("mousewheel",this._onMouseWheel.bind(this)),this.body.emitter.on("touch",this._onTouch.bind(this)),this.body.emitter.on("pinch",this._onPinch.bind(this)),this.setOptions(e)}function n(t){if("horizontal"!=t&&"vertical"!=t)throw new TypeError('Unknown direction "'+t+'". Choose "horizontal" or "vertical".')}function s(t,e){return{x:t.x-r.getAbsoluteLeft(e),y:t.y-r.getAbsoluteTop(e)}}var r=i(57),a=(i(48),i(40)),h=i(25),d=i(15);o.prototype=new h,o.prototype.setOptions=function(t){if(t){var e=["direction","min","max","zoomMin","zoomMax","moveable","zoomable","activate","hiddenDates"];r.selectiveExtend(e,this.options,t),("start"in t||"end"in t)&&this.setRange(t.start,t.end)}},o.prototype.setRange=function(t,e,i,o){o!==!0&&(o=!1);var n=void 0!=t?r.convert(t,"Date").valueOf():null,s=void 0!=e?r.convert(e,"Date").valueOf():null;if(this._cancelAnimation(),i){var a=this,h=this.start,l=this.end,u="object"==typeof i&&"duration"in i?i.duration:500,c="object"==typeof i&&"easingFunction"in i?i.easingFunction:"easeInOutQuad",p=r.easingFunctions[c];if(!p)throw new Error("Unknown easing function "+JSON.stringify(c)+". Choose from: "+Object.keys(r.easingFunctions).join(", "));var f=(new Date).valueOf(),m=!1,v=function b(){if(!a.props.touch.dragging){var t=(new Date).valueOf(),e=t-f,i=p(e/u),r=e>u,c=r||null===n?n:h+(n-h)*i,v=r||null===s?s:l+(s-l)*i;g=a._applyRange(c,v),d.updateHiddenDates(a.body,a.options.hiddenDates),m=m||g,g&&a.body.emitter.emit("rangechange",{start:new Date(a.start),end:new Date(a.end),byUser:o}),r?m&&a.body.emitter.emit("rangechanged",{start:new Date(a.start),end:new Date(a.end),byUser:o}):a.animationTimer=setTimeout(b,20)}};return v()}var g=this._applyRange(n,s);if(d.updateHiddenDates(this.body,this.options.hiddenDates),g){var y={start:new Date(this.start),end:new Date(this.end),byUser:o};this.body.emitter.emit("rangechange",y),this.body.emitter.emit("rangechanged",y)}},o.prototype._cancelAnimation=function(){this.animationTimer&&(clearTimeout(this.animationTimer),this.animationTimer=null)},o.prototype._applyRange=function(t,e){var i,o=null!=t?r.convert(t,"Date").valueOf():this.start,n=null!=e?r.convert(e,"Date").valueOf():this.end,s=null!=this.options.max?r.convert(this.options.max,"Date").valueOf():null,a=null!=this.options.min?r.convert(this.options.min,"Date").valueOf():null;if(isNaN(o)||null===o)throw new Error('Invalid start "'+t+'"');if(isNaN(n)||null===n)throw new Error('Invalid end "'+e+'"');if(o>n&&(n=o),null!==a&&a>o&&(i=a-o,o+=i,n+=i,null!=s&&n>s&&(n=s)),null!==s&&n>s&&(i=n-s,o-=i,n-=i,null!=a&&a>o&&(o=a)),null!==this.options.zoomMin){var h=parseFloat(this.options.zoomMin);0>h&&(h=0),h>n-o&&(this.end-this.start===h&&o>this.start&&nd&&(d=0),n-o>d&&(this.end-this.start===d&&othis.end?(o=this.start,n=this.end):(i=n-o-d,o+=i/2,n-=i/2))}var l=this.start!=o||this.end!=n;return o>=this.start&&o<=this.end||n>=this.start&&n<=this.end||this.start>=o&&this.start<=n||this.end>=o&&this.end<=n||this.body.emitter.emit("checkRangedItems"),this.start=o,this.end=n,l},o.prototype.getRange=function(){return{start:this.start,end:this.end}},o.prototype.conversion=function(t,e){return o.conversion(this.start,this.end,t,e)},o.conversion=function(t,e,i,o){return void 0===o&&(o=0),0!=i&&e-t!=0?{offset:t,scale:i/(e-t-o)}:{offset:0,scale:1}},o.prototype._onDragStart=function(t){this.deltaDifference=0,this.previousDelta=0,this.options.moveable&&this.props.touch.allowDragging&&(this.props.touch.start=this.start,this.props.touch.end=this.end,this.props.touch.dragging=!0,this.body.dom.root&&(this.body.dom.root.style.cursor="move"))},o.prototype._onDrag=function(t){if(this.options.moveable&&this.props.touch.allowDragging){var e=this.options.direction;n(e);var i="horizontal"==e?t.deltaX:t.deltaY;i-=this.deltaDifference;var o=this.props.touch.end-this.props.touch.start,s=d.getHiddenDurationBetween(this.body.hiddenDates,this.start,this.end);o-=s;var r="horizontal"==e?this.body.domProps.center.width:this.body.domProps.center.height,a=-i/r*o,h=this.props.touch.start+a,l=this.props.touch.end+a,u=d.snapAwayFromHidden(this.body.hiddenDates,h,this.previousDelta-i,!0),c=d.snapAwayFromHidden(this.body.hiddenDates,l,this.previousDelta-i,!0);if(u!=h||c!=l)return this.deltaDifference+=i,this.props.touch.start=u,this.props.touch.end=c,void this._onDrag(t);this.previousDelta=i,this._applyRange(h,l),this.body.emitter.emit("rangechange",{start:new Date(this.start),end:new Date(this.end),byUser:!0})}},o.prototype._onDragEnd=function(t){this.options.moveable&&this.props.touch.allowDragging&&(this.props.touch.dragging=!1,this.body.dom.root&&(this.body.dom.root.style.cursor="auto"),this.body.emitter.emit("rangechanged",{start:new Date(this.start),end:new Date(this.end),byUser:!0}))},o.prototype._onMouseWheel=function(t){if(this.options.zoomable&&this.options.moveable){var e=0;if(t.wheelDelta?e=t.wheelDelta/120:t.detail&&(e=-t.detail/3),e){var i;i=0>e?1-e/5:1/(1+e/5);var o=s({x:t.clientX,y:t.clientY},this.body.dom.center),n=this._pointerToDate(o);this.zoom(i,n,e)}t.preventDefault()}},o.prototype._onTouch=function(t){this.props.touch.start=this.start,this.props.touch.end=this.end,this.props.touch.allowDragging=!0,this.props.touch.center=null,this.scaleOffset=0,this.deltaDifference=0},o.prototype._onPinch=function(t){if(this.options.zoomable&&this.options.moveable){this.props.touch.allowDragging=!1,this.props.touch.center||(this.props.touch.center=s(t.center,this.body.dom.center));var e=1/(t.scale+this.scaleOffset),i=this._pointerToDate(this.props.touch.center),o=d.getHiddenDurationBetween(this.body.hiddenDates,this.start,this.end),n=d.getHiddenDurationBefore(this.body.hiddenDates,this,i),r=o-n,a=i-n+(this.props.touch.start-(i-n))*e,h=i+r+(this.props.touch.end-(i+r))*e;this.startToFront=0>=1-e,this.endToFront=0>=e-1;var l=d.snapAwayFromHidden(this.body.hiddenDates,a,1-e,!0),u=d.snapAwayFromHidden(this.body.hiddenDates,h,e-1,!0);(l!=a||u!=h)&&(this.props.touch.start=l,this.props.touch.end=u,this.scaleOffset=1-t.scale,a=l,h=u),this.setRange(a,h,!1,!0),this.startToFront=!1,this.endToFront=!0}},o.prototype._pointerToDate=function(t){var e,i=this.options.direction;if(n(i),"horizontal"==i)return this.body.util.toTime(t.x).valueOf();var o=this.body.domProps.center.height;return e=this.conversion(o),t.y/e.scale+e.offset},o.prototype.zoom=function(t,e,i){null==e&&(e=(this.start+this.end)/2);var o=d.getHiddenDurationBetween(this.body.hiddenDates,this.start,this.end),n=d.getHiddenDurationBefore(this.body.hiddenDates,this,e),s=o-n,r=e-n+(this.start-(e-n))*t,a=e+s+(this.end-(e+s))*t;this.startToFront=i>0?!1:!0,this.endToFront=-i>0?!1:!0;var h=d.snapAwayFromHidden(this.body.hiddenDates,r,i,!0),l=d.snapAwayFromHidden(this.body.hiddenDates,a,-i,!0);(h!=r||l!=a)&&(r=h,a=l),this.setRange(r,a,!1,!0),this.startToFront=!1,this.endToFront=!0},o.prototype.move=function(t){var e=this.end-this.start,i=this.start+e*t,o=this.end+e*t;this.start=i,this.end=o},o.prototype.moveTo=function(t){var e=(this.start+this.end)/2,i=e-t,o=this.start-i,n=this.end-i;this.setRange(o,n)},t.exports=o},function(t,e,i){var o=.001;e.orderByStart=function(t){t.sort(function(t,e){return t.data.start-e.data.start})},e.orderByEnd=function(t){t.sort(function(t,e){var i="end"in t.data?t.data.end:t.data.start,o="end"in e.data?e.data.end:e.data.start;return i-o})},e.stack=function(t,i,o){var n,s;if(o)for(n=0,s=t.length;s>n;n++)t[n].top=null;for(n=0,s=t.length;s>n;n++){var r=t[n];if(r.stack&&null===r.top){r.top=i.axis;do{for(var a=null,h=0,d=t.length;d>h;h++){var l=t[h];if(null!==l.top&&l!==r&&l.stack&&e.collision(r,l,i.item)){a=l;break}}null!=a&&(r.top=a.top+a.height+i.item.vertical)}while(a)}}},e.nostack=function(t,e,i){var o,n,s;for(o=0,n=t.length;n>o;o++)if(void 0!==t[o].data.subgroup){s=e.axis;for(var r in i)i.hasOwnProperty(r)&&1==i[r].visible&&i[r].indexe.left&&t.top-i.vertical+oe.top}},function(t,e,i){function o(t,e,i,n){this.current=new Date,this._start=new Date,this._end=new Date,this.autoScale=!0,this.scale="day",this.step=1,this.setRange(t,e,i),this.switchedDay=!1,this.switchedMonth=!1,this.switchedYear=!1,this.hiddenDates=n,void 0===n&&(this.hiddenDates=[]),this.format=o.FORMAT}var n=i(40),s=i(15),r=i(57);o.FORMAT={minorLabels:{millisecond:"SSS",second:"s",minute:"HH:mm",hour:"HH:mm",weekday:"ddd D",day:"D",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",month:"YYYY",year:""}},o.prototype.setFormat=function(t){var e=r.deepExtend({},o.FORMAT);this.format=r.deepExtend(e,t)},o.prototype.setRange=function(t,e,i){if(!(t instanceof Date&&e instanceof Date))throw"No legal start or end date in method setRange";this._start=void 0!=t?new Date(t.valueOf()):new Date,this._end=void 0!=e?new Date(e.valueOf()):new Date,this.autoScale&&this.setMinimumStep(i)},o.prototype.first=function(){this.current=new Date(this._start.valueOf()),this.roundToMinor()},o.prototype.roundToMinor=function(){ -switch(this.scale){case"year":this.current.setFullYear(this.step*Math.floor(this.current.getFullYear()/this.step)),this.current.setMonth(0);case"month":this.current.setDate(1);case"day":case"weekday":this.current.setHours(0);case"hour":this.current.setMinutes(0);case"minute":this.current.setSeconds(0);case"second":this.current.setMilliseconds(0)}if(1!=this.step)switch(this.scale){case"millisecond":this.current.setMilliseconds(this.current.getMilliseconds()-this.current.getMilliseconds()%this.step);break;case"second":this.current.setSeconds(this.current.getSeconds()-this.current.getSeconds()%this.step);break;case"minute":this.current.setMinutes(this.current.getMinutes()-this.current.getMinutes()%this.step);break;case"hour":this.current.setHours(this.current.getHours()-this.current.getHours()%this.step);break;case"weekday":case"day":this.current.setDate(this.current.getDate()-1-(this.current.getDate()-1)%this.step+1);break;case"month":this.current.setMonth(this.current.getMonth()-this.current.getMonth()%this.step);break;case"year":this.current.setFullYear(this.current.getFullYear()-this.current.getFullYear()%this.step)}},o.prototype.hasNext=function(){return this.current.valueOf()<=this._end.valueOf()},o.prototype.next=function(){var t=this.current.valueOf();if(this.current.getMonth()<6)switch(this.scale){case"millisecond":this.current=new Date(this.current.valueOf()+this.step);break;case"second":this.current=new Date(this.current.valueOf()+1e3*this.step);break;case"minute":this.current=new Date(this.current.valueOf()+1e3*this.step*60);break;case"hour":this.current=new Date(this.current.valueOf()+1e3*this.step*60*60);var e=this.current.getHours();this.current.setHours(e-e%this.step);break;case"weekday":case"day":this.current.setDate(this.current.getDate()+this.step);break;case"month":this.current.setMonth(this.current.getMonth()+this.step);break;case"year":this.current.setFullYear(this.current.getFullYear()+this.step)}else switch(this.scale){case"millisecond":this.current=new Date(this.current.valueOf()+this.step);break;case"second":this.current.setSeconds(this.current.getSeconds()+this.step);break;case"minute":this.current.setMinutes(this.current.getMinutes()+this.step);break;case"hour":this.current.setHours(this.current.getHours()+this.step);break;case"weekday":case"day":this.current.setDate(this.current.getDate()+this.step);break;case"month":this.current.setMonth(this.current.getMonth()+this.step);break;case"year":this.current.setFullYear(this.current.getFullYear()+this.step)}if(1!=this.step)switch(this.scale){case"millisecond":this.current.getMilliseconds()0?t.step:1,this.autoScale=!1)},o.prototype.setAutoScale=function(t){this.autoScale=t},o.prototype.setMinimumStep=function(t){if(void 0!=t){var e=31104e6,i=2592e6,o=864e5,n=36e5,s=6e4,r=1e3,a=1;1e3*e>t&&(this.scale="year",this.step=1e3),500*e>t&&(this.scale="year",this.step=500),100*e>t&&(this.scale="year",this.step=100),50*e>t&&(this.scale="year",this.step=50),10*e>t&&(this.scale="year",this.step=10),5*e>t&&(this.scale="year",this.step=5),e>t&&(this.scale="year",this.step=1),3*i>t&&(this.scale="month",this.step=3),i>t&&(this.scale="month",this.step=1),5*o>t&&(this.scale="day",this.step=5),2*o>t&&(this.scale="day",this.step=2),o>t&&(this.scale="day",this.step=1),o/2>t&&(this.scale="weekday",this.step=1),4*n>t&&(this.scale="hour",this.step=4),n>t&&(this.scale="hour",this.step=1),15*s>t&&(this.scale="minute",this.step=15),10*s>t&&(this.scale="minute",this.step=10),5*s>t&&(this.scale="minute",this.step=5),s>t&&(this.scale="minute",this.step=1),15*r>t&&(this.scale="second",this.step=15),10*r>t&&(this.scale="second",this.step=10),5*r>t&&(this.scale="second",this.step=5),r>t&&(this.scale="second",this.step=1),200*a>t&&(this.scale="millisecond",this.step=200),100*a>t&&(this.scale="millisecond",this.step=100),50*a>t&&(this.scale="millisecond",this.step=50),10*a>t&&(this.scale="millisecond",this.step=10),5*a>t&&(this.scale="millisecond",this.step=5),a>t&&(this.scale="millisecond",this.step=1)}},o.snap=function(t,e,i){var o=new Date(t.valueOf());if("year"==e){var n=o.getFullYear()+Math.round(o.getMonth()/12);o.setFullYear(Math.round(n/i)*i),o.setMonth(0),o.setDate(0),o.setHours(0),o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0)}else if("month"==e)o.getDate()>15?(o.setDate(1),o.setMonth(o.getMonth()+1)):o.setDate(1),o.setHours(0),o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0);else if("day"==e){switch(i){case 5:case 2:o.setHours(24*Math.round(o.getHours()/24));break;default:o.setHours(12*Math.round(o.getHours()/12))}o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0)}else if("weekday"==e){switch(i){case 5:case 2:o.setHours(12*Math.round(o.getHours()/12));break;default:o.setHours(6*Math.round(o.getHours()/6))}o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0)}else if("hour"==e){switch(i){case 4:o.setMinutes(60*Math.round(o.getMinutes()/60));break;default:o.setMinutes(30*Math.round(o.getMinutes()/30))}o.setSeconds(0),o.setMilliseconds(0)}else if("minute"==e){switch(i){case 15:case 10:o.setMinutes(5*Math.round(o.getMinutes()/5)),o.setSeconds(0);break;case 5:o.setSeconds(60*Math.round(o.getSeconds()/60));break;default:o.setSeconds(30*Math.round(o.getSeconds()/30))}o.setMilliseconds(0)}else if("second"==e)switch(i){case 15:case 10:o.setSeconds(5*Math.round(o.getSeconds()/5)),o.setMilliseconds(0);break;case 5:o.setMilliseconds(1e3*Math.round(o.getMilliseconds()/1e3));break;default:o.setMilliseconds(500*Math.round(o.getMilliseconds()/500))}else if("millisecond"==e){var s=i>5?i/2:1;o.setMilliseconds(Math.round(o.getMilliseconds()/s)*s)}return o},o.prototype.isMajor=function(){if(1==this.switchedYear)switch(this.switchedYear=!1,this.scale){case"year":case"month":case"weekday":case"day":case"hour":case"minute":case"second":case"millisecond":return!0;default:return!1}else if(1==this.switchedMonth)switch(this.switchedMonth=!1,this.scale){case"weekday":case"day":case"hour":case"minute":case"second":case"millisecond":return!0;default:return!1}else if(1==this.switchedDay)switch(this.switchedDay=!1,this.scale){case"millisecond":case"second":case"minute":case"hour":return!0;default:return!1}switch(this.scale){case"millisecond":return 0==this.current.getMilliseconds();case"second":return 0==this.current.getSeconds();case"minute":return 0==this.current.getHours()&&0==this.current.getMinutes();case"hour":return 0==this.current.getHours();case"weekday":case"day":return 1==this.current.getDate();case"month":return 0==this.current.getMonth();case"year":return!1;default:return!1}},o.prototype.getLabelMinor=function(t){void 0==t&&(t=this.current);var e=this.format.minorLabels[this.scale];return e&&e.length>0?n(t).format(e):""},o.prototype.getLabelMajor=function(t){void 0==t&&(t=this.current);var e=this.format.majorLabels[this.scale];return e&&e.length>0?n(t).format(e):""},o.prototype.getClassName=function(){function t(t){return t/h%2==0?" vis-even":" vis-odd"}function e(t){return t.isSame(new Date,"day")?" vis-today":t.isSame(n().add(1,"day"),"day")?" vis-tomorrow":t.isSame(n().add(-1,"day"),"day")?" vis-yesterday":""}function i(t){return t.isSame(new Date,"week")?" vis-current-week":""}function o(t){return t.isSame(new Date,"month")?" vis-current-month":""}function s(t){return t.isSame(new Date,"year")?" vis-current-year":""}var r=n(this.current),a=r.locale?r.locale("en"):r.lang("en"),h=this.step;switch(this.scale){case"millisecond":return t(a.milliseconds()).trim();case"second":return t(a.seconds()).trim();case"minute":return t(a.minutes()).trim();case"hour":var d=a.hours();return 4==this.step&&(d=d+"-h"+(d+4)),"vis-h"+d+e(a)+t(a.hours());case"weekday":return"vis-"+a.format("dddd").toLowerCase()+e(a)+i(a)+t(a.date());case"day":var l=a.date(),u=a.format("MMMM").toLowerCase();return"vis-day"+l+" vis-"+u+o(a)+t(l-1);case"month":return"vis-"+a.format("MMMM").toLowerCase()+o(a)+t(a.month());case"year":var c=a.year();return"vis-year"+c+s(a)+t(c);default:return""}},t.exports=o},function(t,e,i){function o(t,e,i){if(this.props={dot:{width:0,height:0},line:{width:0,height:0}},t&&void 0==t.start)throw new Error('Property "start" missing in item '+t);n.call(this,t,e,i)}var n=i(21);i(57);o.prototype=new n(null,null,null),o.prototype.isVisible=function(t){var e=(t.end-t.start)/4;return this.data.start>t.start-e&&this.data.start0){var e=[];if(Array.isArray(this.options.dataAttributes))e=this.options.dataAttributes;else{if("all"!=this.options.dataAttributes)return;e=Object.keys(this.data)}for(var i=0;it.start},o.prototype.redraw=function(){var t=this.dom;if(t||(this.dom={},t=this.dom,t.box=document.createElement("div"),t.frame=document.createElement("div"),t.frame.className="vis-item-overflow",t.box.appendChild(t.frame),t.content=document.createElement("div"),t.content.className="vis-item-content",t.frame.appendChild(t.content),this.dirty=!0),!this.parent)throw new Error("Cannot redraw item: no parent attached");if(!t.box.parentNode){var e=this.parent.dom.background;if(!e)throw new Error("Cannot redraw item: parent has no background container element");e.appendChild(t.box)}if(this.displayed=!0,this.dirty){this._updateContents(this.dom.content),this._updateTitle(this.dom.content),this._updateDataAttributes(this.dom.content),this._updateStyle(this.dom.box);var i=(this.data.className?" "+this.data.className:"")+(this.selected?" vis-selected":"");t.box.className=this.baseClassName+i,this.overflow="hidden"!==window.getComputedStyle(t.content).overflow,this.props.content.width=this.dom.content.offsetWidth,this.height=0,this.dirty=!1}},o.prototype.show=r.prototype.show,o.prototype.hide=r.prototype.hide,o.prototype.repositionX=r.prototype.repositionX,o.prototype.repositionY=function(t){var e="top"===this.options.orientation.item;this.dom.content.style.top=e?"":"0",this.dom.content.style.bottom=e?"0":"";var i;if(void 0!==this.data.subgroup){var o=this.data.subgroup,n=this.parent.subgroups,r=n[o].index;if(1==e){i=this.parent.subgroups[o].height+t.item.vertical,i+=0==r?t.axis-.5*t.item.vertical:0;var a=this.parent.top;for(var h in n)n.hasOwnProperty(h)&&1==n[h].visible&&n[h].indexr&&(a+=l)}i=this.parent.subgroups[o].height+t.item.vertical,this.dom.box.style.top=this.parent.height-d+a+"px",this.dom.box.style.bottom=""}}else this.parent instanceof s?(i=Math.max(this.parent.height,this.parent.itemSet.body.domProps.center.height,this.parent.itemSet.body.domProps.centerContainer.height),this.dom.box.style.top=e?"0":"",this.dom.box.style.bottom=e?"":"0"):(i=this.parent.height,this.dom.box.style.top=this.parent.top+"px",this.dom.box.style.bottom="");this.dom.box.style.height=i+"px"},t.exports=o},function(t,e,i){function o(t,e,i){if(this.props={dot:{top:0,width:0,height:0},content:{height:0,marginLeft:0}},t&&void 0==t.start)throw new Error('Property "start" missing in item '+t);n.call(this,t,e,i)}var n=i(21);o.prototype=new n(null,null,null),o.prototype.isVisible=function(t){var e=(t.end-t.start)/4;return this.data.start>t.start-e&&this.data.startt.start},o.prototype.redraw=function(){var t=this.dom;if(t||(this.dom={},t=this.dom,t.box=document.createElement("div"),t.frame=document.createElement("div"),t.frame.className="vis-item-overflow",t.box.appendChild(t.frame),t.content=document.createElement("div"),t.content.className="vis-item-content",t.frame.appendChild(t.content),t.box["timeline-item"]=this,this.dirty=!0),!this.parent)throw new Error("Cannot redraw item: no parent attached");if(!t.box.parentNode){var e=this.parent.dom.foreground;if(!e)throw new Error("Cannot redraw item: parent has no foreground container element");e.appendChild(t.box)}if(this.displayed=!0,this.dirty){this._updateContents(this.dom.content),this._updateTitle(this.dom.box),this._updateDataAttributes(this.dom.box),this._updateStyle(this.dom.box);var i=(this.data.className?" "+this.data.className:"")+(this.selected?" vis-selected":"");t.box.className=this.baseClassName+i,this.overflow="hidden"!==window.getComputedStyle(t.frame).overflow,this.dom.content.style.maxWidth="none",this.props.content.width=this.dom.content.offsetWidth,this.height=this.dom.box.offsetHeight,this.dom.content.style.maxWidth="",this.dirty=!1}this._repaintDeleteButton(t.box),this._repaintDragLeft(),this._repaintDragRight()},o.prototype.show=function(){this.displayed||this.redraw()},o.prototype.hide=function(){if(this.displayed){var t=this.dom.box;t.parentNode&&t.parentNode.removeChild(t),this.displayed=!1}},o.prototype.repositionX=function(t){var e,i,o=this.parent.width,n=this.conversion.toScreen(this.data.start),s=this.conversion.toScreen(this.data.end);(void 0===t||t===!0)&&(-o>n&&(n=-o),s>2*o&&(s=2*o));var r=Math.max(s-n,1);switch(this.overflow?(this.left=n,this.width=r+this.props.content.width,i=this.props.content.width):(this.left=n,this.width=r,i=Math.min(s-n,this.props.content.width)),this.dom.box.style.left=this.left+"px",this.dom.box.style.width=r+"px",this.options.align){case"left":this.dom.content.style.left="0";break;case"right":this.dom.content.style.left=Math.max(r-i,0)+"px";break;case"center":this.dom.content.style.left=Math.max((r-i)/2,0)+"px";break;default:e=this.overflow?s>0?Math.max(-n,0):-i:0>n?-n:0,this.dom.content.style.left=e+"px"}},o.prototype.repositionY=function(){var t=this.options.orientation.item,e=this.dom.box;"top"==t?e.style.top=this.top+"px":e.style.top=this.parent.height-this.top-this.height+"px"},o.prototype._repaintDragLeft=function(){if(this.selected&&this.options.editable.updateTime&&!this.dom.dragLeft){var t=document.createElement("div");t.className="vis-drag-left",t.dragLeftItem=this,this.dom.box.appendChild(t),this.dom.dragLeft=t}else!this.selected&&this.dom.dragLeft&&(this.dom.dragLeft.parentNode&&this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft),this.dom.dragLeft=null)},o.prototype._repaintDragRight=function(){if(this.selected&&this.options.editable.updateTime&&!this.dom.dragRight){var t=document.createElement("div");t.className="vis-drag-right",t.dragRightItem=this,this.dom.box.appendChild(t),this.dom.dragRight=t}else!this.selected&&this.dom.dragRight&&(this.dom.dragRight.parentNode&&this.dom.dragRight.parentNode.removeChild(this.dom.dragRight),this.dom.dragRight=null)},t.exports=o},function(t,e,i){function o(t,e){this.options=null,this.props=null}o.prototype.setOptions=function(t){t&&util.extend(this.options,t)},o.prototype.redraw=function(){return!1},o.prototype.destroy=function(){},o.prototype._isResized=function(){var t=this.props._previousWidth!==this.props.width||this.props._previousHeight!==this.props.height;return this.props._previousWidth=this.props.width,this.props._previousHeight=this.props.height,t},t.exports=o},function(t,e,i){function o(t,e){this.body=t,this.defaultOptions={showCurrentTime:!0,locales:a,locale:"en"},this.options=n.extend({},this.defaultOptions),this.offset=0,this._create(),this.setOptions(e)}var n=i(57),s=i(25),r=i(40),a=i(49);o.prototype=new s,o.prototype._create=function(){var t=document.createElement("div");t.className="vis-current-time",t.style.position="absolute",t.style.top="0px",t.style.height="100%",this.bar=t},o.prototype.destroy=function(){this.options.showCurrentTime=!1,this.redraw(),this.body=null},o.prototype.setOptions=function(t){t&&n.selectiveExtend(["showCurrentTime","locale","locales"],this.options,t)},o.prototype.redraw=function(){if(this.options.showCurrentTime){var t=this.body.dom.backgroundVertical;this.bar.parentNode!=t&&(this.bar.parentNode&&this.bar.parentNode.removeChild(this.bar),t.appendChild(this.bar),this.start());var e=new Date((new Date).valueOf()+this.offset),i=this.body.util.toScreen(e),o=this.options.locales[this.options.locale];o||(this.warned||(console.log("WARNING: options.locales['"+this.options.locale+"'] not found. See http://visjs.org/docs/timeline.html#Localization"),this.warned=!0),o=this.options.locales.en);var n=o.current+" "+o.time+": "+r(e).format("dddd, MMMM Do YYYY, H:mm:ss");n=n.charAt(0).toUpperCase()+n.substring(1),this.bar.style.left=i+"px",this.bar.title=n}else this.bar.parentNode&&this.bar.parentNode.removeChild(this.bar),this.stop();return!1},o.prototype.start=function(){function t(){e.stop();var i=e.body.range.conversion(e.body.domProps.center.width).scale,o=1/i/10;30>o&&(o=30),o>1e3&&(o=1e3),e.redraw(),e.currentTimeTimer=setTimeout(t,o)}var e=this;t()},o.prototype.stop=function(){void 0!==this.currentTimeTimer&&(clearTimeout(this.currentTimeTimer),delete this.currentTimeTimer)},o.prototype.setCurrentTime=function(t){var e=n.convert(t,"Date").valueOf(),i=(new Date).valueOf();this.offset=e-i,this.redraw()},o.prototype.getCurrentTime=function(){return new Date((new Date).valueOf()+this.offset)},t.exports=o},function(t,e,i){function o(t,e){this.body=t,this.defaultOptions={locales:h,locale:"en",id:void 0},this.options=s.extend({},this.defaultOptions),e&&e.time?this.customTime=e.time:this.customTime=new Date,this.eventParams={},this._create(),this.setOptions(e)}var n=i(41),s=i(57),r=i(25),a=i(40),h=i(49);o.prototype=new r,o.prototype.setOptions=function(t){t&&s.selectiveExtend(["locale","locales","id"],this.options,t)},o.prototype._create=function(){var t=document.createElement("div");t["custom-time"]=this,t.className="vis-custom-time",t.style.position="absolute",t.style.top="0px",t.style.height="100%",this.bar=t;var e=document.createElement("div");e.style.position="relative",e.style.top="0px",e.style.left="-10px",e.style.height="100%",e.style.width="20px",t.appendChild(e),this.hammer=new n(e),this.hammer.on("panstart",this._onDragStart.bind(this)),this.hammer.on("panmove",this._onDrag.bind(this)),this.hammer.on("panend",this._onDragEnd.bind(this))},o.prototype.destroy=function(){this.hide(),this.hammer.destroy(),this.hammer=null,this.body=null},o.prototype.redraw=function(){var t=this.body.dom.backgroundVertical;this.bar.parentNode!=t&&(this.bar.parentNode&&this.bar.parentNode.removeChild(this.bar),t.appendChild(this.bar));var e=this.body.util.toScreen(this.customTime),i=this.options.locales[this.options.locale];i||(this.warned||(console.log("WARNING: options.locales['"+this.options.locale+"'] not found. See http://visjs.org/docs/timeline.html#Localization"),this.warned=!0),i=this.options.locales.en);var o=i.time+": "+a(this.customTime).format("dddd, MMMM Do YYYY, H:mm:ss");return o=o.charAt(0).toUpperCase()+o.substring(1),this.bar.style.left=e+"px",this.bar.title=o,!1},o.prototype.hide=function(){this.bar.parentNode&&this.bar.parentNode.removeChild(this.bar)},o.prototype.setCustomTime=function(t){this.customTime=s.convert(t,"Date"),this.redraw()},o.prototype.getCustomTime=function(){return new Date(this.customTime.valueOf())},o.prototype._onDragStart=function(t){this.eventParams.dragging=!0,this.eventParams.customTime=this.customTime,t.stopPropagation()},o.prototype._onDrag=function(t){if(this.eventParams.dragging){var e=this.body.util.toScreen(this.eventParams.customTime)+t.deltaX,i=this.body.util.toTime(e);this.setCustomTime(i),this.body.emitter.emit("timechange",{id:this.options.id,time:new Date(this.customTime.valueOf())}),t.stopPropagation()}},o.prototype._onDragEnd=function(t){this.eventParams.dragging&&(this.body.emitter.emit("timechanged",{id:this.options.id,time:new Date(this.customTime.valueOf())}),t.stopPropagation())},o.customTimeFromTarget=function(t){for(var e=t.target;e;){if(e.hasOwnProperty("custom-time"))return e["custom-time"];e=e.parentNode}return null},t.exports=o},function(t,e,i){function o(t,e,i,o){this.id=n.randomUUID(),this.body=t,this.defaultOptions={orientation:"left",showMinorLabels:!0,showMajorLabels:!0,icons:!0,majorLinesOffset:7,minorLinesOffset:4,labelOffsetX:10,labelOffsetY:2,iconWidth:20,width:"40px",visible:!0,alignZeros:!0,left:{range:{min:void 0,max:void 0},format:function(t){return t},title:{text:void 0,style:void 0}},right:{range:{min:void 0,max:void 0},format:function(t){return t},title:{text:void 0,style:void 0}}},this.linegraphOptions=o,this.linegraphSVG=i,this.props={},this.DOMelements={lines:{},labels:{},title:{}},this.dom={},this.range={start:0,end:0},this.options=n.extend({},this.defaultOptions),this.conversionFactor=1,this.setOptions(e),this.width=Number((""+this.options.width).replace("px","")),this.minWidth=this.width,this.height=this.linegraphSVG.offsetHeight,this.hidden=!1,this.stepPixels=25,this.zeroCrossing=-1,this.amountOfSteps=-1,this.lineOffset=0,this.master=!0,this.svgElements={},this.iconsRemoved=!1,this.groups={},this.amountOfGroups=0,this._create();var s=this;this.body.emitter.on("verticalDrag",function(){s.dom.lineContainer.style.top=s.body.domProps.scrollTop+"px"})}var n=i(57),s=i(2),r=i(25),a=i(16);o.prototype=new r,o.prototype.addGroup=function(t,e){this.groups.hasOwnProperty(t)||(this.groups[t]=e),this.amountOfGroups+=1},o.prototype.updateGroup=function(t,e){this.groups[t]=e},o.prototype.removeGroup=function(t){this.groups.hasOwnProperty(t)&&(delete this.groups[t],this.amountOfGroups-=1)},o.prototype.setOptions=function(t){if(t){var e=!1;this.options.orientation!=t.orientation&&void 0!==t.orientation&&(e=!0);var i=["orientation","showMinorLabels","showMajorLabels","icons","majorLinesOffset","minorLinesOffset","labelOffsetX","labelOffsetY","iconWidth","width","visible","left","right","alignZeros"];n.selectiveExtend(i,this.options,t),this.minWidth=Number((""+this.options.width).replace("px","")),e===!0&&this.dom.frame&&(this.hide(),this.show())}},o.prototype._create=function(){this.dom.frame=document.createElement("div"),this.dom.frame.style.width=this.options.width,this.dom.frame.style.height=this.height,this.dom.lineContainer=document.createElement("div"),this.dom.lineContainer.style.width="100%",this.dom.lineContainer.style.height=this.height,this.dom.lineContainer.style.position="relative",this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.style.position="absolute",this.svg.style.top="0px",this.svg.style.height="100%",this.svg.style.width="100%",this.svg.style.display="block",this.dom.frame.appendChild(this.svg)},o.prototype._redrawGroupIcons=function(){s.prepareElements(this.svgElements);var t,e=this.options.iconWidth,i=15,o=4,n=o+.5*i;t="left"===this.options.orientation?o:this.width-e-o;var r=Object.keys(this.groups);r.sort(function(t,e){return e>t?-1:1});for(var a=0;a0&&(t=0),this.range.start=t,this.range.end=e},o.prototype.redraw=function(){var t=!1,e=0;this.dom.lineContainer.style.top=this.body.domProps.scrollTop+"px";for(var i in this.groups)this.groups.hasOwnProperty(i)&&(this.groups[i].visible!==!0||void 0!==this.linegraphOptions.visibility[i]&&this.linegraphOptions.visibility[i]!==!0||e++);if(0===this.amountOfGroups||0===e)this.hide();else{this.show(),this.height=Number(this.linegraphSVG.style.height.replace("px","")),this.dom.lineContainer.style.height=this.height+"px",this.width=this.options.visible===!0?Number((""+this.options.width).replace("px","")):0;var o=this.props,n=this.dom.frame;n.className="vis-data-axis",this._calculateCharSize();var s=this.options.orientation,r=this.options.showMinorLabels,a=this.options.showMajorLabels;o.minorLabelHeight=r?o.minorCharHeight:0,o.majorLabelHeight=a?o.majorCharHeight:0,o.minorLineWidth=this.body.dom.backgroundHorizontal.offsetWidth-this.lineOffset-this.width+2*this.options.minorLinesOffset,o.minorLineHeight=1,o.majorLineWidth=this.body.dom.backgroundHorizontal.offsetWidth-this.lineOffset-this.width+2*this.options.majorLinesOffset,o.majorLineHeight=1,"left"===s?(n.style.top="0",n.style.left="0",n.style.bottom="",n.style.width=this.width+"px",n.style.height=this.height+"px",this.props.width=this.body.domProps.left.width,this.props.height=this.body.domProps.left.height):(n.style.top="",n.style.bottom="0",n.style.left="0",n.style.width=this.width+"px",n.style.height=this.height+"px",this.props.width=this.body.domProps.right.width,this.props.height=this.body.domProps.right.height),t=this._redrawLabels(),t=this._isResized()||t,this.options.icons===!0?this._redrawGroupIcons():this._cleanupIcons(),this._redrawTitle(s)}return t},o.prototype._redrawLabels=function(){var t=!1;s.prepareElements(this.DOMelements.lines),s.prepareElements(this.DOMelements.labels);var e,i=this.options.orientation;if(this.master===!1){var o,n,r,h;-1!==this.zeroCrossing&&this.options.alignZeros===!0?this.range.end>0?(o=this.range.end/this.zeroCrossing,n=this.range.end-this.amountOfSteps*o,r=this.range.end):(o=-1*this.range.start/(this.amountOfSteps-this.zeroCrossing),n=this.range.start,r=this.range.start+o*this.amountOfSteps):(n=this.range.start,r=this.range.end),h=this.stepPixels}else h=this.props.majorCharHeight,n=this.range.start,r=this.range.end;if(this.step=e=new a(n,r,h,this.dom.frame.offsetHeight,this.options[this.options.orientation].range,this.options[this.options.orientation].format,this.master===!1&&this.options.alignZeros),this.master===!0)this.stepPixels=this.dom.frame.offsetHeight/e.marginRange*e.step,this.amountOfSteps=Math.ceil(this.dom.frame.offsetHeight/this.stepPixels);else if(this.options.alignZeros===!0&&-1!==this.zeroCrossing){var d=(e.current-this.zeroCrossing*e.step)/e.step;this.step.shift(d)}this.valueAtBottom=e.marginEnd,this.maxLabelSize=0;for(var l=0,u=0,c=!1;u0&&u!==this.amountOfSteps&&((this.options.showMinorLabels&&c===!1||this.master===!1&&this.options.showMinorLabels===!0)&&this._redrawLabel(l-2,e.getCurrent(),i,"vis-y-axis vis-minor",this.props.minorCharHeight),c&&this.options.showMajorLabels&&this.master===!0||this.options.showMinorLabels===!1&&this.master===!1&&c===!0?(l>=0&&this._redrawLabel(l-2,e.getCurrent(),i,"vis-y-axis vis-major",this.props.majorCharHeight),this._redrawLine(l,i,"vis-grid vis-horizontal vis-major",this.options.majorLinesOffset,this.props.majorLineWidth)):this._redrawLine(l,i,"vis-grid vis-horizontal vis-minor",this.options.minorLinesOffset,this.props.minorLineWidth)),this.master===!0&&0===e.current&&(this.zeroCrossing=u),e.next(),u+=1;this.master===!0&&0===e.current&&(this.zeroCrossing=u),this.conversionFactor=this.stepPixels/e.step;var p=0;void 0!==this.options[i].title&&void 0!==this.options[i].title.text&&(p=this.props.titleCharHeight);var f=this.options.icons===!0?Math.max(this.options.iconWidth,p)+this.options.labelOffsetX+15:p+this.options.labelOffsetX+15;return this.maxLabelSize>this.width-f&&this.options.visible===!0?(this.width=this.maxLabelSize+f,this.options.width=this.width+"px",s.cleanupElements(this.DOMelements.lines),s.cleanupElements(this.DOMelements.labels),this.redraw(),t=!0):this.maxLabelSizethis.minWidth?(this.width=Math.max(this.minWidth,this.maxLabelSize+f),this.options.width=this.width+"px",s.cleanupElements(this.DOMelements.lines),s.cleanupElements(this.DOMelements.labels),this.redraw(),t=!0):(s.cleanupElements(this.DOMelements.lines),s.cleanupElements(this.DOMelements.labels),t=!1),t},o.prototype.convertValue=function(t){var e=this.valueAtBottom-t,i=e*this.conversionFactor;return i},o.prototype.screenToValue=function(t){return this.valueAtBottom-t/this.conversionFactor},o.prototype._redrawLabel=function(t,e,i,o,n){var r=s.getDOMElement("div",this.DOMelements.labels,this.dom.frame);r.className=o,r.innerHTML=e,"left"===i?(r.style.left="-"+this.options.labelOffsetX+"px",r.style.textAlign="right"):(r.style.right="-"+this.options.labelOffsetX+"px",r.style.textAlign="left"),r.style.top=t-.5*n+this.options.labelOffsetY+"px",e+="";var a=Math.max(this.props.majorCharWidth,this.props.minorCharWidth);this.maxLabelSizec;c++){var f=this.visibleItems[c];f.repositionY(e)}return o},o.prototype._calculateHeight=function(t){var e,i=this.visibleItems;this.resetSubgroups();var o=this;if(i.length>0){var s=i[0].top,r=i[0].top+i[0].height;if(n.forEach(i,function(t){s=Math.min(s,t.top),r=Math.max(r,t.top+t.height),void 0!==t.data.subgroup&&(o.subgroups[t.data.subgroup].height=Math.max(o.subgroups[t.data.subgroup].height,t.height),o.subgroups[t.data.subgroup].visible=!0)}),s>t.axis){var a=s-t.axis;r-=a,n.forEach(i,function(t){t.top-=a})}e=r+t.item.vertical/2}else e=0;return e=Math.max(e,this.props.label.height)},o.prototype.show=function(){this.dom.label.parentNode||this.itemSet.dom.labelSet.appendChild(this.dom.label),this.dom.foreground.parentNode||this.itemSet.dom.foreground.appendChild(this.dom.foreground),this.dom.background.parentNode||this.itemSet.dom.background.appendChild(this.dom.background),this.dom.axis.parentNode||this.itemSet.dom.axis.appendChild(this.dom.axis)},o.prototype.hide=function(){var t=this.dom.label;t.parentNode&&t.parentNode.removeChild(t);var e=this.dom.foreground;e.parentNode&&e.parentNode.removeChild(e);var i=this.dom.background;i.parentNode&&i.parentNode.removeChild(i);var o=this.dom.axis;o.parentNode&&o.parentNode.removeChild(o)},o.prototype.add=function(t){if(this.items[t.id]=t,t.setParent(this),void 0!==t.data.subgroup&&(void 0===this.subgroups[t.data.subgroup]&&(this.subgroups[t.data.subgroup]={height:0,visible:!1,index:this.subgroupIndex,items:[]},this.subgroupIndex++),this.subgroups[t.data.subgroup].items.push(t)),this.orderSubgroups(),-1==this.visibleItems.indexOf(t)){var e=this.itemSet.body.range;this._checkIfVisible(t,this.visibleItems,e)}},o.prototype.orderSubgroups=function(){if(void 0!==this.subgroupOrderer){var t=[];if("string"==typeof this.subgroupOrderer){for(var e in this.subgroups)t.push({subgroup:e,sortField:this.subgroups[e].items[0].data[this.subgroupOrderer]});t.sort(function(t,e){return t.sortField-e.sortField})}else if("function"==typeof this.subgroupOrderer){for(var e in this.subgroups)t.push(this.subgroups[e].items[0].data);t.sort(this.subgroupOrderer)}if(t.length>0)for(var i=0;it?-1:l>=t?0:1};if(e.length>0)for(s=0;sl}),1==this.checkRangedItems)for(this.checkRangedItems=!1,s=0;sl})}for(s=0;s=0&&(s=e[r],!n(s));r--)void 0===o[s.id]&&(o[s.id]=!0,i.push(s));for(r=t+1;rn;n++){var r=this.visibleItems[n];r.repositionY(e)}return o},o.prototype.show=function(){this.dom.background.parentNode||this.itemSet.dom.background.appendChild(this.dom.background)},t.exports=o},function(t,e,i){function o(t,e){this.body=t,this.defaultOptions={type:null,orientation:{item:"bottom"},align:"auto",stack:!0,groupOrder:null,selectable:!0,multiselect:!1,editable:{updateTime:!1,updateGroup:!1,add:!1,remove:!1},snap:h.snap,onAdd:function(t,e){e(t)},onUpdate:function(t,e){e(t)},onMove:function(t,e){e(t)},onRemove:function(t,e){e(t)},onMoving:function(t,e){e(t)},margin:{item:{horizontal:10,vertical:10},axis:20}},this.options=s.extend({},this.defaultOptions),this.itemOptions={type:{start:"Date",end:"Date"}},this.conversion={toScreen:t.util.toScreen,toTime:t.util.toTime},this.dom={},this.props={},this.hammer=null;var i=this;this.itemsData=null,this.groupsData=null,this.itemListeners={add:function(t,e,o){i._onAdd(e.items)},update:function(t,e,o){i._onUpdate(e.items)},remove:function(t,e,o){i._onRemove(e.items)}},this.groupListeners={add:function(t,e,o){i._onAddGroups(e.items)},update:function(t,e,o){i._onUpdateGroups(e.items)},remove:function(t,e,o){i._onRemoveGroups(e.items)}},this.items={},this.groups={},this.groupIds=[],this.selection=[],this.stackDirty=!0,this.touchParams={},this._create(),this.setOptions(e)}var n=i(41),s=i(57),r=i(3),a=i(4),h=i(19),d=i(25),l=i(30),u=i(31),c=i(20),p=i(23),f=i(24),m=i(22),v="__ungrouped__",g="__background__";o.prototype=new d,o.types={background:m,box:c,range:f,point:p},o.prototype._create=function(){var t=document.createElement("div");t.className="vis-itemset",t["timeline-itemset"]=this,this.dom.frame=t;var e=document.createElement("div");e.className="vis-background",t.appendChild(e),this.dom.background=e;var i=document.createElement("div");i.className="vis-foreground",t.appendChild(i),this.dom.foreground=i;var o=document.createElement("div");o.className="vis-axis",this.dom.axis=o;var s=document.createElement("div");s.className="vis-labelset",this.dom.labelSet=s,this._updateUngrouped();var r=new u(g,null,this);r.show(),this.groups[g]=r,this.hammer=new n(this.body.dom.centerContainer),this.hammer.on("hammer.input",function(t){t.isFirst&&this._onTouch(t)}.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.on("tap",this._onSelectItem.bind(this)),this.hammer.on("press",this._onMultiSelectItem.bind(this)),this.hammer.on("doubletap",this._onAddItem.bind(this)),this.show()},o.prototype.setOptions=function(t){if(t){var e=["type","align","order","stack","selectable","multiselect","groupOrder","dataAttributes","template","hide","snap"];s.selectiveExtend(e,this.options,t),"orientation"in t&&("string"==typeof t.orientation?this.options.orientation.item="top"===t.orientation?"top":"bottom":"object"==typeof t.orientation&&"item"in t.orientation&&(this.options.orientation.item=t.orientation.item)),"margin"in t&&("number"==typeof t.margin?(this.options.margin.axis=t.margin,this.options.margin.item.horizontal=t.margin,this.options.margin.item.vertical=t.margin):"object"==typeof t.margin&&(s.selectiveExtend(["axis"],this.options.margin,t.margin),"item"in t.margin&&("number"==typeof t.margin.item?(this.options.margin.item.horizontal=t.margin.item,this.options.margin.item.vertical=t.margin.item):"object"==typeof t.margin.item&&s.selectiveExtend(["horizontal","vertical"],this.options.margin.item,t.margin.item)))),"editable"in t&&("boolean"==typeof t.editable?(this.options.editable.updateTime=t.editable,this.options.editable.updateGroup=t.editable,this.options.editable.add=t.editable,this.options.editable.remove=t.editable):"object"==typeof t.editable&&s.selectiveExtend(["updateTime","updateGroup","add","remove"],this.options.editable,t.editable));var i=function(e){var i=t[e];if(i){if(!(i instanceof Function))throw new Error("option "+e+" must be a function "+e+"(item, callback)");this.options[e]=i}}.bind(this);["onAdd","onUpdate","onRemove","onMove","onMoving"].forEach(i),this.markDirty()}},o.prototype.markDirty=function(t){this.groupIds=[],this.stackDirty=!0,t&&t.refreshItems&&s.forEach(this.items,function(t){t.dirty=!0,t.displayed&&t.redraw()})},o.prototype.destroy=function(){this.hide(),this.setItems(null),this.setGroups(null),this.hammer=null,this.body=null,this.conversion=null},o.prototype.hide=function(){this.dom.frame.parentNode&&this.dom.frame.parentNode.removeChild(this.dom.frame),this.dom.axis.parentNode&&this.dom.axis.parentNode.removeChild(this.dom.axis),this.dom.labelSet.parentNode&&this.dom.labelSet.parentNode.removeChild(this.dom.labelSet)},o.prototype.show=function(){this.dom.frame.parentNode||this.body.dom.center.appendChild(this.dom.frame),this.dom.axis.parentNode||this.body.dom.backgroundVertical.appendChild(this.dom.axis),this.dom.labelSet.parentNode||this.body.dom.left.appendChild(this.dom.labelSet)},o.prototype.setSelection=function(t){var e,i,o,n;for(void 0==t&&(t=[]),Array.isArray(t)||(t=[t]),e=0,i=this.selection.length;i>e;e++)o=this.selection[e],n=this.items[o],n&&n.unselect();for(this.selection=[],e=0,i=t.length;i>e;e++)o=t[e],n=this.items[o],n&&(this.selection.push(o),n.select())},o.prototype.getSelection=function(){return this.selection.concat([])},o.prototype.getVisibleItems=function(){var t=this.body.range.getRange(),e=this.body.util.toScreen(t.start),i=this.body.util.toScreen(t.end),o=[];for(var n in this.groups)if(this.groups.hasOwnProperty(n))for(var s=this.groups[n],r=s.visibleItems,a=0;ae&&o.push(h.id)}return o},o.prototype._deselect=function(t){for(var e=this.selection,i=0,o=e.length;o>i;i++)if(e[i]==t){e.splice(i,1);break}},o.prototype.redraw=function(){var t=this.options.margin,e=this.body.range,i=s.option.asSize,o=this.options,n=o.orientation.item,r=!1,a=this.dom.frame,h=o.editable.updateTime||o.editable.updateGroup;this.props.top=this.body.domProps.top.height+this.body.domProps.border.top,this.props.left=this.body.domProps.left.width+this.body.domProps.border.left,a.className="vis-itemset"+(h?" vis-editable":""),r=this._orderGroups()||r;var d=e.end-e.start,l=d!=this.lastVisibleInterval||this.props.width!=this.props.lastWidth;l&&(this.stackDirty=!0),this.lastVisibleInterval=d,this.props.lastWidth=this.props.width;var u=this.stackDirty,c=this._firstGroup(),p={item:t.item,axis:t.axis},f={item:t.item,axis:t.item.vertical/2},m=0,v=t.axis+t.item.vertical;return this.groups[g].redraw(e,f,u),s.forEach(this.groups,function(t){var i=t==c?p:f,o=t.redraw(e,i,u);r=o||r,m+=t.height}),m=Math.max(m,v),this.stackDirty=!1,a.style.height=i(m),this.props.width=a.offsetWidth,this.props.height=m,this.dom.axis.style.top=i("top"==n?this.body.domProps.top.height+this.body.domProps.border.top:this.body.domProps.top.height+this.body.domProps.centerContainer.height),this.dom.axis.style.left="0",r=this._isResized()||r},o.prototype._firstGroup=function(){var t="top"==this.options.orientation.item?0:this.groupIds.length-1,e=this.groupIds[t],i=this.groups[e]||this.groups[v];return i||null},o.prototype._updateUngrouped=function(){var t,e,i=this.groups[v];this.groups[g];if(this.groupsData){if(i){i.hide(),delete this.groups[v];for(e in this.items)if(this.items.hasOwnProperty(e)){t=this.items[e],t.parent&&t.parent.remove(t);var o=this._getGroupId(t.data),n=this.groups[o];n&&n.add(t)||t.hide()}}}else if(!i){var s=null,r=null;i=new l(s,r,this),this.groups[v]=i;for(e in this.items)this.items.hasOwnProperty(e)&&(t=this.items[e],i.add(t));i.show()}},o.prototype.getLabelSet=function(){return this.dom.labelSet},o.prototype.setItems=function(t){var e,i=this,o=this.itemsData;if(t){if(!(t instanceof r||t instanceof a))throw new TypeError("Data must be an instance of DataSet or DataView");this.itemsData=t}else this.itemsData=null;if(o&&(s.forEach(this.itemListeners,function(t,e){o.off(e,t)}),e=o.getIds(),this._onRemove(e)),this.itemsData){var n=this.id;s.forEach(this.itemListeners,function(t,e){i.itemsData.on(e,t,n)}),e=this.itemsData.getIds(),this._onAdd(e),this._updateUngrouped()}},o.prototype.getItems=function(){return this.itemsData},o.prototype.setGroups=function(t){var e,i=this;if(this.groupsData&&(s.forEach(this.groupListeners,function(t,e){i.groupsData.unsubscribe(e,t)}),e=this.groupsData.getIds(),this.groupsData=null,this._onRemoveGroups(e)),t){if(!(t instanceof r||t instanceof a))throw new TypeError("Data must be an instance of DataSet or DataView");this.groupsData=t}else this.groupsData=null;if(this.groupsData){var o=this.id;s.forEach(this.groupListeners,function(t,e){i.groupsData.on(e,t,o)}),e=this.groupsData.getIds(),this._onAddGroups(e)}this._updateUngrouped(),this._order(),this.body.emitter.emit("change",{queue:!0})},o.prototype.getGroups=function(){return this.groupsData},o.prototype.removeItem=function(t){var e=this.itemsData.get(t),i=this.itemsData.getDataSet();e&&this.options.onRemove(e,function(e){e&&i.remove(t)})},o.prototype._getType=function(t){return t.type||this.options.type||(t.end?"range":"box")},o.prototype._getGroupId=function(t){var e=this._getType(t);return"background"==e&&void 0==t.group?g:this.groupsData?t.group:v},o.prototype._onUpdate=function(t){var e=this;t.forEach(function(t){var i,n=e.itemsData.get(t,e.itemOptions),s=e.items[t],r=e._getType(n),a=o.types[r];if(s&&(a&&s instanceof a?e._updateItem(s,n):(i=s.selected,e._removeItem(s),s=null)),!s){if(!a)throw"rangeoverflow"==r?new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: .vis-item.vis-range .vis-item-content {overflow: visible;}'):new TypeError('Unknown item type "'+r+'"');s=new a(n,e.conversion,e.options),s.id=t,e._addItem(s),i&&(this.selection.push(t),s.select())}}.bind(this)),this._order(),this.stackDirty=!0,this.body.emitter.emit("change",{queue:!0})},o.prototype._onAdd=o.prototype._onUpdate,o.prototype._onRemove=function(t){var e=0,i=this;t.forEach(function(t){var o=i.items[t];o&&(e++,i._removeItem(o))}),e&&(this._order(),this.stackDirty=!0,this.body.emitter.emit("change",{queue:!0}))},o.prototype._order=function(){s.forEach(this.groups,function(t){t.order()})},o.prototype._onUpdateGroups=function(t){this._onAddGroups(t)},o.prototype._onAddGroups=function(t){var e=this;t.forEach(function(t){var i=e.groupsData.get(t),o=e.groups[t];if(o)o.setData(i);else{if(t==v||t==g)throw new Error("Illegal group id. "+t+" is a reserved id.");var n=Object.create(e.options);s.extend(n,{height:null}),o=new l(t,i,e),e.groups[t]=o;for(var r in e.items)if(e.items.hasOwnProperty(r)){var a=e.items[r];a.data.group==t&&o.add(a)}o.order(),o.show()}}),this.body.emitter.emit("change",{queue:!0})},o.prototype._onRemoveGroups=function(t){var e=this.groups;t.forEach(function(t){var i=e[t];i&&(i.hide(),delete e[t])}),this.markDirty(),this.body.emitter.emit("change",{queue:!0})},o.prototype._orderGroups=function(){if(this.groupsData){var t=this.groupsData.getIds({order:this.options.groupOrder}),e=!s.equalArray(t,this.groupIds);if(e){var i=this.groups;t.forEach(function(t){i[t].hide()}),t.forEach(function(t){i[t].show()}),this.groupIds=t}return e}return!1},o.prototype._addItem=function(t){this.items[t.id]=t;var e=this._getGroupId(t.data),i=this.groups[e];i&&i.add(t)},o.prototype._updateItem=function(t,e){var i=t.data.group,o=t.data.subgroup;if(t.setData(e),i!=t.data.group||o!=t.data.subgroup){var n=this.groups[i];n&&n.remove(t);var s=this._getGroupId(t.data),r=this.groups[s];r&&r.add(t)}},o.prototype._removeItem=function(t){t.hide(),delete this.items[t.id];var e=this.selection.indexOf(t.id);-1!=e&&this.selection.splice(e,1),t.parent&&t.parent.remove(t)},o.prototype._constructByEndArray=function(t){for(var e=[],i=0;i0||o.length>0)&&this.body.emitter.emit("select",{items:r})}},o.prototype._onAddItem=function(t){if(this.options.selectable&&this.options.editable.add){var e=this,i=this.options.snap||null,o=this.itemFromTarget(t);if(o){var n=e.itemsData.get(o.id);this.options.onUpdate(n,function(t){t&&e.itemsData.getDataSet().update(t)})}else{var r=s.getAbsoluteLeft(this.dom.frame),a=t.center.x-r,h=this.body.util.toTime(a),d=this.body.util.getScale(),l=this.body.util.getStep(),u={start:i?i(h,d,l):h,content:"new item"};if("range"===this.options.type){var c=this.body.util.toTime(a+this.props.width/5);u.end=i?i(c,d,l):c}u[this.itemsData._fieldId]=s.randomUUID();var p=this.groupFromTarget(t);p&&(u.group=p.groupId),this.options.onAdd(u,function(t){t&&e.itemsData.getDataSet().add(t)})}}},o.prototype._onMultiSelectItem=function(t){if(this.options.selectable){var e=this.itemFromTarget(t);if(e){var i=this.options.multiselect?this.getSelection():[],n=t.srcEvent&&t.srcEvent.shiftKey||!1;if(n&&this.options.multiselect){i.push(e.id);var s=o._getItemRange(this.itemsData.get(i,this.itemOptions));i=[];for(var r in this.items)if(this.items.hasOwnProperty(r)){var a=this.items[r],h=a.data.start,d=void 0!==a.data.end?a.data.end:h;h>=s.min&&d<=s.max&&!(a instanceof m)&&i.push(a.id)}}else{var l=i.indexOf(e.id);-1==l?i.push(e.id):i.splice(l,1)}this.setSelection(i),this.body.emitter.emit("select",{items:this.getSelection()})}}},o._getItemRange=function(t){var e=null,i=null;return t.forEach(function(t){(null==i||t.starte)&&(e=t.end):(null==e||t.start>e)&&(e=t.start)}),{min:i,max:e}},o.prototype.itemFromTarget=function(t){for(var e=t.target;e;){if(e.hasOwnProperty("timeline-item"))return e["timeline-item"];e=e.parentNode}return null},o.prototype.groupFromTarget=function(t){for(var e=t.center?t.center.y:t.clientY,i=0;ia&&ea)return n}else if(0===i&&et?-1:1});for(var i=0;i")}this.dom.textArea.innerHTML=s,this.dom.textArea.style.lineHeight=.75*this.options.iconSize+this.options.iconSpacing+"px"}},o.prototype.drawLegendIcons=function(){if(this.dom.frame.parentNode){var t=Object.keys(this.groups);t.sort(function(t,e){return e>t?-1:1}),s.prepareElements(this.svgElements);var e=window.getComputedStyle(this.dom.frame).paddingTop,i=Number(e.replace("px","")),o=i,n=this.options.iconSize,r=.75*this.options.iconSize,a=i+.5*r+3;this.svg.style.width=n+5+i+"px";for(var h=0;h0){var d=this.body.util.toGlobalTime(-this.body.domProps.root.width),l=this.body.util.toGlobalTime(2*this.body.domProps.root.width),u={};for(this._getRelevantData(a,u,d,l),this._applySampling(a,u),e=0;ep&&console.log("WARNING: there may be an infinite loop in the _updateGraph emitter cycle."),this.COUNTER=0,this.abortedGraphUpdate=!1,e=0;e0)for(r=0;ro){d.push(h);break}d.push(h)}}else for(a=0;ai&&h.x0)for(var o=0;o0){var s=1,r=n.length,a=this.body.util.toGlobalScreen(n[n.length-1].x)-this.body.util.toGlobalScreen(n[0].x),h=r/a;s=Math.min(Math.ceil(.2*r),Math.max(1,Math.round(h)));for(var d=[],l=0;r>l;l+=s)d.push(n[l]);e[t[o]]=d}}},o.prototype._getYRanges=function(t,e,i){var o,n,s,r,a=[],h=[];if(t.length>0){for(s=0;s0&&(n=this.groups[t[s]],r.stack===!0?"left"==r.yAxisOrientation?a=a.concat(n.getData(o)):h=h.concat(n.getData(o)):i[t[s]]=n.getYRange(o,t[s]));c.getStackedYRange(a,i,t,"__barStackLeft","left"),c.getStackedYRange(h,i,t,"__barStackRight","right"),p.getStackedYRange(a,i,t,"__lineStackLeft","left"),p.getStackedYRange(h,i,t,"__lineStackRight","right")}},o.prototype._updateYAxis=function(t,e){var i,o,n=!1,s=!1,r=!1,a=1e9,h=1e9,d=-1e9,l=-1e9;if(t.length>0){for(var u=0;ui?i:a,d=o>d?o:d):(r=!0,h=h>i?i:h,l=o>l?o:l));1==s&&this.yAxisLeft.setRange(a,d),1==r&&this.yAxisRight.setRange(h,l)}n=this._toggleAxisVisiblity(s,this.yAxisLeft)||n,n=this._toggleAxisVisiblity(r,this.yAxisRight)||n,1==r&&1==s?(this.yAxisLeft.drawIcons=!0,this.yAxisRight.drawIcons=!0):(this.yAxisLeft.drawIcons=!1,this.yAxisRight.drawIcons=!1),this.yAxisRight.master=!s,0==this.yAxisRight.master?(1==r?this.yAxisLeft.lineOffset=this.yAxisRight.width:this.yAxisLeft.lineOffset=0,n=this.yAxisLeft.redraw()||n,this.yAxisRight.stepPixels=this.yAxisLeft.stepPixels,this.yAxisRight.zeroCrossing=this.yAxisLeft.zeroCrossing,this.yAxisRight.amountOfSteps=this.yAxisLeft.amountOfSteps,n=this.yAxisRight.redraw()||n):n=this.yAxisRight.redraw()||n;for(var p=["__barStackLeft","__barStackRight","__lineStackLeft","__lineStackRight"],u=0;uy;)y++,l=h.getCurrent(),u=h.isMajor(),p=h.getClassName(),m=f,f=this.body.util.toScreen(l),v=f-m,c&&(c.style.width=v+"px"),this.options.showMinorLabels&&this._repaintMinorText(f,h.getLabelMinor(),t,p),u&&this.options.showMajorLabels?(f>0&&(void 0==g&&(g=f),this._repaintMajorText(f,h.getLabelMajor(),t,p)),c=this._repaintMajorLine(f,t,p)):c=this._repaintMinorLine(f,t,p),h.next();if(this.options.showMajorLabels){var b=this.body.util.toTime(0),w=h.getLabelMajor(b),_=w.length*(this.props.majorCharWidth||10)+10;(void 0==g||g>_)&&this._repaintMajorText(0,w,t,p)}n.forEach(this.dom.redundant,function(t){for(;t.length;){var e=t.pop();e&&e.parentNode&&e.parentNode.removeChild(e)}})},o.prototype._repaintMinorText=function(t,e,i,o){var n=this.dom.redundant.minorTexts.shift();if(!n){var s=document.createTextNode("");n=document.createElement("div"),n.appendChild(s),this.dom.foreground.appendChild(n)}this.dom.minorTexts.push(n),n.childNodes[0].nodeValue=e,n.style.top="top"==i?this.props.majorLabelHeight+"px":"0",n.style.left=t+"px",n.className="vis-text vis-minor "+o},o.prototype._repaintMajorText=function(t,e,i,o){var n=this.dom.redundant.majorTexts.shift();if(!n){var s=document.createTextNode(e);n=document.createElement("div"),n.appendChild(s),this.dom.foreground.appendChild(n)}this.dom.majorTexts.push(n),n.childNodes[0].nodeValue=e,n.className="vis-text vis-major "+o,n.style.top="top"==i?"0":this.props.minorLabelHeight+"px",n.style.left=t+"px"},o.prototype._repaintMinorLine=function(t,e,i){var o=this.dom.redundant.lines.shift();o||(o=document.createElement("div"),this.dom.background.appendChild(o)),this.dom.lines.push(o);var n=this.props;return"top"==e?o.style.top=n.majorLabelHeight+"px":o.style.top=this.body.domProps.top.height+"px",o.style.height=n.minorLineHeight+"px",o.style.left=t-n.minorLineWidth/2+"px",o.className="vis-grid vis-vertical vis-minor "+i,o},o.prototype._repaintMajorLine=function(t,e,i){var o=this.dom.redundant.lines.shift();o||(o=document.createElement("div"),this.dom.background.appendChild(o)),this.dom.lines.push(o);var n=this.props;return"top"==e?o.style.top="0":o.style.top=this.body.domProps.top.height+"px",o.style.left=t-n.majorLineWidth/2+"px",o.style.height=n.majorLineHeight+"px",o.className="vis-grid vis-vertical vis-major "+i,o},o.prototype._calculateCharSize=function(){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,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},t.exports=o},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e,i){var o=this;if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");this.options={},this.defaultOptions={locale:"en",locales:j,clickToUse:!1},A.extend(this.options,this.defaultOptions),this.body={nodes:{},nodeIndices:[],edges:{},edgeIndices:[],data:{nodes:null,edges:null},functions:{createNode:function(){},createEdge:function(){},getPointer:function(){}},emitter:{on:this.on.bind(this),off:this.off.bind(this),emit:this.emit.bind(this),once:this.once.bind(this)},eventListeners:{onTap:function(){},onTouch:function(){},onDoubleTap:function(){},onHold:function(){},onDragStart:function(){},onDrag:function(){},onDragEnd:function(){},onMouseWheel:function(){},onPinch:function(){},onMouseMove:function(){},onRelease:function(){},onContext:function(){}},container:t,view:{scale:1,translation:{x:0,y:0}}},this.bindEventListeners(),this.images=new R(function(){return o.body.emitter.emit("_requestRedraw")}),this.groups=new r["default"],this.canvas=new y["default"](this.body),this.selectionHandler=new M["default"](this.body,this.canvas),this.interactionHandler=new x["default"](this.body,this.canvas,this.selectionHandler),this.view=new w["default"](this.body,this.canvas),this.renderer=new v["default"](this.body,this.canvas),this.physics=new c["default"](this.body),this.layoutEngine=new D["default"](this.body),this.clustering=new f["default"](this.body),this.manipulation=new C["default"](this.body,this.canvas,this.selectionHandler),this.nodesHandler=new h["default"](this.body,this.images,this.groups,this.layoutEngine),this.edgesHandler=new l["default"](this.body,this.images,this.groups),this.canvas._create(),this.configurator=new S["default"](this,this.body.container,N.configureOptions,this.canvas.pixelRatio),this.setOptions(i),this.setData(e)}var s=i(53),r=o(s),a=i(54),h=o(a),d=i(55),l=o(d),u=i(56),c=o(u),p=i(1),f=o(p),m=i(58),v=o(m),g=i(59),y=o(g),b=i(60),w=o(b),_=i(61),x=o(_),k=i(62),M=o(k),O=i(63),D=o(O),T=i(64),C=o(T),E=i(44),S=o(E),P=i(45),I=o(P),N=i(65);i(66);var z=i(69),A=(i(41),i(57)),L=(i(3),i(4),i(38)),B=i(39),R=i(37),F=i(67),j=i(68);z(n.prototype),n.prototype.setOptions=function(t){if(void 0!==t){var e=I["default"].validate(t,N.allOptions);e===!0&&console.log("%cErrors have been found in the supplied options object.",P.printStyle);var i=["locale","locales","clickToUse"];if(A.selectiveDeepExtend(i,this.options,t),t=this.layoutEngine.setOptions(t.layout,t),this.canvas.setOptions(t),this.groups.setOptions(t.groups),this.nodesHandler.setOptions(t.nodes),this.edgesHandler.setOptions(t.edges), -this.physics.setOptions(t.physics),this.manipulation.setOptions(t.manipulation,t,this.options),this.interactionHandler.setOptions(t.interaction),this.renderer.setOptions(t.interaction),this.selectionHandler.setOptions(t.interaction),void 0!==t.groups&&this.body.emitter.emit("refreshNodes"),this.configurator.setOptions(t.configure),this.configurator.options.enabled===!0){var o={nodes:{},edges:{},layout:{},interaction:{},manipulation:{},physics:{},global:{}};A.deepExtend(o.nodes,this.nodesHandler.options),A.deepExtend(o.edges,this.edgesHandler.options),A.deepExtend(o.layout,this.layoutEngine.options),A.deepExtend(o.interaction,this.selectionHandler.options),A.deepExtend(o.interaction,this.renderer.options),A.deepExtend(o.interaction,this.interactionHandler.options),A.deepExtend(o.manipulation,this.manipulation.options),A.deepExtend(o.physics,this.physics.options),A.deepExtend(o.global,this.canvas.options),A.deepExtend(o.global,this.options),this.configurator.setModuleOptions(o)}void 0!==t.clickToUse?t.clickToUse===!0?void 0===this.activator&&(this.activator=new F(this.frame),this.activator.on("change",this._createKeyBinds.bind(this))):(void 0!==this.activator&&(this.activator.destroy(),delete this.activator),this.body.emitter.emit("activate")):this.body.emitter.emit("activate"),this.canvas.setSize(),this.body.emitter.emit("startSimulation")}},n.prototype._updateVisibleIndices=function(){var t=this.body.nodes,e=this.body.edges;this.body.nodeIndices=[],this.body.edgeIndices=[];for(var i in t)t.hasOwnProperty(i)&&t[i].options.hidden===!1&&this.body.nodeIndices.push(i);for(var o in e)e.hasOwnProperty(o)&&e[o].options.hidden===!1&&this.body.edgeIndices.push(o)},n.prototype.bindEventListeners=function(){var t=this;this.body.emitter.on("_dataChanged",function(){t._updateVisibleIndices(),t.physics.updatePhysicsData(),t.body.emitter.emit("_dataUpdated")}),this.body.emitter.on("_dataUpdated",function(){t._updateValueRange(t.body.nodes),t._updateValueRange(t.body.edges),t.body.emitter.emit("startSimulation")})},n.prototype.setData=function(t){if(this.body.emitter.emit("resetPhysics"),this.body.emitter.emit("_resetData"),this.selectionHandler.unselectAll(),t&&t.dot&&(t.nodes||t.edges))throw new SyntaxError('Data must contain either parameter "dot" or parameter pair "nodes" and "edges", but not both.');if(this.setOptions(t&&t.options),t&&t.dot){console.log("The dot property has been depricated. Please use the static convertDot method to convert DOT into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertDot(dotString);");var e=L.DOTToGraph(t.dot);return void this.setData(e)}if(t&&t.gephi){console.log("The gephi property has been depricated. Please use the static convertGephi method to convert gephi into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertGephi(gephiJson);");var i=B.parseGephi(t.gephi);return void this.setData(i)}this.nodesHandler.setData(t&&t.nodes,!0),this.edgesHandler.setData(t&&t.edges,!0),this.body.emitter.emit("_dataChanged"),this.body.emitter.emit("initPhysics")},n.prototype.destroy=function(){this.body.emitter.emit("destroy"),this.body.emitter.off(),this.off(),delete this.groups,delete this.canvas,delete this.selectionHandler,delete this.interactionHandler,delete this.view,delete this.renderer,delete this.physics,delete this.layoutEngine,delete this.clustering,delete this.manipulation,delete this.nodesHandler,delete this.edgesHandler,delete this.configurator,delete this.images,delete this.body.emitter.emit,delete this.body.emitter.on,delete this.body.emitter.off,delete this.body.emitter.once,delete this.body.emitter;for(var t in this.body.nodes)delete this.body.nodes[t];for(var e in this.body.edges)delete this.body.edges[e];A.recursiveDOMDelete(this.body.container)},n.prototype._updateValueRange=function(t){var e,i=void 0,o=void 0,n=0;for(e in t)if(t.hasOwnProperty(e)){var s=t[e].getValue();void 0!==s&&(i=void 0===i?s:Math.min(s,i),o=void 0===o?s:Math.max(s,o),n+=s)}if(void 0!==i&&void 0!==o)for(e in t)t.hasOwnProperty(e)&&t[e].setValueRange(i,o,n)},n.prototype.isActive=function(){return!this.activator||this.activator.active},n.prototype.setSize=function(){return this.canvas.setSize.apply(this.canvas,arguments)},n.prototype.canvasToDOM=function(){return this.canvas.canvasToDOM.apply(this.canvas,arguments)},n.prototype.DOMtoCanvas=function(){return this.canvas.setSize.DOMtoCanvas(this.canvas,arguments)},n.prototype.findNode=function(){return this.clustering.findNode.apply(this.clustering,arguments)},n.prototype.isCluster=function(){return this.clustering.isCluster.apply(this.clustering,arguments)},n.prototype.openCluster=function(){return this.clustering.openCluster.apply(this.clustering,arguments)},n.prototype.cluster=function(){return this.clustering.cluster.apply(this.clustering,arguments)},n.prototype.clusterByConnection=function(){return this.clustering.clusterByConnection.apply(this.clustering,arguments)},n.prototype.clusterByHubsize=function(){return this.clustering.clusterByHubsize.apply(this.clustering,arguments)},n.prototype.clusterOutliers=function(){return this.clustering.clusterOutliers.apply(this.clustering,arguments)},n.prototype.getSeed=function(){return this.layoutEngine.getSeed.apply(this.layoutEngine,arguments)},n.prototype.enableEditMode=function(){return this.manipulation.enableEditMode.apply(this.manipulation,arguments)},n.prototype.disableEditMode=function(){return this.manipulation.disableEditMode.apply(this.manipulation,arguments)},n.prototype.addNodeMode=function(){return this.manipulation.addNodeMode.apply(this.manipulation,arguments)},n.prototype.editNodeMode=function(){return this.manipulation.editNodeMode.apply(this.manipulation,arguments)},n.prototype.addEdgeMode=function(){return this.manipulation.addEdgeMode.apply(this.manipulation,arguments)},n.prototype.editEdgeMode=function(){return this.manipulation.editEdgeMode.apply(this.manipulation,arguments)},n.prototype.deleteSelected=function(){return this.manipulation.deleteSelected.apply(this.manipulation,arguments)},n.prototype.getPositions=function(){return this.nodesHandler.getPositions.apply(this.nodesHandler,arguments)},n.prototype.storePositions=function(){return this.nodesHandler.storePositions.apply(this.nodesHandler,arguments)},n.prototype.getBoundingBox=function(){return this.nodesHandler.getBoundingBox.apply(this.nodesHandler,arguments)},n.prototype.getConnectedNodes=function(t){return void 0!==this.body.nodes[t]?this.nodesHandler.getConnectedNodes.apply(this.nodesHandler,arguments):this.edgesHandler.getConnectedNodes.apply(this.edgesHandler,arguments)},n.prototype.getEdges=function(){return this.nodesHandler.getEdges.apply(this.nodesHandler,arguments)},n.prototype.startSimulation=function(){return this.physics.startSimulation.apply(this.physics,arguments)},n.prototype.stopSimulation=function(){return this.physics.stopSimulation.apply(this.physics,arguments)},n.prototype.stabilize=function(){return this.physics.stabilize.apply(this.physics,arguments)},n.prototype.getSelection=function(){return this.selectionHandler.getSelection.apply(this.selectionHandler,arguments)},n.prototype.getSelectedNodes=function(){return this.selectionHandler.getSelectedNodes.apply(this.selectionHandler,arguments)},n.prototype.getSelectedEdges=function(){return this.selectionHandler.getSelectedEdges.apply(this.selectionHandler,arguments)},n.prototype.getNodeAt=function(){return this.selectionHandler.getNodeAt.apply(this.selectionHandler,arguments)},n.prototype.getEdgeAt=function(){return this.selectionHandler.getEdgeAt.apply(this.selectionHandler,arguments)},n.prototype.selectNodes=function(){return this.selectionHandler.selectNodes.apply(this.selectionHandler,arguments)},n.prototype.selectEdges=function(){return this.selectionHandler.selectEdges.apply(this.selectionHandler,arguments)},n.prototype.unselectAll=function(){return this.selectionHandler.unselectAll.apply(this.selectionHandler,arguments)},n.prototype.redraw=function(){return this.renderer.redraw.apply(this.renderer,arguments)},n.prototype.getScale=function(){return this.view.getScale.apply(this.view,arguments)},n.prototype.getViewPosition=function(){return this.view.getViewPosition.apply(this.view,arguments)},n.prototype.fit=function(){return this.view.fit.apply(this.view,arguments)},n.prototype.moveTo=function(){return this.view.moveTo.apply(this.view,arguments)},n.prototype.focus=function(){return this.view.focus.apply(this.view,arguments)},n.prototype.releaseNode=function(){return this.view.releaseNode.apply(this.view,arguments)},t.exports=n},function(t,e,i){function o(t){this.images={},this.imageBroken={},this.callback=t}o.prototype.load=function(t,e){var i=this.images[t];if(void 0===i){var o=this;i=new Image,i.onload=function(){0===this.width&&(document.body.appendChild(this),this.width=this.offsetWidth,this.height=this.offsetHeight,document.body.removeChild(this)),o.callback&&(o.images[t]=i,o.callback(this))},i.onerror=function(){void 0===e?(console.error("Could not load image:",t),delete this.src,o.callback&&o.callback(this)):o.imageBroken[t]===!0?(console.error("Could not load brokenImage:",e),delete this.src,o.callback&&o.callback(this)):(console.error("Could not load image:",t),this.src=e,o.imageBroken[t]=!0)},i.src=t}return i},t.exports=o},function(t,e,i){function o(t){return I=t,f()}function n(){N=0,z=I.charAt(0)}function s(){N++,z=I.charAt(N)}function r(){return I.charAt(N+1)}function a(t){return B.test(t)}function h(t,e){if(t||(t={}),e)for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t}function d(t,e,i){for(var o=e.split("."),n=t;o.length;){var s=o.shift();o.length?(n[s]||(n[s]={}),n=n[s]):n[s]=i}}function l(t,e){for(var i,o,n=null,s=[t],r=t;r.parent;)s.push(r.parent),r=r.parent;if(r.nodes)for(i=0,o=r.nodes.length;o>i;i++)if(e.id===r.nodes[i].id){n=r.nodes[i];break}for(n||(n={id:e.id},t.node&&(n.attr=h(n.attr,t.node))),i=s.length-1;i>=0;i--){var a=s[i];a.nodes||(a.nodes=[]),-1===a.nodes.indexOf(n)&&a.nodes.push(n)}e.attr&&(n.attr=h(n.attr,e.attr))}function u(t,e){if(t.edges||(t.edges=[]),t.edges.push(e),t.edge){var i=h({},t.edge);e.attr=h(i,e.attr)}}function c(t,e,i,o,n){var s={from:e,to:i,type:o};return t.edge&&(s.attr=h({},t.edge)),s.attr=h(s.attr||{},n),s}function p(){for(L=S.NULL,A="";" "===z||" "===z||"\n"===z||"\r"===z;)s();do{var t=!1;if("#"===z){for(var e=N-1;" "===I.charAt(e)||" "===I.charAt(e);)e--;if("\n"===I.charAt(e)||""===I.charAt(e)){for(;""!=z&&"\n"!=z;)s();t=!0}}if("/"===z&&"/"===r()){for(;""!=z&&"\n"!=z;)s();t=!0}if("/"===z&&"*"===r()){for(;""!=z;){if("*"===z&&"/"===r()){s(),s();break}s()}t=!0}for(;" "===z||" "===z||"\n"===z||"\r"===z;)s()}while(t);if(""===z)return void(L=S.DELIMITER);var i=z+r();if(P[i])return L=S.DELIMITER,A=i,s(),void s();if(P[z])return L=S.DELIMITER,A=z,void s();if(a(z)||"-"===z){for(A+=z,s();a(z);)A+=z,s();return"false"===A?A=!1:"true"===A?A=!0:isNaN(Number(A))||(A=Number(A)),void(L=S.IDENTIFIER)}if('"'===z){for(s();""!=z&&('"'!=z||'"'===z&&'"'===r());)A+=z,'"'===z&&s(),s();if('"'!=z)throw x('End of string " expected');return s(),void(L=S.IDENTIFIER)}for(L=S.UNKNOWN;""!=z;)A+=z,s();throw new SyntaxError('Syntax error in part "'+k(A,30)+'"')}function f(){var t={};if(n(),p(),"strict"===A&&(t.strict=!0,p()),("graph"===A||"digraph"===A)&&(t.type=A,p()),L===S.IDENTIFIER&&(t.id=A,p()),"{"!=A)throw x("Angle bracket { expected");if(p(),m(t),"}"!=A)throw x("Angle bracket } expected");if(p(),""!==A)throw x("End of file expected");return p(),delete t.node,delete t.edge,delete t.graph,t}function m(t){for(;""!==A&&"}"!=A;)v(t),";"===A&&p()}function v(t){var e=g(t);if(e)return void w(t,e);var i=y(t);if(!i){if(L!=S.IDENTIFIER)throw x("Identifier expected");var o=A;if(p(),"="===A){if(p(),L!=S.IDENTIFIER)throw x("Identifier expected");t[o]=A,p()}else b(t,o)}}function g(t){var e=null;if("subgraph"===A&&(e={},e.type="subgraph",p(),L===S.IDENTIFIER&&(e.id=A,p())),"{"===A){if(p(),e||(e={}),e.parent=t,e.node=t.node,e.edge=t.edge,e.graph=t.graph,m(e),"}"!=A)throw x("Angle bracket } expected");p(),delete e.node,delete e.edge,delete e.graph,delete e.parent,t.subgraphs||(t.subgraphs=[]),t.subgraphs.push(e)}return e}function y(t){return"node"===A?(p(),t.node=_(),"node"):"edge"===A?(p(),t.edge=_(),"edge"):"graph"===A?(p(),t.graph=_(),"graph"):null}function b(t,e){var i={id:e},o=_();o&&(i.attr=o),l(t,i),w(t,e)}function w(t,e){for(;"->"===A||"--"===A;){var i,o=A;p();var n=g(t);if(n)i=n;else{if(L!=S.IDENTIFIER)throw x("Identifier or subgraph expected");i=A,l(t,{id:i}),p()}var s=_(),r=c(t,e,i,o,s);u(t,r),e=i}}function _(){for(var t=null;"["===A;){for(p(),t={};""!==A&&"]"!=A;){if(L!=S.IDENTIFIER)throw x("Attribute name expected");var e=A;if(p(),"="!=A)throw x("Equal sign = expected");if(p(),L!=S.IDENTIFIER)throw x("Attribute value expected");var i=A;d(t,e,i),p(),","==A&&p()}if("]"!=A)throw x("Bracket ] expected");p()}return t}function x(t){return new SyntaxError(t+', got "'+k(A,30)+'" (char '+N+")")}function k(t,e){return t.length<=e?t:t.substr(0,27)+"..."}function M(t,e,i){Array.isArray(t)?t.forEach(function(t){Array.isArray(e)?e.forEach(function(e){i(t,e)}):i(t,e)}):Array.isArray(e)?e.forEach(function(e){i(t,e)}):i(t,e)}function O(t,e,i){for(var o=e.split("."),n=o.pop(),s=t,r=0;r":!0,"--":!0},I="",N=0,z="",A="",L=S.NULL,B=/[a-zA-Z_0-9.:#]/;e.parseDOT=o,e.DOTToGraph=T},function(t,e,i){function o(t,e){var i=[],o=[],n={edges:{inheritColor:!1},nodes:{fixed:!1,parseColor:!1}};void 0!==e&&(void 0!==e.fixed&&(n.nodes.fixed=e.fixed),void 0!==e.parseColor&&(n.nodes.parseColor=e.parseColor),void 0!==e.inheritColor&&(n.edges.inheritColor=e.inheritColor));for(var s=t.edges,r=t.nodes,a=0;an&&(e[o+n++]=u[t])});16>n;)e[o+n++]=0;return e}function o(t,e){var i=e||0,o=l;return o[t[i++]]+o[t[i++]]+o[t[i++]]+o[t[i++]]+"-"+o[t[i++]]+o[t[i++]]+"-"+o[t[i++]]+o[t[i++]]+"-"+o[t[i++]]+o[t[i++]]+"-"+o[t[i++]]+o[t[i++]]+o[t[i++]]+o[t[i++]]+o[t[i++]]+o[t[i++]]}function n(t,e,i){var n=e&&i||0,s=e||[];t=t||{};var r=void 0!==t.clockseq?t.clockseq:m,a=void 0!==t.msecs?t.msecs:(new Date).getTime(),h=void 0!==t.nsecs?t.nsecs:g+1,d=a-v+(h-g)/1e4;if(0>d&&void 0===t.clockseq&&(r=r+1&16383),(0>d||a>v)&&void 0===t.nsecs&&(h=0),h>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");v=a,g=h,m=r,a+=122192928e5;var l=(1e4*(268435455&a)+h)%4294967296;s[n++]=l>>>24&255,s[n++]=l>>>16&255,s[n++]=l>>>8&255,s[n++]=255&l;var u=a/4294967296*1e4&268435455;s[n++]=u>>>8&255,s[n++]=255&u,s[n++]=u>>>24&15|16,s[n++]=u>>>16&255,s[n++]=r>>>8|128,s[n++]=255&r;for(var c=t.node||f,p=0;6>p;p++)s[n+p]=c[p];return e?e:o(s)}function s(t,e,i){var n=e&&i||0;"string"==typeof t&&(e="binary"==t?new Array(16):null,t=null),t=t||{};var s=t.random||(t.rng||r)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var a=0;16>a;a++)e[n+a]=s[a];return e||o(s)}var r,a="undefined"!=typeof window?window:"undefined"!=typeof e?e:null;if(a&&a.crypto&&crypto.getRandomValues){var h=new Uint8Array(16);r=function(){return crypto.getRandomValues(h),h}}if(!r){var d=new Array(16);r=function(){for(var t,e=0;16>e;e++)0===(3&e)&&(t=4294967296*Math.random()),d[e]=t>>>((3&e)<<3)&255;return d}}for(var l=[],u={},c=0;256>c;c++)l[c]=(c+256).toString(16).substr(1),u[l[c]]=c;var p=r(),f=[1|p[0],p[1],p[2],p[3],p[4],p[5]],m=16383&(p[6]<<8|p[7]),v=0,g=0,y=s;y.v1=n,y.v4=s,y.parse=i,y.unparse=o,t.exports=y}).call(e,function(){return this}())},function(t,e,i){function o(){}var n=i(69),s=i(41),r=i(48),a=i(57),h=(i(3),i(4),i(17),i(32),i(35)),d=i(67),l=i(15),u=i(27);n(o.prototype),o.prototype._create=function(t){function e(t){i.isActive()&&i.emit("mousewheel",t)}this.dom={},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.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.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.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),this.on("rangechange",this.redraw.bind(this)),this.on("touch",this._onTouch.bind(this)),this.on("pan",this._onDrag.bind(this));var i=this;this.on("change",function(t){t&&1==t.queue?i._redrawTimer||(i._redrawTimer=setTimeout(function(){i._redrawTimer=null,i._redraw()},0)):i._redraw()}),this.hammer=new s(this.dom.root),this.hammer.get("pinch").set({enable:!0}),this.listeners={};var o=["tap","doubletap","press","pinch","pan","panstart","panmove","panend"];if(o.forEach(function(t){var e=function(e){i.isActive()&&i.emit(t,e)};i.hammer.on(t,e),i.listeners[t]=e}),r.onTouch(this.hammer,function(t){i.emit("touch",t)}.bind(this)),r.onRelease(this.hammer,function(t){i.emit("release",t)}.bind(this)),this.dom.root.addEventListener("mousewheel",e),this.dom.root.addEventListener("DOMMouseScroll",e),this.props={root:{},background:{},centerContainer:{},leftContainer:{},rightContainer:{},center:{},left:{},right:{},top:{},bottom:{},border:{},scrollTop:0,scrollTopMin:0},this.customTimes=[],this.touch={},this.redrawCount=0,!t)throw new Error("No container provided");t.appendChild(this.dom.root)},o.prototype.setOptions=function(t){if(t){var e=["width","height","minHeight","maxHeight","autoResize","start","end","clickToUse","dataAttributes","hiddenDates"];if(a.selectiveExtend(e,this.options,t),"orientation"in t&&("string"==typeof t.orientation?this.options.orientation={item:t.orientation,axis:t.orientation}:"object"==typeof t.orientation&&("item"in t.orientation&&(this.options.orientation.item=t.orientation.item),"axis"in t.orientation&&(this.options.orientation.axis=t.orientation.axis))),"both"===this.options.orientation.axis){if(!this.timeAxis2){var i=this.timeAxis2=new h(this.body);i.setOptions=function(t){var e=t?a.extend({},t):{};e.orientation="top",h.prototype.setOptions.call(i,e)},this.components.push(i)}}else if(this.timeAxis2){var o=this.components.indexOf(this.timeAxis2);-1!==o&&this.components.splice(o,1),this.timeAxis2.destroy(),this.timeAxis2=null}if("hiddenDates"in this.options&&l.convertHiddenOptions(this.body,this.options.hiddenDates),"clickToUse"in t&&(t.clickToUse?this.activator||(this.activator=new d(this.dom.root)):this.activator&&(this.activator.destroy(),delete this.activator)),"showCustomTime"in t)throw new Error("Option `showCustomTime` is deprecated. Create a custom time bar via timeline.addCustomTime(time [, id])");this._initAutoResize()}if(this.components.forEach(function(e){return e.setOptions(t)}),this.configurator){this.configurator.setOptions(t.configure);var n=a.deepExtend({},this.options);this.components.forEach(function(t){a.deepExtend(n,t.options)}),this.configurator.setModuleOptions({global:n})}this._redraw()},o.prototype.isActive=function(){return!this.activator||this.activator.active},o.prototype.destroy=function(){this.setItems(null),this.setGroups(null),this.off(),this._stopAutoResize(),this.dom.root.parentNode&&this.dom.root.parentNode.removeChild(this.dom.root),this.dom=null,this.activator&&(this.activator.destroy(),delete this.activator);for(var t in this.listeners)this.listeners.hasOwnProperty(t)&&delete this.listeners[t];this.listeners=null,this.hammer=null,this.components.forEach(function(t){return t.destroy()}),this.body=null},o.prototype.setCustomTime=function(t,e){var i=this.customTimes.filter(function(t){return e===t.options.id});if(0===i.length)throw new Error("No custom time bar found with id "+JSON.stringify(e));i.length>0&&i[0].setCustomTime(t)},o.prototype.getCustomTime=function(t){var e=this.customTimes.filter(function(e){return e.options.id===t});if(0===e.length)throw new Error("No custom time bar found with id "+JSON.stringify(t));return e[0].getCustomTime()},o.prototype.addCustomTime=function(t,e){var i=void 0!==t?a.convert(t,"Date").valueOf():new Date,o=this.customTimes.some(function(t){return t.options.id===e});if(o)throw new Error("A custom time with id "+JSON.stringify(e)+" already exists");var n=new u(this.body,{time:i,id:e});return this.customTimes.push(n),this.components.push(n),this.redraw(),e},o.prototype.removeCustomTime=function(t){var e=this.customTimes.filter(function(e){return e.options.id===t});if(0===e.length)throw new Error("No custom time bar found with id "+JSON.stringify(t));e.forEach(function(t){this.customTimes.splice(this.customTimes.indexOf(t),1),this.components.splice(this.components.indexOf(t),1),t.destroy()}.bind(this))},o.prototype.getVisibleItems=function(){return this.itemSet&&this.itemSet.getVisibleItems()||[]},o.prototype.fit=function(t){var e=this._getDataRange();if(null!==e.start||null!==e.end){var i=t&&void 0!==t.animation?t.animation:!0;this.range.setRange(e.start,e.end,i)}},o.prototype._getDataRange=function(){var t=this.getItemRange(),e=t.min,i=t.max;if(null!=e&&null!=i){var o=i.valueOf()-e.valueOf();0>=o&&(o=864e5),e=new Date(e.valueOf()-.05*o),i=new Date(i.valueOf()+.05*o)}return{start:e,end:i}},o.prototype.setWindow=function(t,e,i){var o;if(1==arguments.length){var n=arguments[0];o=void 0!==n.animation?n.animation:!0,this.range.setRange(n.start,n.end,o)}else o=i&&void 0!==i.animation?i.animation:!0,this.range.setRange(t,e,o)},o.prototype.moveTo=function(t,e){var i=this.range.end-this.range.start,o=a.convert(t,"Date").valueOf(),n=o-i/2,s=o+i/2,r=e&&void 0!==e.animation?e.animation:!0;this.range.setRange(n,s,r)},o.prototype.getWindow=function(){var t=this.range.getRange();return{start:new Date(t.start),end:new Date(t.end)}},o.prototype.redraw=function(){this._redraw()},o.prototype._redraw=function(){var t=!1,e=this.options,i=this.props,o=this.dom;if(o){l.updateHiddenDates(this.body,this.options.hiddenDates),"top"==e.orientation?(a.addClassName(o.root,"vis-top"),a.removeClassName(o.root,"vis-bottom")):(a.removeClassName(o.root,"vis-top"),a.addClassName(o.root,"vis-bottom")),o.root.style.maxHeight=a.option.asSize(e.maxHeight,""),o.root.style.minHeight=a.option.asSize(e.minHeight,""),o.root.style.width=a.option.asSize(e.width,""),i.border.left=(o.centerContainer.offsetWidth-o.centerContainer.clientWidth)/2,i.border.right=i.border.left,i.border.top=(o.centerContainer.offsetHeight-o.centerContainer.clientHeight)/2,i.border.bottom=i.border.top;var n=o.root.offsetHeight-o.root.clientHeight,s=o.root.offsetWidth-o.root.clientWidth;0===o.centerContainer.clientHeight&&(i.border.left=i.border.top,i.border.right=i.border.left),0===o.root.clientHeight&&(s=n),i.center.height=o.center.offsetHeight,i.left.height=o.left.offsetHeight,i.right.height=o.right.offsetHeight,i.top.height=o.top.clientHeight||-i.border.top,i.bottom.height=o.bottom.clientHeight||-i.border.bottom;var r=Math.max(i.left.height,i.center.height,i.right.height),h=i.top.height+r+i.bottom.height+n+i.border.top+i.border.bottom;o.root.style.height=a.option.asSize(e.height,h+"px"),i.root.height=o.root.offsetHeight,i.background.height=i.root.height-n;var d=i.root.height-i.top.height-i.bottom.height-n;i.centerContainer.height=d,i.leftContainer.height=d,i.rightContainer.height=i.leftContainer.height,i.root.width=o.root.offsetWidth,i.background.width=i.root.width-s,i.left.width=o.leftContainer.clientWidth||-i.border.left,i.leftContainer.width=i.left.width,i.right.width=o.rightContainer.clientWidth||-i.border.right,i.rightContainer.width=i.right.width;var u=i.root.width-i.left.width-i.right.width-s;i.center.width=u,i.centerContainer.width=u,i.top.width=u,i.bottom.width=u,o.background.style.height=i.background.height+"px",o.backgroundVertical.style.height=i.background.height+"px",o.backgroundHorizontal.style.height=i.centerContainer.height+"px",o.centerContainer.style.height=i.centerContainer.height+"px",o.leftContainer.style.height=i.leftContainer.height+"px",o.rightContainer.style.height=i.rightContainer.height+"px",o.background.style.width=i.background.width+"px",o.backgroundVertical.style.width=i.centerContainer.width+"px",o.backgroundHorizontal.style.width=i.background.width+"px",o.centerContainer.style.width=i.center.width+"px",o.top.style.width=i.top.width+"px",o.bottom.style.width=i.bottom.width+"px",o.background.style.left="0",o.background.style.top="0",o.backgroundVertical.style.left=i.left.width+i.border.left+"px",o.backgroundVertical.style.top="0",o.backgroundHorizontal.style.left="0",o.backgroundHorizontal.style.top=i.top.height+"px",o.centerContainer.style.left=i.left.width+"px",o.centerContainer.style.top=i.top.height+"px",o.leftContainer.style.left="0",o.leftContainer.style.top=i.top.height+"px",o.rightContainer.style.left=i.left.width+i.center.width+"px",o.rightContainer.style.top=i.top.height+"px",o.top.style.left=i.left.width+"px",o.top.style.top="0",o.bottom.style.left=i.left.width+"px",o.bottom.style.top=i.top.height+i.centerContainer.height+"px",this._updateScrollTop();var c=this.props.scrollTop;"top"!=e.orientation.item&&(c+=Math.max(this.props.centerContainer.height-this.props.center.height-this.props.border.top-this.props.border.bottom,0)),o.center.style.left="0",o.center.style.top=c+"px",o.left.style.left="0",o.left.style.top=c+"px",o.right.style.left="0",o.right.style.top=c+"px";var p=0==this.props.scrollTop?"hidden":"",f=this.props.scrollTop==this.props.scrollTopMin?"hidden":"";if(o.shadowTop.style.visibility=p,o.shadowBottom.style.visibility=f,o.shadowTopLeft.style.visibility=p,o.shadowBottomLeft.style.visibility=f,o.shadowTopRight.style.visibility=p,o.shadowBottomRight.style.visibility=f,this.components.forEach(function(e){t=e.redraw()||t}),t){var m=3;this.redrawCount0&&(this.props.scrollTop=0),this.props.scrollTop0&&this._makeItem([]),this._makeHeader(n),this._handleObject(this.configureOptions[n],[n])),i++);this.options.showButton===!0&&!function(){var e=document.createElement("div");e.className="vis-network-configuration button",e.innerHTML="generate options",e.onclick=function(){t._printOptions()},e.onmouseover=function(){e.className="vis-network-configuration button hover"},e.onmouseout=function(){e.className="vis-network-configuration button"},t.optionsContainer=document.createElement("div"),t.optionsContainer.className="vis-network-configuration vis-option-container",t.domElements.push(t.optionsContainer),t.domElements.push(e)}(),this._push(),this.colorPicker.insertTo(this.container)}},{key:"_push",value:function(){this.wrapper=document.createElement("div"),this.wrapper.className="vis-network-configuration-wrapper",this.container.appendChild(this.wrapper);for(var t=0;t1?i-1:0),n=1;i>n;n++)o[n-1]=arguments[n];this.allowCreation===!0&&!function(){var i=document.createElement("div");i.className="vis-network-configuration item s"+t.length,o.forEach(function(t){i.appendChild(t)}),e.domElements.push(i)}()}},{key:"_makeHeader",value:function(t){var e=document.createElement("div");e.className="vis-network-configuration header",e.innerHTML=t,this._makeItem([],e)}},{key:"_makeLabel",value:function(t,e){var i=void 0===arguments[2]?!1:arguments[2],o=document.createElement("div");return o.className="vis-network-configuration label s"+e.length,i===!0?o.innerHTML=""+t+":":o.innerHTML=t+":",o}},{key:"_makeDropdown",value:function(t,e,i){var o=document.createElement("select");o.className="vis-network-configuration select";var n=0;void 0!==e&&-1!==t.indexOf(e)&&(n=t.indexOf(e));for(var s=0;s.1*e&&(a.min=e/10),2*e>s&&1!==s&&(a.max=2*e),a.value=e):a.value=o;var h=document.createElement("input");h.className="vis-network-configuration rangeinput",h.value=a.value;var d=this;a.onchange=function(){h.value=this.value,d._update(Number(this.value),i)},a.oninput=function(){h.value=this.value};var l=this._makeLabel(i[i.length-1],i);this._makeItem(i,l,a,h)}},{key:"_makeCheckbox",value:function(t,e,i){var o=document.createElement("input");o.type="checkbox",o.className="vis-network-configuration checkbox",o.checked=t,void 0!==e&&(o.checked=e,e!==t&&("object"==typeof t?e!==t.enabled&&this.changedOptions.push({path:i,value:e}):this.changedOptions.push({path:i,value:e})));var n=this;o.onchange=function(){n._update(this.checked,i)};var s=this._makeLabel(i[i.length-1],i);this._makeItem(i,s,o)}},{key:"_makeTextInput",value:function(t,e,i){var o=document.createElement("input");o.type="text",o.className="vis-network-configuration text",o.value=e,e!==t&&this.changedOptions.push({path:i,value:e});var n=this;o.onchange=function(){n._update(this.value,i)};var s=this._makeLabel(i[i.length-1],i);this._makeItem(i,s,o)}},{key:"_makeColorField",value:function(t,e,i){var o=this,n=t[1],s=document.createElement("div");e=void 0===e?n:e,"none"!==e?(s.className="vis-network-configuration colorBlock",s.style.backgroundColor=e):s.className="vis-network-configuration colorBlock none",e=void 0===e?n:e,s.onclick=function(){o._showColorPicker(e,s,i)};var r=this._makeLabel(i[i.length-1],i);this._makeItem(i,r,s)}},{key:"_showColorPicker",value:function(t,e,i){var o=this,n=e.getBoundingClientRect(),s=document.body.getBoundingClientRect(),r=n.left+n.width+5,a=n.top-s.top+.5*n.height;this.colorPicker.show(r,a),this.colorPicker.setColor(t),this.colorPicker.setCallback(function(t){var n="rgba("+t.r+","+t.g+","+t.b+","+t.a+")";e.style.backgroundColor=n,o._update(n,i)})}},{key:"_handleObject",value:function(t){var e=void 0===arguments[1]?[]:arguments[1],i=void 0===arguments[2]?!1:arguments[2],o=!1,n=this.options.filter,s=!1;for(var r in t)if(t.hasOwnProperty(r)){o=!0;var a=t[r],d=h.copyAndExtendArray(e,r);if("function"==typeof n&&(o=n(r,e),o===!1&&!(a instanceof Array)&&"string"!=typeof a&&"boolean"!=typeof a&&a instanceof Object&&(this.allowCreation=!1,o=this._handleObject(a,d,!0),this.allowCreation=i===!1)),o!==!1){s=!0;var l=this._getValue(d);if(a instanceof Array)this._handleArray(a,l,d);else if("string"==typeof a)this._makeTextInput(a,l,d);else if("boolean"==typeof a)this._makeCheckbox(a,l,d);else if(a instanceof Object){var u=!0;if(-1!==e.indexOf("physics")&&this.moduleOptions.physics.solver!==r&&(u=!1),u===!0)if(void 0!==a.enabled){var c=h.copyAndExtendArray(d,"enabled"),p=this._getValue(c);if(p===!0){var f=this._makeLabel(r,d,!0);this._makeItem(d,f),s=this._handleObject(a,d)||s}else this._makeCheckbox(a,p,d)}else{var f=this._makeLabel(r,d,!0);this._makeItem(d,f),s=this._handleObject(a,d)||s}}else console.error("dont know how to handle",a,r,d)}}return s}},{key:"_handleArray",value:function(t,e,i){"string"==typeof t[0]&&"color"===t[0]?(this._makeColorField(t,e,i),t[1]!==e&&this.changedOptions.push({path:i,value:e})):"string"==typeof t[0]?(this._makeDropdown(t,e,i),t[0]!==e&&this.changedOptions.push({path:i,value:e})):"number"==typeof t[0]&&(this._makeRange(t,e,i),t[0]!==e&&this.changedOptions.push({path:i,value:Number(e)}))}},{key:"_update",value:function(t,e){var i=this._constructOptions(t,e);this.parent.setOptions(i)}},{key:"_constructOptions",value:function(t,e){var i=void 0===arguments[2]?{}:arguments[2],o=i;t="true"===t?!0:t,t="false"===t?!1:t;for(var n=0;nvar options = "+JSON.stringify(t,null,2)+""}}]),t}();e["default"]=d,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;is.distance?console.log('%cUnknown option detected: "'+e+'" in '+t.printLocation(n.path,e,"")+"Perhaps it was misplaced? Matching option found at: "+t.printLocation(s.path,s.closestMatch,""),h):n.distance<=d?console.log('%cUnknown option detected: "'+e+'". Did you mean "'+n.closestMatch+'"?'+t.printLocation(n.path,e),h):console.log('%cUnknown option detected: "'+e+'". Did you mean one of these: '+t.print(Object.keys(i))+t.printLocation(o,e),h),r=!0}},{key:"findInOptions",value:function(e,i,o){var n=void 0===arguments[3]?!1:arguments[3],r=1e9,a="",h=[],d=e.toLowerCase(),l=void 0;for(var u in i){var c=void 0;if(void 0!==i[u].__type__&&n===!0){var p=t.findInOptions(e,i[u],s.copyAndExtendArray(o,u));r>p.distance&&(a=p.closestMatch,h=p.path,r=p.distance,l=p.indexMatch)}else-1!==u.toLowerCase().indexOf(d)&&(l=u),c=t.levenshteinDistance(e,u),r>c&&(a=u,h=s.copyArray(o),r=c)}return{closestMatch:a,path:h,distance:r,indexMatch:l}}},{key:"printLocation",value:function(t,e){for(var i=void 0===arguments[2]?"Problem value found at: \n":arguments[2],o="\n\n"+i+"options = {\n",n=0;ns;s++)o+=" ";o+=t[n]+": {\n"}for(var s=0;st[o].y?t[o].y:e,i=i0){t.sort(function(t,e){return t.x===e.x?t.groupIde[s].y?e[s].y:o,n=nt[r].accumulatedNegative?t[r].accumulatedNegative:o,o=o>t[r].accumulatedPositive?t[r].accumulatedPositive:o,n=n0&&(i=Math.min(i,Math.abs(e[o-1].x-e[o].x))),0===i&&(void 0===t[e[o].x]&&(t[e[o].x]={amount:0,resolved:0,accumulatedPositive:0,accumulatedNegative:0}),t[e[o].x].amount+=1)},o.prototype.draw=function(t,e,i){if(null!=t&&t.length>0){var r,a,h=Number(i.svg.style.height.replace("px",""));if(r=n.getSVGElement("path",i.svgElements,i.svg),r.setAttributeNS(null,"class",e.className),void 0!==e.style&&r.setAttributeNS(null,"style",e.style),a=1==e.options.interpolation.enabled?o._catmullRom(t,e):o._linear(t),1==e.options.shaded.enabled){var d,l=n.getSVGElement("path",i.svgElements,i.svg);d="top"==e.options.shaded.orientation?"M"+t[0].x+",0 "+a+"L"+t[t.length-1].x+",0":"M"+t[0].x+","+h+" "+a+"L"+t[t.length-1].x+","+h,l.setAttributeNS(null,"class",e.className+" vis-fill"),void 0!==e.options.shaded.style&&l.setAttributeNS(null,"style",e.options.shaded.style),l.setAttributeNS(null,"d",d)}r.setAttributeNS(null,"d","M"+a),1==e.options.drawPoints.enabled&&s.draw(t,e,i)}},o._catmullRomUniform=function(t){for(var e,i,o,n,s,r,a=Math.round(t[0].x)+","+Math.round(t[0].y)+" ",h=1/6,d=t.length,l=0;d-1>l;l++)e=0==l?t[0]:t[l-1],i=t[l],o=t[l+1],n=d>l+2?t[l+2]:o,s={x:(-e.x+6*i.x+o.x)*h,y:(-e.y+6*i.y+o.y)*h},r={x:(i.x+6*o.x-n.x)*h,y:(i.y+6*o.y-n.y)*h},a+="C"+s.x+","+s.y+" "+r.x+","+r.y+" "+o.x+","+o.y+" ";return a},o._catmullRom=function(t,e){var i=e.options.interpolation.alpha;if(0==i||void 0===i)return this._catmullRomUniform(t);for(var o,n,s,r,a,h,d,l,u,c,p,f,m,v,g,y,b,w,_,x=Math.round(t[0].x)+","+Math.round(t[0].y)+" ",k=t.length,M=0;k-1>M;M++)o=0==M?t[0]:t[M-1],n=t[M],s=t[M+1],r=k>M+2?t[M+2]:s,d=Math.sqrt(Math.pow(o.x-n.x,2)+Math.pow(o.y-n.y,2)),l=Math.sqrt(Math.pow(n.x-s.x,2)+Math.pow(n.y-s.y,2)),u=Math.sqrt(Math.pow(s.x-r.x,2)+Math.pow(s.y-r.y,2)),v=Math.pow(u,i),y=Math.pow(u,2*i),g=Math.pow(l,i),b=Math.pow(l,2*i),_=Math.pow(d,i),w=Math.pow(d,2*i),c=2*w+3*_*g+b,p=2*y+3*v*g+b,f=3*_*(_+g),f>0&&(f=1/f),m=3*v*(v+g),m>0&&(m=1/m),a={x:(-b*o.x+c*n.x+w*s.x)*f,y:(-b*o.y+c*n.y+w*s.y)*f},h={x:(y*n.x+p*s.x-b*r.x)*m,y:(y*n.y+p*s.y-b*r.y)*m},0==a.x&&0==a.y&&(a=n),0==h.x&&0==h.y&&(h=s),x+="C"+a.x+","+a.y+" "+h.x+","+h.y+" "+s.x+","+s.y+" ";return x},o._linear=function(t){for(var e="",i=0;it[o].y?t[o].y:e,i=i0&&(r=Math.min(r,Math.abs(c[l-1].x-a))),h=o._getSafeDrawData(r,d,m);else{var g=l+(p[a].amount-p[a].resolved),y=l-(p[a].resolved+1);g0&&(r=Math.min(r,Math.abs(c[y].x-a))),h=o._getSafeDrawData(r,d,m),p[a].resolved+=1,d.options.stack===!0?c[l].y0&&(i=Math.min(i,Math.abs(e[o-1].x-e[o].x))),0===i&&(void 0===t[e[o].x]&&(t[e[o].x]={amount:0,resolved:0,accumulatedPositive:0,accumulatedNegative:0}),t[e[o].x].amount+=1)},o._getSafeDrawData=function(t,e,i){var o,n;return t0?(o=i>t?i:t,n=0,"left"===e.options.barChart.align?n-=.5*t:"right"===e.options.barChart.align&&(n+=.5*t)):(o=e.options.barChart.width,n=0,"left"===e.options.barChart.align?n-=.5*e.options.barChart.width:"right"===e.options.barChart.align&&(n+=.5*e.options.barChart.width)),{width:o,offset:n}},o.getStackedYRange=function(t,e,i,n,s){if(t.length>0){t.sort(function(t,e){return t.x===e.x?t.groupIde[s].y?e[s].y:o,n=nt[r].accumulatedNegative?t[r].accumulatedNegative:o,o=o>t[r].accumulatedPositive?t[r].accumulatedPositive:o,n=nt[o].y?t[o].y:e,i=i0){var i=this.groupIndex%this.groupsArray.length;this.groupIndex++,e={},e.color=this.groups[this.groupsArray[i]],this.groups[t]=e}else{var i=this.defaultIndex%this.defaultGroups.length;this.defaultIndex++,e={},e.color=this.defaultGroups[i],this.groups[t]=e}return e}},{key:"add",value:function(t,e){return this.groups[t]=e,this.groupsArray.push(t),e}}]),t}();e["default"]=r,t.exports=e["default"]},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function t(t,e){for(var i=0;i1&&(this.startedStabilization=!1),this.stopSimulation())}},{key:"_emitStabilized",value:function(){var t=this;this.stabilizationIterations>1&&setTimeout(function(){t.body.emitter.emit("stabilized",{iterations:t.stabilizationIterations}),t.stabilizationIterations=0},0)}},{key:"physicsTick",value:function(){this.stabilized===!1&&(this.calculateForces(),this.stabilized=this.moveNodes(),this.stabilized===!0?this.revert():this.startedStabilization===!1&&(this.body.emitter.emit("startStabilizing"),this.startedStabilization=!0),this.stabilizationIterations++)}},{key:"updatePhysicsData",value:function(){this.physicsBody.forces={},this.physicsBody.physicsNodeIndices=[],this.physicsBody.physicsEdgeIndices=[];var t=this.body.nodes,e=this.body.edges;for(var i in t)t.hasOwnProperty(i)&&t[i].options.physics===!0&&this.physicsBody.physicsNodeIndices.push(i);for(var o in e)e.hasOwnProperty(o)&&e[o].options.physics===!0&&this.physicsBody.physicsEdgeIndices.push(o);for(var n=0;na&&o===!0,t=!0}return t===!0?n>.5*this.options.maxVelocity?!1:o:!0}},{key:"_performStep",value:function(t,e){var i=this.body.nodes[t],o=this.options.timestep,n=this.physicsBody.forces,s=this.physicsBody.velocities;if(this.previousStates[t]={x:i.x,y:i.y,vx:s[t].x,vy:s[t].y},i.options.fixed.x===!1){var r=this.modelOptions.damping*s[t].x,a=(n[t].x-r)/i.options.mass;s[t].x+=a*o,s[t].x=Math.abs(s[t].x)>e?s[t].x>0?e:-e:s[t].x,i.x+=s[t].x*o}else n[t].x=0,s[t].x=0;if(i.options.fixed.y===!1){var h=this.modelOptions.damping*s[t].y,d=(n[t].y-h)/i.options.mass;s[t].y+=d*o,s[t].y=Math.abs(s[t].y)>e?s[t].y>0?e:-e:s[t].y,i.y+=s[t].y*o}else n[t].y=0,s[t].y=0;var l=Math.sqrt(Math.pow(s[t].x,2)+Math.pow(s[t].y,2));return l}},{key:"calculateForces",value:function(){this.gravitySolver.solve(),this.nodesSolver.solve(),this.edgesSolver.solve()}},{key:"_freezeNodes",value:function(){var t=this.body.nodes;for(var e in t)t.hasOwnProperty(e)&&t[e].x&&t[e].y&&(this.freezeCache[e]={x:t[e].options.fixed.x,y:t[e].options.fixed.y},t[e].options.fixed.x=!0,t[e].options.fixed.y=!0)}},{key:"_restoreFrozenNodes",value:function(){var t=this.body.nodes;for(var e in t)t.hasOwnProperty(e)&&void 0!==this.freezeCache[e]&&(t[e].options.fixed.x=this.freezeCache[e].x,t[e].options.fixed.y=this.freezeCache[e].y);this.freezeCache={}}},{key:"stabilize",value:function(){var t=this,e=void 0===arguments[0]?this.options.stabilization.iterations:arguments[0];"number"!=typeof e&&(console.log("The stabilize method needs a numeric amount of iterations. Switching to default: ",this.options.stabilization.iterations),e=this.options.stabilization.iterations),this.body.emitter.emit("_resizeNodes"),this.stopSimulation(),this.stabilized=!1,this.body.emitter.emit("_blockRedrawRequests"),this.targetIterations=e,this.options.stabilization.onlyDynamicEdges===!0&&this._freezeNodes(),this.stabilizationIterations=0,setTimeout(function(){return t._stabilizationBatch()},0)}},{key:"_stabilizationBatch",value:function(){for(var t=0;this.stabilized===!1&&ti;i++)if(t[i]!=e[i])return!1;return!0},e.convert=function(t,i){var n;if(void 0===t)return void 0;if(null===t)return null;if(!i)return t;if("string"!=typeof i&&!(i instanceof String))throw new Error("Type must be a string");switch(i){case"boolean":case"Boolean":return Boolean(t);case"number":case"Number":return Number(t.valueOf());case"string":case"String":return String(t);case"Date":if(e.isNumber(t))return new Date(t);if(t instanceof Date)return new Date(t.valueOf());if(o.isMoment(t))return new Date(t.valueOf());if(e.isString(t))return n=s.exec(t),n?new Date(Number(n[1])):o(t).toDate();throw new Error("Cannot convert object of type "+e.getType(t)+" to type Date");case"Moment":if(e.isNumber(t))return o(t);if(t instanceof Date)return o(t.valueOf());if(o.isMoment(t))return o(t);if(e.isString(t))return n=s.exec(t),o(n?Number(n[1]):t);throw new Error("Cannot convert object of type "+e.getType(t)+" to type Date");case"ISODate":if(e.isNumber(t))return new Date(t);if(t instanceof Date)return t.toISOString();if(o.isMoment(t))return t.toDate().toISOString();if(e.isString(t))return n=s.exec(t),n?new Date(Number(n[1])).toISOString():new Date(t).toISOString();throw new Error("Cannot convert object of type "+e.getType(t)+" to type ISODate");case"ASPDate":if(e.isNumber(t))return"/Date("+t+")/";if(t instanceof Date)return"/Date("+t.valueOf()+")/";if(e.isString(t)){n=s.exec(t);var r;return r=n?new Date(Number(n[1])).valueOf():new Date(t).valueOf(),"/Date("+r+")/"}throw new Error("Cannot convert object of type "+e.getType(t)+" to type ASPDate");default:throw new Error('Unknown type "'+i+'"')}};var s=/^\/?Date\((\-?\d+)/i;e.getType=function(t){var e=typeof t;return"object"==e?null===t?"null":t instanceof Boolean?"Boolean":t instanceof Number?"Number":t instanceof String?"String":Array.isArray(t)?"Array":t instanceof Date?"Date":"Object":"number"==e?"Number":"boolean"==e?"Boolean":"string"==e?"String":void 0===e?"undefined":e},e.copyAndExtendArray=function(t,e){for(var i=[],o=0;oi;i++)e(t[i],i,t);else for(i in t)t.hasOwnProperty(i)&&e(t[i],i,t)},e.toArray=function(t){var e=[];for(var i in t)t.hasOwnProperty(i)&&e.push(t[i]);return e},e.updateProperty=function(t,e,i){return t[e]!==i?(t[e]=i,!0):!1},e.addEventListener=function(t,e,i,o){t.addEventListener?(void 0===o&&(o=!1),"mousewheel"===e&&navigator.userAgent.indexOf("Firefox")>=0&&(e="DOMMouseScroll"),t.addEventListener(e,i,o)):t.attachEvent("on"+e,i)},e.removeEventListener=function(t,e,i,o){t.removeEventListener?(void 0===o&&(o=!1),"mousewheel"===e&&navigator.userAgent.indexOf("Firefox")>=0&&(e="DOMMouseScroll"),t.removeEventListener(e,i,o)):t.detachEvent("on"+e,i)},e.preventDefault=function(t){t||(t=window.event),t.preventDefault?t.preventDefault():t.returnValue=!1},e.getTarget=function(t){t||(t=window.event);var e;return t.target?e=t.target:t.srcElement&&(e=t.srcElement),void 0!=e.nodeType&&3==e.nodeType&&(e=e.parentNode),e},e.hasParent=function(t,e){for(var i=t;i;){if(i===e)return!0;i=i.parentNode}return!1},e.option={},e.option.asBoolean=function(t,e){return"function"==typeof t&&(t=t()),null!=t?0!=t:e||null},e.option.asNumber=function(t,e){return"function"==typeof t&&(t=t()),null!=t?Number(t)||e||null:e||null},e.option.asString=function(t,e){return"function"==typeof t&&(t=t()),null!=t?String(t):e||null},e.option.asSize=function(t,i){return"function"==typeof t&&(t=t()),e.isString(t)?t:e.isNumber(t)?t+"px":i||null},e.option.asElement=function(t,e){return"function"==typeof t&&(t=t()),t||e||null},e.hexToRGB=function(t){var e=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(e,function(t,e,i,o){return e+e+i+i+o+o});var i=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return i?{r:parseInt(i[1],16),g:parseInt(i[2],16),b:parseInt(i[3],16)}:null},e.overrideOpacity=function(t,i){if(-1!=t.indexOf("rgba"))return t;if(-1!=t.indexOf("rgb")){var o=t.substr(t.indexOf("(")+1).replace(")","").split(",");return"rgba("+o[0]+","+o[1]+","+o[2]+","+i+")"}var o=e.hexToRGB(t);return null==o?t:"rgba("+o.r+","+o.g+","+o.b+","+i+")"},e.RGBToHex=function(t,e,i){return"#"+((1<<24)+(t<<16)+(e<<8)+i).toString(16).slice(1)},e.parseColor=function(t){var i;if(e.isString(t)===!0){if(e.isValidRGB(t)===!0){var o=t.substr(4).substr(0,t.length-5).split(",").map(function(t){return parseInt(t)});t=e.RGBToHex(o[0],o[1],o[2])}if(e.isValidHex(t)===!0){var n=e.hexToHSV(t),s={h:n.h,s:.8*n.s,v:Math.min(1,1.02*n.v)},r={h:n.h,s:Math.min(1,1.25*n.s),v:.8*n.v},a=e.HSVToHex(r.h,r.s,r.v),h=e.HSVToHex(s.h,s.s,s.v);i={background:t,border:a,highlight:{background:h,border:a},hover:{background:h,border:a}}}else i={background:t,border:t,highlight:{background:t,border:t},hover:{background:t,border:t}}}else i={},i.background=t.background||void 0,i.border=t.border||void 0,e.isString(t.highlight)?i.highlight={border:t.highlight,background:t.highlight}:(i.highlight={},i.highlight.background=t.highlight&&t.highlight.background||void 0,i.highlight.border=t.highlight&&t.highlight.border||void 0),e.isString(t.hover)?i.hover={border:t.hover,background:t.hover}:(i.hover={},i.hover.background=t.hover&&t.hover.background||void 0,i.hover.border=t.hover&&t.hover.border||void 0);return i},e.RGBToHSV=function(t,e,i){t/=255,e/=255,i/=255;var o=Math.min(t,Math.min(e,i)),n=Math.max(t,Math.max(e,i));if(o==n)return{h:0,s:0,v:o};var s=t==o?e-i:i==o?t-e:i-t,r=t==o?3:i==o?1:5,a=60*(r-s/(n-o))/360,h=(n-o)/n,d=n;return{h:a,s:h,v:d}};var r={split:function(t){var e={};return t.split(";").forEach(function(t){if(""!=t.trim()){var i=t.split(":"),o=i[0].trim(),n=i[1].trim();e[o]=n}}),e},join:function(t){return Object.keys(t).map(function(e){return e+": "+t[e]}).join("; ")}};e.addCssText=function(t,i){var o=r.split(t.style.cssText),n=r.split(i),s=e.extend(o,n);t.style.cssText=r.join(s)},e.removeCssText=function(t,e){var i=r.split(t.style.cssText),o=r.split(e);for(var n in o)o.hasOwnProperty(n)&&delete i[n];t.style.cssText=r.join(i)},e.HSVToRGB=function(t,e,i){var o,n,s,r=Math.floor(6*t),a=6*t-r,h=i*(1-e),d=i*(1-a*e),l=i*(1-(1-a)*e);switch(r%6){case 0:o=i,n=l,s=h;break;case 1:o=d,n=i,s=h;break;case 2:o=h,n=i,s=l;break;case 3:o=h,n=d,s=i;break;case 4:o=l,n=h,s=i;break;case 5:o=i,n=h,s=d}return{r:Math.floor(255*o),g:Math.floor(255*n),b:Math.floor(255*s)}},e.HSVToHex=function(t,i,o){var n=e.HSVToRGB(t,i,o);return e.RGBToHex(n.r,n.g,n.b)},e.hexToHSV=function(t){var i=e.hexToRGB(t);return e.RGBToHSV(i.r,i.g,i.b)},e.isValidHex=function(t){var e=/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(t);return e},e.isValidRGB=function(t){t=t.replace(" ","");var e=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(t);return e},e.isValidRGBA=function(t){ -t=t.replace(" ","");var e=/rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),(.{1,3})\)/i.test(t);return e},e.selectiveBridgeObject=function(t,i){if("object"==typeof i){for(var o=Object.create(i),n=0;n=r&&n>s;){var h=Math.floor((r+a)/2),d=t[h],l=void 0===o?d[i]:d[i][o],u=e(l);if(0==u)return h;-1==u?r=h+1:a=h-1,s++}return-1},e.binarySearchValue=function(t,e,i,o){for(var n,s,r,a,h=1e4,d=0,l=0,u=t.length-1;u>=l&&h>d;){if(a=Math.floor(.5*(u+l)),n=t[Math.max(0,a-1)][i],s=t[a][i],r=t[Math.min(t.length-1,a+1)][i],s==e)return a;if(e>n&&s>e)return"before"==o?Math.max(0,a-1):a;if(e>s&&r>e)return"before"==o?a:Math.min(t.length-1,a+1);e>s?l=a+1:u=a-1,d++}return-1},e.easingFunctions={linear:function(t){return t},easeInQuad:function(t){return t*t},easeOutQuad:function(t){return t*(2-t)},easeInOutQuad:function(t){return.5>t?2*t*t:-1+(4-2*t)*t},easeInCubic:function(t){return t*t*t},easeOutCubic:function(t){return--t*t*t+1},easeInOutCubic:function(t){return.5>t?4*t*t*t:(t-1)*(2*t-2)*(2*t-2)+1},easeInQuart:function(t){return t*t*t*t},easeOutQuart:function(t){return 1- --t*t*t*t},easeInOutQuart:function(t){return.5>t?8*t*t*t*t:1-8*--t*t*t*t},easeInQuint:function(t){return t*t*t*t*t},easeOutQuint:function(t){return 1+--t*t*t*t*t},easeInOutQuint:function(t){return.5>t?16*t*t*t*t*t:1+16*--t*t*t*t*t}}},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;i0,t.renderTimer=void 0}),this.body.emitter.on("destroy",function(){t.renderRequests=0,t.renderingActive=!1,t.requiresTimeout===!0?clearTimeout(t.renderTimer):cancelAnimationFrame(t.renderTimer),t.body.emitter.off()})}},{key:"setOptions",value:function(t){if(void 0!==t){var e=["hideEdgesOnDrag","hideNodesOnDrag"];s.selectiveDeepExtend(e,this.options,t)}}},{key:"_startRendering",value:function(){this.renderingActive===!0&&void 0===this.renderTimer&&(this.requiresTimeout===!0?this.renderTimer=window.setTimeout(this._renderStep.bind(this),this.simulationInterval):this.renderTimer=window.requestAnimationFrame(this._renderStep.bind(this)))}},{key:"_renderStep",value:function(){this.renderingActive===!0&&(this.renderTimer=void 0,this.requiresTimeout===!0&&this._startRendering(),this._redraw(),this.requiresTimeout===!1&&this._startRendering())}},{key:"redraw",value:function(){this.body.emitter.emit("setSize"),this._redraw()}},{key:"_requestRedraw",value:function(){this.redrawRequested!==!0&&this.renderingActive===!1&&this.allowRedrawRequests===!0&&(this.redrawRequested=!0,this.requiresTimeout===!0?window.setTimeout(this._redraw.bind(this,!1),0):window.requestAnimationFrame(this._redraw.bind(this,!1)))}},{key:"_redraw",value:function(){var t=void 0===arguments[0]?!1:arguments[0];this.body.emitter.emit("initRedraw"),this.redrawRequested=!1;var e=this.canvas.frame.canvas.getContext("2d");(0===this.canvas.frame.canvas.width||0===this.canvas.frame.canvas.height)&&this.canvas.setSize(),void 0===this.pixelRatio&&(this.pixelRatio=(window.devicePixelRatio||1)/(e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1)),e.setTransform(this.pixelRatio,0,0,this.pixelRatio,0,0);var i=this.canvas.frame.canvas.clientWidth,o=this.canvas.frame.canvas.clientHeight;e.clearRect(0,0,i,o),e.save(),e.translate(this.body.view.translation.x,this.body.view.translation.y),e.scale(this.body.view.scale,this.body.view.scale),e.beginPath(),this.body.emitter.emit("beforeDrawing",e),e.closePath(),t===!1&&(this.dragging===!1||this.dragging===!0&&this.options.hideEdgesOnDrag===!1)&&this._drawEdges(e),(this.dragging===!1||this.dragging===!0&&this.options.hideNodesOnDrag===!1)&&this._drawNodes(e,t),this.controlNodesActive===!0&&this._drawControlNodes(e),e.beginPath(),this.body.emitter.emit("afterDrawing",e),e.closePath(),e.restore(),t===!0&&e.clearRect(0,0,i,o)}},{key:"_resizeNodes",value:function(){var t=this.canvas.frame.canvas.getContext("2d");void 0===this.pixelRatio&&(this.pixelRatio=(window.devicePixelRatio||1)/(t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1)),t.setTransform(this.pixelRatio,0,0,this.pixelRatio,0,0),t.save(),t.translate(this.body.view.translation.x,this.body.view.translation.y),t.scale(this.body.view.scale,this.body.view.scale);var e=this.body.nodes,i=void 0;for(var o in e)e.hasOwnProperty(o)&&(i=e[o],i.resize(t),i.updateBoundingBox(t));t.restore()}},{key:"_drawNodes",value:function(t){for(var e=void 0===arguments[1]?!1:arguments[1],i=this.body.nodes,o=this.body.nodeIndices,n=void 0,s=[],r=20,a=this.canvas.DOMtoCanvas({x:-r,y:-r}),h=this.canvas.DOMtoCanvas({x:this.canvas.frame.canvas.clientWidth+r,y:this.canvas.frame.canvas.clientHeight+r}),d={top:a.y,left:a.x,bottom:h.y,right:h.x},l=0;l0)for(var r=0;rt.shape.boundingBox.left&&(n=t.shape.boundingBox.left),st.shape.boundingBox.top&&(i=t.shape.boundingBox.top),ot.shape.boundingBox.left&&(n=t.shape.boundingBox.left),st.shape.boundingBox.top&&(i=t.shape.boundingBox.top),o.5*this.body.nodeIndices.length)return void this.fit(i,!1);t=this._getRange(i.nodes);var a=this.body.nodeIndices.length;e=12.662/(a+7.4147)+.0964822;var h=Math.min(this.canvas.frame.canvas.clientWidth/600,this.canvas.frame.canvas.clientHeight/600);e*=h}else{this.body.emitter.emit("_resizeNodes"),t=this._getRange(i.nodes);var d=1.1*Math.abs(t.maxX-t.minX),l=1.1*Math.abs(t.maxY-t.minY),u=this.canvas.frame.canvas.clientWidth/d,c=this.canvas.frame.canvas.clientHeight/l;e=c>=u?u:c}e>1?e=1:0===e&&(e=1);var p=this._findCenter(t),f={position:p,scale:e,animation:i.animation};this.moveTo(f)}},{key:"focus",value:function(t){var e=void 0===arguments[1]?{}:arguments[1];if(void 0!==this.body.nodes[t]){var i={x:this.body.nodes[t].x,y:this.body.nodes[t].y};e.position=i,e.lockedOnNode=t,this.moveTo(e)}else console.log("Node: "+t+" cannot be found.")}},{key:"moveTo",value:function(t){return void 0===t?void(t={}):(void 0===t.offset&&(t.offset={x:0,y:0}),void 0===t.offset.x&&(t.offset.x=0),void 0===t.offset.y&&(t.offset.y=0),void 0===t.scale&&(t.scale=this.body.view.scale),void 0===t.position&&(t.position=this.body.view.translation),void 0===t.animation&&(t.animation={duration:0}),t.animation===!1&&(t.animation={duration:0}),t.animation===!0&&(t.animation={}),void 0===t.animation.duration&&(t.animation.duration=1e3),void 0===t.animation.easingFunction&&(t.animation.easingFunction="easeInOutQuad"),void this.animateView(t))}},{key:"animateView",value:function(t){if(void 0!==t){this.animationEasingFunction=t.animation.easingFunction,this.releaseNode(),t.locked===!0&&(this.lockedOnNodeId=t.lockedOnNode,this.lockedOnNodeOffset=t.offset),0!=this.easingTime&&this._transitionRedraw(!0),this.sourceScale=this.body.view.scale,this.sourceTranslation=this.body.view.translation,this.targetScale=t.scale,this.body.view.scale=this.targetScale;var e=this.canvas.DOMtoCanvas({x:.5*this.canvas.frame.canvas.clientWidth,y:.5*this.canvas.frame.canvas.clientHeight}),i={x:e.x-t.position.x,y:e.y-t.position.y};this.targetTranslation={x:this.sourceTranslation.x+i.x*this.targetScale+t.offset.x,y:this.sourceTranslation.y+i.y*this.targetScale+t.offset.y},0===t.animation.duration?void 0!=this.lockedOnNodeId?(this.viewFunction=this._lockedRedraw.bind(this),this.body.emitter.on("initRedraw",this.viewFunction)):(this.body.view.scale=this.targetScale,this.body.view.translation=this.targetTranslation,this.body.emitter.emit("_requestRedraw")):(this.animationSpeed=1/(60*t.animation.duration*.001)||1/60,this.animationEasingFunction=t.animation.easingFunction,this.viewFunction=this._transitionRedraw.bind(this),this.body.emitter.on("initRedraw",this.viewFunction),this.body.emitter.emit("_startRendering"))}}},{key:"_lockedRedraw",value:function(){var t={x:this.body.nodes[this.lockedOnNodeId].x,y:this.body.nodes[this.lockedOnNodeId].y},e=this.DOMtoCanvas({x:.5*this.frame.canvas.clientWidth,y:.5*this.frame.canvas.clientHeight}),i={x:e.x-t.x,y:e.y-t.y},o=this.body.view.translation,n={x:o.x+i.x*this.body.view.scale+this.lockedOnNodeOffset.x,y:o.y+i.y*this.body.view.scale+this.lockedOnNodeOffset.y};this.body.view.translation=n}},{key:"releaseNode",value:function(){void 0!==this.lockedOnNodeId&&void 0!==this.viewFunction&&(this.body.emitter.off("initRedraw",this.viewFunction),this.lockedOnNodeId=void 0,this.lockedOnNodeOffset=void 0)}},{key:"_transitionRedraw",value:function(){var t=void 0===arguments[0]?!1:arguments[0];this.easingTime+=this.animationSpeed,this.easingTime=t===!0?1:this.easingTime;var e=s.easingFunctions[this.animationEasingFunction](this.easingTime);this.body.view.scale=this.sourceScale+(this.targetScale-this.sourceScale)*e,this.body.view.translation={x:this.sourceTranslation.x+(this.targetTranslation.x-this.sourceTranslation.x)*e,y:this.sourceTranslation.y+(this.targetTranslation.y-this.sourceTranslation.y)*e},this.easingTime>=1&&(this.body.emitter.off("initRedraw",this.viewFunction),this.easingTime=0,void 0!=this.lockedOnNodeId&&(this.viewFunction=this._lockedRedraw.bind(this),this.body.emitter.on("initRedraw",this.viewFunction)),this.body.emitter.emit("animationFinished"))}},{key:"getScale",value:function(){return this.body.view.scale}},{key:"getViewPosition",value:function(){return{x:this.body.view.translation.x,y:this.body.view.translation.y}}}]),t}();e["default"]=r,t.exports=e["default"]},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function t(t,e){for(var i=0;i50&&(this.drag.pointer=this.getPointer(t.center),this.drag.pinched=!1,this.pinch.scale=this.body.view.scale,this.touchTime=(new Date).valueOf())}},{key:"onTap",value:function(t){var e=this.getPointer(t.center),i=this.selectionHandler.options.multiselect&&t.changedPointers[0].ctrlKey;this.checkSelectionChanges(e,t,i),this.selectionHandler._generateClickEvent("click",t,e)}},{key:"onDoubleTap",value:function(t){var e=this.getPointer(t.center);this.selectionHandler._generateClickEvent("doubleClick",t,e)}},{key:"onHold",value:function(t){var e=this.getPointer(t.center),i=this.selectionHandler.options.multiselect;this.checkSelectionChanges(e,t,i),this.selectionHandler._generateClickEvent("click",t,e),this.selectionHandler._generateClickEvent("hold",t,e)}},{key:"onRelease",value:function(t){if((new Date).valueOf()-this.touchTime>10){var e=this.getPointer(t.center);this.selectionHandler._generateClickEvent("release",t,e),this.touchTime=(new Date).valueOf()}}},{key:"onContext",value:function(t){var e=this.getPointer({x:t.pageX,y:t.pageY});this.selectionHandler._generateClickEvent("oncontext",t,e)}},{key:"checkSelectionChanges",value:function(t,e){var i=void 0===arguments[2]?!1:arguments[2],o=this.selectionHandler._getSelectedEdgeCount(),n=this.selectionHandler._getSelectedNodeCount(),s=this.selectionHandler.getSelection(),r=void 0;r=i===!0?this.selectionHandler.selectAdditionalOnPoint(t):this.selectionHandler.selectOnPoint(t);var a=this.selectionHandler._getSelectedEdgeCount(),h=this.selectionHandler._getSelectedNodeCount();h-n>0?(this.selectionHandler._generateClickEvent("selectNode",e,t),r=!0):0>h-n&&(this.selectionHandler._generateClickEvent("deselectNode",e,t,s),r=!0),a-o>0?(this.selectionHandler._generateClickEvent("selectEdge",e,t),r=!0):0>a-o&&(this.selectionHandler._generateClickEvent("deselectEdge",e,t,s),r=!0),r===!0&&this.selectionHandler._generateClickEvent("select",e,t)}},{key:"onDragStart",value:function(t){void 0===this.drag.pointer&&this.onTouch(t);var e=this.selectionHandler.getNodeAt(this.drag.pointer);if(this.drag.dragging=!0,this.drag.selection=[],this.drag.translation=l.extend({},this.body.view.translation),this.drag.nodeId=void 0,this.selectionHandler._generateClickEvent("dragStart",t,this.drag.pointer),void 0!==e&&this.options.dragNodes===!0){this.drag.nodeId=e.id,e.isSelected()===!1&&(this.selectionHandler.unselectAll(),this.selectionHandler.selectObject(e));var i=this.selectionHandler.selectionObj.nodes;for(var o in i)if(i.hasOwnProperty(o)){var n=i[o],s={id:n.id,node:n,x:n.x,y:n.y,xFixed:n.options.fixed.x,yFixed:n.options.fixed.y};n.options.fixed.x=!0,n.options.fixed.y=!0,this.drag.selection.push(s)}}}},{key:"onDrag",value:function(t){var e=this;if(this.drag.pinched!==!0){this.body.emitter.emit("unlockNode");var i=this.getPointer(t.center);this.selectionHandler._generateClickEvent("dragging",t,i);var o=this.drag.selection;if(o&&o.length&&this.options.dragNodes===!0)!function(){var t=i.x-e.drag.pointer.x,n=i.y-e.drag.pointer.y;o.forEach(function(i){var o=i.node;i.xFixed===!1&&(o.x=e.canvas._XconvertDOMtoCanvas(e.canvas._XconvertCanvasToDOM(i.x)+t)),i.yFixed===!1&&(o.y=e.canvas._YconvertDOMtoCanvas(e.canvas._YconvertCanvasToDOM(i.y)+n))}),e.body.emitter.emit("startSimulation")}();else if(this.options.dragView===!0){if(void 0===this.drag.pointer)return void this._handleDragStart(t);var n=i.x-this.drag.pointer.x,s=i.y-this.drag.pointer.y;this.body.view.translation={x:this.drag.translation.x+n,y:this.drag.translation.y+s},this.body.emitter.emit("_redraw")}}}},{key:"onDragEnd",value:function(t){this.drag.dragging=!1;var e=this.drag.selection;e&&e.length?(e.forEach(function(t){t.node.options.fixed.x=t.xFixed,t.node.options.fixed.y=t.yFixed}),this.body.emitter.emit("startSimulation")):this.body.emitter.emit("_requestRedraw"),this.selectionHandler._generateClickEvent("dragEnd",t,this.getPointer(t.center))}},{key:"onPinch",value:function(t){var e=this.getPointer(t.center);this.drag.pinched=!0,void 0===this.pinch.scale&&(this.pinch.scale=1);var i=this.pinch.scale*t.scale;this.zoom(i,e)}},{key:"zoom",value:function(t,e){if(this.options.zoomView===!0){var i=this.body.view.scale;1e-5>t&&(t=1e-5),t>10&&(t=10);var o=void 0;void 0!==this.drag&&this.drag.dragging===!0&&(o=this.canvas.DOMtoCanvas(this.drag.pointer));var n=this.body.view.translation,s=t/i,r=(1-s)*e.x+n.x*s,a=(1-s)*e.y+n.y*s;if(this.body.view.scale=t,this.body.view.translation={x:r,y:a},void 0!=o){var h=this.canvas.canvasToDOM(o);this.drag.pointer.x=h.x,this.drag.pointer.y=h.y}this.body.emitter.emit("_requestRedraw"),t>i?this.body.emitter.emit("zoom",{direction:"+",scale:this.body.view.scale}):this.body.emitter.emit("zoom",{direction:"-",scale:this.body.view.scale})}}},{key:"onMouseWheel",value:function(t){var e=0;if(t.wheelDelta?e=t.wheelDelta/120:t.detail&&(e=-t.detail/3),0!==e){var i=this.body.view.scale,o=e/10;0>e&&(o/=1-o),i*=1+o;var n=this.getPointer({x:t.pageX,y:t.pageY});this.zoom(i,n)}t.preventDefault()}},{key:"onMouseMove",value:function(t){var e=this,i=this.getPointer({x:t.pageX,y:t.pageY}),o=!1;if(void 0!==this.popup&&(this.popup.hidden===!1&&this._checkHidePopup(i),this.popup.hidden===!1&&(o=!0,this.popup.setPosition(i.x+3,i.y-5),this.popup.show())),this.options.keyboard.bindToWindow===!1&&this.options.keyboard.enabled===!0&&this.canvas.frame.focus(),o===!1&&(void 0!==this.popupTimer&&(clearInterval(this.popupTimer),this.popupTimer=void 0),this.drag.dragging||(this.popupTimer=setTimeout(function(){return e._checkShowPopup(i)},this.options.tooltipDelay))),this.options.hover===!0){var n=this.selectionHandler.getNodeAt(i);void 0===n&&(n=this.selectionHandler.getEdgeAt(i)),this.selectionHandler.hoverObject(n)}}},{key:"_checkShowPopup",value:function(t){var e=this.canvas._XconvertDOMtoCanvas(t.x),i=this.canvas._YconvertDOMtoCanvas(t.y),o={left:e,top:i,right:e,bottom:i},n=void 0===this.popupObj?void 0:this.popupObj.id,s=!1,r="node";if(void 0===this.popupObj){for(var a=this.body.nodeIndices,h=this.body.nodes,l=void 0,u=[],c=0;c0&&(this.popupObj=h[u[u.length-1]],s=!0)}if(void 0===this.popupObj&&s===!1){for(var p=this.body.edgeIndices,f=this.body.edges,m=void 0,v=[],c=0;c0&&(this.popupObj=f[v[v.length-1]],r="edge")}void 0!==this.popupObj?this.popupObj.id!==n&&(void 0===this.popup&&(this.popup=new d["default"](this.canvas.frame)),this.popup.popupTargetType=r,this.popup.popupTargetId=this.popupObj.id,this.popup.setPosition(t.x+3,t.y-5),this.popup.setText(this.popupObj.getTitle()),this.popup.show(),this.body.emitter.emit("showPopup",this.popupObj.id)):void 0!==this.popup&&(this.popup.hide(),this.body.emitter.emit("hidePopup"))}},{key:"_checkHidePopup",value:function(t){var e=this.selectionHandler._pointerToPositionObject(t),i=!1;if("node"===this.popup.popupTargetType){if(void 0!==this.body.nodes[this.popup.popupTargetId]&&(i=this.body.nodes[this.popup.popupTargetId].isOverlappingWith(e),i===!0)){var o=this.selectionHandler.getNodeAt(t);i=o.id===this.popup.popupTargetId}}else void 0===this.selectionHandler.getNodeAt(t)&&void 0!==this.body.edges[this.popup.popupTargetId]&&(i=this.body.edges[this.popup.popupTargetId].isOverlappingWith(e));i===!1&&(this.popupObj=void 0,this.popup.hide(),this.body.emitter.emit("hidePopup"))}}]),t}();e["default"]=u,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;i0?e===!0?this.body.nodes[o[o.length-1]]:o[o.length-1]:void 0}},{key:"_getEdgesOverlappingWith",value:function(t,e){for(var i=this.body.edges,o=0;o0?e===!0?this.body.edges[o[o.length-1]]:o[o.length-1]:void 0}},{key:"_addToSelection",value:function(t){t instanceof s?this.selectionObj.nodes[t.id]=t:this.selectionObj.edges[t.id]=t}},{key:"_addToHover",value:function(t){t instanceof s?this.hoverObj.nodes[t.id]=t:this.hoverObj.edges[t.id]=t}},{key:"_removeFromSelection",value:function(t){t instanceof s?delete this.selectionObj.nodes[t.id]:delete this.selectionObj.edges[t.id]}},{key:"unselectAll",value:function(){for(var t in this.selectionObj.nodes)this.selectionObj.nodes.hasOwnProperty(t)&&this.selectionObj.nodes[t].unselect();for(var e in this.selectionObj.edges)this.selectionObj.edges.hasOwnProperty(e)&&this.selectionObj.edges[e].unselect();this.selectionObj={nodes:{},edges:{}}}},{key:"_getSelectedNodeCount",value:function(){var t=0;for(var e in this.selectionObj.nodes)this.selectionObj.nodes.hasOwnProperty(e)&&(t+=1);return t}},{key:"_getSelectedNode",value:function(){for(var t in this.selectionObj.nodes)if(this.selectionObj.nodes.hasOwnProperty(t))return this.selectionObj.nodes[t];return void 0}},{key:"_getSelectedEdge",value:function(){for(var t in this.selectionObj.edges)if(this.selectionObj.edges.hasOwnProperty(t))return this.selectionObj.edges[t];return void 0}},{key:"_getSelectedEdgeCount",value:function(){var t=0;for(var e in this.selectionObj.edges)this.selectionObj.edges.hasOwnProperty(e)&&(t+=1);return t}},{key:"_getSelectedObjectCount",value:function(){var t=0;for(var e in this.selectionObj.nodes)this.selectionObj.nodes.hasOwnProperty(e)&&(t+=1);for(var i in this.selectionObj.edges)this.selectionObj.edges.hasOwnProperty(i)&&(t+=1);return t}},{key:"_selectionIsEmpty",value:function(){for(var t in this.selectionObj.nodes)if(this.selectionObj.nodes.hasOwnProperty(t))return!1;for(var e in this.selectionObj.edges)if(this.selectionObj.edges.hasOwnProperty(e))return!1;return!0}},{key:"_clusterInSelection",value:function(){for(var t in this.selectionObj.nodes)if(this.selectionObj.nodes.hasOwnProperty(t)&&this.selectionObj.nodes[t].clusterSize>1)return!0;return!1}},{key:"_selectConnectedEdges",value:function(t){for(var e=0;e0&&(this.options.hierarchical.levelSeparation*=-1):this.options.hierarchical.levelSeparation<0&&(this.options.hierarchical.levelSeparation*=-1),this.body.emitter.emit("_resetHierarchicalLayout"),this.adaptAllOptions(e);if(i===!0)return this.body.emitter.emit("refresh"),s.deepExtend(e,this.optionsBackup)}return e}},{key:"adaptAllOptions",value:function(t){if(this.options.hierarchical.enabled===!0){void 0===t.physics||t.physics===!0?(t.physics={solver:"hierarchicalRepulsion"},this.optionsBackup.physics={solver:"barnesHut"}):"object"==typeof options.physics?(this.optionsBackup.physics={solver:"barnesHut"},void 0!==options.physics.solver&&(this.optionsBackup.physics={solver:options.physics.solver}),t.physics.solver="hierarchicalRepulsion"):options.physics!==!1&&(this.optionsBackup.physics={solver:"barnesHut"},t.physics.solver="hierarchicalRepulsion");var e="horizontal";("RL"===this.options.hierarchical.direction||"LR"===this.options.hierarchical.direction)&&(e="vertical"),void 0===t.edges?(this.optionsBackup.edges={smooth:!0,dynamic:!0},t.edges={smooth:!1}):void 0===t.edges.smooth?(this.optionsBackup.edges={smooth:!0,dynamic:!0},t.edges.smooth=!1):"boolean"==typeof t.edges.smooth?(this.optionsBackup.edges={smooth:t.edges.smooth,dynamic:!0},t.edges.smooth={enabled:t.edges.smooth,dynamic:!1,type:e}):(this.optionsBackup.edges={smooth:void 0===t.edges.smooth.enabled?!0:t.edges.smooth.enabled,dynamic:!0},t.edges.smooth={enabled:void 0===t.edges.smooth.enabled?!0:t.edges.smooth.enabled,dynamic:!1,type:e}),this.body.emitter.emit("_forceDisableDynamicCurves",e)}return t}},{key:"seededRandom",value:function(){var t=1e4*Math.sin(this.randomSeed++);return t-Math.floor(t)}},{key:"positionInitially",value:function(t){if(this.options.hierarchical.enabled!==!0){this.randomSeed=this.initialRandomSeed;for(var e=0;e0){var t=void 0,e=void 0,i=!1,o=!1;this.hierarchicalLevels={},this.nodeSpacing=100;for(e in this.body.nodes)this.body.nodes.hasOwnProperty(e)&&(t=this.body.nodes[e],void 0!==t.options.level?(i=!0,this.hierarchicalLevels[e]=t.options.level):o=!0);if(o===!0&&i===!0)throw new Error("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");o===!0&&("hubsize"===this.options.hierarchical.sortMethod?this._determineLevelsByHubsize():("directed"===this.options.hierarchical.sortMethod,0||this._determineLevelsDirected()));var n=this._getDistribution();this._placeNodesByHierarchy(n)}}},{key:"_placeNodesByHierarchy",value:function(t){var e=void 0,i=void 0;this.positionedNodes={};for(var o in t)if(t.hasOwnProperty(o))for(e in t[o].nodes)t[o].nodes.hasOwnProperty(e)&&(i=t[o].nodes[e],"UD"===this.options.hierarchical.direction||"DU"===this.options.hierarchical.direction?(void 0===i.x&&(i.x=t[o].distance),t[o].distance=i.x+this.nodeSpacing):(void 0===i.y&&(i.y=t[o].distance),t[o].distance=i.y+this.nodeSpacing),this.positionedNodes[e]=!0,this._placeBranchNodes(i.edges,i.id,t,o))}},{key:"_getDistribution",value:function(){var t={},e=void 0,i=void 0;for(e in this.body.nodes)if(this.body.nodes.hasOwnProperty(e)){i=this.body.nodes[e];var o=void 0===this.hierarchicalLevels[e]?0:this.hierarchicalLevels[e];"UD"===this.options.hierarchical.direction||"DU"===this.options.hierarchical.direction?(i.y=this.options.hierarchical.levelSeparation*o,i.options.fixed.y=!0):(i.x=this.options.hierarchical.levelSeparation*o,i.options.fixed.x=!0),void 0===t[o]&&(t[o]={amount:0,nodes:{},distance:0}),t[o].amount+=1,t[o].nodes[e]=i}return t}},{key:"_getHubSize",value:function(){var t=0;for(var e in this.body.nodes)if(this.body.nodes.hasOwnProperty(e)){var i=this.body.nodes[e];void 0===this.hierarchicalLevels[e]&&(t=i.edges.length0&&(i=this._getHubSize(),0!==i);)for(t in this.body.nodes)this.body.nodes.hasOwnProperty(t)&&(e=this.body.nodes[t],e.edges.length===i&&this._setLevel(0,e))}},{key:"_setLevel",value:function(t,e){if(void 0===this.hierarchicalLevels[e.id]){var i=void 0;this.hierarchicalLevels[e.id]=t;for(var o=0;oo&&("UD"===this.options.hierarchical.direction||"DU"===this.options.hierarchical.direction?(void 0===s.x&&(s.x=Math.max(i[a].distance,r.x)),i[a].distance=s.x+this.nodeSpacing,this.positionedNodes[s.id]=!0):(void 0===s.y&&(s.y=Math.max(i[a].distance,r.y)),i[a].distance=s.y+this.nodeSpacing),this.positionedNodes[s.id]=!0,s.edges.length>1&&this._placeBranchNodes(s.edges,s.id,i,a))}}}]),t}();e["default"]=r,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;i0){for(var n=0;n0&&"function"==typeof this.options.deleteEdge&&(o=this.options.deleteEdge);if("function"==typeof o){var s={nodes:e,edges:i};if(2!==o.length)throw new Error("The function for delete does not support two arguments (data, callback)");o(s,function(e){null!==e&&void 0!==e&&"delete"===t.inMode&&(t.body.data.edges.remove(e.edges),t.body.data.nodes.remove(e.nodes),t.body.emitter.emit("startSimulation"),t.showManipulatorToolbar())})}else this.body.data.edges.remove(i),this.body.data.nodes.remove(e),this.body.emitter.emit("startSimulation"),this.showManipulatorToolbar()}},{key:"_setup",value:function(){this.options.enabled===!0?(this.guiEnabled=!0,this._createWrappers(),this.editMode===!1?this._createEditButton():this.showManipulatorToolbar()):(this._removeManipulationDOM(),this.guiEnabled=!1)}},{key:"_createWrappers",value:function(){void 0===this.manipulationDiv&&(this.manipulationDiv=document.createElement("div"),this.manipulationDiv.className="vis-manipulation",this.editMode===!0?this.manipulationDiv.style.display="block":this.manipulationDiv.style.display="none",this.canvas.frame.appendChild(this.manipulationDiv)),void 0===this.editModeDiv&&(this.editModeDiv=document.createElement("div"),this.editModeDiv.className="vis-edit-mode",this.editMode===!0?this.editModeDiv.style.display="none":this.editModeDiv.style.display="block",this.canvas.frame.appendChild(this.editModeDiv)),void 0===this.closeDiv&&(this.closeDiv=document.createElement("div"),this.closeDiv.className="vis-close",this.closeDiv.style.display=this.manipulationDiv.style.display,this.canvas.frame.appendChild(this.closeDiv))}},{key:"_getNewTargetNode",value:function(t,e){var i=s.deepExtend({},this.options.controlNodeStyle);return i.id="targetNode"+s.randomUUID(),i.hidden=!1,i.physics=!1,i.x=t,i.y=e,this.body.functions.createNode(i)}},{key:"_createEditButton",value:function(){this._clean(),this.manipulationDOM={},s.recursiveDOMDelete(this.editModeDiv);var t=this.options.locales[this.options.locale],e=this._createButton("editMode","vis-button vis-edit vis-edit-mode",t.edit||this.options.locales.en.edit);this.editModeDiv.appendChild(e),this._bindHammerToDiv(e,this.toggleEditMode.bind(this))}},{key:"_clean",value:function(){this.inMode=!1,this.guiEnabled===!0&&(s.recursiveDOMDelete(this.editModeDiv),s.recursiveDOMDelete(this.manipulationDiv),this._cleanManipulatorHammers()),this._cleanupTemporaryNodesAndEdges(),this._unbindTemporaryUIs(),this._unbindTemporaryEvents(),this.body.emitter.emit("restorePhysics")}},{key:"_cleanManipulatorHammers",value:function(){if(0!=this.manipulationHammers.length){for(var t=0;t=0;r--)if(n[r]!==this.selectedControlNode.id){s=this.body.nodes[n[r]];break}if(void 0!==s&&void 0!==this.selectedControlNode)if(s.isCluster===!0)alert(this.options.locales[this.options.locale].createEdgeError||this.options.locales.en.createEdgeError);else{var a=this.body.nodes[this.temporaryIds.nodes[0]];this.selectedControlNode.id===a.id?this._performEditEdge(s.id,o.to.id):this._performEditEdge(o.from.id,s.id)}else o.updateEdgeType(),this.body.emitter.emit("restorePhysics");this.body.emitter.emit("_redraw")}},{key:"_handleConnect",value:function(t){if((new Date).valueOf()-this.touchTime>100){this.lastTouch=this.body.functions.getPointer(t.center),this.lastTouch.translation=s.extend({},this.body.view.translation);var e=this.lastTouch,i=this.selectionHandler.getNodeAt(e);if(void 0!==i)if(i.isCluster===!0)alert(this.options.locales[this.options.locale].createEdgeError||this.options.locales.en.createEdgeError);else{var o=this._getNewTargetNode(i.x,i.y);this.body.nodes[o.id]=o,this.body.nodeIndices.push(o.id);var n=this.body.functions.createEdge({id:"connectionEdge"+s.randomUUID(),from:i.id,to:o.id,physics:!1,smooth:{enabled:!0,dynamic:!1,type:"continuous",roundness:.5}});this.body.edges[n.id]=n,this.body.edgeIndices.push(n.id),this.temporaryIds.nodes.push(o.id),this.temporaryIds.edges.push(n.id)}this.touchTime=(new Date).valueOf()}}},{key:"_dragControlNode",value:function(t){var e=this.body.functions.getPointer(t.center);if(void 0!==this.temporaryIds.nodes[0]){var i=this.body.nodes[this.temporaryIds.nodes[0]];i.x=this.canvas._XconvertDOMtoCanvas(e.x), -i.y=this.canvas._YconvertDOMtoCanvas(e.y),this.body.emitter.emit("_redraw")}else{var o=e.x-this.lastTouch.x,n=e.y-this.lastTouch.y;this.body.view.translation={x:this.lastTouch.translation.x+o,y:this.lastTouch.translation.y+n}}}},{key:"_finishConnect",value:function(t){var e=this.body.functions.getPointer(t.center),i=this.selectionHandler._pointerToPositionObject(e),o=void 0;void 0!==this.temporaryIds.edges[0]&&(o=this.body.edges[this.temporaryIds.edges[0]].fromId);for(var n=this.selectionHandler._getAllNodesOverlappingWith(i),s=void 0,r=n.length-1;r>=0;r--)if(-1===this.temporaryIds.nodes.indexOf(n[r])){s=this.body.nodes[n[r]];break}this._cleanupTemporaryNodesAndEdges(),void 0!==s&&(s.isCluster===!0?alert(this.options.locales[this.options.locale].createEdgeError||this.options.locales.en.createEdgeError):void 0!==this.body.nodes[o]&&void 0!==this.body.nodes[s.id]&&this._performAddEdge(o,s.id)),this.body.emitter.emit("_redraw")}},{key:"_performAddNode",value:function(t){var e=this,i={id:s.randomUUID(),x:t.pointer.canvas.x,y:t.pointer.canvas.y,label:"new"};if("function"==typeof this.options.addNode){if(2!==this.options.addNode.length)throw new Error("The function for add does not support two arguments (data,callback)");this.options.addNode(i,function(t){null!==t&&void 0!==t&&"addNode"===e.inMode&&(e.body.data.nodes.add(t),e.showManipulatorToolbar())})}else this.body.data.nodes.add(i),this.showManipulatorToolbar()}},{key:"_performAddEdge",value:function(t,e){var i=this,o={from:t,to:e};if("function"==typeof this.options.addEdge){if(2!==this.options.addEdge.length)throw new Error("The function for connect does not support two arguments (data,callback)");this.options.addEdge(o,function(t){null!==t&&void 0!==t&&"addEdge"===i.inMode&&(i.body.data.edges.add(t),i.selectionHandler.unselectAll(),i.showManipulatorToolbar())})}else this.body.data.edges.add(o),this.selectionHandler.unselectAll(),this.showManipulatorToolbar()}},{key:"_performEditEdge",value:function(t,e){var i=this,o={id:this.edgeBeingEditedId,from:t,to:e};if("function"==typeof this.options.editEdge){if(2!==this.options.editEdge.length)throw new Error("The function for edit does not support two arguments (data, callback)");this.options.editEdge(o,function(t){null===t||void 0===t||"editEdge"!==i.inMode?(i.body.edges[o.id].updateEdgeType(),i.body.emitter.emit("_redraw")):(i.body.data.edges.update(t),i.selectionHandler.unselectAll(),i.showManipulatorToolbar())})}else this.body.data.edges.update(o),this.selectionHandler.unselectAll(),this.showManipulatorToolbar()}}]),t}();e["default"]=h,t.exports=e["default"]},function(t,e,i){Object.defineProperty(e,"__esModule",{value:!0});var o="string",n="boolean",s="number",r="array",a="object",h="dom",d="function",l="undefined",u={configure:{enabled:{"boolean":n},filter:{"boolean":n,string:o,array:r,fn:d},container:{dom:h},showButton:{"boolean":n},__type__:{object:a,"boolean":n,string:o,array:r,fn:d}},edges:{arrows:{to:{enabled:{"boolean":n},scaleFactor:{number:s},__type__:{object:a,"boolean":n}},middle:{enabled:{"boolean":n},scaleFactor:{number:s},__type__:{object:a,"boolean":n}},from:{enabled:{"boolean":n},scaleFactor:{number:s},__type__:{object:a,"boolean":n}},__type__:{string:["from","to","middle"],object:a}},color:{color:{string:o},highlight:{string:o},hover:{string:o},inherit:{string:["from","to","both"],"boolean":n},opacity:{number:s},__type__:{object:a,string:o}},dashes:{"boolean":n,array:r},font:{color:{string:o},size:{number:s},face:{string:o},background:{string:o},strokeWidth:{number:s},strokeColor:{string:o},align:{string:["horizontal","top","middle","bottom"]},__type__:{object:a,string:o}},hidden:{"boolean":n},hoverWidth:{fn:d,number:s},label:{string:o,undef:l},length:{number:s,undef:l},physics:{"boolean":n},scaling:{min:{number:s},max:{number:s},label:{enabled:{"boolean":n},min:{number:s},max:{number:s},maxVisible:{number:s},drawThreshold:{number:s},__type__:{object:a,"boolean":n}},customScalingFunction:{fn:d},__type__:{object:a}},selectionWidth:{fn:d,number:s},selfReferenceSize:{number:s},shadow:{enabled:{"boolean":n},size:{number:s},x:{number:s},y:{number:s},__type__:{object:a,"boolean":n}},smooth:{enabled:{"boolean":n},type:{string:["dynamic","continuous","discrete","diagonalCross","straightCross","horizontal","vertical","curvedCW","curvedCCW"]},roundness:{number:s},__type__:{object:a,"boolean":n}},title:{string:o,undef:l},width:{number:s},value:{number:s,undef:l},__type__:{object:a}},groups:{useDefaultGroups:{"boolean":n},__any__:"get from nodes, will be overwritten below",__type__:{object:a}},interaction:{dragNodes:{"boolean":n},dragView:{"boolean":n},hideEdgesOnDrag:{"boolean":n},hideNodesOnDrag:{"boolean":n},hover:{"boolean":n},keyboard:{enabled:{"boolean":n},speed:{x:{number:s},y:{number:s},zoom:{number:s},__type__:{object:a}},bindToWindow:{"boolean":n},__type__:{object:a,"boolean":n}},multiselect:{"boolean":n},navigationButtons:{"boolean":n},selectable:{"boolean":n},selectConnectedEdges:{"boolean":n},tooltipDelay:{number:s},zoomView:{"boolean":n},__type__:{object:a}},layout:{randomSeed:{undef:l,number:s},hierarchical:{enabled:{"boolean":n},levelSeparation:{number:s},direction:{string:["UD","DU","LR","RL"]},sortMethod:{string:["hubsize","directed"]},__type__:{object:a,"boolean":n}},__type__:{object:a}},manipulation:{enabled:{"boolean":n},initiallyActive:{"boolean":n},addNode:{"boolean":n,fn:d},addEdge:{"boolean":n,fn:d},editNode:{fn:d},editEdge:{"boolean":n,fn:d},deleteNode:{"boolean":n,fn:d},deleteEdge:{"boolean":n,fn:d},controlNodeStyle:"get from nodes, will be overwritten below",__type__:{object:a,"boolean":n}},nodes:{borderWidth:{number:s},borderWidthSelected:{number:s,undef:l},brokenImage:{string:o,undef:l},color:{border:{string:o},background:{string:o},highlight:{border:{string:o},background:{string:o},__type__:{object:a,string:o}},hover:{border:{string:o},background:{string:o},__type__:{object:a,string:o}},__type__:{object:a,string:o}},fixed:{x:{"boolean":n},y:{"boolean":n},__type__:{object:a,"boolean":n}},font:{color:{string:o},size:{number:s},face:{string:o},background:{string:o},strokeWidth:{number:s},strokeColor:{string:o},__type__:{object:a,string:o}},group:{string:o,number:s,undef:l},hidden:{"boolean":n},icon:{face:{string:o},code:{string:o},size:{number:s},color:{string:o},__type__:{object:a}},id:{string:o,number:s},image:{string:o,undef:l},label:{string:o,undef:l},level:{number:s,undef:l},mass:{number:s},physics:{"boolean":n},scaling:{min:{number:s},max:{number:s},label:{enabled:{"boolean":n},min:{number:s},max:{number:s},maxVisible:{number:s},drawThreshold:{number:s},__type__:{object:a,"boolean":n}},customScalingFunction:{fn:d},__type__:{object:a}},shadow:{enabled:{"boolean":n},size:{number:s},x:{number:s},y:{number:s},__type__:{object:a,"boolean":n}},shape:{string:["ellipse","circle","database","box","text","image","circularImage","diamond","dot","star","triangle","triangleDown","square","icon"]},size:{number:s},title:{string:o,undef:l},value:{number:s,undef:l},x:{number:s},y:{number:s},__type__:{object:a}},physics:{barnesHut:{gravitationalConstant:{number:s},centralGravity:{number:s},springLength:{number:s},springConstant:{number:s},damping:{number:s},avoidOverlap:{number:s},__type__:{object:a}},forceAtlas2Based:{gravitationalConstant:{number:s},centralGravity:{number:s},springLength:{number:s},springConstant:{number:s},damping:{number:s},avoidOverlap:{number:s},__type__:{object:a}},repulsion:{centralGravity:{number:s},springLength:{number:s},springConstant:{number:s},nodeDistance:{number:s},damping:{number:s},__type__:{object:a}},hierarchicalRepulsion:{centralGravity:{number:s},springLength:{number:s},springConstant:{number:s},nodeDistance:{number:s},damping:{number:s},__type__:{object:a}},maxVelocity:{number:s},minVelocity:{number:s},solver:{string:["barnesHut","repulsion","hierarchicalRepulsion","forceAtlas2Based"]},stabilization:{enabled:{"boolean":n},iterations:{number:s},updateInterval:{number:s},onlyDynamicEdges:{"boolean":n},fit:{"boolean":n},__type__:{object:a,"boolean":n}},timestep:{number:s},__type__:{object:a,"boolean":n}},autoResize:{"boolean":n},clickToUse:{"boolean":n},locale:{string:o},locales:{__any__:{object:a},__type__:{object:a}},height:{string:o},width:{string:o},__type__:{object:a}};u.groups.__any__=u.nodes,u.manipulation.controlNodeStyle=u.nodes;var c={nodes:{borderWidth:[1,0,10,1],borderWidthSelected:[2,0,10,1],color:{border:["color","#2B7CE9"],background:["color","#97C2FC"],highlight:{border:["color","#2B7CE9"],background:["color","#D2E5FF"]},hover:{border:["color","#2B7CE9"],background:["color","#D2E5FF"]}},fixed:{x:!1,y:!1},font:{color:["color","#343434"],size:[14,0,100,1],face:["arial","verdana","tahoma"],background:["color","none"],strokeWidth:[0,0,50,1],strokeColor:["color","#ffffff"]},hidden:!1,physics:!0,scaling:{min:[10,0,200,1],max:[30,0,200,1],label:{enabled:!1,min:[14,0,200,1],max:[30,0,200,1],maxVisible:[30,0,200,1],drawThreshold:[5,0,20,1]}},shadow:{enabled:!1,size:[10,0,20,1],x:[5,-30,30,1],y:[5,-30,30,1]},shape:["ellipse","box","circle","database","diamond","dot","square","star","text","triangle","triangleDown"],size:[25,0,200,1]},edges:{arrows:{to:{enabled:!1,scaleFactor:[1,0,3,.05]},middle:{enabled:!1,scaleFactor:[1,0,3,.05]},from:{enabled:!1,scaleFactor:[1,0,3,.05]}},color:{color:["color","#848484"],highlight:["color","#848484"],hover:["color","#848484"],inherit:["from","to","both",!0,!1],opacity:[1,0,1,.05]},dashes:!1,font:{color:["color","#343434"],size:[14,0,100,1],face:["arial","verdana","tahoma"],background:["color","none"],strokeWidth:[2,0,50,1],strokeColor:["color","#ffffff"],align:["horizontal","top","middle","bottom"]},hidden:!1,hoverWidth:[1.5,0,5,.1],physics:!0,scaling:{min:[1,0,100,1],max:[15,0,100,1],label:{enabled:!0,min:[14,0,200,1],max:[30,0,200,1],maxVisible:[30,0,200,1],drawThreshold:[5,0,20,1]}},selectionWidth:[1.5,0,5,.1],selfReferenceSize:[20,0,200,1],shadow:{enabled:!1,size:[10,0,20,1],x:[5,-30,30,1],y:[5,-30,30,1]},smooth:{enabled:!0,type:["dynamic","continuous","discrete","diagonalCross","straightCross","horizontal","vertical","curvedCW","curvedCCW"],roundness:[.5,0,1,.05]},width:[1,0,30,1]},layout:{hierarchical:{enabled:!1,levelSeparation:[150,20,500,5],direction:["UD","DU","LR","RL"],sortMethod:["hubsize","directed"]}},interaction:{dragNodes:!0,dragView:!0,hideEdgesOnDrag:!1,hideNodesOnDrag:!1,hover:!1,keyboard:{enabled:!1,speed:{x:[10,0,40,1],y:[10,0,40,1],zoom:[.02,0,.1,.005]},bindToWindow:!0},multiselect:!1,navigationButtons:!1,selectable:!0,selectConnectedEdges:!0,tooltipDelay:[300,0,1e3,25],zoomView:!0},manipulation:{enabled:!1,initiallyActive:!1},physics:{barnesHut:{gravitationalConstant:[-2e3,-3e4,0,50],centralGravity:[.3,0,10,.05],springLength:[95,0,500,5],springConstant:[.04,0,1.2,.005],damping:[.09,0,1,.01],avoidOverlap:[0,0,1,.01]},forceAtlas2Based:{gravitationalConstant:[-50,-500,0,1],centralGravity:[.01,0,1,.005],springLength:[95,0,500,5],springConstant:[.08,0,1.2,.005],damping:[.4,0,1,.01],avoidOverlap:[0,0,1,.01]},repulsion:{centralGravity:[.2,0,10,.05],springLength:[200,0,500,5],springConstant:[.05,0,1.2,.005],nodeDistance:[100,0,500,5],damping:[.09,0,1,.01]},hierarchicalRepulsion:{centralGravity:[.2,0,10,.05],springLength:[100,0,500,5],springConstant:[.01,0,1.2,.005],nodeDistance:[120,0,500,5],damping:[.09,0,1,.01]},maxVelocity:[50,0,150,1],minVelocity:[.1,.01,.5,.01],solver:["barnesHut","forceAtlas2Based","repulsion","hierarchicalRepulsion"],timestep:[.5,.01,1,.01]},global:{locale:["en","nl"]}};e.allOptions=u,e.configureOptions=c},function(t,e,i){"undefined"!=typeof CanvasRenderingContext2D&&(CanvasRenderingContext2D.prototype.circle=function(t,e,i){this.beginPath(),this.arc(t,e,i,0,2*Math.PI,!1),this.closePath()},CanvasRenderingContext2D.prototype.square=function(t,e,i){this.beginPath(),this.rect(t-i,e-i,2*i,2*i),this.closePath()},CanvasRenderingContext2D.prototype.triangle=function(t,e,i){this.beginPath(),i*=1.15,e+=.275*i;var o=2*i,n=o/2,s=Math.sqrt(3)/6*o,r=Math.sqrt(o*o-n*n);this.moveTo(t,e-(r-s)),this.lineTo(t+n,e+s),this.lineTo(t-n,e+s),this.lineTo(t,e-(r-s)),this.closePath()},CanvasRenderingContext2D.prototype.triangleDown=function(t,e,i){this.beginPath(),i*=1.15,e-=.275*i;var o=2*i,n=o/2,s=Math.sqrt(3)/6*o,r=Math.sqrt(o*o-n*n);this.moveTo(t,e+(r-s)),this.lineTo(t+n,e-s),this.lineTo(t-n,e-s),this.lineTo(t,e+(r-s)),this.closePath()},CanvasRenderingContext2D.prototype.star=function(t,e,i){this.beginPath(),i*=.82,e+=.1*i;for(var o=0;10>o;o++){var n=o%2===0?1.3*i:.5*i;this.lineTo(t+n*Math.sin(2*o*Math.PI/10),e-n*Math.cos(2*o*Math.PI/10))}this.closePath()},CanvasRenderingContext2D.prototype.diamond=function(t,e,i){this.beginPath(),this.lineTo(t,e+i),this.lineTo(t+i,e),this.lineTo(t,e-i),this.lineTo(t-i,e),this.closePath()},CanvasRenderingContext2D.prototype.roundRect=function(t,e,i,o,n){var s=Math.PI/180;0>i-2*n&&(n=i/2),0>o-2*n&&(n=o/2),this.beginPath(),this.moveTo(t+n,e),this.lineTo(t+i-n,e),this.arc(t+i-n,e+n,n,270*s,360*s,!1),this.lineTo(t+i,e+o-n),this.arc(t+i-n,e+o-n,n,0,90*s,!1),this.lineTo(t+n,e+o),this.arc(t+n,e+o-n,n,90*s,180*s,!1),this.lineTo(t,e+n),this.arc(t+n,e+n,n,180*s,270*s,!1),this.closePath()},CanvasRenderingContext2D.prototype.ellipse=function(t,e,i,o){var n=.5522848,s=i/2*n,r=o/2*n,a=t+i,h=e+o,d=t+i/2,l=e+o/2;this.beginPath(),this.moveTo(t,l),this.bezierCurveTo(t,l-r,d-s,e,d,e),this.bezierCurveTo(d+s,e,a,l-r,a,l),this.bezierCurveTo(a,l+r,d+s,h,d,h),this.bezierCurveTo(d-s,h,t,l+r,t,l),this.closePath()},CanvasRenderingContext2D.prototype.database=function(t,e,i,o){var n=1/3,s=i,r=o*n,a=.5522848,h=s/2*a,d=r/2*a,l=t+s,u=e+r,c=t+s/2,p=e+r/2,f=e+(o-r/2),m=e+o;this.beginPath(),this.moveTo(l,p),this.bezierCurveTo(l,p+d,c+h,u,c,u),this.bezierCurveTo(c-h,u,t,p+d,t,p),this.bezierCurveTo(t,p-d,c-h,e,c,e),this.bezierCurveTo(c+h,e,l,p-d,l,p),this.lineTo(l,f),this.bezierCurveTo(l,f+d,c+h,m,c,m),this.bezierCurveTo(c-h,m,t,f+d,t,f),this.lineTo(t,p)},CanvasRenderingContext2D.prototype.arrow=function(t,e,i,o){var n=t-o*Math.cos(i),s=e-o*Math.sin(i),r=t-.9*o*Math.cos(i),a=e-.9*o*Math.sin(i),h=n+o/3*Math.cos(i+.5*Math.PI),d=s+o/3*Math.sin(i+.5*Math.PI),l=n+o/3*Math.cos(i-.5*Math.PI),u=s+o/3*Math.sin(i-.5*Math.PI);this.beginPath(),this.moveTo(t,e),this.lineTo(h,d),this.lineTo(r,a),this.lineTo(l,u),this.closePath()},CanvasRenderingContext2D.prototype.dashedLine=function(t,e,i,o,n){this.beginPath(),this.moveTo(t,e);for(var s=n.length,r=i-t,a=o-e,h=a/r,d=Math.sqrt(r*r+a*a),l=0,u=!0,c=0,p=n[0];d>=.1;)p=n[l++%s],p>d&&(p=d),c=Math.sqrt(p*p/(1+h*h)),c=0>r?-c:c,t+=c,e+=h*c,u===!0?this.lineTo(t,e):this.moveTo(t,e),d-=p,u=!u})},function(t,e,i){function o(t){this.active=!1,this.dom={container:t},this.dom.overlay=document.createElement("div"),this.dom.overlay.className="vis-overlay",this.dom.container.appendChild(this.dom.overlay),this.hammer=a(this.dom.overlay),this.hammer.on("tap",this._onTapOverlay.bind(this));var e=this,i=["tap","doubletap","press","pinch","pan","panstart","panmove","panend"];i.forEach(function(t){e.hammer.on(t,function(t){t.stopPropagation()})}),this.bodyHammer=a(document&&document.body,{prevent_default:!1}),this.bodyHammer.on("tap",function(i){n(i.target,t)||e.deactivate()}),void 0!==this.keycharm&&this.keycharm.destroy(),this.keycharm=s(),this.escListener=this.deactivate.bind(this)}function n(t,e){for(;t;){if(t===e)return!0;t=t.parentNode}return!1}var s=i(88),r=i(69),a=i(41),h=i(57);r(o.prototype),o.current=null,o.prototype.destroy=function(){this.deactivate(),this.dom.overlay.parentNode.removeChild(this.dom.overlay),this.hammer=null,this.bodyHammer=null},o.prototype.activate=function(){o.current&&o.current.deactivate(),o.current=this,this.active=!0,this.dom.overlay.style.display="none",h.addClassName(this.dom.container,"vis-active"),this.emit("change"),this.emit("activate"),this.keycharm.bind("esc",this.escListener)},o.prototype.deactivate=function(){this.active=!1,this.dom.overlay.style.display="",h.removeClassName(this.dom.container,"vis-active"),this.keycharm.unbind("esc",this.escListener),this.emit("change"),this.emit("deactivate")},o.prototype._onTapOverlay=function(t){this.activate(),t.stopPropagation()},t.exports=o},function(t,e,i){e.en={edit:"Edit",del:"Delete selected",back:"Back",addNode:"Add Node",addEdge:"Add Edge",editNode:"Edit Node",editEdge:"Edit Edge",addDescription:"Click in an empty space to place a new node.",edgeDescription:"Click on a node and drag the edge to another node to connect them.",editEdgeDescription:"Click on the control points and drag them to a node to connect to it.",createEdgeError:"Cannot link edges to a cluster.",deleteClusterError:"Clusters cannot be deleted.",editClusterError:"Clusters cannot be edited."},e.en_EN=e.en,e.en_US=e.en,e.nl={edit:"Wijzigen",del:"Selectie verwijderen",back:"Terug",addNode:"Node toevoegen",addEdge:"Link toevoegen",editNode:"Node wijzigen",editEdge:"Link wijzigen",addDescription:"Klik op een leeg gebied om een nieuwe node te maken.",edgeDescription:"Klik op een node en sleep de link naar een andere node om ze te verbinden.",editEdgeDescription:"Klik op de verbindingspunten en sleep ze naar een node om daarmee te verbinden.",createEdgeError:"Kan geen link maken naar een cluster.",deleteClusterError:"Clusters kunnen niet worden verwijderd.",editClusterError:"Clusters kunnen niet worden aangepast."},e.nl_NL=e.nl,e.nl_BE=e.nl},function(t,e,i){function o(t){return t?n(t):void 0}function n(t){for(var e in o.prototype)t[e]=o.prototype[e];return t}t.exports=o,o.prototype.on=o.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks[t]=this._callbacks[t]||[]).push(e),this},o.prototype.once=function(t,e){function i(){o.off(t,i),e.apply(this,arguments)}var o=this;return this._callbacks=this._callbacks||{},i.fn=e,this.on(t,i),this},o.prototype.off=o.prototype.removeListener=o.prototype.removeAllListeners=o.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var i=this._callbacks[t];if(!i)return this;if(1==arguments.length)return delete this._callbacks[t],this;for(var o,n=0;no;++o)i[o].apply(this,e)}return this},o.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks[t]||[]},o.prototype.hasListeners=function(t){return!!this.listeners(t).length}},function(t,e,i){(function(t){!function(e,i){t.exports=i()}(this,function(){function e(){return Si.apply(null,arguments)}function i(t){Si=t}function o(t){return"[object Array]"===Object.prototype.toString.call(t)}function n(t){return t instanceof Date||"[object Date]"===Object.prototype.toString.call(t)}function s(t,e){var i,o=[];for(i=0;i0)for(i in Ii)o=Ii[i],n=e[o],"undefined"!=typeof n&&(t[o]=n);return t}function f(t){p(this,t),this._d=new Date(+t._d),Ni===!1&&(Ni=!0,e.updateOffset(this),Ni=!1)}function m(t){return t instanceof f||null!=t&&null!=t._isAMomentObject}function v(t){var e=+t,i=0;return 0!==e&&isFinite(e)&&(i=e>=0?Math.floor(e):Math.ceil(e)),i}function g(t,e,i){var o,n=Math.min(t.length,e.length),s=Math.abs(t.length-e.length),r=0;for(o=0;n>o;o++)(i&&t[o]!==e[o]||!i&&v(t[o])!==v(e[o]))&&r++;return r+s}function y(){}function b(t){return t?t.toLowerCase().replace("_","-"):t}function w(t){for(var e,i,o,n,s=0;s0;){if(o=_(n.slice(0,e).join("-")))return o;if(i&&i.length>=e&&g(n,i,!0)>=e-1)break;e--}s++}return null}function _(e){var i=null;if(!zi[e]&&"undefined"!=typeof t&&t&&t.exports)try{i=Pi._abbr,!function(){var t=new Error('Cannot find module "./locale"');throw t.code="MODULE_NOT_FOUND",t}(),x(i)}catch(o){}return zi[e]}function x(t,e){var i;return t&&(i="undefined"==typeof e?M(t):k(t,e),i&&(Pi=i)),Pi._abbr}function k(t,e){return null!==e?(e.abbr=t,zi[t]||(zi[t]=new y),zi[t].set(e),x(t),zi[t]):(delete zi[t],null)}function M(t){var e;if(t&&t._locale&&t._locale._abbr&&(t=t._locale._abbr),!t)return Pi;if(!o(t)){if(e=_(t))return e;t=[t]}return w(t)}function O(t,e){var i=t.toLowerCase();Ai[i]=Ai[i+"s"]=Ai[e]=t}function D(t){return"string"==typeof t?Ai[t]||Ai[t.toLowerCase()]:void 0}function T(t){var e,i,o={};for(i in t)r(t,i)&&(e=D(i),e&&(o[e]=t[i]));return o}function C(t,i){return function(o){return null!=o?(S(this,t,o),e.updateOffset(this,i),this):E(this,t)}}function E(t,e){return t._d["get"+(t._isUTC?"UTC":"")+e]()}function S(t,e,i){return t._d["set"+(t._isUTC?"UTC":"")+e](i)}function P(t,e){var i;if("object"==typeof t)for(i in t)this.set(i,t[i]);else if(t=D(t),"function"==typeof this[t])return this[t](e);return this}function I(t,e,i){for(var o=""+Math.abs(t),n=t>=0;o.lengthe;e++)Fi[o[e]]?o[e]=Fi[o[e]]:o[e]=z(o[e]);return function(n){var s="";for(e=0;i>e;e++)s+=o[e]instanceof Function?o[e].call(n,t):o[e];return s}}function L(t,e){return t.isValid()?(e=B(e,t.localeData()),Ri[e]||(Ri[e]=A(e)),Ri[e](t)):t.localeData().invalidDate()}function B(t,e){function i(t){return e.longDateFormat(t)||t}var o=5;for(Bi.lastIndex=0;o>=0&&Bi.test(t);)t=t.replace(Bi,i),Bi.lastIndex=0,o-=1;return t}function R(t,e,i){to[t]="function"==typeof e?e:function(t){return t&&i?i:e}}function F(t,e){return r(to,t)?to[t](e._strict,e._locale):new RegExp(j(t))}function j(t){return t.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(t,e,i,o,n){return e||i||o||n}).replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function H(t,e){var i,o=e;for("string"==typeof t&&(t=[t]),"number"==typeof e&&(o=function(t,i){i[e]=v(t)}),i=0;io;o++){if(n=h([2e3,o]),i&&!this._longMonthsParse[o]&&(this._longMonthsParse[o]=new RegExp("^"+this.months(n,"").replace(".","")+"$","i"),this._shortMonthsParse[o]=new RegExp("^"+this.monthsShort(n,"").replace(".","")+"$","i")),i||this._monthsParse[o]||(s="^"+this.months(n,"")+"|^"+this.monthsShort(n,""),this._monthsParse[o]=new RegExp(s.replace(".",""),"i")),i&&"MMMM"===e&&this._longMonthsParse[o].test(t))return o;if(i&&"MMM"===e&&this._shortMonthsParse[o].test(t))return o;if(!i&&this._monthsParse[o].test(t))return o}}function X(t,e){var i;return"string"==typeof e&&(e=t.localeData().monthsParse(e),"number"!=typeof e)?t:(i=Math.min(t.date(),G(t.year(),e)),t._d["set"+(t._isUTC?"UTC":"")+"Month"](e,i),t)}function Z(t){return null!=t?(X(this,t),e.updateOffset(this,!0),this):E(this,"Month")}function K(){return G(this.year(),this.month())}function J(t){var e,i=t._a;return i&&-2===l(t).overflow&&(e=i[oo]<0||i[oo]>11?oo:i[no]<1||i[no]>G(i[io],i[oo])?no:i[so]<0||i[so]>24||24===i[so]&&(0!==i[ro]||0!==i[ao]||0!==i[ho])?so:i[ro]<0||i[ro]>59?ro:i[ao]<0||i[ao]>59?ao:i[ho]<0||i[ho]>999?ho:-1,l(t)._overflowDayOfYear&&(io>e||e>no)&&(e=no),l(t).overflow=e),t}function Q(t){e.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+t)}function $(t,e){var i=!0,o=t+"\n"+(new Error).stack;return a(function(){return i&&(Q(o),i=!1),e.apply(this,arguments)},e)}function tt(t,e){co[t]||(Q(e),co[t]=!0)}function et(t){var e,i,o=t._i,n=po.exec(o);if(n){for(l(t).iso=!0,e=0,i=fo.length;i>e;e++)if(fo[e][1].exec(o)){t._f=fo[e][0]+(n[6]||" ");break}for(e=0,i=mo.length;i>e;e++)if(mo[e][1].exec(o)){t._f+=mo[e][0];break}o.match(Ji)&&(t._f+="Z"),wt(t)}else t._isValid=!1}function it(t){var i=vo.exec(t._i);return null!==i?void(t._d=new Date(+i[1])):(et(t),void(t._isValid===!1&&(delete t._isValid,e.createFromInputFallback(t))))}function ot(t,e,i,o,n,s,r){var a=new Date(t,e,i,o,n,s,r);return 1970>t&&a.setFullYear(t),a}function nt(t){var e=new Date(Date.UTC.apply(null,arguments));return 1970>t&&e.setUTCFullYear(t),e}function st(t){return rt(t)?366:365}function rt(t){return t%4===0&&t%100!==0||t%400===0}function at(){return rt(this.year())}function ht(t,e,i){var o,n=i-e,s=i-t.day();return s>n&&(s-=7),n-7>s&&(s+=7),o=Tt(t).add(s,"d"),{week:Math.ceil(o.dayOfYear()/7),year:o.year()}}function dt(t){return ht(t,this._week.dow,this._week.doy).week}function lt(){return this._week.dow}function ut(){return this._week.doy}function ct(t){var e=this.localeData().week(this);return null==t?e:this.add(7*(t-e),"d")}function pt(t){var e=ht(this,1,4).week;return null==t?e:this.add(7*(t-e),"d")}function ft(t,e,i,o,n){var s,r,a=nt(t,0,1).getUTCDay();return a=0===a?7:a,i=null!=i?i:n,s=n-a+(a>o?7:0)-(n>a?7:0),r=7*(e-1)+(i-n)+s+1,{year:r>0?t:t-1,dayOfYear:r>0?r:st(t-1)+r}}function mt(t){var e=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==t?e:this.add(t-e,"d")}function vt(t,e,i){return null!=t?t:null!=e?e:i}function gt(t){var e=new Date;return t._useUTC?[e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()]:[e.getFullYear(),e.getMonth(),e.getDate()]}function yt(t){var e,i,o,n,s=[];if(!t._d){for(o=gt(t),t._w&&null==t._a[no]&&null==t._a[oo]&&bt(t),t._dayOfYear&&(n=vt(t._a[io],o[io]),t._dayOfYear>st(n)&&(l(t)._overflowDayOfYear=!0),i=nt(n,0,t._dayOfYear),t._a[oo]=i.getUTCMonth(),t._a[no]=i.getUTCDate()),e=0;3>e&&null==t._a[e];++e)t._a[e]=s[e]=o[e];for(;7>e;e++)t._a[e]=s[e]=null==t._a[e]?2===e?1:0:t._a[e];24===t._a[so]&&0===t._a[ro]&&0===t._a[ao]&&0===t._a[ho]&&(t._nextDay=!0,t._a[so]=0),t._d=(t._useUTC?nt:ot).apply(null,s),null!=t._tzm&&t._d.setUTCMinutes(t._d.getUTCMinutes()-t._tzm),t._nextDay&&(t._a[so]=24)}}function bt(t){var e,i,o,n,s,r,a;e=t._w,null!=e.GG||null!=e.W||null!=e.E?(s=1,r=4,i=vt(e.GG,t._a[io],ht(Tt(),1,4).year),o=vt(e.W,1),n=vt(e.E,1)):(s=t._locale._week.dow,r=t._locale._week.doy,i=vt(e.gg,t._a[io],ht(Tt(),s,r).year),o=vt(e.w,1),null!=e.d?(n=e.d,s>n&&++o):n=null!=e.e?e.e+s:s),a=ft(i,o,n,r,s),t._a[io]=a.year,t._dayOfYear=a.dayOfYear}function wt(t){if(t._f===e.ISO_8601)return void et(t);t._a=[],l(t).empty=!0;var i,o,n,s,r,a=""+t._i,h=a.length,d=0;for(n=B(t._f,t._locale).match(Li)||[],i=0;i0&&l(t).unusedInput.push(r),a=a.slice(a.indexOf(o)+o.length),d+=o.length),Fi[s]?(o?l(t).empty=!1:l(t).unusedTokens.push(s),W(s,o,t)):t._strict&&!o&&l(t).unusedTokens.push(s);l(t).charsLeftOver=h-d,a.length>0&&l(t).unusedInput.push(a),l(t).bigHour===!0&&t._a[so]<=12&&t._a[so]>0&&(l(t).bigHour=void 0),t._a[so]=_t(t._locale,t._a[so],t._meridiem),yt(t),J(t)}function _t(t,e,i){var o;return null==i?e:null!=t.meridiemHour?t.meridiemHour(e,i):null!=t.isPM?(o=t.isPM(i),o&&12>e&&(e+=12),o||12!==e||(e=0),e):e}function xt(t){var e,i,o,n,s;if(0===t._f.length)return l(t).invalidFormat=!0,void(t._d=new Date(NaN));for(n=0;ns)&&(o=s,i=e));a(t,i||e)}function kt(t){if(!t._d){var e=T(t._i);t._a=[e.year,e.month,e.day||e.date,e.hour,e.minute,e.second,e.millisecond],yt(t)}}function Mt(t){var e,i=t._i,s=t._f;return t._locale=t._locale||M(t._l),null===i||void 0===s&&""===i?c({nullInput:!0}):("string"==typeof i&&(t._i=i=t._locale.preparse(i)),m(i)?new f(J(i)):(o(s)?xt(t):s?wt(t):n(i)?t._d=i:Ot(t),e=new f(J(t)),e._nextDay&&(e.add(1,"d"),e._nextDay=void 0),e))}function Ot(t){var i=t._i;void 0===i?t._d=new Date:n(i)?t._d=new Date(+i):"string"==typeof i?it(t):o(i)?(t._a=s(i.slice(0),function(t){return parseInt(t,10)}),yt(t)):"object"==typeof i?kt(t):"number"==typeof i?t._d=new Date(i):e.createFromInputFallback(t)}function Dt(t,e,i,o,n){var s={};return"boolean"==typeof i&&(o=i,i=void 0),s._isAMomentObject=!0,s._useUTC=s._isUTC=n,s._l=i,s._i=t,s._f=e,s._strict=o,Mt(s)}function Tt(t,e,i,o){return Dt(t,e,i,o,!1)}function Ct(t,e){var i,n;if(1===e.length&&o(e[0])&&(e=e[0]),!e.length)return Tt();for(i=e[0],n=1;nt&&(t=-t,i="-"),i+I(~~(t/60),2)+e+I(~~t%60,2)})}function zt(t){var e=(t||"").match(Ji)||[],i=e[e.length-1]||[],o=(i+"").match(_o)||["-",0,0],n=+(60*o[1])+v(o[2]);return"+"===o[0]?n:-n}function At(t,i){var o,s;return i._isUTC?(o=i.clone(),s=(m(t)||n(t)?+t:+Tt(t))-+o,o._d.setTime(+o._d+s),e.updateOffset(o,!1),o):Tt(t).local()}function Lt(t){return 15*-Math.round(t._d.getTimezoneOffset()/15)}function Bt(t,i){var o,n=this._offset||0;return null!=t?("string"==typeof t&&(t=zt(t)),Math.abs(t)<16&&(t=60*t),!this._isUTC&&i&&(o=Lt(this)),this._offset=t,this._isUTC=!0,null!=o&&this.add(o,"m"),n!==t&&(!i||this._changeInProgress?$t(this,Xt(t-n,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,e.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?n:Lt(this)}function Rt(t,e){return null!=t?("string"!=typeof t&&(t=-t),this.utcOffset(t,e),this):-this.utcOffset()}function Ft(t){return this.utcOffset(0,t)}function jt(t){return this._isUTC&&(this.utcOffset(0,t),this._isUTC=!1,t&&this.subtract(Lt(this),"m")),this}function Ht(){return this._tzm?this.utcOffset(this._tzm):"string"==typeof this._i&&this.utcOffset(zt(this._i)),this}function Yt(t){return t=t?Tt(t).utcOffset():0,(this.utcOffset()-t)%60===0}function Wt(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function Gt(){ -if(this._a){var t=this._isUTC?h(this._a):Tt(this._a);return this.isValid()&&g(this._a,t.toArray())>0}return!1}function Ut(){return!this._isUTC}function Vt(){return this._isUTC}function qt(){return this._isUTC&&0===this._offset}function Xt(t,e){var i,o,n,s=t,a=null;return It(t)?s={ms:t._milliseconds,d:t._days,M:t._months}:"number"==typeof t?(s={},e?s[e]=t:s.milliseconds=t):(a=xo.exec(t))?(i="-"===a[1]?-1:1,s={y:0,d:v(a[no])*i,h:v(a[so])*i,m:v(a[ro])*i,s:v(a[ao])*i,ms:v(a[ho])*i}):(a=ko.exec(t))?(i="-"===a[1]?-1:1,s={y:Zt(a[2],i),M:Zt(a[3],i),d:Zt(a[4],i),h:Zt(a[5],i),m:Zt(a[6],i),s:Zt(a[7],i),w:Zt(a[8],i)}):null==s?s={}:"object"==typeof s&&("from"in s||"to"in s)&&(n=Jt(Tt(s.from),Tt(s.to)),s={},s.ms=n.milliseconds,s.M=n.months),o=new Pt(s),It(t)&&r(t,"_locale")&&(o._locale=t._locale),o}function Zt(t,e){var i=t&&parseFloat(t.replace(",","."));return(isNaN(i)?0:i)*e}function Kt(t,e){var i={milliseconds:0,months:0};return i.months=e.month()-t.month()+12*(e.year()-t.year()),t.clone().add(i.months,"M").isAfter(e)&&--i.months,i.milliseconds=+e-+t.clone().add(i.months,"M"),i}function Jt(t,e){var i;return e=At(e,t),t.isBefore(e)?i=Kt(t,e):(i=Kt(e,t),i.milliseconds=-i.milliseconds,i.months=-i.months),i}function Qt(t,e){return function(i,o){var n,s;return null===o||isNaN(+o)||(tt(e,"moment()."+e+"(period, number) is deprecated. Please use moment()."+e+"(number, period)."),s=i,i=o,o=s),i="string"==typeof i?+i:i,n=Xt(i,o),$t(this,n,t),this}}function $t(t,i,o,n){var s=i._milliseconds,r=i._days,a=i._months;n=null==n?!0:n,s&&t._d.setTime(+t._d+s*o),r&&S(t,"Date",E(t,"Date")+r*o),a&&X(t,E(t,"Month")+a*o),n&&e.updateOffset(t,r||a)}function te(t){var e=t||Tt(),i=At(e,this).startOf("day"),o=this.diff(i,"days",!0),n=-6>o?"sameElse":-1>o?"lastWeek":0>o?"lastDay":1>o?"sameDay":2>o?"nextDay":7>o?"nextWeek":"sameElse";return this.format(this.localeData().calendar(n,this,Tt(e)))}function ee(){return new f(this)}function ie(t,e){var i;return e=D("undefined"!=typeof e?e:"millisecond"),"millisecond"===e?(t=m(t)?t:Tt(t),+this>+t):(i=m(t)?+t:+Tt(t),i<+this.clone().startOf(e))}function oe(t,e){var i;return e=D("undefined"!=typeof e?e:"millisecond"),"millisecond"===e?(t=m(t)?t:Tt(t),+t>+this):(i=m(t)?+t:+Tt(t),+this.clone().endOf(e)t?Math.ceil(t):Math.floor(t)}function ae(t,e,i){var o,n,s=At(t,this),r=6e4*(s.utcOffset()-this.utcOffset());return e=D(e),"year"===e||"month"===e||"quarter"===e?(n=he(this,s),"quarter"===e?n/=3:"year"===e&&(n/=12)):(o=this-s,n="second"===e?o/1e3:"minute"===e?o/6e4:"hour"===e?o/36e5:"day"===e?(o-r)/864e5:"week"===e?(o-r)/6048e5:o),i?n:re(n)}function he(t,e){var i,o,n=12*(e.year()-t.year())+(e.month()-t.month()),s=t.clone().add(n,"months");return 0>e-s?(i=t.clone().add(n-1,"months"),o=(e-s)/(s-i)):(i=t.clone().add(n+1,"months"),o=(e-s)/(i-s)),-(n+o)}function de(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function le(){var t=this.clone().utc();return 0e;e++)if(this._weekdaysParse[e]||(i=Tt([2e3,1]).day(e),o="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[e]=new RegExp(o.replace(".",""),"i")),this._weekdaysParse[e].test(t))return e}function Fe(t){var e=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=t?(t=ze(t,this.localeData()),this.add(t-e,"d")):e}function je(t){var e=(this.day()+7-this.localeData()._week.dow)%7;return null==t?e:this.add(t-e,"d")}function He(t){return null==t?this.day()||7:this.day(this.day()%7?t:t-7)}function Ye(t,e){N(t,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),e)})}function We(t,e){return e._meridiemParse}function Ge(t){return"p"===(t+"").toLowerCase().charAt(0)}function Ue(t,e,i){return t>11?i?"pm":"PM":i?"am":"AM"}function Ve(t){N(0,[t,3],0,"millisecond")}function qe(){return this._isUTC?"UTC":""}function Xe(){return this._isUTC?"Coordinated Universal Time":""}function Ze(t){return Tt(1e3*t)}function Ke(){return Tt.apply(null,arguments).parseZone()}function Je(t,e,i){var o=this._calendar[t];return"function"==typeof o?o.call(e,i):o}function Qe(t){var e=this._longDateFormat[t];return!e&&this._longDateFormat[t.toUpperCase()]&&(e=this._longDateFormat[t.toUpperCase()].replace(/MMMM|MM|DD|dddd/g,function(t){return t.slice(1)}),this._longDateFormat[t]=e),e}function $e(){return this._invalidDate}function ti(t){return this._ordinal.replace("%d",t)}function ei(t){return t}function ii(t,e,i,o){var n=this._relativeTime[i];return"function"==typeof n?n(t,e,i,o):n.replace(/%d/i,t)}function oi(t,e){var i=this._relativeTime[t>0?"future":"past"];return"function"==typeof i?i(e):i.replace(/%s/i,e)}function ni(t){var e,i;for(i in t)e=t[i],"function"==typeof e?this[i]=e:this["_"+i]=e;this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)}function si(t,e,i,o){var n=M(),s=h().set(o,e);return n[i](s,t)}function ri(t,e,i,o,n){if("number"==typeof t&&(e=t,t=void 0),t=t||"",null!=e)return si(t,e,i,n);var s,r=[];for(s=0;o>s;s++)r[s]=si(t,s,i,n);return r}function ai(t,e){return ri(t,e,"months",12,"month")}function hi(t,e){return ri(t,e,"monthsShort",12,"month")}function di(t,e){return ri(t,e,"weekdays",7,"day")}function li(t,e){return ri(t,e,"weekdaysShort",7,"day")}function ui(t,e){return ri(t,e,"weekdaysMin",7,"day")}function ci(){var t=this._data;return this._milliseconds=Uo(this._milliseconds),this._days=Uo(this._days),this._months=Uo(this._months),t.milliseconds=Uo(t.milliseconds),t.seconds=Uo(t.seconds),t.minutes=Uo(t.minutes),t.hours=Uo(t.hours),t.months=Uo(t.months),t.years=Uo(t.years),this}function pi(t,e,i,o){var n=Xt(e,i);return t._milliseconds+=o*n._milliseconds,t._days+=o*n._days,t._months+=o*n._months,t._bubble()}function fi(t,e){return pi(this,t,e,1)}function mi(t,e){return pi(this,t,e,-1)}function vi(){var t,e,i,o=this._milliseconds,n=this._days,s=this._months,r=this._data,a=0;return r.milliseconds=o%1e3,t=re(o/1e3),r.seconds=t%60,e=re(t/60),r.minutes=e%60,i=re(e/60),r.hours=i%24,n+=re(i/24),a=re(gi(n)),n-=re(yi(a)),s+=re(n/30),n%=30,a+=re(s/12),s%=12,r.days=n,r.months=s,r.years=a,this}function gi(t){return 400*t/146097}function yi(t){return 146097*t/400}function bi(t){var e,i,o=this._milliseconds;if(t=D(t),"month"===t||"year"===t)return e=this._days+o/864e5,i=this._months+12*gi(e),"month"===t?i:i/12;switch(e=this._days+Math.round(yi(this._months/12)),t){case"week":return e/7+o/6048e5;case"day":return e+o/864e5;case"hour":return 24*e+o/36e5;case"minute":return 1440*e+o/6e4;case"second":return 86400*e+o/1e3;case"millisecond":return Math.floor(864e5*e)+o;default:throw new Error("Unknown unit "+t)}}function wi(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*v(this._months/12)}function _i(t){return function(){return this.as(t)}}function xi(t){return t=D(t),this[t+"s"]()}function ki(t){return function(){return this._data[t]}}function Mi(){return re(this.days()/7)}function Oi(t,e,i,o,n){return n.relativeTime(e||1,!!i,t,o)}function Di(t,e,i){var o=Xt(t).abs(),n=hn(o.as("s")),s=hn(o.as("m")),r=hn(o.as("h")),a=hn(o.as("d")),h=hn(o.as("M")),d=hn(o.as("y")),l=n0,l[4]=i,Oi.apply(null,l)}function Ti(t,e){return void 0===dn[t]?!1:void 0===e?dn[t]:(dn[t]=e,!0)}function Ci(t){var e=this.localeData(),i=Di(this,!t,e);return t&&(i=e.pastFuture(+this,i)),e.postformat(i)}function Ei(){var t=ln(this.years()),e=ln(this.months()),i=ln(this.days()),o=ln(this.hours()),n=ln(this.minutes()),s=ln(this.seconds()+this.milliseconds()/1e3),r=this.asSeconds();return r?(0>r?"-":"")+"P"+(t?t+"Y":"")+(e?e+"M":"")+(i?i+"D":"")+(o||n||s?"T":"")+(o?o+"H":"")+(n?n+"M":"")+(s?s+"S":""):"P0D"}var Si,Pi,Ii=e.momentProperties=[],Ni=!1,zi={},Ai={},Li=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g,Bi=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Ri={},Fi={},ji=/\d/,Hi=/\d\d/,Yi=/\d{3}/,Wi=/\d{4}/,Gi=/[+-]?\d{6}/,Ui=/\d\d?/,Vi=/\d{1,3}/,qi=/\d{1,4}/,Xi=/[+-]?\d{1,6}/,Zi=/\d+/,Ki=/[+-]?\d+/,Ji=/Z|[+-]\d\d:?\d\d/gi,Qi=/[+-]?\d+(\.\d{1,3})?/,$i=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,to={},eo={},io=0,oo=1,no=2,so=3,ro=4,ao=5,ho=6;N("M",["MM",2],"Mo",function(){return this.month()+1}),N("MMM",0,0,function(t){return this.localeData().monthsShort(this,t)}),N("MMMM",0,0,function(t){return this.localeData().months(this,t)}),O("month","M"),R("M",Ui),R("MM",Ui,Hi),R("MMM",$i),R("MMMM",$i),H(["M","MM"],function(t,e){e[oo]=v(t)-1}),H(["MMM","MMMM"],function(t,e,i,o){var n=i._locale.monthsParse(t,o,i._strict);null!=n?e[oo]=n:l(i).invalidMonth=t});var lo="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),uo="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),co={};e.suppressDeprecationWarnings=!1;var po=/^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,fo=[["YYYYYY-MM-DD",/[+-]\d{6}-\d{2}-\d{2}/],["YYYY-MM-DD",/\d{4}-\d{2}-\d{2}/],["GGGG-[W]WW-E",/\d{4}-W\d{2}-\d/],["GGGG-[W]WW",/\d{4}-W\d{2}/],["YYYY-DDD",/\d{4}-\d{3}/]],mo=[["HH:mm:ss.SSSS",/(T| )\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],vo=/^\/?Date\((\-?\d+)/i;e.createFromInputFallback=$("moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.",function(t){t._d=new Date(t._i+(t._useUTC?" UTC":""))}),N(0,["YY",2],0,function(){return this.year()%100}),N(0,["YYYY",4],0,"year"),N(0,["YYYYY",5],0,"year"),N(0,["YYYYYY",6,!0],0,"year"),O("year","y"),R("Y",Ki),R("YY",Ui,Hi),R("YYYY",qi,Wi),R("YYYYY",Xi,Gi),R("YYYYYY",Xi,Gi),H(["YYYY","YYYYY","YYYYYY"],io),H("YY",function(t,i){i[io]=e.parseTwoDigitYear(t)}),e.parseTwoDigitYear=function(t){return v(t)+(v(t)>68?1900:2e3)};var go=C("FullYear",!1);N("w",["ww",2],"wo","week"),N("W",["WW",2],"Wo","isoWeek"),O("week","w"),O("isoWeek","W"),R("w",Ui),R("ww",Ui,Hi),R("W",Ui),R("WW",Ui,Hi),Y(["w","ww","W","WW"],function(t,e,i,o){e[o.substr(0,1)]=v(t)});var yo={dow:0,doy:6};N("DDD",["DDDD",3],"DDDo","dayOfYear"),O("dayOfYear","DDD"),R("DDD",Vi),R("DDDD",Yi),H(["DDD","DDDD"],function(t,e,i){i._dayOfYear=v(t)}),e.ISO_8601=function(){};var bo=$("moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548",function(){var t=Tt.apply(null,arguments);return this>t?this:t}),wo=$("moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548",function(){var t=Tt.apply(null,arguments);return t>this?this:t});Nt("Z",":"),Nt("ZZ",""),R("Z",Ji),R("ZZ",Ji),H(["Z","ZZ"],function(t,e,i){i._useUTC=!0,i._tzm=zt(t)});var _o=/([\+\-]|\d\d)/gi;e.updateOffset=function(){};var xo=/(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,ko=/^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/;Xt.fn=Pt.prototype;var Mo=Qt(1,"add"),Oo=Qt(-1,"subtract");e.defaultFormat="YYYY-MM-DDTHH:mm:ssZ";var Do=$("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(t){return void 0===t?this.localeData():this.locale(t)});N(0,["gg",2],0,function(){return this.weekYear()%100}),N(0,["GG",2],0,function(){return this.isoWeekYear()%100}),Te("gggg","weekYear"),Te("ggggg","weekYear"),Te("GGGG","isoWeekYear"),Te("GGGGG","isoWeekYear"),O("weekYear","gg"),O("isoWeekYear","GG"),R("G",Ki),R("g",Ki),R("GG",Ui,Hi),R("gg",Ui,Hi),R("GGGG",qi,Wi),R("gggg",qi,Wi),R("GGGGG",Xi,Gi),R("ggggg",Xi,Gi),Y(["gggg","ggggg","GGGG","GGGGG"],function(t,e,i,o){e[o.substr(0,2)]=v(t)}),Y(["gg","GG"],function(t,i,o,n){i[n]=e.parseTwoDigitYear(t)}),N("Q",0,0,"quarter"),O("quarter","Q"),R("Q",ji),H("Q",function(t,e){e[oo]=3*(v(t)-1)}),N("D",["DD",2],"Do","date"),O("date","D"),R("D",Ui),R("DD",Ui,Hi),R("Do",function(t,e){return t?e._ordinalParse:e._ordinalParseLenient}),H(["D","DD"],no),H("Do",function(t,e){e[no]=v(t.match(Ui)[0],10)});var To=C("Date",!0);N("d",0,"do","day"),N("dd",0,0,function(t){return this.localeData().weekdaysMin(this,t)}),N("ddd",0,0,function(t){return this.localeData().weekdaysShort(this,t)}),N("dddd",0,0,function(t){return this.localeData().weekdays(this,t)}),N("e",0,0,"weekday"),N("E",0,0,"isoWeekday"),O("day","d"),O("weekday","e"),O("isoWeekday","E"),R("d",Ui),R("e",Ui),R("E",Ui),R("dd",$i),R("ddd",$i),R("dddd",$i),Y(["dd","ddd","dddd"],function(t,e,i){var o=i._locale.weekdaysParse(t);null!=o?e.d=o:l(i).invalidWeekday=t}),Y(["d","e","E"],function(t,e,i,o){e[o]=v(t)});var Co="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Eo="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),So="Su_Mo_Tu_We_Th_Fr_Sa".split("_");N("H",["HH",2],0,"hour"),N("h",["hh",2],0,function(){return this.hours()%12||12}),Ye("a",!0),Ye("A",!1),O("hour","h"),R("a",We),R("A",We),R("H",Ui),R("h",Ui),R("HH",Ui,Hi),R("hh",Ui,Hi),H(["H","HH"],so),H(["a","A"],function(t,e,i){i._isPm=i._locale.isPM(t),i._meridiem=t}),H(["h","hh"],function(t,e,i){e[so]=v(t),l(i).bigHour=!0});var Po=/[ap]\.?m?\.?/i,Io=C("Hours",!0);N("m",["mm",2],0,"minute"),O("minute","m"),R("m",Ui),R("mm",Ui,Hi),H(["m","mm"],ro);var No=C("Minutes",!1);N("s",["ss",2],0,"second"),O("second","s"),R("s",Ui),R("ss",Ui,Hi),H(["s","ss"],ao);var zo=C("Seconds",!1);N("S",0,0,function(){return~~(this.millisecond()/100)}),N(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),Ve("SSS"),Ve("SSSS"),O("millisecond","ms"),R("S",Vi,ji),R("SS",Vi,Hi),R("SSS",Vi,Yi),R("SSSS",Zi),H(["S","SS","SSS","SSSS"],function(t,e){e[ho]=v(1e3*("0."+t))});var Ao=C("Milliseconds",!1);N("z",0,0,"zoneAbbr"),N("zz",0,0,"zoneName");var Lo=f.prototype;Lo.add=Mo,Lo.calendar=te,Lo.clone=ee,Lo.diff=ae,Lo.endOf=be,Lo.format=ue,Lo.from=ce,Lo.fromNow=pe,Lo.to=fe,Lo.toNow=me,Lo.get=P,Lo.invalidAt=De,Lo.isAfter=ie,Lo.isBefore=oe,Lo.isBetween=ne,Lo.isSame=se,Lo.isValid=Me,Lo.lang=Do,Lo.locale=ve,Lo.localeData=ge,Lo.max=wo,Lo.min=bo,Lo.parsingFlags=Oe,Lo.set=P,Lo.startOf=ye,Lo.subtract=Oo,Lo.toArray=ke,Lo.toDate=xe,Lo.toISOString=le,Lo.toJSON=le,Lo.toString=de,Lo.unix=_e,Lo.valueOf=we,Lo.year=go,Lo.isLeapYear=at,Lo.weekYear=Ee,Lo.isoWeekYear=Se,Lo.quarter=Lo.quarters=Ne,Lo.month=Z,Lo.daysInMonth=K,Lo.week=Lo.weeks=ct,Lo.isoWeek=Lo.isoWeeks=pt,Lo.weeksInYear=Ie,Lo.isoWeeksInYear=Pe,Lo.date=To,Lo.day=Lo.days=Fe,Lo.weekday=je,Lo.isoWeekday=He,Lo.dayOfYear=mt,Lo.hour=Lo.hours=Io,Lo.minute=Lo.minutes=No,Lo.second=Lo.seconds=zo,Lo.millisecond=Lo.milliseconds=Ao,Lo.utcOffset=Bt,Lo.utc=Ft,Lo.local=jt,Lo.parseZone=Ht,Lo.hasAlignedHourOffset=Yt,Lo.isDST=Wt,Lo.isDSTShifted=Gt,Lo.isLocal=Ut,Lo.isUtcOffset=Vt,Lo.isUtc=qt,Lo.isUTC=qt,Lo.zoneAbbr=qe,Lo.zoneName=Xe,Lo.dates=$("dates accessor is deprecated. Use date instead.",To),Lo.months=$("months accessor is deprecated. Use month instead",Z),Lo.years=$("years accessor is deprecated. Use year instead",go),Lo.zone=$("moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779",Rt);var Bo=Lo,Ro={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},Fo={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY LT",LLLL:"dddd, MMMM D, YYYY LT"},jo="Invalid date",Ho="%d",Yo=/\d{1,2}/,Wo={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},Go=y.prototype;Go._calendar=Ro,Go.calendar=Je,Go._longDateFormat=Fo,Go.longDateFormat=Qe,Go._invalidDate=jo,Go.invalidDate=$e,Go._ordinal=Ho,Go.ordinal=ti,Go._ordinalParse=Yo,Go.preparse=ei,Go.postformat=ei,Go._relativeTime=Wo,Go.relativeTime=ii,Go.pastFuture=oi,Go.set=ni,Go.months=U,Go._months=lo,Go.monthsShort=V,Go._monthsShort=uo,Go.monthsParse=q,Go.week=dt,Go._week=yo,Go.firstDayOfYear=ut,Go.firstDayOfWeek=lt,Go.weekdays=Ae,Go._weekdays=Co,Go.weekdaysMin=Be,Go._weekdaysMin=So,Go.weekdaysShort=Le,Go._weekdaysShort=Eo,Go.weekdaysParse=Re,Go.isPM=Ge,Go._meridiemParse=Po,Go.meridiem=Ue,x("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(t){var e=t%10,i=1===v(t%100/10)?"th":1===e?"st":2===e?"nd":3===e?"rd":"th";return t+i}}),e.lang=$("moment.lang is deprecated. Use moment.locale instead.",x),e.langData=$("moment.langData is deprecated. Use moment.localeData instead.",M);var Uo=Math.abs,Vo=_i("ms"),qo=_i("s"),Xo=_i("m"),Zo=_i("h"),Ko=_i("d"),Jo=_i("w"),Qo=_i("M"),$o=_i("y"),tn=ki("milliseconds"),en=ki("seconds"),on=ki("minutes"),nn=ki("hours"),sn=ki("days"),rn=ki("months"),an=ki("years"),hn=Math.round,dn={s:45,m:45,h:22,d:26,M:11},ln=Math.abs,un=Pt.prototype;un.abs=ci,un.add=fi,un.subtract=mi,un.as=bi,un.asMilliseconds=Vo,un.asSeconds=qo,un.asMinutes=Xo,un.asHours=Zo,un.asDays=Ko,un.asWeeks=Jo,un.asMonths=Qo,un.asYears=$o,un.valueOf=wi,un._bubble=vi,un.get=xi,un.milliseconds=tn,un.seconds=en,un.minutes=on,un.hours=nn,un.days=sn,un.weeks=Mi,un.months=rn,un.years=an,un.humanize=Ci,un.toISOString=Ei,un.toString=Ei,un.toJSON=Ei,un.locale=ve,un.localeData=ge,un.toIsoString=$("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Ei),un.lang=Do,N("X",0,0,"unix"),N("x",0,0,"valueOf"),R("x",Ki),R("X",Qi),H("X",function(t,e,i){i._d=new Date(1e3*parseFloat(t,10))}),H("x",function(t,e,i){i._d=new Date(v(t))}),e.version="2.10.3",i(Tt),e.fn=Bo,e.min=Et,e.max=St,e.utc=h,e.unix=Ze,e.months=ai,e.isDate=n,e.locale=x,e.invalid=c,e.duration=Xt,e.isMoment=m,e.weekdays=di,e.parseZone=Ke,e.localeData=M,e.isDuration=It,e.monthsShort=hi,e.weekdaysMin=ui,e.defineLocale=k,e.weekdaysShort=li,e.normalizeUnits=D,e.relativeTimeThreshold=Ti;var cn=e;return cn})}).call(e,i(107)(t))},function(t,e,i){var o,n,s;!function(i){n=[],o=i,s="function"==typeof o?o.apply(e,n):o,!(void 0!==s&&(t.exports=s))}(function(){var t=null,e=!1;return function i(o,n){function s(t){return t.match(/[^ ]+/g)}function r(e){if("hammer.input"!==e.type){if(e.srcEvent._handled||(e.srcEvent._handled={}),e.srcEvent._handled[e.type])return;e.srcEvent._handled[e.type]=!0}var i=!1;e.stopPropagation=function(){i=!0},e.firstTarget=t;for(var o=t;o&&!i;){var n=o.hammer&&o.hammer._handlers[e.type];if(n)for(var s=0;s0?o._handlers[t]=i:(o._off(t,r),delete o._handlers[t]))}),o},o.emit=function(i,n){e||(t=n.target),o._emit(i,n)},o.destroy=function(){var t=o.element;delete t.hammer,o._handlers={},o._destroy()},o}})},function(t,e,i){var o;!function(n,s,r,a){function h(t,e,i){return setTimeout(f(t,i),e)}function d(t,e,i){return Array.isArray(t)?(l(t,i[e],i),!0):!1}function l(t,e,i){var o;if(t)if(t.forEach)t.forEach(e,i);else if(t.length!==a)for(o=0;o-1}function _(t){return t.trim().split(/\s+/g)}function x(t,e,i){if(t.indexOf&&!i)return t.indexOf(e);for(var o=0;oi[e]}):o.sort()),o}function O(t,e){for(var i,o,n=e[0].toUpperCase()+e.slice(1),s=0;s1&&!i.firstMultiple?i.firstMultiple=z(e):1===n&&(i.firstMultiple=!1);var s=i.firstInput,r=i.firstMultiple,a=r?r.center:s.center,h=e.center=A(o);e.timeStamp=gt(),e.deltaTime=e.timeStamp-s.timeStamp,e.angle=F(a,h),e.distance=R(a,h),I(i,e),e.offsetDirection=B(e.deltaX,e.deltaY),e.scale=r?H(r.pointers,o):1,e.rotation=r?j(r.pointers,o):0,N(i,e);var d=t.element;b(e.srcEvent.target,d)&&(d=e.srcEvent.target),e.target=d}function I(t,e){var i=e.center,o=t.offsetDelta||{},n=t.prevDelta||{},s=t.prevInput||{};(e.eventType===Ct||s.eventType===St)&&(n=t.prevDelta={x:s.deltaX||0,y:s.deltaY||0},o=t.offsetDelta={x:i.x,y:i.y}),e.deltaX=n.x+(i.x-o.x),e.deltaY=n.y+(i.y-o.y)}function N(t,e){var i,o,n,s,r=t.lastInterval||e,h=e.timeStamp-r.timeStamp;if(e.eventType!=Pt&&(h>Tt||r.velocity===a)){var d=r.deltaX-e.deltaX,l=r.deltaY-e.deltaY,u=L(h,d,l);o=u.x,n=u.y,i=vt(u.x)>vt(u.y)?u.x:u.y,s=B(d,l),t.lastInterval=e}else i=r.velocity,o=r.velocityX,n=r.velocityY,s=r.direction;e.velocity=i,e.velocityX=o,e.velocityY=n,e.direction=s}function z(t){for(var e=[],i=0;in;)i+=t[n].clientX,o+=t[n].clientY,n++;return{x:mt(i/e),y:mt(o/e)}}function L(t,e,i){return{x:e/t||0,y:i/t||0}}function B(t,e){return t===e?It:vt(t)>=vt(e)?t>0?Nt:zt:e>0?At:Lt}function R(t,e,i){i||(i=jt);var o=e[i[0]]-t[i[0]],n=e[i[1]]-t[i[1]];return Math.sqrt(o*o+n*n)}function F(t,e,i){i||(i=jt);var o=e[i[0]]-t[i[0]],n=e[i[1]]-t[i[1]];return 180*Math.atan2(n,o)/Math.PI}function j(t,e){return F(e[1],e[0],Ht)-F(t[1],t[0],Ht)}function H(t,e){return R(e[0],e[1],Ht)/R(t[0],t[1],Ht)}function Y(){this.evEl=Wt,this.evWin=Gt,this.allow=!0,this.pressed=!1,C.apply(this,arguments)}function W(){this.evEl=qt,this.evWin=Xt,C.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}function G(){this.evTarget=Kt,this.evWin=Jt,this.started=!1,C.apply(this,arguments)}function U(t,e){var i=k(t.touches),o=k(t.changedTouches);return e&(St|Pt)&&(i=M(i.concat(o),"identifier",!0)),[i,o]}function V(){this.evTarget=$t,this.targetIds={},C.apply(this,arguments)}function q(t,e){var i=k(t.touches),o=this.targetIds;if(e&(Ct|Et)&&1===i.length)return o[i[0].identifier]=!0,[i,i];var n,s,r=k(t.changedTouches),a=[],h=this.target;if(s=i.filter(function(t){return b(t.target,h)}),e===Ct)for(n=0;na&&(e.push(t),a=e.length-1):n&(St|Pt)&&(i=!0),0>a||(e[a]=t,this.callback(this.manager,n,{pointers:e,changedPointers:[t],pointerType:s,srcEvent:t}),i&&e.splice(a,1))}});var Zt={touchstart:Ct,touchmove:Et,touchend:St,touchcancel:Pt},Kt="touchstart",Jt="touchstart touchmove touchend touchcancel";p(G,C,{handler:function(t){var e=Zt[t.type];if(e===Ct&&(this.started=!0),this.started){var i=U.call(this,t,e);e&(St|Pt)&&i[0].length-i[1].length===0&&(this.started=!1),this.callback(this.manager,e,{pointers:i[0],changedPointers:i[1],pointerType:kt,srcEvent:t})}}});var Qt={touchstart:Ct,touchmove:Et,touchend:St,touchcancel:Pt},$t="touchstart touchmove touchend touchcancel";p(V,C,{handler:function(t){var e=Qt[t.type],i=q.call(this,t,e);i&&this.callback(this.manager,e,{pointers:i[0],changedPointers:i[1],pointerType:kt,srcEvent:t})}}),p(X,C,{handler:function(t,e,i){var o=i.pointerType==kt,n=i.pointerType==Ot;if(o)this.mouse.allow=!1;else if(n&&!this.mouse.allow)return;e&(St|Pt)&&(this.mouse.allow=!0),this.callback(t,e,i)},destroy:function(){this.touch.destroy(),this.mouse.destroy()}});var te=O(pt.style,"touchAction"),ee=te!==a,ie="compute",oe="auto",ne="manipulation",se="none",re="pan-x",ae="pan-y";Z.prototype={set:function(t){t==ie&&(t=this.compute()),ee&&(this.manager.element.style[te]=t),this.actions=t.toLowerCase().trim()},update:function(){this.set(this.manager.options.touchAction)},compute:function(){ -var t=[];return l(this.manager.recognizers,function(e){m(e.options.enable,[e])&&(t=t.concat(e.getTouchAction()))}),K(t.join(" "))},preventDefaults:function(t){if(!ee){var e=t.srcEvent,i=t.offsetDirection;if(this.manager.session.prevented)return void e.preventDefault();var o=this.actions,n=w(o,se),s=w(o,ae),r=w(o,re);return n||s&&i&Bt||r&&i&Rt?this.preventSrc(e):void 0}},preventSrc:function(t){this.manager.session.prevented=!0,t.preventDefault()}};var he=1,de=2,le=4,ue=8,ce=ue,pe=16,fe=32;J.prototype={defaults:{},set:function(t){return u(this.options,t),this.manager&&this.manager.touchAction.update(),this},recognizeWith:function(t){if(d(t,"recognizeWith",this))return this;var e=this.simultaneous;return t=tt(t,this),e[t.id]||(e[t.id]=t,t.recognizeWith(this)),this},dropRecognizeWith:function(t){return d(t,"dropRecognizeWith",this)?this:(t=tt(t,this),delete this.simultaneous[t.id],this)},requireFailure:function(t){if(d(t,"requireFailure",this))return this;var e=this.requireFail;return t=tt(t,this),-1===x(e,t)&&(e.push(t),t.requireFailure(this)),this},dropRequireFailure:function(t){if(d(t,"dropRequireFailure",this))return this;t=tt(t,this);var e=x(this.requireFail,t);return e>-1&&this.requireFail.splice(e,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(t){return!!this.simultaneous[t.id]},emit:function(t){function e(e){i.manager.emit(i.options.event+(e?Q(o):""),t)}var i=this,o=this.state;ue>o&&e(!0),e(),o>=ue&&e(!0)},tryEmit:function(t){return this.canEmit()?this.emit(t):void(this.state=fe)},canEmit:function(){for(var t=0;ts?Nt:zt,i=s!=this.pX,o=Math.abs(t.deltaX)):(n=0===r?It:0>r?At:Lt,i=r!=this.pY,o=Math.abs(t.deltaY))),t.direction=n,i&&o>e.threshold&&n&e.direction},attrTest:function(t){return et.prototype.attrTest.call(this,t)&&(this.state&de||!(this.state&de)&&this.directionTest(t))},emit:function(t){this.pX=t.deltaX,this.pY=t.deltaY;var e=$(t.direction);e&&this.manager.emit(this.options.event+e,t),this._super.emit.call(this,t)}}),p(ot,et,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[se]},attrTest:function(t){return this._super.attrTest.call(this,t)&&(Math.abs(t.scale-1)>this.options.threshold||this.state&de)},emit:function(t){if(this._super.emit.call(this,t),1!==t.scale){var e=t.scale<1?"in":"out";this.manager.emit(this.options.event+e,t)}}}),p(nt,J,{defaults:{event:"press",pointers:1,time:500,threshold:5},getTouchAction:function(){return[oe]},process:function(t){var e=this.options,i=t.pointers.length===e.pointers,o=t.distancee.time;if(this._input=t,!o||!i||t.eventType&(St|Pt)&&!n)this.reset();else if(t.eventType&Ct)this.reset(),this._timer=h(function(){this.state=ce,this.tryEmit()},e.time,this);else if(t.eventType&St)return ce;return fe},reset:function(){clearTimeout(this._timer)},emit:function(t){this.state===ce&&(t&&t.eventType&St?this.manager.emit(this.options.event+"up",t):(this._input.timeStamp=gt(),this.manager.emit(this.options.event,this._input)))}}),p(st,et,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[se]},attrTest:function(t){return this._super.attrTest.call(this,t)&&(Math.abs(t.rotation)>this.options.threshold||this.state&de)}}),p(rt,et,{defaults:{event:"swipe",threshold:10,velocity:.65,direction:Bt|Rt,pointers:1},getTouchAction:function(){return it.prototype.getTouchAction.call(this)},attrTest:function(t){var e,i=this.options.direction;return i&(Bt|Rt)?e=t.velocity:i&Bt?e=t.velocityX:i&Rt&&(e=t.velocityY),this._super.attrTest.call(this,t)&&i&t.direction&&t.distance>this.options.threshold&&vt(e)>this.options.velocity&&t.eventType&St},emit:function(t){var e=$(t.direction);e&&this.manager.emit(this.options.event+e,t),this.manager.emit(this.options.event,t)}}),p(at,J,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:2,posThreshold:10},getTouchAction:function(){return[ne]},process:function(t){var e=this.options,i=t.pointers.length===e.pointers,o=t.distances;s++)for(r=0;rp?p+1:p;var f=l/this.r,m=a.RGBToHSV(this.color.r,this.color.g,this.color.b);m.h=p,m.s=f;var v=a.HSVToRGB(m.h,m.s,m.v);v.a=this.color.a,this.color=v,this.initialColorDiv.style.backgroundColor="rgba("+this.initialColor.r+","+this.initialColor.g+","+this.initialColor.b+","+this.initialColor.a+")",this.newColorDiv.style.backgroundColor="rgba("+this.color.r+","+this.color.g+","+this.color.b+","+this.color.a+")"}}]),t}();e["default"]=h,t.exports=e["default"]},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function t(t,e){for(var i=0;it.left&&this.shape.topt.top}},{key:"isBoundingBoxOverlappingWith",value:function(t){return this.shape.boundingBox.leftt.left&&this.shape.boundingBox.topt.top}}],[{key:"parseOptions",value:function(t,e){var i=void 0===arguments[2]?!1:arguments[2],o=["color","font","fixed","shadow"];if(B.selectiveNotDeepExtend(o,t,e,i),B.mergeOptions(t,e,"shadow"),void 0!==e.color&&null!==e.color){var n=B.parseColor(e.color);B.fillIfDefined(t.color,n)}else i===!0&&null===e.color&&(t.color=void 0,delete t.color);void 0!==e.fixed&&null!==e.fixed&&("boolean"==typeof e.fixed?(t.fixed.x=e.fixed,t.fixed.y=e.fixed):(void 0!==e.fixed.x&&"boolean"==typeof e.fixed.x&&(t.fixed.x=e.fixed.x),void 0!==e.fixed.y&&"boolean"==typeof e.fixed.y&&(t.fixed.y=e.fixed.y))),void 0!==e.font&&a["default"].parseOptions(t.font,e),void 0!==e.scaling&&B.mergeOptions(t.scaling,e.scaling,"label")}}]),t}();e["default"]=R,t.exports=e["default"]},function(t,e,i){function o(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t)){var i=[],o=!0,n=!1,s=void 0;try{for(var r,a=t[Symbol.iterator]();!(o=(r=a.next()).done)&&(i.push(r.value),!e||i.length!==e);o=!0);}catch(h){n=!0,s=h}finally{try{!o&&a["return"]&&a["return"]()}finally{if(n)throw s}}return i}throw new TypeError("Invalid attempt to destructure non-iterable instance")}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function t(t,e){for(var i=0;i=this.options.scaling.label.maxVisible&&(r=Number(this.options.scaling.label.maxVisible)/this.body.view.scale);var h=this.size.yLine,d=this._getColor(a),l=o(d,2),u=l[0],c=l[1],p=this._setAlignment(t,i,h,s),f=o(p,2);i=f[0],h=f[1],t.font=(e?"bold ":"")+r+"px "+this.options.font.face,t.fillStyle=u,t.textAlign="center",this.options.font.strokeWidth>0&&(t.lineWidth=this.options.font.strokeWidth,t.strokeStyle=c,t.lineJoin="round");for(var m=0;m0&&t.strokeText(this.lines[m],i,h),t.fillText(this.lines[m],i,h),h+=r}},{key:"_setAlignment",value:function(t,e,i,o){if("horizontal"!==this.options.font.align){e=0,i=0;var n=2;"top"===this.options.font.align?(t.textBaseline="alphabetic",i-=2*n):"bottom"===this.options.font.align?(t.textBaseline="hanging",i+=2*n):t.textBaseline="middle"}else t.textBaseline=o;return[e,i]}},{key:"_getColor",value:function(t){var e=this.options.font.color||"#000000",i=this.options.font.strokeColor||"#ffffff";if(t<=this.options.scaling.label.drawThreshold){ -var o=Math.max(0,Math.min(1,1-(this.options.scaling.label.drawThreshold-t)));e=r.overrideOpacity(e,o),i=r.overrideOpacity(i,o)}return[e,i]}},{key:"getTextSize",value:function(t){var e=void 0===arguments[1]?!1:arguments[1],i={width:this._processLabel(t,e),height:this.options.font.size*this.lineCount,lineCount:this.lineCount};return i}},{key:"calculateLabelSize",value:function(t,e){var i=void 0===arguments[2]?0:arguments[2],o=void 0===arguments[3]?0:arguments[3],n=void 0===arguments[4]?"middle":arguments[4];this.labelDirty===!0&&(this.size.width=this._processLabel(t,e)),this.size.height=this.options.font.size*this.lineCount,this.size.left=i-.5*this.size.width,this.size.top=o-.5*this.size.height,this.size.yLine=o+.5*(1-this.lineCount)*this.options.font.size,"hanging"===n&&(this.size.top+=.5*this.options.font.size,this.size.top+=4,this.size.yLine+=4),this.labelDirty=!1}},{key:"_processLabel",value:function(t,e){var i=0,o=[""],n=0;if(void 0!==this.options.label){o=String(this.options.label).split("\n"),n=o.length,t.font=(e?"bold ":"")+this.options.font.size+"px "+this.options.font.face,i=t.measureText(o[0]).width;for(var s=1;n>s;s++){var r=t.measureText(o[s]).width;i=r>i?r:i}}return this.lines=o,this.lineCount=n,i}}],[{key:"parseOptions",value:function(t,e){var i=void 0===arguments[2]?!1:arguments[2];if("string"==typeof e.font){var o=e.font.split(" ");t.size=o[0].replace("px",""),t.face=o[1],t.color=o[2]}else"object"==typeof e.font&&r.fillIfDefined(t,e.font,i);t.size=Number(t.size)}}]),t}();e["default"]=a,t.exports=e["default"]},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function t(t,e){for(var i=0;ii.shape.height?(r=i.x+.5*i.shape.width,a=i.y-h):(r=i.x+h,a=i.y-.5*i.shape.height),s=this._pointOnCircle(r,a,h,.125),this.labelModule.draw(t,s.x,s.y,n)}}}},{key:"isOverlappingWith",value:function(t){if(this.connected){var e=10,i=this.from.x,o=this.from.y,n=this.to.x,s=this.to.y,r=t.left,a=t.top,h=this.edgeType.getDistanceToEdge(i,o,n,s,r,a);return e>h}return!1}},{key:"_rotateForLabelAlignment",value:function(t){var e=this.from.y-this.to.y,i=this.from.x-this.to.x,o=Math.atan2(e,i);(-1>o&&0>i||o>0&&0>i)&&(o+=Math.PI),t.rotate(o)}},{key:"_pointOnCircle",value:function(t,e,i,o){var n=2*o*Math.PI;return{x:t+i*Math.cos(n),y:e-i*Math.sin(n)}}},{key:"select",value:function(){this.selected=!0}},{key:"unselect",value:function(){this.selected=!1}}],[{key:"parseOptions",value:function(t,e){var i=void 0===arguments[2]?!1:arguments[2],o=["id","from","hidden","hoverWidth","label","length","line","opacity","physics","selectionWidth","selfReferenceSize","to","title","value","width"];if(f.selectiveDeepExtend(o,t,e,i),f.mergeOptions(t,e,"smooth"),f.mergeOptions(t,e,"shadow"),void 0!==e.dashes&&null!==e.dashes?t.dashes=e.dashes:i===!0&&null===e.dashes&&(t.dashes=void 0,delete t.dashes),void 0!==e.scaling&&null!==e.scaling?(void 0!==e.scaling.min&&(t.scaling.min=e.scaling.min),void 0!==e.scaling.max&&(t.scaling.max=e.scaling.max),f.mergeOptions(t.scaling,e.scaling,"label")):i===!0&&null===e.scaling&&(t.scaling=void 0,delete t.scaling),void 0!==e.arrows&&null!==e.arrows)if("string"==typeof e.arrows){var n=e.arrows.toLowerCase();-1!=n.indexOf("to")&&(t.arrows.to.enabled=!0),-1!=n.indexOf("middle")&&(t.arrows.middle.enabled=!0),-1!=n.indexOf("from")&&(t.arrows.from.enabled=!0)}else{if("object"!=typeof e.arrows)throw new Error("The arrow newOptions can only be an object or a string. Refer to the documentation. You used:"+JSON.stringify(e.arrows));f.mergeOptions(t.arrows,e.arrows,"to"),f.mergeOptions(t.arrows,e.arrows,"middle"),f.mergeOptions(t.arrows,e.arrows,"from")}else i===!0&&null===e.arrows&&(t.arrows=void 0,delete t.arrows);if(void 0!==e.color&&null!==e.color)if(f.isString(e.color))t.color.color=e.color,t.color.highlight=e.color,t.color.hover=e.color,t.color.inherit=!1;else{var s=!1;void 0!==e.color.color&&(t.color.color=e.color.color,s=!0),void 0!==e.color.highlight&&(t.color.highlight=e.color.highlight,s=!0),void 0!==e.color.hover&&(t.color.hover=e.color.hover,s=!0),void 0!==e.color.inherit&&(t.color.inherit=e.color.inherit),void 0!==e.color.opacity&&(t.color.opacity=Math.min(1,Math.max(0,e.color.opacity))),void 0===e.color.inherit&&s===!0&&(t.color.inherit=!1)}else i===!0&&null===e.color&&(t.color=void 0,delete t.color);void 0!==e.font&&a["default"].parseOptions(t.font,e)}}]),t}();e["default"]=m,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;i0){var t=void 0,e=this.body.nodes,i=this.physicsBody.physicsNodeIndices,o=i.length,n=this._formBarnesHutTree(e,i);this.barnesHutTree=n;for(var s=0;o>s;s++)t=e[i[s]],t.options.mass>0&&(this._getForceContribution(n.root.children.NW,t),this._getForceContribution(n.root.children.NE,t),this._getForceContribution(n.root.children.SW,t),this._getForceContribution(n.root.children.SE,t))}}},{key:"_getForceContribution",value:function(t,e){if(t.childrenCount>0){var i=void 0,o=void 0,n=void 0;i=t.centerOfMass.x-e.x,o=t.centerOfMass.y-e.y,n=Math.sqrt(i*i+o*o),n*t.calcSize>this.thetaInversed?this._calculateForces(n,i,o,e,t):4===t.childrenCount?(this._getForceContribution(t.children.NW,e),this._getForceContribution(t.children.NE,e),this._getForceContribution(t.children.SW,e),this._getForceContribution(t.children.SE,e)):t.children.data.id!=e.id&&this._calculateForces(n,i,o,e,t)}}},{key:"_calculateForces",value:function(t,e,i,o,n){0===t&&(t=.1*Math.random(),e=t),this.overlapAvoidanceFactor<1&&(t=Math.max(.1+this.overlapAvoidanceFactor*o.shape.radius,t-o.shape.radius));var s=this.options.gravitationalConstant*n.mass*o.options.mass/Math.pow(t,3),r=e*s,a=i*s;this.physicsBody.forces[o.id].x+=r,this.physicsBody.forces[o.id].y+=a}},{key:"_formBarnesHutTree",value:function(t,e){for(var i=void 0,o=e.length,n=t[e[0]].x,s=t[e[0]].y,r=t[e[0]].x,a=t[e[0]].y,h=1;o>h;h++){var d=t[e[h]].x,l=t[e[h]].y;t[e[h]].options.mass>0&&(n>d&&(n=d),d>r&&(r=d),s>l&&(s=l),l>a&&(a=l))}var u=Math.abs(r-n)-Math.abs(a-s);u>0?(s-=.5*u,a+=.5*u):(n+=.5*u,r-=.5*u);var c=1e-5,p=Math.max(c,Math.abs(r-n)),f=.5*p,m=.5*(n+r),v=.5*(s+a),g={root:{centerOfMass:{x:0,y:0},mass:0,range:{minX:m-f,maxX:m+f,minY:v-f,maxY:v+f},size:p,calcSize:1/p,children:{data:null},maxWidth:0,level:0,childrenCount:4}};this._splitBranch(g.root);for(var h=0;o>h;h++)i=t[e[h]],i.options.mass>0&&this._placeInTree(g.root,i);return g}},{key:"_updateBranchMass",value:function(t,e){var i=t.mass+e.options.mass,o=1/i;t.centerOfMass.x=t.centerOfMass.x*t.mass+e.x*e.options.mass,t.centerOfMass.x*=o,t.centerOfMass.y=t.centerOfMass.y*t.mass+e.y*e.options.mass,t.centerOfMass.y*=o,t.mass=i;var n=Math.max(Math.max(e.height,e.radius),e.width);t.maxWidth=t.maxWidthe.x?t.children.NW.range.maxY>e.y?this._placeInRegion(t,e,"NW"):this._placeInRegion(t,e,"SW"):t.children.NW.range.maxY>e.y?this._placeInRegion(t,e,"NE"):this._placeInRegion(t,e,"SE")}},{key:"_placeInRegion",value:function(t,e,i){switch(t.children[i].childrenCount){case 0:t.children[i].children.data=e,t.children[i].childrenCount=1,this._updateBranchMass(t.children[i],e);break;case 1:t.children[i].children.data.x===e.x&&t.children[i].children.data.y===e.y?(e.x+=Math.random(),e.y+=Math.random()):(this._splitBranch(t.children[i]),this._placeInTree(t.children[i],e));break;case 4:this._placeInTree(t.children[i],e)}}},{key:"_splitBranch",value:function(t){var e=null;1===t.childrenCount&&(e=t.children.data,t.mass=0,t.centerOfMass.x=0,t.centerOfMass.y=0),t.childrenCount=4,t.children.data=null,this._insertRegion(t,"NW"),this._insertRegion(t,"NE"),this._insertRegion(t,"SW"),this._insertRegion(t,"SE"),null!=e&&this._placeInTree(t,e)}},{key:"_insertRegion",value:function(t,e){var i=void 0,o=void 0,n=void 0,s=void 0,r=.5*t.size;switch(e){case"NW":i=t.range.minX,o=t.range.minX+r,n=t.range.minY,s=t.range.minY+r;break;case"NE":i=t.range.minX+r,o=t.range.maxX,n=t.range.minY,s=t.range.minY+r;break;case"SW":i=t.range.minX,o=t.range.minX+r,n=t.range.minY+r,s=t.range.maxY;break;case"SE":i=t.range.minX+r,o=t.range.maxX,n=t.range.minY+r,s=t.range.maxY}t.children[e]={centerOfMass:{x:0,y:0},mass:0,range:{minX:i,maxX:o,minY:n,maxY:s},size:.5*t.size,calcSize:2*t.calcSize,children:{data:null},maxWidth:0,level:t.level+1,childrenCount:0}}},{key:"_debug",value:function(t,e){void 0!==this.barnesHutTree&&(t.lineWidth=1,this._drawBranch(this.barnesHutTree.root,t,e))}},{key:"_drawBranch",value:function(t,e,i){void 0===i&&(i="#FF0000"),4===t.childrenCount&&(this._drawBranch(t.children.NW,e),this._drawBranch(t.children.NE,e),this._drawBranch(t.children.SE,e),this._drawBranch(t.children.SW,e)),e.strokeStyle=i,e.beginPath(),e.moveTo(t.range.minX,t.range.minY),e.lineTo(t.range.maxX,t.range.minY),e.stroke(),e.beginPath(),e.moveTo(t.range.maxX,t.range.minY),e.lineTo(t.range.maxX,t.range.maxY),e.stroke(),e.beginPath(),e.moveTo(t.range.maxX,t.range.maxY),e.lineTo(t.range.minX,t.range.maxY),e.stroke(),e.beginPath(),e.moveTo(t.range.minX,t.range.maxY),e.lineTo(t.range.minX,t.range.minY),e.stroke()}}]),t}();e["default"]=s,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;ii&&(s=.5*u>i?1:c*i+p,s/=i,o=t*s,n=e*s,l[r.id].x-=o,l[r.id].y-=n,l[a.id].x+=o,l[a.id].y+=n)}}}]),t}();e["default"]=s,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;ii?-Math.pow(f*i,2)+Math.pow(f*p,2):0,0===i?i=.01:s/=i,o=t*s,n=e*s,c[r.id].x-=o,c[r.id].y-=n,c[a.id].x+=o,c[a.id].y+=n}}}]),t}();e["default"]=s,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;i0){var s=n.edges.length+1,r=this.options.centralGravity*s*n.options.mass;o[n.id].x=e*r,o[n.id].y=i*r}}}]),e}(d["default"]);e["default"]=l,t.exports=e["default"]},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var r=function(t,e,i){for(var o=!0;o;){var n=t,s=e,r=i;a=d=h=void 0,o=!1;var a=Object.getOwnPropertyDescriptor(n,s);if(void 0!==a){if("value"in a)return a.value;var h=a.get;return void 0===h?void 0:h.call(r)}var d=Object.getPrototypeOf(n);if(null===d)return void 0;t=d,e=s,i=r,o=!0}},a=i(74),h=o(a),d=function(t){function e(t,i,o,s,a){n(this,e),r(Object.getPrototypeOf(e.prototype),"constructor",this).call(this,t,i,o,s,a),this.isCluster=!0,this.containedNodes={},this.containedEdges={}}return s(e,t),e}(h["default"]);e["default"]=d,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;i700&&(this.body.emitter.emit("fit",{duration:700}),this.touchTime=(new Date).valueOf())}},{key:"_stopMovement",value:function(){for(var t in this.boundFunctions)this.boundFunctions.hasOwnProperty(t)&&(this.body.emitter.off("initRedraw",this.boundFunctions[t]),this.body.emitter.emit("_stopRendering"));this.boundFunctions={}}},{key:"_moveUp",value:function(){this.body.view.translation.y+=this.options.keyboard.speed.y}},{key:"_moveDown",value:function(){this.body.view.translation.y-=this.options.keyboard.speed.y}},{key:"_moveLeft",value:function(){this.body.view.translation.x+=this.options.keyboard.speed.x}},{key:"_moveRight",value:function(){this.body.view.translation.x-=this.options.keyboard.speed.x}},{key:"_zoomIn",value:function(){this.body.view.scale*=1+this.options.keyboard.speed.zoom}},{key:"_zoomOut",value:function(){this.body.view.scale/=1+this.options.keyboard.speed.zoom}},{key:"configureKeyboardBindings",value:function(){void 0!==this.keycharm&&this.keycharm.destroy(),this.options.keyboard.enabled===!0&&(this.options.keyboard.bindToWindow===!0?this.keycharm=a({container:window,preventDefault:!0}):this.keycharm=a({container:this.canvas.frame,preventDefault:!0}),this.keycharm.reset(),this.activated===!0&&(this.keycharm.bind("up",this.bindToRedraw.bind(this,"_moveUp"),"keydown"),this.keycharm.bind("down",this.bindToRedraw.bind(this,"_moveDown"),"keydown"),this.keycharm.bind("left",this.bindToRedraw.bind(this,"_moveLeft"),"keydown"),this.keycharm.bind("right",this.bindToRedraw.bind(this,"_moveRight"),"keydown"),this.keycharm.bind("=",this.bindToRedraw.bind(this,"_zoomIn"),"keydown"),this.keycharm.bind("num+",this.bindToRedraw.bind(this,"_zoomIn"),"keydown"),this.keycharm.bind("num-",this.bindToRedraw.bind(this,"_zoomOut"),"keydown"),this.keycharm.bind("-",this.bindToRedraw.bind(this,"_zoomOut"),"keydown"),this.keycharm.bind("[",this.bindToRedraw.bind(this,"_zoomOut"),"keydown"),this.keycharm.bind("]",this.bindToRedraw.bind(this,"_zoomIn"),"keydown"),this.keycharm.bind("pageup",this.bindToRedraw.bind(this,"_zoomIn"),"keydown"),this.keycharm.bind("pagedown",this.bindToRedraw.bind(this,"_zoomOut"),"keydown"),this.keycharm.bind("up",this.unbindFromRedraw.bind(this,"_moveUp"),"keyup"),this.keycharm.bind("down",this.unbindFromRedraw.bind(this,"_moveDown"),"keyup"),this.keycharm.bind("left",this.unbindFromRedraw.bind(this,"_moveLeft"),"keyup"),this.keycharm.bind("right",this.unbindFromRedraw.bind(this,"_moveRight"),"keyup"),this.keycharm.bind("=",this.unbindFromRedraw.bind(this,"_zoomIn"),"keyup"),this.keycharm.bind("num+",this.unbindFromRedraw.bind(this,"_zoomIn"),"keyup"),this.keycharm.bind("num-",this.unbindFromRedraw.bind(this,"_zoomOut"),"keyup"),this.keycharm.bind("-",this.unbindFromRedraw.bind(this,"_zoomOut"),"keyup"),this.keycharm.bind("[",this.unbindFromRedraw.bind(this,"_zoomOut"),"keyup"),this.keycharm.bind("]",this.unbindFromRedraw.bind(this,"_zoomIn"),"keyup"),this.keycharm.bind("pageup",this.unbindFromRedraw.bind(this,"_zoomIn"),"keyup"),this.keycharm.bind("pagedown",this.unbindFromRedraw.bind(this,"_zoomOut"),"keyup")))}}]),t}();e["default"]=h,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;io&&(s=o-e-this.padding),sn&&(r=n-i-this.padding),r=e;e++)r[String.fromCharCode(e)]={code:65+(e-97),shift:!1};for(e=65;90>=e;e++)r[String.fromCharCode(e)]={code:e,shift:!0};for(e=0;9>=e;e++)r[""+e]={code:48+e,shift:!1};for(e=1;12>=e;e++)r["F"+e]={code:111+e,shift:!1};for(e=0;9>=e;e++)r["num"+e]={code:96+e,shift:!1};r["num*"]={code:106,shift:!1},r["num+"]={code:107,shift:!1},r["num-"]={code:109,shift:!1},r["num/"]={code:111,shift:!1},r["num."]={code:110,shift:!1},r.left={code:37,shift:!1},r.up={code:38,shift:!1},r.right={code:39,shift:!1},r.down={code:40,shift:!1},r.space={code:32,shift:!1},r.enter={code:13,shift:!1},r.shift={code:16,shift:void 0},r.esc={code:27,shift:!1},r.backspace={code:8,shift:!1},r.tab={code:9,shift:!1},r.ctrl={code:17,shift:!1},r.alt={code:18,shift:!1},r["delete"]={code:46,shift:!1},r.pageup={code:33,shift:!1},r.pagedown={code:34,shift:!1},r["="]={code:187,shift:!1},r["-"]={code:189,shift:!1},r["]"]={code:221,shift:!1},r["["]={code:219,shift:!1};var a=function(t){d(t,"keydown")},h=function(t){d(t,"keyup")},d=function(t,e){if(void 0!==s[e][t.keyCode]){for(var o=s[e][t.keyCode],n=0;nthis.to.y?this.from.xthis.to.x&&(t=this.from.x-i*s,e=this.from.y-i*s):this.from.ythis.to.x&&(t=this.from.x-i*s,e=this.from.y+i*s)),"discrete"===o&&(t=i*s>n?this.from.x:t)):Math.abs(this.from.x-this.to.x)>Math.abs(this.from.y-this.to.y)&&(this.from.y>this.to.y?this.from.xthis.to.x&&(t=this.from.x-i*n,e=this.from.y-i*n):this.from.ythis.to.x&&(t=this.from.x-i*n,e=this.from.y+i*n)),"discrete"===o&&(e=i*n>s?this.from.y:e));else if("straightCross"===o)Math.abs(this.from.x-this.to.x)Math.abs(this.from.y-this.to.y)&&(t=this.from.xthis.to.y?this.from.xthis.to.x&&(t=this.from.x-i*s,e=this.from.y-i*s,t=this.to.x>t?this.to.x:t):this.from.ythis.to.x&&(t=this.from.x-i*s,e=this.from.y+i*s,t=this.to.x>t?this.to.x:t)):Math.abs(this.from.x-this.to.x)>Math.abs(this.from.y-this.to.y)&&(this.from.y>this.to.y?this.from.xe?this.to.y:e):this.from.x>this.to.x&&(t=this.from.x-i*n,e=this.from.y-i*n,e=this.to.y>e?this.to.y:e):this.from.ythis.to.x&&(t=this.from.x-i*n,e=this.from.y+i*n,e=this.to.ythis.imageObj.height?(i=this.imageObj.width/this.imageObj.height,t=2*this.options.size*i||this.imageObj.width,e=2*this.options.size||this.imageObj.height):(i=this.imageObj.width&&this.imageObj.height?this.imageObj.height/this.imageObj.width:1,t=2*this.options.size||this.imageObj.width,e=2*this.options.size*i||this.imageObj.height),this.width=t,this.height=e,this.radius=.5*this.width}}},{key:"_drawRawCircle",value:function(t,e,i,o,n,s){var r=this.options.borderWidth,a=this.options.borderWidthSelected||2*this.options.borderWidth;t.strokeStyle=o?this.options.color.highlight.border:n?this.options.color.hover.border:this.options.color.border,t.lineWidth=o?a:r,t.lineWidth*=this.networkScaleInv,t.lineWidth=Math.min(this.width,t.lineWidth),t.fillStyle=o?this.options.color.highlight.background:n?this.options.color.hover.background:this.options.color.background,t.circle(e,i,s),this.enableShadow(t),t.fill(),this.disableShadow(t),t.stroke()}},{key:"_drawImageAtPosition",value:function(t){0!=this.imageObj.width&&(t.globalAlpha=1,this.enableShadow(t),t.drawImage(this.imageObj,this.left,this.top,this.width,this.height),this.disableShadow(t))}},{key:"_drawImageLabel",value:function(t,e,i,o){var n,s=0;if(void 0!==this.height){s=.5*this.height;var r=this.labelModule.getTextSize(t);r.lineCount>=1&&(s+=r.height/2)}n=i+s,this.options.label&&(this.labelOffset=s),this.labelModule.draw(t,e,n,o,"hanging")}}]),e}(d["default"]);e["default"]=l,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;i=l&&h>d;){var m=.5*(l+u);if(i=this.getPoint(m,a),o=Math.atan2(p.y-i.y,p.x-i.x),n=p.distanceToBorder(e,o),s=Math.sqrt(Math.pow(i.x-p.x,2)+Math.pow(i.y-p.y,2)),r=n-s,Math.abs(r)r?f===!1?l=m:u=m:f===!1?u=m:l=m,d++}return i.t=m,i}},{key:"_getDistanceToBezierEdge",value:function(t,e,i,o,n,s,r){var a=void 0,h=void 0;a=r.x,h=r.y;var d=1e9,l=void 0,u=void 0,c=void 0,p=void 0,f=void 0,m=t,v=e;for(u=1;10>u;u++)c=.1*u,p=Math.pow(1-c,2)*t+2*c*(1-c)*a+Math.pow(c,2)*i,f=Math.pow(1-c,2)*e+2*c*(1-c)*h+Math.pow(c,2)*o,u>0&&(l=this._getDistanceToLine(m,v,p,f,n,s),d=d>l?l:d),m=p,v=f;return d}}]),e}(d["default"]);e["default"]=l,t.exports=e["default"]},function(t,e,i){function o(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t)){var i=[],o=!0,n=!1,s=void 0;try{for(var r,a=t[Symbol.iterator]();!(o=(r=a.next()).done)&&(i.push(r.value),!e||i.length!==e);o=!0);}catch(h){n=!0,s=h}finally{try{!o&&a["return"]&&a["return"]()}finally{if(n)throw s}}return i}throw new TypeError("Invalid attempt to destructure non-iterable instance")}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function t(t,e){for(var i=0;io.shape.height?(e=o.x+.5*o.shape.width,i=o.y-n):(e=o.x+n,i=o.y-.5*o.shape.height),[e,i,n]}},{key:"_pointOnCircle",value:function(t,e,i,o){var n=2*o*Math.PI;return{x:t+i*Math.cos(n),y:e-i*Math.sin(n)}}},{key:"_findBorderPositionCircle",value:function(t,e,i){for(var o=i.x,n=i.y,s=i.low,r=i.high,a=i.direction,h=10,d=0,l=this.options.selfReferenceSize,u=void 0,c=void 0,p=void 0,f=void 0,m=void 0,v=.05,g=.5*(s+r);r>=s&&h>d&&(g=.5*(s+r),u=this._pointOnCircle(o,n,l,g),c=Math.atan2(t.y-u.y,t.x-u.x),p=t.distanceToBorder(e,c),f=Math.sqrt(Math.pow(u.x-t.x,2)+Math.pow(u.y-t.y,2)),m=p-f,!(Math.abs(m)0?a>0?s=g:r=g:a>0?r=g:s=g,d++;return u.t=g,u}},{key:"getLineWidth",value:function(t,e){return t===!0?Math.max(this.selectionWidth,.3/this.body.view.scale):e===!0?Math.max(this.hoverWidth,.3/this.body.view.scale):Math.max(this.options.width,.3/this.body.view.scale)}},{key:"getColor",value:function(t){var e=this.options.color;if(e.inherit!==!1){if("both"===e.inherit&&this.from.id!==this.to.id){var i=t.createLinearGradient(this.from.x,this.from.y,this.to.x,this.to.y),o=void 0,n=void 0;return o=this.from.options.color.highlight.border,n=this.to.options.color.highlight.border,this.from.selected===!1&&this.to.selected===!1?(o=r.overrideOpacity(this.from.options.color.border,this.options.color.opacity),n=r.overrideOpacity(this.to.options.color.border,this.options.color.opacity)):this.from.selected===!0&&this.to.selected===!1?n=this.to.options.color.border:this.from.selected===!1&&this.to.selected===!0&&(o=this.from.options.color.border),i.addColorStop(0,o),i.addColorStop(1,n),i}this.colorDirty===!0&&("to"===e.inherit?(this.color.highlight=this.to.options.color.highlight.border,this.color.hover=this.to.options.color.hover.border,this.color.color=r.overrideOpacity(this.to.options.color.border,e.opacity)):(this.color.highlight=this.from.options.color.highlight.border,this.color.hover=this.from.options.color.hover.border,this.color.color=r.overrideOpacity(this.from.options.color.border,e.opacity)))}else this.colorDirty===!0&&(this.color.highlight=e.highlight,this.color.hover=e.hover,this.color.color=r.overrideOpacity(e.color,e.opacity));return this.colorDirty=!1,this.selected===!0?this.color.highlight:this.hover===!0?this.color.hover:this.color.color}},{key:"_circle",value:function(t,e,i,o){this.enableShadow(t),t.beginPath(),t.arc(e,i,o,0,2*Math.PI,!1),t.stroke(),this.disableShadow(t)}},{key:"getDistanceToEdge",value:function(t,e,i,n,s,r,a){var h=0;if(this.from!=this.to)h=this._getDistanceToEdge(t,e,i,n,s,r,a);else{var d=this._getCircleData(),l=o(d,3),u=l[0],c=l[1],p=l[2],f=u-s,m=c-r;h=Math.abs(Math.sqrt(f*f+m*m)-p)}return this.labelModule.size.lefts&&this.labelModule.size.topr?0:h}},{key:"_getDistanceToLine",value:function(t,e,i,o,n,s){var r=i-t,a=o-e,h=r*r+a*a,d=((n-t)*r+(s-e)*a)/h;d>1?d=1:0>d&&(d=0);var l=t+d*r,u=e+d*a,c=l-n,p=u-s;return Math.sqrt(c*c+p*p)}},{key:"drawArrowHead",value:function(t,e,i,n,s){t.strokeStyle=this.getColor(t),t.fillStyle=t.strokeStyle,t.lineWidth=this.getLineWidth(n,s);var r=void 0,a=void 0,h=void 0,d=void 0,l=void 0,u=void 0,c=void 0;if("from"===e?(d=this.from,l=this.to,u=.1,c=this.options.arrows.from.scaleFactor):"to"===e?(d=this.to,l=this.from,u=-.1,c=this.options.arrows.to.scaleFactor):(d=this.to,l=this.from,c=this.options.arrows.middle.scaleFactor),d!=l){if("middle"!==e)if(this.options.smooth.enabled===!0){h=this.findBorderPosition(d,t,{via:i});var p=this.getPoint(Math.max(0,Math.min(1,h.t+u)),i);r=Math.atan2(h.y-p.y,h.x-p.x)}else r=Math.atan2(d.y-l.y,d.x-l.x),h=this.findBorderPosition(d,t);else r=Math.atan2(d.y-l.y,d.x-l.x),h=this.getPoint(.6,i);a=(10+5*this.options.width)*c,t.arrow(h.x,h.y,r,a),this.enableShadow(t),t.fill(),this.disableShadow(t),t.stroke()}else{var f=void 0,m=void 0,v=this._getCircleData(t),g=o(v,3),y=g[0],b=g[1],w=g[2];"from"===e?(m=this.findBorderPosition(this.from,t,{x:y,y:b,low:.25,high:.6,direction:-1}),f=-2*m.t*Math.PI+1.5*Math.PI+.1*Math.PI):"to"===e?(m=this.findBorderPosition(this.from,t,{x:y,y:b,low:.6,high:1,direction:1}),f=-2*m.t*Math.PI+1.5*Math.PI-1.1*Math.PI):(m=this._pointOnCircle(y,b,w,.175),f=3.9269908169872414);var _=(10+5*this.options.width)*c;t.arrow(m.x,m.y,f,_),this.enableShadow(t),t.fill(),this.disableShadow(t),t.stroke()}}},{key:"enableShadow",value:function(t){this.options.shadow.enabled===!0&&(t.shadowColor="rgba(0,0,0,0.5)",t.shadowBlur=this.options.shadow.size,t.shadowOffsetX=this.options.shadow.x,t.shadowOffsetY=this.options.shadow.y)}},{key:"disableShadow",value:function(t){this.options.shadow.enabled===!0&&(t.shadowColor="rgba(0,0,0,0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0)}}]),t}();e["default"]=a,t.exports=e["default"]}])}); +"use strict";!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):"object"==typeof exports?exports.vis=e():t.vis=e()}(this,function(){return function(t){function e(o){if(i[o])return i[o].exports;var n=i[o]={exports:{},id:o,loaded:!1};return t[o].call(n.exports,n,n.exports,e),n.loaded=!0,n.exports}var i={};return e.m=t,e.c=i,e.p="",e(0)}([function(t,e,i){e.util=i(7),e.DOMutil=i(13),e.DataSet=i(14),e.DataView=i(16),e.Queue=i(15),e.Graph3d=i(17),e.graph3d={Camera:i(21),Filter:i(22),Point2d:i(18),Point3d:i(20),Slider:i(23),StepNumber:i(24)},e.Timeline=i(25),e.Graph2d=i(49),e.timeline={DateUtil:i(31),DataStep:i(52),Range:i(29),stack:i(35),TimeStep:i(37),components:{items:{Item:i(2),BackgroundItem:i(40),BoxItem:i(1),PointItem:i(39),RangeItem:i(36)},Component:i(27),CurrentTime:i(26),CustomTime:i(44),DataAxis:i(51),GraphGroup:i(53),Group:i(34),BackgroundGroup:i(38),ItemSet:i(33),Legend:i(57),LineGraph:i(50),TimeAxis:i(41)}},e.Network=i(59),e.network={Images:i(112),dotparser:i(110),gephiParser:i(111)},e.network.convertDot=function(t){return e.network.dotparser.DOTToGraph(t)},e.network.convertGephi=function(t,i){return e.network.gephiParser.parseGephi(t,i)},e.Graph=function(){throw new Error("Graph is renamed to Network. Please create a graph as new vis.Network(...)")},e.moment=i(8),e.hammer=i(3),e.Hammer=i(3)},function(t,e,i){function o(t,e,i){if(this.props={dot:{width:0,height:0},line:{width:0,height:0}},t&&void 0==t.start)throw new Error('Property "start" missing in item '+t);n.call(this,t,e,i)}var n=i(2);i(7);o.prototype=new n(null,null,null),o.prototype.isVisible=function(t){var e=(t.end-t.start)/4;return this.data.start>t.start-e&&this.data.start0){var e=[];if(Array.isArray(this.options.dataAttributes))e=this.options.dataAttributes;else{if("all"!=this.options.dataAttributes)return;e=Object.keys(this.data)}for(var i=0;i0?o._handlers[t]=i:(o._off(t,r),delete o._handlers[t]))}),o},o.emit=function(i,n){e||(t=n.target),o._emit(i,n)},o.destroy=function(){var t=o.element;delete t.hammer,o._handlers={},o._destroy()},o}})},function(t,e,i){var o;!function(n,s,r,a){function h(t,e,i){return setTimeout(f(t,i),e)}function d(t,e,i){return Array.isArray(t)?(l(t,i[e],i),!0):!1}function l(t,e,i){var o;if(t)if(t.forEach)t.forEach(e,i);else if(t.length!==a)for(o=0;o-1}function _(t){return t.trim().split(/\s+/g)}function x(t,e,i){if(t.indexOf&&!i)return t.indexOf(e);for(var o=0;oi[e]}):o.sort()),o}function O(t,e){for(var i,o,n=e[0].toUpperCase()+e.slice(1),s=0;s1&&!i.firstMultiple?i.firstMultiple=z(e):1===n&&(i.firstMultiple=!1);var s=i.firstInput,r=i.firstMultiple,a=r?r.center:s.center,h=e.center=A(o);e.timeStamp=gt(),e.deltaTime=e.timeStamp-s.timeStamp,e.angle=F(a,h),e.distance=R(a,h),I(i,e),e.offsetDirection=B(e.deltaX,e.deltaY),e.scale=r?H(r.pointers,o):1,e.rotation=r?j(r.pointers,o):0,N(i,e);var d=t.element;b(e.srcEvent.target,d)&&(d=e.srcEvent.target),e.target=d}function I(t,e){var i=e.center,o=t.offsetDelta||{},n=t.prevDelta||{},s=t.prevInput||{};(e.eventType===Ct||s.eventType===St)&&(n=t.prevDelta={x:s.deltaX||0,y:s.deltaY||0},o=t.offsetDelta={x:i.x,y:i.y}),e.deltaX=n.x+(i.x-o.x),e.deltaY=n.y+(i.y-o.y)}function N(t,e){var i,o,n,s,r=t.lastInterval||e,h=e.timeStamp-r.timeStamp;if(e.eventType!=Pt&&(h>Tt||r.velocity===a)){var d=r.deltaX-e.deltaX,l=r.deltaY-e.deltaY,u=L(h,d,l);o=u.x,n=u.y,i=vt(u.x)>vt(u.y)?u.x:u.y,s=B(d,l),t.lastInterval=e}else i=r.velocity,o=r.velocityX,n=r.velocityY,s=r.direction;e.velocity=i,e.velocityX=o,e.velocityY=n,e.direction=s}function z(t){for(var e=[],i=0;in;)i+=t[n].clientX,o+=t[n].clientY,n++;return{x:mt(i/e),y:mt(o/e)}}function L(t,e,i){return{x:e/t||0,y:i/t||0}}function B(t,e){return t===e?It:vt(t)>=vt(e)?t>0?Nt:zt:e>0?At:Lt}function R(t,e,i){i||(i=jt);var o=e[i[0]]-t[i[0]],n=e[i[1]]-t[i[1]];return Math.sqrt(o*o+n*n)}function F(t,e,i){i||(i=jt);var o=e[i[0]]-t[i[0]],n=e[i[1]]-t[i[1]];return 180*Math.atan2(n,o)/Math.PI}function j(t,e){return F(e[1],e[0],Ht)-F(t[1],t[0],Ht)}function H(t,e){return R(e[0],e[1],Ht)/R(t[0],t[1],Ht)}function Y(){this.evEl=Wt,this.evWin=Gt,this.allow=!0,this.pressed=!1,C.apply(this,arguments)}function W(){this.evEl=qt,this.evWin=Xt,C.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}function G(){this.evTarget=Kt,this.evWin=Jt,this.started=!1,C.apply(this,arguments)}function U(t,e){var i=k(t.touches),o=k(t.changedTouches);return e&(St|Pt)&&(i=M(i.concat(o),"identifier",!0)),[i,o]}function V(){this.evTarget=$t,this.targetIds={},C.apply(this,arguments)}function q(t,e){var i=k(t.touches),o=this.targetIds;if(e&(Ct|Et)&&1===i.length)return o[i[0].identifier]=!0,[i,i];var n,s,r=k(t.changedTouches),a=[],h=this.target;if(s=i.filter(function(t){return b(t.target,h)}),e===Ct)for(n=0;na&&(e.push(t),a=e.length-1):n&(St|Pt)&&(i=!0),0>a||(e[a]=t,this.callback(this.manager,n,{pointers:e,changedPointers:[t],pointerType:s,srcEvent:t}),i&&e.splice(a,1))}});var Zt={touchstart:Ct,touchmove:Et,touchend:St,touchcancel:Pt},Kt="touchstart",Jt="touchstart touchmove touchend touchcancel";p(G,C,{handler:function(t){var e=Zt[t.type];if(e===Ct&&(this.started=!0),this.started){var i=U.call(this,t,e);e&(St|Pt)&&i[0].length-i[1].length===0&&(this.started=!1),this.callback(this.manager,e,{pointers:i[0],changedPointers:i[1],pointerType:kt,srcEvent:t})}}});var Qt={touchstart:Ct,touchmove:Et,touchend:St,touchcancel:Pt},$t="touchstart touchmove touchend touchcancel";p(V,C,{handler:function(t){var e=Qt[t.type],i=q.call(this,t,e);i&&this.callback(this.manager,e,{pointers:i[0],changedPointers:i[1],pointerType:kt,srcEvent:t})}}),p(X,C,{handler:function(t,e,i){var o=i.pointerType==kt,n=i.pointerType==Ot;if(o)this.mouse.allow=!1;else if(n&&!this.mouse.allow)return;e&(St|Pt)&&(this.mouse.allow=!0),this.callback(t,e,i)},destroy:function(){this.touch.destroy(),this.mouse.destroy()}});var te=O(pt.style,"touchAction"),ee=te!==a,ie="compute",oe="auto",ne="manipulation",se="none",re="pan-x",ae="pan-y";Z.prototype={set:function(t){t==ie&&(t=this.compute()),ee&&(this.manager.element.style[te]=t),this.actions=t.toLowerCase().trim()},update:function(){this.set(this.manager.options.touchAction)},compute:function(){var t=[];return l(this.manager.recognizers,function(e){m(e.options.enable,[e])&&(t=t.concat(e.getTouchAction()))}),K(t.join(" "))},preventDefaults:function(t){if(!ee){var e=t.srcEvent,i=t.offsetDirection;if(this.manager.session.prevented)return void e.preventDefault();var o=this.actions,n=w(o,se),s=w(o,ae),r=w(o,re);return n||s&&i&Bt||r&&i&Rt?this.preventSrc(e):void 0}},preventSrc:function(t){this.manager.session.prevented=!0,t.preventDefault()}};var he=1,de=2,le=4,ue=8,ce=ue,pe=16,fe=32;J.prototype={defaults:{},set:function(t){return u(this.options,t),this.manager&&this.manager.touchAction.update(),this},recognizeWith:function(t){if(d(t,"recognizeWith",this))return this;var e=this.simultaneous;return t=tt(t,this),e[t.id]||(e[t.id]=t,t.recognizeWith(this)),this},dropRecognizeWith:function(t){return d(t,"dropRecognizeWith",this)?this:(t=tt(t,this),delete this.simultaneous[t.id],this)},requireFailure:function(t){if(d(t,"requireFailure",this))return this;var e=this.requireFail;return t=tt(t,this),-1===x(e,t)&&(e.push(t),t.requireFailure(this)),this},dropRequireFailure:function(t){if(d(t,"dropRequireFailure",this))return this;t=tt(t,this);var e=x(this.requireFail,t);return e>-1&&this.requireFail.splice(e,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(t){return!!this.simultaneous[t.id]},emit:function(t){function e(e){i.manager.emit(i.options.event+(e?Q(o):""),t)}var i=this,o=this.state;ue>o&&e(!0),e(),o>=ue&&e(!0)},tryEmit:function(t){return this.canEmit()?this.emit(t):void(this.state=fe)},canEmit:function(){for(var t=0;ts?Nt:zt,i=s!=this.pX,o=Math.abs(t.deltaX)):(n=0===r?It:0>r?At:Lt,i=r!=this.pY,o=Math.abs(t.deltaY))),t.direction=n,i&&o>e.threshold&&n&e.direction},attrTest:function(t){return et.prototype.attrTest.call(this,t)&&(this.state&de||!(this.state&de)&&this.directionTest(t))},emit:function(t){this.pX=t.deltaX,this.pY=t.deltaY;var e=$(t.direction);e&&this.manager.emit(this.options.event+e,t),this._super.emit.call(this,t)}}),p(ot,et,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[se]},attrTest:function(t){return this._super.attrTest.call(this,t)&&(Math.abs(t.scale-1)>this.options.threshold||this.state&de)},emit:function(t){if(this._super.emit.call(this,t),1!==t.scale){var e=t.scale<1?"in":"out";this.manager.emit(this.options.event+e,t)}}}),p(nt,J,{defaults:{event:"press",pointers:1,time:500,threshold:5},getTouchAction:function(){return[oe]},process:function(t){var e=this.options,i=t.pointers.length===e.pointers,o=t.distancee.time;if(this._input=t,!o||!i||t.eventType&(St|Pt)&&!n)this.reset();else if(t.eventType&Ct)this.reset(),this._timer=h(function(){this.state=ce,this.tryEmit()},e.time,this);else if(t.eventType&St)return ce;return fe},reset:function(){clearTimeout(this._timer)},emit:function(t){this.state===ce&&(t&&t.eventType&St?this.manager.emit(this.options.event+"up",t):(this._input.timeStamp=gt(),this.manager.emit(this.options.event,this._input)))}}),p(st,et,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[se]},attrTest:function(t){return this._super.attrTest.call(this,t)&&(Math.abs(t.rotation)>this.options.threshold||this.state&de)}}),p(rt,et,{defaults:{event:"swipe",threshold:10,velocity:.65,direction:Bt|Rt,pointers:1},getTouchAction:function(){return it.prototype.getTouchAction.call(this)},attrTest:function(t){var e,i=this.options.direction;return i&(Bt|Rt)?e=t.velocity:i&Bt?e=t.velocityX:i&Rt&&(e=t.velocityY),this._super.attrTest.call(this,t)&&i&t.direction&&t.distance>this.options.threshold&&vt(e)>this.options.velocity&&t.eventType&St},emit:function(t){var e=$(t.direction);e&&this.manager.emit(this.options.event+e,t),this.manager.emit(this.options.event,t)}}),p(at,J,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:2,posThreshold:10},getTouchAction:function(){return[ne]},process:function(t){var e=this.options,i=t.pointers.length===e.pointers,o=t.distancei;i++)if(t[i]!=e[i])return!1;return!0},e.convert=function(t,i){var n;if(void 0===t)return void 0;if(null===t)return null;if(!i)return t;if("string"!=typeof i&&!(i instanceof String))throw new Error("Type must be a string");switch(i){case"boolean":case"Boolean":return Boolean(t);case"number":case"Number":return Number(t.valueOf());case"string":case"String":return String(t);case"Date":if(e.isNumber(t))return new Date(t);if(t instanceof Date)return new Date(t.valueOf());if(o.isMoment(t))return new Date(t.valueOf());if(e.isString(t))return n=s.exec(t),n?new Date(Number(n[1])):o(t).toDate();throw new Error("Cannot convert object of type "+e.getType(t)+" to type Date");case"Moment":if(e.isNumber(t))return o(t);if(t instanceof Date)return o(t.valueOf());if(o.isMoment(t))return o(t);if(e.isString(t))return n=s.exec(t),o(n?Number(n[1]):t);throw new Error("Cannot convert object of type "+e.getType(t)+" to type Date");case"ISODate":if(e.isNumber(t))return new Date(t);if(t instanceof Date)return t.toISOString();if(o.isMoment(t))return t.toDate().toISOString();if(e.isString(t))return n=s.exec(t),n?new Date(Number(n[1])).toISOString():new Date(t).toISOString();throw new Error("Cannot convert object of type "+e.getType(t)+" to type ISODate");case"ASPDate":if(e.isNumber(t))return"/Date("+t+")/";if(t instanceof Date)return"/Date("+t.valueOf()+")/";if(e.isString(t)){n=s.exec(t);var r;return r=n?new Date(Number(n[1])).valueOf():new Date(t).valueOf(),"/Date("+r+")/"}throw new Error("Cannot convert object of type "+e.getType(t)+" to type ASPDate");default:throw new Error('Unknown type "'+i+'"')}};var s=/^\/?Date\((\-?\d+)/i;e.getType=function(t){var e=typeof t;return"object"==e?null===t?"null":t instanceof Boolean?"Boolean":t instanceof Number?"Number":t instanceof String?"String":Array.isArray(t)?"Array":t instanceof Date?"Date":"Object":"number"==e?"Number":"boolean"==e?"Boolean":"string"==e?"String":void 0===e?"undefined":e; +},e.copyAndExtendArray=function(t,e){for(var i=[],o=0;oi;i++)e(t[i],i,t);else for(i in t)t.hasOwnProperty(i)&&e(t[i],i,t)},e.toArray=function(t){var e=[];for(var i in t)t.hasOwnProperty(i)&&e.push(t[i]);return e},e.updateProperty=function(t,e,i){return t[e]!==i?(t[e]=i,!0):!1},e.addEventListener=function(t,e,i,o){t.addEventListener?(void 0===o&&(o=!1),"mousewheel"===e&&navigator.userAgent.indexOf("Firefox")>=0&&(e="DOMMouseScroll"),t.addEventListener(e,i,o)):t.attachEvent("on"+e,i)},e.removeEventListener=function(t,e,i,o){t.removeEventListener?(void 0===o&&(o=!1),"mousewheel"===e&&navigator.userAgent.indexOf("Firefox")>=0&&(e="DOMMouseScroll"),t.removeEventListener(e,i,o)):t.detachEvent("on"+e,i)},e.preventDefault=function(t){t||(t=window.event),t.preventDefault?t.preventDefault():t.returnValue=!1},e.getTarget=function(t){t||(t=window.event);var e;return t.target?e=t.target:t.srcElement&&(e=t.srcElement),void 0!=e.nodeType&&3==e.nodeType&&(e=e.parentNode),e},e.hasParent=function(t,e){for(var i=t;i;){if(i===e)return!0;i=i.parentNode}return!1},e.option={},e.option.asBoolean=function(t,e){return"function"==typeof t&&(t=t()),null!=t?0!=t:e||null},e.option.asNumber=function(t,e){return"function"==typeof t&&(t=t()),null!=t?Number(t)||e||null:e||null},e.option.asString=function(t,e){return"function"==typeof t&&(t=t()),null!=t?String(t):e||null},e.option.asSize=function(t,i){return"function"==typeof t&&(t=t()),e.isString(t)?t:e.isNumber(t)?t+"px":i||null},e.option.asElement=function(t,e){return"function"==typeof t&&(t=t()),t||e||null},e.hexToRGB=function(t){var e=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(e,function(t,e,i,o){return e+e+i+i+o+o});var i=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return i?{r:parseInt(i[1],16),g:parseInt(i[2],16),b:parseInt(i[3],16)}:null},e.overrideOpacity=function(t,i){if(-1!=t.indexOf("rgba"))return t;if(-1!=t.indexOf("rgb")){var o=t.substr(t.indexOf("(")+1).replace(")","").split(",");return"rgba("+o[0]+","+o[1]+","+o[2]+","+i+")"}var o=e.hexToRGB(t);return null==o?t:"rgba("+o.r+","+o.g+","+o.b+","+i+")"},e.RGBToHex=function(t,e,i){return"#"+((1<<24)+(t<<16)+(e<<8)+i).toString(16).slice(1)},e.parseColor=function(t){var i;if(e.isString(t)===!0){if(e.isValidRGB(t)===!0){var o=t.substr(4).substr(0,t.length-5).split(",").map(function(t){return parseInt(t)});t=e.RGBToHex(o[0],o[1],o[2])}if(e.isValidHex(t)===!0){var n=e.hexToHSV(t),s={h:n.h,s:.8*n.s,v:Math.min(1,1.02*n.v)},r={h:n.h,s:Math.min(1,1.25*n.s),v:.8*n.v},a=e.HSVToHex(r.h,r.s,r.v),h=e.HSVToHex(s.h,s.s,s.v);i={background:t,border:a,highlight:{background:h,border:a},hover:{background:h,border:a}}}else i={background:t,border:t,highlight:{background:t,border:t},hover:{background:t,border:t}}}else i={},i.background=t.background||void 0,i.border=t.border||void 0,e.isString(t.highlight)?i.highlight={border:t.highlight,background:t.highlight}:(i.highlight={},i.highlight.background=t.highlight&&t.highlight.background||void 0,i.highlight.border=t.highlight&&t.highlight.border||void 0),e.isString(t.hover)?i.hover={border:t.hover,background:t.hover}:(i.hover={},i.hover.background=t.hover&&t.hover.background||void 0,i.hover.border=t.hover&&t.hover.border||void 0);return i},e.RGBToHSV=function(t,e,i){t/=255,e/=255,i/=255;var o=Math.min(t,Math.min(e,i)),n=Math.max(t,Math.max(e,i));if(o==n)return{h:0,s:0,v:o};var s=t==o?e-i:i==o?t-e:i-t,r=t==o?3:i==o?1:5,a=60*(r-s/(n-o))/360,h=(n-o)/n,d=n;return{h:a,s:h,v:d}};var r={split:function(t){var e={};return t.split(";").forEach(function(t){if(""!=t.trim()){var i=t.split(":"),o=i[0].trim(),n=i[1].trim();e[o]=n}}),e},join:function(t){return Object.keys(t).map(function(e){return e+": "+t[e]}).join("; ")}};e.addCssText=function(t,i){var o=r.split(t.style.cssText),n=r.split(i),s=e.extend(o,n);t.style.cssText=r.join(s)},e.removeCssText=function(t,e){var i=r.split(t.style.cssText),o=r.split(e);for(var n in o)o.hasOwnProperty(n)&&delete i[n];t.style.cssText=r.join(i)},e.HSVToRGB=function(t,e,i){var o,n,s,r=Math.floor(6*t),a=6*t-r,h=i*(1-e),d=i*(1-a*e),l=i*(1-(1-a)*e);switch(r%6){case 0:o=i,n=l,s=h;break;case 1:o=d,n=i,s=h;break;case 2:o=h,n=i,s=l;break;case 3:o=h,n=d,s=i;break;case 4:o=l,n=h,s=i;break;case 5:o=i,n=h,s=d}return{r:Math.floor(255*o),g:Math.floor(255*n),b:Math.floor(255*s)}},e.HSVToHex=function(t,i,o){var n=e.HSVToRGB(t,i,o);return e.RGBToHex(n.r,n.g,n.b)},e.hexToHSV=function(t){var i=e.hexToRGB(t);return e.RGBToHSV(i.r,i.g,i.b)},e.isValidHex=function(t){var e=/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(t);return e},e.isValidRGB=function(t){t=t.replace(" ","");var e=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(t);return e},e.isValidRGBA=function(t){t=t.replace(" ","");var e=/rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),(.{1,3})\)/i.test(t);return e},e.selectiveBridgeObject=function(t,i){if("object"==typeof i){for(var o=Object.create(i),n=0;n=r&&n>s;){var h=Math.floor((r+a)/2),d=t[h],l=void 0===o?d[i]:d[i][o],u=e(l);if(0==u)return h;-1==u?r=h+1:a=h-1,s++}return-1},e.binarySearchValue=function(t,e,i,o){for(var n,s,r,a,h=1e4,d=0,l=0,u=t.length-1;u>=l&&h>d;){if(a=Math.floor(.5*(u+l)),n=t[Math.max(0,a-1)][i],s=t[a][i],r=t[Math.min(t.length-1,a+1)][i],s==e)return a;if(e>n&&s>e)return"before"==o?Math.max(0,a-1):a;if(e>s&&r>e)return"before"==o?a:Math.min(t.length-1,a+1);e>s?l=a+1:u=a-1,d++}return-1},e.easingFunctions={linear:function(t){return t},easeInQuad:function(t){return t*t},easeOutQuad:function(t){return t*(2-t)},easeInOutQuad:function(t){return.5>t?2*t*t:-1+(4-2*t)*t},easeInCubic:function(t){return t*t*t},easeOutCubic:function(t){return--t*t*t+1},easeInOutCubic:function(t){return.5>t?4*t*t*t:(t-1)*(2*t-2)*(2*t-2)+1},easeInQuart:function(t){return t*t*t*t},easeOutQuart:function(t){return 1- --t*t*t*t},easeInOutQuart:function(t){return.5>t?8*t*t*t*t:1-8*--t*t*t*t},easeInQuint:function(t){return t*t*t*t*t},easeOutQuint:function(t){return 1+--t*t*t*t*t},easeInOutQuint:function(t){return.5>t?16*t*t*t*t*t:1+16*--t*t*t*t*t}}},function(t,e,i){t.exports="undefined"!=typeof window&&window.moment||i(9)},function(t,e,i){(function(t){!function(e,i){t.exports=i()}(this,function(){function e(){return Si.apply(null,arguments)}function i(t){Si=t}function o(t){return"[object Array]"===Object.prototype.toString.call(t)}function n(t){return t instanceof Date||"[object Date]"===Object.prototype.toString.call(t)}function s(t,e){var i,o=[];for(i=0;i0)for(i in Ii)o=Ii[i],n=e[o],"undefined"!=typeof n&&(t[o]=n);return t}function f(t){p(this,t),this._d=new Date(+t._d),Ni===!1&&(Ni=!0,e.updateOffset(this),Ni=!1)}function m(t){return t instanceof f||null!=t&&null!=t._isAMomentObject}function v(t){var e=+t,i=0;return 0!==e&&isFinite(e)&&(i=e>=0?Math.floor(e):Math.ceil(e)),i}function g(t,e,i){var o,n=Math.min(t.length,e.length),s=Math.abs(t.length-e.length),r=0;for(o=0;n>o;o++)(i&&t[o]!==e[o]||!i&&v(t[o])!==v(e[o]))&&r++;return r+s}function y(){}function b(t){return t?t.toLowerCase().replace("_","-"):t}function w(t){for(var e,i,o,n,s=0;s0;){if(o=_(n.slice(0,e).join("-")))return o;if(i&&i.length>=e&&g(n,i,!0)>=e-1)break;e--}s++}return null}function _(e){var i=null;if(!zi[e]&&"undefined"!=typeof t&&t&&t.exports)try{i=Pi._abbr,!function(){var t=new Error('Cannot find module "./locale"');throw t.code="MODULE_NOT_FOUND",t}(),x(i)}catch(o){}return zi[e]}function x(t,e){var i;return t&&(i="undefined"==typeof e?M(t):k(t,e),i&&(Pi=i)),Pi._abbr}function k(t,e){return null!==e?(e.abbr=t,zi[t]||(zi[t]=new y),zi[t].set(e),x(t),zi[t]):(delete zi[t],null)}function M(t){var e;if(t&&t._locale&&t._locale._abbr&&(t=t._locale._abbr),!t)return Pi;if(!o(t)){if(e=_(t))return e;t=[t]}return w(t)}function O(t,e){var i=t.toLowerCase();Ai[i]=Ai[i+"s"]=Ai[e]=t}function D(t){return"string"==typeof t?Ai[t]||Ai[t.toLowerCase()]:void 0}function T(t){var e,i,o={};for(i in t)r(t,i)&&(e=D(i),e&&(o[e]=t[i]));return o}function C(t,i){return function(o){return null!=o?(S(this,t,o),e.updateOffset(this,i),this):E(this,t)}}function E(t,e){return t._d["get"+(t._isUTC?"UTC":"")+e]()}function S(t,e,i){return t._d["set"+(t._isUTC?"UTC":"")+e](i)}function P(t,e){var i;if("object"==typeof t)for(i in t)this.set(i,t[i]);else if(t=D(t),"function"==typeof this[t])return this[t](e);return this}function I(t,e,i){for(var o=""+Math.abs(t),n=t>=0;o.lengthe;e++)Fi[o[e]]?o[e]=Fi[o[e]]:o[e]=z(o[e]);return function(n){var s="";for(e=0;i>e;e++)s+=o[e]instanceof Function?o[e].call(n,t):o[e];return s}}function L(t,e){return t.isValid()?(e=B(e,t.localeData()),Ri[e]||(Ri[e]=A(e)),Ri[e](t)):t.localeData().invalidDate()}function B(t,e){function i(t){return e.longDateFormat(t)||t}var o=5;for(Bi.lastIndex=0;o>=0&&Bi.test(t);)t=t.replace(Bi,i),Bi.lastIndex=0,o-=1;return t}function R(t,e,i){to[t]="function"==typeof e?e:function(t){return t&&i?i:e}}function F(t,e){return r(to,t)?to[t](e._strict,e._locale):new RegExp(j(t))}function j(t){return t.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(t,e,i,o,n){return e||i||o||n}).replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function H(t,e){var i,o=e;for("string"==typeof t&&(t=[t]),"number"==typeof e&&(o=function(t,i){i[e]=v(t)}),i=0;io;o++){if(n=h([2e3,o]),i&&!this._longMonthsParse[o]&&(this._longMonthsParse[o]=new RegExp("^"+this.months(n,"").replace(".","")+"$","i"),this._shortMonthsParse[o]=new RegExp("^"+this.monthsShort(n,"").replace(".","")+"$","i")),i||this._monthsParse[o]||(s="^"+this.months(n,"")+"|^"+this.monthsShort(n,""),this._monthsParse[o]=new RegExp(s.replace(".",""),"i")),i&&"MMMM"===e&&this._longMonthsParse[o].test(t))return o;if(i&&"MMM"===e&&this._shortMonthsParse[o].test(t))return o;if(!i&&this._monthsParse[o].test(t))return o}}function X(t,e){var i;return"string"==typeof e&&(e=t.localeData().monthsParse(e),"number"!=typeof e)?t:(i=Math.min(t.date(),G(t.year(),e)),t._d["set"+(t._isUTC?"UTC":"")+"Month"](e,i),t)}function Z(t){return null!=t?(X(this,t),e.updateOffset(this,!0),this):E(this,"Month")}function K(){return G(this.year(),this.month())}function J(t){var e,i=t._a;return i&&-2===l(t).overflow&&(e=i[oo]<0||i[oo]>11?oo:i[no]<1||i[no]>G(i[io],i[oo])?no:i[so]<0||i[so]>24||24===i[so]&&(0!==i[ro]||0!==i[ao]||0!==i[ho])?so:i[ro]<0||i[ro]>59?ro:i[ao]<0||i[ao]>59?ao:i[ho]<0||i[ho]>999?ho:-1,l(t)._overflowDayOfYear&&(io>e||e>no)&&(e=no),l(t).overflow=e),t}function Q(t){e.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+t)}function $(t,e){var i=!0,o=t+"\n"+(new Error).stack;return a(function(){return i&&(Q(o),i=!1),e.apply(this,arguments)},e)}function tt(t,e){co[t]||(Q(e),co[t]=!0)}function et(t){var e,i,o=t._i,n=po.exec(o);if(n){for(l(t).iso=!0,e=0,i=fo.length;i>e;e++)if(fo[e][1].exec(o)){t._f=fo[e][0]+(n[6]||" ");break}for(e=0,i=mo.length;i>e;e++)if(mo[e][1].exec(o)){t._f+=mo[e][0];break}o.match(Ji)&&(t._f+="Z"),wt(t)}else t._isValid=!1}function it(t){var i=vo.exec(t._i);return null!==i?void(t._d=new Date(+i[1])):(et(t),void(t._isValid===!1&&(delete t._isValid,e.createFromInputFallback(t))))}function ot(t,e,i,o,n,s,r){var a=new Date(t,e,i,o,n,s,r);return 1970>t&&a.setFullYear(t),a}function nt(t){var e=new Date(Date.UTC.apply(null,arguments));return 1970>t&&e.setUTCFullYear(t),e}function st(t){return rt(t)?366:365}function rt(t){return t%4===0&&t%100!==0||t%400===0}function at(){return rt(this.year())}function ht(t,e,i){var o,n=i-e,s=i-t.day();return s>n&&(s-=7),n-7>s&&(s+=7),o=Tt(t).add(s,"d"),{week:Math.ceil(o.dayOfYear()/7),year:o.year()}}function dt(t){return ht(t,this._week.dow,this._week.doy).week}function lt(){return this._week.dow}function ut(){return this._week.doy}function ct(t){var e=this.localeData().week(this);return null==t?e:this.add(7*(t-e),"d")}function pt(t){var e=ht(this,1,4).week;return null==t?e:this.add(7*(t-e),"d")}function ft(t,e,i,o,n){var s,r,a=nt(t,0,1).getUTCDay();return a=0===a?7:a,i=null!=i?i:n,s=n-a+(a>o?7:0)-(n>a?7:0),r=7*(e-1)+(i-n)+s+1,{year:r>0?t:t-1,dayOfYear:r>0?r:st(t-1)+r}}function mt(t){var e=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==t?e:this.add(t-e,"d")}function vt(t,e,i){return null!=t?t:null!=e?e:i}function gt(t){var e=new Date;return t._useUTC?[e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()]:[e.getFullYear(),e.getMonth(),e.getDate()]}function yt(t){var e,i,o,n,s=[];if(!t._d){for(o=gt(t),t._w&&null==t._a[no]&&null==t._a[oo]&&bt(t),t._dayOfYear&&(n=vt(t._a[io],o[io]),t._dayOfYear>st(n)&&(l(t)._overflowDayOfYear=!0),i=nt(n,0,t._dayOfYear),t._a[oo]=i.getUTCMonth(),t._a[no]=i.getUTCDate()),e=0;3>e&&null==t._a[e];++e)t._a[e]=s[e]=o[e];for(;7>e;e++)t._a[e]=s[e]=null==t._a[e]?2===e?1:0:t._a[e];24===t._a[so]&&0===t._a[ro]&&0===t._a[ao]&&0===t._a[ho]&&(t._nextDay=!0,t._a[so]=0),t._d=(t._useUTC?nt:ot).apply(null,s),null!=t._tzm&&t._d.setUTCMinutes(t._d.getUTCMinutes()-t._tzm),t._nextDay&&(t._a[so]=24)}}function bt(t){var e,i,o,n,s,r,a;e=t._w,null!=e.GG||null!=e.W||null!=e.E?(s=1,r=4,i=vt(e.GG,t._a[io],ht(Tt(),1,4).year),o=vt(e.W,1),n=vt(e.E,1)):(s=t._locale._week.dow,r=t._locale._week.doy,i=vt(e.gg,t._a[io],ht(Tt(),s,r).year),o=vt(e.w,1),null!=e.d?(n=e.d,s>n&&++o):n=null!=e.e?e.e+s:s),a=ft(i,o,n,r,s),t._a[io]=a.year,t._dayOfYear=a.dayOfYear}function wt(t){if(t._f===e.ISO_8601)return void et(t);t._a=[],l(t).empty=!0;var i,o,n,s,r,a=""+t._i,h=a.length,d=0;for(n=B(t._f,t._locale).match(Li)||[],i=0;i0&&l(t).unusedInput.push(r),a=a.slice(a.indexOf(o)+o.length),d+=o.length),Fi[s]?(o?l(t).empty=!1:l(t).unusedTokens.push(s),W(s,o,t)):t._strict&&!o&&l(t).unusedTokens.push(s);l(t).charsLeftOver=h-d,a.length>0&&l(t).unusedInput.push(a),l(t).bigHour===!0&&t._a[so]<=12&&t._a[so]>0&&(l(t).bigHour=void 0),t._a[so]=_t(t._locale,t._a[so],t._meridiem),yt(t),J(t)}function _t(t,e,i){var o;return null==i?e:null!=t.meridiemHour?t.meridiemHour(e,i):null!=t.isPM?(o=t.isPM(i),o&&12>e&&(e+=12),o||12!==e||(e=0),e):e}function xt(t){var e,i,o,n,s;if(0===t._f.length)return l(t).invalidFormat=!0,void(t._d=new Date(NaN));for(n=0;ns)&&(o=s,i=e));a(t,i||e)}function kt(t){if(!t._d){var e=T(t._i);t._a=[e.year,e.month,e.day||e.date,e.hour,e.minute,e.second,e.millisecond],yt(t)}}function Mt(t){var e,i=t._i,s=t._f;return t._locale=t._locale||M(t._l),null===i||void 0===s&&""===i?c({nullInput:!0}):("string"==typeof i&&(t._i=i=t._locale.preparse(i)),m(i)?new f(J(i)):(o(s)?xt(t):s?wt(t):n(i)?t._d=i:Ot(t),e=new f(J(t)),e._nextDay&&(e.add(1,"d"),e._nextDay=void 0),e))}function Ot(t){var i=t._i;void 0===i?t._d=new Date:n(i)?t._d=new Date(+i):"string"==typeof i?it(t):o(i)?(t._a=s(i.slice(0),function(t){return parseInt(t,10)}),yt(t)):"object"==typeof i?kt(t):"number"==typeof i?t._d=new Date(i):e.createFromInputFallback(t)}function Dt(t,e,i,o,n){var s={};return"boolean"==typeof i&&(o=i,i=void 0),s._isAMomentObject=!0,s._useUTC=s._isUTC=n,s._l=i,s._i=t,s._f=e,s._strict=o,Mt(s)}function Tt(t,e,i,o){return Dt(t,e,i,o,!1)}function Ct(t,e){var i,n;if(1===e.length&&o(e[0])&&(e=e[0]),!e.length)return Tt();for(i=e[0],n=1;nt&&(t=-t,i="-"),i+I(~~(t/60),2)+e+I(~~t%60,2)})}function zt(t){var e=(t||"").match(Ji)||[],i=e[e.length-1]||[],o=(i+"").match(_o)||["-",0,0],n=+(60*o[1])+v(o[2]);return"+"===o[0]?n:-n}function At(t,i){var o,s;return i._isUTC?(o=i.clone(),s=(m(t)||n(t)?+t:+Tt(t))-+o,o._d.setTime(+o._d+s),e.updateOffset(o,!1),o):Tt(t).local()}function Lt(t){return 15*-Math.round(t._d.getTimezoneOffset()/15)}function Bt(t,i){var o,n=this._offset||0;return null!=t?("string"==typeof t&&(t=zt(t)),Math.abs(t)<16&&(t=60*t),!this._isUTC&&i&&(o=Lt(this)),this._offset=t,this._isUTC=!0,null!=o&&this.add(o,"m"),n!==t&&(!i||this._changeInProgress?$t(this,Xt(t-n,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,e.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?n:Lt(this)}function Rt(t,e){return null!=t?("string"!=typeof t&&(t=-t),this.utcOffset(t,e),this):-this.utcOffset()}function Ft(t){return this.utcOffset(0,t)}function jt(t){return this._isUTC&&(this.utcOffset(0,t),this._isUTC=!1,t&&this.subtract(Lt(this),"m")),this}function Ht(){return this._tzm?this.utcOffset(this._tzm):"string"==typeof this._i&&this.utcOffset(zt(this._i)),this}function Yt(t){return t=t?Tt(t).utcOffset():0,(this.utcOffset()-t)%60===0}function Wt(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function Gt(){if(this._a){var t=this._isUTC?h(this._a):Tt(this._a);return this.isValid()&&g(this._a,t.toArray())>0}return!1}function Ut(){return!this._isUTC}function Vt(){return this._isUTC}function qt(){return this._isUTC&&0===this._offset}function Xt(t,e){var i,o,n,s=t,a=null;return It(t)?s={ms:t._milliseconds,d:t._days,M:t._months}:"number"==typeof t?(s={},e?s[e]=t:s.milliseconds=t):(a=xo.exec(t))?(i="-"===a[1]?-1:1,s={y:0,d:v(a[no])*i,h:v(a[so])*i,m:v(a[ro])*i,s:v(a[ao])*i,ms:v(a[ho])*i}):(a=ko.exec(t))?(i="-"===a[1]?-1:1,s={y:Zt(a[2],i),M:Zt(a[3],i),d:Zt(a[4],i),h:Zt(a[5],i),m:Zt(a[6],i),s:Zt(a[7],i),w:Zt(a[8],i)}):null==s?s={}:"object"==typeof s&&("from"in s||"to"in s)&&(n=Jt(Tt(s.from),Tt(s.to)),s={},s.ms=n.milliseconds,s.M=n.months),o=new Pt(s),It(t)&&r(t,"_locale")&&(o._locale=t._locale),o}function Zt(t,e){var i=t&&parseFloat(t.replace(",","."));return(isNaN(i)?0:i)*e}function Kt(t,e){var i={milliseconds:0,months:0};return i.months=e.month()-t.month()+12*(e.year()-t.year()),t.clone().add(i.months,"M").isAfter(e)&&--i.months,i.milliseconds=+e-+t.clone().add(i.months,"M"),i}function Jt(t,e){var i;return e=At(e,t),t.isBefore(e)?i=Kt(t,e):(i=Kt(e,t),i.milliseconds=-i.milliseconds,i.months=-i.months),i}function Qt(t,e){return function(i,o){var n,s;return null===o||isNaN(+o)||(tt(e,"moment()."+e+"(period, number) is deprecated. Please use moment()."+e+"(number, period)."),s=i,i=o,o=s),i="string"==typeof i?+i:i,n=Xt(i,o),$t(this,n,t),this}}function $t(t,i,o,n){var s=i._milliseconds,r=i._days,a=i._months;n=null==n?!0:n,s&&t._d.setTime(+t._d+s*o),r&&S(t,"Date",E(t,"Date")+r*o),a&&X(t,E(t,"Month")+a*o),n&&e.updateOffset(t,r||a)}function te(t){var e=t||Tt(),i=At(e,this).startOf("day"),o=this.diff(i,"days",!0),n=-6>o?"sameElse":-1>o?"lastWeek":0>o?"lastDay":1>o?"sameDay":2>o?"nextDay":7>o?"nextWeek":"sameElse";return this.format(this.localeData().calendar(n,this,Tt(e)))}function ee(){return new f(this)}function ie(t,e){var i;return e=D("undefined"!=typeof e?e:"millisecond"),"millisecond"===e?(t=m(t)?t:Tt(t),+this>+t):(i=m(t)?+t:+Tt(t),i<+this.clone().startOf(e))}function oe(t,e){var i;return e=D("undefined"!=typeof e?e:"millisecond"),"millisecond"===e?(t=m(t)?t:Tt(t),+t>+this):(i=m(t)?+t:+Tt(t),+this.clone().endOf(e)t?Math.ceil(t):Math.floor(t)}function ae(t,e,i){var o,n,s=At(t,this),r=6e4*(s.utcOffset()-this.utcOffset());return e=D(e),"year"===e||"month"===e||"quarter"===e?(n=he(this,s),"quarter"===e?n/=3:"year"===e&&(n/=12)):(o=this-s,n="second"===e?o/1e3:"minute"===e?o/6e4:"hour"===e?o/36e5:"day"===e?(o-r)/864e5:"week"===e?(o-r)/6048e5:o),i?n:re(n)}function he(t,e){var i,o,n=12*(e.year()-t.year())+(e.month()-t.month()),s=t.clone().add(n,"months");return 0>e-s?(i=t.clone().add(n-1,"months"),o=(e-s)/(s-i)):(i=t.clone().add(n+1,"months"),o=(e-s)/(i-s)),-(n+o)}function de(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function le(){var t=this.clone().utc();return 0e;e++)if(this._weekdaysParse[e]||(i=Tt([2e3,1]).day(e),o="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[e]=new RegExp(o.replace(".",""),"i")),this._weekdaysParse[e].test(t))return e}function Fe(t){var e=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=t?(t=ze(t,this.localeData()),this.add(t-e,"d")):e}function je(t){var e=(this.day()+7-this.localeData()._week.dow)%7;return null==t?e:this.add(t-e,"d")}function He(t){return null==t?this.day()||7:this.day(this.day()%7?t:t-7)}function Ye(t,e){N(t,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),e)})}function We(t,e){return e._meridiemParse}function Ge(t){return"p"===(t+"").toLowerCase().charAt(0)}function Ue(t,e,i){return t>11?i?"pm":"PM":i?"am":"AM"}function Ve(t){N(0,[t,3],0,"millisecond")}function qe(){return this._isUTC?"UTC":""}function Xe(){return this._isUTC?"Coordinated Universal Time":""}function Ze(t){return Tt(1e3*t)}function Ke(){return Tt.apply(null,arguments).parseZone()}function Je(t,e,i){var o=this._calendar[t];return"function"==typeof o?o.call(e,i):o}function Qe(t){var e=this._longDateFormat[t];return!e&&this._longDateFormat[t.toUpperCase()]&&(e=this._longDateFormat[t.toUpperCase()].replace(/MMMM|MM|DD|dddd/g,function(t){return t.slice(1)}),this._longDateFormat[t]=e),e}function $e(){return this._invalidDate}function ti(t){return this._ordinal.replace("%d",t)}function ei(t){return t}function ii(t,e,i,o){var n=this._relativeTime[i];return"function"==typeof n?n(t,e,i,o):n.replace(/%d/i,t)}function oi(t,e){var i=this._relativeTime[t>0?"future":"past"];return"function"==typeof i?i(e):i.replace(/%s/i,e)}function ni(t){var e,i;for(i in t)e=t[i],"function"==typeof e?this[i]=e:this["_"+i]=e;this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)}function si(t,e,i,o){var n=M(),s=h().set(o,e);return n[i](s,t)}function ri(t,e,i,o,n){if("number"==typeof t&&(e=t,t=void 0),t=t||"",null!=e)return si(t,e,i,n);var s,r=[];for(s=0;o>s;s++)r[s]=si(t,s,i,n);return r}function ai(t,e){return ri(t,e,"months",12,"month")}function hi(t,e){return ri(t,e,"monthsShort",12,"month")}function di(t,e){return ri(t,e,"weekdays",7,"day")}function li(t,e){return ri(t,e,"weekdaysShort",7,"day")}function ui(t,e){return ri(t,e,"weekdaysMin",7,"day")}function ci(){var t=this._data;return this._milliseconds=Uo(this._milliseconds),this._days=Uo(this._days),this._months=Uo(this._months),t.milliseconds=Uo(t.milliseconds),t.seconds=Uo(t.seconds),t.minutes=Uo(t.minutes),t.hours=Uo(t.hours),t.months=Uo(t.months),t.years=Uo(t.years),this}function pi(t,e,i,o){var n=Xt(e,i);return t._milliseconds+=o*n._milliseconds,t._days+=o*n._days,t._months+=o*n._months,t._bubble()}function fi(t,e){return pi(this,t,e,1)}function mi(t,e){return pi(this,t,e,-1)}function vi(){var t,e,i,o=this._milliseconds,n=this._days,s=this._months,r=this._data,a=0;return r.milliseconds=o%1e3,t=re(o/1e3),r.seconds=t%60,e=re(t/60),r.minutes=e%60,i=re(e/60),r.hours=i%24,n+=re(i/24),a=re(gi(n)),n-=re(yi(a)),s+=re(n/30),n%=30,a+=re(s/12),s%=12,r.days=n,r.months=s,r.years=a,this}function gi(t){return 400*t/146097}function yi(t){return 146097*t/400}function bi(t){var e,i,o=this._milliseconds;if(t=D(t),"month"===t||"year"===t)return e=this._days+o/864e5,i=this._months+12*gi(e),"month"===t?i:i/12;switch(e=this._days+Math.round(yi(this._months/12)),t){case"week":return e/7+o/6048e5;case"day":return e+o/864e5;case"hour":return 24*e+o/36e5;case"minute":return 1440*e+o/6e4;case"second":return 86400*e+o/1e3;case"millisecond":return Math.floor(864e5*e)+o;default:throw new Error("Unknown unit "+t)}}function wi(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*v(this._months/12)}function _i(t){return function(){return this.as(t)}}function xi(t){return t=D(t),this[t+"s"]()}function ki(t){return function(){return this._data[t]}}function Mi(){return re(this.days()/7)}function Oi(t,e,i,o,n){return n.relativeTime(e||1,!!i,t,o)}function Di(t,e,i){var o=Xt(t).abs(),n=hn(o.as("s")),s=hn(o.as("m")),r=hn(o.as("h")),a=hn(o.as("d")),h=hn(o.as("M")),d=hn(o.as("y")),l=n0,l[4]=i,Oi.apply(null,l)}function Ti(t,e){return void 0===dn[t]?!1:void 0===e?dn[t]:(dn[t]=e,!0)}function Ci(t){var e=this.localeData(),i=Di(this,!t,e);return t&&(i=e.pastFuture(+this,i)),e.postformat(i)}function Ei(){var t=ln(this.years()),e=ln(this.months()),i=ln(this.days()),o=ln(this.hours()),n=ln(this.minutes()),s=ln(this.seconds()+this.milliseconds()/1e3),r=this.asSeconds();return r?(0>r?"-":"")+"P"+(t?t+"Y":"")+(e?e+"M":"")+(i?i+"D":"")+(o||n||s?"T":"")+(o?o+"H":"")+(n?n+"M":"")+(s?s+"S":""):"P0D"}var Si,Pi,Ii=e.momentProperties=[],Ni=!1,zi={},Ai={},Li=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g,Bi=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Ri={},Fi={},ji=/\d/,Hi=/\d\d/,Yi=/\d{3}/,Wi=/\d{4}/,Gi=/[+-]?\d{6}/,Ui=/\d\d?/,Vi=/\d{1,3}/,qi=/\d{1,4}/,Xi=/[+-]?\d{1,6}/,Zi=/\d+/,Ki=/[+-]?\d+/,Ji=/Z|[+-]\d\d:?\d\d/gi,Qi=/[+-]?\d+(\.\d{1,3})?/,$i=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,to={},eo={},io=0,oo=1,no=2,so=3,ro=4,ao=5,ho=6;N("M",["MM",2],"Mo",function(){return this.month()+1}),N("MMM",0,0,function(t){return this.localeData().monthsShort(this,t)}),N("MMMM",0,0,function(t){return this.localeData().months(this,t)}),O("month","M"),R("M",Ui), +R("MM",Ui,Hi),R("MMM",$i),R("MMMM",$i),H(["M","MM"],function(t,e){e[oo]=v(t)-1}),H(["MMM","MMMM"],function(t,e,i,o){var n=i._locale.monthsParse(t,o,i._strict);null!=n?e[oo]=n:l(i).invalidMonth=t});var lo="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),uo="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),co={};e.suppressDeprecationWarnings=!1;var po=/^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,fo=[["YYYYYY-MM-DD",/[+-]\d{6}-\d{2}-\d{2}/],["YYYY-MM-DD",/\d{4}-\d{2}-\d{2}/],["GGGG-[W]WW-E",/\d{4}-W\d{2}-\d/],["GGGG-[W]WW",/\d{4}-W\d{2}/],["YYYY-DDD",/\d{4}-\d{3}/]],mo=[["HH:mm:ss.SSSS",/(T| )\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],vo=/^\/?Date\((\-?\d+)/i;e.createFromInputFallback=$("moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.",function(t){t._d=new Date(t._i+(t._useUTC?" UTC":""))}),N(0,["YY",2],0,function(){return this.year()%100}),N(0,["YYYY",4],0,"year"),N(0,["YYYYY",5],0,"year"),N(0,["YYYYYY",6,!0],0,"year"),O("year","y"),R("Y",Ki),R("YY",Ui,Hi),R("YYYY",qi,Wi),R("YYYYY",Xi,Gi),R("YYYYYY",Xi,Gi),H(["YYYY","YYYYY","YYYYYY"],io),H("YY",function(t,i){i[io]=e.parseTwoDigitYear(t)}),e.parseTwoDigitYear=function(t){return v(t)+(v(t)>68?1900:2e3)};var go=C("FullYear",!1);N("w",["ww",2],"wo","week"),N("W",["WW",2],"Wo","isoWeek"),O("week","w"),O("isoWeek","W"),R("w",Ui),R("ww",Ui,Hi),R("W",Ui),R("WW",Ui,Hi),Y(["w","ww","W","WW"],function(t,e,i,o){e[o.substr(0,1)]=v(t)});var yo={dow:0,doy:6};N("DDD",["DDDD",3],"DDDo","dayOfYear"),O("dayOfYear","DDD"),R("DDD",Vi),R("DDDD",Yi),H(["DDD","DDDD"],function(t,e,i){i._dayOfYear=v(t)}),e.ISO_8601=function(){};var bo=$("moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548",function(){var t=Tt.apply(null,arguments);return this>t?this:t}),wo=$("moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548",function(){var t=Tt.apply(null,arguments);return t>this?this:t});Nt("Z",":"),Nt("ZZ",""),R("Z",Ji),R("ZZ",Ji),H(["Z","ZZ"],function(t,e,i){i._useUTC=!0,i._tzm=zt(t)});var _o=/([\+\-]|\d\d)/gi;e.updateOffset=function(){};var xo=/(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,ko=/^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/;Xt.fn=Pt.prototype;var Mo=Qt(1,"add"),Oo=Qt(-1,"subtract");e.defaultFormat="YYYY-MM-DDTHH:mm:ssZ";var Do=$("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(t){return void 0===t?this.localeData():this.locale(t)});N(0,["gg",2],0,function(){return this.weekYear()%100}),N(0,["GG",2],0,function(){return this.isoWeekYear()%100}),Te("gggg","weekYear"),Te("ggggg","weekYear"),Te("GGGG","isoWeekYear"),Te("GGGGG","isoWeekYear"),O("weekYear","gg"),O("isoWeekYear","GG"),R("G",Ki),R("g",Ki),R("GG",Ui,Hi),R("gg",Ui,Hi),R("GGGG",qi,Wi),R("gggg",qi,Wi),R("GGGGG",Xi,Gi),R("ggggg",Xi,Gi),Y(["gggg","ggggg","GGGG","GGGGG"],function(t,e,i,o){e[o.substr(0,2)]=v(t)}),Y(["gg","GG"],function(t,i,o,n){i[n]=e.parseTwoDigitYear(t)}),N("Q",0,0,"quarter"),O("quarter","Q"),R("Q",ji),H("Q",function(t,e){e[oo]=3*(v(t)-1)}),N("D",["DD",2],"Do","date"),O("date","D"),R("D",Ui),R("DD",Ui,Hi),R("Do",function(t,e){return t?e._ordinalParse:e._ordinalParseLenient}),H(["D","DD"],no),H("Do",function(t,e){e[no]=v(t.match(Ui)[0],10)});var To=C("Date",!0);N("d",0,"do","day"),N("dd",0,0,function(t){return this.localeData().weekdaysMin(this,t)}),N("ddd",0,0,function(t){return this.localeData().weekdaysShort(this,t)}),N("dddd",0,0,function(t){return this.localeData().weekdays(this,t)}),N("e",0,0,"weekday"),N("E",0,0,"isoWeekday"),O("day","d"),O("weekday","e"),O("isoWeekday","E"),R("d",Ui),R("e",Ui),R("E",Ui),R("dd",$i),R("ddd",$i),R("dddd",$i),Y(["dd","ddd","dddd"],function(t,e,i){var o=i._locale.weekdaysParse(t);null!=o?e.d=o:l(i).invalidWeekday=t}),Y(["d","e","E"],function(t,e,i,o){e[o]=v(t)});var Co="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Eo="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),So="Su_Mo_Tu_We_Th_Fr_Sa".split("_");N("H",["HH",2],0,"hour"),N("h",["hh",2],0,function(){return this.hours()%12||12}),Ye("a",!0),Ye("A",!1),O("hour","h"),R("a",We),R("A",We),R("H",Ui),R("h",Ui),R("HH",Ui,Hi),R("hh",Ui,Hi),H(["H","HH"],so),H(["a","A"],function(t,e,i){i._isPm=i._locale.isPM(t),i._meridiem=t}),H(["h","hh"],function(t,e,i){e[so]=v(t),l(i).bigHour=!0});var Po=/[ap]\.?m?\.?/i,Io=C("Hours",!0);N("m",["mm",2],0,"minute"),O("minute","m"),R("m",Ui),R("mm",Ui,Hi),H(["m","mm"],ro);var No=C("Minutes",!1);N("s",["ss",2],0,"second"),O("second","s"),R("s",Ui),R("ss",Ui,Hi),H(["s","ss"],ao);var zo=C("Seconds",!1);N("S",0,0,function(){return~~(this.millisecond()/100)}),N(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),Ve("SSS"),Ve("SSSS"),O("millisecond","ms"),R("S",Vi,ji),R("SS",Vi,Hi),R("SSS",Vi,Yi),R("SSSS",Zi),H(["S","SS","SSS","SSSS"],function(t,e){e[ho]=v(1e3*("0."+t))});var Ao=C("Milliseconds",!1);N("z",0,0,"zoneAbbr"),N("zz",0,0,"zoneName");var Lo=f.prototype;Lo.add=Mo,Lo.calendar=te,Lo.clone=ee,Lo.diff=ae,Lo.endOf=be,Lo.format=ue,Lo.from=ce,Lo.fromNow=pe,Lo.to=fe,Lo.toNow=me,Lo.get=P,Lo.invalidAt=De,Lo.isAfter=ie,Lo.isBefore=oe,Lo.isBetween=ne,Lo.isSame=se,Lo.isValid=Me,Lo.lang=Do,Lo.locale=ve,Lo.localeData=ge,Lo.max=wo,Lo.min=bo,Lo.parsingFlags=Oe,Lo.set=P,Lo.startOf=ye,Lo.subtract=Oo,Lo.toArray=ke,Lo.toDate=xe,Lo.toISOString=le,Lo.toJSON=le,Lo.toString=de,Lo.unix=_e,Lo.valueOf=we,Lo.year=go,Lo.isLeapYear=at,Lo.weekYear=Ee,Lo.isoWeekYear=Se,Lo.quarter=Lo.quarters=Ne,Lo.month=Z,Lo.daysInMonth=K,Lo.week=Lo.weeks=ct,Lo.isoWeek=Lo.isoWeeks=pt,Lo.weeksInYear=Ie,Lo.isoWeeksInYear=Pe,Lo.date=To,Lo.day=Lo.days=Fe,Lo.weekday=je,Lo.isoWeekday=He,Lo.dayOfYear=mt,Lo.hour=Lo.hours=Io,Lo.minute=Lo.minutes=No,Lo.second=Lo.seconds=zo,Lo.millisecond=Lo.milliseconds=Ao,Lo.utcOffset=Bt,Lo.utc=Ft,Lo.local=jt,Lo.parseZone=Ht,Lo.hasAlignedHourOffset=Yt,Lo.isDST=Wt,Lo.isDSTShifted=Gt,Lo.isLocal=Ut,Lo.isUtcOffset=Vt,Lo.isUtc=qt,Lo.isUTC=qt,Lo.zoneAbbr=qe,Lo.zoneName=Xe,Lo.dates=$("dates accessor is deprecated. Use date instead.",To),Lo.months=$("months accessor is deprecated. Use month instead",Z),Lo.years=$("years accessor is deprecated. Use year instead",go),Lo.zone=$("moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779",Rt);var Bo=Lo,Ro={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},Fo={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY LT",LLLL:"dddd, MMMM D, YYYY LT"},jo="Invalid date",Ho="%d",Yo=/\d{1,2}/,Wo={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},Go=y.prototype;Go._calendar=Ro,Go.calendar=Je,Go._longDateFormat=Fo,Go.longDateFormat=Qe,Go._invalidDate=jo,Go.invalidDate=$e,Go._ordinal=Ho,Go.ordinal=ti,Go._ordinalParse=Yo,Go.preparse=ei,Go.postformat=ei,Go._relativeTime=Wo,Go.relativeTime=ii,Go.pastFuture=oi,Go.set=ni,Go.months=U,Go._months=lo,Go.monthsShort=V,Go._monthsShort=uo,Go.monthsParse=q,Go.week=dt,Go._week=yo,Go.firstDayOfYear=ut,Go.firstDayOfWeek=lt,Go.weekdays=Ae,Go._weekdays=Co,Go.weekdaysMin=Be,Go._weekdaysMin=So,Go.weekdaysShort=Le,Go._weekdaysShort=Eo,Go.weekdaysParse=Re,Go.isPM=Ge,Go._meridiemParse=Po,Go.meridiem=Ue,x("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(t){var e=t%10,i=1===v(t%100/10)?"th":1===e?"st":2===e?"nd":3===e?"rd":"th";return t+i}}),e.lang=$("moment.lang is deprecated. Use moment.locale instead.",x),e.langData=$("moment.langData is deprecated. Use moment.localeData instead.",M);var Uo=Math.abs,Vo=_i("ms"),qo=_i("s"),Xo=_i("m"),Zo=_i("h"),Ko=_i("d"),Jo=_i("w"),Qo=_i("M"),$o=_i("y"),tn=ki("milliseconds"),en=ki("seconds"),on=ki("minutes"),nn=ki("hours"),sn=ki("days"),rn=ki("months"),an=ki("years"),hn=Math.round,dn={s:45,m:45,h:22,d:26,M:11},ln=Math.abs,un=Pt.prototype;un.abs=ci,un.add=fi,un.subtract=mi,un.as=bi,un.asMilliseconds=Vo,un.asSeconds=qo,un.asMinutes=Xo,un.asHours=Zo,un.asDays=Ko,un.asWeeks=Jo,un.asMonths=Qo,un.asYears=$o,un.valueOf=wi,un._bubble=vi,un.get=xi,un.milliseconds=tn,un.seconds=en,un.minutes=on,un.hours=nn,un.days=sn,un.weeks=Mi,un.months=rn,un.years=an,un.humanize=Ci,un.toISOString=Ei,un.toString=Ei,un.toJSON=Ei,un.locale=ve,un.localeData=ge,un.toIsoString=$("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Ei),un.lang=Do,N("X",0,0,"unix"),N("x",0,0,"valueOf"),R("x",Ki),R("X",Qi),H("X",function(t,e,i){i._d=new Date(1e3*parseFloat(t,10))}),H("x",function(t,e,i){i._d=new Date(v(t))}),e.version="2.10.3",i(Tt),e.fn=Bo,e.min=Et,e.max=St,e.utc=h,e.unix=Ze,e.months=ai,e.isDate=n,e.locale=x,e.invalid=c,e.duration=Xt,e.isMoment=m,e.weekdays=di,e.parseZone=Ke,e.localeData=M,e.isDuration=It,e.monthsShort=hi,e.weekdaysMin=ui,e.defineLocale=k,e.weekdaysShort=li,e.normalizeUnits=D,e.relativeTimeThreshold=Ti;var cn=e;return cn})}).call(e,i(10)(t))},function(t,e,i){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children=[],t.webpackPolyfill=1),t}},function(t,e,i){function o(t){throw new Error("Cannot find module '"+t+"'.")}o.keys=function(){return[]},o.resolve=o,t.exports=o,o.id=11},function(t,e,i){(function(e){function i(t,e,i){var o=e&&i||0,n=0;for(e=e||[],t.toLowerCase().replace(/[0-9a-f]{2}/g,function(t){16>n&&(e[o+n++]=u[t])});16>n;)e[o+n++]=0;return e}function o(t,e){var i=e||0,o=l;return o[t[i++]]+o[t[i++]]+o[t[i++]]+o[t[i++]]+"-"+o[t[i++]]+o[t[i++]]+"-"+o[t[i++]]+o[t[i++]]+"-"+o[t[i++]]+o[t[i++]]+"-"+o[t[i++]]+o[t[i++]]+o[t[i++]]+o[t[i++]]+o[t[i++]]+o[t[i++]]}function n(t,e,i){var n=e&&i||0,s=e||[];t=t||{};var r=void 0!==t.clockseq?t.clockseq:m,a=void 0!==t.msecs?t.msecs:(new Date).getTime(),h=void 0!==t.nsecs?t.nsecs:g+1,d=a-v+(h-g)/1e4;if(0>d&&void 0===t.clockseq&&(r=r+1&16383),(0>d||a>v)&&void 0===t.nsecs&&(h=0),h>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");v=a,g=h,m=r,a+=122192928e5;var l=(1e4*(268435455&a)+h)%4294967296;s[n++]=l>>>24&255,s[n++]=l>>>16&255,s[n++]=l>>>8&255,s[n++]=255&l;var u=a/4294967296*1e4&268435455;s[n++]=u>>>8&255,s[n++]=255&u,s[n++]=u>>>24&15|16,s[n++]=u>>>16&255,s[n++]=r>>>8|128,s[n++]=255&r;for(var c=t.node||f,p=0;6>p;p++)s[n+p]=c[p];return e?e:o(s)}function s(t,e,i){var n=e&&i||0;"string"==typeof t&&(e="binary"==t?new Array(16):null,t=null),t=t||{};var s=t.random||(t.rng||r)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var a=0;16>a;a++)e[n+a]=s[a];return e||o(s)}var r,a="undefined"!=typeof window?window:"undefined"!=typeof e?e:null;if(a&&a.crypto&&crypto.getRandomValues){var h=new Uint8Array(16);r=function(){return crypto.getRandomValues(h),h}}if(!r){var d=new Array(16);r=function(){for(var t,e=0;16>e;e++)0===(3&e)&&(t=4294967296*Math.random()),d[e]=t>>>((3&e)<<3)&255;return d}}for(var l=[],u={},c=0;256>c;c++)l[c]=(c+256).toString(16).substr(1),u[l[c]]=c;var p=r(),f=[1|p[0],p[1],p[2],p[3],p[4],p[5]],m=16383&(p[6]<<8|p[7]),v=0,g=0,y=s;y.v1=n,y.v4=s,y.parse=i,y.unparse=o,t.exports=y}).call(e,function(){return this}())},function(t,e,i){e.prepareElements=function(t){for(var e in t)t.hasOwnProperty(e)&&(t[e].redundant=t[e].used,t[e].used=[])},e.cleanupElements=function(t){for(var e in t)if(t.hasOwnProperty(e)&&t[e].redundant){for(var i=0;i0?(o=e[t].redundant[0],e[t].redundant.shift()):(o=document.createElementNS("http://www.w3.org/2000/svg",t),i.appendChild(o)):(o=document.createElementNS("http://www.w3.org/2000/svg",t),e[t]={used:[],redundant:[]},i.appendChild(o)),e[t].used.push(o),o},e.getDOMElement=function(t,e,i,o){var n;return e.hasOwnProperty(t)?e[t].redundant.length>0?(n=e[t].redundant[0],e[t].redundant.shift()):(n=document.createElement(t),void 0!==o?i.insertBefore(n,o):i.appendChild(n)):(n=document.createElement(t),e[t]={used:[],redundant:[]},void 0!==o?i.insertBefore(n,o):i.appendChild(n)),e[t].used.push(n),n},e.drawPoint=function(t,i,o,n,s,r){var a;if("circle"==o.options.drawPoints.style?(a=e.getSVGElement("circle",n,s),a.setAttributeNS(null,"cx",t),a.setAttributeNS(null,"cy",i),a.setAttributeNS(null,"r",.5*o.options.drawPoints.size)):(a=e.getSVGElement("rect",n,s),a.setAttributeNS(null,"x",t-.5*o.options.drawPoints.size),a.setAttributeNS(null,"y",i-.5*o.options.drawPoints.size),a.setAttributeNS(null,"width",o.options.drawPoints.size),a.setAttributeNS(null,"height",o.options.drawPoints.size)),void 0!==o.options.drawPoints.styles&&a.setAttributeNS(null,"style",o.group.options.drawPoints.styles),a.setAttributeNS(null,"class",o.className+" vis-point"),r){var h=e.getSVGElement("text",n,s);r.xOffset&&(t+=r.xOffset),r.yOffset&&(i+=r.yOffset),r.content&&(h.textContent=r.content),r.className&&h.setAttributeNS(null,"class",r.className+" vis-label"),h.setAttributeNS(null,"x",t),h.setAttributeNS(null,"y",i)}return a},e.drawBar=function(t,i,o,n,s,r,a,h){if(0!=n){0>n&&(n*=-1,i-=n);var d=e.getSVGElement("rect",r,a);d.setAttributeNS(null,"x",t-.5*o),d.setAttributeNS(null,"y",i),d.setAttributeNS(null,"width",o),d.setAttributeNS(null,"height",n),d.setAttributeNS(null,"class",s),h&&d.setAttributeNS(null,"style",h)}}},function(t,e,i){function o(t,e){if(t&&!Array.isArray(t)&&(e=t,t=null),this._options=e||{},this._data={},this.length=0,this._fieldId=this._options.fieldId||"id",this._type={},this._options.type)for(var i in this._options.type)if(this._options.type.hasOwnProperty(i)){var o=this._options.type[i];"Date"==o||"ISODate"==o||"ASPDate"==o?this._type[i]="Date":this._type[i]=o}if(this._options.convert)throw new Error('Option "convert" is deprecated. Use "type" instead.');this._subscribers={},t&&this.add(t),this.setOptions(e)}var n=i(7),s=i(15);o.prototype.setOptions=function(t){t&&void 0!==t.queue&&(t.queue===!1?this._queue&&(this._queue.destroy(),delete this._queue):(this._queue||(this._queue=s.extend(this,{replace:["add","update","remove"]})),"object"==typeof t.queue&&this._queue.setOptions(t.queue)))},o.prototype.on=function(t,e){var i=this._subscribers[t];i||(i=[],this._subscribers[t]=i),i.push({callback:e})},o.prototype.subscribe=function(){throw new Error("DataSet.subscribe is deprecated. Use DataSet.on instead.")},o.prototype.off=function(t,e){var i=this._subscribers[t];i&&(this._subscribers[t]=i.filter(function(t){return t.callback!=e}))},o.prototype.unsubscribe=function(){throw new Error("DataSet.unsubscribe is deprecated. Use DataSet.off instead.")},o.prototype._trigger=function(t,e,i){if("*"==t)throw new Error("Cannot trigger event *");var o=[];t in this._subscribers&&(o=o.concat(this._subscribers[t])),"*"in this._subscribers&&(o=o.concat(this._subscribers["*"]));for(var n=0;ns;s++)i=n._addItem(t[s]),o.push(i);else{if(!(t instanceof Object))throw new Error("Unknown dataType");i=n._addItem(t),o.push(i)}return o.length&&this._trigger("add",{items:o},e),o},o.prototype.update=function(t,e){var i=[],o=[],n=[],s=this,r=s._fieldId,a=function(t){var e=t[r];s._data[e]?(e=s._updateItem(t),o.push(e),n.push(t)):(e=s._addItem(t),i.push(e))};if(Array.isArray(t))for(var h=0,d=t.length;d>h;h++)a(t[h]);else{if(!(t instanceof Object))throw new Error("Unknown dataType");a(t)}return i.length&&this._trigger("add",{items:i},e),o.length&&this._trigger("update",{items:o,data:n},e),i.concat(o)},o.prototype.get=function(t){var e,i,o,s=this,r=n.getType(arguments[0]);"String"==r||"Number"==r?(e=arguments[0],o=arguments[1]):"Array"==r?(i=arguments[0],o=arguments[1]):o=arguments[0];var a;if(o&&o.returnType){var h=["Array","Object"];a=-1==h.indexOf(o.returnType)?"Array":o.returnType}else a="Array";var d,l,u,c,p=o&&o.type||this._options.type,f=o&&o.filter,m=[];if(void 0!=e)d=s._getItem(e,p),f&&!f(d)&&(d=null);else if(void 0!=i)for(u=0,c=i.length;c>u;u++)d=s._getItem(i[u],p),(!f||f(d))&&m.push(d);else for(l in this._data)this._data.hasOwnProperty(l)&&(d=s._getItem(l,p),(!f||f(d))&&m.push(d));if(o&&o.order&&void 0==e&&this._sort(m,o.order),o&&o.fields){var v=o.fields;if(void 0!=e)d=this._filterFields(d,v);else for(u=0,c=m.length;c>u;u++)m[u]=this._filterFields(m[u],v)}if("Object"==a){var g={};for(u=0;ue;e++)l[e]=s[e][this._fieldId]}else for(o in r)r.hasOwnProperty(o)&&(n=this._getItem(o,d),a(n)&&l.push(n[this._fieldId]));else if(h){s=[];for(o in r)r.hasOwnProperty(o)&&s.push(r[o]);for(this._sort(s,h),e=0,i=s.length;i>e;e++)l[e]=s[e][this._fieldId]}else for(o in r)r.hasOwnProperty(o)&&(n=r[o],l.push(n[this._fieldId]));return l},o.prototype.getDataSet=function(){return this},o.prototype.forEach=function(t,e){var i,o,n=e&&e.filter,s=e&&e.type||this._options.type,r=this._data;if(e&&e.order)for(var a=this.get(e),h=0,d=a.length;d>h;h++)i=a[h],o=i[this._fieldId],t(i,o);else for(o in r)r.hasOwnProperty(o)&&(i=this._getItem(o,s),(!n||n(i))&&t(i,o))},o.prototype.map=function(t,e){var i,o=e&&e.filter,n=e&&e.type||this._options.type,s=[],r=this._data;for(var a in r)r.hasOwnProperty(a)&&(i=this._getItem(a,n),(!o||o(i))&&s.push(t(i,a)));return e&&e.order&&this._sort(s,e.order),s},o.prototype._filterFields=function(t,e){if(!t)return t;var i={};if(Array.isArray(e))for(var o in t)t.hasOwnProperty(o)&&-1!=e.indexOf(o)&&(i[o]=t[o]);else for(var o in t)t.hasOwnProperty(o)&&e.hasOwnProperty(o)&&(i[e[o]]=t[o]);return i},o.prototype._sort=function(t,e){if(n.isString(e)){var i=e;t.sort(function(t,e){var o=t[i],n=e[i];return o>n?1:n>o?-1:0})}else{if("function"!=typeof e)throw new TypeError("Order must be a function or a string");t.sort(e)}},o.prototype.remove=function(t,e){var i,o,n,s=[];if(Array.isArray(t))for(i=0,o=t.length;o>i;i++)n=this._remove(t[i]),null!=n&&s.push(n);else n=this._remove(t),null!=n&&s.push(n);return s.length&&this._trigger("remove",{items:s},e),s},o.prototype._remove=function(t){if(n.isNumber(t)||n.isString(t)){if(this._data[t])return delete this._data[t],this.length--,t}else if(t instanceof Object){var e=t[this._fieldId];if(e&&this._data[e])return delete this._data[e],this.length--,e}return null},o.prototype.clear=function(t){var e=Object.keys(this._data);return this._data={},this.length=0,this._trigger("remove",{items:e},t),e},o.prototype.max=function(t){var e=this._data,i=null,o=null;for(var n in e)if(e.hasOwnProperty(n)){var s=e[n],r=s[t];null!=r&&(!i||r>o)&&(i=s,o=r)}return i},o.prototype.min=function(t){var e=this._data,i=null,o=null;for(var n in e)if(e.hasOwnProperty(n)){var s=e[n],r=s[t];null!=r&&(!i||o>r)&&(i=s,o=r)}return i},o.prototype.distinct=function(t){var e,i=this._data,o=[],s=this._options.type&&this._options.type[t]||null,r=0;for(var a in i)if(i.hasOwnProperty(a)){var h=i[a],d=h[t],l=!1;for(e=0;r>e;e++)if(o[e]==d){l=!0;break}l||void 0===d||(o[r]=d,r++)}if(s)for(e=0;ethis.max&&this.flush(),clearTimeout(this._timeout),this.queue.length>0&&"number"==typeof this.delay){var t=this;this._timeout=setTimeout(function(){t.flush()},this.delay)}},o.prototype.flush=function(){for(;this._queue.length>0;){var t=this._queue.shift();t.fn.apply(t.context||t.fn,t.args||[])}},t.exports=o},function(t,e,i){function o(t,e){this._data=null,this._ids={},this.length=0,this._options=e||{},this._fieldId="id",this._subscribers={};var i=this;this.listener=function(){i._onEvent.apply(i,arguments)},this.setData(t)}var n=i(7),s=i(14);o.prototype.setData=function(t){var e,i,o;if(this._data){this._data.off&&this._data.off("*",this.listener),e=[];for(var n in this._ids)this._ids.hasOwnProperty(n)&&e.push(n);this._ids={},this.length=0,this._trigger("remove",{items:e})}if(this._data=t,this._data){for(this._fieldId=this._options.fieldId||this._data&&this._data.options&&this._data.options.fieldId||"id",e=this._data.getIds({filter:this._options&&this._options.filter}),i=0,o=e.length;o>i;i++)n=e[i],this._ids[n]=!0;this.length=e.length,this._trigger("add",{items:e}),this._data.on&&this._data.on("*",this.listener)}},o.prototype.refresh=function(){for(var t,e=this._data.getIds({filter:this._options&&this._options.filter}),i={},o=[],n=[],s=0;so;o++)s=a[o],r=this.get(s),r&&(this._ids[s]=!0,l.push(s));break;case"update":for(o=0,n=a.length;n>o;o++)s=a[o],r=this.get(s),r?this._ids[s]?(u.push(s),d.push(e.data[o])):(this._ids[s]=!0,l.push(s)):this._ids[s]&&(delete this._ids[s],c.push(s));break;case"remove":for(o=0,n=a.length;n>o;o++)s=a[o],this._ids[s]&&(delete this._ids[s],c.push(s))}this.length+=l.length-c.length,l.length&&this._trigger("add",{items:l},i),u.length&&this._trigger("update",{items:u,data:d},i),c.length&&this._trigger("remove",{items:c},i)}},o.prototype.on=s.prototype.on,o.prototype.off=s.prototype.off,o.prototype._trigger=s.prototype._trigger,o.prototype.subscribe=o.prototype.on,o.prototype.unsubscribe=o.prototype.off,t.exports=o},function(t,e,i){function o(t,e,i){if(!(this instanceof o))throw new SyntaxError("Constructor must be called with the new operator");this.containerElement=t,this.width="400px",this.height="400px",this.margin=10,this.defaultXCenter="55%",this.defaultYCenter="50%",this.xLabel="x",this.yLabel="y",this.zLabel="z";var n=function(t){return t};this.xValueLabel=n,this.yValueLabel=n,this.zValueLabel=n,this.filterLabel="time",this.legendLabel="value",this.style=o.STYLE.DOT,this.showPerspective=!0,this.showGrid=!0,this.keepAspectRatio=!0,this.showShadow=!1,this.showGrayBottom=!1,this.showTooltip=!1,this.verticalRatio=.5,this.animationInterval=1e3,this.animationPreload=!1,this.camera=new c,this.eye=new l(0,0,-1),this.dataTable=null,this.dataPoints=null,this.colX=void 0,this.colY=void 0,this.colZ=void 0,this.colValue=void 0,this.colFilter=void 0,this.xMin=0,this.xStep=void 0,this.xMax=1,this.yMin=0,this.yStep=void 0,this.yMax=1,this.zMin=0,this.zStep=void 0,this.zMax=1,this.valueMin=0,this.valueMax=1,this.xBarWidth=1,this.yBarWidth=1,this.colorAxis="#4D4D4D",this.colorGrid="#D3D3D3",this.colorDot="#7DC1FF",this.colorDotBorder="#3267D2",this.create(),this.setOptions(i),e&&this.setData(e)}function n(t){return"clientX"in t?t.clientX:t.targetTouches[0]&&t.targetTouches[0].clientX||0}function s(t){return"clientY"in t?t.clientY:t.targetTouches[0]&&t.targetTouches[0].clientY||0}var r=i(19),a=i(14),h=i(16),d=i(7),l=i(20),u=i(18),c=i(21),p=i(22),f=i(23),m=i(24);r(o.prototype),o.prototype._setScale=function(){this.scale=new l(1/(this.xMax-this.xMin),1/(this.yMax-this.yMin),1/(this.zMax-this.zMin)),this.keepAspectRatio&&(this.scale.x3&&(this.colFilter=3);else{if(this.style!==o.STYLE.DOTCOLOR&&this.style!==o.STYLE.DOTSIZE&&this.style!==o.STYLE.BARCOLOR&&this.style!==o.STYLE.BARSIZE)throw'Unknown style "'+this.style+'"';this.colX=0,this.colY=1,this.colZ=2,this.colValue=3,t.getNumberOfColumns()>4&&(this.colFilter=4)}},o.prototype.getNumberOfRows=function(t){return t.length},o.prototype.getNumberOfColumns=function(t){var e=0;for(var i in t[0])t[0].hasOwnProperty(i)&&e++;return e},o.prototype.getDistinctValues=function(t,e){for(var i=[],o=0;ot[o][e]&&(i.min=t[o][e]),i.maxt;t++){var f=(t-c)/(p-c),v=240*f,g=this._hsv2rgb(v,1,1);u.strokeStyle=g,u.beginPath(),u.moveTo(h,r+t),u.lineTo(a,r+t),u.stroke()}u.strokeStyle=this.colorAxis,u.strokeRect(h,r,i,s)}if(this.style===o.STYLE.DOTSIZE&&(u.strokeStyle=this.colorAxis,u.fillStyle=this.colorDot,u.beginPath(),u.moveTo(h,r),u.lineTo(a,r),u.lineTo(a-i+e,d),u.lineTo(h,d),u.closePath(),u.fill(),u.stroke()),this.style===o.STYLE.DOTCOLOR||this.style===o.STYLE.DOTSIZE){var y=5,b=new m(this.valueMin,this.valueMax,(this.valueMax-this.valueMin)/5,!0);for(b.start(),b.getCurrent()0?this.yMin:this.yMax,n=this._convert3Dto2D(new l(_,r,this.zMin)),Math.cos(2*w)>0?(v.textAlign="center",v.textBaseline="top",n.y+=b):Math.sin(2*w)<0?(v.textAlign="right",v.textBaseline="middle"):(v.textAlign="left",v.textBaseline="middle"),v.fillStyle=this.colorAxis,v.fillText(" "+this.xValueLabel(i.getCurrent())+" ",n.x,n.y),i.next()}for(v.lineWidth=1,o=void 0===this.defaultYStep,i=new m(this.yMin,this.yMax,this.yStep,o),i.start(),i.getCurrent()0?this.xMin:this.xMax,n=this._convert3Dto2D(new l(s,i.getCurrent(),this.zMin)),Math.cos(2*w)<0?(v.textAlign="center",v.textBaseline="top",n.y+=b):Math.sin(2*w)>0?(v.textAlign="right",v.textBaseline="middle"):(v.textAlign="left",v.textBaseline="middle"),v.fillStyle=this.colorAxis,v.fillText(" "+this.yValueLabel(i.getCurrent())+" ",n.x,n.y),i.next();for(v.lineWidth=1,o=void 0===this.defaultZStep,i=new m(this.zMin,this.zMax,this.zStep,o),i.start(),i.getCurrent()0?this.xMin:this.xMax,r=Math.sin(w)<0?this.yMin:this.yMax;!i.end();)t=this._convert3Dto2D(new l(s,r,i.getCurrent())),v.strokeStyle=this.colorAxis,v.beginPath(),v.moveTo(t.x,t.y),v.lineTo(t.x-b,t.y),v.stroke(),v.textAlign="right",v.textBaseline="middle",v.fillStyle=this.colorAxis,v.fillText(this.zValueLabel(i.getCurrent())+" ",t.x-5,t.y),i.next();v.lineWidth=1,t=this._convert3Dto2D(new l(s,r,this.zMin)),e=this._convert3Dto2D(new l(s,r,this.zMax)),v.strokeStyle=this.colorAxis,v.beginPath(),v.moveTo(t.x,t.y),v.lineTo(e.x,e.y),v.stroke(),v.lineWidth=1,c=this._convert3Dto2D(new l(this.xMin,this.yMin,this.zMin)),p=this._convert3Dto2D(new l(this.xMax,this.yMin,this.zMin)),v.strokeStyle=this.colorAxis,v.beginPath(),v.moveTo(c.x,c.y),v.lineTo(p.x,p.y),v.stroke(),c=this._convert3Dto2D(new l(this.xMin,this.yMax,this.zMin)),p=this._convert3Dto2D(new l(this.xMax,this.yMax,this.zMin)),v.strokeStyle=this.colorAxis,v.beginPath(),v.moveTo(c.x,c.y),v.lineTo(p.x,p.y),v.stroke(),v.lineWidth=1,t=this._convert3Dto2D(new l(this.xMin,this.yMin,this.zMin)),e=this._convert3Dto2D(new l(this.xMin,this.yMax,this.zMin)),v.strokeStyle=this.colorAxis,v.beginPath(),v.moveTo(t.x,t.y),v.lineTo(e.x,e.y),v.stroke(),t=this._convert3Dto2D(new l(this.xMax,this.yMin,this.zMin)),e=this._convert3Dto2D(new l(this.xMax,this.yMax,this.zMin)),v.strokeStyle=this.colorAxis,v.beginPath(),v.moveTo(t.x,t.y),v.lineTo(e.x,e.y),v.stroke();var x=this.xLabel;x.length>0&&(u=.1/this.scale.y,s=(this.xMin+this.xMax)/2,r=Math.cos(w)>0?this.yMin-u:this.yMax+u,n=this._convert3Dto2D(new l(s,r,this.zMin)),Math.cos(2*w)>0?(v.textAlign="center",v.textBaseline="top"):Math.sin(2*w)<0?(v.textAlign="right",v.textBaseline="middle"):(v.textAlign="left",v.textBaseline="middle"),v.fillStyle=this.colorAxis,v.fillText(x,n.x,n.y));var k=this.yLabel;k.length>0&&(d=.1/this.scale.x,s=Math.sin(w)>0?this.xMin-d:this.xMax+d,r=(this.yMin+this.yMax)/2,n=this._convert3Dto2D(new l(s,r,this.zMin)),Math.cos(2*w)<0?(v.textAlign="center",v.textBaseline="top"):Math.sin(2*w)>0?(v.textAlign="right",v.textBaseline="middle"):(v.textAlign="left",v.textBaseline="middle"),v.fillStyle=this.colorAxis,v.fillText(k,n.x,n.y));var M=this.zLabel;M.length>0&&(h=30,s=Math.cos(w)>0?this.xMin:this.xMax,r=Math.sin(w)<0?this.yMin:this.yMax,a=(this.zMin+this.zMax)/2,n=this._convert3Dto2D(new l(s,r,a)),v.textAlign="right",v.textBaseline="middle",v.fillStyle=this.colorAxis,v.fillText(M,n.x-h,n.y))},o.prototype._hsv2rgb=function(t,e,i){var o,n,s,r,a,h;switch(r=i*e,a=Math.floor(t/60),h=r*(1-Math.abs(t/60%2-1)),a){case 0:o=r,n=h,s=0;break;case 1:o=h,n=r,s=0;break;case 2:o=0,n=r,s=h;break;case 3:o=0,n=h,s=r;break;case 4:o=h,n=0,s=r;break;case 5:o=r,n=0,s=h;break;default:o=0,n=0,s=0}return"RGB("+parseInt(255*o)+","+parseInt(255*n)+","+parseInt(255*s)+")"},o.prototype._redrawDataGrid=function(){var t,e,i,n,s,r,a,h,d,u,c,p,f,m=this.frame.canvas,v=m.getContext("2d");if(!(void 0===this.dataPoints||this.dataPoints.length<=0)){for(s=0;s0}else r=!0;r?(f=(t.point.z+e.point.z+i.point.z+n.point.z)/4,u=240*(1-(f-this.zMin)*this.scale.z/this.verticalRatio),c=1,this.showShadow?(p=Math.min(1+k.x/M/2,1),a=this._hsv2rgb(u,c,p),h=a):(p=1,a=this._hsv2rgb(u,c,p),h=this.colorAxis)):(a="gray",h=this.colorAxis),d=.5,v.lineWidth=d,v.fillStyle=a,v.strokeStyle=h,v.beginPath(),v.moveTo(t.screen.x,t.screen.y),v.lineTo(e.screen.x,e.screen.y),v.lineTo(n.screen.x,n.screen.y),v.lineTo(i.screen.x,i.screen.y),v.closePath(),v.fill(),v.stroke()}}else for(s=0;sc&&(c=0);var p,f,m;this.style===o.STYLE.DOTCOLOR?(p=240*(1-(d.point.value-this.valueMin)*this.scale.value),f=this._hsv2rgb(p,1,1),m=this._hsv2rgb(p,1,.8)):this.style===o.STYLE.DOTSIZE?(f=this.colorDot,m=this.colorDotBorder):(p=240*(1-(d.point.z-this.zMin)*this.scale.z/this.verticalRatio),f=this._hsv2rgb(p,1,1),m=this._hsv2rgb(p,1,.8)),i.lineWidth=1,i.strokeStyle=m,i.fillStyle=f,i.beginPath(),i.arc(d.screen.x,d.screen.y,c,0,2*Math.PI,!0),i.fill(),i.stroke()}}},o.prototype._redrawDataBar=function(){var t,e,i,n,s=this.frame.canvas,r=s.getContext("2d");if(!(void 0===this.dataPoints||this.dataPoints.length<=0)){for(t=0;t0&&(t=this.dataPoints[0],o.lineWidth=1,o.strokeStyle="blue",o.beginPath(),o.moveTo(t.screen.x,t.screen.y)),e=1;e0&&o.stroke()}},o.prototype._onMouseDown=function(t){if(t=t||window.event,this.leftButtonDown&&this._onMouseUp(t),this.leftButtonDown=t.which?1===t.which:1===t.button,this.leftButtonDown||this.touchDown){this.startMouseX=n(t),this.startMouseY=s(t),this.startStart=new Date(this.start),this.startEnd=new Date(this.end),this.startArmRotation=this.camera.getArmRotation(),this.frame.style.cursor="move";var e=this;this.onmousemove=function(t){e._onMouseMove(t)},this.onmouseup=function(t){e._onMouseUp(t)},d.addEventListener(document,"mousemove",e.onmousemove),d.addEventListener(document,"mouseup",e.onmouseup),d.preventDefault(t)}},o.prototype._onMouseMove=function(t){t=t||window.event;var e=parseFloat(n(t))-this.startMouseX,i=parseFloat(s(t))-this.startMouseY,o=this.startArmRotation.horizontal+e/200,r=this.startArmRotation.vertical+i/200,a=4,h=Math.sin(a/360*2*Math.PI);Math.abs(Math.sin(o))0?1:0>t?-1:0}var o=e[0],n=e[1],s=e[2],r=i((n.x-o.x)*(t.y-o.y)-(n.y-o.y)*(t.x-o.x)),a=i((s.x-n.x)*(t.y-n.y)-(s.y-n.y)*(t.x-n.x)),h=i((o.x-s.x)*(t.y-s.y)-(o.y-s.y)*(t.x-s.x));return!(0!=r&&0!=a&&r!=a||0!=a&&0!=h&&a!=h||0!=r&&0!=h&&r!=h)},o.prototype._dataPointFromXY=function(t,e){var i,n=100,s=null,r=null,a=null,h=new u(t,e);if(this.style===o.STYLE.BAR||this.style===o.STYLE.BARCOLOR||this.style===o.STYLE.BARSIZE)for(i=this.dataPoints.length-1;i>=0;i--){s=this.dataPoints[i];var d=s.surfaces;if(d)for(var l=d.length-1;l>=0;l--){var c=d[l],p=c.corners,f=[p[0].screen,p[1].screen,p[2].screen],m=[p[2].screen,p[3].screen,p[0].screen];if(this._insideTriangle(h,f)||this._insideTriangle(h,m))return s}}else for(i=0;ib)&&n>b&&(a=b,r=s)}}return r},o.prototype._showTooltip=function(t){var e,i,o;this.tooltip?(e=this.tooltip.dom.content,i=this.tooltip.dom.line,o=this.tooltip.dom.dot):(e=document.createElement("div"),e.style.position="absolute",e.style.padding="10px",e.style.border="1px solid #4d4d4d",e.style.color="#1a1a1a",e.style.background="rgba(255,255,255,0.7)",e.style.borderRadius="2px",e.style.boxShadow="5px 5px 10px rgba(128,128,128,0.5)",i=document.createElement("div"),i.style.position="absolute",i.style.height="40px",i.style.width="0",i.style.borderLeft="1px solid #4d4d4d",o=document.createElement("div"),o.style.position="absolute",o.style.height="0",o.style.width="0",o.style.border="5px solid #4d4d4d",o.style.borderRadius="5px",this.tooltip={dataPoint:null,dom:{content:e,line:i,dot:o}}),this._hideTooltip(),this.tooltip.dataPoint=t,"function"==typeof this.showTooltip?e.innerHTML=this.showTooltip(t.point):e.innerHTML="
x:"+t.point.x+"
y:"+t.point.y+"
z:"+t.point.z+"
",e.style.left="0",e.style.top="0",this.frame.appendChild(e),this.frame.appendChild(i),this.frame.appendChild(o);var n=e.offsetWidth,s=e.offsetHeight,r=i.offsetHeight,a=o.offsetWidth,h=o.offsetHeight,d=t.screen.x-n/2;d=Math.min(Math.max(d,10),this.frame.clientWidth-10-n),i.style.left=t.screen.x+"px",i.style.top=t.screen.y-r+"px",e.style.left=d+"px",e.style.top=t.screen.y-r-s+"px",o.style.left=t.screen.x-a/2+"px",o.style.top=t.screen.y-h/2+"px"},o.prototype._hideTooltip=function(){if(this.tooltip){this.tooltip.dataPoint=null;for(var t in this.tooltip.dom)if(this.tooltip.dom.hasOwnProperty(t)){var e=this.tooltip.dom[t];e&&e.parentNode&&e.parentNode.removeChild(e)}}},t.exports=o},function(t,e,i){function o(t,e){this.x=void 0!==t?t:0,this.y=void 0!==e?e:0}t.exports=o},function(t,e,i){function o(t){return t?n(t):void 0}function n(t){for(var e in o.prototype)t[e]=o.prototype[e];return t}t.exports=o,o.prototype.on=o.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks[t]=this._callbacks[t]||[]).push(e),this},o.prototype.once=function(t,e){function i(){o.off(t,i),e.apply(this,arguments)}var o=this;return this._callbacks=this._callbacks||{},i.fn=e,this.on(t,i),this},o.prototype.off=o.prototype.removeListener=o.prototype.removeAllListeners=o.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var i=this._callbacks[t];if(!i)return this;if(1==arguments.length)return delete this._callbacks[t],this;for(var o,n=0;no;++o)i[o].apply(this,e)}return this},o.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks[t]||[]},o.prototype.hasListeners=function(t){return!!this.listeners(t).length}},function(t,e,i){function o(t,e,i){this.x=void 0!==t?t:0,this.y=void 0!==e?e:0,this.z=void 0!==i?i:0}o.subtract=function(t,e){var i=new o;return i.x=t.x-e.x,i.y=t.y-e.y,i.z=t.z-e.z,i},o.add=function(t,e){var i=new o;return i.x=t.x+e.x,i.y=t.y+e.y,i.z=t.z+e.z,i},o.avg=function(t,e){return new o((t.x+e.x)/2,(t.y+e.y)/2,(t.z+e.z)/2)},o.crossProduct=function(t,e){var i=new o;return i.x=t.y*e.z-t.z*e.y,i.y=t.z*e.x-t.x*e.z,i.z=t.x*e.y-t.y*e.x,i},o.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},t.exports=o},function(t,e,i){function o(){this.armLocation=new n,this.armRotation={},this.armRotation.horizontal=0,this.armRotation.vertical=0,this.armLength=1.7,this.cameraLocation=new n,this.cameraRotation=new n(.5*Math.PI,0,0),this.calculateCameraOrientation()}var n=i(20);o.prototype.setArmLocation=function(t,e,i){this.armLocation.x=t,this.armLocation.y=e,this.armLocation.z=i,this.calculateCameraOrientation()},o.prototype.setArmRotation=function(t,e){void 0!==t&&(this.armRotation.horizontal=t),void 0!==e&&(this.armRotation.vertical=e,this.armRotation.vertical<0&&(this.armRotation.vertical=0),this.armRotation.vertical>.5*Math.PI&&(this.armRotation.vertical=.5*Math.PI)),(void 0!==t||void 0!==e)&&this.calculateCameraOrientation()},o.prototype.getArmRotation=function(){var t={};return t.horizontal=this.armRotation.horizontal,t.vertical=this.armRotation.vertical,t},o.prototype.setArmLength=function(t){void 0!==t&&(this.armLength=t,this.armLength<.71&&(this.armLength=.71),this.armLength>5&&(this.armLength=5),this.calculateCameraOrientation())},o.prototype.getArmLength=function(){return this.armLength},o.prototype.getCameraLocation=function(){return this.cameraLocation},o.prototype.getCameraRotation=function(){return this.cameraRotation},o.prototype.calculateCameraOrientation=function(){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),this.cameraRotation.x=Math.PI/2-this.armRotation.vertical,this.cameraRotation.y=0,this.cameraRotation.z=-this.armRotation.horizontal},t.exports=o},function(t,e,i){function o(t,e,i){this.data=t,this.column=e,this.graph=i,this.index=void 0,this.value=void 0,this.values=i.getDistinctValues(t.get(),this.column),this.values.sort(function(t,e){return t>e?1:e>t?-1:0}),this.values.length>0&&this.selectValue(0),this.dataPoints=[],this.loaded=!1,this.onLoadCallback=void 0,i.animationPreload?(this.loaded=!1,this.loadInBackground()):this.loaded=!0}var n=i(16);o.prototype.isLoaded=function(){return this.loaded},o.prototype.getLoadedProgress=function(){for(var t=this.values.length,e=0;this.dataPoints[e];)e++;return Math.round(e/t*100)},o.prototype.getLabel=function(){return this.graph.filterLabel},o.prototype.getColumn=function(){return this.column},o.prototype.getSelectedValue=function(){ +return void 0===this.index?void 0:this.values[this.index]},o.prototype.getValues=function(){return this.values},o.prototype.getValue=function(t){if(t>=this.values.length)throw"Error: index out of range";return this.values[t]},o.prototype._getDataPoints=function(t){if(void 0===t&&(t=this.index),void 0===t)return[];var e;if(this.dataPoints[t])e=this.dataPoints[t];else{var i={};i.column=this.column,i.value=this.values[t];var o=new n(this.data,{filter:function(t){return t[i.column]==i.value}}).get();e=this.graph._getDataPoints(o),this.dataPoints[t]=e}return e},o.prototype.setOnLoadCallback=function(t){this.onLoadCallback=t},o.prototype.selectValue=function(t){if(t>=this.values.length)throw"Error: index out of range";this.index=t,this.value=this.values[t]},o.prototype.loadInBackground=function(t){void 0===t&&(t=0);var e=this.graph.frame;if(t0&&(t--,this.setIndex(t))},o.prototype.next=function(){var t=this.getIndex();t0?this.setIndex(0):this.index=void 0},o.prototype.setIndex=function(t){if(!(to&&(o=0),o>this.values.length-1&&(o=this.values.length-1),o},o.prototype.indexToLeft=function(t){var e=parseFloat(this.frame.bar.style.width)-this.frame.slide.clientWidth-10,i=t/(this.values.length-1)*e,o=i+3;return o},o.prototype._onMouseMove=function(t){var e=t.clientX-this.startClientX,i=this.startSlideX+e,o=this.leftToIndex(i);this.setIndex(o),n.preventDefault()},o.prototype._onMouseUp=function(t){this.frame.style.cursor="auto",n.removeEventListener(document,"mousemove",this.onmousemove),n.removeEventListener(document,"mouseup",this.onmouseup),n.preventDefault()},t.exports=o},function(t,e,i){function o(t,e,i,o){this._start=0,this._end=0,this._step=1,this.prettyStep=!0,this.precision=5,this._current=0,this.setRange(t,e,i,o)}o.prototype.setRange=function(t,e,i,o){this._start=t?t:0,this._end=e?e:0,this.setStep(i,o)},o.prototype.setStep=function(t,e){void 0===t||0>=t||(void 0!==e&&(this.prettyStep=e),this.prettyStep===!0?this._step=o.calculatePrettyStep(t):this._step=t)},o.calculatePrettyStep=function(t){var e=function(t){return Math.log(t)/Math.LN10},i=Math.pow(10,Math.round(e(t))),o=2*Math.pow(10,Math.round(e(t/2))),n=5*Math.pow(10,Math.round(e(t/5))),s=i;return Math.abs(o-t)<=Math.abs(s-t)&&(s=o),Math.abs(n-t)<=Math.abs(s-t)&&(s=n),0>=s&&(s=1),s},o.prototype.getCurrent=function(){return parseFloat(this._current.toPrecision(this.precision))},o.prototype.getStep=function(){return this._step},o.prototype.start=function(){this._current=this._start-this._start%this._step},o.prototype.next=function(){this._current+=this._step},o.prototype.end=function(){return this._current>this._end},t.exports=o},function(t,e,i){function o(t,e,i,h){if(!(this instanceof o))throw new SyntaxError("Constructor must be called with the new operator");if(!(Array.isArray(i)||i instanceof s||i instanceof r)&&i instanceof Object){var u=h;h=i,i=u}var f=this;this.defaultOptions={start:null,end:null,autoResize:!0,orientation:{axis:"bottom",item:"bottom"},width:null,height:null,maxHeight:null,minHeight:null},this.options=n.deepExtend({},this.defaultOptions),this._create(t),this.components=[],this.body={dom:this.dom,domProps:this.props,emitter:{on:this.on.bind(this),off:this.off.bind(this),emit:this.emit.bind(this)},hiddenDates:[],util:{getScale:function(){return f.timeAxis.step.scale},getStep:function(){return f.timeAxis.step.step},toScreen:f._toScreen.bind(f),toGlobalScreen:f._toGlobalScreen.bind(f),toTime:f._toTime.bind(f),toGlobalTime:f._toGlobalTime.bind(f)}},this.range=new a(this.body),this.components.push(this.range),this.body.range=this.range,this.timeAxis=new d(this.body),this.timeAxis2=null,this.components.push(this.timeAxis),this.currentTime=new l(this.body),this.components.push(this.currentTime),this.itemSet=new c(this.body),this.components.push(this.itemSet),this.itemsData=null,this.groupsData=null,this.on("tap",function(t){f.emit("click",f.getEventProperties(t))}),this.on("doubletap",function(t){f.emit("doubleClick",f.getEventProperties(t))}),this.dom.root.oncontextmenu=function(t){f.emit("contextmenu",f.getEventProperties(t))},this.configurator=new p(this,t,g),h&&this.setOptions(h),i&&this.setGroups(i),e?this.setItems(e):this._redraw()}var n=(i(19),i(3),i(7)),s=i(14),r=i(16),a=i(29),h=i(32),d=i(41),l=i(26),u=i(44),c=i(33),p=i(45),f=i(47)["default"],m=i(47).printStyle,v=i(48).allOptions,g=i(48).configureOptions;o.prototype=new h,o.prototype.redraw=function(){this.itemSet&&this.itemSet.markDirty({refreshItems:!0}),this._redraw()},o.prototype.setOptions=function(t){var e=f.validate(t,v);if(e===!0&&console.log("%cErrors have been found in the supplied options object.",m),h.prototype.setOptions.call(this,t),"type"in t&&t.type!==this.options.type){this.options.type=t.type;var i=this.itemsData;if(i){var o=this.getSelection();this.setItems(null),this.setItems(i),this.setSelection(o)}}},o.prototype.setItems=function(t){var e,i=null==this.itemsData;if(e=t?t instanceof s||t instanceof r?t:new s(t,{type:{start:"Date",end:"Date"}}):null,this.itemsData=e,this.itemSet&&this.itemSet.setItems(e),i)if(void 0!=this.options.start||void 0!=this.options.end){if(void 0==this.options.start||void 0==this.options.end)var o=this._getDataRange();var n=void 0!=this.options.start?this.options.start:o.start,a=void 0!=this.options.end?this.options.end:o.end;this.setWindow(n,a,{animation:!1})}else this.fit({animation:!1})},o.prototype.setGroups=function(t){var e;e=t?t instanceof s||t instanceof r?t:new s(t):null,this.groupsData=e,this.itemSet.setGroups(e)},o.prototype.setData=function(t){t&&t.groups&&this.setGroups(t.groups),t&&t.items&&this.setItems(t.items)},o.prototype.setSelection=function(t,e){this.itemSet&&this.itemSet.setSelection(t),e&&e.focus&&this.focus(t,e)},o.prototype.getSelection=function(){return this.itemSet&&this.itemSet.getSelection()||[]},o.prototype.focus=function(t,e){if(this.itemsData&&void 0!=t){var i=Array.isArray(t)?t:[t],o=this.itemsData.getDataSet().get(i,{type:{start:"Date",end:"Date"}}),n=null,s=null;if(o.forEach(function(t){var e=t.start.valueOf(),i="end"in t?t.end.valueOf():t.start.valueOf();(null===n||n>e)&&(n=e),(null===s||i>s)&&(s=i)}),null!==n&&null!==s){var r=(n+s)/2,a=Math.max(this.range.end-this.range.start,1.1*(s-n)),h=e&&void 0!==e.animation?e.animation:!0;this.range.setRange(r-a/2,r+a/2,h)}}},o.prototype.getItemRange=function(){var t=this.itemsData&&this.itemsData.getDataSet(),e=null,i=null;if(t){var o=t.min("start");e=o?n.convert(o.start,"Date").valueOf():null;var s=t.max("start");s&&(i=n.convert(s.start,"Date").valueOf());var r=t.max("end");r&&(i=null==i?n.convert(r.end,"Date").valueOf():Math.max(i,n.convert(r.end,"Date").valueOf()))}return{min:null!=e?new Date(e):null,max:null!=i?new Date(i):null}},o.prototype.getEventProperties=function(t){var e=t.center?t.center.x:t.clientX,i=t.center?t.center.y:t.clientY,o=e-n.getAbsoluteLeft(this.dom.centerContainer),s=i-n.getAbsoluteTop(this.dom.centerContainer),r=this.itemSet.itemFromTarget(t),a=this.itemSet.groupFromTarget(t),h=u.customTimeFromTarget(t),d=this.itemSet.options.snap||null,l=this.body.util.getScale(),c=this.body.util.getStep(),p=this._toTime(o),f=d?d(p,l,c):p,m=n.getTarget(t),v=null;return null!=r?v="item":null!=h?v="custom-time":n.hasParent(m,this.timeAxis.dom.foreground)?v="axis":this.timeAxis2&&n.hasParent(m,this.timeAxis2.dom.foreground)?v="axis":n.hasParent(m,this.itemSet.dom.labelSet)?v="group-label":n.hasParent(m,this.currentTime.bar)?v="current-time":n.hasParent(m,this.dom.center)&&(v="background"),{event:t,item:r?r.id:null,group:a?a.groupId:null,what:v,pageX:t.srcEvent?t.srcEvent.pageX:t.pageX,pageY:t.srcEvent?t.srcEvent.pageY:t.pageY,x:o,y:s,time:p,snappedTime:f}},t.exports=o},function(t,e,i){function o(t,e){this.body=t,this.defaultOptions={showCurrentTime:!0,locales:a,locale:"en"},this.options=n.extend({},this.defaultOptions),this.offset=0,this._create(),this.setOptions(e)}var n=i(7),s=i(27),r=i(8),a=i(28);o.prototype=new s,o.prototype._create=function(){var t=document.createElement("div");t.className="vis-current-time",t.style.position="absolute",t.style.top="0px",t.style.height="100%",this.bar=t},o.prototype.destroy=function(){this.options.showCurrentTime=!1,this.redraw(),this.body=null},o.prototype.setOptions=function(t){t&&n.selectiveExtend(["showCurrentTime","locale","locales"],this.options,t)},o.prototype.redraw=function(){if(this.options.showCurrentTime){var t=this.body.dom.backgroundVertical;this.bar.parentNode!=t&&(this.bar.parentNode&&this.bar.parentNode.removeChild(this.bar),t.appendChild(this.bar),this.start());var e=new Date((new Date).valueOf()+this.offset),i=this.body.util.toScreen(e),o=this.options.locales[this.options.locale];o||(this.warned||(console.log("WARNING: options.locales['"+this.options.locale+"'] not found. See http://visjs.org/docs/timeline.html#Localization"),this.warned=!0),o=this.options.locales.en);var n=o.current+" "+o.time+": "+r(e).format("dddd, MMMM Do YYYY, H:mm:ss");n=n.charAt(0).toUpperCase()+n.substring(1),this.bar.style.left=i+"px",this.bar.title=n}else this.bar.parentNode&&this.bar.parentNode.removeChild(this.bar),this.stop();return!1},o.prototype.start=function(){function t(){e.stop();var i=e.body.range.conversion(e.body.domProps.center.width).scale,o=1/i/10;30>o&&(o=30),o>1e3&&(o=1e3),e.redraw(),e.currentTimeTimer=setTimeout(t,o)}var e=this;t()},o.prototype.stop=function(){void 0!==this.currentTimeTimer&&(clearTimeout(this.currentTimeTimer),delete this.currentTimeTimer)},o.prototype.setCurrentTime=function(t){var e=n.convert(t,"Date").valueOf(),i=(new Date).valueOf();this.offset=e-i,this.redraw()},o.prototype.getCurrentTime=function(){return new Date((new Date).valueOf()+this.offset)},t.exports=o},function(t,e,i){function o(t,e){this.options=null,this.props=null}o.prototype.setOptions=function(t){t&&util.extend(this.options,t)},o.prototype.redraw=function(){return!1},o.prototype.destroy=function(){},o.prototype._isResized=function(){var t=this.props._previousWidth!==this.props.width||this.props._previousHeight!==this.props.height;return this.props._previousWidth=this.props.width,this.props._previousHeight=this.props.height,t},t.exports=o},function(t,e,i){e.en={current:"current",time:"time"},e.en_EN=e.en,e.en_US=e.en,e.nl={current:"huidige",time:"tijd"},e.nl_NL=e.nl,e.nl_BE=e.nl},function(t,e,i){function o(t,e){var i=a().hours(0).minutes(0).seconds(0).milliseconds(0);this.start=i.clone().add(-3,"days").valueOf(),this.end=i.clone().add(4,"days").valueOf(),this.body=t,this.deltaDifference=0,this.scaleOffset=0,this.startToFront=!1,this.endToFront=!0,this.defaultOptions={start:null,end:null,direction:"horizontal",moveable:!0,zoomable:!0,min:null,max:null,zoomMin:10,zoomMax:31536e10},this.options=r.extend({},this.defaultOptions),this.props={touch:{}},this.animationTimer=null,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)),this.body.emitter.on("mousewheel",this._onMouseWheel.bind(this)),this.body.emitter.on("touch",this._onTouch.bind(this)),this.body.emitter.on("pinch",this._onPinch.bind(this)),this.setOptions(e)}function n(t){if("horizontal"!=t&&"vertical"!=t)throw new TypeError('Unknown direction "'+t+'". Choose "horizontal" or "vertical".')}function s(t,e){return{x:t.x-r.getAbsoluteLeft(e),y:t.y-r.getAbsoluteTop(e)}}var r=i(7),a=(i(30),i(8)),h=i(27),d=i(31);o.prototype=new h,o.prototype.setOptions=function(t){if(t){var e=["direction","min","max","zoomMin","zoomMax","moveable","zoomable","activate","hiddenDates"];r.selectiveExtend(e,this.options,t),("start"in t||"end"in t)&&this.setRange(t.start,t.end)}},o.prototype.setRange=function(t,e,i,o){o!==!0&&(o=!1);var n=void 0!=t?r.convert(t,"Date").valueOf():null,s=void 0!=e?r.convert(e,"Date").valueOf():null;if(this._cancelAnimation(),i){var a=this,h=this.start,l=this.end,u="object"==typeof i&&"duration"in i?i.duration:500,c="object"==typeof i&&"easingFunction"in i?i.easingFunction:"easeInOutQuad",p=r.easingFunctions[c];if(!p)throw new Error("Unknown easing function "+JSON.stringify(c)+". Choose from: "+Object.keys(r.easingFunctions).join(", "));var f=(new Date).valueOf(),m=!1,v=function b(){if(!a.props.touch.dragging){var t=(new Date).valueOf(),e=t-f,i=p(e/u),r=e>u,c=r||null===n?n:h+(n-h)*i,v=r||null===s?s:l+(s-l)*i;g=a._applyRange(c,v),d.updateHiddenDates(a.body,a.options.hiddenDates),m=m||g,g&&a.body.emitter.emit("rangechange",{start:new Date(a.start),end:new Date(a.end),byUser:o}),r?m&&a.body.emitter.emit("rangechanged",{start:new Date(a.start),end:new Date(a.end),byUser:o}):a.animationTimer=setTimeout(b,20)}};return v()}var g=this._applyRange(n,s);if(d.updateHiddenDates(this.body,this.options.hiddenDates),g){var y={start:new Date(this.start),end:new Date(this.end),byUser:o};this.body.emitter.emit("rangechange",y),this.body.emitter.emit("rangechanged",y)}},o.prototype._cancelAnimation=function(){this.animationTimer&&(clearTimeout(this.animationTimer),this.animationTimer=null)},o.prototype._applyRange=function(t,e){var i,o=null!=t?r.convert(t,"Date").valueOf():this.start,n=null!=e?r.convert(e,"Date").valueOf():this.end,s=null!=this.options.max?r.convert(this.options.max,"Date").valueOf():null,a=null!=this.options.min?r.convert(this.options.min,"Date").valueOf():null;if(isNaN(o)||null===o)throw new Error('Invalid start "'+t+'"');if(isNaN(n)||null===n)throw new Error('Invalid end "'+e+'"');if(o>n&&(n=o),null!==a&&a>o&&(i=a-o,o+=i,n+=i,null!=s&&n>s&&(n=s)),null!==s&&n>s&&(i=n-s,o-=i,n-=i,null!=a&&a>o&&(o=a)),null!==this.options.zoomMin){var h=parseFloat(this.options.zoomMin);0>h&&(h=0),h>n-o&&(this.end-this.start===h&&o>this.start&&nd&&(d=0),n-o>d&&(this.end-this.start===d&&othis.end?(o=this.start,n=this.end):(i=n-o-d,o+=i/2,n-=i/2))}var l=this.start!=o||this.end!=n;return o>=this.start&&o<=this.end||n>=this.start&&n<=this.end||this.start>=o&&this.start<=n||this.end>=o&&this.end<=n||this.body.emitter.emit("checkRangedItems"),this.start=o,this.end=n,l},o.prototype.getRange=function(){return{start:this.start,end:this.end}},o.prototype.conversion=function(t,e){return o.conversion(this.start,this.end,t,e)},o.conversion=function(t,e,i,o){return void 0===o&&(o=0),0!=i&&e-t!=0?{offset:t,scale:i/(e-t-o)}:{offset:0,scale:1}},o.prototype._onDragStart=function(t){this.deltaDifference=0,this.previousDelta=0,this.options.moveable&&this.props.touch.allowDragging&&(this.props.touch.start=this.start,this.props.touch.end=this.end,this.props.touch.dragging=!0,this.body.dom.root&&(this.body.dom.root.style.cursor="move"))},o.prototype._onDrag=function(t){if(this.options.moveable&&this.props.touch.allowDragging){var e=this.options.direction;n(e);var i="horizontal"==e?t.deltaX:t.deltaY;i-=this.deltaDifference;var o=this.props.touch.end-this.props.touch.start,s=d.getHiddenDurationBetween(this.body.hiddenDates,this.start,this.end);o-=s;var r="horizontal"==e?this.body.domProps.center.width:this.body.domProps.center.height,a=-i/r*o,h=this.props.touch.start+a,l=this.props.touch.end+a,u=d.snapAwayFromHidden(this.body.hiddenDates,h,this.previousDelta-i,!0),c=d.snapAwayFromHidden(this.body.hiddenDates,l,this.previousDelta-i,!0);if(u!=h||c!=l)return this.deltaDifference+=i,this.props.touch.start=u,this.props.touch.end=c,void this._onDrag(t);this.previousDelta=i,this._applyRange(h,l),this.body.emitter.emit("rangechange",{start:new Date(this.start),end:new Date(this.end),byUser:!0})}},o.prototype._onDragEnd=function(t){this.options.moveable&&this.props.touch.allowDragging&&(this.props.touch.dragging=!1,this.body.dom.root&&(this.body.dom.root.style.cursor="auto"),this.body.emitter.emit("rangechanged",{start:new Date(this.start),end:new Date(this.end),byUser:!0}))},o.prototype._onMouseWheel=function(t){if(this.options.zoomable&&this.options.moveable){var e=0;if(t.wheelDelta?e=t.wheelDelta/120:t.detail&&(e=-t.detail/3),e){var i;i=0>e?1-e/5:1/(1+e/5);var o=s({x:t.clientX,y:t.clientY},this.body.dom.center),n=this._pointerToDate(o);this.zoom(i,n,e)}t.preventDefault()}},o.prototype._onTouch=function(t){this.props.touch.start=this.start,this.props.touch.end=this.end,this.props.touch.allowDragging=!0,this.props.touch.center=null,this.scaleOffset=0,this.deltaDifference=0},o.prototype._onPinch=function(t){if(this.options.zoomable&&this.options.moveable){this.props.touch.allowDragging=!1,this.props.touch.center||(this.props.touch.center=s(t.center,this.body.dom.center));var e=1/(t.scale+this.scaleOffset),i=this._pointerToDate(this.props.touch.center),o=d.getHiddenDurationBetween(this.body.hiddenDates,this.start,this.end),n=d.getHiddenDurationBefore(this.body.hiddenDates,this,i),r=o-n,a=i-n+(this.props.touch.start-(i-n))*e,h=i+r+(this.props.touch.end-(i+r))*e;this.startToFront=0>=1-e,this.endToFront=0>=e-1;var l=d.snapAwayFromHidden(this.body.hiddenDates,a,1-e,!0),u=d.snapAwayFromHidden(this.body.hiddenDates,h,e-1,!0);(l!=a||u!=h)&&(this.props.touch.start=l,this.props.touch.end=u,this.scaleOffset=1-t.scale,a=l,h=u),this.setRange(a,h,!1,!0),this.startToFront=!1,this.endToFront=!0}},o.prototype._pointerToDate=function(t){var e,i=this.options.direction;if(n(i),"horizontal"==i)return this.body.util.toTime(t.x).valueOf();var o=this.body.domProps.center.height;return e=this.conversion(o),t.y/e.scale+e.offset},o.prototype.zoom=function(t,e,i){null==e&&(e=(this.start+this.end)/2);var o=d.getHiddenDurationBetween(this.body.hiddenDates,this.start,this.end),n=d.getHiddenDurationBefore(this.body.hiddenDates,this,e),s=o-n,r=e-n+(this.start-(e-n))*t,a=e+s+(this.end-(e+s))*t;this.startToFront=i>0?!1:!0,this.endToFront=-i>0?!1:!0;var h=d.snapAwayFromHidden(this.body.hiddenDates,r,i,!0),l=d.snapAwayFromHidden(this.body.hiddenDates,a,-i,!0);(h!=r||l!=a)&&(r=h,a=l),this.setRange(r,a,!1,!0),this.startToFront=!1,this.endToFront=!0},o.prototype.move=function(t){var e=this.end-this.start,i=this.start+e*t,o=this.end+e*t;this.start=i,this.end=o},o.prototype.moveTo=function(t){var e=(this.start+this.end)/2,i=e-t,o=this.start-i,n=this.end-i;this.setRange(o,n)},t.exports=o},function(t,e,i){i(3);e.onTouch=function(t,e){e.inputHandler=function(t){t.isFirst&&!o&&(e(t),o=!0,setTimeout(function(){o=!1},0))},t.on("hammer.input",e.inputHandler)};var o=!1;e.onRelease=function(t,e){return e.inputHandler=function(t){t.isFinal&&!n&&(e(t),n=!0,setTimeout(function(){n=!1},0))},t.on("hammer.input",e.inputHandler)};var n=!1;e.offTouch=function(t,e){t.off("hammer.input",e.inputHandler)},e.offRelease=e.offTouch},function(t,e,i){var o=i(8);e.convertHiddenOptions=function(t,e){if(t.hiddenDates=[],e&&1==Array.isArray(e)){for(var i=0;i=4*a){var c=0,p=s.clone();switch(i[h].repeat){case"daily":d.day()!=l.day()&&(c=1),d.dayOfYear(n.dayOfYear()),d.year(n.year()),d.subtract(7,"days"),l.dayOfYear(n.dayOfYear()),l.year(n.year()),l.subtract(7-c,"days"),p.add(1,"weeks");break;case"weekly":var f=l.diff(d,"days"),m=d.day();d.date(n.date()),d.month(n.month()),d.year(n.year()),l=d.clone(),d.day(m),l.day(m),l.add(f,"days"),d.subtract(1,"weeks"),l.subtract(1,"weeks"),p.add(1,"weeks");break;case"monthly":d.month()!=l.month()&&(c=1),d.month(n.month()),d.year(n.year()),d.subtract(1,"months"),l.month(n.month()),l.year(n.year()),l.subtract(1,"months"),l.add(c,"months"),p.add(1,"months");break;case"yearly":d.year()!=l.year()&&(c=1),d.year(n.year()),d.subtract(1,"years"),l.year(n.year()),l.subtract(1,"years"),l.add(c,"years"),p.add(1,"years");break;default:return void console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:",i[h].repeat)}for(;p>d;)switch(t.hiddenDates.push({start:d.valueOf(),end:l.valueOf()}),i[h].repeat){case"daily":d.add(1,"days"),l.add(1,"days");break;case"weekly":d.add(1,"weeks"),l.add(1,"weeks");break;case"monthly":d.add(1,"months"),l.add(1,"months");break;case"yearly":d.add(1,"y"),l.add(1,"y");break;default:return void console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:",i[h].repeat)}t.hiddenDates.push({start:d.valueOf(),end:l.valueOf()})}}e.removeDuplicates(t);var v=e.isHidden(t.range.start,t.hiddenDates),g=e.isHidden(t.range.end,t.hiddenDates),y=t.range.start,b=t.range.end;1==v.hidden&&(y=1==t.range.startToFront?v.startDate-1:v.endDate+1),1==g.hidden&&(b=1==t.range.endToFront?g.startDate-1:g.endDate+1),(1==v.hidden||1==g.hidden)&&t.range._applyRange(y,b)}},e.removeDuplicates=function(t){for(var e=t.hiddenDates,i=[],o=0;o=e[o].start&&e[n].end<=e[o].end?e[n].remove=!0:e[n].start>=e[o].start&&e[n].start<=e[o].end?(e[o].end=e[n].end,e[n].remove=!0):e[n].end>=e[o].start&&e[n].end<=e[o].end&&(e[o].start=e[n].start,e[n].remove=!0));for(var o=0;o=r&&a>n){i=!0;break}}if(1==i&&n=e&&i>r&&(o+=r-s)}return o},e.correctTimeForHidden=function(t,i,n){return n=o(n).toDate().valueOf(),n-=e.getHiddenDurationBefore(t,i,n)},e.getHiddenDurationBefore=function(t,e,i){var n=0;i=o(i).toDate().valueOf();for(var s=0;s=e.start&&a=a&&(n+=a-r)}return n},e.getAccumulatedHiddenDuration=function(t,e,i){for(var o=0,n=0,s=e.start,r=0;r=e.start&&h=i)break;o+=h-a}}return o},e.snapAwayFromHidden=function(t,i,o,n){var s=e.isHidden(i,t);return 1==s.hidden?0>o?1==n?s.startDate-(s.endDate-i)-1:s.startDate-1:1==n?s.endDate+(i-s.startDate)+1:s.endDate+1:i},e.isHidden=function(t,e){for(var i=0;i=o&&n>t)return{hidden:!0,startDate:o,endDate:n}}return{hidden:!1,startDate:o,endDate:n}}},function(t,e,i){function o(){}var n=i(19),s=i(3),r=i(30),a=i(7),h=(i(14),i(16),i(29),i(33),i(41)),d=i(42),l=i(31),u=i(44);n(o.prototype),o.prototype._create=function(t){function e(t){i.isActive()&&i.emit("mousewheel",t)}this.dom={},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.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.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.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),this.on("rangechange",this.redraw.bind(this)),this.on("touch",this._onTouch.bind(this)),this.on("pan",this._onDrag.bind(this));var i=this;this.on("change",function(t){t&&1==t.queue?i._redrawTimer||(i._redrawTimer=setTimeout(function(){i._redrawTimer=null,i._redraw()},0)):i._redraw()}),this.hammer=new s(this.dom.root),this.hammer.get("pinch").set({enable:!0}),this.listeners={};var o=["tap","doubletap","press","pinch","pan","panstart","panmove","panend"];if(o.forEach(function(t){var e=function(e){ +i.isActive()&&i.emit(t,e)};i.hammer.on(t,e),i.listeners[t]=e}),r.onTouch(this.hammer,function(t){i.emit("touch",t)}.bind(this)),r.onRelease(this.hammer,function(t){i.emit("release",t)}.bind(this)),this.dom.root.addEventListener("mousewheel",e),this.dom.root.addEventListener("DOMMouseScroll",e),this.props={root:{},background:{},centerContainer:{},leftContainer:{},rightContainer:{},center:{},left:{},right:{},top:{},bottom:{},border:{},scrollTop:0,scrollTopMin:0},this.customTimes=[],this.touch={},this.redrawCount=0,!t)throw new Error("No container provided");t.appendChild(this.dom.root)},o.prototype.setOptions=function(t){if(t){var e=["width","height","minHeight","maxHeight","autoResize","start","end","clickToUse","dataAttributes","hiddenDates"];if(a.selectiveExtend(e,this.options,t),"orientation"in t&&("string"==typeof t.orientation?this.options.orientation={item:t.orientation,axis:t.orientation}:"object"==typeof t.orientation&&("item"in t.orientation&&(this.options.orientation.item=t.orientation.item),"axis"in t.orientation&&(this.options.orientation.axis=t.orientation.axis))),"both"===this.options.orientation.axis){if(!this.timeAxis2){var i=this.timeAxis2=new h(this.body);i.setOptions=function(t){var e=t?a.extend({},t):{};e.orientation="top",h.prototype.setOptions.call(i,e)},this.components.push(i)}}else if(this.timeAxis2){var o=this.components.indexOf(this.timeAxis2);-1!==o&&this.components.splice(o,1),this.timeAxis2.destroy(),this.timeAxis2=null}if("hiddenDates"in this.options&&l.convertHiddenOptions(this.body,this.options.hiddenDates),"clickToUse"in t&&(t.clickToUse?this.activator||(this.activator=new d(this.dom.root)):this.activator&&(this.activator.destroy(),delete this.activator)),"showCustomTime"in t)throw new Error("Option `showCustomTime` is deprecated. Create a custom time bar via timeline.addCustomTime(time [, id])");this._initAutoResize()}if(this.components.forEach(function(e){return e.setOptions(t)}),this.configurator){this.configurator.setOptions(t.configure);var n=a.deepExtend({},this.options);this.components.forEach(function(t){a.deepExtend(n,t.options)}),this.configurator.setModuleOptions({global:n})}this._redraw()},o.prototype.isActive=function(){return!this.activator||this.activator.active},o.prototype.destroy=function(){this.setItems(null),this.setGroups(null),this.off(),this._stopAutoResize(),this.dom.root.parentNode&&this.dom.root.parentNode.removeChild(this.dom.root),this.dom=null,this.activator&&(this.activator.destroy(),delete this.activator);for(var t in this.listeners)this.listeners.hasOwnProperty(t)&&delete this.listeners[t];this.listeners=null,this.hammer=null,this.components.forEach(function(t){return t.destroy()}),this.body=null},o.prototype.setCustomTime=function(t,e){var i=this.customTimes.filter(function(t){return e===t.options.id});if(0===i.length)throw new Error("No custom time bar found with id "+JSON.stringify(e));i.length>0&&i[0].setCustomTime(t)},o.prototype.getCustomTime=function(t){var e=this.customTimes.filter(function(e){return e.options.id===t});if(0===e.length)throw new Error("No custom time bar found with id "+JSON.stringify(t));return e[0].getCustomTime()},o.prototype.addCustomTime=function(t,e){var i=void 0!==t?a.convert(t,"Date").valueOf():new Date,o=this.customTimes.some(function(t){return t.options.id===e});if(o)throw new Error("A custom time with id "+JSON.stringify(e)+" already exists");var n=new u(this.body,{time:i,id:e});return this.customTimes.push(n),this.components.push(n),this.redraw(),e},o.prototype.removeCustomTime=function(t){var e=this.customTimes.filter(function(e){return e.options.id===t});if(0===e.length)throw new Error("No custom time bar found with id "+JSON.stringify(t));e.forEach(function(t){this.customTimes.splice(this.customTimes.indexOf(t),1),this.components.splice(this.components.indexOf(t),1),t.destroy()}.bind(this))},o.prototype.getVisibleItems=function(){return this.itemSet&&this.itemSet.getVisibleItems()||[]},o.prototype.fit=function(t){var e=this._getDataRange();if(null!==e.start||null!==e.end){var i=t&&void 0!==t.animation?t.animation:!0;this.range.setRange(e.start,e.end,i)}},o.prototype._getDataRange=function(){var t=this.getItemRange(),e=t.min,i=t.max;if(null!=e&&null!=i){var o=i.valueOf()-e.valueOf();0>=o&&(o=864e5),e=new Date(e.valueOf()-.05*o),i=new Date(i.valueOf()+.05*o)}return{start:e,end:i}},o.prototype.setWindow=function(t,e,i){var o;if(1==arguments.length){var n=arguments[0];o=void 0!==n.animation?n.animation:!0,this.range.setRange(n.start,n.end,o)}else o=i&&void 0!==i.animation?i.animation:!0,this.range.setRange(t,e,o)},o.prototype.moveTo=function(t,e){var i=this.range.end-this.range.start,o=a.convert(t,"Date").valueOf(),n=o-i/2,s=o+i/2,r=e&&void 0!==e.animation?e.animation:!0;this.range.setRange(n,s,r)},o.prototype.getWindow=function(){var t=this.range.getRange();return{start:new Date(t.start),end:new Date(t.end)}},o.prototype.redraw=function(){this._redraw()},o.prototype._redraw=function(){var t=!1,e=this.options,i=this.props,o=this.dom;if(o){l.updateHiddenDates(this.body,this.options.hiddenDates),"top"==e.orientation?(a.addClassName(o.root,"vis-top"),a.removeClassName(o.root,"vis-bottom")):(a.removeClassName(o.root,"vis-top"),a.addClassName(o.root,"vis-bottom")),o.root.style.maxHeight=a.option.asSize(e.maxHeight,""),o.root.style.minHeight=a.option.asSize(e.minHeight,""),o.root.style.width=a.option.asSize(e.width,""),i.border.left=(o.centerContainer.offsetWidth-o.centerContainer.clientWidth)/2,i.border.right=i.border.left,i.border.top=(o.centerContainer.offsetHeight-o.centerContainer.clientHeight)/2,i.border.bottom=i.border.top;var n=o.root.offsetHeight-o.root.clientHeight,s=o.root.offsetWidth-o.root.clientWidth;0===o.centerContainer.clientHeight&&(i.border.left=i.border.top,i.border.right=i.border.left),0===o.root.clientHeight&&(s=n),i.center.height=o.center.offsetHeight,i.left.height=o.left.offsetHeight,i.right.height=o.right.offsetHeight,i.top.height=o.top.clientHeight||-i.border.top,i.bottom.height=o.bottom.clientHeight||-i.border.bottom;var r=Math.max(i.left.height,i.center.height,i.right.height),h=i.top.height+r+i.bottom.height+n+i.border.top+i.border.bottom;o.root.style.height=a.option.asSize(e.height,h+"px"),i.root.height=o.root.offsetHeight,i.background.height=i.root.height-n;var d=i.root.height-i.top.height-i.bottom.height-n;i.centerContainer.height=d,i.leftContainer.height=d,i.rightContainer.height=i.leftContainer.height,i.root.width=o.root.offsetWidth,i.background.width=i.root.width-s,i.left.width=o.leftContainer.clientWidth||-i.border.left,i.leftContainer.width=i.left.width,i.right.width=o.rightContainer.clientWidth||-i.border.right,i.rightContainer.width=i.right.width;var u=i.root.width-i.left.width-i.right.width-s;i.center.width=u,i.centerContainer.width=u,i.top.width=u,i.bottom.width=u,o.background.style.height=i.background.height+"px",o.backgroundVertical.style.height=i.background.height+"px",o.backgroundHorizontal.style.height=i.centerContainer.height+"px",o.centerContainer.style.height=i.centerContainer.height+"px",o.leftContainer.style.height=i.leftContainer.height+"px",o.rightContainer.style.height=i.rightContainer.height+"px",o.background.style.width=i.background.width+"px",o.backgroundVertical.style.width=i.centerContainer.width+"px",o.backgroundHorizontal.style.width=i.background.width+"px",o.centerContainer.style.width=i.center.width+"px",o.top.style.width=i.top.width+"px",o.bottom.style.width=i.bottom.width+"px",o.background.style.left="0",o.background.style.top="0",o.backgroundVertical.style.left=i.left.width+i.border.left+"px",o.backgroundVertical.style.top="0",o.backgroundHorizontal.style.left="0",o.backgroundHorizontal.style.top=i.top.height+"px",o.centerContainer.style.left=i.left.width+"px",o.centerContainer.style.top=i.top.height+"px",o.leftContainer.style.left="0",o.leftContainer.style.top=i.top.height+"px",o.rightContainer.style.left=i.left.width+i.center.width+"px",o.rightContainer.style.top=i.top.height+"px",o.top.style.left=i.left.width+"px",o.top.style.top="0",o.bottom.style.left=i.left.width+"px",o.bottom.style.top=i.top.height+i.centerContainer.height+"px",this._updateScrollTop();var c=this.props.scrollTop;"top"!=e.orientation.item&&(c+=Math.max(this.props.centerContainer.height-this.props.center.height-this.props.border.top-this.props.border.bottom,0)),o.center.style.left="0",o.center.style.top=c+"px",o.left.style.left="0",o.left.style.top=c+"px",o.right.style.left="0",o.right.style.top=c+"px";var p=0==this.props.scrollTop?"hidden":"",f=this.props.scrollTop==this.props.scrollTopMin?"hidden":"";if(o.shadowTop.style.visibility=p,o.shadowBottom.style.visibility=f,o.shadowTopLeft.style.visibility=p,o.shadowBottomLeft.style.visibility=f,o.shadowTopRight.style.visibility=p,o.shadowBottomRight.style.visibility=f,this.components.forEach(function(e){t=e.redraw()||t}),t){var m=3;this.redrawCount0&&(this.props.scrollTop=0),this.props.scrollTope;e++)o=this.selection[e],n=this.items[o],n&&n.unselect();for(this.selection=[],e=0,i=t.length;i>e;e++)o=t[e],n=this.items[o],n&&(this.selection.push(o),n.select())},o.prototype.getSelection=function(){return this.selection.concat([])},o.prototype.getVisibleItems=function(){var t=this.body.range.getRange(),e=this.body.util.toScreen(t.start),i=this.body.util.toScreen(t.end),o=[];for(var n in this.groups)if(this.groups.hasOwnProperty(n))for(var s=this.groups[n],r=s.visibleItems,a=0;ae&&o.push(h.id)}return o},o.prototype._deselect=function(t){for(var e=this.selection,i=0,o=e.length;o>i;i++)if(e[i]==t){e.splice(i,1);break}},o.prototype.redraw=function(){var t=this.options.margin,e=this.body.range,i=s.option.asSize,o=this.options,n=o.orientation.item,r=!1,a=this.dom.frame,h=o.editable.updateTime||o.editable.updateGroup;this.props.top=this.body.domProps.top.height+this.body.domProps.border.top,this.props.left=this.body.domProps.left.width+this.body.domProps.border.left,a.className="vis-itemset"+(h?" vis-editable":""),r=this._orderGroups()||r;var d=e.end-e.start,l=d!=this.lastVisibleInterval||this.props.width!=this.props.lastWidth;l&&(this.stackDirty=!0),this.lastVisibleInterval=d,this.props.lastWidth=this.props.width;var u=this.stackDirty,c=this._firstGroup(),p={item:t.item,axis:t.axis},f={item:t.item,axis:t.item.vertical/2},m=0,v=t.axis+t.item.vertical;return this.groups[g].redraw(e,f,u),s.forEach(this.groups,function(t){var i=t==c?p:f,o=t.redraw(e,i,u);r=o||r,m+=t.height}),m=Math.max(m,v),this.stackDirty=!1,a.style.height=i(m),this.props.width=a.offsetWidth,this.props.height=m,this.dom.axis.style.top=i("top"==n?this.body.domProps.top.height+this.body.domProps.border.top:this.body.domProps.top.height+this.body.domProps.centerContainer.height),this.dom.axis.style.left="0",r=this._isResized()||r},o.prototype._firstGroup=function(){var t="top"==this.options.orientation.item?0:this.groupIds.length-1,e=this.groupIds[t],i=this.groups[e]||this.groups[v];return i||null},o.prototype._updateUngrouped=function(){var t,e,i=this.groups[v];this.groups[g];if(this.groupsData){if(i){i.hide(),delete this.groups[v];for(e in this.items)if(this.items.hasOwnProperty(e)){t=this.items[e],t.parent&&t.parent.remove(t);var o=this._getGroupId(t.data),n=this.groups[o];n&&n.add(t)||t.hide()}}}else if(!i){var s=null,r=null;i=new l(s,r,this),this.groups[v]=i;for(e in this.items)this.items.hasOwnProperty(e)&&(t=this.items[e],i.add(t));i.show()}},o.prototype.getLabelSet=function(){return this.dom.labelSet},o.prototype.setItems=function(t){var e,i=this,o=this.itemsData;if(t){if(!(t instanceof r||t instanceof a))throw new TypeError("Data must be an instance of DataSet or DataView");this.itemsData=t}else this.itemsData=null;if(o&&(s.forEach(this.itemListeners,function(t,e){o.off(e,t)}),e=o.getIds(),this._onRemove(e)),this.itemsData){var n=this.id;s.forEach(this.itemListeners,function(t,e){i.itemsData.on(e,t,n)}),e=this.itemsData.getIds(),this._onAdd(e),this._updateUngrouped()}},o.prototype.getItems=function(){return this.itemsData},o.prototype.setGroups=function(t){var e,i=this;if(this.groupsData&&(s.forEach(this.groupListeners,function(t,e){i.groupsData.off(e,t)}),e=this.groupsData.getIds(),this.groupsData=null,this._onRemoveGroups(e)),t){if(!(t instanceof r||t instanceof a))throw new TypeError("Data must be an instance of DataSet or DataView");this.groupsData=t}else this.groupsData=null;if(this.groupsData){var o=this.id;s.forEach(this.groupListeners,function(t,e){i.groupsData.on(e,t,o)}),e=this.groupsData.getIds(),this._onAddGroups(e)}this._updateUngrouped(),this._order(),this.body.emitter.emit("change",{queue:!0})},o.prototype.getGroups=function(){return this.groupsData},o.prototype.removeItem=function(t){var e=this.itemsData.get(t),i=this.itemsData.getDataSet();e&&this.options.onRemove(e,function(e){e&&i.remove(t)})},o.prototype._getType=function(t){return t.type||this.options.type||(t.end?"range":"box")},o.prototype._getGroupId=function(t){var e=this._getType(t);return"background"==e&&void 0==t.group?g:this.groupsData?t.group:v},o.prototype._onUpdate=function(t){var e=this;t.forEach(function(t){var i,n=e.itemsData.get(t,e.itemOptions),s=e.items[t],r=e._getType(n),a=o.types[r];if(s&&(a&&s instanceof a?e._updateItem(s,n):(i=s.selected,e._removeItem(s),s=null)),!s){if(!a)throw"rangeoverflow"==r?new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: .vis-item.vis-range .vis-item-content {overflow: visible;}'):new TypeError('Unknown item type "'+r+'"');s=new a(n,e.conversion,e.options),s.id=t,e._addItem(s),i&&(this.selection.push(t),s.select())}}.bind(this)),this._order(),this.stackDirty=!0,this.body.emitter.emit("change",{queue:!0})},o.prototype._onAdd=o.prototype._onUpdate,o.prototype._onRemove=function(t){var e=0,i=this;t.forEach(function(t){var o=i.items[t];o&&(e++,i._removeItem(o))}),e&&(this._order(),this.stackDirty=!0,this.body.emitter.emit("change",{queue:!0}))},o.prototype._order=function(){s.forEach(this.groups,function(t){t.order()})},o.prototype._onUpdateGroups=function(t){this._onAddGroups(t)},o.prototype._onAddGroups=function(t){var e=this;t.forEach(function(t){var i=e.groupsData.get(t),o=e.groups[t];if(o)o.setData(i);else{if(t==v||t==g)throw new Error("Illegal group id. "+t+" is a reserved id.");var n=Object.create(e.options);s.extend(n,{height:null}),o=new l(t,i,e),e.groups[t]=o;for(var r in e.items)if(e.items.hasOwnProperty(r)){var a=e.items[r];a.data.group==t&&o.add(a)}o.order(),o.show()}}),this.body.emitter.emit("change",{queue:!0})},o.prototype._onRemoveGroups=function(t){var e=this.groups;t.forEach(function(t){var i=e[t];i&&(i.hide(),delete e[t])}),this.markDirty(),this.body.emitter.emit("change",{queue:!0})},o.prototype._orderGroups=function(){if(this.groupsData){var t=this.groupsData.getIds({order:this.options.groupOrder}),e=!s.equalArray(t,this.groupIds);if(e){var i=this.groups;t.forEach(function(t){i[t].hide()}),t.forEach(function(t){i[t].show()}),this.groupIds=t}return e}return!1},o.prototype._addItem=function(t){this.items[t.id]=t;var e=this._getGroupId(t.data),i=this.groups[e];i&&i.add(t)},o.prototype._updateItem=function(t,e){var i=t.data.group,o=t.data.subgroup;if(t.setData(e),i!=t.data.group||o!=t.data.subgroup){var n=this.groups[i];n&&n.remove(t);var s=this._getGroupId(t.data),r=this.groups[s];r&&r.add(t)}},o.prototype._removeItem=function(t){t.hide(),delete this.items[t.id];var e=this.selection.indexOf(t.id);-1!=e&&this.selection.splice(e,1),t.parent&&t.parent.remove(t)},o.prototype._constructByEndArray=function(t){for(var e=[],i=0;i0||o.length>0)&&this.body.emitter.emit("select",{items:r})}},o.prototype._onAddItem=function(t){if(this.options.selectable&&this.options.editable.add){var e=this,i=this.options.snap||null,o=this.itemFromTarget(t);if(t.stopPropagation(),o){var n=e.itemsData.get(o.id);this.options.onUpdate(n,function(t){t&&e.itemsData.getDataSet().update(t)})}else{var r=s.getAbsoluteLeft(this.dom.frame),a=t.center.x-r,h=this.body.util.toTime(a),d=this.body.util.getScale(),l=this.body.util.getStep(),u={start:i?i(h,d,l):h,content:"new item"};if("range"===this.options.type){var c=this.body.util.toTime(a+this.props.width/5);u.end=i?i(c,d,l):c}u[this.itemsData._fieldId]=s.randomUUID();var p=this.groupFromTarget(t);p&&(u.group=p.groupId),this.options.onAdd(u,function(t){t&&e.itemsData.getDataSet().add(t)})}}},o.prototype._onMultiSelectItem=function(t){if(this.options.selectable){var e=this.itemFromTarget(t);if(e){var i=this.options.multiselect?this.getSelection():[],n=t.srcEvent&&t.srcEvent.shiftKey||!1;if(n&&this.options.multiselect){i.push(e.id);var s=o._getItemRange(this.itemsData.get(i,this.itemOptions));i=[];for(var r in this.items)if(this.items.hasOwnProperty(r)){var a=this.items[r],h=a.data.start,d=void 0!==a.data.end?a.data.end:h;h>=s.min&&d<=s.max&&!(a instanceof m)&&i.push(a.id)}}else{var l=i.indexOf(e.id);-1==l?i.push(e.id):i.splice(l,1)}this.setSelection(i),this.body.emitter.emit("select",{items:this.getSelection()})}}},o._getItemRange=function(t){var e=null,i=null;return t.forEach(function(t){(null==i||t.starte)&&(e=t.end):(null==e||t.start>e)&&(e=t.start)}),{min:i,max:e}},o.prototype.itemFromTarget=function(t){for(var e=t.target;e;){if(e.hasOwnProperty("timeline-item"))return e["timeline-item"];e=e.parentNode}return null},o.prototype.groupFromTarget=function(t){for(var e=t.center?t.center.y:t.clientY,i=0;ia&&ea)return n}else if(0===i&&ec;c++){var f=this.visibleItems[c];f.repositionY(e)}return o},o.prototype._calculateHeight=function(t){var e,i=this.visibleItems;this.resetSubgroups();var o=this;if(i.length>0){var s=i[0].top,r=i[0].top+i[0].height;if(n.forEach(i,function(t){s=Math.min(s,t.top),r=Math.max(r,t.top+t.height),void 0!==t.data.subgroup&&(o.subgroups[t.data.subgroup].height=Math.max(o.subgroups[t.data.subgroup].height,t.height),o.subgroups[t.data.subgroup].visible=!0)}),s>t.axis){var a=s-t.axis;r-=a,n.forEach(i,function(t){t.top-=a})}e=r+t.item.vertical/2}else e=0;return e=Math.max(e,this.props.label.height)},o.prototype.show=function(){this.dom.label.parentNode||this.itemSet.dom.labelSet.appendChild(this.dom.label),this.dom.foreground.parentNode||this.itemSet.dom.foreground.appendChild(this.dom.foreground),this.dom.background.parentNode||this.itemSet.dom.background.appendChild(this.dom.background),this.dom.axis.parentNode||this.itemSet.dom.axis.appendChild(this.dom.axis)},o.prototype.hide=function(){var t=this.dom.label;t.parentNode&&t.parentNode.removeChild(t);var e=this.dom.foreground;e.parentNode&&e.parentNode.removeChild(e);var i=this.dom.background;i.parentNode&&i.parentNode.removeChild(i);var o=this.dom.axis;o.parentNode&&o.parentNode.removeChild(o)},o.prototype.add=function(t){if(this.items[t.id]=t,t.setParent(this),void 0!==t.data.subgroup&&(void 0===this.subgroups[t.data.subgroup]&&(this.subgroups[t.data.subgroup]={height:0,visible:!1,index:this.subgroupIndex,items:[]},this.subgroupIndex++),this.subgroups[t.data.subgroup].items.push(t)),this.orderSubgroups(),-1==this.visibleItems.indexOf(t)){var e=this.itemSet.body.range;this._checkIfVisible(t,this.visibleItems,e)}},o.prototype.orderSubgroups=function(){if(void 0!==this.subgroupOrderer){var t=[];if("string"==typeof this.subgroupOrderer){for(var e in this.subgroups)t.push({subgroup:e,sortField:this.subgroups[e].items[0].data[this.subgroupOrderer]});t.sort(function(t,e){return t.sortField-e.sortField})}else if("function"==typeof this.subgroupOrderer){for(var e in this.subgroups)t.push(this.subgroups[e].items[0].data);t.sort(this.subgroupOrderer)}if(t.length>0)for(var i=0;it?-1:l>=t?0:1};if(e.length>0)for(s=0;sl}),1==this.checkRangedItems)for(this.checkRangedItems=!1,s=0;sl})}for(s=0;s=0&&(s=e[r],!n(s));r--)void 0===o[s.id]&&(o[s.id]=!0,i.push(s));for(r=t+1;rn;n++)t[n].top=null;for(n=0,s=t.length;s>n;n++){var r=t[n];if(r.stack&&null===r.top){r.top=i.axis;do{for(var a=null,h=0,d=t.length;d>h;h++){var l=t[h];if(null!==l.top&&l!==r&&l.stack&&e.collision(r,l,i.item)){a=l;break}}null!=a&&(r.top=a.top+a.height+i.item.vertical)}while(a)}}},e.nostack=function(t,e,i){var o,n,s;for(o=0,n=t.length;n>o;o++)if(void 0!==t[o].data.subgroup){s=e.axis;for(var r in i)i.hasOwnProperty(r)&&1==i[r].visible&&i[r].indexe.left&&t.top-i.vertical+oe.top}},function(t,e,i){function o(t,e,i){if(this.props={content:{width:0}},this.overflow=!1,t){if(void 0==t.start)throw new Error('Property "start" missing in item '+t.id);if(void 0==t.end)throw new Error('Property "end" missing in item '+t.id)}n.call(this,t,e,i)}var n=(i(3),i(2));o.prototype=new n(null,null,null),o.prototype.baseClassName="vis-item vis-range",o.prototype.isVisible=function(t){return this.data.startt.start},o.prototype.redraw=function(){var t=this.dom;if(t||(this.dom={},t=this.dom,t.box=document.createElement("div"),t.frame=document.createElement("div"),t.frame.className="vis-item-overflow",t.box.appendChild(t.frame),t.content=document.createElement("div"),t.content.className="vis-item-content",t.frame.appendChild(t.content),t.box["timeline-item"]=this,this.dirty=!0),!this.parent)throw new Error("Cannot redraw item: no parent attached");if(!t.box.parentNode){var e=this.parent.dom.foreground;if(!e)throw new Error("Cannot redraw item: parent has no foreground container element");e.appendChild(t.box)}if(this.displayed=!0,this.dirty){this._updateContents(this.dom.content),this._updateTitle(this.dom.box),this._updateDataAttributes(this.dom.box),this._updateStyle(this.dom.box);var i=(this.data.className?" "+this.data.className:"")+(this.selected?" vis-selected":"");t.box.className=this.baseClassName+i,this.overflow="hidden"!==window.getComputedStyle(t.frame).overflow,this.dom.content.style.maxWidth="none",this.props.content.width=this.dom.content.offsetWidth,this.height=this.dom.box.offsetHeight,this.dom.content.style.maxWidth="",this.dirty=!1}this._repaintDeleteButton(t.box),this._repaintDragLeft(),this._repaintDragRight()},o.prototype.show=function(){this.displayed||this.redraw()},o.prototype.hide=function(){if(this.displayed){var t=this.dom.box;t.parentNode&&t.parentNode.removeChild(t),this.displayed=!1}},o.prototype.repositionX=function(t){var e,i,o=this.parent.width,n=this.conversion.toScreen(this.data.start),s=this.conversion.toScreen(this.data.end);(void 0===t||t===!0)&&(-o>n&&(n=-o),s>2*o&&(s=2*o));var r=Math.max(s-n,1);switch(this.overflow?(this.left=n,this.width=r+this.props.content.width,i=this.props.content.width):(this.left=n,this.width=r,i=Math.min(s-n,this.props.content.width)),this.dom.box.style.left=this.left+"px",this.dom.box.style.width=r+"px",this.options.align){case"left":this.dom.content.style.left="0";break;case"right":this.dom.content.style.left=Math.max(r-i,0)+"px";break;case"center":this.dom.content.style.left=Math.max((r-i)/2,0)+"px";break;default:e=this.overflow?s>0?Math.max(-n,0):-i:0>n?-n:0,this.dom.content.style.left=e+"px"}},o.prototype.repositionY=function(){var t=this.options.orientation.item,e=this.dom.box;"top"==t?e.style.top=this.top+"px":e.style.top=this.parent.height-this.top-this.height+"px"},o.prototype._repaintDragLeft=function(){if(this.selected&&this.options.editable.updateTime&&!this.dom.dragLeft){var t=document.createElement("div");t.className="vis-drag-left",t.dragLeftItem=this,this.dom.box.appendChild(t),this.dom.dragLeft=t}else!this.selected&&this.dom.dragLeft&&(this.dom.dragLeft.parentNode&&this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft),this.dom.dragLeft=null)},o.prototype._repaintDragRight=function(){if(this.selected&&this.options.editable.updateTime&&!this.dom.dragRight){var t=document.createElement("div");t.className="vis-drag-right",t.dragRightItem=this,this.dom.box.appendChild(t),this.dom.dragRight=t}else!this.selected&&this.dom.dragRight&&(this.dom.dragRight.parentNode&&this.dom.dragRight.parentNode.removeChild(this.dom.dragRight),this.dom.dragRight=null)},t.exports=o},function(t,e,i){function o(t,e,i,n){this.current=new Date,this._start=new Date,this._end=new Date,this.autoScale=!0,this.scale="day",this.step=1,this.setRange(t,e,i),this.switchedDay=!1,this.switchedMonth=!1,this.switchedYear=!1,this.hiddenDates=n,void 0===n&&(this.hiddenDates=[]),this.format=o.FORMAT}var n=i(8),s=i(31),r=i(7);o.FORMAT={minorLabels:{millisecond:"SSS",second:"s",minute:"HH:mm",hour:"HH:mm",weekday:"ddd D",day:"D",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",month:"YYYY",year:""}},o.prototype.setFormat=function(t){var e=r.deepExtend({},o.FORMAT);this.format=r.deepExtend(e,t)},o.prototype.setRange=function(t,e,i){if(!(t instanceof Date&&e instanceof Date))throw"No legal start or end date in method setRange";this._start=void 0!=t?new Date(t.valueOf()):new Date,this._end=void 0!=e?new Date(e.valueOf()):new Date,this.autoScale&&this.setMinimumStep(i)},o.prototype.first=function(){this.current=new Date(this._start.valueOf()),this.roundToMinor()},o.prototype.roundToMinor=function(){switch(this.scale){case"year":this.current.setFullYear(this.step*Math.floor(this.current.getFullYear()/this.step)),this.current.setMonth(0);case"month":this.current.setDate(1);case"day":case"weekday":this.current.setHours(0);case"hour":this.current.setMinutes(0);case"minute":this.current.setSeconds(0);case"second":this.current.setMilliseconds(0)}if(1!=this.step)switch(this.scale){case"millisecond":this.current.setMilliseconds(this.current.getMilliseconds()-this.current.getMilliseconds()%this.step);break;case"second":this.current.setSeconds(this.current.getSeconds()-this.current.getSeconds()%this.step);break;case"minute":this.current.setMinutes(this.current.getMinutes()-this.current.getMinutes()%this.step);break;case"hour":this.current.setHours(this.current.getHours()-this.current.getHours()%this.step);break;case"weekday":case"day":this.current.setDate(this.current.getDate()-1-(this.current.getDate()-1)%this.step+1);break;case"month":this.current.setMonth(this.current.getMonth()-this.current.getMonth()%this.step);break;case"year":this.current.setFullYear(this.current.getFullYear()-this.current.getFullYear()%this.step)}},o.prototype.hasNext=function(){return this.current.valueOf()<=this._end.valueOf()},o.prototype.next=function(){var t=this.current.valueOf();if(this.current.getMonth()<6)switch(this.scale){case"millisecond":this.current=new Date(this.current.valueOf()+this.step);break;case"second":this.current=new Date(this.current.valueOf()+1e3*this.step);break;case"minute":this.current=new Date(this.current.valueOf()+1e3*this.step*60);break;case"hour":this.current=new Date(this.current.valueOf()+1e3*this.step*60*60);var e=this.current.getHours();this.current.setHours(e-e%this.step);break;case"weekday":case"day":this.current.setDate(this.current.getDate()+this.step);break;case"month":this.current.setMonth(this.current.getMonth()+this.step);break;case"year":this.current.setFullYear(this.current.getFullYear()+this.step)}else switch(this.scale){case"millisecond":this.current=new Date(this.current.valueOf()+this.step);break;case"second":this.current.setSeconds(this.current.getSeconds()+this.step);break;case"minute":this.current.setMinutes(this.current.getMinutes()+this.step);break;case"hour":this.current.setHours(this.current.getHours()+this.step);break;case"weekday":case"day":this.current.setDate(this.current.getDate()+this.step);break;case"month":this.current.setMonth(this.current.getMonth()+this.step);break;case"year":this.current.setFullYear(this.current.getFullYear()+this.step)}if(1!=this.step)switch(this.scale){case"millisecond":this.current.getMilliseconds()0?t.step:1,this.autoScale=!1)},o.prototype.setAutoScale=function(t){this.autoScale=t},o.prototype.setMinimumStep=function(t){if(void 0!=t){var e=31104e6,i=2592e6,o=864e5,n=36e5,s=6e4,r=1e3,a=1;1e3*e>t&&(this.scale="year",this.step=1e3),500*e>t&&(this.scale="year",this.step=500),100*e>t&&(this.scale="year",this.step=100),50*e>t&&(this.scale="year",this.step=50),10*e>t&&(this.scale="year",this.step=10),5*e>t&&(this.scale="year",this.step=5),e>t&&(this.scale="year",this.step=1),3*i>t&&(this.scale="month",this.step=3),i>t&&(this.scale="month",this.step=1),5*o>t&&(this.scale="day",this.step=5),2*o>t&&(this.scale="day",this.step=2),o>t&&(this.scale="day",this.step=1),o/2>t&&(this.scale="weekday",this.step=1),4*n>t&&(this.scale="hour",this.step=4),n>t&&(this.scale="hour",this.step=1),15*s>t&&(this.scale="minute",this.step=15),10*s>t&&(this.scale="minute",this.step=10),5*s>t&&(this.scale="minute",this.step=5),s>t&&(this.scale="minute",this.step=1),15*r>t&&(this.scale="second",this.step=15),10*r>t&&(this.scale="second",this.step=10),5*r>t&&(this.scale="second",this.step=5),r>t&&(this.scale="second",this.step=1),200*a>t&&(this.scale="millisecond",this.step=200),100*a>t&&(this.scale="millisecond",this.step=100),50*a>t&&(this.scale="millisecond",this.step=50),10*a>t&&(this.scale="millisecond",this.step=10),5*a>t&&(this.scale="millisecond",this.step=5),a>t&&(this.scale="millisecond",this.step=1)}},o.snap=function(t,e,i){var o=new Date(t.valueOf());if("year"==e){var n=o.getFullYear()+Math.round(o.getMonth()/12);o.setFullYear(Math.round(n/i)*i),o.setMonth(0),o.setDate(0),o.setHours(0),o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0)}else if("month"==e)o.getDate()>15?(o.setDate(1),o.setMonth(o.getMonth()+1)):o.setDate(1),o.setHours(0),o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0);else if("day"==e){switch(i){case 5:case 2:o.setHours(24*Math.round(o.getHours()/24));break;default:o.setHours(12*Math.round(o.getHours()/12))}o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0)}else if("weekday"==e){switch(i){case 5:case 2:o.setHours(12*Math.round(o.getHours()/12));break;default:o.setHours(6*Math.round(o.getHours()/6))}o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0)}else if("hour"==e){switch(i){case 4:o.setMinutes(60*Math.round(o.getMinutes()/60));break;default:o.setMinutes(30*Math.round(o.getMinutes()/30))}o.setSeconds(0),o.setMilliseconds(0)}else if("minute"==e){switch(i){case 15:case 10:o.setMinutes(5*Math.round(o.getMinutes()/5)),o.setSeconds(0);break;case 5:o.setSeconds(60*Math.round(o.getSeconds()/60));break;default:o.setSeconds(30*Math.round(o.getSeconds()/30))}o.setMilliseconds(0)}else if("second"==e)switch(i){case 15:case 10:o.setSeconds(5*Math.round(o.getSeconds()/5)),o.setMilliseconds(0);break;case 5:o.setMilliseconds(1e3*Math.round(o.getMilliseconds()/1e3));break;default:o.setMilliseconds(500*Math.round(o.getMilliseconds()/500))}else if("millisecond"==e){var s=i>5?i/2:1;o.setMilliseconds(Math.round(o.getMilliseconds()/s)*s)}return o},o.prototype.isMajor=function(){if(1==this.switchedYear)switch(this.switchedYear=!1,this.scale){case"year":case"month":case"weekday":case"day":case"hour":case"minute":case"second":case"millisecond":return!0;default:return!1}else if(1==this.switchedMonth)switch(this.switchedMonth=!1,this.scale){case"weekday":case"day":case"hour":case"minute":case"second":case"millisecond":return!0;default:return!1}else if(1==this.switchedDay)switch(this.switchedDay=!1,this.scale){case"millisecond":case"second":case"minute":case"hour":return!0;default:return!1}switch(this.scale){case"millisecond":return 0==this.current.getMilliseconds();case"second":return 0==this.current.getSeconds();case"minute":return 0==this.current.getHours()&&0==this.current.getMinutes();case"hour":return 0==this.current.getHours();case"weekday":case"day":return 1==this.current.getDate();case"month":return 0==this.current.getMonth();case"year":return!1;default:return!1}},o.prototype.getLabelMinor=function(t){void 0==t&&(t=this.current);var e=this.format.minorLabels[this.scale];return e&&e.length>0?n(t).format(e):""},o.prototype.getLabelMajor=function(t){void 0==t&&(t=this.current);var e=this.format.majorLabels[this.scale];return e&&e.length>0?n(t).format(e):""},o.prototype.getClassName=function(){function t(t){return t/h%2==0?" vis-even":" vis-odd"}function e(t){return t.isSame(new Date,"day")?" vis-today":t.isSame(n().add(1,"day"),"day")?" vis-tomorrow":t.isSame(n().add(-1,"day"),"day")?" vis-yesterday":""}function i(t){return t.isSame(new Date,"week")?" vis-current-week":""}function o(t){return t.isSame(new Date,"month")?" vis-current-month":""}function s(t){return t.isSame(new Date,"year")?" vis-current-year":""}var r=n(this.current),a=r.locale?r.locale("en"):r.lang("en"),h=this.step;switch(this.scale){case"millisecond":return t(a.milliseconds()).trim();case"second":return t(a.seconds()).trim();case"minute":return t(a.minutes()).trim();case"hour":var d=a.hours();return 4==this.step&&(d=d+"-h"+(d+4)),"vis-h"+d+e(a)+t(a.hours());case"weekday":return"vis-"+a.format("dddd").toLowerCase()+e(a)+i(a)+t(a.date());case"day":var l=a.date(),u=a.format("MMMM").toLowerCase();return"vis-day"+l+" vis-"+u+o(a)+t(l-1);case"month":return"vis-"+a.format("MMMM").toLowerCase()+o(a)+t(a.month());case"year":var c=a.year();return"vis-year"+c+s(a)+t(c);default:return""}},t.exports=o},function(t,e,i){function o(t,e,i){n.call(this,t,e,i),this.width=0,this.height=0,this.top=0,this.left=0}var n=(i(7),i(34));o.prototype=Object.create(n.prototype),o.prototype.redraw=function(t,e,i){var o=!1;this.visibleItems=this._updateVisibleItems(this.orderedItems,this.visibleItems,t),this.width=this.dom.background.offsetWidth,this.dom.background.style.height="0";for(var n=0,s=this.visibleItems.length;s>n;n++){var r=this.visibleItems[n];r.repositionY(e)}return o},o.prototype.show=function(){this.dom.background.parentNode||this.itemSet.dom.background.appendChild(this.dom.background)},t.exports=o},function(t,e,i){function o(t,e,i){if(this.props={dot:{top:0,width:0,height:0},content:{height:0,marginLeft:0}},t&&void 0==t.start)throw new Error('Property "start" missing in item '+t);n.call(this,t,e,i)}var n=i(2);o.prototype=new n(null,null,null),o.prototype.isVisible=function(t){var e=(t.end-t.start)/4;return this.data.start>t.start-e&&this.data.startt.start},o.prototype.redraw=function(){var t=this.dom;if(t||(this.dom={},t=this.dom,t.box=document.createElement("div"),t.frame=document.createElement("div"),t.frame.className="vis-item-overflow",t.box.appendChild(t.frame),t.content=document.createElement("div"),t.content.className="vis-item-content",t.frame.appendChild(t.content),this.dirty=!0),!this.parent)throw new Error("Cannot redraw item: no parent attached");if(!t.box.parentNode){var e=this.parent.dom.background;if(!e)throw new Error("Cannot redraw item: parent has no background container element");e.appendChild(t.box)}if(this.displayed=!0,this.dirty){this._updateContents(this.dom.content),this._updateTitle(this.dom.content),this._updateDataAttributes(this.dom.content),this._updateStyle(this.dom.box);var i=(this.data.className?" "+this.data.className:"")+(this.selected?" vis-selected":"");t.box.className=this.baseClassName+i,this.overflow="hidden"!==window.getComputedStyle(t.content).overflow,this.props.content.width=this.dom.content.offsetWidth,this.height=0,this.dirty=!1}},o.prototype.show=r.prototype.show,o.prototype.hide=r.prototype.hide,o.prototype.repositionX=r.prototype.repositionX,o.prototype.repositionY=function(t){var e="top"===this.options.orientation.item;this.dom.content.style.top=e?"":"0",this.dom.content.style.bottom=e?"0":"";var i;if(void 0!==this.data.subgroup){var o=this.data.subgroup,n=this.parent.subgroups,r=n[o].index;if(1==e){i=this.parent.subgroups[o].height+t.item.vertical,i+=0==r?t.axis-.5*t.item.vertical:0;var a=this.parent.top;for(var h in n)n.hasOwnProperty(h)&&1==n[h].visible&&n[h].indexr&&(a+=l)}i=this.parent.subgroups[o].height+t.item.vertical,this.dom.box.style.top=this.parent.height-d+a+"px",this.dom.box.style.bottom=""}}else this.parent instanceof s?(i=Math.max(this.parent.height,this.parent.itemSet.body.domProps.center.height,this.parent.itemSet.body.domProps.centerContainer.height),this.dom.box.style.top=e?"0":"",this.dom.box.style.bottom=e?"":"0"):(i=this.parent.height,this.dom.box.style.top=this.parent.top+"px",this.dom.box.style.bottom="");this.dom.box.style.height=i+"px"},t.exports=o},function(t,e,i){function o(t,e){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"},showMinorLabels:!0,showMajorLabels:!0,format:r.FORMAT,timeAxis:null},this.options=n.extend({},this.defaultOptions),this.body=t,this._create(),this.setOptions(e)}var n=i(7),s=i(27),r=i(37),a=i(31),h=i(8);o.prototype=new s,o.prototype.setOptions=function(t){t&&(n.selectiveExtend(["showMinorLabels","showMajorLabels","hiddenDates","timeAxis"],this.options,t),n.selectiveDeepExtend(["format"],this.options,t),"orientation"in t&&("string"==typeof t.orientation?this.options.orientation.axis=t.orientation:"object"==typeof t.orientation&&"axis"in t.orientation&&(this.options.orientation.axis=t.orientation.axis)),"locale"in t&&("function"==typeof h.locale?h.locale(t.locale):h.lang(t.locale)))},o.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"},o.prototype.destroy=function(){this.dom.foreground.parentNode&&this.dom.foreground.parentNode.removeChild(this.dom.foreground),this.dom.background.parentNode&&this.dom.background.parentNode.removeChild(this.dom.background),this.body=null},o.prototype.redraw=function(){var t=this.options,e=this.props,i=this.dom.foreground,o=this.dom.background,n="top"==t.orientation.axis?this.body.dom.top:this.body.dom.bottom,s=i.parentNode!==n;this._calculateCharSize();var r=this.options.showMinorLabels,a=this.options.showMajorLabels;e.minorLabelHeight=r?e.minorCharHeight:0,e.majorLabelHeight=a?e.majorCharHeight:0,e.height=e.minorLabelHeight+e.majorLabelHeight,e.width=i.offsetWidth,e.minorLineHeight=this.body.domProps.root.height-e.majorLabelHeight-("top"==t.orientation.axis?this.body.domProps.bottom.height:this.body.domProps.top.height),e.minorLineWidth=1,e.majorLineHeight=e.minorLineHeight+e.majorLabelHeight,e.majorLineWidth=1;var h=i.nextSibling,d=o.nextSibling;return i.parentNode&&i.parentNode.removeChild(i),o.parentNode&&o.parentNode.removeChild(o),i.style.height=this.props.height+"px",this._repaintLabels(),h?n.insertBefore(i,h):n.appendChild(i),d?this.body.dom.backgroundVertical.insertBefore(o,d):this.body.dom.backgroundVertical.appendChild(o),this._isResized()||s},o.prototype._repaintLabels=function(){var t=this.options.orientation.axis,e=n.convert(this.body.range.start,"Number"),i=n.convert(this.body.range.end,"Number"),o=this.body.util.toTime(7*(this.props.minorCharWidth||10)).valueOf(),s=o-a.getHiddenDurationBefore(this.body.hiddenDates,this.body.range,o);s-=this.body.util.toTime(0).valueOf();var h=new r(new Date(e),new Date(i),s,this.body.hiddenDates);this.options.format&&h.setFormat(this.options.format),this.options.timeAxis&&h.setScale(this.options.timeAxis),this.step=h;var d=this.dom;d.redundant.lines=d.lines,d.redundant.majorTexts=d.majorTexts,d.redundant.minorTexts=d.minorTexts,d.lines=[],d.majorTexts=[],d.minorTexts=[];var l,u,c,p,f=0,m=0,v=0,g=void 0,y=0;for(h.first();h.hasNext()&&1e3>y;)y++,l=h.getCurrent(),u=h.isMajor(),p=h.getClassName(),m=f,f=this.body.util.toScreen(l),v=f-m,c&&(c.style.width=v+"px"),this.options.showMinorLabels&&this._repaintMinorText(f,h.getLabelMinor(),t,p),u&&this.options.showMajorLabels?(f>0&&(void 0==g&&(g=f),this._repaintMajorText(f,h.getLabelMajor(),t,p)),c=this._repaintMajorLine(f,t,p)):c=this._repaintMinorLine(f,t,p),h.next();if(this.options.showMajorLabels){var b=this.body.util.toTime(0),w=h.getLabelMajor(b),_=w.length*(this.props.majorCharWidth||10)+10;(void 0==g||g>_)&&this._repaintMajorText(0,w,t,p)}n.forEach(this.dom.redundant,function(t){for(;t.length;){var e=t.pop();e&&e.parentNode&&e.parentNode.removeChild(e)}})},o.prototype._repaintMinorText=function(t,e,i,o){var n=this.dom.redundant.minorTexts.shift();if(!n){var s=document.createTextNode("");n=document.createElement("div"),n.appendChild(s),this.dom.foreground.appendChild(n)}this.dom.minorTexts.push(n),n.childNodes[0].nodeValue=e,n.style.top="top"==i?this.props.majorLabelHeight+"px":"0",n.style.left=t+"px",n.className="vis-text vis-minor "+o},o.prototype._repaintMajorText=function(t,e,i,o){var n=this.dom.redundant.majorTexts.shift();if(!n){var s=document.createTextNode(e);n=document.createElement("div"),n.appendChild(s),this.dom.foreground.appendChild(n)}this.dom.majorTexts.push(n),n.childNodes[0].nodeValue=e,n.className="vis-text vis-major "+o,n.style.top="top"==i?"0":this.props.minorLabelHeight+"px",n.style.left=t+"px"},o.prototype._repaintMinorLine=function(t,e,i){var o=this.dom.redundant.lines.shift();o||(o=document.createElement("div"),this.dom.background.appendChild(o)),this.dom.lines.push(o);var n=this.props;return"top"==e?o.style.top=n.majorLabelHeight+"px":o.style.top=this.body.domProps.top.height+"px",o.style.height=n.minorLineHeight+"px",o.style.left=t-n.minorLineWidth/2+"px",o.className="vis-grid vis-vertical vis-minor "+i,o},o.prototype._repaintMajorLine=function(t,e,i){var o=this.dom.redundant.lines.shift();o||(o=document.createElement("div"),this.dom.background.appendChild(o)),this.dom.lines.push(o);var n=this.props;return"top"==e?o.style.top="0":o.style.top=this.body.domProps.top.height+"px",o.style.left=t-n.majorLineWidth/2+"px",o.style.height=n.majorLineHeight+"px",o.className="vis-grid vis-vertical vis-major "+i,o},o.prototype._calculateCharSize=function(){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,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},t.exports=o},function(t,e,i){function o(t){this.active=!1,this.dom={container:t},this.dom.overlay=document.createElement("div"),this.dom.overlay.className="vis-overlay",this.dom.container.appendChild(this.dom.overlay),this.hammer=a(this.dom.overlay),this.hammer.on("tap",this._onTapOverlay.bind(this));var e=this,i=["tap","doubletap","press","pinch","pan","panstart","panmove","panend"];i.forEach(function(t){e.hammer.on(t,function(t){t.stopPropagation()})}),this.bodyHammer=a(document&&document.body,{prevent_default:!1}),this.bodyHammer.on("tap",function(i){n(i.target,t)||e.deactivate()}),void 0!==this.keycharm&&this.keycharm.destroy(),this.keycharm=s(),this.escListener=this.deactivate.bind(this)}function n(t,e){for(;t;){if(t===e)return!0;t=t.parentNode}return!1}var s=i(43),r=i(19),a=i(3),h=i(7);r(o.prototype),o.current=null,o.prototype.destroy=function(){ +this.deactivate(),this.dom.overlay.parentNode.removeChild(this.dom.overlay),this.hammer=null,this.bodyHammer=null},o.prototype.activate=function(){o.current&&o.current.deactivate(),o.current=this,this.active=!0,this.dom.overlay.style.display="none",h.addClassName(this.dom.container,"vis-active"),this.emit("change"),this.emit("activate"),this.keycharm.bind("esc",this.escListener)},o.prototype.deactivate=function(){this.active=!1,this.dom.overlay.style.display="",h.removeClassName(this.dom.container,"vis-active"),this.keycharm.unbind("esc",this.escListener),this.emit("change"),this.emit("deactivate")},o.prototype._onTapOverlay=function(t){this.activate(),t.stopPropagation()},t.exports=o},function(t,e,i){var o,n,s;!function(i,r){n=[],o=r,s="function"==typeof o?o.apply(e,n):o,!(void 0!==s&&(t.exports=s))}(this,function(){function t(t){var e,i=t&&t.preventDefault||!1,o=t&&t.container||window,n={},s={keydown:{},keyup:{}},r={};for(e=97;122>=e;e++)r[String.fromCharCode(e)]={code:65+(e-97),shift:!1};for(e=65;90>=e;e++)r[String.fromCharCode(e)]={code:e,shift:!0};for(e=0;9>=e;e++)r[""+e]={code:48+e,shift:!1};for(e=1;12>=e;e++)r["F"+e]={code:111+e,shift:!1};for(e=0;9>=e;e++)r["num"+e]={code:96+e,shift:!1};r["num*"]={code:106,shift:!1},r["num+"]={code:107,shift:!1},r["num-"]={code:109,shift:!1},r["num/"]={code:111,shift:!1},r["num."]={code:110,shift:!1},r.left={code:37,shift:!1},r.up={code:38,shift:!1},r.right={code:39,shift:!1},r.down={code:40,shift:!1},r.space={code:32,shift:!1},r.enter={code:13,shift:!1},r.shift={code:16,shift:void 0},r.esc={code:27,shift:!1},r.backspace={code:8,shift:!1},r.tab={code:9,shift:!1},r.ctrl={code:17,shift:!1},r.alt={code:18,shift:!1},r["delete"]={code:46,shift:!1},r.pageup={code:33,shift:!1},r.pagedown={code:34,shift:!1},r["="]={code:187,shift:!1},r["-"]={code:189,shift:!1},r["]"]={code:221,shift:!1},r["["]={code:219,shift:!1};var a=function(t){d(t,"keydown")},h=function(t){d(t,"keyup")},d=function(t,e){if(void 0!==s[e][t.keyCode]){for(var o=s[e][t.keyCode],n=0;n0&&this._makeItem([]),this._makeHeader(n),this._handleObject(this.configureOptions[n],[n])),i++);this.options.showButton===!0&&!function(){var e=document.createElement("div");e.className="vis-network-configuration button",e.innerHTML="generate options",e.onclick=function(){t._printOptions()},e.onmouseover=function(){e.className="vis-network-configuration button hover"},e.onmouseout=function(){e.className="vis-network-configuration button"},t.optionsContainer=document.createElement("div"),t.optionsContainer.className="vis-network-configuration vis-option-container",t.domElements.push(t.optionsContainer),t.domElements.push(e)}(),this._push(),this.colorPicker.insertTo(this.container)}},{key:"_push",value:function(){this.wrapper=document.createElement("div"),this.wrapper.className="vis-network-configuration-wrapper",this.container.appendChild(this.wrapper);for(var t=0;t1?i-1:0),n=1;i>n;n++)o[n-1]=arguments[n];this.allowCreation===!0&&!function(){var i=document.createElement("div");i.className="vis-network-configuration item s"+t.length,o.forEach(function(t){i.appendChild(t)}),e.domElements.push(i)}()}},{key:"_makeHeader",value:function(t){var e=document.createElement("div");e.className="vis-network-configuration header",e.innerHTML=t,this._makeItem([],e)}},{key:"_makeLabel",value:function(t,e){var i=void 0===arguments[2]?!1:arguments[2],o=document.createElement("div");return o.className="vis-network-configuration label s"+e.length,i===!0?o.innerHTML=""+t+":":o.innerHTML=t+":",o}},{key:"_makeDropdown",value:function(t,e,i){var o=document.createElement("select");o.className="vis-network-configuration select";var n=0;void 0!==e&&-1!==t.indexOf(e)&&(n=t.indexOf(e));for(var s=0;se&&n>2*e?a.min=2*e:n>.1*e&&(a.min=e/10),2*e>s&&1!==s&&(a.max=2*e),a.value=e):a.value=o;var h=document.createElement("input");h.className="vis-network-configuration rangeinput",h.value=a.value;var d=this;a.onchange=function(){h.value=this.value,d._update(Number(this.value),i)},a.oninput=function(){h.value=this.value};var l=this._makeLabel(i[i.length-1],i);this._makeItem(i,l,a,h)}},{key:"_makeCheckbox",value:function(t,e,i){var o=document.createElement("input");o.type="checkbox",o.className="vis-network-configuration checkbox",o.checked=t,void 0!==e&&(o.checked=e,e!==t&&("object"==typeof t?e!==t.enabled&&this.changedOptions.push({path:i,value:e}):this.changedOptions.push({path:i,value:e})));var n=this;o.onchange=function(){n._update(this.checked,i)};var s=this._makeLabel(i[i.length-1],i);this._makeItem(i,s,o)}},{key:"_makeTextInput",value:function(t,e,i){var o=document.createElement("input");o.type="text",o.className="vis-network-configuration text",o.value=e,e!==t&&this.changedOptions.push({path:i,value:e});var n=this;o.onchange=function(){n._update(this.value,i)};var s=this._makeLabel(i[i.length-1],i);this._makeItem(i,s,o)}},{key:"_makeColorField",value:function(t,e,i){var o=this,n=t[1],s=document.createElement("div");e=void 0===e?n:e,"none"!==e?(s.className="vis-network-configuration colorBlock",s.style.backgroundColor=e):s.className="vis-network-configuration colorBlock none",e=void 0===e?n:e,s.onclick=function(){o._showColorPicker(e,s,i)};var r=this._makeLabel(i[i.length-1],i);this._makeItem(i,r,s)}},{key:"_showColorPicker",value:function(t,e,i){var o=this,n=e.getBoundingClientRect(),s=document.body.getBoundingClientRect(),r=n.left+n.width+5,a=n.top-s.top+.5*n.height;this.colorPicker.show(r,a),this.colorPicker.setColor(t),this.colorPicker.setCallback(function(t){var n="rgba("+t.r+","+t.g+","+t.b+","+t.a+")";e.style.backgroundColor=n,o._update(n,i)})}},{key:"_handleObject",value:function(t){var e=void 0===arguments[1]?[]:arguments[1],i=void 0===arguments[2]?!1:arguments[2],o=!1,n=this.options.filter,s=!1;for(var r in t)if(t.hasOwnProperty(r)){o=!0;var a=t[r],d=h.copyAndExtendArray(e,r);if("function"==typeof n&&(o=n(r,e),o===!1&&!(a instanceof Array)&&"string"!=typeof a&&"boolean"!=typeof a&&a instanceof Object&&(this.allowCreation=!1,o=this._handleObject(a,d,!0),this.allowCreation=i===!1)),o!==!1){s=!0;var l=this._getValue(d);if(a instanceof Array)this._handleArray(a,l,d);else if("string"==typeof a)this._makeTextInput(a,l,d);else if("boolean"==typeof a)this._makeCheckbox(a,l,d);else if(a instanceof Object){var u=!0;if(-1!==e.indexOf("physics")&&this.moduleOptions.physics.solver!==r&&(u=!1),u===!0)if(void 0!==a.enabled){var c=h.copyAndExtendArray(d,"enabled"),p=this._getValue(c);if(p===!0){var f=this._makeLabel(r,d,!0);this._makeItem(d,f),s=this._handleObject(a,d)||s}else this._makeCheckbox(a,p,d)}else{var f=this._makeLabel(r,d,!0);this._makeItem(d,f),s=this._handleObject(a,d)||s}}else console.error("dont know how to handle",a,r,d)}}return s}},{key:"_handleArray",value:function(t,e,i){"string"==typeof t[0]&&"color"===t[0]?(this._makeColorField(t,e,i),t[1]!==e&&this.changedOptions.push({path:i,value:e})):"string"==typeof t[0]?(this._makeDropdown(t,e,i),t[0]!==e&&this.changedOptions.push({path:i,value:e})):"number"==typeof t[0]&&(this._makeRange(t,e,i),t[0]!==e&&this.changedOptions.push({path:i,value:Number(e)}))}},{key:"_update",value:function(t,e){var i=this._constructOptions(t,e);this.parent.setOptions(i)}},{key:"_constructOptions",value:function(t,e){var i=void 0===arguments[2]?{}:arguments[2],o=i;t="true"===t?!0:t,t="false"===t?!1:t;for(var n=0;nvar options = "+JSON.stringify(t,null,2)+""}}]),t}();e["default"]=d,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;is;s++)for(r=0;rp?p+1:p;var f=l/this.r,m=a.RGBToHSV(this.color.r,this.color.g,this.color.b);m.h=p,m.s=f;var v=a.HSVToRGB(m.h,m.s,m.v);v.a=this.color.a,this.color=v,this.initialColorDiv.style.backgroundColor="rgba("+this.initialColor.r+","+this.initialColor.g+","+this.initialColor.b+","+this.initialColor.a+")",this.newColorDiv.style.backgroundColor="rgba("+this.color.r+","+this.color.g+","+this.color.b+","+this.color.a+")"}}]),t}();e["default"]=h,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;is.distance?console.log('%cUnknown option detected: "'+e+'" in '+t.printLocation(n.path,e,"")+"Perhaps it was misplaced? Matching option found at: "+t.printLocation(s.path,s.closestMatch,""),h):n.distance<=d?console.log('%cUnknown option detected: "'+e+'". Did you mean "'+n.closestMatch+'"?'+t.printLocation(n.path,e),h):console.log('%cUnknown option detected: "'+e+'". Did you mean one of these: '+t.print(Object.keys(i))+t.printLocation(o,e),h),r=!0}},{key:"findInOptions",value:function(e,i,o){var n=void 0===arguments[3]?!1:arguments[3],r=1e9,a="",h=[],d=e.toLowerCase(),l=void 0;for(var u in i){var c=void 0;if(void 0!==i[u].__type__&&n===!0){var p=t.findInOptions(e,i[u],s.copyAndExtendArray(o,u));r>p.distance&&(a=p.closestMatch,h=p.path,r=p.distance,l=p.indexMatch)}else-1!==u.toLowerCase().indexOf(d)&&(l=u),c=t.levenshteinDistance(e,u),r>c&&(a=u,h=s.copyArray(o),r=c)}return{closestMatch:a,path:h,distance:r,indexMatch:l}}},{key:"printLocation",value:function(t,e){for(var i=void 0===arguments[2]?"Problem value found at: \n":arguments[2],o="\n\n"+i+"options = {\n",n=0;ns;s++)o+=" ";o+=t[n]+": {\n"}for(var s=0;sr?r:t,e=null==e?r:r>e?r:e}return{min:null!=t?new Date(t):null,max:null!=e?new Date(e):null}},o.prototype.getEventProperties=function(t){var e=t.center?t.center.x:t.clientX,i=t.center?t.center.y:t.clientY,o=e-n.getAbsoluteLeft(this.dom.centerContainer),s=i-n.getAbsoluteTop(this.dom.centerContainer),r=this._toTime(o),a=u.customTimeFromTarget(t),h=n.getTarget(t),d=null;n.hasParent(h,this.timeAxis.dom.foreground)?d="axis":this.timeAxis2&&n.hasParent(h,this.timeAxis2.dom.foreground)?d="axis":n.hasParent(h,this.linegraph.yAxisLeft.dom.frame)?d="data-axis":n.hasParent(h,this.linegraph.yAxisRight.dom.frame)?d="data-axis":n.hasParent(h,this.linegraph.legendLeft.dom.frame)?d="legend":n.hasParent(h,this.linegraph.legendRight.dom.frame)?d="legend":null!=a?d="custom-time":n.hasParent(h,this.currentTime.bar)?d="current-time":n.hasParent(h,this.dom.center)&&(d="background");var l=[],c=this.linegraph.yAxisLeft,p=this.linegraph.yAxisRight;return c.hidden||l.push(c.screenToValue(s)),p.hidden||l.push(p.screenToValue(s)),{event:t,what:d,pageX:t.srcEvent?t.srcEvent.pageX:t.pageX,pageY:t.srcEvent?t.srcEvent.pageY:t.pageY,x:o,y:s,time:r,value:l}},t.exports=o},function(t,e,i){function o(t,e){this.id=n.randomUUID(),this.body=t,this.defaultOptions={yAxisOrientation:"left",defaultGroup:"default",sort:!0,sampling:!0,stack:!1,graphHeight:"400px",shaded:{enabled:!1,orientation:"bottom"},style:"line",barChart:{width:50,sideBySide:!1,align:"center"},interpolation:{enabled:!0,parametrization:"centripetal",alpha:.5},drawPoints:{enabled:!0,size:6,style:"square"},dataAxis:{showMinorLabels:!0,showMajorLabels:!0,icons:!1,width:"40px",visible:!0,alignZeros:!0,left:{range:{min:void 0,max:void 0},format:function(t){return t},title:{text:void 0,style:void 0}},right:{range:{min:void 0,max:void 0},format:function(t){return t},title:{text:void 0,style:void 0}}},legend:{enabled:!1,icons:!0,left:{visible:!0,position:"top-left"},right:{visible:!0,position:"top-right"}},groups:{visibility:{}}},this.options=n.extend({},this.defaultOptions),this.dom={},this.props={},this.hammer=null,this.groups={},this.abortedGraphUpdate=!1,this.updateSVGheight=!1,this.updateSVGheightOnResize=!1;var i=this;this.itemsData=null,this.groupsData=null,this.itemListeners={add:function(t,e,o){i._onAdd(e.items)},update:function(t,e,o){i._onUpdate(e.items)},remove:function(t,e,o){i._onRemove(e.items)}},this.groupListeners={add:function(t,e,o){i._onAddGroups(e.items)},update:function(t,e,o){i._onUpdateGroups(e.items)},remove:function(t,e,o){i._onRemoveGroups(e.items)}},this.items={},this.selection=[],this.lastStart=this.body.range.start,this.touchParams={},this.svgElements={},this.setOptions(e),this.groupsUsingDefaultStyles=[0],this.COUNTER=0,this.body.emitter.on("rangechanged",function(){i.lastStart=i.body.range.start,i.svg.style.left=n.option.asSize(-i.props.width),i.redraw.call(i,!0)}),this._create(),this.framework={svg:this.svg,svgElements:this.svgElements,options:this.options,groups:this.groups},this.body.emitter.emit("change")}var n=i(7),s=i(13),r=i(14),a=i(16),h=i(27),d=i(51),l=i(53),u=i(57),c=i(56),p=i(54),f="__ungrouped__";o.prototype=new h,o.prototype._create=function(){var t=document.createElement("div");t.className="vis-line-graph",this.dom.frame=t,this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.style.position="relative",this.svg.style.height=(""+this.options.graphHeight).replace("px","")+"px",this.svg.style.display="block",t.appendChild(this.svg),this.options.dataAxis.orientation="left",this.yAxisLeft=new d(this.body,this.options.dataAxis,this.svg,this.options.groups),this.options.dataAxis.orientation="right",this.yAxisRight=new d(this.body,this.options.dataAxis,this.svg,this.options.groups),delete this.options.dataAxis.orientation,this.legendLeft=new u(this.body,this.options.legend,"left",this.options.groups),this.legendRight=new u(this.body,this.options.legend,"right",this.options.groups),this.show()},o.prototype.setOptions=function(t){if(t){var e=["sampling","defaultGroup","stack","height","graphHeight","yAxisOrientation","style","barChart","dataAxis","sort","groups"];void 0===t.graphHeight&&void 0!==t.height&&void 0!==this.body.domProps.centerContainer.height?(this.updateSVGheight=!0,this.updateSVGheightOnResize=!0):void 0!==this.body.domProps.centerContainer.height&&void 0!==t.graphHeight&&parseInt((t.graphHeight+"").replace("px",""))0){var d=this.body.util.toGlobalTime(-this.body.domProps.root.width),l=this.body.util.toGlobalTime(2*this.body.domProps.root.width),u={};for(this._getRelevantData(a,u,d,l),this._applySampling(a,u),e=0;ep&&console.log("WARNING: there may be an infinite loop in the _updateGraph emitter cycle."),this.COUNTER=0,this.abortedGraphUpdate=!1,e=0;e0)for(r=0;ro){d.push(h);break}d.push(h)}}else for(a=0;ai&&h.x0)for(var o=0;o0){var s=1,r=n.length,a=this.body.util.toGlobalScreen(n[n.length-1].x)-this.body.util.toGlobalScreen(n[0].x),h=r/a;s=Math.min(Math.ceil(.2*r),Math.max(1,Math.round(h)));for(var d=[],l=0;r>l;l+=s)d.push(n[l]);e[t[o]]=d}}},o.prototype._getYRanges=function(t,e,i){var o,n,s,r,a=[],h=[];if(t.length>0){for(s=0;s0&&(n=this.groups[t[s]],r.stack===!0?"left"==r.yAxisOrientation?a=a.concat(n.getData(o)):h=h.concat(n.getData(o)):i[t[s]]=n.getYRange(o,t[s]));c.getStackedYRange(a,i,t,"__barStackLeft","left"),c.getStackedYRange(h,i,t,"__barStackRight","right"),p.getStackedYRange(a,i,t,"__lineStackLeft","left"),p.getStackedYRange(h,i,t,"__lineStackRight","right")}},o.prototype._updateYAxis=function(t,e){var i,o,n=!1,s=!1,r=!1,a=1e9,h=1e9,d=-1e9,l=-1e9;if(t.length>0){for(var u=0;ui?i:a,d=o>d?o:d):(r=!0,h=h>i?i:h,l=o>l?o:l));1==s&&this.yAxisLeft.setRange(a,d),1==r&&this.yAxisRight.setRange(h,l)}n=this._toggleAxisVisiblity(s,this.yAxisLeft)||n,n=this._toggleAxisVisiblity(r,this.yAxisRight)||n,1==r&&1==s?(this.yAxisLeft.drawIcons=!0,this.yAxisRight.drawIcons=!0):(this.yAxisLeft.drawIcons=!1,this.yAxisRight.drawIcons=!1),this.yAxisRight.master=!s,0==this.yAxisRight.master?(1==r?this.yAxisLeft.lineOffset=this.yAxisRight.width:this.yAxisLeft.lineOffset=0,n=this.yAxisLeft.redraw()||n,this.yAxisRight.stepPixels=this.yAxisLeft.stepPixels,this.yAxisRight.zeroCrossing=this.yAxisLeft.zeroCrossing,this.yAxisRight.amountOfSteps=this.yAxisLeft.amountOfSteps,n=this.yAxisRight.redraw()||n):n=this.yAxisRight.redraw()||n;for(var p=["__barStackLeft","__barStackRight","__lineStackLeft","__lineStackRight"],u=0;ut?-1:1});for(var a=0;a0&&(t=0),this.range.start=t,this.range.end=e},o.prototype.redraw=function(){var t=!1,e=0;this.dom.lineContainer.style.top=this.body.domProps.scrollTop+"px";for(var i in this.groups)this.groups.hasOwnProperty(i)&&(this.groups[i].visible!==!0||void 0!==this.linegraphOptions.visibility[i]&&this.linegraphOptions.visibility[i]!==!0||e++);if(0===this.amountOfGroups||0===e)this.hide();else{this.show(),this.height=Number(this.linegraphSVG.style.height.replace("px","")),this.dom.lineContainer.style.height=this.height+"px",this.width=this.options.visible===!0?Number((""+this.options.width).replace("px","")):0;var o=this.props,n=this.dom.frame;n.className="vis-data-axis",this._calculateCharSize();var s=this.options.orientation,r=this.options.showMinorLabels,a=this.options.showMajorLabels;o.minorLabelHeight=r?o.minorCharHeight:0,o.majorLabelHeight=a?o.majorCharHeight:0,o.minorLineWidth=this.body.dom.backgroundHorizontal.offsetWidth-this.lineOffset-this.width+2*this.options.minorLinesOffset,o.minorLineHeight=1,o.majorLineWidth=this.body.dom.backgroundHorizontal.offsetWidth-this.lineOffset-this.width+2*this.options.majorLinesOffset,o.majorLineHeight=1,"left"===s?(n.style.top="0",n.style.left="0",n.style.bottom="",n.style.width=this.width+"px",n.style.height=this.height+"px",this.props.width=this.body.domProps.left.width,this.props.height=this.body.domProps.left.height):(n.style.top="",n.style.bottom="0",n.style.left="0",n.style.width=this.width+"px",n.style.height=this.height+"px",this.props.width=this.body.domProps.right.width,this.props.height=this.body.domProps.right.height),t=this._redrawLabels(),t=this._isResized()||t,this.options.icons===!0?this._redrawGroupIcons():this._cleanupIcons(),this._redrawTitle(s)}return t},o.prototype._redrawLabels=function(){var t=!1;s.prepareElements(this.DOMelements.lines),s.prepareElements(this.DOMelements.labels);var e,i=this.options.orientation;if(this.master===!1){var o,n,r,h;-1!==this.zeroCrossing&&this.options.alignZeros===!0?this.range.end>0?(o=this.range.end/this.zeroCrossing,n=this.range.end-this.amountOfSteps*o,r=this.range.end):(o=-1*this.range.start/(this.amountOfSteps-this.zeroCrossing),n=this.range.start,r=this.range.start+o*this.amountOfSteps):(n=this.range.start,r=this.range.end),h=this.stepPixels}else h=this.props.majorCharHeight,n=this.range.start,r=this.range.end;if(this.step=e=new a(n,r,h,this.dom.frame.offsetHeight,this.options[this.options.orientation].range,this.options[this.options.orientation].format,this.master===!1&&this.options.alignZeros),this.master===!0)this.stepPixels=this.dom.frame.offsetHeight/e.marginRange*e.step,this.amountOfSteps=Math.ceil(this.dom.frame.offsetHeight/this.stepPixels);else if(this.options.alignZeros===!0&&-1!==this.zeroCrossing){var d=(e.current-this.zeroCrossing*e.step)/e.step;this.step.shift(d)}this.valueAtBottom=e.marginEnd,this.maxLabelSize=0;for(var l=0,u=0,c=!1;u0&&u!==this.amountOfSteps&&((this.options.showMinorLabels&&c===!1||this.master===!1&&this.options.showMinorLabels===!0)&&this._redrawLabel(l-2,e.getCurrent(),i,"vis-y-axis vis-minor",this.props.minorCharHeight),c&&this.options.showMajorLabels&&this.master===!0||this.options.showMinorLabels===!1&&this.master===!1&&c===!0?(l>=0&&this._redrawLabel(l-2,e.getCurrent(),i,"vis-y-axis vis-major",this.props.majorCharHeight),this._redrawLine(l,i,"vis-grid vis-horizontal vis-major",this.options.majorLinesOffset,this.props.majorLineWidth)):this._redrawLine(l,i,"vis-grid vis-horizontal vis-minor",this.options.minorLinesOffset,this.props.minorLineWidth)),this.master===!0&&0===e.current&&(this.zeroCrossing=u),e.next(),u+=1;this.master===!0&&0===e.current&&(this.zeroCrossing=u),this.conversionFactor=this.stepPixels/e.step;var p=0;void 0!==this.options[i].title&&void 0!==this.options[i].title.text&&(p=this.props.titleCharHeight);var f=this.options.icons===!0?Math.max(this.options.iconWidth,p)+this.options.labelOffsetX+15:p+this.options.labelOffsetX+15;return this.maxLabelSize>this.width-f&&this.options.visible===!0?(this.width=this.maxLabelSize+f,this.options.width=this.width+"px",s.cleanupElements(this.DOMelements.lines),s.cleanupElements(this.DOMelements.labels),this.redraw(),t=!0):this.maxLabelSizethis.minWidth?(this.width=Math.max(this.minWidth,this.maxLabelSize+f),this.options.width=this.width+"px",s.cleanupElements(this.DOMelements.lines),s.cleanupElements(this.DOMelements.labels),this.redraw(),t=!0):(s.cleanupElements(this.DOMelements.lines),s.cleanupElements(this.DOMelements.labels),t=!1),t},o.prototype.convertValue=function(t){var e=this.valueAtBottom-t,i=e*this.conversionFactor;return i},o.prototype.screenToValue=function(t){return this.valueAtBottom-t/this.conversionFactor},o.prototype._redrawLabel=function(t,e,i,o,n){var r=s.getDOMElement("div",this.DOMelements.labels,this.dom.frame);r.className=o,r.innerHTML=e,"left"===i?(r.style.left="-"+this.options.labelOffsetX+"px",r.style.textAlign="right"):(r.style.right="-"+this.options.labelOffsetX+"px",r.style.textAlign="left"),r.style.top=t-.5*n+this.options.labelOffsetY+"px",e+="";var a=Math.max(this.props.majorCharWidth,this.props.minorCharWidth);this.maxLabelSizes&&(h=s);for(var d=!1,l=h;Math.abs(l)<=Math.abs(s);l++){a=Math.pow(10,l);for(var u=0;u=n){d=!0,r=u;break}}if(d===!0)break}this.stepIndex=r,this.scale=a,this.step=a*this.minorSteps[r]},o.prototype.setFirst=function(t){void 0===t&&(t={});var e=void 0===t.min?this._start-2*this.scale*this.minorSteps[this.stepIndex]:t.min,i=void 0===t.max?this._end+this.scale*this.minorSteps[this.stepIndex]:t.max;this.marginEnd=void 0===t.max?this.roundToMinor(i):t.max,this.marginStart=void 0===t.min?this.roundToMinor(e):t.min,this.alignZeros===!0&&(this.marginEnd-this.marginStart)%this.step!=0&&(this.marginEnd+=this.marginEnd%this.step),this.deadSpace=this.roundToMinor(i)-i+this.roundToMinor(e)-e,this.marginRange=this.marginEnd-this.marginStart,this.current=this.marginEnd},o.prototype.roundToMinor=function(t){var e=t-t%(this.scale*this.minorSteps[this.stepIndex]);return t%(this.scale*this.minorSteps[this.stepIndex])>.5*this.scale*this.minorSteps[this.stepIndex]?e+this.scale*this.minorSteps[this.stepIndex]:e},o.prototype.hasNext=function(){return this.current>=this.marginStart},o.prototype.next=function(){var t=this.current;this.current-=this.step,this.current===t&&(this.current=this._end)},o.prototype.previous=function(){this.current+=this.step,this.marginEnd+=this.step,this.marginRange=this.marginEnd-this.marginStart},o.prototype.getCurrent=function(){var t=Math.abs(this.current)t)for(var e=0;-t>e;e++)this.previous();else if(t>0)for(var e=0;t>e;e++)this.next()},t.exports=o},function(t,e,i){function o(t,e,i,o){this.id=e;var s=["sampling","style","sort","yAxisOrientation","barChart","drawPoints","shaded","interpolation"];this.options=n.selectiveBridgeObject(s,i),this.usingDefaultStyle=void 0===t.className,this.groupsUsingDefaultStyles=o,this.zeroPosition=0,this.update(t),1==this.usingDefaultStyle&&(this.groupsUsingDefaultStyles[0]+=1),this.itemsData=[],this.visible=void 0===t.visible?!0:t.visible}var n=i(7),s=i(13),r=i(54),a=i(56),h=i(55);o.prototype.setItems=function(t){null!=t?(this.itemsData=t,1==this.options.sort&&this.itemsData.sort(function(t,e){return t.x-e.x})):this.itemsData=[]},o.prototype.setZeroPosition=function(t){this.zeroPosition=t},o.prototype.setOptions=function(t){if(void 0!==t){var e=["sampling","style","sort","yAxisOrientation","barChart"];n.selectiveDeepExtend(e,this.options,t),n.mergeOptions(this.options,t,"interpolation"),n.mergeOptions(this.options,t,"drawPoints"),n.mergeOptions(this.options,t,"shaded"),t.interpolation&&"object"==typeof t.interpolation&&t.interpolation.parametrization&&("uniform"==t.interpolation.parametrization?this.options.interpolation.alpha=0:"chordal"==t.interpolation.parametrization?this.options.interpolation.alpha=1:(this.options.interpolation.parametrization="centripetal",this.options.interpolation.alpha=.5))}"line"==this.options.style?this.type=new r(this.id,this.options):"bar"==this.options.style?this.type=new a(this.id,this.options):"points"==this.options.style&&(this.type=new h(this.id,this.options))},o.prototype.update=function(t){this.group=t,this.content=t.content||"graph",this.className=t.className||this.className||"vis-graph-group"+this.groupsUsingDefaultStyles[0]%10,this.visible=void 0===t.visible?!0:t.visible,this.style=t.style,this.setOptions(t.options)},o.prototype.drawIcon=function(t,e,i,o,n,r){var a,h,d=.5*r,l=s.getSVGElement("rect",i,o);if(l.setAttributeNS(null,"x",t),l.setAttributeNS(null,"y",e-d),l.setAttributeNS(null,"width",n),l.setAttributeNS(null,"height",2*d),l.setAttributeNS(null,"class","vis-outline"),"line"==this.options.style)a=s.getSVGElement("path",i,o),a.setAttributeNS(null,"class",this.className),void 0!==this.style&&a.setAttributeNS(null,"style",this.style),a.setAttributeNS(null,"d","M"+t+","+e+" L"+(t+n)+","+e),1==this.options.shaded.enabled&&(h=s.getSVGElement("path",i,o),"top"==this.options.shaded.orientation?h.setAttributeNS(null,"d","M"+t+", "+(e-d)+"L"+t+","+e+" L"+(t+n)+","+e+" L"+(t+n)+","+(e-d)):h.setAttributeNS(null,"d","M"+t+","+e+" L"+t+","+(e+d)+" L"+(t+n)+","+(e+d)+"L"+(t+n)+","+e),h.setAttributeNS(null,"class",this.className+" vis-icon-fill")),1==this.options.drawPoints.enabled&&s.drawPoint(t+.5*n,e,this,i,o);else{var u=Math.round(.3*n),c=Math.round(.4*r),p=Math.round(.75*r),f=Math.round((n-2*u)/3);s.drawBar(t+.5*u+f,e+d-c-1,u,c,this.className+" vis-bar",i,o,this.style),s.drawBar(t+1.5*u+f+2,e+d-p-1,u,p,this.className+" vis-bar",i,o,this.style)}},o.prototype.getLegend=function(t,e){var i=document.createElementNS("http://www.w3.org/2000/svg","svg");return this.drawIcon(0,.5*e,[],i,t,e),{icon:i,label:this.content,orientation:this.options.yAxisOrientation}},o.prototype.getYRange=function(t){return this.type.getYRange(t)},o.prototype.getData=function(t){return this.type.getData(t)},o.prototype.draw=function(t,e,i){this.type.draw(t,e,i)},t.exports=o},function(t,e,i){function o(t,e){this.groupId=t,this.options=e}var n=i(13),s=i(55);o.prototype.getData=function(t){for(var e=[],i=0;it[o].y?t[o].y:e,i=i0){t.sort(function(t,e){return t.x===e.x?t.groupIde[s].y?e[s].y:o,n=nt[r].accumulatedNegative?t[r].accumulatedNegative:o,o=o>t[r].accumulatedPositive?t[r].accumulatedPositive:o,n=n0&&(i=Math.min(i,Math.abs(e[o-1].x-e[o].x))),0===i&&(void 0===t[e[o].x]&&(t[e[o].x]={amount:0,resolved:0,accumulatedPositive:0,accumulatedNegative:0}),t[e[o].x].amount+=1)},o.prototype.draw=function(t,e,i){if(null!=t&&t.length>0){var r,a,h=Number(i.svg.style.height.replace("px",""));if(r=n.getSVGElement("path",i.svgElements,i.svg),r.setAttributeNS(null,"class",e.className),void 0!==e.style&&r.setAttributeNS(null,"style",e.style),a=1==e.options.interpolation.enabled?o._catmullRom(t,e):o._linear(t),1==e.options.shaded.enabled){var d,l=n.getSVGElement("path",i.svgElements,i.svg);d="top"==e.options.shaded.orientation?"M"+t[0].x+",0 "+a+"L"+t[t.length-1].x+",0":"M"+t[0].x+","+h+" "+a+"L"+t[t.length-1].x+","+h,l.setAttributeNS(null,"class",e.className+" vis-fill"),void 0!==e.options.shaded.style&&l.setAttributeNS(null,"style",e.options.shaded.style),l.setAttributeNS(null,"d",d)}r.setAttributeNS(null,"d","M"+a),1==e.options.drawPoints.enabled&&s.draw(t,e,i)}},o._catmullRomUniform=function(t){for(var e,i,o,n,s,r,a=Math.round(t[0].x)+","+Math.round(t[0].y)+" ",h=1/6,d=t.length,l=0;d-1>l;l++)e=0==l?t[0]:t[l-1],i=t[l],o=t[l+1],n=d>l+2?t[l+2]:o,s={x:(-e.x+6*i.x+o.x)*h,y:(-e.y+6*i.y+o.y)*h},r={x:(i.x+6*o.x-n.x)*h,y:(i.y+6*o.y-n.y)*h},a+="C"+s.x+","+s.y+" "+r.x+","+r.y+" "+o.x+","+o.y+" ";return a},o._catmullRom=function(t,e){var i=e.options.interpolation.alpha;if(0==i||void 0===i)return this._catmullRomUniform(t);for(var o,n,s,r,a,h,d,l,u,c,p,f,m,v,g,y,b,w,_,x=Math.round(t[0].x)+","+Math.round(t[0].y)+" ",k=t.length,M=0;k-1>M;M++)o=0==M?t[0]:t[M-1],n=t[M],s=t[M+1],r=k>M+2?t[M+2]:s,d=Math.sqrt(Math.pow(o.x-n.x,2)+Math.pow(o.y-n.y,2)),l=Math.sqrt(Math.pow(n.x-s.x,2)+Math.pow(n.y-s.y,2)),u=Math.sqrt(Math.pow(s.x-r.x,2)+Math.pow(s.y-r.y,2)),v=Math.pow(u,i),y=Math.pow(u,2*i),g=Math.pow(l,i),b=Math.pow(l,2*i),_=Math.pow(d,i),w=Math.pow(d,2*i),c=2*w+3*_*g+b,p=2*y+3*v*g+b,f=3*_*(_+g),f>0&&(f=1/f),m=3*v*(v+g),m>0&&(m=1/m),a={x:(-b*o.x+c*n.x+w*s.x)*f,y:(-b*o.y+c*n.y+w*s.y)*f},h={x:(y*n.x+p*s.x-b*r.x)*m,y:(y*n.y+p*s.y-b*r.y)*m},0==a.x&&0==a.y&&(a=n),0==h.x&&0==h.y&&(h=s),x+="C"+a.x+","+a.y+" "+h.x+","+h.y+" "+s.x+","+s.y+" ";return x},o._linear=function(t){for(var e="",i=0;it[o].y?t[o].y:e,i=it[o].y?t[o].y:e,i=i0&&(r=Math.min(r,Math.abs(c[l-1].x-a))),h=o._getSafeDrawData(r,d,m);else{var g=l+(p[a].amount-p[a].resolved),y=l-(p[a].resolved+1);g0&&(r=Math.min(r,Math.abs(c[y].x-a))),h=o._getSafeDrawData(r,d,m),p[a].resolved+=1,d.options.stack===!0?c[l].y0&&(i=Math.min(i,Math.abs(e[o-1].x-e[o].x))),0===i&&(void 0===t[e[o].x]&&(t[e[o].x]={amount:0,resolved:0,accumulatedPositive:0,accumulatedNegative:0}),t[e[o].x].amount+=1)},o._getSafeDrawData=function(t,e,i){var o,n;return t0?(o=i>t?i:t,n=0,"left"===e.options.barChart.align?n-=.5*t:"right"===e.options.barChart.align&&(n+=.5*t)):(o=e.options.barChart.width,n=0,"left"===e.options.barChart.align?n-=.5*e.options.barChart.width:"right"===e.options.barChart.align&&(n+=.5*e.options.barChart.width)),{width:o,offset:n}},o.getStackedYRange=function(t,e,i,n,s){if(t.length>0){t.sort(function(t,e){return t.x===e.x?t.groupIde[s].y?e[s].y:o,n=nt[r].accumulatedNegative?t[r].accumulatedNegative:o,o=o>t[r].accumulatedPositive?t[r].accumulatedPositive:o,n=nt?-1:1});for(var i=0;i")}this.dom.textArea.innerHTML=s,this.dom.textArea.style.lineHeight=.75*this.options.iconSize+this.options.iconSpacing+"px"}},o.prototype.drawLegendIcons=function(){if(this.dom.frame.parentNode){var t=Object.keys(this.groups);t.sort(function(t,e){return e>t?-1:1}),s.prepareElements(this.svgElements);var e=window.getComputedStyle(this.dom.frame).paddingTop,i=Number(e.replace("px","")),o=i,n=this.options.iconSize,r=.75*this.options.iconSize,a=i+.5*r+3;this.svg.style.width=n+5+i+"px";for(var h=0;h0){var i=this.groupIndex%this.groupsArray.length;this.groupIndex++,e={},e.color=this.groups[this.groupsArray[i]],this.groups[t]=e}else{var i=this.defaultIndex%this.defaultGroups.length;this.defaultIndex++,e={},e.color=this.defaultGroups[i],this.groups[t]=e}return e}},{key:"add",value:function(t,e){return this.groups[t]=e,this.groupsArray.push(t),e}}]),t}();e["default"]=r,t.exports=e["default"]},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function t(t,e){for(var i=0;it.left&&this.shape.topt.top}},{key:"isBoundingBoxOverlappingWith",value:function(t){return this.shape.boundingBox.leftt.left&&this.shape.boundingBox.topt.top}}],[{key:"parseOptions",value:function(t,e){var i=void 0===arguments[2]?!1:arguments[2],o=["color","font","fixed","shadow"];if(B.selectiveNotDeepExtend(o,t,e,i),B.mergeOptions(t,e,"shadow"),void 0!==e.color&&null!==e.color){var n=B.parseColor(e.color);B.fillIfDefined(t.color,n)}else i===!0&&null===e.color&&(t.color=void 0,delete t.color);void 0!==e.fixed&&null!==e.fixed&&("boolean"==typeof e.fixed?(t.fixed.x=e.fixed,t.fixed.y=e.fixed):(void 0!==e.fixed.x&&"boolean"==typeof e.fixed.x&&(t.fixed.x=e.fixed.x),void 0!==e.fixed.y&&"boolean"==typeof e.fixed.y&&(t.fixed.y=e.fixed.y))),void 0!==e.font&&a["default"].parseOptions(t.font,e),void 0!==e.scaling&&B.mergeOptions(t.scaling,e.scaling,"label")}}]),t}();e["default"]=R,t.exports=e["default"]},function(t,e,i){function o(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t)){var i=[],o=!0,n=!1,s=void 0;try{for(var r,a=t[Symbol.iterator]();!(o=(r=a.next()).done)&&(i.push(r.value),!e||i.length!==e);o=!0);}catch(h){n=!0,s=h}finally{try{!o&&a["return"]&&a["return"]()}finally{if(n)throw s}}return i}throw new TypeError("Invalid attempt to destructure non-iterable instance")}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function t(t,e){for(var i=0;i=this.options.scaling.label.maxVisible&&(r=Number(this.options.scaling.label.maxVisible)/this.body.view.scale);var h=this.size.yLine,d=this._getColor(a),l=o(d,2),u=l[0],c=l[1],p=this._setAlignment(t,i,h,s),f=o(p,2);i=f[0],h=f[1],t.font=(e?"bold ":"")+r+"px "+this.options.font.face,t.fillStyle=u,t.textAlign="center",this.options.font.strokeWidth>0&&(t.lineWidth=this.options.font.strokeWidth,t.strokeStyle=c,t.lineJoin="round");for(var m=0;m0&&t.strokeText(this.lines[m],i,h),t.fillText(this.lines[m],i,h),h+=r}},{key:"_setAlignment",value:function(t,e,i,o){if("horizontal"!==this.options.font.align){e=0,i=0;var n=2;"top"===this.options.font.align?(t.textBaseline="alphabetic",i-=2*n):"bottom"===this.options.font.align?(t.textBaseline="hanging",i+=2*n):t.textBaseline="middle"}else t.textBaseline=o;return[e,i]}},{key:"_getColor",value:function(t){var e=this.options.font.color||"#000000",i=this.options.font.strokeColor||"#ffffff";if(t<=this.options.scaling.label.drawThreshold){var o=Math.max(0,Math.min(1,1-(this.options.scaling.label.drawThreshold-t)));e=r.overrideOpacity(e,o),i=r.overrideOpacity(i,o)}return[e,i]}},{key:"getTextSize",value:function(t){var e=void 0===arguments[1]?!1:arguments[1],i={width:this._processLabel(t,e),height:this.options.font.size*this.lineCount,lineCount:this.lineCount};return i}},{key:"calculateLabelSize",value:function(t,e){var i=void 0===arguments[2]?0:arguments[2],o=void 0===arguments[3]?0:arguments[3],n=void 0===arguments[4]?"middle":arguments[4];this.labelDirty===!0&&(this.size.width=this._processLabel(t,e)),this.size.height=this.options.font.size*this.lineCount,this.size.left=i-.5*this.size.width,this.size.top=o-.5*this.size.height,this.size.yLine=o+.5*(1-this.lineCount)*this.options.font.size,"hanging"===n&&(this.size.top+=.5*this.options.font.size,this.size.top+=4,this.size.yLine+=4),this.labelDirty=!1}},{key:"_processLabel",value:function(t,e){var i=0,o=[""],n=0;if(void 0!==this.options.label){o=String(this.options.label).split("\n"),n=o.length,t.font=(e?"bold ":"")+this.options.font.size+"px "+this.options.font.face,i=t.measureText(o[0]).width;for(var s=1;n>s;s++){var r=t.measureText(o[s]).width;i=r>i?r:i}}return this.lines=o,this.lineCount=n,i}}],[{key:"parseOptions",value:function(t,e){var i=void 0===arguments[2]?!1:arguments[2];if("string"==typeof e.font){var o=e.font.split(" ");t.size=o[0].replace("px",""),t.face=o[1],t.color=o[2]}else"object"==typeof e.font&&r.fillIfDefined(t,e.font,i);t.size=Number(t.size)}}]),t}();e["default"]=a,t.exports=e["default"]},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var i=0;ithis.imageObj.height?(o=this.imageObj.width/this.imageObj.height,e=2*this.options.size*o||this.imageObj.width,i=2*this.options.size||this.imageObj.height):(o=this.imageObj.width&&this.imageObj.height?this.imageObj.height/this.imageObj.width:1,e=2*this.options.size||this.imageObj.width,i=2*this.options.size*o||this.imageObj.height),this.width=e, +this.height=i,this.radius=.5*this.width}}},{key:"_drawRawCircle",value:function(t,e,i,o,n,s){var r=this.options.borderWidth,a=this.options.borderWidthSelected||2*this.options.borderWidth;t.strokeStyle=o?this.options.color.highlight.border:n?this.options.color.hover.border:this.options.color.border,t.lineWidth=o?a:r,t.lineWidth*=this.networkScaleInv,t.lineWidth=Math.min(this.width,t.lineWidth),t.fillStyle=o?this.options.color.highlight.background:n?this.options.color.hover.background:this.options.color.background,t.circle(e,i,s),this.enableShadow(t),t.fill(),this.disableShadow(t),t.stroke()}},{key:"_drawImageAtPosition",value:function(t){0!=this.imageObj.width&&(t.globalAlpha=1,this.enableShadow(t),t.drawImage(this.imageObj,this.left,this.top,this.width,this.height),this.disableShadow(t))}},{key:"_drawImageLabel",value:function(t,e,i,o){var n,s=0;if(void 0!==this.height){s=.5*this.height;var r=this.labelModule.getTextSize(t);r.lineCount>=1&&(s+=r.height/2)}n=i+s,this.options.label&&(this.labelOffset=s),this.labelModule.draw(t,e,n,o,"hanging")}}]),e}(d["default"]);e["default"]=l,t.exports=e["default"]},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var i=0;ii.shape.height?(r=i.x+.5*i.shape.width,a=i.y-h):(r=i.x+h,a=i.y-.5*i.shape.height),s=this._pointOnCircle(r,a,h,.125),this.labelModule.draw(t,s.x,s.y,n)}}}},{key:"isOverlappingWith",value:function(t){if(this.connected){var e=10,i=this.from.x,o=this.from.y,n=this.to.x,s=this.to.y,r=t.left,a=t.top,h=this.edgeType.getDistanceToEdge(i,o,n,s,r,a);return e>h}return!1}},{key:"_rotateForLabelAlignment",value:function(t){var e=this.from.y-this.to.y,i=this.from.x-this.to.x,o=Math.atan2(e,i);(-1>o&&0>i||o>0&&0>i)&&(o+=Math.PI),t.rotate(o)}},{key:"_pointOnCircle",value:function(t,e,i,o){var n=2*o*Math.PI;return{x:t+i*Math.cos(n),y:e-i*Math.sin(n)}}},{key:"select",value:function(){this.selected=!0}},{key:"unselect",value:function(){this.selected=!1}}],[{key:"parseOptions",value:function(t,e){var i=void 0===arguments[2]?!1:arguments[2],o=["id","from","hidden","hoverWidth","label","length","line","opacity","physics","selectionWidth","selfReferenceSize","to","title","value","width"];if(f.selectiveDeepExtend(o,t,e,i),f.mergeOptions(t,e,"smooth"),f.mergeOptions(t,e,"shadow"),void 0!==e.dashes&&null!==e.dashes?t.dashes=e.dashes:i===!0&&null===e.dashes&&(t.dashes=void 0,delete t.dashes),void 0!==e.scaling&&null!==e.scaling?(void 0!==e.scaling.min&&(t.scaling.min=e.scaling.min),void 0!==e.scaling.max&&(t.scaling.max=e.scaling.max),f.mergeOptions(t.scaling,e.scaling,"label")):i===!0&&null===e.scaling&&(t.scaling=void 0,delete t.scaling),void 0!==e.arrows&&null!==e.arrows)if("string"==typeof e.arrows){var n=e.arrows.toLowerCase();-1!=n.indexOf("to")&&(t.arrows.to.enabled=!0),-1!=n.indexOf("middle")&&(t.arrows.middle.enabled=!0),-1!=n.indexOf("from")&&(t.arrows.from.enabled=!0)}else{if("object"!=typeof e.arrows)throw new Error("The arrow newOptions can only be an object or a string. Refer to the documentation. You used:"+JSON.stringify(e.arrows));f.mergeOptions(t.arrows,e.arrows,"to"),f.mergeOptions(t.arrows,e.arrows,"middle"),f.mergeOptions(t.arrows,e.arrows,"from")}else i===!0&&null===e.arrows&&(t.arrows=void 0,delete t.arrows);if(void 0!==e.color&&null!==e.color)if(f.isString(e.color))t.color.color=e.color,t.color.highlight=e.color,t.color.hover=e.color,t.color.inherit=!1;else{var s=!1;void 0!==e.color.color&&(t.color.color=e.color.color,s=!0),void 0!==e.color.highlight&&(t.color.highlight=e.color.highlight,s=!0),void 0!==e.color.hover&&(t.color.hover=e.color.hover,s=!0),void 0!==e.color.inherit&&(t.color.inherit=e.color.inherit),void 0!==e.color.opacity&&(t.color.opacity=Math.min(1,Math.max(0,e.color.opacity))),void 0===e.color.inherit&&s===!0&&(t.color.inherit=!1)}else i===!0&&null===e.color&&(t.color=void 0,delete t.color);void 0!==e.font&&a["default"].parseOptions(t.font,e)}}]),t}();e["default"]=m,t.exports=e["default"]},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var i=0;i=l&&h>d;){var m=.5*(l+u);if(i=this.getPoint(m,a),o=Math.atan2(p.y-i.y,p.x-i.x),n=p.distanceToBorder(e,o),s=Math.sqrt(Math.pow(i.x-p.x,2)+Math.pow(i.y-p.y,2)),r=n-s,Math.abs(r)r?f===!1?l=m:u=m:f===!1?u=m:l=m,d++}return i.t=m,i}},{key:"_getDistanceToBezierEdge",value:function(t,e,i,o,n,s,r){var a=void 0,h=void 0;a=r.x,h=r.y;var d=1e9,l=void 0,u=void 0,c=void 0,p=void 0,f=void 0,m=t,v=e;for(u=1;10>u;u++)c=.1*u,p=Math.pow(1-c,2)*t+2*c*(1-c)*a+Math.pow(c,2)*i,f=Math.pow(1-c,2)*e+2*c*(1-c)*h+Math.pow(c,2)*o,u>0&&(l=this._getDistanceToLine(m,v,p,f,n,s),d=d>l?l:d),m=p,v=f;return d}}]),e}(d["default"]);e["default"]=l,t.exports=e["default"]},function(t,e,i){function o(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t)){var i=[],o=!0,n=!1,s=void 0;try{for(var r,a=t[Symbol.iterator]();!(o=(r=a.next()).done)&&(i.push(r.value),!e||i.length!==e);o=!0);}catch(h){n=!0,s=h}finally{try{!o&&a["return"]&&a["return"]()}finally{if(n)throw s}}return i}throw new TypeError("Invalid attempt to destructure non-iterable instance")}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function t(t,e){for(var i=0;io.shape.height?(e=o.x+.5*o.shape.width,i=o.y-n):(e=o.x+n,i=o.y-.5*o.shape.height),[e,i,n]}},{key:"_pointOnCircle",value:function(t,e,i,o){var n=2*o*Math.PI;return{x:t+i*Math.cos(n),y:e-i*Math.sin(n)}}},{key:"_findBorderPositionCircle",value:function(t,e,i){for(var o=i.x,n=i.y,s=i.low,r=i.high,a=i.direction,h=10,d=0,l=this.options.selfReferenceSize,u=void 0,c=void 0,p=void 0,f=void 0,m=void 0,v=.05,g=.5*(s+r);r>=s&&h>d&&(g=.5*(s+r),u=this._pointOnCircle(o,n,l,g),c=Math.atan2(t.y-u.y,t.x-u.x),p=t.distanceToBorder(e,c),f=Math.sqrt(Math.pow(u.x-t.x,2)+Math.pow(u.y-t.y,2)),m=p-f,!(Math.abs(m)0?a>0?s=g:r=g:a>0?r=g:s=g,d++;return u.t=g,u}},{key:"getLineWidth",value:function(t,e){return t===!0?Math.max(this.selectionWidth,.3/this.body.view.scale):e===!0?Math.max(this.hoverWidth,.3/this.body.view.scale):Math.max(this.options.width,.3/this.body.view.scale)}},{key:"getColor",value:function(t,e,i){var o=this.options.color;if(o.inherit!==!1){if("both"===o.inherit&&this.from.id!==this.to.id){var n=t.createLinearGradient(this.from.x,this.from.y,this.to.x,this.to.y),s=void 0,a=void 0;return s=this.from.options.color.highlight.border,a=this.to.options.color.highlight.border,this.from.selected===!1&&this.to.selected===!1?(s=r.overrideOpacity(this.from.options.color.border,this.options.color.opacity),a=r.overrideOpacity(this.to.options.color.border,this.options.color.opacity)):this.from.selected===!0&&this.to.selected===!1?a=this.to.options.color.border:this.from.selected===!1&&this.to.selected===!0&&(s=this.from.options.color.border),n.addColorStop(0,s),n.addColorStop(1,a),n}this.colorDirty===!0&&("to"===o.inherit?(this.color.highlight=this.to.options.color.highlight.border,this.color.hover=this.to.options.color.hover.border,this.color.color=r.overrideOpacity(this.to.options.color.border,o.opacity)):(this.color.highlight=this.from.options.color.highlight.border,this.color.hover=this.from.options.color.hover.border,this.color.color=r.overrideOpacity(this.from.options.color.border,o.opacity)))}else this.colorDirty===!0&&(this.color.highlight=o.highlight,this.color.hover=o.hover,this.color.color=r.overrideOpacity(o.color,o.opacity));return this.colorDirty=!1,e===!0?this.color.highlight:i===!0?this.color.hover:this.color.color}},{key:"_circle",value:function(t,e,i,o){this.enableShadow(t),t.beginPath(),t.arc(e,i,o,0,2*Math.PI,!1),t.stroke(),this.disableShadow(t)}},{key:"getDistanceToEdge",value:function(t,e,i,n,s,r,a){var h=0;if(this.from!=this.to)h=this._getDistanceToEdge(t,e,i,n,s,r,a);else{var d=this._getCircleData(),l=o(d,3),u=l[0],c=l[1],p=l[2],f=u-s,m=c-r;h=Math.abs(Math.sqrt(f*f+m*m)-p)}return this.labelModule.size.lefts&&this.labelModule.size.topr?0:h}},{key:"_getDistanceToLine",value:function(t,e,i,o,n,s){var r=i-t,a=o-e,h=r*r+a*a,d=((n-t)*r+(s-e)*a)/h;d>1?d=1:0>d&&(d=0);var l=t+d*r,u=e+d*a,c=l-n,p=u-s;return Math.sqrt(c*c+p*p)}},{key:"drawArrowHead",value:function(t,e,i,n,s){t.strokeStyle=this.getColor(t,n,s),t.fillStyle=t.strokeStyle,t.lineWidth=this.getLineWidth(n,s);var r=void 0,a=void 0,h=void 0,d=void 0,l=void 0,u=void 0,c=void 0;if("from"===e?(d=this.from,l=this.to,u=.1,c=this.options.arrows.from.scaleFactor):"to"===e?(d=this.to,l=this.from,u=-.1,c=this.options.arrows.to.scaleFactor):(d=this.to,l=this.from,c=this.options.arrows.middle.scaleFactor),d!=l){if("middle"!==e)if(this.options.smooth.enabled===!0){h=this.findBorderPosition(d,t,{via:i});var p=this.getPoint(Math.max(0,Math.min(1,h.t+u)),i);r=Math.atan2(h.y-p.y,h.x-p.x)}else r=Math.atan2(d.y-l.y,d.x-l.x),h=this.findBorderPosition(d,t);else r=Math.atan2(d.y-l.y,d.x-l.x),h=this.getPoint(.6,i);a=(10+5*this.options.width)*c,t.arrow(h.x,h.y,r,a),this.enableShadow(t),t.fill(),this.disableShadow(t),t.stroke()}else{var f=void 0,m=void 0,v=this._getCircleData(t),g=o(v,3),y=g[0],b=g[1],w=g[2];"from"===e?(m=this.findBorderPosition(this.from,t,{x:y,y:b,low:.25,high:.6,direction:-1}),f=-2*m.t*Math.PI+1.5*Math.PI+.1*Math.PI):"to"===e?(m=this.findBorderPosition(this.from,t,{x:y,y:b,low:.6,high:1,direction:1}),f=-2*m.t*Math.PI+1.5*Math.PI-1.1*Math.PI):(m=this._pointOnCircle(y,b,w,.175),f=3.9269908169872414);var _=(10+5*this.options.width)*c;t.arrow(m.x,m.y,f,_),this.enableShadow(t),t.fill(),this.disableShadow(t),t.stroke()}}},{key:"enableShadow",value:function(t){this.options.shadow.enabled===!0&&(t.shadowColor="rgba(0,0,0,0.5)",t.shadowBlur=this.options.shadow.size,t.shadowOffsetX=this.options.shadow.x,t.shadowOffsetY=this.options.shadow.y)}},{key:"disableShadow",value:function(t){this.options.shadow.enabled===!0&&(t.shadowColor="rgba(0,0,0,0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0)}}]),t}();e["default"]=a,t.exports=e["default"]},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var i=0;ithis.to.y?this.from.xthis.to.x&&(t=this.from.x-i*s,e=this.from.y-i*s):this.from.ythis.to.x&&(t=this.from.x-i*s,e=this.from.y+i*s)),"discrete"===o&&(t=i*s>n?this.from.x:t)):Math.abs(this.from.x-this.to.x)>Math.abs(this.from.y-this.to.y)&&(this.from.y>this.to.y?this.from.xthis.to.x&&(t=this.from.x-i*n,e=this.from.y-i*n):this.from.ythis.to.x&&(t=this.from.x-i*n,e=this.from.y+i*n)),"discrete"===o&&(e=i*n>s?this.from.y:e));else if("straightCross"===o)Math.abs(this.from.x-this.to.x)Math.abs(this.from.y-this.to.y)&&(t=this.from.xthis.to.y?this.from.xthis.to.x&&(t=this.from.x-i*s,e=this.from.y-i*s,t=this.to.x>t?this.to.x:t):this.from.ythis.to.x&&(t=this.from.x-i*s,e=this.from.y+i*s,t=this.to.x>t?this.to.x:t)):Math.abs(this.from.x-this.to.x)>Math.abs(this.from.y-this.to.y)&&(this.from.y>this.to.y?this.from.xe?this.to.y:e):this.from.x>this.to.x&&(t=this.from.x-i*n,e=this.from.y-i*n,e=this.to.y>e?this.to.y:e):this.from.ythis.to.x&&(t=this.from.x-i*n,e=this.from.y+i*n,e=this.to.y1&&(this.startedStabilization=!1),this.stopSimulation())}},{key:"_emitStabilized",value:function(){var t=this;this.stabilizationIterations>1&&setTimeout(function(){t.body.emitter.emit("stabilized",{iterations:t.stabilizationIterations}),t.stabilizationIterations=0},0)}},{key:"physicsTick",value:function(){this.stabilized===!1&&(this.calculateForces(),this.stabilized=this.moveNodes(),this.stabilized===!0?this.revert():this.startedStabilization===!1&&(this.body.emitter.emit("startStabilizing"),this.startedStabilization=!0),this.stabilizationIterations++)}},{key:"updatePhysicsData",value:function(){this.physicsBody.forces={},this.physicsBody.physicsNodeIndices=[],this.physicsBody.physicsEdgeIndices=[];var t=this.body.nodes,e=this.body.edges;for(var i in t)t.hasOwnProperty(i)&&t[i].options.physics===!0&&this.physicsBody.physicsNodeIndices.push(i);for(var o in e)e.hasOwnProperty(o)&&e[o].options.physics===!0&&this.physicsBody.physicsEdgeIndices.push(o);for(var n=0;na&&o===!0,t=!0}return t===!0?n>.5*this.options.maxVelocity?!1:o:!0}},{key:"_performStep",value:function(t,e){var i=this.body.nodes[t],o=this.options.timestep,n=this.physicsBody.forces,s=this.physicsBody.velocities;if(this.previousStates[t]={x:i.x,y:i.y,vx:s[t].x,vy:s[t].y},i.options.fixed.x===!1){var r=this.modelOptions.damping*s[t].x,a=(n[t].x-r)/i.options.mass;s[t].x+=a*o,s[t].x=Math.abs(s[t].x)>e?s[t].x>0?e:-e:s[t].x,i.x+=s[t].x*o}else n[t].x=0,s[t].x=0;if(i.options.fixed.y===!1){var h=this.modelOptions.damping*s[t].y,d=(n[t].y-h)/i.options.mass;s[t].y+=d*o,s[t].y=Math.abs(s[t].y)>e?s[t].y>0?e:-e:s[t].y,i.y+=s[t].y*o}else n[t].y=0,s[t].y=0;var l=Math.sqrt(Math.pow(s[t].x,2)+Math.pow(s[t].y,2));return l}},{key:"calculateForces",value:function(){this.gravitySolver.solve(),this.nodesSolver.solve(),this.edgesSolver.solve()}},{key:"_freezeNodes",value:function(){var t=this.body.nodes;for(var e in t)t.hasOwnProperty(e)&&t[e].x&&t[e].y&&(this.freezeCache[e]={x:t[e].options.fixed.x,y:t[e].options.fixed.y},t[e].options.fixed.x=!0,t[e].options.fixed.y=!0)}},{key:"_restoreFrozenNodes",value:function(){var t=this.body.nodes;for(var e in t)t.hasOwnProperty(e)&&void 0!==this.freezeCache[e]&&(t[e].options.fixed.x=this.freezeCache[e].x,t[e].options.fixed.y=this.freezeCache[e].y);this.freezeCache={}}},{key:"stabilize",value:function(){var t=this,e=void 0===arguments[0]?this.options.stabilization.iterations:arguments[0];"number"!=typeof e&&(console.log("The stabilize method needs a numeric amount of iterations. Switching to default: ",this.options.stabilization.iterations),e=this.options.stabilization.iterations),this.body.emitter.emit("_resizeNodes"),this.stopSimulation(),this.stabilized=!1,this.body.emitter.emit("_blockRedrawRequests"),this.targetIterations=e,this.options.stabilization.onlyDynamicEdges===!0&&this._freezeNodes(),this.stabilizationIterations=0,setTimeout(function(){return t._stabilizationBatch()},0)}},{key:"_stabilizationBatch",value:function(){for(var t=0;this.stabilized===!1&&t0){var t=void 0,e=this.body.nodes,i=this.physicsBody.physicsNodeIndices,o=i.length,n=this._formBarnesHutTree(e,i);this.barnesHutTree=n;for(var s=0;o>s;s++)t=e[i[s]],t.options.mass>0&&(this._getForceContribution(n.root.children.NW,t),this._getForceContribution(n.root.children.NE,t),this._getForceContribution(n.root.children.SW,t),this._getForceContribution(n.root.children.SE,t))}}},{key:"_getForceContribution",value:function(t,e){if(t.childrenCount>0){var i=void 0,o=void 0,n=void 0;i=t.centerOfMass.x-e.x,o=t.centerOfMass.y-e.y,n=Math.sqrt(i*i+o*o),n*t.calcSize>this.thetaInversed?this._calculateForces(n,i,o,e,t):4===t.childrenCount?(this._getForceContribution(t.children.NW,e),this._getForceContribution(t.children.NE,e),this._getForceContribution(t.children.SW,e),this._getForceContribution(t.children.SE,e)):t.children.data.id!=e.id&&this._calculateForces(n,i,o,e,t)}}},{key:"_calculateForces",value:function(t,e,i,o,n){0===t&&(t=.1,e=t),this.overlapAvoidanceFactor<1&&(t=Math.max(.1+this.overlapAvoidanceFactor*o.shape.radius,t-o.shape.radius));var s=this.options.gravitationalConstant*n.mass*o.options.mass/Math.pow(t,3),r=e*s,a=i*s;this.physicsBody.forces[o.id].x+=r,this.physicsBody.forces[o.id].y+=a}},{key:"_formBarnesHutTree",value:function(t,e){for(var i=void 0,o=e.length,n=t[e[0]].x,s=t[e[0]].y,r=t[e[0]].x,a=t[e[0]].y,h=1;o>h;h++){var d=t[e[h]].x,l=t[e[h]].y;t[e[h]].options.mass>0&&(n>d&&(n=d),d>r&&(r=d),s>l&&(s=l),l>a&&(a=l))}var u=Math.abs(r-n)-Math.abs(a-s);u>0?(s-=.5*u,a+=.5*u):(n+=.5*u,r-=.5*u);var c=1e-5,p=Math.max(c,Math.abs(r-n)),f=.5*p,m=.5*(n+r),v=.5*(s+a),g={root:{centerOfMass:{x:0,y:0},mass:0,range:{minX:m-f,maxX:m+f,minY:v-f,maxY:v+f},size:p,calcSize:1/p,children:{data:null},maxWidth:0,level:0,childrenCount:4}};this._splitBranch(g.root);for(var h=0;o>h;h++)i=t[e[h]],i.options.mass>0&&this._placeInTree(g.root,i);return g}},{key:"_updateBranchMass",value:function(t,e){var i=t.mass+e.options.mass,o=1/i;t.centerOfMass.x=t.centerOfMass.x*t.mass+e.x*e.options.mass,t.centerOfMass.x*=o,t.centerOfMass.y=t.centerOfMass.y*t.mass+e.y*e.options.mass,t.centerOfMass.y*=o,t.mass=i;var n=Math.max(Math.max(e.height,e.radius),e.width);t.maxWidth=t.maxWidthe.x?t.children.NW.range.maxY>e.y?this._placeInRegion(t,e,"NW"):this._placeInRegion(t,e,"SW"):t.children.NW.range.maxY>e.y?this._placeInRegion(t,e,"NE"):this._placeInRegion(t,e,"SE")}},{key:"_placeInRegion",value:function(t,e,i){switch(t.children[i].childrenCount){case 0:t.children[i].children.data=e,t.children[i].childrenCount=1,this._updateBranchMass(t.children[i],e);break;case 1:t.children[i].children.data.x===e.x&&t.children[i].children.data.y===e.y?(e.x+=.1,e.y+=.1):(this._splitBranch(t.children[i]),this._placeInTree(t.children[i],e));break;case 4:this._placeInTree(t.children[i],e)}}},{key:"_splitBranch",value:function(t){var e=null;1===t.childrenCount&&(e=t.children.data,t.mass=0,t.centerOfMass.x=0,t.centerOfMass.y=0),t.childrenCount=4,t.children.data=null,this._insertRegion(t,"NW"),this._insertRegion(t,"NE"),this._insertRegion(t,"SW"),this._insertRegion(t,"SE"),null!=e&&this._placeInTree(t,e)}},{key:"_insertRegion",value:function(t,e){var i=void 0,o=void 0,n=void 0,s=void 0,r=.5*t.size;switch(e){case"NW":i=t.range.minX,o=t.range.minX+r,n=t.range.minY,s=t.range.minY+r;break;case"NE":i=t.range.minX+r,o=t.range.maxX,n=t.range.minY,s=t.range.minY+r;break;case"SW":i=t.range.minX,o=t.range.minX+r,n=t.range.minY+r,s=t.range.maxY;break;case"SE":i=t.range.minX+r,o=t.range.maxX,n=t.range.minY+r,s=t.range.maxY}t.children[e]={centerOfMass:{x:0,y:0},mass:0,range:{minX:i,maxX:o,minY:n,maxY:s},size:.5*t.size,calcSize:2*t.calcSize,children:{data:null},maxWidth:0,level:t.level+1,childrenCount:0}}},{key:"_debug",value:function(t,e){void 0!==this.barnesHutTree&&(t.lineWidth=1,this._drawBranch(this.barnesHutTree.root,t,e))}},{key:"_drawBranch",value:function(t,e,i){void 0===i&&(i="#FF0000"),4===t.childrenCount&&(this._drawBranch(t.children.NW,e),this._drawBranch(t.children.NE,e),this._drawBranch(t.children.SE,e),this._drawBranch(t.children.SW,e)),e.strokeStyle=i,e.beginPath(),e.moveTo(t.range.minX,t.range.minY),e.lineTo(t.range.maxX,t.range.minY),e.stroke(),e.beginPath(),e.moveTo(t.range.maxX,t.range.minY),e.lineTo(t.range.maxX,t.range.maxY),e.stroke(),e.beginPath(),e.moveTo(t.range.maxX,t.range.maxY),e.lineTo(t.range.minX,t.range.maxY),e.stroke(),e.beginPath(),e.moveTo(t.range.minX,t.range.maxY),e.lineTo(t.range.minX,t.range.minY),e.stroke()}}]),t}();e["default"]=s,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;ii&&(s=.5*u>i?1:c*i+p,s/=i,o=t*s,n=e*s,l[r.id].x-=o,l[r.id].y-=n,l[a.id].x+=o,l[a.id].y+=n)}}}]),t}();e["default"]=s,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;ii?-Math.pow(f*i,2)+Math.pow(f*p,2):0,0===i?i=.01:s/=i,o=t*s,n=e*s,c[r.id].x-=o,c[r.id].y-=n,c[a.id].x+=o,c[a.id].y+=n}}}]),t}();e["default"]=s,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;i0){var s=n.edges.length+1,r=this.options.centralGravity*s*n.options.mass;o[n.id].x=e*r,o[n.id].y=i*r}}}]),e}(d["default"]);e["default"]=l,t.exports=e["default"]},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function t(t,e){for(var i=0;i=t&&i.push(n.id)}for(var o=0;o0&&Object.keys(s).length>0&&i.push({nodes:n,edges:s})}}}for(var o=0;oo?r.x:o,n=r.ys?r.y:s;return{x:.5*(i+o),y:.5*(n+s)}}},{key:"openCluster",value:function(t){var e=void 0===arguments[1]?!0:arguments[1];if(void 0===t)throw new Error("No clusterNodeId supplied to openCluster.");if(void 0===this.body.nodes[t])throw new Error("The clusterNodeId supplied to openCluster does not exist.");if(void 0===this.body.nodes[t].containedNodes)return void console.log("The node:"+t+" is not a cluster.");var i=this.body.nodes[t],o=i.containedNodes,n=i.containedEdges;for(var s in o)if(o.hasOwnProperty(s)){var r=this.body.nodes[s];r=o[s],r.x=i.x,r.y=i.y,r.vx=i.vx,r.vy=i.vy,r.options.hidden=!1,r.togglePhysics(!0),delete this.clusteredNodes[s]}for(var a in n)if(n.hasOwnProperty(a)){var d=n[a];if(void 0===this.body.nodes[d.fromId]||void 0===this.body.nodes[d.toId])d.edgeType.cleanup(),d.disconnect(),delete this.body.edges[a];else if(void 0!==this.clusteredNodes[d.fromId]||void 0!==this.clusteredNodes[d.toId]){var l=void 0,u=void 0,c=this.clusteredNodes[d.fromId]||this.clusteredNodes[d.toId],p=c.clusterId,f=this.body.nodes[p];if(f.containedEdges[a]=d,void 0!==this.clusteredNodes[d.fromId]?(l=p,u=d.toId):(l=d.fromId,u=p),this.body.nodes[l].options.hidden!==!0&&this.body.nodes[u].options.hidden!==!0){var m=this._cloneOptions(d,"edge"),v="clusterEdge:"+h.randomUUID();h.deepExtend(m,f.clusterEdgeProperties),h.deepExtend(m,{from:l,to:u,hidden:!1,physics:!0,id:v});var g=this.body.functions.createEdge(m);this.body.edges[v]=g,this.body.edges[v].connect()}}else d.options.hidden=!1,d.togglePhysics(!0)}for(var y=0;yo;)e.push(this.clusteredNodes[t].node),t=this.clusteredNodes[t].clusterId,o++;return e.push(this.body.nodes[t]),e}},{key:"_getConnectedId",value:function(t,e){return t.toId!=e?t.toId:t.fromId!=e?t.fromId:t.fromId}},{key:"_getHubSize",value:function(){for(var t=0,e=0,i=0,o=0,n=0;no&&(o=s.edges.length),t+=s.edges.length,e+=Math.pow(s.edges.length,2),i+=1}t/=i,e/=i;var r=e-Math.pow(t,2),a=Math.sqrt(r),h=Math.floor(t+2*a);return h>o&&(h=o),h}}]),t}();e["default"]=d,t.exports=e["default"]},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var r=function(t,e,i){for(var o=!0;o;){var n=t,s=e,r=i;a=d=h=void 0,o=!1;var a=Object.getOwnPropertyDescriptor(n,s);if(void 0!==a){if("value"in a)return a.value;var h=a.get;return void 0===h?void 0:h.call(r)}var d=Object.getPrototypeOf(n);if(null===d)return void 0;t=d,e=s,i=r,o=!0}},a=i(62),h=o(a),d=function(t){function e(t,i,o,s,a){n(this,e),r(Object.getPrototypeOf(e.prototype),"constructor",this).call(this,t,i,o,s,a),this.isCluster=!0,this.containedNodes={},this.containedEdges={}}return s(e,t),e}(h["default"]);e["default"]=d,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;i0,t.renderTimer=void 0}),this.body.emitter.on("destroy",function(){t.renderRequests=0,t.renderingActive=!1,t.requiresTimeout===!0?clearTimeout(t.renderTimer):cancelAnimationFrame(t.renderTimer),t.body.emitter.off()})}},{key:"setOptions",value:function(t){if(void 0!==t){var e=["hideEdgesOnDrag","hideNodesOnDrag"];s.selectiveDeepExtend(e,this.options,t)}}},{key:"_startRendering",value:function(){this.renderingActive===!0&&void 0===this.renderTimer&&(this.requiresTimeout===!0?this.renderTimer=window.setTimeout(this._renderStep.bind(this),this.simulationInterval):this.renderTimer=window.requestAnimationFrame(this._renderStep.bind(this)))}},{key:"_renderStep",value:function(){this.renderingActive===!0&&(this.renderTimer=void 0,this.requiresTimeout===!0&&this._startRendering(),this._redraw(),this.requiresTimeout===!1&&this._startRendering())}},{key:"redraw",value:function(){this.body.emitter.emit("setSize"),this._redraw()}},{key:"_requestRedraw",value:function(){this.redrawRequested!==!0&&this.renderingActive===!1&&this.allowRedrawRequests===!0&&(this.redrawRequested=!0,this.requiresTimeout===!0?window.setTimeout(this._redraw.bind(this,!1),0):window.requestAnimationFrame(this._redraw.bind(this,!1)))}},{key:"_redraw",value:function(){var t=void 0===arguments[0]?!1:arguments[0];this.body.emitter.emit("initRedraw"),this.redrawRequested=!1;var e=this.canvas.frame.canvas.getContext("2d");(0===this.canvas.frame.canvas.width||0===this.canvas.frame.canvas.height)&&this.canvas.setSize(),void 0===this.pixelRatio&&(this.pixelRatio=(window.devicePixelRatio||1)/(e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1)),e.setTransform(this.pixelRatio,0,0,this.pixelRatio,0,0);var i=this.canvas.frame.canvas.clientWidth,o=this.canvas.frame.canvas.clientHeight;e.clearRect(0,0,i,o),e.save(),e.translate(this.body.view.translation.x,this.body.view.translation.y),e.scale(this.body.view.scale,this.body.view.scale),e.beginPath(),this.body.emitter.emit("beforeDrawing",e),e.closePath(),t===!1&&(this.dragging===!1||this.dragging===!0&&this.options.hideEdgesOnDrag===!1)&&this._drawEdges(e),(this.dragging===!1||this.dragging===!0&&this.options.hideNodesOnDrag===!1)&&this._drawNodes(e,t),this.controlNodesActive===!0&&this._drawControlNodes(e),e.beginPath(),this.body.emitter.emit("afterDrawing",e),e.closePath(),e.restore(),t===!0&&e.clearRect(0,0,i,o)}},{key:"_resizeNodes",value:function(){var t=this.canvas.frame.canvas.getContext("2d");void 0===this.pixelRatio&&(this.pixelRatio=(window.devicePixelRatio||1)/(t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1)),t.setTransform(this.pixelRatio,0,0,this.pixelRatio,0,0),t.save(),t.translate(this.body.view.translation.x,this.body.view.translation.y),t.scale(this.body.view.scale,this.body.view.scale);var e=this.body.nodes,i=void 0;for(var o in e)e.hasOwnProperty(o)&&(i=e[o],i.resize(t),i.updateBoundingBox(t));t.restore()}},{key:"_drawNodes",value:function(t){for(var e=void 0===arguments[1]?!1:arguments[1],i=this.body.nodes,o=this.body.nodeIndices,n=void 0,s=[],r=20,a=this.canvas.DOMtoCanvas({x:-r,y:-r}),h=this.canvas.DOMtoCanvas({x:this.canvas.frame.canvas.clientWidth+r,y:this.canvas.frame.canvas.clientHeight+r}),d={top:a.y,left:a.x,bottom:h.y,right:h.x},l=0;l0)for(var r=0;rt.shape.boundingBox.left&&(n=t.shape.boundingBox.left),st.shape.boundingBox.top&&(i=t.shape.boundingBox.top),ot.shape.boundingBox.left&&(n=t.shape.boundingBox.left),st.shape.boundingBox.top&&(i=t.shape.boundingBox.top),o.5*this.body.nodeIndices.length)return void this.fit(i,!1);t=this._getRange(i.nodes);var a=this.body.nodeIndices.length;e=12.662/(a+7.4147)+.0964822;var h=Math.min(this.canvas.frame.canvas.clientWidth/600,this.canvas.frame.canvas.clientHeight/600);e*=h}else{this.body.emitter.emit("_resizeNodes"),t=this._getRange(i.nodes);var d=1.1*Math.abs(t.maxX-t.minX),l=1.1*Math.abs(t.maxY-t.minY),u=this.canvas.frame.canvas.clientWidth/d,c=this.canvas.frame.canvas.clientHeight/l;e=c>=u?u:c}e>1?e=1:0===e&&(e=1);var p=this._findCenter(t),f={position:p,scale:e,animation:i.animation};this.moveTo(f)}},{key:"focus",value:function(t){var e=void 0===arguments[1]?{}:arguments[1];if(void 0!==this.body.nodes[t]){var i={x:this.body.nodes[t].x,y:this.body.nodes[t].y};e.position=i,e.lockedOnNode=t,this.moveTo(e)}else console.log("Node: "+t+" cannot be found.")}},{key:"moveTo",value:function(t){return void 0===t?void(t={}):(void 0===t.offset&&(t.offset={x:0,y:0}),void 0===t.offset.x&&(t.offset.x=0),void 0===t.offset.y&&(t.offset.y=0),void 0===t.scale&&(t.scale=this.body.view.scale),void 0===t.position&&(t.position=this.getViewPosition()),void 0===t.animation&&(t.animation={duration:0}),t.animation===!1&&(t.animation={duration:0}),t.animation===!0&&(t.animation={}),void 0===t.animation.duration&&(t.animation.duration=1e3),void 0===t.animation.easingFunction&&(t.animation.easingFunction="easeInOutQuad"),void this.animateView(t))}},{key:"animateView",value:function(t){if(void 0!==t){this.animationEasingFunction=t.animation.easingFunction,this.releaseNode(),t.locked===!0&&(this.lockedOnNodeId=t.lockedOnNode,this.lockedOnNodeOffset=t.offset),0!=this.easingTime&&this._transitionRedraw(!0),this.sourceScale=this.body.view.scale,this.sourceTranslation=this.body.view.translation,this.targetScale=t.scale,this.body.view.scale=this.targetScale;var e=this.canvas.DOMtoCanvas({x:.5*this.canvas.frame.canvas.clientWidth,y:.5*this.canvas.frame.canvas.clientHeight}),i={x:e.x-t.position.x,y:e.y-t.position.y};this.targetTranslation={x:this.sourceTranslation.x+i.x*this.targetScale+t.offset.x,y:this.sourceTranslation.y+i.y*this.targetScale+t.offset.y},0===t.animation.duration?void 0!=this.lockedOnNodeId?(this.viewFunction=this._lockedRedraw.bind(this),this.body.emitter.on("initRedraw",this.viewFunction)):(this.body.view.scale=this.targetScale,this.body.view.translation=this.targetTranslation,this.body.emitter.emit("_requestRedraw")):(this.animationSpeed=1/(60*t.animation.duration*.001)||1/60,this.animationEasingFunction=t.animation.easingFunction,this.viewFunction=this._transitionRedraw.bind(this),this.body.emitter.on("initRedraw",this.viewFunction),this.body.emitter.emit("_startRendering"))}}},{key:"_lockedRedraw",value:function(){var t={x:this.body.nodes[this.lockedOnNodeId].x,y:this.body.nodes[this.lockedOnNodeId].y},e=this.DOMtoCanvas({x:.5*this.frame.canvas.clientWidth,y:.5*this.frame.canvas.clientHeight}),i={x:e.x-t.x,y:e.y-t.y},o=this.body.view.translation,n={x:o.x+i.x*this.body.view.scale+this.lockedOnNodeOffset.x,y:o.y+i.y*this.body.view.scale+this.lockedOnNodeOffset.y};this.body.view.translation=n}},{key:"releaseNode",value:function(){void 0!==this.lockedOnNodeId&&void 0!==this.viewFunction&&(this.body.emitter.off("initRedraw",this.viewFunction),this.lockedOnNodeId=void 0,this.lockedOnNodeOffset=void 0)}},{key:"_transitionRedraw",value:function(){var t=void 0===arguments[0]?!1:arguments[0];this.easingTime+=this.animationSpeed,this.easingTime=t===!0?1:this.easingTime;var e=s.easingFunctions[this.animationEasingFunction](this.easingTime);this.body.view.scale=this.sourceScale+(this.targetScale-this.sourceScale)*e,this.body.view.translation={x:this.sourceTranslation.x+(this.targetTranslation.x-this.sourceTranslation.x)*e,y:this.sourceTranslation.y+(this.targetTranslation.y-this.sourceTranslation.y)*e},this.easingTime>=1&&(this.body.emitter.off("initRedraw",this.viewFunction),this.easingTime=0,void 0!=this.lockedOnNodeId&&(this.viewFunction=this._lockedRedraw.bind(this),this.body.emitter.on("initRedraw",this.viewFunction)),this.body.emitter.emit("animationFinished"))}},{key:"getScale",value:function(){return this.body.view.scale}},{key:"getViewPosition",value:function(){return this.canvas.DOMtoCanvas({x:.5*this.canvas.frame.canvas.clientWidth,y:.5*this.canvas.frame.canvas.clientHeight})}}]),t}();e["default"]=r,t.exports=e["default"]},function(t,e,i){function o(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function t(t,e){for(var i=0;i50&&(this.drag.pointer=this.getPointer(t.center),this.drag.pinched=!1,this.pinch.scale=this.body.view.scale,this.touchTime=(new Date).valueOf())}},{key:"onTap",value:function(t){var e=this.getPointer(t.center),i=this.selectionHandler.options.multiselect&&(t.changedPointers[0].ctrlKey||t.changedPointers[0].metaKey);this.checkSelectionChanges(e,t,i),this.selectionHandler._generateClickEvent("click",t,e)}},{key:"onDoubleTap",value:function(t){var e=this.getPointer(t.center);this.selectionHandler._generateClickEvent("doubleClick",t,e)}},{key:"onHold",value:function(t){var e=this.getPointer(t.center),i=this.selectionHandler.options.multiselect;this.checkSelectionChanges(e,t,i),this.selectionHandler._generateClickEvent("click",t,e),this.selectionHandler._generateClickEvent("hold",t,e)}},{key:"onRelease",value:function(t){if((new Date).valueOf()-this.touchTime>10){var e=this.getPointer(t.center);this.selectionHandler._generateClickEvent("release",t,e),this.touchTime=(new Date).valueOf()}}},{key:"onContext",value:function(t){var e=this.getPointer({x:t.clientX,y:t.clientY});this.selectionHandler._generateClickEvent("oncontext",t,e)}},{key:"checkSelectionChanges",value:function(t,e){var i=void 0===arguments[2]?!1:arguments[2],o=this.selectionHandler._getSelectedEdgeCount(),n=this.selectionHandler._getSelectedNodeCount(),s=this.selectionHandler.getSelection(),r=void 0;r=i===!0?this.selectionHandler.selectAdditionalOnPoint(t):this.selectionHandler.selectOnPoint(t);var a=this.selectionHandler._getSelectedEdgeCount(),h=this.selectionHandler._getSelectedNodeCount(),d=this.selectionHandler.getSelection(),l=this._determineIfDifferent(s,d),u=l.nodesChanges,c=l.edgesChanges;h-n>0?(this.selectionHandler._generateClickEvent("selectNode",e,t),r=!0):0>h-n?(this.selectionHandler._generateClickEvent("deselectNode",e,t,s),r=!0):h===n&&u===!0&&(this.selectionHandler._generateClickEvent("deselectNode",e,t,s),this.selectionHandler._generateClickEvent("selectNode",e,t),r=!0),a-o>0?(this.selectionHandler._generateClickEvent("selectEdge",e,t),r=!0):0>a-o?(this.selectionHandler._generateClickEvent("deselectEdge",e,t,s),r=!0):a===o&&c===!0&&(this.selectionHandler._generateClickEvent("deselectEdge",e,t,s),this.selectionHandler._generateClickEvent("selectEdge",e,t),r=!0),r===!0&&this.selectionHandler._generateClickEvent("select",e,t)}},{key:"_determineIfDifferent",value:function(t,e){for(var i=!1,o=!1,n=0;nt&&(t=1e-5),t>10&&(t=10);var o=void 0;void 0!==this.drag&&this.drag.dragging===!0&&(o=this.canvas.DOMtoCanvas(this.drag.pointer));var n=this.body.view.translation,s=t/i,r=(1-s)*e.x+n.x*s,a=(1-s)*e.y+n.y*s;if(this.body.view.scale=t,this.body.view.translation={x:r,y:a},void 0!=o){var h=this.canvas.canvasToDOM(o);this.drag.pointer.x=h.x,this.drag.pointer.y=h.y}this.body.emitter.emit("_requestRedraw"),t>i?this.body.emitter.emit("zoom",{direction:"+",scale:this.body.view.scale}):this.body.emitter.emit("zoom",{direction:"-",scale:this.body.view.scale})}}},{key:"onMouseWheel",value:function(t){var e=0;if(t.wheelDelta?e=t.wheelDelta/120:t.detail&&(e=-t.detail/3),0!==e){var i=this.body.view.scale,o=e/10;0>e&&(o/=1-o),i*=1+o;var n=this.getPointer({x:t.clientX,y:t.clientY});this.zoom(i,n)}t.preventDefault()}},{key:"onMouseMove",value:function(t){var e=this,i=this.getPointer({x:t.clientX,y:t.clientY}),o=!1;if(void 0!==this.popup&&(this.popup.hidden===!1&&this._checkHidePopup(i),this.popup.hidden===!1&&(o=!0,this.popup.setPosition(i.x+3,i.y-5),this.popup.show())),this.options.keyboard.bindToWindow===!1&&this.options.keyboard.enabled===!0&&this.canvas.frame.focus(),o===!1&&(void 0!==this.popupTimer&&(clearInterval(this.popupTimer),this.popupTimer=void 0),this.drag.dragging||(this.popupTimer=setTimeout(function(){return e._checkShowPopup(i)},this.options.tooltipDelay))),this.options.hover===!0){var n=this.selectionHandler.getNodeAt(i);void 0===n&&(n=this.selectionHandler.getEdgeAt(i)),this.selectionHandler.hoverObject(n)}}},{key:"_checkShowPopup",value:function(t){var e=this.canvas._XconvertDOMtoCanvas(t.x),i=this.canvas._YconvertDOMtoCanvas(t.y),o={left:e,top:i,right:e,bottom:i},n=void 0===this.popupObj?void 0:this.popupObj.id,s=!1,r="node";if(void 0===this.popupObj){for(var a=this.body.nodeIndices,h=this.body.nodes,l=void 0,u=[],c=0;c0&&(this.popupObj=h[u[u.length-1]],s=!0)}if(void 0===this.popupObj&&s===!1){for(var p=this.body.edgeIndices,f=this.body.edges,m=void 0,v=[],c=0;c0&&(this.popupObj=f[v[v.length-1]],r="edge")}void 0!==this.popupObj?this.popupObj.id!==n&&(void 0===this.popup&&(this.popup=new d["default"](this.canvas.frame)),this.popup.popupTargetType=r,this.popup.popupTargetId=this.popupObj.id,this.popup.setPosition(t.x+3,t.y-5),this.popup.setText(this.popupObj.getTitle()),this.popup.show(),this.body.emitter.emit("showPopup",this.popupObj.id)):void 0!==this.popup&&(this.popup.hide(),this.body.emitter.emit("hidePopup"))}},{key:"_checkHidePopup",value:function(t){var e=this.selectionHandler._pointerToPositionObject(t),i=!1;if("node"===this.popup.popupTargetType){if(void 0!==this.body.nodes[this.popup.popupTargetId]&&(i=this.body.nodes[this.popup.popupTargetId].isOverlappingWith(e),i===!0)){var o=this.selectionHandler.getNodeAt(t);i=o.id===this.popup.popupTargetId}}else void 0===this.selectionHandler.getNodeAt(t)&&void 0!==this.body.edges[this.popup.popupTargetId]&&(i=this.body.edges[this.popup.popupTargetId].isOverlappingWith(e));i===!1&&(this.popupObj=void 0,this.popup.hide(),this.body.emitter.emit("hidePopup"))}}]),t}();e["default"]=u,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;i700&&(this.body.emitter.emit("fit",{duration:700}),this.touchTime=(new Date).valueOf())}},{key:"_stopMovement",value:function(){for(var t in this.boundFunctions)this.boundFunctions.hasOwnProperty(t)&&(this.body.emitter.off("initRedraw",this.boundFunctions[t]),this.body.emitter.emit("_stopRendering"));this.boundFunctions={}}},{key:"_moveUp",value:function(){this.body.view.translation.y+=this.options.keyboard.speed.y}},{key:"_moveDown",value:function(){this.body.view.translation.y-=this.options.keyboard.speed.y}},{key:"_moveLeft",value:function(){this.body.view.translation.x+=this.options.keyboard.speed.x}},{key:"_moveRight",value:function(){this.body.view.translation.x-=this.options.keyboard.speed.x}},{key:"_zoomIn",value:function(){this.body.view.scale*=1+this.options.keyboard.speed.zoom; +}},{key:"_zoomOut",value:function(){this.body.view.scale/=1+this.options.keyboard.speed.zoom}},{key:"configureKeyboardBindings",value:function(){void 0!==this.keycharm&&this.keycharm.destroy(),this.options.keyboard.enabled===!0&&(this.options.keyboard.bindToWindow===!0?this.keycharm=a({container:window,preventDefault:!0}):this.keycharm=a({container:this.canvas.frame,preventDefault:!0}),this.keycharm.reset(),this.activated===!0&&(this.keycharm.bind("up",this.bindToRedraw.bind(this,"_moveUp"),"keydown"),this.keycharm.bind("down",this.bindToRedraw.bind(this,"_moveDown"),"keydown"),this.keycharm.bind("left",this.bindToRedraw.bind(this,"_moveLeft"),"keydown"),this.keycharm.bind("right",this.bindToRedraw.bind(this,"_moveRight"),"keydown"),this.keycharm.bind("=",this.bindToRedraw.bind(this,"_zoomIn"),"keydown"),this.keycharm.bind("num+",this.bindToRedraw.bind(this,"_zoomIn"),"keydown"),this.keycharm.bind("num-",this.bindToRedraw.bind(this,"_zoomOut"),"keydown"),this.keycharm.bind("-",this.bindToRedraw.bind(this,"_zoomOut"),"keydown"),this.keycharm.bind("[",this.bindToRedraw.bind(this,"_zoomOut"),"keydown"),this.keycharm.bind("]",this.bindToRedraw.bind(this,"_zoomIn"),"keydown"),this.keycharm.bind("pageup",this.bindToRedraw.bind(this,"_zoomIn"),"keydown"),this.keycharm.bind("pagedown",this.bindToRedraw.bind(this,"_zoomOut"),"keydown"),this.keycharm.bind("up",this.unbindFromRedraw.bind(this,"_moveUp"),"keyup"),this.keycharm.bind("down",this.unbindFromRedraw.bind(this,"_moveDown"),"keyup"),this.keycharm.bind("left",this.unbindFromRedraw.bind(this,"_moveLeft"),"keyup"),this.keycharm.bind("right",this.unbindFromRedraw.bind(this,"_moveRight"),"keyup"),this.keycharm.bind("=",this.unbindFromRedraw.bind(this,"_zoomIn"),"keyup"),this.keycharm.bind("num+",this.unbindFromRedraw.bind(this,"_zoomIn"),"keyup"),this.keycharm.bind("num-",this.unbindFromRedraw.bind(this,"_zoomOut"),"keyup"),this.keycharm.bind("-",this.unbindFromRedraw.bind(this,"_zoomOut"),"keyup"),this.keycharm.bind("[",this.unbindFromRedraw.bind(this,"_zoomOut"),"keyup"),this.keycharm.bind("]",this.unbindFromRedraw.bind(this,"_zoomIn"),"keyup"),this.keycharm.bind("pageup",this.unbindFromRedraw.bind(this,"_zoomIn"),"keyup"),this.keycharm.bind("pagedown",this.unbindFromRedraw.bind(this,"_zoomOut"),"keyup")))}}]),t}();e["default"]=h,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;io&&(s=o-e-this.padding),sn&&(r=n-i-this.padding),r0?e===!0?this.body.nodes[o[o.length-1]]:o[o.length-1]:void 0}},{key:"_getEdgesOverlappingWith",value:function(t,e){for(var i=this.body.edges,o=0;o0?e===!0?this.body.edges[o[o.length-1]]:o[o.length-1]:void 0}},{key:"_addToSelection",value:function(t){t instanceof s?this.selectionObj.nodes[t.id]=t:this.selectionObj.edges[t.id]=t}},{key:"_addToHover",value:function(t){t instanceof s?this.hoverObj.nodes[t.id]=t:this.hoverObj.edges[t.id]=t}},{key:"_removeFromSelection",value:function(t){t instanceof s?delete this.selectionObj.nodes[t.id]:delete this.selectionObj.edges[t.id]}},{key:"unselectAll",value:function(){for(var t in this.selectionObj.nodes)this.selectionObj.nodes.hasOwnProperty(t)&&this.selectionObj.nodes[t].unselect();for(var e in this.selectionObj.edges)this.selectionObj.edges.hasOwnProperty(e)&&this.selectionObj.edges[e].unselect();this.selectionObj={nodes:{},edges:{}}}},{key:"_getSelectedNodeCount",value:function(){var t=0;for(var e in this.selectionObj.nodes)this.selectionObj.nodes.hasOwnProperty(e)&&(t+=1);return t}},{key:"_getSelectedNode",value:function(){for(var t in this.selectionObj.nodes)if(this.selectionObj.nodes.hasOwnProperty(t))return this.selectionObj.nodes[t];return void 0}},{key:"_getSelectedEdge",value:function(){for(var t in this.selectionObj.edges)if(this.selectionObj.edges.hasOwnProperty(t))return this.selectionObj.edges[t];return void 0}},{key:"_getSelectedEdgeCount",value:function(){var t=0;for(var e in this.selectionObj.edges)this.selectionObj.edges.hasOwnProperty(e)&&(t+=1);return t}},{key:"_getSelectedObjectCount",value:function(){var t=0;for(var e in this.selectionObj.nodes)this.selectionObj.nodes.hasOwnProperty(e)&&(t+=1);for(var i in this.selectionObj.edges)this.selectionObj.edges.hasOwnProperty(i)&&(t+=1);return t}},{key:"_selectionIsEmpty",value:function(){for(var t in this.selectionObj.nodes)if(this.selectionObj.nodes.hasOwnProperty(t))return!1;for(var e in this.selectionObj.edges)if(this.selectionObj.edges.hasOwnProperty(e))return!1;return!0}},{key:"_clusterInSelection",value:function(){for(var t in this.selectionObj.nodes)if(this.selectionObj.nodes.hasOwnProperty(t)&&this.selectionObj.nodes[t].clusterSize>1)return!0;return!1}},{key:"_selectConnectedEdges",value:function(t){for(var e=0;e0&&(this.options.hierarchical.levelSeparation*=-1):this.options.hierarchical.levelSeparation<0&&(this.options.hierarchical.levelSeparation*=-1),this.body.emitter.emit("_resetHierarchicalLayout"),this.adaptAllOptions(e);if(i===!0)return this.body.emitter.emit("refresh"),s.deepExtend(e,this.optionsBackup)}return e}},{key:"adaptAllOptions",value:function(t){if(this.options.hierarchical.enabled===!0){void 0===t.physics||t.physics===!0?(t.physics={solver:"hierarchicalRepulsion"},this.optionsBackup.physics={solver:"barnesHut"}):"object"==typeof t.physics?(this.optionsBackup.physics={solver:"barnesHut"},void 0!==t.physics.solver&&(this.optionsBackup.physics={solver:t.physics.solver}),t.physics.solver="hierarchicalRepulsion"):t.physics!==!1&&(this.optionsBackup.physics={solver:"barnesHut"},t.physics.solver="hierarchicalRepulsion");var e="horizontal";("RL"===this.options.hierarchical.direction||"LR"===this.options.hierarchical.direction)&&(e="vertical"),void 0===t.edges?(this.optionsBackup.edges={smooth:{enabled:!0,type:"dynamic"}},t.edges={smooth:!1}):void 0===t.edges.smooth?(this.optionsBackup.edges={smooth:{enabled:!0,type:"dynamic"}},t.edges.smooth=!1):"boolean"==typeof t.edges.smooth?(this.optionsBackup.edges={smooth:t.edges.smooth},t.edges.smooth={enabled:t.edges.smooth,type:e}):(void 0!==t.edges.smooth.type&&"dynamic"!==t.edges.smooth.type&&(e=t.edges.smooth.type),this.optionsBackup.edges={smooth:void 0===t.edges.smooth.enabled?!0:t.edges.smooth.enabled,type:void 0===t.edges.smooth.type?"dynamic":t.edges.smooth.type,roundness:void 0===t.edges.smooth.roundness?.5:t.edges.smooth.roundness},t.edges.smooth={enabled:void 0===t.edges.smooth.enabled?!0:t.edges.smooth.enabled,type:e,roundness:void 0===t.edges.smooth.roundness?.5:t.edges.smooth.roundness}),this.body.emitter.emit("_forceDisableDynamicCurves",e)}return t}},{key:"seededRandom",value:function(){var t=1e4*Math.sin(this.randomSeed++);return t-Math.floor(t)}},{key:"positionInitially",value:function(t){if(this.options.hierarchical.enabled!==!0){this.randomSeed=this.initialRandomSeed;for(var e=0;e0){var t=void 0,e=void 0,i=!1,o=!1;this.hierarchicalLevels={},this.nodeSpacing=100;for(e in this.body.nodes)this.body.nodes.hasOwnProperty(e)&&(t=this.body.nodes[e],void 0!==t.options.level?(i=!0,this.hierarchicalLevels[e]=t.options.level):o=!0);if(o===!0&&i===!0)throw new Error("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");o===!0&&("hubsize"===this.options.hierarchical.sortMethod?this._determineLevelsByHubsize():("directed"===this.options.hierarchical.sortMethod,0||this._determineLevelsDirected()));var n=this._getDistribution();this._placeNodesByHierarchy(n)}}},{key:"_placeNodesByHierarchy",value:function(t){var e=void 0,i=void 0;this.positionedNodes={};for(var o in t)if(t.hasOwnProperty(o))for(e in t[o].nodes)t[o].nodes.hasOwnProperty(e)&&(i=t[o].nodes[e],"UD"===this.options.hierarchical.direction||"DU"===this.options.hierarchical.direction?(void 0===i.x&&(i.x=t[o].distance),t[o].distance=i.x+this.nodeSpacing):(void 0===i.y&&(i.y=t[o].distance),t[o].distance=i.y+this.nodeSpacing),this.positionedNodes[e]=!0,this._placeBranchNodes(i.edges,i.id,t,o))}},{key:"_getDistribution",value:function(){var t={},e=void 0,i=void 0;for(e in this.body.nodes)if(this.body.nodes.hasOwnProperty(e)){i=this.body.nodes[e];var o=void 0===this.hierarchicalLevels[e]?0:this.hierarchicalLevels[e];"UD"===this.options.hierarchical.direction||"DU"===this.options.hierarchical.direction?(i.y=this.options.hierarchical.levelSeparation*o,i.options.fixed.y=!0):(i.x=this.options.hierarchical.levelSeparation*o,i.options.fixed.x=!0),void 0===t[o]&&(t[o]={amount:0,nodes:{},distance:0}),t[o].amount+=1,t[o].nodes[e]=i}return t}},{key:"_getHubSize",value:function(){var t=0;for(var e in this.body.nodes)if(this.body.nodes.hasOwnProperty(e)){var i=this.body.nodes[e];void 0===this.hierarchicalLevels[e]&&(t=i.edges.length0&&(i=this._getHubSize(),0!==i);)for(t in this.body.nodes)this.body.nodes.hasOwnProperty(t)&&(e=this.body.nodes[t],e.edges.length===i&&this._setLevelByHubsize(0,e))}},{key:"_setLevelByHubsize",value:function(t,e){if(void 0===this.hierarchicalLevels[e.id]){var i=void 0;this.hierarchicalLevels[e.id]=t;for(var o=0;oo&&("UD"===this.options.hierarchical.direction||"DU"===this.options.hierarchical.direction?(void 0===s.x&&(s.x=Math.max(i[a].distance,r.x)),i[a].distance=s.x+this.nodeSpacing,this.positionedNodes[s.id]=!0):(void 0===s.y&&(s.y=Math.max(i[a].distance,r.y)),i[a].distance=s.y+this.nodeSpacing),this.positionedNodes[s.id]=!0,s.edges.length>1&&this._placeBranchNodes(s.edges,s.id,i,a))}}}]),t}();e["default"]=r,t.exports=e["default"]},function(t,e,i){function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var i=0;i0){for(var n=0;n0&&"function"==typeof this.options.deleteEdge&&(o=this.options.deleteEdge);if("function"==typeof o){var s={nodes:e,edges:i};if(2!==o.length)throw new Error("The function for delete does not support two arguments (data, callback)");o(s,function(e){null!==e&&void 0!==e&&"delete"===t.inMode&&(t.body.data.edges.remove(e.edges),t.body.data.nodes.remove(e.nodes),t.body.emitter.emit("startSimulation"),t.showManipulatorToolbar())})}else this.body.data.edges.remove(i),this.body.data.nodes.remove(e),this.body.emitter.emit("startSimulation"),this.showManipulatorToolbar()}},{key:"_setup",value:function(){this.options.enabled===!0?(this.guiEnabled=!0,this._createWrappers(),this.editMode===!1?this._createEditButton():this.showManipulatorToolbar()):(this._removeManipulationDOM(),this.guiEnabled=!1)}},{key:"_createWrappers",value:function(){void 0===this.manipulationDiv&&(this.manipulationDiv=document.createElement("div"),this.manipulationDiv.className="vis-manipulation",this.editMode===!0?this.manipulationDiv.style.display="block":this.manipulationDiv.style.display="none",this.canvas.frame.appendChild(this.manipulationDiv)),void 0===this.editModeDiv&&(this.editModeDiv=document.createElement("div"),this.editModeDiv.className="vis-edit-mode",this.editMode===!0?this.editModeDiv.style.display="none":this.editModeDiv.style.display="block",this.canvas.frame.appendChild(this.editModeDiv)),void 0===this.closeDiv&&(this.closeDiv=document.createElement("div"),this.closeDiv.className="vis-close",this.closeDiv.style.display=this.manipulationDiv.style.display,this.canvas.frame.appendChild(this.closeDiv))}},{key:"_getNewTargetNode",value:function(t,e){var i=s.deepExtend({},this.options.controlNodeStyle);return i.id="targetNode"+s.randomUUID(),i.hidden=!1,i.physics=!1,i.x=t,i.y=e,this.body.functions.createNode(i)}},{key:"_createEditButton",value:function(){this._clean(),this.manipulationDOM={},s.recursiveDOMDelete(this.editModeDiv);var t=this.options.locales[this.options.locale],e=this._createButton("editMode","vis-button vis-edit vis-edit-mode",t.edit||this.options.locales.en.edit);this.editModeDiv.appendChild(e),this._bindHammerToDiv(e,this.toggleEditMode.bind(this))}},{key:"_clean",value:function(){this.inMode=!1,this.guiEnabled===!0&&(s.recursiveDOMDelete(this.editModeDiv),s.recursiveDOMDelete(this.manipulationDiv),this._cleanManipulatorHammers()),this._cleanupTemporaryNodesAndEdges(),this._unbindTemporaryUIs(),this._unbindTemporaryEvents(),this.body.emitter.emit("restorePhysics")}},{key:"_cleanManipulatorHammers",value:function(){if(0!=this.manipulationHammers.length){for(var t=0;t=0;r--)if(n[r]!==this.selectedControlNode.id){s=this.body.nodes[n[r]];break}if(void 0!==s&&void 0!==this.selectedControlNode)if(s.isCluster===!0)alert(this.options.locales[this.options.locale].createEdgeError||this.options.locales.en.createEdgeError);else{var a=this.body.nodes[this.temporaryIds.nodes[0]];this.selectedControlNode.id===a.id?this._performEditEdge(s.id,o.to.id):this._performEditEdge(o.from.id,s.id)}else o.updateEdgeType(),this.body.emitter.emit("restorePhysics");this.body.emitter.emit("_redraw")}},{key:"_handleConnect",value:function(t){if((new Date).valueOf()-this.touchTime>100){this.lastTouch=this.body.functions.getPointer(t.center),this.lastTouch.translation=s.extend({},this.body.view.translation);var e=this.lastTouch,i=this.selectionHandler.getNodeAt(e);if(void 0!==i)if(i.isCluster===!0)alert(this.options.locales[this.options.locale].createEdgeError||this.options.locales.en.createEdgeError);else{var o=this._getNewTargetNode(i.x,i.y);this.body.nodes[o.id]=o,this.body.nodeIndices.push(o.id);var n=this.body.functions.createEdge({id:"connectionEdge"+s.randomUUID(),from:i.id,to:o.id,physics:!1,smooth:{enabled:!0,type:"continuous",roundness:.5}});this.body.edges[n.id]=n,this.body.edgeIndices.push(n.id),this.temporaryIds.nodes.push(o.id),this.temporaryIds.edges.push(n.id)}this.touchTime=(new Date).valueOf()}}},{key:"_dragControlNode",value:function(t){var e=this.body.functions.getPointer(t.center);if(void 0!==this.temporaryIds.nodes[0]){var i=this.body.nodes[this.temporaryIds.nodes[0]];i.x=this.canvas._XconvertDOMtoCanvas(e.x),i.y=this.canvas._YconvertDOMtoCanvas(e.y),this.body.emitter.emit("_redraw")}else{var o=e.x-this.lastTouch.x,n=e.y-this.lastTouch.y;this.body.view.translation={x:this.lastTouch.translation.x+o,y:this.lastTouch.translation.y+n}}}},{key:"_finishConnect",value:function(t){var e=this.body.functions.getPointer(t.center),i=this.selectionHandler._pointerToPositionObject(e),o=void 0;void 0!==this.temporaryIds.edges[0]&&(o=this.body.edges[this.temporaryIds.edges[0]].fromId);for(var n=this.selectionHandler._getAllNodesOverlappingWith(i),s=void 0,r=n.length-1;r>=0;r--)if(-1===this.temporaryIds.nodes.indexOf(n[r])){s=this.body.nodes[n[r]];break}this._cleanupTemporaryNodesAndEdges(),void 0!==s&&(s.isCluster===!0?alert(this.options.locales[this.options.locale].createEdgeError||this.options.locales.en.createEdgeError):void 0!==this.body.nodes[o]&&void 0!==this.body.nodes[s.id]&&this._performAddEdge(o,s.id)),this.body.emitter.emit("_redraw")}},{key:"_performAddNode",value:function(t){var e=this,i={id:s.randomUUID(),x:t.pointer.canvas.x,y:t.pointer.canvas.y,label:"new"};if("function"==typeof this.options.addNode){if(2!==this.options.addNode.length)throw new Error("The function for add does not support two arguments (data,callback)");this.options.addNode(i,function(t){null!==t&&void 0!==t&&"addNode"===e.inMode&&(e.body.data.nodes.add(t),e.showManipulatorToolbar())})}else this.body.data.nodes.add(i),this.showManipulatorToolbar()}},{key:"_performAddEdge",value:function(t,e){var i=this,o={from:t,to:e};if("function"==typeof this.options.addEdge){if(2!==this.options.addEdge.length)throw new Error("The function for connect does not support two arguments (data,callback)");this.options.addEdge(o,function(t){null!==t&&void 0!==t&&"addEdge"===i.inMode&&(i.body.data.edges.add(t),i.selectionHandler.unselectAll(),i.showManipulatorToolbar())})}else this.body.data.edges.add(o),this.selectionHandler.unselectAll(),this.showManipulatorToolbar()}},{key:"_performEditEdge",value:function(t,e){var i=this,o={id:this.edgeBeingEditedId,from:t,to:e};if("function"==typeof this.options.editEdge){if(2!==this.options.editEdge.length)throw new Error("The function for edit does not support two arguments (data, callback)");this.options.editEdge(o,function(t){null===t||void 0===t||"editEdge"!==i.inMode?(i.body.edges[o.id].updateEdgeType(),i.body.emitter.emit("_redraw")):(i.body.data.edges.update(t),i.selectionHandler.unselectAll(),i.showManipulatorToolbar())})}else this.body.data.edges.update(o),this.selectionHandler.unselectAll(),this.showManipulatorToolbar()}}]),t}();e["default"]=h,t.exports=e["default"]},function(t,e,i){Object.defineProperty(e,"__esModule",{value:!0});var o="string",n="boolean",s="number",r="array",a="object",h="dom",d="function",l="undefined",u={configure:{enabled:{"boolean":n},filter:{"boolean":n,string:o,array:r,fn:d},container:{dom:h},showButton:{"boolean":n},__type__:{object:a,"boolean":n,string:o,array:r,fn:d}},edges:{arrows:{to:{enabled:{"boolean":n},scaleFactor:{number:s},__type__:{object:a,"boolean":n}},middle:{enabled:{"boolean":n},scaleFactor:{number:s},__type__:{object:a,"boolean":n}},from:{enabled:{"boolean":n},scaleFactor:{number:s},__type__:{object:a,"boolean":n}},__type__:{string:["from","to","middle"],object:a}},color:{color:{string:o},highlight:{string:o},hover:{string:o},inherit:{string:["from","to","both"],"boolean":n},opacity:{number:s},__type__:{object:a,string:o}},dashes:{"boolean":n,array:r},font:{color:{string:o},size:{number:s},face:{string:o},background:{string:o},strokeWidth:{number:s},strokeColor:{string:o},align:{string:["horizontal","top","middle","bottom"]},__type__:{object:a,string:o}},hidden:{"boolean":n},hoverWidth:{fn:d,number:s},label:{string:o,undef:l},length:{number:s,undef:l},physics:{"boolean":n},scaling:{min:{number:s},max:{number:s},label:{enabled:{"boolean":n},min:{number:s},max:{number:s},maxVisible:{number:s},drawThreshold:{number:s},__type__:{object:a,"boolean":n}},customScalingFunction:{fn:d},__type__:{object:a}},selectionWidth:{fn:d,number:s},selfReferenceSize:{number:s},shadow:{enabled:{"boolean":n},size:{number:s},x:{number:s},y:{number:s},__type__:{object:a,"boolean":n}},smooth:{enabled:{"boolean":n},type:{string:["dynamic","continuous","discrete","diagonalCross","straightCross","horizontal","vertical","curvedCW","curvedCCW"]},roundness:{number:s},__type__:{object:a,"boolean":n}},title:{string:o,undef:l},width:{number:s},value:{number:s,undef:l},__type__:{object:a}},groups:{useDefaultGroups:{"boolean":n},__any__:"get from nodes, will be overwritten below",__type__:{object:a}},interaction:{dragNodes:{"boolean":n},dragView:{"boolean":n},hideEdgesOnDrag:{"boolean":n},hideNodesOnDrag:{"boolean":n},hover:{"boolean":n},keyboard:{enabled:{"boolean":n},speed:{x:{number:s},y:{number:s},zoom:{number:s},__type__:{object:a}},bindToWindow:{"boolean":n},__type__:{object:a,"boolean":n}},multiselect:{"boolean":n},navigationButtons:{"boolean":n},selectable:{"boolean":n},selectConnectedEdges:{"boolean":n},hoverConnectedEdges:{"boolean":n},tooltipDelay:{number:s},zoomView:{"boolean":n},__type__:{object:a}},layout:{randomSeed:{undef:l,number:s},hierarchical:{enabled:{"boolean":n},levelSeparation:{number:s},direction:{string:["UD","DU","LR","RL"]},sortMethod:{string:["hubsize","directed"]},__type__:{object:a,"boolean":n}},__type__:{object:a}},manipulation:{enabled:{"boolean":n},initiallyActive:{"boolean":n},addNode:{"boolean":n,fn:d},addEdge:{"boolean":n,fn:d},editNode:{fn:d},editEdge:{"boolean":n,fn:d},deleteNode:{"boolean":n,fn:d},deleteEdge:{"boolean":n,fn:d},controlNodeStyle:"get from nodes, will be overwritten below",__type__:{object:a,"boolean":n}},nodes:{borderWidth:{number:s},borderWidthSelected:{number:s,undef:l},brokenImage:{string:o,undef:l},color:{border:{string:o},background:{string:o},highlight:{border:{string:o},background:{string:o},__type__:{object:a,string:o}},hover:{border:{string:o},background:{string:o},__type__:{object:a,string:o}},__type__:{object:a,string:o}},fixed:{x:{"boolean":n},y:{"boolean":n},__type__:{object:a,"boolean":n}},font:{color:{string:o},size:{number:s},face:{string:o},background:{string:o},strokeWidth:{number:s},strokeColor:{string:o},__type__:{object:a,string:o}},group:{string:o,number:s,undef:l},hidden:{"boolean":n},icon:{face:{string:o},code:{string:o},size:{number:s},color:{string:o},__type__:{object:a}},id:{string:o,number:s},image:{string:o,undef:l},label:{string:o,undef:l},level:{number:s,undef:l},mass:{number:s},physics:{"boolean":n},scaling:{min:{number:s},max:{number:s},label:{enabled:{"boolean":n},min:{number:s},max:{number:s},maxVisible:{number:s},drawThreshold:{number:s},__type__:{object:a,"boolean":n}},customScalingFunction:{fn:d},__type__:{object:a}},shadow:{enabled:{"boolean":n},size:{number:s},x:{number:s},y:{number:s},__type__:{object:a,"boolean":n}},shape:{string:["ellipse","circle","database","box","text","image","circularImage","diamond","dot","star","triangle","triangleDown","square","icon"]},size:{number:s},title:{string:o,undef:l},value:{number:s,undef:l},x:{number:s},y:{number:s},__type__:{object:a}},physics:{barnesHut:{gravitationalConstant:{number:s},centralGravity:{number:s},springLength:{number:s},springConstant:{number:s},damping:{number:s},avoidOverlap:{number:s},__type__:{object:a}},forceAtlas2Based:{gravitationalConstant:{number:s},centralGravity:{number:s},springLength:{number:s},springConstant:{number:s},damping:{number:s},avoidOverlap:{number:s},__type__:{object:a}},repulsion:{centralGravity:{number:s},springLength:{number:s},springConstant:{number:s},nodeDistance:{number:s},damping:{number:s},__type__:{object:a}},hierarchicalRepulsion:{centralGravity:{number:s},springLength:{number:s},springConstant:{number:s},nodeDistance:{number:s},damping:{number:s},__type__:{object:a}},maxVelocity:{number:s},minVelocity:{number:s},solver:{string:["barnesHut","repulsion","hierarchicalRepulsion","forceAtlas2Based"]},stabilization:{enabled:{"boolean":n},iterations:{number:s},updateInterval:{number:s},onlyDynamicEdges:{"boolean":n},fit:{"boolean":n},__type__:{object:a,"boolean":n}},timestep:{number:s},__type__:{object:a,"boolean":n}},autoResize:{"boolean":n},clickToUse:{"boolean":n},locale:{string:o},locales:{__any__:{object:a},__type__:{object:a}},height:{string:o},width:{string:o},__type__:{object:a}};u.groups.__any__=u.nodes,u.manipulation.controlNodeStyle=u.nodes;var c={nodes:{borderWidth:[1,0,10,1],borderWidthSelected:[2,0,10,1],color:{border:["color","#2B7CE9"],background:["color","#97C2FC"],highlight:{border:["color","#2B7CE9"],background:["color","#D2E5FF"]},hover:{border:["color","#2B7CE9"],background:["color","#D2E5FF"]}},fixed:{x:!1,y:!1},font:{color:["color","#343434"],size:[14,0,100,1],face:["arial","verdana","tahoma"],background:["color","none"],strokeWidth:[0,0,50,1],strokeColor:["color","#ffffff"]},hidden:!1,physics:!0,scaling:{min:[10,0,200,1],max:[30,0,200,1],label:{enabled:!1,min:[14,0,200,1],max:[30,0,200,1],maxVisible:[30,0,200,1],drawThreshold:[5,0,20,1]}},shadow:{enabled:!1,size:[10,0,20,1],x:[5,-30,30,1],y:[5,-30,30,1]},shape:["ellipse","box","circle","database","diamond","dot","square","star","text","triangle","triangleDown"],size:[25,0,200,1]},edges:{arrows:{to:{enabled:!1,scaleFactor:[1,0,3,.05]},middle:{enabled:!1,scaleFactor:[1,0,3,.05]},from:{enabled:!1,scaleFactor:[1,0,3,.05]}},color:{color:["color","#848484"],highlight:["color","#848484"],hover:["color","#848484"],inherit:["from","to","both",!0,!1],opacity:[1,0,1,.05]},dashes:!1,font:{color:["color","#343434"],size:[14,0,100,1],face:["arial","verdana","tahoma"],background:["color","none"],strokeWidth:[2,0,50,1],strokeColor:["color","#ffffff"],align:["horizontal","top","middle","bottom"]},hidden:!1,hoverWidth:[1.5,0,5,.1],physics:!0,scaling:{min:[1,0,100,1],max:[15,0,100,1],label:{enabled:!0,min:[14,0,200,1],max:[30,0,200,1],maxVisible:[30,0,200,1],drawThreshold:[5,0,20,1]}},selectionWidth:[1.5,0,5,.1],selfReferenceSize:[20,0,200,1],shadow:{enabled:!1,size:[10,0,20,1],x:[5,-30,30,1],y:[5,-30,30,1]},smooth:{enabled:!0,type:["dynamic","continuous","discrete","diagonalCross","straightCross","horizontal","vertical","curvedCW","curvedCCW"],roundness:[.5,0,1,.05]},width:[1,0,30,1]},layout:{hierarchical:{enabled:!1,levelSeparation:[150,20,500,5],direction:["UD","DU","LR","RL"],sortMethod:["hubsize","directed"]}},interaction:{dragNodes:!0,dragView:!0,hideEdgesOnDrag:!1,hideNodesOnDrag:!1,hover:!1,keyboard:{enabled:!1,speed:{x:[10,0,40,1],y:[10,0,40,1],zoom:[.02,0,.1,.005]},bindToWindow:!0},multiselect:!1,navigationButtons:!1,selectable:!0,selectConnectedEdges:!0,hoverConnectedEdges:!0,tooltipDelay:[300,0,1e3,25],zoomView:!0},manipulation:{enabled:!1,initiallyActive:!1},physics:{barnesHut:{gravitationalConstant:[-2e3,-3e4,0,50],centralGravity:[.3,0,10,.05],springLength:[95,0,500,5],springConstant:[.04,0,1.2,.005],damping:[.09,0,1,.01],avoidOverlap:[0,0,1,.01]},forceAtlas2Based:{gravitationalConstant:[-50,-500,0,1],centralGravity:[.01,0,1,.005],springLength:[95,0,500,5],springConstant:[.08,0,1.2,.005],damping:[.4,0,1,.01],avoidOverlap:[0,0,1,.01]},repulsion:{centralGravity:[.2,0,10,.05],springLength:[200,0,500,5],springConstant:[.05,0,1.2,.005],nodeDistance:[100,0,500,5],damping:[.09,0,1,.01]},hierarchicalRepulsion:{centralGravity:[.2,0,10,.05],springLength:[100,0,500,5],springConstant:[.01,0,1.2,.005],nodeDistance:[120,0,500,5],damping:[.09,0,1,.01]},maxVelocity:[50,0,150,1],minVelocity:[.1,.01,.5,.01],solver:["barnesHut","forceAtlas2Based","repulsion","hierarchicalRepulsion"],timestep:[.5,.01,1,.01]},global:{locale:["en","nl"]}};e.allOptions=u,e.configureOptions=c},function(t,e,i){"undefined"!=typeof CanvasRenderingContext2D&&(CanvasRenderingContext2D.prototype.circle=function(t,e,i){this.beginPath(),this.arc(t,e,i,0,2*Math.PI,!1),this.closePath()},CanvasRenderingContext2D.prototype.square=function(t,e,i){this.beginPath(),this.rect(t-i,e-i,2*i,2*i),this.closePath()},CanvasRenderingContext2D.prototype.triangle=function(t,e,i){this.beginPath(),i*=1.15,e+=.275*i;var o=2*i,n=o/2,s=Math.sqrt(3)/6*o,r=Math.sqrt(o*o-n*n);this.moveTo(t,e-(r-s)),this.lineTo(t+n,e+s),this.lineTo(t-n,e+s),this.lineTo(t,e-(r-s)),this.closePath()},CanvasRenderingContext2D.prototype.triangleDown=function(t,e,i){this.beginPath(),i*=1.15,e-=.275*i;var o=2*i,n=o/2,s=Math.sqrt(3)/6*o,r=Math.sqrt(o*o-n*n);this.moveTo(t,e+(r-s)),this.lineTo(t+n,e-s),this.lineTo(t-n,e-s),this.lineTo(t,e+(r-s)),this.closePath()},CanvasRenderingContext2D.prototype.star=function(t,e,i){this.beginPath(),i*=.82,e+=.1*i;for(var o=0;10>o;o++){var n=o%2===0?1.3*i:.5*i;this.lineTo(t+n*Math.sin(2*o*Math.PI/10),e-n*Math.cos(2*o*Math.PI/10))}this.closePath()},CanvasRenderingContext2D.prototype.diamond=function(t,e,i){this.beginPath(),this.lineTo(t,e+i),this.lineTo(t+i,e),this.lineTo(t,e-i),this.lineTo(t-i,e),this.closePath()},CanvasRenderingContext2D.prototype.roundRect=function(t,e,i,o,n){var s=Math.PI/180;0>i-2*n&&(n=i/2),0>o-2*n&&(n=o/2),this.beginPath(),this.moveTo(t+n,e),this.lineTo(t+i-n,e),this.arc(t+i-n,e+n,n,270*s,360*s,!1),this.lineTo(t+i,e+o-n),this.arc(t+i-n,e+o-n,n,0,90*s,!1),this.lineTo(t+n,e+o),this.arc(t+n,e+o-n,n,90*s,180*s,!1),this.lineTo(t,e+n),this.arc(t+n,e+n,n,180*s,270*s,!1),this.closePath()},CanvasRenderingContext2D.prototype.ellipse=function(t,e,i,o){var n=.5522848,s=i/2*n,r=o/2*n,a=t+i,h=e+o,d=t+i/2,l=e+o/2;this.beginPath(),this.moveTo(t,l),this.bezierCurveTo(t,l-r,d-s,e,d,e),this.bezierCurveTo(d+s,e,a,l-r,a,l),this.bezierCurveTo(a,l+r,d+s,h,d,h),this.bezierCurveTo(d-s,h,t,l+r,t,l),this.closePath()},CanvasRenderingContext2D.prototype.database=function(t,e,i,o){var n=1/3,s=i,r=o*n,a=.5522848,h=s/2*a,d=r/2*a,l=t+s,u=e+r,c=t+s/2,p=e+r/2,f=e+(o-r/2),m=e+o;this.beginPath(),this.moveTo(l,p),this.bezierCurveTo(l,p+d,c+h,u,c,u),this.bezierCurveTo(c-h,u,t,p+d,t,p),this.bezierCurveTo(t,p-d,c-h,e,c,e),this.bezierCurveTo(c+h,e,l,p-d,l,p),this.lineTo(l,f),this.bezierCurveTo(l,f+d,c+h,m,c,m),this.bezierCurveTo(c-h,m,t,f+d,t,f),this.lineTo(t,p)},CanvasRenderingContext2D.prototype.arrow=function(t,e,i,o){var n=t-o*Math.cos(i),s=e-o*Math.sin(i),r=t-.9*o*Math.cos(i),a=e-.9*o*Math.sin(i),h=n+o/3*Math.cos(i+.5*Math.PI),d=s+o/3*Math.sin(i+.5*Math.PI),l=n+o/3*Math.cos(i-.5*Math.PI),u=s+o/3*Math.sin(i-.5*Math.PI);this.beginPath(),this.moveTo(t,e),this.lineTo(h,d),this.lineTo(r,a),this.lineTo(l,u),this.closePath()},CanvasRenderingContext2D.prototype.dashedLine=function(t,e,i,o,n){this.beginPath(),this.moveTo(t,e);for(var s=n.length,r=i-t,a=o-e,h=a/r,d=Math.sqrt(r*r+a*a),l=0,u=!0,c=0,p=n[0];d>=.1;)p=n[l++%s],p>d&&(p=d),c=Math.sqrt(p*p/(1+h*h)),c=0>r?-c:c,t+=c,e+=h*c,u===!0?this.lineTo(t,e):this.moveTo(t,e),d-=p,u=!u})},function(t,e,i){function o(t){return I=t,f()}function n(){N=0,z=I.charAt(0)}function s(){N++,z=I.charAt(N)}function r(){return I.charAt(N+1)}function a(t){return B.test(t)}function h(t,e){if(t||(t={}),e)for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t}function d(t,e,i){for(var o=e.split("."),n=t;o.length;){var s=o.shift();o.length?(n[s]||(n[s]={}),n=n[s]):n[s]=i}}function l(t,e){for(var i,o,n=null,s=[t],r=t;r.parent;)s.push(r.parent),r=r.parent;if(r.nodes)for(i=0,o=r.nodes.length;o>i;i++)if(e.id===r.nodes[i].id){n=r.nodes[i];break}for(n||(n={id:e.id},t.node&&(n.attr=h(n.attr,t.node))),i=s.length-1;i>=0;i--){var a=s[i];a.nodes||(a.nodes=[]),-1===a.nodes.indexOf(n)&&a.nodes.push(n)}e.attr&&(n.attr=h(n.attr,e.attr))}function u(t,e){if(t.edges||(t.edges=[]),t.edges.push(e),t.edge){var i=h({},t.edge);e.attr=h(i,e.attr)}}function c(t,e,i,o,n){var s={from:e,to:i,type:o};return t.edge&&(s.attr=h({},t.edge)),s.attr=h(s.attr||{},n),s}function p(){for(L=S.NULL,A="";" "===z||" "===z||"\n"===z||"\r"===z;)s();do{var t=!1;if("#"===z){for(var e=N-1;" "===I.charAt(e)||" "===I.charAt(e);)e--;if("\n"===I.charAt(e)||""===I.charAt(e)){for(;""!=z&&"\n"!=z;)s();t=!0}}if("/"===z&&"/"===r()){for(;""!=z&&"\n"!=z;)s();t=!0}if("/"===z&&"*"===r()){for(;""!=z;){if("*"===z&&"/"===r()){s(),s();break}s()}t=!0}for(;" "===z||" "===z||"\n"===z||"\r"===z;)s()}while(t);if(""===z)return void(L=S.DELIMITER);var i=z+r();if(P[i])return L=S.DELIMITER,A=i,s(),void s();if(P[z])return L=S.DELIMITER,A=z,void s();if(a(z)||"-"===z){for(A+=z,s();a(z);)A+=z,s();return"false"===A?A=!1:"true"===A?A=!0:isNaN(Number(A))||(A=Number(A)),void(L=S.IDENTIFIER)}if('"'===z){for(s();""!=z&&('"'!=z||'"'===z&&'"'===r());)A+=z,'"'===z&&s(),s();if('"'!=z)throw x('End of string " expected');return s(),void(L=S.IDENTIFIER)}for(L=S.UNKNOWN;""!=z;)A+=z,s();throw new SyntaxError('Syntax error in part "'+k(A,30)+'"')}function f(){var t={};if(n(),p(),"strict"===A&&(t.strict=!0,p()),("graph"===A||"digraph"===A)&&(t.type=A,p()),L===S.IDENTIFIER&&(t.id=A,p()),"{"!=A)throw x("Angle bracket { expected");if(p(),m(t),"}"!=A)throw x("Angle bracket } expected");if(p(),""!==A)throw x("End of file expected");return p(),delete t.node,delete t.edge,delete t.graph,t}function m(t){for(;""!==A&&"}"!=A;)v(t),";"===A&&p()}function v(t){var e=g(t);if(e)return void w(t,e);var i=y(t);if(!i){if(L!=S.IDENTIFIER)throw x("Identifier expected");var o=A;if(p(),"="===A){if(p(),L!=S.IDENTIFIER)throw x("Identifier expected");t[o]=A,p()}else b(t,o)}}function g(t){var e=null;if("subgraph"===A&&(e={},e.type="subgraph",p(),L===S.IDENTIFIER&&(e.id=A,p())),"{"===A){if(p(),e||(e={}),e.parent=t,e.node=t.node,e.edge=t.edge,e.graph=t.graph,m(e),"}"!=A)throw x("Angle bracket } expected");p(),delete e.node,delete e.edge,delete e.graph,delete e.parent,t.subgraphs||(t.subgraphs=[]),t.subgraphs.push(e)}return e}function y(t){return"node"===A?(p(),t.node=_(),"node"):"edge"===A?(p(),t.edge=_(),"edge"):"graph"===A?(p(),t.graph=_(),"graph"):null}function b(t,e){var i={id:e},o=_();o&&(i.attr=o),l(t,i),w(t,e)}function w(t,e){for(;"->"===A||"--"===A;){var i,o=A;p();var n=g(t);if(n)i=n;else{if(L!=S.IDENTIFIER)throw x("Identifier or subgraph expected");i=A,l(t,{id:i}),p()}var s=_(),r=c(t,e,i,o,s);u(t,r),e=i}}function _(){for(var t=null;"["===A;){for(p(),t={};""!==A&&"]"!=A;){if(L!=S.IDENTIFIER)throw x("Attribute name expected");var e=A;if(p(),"="!=A)throw x("Equal sign = expected");if(p(),L!=S.IDENTIFIER)throw x("Attribute value expected");var i=A;d(t,e,i),p(),","==A&&p()}if("]"!=A)throw x("Bracket ] expected");p()}return t}function x(t){return new SyntaxError(t+', got "'+k(A,30)+'" (char '+N+")")}function k(t,e){return t.length<=e?t:t.substr(0,27)+"..."}function M(t,e,i){Array.isArray(t)?t.forEach(function(t){Array.isArray(e)?e.forEach(function(e){i(t,e)}):i(t,e)}):Array.isArray(e)?e.forEach(function(e){i(t,e)}):i(t,e)}function O(t,e,i){for(var o=e.split("."),n=o.pop(),s=t,r=0;r":!0,"--":!0},I="",N=0,z="",A="",L=S.NULL,B=/[a-zA-Z_0-9.:#]/;e.parseDOT=o,e.DOTToGraph=T},function(t,e,i){function o(t,e){var i=[],o=[],n={edges:{inheritColor:!1},nodes:{fixed:!1,parseColor:!1}};void 0!==e&&(void 0!==e.fixed&&(n.nodes.fixed=e.fixed),void 0!==e.parseColor&&(n.nodes.parseColor=e.parseColor),void 0!==e.inheritColor&&(n.edges.inheritColor=e.inheritColor));for(var s=t.edges,r=t.nodes,a=0;a Date: Thu, 28 May 2015 17:02:27 +0200 Subject: [PATCH 09/11] Bumped version number to 4.1.1-SNAPSHOT --- bower.json | 2 +- dist/vis.js | 2 +- dist/vis.min.js | 2 +- package.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/bower.json b/bower.json index 4713737b..fc4af9f6 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "vis", - "version": "4.1.0", + "version": "4.1.1-SNAPSHOT", "main": ["dist/vis.min.js", "dist/vis.min.css"], "description": "A dynamic, browser-based visualization library.", "homepage": "http://visjs.org/", diff --git a/dist/vis.js b/dist/vis.js index fa8be5bd..5330a76c 100644 --- a/dist/vis.js +++ b/dist/vis.js @@ -4,7 +4,7 @@ * * A dynamic, browser-based visualization library. * - * @version 4.1.0 + * @version 4.1.1-SNAPSHOT * @date 2015-05-28 * * @license diff --git a/dist/vis.min.js b/dist/vis.min.js index ff384416..563ea15b 100644 --- a/dist/vis.min.js +++ b/dist/vis.min.js @@ -4,7 +4,7 @@ * * A dynamic, browser-based visualization library. * - * @version 4.1.0 + * @version 4.1.1-SNAPSHOT * @date 2015-05-28 * * @license diff --git a/package.json b/package.json index 9a5741ba..4abd5125 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "vis", - "version": "4.1.0", + "version": "4.1.1-SNAPSHOT", "description": "A dynamic, browser-based visualization library.", "homepage": "http://visjs.org/", "license": "(Apache-2.0 OR MIT)", From 3e1856950b0ed323a0ed77e9639a688290836b04 Mon Sep 17 00:00:00 2001 From: Eric Gillingham Date: Thu, 28 May 2015 09:40:09 -0700 Subject: [PATCH 10/11] Tell browserify to apply babelify transform Fixes #874 See https://github.com/babel/babelify#why-arent-files-in-node_modules-being-transformed --- package.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/package.json b/package.json index 4abd5125..e6d2b990 100644 --- a/package.json +++ b/package.json @@ -52,5 +52,8 @@ "uglify-js": "^2.4.20", "webpack": "^1.8.5", "yargs": "^3.7.2" + }, + "browserify": { + "transform": ["babelify"] } } From 14a5752ea2e52fd127fd61bcef691e96e42ad259 Mon Sep 17 00:00:00 2001 From: jos Date: Fri, 29 May 2015 12:13:20 +0200 Subject: [PATCH 11/11] Replaced spdx license expression with array with identifiers for bower (see #876) --- bower.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bower.json b/bower.json index fc4af9f6..62594f91 100644 --- a/bower.json +++ b/bower.json @@ -4,7 +4,7 @@ "main": ["dist/vis.min.js", "dist/vis.min.css"], "description": "A dynamic, browser-based visualization library.", "homepage": "http://visjs.org/", - "license": "(Apache-2.0 OR MIT)", + "license": ["Apache-2.0", "MIT"], "repository": { "type": "git", "url": "git://github.com/almende/vis.git"