From ace45e6c2e61af6cda78aeaf21c7f2ed72ad21df Mon Sep 17 00:00:00 2001 From: Alex de Mulder Date: Tue, 30 Jun 2015 17:51:34 +0200 Subject: [PATCH] - Added getOptionsFromConfigurator method. --- HISTORY.md | 1 + dist/vis.js | 26867 ++++++++++++++++++----------------- docs/network/index.html | 15 +- lib/network/Network.js | 7 + lib/shared/Configurator.js | 7 +- 5 files changed, 13467 insertions(+), 13430 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index d4493ddb..cbb3e218 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -27,6 +27,7 @@ http://visjs.org - Fixed #1039, icon now returns correct distance to border - Added blurEdge and hoverEdge events. - Added labelHighlightBold option to edges and nodes. +- Added getOptionsFromConfigurator method. ### Graph2d diff --git a/dist/vis.js b/dist/vis.js index 5b662a3a..965ac949 100644 --- a/dist/vis.js +++ b/dist/vis.js @@ -84,65 +84,65 @@ return /******/ (function(modules) { // webpackBootstrap // utils 'use strict'; - exports.util = __webpack_require__(14); - exports.DOMutil = __webpack_require__(19); + exports.util = __webpack_require__(13); + exports.DOMutil = __webpack_require__(18); // data - exports.DataSet = __webpack_require__(20); - exports.DataView = __webpack_require__(22); - exports.Queue = __webpack_require__(21); + exports.DataSet = __webpack_require__(19); + exports.DataView = __webpack_require__(21); + exports.Queue = __webpack_require__(20); // Graph3d - exports.Graph3d = __webpack_require__(23); + exports.Graph3d = __webpack_require__(22); exports.graph3d = { - Camera: __webpack_require__(27), - Filter: __webpack_require__(28), - Point2d: __webpack_require__(24), - Point3d: __webpack_require__(26), - Slider: __webpack_require__(29), - StepNumber: __webpack_require__(30) + Camera: __webpack_require__(26), + Filter: __webpack_require__(27), + Point2d: __webpack_require__(23), + Point3d: __webpack_require__(25), + Slider: __webpack_require__(28), + StepNumber: __webpack_require__(29) }; // Timeline - exports.Timeline = __webpack_require__(31); - exports.Graph2d = __webpack_require__(55); + exports.Timeline = __webpack_require__(30); + exports.Graph2d = __webpack_require__(52); exports.timeline = { - DateUtil: __webpack_require__(37), - DataStep: __webpack_require__(58), - Range: __webpack_require__(35), - stack: __webpack_require__(41), - TimeStep: __webpack_require__(43), + DateUtil: __webpack_require__(36), + DataStep: __webpack_require__(55), + Range: __webpack_require__(34), + stack: __webpack_require__(40), + TimeStep: __webpack_require__(42), components: { items: { - Item: __webpack_require__(8), - BackgroundItem: __webpack_require__(46), - BoxItem: __webpack_require__(45), - PointItem: __webpack_require__(6), - RangeItem: __webpack_require__(42) + Item: __webpack_require__(6), + BackgroundItem: __webpack_require__(45), + BoxItem: __webpack_require__(44), + PointItem: __webpack_require__(2), + RangeItem: __webpack_require__(41) }, - Component: __webpack_require__(33), - CurrentTime: __webpack_require__(32), - CustomTime: __webpack_require__(50), - DataAxis: __webpack_require__(57), - GraphGroup: __webpack_require__(59), - Group: __webpack_require__(40), - BackgroundGroup: __webpack_require__(44), - ItemSet: __webpack_require__(39), - Legend: __webpack_require__(63), - LineGraph: __webpack_require__(56), - TimeAxis: __webpack_require__(47) + Component: __webpack_require__(32), + CurrentTime: __webpack_require__(31), + CustomTime: __webpack_require__(49), + DataAxis: __webpack_require__(54), + GraphGroup: __webpack_require__(56), + Group: __webpack_require__(39), + BackgroundGroup: __webpack_require__(43), + ItemSet: __webpack_require__(38), + Legend: __webpack_require__(60), + LineGraph: __webpack_require__(53), + TimeAxis: __webpack_require__(46) } }; // Network - exports.Network = __webpack_require__(65); + exports.Network = __webpack_require__(3); exports.network = { Images: __webpack_require__(112), dotparser: __webpack_require__(110), gephiParser: __webpack_require__(111), - allOptions: __webpack_require__(7) + allOptions: __webpack_require__(9) }; exports.network.convertDot = function (input) { return exports.network.dotparser.DOTToGraph(input); @@ -157,10 +157,10 @@ return /******/ (function(modules) { // webpackBootstrap }; // bundled external libraries - exports.moment = __webpack_require__(15); - exports.hammer = __webpack_require__(10); // TODO: deprecate exports.hammer some day - exports.Hammer = __webpack_require__(10); - exports.keycharm = __webpack_require__(49); + exports.moment = __webpack_require__(14); + exports.hammer = __webpack_require__(7); // TODO: deprecate exports.hammer some day + exports.Hammer = __webpack_require__(7); + exports.keycharm = __webpack_require__(48); /***/ }, /* 1 */ @@ -181,2303 +181,2048 @@ return /******/ (function(modules) { // webpackBootstrap 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); + var Item = __webpack_require__(6); - 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 _componentsNode = __webpack_require__(67); + PointItem.prototype = new Item(null, null, null); - var _componentsNode2 = _interopRequireDefault(_componentsNode); + /** + * 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__(4); + /** + * 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__(14); - var DataSet = __webpack_require__(20); - var DataView = __webpack_require__(22); + // contents box, right from the dot + dom.content = document.createElement('div'); + dom.content.className = 'vis-item-content'; + dom.point.appendChild(dom.content); - var NodesHandler = (function () { - function NodesHandler(body, images, groups, layoutEngine) { - var _this = this; + // dot at start + dom.dot = document.createElement('div'); + dom.point.appendChild(dom.dot); - _classCallCheck(this, NodesHandler); + // attach this item as attribute + dom.point['timeline-item'] = this; - this.body = body; - this.images = images; - this.groups = groups; - this.layoutEngine = layoutEngine; + this.dirty = true; + } - // create the node API in the body container - this.body.functions.createNode = 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.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); - } - }; + // 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 = { - 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, - labelHighlightBold: true, - 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); + var editable = (this.options.editable.updateTime || this.options.editable.updateGroup || this.editable === true) && this.editable !== false; - this.bindEventListeners(); - } + // update class + var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : '') + (editable ? ' vis-editable' : ' vis-readonly'); + dom.point.className = 'vis-item vis-point' + className; + dom.dot.className = 'vis-item vis-dot' + className; - _createClass(NodesHandler, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this2 = this; + // recalculate size of dot and contents + this.props.dot.width = dom.dot.offsetWidth; + this.props.dot.height = dom.dot.offsetHeight; + this.props.content.height = dom.content.offsetHeight; - // 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); + // resize contents + dom.content.style.marginLeft = 2 * this.props.dot.width + 'px'; + //dom.content.style.marginRight = ... + 'px'; // TODO: margin right - // 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(); - } - } - } + dom.dot.style.top = (this.height - this.props.dot.height) / 2 + 'px'; + dom.dot.style.left = this.props.dot.width / 2 + 'px'; - // 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(); - } - } - } + // recalculate size + this.width = dom.point.offsetWidth; + this.height = dom.point.offsetHeight; - // 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.dirty = false; + } - // update the state of the letiables if needed - if (options.hidden !== undefined || options.physics !== undefined) { - this.body.emitter.emit('_dataChanged'); - } - } + this._repaintDeleteButton(dom.point); + }; + + /** + * 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(); + } + }; + + /** + * 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: '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.displayed = false; + } + }; - var doNotEmit = arguments[1] === undefined ? false : arguments[1]; + /** + * Reposition the item horizontally + * @Override + */ + PointItem.prototype.repositionX = function () { + var start = this.conversion.toScreen(this.data.start); - var oldNodesData = this.body.data.nodes; + this.left = start - this.props.dot.width; - 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'); - } + // reposition point + this.dom.point.style.left = this.left + 'px'; + }; - if (oldNodesData) { - // unsubscribe from old dataset - util.forEach(this.nodesListeners, function (callback, event) { - oldNodesData.off(event, callback); - }); - } + /** + * Reposition the item vertically + * @Override + */ + PointItem.prototype.repositionY = function () { + var orientation = this.options.orientation.item; + var point = this.dom.point; - // remove drawn nodes - this.body.nodes = {}; + if (orientation == 'top') { + point.style.top = this.top + 'px'; + } else { + point.style.top = this.parent.height - this.top - this.height + 'px'; + } + }; - 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 the width of the item left from its start date + * @return {number} + */ + PointItem.prototype.getWidthLeft = function () { + return this.props.dot.width; + }; - // draw all new nodes - var ids = _this3.body.data.nodes.getIds(); - _this3.add(ids, true); - })(); - } + /** + * Return the width of the item right from its start date + * @return {number} + */ + PointItem.prototype.getWidthRight = function () { + return this.width - this.props.dot.width; + }; - if (doNotEmit === false) { - this.body.emitter.emit('_dataChanged'); - } - } - }, { - key: 'add', + module.exports = PointItem; - /** - * Add nodes - * @param {Number[] | String[]} ids - * @private - */ - value: function add(ids) { - var doNotEmit = arguments[1] === undefined ? false : arguments[1]; +/***/ }, +/* 3 */ +/***/ function(module, exports, __webpack_require__) { - 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 - } + // Load custom shapes into CanvasRenderingContext2D + 'use strict'; - this.layoutEngine.positionInitially(newNodes); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - if (doNotEmit === false) { - this.body.emitter.emit('_dataChanged'); - } - } - }, { - key: 'update', + var _modulesGroups = __webpack_require__(61); - /** - * 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(data); - nodes[id] = node; - } - } - if (dataChanged === true) { - this.body.emitter.emit('_dataChanged'); - } else { - this.body.emitter.emit('_dataUpdated'); - } - } - }, { - key: 'remove', + var _modulesGroups2 = _interopRequireDefault(_modulesGroups); - /** - * 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; + var _modulesNodesHandler = __webpack_require__(62); - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; - delete nodes[id]; - } + var _modulesNodesHandler2 = _interopRequireDefault(_modulesNodesHandler); - this.body.emitter.emit('_dataChanged'); - } - }, { - key: 'create', + var _modulesEdgesHandler = __webpack_require__(82); - /** - * create a node - * @param properties - * @param constructorClass - */ - value: function create(properties) { - var constructorClass = arguments[1] === undefined ? _componentsNode2['default'] : arguments[1]; + var _modulesEdgesHandler2 = _interopRequireDefault(_modulesEdgesHandler); - 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', + var _modulesPhysicsEngine = __webpack_require__(89); - /** - * 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', + var _modulesPhysicsEngine2 = _interopRequireDefault(_modulesPhysicsEngine); - /** - * Load the XY positions of the nodes into the dataset. - */ - value: function storePositions() { - // todo: add support for clusters and hierarchical. - var dataArray = []; - var dataset = this.body.data.nodes.getDataSet(); + var _modulesClustering = __webpack_require__(98); - for (var nodeId in dataset._data) { - if (dataset._data.hasOwnProperty(nodeId)) { - var node = this.body.nodes[nodeId]; - if (dataset._data[nodeId].x != Math.round(node.x) || dataset._data[nodeId].y != Math.round(node.y)) { - dataArray.push({ id: nodeId, x: Math.round(node.x), y: Math.round(node.y) }); - } - } - } - dataset.update(dataArray); - } - }, { - key: 'getBoundingBox', + var _modulesClustering2 = _interopRequireDefault(_modulesClustering); - /** - * 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', + var _modulesCanvasRenderer = __webpack_require__(100); - /** - * 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', + var _modulesCanvasRenderer2 = _interopRequireDefault(_modulesCanvasRenderer); - /** - * 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; - } - }]); + var _modulesCanvas = __webpack_require__(101); - return NodesHandler; - })(); + var _modulesCanvas2 = _interopRequireDefault(_modulesCanvas); - exports['default'] = NodesHandler; - module.exports = exports['default']; + var _modulesView = __webpack_require__(102); -/***/ }, -/* 3 */ -/***/ function(module, exports, __webpack_require__) { + var _modulesView2 = _interopRequireDefault(_modulesView); - 'use strict'; + var _modulesInteractionHandler = __webpack_require__(103); - Object.defineProperty(exports, '__esModule', { - value: true - }); + var _modulesInteractionHandler2 = _interopRequireDefault(_modulesInteractionHandler); - 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 _modulesSelectionHandler = __webpack_require__(106); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var _modulesSelectionHandler2 = _interopRequireDefault(_modulesSelectionHandler); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + var _modulesLayoutEngine = __webpack_require__(107); - var _sharedLabel = __webpack_require__(4); + var _modulesLayoutEngine2 = _interopRequireDefault(_modulesLayoutEngine); - var _sharedLabel2 = _interopRequireDefault(_sharedLabel); + var _modulesManipulationSystem = __webpack_require__(108); - var _edgesBezierEdgeDynamic = __webpack_require__(85); + var _modulesManipulationSystem2 = _interopRequireDefault(_modulesManipulationSystem); - var _edgesBezierEdgeDynamic2 = _interopRequireDefault(_edgesBezierEdgeDynamic); + var _sharedConfigurator = __webpack_require__(4); - var _edgesBezierEdgeStatic = __webpack_require__(88); + var _sharedConfigurator2 = _interopRequireDefault(_sharedConfigurator); - var _edgesBezierEdgeStatic2 = _interopRequireDefault(_edgesBezierEdgeStatic); + var _sharedValidator = __webpack_require__(51); - var _edgesStraightEdge = __webpack_require__(89); + var _sharedValidator2 = _interopRequireDefault(_sharedValidator); - var _edgesStraightEdge2 = _interopRequireDefault(_edgesStraightEdge); + var _optionsJs = __webpack_require__(9); - var util = __webpack_require__(14); + __webpack_require__(109); + + var Emitter = __webpack_require__(24); + var Hammer = __webpack_require__(7); + var util = __webpack_require__(13); + var DataSet = __webpack_require__(19); + var DataView = __webpack_require__(21); + var dotparser = __webpack_require__(110); + var gephiParser = __webpack_require__(111); + var Images = __webpack_require__(112); + var Activator = __webpack_require__(47); + var locales = __webpack_require__(113); /** - * @class Edge + * @constructor Network + * Create a network visualization, displaying nodes and edges. * - * 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 + * @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; - var Edge = (function () { - function Edge(options, body, globalOptions) { - _classCallCheck(this, Edge); + if (!(this instanceof Network)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } - if (body === undefined) { - throw 'No body provided'; - } - this.options = util.bridgeObject(globalOptions); - this.body = body; + // set constant values + this.options = {}; + this.defaultOptions = { + locale: 'en', + locales: locales, + clickToUse: false + }; + util.extend(this.options, this.defaultOptions); - // initialize variables - this.id = undefined; - this.fromId = undefined; - this.toId = undefined; - this.selected = false; - this.hover = false; - this.labelDirty = true; - this.colorDirty = true; + // containers for nodes and edges + this.body = { + container: container, + nodes: {}, + nodeIndices: [], + edges: {}, + edgeIndices: [], + 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() {} + }, + data: { + nodes: null, // A DataSet or DataView + edges: null // A DataSet or DataView + }, + functions: { + createNode: function createNode() {}, + createEdge: function createEdge() {}, + getPointer: function getPointer() {} + }, + view: { + scale: 1, + translation: { x: 0, y: 0 } + } + }; - this.baseWidth = this.options.width; - this.baseFontSize = this.options.font.size; + // bind the event listeners + this.bindEventListeners(); - this.from = undefined; // a node - this.to = undefined; // a node + // 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.edgeType = undefined; + 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 - this.connected = false; + // create the DOM elements + this.canvas._create(); - this.labelModule = new _sharedLabel2['default'](this.body, this.options); + // apply options + this.setOptions(options); - this.setOptions(options); - } + // load data (the disable start variable will be the same as the enabled clustering) + this.setData(data); + } - _createClass(Edge, [{ - key: 'setOptions', + // Extend Network with an Emitter mixin + Emitter(Network.prototype); - /** - * 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; + /** + * Set options + * @param {Object} options + */ + Network.prototype.setOptions = function (options) { + var _this2 = this; - Edge.parseOptions(this.options, options, true); + if (options !== undefined) { - if (options.id !== undefined) { - this.id = options.id; - } - if (options.from !== undefined) { - this.fromId = options.from; - } - if (options.to !== undefined) { - this.toId = options.to; - } - if (options.title !== undefined) { - this.title = options.title; - } - if (options.value !== undefined) { - options.value = parseFloat(options.value); - } + var errorFound = _sharedValidator2['default'].validate(options, _optionsJs.allOptions); + if (errorFound === true) { + console.log('%cErrors have been found in the supplied options object.', _sharedValidator.printStyle); + } - // update label Module - this.updateLabelModule(); + // copy the global fields over + var fields = ['locale', 'locales', 'clickToUse']; + util.selectiveDeepExtend(fields, this.options, options); - var dataChanged = this.updateEdgeType(); + // 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); - // if anything has been updates, reset the selection width and the hover width - this._setInteractionWidths(); + this.canvas.setOptions(options); // options for canvas are in globals - // A node is connected when it has a from and to node that both exist in the network.body.nodes. - this.connect(); + // 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 - if (options.hidden !== undefined || options.physics !== undefined) { - dataChanged = true; - } + 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 - return dataChanged; + // 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'); } - }, { - key: 'updateLabelModule', + // these two do not have options at the moment, here for completeness + //this.view.setOptions(options.view); + //this.clustering.setOptions(options.clustering); - /** - * 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; + if ('configure' in options) { + if (!this.configurator) { + this.configurator = new _sharedConfigurator2['default'](this, this.body.container, _optionsJs.configureOptions, this.canvas.pixelRatio); } - } - }, { - 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; - } + this.configurator.setOptions(options.configure); + } - if (changeInType === true) { - dataChanged = this.edgeType.cleanup(); - } - } + // if the configuration system is enabled, copy all options and put them into the config system + if (this.configurator && 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 render default options in to the interaction group + util.deepExtend(networkOptions.interaction, this.selectionHandler.options); + util.deepExtend(networkOptions.interaction, this.renderer.options); - 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); - } + util.deepExtend(networkOptions.interaction, this.interactionHandler.options); + util.deepExtend(networkOptions.manipulation, this.manipulation.options); + util.deepExtend(networkOptions.physics, this.physics.options); - return dataChanged; - } - }, { - key: 'togglePhysics', + // load globals into the global object + util.deepExtend(networkOptions.global, this.canvas.options); + util.deepExtend(networkOptions.global, this.options); - /** - * Enable or disable the physics. - * @param status - */ - value: function togglePhysics(status) { - this.options.physics = status; - this.edgeType.togglePhysics(status); + this.configurator.setModuleOptions(networkOptions); } - }, { - key: 'connect', - - /** - * Connect an edge to its nodes - */ - value: function connect() { - this.disconnect(); - - this.from = this.body.nodes[this.fromId] || undefined; - this.to = this.body.nodes[this.toId] || undefined; - this.connected = this.from !== undefined && this.to !== undefined; - if (this.connected === true) { - this.from.attachEdge(this); - this.to.attachEdge(this); - } else { - if (this.from) { - this.from.detachEdge(this); + // 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'); + }); } - if (this.to) { - this.to.detachEdge(this); + } else { + if (this.activator !== undefined) { + this.activator.destroy(); + delete this.activator; } + this.body.emitter.emit('activate'); } - - this.edgeType.connect(); + } else { + this.body.emitter.emit('activate'); } - }, { - key: 'disconnect', - /** - * 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; - } + this.canvas.setSize(); + // start the physics simulation. Can be safely called multiple times. + this.body.emitter.emit('startSimulation'); + } + }; - this.connected = false; - } - }, { - key: 'getTitle', + /** + * 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 = []; - /** - * 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; + for (var nodeId in nodes) { + if (nodes.hasOwnProperty(nodeId)) { + if (nodes[nodeId].options.hidden === false) { + this.body.nodeIndices.push(nodeId); + } } - }, { - key: 'isSelected', + } - /** - * check if this node is selecte - * @return {boolean} selected True if node is selected, else false - */ - value: function isSelected() { - return this.selected; + for (var edgeId in edges) { + if (edges.hasOwnProperty(edgeId)) { + if (edges[edgeId].options.hidden === false) { + this.body.edgeIndices.push(edgeId); + } } - }, { - key: 'getValue', + } + }; - /** - * Retrieve the value of the edge. Can be undefined - * @return {Number} value - */ - value: function getValue() { - return this.options.value; - } - }, { - key: 'setValueRange', + /** + * Bind all events + */ + Network.prototype.bindEventListeners = function () { + var _this3 = this; - /** - * 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 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(); + _this3.body.emitter.emit('_requestRedraw'); + // call the dataUpdated event because the only difference between the two is the updating of the indices + _this3.body.emitter.emit('_dataUpdated'); + }); - 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 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'); + _this3.body.emitter.emit('_requestRedraw'); + }); + }; - 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; + /** + * 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; + + 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; } } - }, { - key: 'draw', + } - /** - * 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); + // 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); } } - }, { - 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) { - this.labelModule.pointToSelf = false; - 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); - } + /** + * Returns true when the Network is active. + * @returns {boolean} + */ + Network.prototype.isActive = function () { + return !this.activator || this.activator.active; + }; - // draw the label - this.labelModule.draw(ctx, point.x, point.y, selected); - ctx.restore(); - } else { - // Ignore the orientations. - this.labelModule.pointToSelf = true; - var x, y; - var radius = this.options.selfReferenceSize; - if (node1.shape.width > node1.shape.height) { - x = node1.x + node1.shape.width * 0.5; - y = node1.y - radius; - } else { - x = node1.x + radius; - y = node1.y - node1.shape.height * 0.5; - } - point = this._pointOnCircle(x, y, radius, 0.125); - this.labelModule.draw(ctx, point.x, point.y, selected); - } - } - } - }, { - key: 'isOverlappingWith', + 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.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); + }; + Network.prototype.getOptionsFromConfigurator = function () { + var options = {}; + if (this.configurator) { + options = this.configurator.getOptions.apply(this.configurator); + } + return options; + }; - /** - * 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; + module.exports = Network; - var dist = this.edgeType.getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj); +/***/ }, +/* 4 */ +/***/ function(module, exports, __webpack_require__) { - return dist < distMax; - } else { - return false; - } - } - }, { - key: '_rotateForLabelAlignment', + 'use strict'; - /** - * 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); + Object.defineProperty(exports, '__esModule', { + value: true + }); - // rotate so label it is readable - if (angleInDegrees < -1 && dx < 0 || angleInDegrees > 0 && dx < 0) { - angleInDegrees = angleInDegrees + 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; }; })(); - ctx.rotate(angleInDegrees); - } - }, { - key: '_pointOnCircle', + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - /** - * 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]; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var fields = ['id', 'from', 'hidden', 'hoverWidth', 'label', 'labelHighlightBold', 'length', 'line', 'opacity', 'physics', 'selectionWidth', 'selfReferenceSize', 'to', 'title', 'value', 'width']; + var _ColorPicker = __webpack_require__(50); - // only deep extend the items in the field array. These do not have shorthand. - util.selectiveDeepExtend(fields, parentOptions, newOptions, allowDeletion); + var _ColorPicker2 = _interopRequireDefault(_ColorPicker); - util.mergeOptions(parentOptions, newOptions, 'smooth'); - util.mergeOptions(parentOptions, newOptions, 'shadow'); + var util = __webpack_require__(13); - if (newOptions.dashes !== undefined && newOptions.dashes !== null) { - parentOptions.dashes = newOptions.dashes; - } else if (allowDeletion === true && newOptions.dashes === null) { - parentOptions.dashes = undefined; - delete parentOptions.dashes; - } + /** + * 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 + */ - // 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; - } + var Configurator = (function () { + function Configurator(parentModule, defaultContainer, configureOptions) { + var pixelRatio = arguments[3] === undefined ? 1 : arguments[3]; - // 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; - } + _classCallCheck(this, Configurator); - // 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; + this.parent = parentModule; + this.changedOptions = []; + this.container = defaultContainer; + this.allowCreation = false; + + 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', + + /** + * 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 (newOptions.color.inherit !== undefined) { - parentOptions.color.inherit = newOptions.color.inherit; + if (options.filter !== undefined) { + this.options.filter = options.filter; } - if (newOptions.color.opacity !== undefined) { - parentOptions.color.opacity = Math.min(1, Math.max(0, newOptions.color.opacity)); + if (options.showButton !== undefined) { + this.options.showButton = options.showButton; } - - if (newOptions.color.inherit === undefined && colorsDefined === true) { - parentOptions.color.inherit = false; + if (options.enabled !== undefined) { + enabled = options.enabled; } + } else if (typeof options === 'boolean') { + this.options.filter = true; + enabled = options; + } else if (typeof options === 'function') { + this.options.filter = options; + enabled = true; + } + if (this.options.filter === false) { + enabled = false; } - } 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); + this.options.enabled = enabled; } + this._clean(); } - }]); - - return Edge; - })(); - - exports['default'] = Edge; - module.exports = exports['default']; - -/***/ }, -/* 4 */ -/***/ 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'); } } - - var util = __webpack_require__(14); - - var Label = (function () { - function Label(body, options) { - _classCallCheck(this, Label); + }, { + 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', - this.body = body; + /** + * Create all DOM elements + * @private + */ + value: function _create() { + var _this = this; - this.pointToSelf = false; - this.baseSize = undefined; - this.setOptions(options); - this.size = { top: 0, left: 0, width: 0, height: 0, yLine: 0 }; // could be cached - } + this._clean(); + this.changedOptions = []; - _createClass(Label, [{ - key: 'setOptions', - value: function setOptions(options) { - var allowDeletion = arguments[1] === undefined ? false : arguments[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; + } - this.options = options; + if (show !== false) { + this.allowCreation = true; - if (options.label !== undefined) { - this.labelDirty = true; - } + // linebreak between categories + if (counter > 0) { + this._makeItem([]); + } + // a header for the category + this._makeHeader(option); - 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; + // get the suboptions + this._handleObject(this.configureOptions[option], [option]); } + counter++; } } - } - }, { - 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; + 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'; + }; - // 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; + _this.optionsContainer = document.createElement('div'); + _this.optionsContainer.className = 'vis-network-configuration vis-option-container'; - // update the size cache if required - this.calculateLabelSize(ctx, selected, x, y, baseline); + _this.domElements.push(_this.optionsContainer); + _this.domElements.push(generateButton); + })(); + } - // create the fontfill background - this._drawBackground(ctx); - // draw text - this._drawText(ctx, selected, x, y, baseline); + this._push(); + this.colorPicker.insertTo(this.container); } }, { - key: '_drawBackground', + key: '_push', /** - * Draws the label background - * @param {CanvasRenderingContext2D} ctx + * draw all DOM elements on the screen * @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; - } + 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: '_drawText', + key: '_clean', /** - * - * @param ctx - * @param x - * @param baseline + * delete all DOM elements * @private */ - value: function _drawText(ctx, selected, x, y) { - var baseline = arguments[4] === undefined ? 'middle' : arguments[4]; - - 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; - } - - var yLine = this.size.yLine; - - var _getColor2 = this._getColor(viewFontSize); - - var _getColor22 = _slicedToArray(_getColor2, 2); - - var fontColor = _getColor22[0]; - var strokeColor = _getColor22[1]; - - var _setAlignment2 = this._setAlignment(ctx, x, yLine, baseline); - - var _setAlignment22 = _slicedToArray(_setAlignment2, 2); - - x = _setAlignment22[0]; - yLine = _setAlignment22[1]; - - // configure context for drawing the text - ctx.font = (selected && this.options.labelHighlightBold ? 'bold ' : '') + fontSize + 'px ' + this.options.font.face; - ctx.fillStyle = fontColor; - ctx.textAlign = 'center'; - - // set the strokeWidth - if (this.options.font.strokeWidth > 0) { - ctx.lineWidth = this.options.font.strokeWidth; - ctx.strokeStyle = strokeColor; - ctx.lineJoin = 'round'; + value: function _clean() { + for (var i = 0; i < this.domElements.length; i++) { + this.wrapper.removeChild(this.domElements[i]); } - // 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; + if (this.wrapper !== undefined) { + this.container.removeChild(this.wrapper); + this.wrapper = undefined; } + this.domElements = []; } }, { - 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' && this.pointToSelf === false) { - x = 0; - yLine = 0; + key: '_getValue', - 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 + /** + * 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 { - ctx.textBaseline = 'middle'; + base = undefined; + break; } - } else { - ctx.textBaseline = baseline; } - - return [x, yLine]; + return base; } }, { - key: '_getColor', + key: '_makeItem', /** - * 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 {*[]} + * all option elements are wrapped in an item + * @param path + * @param domElements * @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); + value: function _makeItem(path) { + var _this2 = this; + + 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); + })(); } - return [fontColor, strokeColor]; } }, { - key: 'getTextSize', + key: '_makeHeader', /** - * - * @param ctx - * @param selected - * @returns {{width: number, height: number}} + * header for major subjects + * @param name + * @private */ - 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; + value: function _makeHeader(name) { + var div = document.createElement('div'); + div.className = 'vis-network-configuration header'; + div.innerHTML = name; + this._makeItem([], div); } }, { - key: 'calculateLabelSize', + key: '_makeLabel', /** - * - * @param ctx - * @param selected - * @param x - * @param y - * @param baseline + * make a label, if it is an object label, it gets different styling. + * @param name + * @param path + * @param objectLabel + * @returns {HTMLElement} + * @private */ - 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]; + value: function _makeLabel(name, path) { + var objectLabel = arguments[2] === undefined ? false : arguments[2]; - 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 + var div = document.createElement('div'); + div.className = 'vis-network-configuration label s' + path.length; + if (objectLabel === true) { + div.innerHTML = '' + name + ':'; + } else { + div.innerHTML = name + ':'; } - - this.labelDirty = false; + return div; } }, { - key: '_processLabel', + key: '_makeDropdown', /** - * This calculates the width as well as explodes the label string and calculates the amount of lines. - * @param ctx - * @param selected - * @returns {number} + * make a dropdown list for multiple possible string optoins + * @param arr + * @param value + * @param path * @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 && this.options.labelHighlightBold ? '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; + 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.lines = lines; - this.lineCount = lineCount; - return width; - } - }], [{ - key: 'parseOptions', - value: function parseOptions(parentOptions, newOptions) { - var allowDeletion = arguments[2] === undefined ? false : arguments[2]; + 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); + } - 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 Label; - })(); - - exports['default'] = Label; - module.exports = exports['default']; - -/***/ }, -/* 5 */ -/***/ 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 Node = __webpack_require__(67); - var Edge = __webpack_require__(3); - var util = __webpack_require__(14); - - var SelectionHandler = (function () { - function SelectionHandler(body, canvas) { - var _this = this; - - _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); - - this.body.emitter.on("_dataChanged", function () { - _this.updateSelection(); - }); - } + var me = this; + select.onchange = function () { + me._update(this.value, path); + }; - _createClass(SelectionHandler, [{ - key: "setOptions", - value: function setOptions(options) { - if (options !== undefined) { - var fields = ["multiselect", "hoverConnectedEdges", "selectable", "selectConnectedEdges"]; - util.selectiveDeepExtend(fields, this.options, options); - } + var label = this._makeLabel(path[path.length - 1], path); + this._makeItem(path, label, select); } }, { - key: "selectOnPoint", + key: '_makeRange', /** - * handles the selection part of the tap; - * - * @param {Object} pointer + * make a range object for numeric options + * @param arr + * @param value + * @param path * @private */ - value: function selectOnPoint(pointer) { - var selected = false; - if (this.options.selectable === true) { - var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer); - - // unselect after getting the objects in order to restore width and height. - this.unselectAll(); + value: function _makeRange(arr, value, path) { + var defaultValue = arr[0]; + var min = arr[1]; + var max = arr[2]; + var step = arr[3]; + var range = document.createElement('input'); + range.className = 'vis-network-configuration range'; + try { + range.type = 'range'; // not supported on IE9 + range.min = min; + range.max = max; + } catch (err) {} + range.step = step; - if (obj !== undefined) { - selected = this.selectObject(obj); + if (value !== undefined) { + if (value < 0 && value * 2 < min) { + range.min = value * 2; + } else if (value * 0.1 < min) { + range.min = value / 10; } - 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); - } - - this.body.emitter.emit("_requestRedraw"); + if (value * 2 > max && max !== 1) { + range.max = value * 2; } - } - return selectionChanged; - } - }, { - key: "_generateClickEvent", - value: function _generateClickEvent(eventType, event, pointer, oldSelection) { - var emptySelection = arguments[4] === undefined ? false : arguments[4]; - - var properties = undefined; - if (emptySelection === true) { - properties = { nodes: [], edges: [] }; + range.value = value; } else { - properties = this.getSelection(); + range.value = defaultValue; } - 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]; + var input = document.createElement('input'); + input.className = 'vis-network-configuration rangeinput'; + input.value = range.value; - 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); - } + 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: "_getAllNodesOverlappingWith", + key: '_makeCheckbox', /** - * 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 + * make a checkbox for boolean options. + * @param defaultValue + * @param value + * @param path * @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); + 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 }); + } } } - return overlappingNodes; + + 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: "_pointerToPositionObject", + key: '_makeTextInput', /** - * Return a position object in canvasspace from a single point in screenspace - * - * @param pointer - * @returns {{left: number, top: number, right: number, bottom: number}} + * make a text input field for string options. + * @param defaultValue + * @param value + * @param path * @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 + 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: "getNodeAt", + key: '_makeColorField', /** - * Get the top node at the a specific point (like a click) - * - * @param {{x: Number, y: Number}} pointer - * @return {Node | undefined} node + * make a color field with a color picker for color fields + * @param arr + * @param value + * @param path * @private */ - value: function getNodeAt(pointer) { - var returnNode = arguments[1] === undefined ? true : arguments[1]; + value: function _makeColorField(arr, value, path) { + var _this3 = this; - // 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]; - } + 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; } else { - return undefined; + div.className = 'vis-network-configuration colorBlock none'; } - } - }, { - 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); - } - } + 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: "_getAllEdgesOverlappingWith", + key: '_showColorPicker', /** - * 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 + * used by the color buttons to call the color picker. + * @param event + * @param value + * @param div + * @param path * @private */ - value: function _getAllEdgesOverlappingWith(object) { - var overlappingEdges = []; - this._getEdgesOverlappingWith(object, overlappingEdges); - return overlappingEdges; + 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: "getEdgeAt", + key: '_handleObject', /** - * 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} + * parse an object and draw the correct items + * @param obj + * @param path * @private */ - value: function getEdgeAt(pointer) { - var returnEdge = arguments[1] === undefined ? true : arguments[1]; + value: function _handleObject(obj) { + var path = arguments[1] === undefined ? [] : arguments[1]; + var checkOnly = arguments[2] === undefined ? false : arguments[2]; - var positionObject = this._pointerToPositionObject(pointer); - var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject); + 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 (overlappingEdges.length > 0) { - if (returnEdge === true) { - return this.body.edges[overlappingEdges[overlappingEdges.length - 1]]; - } else { - return overlappingEdges[overlappingEdges.length - 1]; + // if needed we must go deeper into the object. + if (show === false) { + if (!(item instanceof Array) && typeof item !== 'string' && typeof item !== 'boolean' && item instanceof Object) { + this.allowCreation = false; + show = this._handleObject(item, newPath, true); + this.allowCreation = checkOnly === false; + } + } + } + + if (show !== false) { + visibleInSet = true; + var value = this._getValue(newPath); + + if (item instanceof Array) { + this._handleArray(item, value, newPath); + } else if (typeof item === 'string') { + this._makeTextInput(item, value, newPath); + } else if (typeof item === 'boolean') { + this._makeCheckbox(item, value, newPath); + } else if (item instanceof Object) { + // collapse the physics options that are not enabled + var draw = true; + if (path.indexOf('physics') !== -1) { + if (this.moduleOptions.physics.solver !== subObj) { + draw = false; + } + } + + if (draw === true) { + // initially collapse options with an disabled enabled option. + if (item.enabled !== undefined) { + var enabledPath = util.copyAndExtendArray(newPath, 'enabled'); + var enabledValue = this._getValue(enabledPath); + if (enabledValue === true) { + var label = this._makeLabel(subObj, newPath, true); + this._makeItem(newPath, label); + visibleInSet = this._handleObject(item, newPath) || visibleInSet; + } else { + this._makeCheckbox(item, enabledValue, newPath); + } + } else { + var label = this._makeLabel(subObj, newPath, true); + this._makeItem(newPath, label); + visibleInSet = this._handleObject(item, newPath) || visibleInSet; + } + } + } else { + console.error('dont know how to handle', item, subObj, newPath); + } + } } - } else { - return undefined; } + return visibleInSet; } }, { - key: "_addToSelection", + key: '_handleArray', /** - * Add object to the selection array. - * - * @param obj + * handle the array type of option + * @param optionName + * @param arr + * @param value + * @param path * @private */ - value: function _addToSelection(obj) { - if (obj instanceof Node) { - this.selectionObj.nodes[obj.id] = obj; - } else { - this.selectionObj.edges[obj.id] = obj; + 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: "_addToHover", + key: '_update', /** - * Add object to the selection array. - * - * @param obj + * called to update the network with the new settings. + * @param value + * @param path * @private */ - value: function _addToHover(obj) { - if (obj instanceof Node) { - this.hoverObj.nodes[obj.id] = obj; - } else { - this.hoverObj.edges[obj.id] = obj; - } + value: function _update(value, path) { + var options = this._constructOptions(value, path); + this.parent.setOptions(options); } }, { - key: "_removeFromSelection", + key: '_constructOptions', + value: function _constructOptions(value, path) { + var optionsObj = arguments[2] === undefined ? {} : arguments[2]; - /** - * 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 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: "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: '_printOptions', + value: function _printOptions() { + var options = this.getOptions(); + this.optionsContainer.innerHTML = '
var options = ' + JSON.stringify(options, null, 2) + '
'; } }, { - 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; - } + key: 'getOptions', + value: function getOptions() { + var options = {}; + for (var i = 0; i < this.changedOptions.length; i++) { + this._constructOptions(this.changedOptions[i].value, this.changedOptions[i].path, options); } - return count; + return options; } - }, { - 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 Configurator; + })(); - /** - * 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", + exports['default'] = Configurator; + module.exports = exports['default']; - /** - * 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", +/***/ }, +/* 5 */ +/***/ function(module, exports, __webpack_require__) { - /** - * 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", + /** + * 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'; - /** - * 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", + 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 any = 'any'; - /** - * 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", + var allOptions = { + configure: { + enabled: { boolean: boolean }, + filter: { boolean: boolean, 'function': 'function' }, + container: { dom: dom }, + __type__: { object: object, boolean: boolean, 'function': 'function' } + }, - /** - * 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: "_hoverConnectedEdges", + //globals : + align: { string: string }, + autoResize: { boolean: boolean }, + clickToUse: { boolean: boolean }, + dataAttributes: { string: string, array: array }, + editable: { + add: { boolean: boolean, 'undefined': 'undefined' }, + remove: { boolean: boolean, 'undefined': 'undefined' }, + updateGroup: { boolean: boolean, 'undefined': 'undefined' }, + updateTime: { boolean: boolean, 'undefined': 'undefined' }, + __type__: { boolean: boolean, object: object } + }, + end: { number: number, date: date, string: string, moment: moment }, + format: { + minorLabels: { + millisecond: { string: string, 'undefined': 'undefined' }, + second: { string: string, 'undefined': 'undefined' }, + minute: { string: string, 'undefined': 'undefined' }, + hour: { string: string, 'undefined': 'undefined' }, + weekday: { string: string, 'undefined': 'undefined' }, + day: { string: string, 'undefined': 'undefined' }, + month: { string: string, 'undefined': 'undefined' }, + year: { string: string, 'undefined': 'undefined' }, + __type__: { object: object } + }, + majorLabels: { + millisecond: { string: string, 'undefined': 'undefined' }, + second: { string: string, 'undefined': 'undefined' }, + minute: { string: string, 'undefined': 'undefined' }, + hour: { string: string, 'undefined': 'undefined' }, + weekday: { string: string, 'undefined': 'undefined' }, + day: { string: string, 'undefined': 'undefined' }, + month: { string: string, 'undefined': 'undefined' }, + year: { string: string, 'undefined': 'undefined' }, + __type__: { object: object } + }, + __type__: { object: object } + }, + groupOrder: { string: string, 'function': 'function' }, + height: { string: string, number: number }, + hiddenDates: { object: object, array: array }, + locale: { string: string }, + locales: { + __any__: { any: any }, + __type__: { object: object } + }, + margin: { + axis: { number: number }, + item: { + horizontal: { number: number, 'undefined': 'undefined' }, + vertical: { number: number, 'undefined': 'undefined' }, + __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: { 'function': 'function' }, + onUpdate: { 'function': 'function' }, + onMove: { 'function': 'function' }, + onMoving: { 'function': 'function' }, + onRemove: { 'function': 'function' }, + order: { 'function': 'function' }, + orientation: { + axis: { string: string, 'undefined': 'undefined' }, + item: { string: string, 'undefined': 'undefined' }, + __type__: { string: string, object: object } + }, + selectable: { boolean: boolean }, + showCurrentTime: { boolean: boolean }, + showMajorLabels: { boolean: boolean }, + showMinorLabels: { boolean: boolean }, + stack: { boolean: boolean }, + snap: { 'function': 'function', 'null': 'null' }, + start: { date: date, number: number, string: string, moment: moment }, + template: { 'function': 'function' }, + timeAxis: { + scale: { string: string, 'undefined': 'undefined' }, + step: { number: number, 'undefined': 'undefined' }, + __type__: { object: object } + }, + type: { string: string }, + width: { string: string, number: number }, + zoomable: { boolean: boolean }, + zoomMax: { number: number }, + zoomMin: { number: number }, - /** - * 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", + __type__: { object: object } + }; - /** - * 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); + 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: '' } - } - }, { - 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; - if (object instanceof Node) { - this.body.emitter.emit("blurNode", { node: object.id }); - } else { - this.body.emitter.emit("blurEdge", { edge: object.id }); - } + //groupOrder: {string, 'function': 'function'}, + height: '', + //hiddenDates: {object, array}, + locale: '', + margin: { + axis: [20, 0, 100, 1], + item: { + horizontal: [10, 0, 100, 1], + vertical: [10, 0, 100, 1] } - } - }, { - key: "hoverObject", + }, + max: '', + maxHeight: '', + min: '', + minHeight: '', + moveable: false, + multiselect: false, + //onAdd: {'function': 'function'}, + //onUpdate: {'function': 'function'}, + //onMove: {'function': 'function'}, + //onMoving: {'function': 'function'}, + //onRename: {'function': 'function'}, + //order: {'function': 'function'}, + orientation: { + axis: ['both', 'bottom', 'top'], + item: ['bottom', 'top'] + }, + selectable: true, + showCurrentTime: false, + showMajorLabels: true, + showMinorLabels: true, + stack: true, + //snap: {'function': 'function', nada}, + start: '', + //template: {'function': 'function'}, + //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 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]; - } - } - } + exports.allOptions = allOptions; + exports.configureOptions = configureOptions; - // 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]; - } - } +/***/ }, +/* 6 */ +/***/ 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 }); - } else { - this.body.emitter.emit("hoverEdge", { edge: object.id }); - } - } - if (object instanceof Node && this.options.hoverConnectedEdges === true) { - this._hoverConnectedEdges(object); - } - } + 'use strict'; - if (hoverChanged === true) { - this.body.emitter.emit("_requestRedraw"); - } - } - }, { - key: "getSelection", + var Hammer = __webpack_require__(7); + var util = __webpack_require__(13); - /** - * - * 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", + /** + * @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 || {}; - /** - * - * 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", - - /** - * - * 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", - - /** - * 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]; - - var i = undefined, - id = undefined; - - if (!selection || selection.length === undefined) throw "Selection must be an array with ids"; - - // first unselect any selected node - this.unselectAll(); - - for (i = 0; i < selection.length; i++) { - id = selection[i]; - - 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", - - /** - * 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; - - if (!selection || selection.length === undefined) throw "Selection must be an array with ids"; - - // first unselect any selected objects - this.unselectAll(); + this.selected = false; + this.displayed = false; + this.dirty = true; - for (i = 0; i < selection.length; i++) { - id = selection[i]; + this.top = null; + this.left = null; + this.width = null; + this.height = null; - 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", + this.editable = null; + if (this.data && this.data.hasOwnProperty('editable') && typeof this.data.editable === 'boolean') { + this.editable = data.editable; + } + } - /** - * 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]; - } - } - } - } - }]); + Item.prototype.stack = true; - return SelectionHandler; - })(); + /** + * Select current item + */ + Item.prototype.select = function () { + this.selected = true; + this.dirty = true; + if (this.displayed) this.redraw(); + }; - exports["default"] = SelectionHandler; - module.exports = exports["default"]; + /** + * Unselect current item + */ + Item.prototype.unselect = function () { + this.selected = false; + this.dirty = true; + if (this.displayed) this.redraw(); + }; -/***/ }, -/* 6 */ -/***/ function(module, exports, __webpack_require__) { + /** + * 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); + } - 'use strict'; + if (data.hasOwnProperty('editable') && typeof data.editable === 'boolean') { + this.editable = data.editable; + } - var Item = __webpack_require__(8); + this.data = data; + this.dirty = true; + if (this.displayed) this.redraw(); + }; /** - * @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 + * Set a parent for the item + * @param {ItemSet | Group} parent */ - function PointItem(data, conversion, options) { - this.props = { - dot: { - top: 0, - width: 0, - height: 0 - }, - content: { - height: 0, - marginLeft: 0 - } - }; - - // validate data - if (data) { - if (data.start == undefined) { - throw new Error('Property "start" missing in item ' + data); + Item.prototype.setParent = function (parent) { + if (this.displayed) { + this.hide(); + this.parent = parent; + if (this.parent) { + this.show(); } + } else { + this.parent = parent; } - - Item.call(this, data, conversion, options); - } - - PointItem.prototype = new Item(null, null, null); + }; /** * 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; + Item.prototype.isVisible = function (range) { + // Should be implemented by Item implementations + return false; }; /** - * Repaint the item + * Show the Item in the DOM (when not already visible) + * @return {Boolean} changed */ - PointItem.prototype.redraw = function () { - var dom = this.dom; - if (!dom) { - // create DOM - this.dom = {}; - dom = this.dom; - - // background box - dom.point = document.createElement('div'); - // className is updated in redraw() - - // contents box, right from the dot - dom.content = document.createElement('div'); - dom.content.className = 'vis-item-content'; - dom.point.appendChild(dom.content); + Item.prototype.show = function () { + return false; + }; - // dot at start - dom.dot = document.createElement('div'); - dom.point.appendChild(dom.dot); + /** + * Hide the Item from the DOM (when visible) + * @return {Boolean} changed + */ + Item.prototype.hide = function () { + return false; + }; - // attach this item as attribute - dom.point['timeline-item'] = this; + /** + * Repaint the item + */ + Item.prototype.redraw = function () {}; - this.dirty = true; - } + /** + * Reposition the Item horizontally + */ + Item.prototype.repositionX = 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'); - } - foreground.appendChild(dom.point); - } - this.displayed = true; + /** + * Reposition the Item vertically + */ + Item.prototype.repositionY = function () {}; - // 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); + /** + * Repaint a delete button on the top right of the item when the item is selected + * @param {HTMLElement} anchor + * @protected + */ + Item.prototype._repaintDeleteButton = function (anchor) { + var editable = (this.options.editable.remove || this.data.editable === true) && this.data.editable !== false; - var editable = (this.options.editable.updateTime || this.options.editable.updateGroup || this.editable === true) && this.editable !== false; + if (this.selected && editable && !this.dom.deleteButton) { + // create and show button + var me = this; - // update class - var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : '') + (editable ? ' vis-editable' : ' vis-readonly'); - dom.point.className = 'vis-item vis-point' + className; - dom.dot.className = 'vis-item vis-dot' + className; + var deleteButton = document.createElement('div'); + deleteButton.className = 'vis-delete'; + deleteButton.title = 'Delete this item'; - // recalculate size of dot and contents - this.props.dot.width = dom.dot.offsetWidth; - this.props.dot.height = dom.dot.offsetHeight; - this.props.content.height = dom.content.offsetHeight; + // TODO: be able to destroy the delete button + new Hammer(deleteButton).on('tap', function (event) { + event.stopPropagation(); + me.parent.removeFromDataSet(me); + }); - // resize contents - dom.content.style.marginLeft = 2 * this.props.dot.width + 'px'; - //dom.content.style.marginRight = ... + 'px'; // TODO: margin right + 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; + } + }; - dom.dot.style.top = (this.height - this.props.dot.height) / 2 + 'px'; - dom.dot.style.left = this.props.dot.width / 2 + 'px'; + /** + * 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; + } - // recalculate size - this.width = dom.point.offsetWidth; - this.height = dom.point.offsetHeight; + 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.dirty = false; + this.content = content; } - - this._repaintDeleteButton(dom.point); }; /** - * Show the item in the DOM (when not already visible). The items DOM will - * be created when needed. + * Set HTML contents for the item + * @param {Element} element HTML element to fill with the contents + * @private */ - PointItem.prototype.show = function () { - if (!this.displayed) { - this.redraw(); + Item.prototype._updateTitle = function (element) { + if (this.data.title != null) { + element.title = this.data.title || ''; + } else { + element.removeAttribute('vis-title'); } }; /** - * Hide the item from the DOM (when visible) + * 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 */ - PointItem.prototype.hide = function () { - if (this.displayed) { - if (this.dom.point.parentNode) { - this.dom.point.parentNode.removeChild(this.dom.point); + 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; } - this.displayed = false; + for (var i = 0; i < attributes.length; i++) { + var name = attributes[i]; + var value = this.data[name]; + + if (value != null) { + element.setAttribute('data-' + name, value); + } else { + element.removeAttribute('data-' + name); + } + } } }; /** - * Reposition the item horizontally - * @Override + * Update custom styles of the element + * @param element + * @private */ - PointItem.prototype.repositionX = function () { - var start = this.conversion.toScreen(this.data.start); - - this.left = start - this.props.dot.width; + Item.prototype._updateStyle = function (element) { + // remove old styles + if (this.style) { + util.removeCssText(element, this.style); + this.style = null; + } - // reposition point - this.dom.point.style.left = this.left + 'px'; + // append new styles + if (this.data.style) { + util.addCssText(element, this.data.style); + this.style = this.data.style; + } }; /** - * Reposition the item vertically - * @Override + * Stringify the items contents + * @param {string | Element | undefined} content + * @returns {string | undefined} + * @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'; - } else { - point.style.top = this.parent.height - this.top - this.height + 'px'; - } + Item.prototype._contentToString = function (content) { + if (typeof content === 'string') return content; + if (content && 'outerHTML' in content) return content.outerHTML; + return content; }; /** * Return the width of the item left from its start date * @return {number} */ - PointItem.prototype.getWidthLeft = function () { - return this.props.dot.width; + Item.prototype.getWidthLeft = function () { + return 0; }; /** - * Return the width of the item right from its start date + * Return the width of the item right from the max of its start and end date * @return {number} */ - PointItem.prototype.getWidthRight = function () { - return this.width - this.props.dot.width; + Item.prototype.getWidthRight = function () { + return 0; }; - module.exports = PointItem; + module.exports = Item; + + // should be implemented by the item + + // should be implemented by the item + + // should be implemented by the item /***/ }, /* 7 */ +/***/ function(module, exports, __webpack_require__) { + + // Only load hammer.js when in a browser environment + // (loading hammer.js in a node.js environment gives errors) + 'use strict'; + + if (typeof window !== 'undefined') { + var propagating = __webpack_require__(10); + var Hammer = window['Hammer'] || __webpack_require__(11); + module.exports = propagating(Hammer, { + preventDefault: 'mouse' + }); + } else { + module.exports = function () { + throw Error('hammer.js is only available in a browser, not in node.js.'); + }; + } + +/***/ }, +/* 8 */ /***/ function(module, exports, __webpack_require__) { /** @@ -2496,51 +2241,320 @@ 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 any = 'any'; var allOptions = { configure: { enabled: { boolean: boolean }, - filter: { boolean: boolean, string: string, array: array, 'function': 'function' }, + filter: { boolean: boolean, 'function': 'function' }, container: { dom: dom }, - showButton: { boolean: boolean }, - __type__: { object: object, boolean: boolean, string: string, array: array, 'function': 'function' } + __type__: { object: object, boolean: boolean, 'function': 'function' } }, - 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: { 'function': 'function', number: number }, - label: { string: string, 'undefined': 'undefined' }, - labelHighlightBold: { boolean: boolean }, - length: { number: number, 'undefined': 'undefined' }, - physics: { boolean: boolean }, - scaling: { + + //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 }, + onRender: { 'function': 'function' }, + size: { number: number }, + style: { string: ['square', 'circle'] }, // square, circle + __type__: { object: object, boolean: boolean, 'function': 'function' } + }, + 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: { 'function': 'function' }, + 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: { 'function': 'function' }, + 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 } + }, + + autoResize: { boolean: boolean }, + clickToUse: { boolean: boolean }, + end: { number: number, date: date, string: string, moment: moment }, + format: { + minorLabels: { + millisecond: { string: string, 'undefined': 'undefined' }, + second: { string: string, 'undefined': 'undefined' }, + minute: { string: string, 'undefined': 'undefined' }, + hour: { string: string, 'undefined': 'undefined' }, + weekday: { string: string, 'undefined': 'undefined' }, + day: { string: string, 'undefined': 'undefined' }, + month: { string: string, 'undefined': 'undefined' }, + year: { string: string, 'undefined': 'undefined' }, + __type__: { object: object } + }, + majorLabels: { + millisecond: { string: string, 'undefined': 'undefined' }, + second: { string: string, 'undefined': 'undefined' }, + minute: { string: string, 'undefined': 'undefined' }, + hour: { string: string, 'undefined': 'undefined' }, + weekday: { string: string, 'undefined': 'undefined' }, + day: { string: string, 'undefined': 'undefined' }, + month: { string: string, 'undefined': 'undefined' }, + year: { string: string, 'undefined': 'undefined' }, + __type__: { object: object } + }, + __type__: { object: object } + }, + height: { string: string, number: number }, + hiddenDates: { object: object, array: array }, + locale: { string: string }, + locales: { + __any__: { any: any }, + __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, 'undefined': 'undefined' }, + step: { number: number, 'undefined': 'undefined' }, + __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 + }, + 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': 'undefined'ined,max:'undefined': 'undefined'ined}, + //format: function (value) {return value;}, + title: { text: '', style: '' } + }, + right: { + //range: {min:'undefined': 'undefined'ined,max:'undefined': 'undefined'ined}, + //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 + } + }, + + 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: '' + } + }, + + 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; + +/***/ }, +/* 9 */ +/***/ 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 any = 'any'; + + var allOptions = { + configure: { + enabled: { boolean: boolean }, + filter: { boolean: boolean, string: string, array: array, 'function': 'function' }, + container: { dom: dom }, + showButton: { boolean: boolean }, + __type__: { object: object, boolean: boolean, string: string, array: array, 'function': 'function' } + }, + 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: { 'function': 'function', number: number }, + label: { string: string, 'undefined': 'undefined' }, + labelHighlightBold: { boolean: boolean }, + length: { number: number, 'undefined': 'undefined' }, + physics: { boolean: boolean }, + scaling: { min: { number: number }, max: { number: number }, label: { @@ -2663,1061 +2677,304 @@ return /******/ (function(modules) { // webpackBootstrap code: { string: string }, //'\uf007', size: { number: number }, //50, color: { string: string }, - __type__: { object: object } - }, - id: { string: string, number: number }, - image: { string: string, 'undefined': 'undefined' }, // --> URL - label: { string: string, 'undefined': 'undefined' }, - labelHighlightBold: { boolean: boolean }, - level: { number: number, 'undefined': 'undefined' }, - 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: { 'function': 'function' }, - __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, 'undefined': 'undefined' }, - value: { number: number, 'undefined': 'undefined' }, - x: { number: number }, - y: { number: number }, - __type__: { object: object } - }, - physics: { - enabled: { boolean: boolean }, - 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__: { any: any }, - __type__: { object: object } - }, - height: { string: string }, - width: { string: string }, - __type__: { object: object } - }; - - allOptions.groups.__any__ = allOptions.nodes; - allOptions.manipulation.controlNodeStyle = allOptions.nodes; - - 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'] - } - }, - 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, - labelHighlightBold: true, - //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] - } - }, - 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], - labelHighlightBold: true, - 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, - navigationButtons: false, - selectable: true, - selectConnectedEdges: true, - hoverConnectedEdges: true, - tooltipDelay: [300, 0, 1000, 25], - zoomView: true - }, - manipulation: { - enabled: false, - initiallyActive: false - }, - physics: { - enabled: true, - 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.allOptions = allOptions; - exports.configureOptions = configureOptions; - -/***/ }, -/* 8 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var Hammer = __webpack_require__(10); - var util = __webpack_require__(14); - - /** - * @constructor Item - * @param {Object} data Object containing (optional) parameters type, - * start, end, content, group, className. - * @param {{toScreen: function, toTime: function}} conversion - * Conversion functions from time to screen and vice versa - * @param {Object} options Configuration options - * // TODO: describe available options - */ - function Item(data, conversion, options) { - this.id = null; - this.parent = null; - this.data = data; - this.dom = null; - this.conversion = conversion || {}; - this.options = options || {}; - - this.selected = false; - this.displayed = false; - this.dirty = true; - - this.top = null; - this.left = null; - this.width = null; - this.height = null; - - this.editable = null; - if (this.data && this.data.hasOwnProperty('editable') && typeof this.data.editable === 'boolean') { - this.editable = data.editable; - } - } - - Item.prototype.stack = true; - - /** - * Select current item - */ - Item.prototype.select = function () { - this.selected = true; - this.dirty = true; - if (this.displayed) this.redraw(); - }; - - /** - * Unselect current item - */ - Item.prototype.unselect = function () { - this.selected = false; - this.dirty = true; - if (this.displayed) this.redraw(); - }; - - /** - * Set data for the item. Existing data will be updated. The id should not - * be changed. When the item is displayed, it will be redrawn immediately. - * @param {Object} data - */ - Item.prototype.setData = function (data) { - var groupChanged = data.group != undefined && this.data.group != data.group; - if (groupChanged) { - this.parent.itemSet._moveToGroup(this, data.group); - } - - if (data.hasOwnProperty('editable') && typeof data.editable === 'boolean') { - this.editable = data.editable; - } - - this.data = data; - this.dirty = true; - if (this.displayed) this.redraw(); - }; - - /** - * 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; - } - }; - - /** - * 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; - }; - - /** - * Repaint the item - */ - Item.prototype.redraw = function () {}; - - /** - * Reposition the Item horizontally - */ - Item.prototype.repositionX = function () {}; - - /** - * Reposition the Item vertically - */ - Item.prototype.repositionY = function () {}; - - /** - * Repaint a delete button on the top right of the item when the item is selected - * @param {HTMLElement} anchor - * @protected - */ - Item.prototype._repaintDeleteButton = function (anchor) { - var editable = (this.options.editable.remove || this.data.editable === true) && this.data.editable !== false; - - if (this.selected && editable && !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; - } - }; - - /** - * 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); - } - } - - 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'); - } - }; - - /** - * Process dataAttributes timeline option and set as data- attributes on dom.content - * @param {Element} element HTML element to which the attributes will be attached - * @private - */ - Item.prototype._updateDataAttributes = function (element) { - if (this.options.dataAttributes && this.options.dataAttributes.length > 0) { - var attributes = []; - - if (Array.isArray(this.options.dataAttributes)) { - attributes = this.options.dataAttributes; - } else if (this.options.dataAttributes == 'all') { - attributes = Object.keys(this.data); - } else { - return; - } - - for (var i = 0; i < attributes.length; i++) { - var name = attributes[i]; - var value = this.data[name]; - - if (value != null) { - element.setAttribute('data-' + name, value); - } else { - element.removeAttribute('data-' + name); - } - } - } - }; - - /** - * Update custom styles of the element - * @param element - * @private - */ - Item.prototype._updateStyle = function (element) { - // remove old styles - if (this.style) { - util.removeCssText(element, this.style); - this.style = null; - } - - // append new styles - if (this.data.style) { - util.addCssText(element, this.data.style); - this.style = this.data.style; - } - }; - - /** - * Stringify the items contents - * @param {string | Element | undefined} content - * @returns {string | undefined} - * @private - */ - Item.prototype._contentToString = function (content) { - if (typeof content === 'string') return content; - if (content && 'outerHTML' in content) return content.outerHTML; - return content; - }; - - /** - * Return the width of the item left from its start date - * @return {number} - */ - Item.prototype.getWidthLeft = function () { - return 0; - }; - - /** - * Return the width of the item right from the max of its start and end date - * @return {number} - */ - Item.prototype.getWidthRight = function () { - return 0; - }; - - module.exports = Item; - - // should be implemented by the item - - // should be implemented by the item - - // should be implemented by the item - -/***/ }, -/* 9 */ -/***/ 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 _componentsEdge = __webpack_require__(3); - - var _componentsEdge2 = _interopRequireDefault(_componentsEdge); - - var _componentsSharedLabel = __webpack_require__(4); - - var _componentsSharedLabel2 = _interopRequireDefault(_componentsSharedLabel); - - var util = __webpack_require__(14); - var DataSet = __webpack_require__(20); - var DataView = __webpack_require__(22); - - var EdgesHandler = (function () { - function EdgesHandler(body, images, groups) { - var _this = this; - - _classCallCheck(this, EdgesHandler); - - this.body = body; - this.images = images; - this.groups = groups; - - // create the edge API in the body container - this.body.functions.createEdge = this.create.bind(this); - - 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); - } - }; - - 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, - labelHighlightBold: true, - 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 - }; - - util.extend(this.options, this.defaultOptions); - - this.bindEventListeners(); - } - - _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'; - } - 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]; - - // 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 is called when options of EXISTING nodes or edges have changed. - this.body.emitter.on('_dataUpdated', function () { - _this2.reconnectEdges(); - _this2.markAllEdgesAsDirty(); - }); - - // 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); - - // 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.font, options); - for (var edgeId in this.body.edges) { - if (this.body.edges.hasOwnProperty(edgeId)) { - this.body.edges[edgeId].updateLabelModule(); - } - } - } - - // update the state of the variables if needed - if (options.hidden !== undefined || options.physics !== undefined || dataChanged === true) { - this.body.emitter.emit('_dataChanged'); - } - } - } - }, { - key: 'setData', - - /** - * 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; - - 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(); - } 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) { - edge.edgeType.cleanup(); - edge.disconnect(); - delete edges[id]; - } - } + __type__: { object: object } + }, + id: { string: string, number: number }, + image: { string: string, 'undefined': 'undefined' }, // --> URL + label: { string: string, 'undefined': 'undefined' }, + labelHighlightBold: { boolean: boolean }, + level: { number: number, 'undefined': 'undefined' }, + 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: { 'function': 'function' }, + __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, 'undefined': 'undefined' }, + value: { number: number, 'undefined': 'undefined' }, + x: { number: number }, + y: { number: number }, + __type__: { object: object } + }, + physics: { + enabled: { boolean: boolean }, + 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.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', + //globals : + autoResize: { boolean: boolean }, + clickToUse: { boolean: boolean }, + locale: { string: string }, + locales: { + __any__: { any: any }, + __type__: { object: object } + }, + height: { string: string }, + width: { string: string }, + __type__: { object: object } + }; - /** - * Reconnect all edges - * @private - */ - value: function reconnectEdges() { - var id; - var nodes = this.body.nodes; - var edges = this.body.edges; + allOptions.groups.__any__ = allOptions.nodes; + allOptions.manipulation.controlNodeStyle = allOptions.nodes; - for (id in nodes) { - if (nodes.hasOwnProperty(id)) { - nodes[id].edges = []; - } + 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 (id in edges) { - if (edges.hasOwnProperty(id)) { - var edge = edges[id]; - edge.from = null; - edge.to = null; - edge.connect(); - } + }, + 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, + labelHighlightBold: true, + //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: '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); - } + }, + 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], + labelHighlightBold: true, + 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 nodeList; + }, + 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 } - }]); - - return EdgesHandler; - })(); + }, + 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: { + enabled: true, + 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'] = EdgesHandler; - module.exports = exports['default']; + exports.allOptions = allOptions; + exports.configureOptions = configureOptions; /***/ }, /* 10 */ -/***/ function(module, exports, __webpack_require__) { - - // Only load hammer.js when in a browser environment - // (loading hammer.js in a node.js environment gives errors) - 'use strict'; - - if (typeof window !== 'undefined') { - var propagating = __webpack_require__(11); - var Hammer = window['Hammer'] || __webpack_require__(12); - module.exports = propagating(Hammer, { - preventDefault: 'mouse' - }); - } else { - module.exports = function () { - throw Error('hammer.js is only available in a browser, not in node.js.'); - }; - } - -/***/ }, -/* 11 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; @@ -3938,7 +3195,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 12 */ +/* 11 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v2.0.4 - 2014-09-28 @@ -6394,7 +5651,7 @@ return /******/ (function(modules) { // webpackBootstrap prefixed: prefixed }); - if ("function" == TYPE_FUNCTION && __webpack_require__(13)) { + if ("function" == TYPE_FUNCTION && __webpack_require__(12)) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return Hammer; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); @@ -6408,7 +5665,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 13 */ +/* 12 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__; @@ -6416,7 +5673,7 @@ return /******/ (function(modules) { // webpackBootstrap /* WEBPACK VAR INJECTION */}.call(exports, {})) /***/ }, -/* 14 */ +/* 13 */ /***/ function(module, exports, __webpack_require__) { // utility functions @@ -6426,8 +5683,8 @@ return /******/ (function(modules) { // webpackBootstrap 'use strict'; - var moment = __webpack_require__(15); - var uuid = __webpack_require__(18); + var moment = __webpack_require__(14); + var uuid = __webpack_require__(17); /** * Test whether given object is a number @@ -7762,17 +7019,17 @@ return /******/ (function(modules) { // webpackBootstrap }; /***/ }, -/* 15 */ +/* 14 */ /***/ function(module, exports, __webpack_require__) { // 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 = typeof window !== 'undefined' && window['moment'] || __webpack_require__(16); + module.exports = typeof window !== 'undefined' && window['moment'] || __webpack_require__(15); /***/ }, -/* 16 */ +/* 15 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {//! moment.js @@ -10886,10 +10143,10 @@ return /******/ (function(modules) { // webpackBootstrap return _moment; })); - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17)(module))) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(16)(module))) /***/ }, -/* 17 */ +/* 16 */ /***/ function(module, exports, __webpack_require__) { module.exports = function(module) { @@ -10905,7 +10162,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 18 */ +/* 17 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; @@ -11121,7 +10378,7 @@ return /******/ (function(modules) { // webpackBootstrap /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, -/* 19 */ +/* 18 */ /***/ function(module, exports, __webpack_require__) { // DOM utility methods @@ -11323,13 +10580,13 @@ return /******/ (function(modules) { // webpackBootstrap }; /***/ }, -/* 20 */ +/* 19 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var util = __webpack_require__(14); - var Queue = __webpack_require__(21); + var util = __webpack_require__(13); + var Queue = __webpack_require__(20); /** * DataSet @@ -12218,7 +11475,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = DataSet; /***/ }, -/* 21 */ +/* 20 */ /***/ function(module, exports, __webpack_require__) { /** @@ -12423,13 +11680,13 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Queue; /***/ }, -/* 22 */ +/* 21 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var util = __webpack_require__(14); - var DataSet = __webpack_require__(20); + var util = __webpack_require__(13); + var DataSet = __webpack_require__(19); /** * DataView @@ -12771,21 +12028,21 @@ return /******/ (function(modules) { // webpackBootstrap // nothing interesting for me :-( /***/ }, -/* 23 */ +/* 22 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Emitter = __webpack_require__(25); - var DataSet = __webpack_require__(20); - var DataView = __webpack_require__(22); - var util = __webpack_require__(14); - var Point3d = __webpack_require__(26); - var Point2d = __webpack_require__(24); - var Camera = __webpack_require__(27); - var Filter = __webpack_require__(28); - var Slider = __webpack_require__(29); - var StepNumber = __webpack_require__(30); + var Emitter = __webpack_require__(24); + var DataSet = __webpack_require__(19); + var DataView = __webpack_require__(21); + var util = __webpack_require__(13); + var Point3d = __webpack_require__(25); + var Point2d = __webpack_require__(23); + var Camera = __webpack_require__(26); + var Filter = __webpack_require__(27); + var Slider = __webpack_require__(28); + var StepNumber = __webpack_require__(29); /** * @constructor Graph3d @@ -15019,7 +14276,7 @@ return /******/ (function(modules) { // webpackBootstrap // use use defaults /***/ }, -/* 24 */ +/* 23 */ /***/ function(module, exports, __webpack_require__) { /** @@ -15037,7 +14294,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Point2d; /***/ }, -/* 25 */ +/* 24 */ /***/ function(module, exports, __webpack_require__) { @@ -15207,7 +14464,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 26 */ +/* 25 */ /***/ function(module, exports, __webpack_require__) { /** @@ -15290,12 +14547,12 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Point3d; /***/ }, -/* 27 */ +/* 26 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Point3d = __webpack_require__(26); + var Point3d = __webpack_require__(25); /** * @class Camera @@ -15431,12 +14688,12 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Camera; /***/ }, -/* 28 */ +/* 27 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var DataView = __webpack_require__(22); + var DataView = __webpack_require__(21); /** * @class Filter @@ -15642,12 +14899,12 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Filter; /***/ }, -/* 29 */ +/* 28 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var util = __webpack_require__(14); + var util = __webpack_require__(13); /** * @constructor Slider @@ -15990,7 +15247,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Slider; /***/ }, -/* 30 */ +/* 29 */ /***/ function(module, exports, __webpack_require__) { /** @@ -16134,28 +15391,28 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = StepNumber; /***/ }, -/* 31 */ +/* 30 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Emitter = __webpack_require__(25); - var Hammer = __webpack_require__(10); - var util = __webpack_require__(14); - var DataSet = __webpack_require__(20); - var DataView = __webpack_require__(22); - var Range = __webpack_require__(35); - var Core = __webpack_require__(38); - var TimeAxis = __webpack_require__(47); - var CurrentTime = __webpack_require__(32); - var CustomTime = __webpack_require__(50); - var ItemSet = __webpack_require__(39); - - var Configurator = __webpack_require__(51); - var Validator = __webpack_require__(53)['default']; - var printStyle = __webpack_require__(53).printStyle; - var allOptions = __webpack_require__(54).allOptions; - var configureOptions = __webpack_require__(54).configureOptions; + var Emitter = __webpack_require__(24); + var Hammer = __webpack_require__(7); + var util = __webpack_require__(13); + var DataSet = __webpack_require__(19); + var DataView = __webpack_require__(21); + var Range = __webpack_require__(34); + var Core = __webpack_require__(37); + var TimeAxis = __webpack_require__(46); + var CurrentTime = __webpack_require__(31); + var CustomTime = __webpack_require__(49); + var ItemSet = __webpack_require__(38); + + var Configurator = __webpack_require__(4); + var Validator = __webpack_require__(51)['default']; + var printStyle = __webpack_require__(51).printStyle; + var allOptions = __webpack_require__(5).allOptions; + var configureOptions = __webpack_require__(5).configureOptions; /** * Create a timeline visualization @@ -16664,15 +15921,15 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Timeline; /***/ }, -/* 32 */ +/* 31 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var util = __webpack_require__(14); - var Component = __webpack_require__(33); - var moment = __webpack_require__(15); - var locales = __webpack_require__(34); + var util = __webpack_require__(13); + var Component = __webpack_require__(32); + var moment = __webpack_require__(14); + var locales = __webpack_require__(33); /** * A current time bar @@ -16840,7 +16097,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = CurrentTime; /***/ }, -/* 33 */ +/* 32 */ /***/ function(module, exports, __webpack_require__) { /** @@ -16900,7 +16157,7 @@ return /******/ (function(modules) { // webpackBootstrap // should be implemented by the component /***/ }, -/* 34 */ +/* 33 */ /***/ function(module, exports, __webpack_require__) { // English @@ -16922,16 +16179,16 @@ return /******/ (function(modules) { // webpackBootstrap exports['nl_BE'] = exports['nl']; /***/ }, -/* 35 */ +/* 34 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var util = __webpack_require__(14); - var hammerUtil = __webpack_require__(36); - var moment = __webpack_require__(15); - var Component = __webpack_require__(33); - var DateUtil = __webpack_require__(37); + var util = __webpack_require__(13); + var hammerUtil = __webpack_require__(35); + var moment = __webpack_require__(14); + var Component = __webpack_require__(32); + var DateUtil = __webpack_require__(36); /** * @constructor Range @@ -17598,12 +16855,12 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Range; /***/ }, -/* 36 */ +/* 35 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Hammer = __webpack_require__(10); + var Hammer = __webpack_require__(7); /** * Register a touch event, taking place before a gesture @@ -17670,12 +16927,12 @@ return /******/ (function(modules) { // webpackBootstrap exports.offRelease = exports.offTouch; /***/ }, -/* 37 */ +/* 36 */ /***/ function(module, exports, __webpack_require__) { "use strict"; - var moment = __webpack_require__(15); + var moment = __webpack_require__(14); /** * used in Core to convert the options into a volatile variable @@ -18130,23 +17387,23 @@ return /******/ (function(modules) { // webpackBootstrap }; /***/ }, -/* 38 */ +/* 37 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Emitter = __webpack_require__(25); - var Hammer = __webpack_require__(10); - var hammerUtil = __webpack_require__(36); - var util = __webpack_require__(14); - var DataSet = __webpack_require__(20); - var DataView = __webpack_require__(22); - var Range = __webpack_require__(35); - var ItemSet = __webpack_require__(39); - var TimeAxis = __webpack_require__(47); - var Activator = __webpack_require__(48); - var DateUtil = __webpack_require__(37); - var CustomTime = __webpack_require__(50); + var Emitter = __webpack_require__(24); + var Hammer = __webpack_require__(7); + var hammerUtil = __webpack_require__(35); + var util = __webpack_require__(13); + var DataSet = __webpack_require__(19); + var DataView = __webpack_require__(21); + var Range = __webpack_require__(34); + var ItemSet = __webpack_require__(38); + var TimeAxis = __webpack_require__(46); + var Activator = __webpack_require__(47); + var DateUtil = __webpack_require__(36); + var CustomTime = __webpack_require__(49); /** * Create a timeline visualization @@ -19106,23 +18363,23 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Core; /***/ }, -/* 39 */ +/* 38 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Hammer = __webpack_require__(10); - var util = __webpack_require__(14); - var DataSet = __webpack_require__(20); - var DataView = __webpack_require__(22); - var TimeStep = __webpack_require__(43); - var Component = __webpack_require__(33); - var Group = __webpack_require__(40); - var BackgroundGroup = __webpack_require__(44); - var BoxItem = __webpack_require__(45); - var PointItem = __webpack_require__(6); - var RangeItem = __webpack_require__(42); - var BackgroundItem = __webpack_require__(46); + var Hammer = __webpack_require__(7); + var util = __webpack_require__(13); + var DataSet = __webpack_require__(19); + var DataView = __webpack_require__(21); + var TimeStep = __webpack_require__(42); + var Component = __webpack_require__(32); + var Group = __webpack_require__(39); + var BackgroundGroup = __webpack_require__(43); + var BoxItem = __webpack_require__(44); + var PointItem = __webpack_require__(2); + var RangeItem = __webpack_require__(41); + var BackgroundItem = __webpack_require__(45); var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items var BACKGROUND = '__background__'; // reserved group id for background items without group @@ -20733,14 +19990,14 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = ItemSet; /***/ }, -/* 40 */ +/* 39 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var util = __webpack_require__(14); - var stack = __webpack_require__(41); - var RangeItem = __webpack_require__(42); + var util = __webpack_require__(13); + var stack = __webpack_require__(40); + var RangeItem = __webpack_require__(41); /** * @constructor Group @@ -21319,7 +20576,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Group; /***/ }, -/* 41 */ +/* 40 */ /***/ function(module, exports, __webpack_require__) { // Utility functions for ordering and stacking of items @@ -21443,13 +20700,13 @@ return /******/ (function(modules) { // webpackBootstrap }; /***/ }, -/* 42 */ +/* 41 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Hammer = __webpack_require__(10); - var Item = __webpack_require__(8); + var Hammer = __webpack_require__(7); + var Item = __webpack_require__(6); /** * @constructor RangeItem @@ -21739,14 +20996,14 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = RangeItem; /***/ }, -/* 43 */ +/* 42 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var moment = __webpack_require__(15); - var DateUtil = __webpack_require__(37); - var util = __webpack_require__(14); + var moment = __webpack_require__(14); + var DateUtil = __webpack_require__(36); + var util = __webpack_require__(13); /** * @constructor TimeStep @@ -22429,13 +21686,13 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = TimeStep; /***/ }, -/* 44 */ +/* 43 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var util = __webpack_require__(14); - var Group = __webpack_require__(40); + var util = __webpack_require__(13); + var Group = __webpack_require__(39); /** * @constructor BackgroundGroup @@ -22493,13 +21750,13 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = BackgroundGroup; /***/ }, -/* 45 */ +/* 44 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Item = __webpack_require__(8); - var util = __webpack_require__(14); + var Item = __webpack_require__(6); + var util = __webpack_require__(13); /** * @constructor BoxItem @@ -22733,15 +21990,15 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = BoxItem; /***/ }, -/* 46 */ +/* 45 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Hammer = __webpack_require__(10); - var Item = __webpack_require__(8); - var BackgroundGroup = __webpack_require__(44); - var RangeItem = __webpack_require__(42); + var Hammer = __webpack_require__(7); + var Item = __webpack_require__(6); + var BackgroundGroup = __webpack_require__(43); + var RangeItem = __webpack_require__(41); /** * @constructor BackgroundItem @@ -22954,16 +22211,16 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = BackgroundItem; /***/ }, -/* 47 */ +/* 46 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var util = __webpack_require__(14); - var Component = __webpack_require__(33); - var TimeStep = __webpack_require__(43); - var DateUtil = __webpack_require__(37); - var moment = __webpack_require__(15); + var util = __webpack_require__(13); + var Component = __webpack_require__(32); + var TimeStep = __webpack_require__(42); + var DateUtil = __webpack_require__(36); + var moment = __webpack_require__(14); /** * A horizontal time axis @@ -23393,15 +22650,15 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = TimeAxis; /***/ }, -/* 48 */ +/* 47 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var keycharm = __webpack_require__(49); - var Emitter = __webpack_require__(25); - var Hammer = __webpack_require__(10); - var util = __webpack_require__(14); + var keycharm = __webpack_require__(48); + var Emitter = __webpack_require__(24); + var Hammer = __webpack_require__(7); + var util = __webpack_require__(13); /** * Turn an element into an clickToUse element. @@ -23552,7 +22809,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Activator; /***/ }, -/* 49 */ +/* 48 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict"; @@ -23751,16 +23008,16 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 50 */ +/* 49 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Hammer = __webpack_require__(10); - var util = __webpack_require__(14); - var Component = __webpack_require__(33); - var moment = __webpack_require__(15); - var locales = __webpack_require__(34); + var Hammer = __webpack_require__(7); + var util = __webpack_require__(13); + var Component = __webpack_require__(32); + var moment = __webpack_require__(14); + var locales = __webpack_require__(33); /** * A custom time bar @@ -23991,7 +23248,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = CustomTime; /***/ }, -/* 51 */ +/* 50 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -24002,676 +23259,893 @@ 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 _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__(52); - - var _ColorPicker2 = _interopRequireDefault(_ColorPicker); - - var util = __webpack_require__(14); - - /** - * 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 - */ - - var Configurator = (function () { - function Configurator(parentModule, defaultContainer, configureOptions) { - var pixelRatio = arguments[3] === undefined ? 1 : arguments[3]; - - _classCallCheck(this, Configurator); + var Hammer = __webpack_require__(7); + var hammerUtil = __webpack_require__(35); + var util = __webpack_require__(13); - this.parent = parentModule; - this.changedOptions = []; - this.container = defaultContainer; - this.allowCreation = false; + var ColorPicker = (function () { + function ColorPicker() { + var pixelRatio = arguments[0] === undefined ? 1 : arguments[0]; - this.options = {}; - this.defaultOptions = { - enabled: false, - filter: true, - container: undefined, - showButton: true - }; - util.extend(this.options, this.defaultOptions); + _classCallCheck(this, ColorPicker); - this.configureOptions = configureOptions; - this.moduleOptions = {}; - this.domElements = []; - this.colorPicker = new _ColorPicker2['default'](pixelRatio); - this.wrapper = undefined; + 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(Configurator, [{ - key: 'setOptions', + _createClass(ColorPicker, [{ + key: 'insertTo', /** - * refresh all options. - * Because all modules parse their options by themselves, we just use their options. We copy them here. - * - * @param options + * this inserts the colorPicker into a div from the DOM + * @param container */ - 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; - } - if (this.options.filter === false) { - enabled = false; - } + 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.options.enabled = enabled; + this._setSize(); + } + }, { + key: 'setCallback', + + /** + * 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.'); } - 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: '_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: '_create', + key: 'setColor', /** - * Create all DOM elements - * @private + * 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 _create() { - var _this = this; - - this._clean(); - this.changedOptions = []; + value: function setColor(color) { + var setInitial = arguments[1] === undefined ? true : arguments[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 (color === 'none') { + return; + } - if (show !== false) { - this.allowCreation = true; + var rgba = undefined; - // linebreak between categories - if (counter > 0) { - this._makeItem([]); - } - // a header for the category - this._makeHeader(option); + // if a html color shorthand is used, convert to hex + var htmlColor = this._isColorString(color); + if (htmlColor !== undefined) { + color = htmlColor; + } - // get the suboptions - this._handleObject(this.configureOptions[option], [option]); + // 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 }; } - 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'; - }; + // 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.optionsContainer = document.createElement('div'); - _this.optionsContainer.className = 'vis-network-configuration vis-option-container'; + /** + * 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', - _this.domElements.push(_this.optionsContainer); - _this.domElements.push(generateButton); - })(); + // ------------------------------------------ PRIVATE ----------------------------- // + + /** + * 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]; + + // store the previous color for next time; + if (storePrevious === true) { + this.previousColor = util.extend({}, this.color); } - this._push(); - this.colorPicker.insertTo(this.container); + if (this.applied === true) { + this.updateCallback(this.initialColor); + } + + this.frame.style.display = 'none'; } }, { - key: '_push', + key: '_save', /** - * draw all DOM elements on the screen + * bound to the save button. Saves and hides. * @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 _save() { + this.updateCallback(this.color); + this.applied = false; + this._hide(); } }, { - key: '_clean', + key: '_apply', /** - * delete all DOM elements + * Bound to apply button. Saves but does not close. Is undone by the cancel button. * @private */ - value: function _clean() { - for (var i = 0; i < this.domElements.length; i++) { - this.wrapper.removeChild(this.domElements[i]); - } + value: function _apply() { + this.applied = true; + this.updateCallback(this.color); + this._updatePicker(this.color); + } + }, { + key: '_loadLast', - if (this.wrapper !== undefined) { - this.container.removeChild(this.wrapper); - this.wrapper = undefined; + /** + * 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.domElements = []; } }, { - key: '_getValue', + key: '_setColor', /** - * get the value from the actualOptions if it exists - * @param {array} path | where to look for the actual option - * @returns {*} + * set the color, place the picker + * @param rgba + * @param setInitial * @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 _setColor(rgba) { + var setInitial = arguments[1] === undefined ? true : arguments[1]; + + // store the initial color + if (setInitial === true) { + this.initialColor = util.extend({}, rgba); } - return base; + + 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: '_makeItem', + key: '_setOpacity', /** - * all option elements are wrapped in an item - * @param path - * @param domElements + * bound to opacity control + * @param value * @private */ - value: function _makeItem(path) { - var _this2 = this; + value: function _setOpacity(value) { + this.color.a = value / 100; + this._updatePicker(this.color); + } + }, { + key: '_setBrightness', - for (var _len = arguments.length, domElements = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - domElements[_key - 1] = arguments[_key]; - } + /** + * 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', - 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); - })(); + /** + * 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: '_makeHeader', + key: '_setSize', /** - * header for major subjects - * @param name + * used by create to set the size of the canvas. * @private */ - value: function _makeHeader(name) { - var div = document.createElement('div'); - div.className = 'vis-network-configuration header'; - div.innerHTML = name; - this._makeItem([], div); + 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; + } + }, { + 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); + } + + 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'); + try { + this.opacityRange.type = 'range'; // Not supported on IE9 + this.opacityRange.min = '0'; + this.opacityRange.max = '100'; + } catch (err) {} + this.opacityRange.value = '100'; + this.opacityRange.className = 'vis-range'; + + this.brightnessRange = document.createElement('input'); + try { + this.brightnessRange.type = 'range'; // Not supported on IE9 + this.brightnessRange.min = '0'; + this.brightnessRange.max = '100'; + } catch (err) {} + 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: '_makeLabel', + key: '_bindHammer', /** - * make a label, if it is an object label, it gets different styling. - * @param name - * @param path - * @param objectLabel - * @returns {HTMLElement} + * bind hammer to the color picker * @private */ - value: function _makeLabel(name, path) { - var objectLabel = arguments[2] === undefined ? false : arguments[2]; + value: function _bindHammer() { + var _this = this; - 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; + 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: '_makeDropdown', + key: '_generateHueCircle', /** - * make a dropdown list for multiple possible string optoins - * @param arr - * @param value - * @param path + * generate the hue circle. This is relatively heavy (200ms) and is done only once on the first time it is shown. * @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 _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); - 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); - } + // clear the canvas + var w = this.colorPickerCanvas.clientWidth; + var h = this.colorPickerCanvas.clientHeight; + ctx.clearRect(0, 0, w, h); - var me = this; - select.onchange = function () { - me._update(this.value, path); - }; + // 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(); - var label = this._makeLabel(path[path.length - 1], path); - this._makeItem(path, label, select); + this.hueCircle = ctx.getImageData(0, 0, w, h); + } + this.generated = true; } }, { - key: '_makeRange', + key: '_moveSelector', /** - * make a range object for numeric options - * @param arr - * @param value - * @param path + * move the selector. This is called by hammer functions. + * + * @param event * @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.className = 'vis-network-configuration range'; - try { - range.type = 'range'; // not supported on IE9 - range.min = min; - range.max = max; - } catch (err) {} - range.step = step; + value: function _moveSelector(event) { + var rect = this.colorPickerDiv.getBoundingClientRect(); + var left = event.center.x - rect.left; + var top = event.center.y - rect.top; - 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 centerY = 0.5 * this.colorPickerDiv.clientHeight; + var centerX = 0.5 * this.colorPickerDiv.clientWidth; - var input = document.createElement('input'); - input.className = 'vis-network-configuration rangeinput'; - input.value = range.value; + var x = left - centerX; + var y = top - centerY; - var me = this; - range.onchange = function () { - input.value = this.value;me._update(Number(this.value), path); - }; - range.oninput = function () { - input.value = this.value; - }; + var angle = Math.atan2(x, y); + var radius = 0.98 * Math.min(Math.sqrt(x * x + y * y), centerX); - var label = this._makeLabel(path[path.length - 1], path); - this._makeItem(path, label, range, input); - } - }, { - key: '_makeCheckbox', + var newTop = Math.cos(angle) * radius + centerY; + var newLeft = Math.sin(angle) * radius + centerX; - /** - * 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 }); - } - } - } + this.colorPickerSelector.style.top = newTop - 0.5 * this.colorPickerSelector.clientHeight + 'px'; + this.colorPickerSelector.style.left = newLeft - 0.5 * this.colorPickerSelector.clientWidth + 'px'; - var me = this; - checkbox.onchange = function () { - me._update(this.checked, path); - }; + // 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; - var label = this._makeLabel(path[path.length - 1], path); - this._makeItem(path, label, checkbox); + // 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 + ')'; } - }, { - key: '_makeTextInput', + }]); + + return ColorPicker; + })(); + + exports['default'] = ColorPicker; + module.exports = exports['default']; + +/***/ }, +/* 51 */ +/***/ 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__(13); + + 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', /** - * make a text input field for string options. - * @param defaultValue - * @param value - * @param path - * @private + * Main function to be called + * @param options + * @param subObject + * @returns {boolean} */ - 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 validate(options, referenceOptions, subObject) { + errorFound = false; + allOptions = referenceOptions; + var usedOptions = referenceOptions; + if (subObject !== undefined) { + usedOptions = referenceOptions[subObject]; } - - 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); + Validator.parse(options, usedOptions, []); + return errorFound; } }, { - key: '_makeColorField', + key: 'parse', /** - * make a color field with a color picker for color fields - * @param arr - * @param value + * Will traverse an object recursively and check every value + * @param options + * @param referenceOptions * @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; - - if (value !== 'none') { - div.className = 'vis-network-configuration colorBlock'; - div.style.backgroundColor = value; - } else { - div.className = 'vis-network-configuration colorBlock none'; + value: function parse(options, referenceOptions, path) { + for (var option in options) { + if (options.hasOwnProperty(option)) { + Validator.check(option, options, referenceOptions, path); + } } - - 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: 'check', /** - * used by the color buttons to call the color picker. - * @param event - * @param value - * @param div + * Check every value. If the value is an object, call the parse function on that object. + * @param option + * @param options + * @param referenceOptions * @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); - }); + 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' && referenceOptions['__any__'].__type__ !== undefined) { + // if the any subgroup is not a predefined object int he configurator we do not look deeper into the object. + Validator.checkFields(option, options, referenceOptions, '__any__', referenceOptions['__any__'].__type__, path); + } else { + Validator.checkFields(option, options, referenceOptions, '__any__', referenceOptions['__any__'], 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: '_handleObject', + key: 'checkFields', /** - * parse an object and draw the correct items - * @param obj - * @param path - * @private + * + * @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 _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; - } - } + 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' && referenceOption !== '__any__') { + path = util.copyAndExtendArray(path, option); + Validator.parse(options[option], referenceOptions[referenceOption], path); } + } else if (optionType === 'object' && referenceOption !== '__any__') { + path = util.copyAndExtendArray(path, option); + Validator.parse(options[option], referenceOptions[referenceOption], path); + } + } else if (refOptionObj['any'] === undefined) { + // type of the field is incorrect and the field cannot be any + 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; - if (show !== false) { - visibleInSet = true; - var value = this._getValue(newPath); - - if (item instanceof Array) { - this._handleArray(item, value, newPath); - } else if (typeof item === 'string') { - this._makeTextInput(item, value, newPath); - } else if (typeof item === 'boolean') { - this._makeCheckbox(item, value, newPath); - } else if (item instanceof Object) { - // collapse the physics options that are not enabled - var draw = true; - if (path.indexOf('physics') !== -1) { - if (this.moduleOptions.physics.solver !== subObj) { - draw = false; - } - } - - if (draw === true) { - // initially collapse options with an disabled enabled option. - if (item.enabled !== undefined) { - var enabledPath = util.copyAndExtendArray(newPath, 'enabled'); - var enabledValue = this._getValue(enabledPath); - if (enabledValue === true) { - var label = this._makeLabel(subObj, newPath, true); - this._makeItem(newPath, label); - visibleInSet = this._handleObject(item, newPath) || visibleInSet; - } else { - this._makeCheckbox(item, enabledValue, newPath); - } - } else { - var label = this._makeLabel(subObj, newPath, true); - this._makeItem(newPath, label); - visibleInSet = this._handleObject(item, newPath) || visibleInSet; - } - } - } else { - console.error('dont know how to handle', item, subObj, newPath); - } - } + 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 localSearchThreshold = 8; + var globalSearchThreshold = 4; + + 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); } - return visibleInSet; + + errorFound = true; } }, { - key: '_handleArray', + key: 'findInOptions', /** - * handle the array type of option - * @param optionName - * @param arr - * @param value + * traverse the options in search for a match. + * @param option + * @param options * @param path - * @private + * @param recursive + * @returns {{closestMatch: string, path: Array, distance: number}} */ - 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 }); + value: function findInOptions(option, options, path) { + var recursive = arguments[3] === undefined ? false : arguments[3]; + + 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; + } } - } else if (typeof arr[0] === 'string') { - this._makeDropdown(arr, value, path); - if (arr[0] !== value) { - this.changedOptions.push({ path: path, value: value }); + } + 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]; + + var str = '\n\n' + prefix + 'options = {\n'; + for (var i = 0; i < path.length; i++) { + for (var j = 0; j < i + 1; j++) { + str += ' '; } - } else if (typeof arr[0] === 'number') { - this._makeRange(arr, value, path); - if (arr[0] !== value) { - this.changedOptions.push({ path: path, value: Number(value) }); + 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: '_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: 'print', + value: function print(options) { + return JSON.stringify(options).replace(/(\")|(\[)|(\])|(,"__type__")/g, '').replace(/(\,)/g, ', '); } }, { - key: '_constructOptions', - value: function _constructOptions(value, path) { - var optionsObj = arguments[2] === undefined ? {} : arguments[2]; + key: 'levenshteinDistance', - var pointer = optionsObj; + // 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; - // when dropdown boxes can be string or boolean, we typecast it into correct types - value = value === 'true' ? true : value; - value = value === 'false' ? false : value; + var matrix = []; - 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]]; + // increment along the first column of each row + var i; + for (i = 0; i <= b.length; i++) { + matrix[i] = [i]; + } + + // increment each column in the first row + var j; + for (j = 0; j <= a.length; j++) { + matrix[0][j] = j; + } + + // Fill in the rest of the matrix + for (i = 1; i <= b.length; i++) { + for (j = 1; j <= a.length; j++) { + if (b.charAt(i - 1) == a.charAt(j - 1)) { + matrix[i][j] = matrix[i - 1][j - 1]; } else { - pointer[path[i]] = value; + 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 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) + '
'; + + return matrix[b.length][a.length]; } }]); - return Configurator; + return Validator; })(); - exports['default'] = Configurator; - module.exports = exports['default']; + exports['default'] = Validator; + exports.printStyle = printStyle; /***/ }, /* 52 */ @@ -24679,5326 +24153,5060 @@ 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - var Hammer = __webpack_require__(10); - var hammerUtil = __webpack_require__(36); - var util = __webpack_require__(14); - - 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 () {}; + var Emitter = __webpack_require__(24); + var Hammer = __webpack_require__(7); + var util = __webpack_require__(13); + var DataSet = __webpack_require__(19); + var DataView = __webpack_require__(21); + var Range = __webpack_require__(34); + var Core = __webpack_require__(37); + var TimeAxis = __webpack_require__(46); + var CurrentTime = __webpack_require__(31); + var CustomTime = __webpack_require__(49); + var LineGraph = __webpack_require__(53); + + var Configurator = __webpack_require__(4); + var Validator = __webpack_require__(51)['default']; + var printStyle = __webpack_require__(51).printStyle; + var allOptions = __webpack_require__(8).allOptions; + var configureOptions = __webpack_require__(8).configureOptions; - // create all DOM elements - this._create(); + /** + * 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(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: 'setCallback', - - /** - * 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]; - } - } - }, { - key: 'setColor', - - /** - * 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 me = this; + this.defaultOptions = { + start: null, + end: null, - if (color === 'none') { - return; - } + autoResize: true, - var rgba = undefined; + orientation: { + axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both' + item: 'bottom' // not relevant for Graph2d + }, - // if a html color shorthand is used, convert to hex - var htmlColor = this._isColorString(color); - if (htmlColor !== undefined) { - color = htmlColor; - } + width: null, + height: null, + maxHeight: null, + minHeight: null + }; + this.options = util.deepExtend({}, this.defaultOptions); - // 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 }; - } - } - } + // Create the DOM, props, and emitter + this._create(container); - // 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', + // all components listed here will be repainted automatically + this.components = []; - /** - * 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(); + 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: '_hide', - - // ------------------------------------------ PRIVATE ----------------------------- // + }; - /** - * 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]; + // range + this.range = new Range(this.body); + this.components.push(this.range); + this.body.range = this.range; - // store the previous color for next time; - if (storePrevious === true) { - this.previousColor = util.extend({}, this.color); - } + // time axis + this.timeAxis = new TimeAxis(this.body); + this.components.push(this.timeAxis); + //this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); - if (this.applied === true) { - this.updateCallback(this.initialColor); - } + // current time bar + this.currentTime = new CurrentTime(this.body); + this.components.push(this.currentTime); - this.frame.style.display = 'none'; - } - }, { - key: '_save', + // item set + this.linegraph = new LineGraph(this.body); + this.components.push(this.linegraph); - /** - * bound to the save button. Saves and hides. - * @private - */ - value: function _save() { - this.updateCallback(this.color); - this.applied = false; - this._hide(); - } - }, { - key: '_apply', + this.itemsData = null; // DataSet + this.groupsData = null; // DataSet - /** - * 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', + 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)); + }; - /** - * 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: '_setColor', + // apply options + if (options) { + this.setOptions(options); + } - /** - * set the color, place the picker - * @param rgba - * @param setInitial - * @private - */ - value: function _setColor(rgba) { - var setInitial = arguments[1] === undefined ? true : arguments[1]; + // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! + if (groups) { + this.setGroups(groups); + } - // store the initial color - if (setInitial === true) { - this.initialColor = util.extend({}, rgba); - } + // create itemset + if (items) { + this.setItems(items); + } else { + this._redraw(); + } + } - this.color = rgba; - var hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b); + // Extend the functionality from Core + Graph2d.prototype = new Core(); - 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); + 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.colorPickerSelector.style.left = x - 0.5 * this.colorPickerSelector.clientWidth + 'px'; - this.colorPickerSelector.style.top = y - 0.5 * this.colorPickerSelector.clientHeight + 'px'; + Core.prototype.setOptions.call(this, options); + }; - this._updatePicker(rgba); - } - }, { - key: '_setOpacity', + /** + * Set items + * @param {vis.DataSet | Array | null} items + */ + Graph2d.prototype.setItems = function (items) { + var initialLoad = this.itemsData == null; - /** - * bound to opacity control - * @param value - * @private - */ - value: function _setOpacity(value) { - this.color.a = value / 100; - this._updatePicker(this.color); - } - }, { - key: '_setBrightness', + // 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' + } + }); + } - /** - * 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', + // set items + this.itemsData = newDataSet; + this.linegraph && this.linegraph.setItems(newDataSet); - /** - * 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 (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; - 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); + this.setWindow(start, end, { animation: false }); + } else { + this.fit({ animation: false }); + } + } + }; - // clear the canvas - var w = this.colorPickerCanvas.clientWidth; - var h = this.colorPickerCanvas.clientHeight; - ctx.clearRect(0, 0, w, h); + /** + * 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); + } - 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.groupsData = newDataSet; + this.linegraph.setGroups(newDataSet); + }; - this.brightnessRange.value = 100 * hsv.v; - this.opacityRange.value = 100 * rgba.a; + /** + * 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.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', + /** + * 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; + } + }; - /** - * used by create to set the size of the canvas. - * @private - */ - value: function _setSize() { - this.colorPickerCanvas.style.width = '100%'; - this.colorPickerCanvas.style.height = '100%'; + /** + * 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.getDataRange = function () { + var min = null; + var max = null; - this.colorPickerCanvas.width = 289 * this.pixelRatio; - this.colorPickerCanvas.height = 289 * this.pixelRatio; + // 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: '_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'; + return { + min: min != null ? new Date(min) : null, + max: max != null ? new Date(max) : null + }; + }; - this.colorPickerDiv = document.createElement('div'); - this.colorPickerSelector = document.createElement('div'); - this.colorPickerSelector.className = 'vis-selector'; - this.colorPickerDiv.appendChild(this.colorPickerSelector); + /** + * 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.colorPickerCanvas = document.createElement('canvas'); - this.colorPickerDiv.appendChild(this.colorPickerCanvas); + var customTime = CustomTime.customTimeFromTarget(event); - 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 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'; + } - this.colorPickerCanvas.getContext('2d').setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); - } + 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)); + } - this.colorPickerDiv.className = 'vis-color'; + 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.opacityDiv = document.createElement('div'); - this.opacityDiv.className = 'vis-opacity'; + /** + * Load a configurator + * @return {Object} + * @private + */ + Graph2d.prototype._createConfigurator = function () { + return new Configurator(this, this.dom.container, configureOptions); + }; - this.brightnessDiv = document.createElement('div'); - this.brightnessDiv.className = 'vis-brightness'; + module.exports = Graph2d; - this.arrowDiv = document.createElement('div'); - this.arrowDiv.className = 'vis-arrow'; +/***/ }, +/* 53 */ +/***/ function(module, exports, __webpack_require__) { - this.opacityRange = document.createElement('input'); - try { - this.opacityRange.type = 'range'; // Not supported on IE9 - this.opacityRange.min = '0'; - this.opacityRange.max = '100'; - } catch (err) {} - this.opacityRange.value = '100'; - this.opacityRange.className = 'vis-range'; + 'use strict'; - this.brightnessRange = document.createElement('input'); - try { - this.brightnessRange.type = 'range'; // Not supported on IE9 - this.brightnessRange.min = '0'; - this.brightnessRange.max = '100'; - } catch (err) {} - this.brightnessRange.value = '100'; - this.brightnessRange.className = 'vis-range'; + var util = __webpack_require__(13); + var DOMutil = __webpack_require__(18); + var DataSet = __webpack_require__(19); + var DataView = __webpack_require__(21); + var Component = __webpack_require__(32); + var DataAxis = __webpack_require__(54); + var GraphGroup = __webpack_require__(56); + var Legend = __webpack_require__(60); + var BarFunctions = __webpack_require__(59); + var LineFunctions = __webpack_require__(57); - this.opacityDiv.appendChild(this.opacityRange); - this.brightnessDiv.appendChild(this.brightnessRange); + var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items - 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 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; - this.brightnessLabel = document.createElement('div'); - this.brightnessLabel.className = 'vis-label vis-brightness'; - this.brightnessLabel.innerHTML = 'brightness:'; + 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.opacityLabel = document.createElement('div'); - this.opacityLabel.className = 'vis-label vis-opacity'; - this.opacityLabel.innerHTML = 'opacity:'; + // 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.newColorDiv = document.createElement('div'); - this.newColorDiv.className = 'vis-new-color'; - this.newColorDiv.innerHTML = 'new'; + var me = this; + this.itemsData = null; // DataSet + this.groupsData = null; // DataSet - this.initialColorDiv = document.createElement('div'); - this.initialColorDiv.className = 'vis-initial-color'; - this.initialColorDiv.innerHTML = 'initial'; + // 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.cancelButton = document.createElement('div'); - this.cancelButton.className = 'vis-button vis-cancel'; - this.cancelButton.innerHTML = 'cancel'; - this.cancelButton.onclick = this._hide.bind(this, false); + // 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.applyButton = document.createElement('div'); - this.applyButton.className = 'vis-button vis-apply'; - this.applyButton.innerHTML = 'apply'; - this.applyButton.onclick = this._apply.bind(this); + 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 - this.saveButton = document.createElement('div'); - this.saveButton.className = 'vis-button vis-save'; - this.saveButton.innerHTML = 'save'; - this.saveButton.onclick = this._save.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); + }); - this.loadButton = document.createElement('div'); - this.loadButton.className = 'vis-button vis-load'; - this.loadButton.innerHTML = 'load last'; - this.loadButton.onclick = this._loadLast.bind(this); + // 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'); + } - 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); + LineGraph.prototype = new Component(); - this.frame.appendChild(this.cancelButton); - this.frame.appendChild(this.applyButton); - this.frame.appendChild(this.saveButton); - this.frame.appendChild(this.loadButton); - } - }, { - key: '_bindHammer', + /** + * 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; - /** - * bind hammer to the color picker - * @private - */ - value: function _bindHammer() { - var _this = 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.drag = {}; - this.pinch = {}; - this.hammer = new Hammer(this.colorPickerCanvas); - this.hammer.get('pinch').set({ enable: true }); + // data axis + this.options.dataAxis.orientation = 'left'; + this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups); - 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', + this.options.dataAxis.orientation = 'right'; + this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups); + delete this.options.dataAxis.orientation; - /** - * 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); + // 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); - // clear the canvas - var w = this.colorPickerCanvas.clientWidth; - var h = this.colorPickerCanvas.clientHeight; - ctx.clearRect(0, 0, w, h); + this.show(); + }; - // 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); + /** + * 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'); + + 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; } } - 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); + if (this.yAxisLeft) { + if (options.dataAxis !== undefined) { + this.yAxisLeft.setOptions(this.options.dataAxis); + this.yAxisRight.setOptions(this.options.dataAxis); } - 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; + if (this.legendLeft) { + if (options.legend !== undefined) { + this.legendLeft.setOptions(this.options.legend); + this.legendRight.setOptions(this.options.legend); + } + } - var centerY = 0.5 * this.colorPickerDiv.clientHeight; - var centerX = 0.5 * this.colorPickerDiv.clientWidth; + if (this.groups.hasOwnProperty(UNGROUPED)) { + this.groups[UNGROUPED].setOptions(options); + } + } - var x = left - centerX; - var y = top - centerY; + // this is used to redraw the graph if the visibility of the groups is changed. + if (this.dom.frame) { + this.redraw(true); + } + }; - var angle = Math.atan2(x, y); - var radius = 0.98 * Math.min(Math.sqrt(x * x + y * y), centerX); + /** + * 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); + } + }; - var newTop = Math.cos(angle) * radius + centerY; - var newLeft = Math.sin(angle) * radius + centerX; + /** + * 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); + } + }; - this.colorPickerSelector.style.top = newTop - 0.5 * this.colorPickerSelector.clientHeight + 'px'; - this.colorPickerSelector.style.left = newLeft - 0.5 * this.colorPickerSelector.clientWidth + 'px'; + /** + * Set items + * @param {vis.DataSet | null} items + */ + LineGraph.prototype.setItems = function (items) { + var me = this, + ids, + oldItemsData = this.itemsData; - // 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; + // 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'); + } - // 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 + ')'; - } - }]); + if (oldItemsData) { + // unsubscribe from old dataset + util.forEach(this.itemListeners, function (callback, event) { + oldItemsData.off(event, callback); + }); - return ColorPicker; - })(); + // remove all drawn items + ids = oldItemsData.getIds(); + this._onRemove(ids); + } - exports['default'] = ColorPicker; - module.exports = exports['default']; + if (this.itemsData) { + // subscribe to new dataset + var id = this.id; + util.forEach(this.itemListeners, function (callback, event) { + me.itemsData.on(event, callback, id); + }); -/***/ }, -/* 53 */ -/***/ function(module, exports, __webpack_require__) { + // add all new items + ids = this.itemsData.getIds(); + this._onAdd(ids); + } + this._updateUngrouped(); + //this._updateGraph(); + this.redraw(true); + }; - 'use strict'; + /** + * Set groups + * @param {vis.DataSet} groups + */ + LineGraph.prototype.setGroups = function (groups) { + var me = this; + var ids; - Object.defineProperty(exports, '__esModule', { - value: true - }); + // unsubscribe from current dataset + if (this.groupsData) { + util.forEach(this.groupListeners, function (callback, event) { + me.groupsData.off(event, callback); + }); - 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 all drawn groups + ids = this.groupsData.getIds(); + this.groupsData = null; + this._onRemoveGroups(ids); // note: this will cause a redraw + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + // 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 util = __webpack_require__(14); + if (this.groupsData) { + // subscribe to new dataset + var id = this.id; + util.forEach(this.groupListeners, function (callback, event) { + me.groupsData.on(event, callback, id); + }); + + // draw all ms + ids = this.groupsData.getIds(); + this._onAddGroups(ids); + } + this._onUpdate(); + }; - var errorFound = false; - var allOptions = undefined; - var printStyle = 'background: #FFeeee; color: #dd0000'; /** - * Used to validate options. + * Update the data + * @param [ids] + * @private */ - - var Validator = (function () { - function Validator() { - _classCallCheck(this, Validator); + 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]); } - _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: 'parse', - - /** - * 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._updateGraph(); + this.redraw(true); + }; + LineGraph.prototype._onAddGroups = function (groupIds) { + this._onUpdateGroups(groupIds); + }; - /** - * 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' && referenceOptions['__any__'].__type__ !== undefined) { - // if the any subgroup is not a predefined object int he configurator we do not look deeper into the object. - Validator.checkFields(option, options, referenceOptions, '__any__', referenceOptions['__any__'].__type__, path); - } else { - Validator.checkFields(option, options, referenceOptions, '__any__', referenceOptions['__any__'], path); - } + /** + * 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 { - // 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', - - /** - * - * @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' && referenceOption !== '__any__') { - path = util.copyAndExtendArray(path, option); - Validator.parse(options[option], referenceOptions[referenceOption], path); - } - } else if (optionType === 'object' && referenceOption !== '__any__') { - path = util.copyAndExtendArray(path, option); - Validator.parse(options[option], referenceOptions[referenceOption], path); - } - } else if (refOptionObj['any'] === undefined) { - // type of the field is incorrect and the field cannot be any - 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.yAxisLeft.removeGroup(groupIds[i]); + this.legendLeft.removeGroup(groupIds[i]); + this.legendLeft.redraw(); } + delete this.groups[groupIds[i]]; } - }, { - key: 'getType', - value: function getType(object) { - var type = typeof object; + } + this._updateUngrouped(); + //this._updateGraph(); + this.redraw(true); + }; - 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; + /** + * 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]); } - }, { - key: 'getSuggestion', - value: function getSuggestion(option, options, path) { - var localSearch = Validator.findInOptions(option, options, path, false); - var globalSearch = Validator.findInOptions(option, allOptions, [], true); - - var localSearchThreshold = 8; - var globalSearchThreshold = 4; - - 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); - } - - errorFound = true; + } 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]); } - }, { - key: 'findInOptions', - - /** - * 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]; + } + this.legendLeft.redraw(); + this.legendRight.redraw(); + }; - 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; - } - } + /** + * 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] = []; } - 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]; - - 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 += ' '; + 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.'); } - str += '}\n'; + item.x = util.convert(item.x, 'Date'); + groupsContent[item.group].push(item); } - return str + '\n\n'; - } - }, { - key: 'print', - value: function print(options) { - return JSON.stringify(options).replace(/(\")|(\[)|(\])|(,"__type__")/g, '').replace(/(\,)/g, ', '); } - }, { - key: 'levenshteinDistance', - - // 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; - - var matrix = []; - - // increment along the first column of each row - var i; - for (i = 0; i <= b.length; i++) { - matrix[i] = [i]; - } - - // increment each column in the first row - var j; - for (j = 0; j <= a.length; j++) { - matrix[0][j] = j; + for (groupId in this.groups) { + if (this.groups.hasOwnProperty(groupId)) { + this.groups[groupId].setItems(groupsContent[groupId]); } + } + } + }; - // 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]; + /** + * 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 { - 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 + item.group = UNGROUPED; } + ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter; } } - - return matrix[b.length][a.length]; } - }]); - - return Validator; - })(); - exports['default'] = Validator; - exports.printStyle = printStyle; + 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); + } -/***/ }, -/* 54 */ -/***/ function(module, exports, __webpack_require__) { + this.legendLeft.redraw(); + this.legendRight.redraw(); + }; /** - * 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 + * Redraw the component, mandatory function + * @return {boolean} Returns true if the component is resized */ - 'use strict'; + LineGraph.prototype.redraw = function (forceGraphUpdate) { + var resized = false; - 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 any = 'any'; + // 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; - var allOptions = { - configure: { - enabled: { boolean: boolean }, - filter: { boolean: boolean, 'function': 'function' }, - container: { dom: dom }, - __type__: { object: object, boolean: boolean, 'function': 'function' } - }, + // update the graph if there is no lastWidth or with, used for the initial draw + if (this.lastWidth === undefined && this.props.width) { + forceGraphUpdate = true; + } - //globals : - align: { string: string }, - autoResize: { boolean: boolean }, - clickToUse: { boolean: boolean }, - dataAttributes: { string: string, array: array }, - editable: { - add: { boolean: boolean, 'undefined': 'undefined' }, - remove: { boolean: boolean, 'undefined': 'undefined' }, - updateGroup: { boolean: boolean, 'undefined': 'undefined' }, - updateTime: { boolean: boolean, 'undefined': 'undefined' }, - __type__: { boolean: boolean, object: object } - }, - end: { number: number, date: date, string: string, moment: moment }, - format: { - minorLabels: { - millisecond: { string: string, 'undefined': 'undefined' }, - second: { string: string, 'undefined': 'undefined' }, - minute: { string: string, 'undefined': 'undefined' }, - hour: { string: string, 'undefined': 'undefined' }, - weekday: { string: string, 'undefined': 'undefined' }, - day: { string: string, 'undefined': 'undefined' }, - month: { string: string, 'undefined': 'undefined' }, - year: { string: string, 'undefined': 'undefined' }, - __type__: { object: object } - }, - majorLabels: { - millisecond: { string: string, 'undefined': 'undefined' }, - second: { string: string, 'undefined': 'undefined' }, - minute: { string: string, 'undefined': 'undefined' }, - hour: { string: string, 'undefined': 'undefined' }, - weekday: { string: string, 'undefined': 'undefined' }, - day: { string: string, 'undefined': 'undefined' }, - month: { string: string, 'undefined': 'undefined' }, - year: { string: string, 'undefined': 'undefined' }, - __type__: { object: object } - }, - __type__: { object: object } - }, - groupOrder: { string: string, 'function': 'function' }, - height: { string: string, number: number }, - hiddenDates: { object: object, array: array }, - locale: { string: string }, - locales: { - __any__: { any: any }, - __type__: { object: object } - }, - margin: { - axis: { number: number }, - item: { - horizontal: { number: number, 'undefined': 'undefined' }, - vertical: { number: number, 'undefined': 'undefined' }, - __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: { 'function': 'function' }, - onUpdate: { 'function': 'function' }, - onMove: { 'function': 'function' }, - onMoving: { 'function': 'function' }, - onRemove: { 'function': 'function' }, - order: { 'function': 'function' }, - orientation: { - axis: { string: string, 'undefined': 'undefined' }, - item: { string: string, 'undefined': 'undefined' }, - __type__: { string: string, object: object } - }, - selectable: { boolean: boolean }, - showCurrentTime: { boolean: boolean }, - showMajorLabels: { boolean: boolean }, - showMinorLabels: { boolean: boolean }, - stack: { boolean: boolean }, - snap: { 'function': 'function', 'null': 'null' }, - start: { date: date, number: number, string: string, moment: moment }, - template: { 'function': 'function' }, - timeAxis: { - scale: { string: string, 'undefined': 'undefined' }, - step: { number: number, 'undefined': 'undefined' }, - __type__: { object: object } - }, - type: { string: string }, - width: { string: string, number: number }, - zoomable: { boolean: boolean }, - zoomMax: { number: number }, - zoomMin: { number: number }, + // check if this component is resized + resized = this._isResized() || resized; - __type__: { object: object } - }; + // 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; - 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: '' - } - }, + // 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); - //groupOrder: {string, 'function': 'function'}, - 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: {'function': 'function'}, - //onUpdate: {'function': 'function'}, - //onMove: {'function': 'function'}, - //onMoving: {'function': 'function'}, - //onRename: {'function': 'function'}, - //order: {'function': 'function'}, - orientation: { - axis: ['both', 'bottom', 'top'], - item: ['bottom', 'top'] - }, - selectable: true, - showCurrentTime: false, - showMajorLabels: true, - showMinorLabels: true, - stack: true, - //snap: {'function': 'function', nada}, - start: '', - //template: {'function': 'function'}, - //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] + // 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; + } } - }; - exports.allOptions = allOptions; - exports.configureOptions = configureOptions; - -/***/ }, -/* 55 */ -/***/ function(module, exports, __webpack_require__) { + // 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'; + } - 'use strict'; + // 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'; + } + } + } - var Emitter = __webpack_require__(25); - var Hammer = __webpack_require__(10); - var util = __webpack_require__(14); - var DataSet = __webpack_require__(20); - var DataView = __webpack_require__(22); - var Range = __webpack_require__(35); - var Core = __webpack_require__(38); - var TimeAxis = __webpack_require__(47); - var CurrentTime = __webpack_require__(32); - var CustomTime = __webpack_require__(50); - var LineGraph = __webpack_require__(56); - - var Configurator = __webpack_require__(51); - var Validator = __webpack_require__(53)['default']; - var printStyle = __webpack_require__(53).printStyle; - var allOptions = __webpack_require__(64).allOptions; - var configureOptions = __webpack_require__(64).configureOptions; + this.legendLeft.redraw(); + this.legendRight.redraw(); + return resized; + }; /** - * 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 + * Update and redraw the graph. + * */ - 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, - - autoResize: true, - - orientation: { - axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both' - item: 'bottom' // not relevant for Graph2d - }, - - 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 = []; + 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; - 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) + // 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); + } + } } - }; - - // 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.components.push(this.timeAxis); - //this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); - - // current time bar - this.currentTime = new CurrentTime(this.body); - this.components.push(this.currentTime); - - // item set - this.linegraph = new LineGraph(this.body); - this.components.push(this.linegraph); - - this.itemsData = null; // DataSet - this.groupsData = null; // DataSet + 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); - 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)); - }; + // apply sampling, if disabled, it will pass through this function. + this._applySampling(groupIds, groupsData); - // apply options - if (options) { - this.setOptions(options); - } + // we transform the X coordinates to detect collisions + for (i = 0; i < groupIds.length; i++) { + preprocessedGroupData[groupIds[i]] = this._convertXcoordinates(groupsData[groupIds[i]]); + } - // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! - if (groups) { - this.setGroups(groups); - } + // now all needed data has been collected we start the processing. + this._getYRanges(groupIds, preprocessedGroupData, groupRanges); - // create itemset - if (items) { - this.setItems(items); - } else { - this._redraw(); - } - } + // 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; - // Extend the functionality from Core - Graph2d.prototype = new Core(); + // 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); + } - 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); + // 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); + } + } } - Core.prototype.setOptions.call(this, options); + // cleanup unused svg elements + DOMutil.cleanupElements(this.svgElements); + return false; }; /** - * Set items - * @param {vis.DataSet | Array | null} items + * 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 */ - 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' + 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); + } + } + } } - }); - } - - // set items - this.itemsData = newDataSet; - this.linegraph && this.linegraph.setItems(newDataSet); - - 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.setWindow(start, end, { animation: false }); - } else { - this.fit({ animation: false }); } } }; /** - * Set groups - * @param {vis.DataSet | Array} groups + * + * @param groupIds + * @param groupsData + * @private */ - 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); - } + 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; - this.groupsData = newDataSet; - this.linegraph.setGroups(newDataSet); - }; + // 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))); - /** - * 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; + var sampledData = []; + for (var j = 0; j < amountOfPoints; j += increment) { + sampledData.push(dataContainer[j]); + } + groupsData[groupIds[i]] = sampledData; + } + } + } } }; /** - * This checks if the visible option of the supplied group (by ID) is true or false. - * @param groupId - * @returns {*} + * + * + * @param {array} groupIds + * @param {object} groupsData + * @param {object} groupRanges | this is being filled here + * @private */ - 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; + 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 && options.style === 'bar') { + 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]); + } + } + } + + // 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'); } }; /** - * 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 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 */ - Graph2d.prototype.getDataRange = 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; - } + 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 = 1000000000; + maxLeft = -1000000000; + } else if (group && group.options.yAxisOrientation) { + yAxisRightUsed = true; + minRight = 1000000000; + maxRight = -1000000000; } } - } - return { - min: min != null ? new Date(min) : null, - max: max != null ? new Date(max) : null - }; - }; + // 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; - /** - * 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); + 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; + } + } + } + } - var customTime = CustomTime.customTimeFromTarget(event); + 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; - 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'; + 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; + } - var value = []; - var yAxisLeft = this.linegraph.yAxisLeft; - var yAxisRight = this.linegraph.yAxisRight; - if (!yAxisLeft.hidden) { - value.push(yAxisLeft.screenToValue(y)); + 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; } - if (!yAxisRight.hidden) { - value.push(yAxisRight.screenToValue(y)); + + // 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); + } } - 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 - }; + return resized; }; /** - * Load a configurator - * @return {Object} + * 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 */ - Graph2d.prototype._createConfigurator = function () { - return new Configurator(this, this.dom.container, configureOptions); + 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; }; - module.exports = Graph2d; - -/***/ }, -/* 56 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; + /** + * 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 util = __webpack_require__(14); - var DOMutil = __webpack_require__(19); - var DataSet = __webpack_require__(20); - var DataView = __webpack_require__(22); - var Component = __webpack_require__(33); - var DataAxis = __webpack_require__(57); - var GraphGroup = __webpack_require__(59); - var Legend = __webpack_require__(63); - var BarFunctions = __webpack_require__(62); - var LineFunctions = __webpack_require__(60); + 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 UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items + return extractedData; + }; /** - * This is the constructor of the LineGraph. It requires a Timeline body and options. + * 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 body - * @param options - * @constructor + * @param datapoints + * @param group + * @returns {Array} + * @private */ - function LineGraph(body, options) { - this.id = util.randomUUID(); - this.body = body; + 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; + } - 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 } + 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 }); + } + + group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0))); + + return extractedData; + }; + + module.exports = LineGraph; + +/***/ }, +/* 54 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var util = __webpack_require__(13); + var DOMutil = __webpack_require__(18); + var Component = __webpack_require__(32); + var DataStep = __webpack_require__(55); + + /** + * 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.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; }, - right: { - range: { min: undefined, max: undefined }, - format: function format(value) { - return value; - }, - title: { text: undefined, style: undefined } - } + title: { text: undefined, style: undefined } }, - legend: { - enabled: false, - icons: true, - left: { - visible: true, - position: 'top-left' // top/bottom - left,right + right: { + range: { min: undefined, max: undefined }, + format: function format(value) { + return value; }, - right: { - visible: true, - position: 'top-right' // top/bottom - left,right - } - }, - groups: { - visibility: {} + title: { text: undefined, style: undefined } } }; - // options is shared by this ItemSet and all its items - this.options = util.extend({}, this.defaultOptions); - this.dom = {}; + this.linegraphOptions = linegraphOptions; + this.linegraphSVG = svg; this.props = {}; - this.hammer = null; - this.groups = {}; - this.abortedGraphUpdate = false; - this.updateSVGheight = false; - this.updateSVGheightOnResize = false; + this.DOMelements = { // dynamic elements + lines: {}, + labels: {}, + title: {} + }; - var me = this; - this.itemsData = null; // DataSet - this.groupsData = null; // DataSet + this.dom = {}; - // 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.range = { start: 0, end: 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.options = util.extend({}, this.defaultOptions); + this.conversionFactor = 1; - 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 + 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.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); - }); + this.iconsRemoved = false; + + this.groups = {}; + this.amountOfGroups = 0; // 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'); - } - - LineGraph.prototype = new Component(); - - /** - * 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; - // 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 me = this; + this.body.emitter.on('verticalDrag', function () { + me.dom.lineContainer.style.top = me.body.domProps.scrollTop + 'px'; + }); + } - // data axis - this.options.dataAxis.orientation = 'left'; - this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups); + DataAxis.prototype = new Component(); - this.options.dataAxis.orientation = 'right'; - this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups); - delete this.options.dataAxis.orientation; + DataAxis.prototype.addGroup = function (label, graphOptions) { + if (!this.groups.hasOwnProperty(label)) { + this.groups[label] = graphOptions; + } + this.amountOfGroups += 1; + }; - // 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); + DataAxis.prototype.updateGroup = function (label, graphOptions) { + this.groups[label] = graphOptions; + }; - this.show(); + DataAxis.prototype.removeGroup = function (label) { + if (this.groups.hasOwnProperty(label)) { + delete this.groups[label]; + this.amountOfGroups -= 1; + } }; - /** - * 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) { + DataAxis.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'); - - 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.yAxisLeft) { - if (options.dataAxis !== undefined) { - this.yAxisLeft.setOptions(this.options.dataAxis); - this.yAxisRight.setOptions(this.options.dataAxis); - } + 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 (this.legendLeft) { - if (options.legend !== undefined) { - this.legendLeft.setOptions(this.options.legend); - this.legendRight.setOptions(this.options.legend); - } - } + this.minWidth = Number(('' + this.options.width).replace('px', '')); - if (this.groups.hasOwnProperty(UNGROUPED)) { - this.groups[UNGROUPED].setOptions(options); + if (redraw === true && this.dom.frame) { + this.hide(); + this.show(); } } - - // this is used to redraw the graph if the visibility of the groups is changed. - if (this.dom.frame) { - this.redraw(true); - } }; /** - * Hide the component from the DOM + * Create the HTML DOM for the DataAxis */ - LineGraph.prototype.hide = function () { - // remove the frame containing the items - if (this.dom.frame.parentNode) { - this.dom.frame.parentNode.removeChild(this.dom.frame); - } - }; + 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; - /** - * 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); - } + 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'; + + // 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); }; - /** - * Set items - * @param {vis.DataSet | null} items - */ - LineGraph.prototype.setItems = function (items) { - var me = this, - ids, - oldItemsData = this.itemsData; + DataAxis.prototype._redrawGroupIcons = function () { + DOMutil.prepareElements(this.svgElements); - // replace the dataset - if (!items) { - this.itemsData = null; - } else if (items instanceof DataSet || items instanceof DataView) { - this.itemsData = items; + 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 { - throw new TypeError('Data must be an instance of DataSet or DataView'); + x = this.width - iconWidth - iconOffset; } - if (oldItemsData) { - // unsubscribe from old dataset - util.forEach(this.itemListeners, function (callback, event) { - oldItemsData.off(event, callback); - }); + var groupArray = Object.keys(this.groups); + groupArray.sort(function (a, b) { + return a < b ? -1 : 1; + }); - // remove all drawn items - ids = oldItemsData.getIds(); - this._onRemove(ids); + 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; + } } - if (this.itemsData) { - // subscribe to new dataset - var id = this.id; - util.forEach(this.itemListeners, function (callback, event) { - me.itemsData.on(event, callback, id); - }); + DOMutil.cleanupElements(this.svgElements); + this.iconsRemoved = false; + }; - // add all new items - ids = this.itemsData.getIds(); - this._onAdd(ids); + DataAxis.prototype._cleanupIcons = function () { + if (this.iconsRemoved === false) { + DOMutil.prepareElements(this.svgElements); + DOMutil.cleanupElements(this.svgElements); + this.iconsRemoved = true; } - this._updateUngrouped(); - //this._updateGraph(); - this.redraw(true); }; /** - * Set groups - * @param {vis.DataSet} groups + * Create the HTML DOM for the DataAxis */ - 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); - }); - - // 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'); + 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); + } } - if (this.groupsData) { - // subscribe to new dataset - var id = this.id; - util.forEach(this.groupListeners, function (callback, event) { - me.groupsData.on(event, callback, id); - }); - - // draw all ms - ids = this.groupsData.getIds(); - this._onAddGroups(ids); + if (!this.dom.lineContainer.parentNode) { + this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer); } - this._onUpdate(); }; /** - * Update the data - * @param [ids] - * @private + * Create the HTML DOM for the DataAxis */ - 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]); + DataAxis.prototype.hide = function () { + this.hidden = true; + if (this.dom.frame.parentNode) { + this.dom.frame.parentNode.removeChild(this.dom.frame); } - //this._updateGraph(); - this.redraw(true); - }; - LineGraph.prototype._onAddGroups = function (groupIds) { - this._onUpdateGroups(groupIds); + if (this.dom.lineContainer.parentNode) { + this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer); + } }; /** - * this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph - * @param {Array} groupIds - * @private + * Set a range (start and end) + * @param end + * @param start + * @param end */ - 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]]; + DataAxis.prototype.setRange = function (start, end) { + if (this.master === false && this.options.alignZeros === true && this.zeroCrossing != -1) { + if (start > 0) { + start = 0; } } - this._updateUngrouped(); - //this._updateGraph(); - this.redraw(true); + this.range.start = start; + this.range.end = end; }; /** - * update a group object with the group dataset entree - * - * @param group - * @param groupId - * @private + * Repaint the component + * @return {boolean} Returns true if the component is resized */ - 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]); + DataAxis.prototype.redraw = function () { + var resized = false; + var activeGroups = 0; + + // 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', '')); + + // 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 props = this.props; + var frame = this.dom.frame; + + // update classname + frame.className = 'vis-data-axis'; + + // calculate character width and height + this._calculateCharSize(); + + 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 { - this.yAxisLeft.addGroup(groupId, this.groups[groupId]); - this.legendLeft.addGroup(groupId, this.groups[groupId]); + // 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; } - } 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]); + + resized = this._redrawLabels(); + resized = this._isResized() || resized; + + if (this.options.icons === true) { + this._redrawGroupIcons(); } else { - this.yAxisLeft.updateGroup(groupId, this.groups[groupId]); - this.legendLeft.updateGroup(groupId, this.groups[groupId]); + this._cleanupIcons(); } + + this._redrawTitle(orientation); } - this.legendLeft.redraw(); - this.legendRight.redraw(); + return resized; }; /** - * this updates all groups, it is used when there is an update the the itemset. - * + * Repaint major and minor text labels and vertical grid lines * @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]); - } - } - } - }; + DataAxis.prototype._redrawLabels = function () { + var resized = false; + DOMutil.prepareElements(this.DOMelements.lines); + DOMutil.prepareElements(this.DOMelements.labels); + var orientation = this.options['orientation']; - /** - * 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 { - item.group = UNGROUPED; - } - ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter; - } + // 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; } - } - - 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); + rangeStart = this.range.start; + rangeEnd = this.range.end; } + minimumStep = this.stepPixels; } else { - delete this.groups[UNGROUPED]; - this.legendLeft.removeGroup(UNGROUPED); - this.legendRight.removeGroup(UNGROUPED); - this.yAxisLeft.removeGroup(UNGROUPED); - this.yAxisRight.removeGroup(UNGROUPED); + // 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.legendLeft.redraw(); - this.legendRight.redraw(); - }; - - /** - * Redraw the component, mandatory function - * @return {boolean} Returns true if the component is resized - */ - LineGraph.prototype.redraw = function (forceGraphUpdate) { - var resized = false; - - // 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; + 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 + ); - // update the graph if there is no lastWidth or with, used for the initial draw - if (this.lastWidth === undefined && this.props.width) { - forceGraphUpdate = true; + // 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 if this component is resized - resized = this._isResized() || resized; + // value at the bottom of the SVG + this.valueAtBottom = step.marginEnd; - // 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; + 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 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 (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 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; + 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); + } } - } - // 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'; + // get zero crossing + if (this.master === true && step.current === 0) { + this.zeroCrossing = stepIndex; } - this.updateSVGheight = false; - } else { - this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px'; + + step.next(); + stepIndex += 1; } - // zoomed is here to ensure that animations are shown correctly. - if (resized == true || zoomed == true || this.abortedGraphUpdate == true || forceGraphUpdate == true) { - resized = this._updateGraph() || resized; + // 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 { - // 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'; - } - } + DOMutil.cleanupElements(this.DOMelements.lines); + DOMutil.cleanupElements(this.DOMelements.labels); + resized = false; } - this.legendLeft.redraw(); - this.legendRight.redraw(); return resized; }; - /** - * 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; + DataAxis.prototype.convertValue = function (value) { + var invertedValue = this.valueAtBottom - value; + var convertedValue = invertedValue * this.conversionFactor; + return convertedValue; + }; - // 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); + DataAxis.prototype.screenToValue = function (x) { + return this.valueAtBottom - x / this.conversionFactor; + }; - // apply sampling, if disabled, it will pass through this function. - this._applySampling(groupIds, groupsData); + /** + * 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'; + } - // we transform the X coordinates to detect collisions - for (i = 0; i < groupIds.length; i++) { - preprocessedGroupData[groupIds[i]] = this._convertXcoordinates(groupsData[groupIds[i]]); - } + label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px'; - // now all needed data has been collected we start the processing. - this._getYRanges(groupIds, preprocessedGroupData, groupRanges); + text += ''; - // 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; + var largestWidth = Math.max(this.props.majorCharWidth, this.props.minorCharWidth); + if (this.maxLabelSize < text.length * largestWidth) { + this.maxLabelSize = text.length * largestWidth; + } + }; - // 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); - } + /** + * 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 = ''; - // 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); - } + if (orientation === 'left') { + line.style.left = this.width - offset + 'px'; + } else { + line.style.right = this.width - offset + 'px'; } - } - // cleanup unused svg elements - DOMutil.cleanupElements(this.svgElements); - return false; + line.style.width = width + 'px'; + line.style.top = y + 'px'; + } }; /** - * 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 + * Create a title for the axis * @private + * @param orientation */ - 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); - } - } - } - } + 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); }; /** - * - * @param groupIds - * @param groupsData + * 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 */ - 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; + 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); - // 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))); + this.props.minorCharHeight = measureCharMinor.clientHeight; + this.props.minorCharWidth = measureCharMinor.clientWidth; - var sampledData = []; - for (var j = 0; j < amountOfPoints; j += increment) { - sampledData.push(dataContainer[j]); - } - groupsData[groupIds[i]] = sampledData; - } - } - } + 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; + +/***/ }, +/* 55 */ +/***/ function(module, exports, __webpack_require__) { + /** + * @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 * - * @param {array} groupIds - * @param {object} groupsData - * @param {object} groupRanges | this is being filled here - * @private + * 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 */ - 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 && options.style === 'bar') { - 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]); - } - } - } + 'use strict'; - // 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 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); + } + + /** + * 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); }; /** - * 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 + * Automatically determine the scale that bests fits the provided minimum step + * @param {Number} [minimumStep] The minimum step size in pixels */ - 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 = 1000000000; - maxLeft = -1000000000; - } else if (group && group.options.yAxisOrientation) { - yAxisRightUsed = true; - minRight = 1000000000; - maxRight = -1000000000; - } - } + 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); - // 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; + var minorStepIdx = -1; + var magnitudefactor = Math.pow(10, orderOfMagnitude); - 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; - } - } - } - } + var start = 0; + if (orderOfMagnitude < 0) { + start = orderOfMagnitude; + } - if (yAxisLeftUsed == true) { - this.yAxisLeft.setRange(minLeft, maxLeft); + 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 (yAxisRightUsed == true) { - this.yAxisRight.setRange(minRight, maxRight); + if (solutionFound === true) { + break; } } - resized = this._toggleAxisVisiblity(yAxisLeftUsed, this.yAxisLeft) || resized; - resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized; + this.stepIndex = minorStepIdx; + this.scale = magnitudefactor; + this.step = magnitudefactor * this.minorSteps[minorStepIdx]; + }; - if (yAxisRightUsed == true && yAxisLeftUsed == true) { - this.yAxisLeft.drawIcons = true; - this.yAxisRight.drawIcons = true; - } else { - this.yAxisLeft.drawIcons = false; - this.yAxisRight.drawIcons = false; + /** + * 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 = {}; } - this.yAxisRight.master = !yAxisLeftUsed; - if (this.yAxisRight.master == false) { - if (yAxisRightUsed == true) { - this.yAxisLeft.lineOffset = this.yAxisRight.width; - } else { - this.yAxisLeft.lineOffset = 0; - } - 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; - } + 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; - // 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); - } + 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; } - return resized; + this.deadSpace = this.roundToMinor(niceEnd) - niceEnd + this.roundToMinor(niceStart) - niceStart; + this.marginRange = this.marginEnd - this.marginStart; + + this.current = this.marginEnd; }; - /** - * 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; - } + 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 { - if (!axis.dom.frame.parentNode && axis.hidden == true) { - axis.show(); - changed = true; - } + return rounded; } - return changed; }; /** - * 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 + * Check if the there is a next step + * @return {boolean} true if the current date has not passed the end date */ - LineGraph.prototype._convertXcoordinates = function (datapoints) { - var extractedData = []; - var xValue, yValue; - var toScreen = this.body.util.toScreen; + DataStep.prototype.hasNext = function () { + return this.current >= this.marginStart; + }; - 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 }); + /** + * 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; } + }; - return extractedData; + /** + * Do the next step + */ + DataStep.prototype.previous = function () { + this.current += this.step; + this.marginEnd += this.step; + this.marginRange = this.marginEnd - this.marginStart; }; /** - * 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 + * Get the current datetime + * @return {String} current The current date */ - 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; + 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); } - 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 }); + if (typeof returnValue === 'number') { + return '' + returnValue; + } else if (typeof returnValue === 'string') { + return returnValue; + } else { + return current.toPrecision(5); } + }; - group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0))); + /** + * 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; + }; - return extractedData; + 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 = LineGraph; + module.exports = DataStep; /***/ }, -/* 57 */ +/* 56 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var util = __webpack_require__(14); - var DOMutil = __webpack_require__(19); - var Component = __webpack_require__(33); - var DataStep = __webpack_require__(58); + var util = __webpack_require__(13); + var DOMutil = __webpack_require__(18); + var Line = __webpack_require__(57); + var Bar = __webpack_require__(59); + var Points = __webpack_require__(58); /** - * A horizontal time axis - * @param {Object} [options] See DataAxis.setOptions for the available - * options. - * @constructor DataAxis - * @extends Component - * @param body + * /** + * @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 DataAxis(body, options, svg, linegraphOptions) { - this.id = util.randomUUID(); - this.body = body; + 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.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 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; + }); } - }; - - this.linegraphOptions = linegraphOptions; - this.linegraphSVG = svg; - this.props = {}; - this.DOMelements = { // dynamic elements - lines: {}, - labels: {}, - title: {} - }; - - this.dom = {}; - - this.range = { start: 0, end: 0 }; - - this.options = util.extend({}, this.defaultOptions); - this.conversionFactor = 1; - - 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; + // typecast all items to numbers. Takes around 10ms for 500.000 items + for (var i = 0; i < this.itemsData.length; i++) { + this.itemsData[i].y = Number(this.itemsData[i].y); + } + } else { + this.itemsData = []; + } + }; - this.lineOffset = 0; - this.master = true; - this.svgElements = {}; - this.iconsRemoved = false; + /** + * 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; + }; - this.groups = {}; - this.amountOfGroups = 0; + /** + * 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); - // create the HTML DOM - this._create(); + // if the group's drawPoints is a function delegate the callback to the onRender property + if (typeof options.drawPoints == 'function') { + options.drawPoints = { + onRender: options.drawPoints + }; + } - var me = this; - this.body.emitter.on('verticalDrag', function () { - me.dom.lineContainer.style.top = me.body.domProps.scrollTop + 'px'; - }); - } + util.mergeOptions(this.options, options, 'interpolation'); + util.mergeOptions(this.options, options, 'drawPoints'); + util.mergeOptions(this.options, options, 'shaded'); - DataAxis.prototype = new Component(); + 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; + } + } + } + } + } - DataAxis.prototype.addGroup = function (label, graphOptions) { - if (!this.groups.hasOwnProperty(label)) { - this.groups[label] = graphOptions; + 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.amountOfGroups += 1; }; - DataAxis.prototype.updateGroup = function (label, graphOptions) { - this.groups[label] = graphOptions; + /** + * 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); }; - DataAxis.prototype.removeGroup = function (label) { - if (this.groups.hasOwnProperty(label)) { - delete this.groups[label]; - this.amountOfGroups -= 1; - } - }; + /** + * 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; - DataAxis.prototype.setOptions = function (options) { - if (options) { - var redraw = false; - if (this.options.orientation != options.orientation && options.orientation !== undefined) { - redraw = true; + 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); } - 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', '')); + 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 (redraw === true && this.dom.frame) { - this.hide(); - this.show(); + if (this.options.drawPoints.enabled == true) { + var groupTemplate = { + style: this.options.drawPoints.style, + size: this.options.drawPoints.size, + className: this.className + }; + DOMutil.drawPoint(x + 0.5 * iconWidth, y, groupTemplate, 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); } }; /** - * Create the HTML DOM for the DataAxis + * return the legend entree for this group. + * + * @param iconWidth + * @param iconHeight + * @returns {{icon: HTMLElement, label: (group.content|*|string), orientation: (.options.yAxisOrientation|*)}} */ - 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; + 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 }; + }; - 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'; + GraphGroup.prototype.getYRange = function (groupData) { + return this.type.getYRange(groupData); + }; - // 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); + GraphGroup.prototype.getData = function (groupData) { + return this.type.getData(groupData); }; - DataAxis.prototype._redrawGroupIcons = function () { - DOMutil.prepareElements(this.svgElements); + GraphGroup.prototype.draw = function (dataset, group, framework) { + this.type.draw(dataset, group, framework); + }; - var x; - var iconWidth = this.options.iconWidth; - var iconHeight = 15; - var iconOffset = 4; - var y = iconOffset + 0.5 * iconHeight; + module.exports = GraphGroup; - if (this.options.orientation === 'left') { - x = iconOffset; - } else { - x = this.width - iconWidth - iconOffset; - } +/***/ }, +/* 57 */ +/***/ function(module, exports, __webpack_require__) { - var groupArray = Object.keys(this.groups); - groupArray.sort(function (a, b) { - return a < b ? -1 : 1; - }); + 'use strict'; - 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; - } + var DOMutil = __webpack_require__(18); + var Points = __webpack_require__(58); + + 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; + }; - DOMutil.cleanupElements(this.svgElements); - this.iconsRemoved = false; + 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 }; }; - DataAxis.prototype._cleanupIcons = function () { - if (this.iconsRemoved === false) { - DOMutil.prepareElements(this.svgElements); - DOMutil.cleanupElements(this.svgElements); - this.iconsRemoved = true; + 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); } }; - /** - * 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); + 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 { - this.body.dom.right.appendChild(this.dom.frame); + if (combinedData[i].y < 0) { + intersections[key].accumulatedNegative += combinedData[i].y; + } else { + intersections[key].accumulatedPositive += combinedData[i].y; + } } } - - if (!this.dom.lineContainer.parentNode) { - this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer); + 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 }; }; /** - * Create the HTML DOM for the DataAxis + * Fill the intersections object with counters of how many datapoints share the same x coordinates + * @param intersections + * @param combinedData + * @private */ - DataAxis.prototype.hide = function () { - this.hidden = true; - if (this.dom.frame.parentNode) { - this.dom.frame.parentNode.removeChild(this.dom.frame); - } - - if (this.dom.lineContainer.parentNode) { - this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer); + 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; + } } }; /** - * Set a range (start and end) - * @param end - * @param start - * @param end + * draw a line graph + * + * @param dataset + * @param group */ - DataAxis.prototype.setRange = function (start, end) { - if (this.master === false && this.options.alignZeros === true && this.zeroCrossing != -1) { - if (start > 0) { - start = 0; + 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.range.start = start; - this.range.end = end; }; /** - * Repaint the component - * @return {boolean} Returns true if the component is resized + * 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 */ - DataAxis.prototype.redraw = function () { - var resized = false; - var activeGroups = 0; + 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++) { - // Make sure the line container adheres to the vertical scrolling. - this.dom.lineContainer.style.top = this.body.domProps.scrollTop + 'px'; + p0 = i == 0 ? data[0] : data[i - 1]; + p1 = data[i]; + p2 = data[i + 1]; + p3 = i + 2 < length ? data[i + 2] : p2; - 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++; - } - } + // 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 + ' '; } - if (this.amountOfGroups === 0 || activeGroups === 0) { - this.hide(); + + 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 { - this.show(); - this.height = Number(this.linegraphSVG.style.height.replace('px', '')); + 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++) { - // 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; + p0 = i == 0 ? data[0] : data[i - 1]; + p1 = data[i]; + p2 = data[i + 1]; + p3 = i + 2 < length ? data[i + 2] : p2; - var props = this.props; - var frame = this.dom.frame; + 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)); - // update classname - frame.className = 'vis-data-axis'; + // Catmull-Rom to Cubic Bezier conversion matrix - // calculate character width and height - this._calculateCharSize(); + // A = 2d1^2a + 3d1^a * d2^a + d3^2a + // B = 2d3^2a + 3d3^a * d2^a + d2^2a - var orientation = this.options.orientation; - var showMinorLabels = this.options.showMinorLabels; - var showMajorLabels = this.options.showMajorLabels; + // [ 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 ] - // determine the width and height of the elements for the axis - props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0; - props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 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); - 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; + 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; + } - // 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; + 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 + ' '; } - resized = this._redrawLabels(); - resized = this._isResized() || resized; + return d; + } + }; - if (this.options.icons === true) { - this._redrawGroupIcons(); + /** + * 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 { - this._cleanupIcons(); + d += ' ' + data[i].x + ',' + data[i].y; } + } + return d; + }; + + module.exports = Line; + +/***/ }, +/* 58 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var DOMutil = __webpack_require__(18); + + function Points(groupId, options) { + this.groupId = groupId; + this.options = options; + } - this._redrawTitle(orientation); + 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 resized; + return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation }; + }; + + Points.prototype.draw = function (dataset, group, framework, offset) { + Points.draw(dataset, group, framework, offset); }; /** - * Repaint major and minor text labels and vertical grid lines - * @private + * draw the data points + * + * @param {Array} dataset + * @param {Object} JSONcontainer + * @param {Object} svg | SVG DOM element + * @param {GraphGroup} group + * @param {Number} [offset] */ - DataAxis.prototype._redrawLabels = function () { - var resized = false; - DOMutil.prepareElements(this.DOMelements.lines); - DOMutil.prepareElements(this.DOMelements.labels); - var orientation = this.options['orientation']; + Points.draw = function (dataset, group, framework, offset) { + offset = offset || 0; + var callback = getCallback(); - // 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; - } + for (var i = 0; i < dataset.length; i++) { + if (!callback) { + // draw the point the simple way. + DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, getGroupTemplate(), framework.svgElements, framework.svg, dataset[i].label); } else { - rangeStart = this.range.start; - rangeEnd = this.range.end; + var callbackResult = callback(dataset[i], group, framework); // result might be true, false or an object + if (callbackResult === true || typeof callbackResult === 'object') { + DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, getGroupTemplate(callbackResult), framework.svgElements, framework.svg, dataset[i].label); + } } - 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 - ); - - // 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); - } + function getGroupTemplate(callbackResult) { + callbackResult = typeof callbackResult === 'undefined' ? {} : callbackResult; + return { + style: callbackResult.style || group.options.drawPoints.style, + size: callbackResult.size || group.options.drawPoints.size, + className: callbackResult.className || group.className + }; } - // 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); - } + function getCallback() { + var callback = undefined; + // check for the graph2d onRender + if (framework.options.drawPoints.onRender && typeof framework.options.drawPoints.onRender == 'function') { + callback = framework.options.drawPoints.onRender; } - // get zero crossing - if (this.master === true && step.current === 0) { - this.zeroCrossing = stepIndex; + // override it with the group onRender if defined + if (group.group.options && group.group.options.drawPoints && group.group.options.drawPoints.onRender && typeof group.group.options.drawPoints.onRender == 'function') { + callback = group.group.options.drawPoints.onRender; } - step.next(); - stepIndex += 1; + return callback; } + }; - // get zero crossing if it's the last step - if (this.master === true && step.current === 0) { - this.zeroCrossing = stepIndex; - } + module.exports = Points; - this.conversionFactor = this.stepPixels / step.step; +/***/ }, +/* 59 */ +/***/ function(module, exports, __webpack_require__) { - // 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; + 'use strict'; - // 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; - } + var DOMutil = __webpack_require__(18); + var Points = __webpack_require__(58); - return resized; - }; + function Bargraph(groupId, options) { + this.groupId = groupId; + this.options = options; + } - DataAxis.prototype.convertValue = function (value) { - var invertedValue = this.valueAtBottom - value; - var convertedValue = invertedValue * this.conversionFactor; - return convertedValue; + 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 }; }; - DataAxis.prototype.screenToValue = function (x) { - return this.valueAtBottom - x / this.conversionFactor; + 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 a label for the axis at position x - * @private - * @param y - * @param text - * @param orientation - * @param className - * @param characterHeight + * draw a bar graph + * + * @param groupIds + * @param processedGroupData */ - 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'; + 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; + } + } + } } - label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px'; + if (barPoints === 0) { + return; + } - text += ''; + // 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 largestWidth = Math.max(this.props.majorCharWidth, this.props.minorCharWidth); - if (this.maxLabelSize < text.length * largestWidth) { - this.maxLabelSize = text.length * largestWidth; - } - }; + // get intersections + Bargraph._getDataIntersections(intersections, combinedData); - /** - * 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 = ''; + // plot barchart + for (i = 0; i < combinedData.length; i++) { + group = framework.groups[combinedData[i].groupId]; + var minWidth = 0.1 * group.options.barChart.width; - if (orientation === 'left') { - line.style.left = this.width - offset + 'px'; + 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 { - line.style.right = this.width - offset + 'px'; - } + 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; - line.style.width = width + 'px'; - line.style.top = y + 'px'; + 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); + } } }; /** - * Create a title for the axis + * Fill the intersections object with counters of how many datapoints share the same x coordinates + * @param intersections + * @param combinedData * @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); + 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 (orientation === 'left') { - title.style.left = this.props.titleCharHeight + 'px'; - } else { - title.style.right = this.props.titleCharHeight + 'px'; + 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; } - - 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. + * 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 */ - 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; + Bargraph._getSafeDrawData = function (coreDistance, group, minWidth) { + var width, offset; + if (coreDistance < group.options.barChart.width && coreDistance > 0) { + width = coreDistance < minWidth ? minWidth : coreDistance; - this.dom.frame.removeChild(measureCharMajor); + 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 (!('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); + return { width: width, offset: offset }; + }; - this.props.titleCharHeight = measureCharTitle.clientHeight; - this.props.titleCharWidth = measureCharTitle.clientWidth; + 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 = {}; - this.dom.frame.removeChild(measureCharTitle); + Bargraph._getDataIntersections(intersections, combinedData); + groupRanges[groupLabel] = Bargraph._getStackedYRange(intersections, combinedData); + groupRanges[groupLabel].yAxisOrientation = orientation; + groupIds.push(groupLabel); } }; - module.exports = DataAxis; - -/***/ }, -/* 58 */ -/***/ function(module, exports, __webpack_require__) { - - /** - * @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 DataStep(start, end, minimumStep, containerHeight, customRange, formattingFunction, alignZeros) { - // variables - this.current = 0; + 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; + } + } - this.autoScale = true; - this.stepIndex = 0; - this.step = 1; - this.scale = 1; - this.formattingFunction = formattingFunction; + return { min: yMin, max: yMax }; + }; - this.marginStart; - this.marginEnd; - this.deadSpace = 0; + module.exports = Bargraph; - this.majorSteps = [1, 2, 5, 10]; - this.minorSteps = [0.25, 0.5, 1, 2]; +/***/ }, +/* 60 */ +/***/ function(module, exports, __webpack_require__) { - this.alignZeros = alignZeros; + 'use strict'; - this.setRange(start, end, minimumStep, containerHeight, customRange); - } + var util = __webpack_require__(13); + var DOMutil = __webpack_require__(18); + var Component = __webpack_require__(32); /** - * 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 + * Legend for Graph2d */ - 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;; - } + 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; - if (this.autoScale === true) { - this.setMinimumStep(minimumStep, containerHeight); - } + this.svgElements = {}; + this.dom = {}; + this.groups = {}; + this.amountOfGroups = 0; + this._create(); - this.setFirst(customRange); - }; + this.setOptions(options); + } - /** - * 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); + Legend.prototype = new Component(); - var minorStepIdx = -1; - var magnitudefactor = Math.pow(10, orderOfMagnitude); + Legend.prototype.clear = function () { + this.groups = {}; + this.amountOfGroups = 0; + }; - var start = 0; - if (orderOfMagnitude < 0) { - start = orderOfMagnitude; - } + Legend.prototype.addGroup = function (label, graphOptions) { - 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; - } + if (!this.groups.hasOwnProperty(label)) { + this.groups[label] = graphOptions; } - this.stepIndex = minorStepIdx; - this.scale = magnitudefactor; - this.step = magnitudefactor * this.minorSteps[minorStepIdx]; + this.amountOfGroups += 1; }; - /** - * 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; + Legend.prototype.updateGroup = function (label, graphOptions) { + this.groups[label] = graphOptions; + }; - // 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; + Legend.prototype.removeGroup = function (label) { + if (this.groups.hasOwnProperty(label)) { + delete this.groups[label]; + this.amountOfGroups -= 1; } + }; - this.deadSpace = this.roundToMinor(niceEnd) - niceEnd + this.roundToMinor(niceStart) - niceStart; - this.marginRange = this.marginEnd - this.marginStart; + 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.current = this.marginEnd; - }; + 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'; - 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; - } + 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); }; /** - * Check if the there is a next step - * @return {boolean} true if the current date has not passed the end date + * Hide the component from the DOM */ - DataStep.prototype.hasNext = function () { - return this.current >= this.marginStart; + Legend.prototype.hide = function () { + // remove the frame containing the items + if (this.dom.frame.parentNode) { + this.dom.frame.parentNode.removeChild(this.dom.frame); + } }; /** - * Do the next step + * Show the component in the DOM (when not already visible). + * @return {Boolean} changed */ - 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; + Legend.prototype.show = function () { + // show frame containing the items + if (!this.dom.frame.parentNode) { + this.body.dom.center.appendChild(this.dom.frame); } }; - /** - * Do the next step - */ - DataStep.prototype.previous = function () { - this.current += this.step; - this.marginEnd += this.step; - this.marginRange = this.marginEnd - this.marginStart; + Legend.prototype.setOptions = function (options) { + var fields = ['enabled', 'orientation', 'icons', 'left', 'right']; + util.selectiveDeepExtend(fields, this.options, options); }; - /** - * 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); + 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 (typeof returnValue === 'number') { - return '' + returnValue; - } else if (typeof returnValue === 'string') { - return returnValue; + if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false || activeGroups == 0) { + this.hide(); } else { - return current.toPrecision(5); + 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'; } }; - /** - * 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; - }; + 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; + }); - 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(); + 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 = DataStep; + module.exports = Legend; /***/ }, -/* 59 */ +/* 61 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; + "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__(14); - var DOMutil = __webpack_require__(19); - var Line = __webpack_require__(60); - var Bar = __webpack_require__(62); - var Points = __webpack_require__(61); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var util = __webpack_require__(13); /** - * /** - * @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 + * @class Groups + * This class can store groups and options specific for groups. */ - 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; + + 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); } - 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; - }); + _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); + } + } + } + } } - // typecast all items to numbers. Takes around 10ms for 500.000 items - for (var i = 0; i < this.itemsData.length; i++) { - this.itemsData[i].y = Number(this.itemsData[i].y); + }, { + key: "clear", + + /** + * Clear all groups + */ + value: function clear() { + this.groups = {}; + this.groupsArray = []; } - } else { - this.itemsData = []; - } - }; + }, { + key: "get", - /** - * 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; - }; + /** + * 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"]; + +/***/ }, +/* 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 _componentsNode = __webpack_require__(63); + + var _componentsNode2 = _interopRequireDefault(_componentsNode); + + var _componentsSharedLabel = __webpack_require__(64); + + var _componentsSharedLabel2 = _interopRequireDefault(_componentsSharedLabel); + + var util = __webpack_require__(13); + var DataSet = __webpack_require__(19); + var DataView = __webpack_require__(21); + + var NodesHandler = (function () { + function NodesHandler(body, images, groups, layoutEngine) { + var _this = this; - /** - * 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); + _classCallCheck(this, NodesHandler); - // if the group's drawPoints is a function delegate the callback to the onRender property - if (typeof options.drawPoints == 'function') { - options.drawPoints = { - onRender: options.drawPoints - }; - } + this.body = body; + this.images = images; + this.groups = groups; + this.layoutEngine = layoutEngine; - util.mergeOptions(this.options, options, 'interpolation'); - util.mergeOptions(this.options, options, 'drawPoints'); - util.mergeOptions(this.options, options, 'shaded'); + // create the node API in the body container + this.body.functions.createNode = this.create.bind(this); - 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; + 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, + labelHighlightBold: true, + 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 { - this.options.interpolation.parametrization = 'centripetal'; - this.options.interpolation.alpha = 0.5; + 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); - 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.bindEventListeners(); } - }; - /** - * 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); - }; + _createClass(NodesHandler, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this2 = this; - /** - * 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; + // 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); - 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'); + // 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(); + } + } + } - 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); - } + // 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(); + } + } + } - 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'); - } + // 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(); + } + } + } - if (this.options.drawPoints.enabled == true) { - var groupTemplate = { - style: this.options.drawPoints.style, - size: this.options.drawPoints.size, - className: this.className - }; - DOMutil.drawPoint(x + 0.5 * iconWidth, y, groupTemplate, JSONcontainer, SVGcontainer); + // update the state of the letiables if needed + if (options.hidden !== undefined || options.physics !== undefined) { + this.body.emitter.emit('_dataChanged'); + } + } } - } 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); + }, { + key: 'setData', - 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); - } - }; + /** + * 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 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 }; - }; + var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - GraphGroup.prototype.getYRange = function (groupData) { - return this.type.getYRange(groupData); - }; + var oldNodesData = this.body.data.nodes; - GraphGroup.prototype.getData = function (groupData) { - return this.type.getData(groupData); - }; + 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'); + } - GraphGroup.prototype.draw = function (dataset, group, framework) { - this.type.draw(dataset, group, framework); - }; + if (oldNodesData) { + // unsubscribe from old dataset + util.forEach(this.nodesListeners, function (callback, event) { + oldNodesData.off(event, callback); + }); + } - module.exports = GraphGroup; + // remove drawn nodes + this.body.nodes = {}; -/***/ }, -/* 60 */ -/***/ function(module, exports, __webpack_require__) { + 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); + }); - 'use strict'; + // draw all new nodes + var ids = _this3.body.data.nodes.getIds(); + _this3.add(ids, true); + })(); + } - var DOMutil = __webpack_require__(19); - var Points = __webpack_require__(61); + if (doNotEmit === false) { + this.body.emitter.emit('_dataChanged'); + } + } + }, { + key: 'add', - function Line(groupId, options) { - this.groupId = groupId; - this.options = options; - } + /** + * Add nodes + * @param {Number[] | String[]} ids + * @private + */ + value: function add(ids) { + var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - 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; - }; + 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 + } - 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 }; - }; + this.layoutEngine.positionInitially(newNodes); - 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; + if (doNotEmit === false) { + this.body.emitter.emit('_dataChanged'); } - }); - var intersections = {}; - - Line._getDataIntersections(intersections, combinedData); - groupRanges[groupLabel] = Line._getStackedYRange(intersections, combinedData); - groupRanges[groupLabel].yAxisOrientation = orientation; - groupIds.push(groupLabel); - } - }; + } + }, { + key: 'update', - 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; + /** + * 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(data); + nodes[id] = node; + } + } + if (dataChanged === true) { + this.body.emitter.emit('_dataChanged'); } else { - intersections[key].accumulatedPositive += combinedData[i].y; + this.body.emitter.emit('_dataUpdated'); } } - } - 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; - } - } + }, { + key: 'remove', - return { min: yMin, max: yMax }; - }; + /** + * 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; - /** - * 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 }; + for (var i = 0; i < ids.length; i++) { + var id = ids[i]; + delete nodes[id]; } - intersections[combinedData[i].x].amount += 1; + + this.body.emitter.emit('_dataChanged'); } - } - }; + }, { + key: 'create', - /** - * 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); - } + /** + * create a node + * @param properties + * @param constructorClass + */ + value: function create(properties) { + var constructorClass = arguments[1] === undefined ? _componentsNode2['default'] : arguments[1]; - // construct path from dataset - if (group.options.interpolation.enabled == true) { - d = Line._catmullRom(dataset, group); - } else { - d = Line._linear(dataset); + 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', - // 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; + /** + * 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 { - dFill = 'M' + dataset[0].x + ',' + svgHeight + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + svgHeight; + if (this.body.nodes[ids] !== undefined) { + var node = this.body.nodes[ids]; + dataArray[ids] = { x: Math.round(node.x), y: Math.round(node.y) }; + } } - fillPath.setAttributeNS(null, 'class', group.className + ' vis-fill'); - if (group.options.shaded.style !== undefined) { - fillPath.setAttributeNS(null, 'style', group.options.shaded.style); + } 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) }; + } } - 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); } + return dataArray; } - } - }; - - /** - * 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; + }, { + key: 'storePositions', - // 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 + /** + * Load the XY positions of the nodes into the dataset. + */ + value: function storePositions() { + // todo: add support for clusters and hierarchical. + var dataArray = []; + var dataset = this.body.data.nodes.getDataSet(); - // 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 }; + for (var nodeId in dataset._data) { + if (dataset._data.hasOwnProperty(nodeId)) { + var node = this.body.nodes[nodeId]; + if (dataset._data[nodeId].x != Math.round(node.x) || dataset._data[nodeId].y != Math.round(node.y)) { + dataArray.push({ id: nodeId, x: Math.round(node.x), y: Math.round(node.y) }); + } + } + } + dataset.update(dataArray); + } + }, { + key: 'getBoundingBox', - d += 'C' + bp1.x + ',' + bp1.y + ' ' + bp2.x + ',' + bp2.y + ' ' + p2.x + ',' + p2.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', - return d; - }; + /** + * 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', - /** - * 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++) { + /** + * 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; + } + }]); - p0 = i == 0 ? data[0] : data[i - 1]; - p1 = data[i]; - p2 = data[i + 1]; - p3 = i + 2 < length ? data[i + 2] : p2; + return NodesHandler; + })(); - 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)); + exports['default'] = NodesHandler; + module.exports = exports['default']; - // Catmull-Rom to Cubic Bezier conversion matrix +/***/ }, +/* 63 */ +/***/ function(module, exports, __webpack_require__) { - // A = 2d1^2a + 3d1^a * d2^a + d3^2a - // B = 2d3^2a + 3d3^a * d2^a + d2^2a + 'use strict'; - // [ 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 ] + Object.defineProperty(exports, '__esModule', { + value: true + }); - 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); + 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; }; })(); - 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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - bp1 = { x: (-d2pow2A * p0.x + A * p1.x + d1pow2A * p2.x) * N, - y: (-d2pow2A * p0.y + A * p1.y + d1pow2A * p2.y) * N }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - bp2 = { x: (d3pow2A * p1.x + B * p2.x - d2pow2A * p3.x) * M, - y: (d3pow2A * p1.y + B * p2.y - d2pow2A * p3.y) * M }; + var _sharedLabel = __webpack_require__(64); - 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 + ' '; - } + var _sharedLabel2 = _interopRequireDefault(_sharedLabel); - return d; - } - }; + var _nodesShapesBox = __webpack_require__(65); - /** - * 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; - }; + var _nodesShapesBox2 = _interopRequireDefault(_nodesShapesBox); - module.exports = Line; + var _nodesShapesCircle = __webpack_require__(67); -/***/ }, -/* 61 */ -/***/ function(module, exports, __webpack_require__) { + var _nodesShapesCircle2 = _interopRequireDefault(_nodesShapesCircle); - 'use strict'; + var _nodesShapesCircularImage = __webpack_require__(69); - var DOMutil = __webpack_require__(19); + var _nodesShapesCircularImage2 = _interopRequireDefault(_nodesShapesCircularImage); - function Points(groupId, options) { - this.groupId = groupId; - this.options = options; - } + var _nodesShapesDatabase = __webpack_require__(70); - 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 }; - }; + var _nodesShapesDatabase2 = _interopRequireDefault(_nodesShapesDatabase); - Points.prototype.draw = function (dataset, group, framework, offset) { - Points.draw(dataset, group, framework, offset); - }; + var _nodesShapesDiamond = __webpack_require__(71); - /** - * 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) { - offset = offset || 0; - var callback = getCallback(); + var _nodesShapesDiamond2 = _interopRequireDefault(_nodesShapesDiamond); - for (var i = 0; i < dataset.length; i++) { - if (!callback) { - // draw the point the simple way. - DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, getGroupTemplate(), framework.svgElements, framework.svg, dataset[i].label); - } else { - var callbackResult = callback(dataset[i], group, framework); // result might be true, false or an object - if (callbackResult === true || typeof callbackResult === 'object') { - DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, getGroupTemplate(callbackResult), framework.svgElements, framework.svg, dataset[i].label); - } - } - } + var _nodesShapesDot = __webpack_require__(73); - function getGroupTemplate(callbackResult) { - callbackResult = typeof callbackResult === 'undefined' ? {} : callbackResult; - return { - style: callbackResult.style || group.options.drawPoints.style, - size: callbackResult.size || group.options.drawPoints.size, - className: callbackResult.className || group.className - }; - } + var _nodesShapesDot2 = _interopRequireDefault(_nodesShapesDot); - function getCallback() { - var callback = undefined; - // check for the graph2d onRender - if (framework.options.drawPoints.onRender && typeof framework.options.drawPoints.onRender == 'function') { - callback = framework.options.drawPoints.onRender; - } + var _nodesShapesEllipse = __webpack_require__(74); - // override it with the group onRender if defined - if (group.group.options && group.group.options.drawPoints && group.group.options.drawPoints.onRender && typeof group.group.options.drawPoints.onRender == 'function') { - callback = group.group.options.drawPoints.onRender; - } + var _nodesShapesEllipse2 = _interopRequireDefault(_nodesShapesEllipse); - return callback; - } - }; + var _nodesShapesIcon = __webpack_require__(75); - module.exports = Points; + var _nodesShapesIcon2 = _interopRequireDefault(_nodesShapesIcon); -/***/ }, -/* 62 */ -/***/ function(module, exports, __webpack_require__) { + var _nodesShapesImage = __webpack_require__(76); - 'use strict'; + var _nodesShapesImage2 = _interopRequireDefault(_nodesShapesImage); - var DOMutil = __webpack_require__(19); - var Points = __webpack_require__(61); + var _nodesShapesSquare = __webpack_require__(77); - function Bargraph(groupId, options) { - this.groupId = groupId; - this.options = options; - } + var _nodesShapesSquare2 = _interopRequireDefault(_nodesShapesSquare); - 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 }; - }; + var _nodesShapesStar = __webpack_require__(78); - 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 _nodesShapesStar2 = _interopRequireDefault(_nodesShapesStar); - /** - * 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; + var _nodesShapesText = __webpack_require__(79); - // 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 _nodesShapesText2 = _interopRequireDefault(_nodesShapesText); - if (barPoints === 0) { - return; - } + var _nodesShapesTriangle = __webpack_require__(80); - // 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 _nodesShapesTriangle2 = _interopRequireDefault(_nodesShapesTriangle); - // get intersections - Bargraph._getDataIntersections(intersections, combinedData); + var _nodesShapesTriangleDown = __webpack_require__(81); - // plot barchart - for (i = 0; i < combinedData.length; i++) { - group = framework.groups[combinedData[i].groupId]; - var minWidth = 0.1 * group.options.barChart.width; + var _nodesShapesTriangleDown2 = _interopRequireDefault(_nodesShapesTriangleDown); - 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; + var _sharedValidator = __webpack_require__(51); - 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); - } - } - }; + var _sharedValidator2 = _interopRequireDefault(_sharedValidator); - /** - * 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; - } - } - }; + var util = __webpack_require__(13); /** - * Get the width and offset for bargraphs based on the coredistance between datapoints + * @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 * - * @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; - } - } + var Node = (function () { + function Node(options, body, imagelist, grouplist, globalOptions) { + _classCallCheck(this, Node); - return { width: width, offset: offset }; - }; + this.options = util.bridgeObject(globalOptions); + this.body = body; - 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 = {}; + this.edges = []; // all edges connected to this node - Bargraph._getDataIntersections(intersections, combinedData); - groupRanges[groupLabel] = Bargraph._getStackedYRange(intersections, combinedData); - groupRanges[groupLabel].yAxisOrientation = orientation; - groupIds.push(groupLabel); + // set defaults for the options + this.id = undefined; + this.imagelist = imagelist; + this.grouplist = grouplist; + + // state options + this.x = undefined; + this.y = undefined; + this.baseSize = this.options.size; + this.baseFontSize = this.options.font.size; + this.predefinedPosition = false; // used to check if initial fit should just take the range or approximate + this.selected = false; + this.hover = false; + + this.labelModule = new _sharedLabel2['default'](this.body, this.options); + this.setOptions(options); } - }; - 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; + _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); } } - } - 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 }; - }; + }, { + key: 'detachEdge', - module.exports = Bargraph; + /** + * 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', -/***/ }, -/* 63 */ -/***/ function(module, exports, __webpack_require__) { + /** + * Enable or disable the physics. + * @param status + */ + value: function togglePhysics(status) { + this.options.physics = status; + } + }, { + key: 'setOptions', - 'use strict'; + /** + * 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; + } - var util = __webpack_require__(14); - var DOMutil = __webpack_require__(19); - var Component = __webpack_require__(33); + if (this.id === undefined) { + throw 'Node must have an id'; + } - /** - * 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; + // 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 = parseFloat(options.value); + } - this.svgElements = {}; - this.dom = {}; - this.groups = {}; - this.amountOfGroups = 0; - this._create(); + // 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); + } - this.setOptions(options); - } + // this transforms all shorthands into fully defined options + Node.parseOptions(this.options, options, true); - Legend.prototype = new Component(); + // load the images + if (this.options.image !== undefined) { + if (this.imagelist) { + this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage, this.id); + } else { + throw 'No imagelist provided'; + } + } - Legend.prototype.clear = function () { - this.groups = {}; - this.amountOfGroups = 0; - }; + this.updateShape(); + this.updateLabelModule(); - Legend.prototype.addGroup = function (label, graphOptions) { + // reset the size of the node, this can be changed + this._reset(); - if (!this.groups.hasOwnProperty(label)) { - this.groups[label] = graphOptions; - } - this.amountOfGroups += 1; - }; + 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', - Legend.prototype.updateGroup = function (label, graphOptions) { - this.groups[label] = graphOptions; - }; + /** + * select this node + */ + value: function select() { + this.selected = true; + this._reset(); + } + }, { + key: 'unselect', - Legend.prototype.removeGroup = function (label) { - if (this.groups.hasOwnProperty(label)) { - delete this.groups[label]; - this.amountOfGroups -= 1; - } - }; + /** + * unselect this node + */ + value: function unselect() { + this.selected = false; + this._reset(); + } + }, { + key: '_reset', - 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'; + /** + * 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', - 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'; + /** + * 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', - 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%'; + /** + * 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.dom.frame.appendChild(this.svg); - this.dom.frame.appendChild(this.dom.textArea); - }; + /** + * 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', - /** - * 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); - } - }; + /** + * check if this node is selecte + * @return {boolean} selected True if node is selected, else false + */ + value: function isSelected() { + return this.selected; + } + }, { + key: 'getValue', - /** - * 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); - } - }; + /** + * Retrieve the value of the node. Can be undefined + * @return {Number} value + */ + value: function getValue() { + return this.options.value; + } + }, { + key: 'setValueRange', - Legend.prototype.setOptions = function (options) { - var fields = ['enabled', 'orientation', 'icons', 'left', 'right']; - util.selectiveDeepExtend(fields, this.options, options); - }; + /** + * 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', - Legend.prototype.redraw = function () { - var activeGroups = 0; - var groupArray = Object.keys(this.groups); - groupArray.sort(function (a, b) { - return a < b ? -1 : 1; - }); + /** + * 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', - 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++; + /** + * Update the bounding box of the shape + */ + value: function updateBoundingBox(ctx) { + this.shape.updateBoundingBox(this.x, this.y, ctx); } - } + }, { + key: 'resize', - 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 = ''; + /** + * 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', - 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 = ''; + /** + * 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', - 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(); + /** + * 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', - 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'; - } - }; + /** + * 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]; - 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; - }); + var fields = ['color', 'font', 'fixed', 'shadow']; + util.selectiveNotDeepExtend(fields, parentOptions, newOptions, allowDeletion); - 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; + // merge the shadow options into the parent. + util.mergeOptions(parentOptions, newOptions, 'shadow'); - this.svg.style.width = iconWidth + 5 + iconOffset + 'px'; + // 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; + } - 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; + // 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; + } + } + } + + // handle the font options + if (newOptions.font !== undefined) { + _sharedLabel2['default'].parseOptions(parentOptions.font, newOptions); + } + + // handle the scaling options, specifically the label part + if (newOptions.scaling !== undefined) { + util.mergeOptions(parentOptions.scaling, newOptions.scaling, 'label'); } } + }]); - DOMutil.cleanupElements(this.svgElements); - } - }; + return Node; + })(); - module.exports = Legend; + exports['default'] = Node; + module.exports = exports['default']; /***/ }, /* 64 */ /***/ 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 any = 'any'; - var allOptions = { - configure: { - enabled: { boolean: boolean }, - filter: { boolean: boolean, 'function': 'function' }, - container: { dom: dom }, - __type__: { object: object, boolean: boolean, 'function': 'function' } - }, + 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 : - 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 }, - onRender: { 'function': 'function' }, - size: { number: number }, - style: { string: ['square', 'circle'] }, // square, circle - __type__: { object: object, boolean: boolean, 'function': 'function' } - }, - 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: { 'function': 'function' }, - 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: { 'function': 'function' }, - 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 _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'); } } - autoResize: { boolean: boolean }, - clickToUse: { boolean: boolean }, - end: { number: number, date: date, string: string, moment: moment }, - format: { - minorLabels: { - millisecond: { string: string, 'undefined': 'undefined' }, - second: { string: string, 'undefined': 'undefined' }, - minute: { string: string, 'undefined': 'undefined' }, - hour: { string: string, 'undefined': 'undefined' }, - weekday: { string: string, 'undefined': 'undefined' }, - day: { string: string, 'undefined': 'undefined' }, - month: { string: string, 'undefined': 'undefined' }, - year: { string: string, 'undefined': 'undefined' }, - __type__: { object: object } - }, - majorLabels: { - millisecond: { string: string, 'undefined': 'undefined' }, - second: { string: string, 'undefined': 'undefined' }, - minute: { string: string, 'undefined': 'undefined' }, - hour: { string: string, 'undefined': 'undefined' }, - weekday: { string: string, 'undefined': 'undefined' }, - day: { string: string, 'undefined': 'undefined' }, - month: { string: string, 'undefined': 'undefined' }, - year: { string: string, 'undefined': 'undefined' }, - __type__: { object: object } - }, - __type__: { object: object } - }, - height: { string: string, number: number }, - hiddenDates: { object: object, array: array }, - locale: { string: string }, - locales: { - __any__: { any: any }, - __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, 'undefined': 'undefined' }, - step: { number: number, 'undefined': 'undefined' }, - __type__: { object: object } - }, - width: { string: string, number: number }, - zoomable: { boolean: boolean }, - zoomMax: { number: number }, - zoomMin: { number: number }, - __type__: { object: object } - }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - 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': 'undefined'ined,max:'undefined': 'undefined'ined}, - //format: function (value) {return value;}, - title: { text: '', style: '' } - }, - right: { - //range: {min:'undefined': 'undefined'ined,max:'undefined': 'undefined'ined}, - //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 util = __webpack_require__(13); + + var Label = (function () { + function Label(body, options) { + _classCallCheck(this, Label); + + this.body = body; + + this.pointToSelf = false; + this.baseSize = undefined; + this.setOptions(options); + this.size = { top: 0, left: 0, width: 0, height: 0, yLine: 0 }; // could be cached + } + + _createClass(Label, [{ + key: 'setOptions', + value: function setOptions(options) { + var allowDeletion = arguments[1] === undefined ? false : arguments[1]; + + this.options = options; + + if (options.label !== undefined) { + this.labelDirty = true; } - }, - 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 (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; + } + } } - }, + } + }, { + key: 'draw', - 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] - } - }; + /** + * 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]; - exports.allOptions = allOptions; - exports.configureOptions = configureOptions; + // if no label, return + if (this.options.label === undefined) return; -/***/ }, -/* 65 */ -/***/ function(module, exports, __webpack_require__) { + // 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; - // Load custom shapes into CanvasRenderingContext2D - 'use strict'; + // update the size cache if required + this.calculateLabelSize(ctx, selected, x, y, baseline); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + // create the fontfill background + this._drawBackground(ctx); + // draw text + this._drawText(ctx, selected, x, y, baseline); + } + }, { + key: '_drawBackground', - var _modulesGroups = __webpack_require__(66); + /** + * 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 _modulesGroups2 = _interopRequireDefault(_modulesGroups); + var lineMargin = 2; - var _modulesNodesHandler = __webpack_require__(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; + } + } + } + }, { + key: '_drawText', - var _modulesNodesHandler2 = _interopRequireDefault(_modulesNodesHandler); + /** + * + * @param ctx + * @param x + * @param baseline + * @private + */ + value: function _drawText(ctx, selected, x, y) { + var baseline = arguments[4] === undefined ? 'middle' : arguments[4]; - var _modulesEdgesHandler = __webpack_require__(9); + 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; + } - var _modulesEdgesHandler2 = _interopRequireDefault(_modulesEdgesHandler); + var yLine = this.size.yLine; - var _modulesPhysicsEngine = __webpack_require__(90); + var _getColor2 = this._getColor(viewFontSize); - var _modulesPhysicsEngine2 = _interopRequireDefault(_modulesPhysicsEngine); + var _getColor22 = _slicedToArray(_getColor2, 2); + + var fontColor = _getColor22[0]; + var strokeColor = _getColor22[1]; + + var _setAlignment2 = this._setAlignment(ctx, x, yLine, baseline); + + var _setAlignment22 = _slicedToArray(_setAlignment2, 2); + + x = _setAlignment22[0]; + yLine = _setAlignment22[1]; + + // configure context for drawing the text + ctx.font = (selected && this.options.labelHighlightBold ? 'bold ' : '') + fontSize + 'px ' + this.options.font.face; + ctx.fillStyle = fontColor; + ctx.textAlign = 'center'; + + // 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' && this.pointToSelf === false) { + x = 0; + yLine = 0; - var _modulesClustering = __webpack_require__(99); + 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; + } - var _modulesClustering2 = _interopRequireDefault(_modulesClustering); + return [x, yLine]; + } + }, { + key: '_getColor', - var _modulesCanvasRenderer = __webpack_require__(101); + /** + * 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 _modulesCanvasRenderer2 = _interopRequireDefault(_modulesCanvasRenderer); + /** + * + * @param ctx + * @param selected + * @returns {{width: number, height: number}} + */ + value: function getTextSize(ctx) { + var selected = arguments[1] === undefined ? false : arguments[1]; - var _modulesCanvas = __webpack_require__(102); + var size = { + width: this._processLabel(ctx, selected), + height: this.options.font.size * this.lineCount, + lineCount: this.lineCount + }; + return size; + } + }, { + key: 'calculateLabelSize', - var _modulesCanvas2 = _interopRequireDefault(_modulesCanvas); + /** + * + * @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 _modulesView = __webpack_require__(103); + 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 + } - var _modulesView2 = _interopRequireDefault(_modulesView); + this.labelDirty = false; + } + }, { + key: '_processLabel', - var _modulesInteractionHandler = __webpack_require__(104); + /** + * 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 && this.options.labelHighlightBold ? '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; - var _modulesInteractionHandler2 = _interopRequireDefault(_modulesInteractionHandler); + return width; + } + }], [{ + key: 'parseOptions', + value: function parseOptions(parentOptions, newOptions) { + var allowDeletion = arguments[2] === undefined ? false : arguments[2]; - var _modulesSelectionHandler = __webpack_require__(5); + 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); + } + }]); - var _modulesSelectionHandler2 = _interopRequireDefault(_modulesSelectionHandler); + return Label; + })(); - var _modulesLayoutEngine = __webpack_require__(107); + exports['default'] = Label; + module.exports = exports['default']; - var _modulesLayoutEngine2 = _interopRequireDefault(_modulesLayoutEngine); +/***/ }, +/* 65 */ +/***/ function(module, exports, __webpack_require__) { - var _modulesManipulationSystem = __webpack_require__(108); + 'use strict'; - var _modulesManipulationSystem2 = _interopRequireDefault(_modulesManipulationSystem); + Object.defineProperty(exports, '__esModule', { + value: true + }); - var _sharedConfigurator = __webpack_require__(51); + 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 _sharedConfigurator2 = _interopRequireDefault(_sharedConfigurator); + 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 _sharedValidator = __webpack_require__(53); + 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 _optionsJs = __webpack_require__(7); + 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; } - __webpack_require__(109); + var _utilNodeBase = __webpack_require__(66); - var Emitter = __webpack_require__(25); - var Hammer = __webpack_require__(10); - var util = __webpack_require__(14); - var DataSet = __webpack_require__(20); - var DataView = __webpack_require__(22); - var dotparser = __webpack_require__(110); - var gephiParser = __webpack_require__(111); - var Images = __webpack_require__(112); - var Activator = __webpack_require__(48); - var locales = __webpack_require__(113); + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - /** - * @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; + var Box = (function (_NodeBase) { + function Box(options, body, labelModule) { + _classCallCheck(this, Box); - if (!(this instanceof Network)) { - throw new SyntaxError('Constructor must be called with the new operator'); + _get(Object.getPrototypeOf(Box.prototype), 'constructor', this).call(this, options, body, labelModule); } - // set constant values - this.options = {}; - this.defaultOptions = { - locale: 'en', - locales: locales, - clickToUse: false - }; - util.extend(this.options, this.defaultOptions); + _inherits(Box, _NodeBase); - // containers for nodes and edges - this.body = { - container: container, - nodes: {}, - nodeIndices: [], - edges: {}, - edgeIndices: [], - 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() {} - }, - data: { - nodes: null, // A DataSet or DataView - edges: null // A DataSet or DataView - }, - functions: { - createNode: function createNode() {}, - createEdge: function createEdge() {}, - getPointer: function getPointer() {} - }, - view: { - scale: 1, - translation: { x: 0, y: 0 } + _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; + } } - }; - - // 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 + }, { + 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.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 borderWidth = this.options.borderWidth; + var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - // create the DOM elements - this.canvas._create(); + 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); - // apply options - this.setOptions(options); + ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; - // load data (the disable start variable will be the same as the enabled clustering) - this.setData(data); - } + var borderRadius = 6; + ctx.roundRect(this.left, this.top, this.width, this.height, borderRadius); - // Extend Network with an Emitter mixin - Emitter(Network.prototype); + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); - /** - * Set options - * @param {Object} options - */ - Network.prototype.setOptions = function (options) { - var _this2 = this; + // disable shadows for other elements. + this.disableShadow(ctx); - if (options !== undefined) { + ctx.stroke(); - var errorFound = _sharedValidator2['default'].validate(options, _optionsJs.allOptions); - if (errorFound === true) { - console.log('%cErrors have been found in the supplied options object.', _sharedValidator.printStyle); + 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; - // 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.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); + } + }]); - this.canvas.setOptions(options); // options for canvas are in globals + return Box; + })(_utilNodeBase2['default']); - // 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 + exports['default'] = Box; + module.exports = exports['default']; - 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 +/***/ }, +/* 66 */ +/***/ function(module, exports, __webpack_require__) { - // 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); + 'use strict'; - if ('configure' in options) { - if (!this.configurator) { - this.configurator = new _sharedConfigurator2['default'](this, this.body.container, _optionsJs.configureOptions, this.canvas.pixelRatio); - } + Object.defineProperty(exports, '__esModule', { + value: true + }); - this.configurator.setOptions(options.configure); - } + 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 the configuration system is enabled, copy all options and put them into the config system - if (this.configurator && 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 render default options in to the interaction group - util.deepExtend(networkOptions.interaction, this.selectionHandler.options); - util.deepExtend(networkOptions.interaction, this.renderer.options); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - util.deepExtend(networkOptions.interaction, this.interactionHandler.options); - util.deepExtend(networkOptions.manipulation, this.manipulation.options); - util.deepExtend(networkOptions.physics, this.physics.options); + var NodeBase = (function () { + function NodeBase(options, body, labelModule) { + _classCallCheck(this, NodeBase); - // load globals into the global object - util.deepExtend(networkOptions.global, this.canvas.options); - util.deepExtend(networkOptions.global, this.options); + 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 }; + } - this.configurator.setModuleOptions(networkOptions); + _createClass(NodeBase, [{ + key: 'setOptions', + value: function setOptions(options) { + this.options = options; } - - // 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'); + }, { + 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; } - - this.canvas.setSize(); - // start the physics simulation. Can be safely called multiple times. - this.body.emitter.emit('startSimulation'); - } - }; - - /** - * 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 = []; - - for (var nodeId in nodes) { - if (nodes.hasOwnProperty(nodeId)) { - if (nodes[nodeId].options.hidden === false) { - this.body.nodeIndices.push(nodeId); + }, { + 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; } } - } - - for (var edgeId in edges) { - if (edges.hasOwnProperty(edgeId)) { - if (edges[edgeId].options.hidden === false) { - this.body.edgeIndices.push(edgeId); + }, { + 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; } } - } - }; + }]); - /** - * Bind all events - */ - Network.prototype.bindEventListeners = function () { - var _this3 = this; + return NodeBase; + })(); - // 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(); - _this3.body.emitter.emit('_requestRedraw'); - // call the dataUpdated event because the only difference between the two is the updating of the indices - _this3.body.emitter.emit('_dataUpdated'); - }); + exports['default'] = NodeBase; + module.exports = exports['default']; - // 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'); - _this3.body.emitter.emit('_requestRedraw'); - }); - }; +/***/ }, +/* 67 */ +/***/ function(module, exports, __webpack_require__) { - /** - * 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'); + 'use strict'; - // unselect all to ensure no selections from old data are carried over. - this.selectionHandler.unselectAll(); + 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 (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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - // 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); - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - // emit change in data - this.body.emitter.emit('_dataChanged'); + 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; } - // find a stable position or start animating to a stable position - this.body.emitter.emit('initPhysics'); - }; + var _utilCircleImageBase = __webpack_require__(68); - /** - * 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(); + var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); - // 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; + var Circle = (function (_CircleImageBase) { + function Circle(options, body, labelModule) { + _classCallCheck(this, Circle); - for (var nodeId in this.body.nodes) { - delete this.body.nodes[nodeId]; - } - for (var edgeId in this.body.edges) { - delete this.body.edges[edgeId]; + _get(Object.getPrototypeOf(Circle.prototype), 'constructor', this).call(this, options, body, labelModule); } - // remove the container and everything inside it recursively - util.recursiveDOMDelete(this.body.container); - }; + _inherits(Circle, _CircleImageBase); - /** - * 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; + _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; - // 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.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; - // 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); - } - } - } - }; + this._drawRawCircle(ctx, x, y, selected, hover, this.options.size); - /** - * Returns true when the Network is active. - * @returns {boolean} - */ - Network.prototype.isActive = function () { - return !this.activator || this.activator.active; - }; + 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; - 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.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); - }; + 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); + } + }]); - module.exports = Network; + return Circle; + })(_utilCircleImageBase2['default']); + + exports['default'] = Circle; + module.exports = exports['default']; /***/ }, -/* 66 */ +/* 68 */ /***/ 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__(14); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - /** - * @class Groups - * This class can store groups and options specific for groups. - */ + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var Groups = (function () { - function Groups() { - _classCallCheck(this, Groups); + 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.clear(); - this.defaultIndex = 0; - this.groupsArray = []; - this.groupIndex = 0; + var _utilNodeBase = __webpack_require__(66); - 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 + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - { border: "#990000", background: "#EE0000", highlight: { border: "#BB0000", background: "#FF3333" }, hover: { border: "#BB0000", background: "#FF3333" } }, // 10:bright red + var CircleImageBase = (function (_NodeBase) { + function CircleImageBase(options, body, labelModule) { + _classCallCheck(this, CircleImageBase); - { 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 + _get(Object.getPrototypeOf(CircleImageBase.prototype), 'constructor', this).call(this, options, body, labelModule); + this.labelOffset = 0; + this.imageLoaded = false; + } - { border: "#EE0000", background: "#990000", highlight: { border: "#FF3333", background: "#BB0000" }, hover: { border: "#FF3333", background: "#BB0000" } } // 20:bright red - ]; + _inherits(CircleImageBase, _NodeBase); - this.options = {}; - this.defaultOptions = { - useDefaultGroups: true - }; - util.extend(this.options, this.defaultOptions); - } + _createClass(CircleImageBase, [{ + key: '_resizeImage', - _createClass(Groups, [{ - key: "setOptions", - value: function setOptions(options) { - var optionFields = ["useDefaultGroups"]; + /** + * 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 (options !== undefined) { - for (var groupName in options) { - if (options.hasOwnProperty(groupName)) { - if (optionFields.indexOf(groupName) === -1) { - var group = options[groupName]; - this.add(groupName, group); - } + 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: "clear", + 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; - /** - * Clear all groups - */ - value: function clear() { - this.groups = {}; - this.groupsArray = []; + 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: "get", + key: '_drawImageAtPosition', + value: function _drawImageAtPosition(ctx) { + if (this.imageObj.width != 0) { + // draw the image + ctx.globalAlpha = 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; - } - } + // draw shadow if enabled + this.enableShadow(ctx); + ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height); - return group; + // disable shadows for other elements. + this.disableShadow(ctx); + } } }, { - key: "add", + key: '_drawImageLabel', + value: function _drawImageLabel(ctx, x, y, selected) { + var yLabel; + var offset = 0; - /** - * 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.height !== undefined) { + offset = this.height * 0.5; + var labelDimensions = this.labelModule.getTextSize(ctx); + if (labelDimensions.lineCount >= 1) { + offset += labelDimensions.height / 2; + } + } + + yLabel = y + offset; + + if (this.options.label) { + this.labelOffset = offset; + } + this.labelModule.draw(ctx, x, yLabel, selected, 'hanging'); } }]); - return Groups; - })(); + return CircleImageBase; + })(_utilNodeBase2['default']); - exports["default"] = Groups; - module.exports = exports["default"]; + exports['default'] = CircleImageBase; + module.exports = exports['default']; /***/ }, -/* 67 */ +/* 69 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -30009,516 +29217,264 @@ 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 _sharedLabel = __webpack_require__(4); - - var _sharedLabel2 = _interopRequireDefault(_sharedLabel); - - var _nodesShapesBox = __webpack_require__(68); - - var _nodesShapesBox2 = _interopRequireDefault(_nodesShapesBox); - - var _nodesShapesCircle = __webpack_require__(70); - - var _nodesShapesCircle2 = _interopRequireDefault(_nodesShapesCircle); - - var _nodesShapesCircularImage = __webpack_require__(72); - - var _nodesShapesCircularImage2 = _interopRequireDefault(_nodesShapesCircularImage); - - var _nodesShapesDatabase = __webpack_require__(73); - - var _nodesShapesDatabase2 = _interopRequireDefault(_nodesShapesDatabase); - - var _nodesShapesDiamond = __webpack_require__(74); - - var _nodesShapesDiamond2 = _interopRequireDefault(_nodesShapesDiamond); + 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 _nodesShapesDot = __webpack_require__(76); + var _utilCircleImageBase = __webpack_require__(68); - var _nodesShapesDot2 = _interopRequireDefault(_nodesShapesDot); + var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); - var _nodesShapesEllipse = __webpack_require__(77); + var CircularImage = (function (_CircleImageBase) { + function CircularImage(options, body, labelModule, imageObj) { + _classCallCheck(this, CircularImage); - var _nodesShapesEllipse2 = _interopRequireDefault(_nodesShapesEllipse); + _get(Object.getPrototypeOf(CircularImage.prototype), 'constructor', this).call(this, options, body, labelModule); + this.imageObj = imageObj; + this._swapToImageResizeWhenImageLoaded = true; + } - var _nodesShapesIcon = __webpack_require__(78); + _inherits(CircularImage, _CircleImageBase); - var _nodesShapesIcon2 = _interopRequireDefault(_nodesShapesIcon); + _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: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(); - var _nodesShapesImage = __webpack_require__(79); + this.left = x - this.width / 2; + this.top = y - this.height / 2; - var _nodesShapesImage2 = _interopRequireDefault(_nodesShapesImage); + var size = Math.min(0.5 * this.height, 0.5 * this.width); - var _nodesShapesSquare = __webpack_require__(80); + this._drawRawCircle(ctx, x, y, selected, hover, size); - var _nodesShapesSquare2 = _interopRequireDefault(_nodesShapesSquare); + ctx.save(); + ctx.circle(x, y, size); + ctx.stroke(); + ctx.clip(); - var _nodesShapesStar = __webpack_require__(81); + this._drawImageAtPosition(ctx); - var _nodesShapesStar2 = _interopRequireDefault(_nodesShapesStar); + ctx.restore(); - var _nodesShapesText = __webpack_require__(82); + this._drawImageLabel(ctx, x, y, selected); - var _nodesShapesText2 = _interopRequireDefault(_nodesShapesText); + 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); + } + }]); - var _nodesShapesTriangle = __webpack_require__(83); + return CircularImage; + })(_utilCircleImageBase2['default']); - var _nodesShapesTriangle2 = _interopRequireDefault(_nodesShapesTriangle); + exports['default'] = CircularImage; + module.exports = exports['default']; - var _nodesShapesTriangleDown = __webpack_require__(84); +/***/ }, +/* 70 */ +/***/ function(module, exports, __webpack_require__) { - var _nodesShapesTriangleDown2 = _interopRequireDefault(_nodesShapesTriangleDown); + 'use strict'; - var _sharedValidator = __webpack_require__(53); + Object.defineProperty(exports, '__esModule', { + value: true + }); - var _sharedValidator2 = _interopRequireDefault(_sharedValidator); + 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__(14); + 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); } } }; - /** - * @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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - var Node = (function () { - function Node(options, body, imagelist, grouplist, globalOptions) { - _classCallCheck(this, Node); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - this.options = util.bridgeObject(globalOptions); - this.body = body; + 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.edges = []; // all edges connected to this node + var _utilNodeBase = __webpack_require__(66); - // set defaults for the options - this.id = undefined; - this.imagelist = imagelist; - this.grouplist = grouplist; + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - // 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; + var Database = (function (_NodeBase) { + function Database(options, body, labelModule) { + _classCallCheck(this, Database); - this.labelModule = new _sharedLabel2['default'](this.body, this.options); - this.setOptions(options); + _get(Object.getPrototypeOf(Database.prototype), 'constructor', this).call(this, options, body, labelModule); } - _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', + _inherits(Database, _NodeBase); - /** - * 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); + _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: 'togglePhysics', - - /** - * Enable or disable the physics. - * @param status - */ - value: function togglePhysics(status) { - this.options.physics = status; - } - }, { - key: 'setOptions', - - /** - * 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; - } - - if (this.id === undefined) { - throw 'Node must have an id'; - } - - // 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 = parseFloat(options.value); - } + 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; - // 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 borderWidth = this.options.borderWidth; + var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - // this transforms all shorthands into fully defined options - Node.parseOptions(this.options, options, true); + 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); - // load the images - if (this.options.image !== undefined) { - if (this.imagelist) { - this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage, this.id); - } else { - throw 'No imagelist provided'; - } - } + 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.updateShape(); - this.updateLabelModule(); + // draw shadow if enabled + this.enableShadow(ctx); + ctx.fill(); - // 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 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', + ctx.stroke(); - /** - * select this node - */ - value: function select() { - this.selected = true; - this._reset(); - } - }, { - key: 'unselect', + this.updateBoundingBox(x, y, ctx); - /** - * unselect this node - */ - value: function unselect() { - this.selected = false; - this._reset(); + this.labelModule.draw(ctx, x, y, selected); } }, { - key: '_reset', + key: 'updateBoundingBox', + value: function updateBoundingBox(x, y, ctx) { + this.resize(ctx); - /** - * 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', + this.left = x - this.width * 0.5; + this.top = y - this.height * 0.5; - /** - * 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; + 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', - - /** - * 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', - - /** - * 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', - - /** - * check if this node is selecte - * @return {boolean} selected True if node is selected, else false - */ - value: function isSelected() { - return this.selected; + 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: 'getValue', + }]); - /** - * Retrieve the value of the node. Can be undefined - * @return {Number} value - */ - value: function getValue() { - return this.options.value; - } - }, { - key: 'setValueRange', + return Database; + })(_utilNodeBase2['default']); - /** - * 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', + exports['default'] = Database; + module.exports = exports['default']; - /** - * 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', +/***/ }, +/* 71 */ +/***/ function(module, exports, __webpack_require__) { - /** - * Update the bounding box of the shape - */ - value: function updateBoundingBox(ctx) { - this.shape.updateBoundingBox(this.x, this.y, ctx); - } - }, { - key: 'resize', + 'use strict'; - /** - * 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', + Object.defineProperty(exports, '__esModule', { + value: true + }); - /** - * 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', + 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 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', + 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 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]; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - var fields = ['color', 'font', 'fixed', 'shadow']; - util.selectiveNotDeepExtend(fields, parentOptions, newOptions, allowDeletion); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - // merge the shadow options into the parent. - util.mergeOptions(parentOptions, newOptions, 'shadow'); + 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; } - // 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 _utilShapeBase = __webpack_require__(72); - // 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; - } - } - } + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); - // handle the font options - if (newOptions.font !== undefined) { - _sharedLabel2['default'].parseOptions(parentOptions.font, newOptions); - } + var Diamond = (function (_ShapeBase) { + function Diamond(options, body, labelModule) { + _classCallCheck(this, Diamond); - // handle the scaling options, specifically the label part - if (newOptions.scaling !== undefined) { - util.mergeOptions(parentOptions.scaling, newOptions.scaling, 'label'); - } + _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: '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); } }]); - return Node; - })(); + return Diamond; + })(_utilShapeBase2['default']); - exports['default'] = Node; + exports['default'] = Diamond; module.exports = exports['default']; /***/ }, -/* 68 */ +/* 72 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -30537,34 +29493,34 @@ 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 _utilNodeBase = __webpack_require__(69); + var _utilNodeBase = __webpack_require__(66); var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - var Box = (function (_NodeBase) { - function Box(options, body, labelModule) { - _classCallCheck(this, Box); + var ShapeBase = (function (_NodeBase) { + function ShapeBase(options, body, labelModule) { + _classCallCheck(this, ShapeBase); - _get(Object.getPrototypeOf(Box.prototype), 'constructor', this).call(this, options, body, labelModule); + _get(Object.getPrototypeOf(ShapeBase.prototype), 'constructor', this).call(this, options, body, labelModule); } - _inherits(Box, _NodeBase); + _inherits(ShapeBase, _NodeBase); - _createClass(Box, [{ - key: 'resize', - value: function resize(ctx, selected) { + _createClass(ShapeBase, [{ + key: '_resizeShape', + value: function _resizeShape() { 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; + var size = 2 * this.options.size; + 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); + 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; @@ -30575,11 +29531,8 @@ return /******/ (function(modules) { // webpackBootstrap 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); + ctx[shape](x, y, this.options.size); // draw shadow if enabled this.enableShadow(ctx); @@ -30590,40 +29543,37 @@ return /******/ (function(modules) { // webpackBootstrap 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'); + } + 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.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 = 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); + if (this.options.label !== undefined && this.labelModule.size.width > 0) { + this.boundingBox.left = Math.min(this.boundingBox.left, this.labelModule.size.left); + this.boundingBox.right = Math.max(this.boundingBox.right, this.labelModule.size.left + this.labelModule.size.width); + this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelModule.size.height + 3); + } } }]); - return Box; + return ShapeBase; })(_utilNodeBase2['default']); - exports['default'] = Box; + exports['default'] = ShapeBase; module.exports = exports['default']; /***/ }, -/* 69 */ +/* 73 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -30634,64 +29584,52 @@ 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 NodeBase = (function () { - function NodeBase(options, body, labelModule) { - _classCallCheck(this, NodeBase); + 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.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 _utilShapeBase = __webpack_require__(72); + + 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); } - _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; + _inherits(Dot, _ShapeBase); + + _createClass(Dot, [{ + key: 'resize', + value: function resize(ctx) { + this._resizeShape(); } }, { - 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: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this._drawShape(ctx, 'circle', 2, x, y, selected, hover); } }, { - 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; - } + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + return this.options.size + this.options.borderWidth; } }]); - return NodeBase; - })(); + return Dot; + })(_utilShapeBase2['default']); - exports['default'] = NodeBase; + exports['default'] = Dot; module.exports = exports['default']; /***/ }, -/* 70 */ +/* 74 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -30710,30 +29648,30 @@ 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 _utilCircleImageBase = __webpack_require__(71); + var _utilNodeBase = __webpack_require__(66); - var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); + var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - var Circle = (function (_CircleImageBase) { - function Circle(options, body, labelModule) { - _classCallCheck(this, Circle); + var Ellipse = (function (_NodeBase) { + function Ellipse(options, body, labelModule) { + _classCallCheck(this, Ellipse); - _get(Object.getPrototypeOf(Circle.prototype), 'constructor', this).call(this, options, body, labelModule); + _get(Object.getPrototypeOf(Ellipse.prototype), 'constructor', this).call(this, options, body, labelModule); } - _inherits(Circle, _CircleImageBase); + _inherits(Ellipse, _NodeBase); - _createClass(Circle, [{ + _createClass(Ellipse, [{ 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.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; } } @@ -30741,47 +29679,66 @@ return /******/ (function(modules) { // webpackBootstrap 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.left = x - this.width * 0.5; + this.top = y - this.height * 0.5; - this._drawRawCircle(ctx, x, y, selected, hover, this.options.size); + var borderWidth = this.options.borderWidth; + var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; - 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; + 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); + + ctx.stroke(); 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; + value: function updateBoundingBox(x, y, ctx) { + this.resize(ctx, false); // just in case + + 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 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 Circle; - })(_utilCircleImageBase2['default']); + return Ellipse; + })(_utilNodeBase2['default']); - exports['default'] = Circle; + exports['default'] = Ellipse; module.exports = exports['default']; /***/ }, -/* 71 */ +/* 75 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -30800,137 +29757,104 @@ 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 _utilNodeBase = __webpack_require__(69); + var _utilNodeBase = __webpack_require__(66); var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - var CircleImageBase = (function (_NodeBase) { - function CircleImageBase(options, body, labelModule) { - _classCallCheck(this, CircleImageBase); + var Icon = (function (_NodeBase) { + function Icon(options, body, labelModule) { + _classCallCheck(this, Icon); - _get(Object.getPrototypeOf(CircleImageBase.prototype), 'constructor', this).call(this, options, body, labelModule); - this.labelOffset = 0; - this.imageLoaded = false; + _get(Object.getPrototypeOf(Icon.prototype), 'constructor', this).call(this, options, body, labelModule); } - _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; - } + _inherits(Icon, _NodeBase); - 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; + _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: '_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); + key: 'draw', + value: function draw(ctx, x, y, selected, hover) { + this.resize(ctx); + this.options.icon.size = this.options.icon.size || 50; - ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background; - ctx.circle(x, y, size); + this.left = x - this.width * 0.5; + this.top = y - this.height * 0.5; + this._icon(ctx, x, y, selected); - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); + if (this.options.label !== undefined) { + var iconTextSpacing = 5; + this.labelModule.draw(ctx, x, y + this.height * 0.5 + iconTextSpacing, selected); + } - // disable shadows for other elements. - this.disableShadow(ctx); + 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; - ctx.stroke(); + if (this.options.label !== undefined && this.labelModule.size.width > 0) { + 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: '_drawImageAtPosition', - value: function _drawImageAtPosition(ctx) { - if (this.imageObj.width != 0) { - // draw the image - ctx.globalAlpha = 1; + key: '_icon', + value: function _icon(ctx, x, y, selected) { + var iconSize = Number(this.options.icon.size); + + if (this.options.icon.code !== undefined) { + ctx.font = (selected ? 'bold ' : '') + iconSize + 'px ' + this.options.icon.face; + + // draw icon + ctx.fillStyle = this.options.icon.color || 'black'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; // draw shadow if enabled this.enableShadow(ctx); - ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height); + ctx.fillText(this.options.icon.code, x, y); // 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: '_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; - } - } - - yLabel = y + offset; - - if (this.options.label) { - this.labelOffset = offset; - } - this.labelModule.draw(ctx, x, yLabel, selected, 'hanging'); + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + this.resize(ctx); + return this._distanceToBorder(angle); } }]); - return CircleImageBase; + return Icon; })(_utilNodeBase2['default']); - exports['default'] = CircleImageBase; + exports['default'] = Icon; module.exports = exports['default']; /***/ }, -/* 72 */ +/* 76 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -30949,93 +29873,76 @@ 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 _utilCircleImageBase = __webpack_require__(71); + var _utilCircleImageBase = __webpack_require__(68); var _utilCircleImageBase2 = _interopRequireDefault(_utilCircleImageBase); - var CircularImage = (function (_CircleImageBase) { - function CircularImage(options, body, labelModule, imageObj) { - _classCallCheck(this, CircularImage); + var Image = (function (_CircleImageBase) { + function Image(options, body, labelModule, imageObj) { + _classCallCheck(this, Image); - _get(Object.getPrototypeOf(CircularImage.prototype), 'constructor', this).call(this, options, body, labelModule); + _get(Object.getPrototypeOf(Image.prototype), 'constructor', this).call(this, options, body, labelModule); this.imageObj = imageObj; - this._swapToImageResizeWhenImageLoaded = true; } - _inherits(CircularImage, _CircleImageBase); + _inherits(Image, _CircleImageBase); - _createClass(CircularImage, [{ + _createClass(Image, [{ 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._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; - - var size = Math.min(0.5 * this.height, 0.5 * this.width); - - this._drawRawCircle(ctx, x, y, selected, hover, size); - - ctx.save(); - ctx.circle(x, y, size); - ctx.stroke(); - ctx.clip(); + this.resize(); + this.left = x - this.width / 2; + this.top = y - this.height / 2; this._drawImageAtPosition(ctx); - ctx.restore(); - - this._drawImageLabel(ctx, x, y, selected); + this._drawImageLabel(ctx, x, y, selected || hover); 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); + this.resize(); + this.left = x - this.width / 2; + this.top = y - this.height / 2; + + 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.labelModule.size.width > 0) { + this.boundingBox.left = Math.min(this.boundingBox.left, this.labelModule.size.left); + this.boundingBox.right = Math.max(this.boundingBox.right, this.labelModule.size.left + this.labelModule.size.width); + this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelOffset); + } } }, { key: 'distanceToBorder', value: function distanceToBorder(ctx, angle) { this.resize(ctx); - return this._distanceToBorder(angle); + 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 CircularImage; + return Image; })(_utilCircleImageBase2['default']); - exports['default'] = CircularImage; + exports['default'] = Image; module.exports = exports['default']; /***/ }, -/* 73 */ +/* 77 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -31054,95 +29961,45 @@ 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 _utilNodeBase = __webpack_require__(69); + var _utilShapeBase = __webpack_require__(72); - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); - var Database = (function (_NodeBase) { - function Database(options, body, labelModule) { - _classCallCheck(this, Database); + var Square = (function (_ShapeBase) { + function Square(options, body, labelModule) { + _classCallCheck(this, Square); - _get(Object.getPrototypeOf(Database.prototype), 'constructor', this).call(this, options, body, labelModule); + _get(Object.getPrototypeOf(Square.prototype), 'constructor', this).call(this, options, body, labelModule); } - _inherits(Database, _NodeBase); + _inherits(Square, _ShapeBase); - _createClass(Database, [{ + _createClass(Square, [{ 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; - } + value: function resize() { + this._resizeShape(); } }, { 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); - - 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); - - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); - - // disable shadows for other elements. - this.disableShadow(ctx); - - ctx.stroke(); - - this.updateBoundingBox(x, y, ctx); - - this.labelModule.draw(ctx, x, y, selected); - } - }, { - key: 'updateBoundingBox', - value: function updateBoundingBox(x, y, ctx) { - this.resize(ctx); - - 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; + this._drawShape(ctx, 'square', 2, x, y, selected, hover); } }, { 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.resize(); + return this._distanceToBorder(angle); } }]); - return Database; - })(_utilNodeBase2['default']); + return Square; + })(_utilShapeBase2['default']); - exports['default'] = Database; + exports['default'] = Square; module.exports = exports['default']; /***/ }, -/* 74 */ +/* 78 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -31161,20 +30018,20 @@ 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 _utilShapeBase = __webpack_require__(75); + var _utilShapeBase = __webpack_require__(72); var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); - var Diamond = (function (_ShapeBase) { - function Diamond(options, body, labelModule) { - _classCallCheck(this, Diamond); + var Star = (function (_ShapeBase) { + function Star(options, body, labelModule) { + _classCallCheck(this, Star); - _get(Object.getPrototypeOf(Diamond.prototype), 'constructor', this).call(this, options, body, labelModule); + _get(Object.getPrototypeOf(Star.prototype), 'constructor', this).call(this, options, body, labelModule); } - _inherits(Diamond, _ShapeBase); + _inherits(Star, _ShapeBase); - _createClass(Diamond, [{ + _createClass(Star, [{ key: 'resize', value: function resize(ctx) { this._resizeShape(); @@ -31182,7 +30039,7 @@ return /******/ (function(modules) { // webpackBootstrap }, { key: 'draw', value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'diamond', 4, x, y, selected, hover); + this._drawShape(ctx, 'star', 4, x, y, selected, hover); } }, { key: 'distanceToBorder', @@ -31191,14 +30048,14 @@ return /******/ (function(modules) { // webpackBootstrap } }]); - return Diamond; + return Star; })(_utilShapeBase2['default']); - exports['default'] = Diamond; + exports['default'] = Star; module.exports = exports['default']; /***/ }, -/* 75 */ +/* 79 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -31217,87 +30074,75 @@ 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 _utilNodeBase = __webpack_require__(69); + var _utilNodeBase = __webpack_require__(66); var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); - var ShapeBase = (function (_NodeBase) { - function ShapeBase(options, body, labelModule) { - _classCallCheck(this, ShapeBase); + var Text = (function (_NodeBase) { + function Text(options, body, labelModule) { + _classCallCheck(this, Text); - _get(Object.getPrototypeOf(ShapeBase.prototype), 'constructor', this).call(this, options, body, labelModule); + _get(Object.getPrototypeOf(Text.prototype), 'constructor', this).call(this, options, body, labelModule); } - _inherits(ShapeBase, _NodeBase); + _inherits(Text, _NodeBase); - _createClass(ShapeBase, [{ - key: '_resizeShape', - value: function _resizeShape() { + _createClass(Text, [{ + key: 'resize', + value: function resize(ctx, selected) { if (this.width === undefined) { - var size = 2 * this.options.size; - this.width = size; - this.height = size; + 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: '_drawShape', - value: function _drawShape(ctx, shape, sizeMultiplier, x, y, selected, hover) { - this._resizeShape(); - + 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; - 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(); + this.labelModule.draw(ctx, x, y, selected || hover); // 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'); - } - 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.resize(); - if (this.options.label !== undefined && this.labelModule.size.width > 0) { - this.boundingBox.left = Math.min(this.boundingBox.left, this.labelModule.size.left); - this.boundingBox.right = Math.max(this.boundingBox.right, this.labelModule.size.left + this.labelModule.size.width); - this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelModule.size.height + 3); - } + this.left = x - this.width / 2; + this.top = y - this.height / 2; + + 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); } }]); - return ShapeBase; + return Text; })(_utilNodeBase2['default']); - exports['default'] = ShapeBase; + exports['default'] = Text; module.exports = exports['default']; /***/ }, -/* 76 */ +/* 80 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -31316,20 +30161,20 @@ 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 _utilShapeBase = __webpack_require__(75); + var _utilShapeBase = __webpack_require__(72); var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); - var Dot = (function (_ShapeBase) { - function Dot(options, body, labelModule) { - _classCallCheck(this, Dot); + var Triangle = (function (_ShapeBase) { + function Triangle(options, body, labelModule) { + _classCallCheck(this, Triangle); - _get(Object.getPrototypeOf(Dot.prototype), 'constructor', this).call(this, options, body, labelModule); + _get(Object.getPrototypeOf(Triangle.prototype), 'constructor', this).call(this, options, body, labelModule); } - _inherits(Dot, _ShapeBase); + _inherits(Triangle, _ShapeBase); - _createClass(Dot, [{ + _createClass(Triangle, [{ key: 'resize', value: function resize(ctx) { this._resizeShape(); @@ -31337,23 +30182,23 @@ return /******/ (function(modules) { // webpackBootstrap }, { key: 'draw', value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'circle', 2, x, y, selected, hover); + this._drawShape(ctx, 'triangle', 3, x, y, selected, hover); } }, { key: 'distanceToBorder', value: function distanceToBorder(ctx, angle) { - return this.options.size + this.options.borderWidth; + return this._distanceToBorder(angle); } }]); - return Dot; + return Triangle; })(_utilShapeBase2['default']); - exports['default'] = Dot; + exports['default'] = Triangle; module.exports = exports['default']; /***/ }, -/* 77 */ +/* 81 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -31372,301 +30217,480 @@ 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 _utilNodeBase = __webpack_require__(69); + var _utilShapeBase = __webpack_require__(72); - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); - var Ellipse = (function (_NodeBase) { - function Ellipse(options, body, labelModule) { - _classCallCheck(this, Ellipse); + var TriangleDown = (function (_ShapeBase) { + function TriangleDown(options, body, labelModule) { + _classCallCheck(this, TriangleDown); - _get(Object.getPrototypeOf(Ellipse.prototype), 'constructor', this).call(this, options, body, labelModule); + _get(Object.getPrototypeOf(TriangleDown.prototype), 'constructor', this).call(this, options, body, labelModule); } - _inherits(Ellipse, _NodeBase); + _inherits(TriangleDown, _ShapeBase); - _createClass(Ellipse, [{ + _createClass(TriangleDown, [{ 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; - } + value: function resize(ctx) { + this._resizeShape(); } }, { 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; + this._drawShape(ctx, 'triangleDown', 3, x, y, selected, hover); + } + }, { + key: 'distanceToBorder', + value: function distanceToBorder(ctx, angle) { + return this._distanceToBorder(angle); + } + }]); - var borderWidth = this.options.borderWidth; - var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; + return TriangleDown; + })(_utilShapeBase2['default']); - ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border; + exports['default'] = TriangleDown; + module.exports = exports['default']; - ctx.lineWidth = selected ? selectionLineWidth : borderWidth; - ctx.lineWidth /= this.body.view.scale; - ctx.lineWidth = Math.min(this.width, ctx.lineWidth); +/***/ }, +/* 82 */ +/***/ function(module, exports, __webpack_require__) { - 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); + 'use strict'; - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fill(); + Object.defineProperty(exports, '__esModule', { + value: true + }); - // disable shadows for other elements. - this.disableShadow(ctx); + 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.stroke(); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - this.updateBoundingBox(x, y); - this.labelModule.draw(ctx, x, y, selected); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + var _componentsEdge = __webpack_require__(83); + + var _componentsEdge2 = _interopRequireDefault(_componentsEdge); + + var _componentsSharedLabel = __webpack_require__(64); + + var _componentsSharedLabel2 = _interopRequireDefault(_componentsSharedLabel); + + var util = __webpack_require__(13); + var DataSet = __webpack_require__(19); + var DataView = __webpack_require__(21); + + var EdgesHandler = (function () { + function EdgesHandler(body, images, groups) { + var _this = this; + + _classCallCheck(this, EdgesHandler); + + this.body = body; + this.images = images; + this.groups = groups; + + // create the edge API in the body container + this.body.functions.createEdge = this.create.bind(this); + + 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); + } + }; + + 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, + labelHighlightBold: true, + 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 + }; + + util.extend(this.options, this.defaultOptions); + + this.bindEventListeners(); + } + + _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'; + } + 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]; + + // 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 is called when options of EXISTING nodes or edges have changed. + this.body.emitter.on('_dataUpdated', function () { + _this2.reconnectEdges(); + _this2.markAllEdgesAsDirty(); + }); + + // 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: 'updateBoundingBox', - value: function updateBoundingBox(x, y, ctx) { - this.resize(ctx, false); // just in case + 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); - this.left = x - this.width * 0.5; - this.top = y - this.height * 0.5; + // hanlde multiple input cases for color + if (options.color !== undefined) { + this.markAllEdgesAsDirty(); + } - this.boundingBox.left = this.left; - this.boundingBox.top = this.top; - this.boundingBox.bottom = this.top + this.height; - this.boundingBox.right = this.left + this.width; + // 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.font, options); + for (var edgeId in this.body.edges) { + if (this.body.edges.hasOwnProperty(edgeId)) { + this.body.edges[edgeId].updateLabelModule(); + } + } + } + + // update the state of the variables if needed + if (options.hidden !== undefined || options.physics !== undefined || dataChanged === true) { + this.body.emitter.emit('_dataChanged'); + } + } } }, { - 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']); + key: 'setData', - exports['default'] = Ellipse; - module.exports = exports['default']; + /** + * 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; -/***/ }, -/* 78 */ -/***/ function(module, exports, __webpack_require__) { + var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - 'use strict'; + var oldEdgesData = this.body.data.edges; - Object.defineProperty(exports, '__esModule', { - value: true - }); + 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'); + } - 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; }; })(); + // 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); + }); + } - 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 drawn edges + this.body.edges = {}; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + // 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); + }); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + // draw all new nodes + var ids = this.body.data.edges.getIds(); + this.add(ids, 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; } + if (doNotEmit === false) { + this.body.emitter.emit('_dataChanged'); + } + } + }, { + key: 'add', - var _utilNodeBase = __webpack_require__(69); + /** + * Add edges + * @param {Number[] | String[]} ids + * @private + */ + value: function add(ids) { + var doNotEmit = arguments[1] === undefined ? false : arguments[1]; - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + var edges = this.body.edges; + var edgesData = this.body.data.edges; - var Icon = (function (_NodeBase) { - function Icon(options, body, labelModule) { - _classCallCheck(this, Icon); + for (var i = 0; i < ids.length; i++) { + var id = ids[i]; - _get(Object.getPrototypeOf(Icon.prototype), 'constructor', this).call(this, options, body, labelModule); - } + var oldEdge = edges[id]; + if (oldEdge) { + oldEdge.disconnect(); + } - _inherits(Icon, _NodeBase); + var data = edgesData.get(id, { 'showInternalIds': true }); + edges[id] = this.create(data); + } - _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; + if (doNotEmit === false) { + this.body.emitter.emit('_dataChanged'); } } }, { - 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: 'update', - if (this.options.label !== undefined) { - var iconTextSpacing = 5; - this.labelModule.draw(ctx, x, y + this.height * 0.5 + iconTextSpacing, selected); + /** + * 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; + } } - this.updateBoundingBox(x, y); + if (dataChanged === true) { + this.body.emitter.emit('_dataChanged'); + } else { + this.body.emitter.emit('_dataUpdated'); + } } }, { - 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; + key: 'remove', - if (this.options.label !== undefined && this.labelModule.size.width > 0) { - 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); + /** + * 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) { + edge.edgeType.cleanup(); + edge.disconnect(); + delete edges[id]; + } } + + this.body.emitter.emit('_dataChanged'); } }, { - key: '_icon', - value: function _icon(ctx, x, y, selected) { - var iconSize = Number(this.options.icon.size); - - if (this.options.icon.code !== undefined) { - ctx.font = (selected ? 'bold ' : '') + iconSize + 'px ' + this.options.icon.face; - - // draw icon - ctx.fillStyle = this.options.icon.color || 'black'; - ctx.textAlign = 'center'; - ctx.textBaseline = 'middle'; - - // draw shadow if enabled - this.enableShadow(ctx); - ctx.fillText(this.options.icon.code, x, y); - - // 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: '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: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - return this._distanceToBorder(angle); - } - }]); - - return Icon; - })(_utilNodeBase2['default']); - - exports['default'] = Icon; - module.exports = exports['default']; - -/***/ }, -/* 79 */ -/***/ 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__(71); - - 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: 'create', + value: function create(properties) { + return new _componentsEdge2['default'](properties, this.body, this.options); } }, { - 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._drawImageAtPosition(ctx); - - this._drawImageLabel(ctx, x, y, selected || hover); - - this.updateBoundingBox(x, y); + key: 'markAllEdgesAsDirty', + value: function markAllEdgesAsDirty() { + for (var edgeId in this.body.edges) { + this.body.edges[edgeId].edgeType.colorDirty = true; + } } }, { - key: 'updateBoundingBox', - value: function updateBoundingBox(x, y) { - this.resize(); - this.left = x - this.width / 2; - this.top = y - this.height / 2; + key: 'reconnectEdges', - this.boundingBox.top = this.top; - this.boundingBox.left = this.left; - this.boundingBox.right = this.left + this.width; - this.boundingBox.bottom = this.top + this.height; + /** + * Reconnect all edges + * @private + */ + value: function reconnectEdges() { + var id; + var nodes = this.body.nodes; + var edges = this.body.edges; - if (this.options.label !== undefined && this.labelModule.size.width > 0) { - this.boundingBox.left = Math.min(this.boundingBox.left, this.labelModule.size.left); - this.boundingBox.right = Math.max(this.boundingBox.right, this.labelModule.size.left + this.labelModule.size.width); - this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelOffset); + 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: '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: '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 Image; - })(_utilCircleImageBase2['default']); + return EdgesHandler; + })(); - exports['default'] = Image; + exports['default'] = EdgesHandler; module.exports = exports['default']; /***/ }, -/* 80 */ +/* 83 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -31677,308 +30701,560 @@ 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__(75); + var _sharedLabel = __webpack_require__(64); - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); - - var Square = (function (_ShapeBase) { - function Square(options, body, labelModule) { - _classCallCheck(this, Square); + var _sharedLabel2 = _interopRequireDefault(_sharedLabel); - _get(Object.getPrototypeOf(Square.prototype), 'constructor', this).call(this, options, body, labelModule); - } + var _edgesBezierEdgeDynamic = __webpack_require__(84); - _inherits(Square, _ShapeBase); + var _edgesBezierEdgeDynamic2 = _interopRequireDefault(_edgesBezierEdgeDynamic); - _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(); - return this._distanceToBorder(angle); - } - }]); + var _edgesBezierEdgeStatic = __webpack_require__(87); - return Square; - })(_utilShapeBase2['default']); + var _edgesBezierEdgeStatic2 = _interopRequireDefault(_edgesBezierEdgeStatic); - exports['default'] = Square; - module.exports = exports['default']; + var _edgesStraightEdge = __webpack_require__(88); -/***/ }, -/* 81 */ -/***/ function(module, exports, __webpack_require__) { + var _edgesStraightEdge2 = _interopRequireDefault(_edgesStraightEdge); - 'use strict'; + var util = __webpack_require__(13); - Object.defineProperty(exports, '__esModule', { - value: true - }); + /** + * @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 _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 Edge = (function () { + function Edge(options, body, globalOptions) { + _classCallCheck(this, 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 (body === undefined) { + throw 'No body provided'; + } + this.options = util.bridgeObject(globalOptions); + this.body = body; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + // initialize variables + this.id = undefined; + this.fromId = undefined; + this.toId = undefined; + this.selected = false; + this.hover = false; + this.labelDirty = true; + this.colorDirty = true; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + this.baseWidth = this.options.width; + this.baseFontSize = this.options.font.size; - 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.from = undefined; // a node + this.to = undefined; // a node - var _utilShapeBase = __webpack_require__(75); + this.edgeType = undefined; - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + this.connected = false; - var Star = (function (_ShapeBase) { - function Star(options, body, labelModule) { - _classCallCheck(this, Star); + this.labelModule = new _sharedLabel2['default'](this.body, this.options); - _get(Object.getPrototypeOf(Star.prototype), 'constructor', this).call(this, options, body, labelModule); + this.setOptions(options); } - _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); - } - }]); - - return Star; - })(_utilShapeBase2['default']); - - exports['default'] = Star; - module.exports = exports['default']; - -/***/ }, -/* 82 */ -/***/ 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; }; })(); + _createClass(Edge, [{ + key: 'setOptions', - 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); } } }; + /** + * 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; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + Edge.parseOptions(this.options, options, true); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + if (options.id !== undefined) { + this.id = options.id; + } + if (options.from !== undefined) { + this.fromId = options.from; + } + if (options.to !== undefined) { + this.toId = options.to; + } + if (options.title !== undefined) { + this.title = options.title; + } + if (options.value !== undefined) { + options.value = parseFloat(options.value); + } - 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; } + // update label Module + this.updateLabelModule(); - var _utilNodeBase = __webpack_require__(69); + var dataChanged = this.updateEdgeType(); - var _utilNodeBase2 = _interopRequireDefault(_utilNodeBase); + // if anything has been updates, reset the selection width and the hover width + this._setInteractionWidths(); - var Text = (function (_NodeBase) { - function Text(options, body, labelModule) { - _classCallCheck(this, Text); + // A node is connected when it has a from and to node that both exist in the network.body.nodes. + this.connect(); - _get(Object.getPrototypeOf(Text.prototype), 'constructor', this).call(this, options, body, labelModule); - } + if (options.hidden !== undefined || options.physics !== undefined) { + dataChanged = true; + } - _inherits(Text, _NodeBase); + return dataChanged; + } + }, { + key: 'updateLabelModule', - _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; + /** + * 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: '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; + key: 'updateEdgeType', - // draw shadow if enabled - this.enableShadow(ctx); - this.labelModule.draw(ctx, x, y, selected || hover); + /** + * 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; + } - // disable shadows for other elements. - this.disableShadow(ctx); + if (changeInType === true) { + dataChanged = this.edgeType.cleanup(); + } + } - this.updateBoundingBox(x, y); + 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: 'updateBoundingBox', - value: function updateBoundingBox(x, y) { - this.resize(); - - this.left = x - this.width / 2; - this.top = y - this.height / 2; + key: 'togglePhysics', - this.boundingBox.top = this.top; - this.boundingBox.left = this.left; - this.boundingBox.right = this.left + this.width; - this.boundingBox.bottom = this.top + this.height; + /** + * Enable or disable the physics. + * @param status + */ + value: function togglePhysics(status) { + this.options.physics = status; + this.edgeType.togglePhysics(status); } }, { - key: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - this.resize(ctx); - return this._distanceToBorder(angle); - } - }]); - - return Text; - })(_utilNodeBase2['default']); - - exports['default'] = Text; - module.exports = exports['default']; - -/***/ }, -/* 83 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; + key: 'connect', - Object.defineProperty(exports, '__esModule', { - value: true - }); + /** + * Connect an edge to its nodes + */ + value: function connect() { + this.disconnect(); - 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.from = this.body.nodes[this.fromId] || undefined; + this.to = this.body.nodes[this.toId] || undefined; + this.connected = this.from !== undefined && this.to !== 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); } } }; + 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); + } + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + this.edgeType.connect(); + } + }, { + key: 'disconnect', - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * 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; + } - 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.connected = false; + } + }, { + key: 'getTitle', - var _utilShapeBase = __webpack_require__(75); + /** + * 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', - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + /** + * 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 Triangle = (function (_ShapeBase) { - function Triangle(options, body, labelModule) { - _classCallCheck(this, Triangle); + /** + * Retrieve the value of the edge. Can be undefined + * @return {Number} value + */ + value: function getValue() { + return this.options.value; + } + }, { + key: 'setValueRange', - _get(Object.getPrototypeOf(Triangle.prototype), 'constructor', this).call(this, options, body, labelModule); - } + /** + * 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; + } - _inherits(Triangle, _ShapeBase); + 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; + } - _createClass(Triangle, [{ - key: 'resize', - value: function resize(ctx) { - this._resizeShape(); + 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', - value: function draw(ctx, x, y, selected, hover) { - this._drawShape(ctx, 'triangle', 3, x, y, selected, hover); + + /** + * 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: 'distanceToBorder', - value: function distanceToBorder(ctx, angle) { - return this._distanceToBorder(angle); + 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) { + this.labelModule.pointToSelf = false; + var point = this.edgeType.getPoint(0.5, viaNode); + ctx.save(); - return Triangle; - })(_utilShapeBase2['default']); + // 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); + } - exports['default'] = Triangle; - module.exports = exports['default']; + // draw the label + this.labelModule.draw(ctx, point.x, point.y, selected); + ctx.restore(); + } else { + // Ignore the orientations. + this.labelModule.pointToSelf = true; + var x, y; + var radius = this.options.selfReferenceSize; + if (node1.shape.width > node1.shape.height) { + x = node1.x + node1.shape.width * 0.5; + y = node1.y - radius; + } else { + x = node1.x + radius; + y = node1.y - node1.shape.height * 0.5; + } + point = this._pointOnCircle(x, y, radius, 0.125); + this.labelModule.draw(ctx, point.x, point.y, selected); + } + } + } + }, { + key: 'isOverlappingWith', -/***/ }, -/* 84 */ -/***/ function(module, exports, __webpack_require__) { + /** + * 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; - 'use strict'; + var dist = this.edgeType.getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj); - Object.defineProperty(exports, '__esModule', { - value: true - }); + return dist < distMax; + } else { + return false; + } + } + }, { + key: '_rotateForLabelAlignment', - 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; }; })(); + /** + * 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); - 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); } } }; + // rotate so label it is readable + if (angleInDegrees < -1 && dx < 0 || angleInDegrees > 0 && dx < 0) { + angleInDegrees = angleInDegrees + Math.PI; + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + ctx.rotate(angleInDegrees); + } + }, { + key: '_pointOnCircle', - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * 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]; - 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 fields = ['id', 'from', 'hidden', 'hoverWidth', 'label', 'labelHighlightBold', 'length', 'line', 'opacity', 'physics', 'selectionWidth', 'selfReferenceSize', 'to', 'title', 'value', 'width']; - var _utilShapeBase = __webpack_require__(75); + // only deep extend the items in the field array. These do not have shorthand. + util.selectiveDeepExtend(fields, parentOptions, newOptions, allowDeletion); - var _utilShapeBase2 = _interopRequireDefault(_utilShapeBase); + util.mergeOptions(parentOptions, newOptions, 'smooth'); + util.mergeOptions(parentOptions, newOptions, 'shadow'); - var TriangleDown = (function (_ShapeBase) { - function TriangleDown(options, body, labelModule) { - _classCallCheck(this, TriangleDown); + if (newOptions.dashes !== undefined && newOptions.dashes !== null) { + parentOptions.dashes = newOptions.dashes; + } else if (allowDeletion === true && newOptions.dashes === null) { + parentOptions.dashes = undefined; + delete parentOptions.dashes; + } - _get(Object.getPrototypeOf(TriangleDown.prototype), 'constructor', this).call(this, options, body, labelModule); - } + // 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; + } - _inherits(TriangleDown, _ShapeBase); + // 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; + } - _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); + // 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; + } + + // handle the font settings + if (newOptions.font !== undefined) { + _sharedLabel2['default'].parseOptions(parentOptions.font, newOptions); + } } }]); - return TriangleDown; - })(_utilShapeBase2['default']); + return Edge; + })(); - exports['default'] = TriangleDown; + exports['default'] = Edge; module.exports = exports['default']; /***/ }, -/* 85 */ +/* 84 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -31997,7 +31273,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 _utilBezierEdgeBase = __webpack_require__(86); + var _utilBezierEdgeBase = __webpack_require__(85); var _utilBezierEdgeBase2 = _interopRequireDefault(_utilBezierEdgeBase); @@ -32143,7 +31419,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = exports['default']; /***/ }, -/* 86 */ +/* 85 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -32162,7 +31438,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 _EdgeBase2 = __webpack_require__(87); + var _EdgeBase2 = __webpack_require__(86); var _EdgeBase3 = _interopRequireDefault(_EdgeBase2); @@ -32290,7 +31566,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = exports['default']; /***/ }, -/* 87 */ +/* 86 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -32305,7 +31581,7 @@ 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__(14); + var util = __webpack_require__(13); var EdgeBase = (function () { function EdgeBase(options, body, labelModule) { @@ -32887,7 +32163,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = exports['default']; /***/ }, -/* 88 */ +/* 87 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -32906,7 +32182,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 _utilBezierEdgeBase = __webpack_require__(86); + var _utilBezierEdgeBase = __webpack_require__(85); var _utilBezierEdgeBase2 = _interopRequireDefault(_utilBezierEdgeBase); @@ -33102,796 +32378,1720 @@ return /******/ (function(modules) { // webpackBootstrap } } } - return { x: xVia, 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']; + +/***/ }, +/* 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 _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 _utilEdgeBase = __webpack_require__(86); + + var _utilEdgeBase2 = _interopRequireDefault(_utilEdgeBase); + + var StraightEdge = (function (_EdgeBase) { + function StraightEdge(options, body, labelModule) { + _classCallCheck(this, StraightEdge); + + _get(Object.getPrototypeOf(StraightEdge.prototype), 'constructor', this).call(this, options, body, labelModule); + } + + _inherits(StraightEdge, _EdgeBase); + + _createClass(StraightEdge, [{ + 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.lineTo(this.to.x, this.to.y); + // draw shadow if enabled + this.enableShadow(ctx); + ctx.stroke(); + this.disableShadow(ctx); + return undefined; + } + }, { + 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) { + 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 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; + + var borderPos = {}; + borderPos.x = (1 - toBorderPoint) * node2.x + toBorderPoint * node1.x; + borderPos.y = (1 - toBorderPoint) * node2.y + toBorderPoint * node1.y; + + 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); + } + }]); + + return StraightEdge; + })(_utilEdgeBase2['default']); + + exports['default'] = StraightEdge; + module.exports = exports['default']; + +/***/ }, +/* 89 */ +/***/ 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 _componentsPhysicsBarnesHutSolver = __webpack_require__(90); + + var _componentsPhysicsBarnesHutSolver2 = _interopRequireDefault(_componentsPhysicsBarnesHutSolver); + + var _componentsPhysicsRepulsionSolver = __webpack_require__(91); + + var _componentsPhysicsRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsRepulsionSolver); + + var _componentsPhysicsHierarchicalRepulsionSolver = __webpack_require__(92); + + var _componentsPhysicsHierarchicalRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsHierarchicalRepulsionSolver); + + var _componentsPhysicsSpringSolver = __webpack_require__(93); + + var _componentsPhysicsSpringSolver2 = _interopRequireDefault(_componentsPhysicsSpringSolver); + + var _componentsPhysicsHierarchicalSpringSolver = __webpack_require__(94); + + var _componentsPhysicsHierarchicalSpringSolver2 = _interopRequireDefault(_componentsPhysicsHierarchicalSpringSolver); + + var _componentsPhysicsCentralGravitySolver = __webpack_require__(95); + + var _componentsPhysicsCentralGravitySolver2 = _interopRequireDefault(_componentsPhysicsCentralGravitySolver); + + var _componentsPhysicsFA2BasedRepulsionSolver = __webpack_require__(96); + + var _componentsPhysicsFA2BasedRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsFA2BasedRepulsionSolver); + + var _componentsPhysicsFA2BasedCentralGravitySolver = __webpack_require__(97); + + var _componentsPhysicsFA2BasedCentralGravitySolver2 = _interopRequireDefault(_componentsPhysicsFA2BasedCentralGravitySolver); + + var util = __webpack_require__(13); + + var PhysicsEngine = (function () { + function PhysicsEngine(body) { + _classCallCheck(this, PhysicsEngine); + + 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.initialStabilizationEmitted = false; + + 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 = { + enabled: true, + 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.options.enabled = false; + this.physicsEnabled = false; + this.stopSimulation(); + } else { + this.physicsEnabled = true; + util.selectiveNotDeepExtend(['stabilization'], this.options, options); + util.mergeOptions(this.options, options, 'stabilization'); + + if (options.enabled === undefined) { + this.options.enabled = true; + } + + if (this.options.enabled === false) { + this.physicsEnabled = false; + this.stopSimulation(); + } + } + } + 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 && this.options.enabled === 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', + + /** + * Start the simulation + */ + value: function startSimulation() { + if (this.physicsEnabled === true && this.options.enabled === true) { + this.stabilized = false; + + // this sets the width of all nodes initially which could be required for the avoidOverlap + this.body.emitter.emit('_resizeNodes'); + 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', + + /** + * Stop the simulation, force stabilization. + */ + 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'); + } + } + } + }, { + key: 'simulationStep', + + /** + * 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; + + // run double speed if it is a little graph + if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) { + this.physicsTick(); + + // this makes sure there is no jitter. The decision is taken once to run it at double speed. + this.runDoubleSpeed = true; + } + + 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: '_findBorderPosition', - value: function _findBorderPosition(nearNode, ctx) { - var options = arguments[2] === undefined ? {} : arguments[2]; + key: '_emitStabilized', + value: function _emitStabilized() { + var _this2 = this; - 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); + if (this.stabilizationIterations > 1 || this.initialStabilizationEmitted === false) { + this.initialStabilizationEmitted = true; + setTimeout(function () { + _this2.body.emitter.emit('stabilized', { iterations: _this2.stabilizationIterations }); + _this2.stabilizationIterations = 0; + }, 0); + } } }, { - key: 'getPoint', + key: 'physicsTick', /** - * 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}} + * A single simulation step (or 'tick') in the physics simulation + * * @private */ - value: function getPoint(percentage) { - var via = arguments[1] === undefined ? this._getViaCoordinates() : arguments[1]; + value: function physicsTick() { + if (this.stabilized === false) { + this.calculateForces(); + this.stabilized = this.moveNodes(); - 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; + // 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 { x: x, y: y }; + this.stabilizationIterations++; + } } - }]); + }, { + key: 'updatePhysicsData', - return BezierEdgeStatic; - })(_utilBezierEdgeBase2['default']); + /** + * 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; - exports['default'] = BezierEdgeStatic; - module.exports = exports['default']; + // 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); + } + } + } -/***/ }, -/* 89 */ -/***/ function(module, exports, __webpack_require__) { + // 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); + } + } + } - 'use strict'; + // 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 }; - Object.defineProperty(exports, '__esModule', { - value: true - }); + // 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 }; + } + } - 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; }; })(); + // 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', - 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); } } }; + /** + * 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; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + 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', - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + /** + * 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); - 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; } + 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; + } - var _utilEdgeBase = __webpack_require__(87); + if (nodesPresent === true) { + if (vminCorrected > 0.5 * this.options.maxVelocity) { + return false; + } else { + return stabilized; + } + } + return true; + } + }, { + key: '_performStep', - var _utilEdgeBase2 = _interopRequireDefault(_utilEdgeBase); + /** + * 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; - var StraightEdge = (function (_EdgeBase) { - function StraightEdge(options, body, labelModule) { - _classCallCheck(this, StraightEdge); + // 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(Object.getPrototypeOf(StraightEdge.prototype), 'constructor', this).call(this, options, body, labelModule); - } + 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; + } - _inherits(StraightEdge, _EdgeBase); + 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; + } - _createClass(StraightEdge, [{ - key: '_line', + var totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x, 2) + Math.pow(velocities[nodeId].y, 2)); + return totalVelocity; + } + }, { + key: 'calculateForces', /** - * Draw a line between two nodes - * @param {CanvasRenderingContext2D} ctx + * 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 _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 _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: 'getPoint', + key: '_restoreFrozenNodes', /** - * 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}} + * Unfreezes the nodes that have been frozen by _freezeDefinedNodes. + * * @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 - }; + 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: '_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: '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; } - 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; + if (this.physicsBody.physicsNodeIndices.length === 0) { + this.ready = true; + return; + } - var borderPos = {}; - borderPos.x = (1 - toBorderPoint) * node2.x + toBorderPoint * node1.x; - borderPos.y = (1 - toBorderPoint) * node2.y + toBorderPoint * node1.y; + // this sets the width of all nodes initially which could be required for the avoidOverlap + this.body.emitter.emit('_resizeNodes'); - return borderPos; + // stop the render loop + this.stopSimulation(); + + // set stabilze to false + this.stabilized = false; + + // block redraw requests + this.body.emitter.emit('_blockRedraw'); + this.targetIterations = iterations; + + // start the stabilization + if (this.options.stabilization.onlyDynamicEdges === true) { + this._freezeNodes(); + } + this.stabilizationIterations = 0; + + setTimeout(function () { + return _this3._stabilizationBatch(); + }, 0); } }, { - 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: '_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('_allowRedraw'); + 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 StraightEdge; - })(_utilEdgeBase2['default']); + return PhysicsEngine; + })(); - exports['default'] = StraightEdge; + exports['default'] = PhysicsEngine; module.exports = exports['default']; /***/ }, /* 90 */ /***/ 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 }; } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - 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.body = body; + this.physicsBody = physicsBody; + this.barnesHutTree; + this.setOptions(options); + this.randomSeed = 5; + } - var _componentsPhysicsBarnesHutSolver = __webpack_require__(91); + _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: "seededRandom", + value: function seededRandom() { + var x = Math.sin(this.randomSeed++) * 10000; + return x - Math.floor(x); + } + }, { + key: "solve", - var _componentsPhysicsBarnesHutSolver2 = _interopRequireDefault(_componentsPhysicsBarnesHutSolver); + /** + * 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; - var _componentsPhysicsRepulsionSolver = __webpack_require__(92); + // create the tree + var barnesHutTree = this._formBarnesHutTree(nodes, nodeIndices); - var _componentsPhysicsRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsRepulsionSolver); + // for debugging + this.barnesHutTree = barnesHutTree; - var _componentsPhysicsHierarchicalRepulsionSolver = __webpack_require__(93); + // 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", - var _componentsPhysicsHierarchicalRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsHierarchicalRepulsionSolver); + /** + * 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; - var _componentsPhysicsSpringSolver = __webpack_require__(94); + // 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); - var _componentsPhysicsSpringSolver2 = _interopRequireDefault(_componentsPhysicsSpringSolver); + // 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); + } + } + } + } + } + }, { + key: "_calculateForces", - var _componentsPhysicsHierarchicalSpringSolver = __webpack_require__(95); + /** + * 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 _componentsPhysicsHierarchicalSpringSolver2 = _interopRequireDefault(_componentsPhysicsHierarchicalSpringSolver); + if (this.overlapAvoidanceFactor < 1) { + distance = Math.max(0.1 + this.overlapAvoidanceFactor * node.shape.radius, distance - node.shape.radius); + } - var _componentsPhysicsCentralGravitySolver = __webpack_require__(96); + // 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; - var _componentsPhysicsCentralGravitySolver2 = _interopRequireDefault(_componentsPhysicsCentralGravitySolver); + this.physicsBody.forces[node.id].x += fx; + this.physicsBody.forces[node.id].y += fy; + } + }, { + key: "_formBarnesHutTree", - var _componentsPhysicsFA2BasedRepulsionSolver = __webpack_require__(97); + /** + * 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; - var _componentsPhysicsFA2BasedRepulsionSolver2 = _interopRequireDefault(_componentsPhysicsFA2BasedRepulsionSolver); + var minX = nodes[nodeIndices[0]].x; + var minY = nodes[nodeIndices[0]].y; + var maxX = nodes[nodeIndices[0]].x; + var maxY = nodes[nodeIndices[0]].y; - var _componentsPhysicsFA2BasedCentralGravitySolver = __webpack_require__(98); + // 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 _componentsPhysicsFA2BasedCentralGravitySolver2 = _interopRequireDefault(_componentsPhysicsFA2BasedCentralGravitySolver); + 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); - var util = __webpack_require__(14); + // 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); - var PhysicsEngine = (function () { - function PhysicsEngine(body) { - _classCallCheck(this, PhysicsEngine); + // 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.body = body; - this.physicsBody = { physicsNodeIndices: [], physicsEdgeIndices: [], forces: {}, velocities: {} }; + // make global + return barnesHutTree; + } + }, { + key: "_updateBranchMass", - this.physicsEnabled = true; - this.simulationInterval = 1000 / 60; - this.requiresTimeout = true; - this.previousStates = {}; - this.freezeCache = {}; - this.renderTimer = undefined; - this.initialStabilizationEmitted = false; + /** + * 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; - this.stabilized = false; - this.startedStabilization = false; - this.stabilizationIterations = 0; - this.ready = false; // will be set to true if the stabilize + parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass; + parentBranch.centerOfMass.x *= totalMassInv; - // default options - this.options = {}; - this.defaultOptions = { - enabled: true, - 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); + parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass; + parentBranch.centerOfMass.y *= totalMassInv; - this.bindEventListeners(); - } + 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", - _createClass(PhysicsEngine, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this = 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); + } - 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(); + 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"); } - }); - this.body.emitter.on('startSimulation', function () { - if (_this.ready === true) { - _this.startSimulation(); + } 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"); } - }); - 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.options.enabled = false; - this.physicsEnabled = false; - this.stopSimulation(); - } else { - this.physicsEnabled = true; - util.selectiveNotDeepExtend(['stabilization'], this.options, options); - util.mergeOptions(this.options, options, 'stabilization'); - - if (options.enabled === undefined) { - this.options.enabled = true; - } + key: "_placeInRegion", - if (this.options.enabled === false) { - this.physicsEnabled = false; - this.stopSimulation(); + /** + * 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 += this.seededRandom(); + node.y += this.seededRandom(); + } 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; } - 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); + 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"); - this.modelOptions = options; + if (containedNode != null) { + this._placeInTree(parentBranch, containedNode); + } } }, { - key: 'initPhysics', - value: function initPhysics() { - if (this.physicsEnabled === true && this.options.enabled === 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: "_insertRegion", + + /** + * 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; } + + 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: 'startSimulation', + key: "_debug", + + //--------------------------- DEBUGGING BELOW ---------------------------// /** - * Start the simulation + * This function is for debugging purposed, it draws the tree. + * + * @param ctx + * @param color + * @private */ - value: function startSimulation() { - if (this.physicsEnabled === true && this.options.enabled === true) { - this.stabilized = false; + value: function _debug(ctx, color) { + if (this.barnesHutTree !== undefined) { - // this sets the width of all nodes initially which could be required for the avoidOverlap - this.body.emitter.emit('_resizeNodes'); - 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'); + ctx.lineWidth = 1; + + this._drawBranch(this.barnesHutTree.root, ctx, color); } } }, { - key: 'stopSimulation', + key: "_drawBranch", /** - * Stop the simulation, force stabilization. + * This function is for debugging purposes. It draws the branches recursively. + * + * @param branch + * @param ctx + * @param color + * @private */ - value: function stopSimulation() { - var emit = arguments[0] === undefined ? true : arguments[0]; - - this.stabilized = true; - if (emit === true) { - this._emitStabilized(); + value: function _drawBranch(branch, ctx, color) { + if (color === undefined) { + color = "#FF0000"; } - if (this.viewFunction !== undefined) { - this.body.emitter.off('initRedraw', this.viewFunction); - this.viewFunction = undefined; - if (emit === true) { - this.body.emitter.emit('_stopRendering'); - } + + 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(); + } + */ } - }, { - key: 'simulationStep', + }]); - /** - * 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; + return BarnesHutSolver; + })(); - // run double speed if it is a little graph - if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) { - this.physicsTick(); + exports["default"] = BarnesHutSolver; + module.exports = exports["default"]; - // this makes sure there is no jitter. The decision is taken once to run it at double speed. - this.runDoubleSpeed = true; - } +/***/ }, +/* 91 */ +/***/ function(module, exports, __webpack_require__) { - 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; + "use strict"; - if (this.stabilizationIterations > 1 || this.initialStabilizationEmitted === false) { - this.initialStabilizationEmitted = true; - setTimeout(function () { - _this2.body.emitter.emit('stabilized', { iterations: _this2.stabilizationIterations }); - _this2.stabilizationIterations = 0; - }, 0); - } - } - }, { - key: 'physicsTick', + Object.defineProperty(exports, "__esModule", { + value: true + }); - /** - * A single simulation step (or 'tick') in the physics simulation - * - * @private - */ - value: function physicsTick() { - if (this.stabilized === false) { - this.calculateForces(); - this.stabilized = this.moveNodes(); + 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; }; })(); - // 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; - } - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - this.stabilizationIterations++; - } + 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: 'updatePhysicsData', + key: "solve", /** - * 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. + * Calculate the forces the nodes apply on each other based on a repulsion field. + * This field is linearly approximated. * * @private */ - value: function updatePhysicsData() { - this.physicsBody.forces = {}; - this.physicsBody.physicsNodeIndices = []; - this.physicsBody.physicsEdgeIndices = []; + value: function solve() { + var dx, dy, distance, fx, fy, repulsingForce, node1, node2; + var nodes = this.body.nodes; - var edges = this.body.edges; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var forces = this.physicsBody.forces; - // 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); + // 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); + + // same condition as BarnesHutSolver, making sure nodes are never 100% overlapping. + if (distance === 0) { + distance = 0.1 * Math.random(); + dx = distance; } - } - } - // 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 (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; + + 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; } } } + } + }]); - // 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 }; + return RepulsionSolver; + })(); - // 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 }; - } - } + exports["default"] = RepulsionSolver; + module.exports = exports["default"]; - // clean deleted nodes from the velocity vector - for (var nodeId in this.physicsBody.velocities) { - if (nodes[nodeId] === undefined) { - delete this.physicsBody.velocities[nodeId]; - } - } +/***/ }, +/* 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; }; })(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var HierarchicalRepulsionSolver = (function () { + function HierarchicalRepulsionSolver(body, physicsBody, options) { + _classCallCheck(this, HierarchicalRepulsionSolver); + + this.body = body; + this.physicsBody = physicsBody; + this.setOptions(options); + } + + _createClass(HierarchicalRepulsionSolver, [{ + key: "setOptions", + value: function setOptions(options) { + this.options = options; } }, { - key: 'revert', + key: "solve", /** - * Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized. + * Calculate the forces the nodes apply on each other based on a repulsion field. + * This field is linearly approximated. + * + * @private */ - value: function revert() { - var nodeIds = Object.keys(this.previousStates); + value: function solve() { + var dx, dy, distance, fx, fy, repulsingForce, node1, node2, i, j; + var nodes = this.body.nodes; - var velocities = this.physicsBody.velocities; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var forces = this.physicsBody.forces; - 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; + // 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); + + 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; } - } 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); + return HierarchicalRepulsionSolver; + })(); - 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; - } + exports["default"] = HierarchicalRepulsionSolver; + module.exports = exports["default"]; - if (nodesPresent === true) { - if (vminCorrected > 0.5 * this.options.maxVelocity) { - return false; - } else { - return stabilized; - } - } - return true; - } - }, { - key: '_performStep', +/***/ }, +/* 93 */ +/***/ function(module, exports, __webpack_require__) { - /** - * 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; + "use strict"; - // store the state so we can revert - this.previousStates[nodeId] = { x: node.x, y: node.y, vx: velocities[nodeId].x, vy: velocities[nodeId].y }; + Object.defineProperty(exports, "__esModule", { + value: true + }); - 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; - } + 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 (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; - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x, 2) + Math.pow(velocities[nodeId].y, 2)); - return totalVelocity; - } - }, { - key: 'calculateForces', + var SpringSolver = (function () { + function SpringSolver(body, physicsBody, options) { + _classCallCheck(this, SpringSolver); - /** - * calculate the forces for one physics iteration. - */ - value: function calculateForces() { - this.gravitySolver.solve(); - this.nodesSolver.solve(); - this.edgesSolver.solve(); + this.body = body; + this.physicsBody = physicsBody; + this.setOptions(options); + } + + _createClass(SpringSolver, [{ + key: "setOptions", + value: function setOptions(options) { + this.options = options; } }, { - key: '_freezeNodes', + key: "solve", /** - * 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. + * This function calculates the springforces on the nodes, accounting for the support nodes. * * @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; + 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); + } } } } } }, { - key: '_restoreFrozenNodes', + key: "_calculateSpringForce", /** - * Unfreezes the nodes that have been frozen by _freezeDefinedNodes. + * This is the code actually performing the calculation for the function above. * + * @param node1 + * @param node2 + * @param edgeLength * @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; - } - } + 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; } - this.freezeCache = {}; + } + }]); + + return SpringSolver; + })(); + + exports["default"] = SpringSolver; + 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; }; })(); + + 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: 'stabilize', + key: "solve", /** - * Find a stable position for all nodes + * This function calculates the springforces on the nodes, accounting for the support nodes. + * * @private */ - value: function stabilize() { - var _this3 = this; - - var iterations = arguments[0] === undefined ? this.options.stabilization.iterations : arguments[0]; + value: function solve() { + var edgeLength, edge; + var dx, dy, fx, fy, springForce, distance; + var edges = this.body.edges; + var factor = 0.5; - 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; - } + var edgeIndices = this.physicsBody.physicsEdgeIndices; + var nodeIndices = this.physicsBody.physicsNodeIndices; + var forces = this.physicsBody.forces; - if (this.physicsBody.physicsNodeIndices.length === 0) { - this.ready = true; - return; + // 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 sets the width of all nodes initially which could be required for the avoidOverlap - this.body.emitter.emit('_resizeNodes'); + // 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; - // stop the render loop - this.stopSimulation(); + 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; - // set stabilze to false - this.stabilized = false; + // the 1/distance is so the fx and fy can be calculated without sine or cosine. + springForce = this.options.springConstant * (edgeLength - distance) / distance; - // block redraw requests - this.body.emitter.emit('_blockRedraw'); - this.targetIterations = iterations; + fx = dx * springForce; + fy = dy * springForce; - // start the stabilization - if (this.options.stabilization.onlyDynamicEdges === true) { - this._freezeNodes(); + if (edge.to.level != edge.from.level) { + if (forces[edge.toId] !== undefined) { + forces[edge.toId].springFx -= fx; + forces[edge.toId].springFy -= fy; + } + if (forces[edge.fromId] !== undefined) { + forces[edge.fromId].springFx += fx; + forces[edge.fromId].springFy += fy; + } + } else { + if (forces[edge.toId] !== undefined) { + forces[edge.toId].x -= factor * fx; + forces[edge.toId].y -= factor * fy; + } + if (forces[edge.fromId] !== undefined) { + forces[edge.fromId].x += factor * fx; + forces[edge.fromId].y += factor * fy; + } + } + } } - 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++; - } + // 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 (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('_allowRedraw'); - if (this.options.stabilization.fit === true) { - this.body.emitter.emit('fit'); + forces[nodeId].x += springFx; + forces[nodeId].y += springFy; } - if (this.options.stabilization.onlyDynamicEdges === true) { - this._restoreFrozenNodes(); + // 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.body.emitter.emit('stabilizationIterationsDone'); - this.body.emitter.emit('_requestRedraw'); - - if (this.stabilized === true) { - this._emitStabilized(); - } else { - this.startSimulation(); + for (var i = 0; i < nodeIndices.length; i++) { + var nodeId = nodeIndices[i]; + forces[nodeId].x -= correctionFx; + forces[nodeId].y -= correctionFy; } - - this.ready = true; } }]); - return PhysicsEngine; + return HierarchicalSpringSolver; })(); - exports['default'] = PhysicsEngine; - module.exports = exports['default']; + exports["default"] = HierarchicalSpringSolver; + module.exports = exports["default"]; /***/ }, -/* 91 */ +/* 95 */ /***/ function(module, exports, __webpack_require__) { "use strict"; @@ -33904,111 +34104,95 @@ return /******/ (function(modules) { // webpackBootstrap 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); + var CentralGravitySolver = (function () { + function CentralGravitySolver(body, physicsBody, options) { + _classCallCheck(this, CentralGravitySolver); this.body = body; this.physicsBody = physicsBody; - this.barnesHutTree; this.setOptions(options); - this.randomSeed = 5; } - _createClass(BarnesHutSolver, [{ + _createClass(CentralGravitySolver, [{ 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: "seededRandom", - value: function seededRandom() { - var x = Math.sin(this.randomSeed++) * 10000; - return x - Math.floor(x); } }, { 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); + 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 debugging - this.barnesHutTree = barnesHutTree; + 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); - // 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); - } - } + this._calculateForces(distance, dx, dy, forces, node); } } }, { - key: "_getForceContribution", + key: "_calculateForces", /** - * 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 + * Calculate the forces based on the distance. * @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; + 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; + } + }]); - // 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); + return CentralGravitySolver; + })(); - // 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); - } - } - } - } - } - }, { + exports["default"] = CentralGravitySolver; + 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 _BarnesHutSolver2 = __webpack_require__(90); + + 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", /** @@ -34023,7 +34207,7 @@ return /******/ (function(modules) { // webpackBootstrap */ value: function _calculateForces(distance, dx, dy, node, parentBranch) { if (distance === 0) { - distance = 0.1; + distance = 0.1 * Math.random(); dx = distance; } @@ -34031,990 +34215,1270 @@ return /******/ (function(modules) { // webpackBootstrap 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 / Math.pow(distance, 3); + 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: "_formBarnesHutTree", + }]); - /** - * 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; + return ForceAtlas2BasedRepulsionSolver; + })(_BarnesHutSolver3["default"]); - var minX = nodes[nodeIndices[0]].x; - var minY = nodes[nodeIndices[0]].y; - var maxX = nodes[nodeIndices[0]].x; - var maxY = nodes[nodeIndices[0]].y; + exports["default"] = ForceAtlas2BasedRepulsionSolver; + module.exports = exports["default"]; - // 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 +/***/ }, +/* 97 */ +/***/ function(module, exports, __webpack_require__) { - 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); + "use strict"; - // 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); + Object.defineProperty(exports, "__esModule", { + value: true + }); - // 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); - } - } + 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; }; })(); - // make global - return barnesHutTree; - } - }, { - key: "_updateBranchMass", + 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 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; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - 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; + 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; } - 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", + var _CentralGravitySolver2 = __webpack_require__(95); - /** - * 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); - } + var _CentralGravitySolver3 = _interopRequireDefault(_CentralGravitySolver2); - 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", + 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", /** - * actually place the node in a region (or branch) - * - * @param parentBranch - * @param node - * @param region + * Calculate the forces based on the distance. * @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 += this.seededRandom(); - node.y += this.seededRandom(); - } 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 _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 ForceAtlas2BasedCentralGravitySolver; + })(_CentralGravitySolver3["default"]); + + exports["default"] = ForceAtlas2BasedCentralGravitySolver; + 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; }; })(); + + 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__(99); + + var _componentsNodesCluster2 = _interopRequireDefault(_componentsNodesCluster); + + var util = __webpack_require__(13); + + var ClusterEngine = (function () { + function ClusterEngine(body) { + var _this = this; + + _classCallCheck(this, ClusterEngine); + + this.body = body; + this.clusteredNodes = {}; + + this.options = {}; + this.defaultOptions = {}; + util.extend(this.options, this.defaultOptions); + + this.body.emitter.on('_resetData', function () { + _this.clusteredNodes = {}; + }); + } + + _createClass(ClusterEngine, [{ + key: 'setOptions', + value: function setOptions(options) { + if (options !== undefined) {} + } }, { - key: "_splitBranch", + key: 'clusterByHubsize', /** - * 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; + * + * @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(); } - parentBranch.childrenCount = 4; - parentBranch.children.data = null; - this._insertRegion(parentBranch, "NW"); - this._insertRegion(parentBranch, "NE"); - this._insertRegion(parentBranch, "SW"); - this._insertRegion(parentBranch, "SE"); - if (containedNode != null) { - this._placeInTree(parentBranch, containedNode); + 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: "_insertRegion", + key: 'cluster', /** - * 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; + * 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 (options.joinCondition === undefined) { + throw new Error('Cannot call clusterByNodeData without a joinCondition function in the options.'); } - 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 - }; + // check if the options object is fine, append if needed + options = this._checkOptions(options); + + var childNodesObj = {}; + var childEdgesObj = {}; + + // 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]; + + // 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._cluster(childNodesObj, childEdgesObj, options, refreshData); } }, { - key: "_debug", - - //--------------------------- DEBUGGING BELOW ---------------------------// + key: 'clusterOutliers', /** - * This function is for debugging purposed, it draws the tree. - * - * @param ctx - * @param color - * @private - */ - value: function _debug(ctx, color) { - if (this.barnesHutTree !== undefined) { + * 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]; - ctx.lineWidth = 1; + options = this._checkOptions(options); + var clusters = []; - this._drawBranch(this.barnesHutTree.root, ctx, color); + // 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 }); + } + } + } + } + + for (var i = 0; i < clusters.length; i++) { + this._cluster(clusters[i].nodes, clusters[i].edges, options, false); + } + + if (refreshData === true) { + this.body.emitter.emit('_dataChanged'); } } }, { - key: "_drawBranch", + 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', /** - * 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"; + * 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]; + + // 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 (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); + 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; } - 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(); + var childNodesObj = {}; + var childEdgesObj = {}; + var parentNodeId = node.id; + var parentClonedOptions = this._cloneOptions(node); + childNodesObj[parentNodeId] = node; - ctx.beginPath(); - ctx.moveTo(branch.range.maxX, branch.range.maxY); - ctx.lineTo(branch.range.minX, branch.range.maxY); - ctx.stroke(); + // 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); - ctx.beginPath(); - ctx.moveTo(branch.range.minX, branch.range.maxY); - ctx.lineTo(branch.range.minX, branch.range.minY); - ctx.stroke(); + 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 (branch.mass > 0) { - ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass); - ctx.stroke(); - } - */ + this._cluster(childNodesObj, childEdgesObj, options, refreshData); } - }]); - - return BarnesHutSolver; - })(); + }, { + key: '_cloneOptions', - exports["default"] = BarnesHutSolver; - module.exports = exports["default"]; + /** + * 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', -/***/ }, -/* 92 */ -/***/ function(module, exports, __webpack_require__) { + /** + * 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; - "use strict"; + var childKeys = Object.keys(childNodesObj); + for (var i = 0; i < childKeys.length; i++) { + childNodeId = childKeys[i]; + childNode = childNodesObj[childNodeId]; - Object.defineProperty(exports, "__esModule", { - value: true - }); + // 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; - 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; }; })(); + // 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; + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + // 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', - var RepulsionSolver = (function () { - function RepulsionSolver(body, physicsBody, options) { - _classCallCheck(this, RepulsionSolver); + /** + * 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]; - this.body = body; - this.physicsBody = physicsBody; - this.setOptions(options); - } + if (options.clusterEdgeProperties === undefined) { + options.clusterEdgeProperties = {}; + } + if (options.clusterNodeProperties === undefined) { + options.clusterNodeProperties = {}; + } - _createClass(RepulsionSolver, [{ - key: "setOptions", - value: function setOptions(options) { - this.options = options; + return options; } }, { - key: "solve", + 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; - - var nodes = this.body.nodes; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var forces = this.physicsBody.forces; + * + * @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]; - // repulsing forces between nodes - var nodeDistance = this.options.nodeDistance; + // kill condition: no children so cant cluster + if (Object.keys(childNodesObj).length === 0) { + return; + } - // approximation constants - var a = -2 / 3 / nodeDistance; - var b = 4 / 3; + var clusterNodeProperties = util.deepExtend({}, options.clusterNodeProperties); - // 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]]; + // 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); + } - dx = node2.x - node1.x; - dy = node2.y - node1.y; - distance = Math.sqrt(dx * dx + dy * dy); + // get clusterproperties based on childNodes + var childEdgesOptions = []; + for (var edgeId in childEdgesObj) { + var clonedOptions = this._cloneOptions(childEdgesObj[edgeId], 'edge'); + childEdgesOptions.push(clonedOptions); + } - // same condition as BarnesHutSolver, making sure nodes are never 100% overlapping. - if (distance === 0) { - distance = 0.1 * Math.random(); - dx = distance; - } + clusterNodeProperties = options.processProperties(clusterNodeProperties, childNodesOptions, childEdgesOptions); + if (!clusterNodeProperties) { + throw new Error('The processProperties function does not return properties!'); + } + } - 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; + // check if we have an unique id; + if (clusterNodeProperties.id === undefined) { + clusterNodeProperties.id = 'cluster:' + util.randomUUID(); + } + var clusterId = clusterNodeProperties.id; - fx = dx * repulsingForce; - fy = dy * repulsingForce; + if (clusterNodeProperties.label === undefined) { + clusterNodeProperties.label = 'cluster'; + } - forces[node1.id].x -= fx; - forces[node1.id].y -= fy; - forces[node2.id].x += fx; - forces[node2.id].y += fy; - } + // 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; } - } - }]); - return RepulsionSolver; - })(); + // force the ID to remain the same + clusterNodeProperties.id = clusterId; - exports["default"] = RepulsionSolver; - module.exports = exports["default"]; + // 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; -/***/ }, -/* 93 */ -/***/ function(module, exports, __webpack_require__) { + // finally put the cluster node into global + this.body.nodes[clusterNodeProperties.id] = clusterNode; - "use strict"; + // create the new edges that will connect to the cluster + var newEdges = []; + this._createClusterEdges(childNodesObj, childEdgesObj, newEdges, clusterNodeProperties, options.clusterEdgeProperties); - Object.defineProperty(exports, "__esModule", { - value: true - }); + // 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; + } + } + } - 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; }; })(); + // 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; + } + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + // 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(); + } - var HierarchicalRepulsionSolver = (function () { - function HierarchicalRepulsionSolver(body, physicsBody, options) { - _classCallCheck(this, HierarchicalRepulsionSolver); + // set ID to undefined so no duplicates arise + clusterNodeProperties.id = undefined; - this.body = body; - this.physicsBody = physicsBody; - this.setOptions(options); - } + // wrap up + if (refreshData === true) { + this.body.emitter.emit('_dataChanged'); + } + } + }, { + key: 'isCluster', - _createClass(HierarchicalRepulsionSolver, [{ - key: "setOptions", - value: function setOptions(options) { - this.options = options; + /** + * 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: "solve", + key: '_getClusterPosition', /** - * 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; + * 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; + } - var nodes = this.body.nodes; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var forces = this.physicsBody.forces; + return { x: 0.5 * (minX + maxX), y: 0.5 * (minY + maxY) }; + } + }, { + key: 'openCluster', - // repulsing forces between nodes - var nodeDistance = this.options.nodeDistance; + /** + * 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, options) { + var refreshData = arguments[2] === undefined ? true : arguments[2]; - // 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]]; + // 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; - // 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); + // allow the user to position the nodes after release. + if (options !== undefined && options.releaseFunction !== undefined && typeof options.releaseFunction === 'function') { + var positions = {}; + var clusterPosition = { x: clusterNode.x, y: clusterNode.y }; + for (var nodeId in containedNodes) { + if (containedNodes.hasOwnProperty(nodeId)) { + var containedNode = this.body.nodes[nodeId]; + positions[nodeId] = { x: containedNode.x, y: containedNode.y }; + } + } + var newPositions = options.releaseFunction(clusterPosition, positions); - 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; + for (var nodeId in containedNodes) { + if (containedNodes.hasOwnProperty(nodeId)) { + var containedNode = this.body.nodes[nodeId]; + if (newPositions[nodeId] !== undefined) { + containedNode.x = newPositions[nodeId].x || clusterNode.x; + containedNode.y = newPositions[nodeId].y || clusterNode.y; } - 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; + } + } + } else { + // copy the position from the cluster + 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; } } } - } - }]); - - return HierarchicalRepulsionSolver; - })(); - - exports["default"] = HierarchicalRepulsionSolver; - 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; }; })(); + // release nodes + for (var nodeId in containedNodes) { + if (containedNodes.hasOwnProperty(nodeId)) { + var containedNode = this.body.nodes[nodeId]; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + // inherit speed + containedNode.vx = clusterNode.vx; + containedNode.vy = clusterNode.vy; - var SpringSolver = (function () { - function SpringSolver(body, physicsBody, options) { - _classCallCheck(this, SpringSolver); + containedNode.options.hidden = false; + containedNode.togglePhysics(true); - this.body = body; - this.physicsBody = physicsBody; - this.setOptions(options); - } + delete this.clusteredNodes[nodeId]; + } + } - _createClass(SpringSolver, [{ - key: "setOptions", - value: function setOptions(options) { - this.options = options; - } - }, { - key: "solve", + // 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; - /** - * 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; + if (this.clusteredNodes[edge.fromId] !== undefined) { + fromId = clusterId; + toId = edge.toId; + } else { + fromId = edge.fromId; + toId = clusterId; + } - // 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 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._calculateSpringForce(node1, node2, 0.5 * edgeLength); - this._calculateSpringForce(node2, node3, 0.5 * edgeLength); + this.body.edges[id] = newEdge; + this.body.edges[id].connect(); + } } 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); + edge.options.hidden = false; + edge.togglePhysics(true); } } } } - } - }, { - key: "_calculateSpringForce", - - /** - * 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; + // 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]; } - if (this.physicsBody.forces[node2.id] !== undefined) { - this.physicsBody.forces[node2.id].x -= fx; - this.physicsBody.forces[node2.id].y -= fy; + // remove clusterNode + delete this.body.nodes[clusterNodeId]; + + if (refreshData === true) { + this.body.emitter.emit('_dataChanged'); } } - }]); - - return SpringSolver; - })(); - - exports["default"] = SpringSolver; - 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; }; })(); - - 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); - } + }, { + 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); + } + } + } - _createClass(HierarchicalSpringSolver, [{ - key: "setOptions", - value: function setOptions(options) { - this.options = options; + return nodesArray; } }, { - key: "solve", + key: 'findNode', /** - * 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; - - var edgeIndices = this.physicsBody.physicsEdgeIndices; - var nodeIndices = this.physicsBody.physicsNodeIndices; - var forces = this.physicsBody.forces; + * 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; - // 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; + 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', - // 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; + /** + * 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', - fx = dx * springForce; - fy = dy * springForce; + /** + * 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; - if (edge.to.level != edge.from.level) { - if (forces[edge.toId] !== undefined) { - forces[edge.toId].springFx -= fx; - forces[edge.toId].springFy -= fy; - } - if (forces[edge.fromId] !== undefined) { - forces[edge.fromId].springFx += fx; - forces[edge.fromId].springFy += fy; - } - } else { - if (forces[edge.toId] !== undefined) { - forces[edge.toId].x -= factor * fx; - forces[edge.toId].y -= factor * fy; - } - if (forces[edge.fromId] !== undefined) { - forces[edge.fromId].x += factor * fx; - forces[edge.fromId].y += factor * fy; - } - } + 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; - // 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)); + var letiance = averageSquared - Math.pow(average, 2); + var standardDeviation = Math.sqrt(letiance); - forces[nodeId].x += springFx; - forces[nodeId].y += springFy; - } + var hubThreshold = Math.floor(average + 2 * standardDeviation); - // 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; + // always have at least one to cluster + if (hubThreshold > largestHub) { + hubThreshold = largestHub; } - 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; - } + return hubThreshold; } }]); - return HierarchicalSpringSolver; + return ClusterEngine; })(); - exports["default"] = HierarchicalSpringSolver; - module.exports = exports["default"]; + exports['default'] = ClusterEngine; + module.exports = exports['default']; /***/ }, -/* 96 */ +/* 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 _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 CentralGravitySolver = (function () { - function CentralGravitySolver(body, physicsBody, options) { - _classCallCheck(this, CentralGravitySolver); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - this.body = body; - this.physicsBody = physicsBody; - this.setOptions(options); - } + 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; } - _createClass(CentralGravitySolver, [{ - 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; + var _Node2 = __webpack_require__(63); - 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); + var _Node3 = _interopRequireDefault(_Node2); - 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; - } - }]); + var Cluster = (function (_Node) { + function Cluster(options, body, imagelist, grouplist, globalOptions) { + _classCallCheck(this, Cluster); - return CentralGravitySolver; - })(); + _get(Object.getPrototypeOf(Cluster.prototype), 'constructor', this).call(this, options, body, imagelist, grouplist, globalOptions); - exports["default"] = CentralGravitySolver; - module.exports = exports["default"]; + this.isCluster = true; + this.containedNodes = {}; + this.containedEdges = {}; + } + + _inherits(Cluster, _Node); + + return Cluster; + })(_Node3['default']); + + exports['default'] = Cluster; + module.exports = exports['default']; /***/ }, -/* 97 */ +/* 100 */ /***/ 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; }; })(); - 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 }; } + if (typeof window !== 'undefined') { + window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var util = __webpack_require__(13); - 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 CanvasRenderer = (function () { + function CanvasRenderer(body, canvas) { + _classCallCheck(this, CanvasRenderer); - var _BarnesHutSolver2 = __webpack_require__(91); + this.body = body; + this.canvas = canvas; - var _BarnesHutSolver3 = _interopRequireDefault(_BarnesHutSolver2); + this.redrawRequested = false; + this.renderTimer = undefined; + this.requiresTimeout = true; + this.renderingActive = false; + this.renderRequests = 0; + this.pixelRatio = undefined; + this.allowRedraw = true; - var ForceAtlas2BasedRepulsionSolver = (function (_BarnesHutSolver) { - function ForceAtlas2BasedRepulsionSolver(body, physicsBody, options) { - _classCallCheck(this, ForceAtlas2BasedRepulsionSolver); + this.dragging = false; + this.options = {}; + this.defaultOptions = { + hideEdgesOnDrag: false, + hideNodesOnDrag: false + }; + util.extend(this.options, this.defaultOptions); - _get(Object.getPrototypeOf(ForceAtlas2BasedRepulsionSolver.prototype), "constructor", this).call(this, body, physicsBody, options); + this._determineBrowserMethod(); + this.bindEventListeners(); } - _inherits(ForceAtlas2BasedRepulsionSolver, _BarnesHutSolver); + _createClass(CanvasRenderer, [{ + key: 'bindEventListeners', + value: function bindEventListeners() { + var _this = this; - _createClass(ForceAtlas2BasedRepulsionSolver, [{ - key: "_calculateForces", + 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('_blockRedraw', function () { + _this.allowRedraw = false; + }); + this.body.emitter.on('_allowRedraw', function () { + _this.allowRedraw = true;_this.redrawRequested = false; + }); + 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', /** - * Calculate the forces based on the distance. - * - * @param distance - * @param dx - * @param dy - * @param node - * @param parentBranch + * 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 _calculateForces(distance, dx, dy, node, parentBranch) { - if (distance === 0) { - distance = 0.1 * Math.random(); - dx = distance; - } + value: function _requestRedraw() { + var _this2 = this; - if (this.overlapAvoidanceFactor < 1) { - distance = Math.max(0.1 + this.overlapAvoidanceFactor * node.shape.radius, distance - node.shape.radius); + if (this.redrawRequested !== true && this.renderingActive === false && this.allowRedraw === true) { + this.redrawRequested = true; + if (this.requiresTimeout === true) { + window.setTimeout(function () { + _this2._redraw(false); + }, 0); + } else { + window.requestAnimationFrame(function () { + _this2._redraw(false); + }); + } } + } + }, { + key: '_redraw', + value: function _redraw() { + var hidden = arguments[0] === undefined ? false : arguments[0]; - 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; + if (this.allowRedraw === true) { + this.body.emitter.emit('initRedraw'); - this.physicsBody.forces[node.id].x += fx; - this.physicsBody.forces[node.id].y += fy; - } - }]); + this.redrawRequested = false; + var ctx = this.canvas.frame.canvas.getContext('2d'); - return ForceAtlas2BasedRepulsionSolver; - })(_BarnesHutSolver3["default"]); + // 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(); + } - exports["default"] = ForceAtlas2BasedRepulsionSolver; - module.exports = exports["default"]; + if (this.pixelRatio === undefined) { + this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + } -/***/ }, -/* 98 */ -/***/ function(module, exports, __webpack_require__) { + ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); - "use strict"; + // clear the canvas + var w = this.canvas.frame.canvas.clientWidth; + var h = this.canvas.frame.canvas.clientHeight; + ctx.clearRect(0, 0, w, h); - Object.defineProperty(exports, "__esModule", { - value: true - }); + // 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 _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.beginPath(); + this.body.emitter.emit('beforeDrawing', ctx); + ctx.closePath(); - 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 (hidden === false) { + if (this.dragging === false || this.dragging === true && this.options.hideEdgesOnDrag === false) { + this._drawEdges(ctx); + } + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + if (this.dragging === false || this.dragging === true && this.options.hideNodesOnDrag === false) { + this._drawNodes(ctx, hidden); + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + if (this.controlNodesActive === true) { + this._drawControlNodes(ctx); + } - 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; } + ctx.beginPath(); + //this.physics.nodesSolver._debug(ctx,"#F00F0F"); + this.body.emitter.emit('afterDrawing', ctx); + ctx.closePath(); + // restore original scaling and translation + ctx.restore(); - var _CentralGravitySolver2 = __webpack_require__(96); + if (hidden === true) { + ctx.clearRect(0, 0, w, h); + } + } + } + }, { + key: '_resizeNodes', - var _CentralGravitySolver3 = _interopRequireDefault(_CentralGravitySolver2); + /** + * 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 ForceAtlas2BasedCentralGravitySolver = (function (_CentralGravitySolver) { - function ForceAtlas2BasedCentralGravitySolver(body, physicsBody, options) { - _classCallCheck(this, ForceAtlas2BasedCentralGravitySolver); + var nodes = this.body.nodes; + var node = undefined; - _get(Object.getPrototypeOf(ForceAtlas2BasedCentralGravitySolver.prototype), "constructor", this).call(this, body, physicsBody, options); - } + // resize all nodes + for (var nodeId in nodes) { + if (nodes.hasOwnProperty(nodeId)) { + node = nodes[nodeId]; + node.resize(ctx); + node.updateBoundingBox(ctx); + } + } - _inherits(ForceAtlas2BasedCentralGravitySolver, _CentralGravitySolver); + // restore original scaling and translation + ctx.restore(); + } + }, { + key: '_drawNodes', - _createClass(ForceAtlas2BasedCentralGravitySolver, [{ - key: "_calculateForces", + /** + * 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); + } + } + } + + // draw the selected nodes on top + for (var i = 0; i < selected.length; i++) { + node = nodes[selected[i]]; + node.draw(ctx); + } + } + }, { + key: '_drawEdges', /** - * Calculate the forces based on the distance. + * 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, 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 _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', + + /** + * 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', + + /** + * 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 ForceAtlas2BasedCentralGravitySolver; - })(_CentralGravitySolver3["default"]); + return CanvasRenderer; + })(); - exports["default"] = ForceAtlas2BasedCentralGravitySolver; - module.exports = exports["default"]; + exports['default'] = CanvasRenderer; + module.exports = exports['default']; /***/ }, -/* 99 */ +/* 101 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -35025,751 +35489,779 @@ 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 _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__(100); - - var _componentsNodesCluster2 = _interopRequireDefault(_componentsNodesCluster); + var Hammer = __webpack_require__(7); + var hammerUtil = __webpack_require__(35); - var util = __webpack_require__(14); + var util = __webpack_require__(13); - var ClusterEngine = (function () { - function ClusterEngine(body) { - var _this = this; + /** + * 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 + */ - _classCallCheck(this, ClusterEngine); + var Canvas = (function () { + function Canvas(body) { + _classCallCheck(this, Canvas); this.body = body; - this.clusteredNodes = {}; + this.pixelRatio = 1; + this.resizeTimer = undefined; + this.resizeFunction = this._onResize.bind(this); this.options = {}; - this.defaultOptions = {}; + this.defaultOptions = { + autoResize: true, + height: '100%', + width: '100%' + }; util.extend(this.options, this.defaultOptions); - this.body.emitter.on('_resetData', function () { - _this.clusteredNodes = {}; - }); + this.bindEventListeners(); } - _createClass(ClusterEngine, [{ - key: 'setOptions', - value: function setOptions(options) { - if (options !== undefined) {} + _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: 'clusterByHubsize', + key: 'setOptions', + value: function setOptions(options) { + var _this2 = this; - /** - * - * @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(); + if (options !== undefined) { + var fields = ['width', 'height', 'autoResize']; + util.selectiveDeepExtend(fields, this.options, options); } - 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); - } + if (this.options.autoResize === true) { + // automatically adapt to a changing size of the browser. + this._cleanUp(); + this.resizeTimer = setInterval(function () { + var changed = _this2.setSize(); + if (changed === true) { + _this2.body.emitter.emit('_requestRedraw'); + } + }, 1000); + this.resizeFunction = this._onResize.bind(this); + util.addEventListener(window, 'resize', this.resizeFunction); } - - for (var i = 0; i < nodesToCluster.length; i++) { - this.clusterByConnection(nodesToCluster[i], options, false); + } + }, { + key: '_cleanUp', + value: function _cleanUp() { + // automatically adapt to a changing size of the browser. + if (this.resizeTimer !== undefined) { + clearInterval(this.resizeTimer); } - this.body.emitter.emit('_dataChanged'); + util.removeEventListener(window, 'resize', this.resizeFunction); + this.resizeFunction = undefined; } }, { - key: 'cluster', + 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', /** - * 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 (options.joinCondition === undefined) { - throw new Error('Cannot call clusterByNodeData without a joinCondition function in the options.'); + * 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 options object is fine, append if needed - options = this._checkOptions(options); + 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 - var childNodesObj = {}; - var childEdgesObj = {}; + ////////////////////////////////////////////////////////////////// - // 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]; + this.frame.canvas = document.createElement('canvas'); + this.frame.canvas.style.position = 'relative'; + this.frame.appendChild(this.frame.canvas); - // 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; - } - } + 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); } - this._cluster(childNodesObj, childEdgesObj, options, refreshData); + // 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: 'clusterOutliers', + key: '_bindHammer', /** - * 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]; + * This function binds hammer, it can be repeated over and over due to the uniqueness check. + * @private + */ + value: function _bindHammer() { + var _this3 = this; - options = this._checkOptions(options); - var clusters = []; + if (this.hammer !== undefined) { + this.hammer.destroy(); + } + this.drag = {}; + this.pinch = {}; - // 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]; - } - } + // 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: 5, direction: 30 }); // 30 is ALL_DIRECTIONS in hammer. - 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]; - } - } + 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); + }); - if (Object.keys(childNodesObj).length > 0 && Object.keys(childEdgesObj).length > 0) { - clusters.push({ nodes: childNodesObj, edges: childEdgesObj }); - } - } - } - } + // 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); + }); - for (var i = 0; i < clusters.length; i++) { - this._cluster(clusters[i].nodes, clusters[i].edges, options, false); - } + this.frame.canvas.addEventListener('mousemove', function (event) { + _this3.body.eventListeners.onMouseMove(event); + }); + this.frame.canvas.addEventListener('contextmenu', function (event) { + _this3.body.eventListeners.onContext(event); + }); - 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; + this.hammerFrame = new Hammer(this.frame); + hammerUtil.onRelease(this.hammerFrame, function (event) { + _this3.body.eventListeners.onRelease(event); + }); } }, { - key: 'clusterByConnection', + key: 'setSize', /** - * 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]; + * 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]; - // 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!'); - } + width = this._prepareValue(width); + height = this._prepareValue(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; - } + var emitEvent = false; + var oldWidth = this.frame.canvas.width; + var oldHeight = this.frame.canvas.height; - var childNodesObj = {}; - var childEdgesObj = {}; - var parentNodeId = node.id; - var parentClonedOptions = this._cloneOptions(node); - childNodesObj[parentNodeId] = node; + 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; - // 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); + this.frame.canvas.style.width = '100%'; + this.frame.canvas.style.height = '100%'; - 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.frame.canvas.width = Math.round(this.frame.canvas.clientWidth * this.pixelRatio); + this.frame.canvas.height = Math.round(this.frame.canvas.clientHeight * this.pixelRatio); - this._cluster(childNodesObj, childEdgesObj, options, refreshData); - } - }, { - key: '_cloneOptions', + this.options.width = width; + this.options.height = height; - /** - * 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; + emitEvent = true; } else { - util.deepExtend(clonedOptions, item.options, true); + // 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 != Math.round(this.frame.canvas.clientWidth * this.pixelRatio)) { + this.frame.canvas.width = Math.round(this.frame.canvas.clientWidth * this.pixelRatio); + emitEvent = true; + } + if (this.frame.canvas.height != Math.round(this.frame.canvas.clientHeight * this.pixelRatio)) { + this.frame.canvas.height = Math.round(this.frame.canvas.clientHeight * this.pixelRatio); + emitEvent = true; + } } - return clonedOptions; + + if (emitEvent === true) { + this.body.emitter.emit('resize', { + width: Math.round(this.frame.canvas.width / this.pixelRatio), + height: Math.round(this.frame.canvas.height / this.pixelRatio), + oldWidth: Math.round(oldWidth / this.pixelRatio), + oldHeight: Math.round(oldHeight / this.pixelRatio) + }); + } + + return emitEvent; } }, { - key: '_createClusterEdges', + key: '_XconvertDOMtoCanvas', /** - * 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)); - } - } - } + * 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: '_checkOptions', + key: '_XconvertCanvasToDOM', /** - * 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]; + * 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', - if (options.clusterEdgeProperties === undefined) { - options.clusterEdgeProperties = {}; - } - if (options.clusterNodeProperties === undefined) { - options.clusterNodeProperties = {}; - } + /** + * 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', - return options; + /** + * 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: '_cluster', + key: 'canvasToDOM', /** - * - * @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]; + * + * @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', - // kill condition: no children so cant cluster - if (Object.keys(childNodesObj).length === 0) { - return; - } + /** + * + * @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) }; + } + }]); - var clusterNodeProperties = util.deepExtend({}, options.clusterNodeProperties); + return Canvas; + })(); - // 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); - } + exports['default'] = Canvas; + module.exports = exports['default']; - // get clusterproperties based on childNodes - var childEdgesOptions = []; - for (var edgeId in childEdgesObj) { - var clonedOptions = this._cloneOptions(childEdgesObj[edgeId], 'edge'); - childEdgesOptions.push(clonedOptions); - } +/***/ }, +/* 102 */ +/***/ function(module, exports, __webpack_require__) { - clusterNodeProperties = options.processProperties(clusterNodeProperties, childNodesOptions, childEdgesOptions); - if (!clusterNodeProperties) { - throw new Error('The processProperties function does not return properties!'); - } - } + "use strict"; - // check if we have an unique id; - if (clusterNodeProperties.id === undefined) { - clusterNodeProperties.id = 'cluster:' + util.randomUUID(); - } - var clusterId = clusterNodeProperties.id; + Object.defineProperty(exports, "__esModule", { + value: true + }); - if (clusterNodeProperties.label === undefined) { - clusterNodeProperties.label = 'cluster'; - } + 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; }; })(); - // 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; - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - // force the ID to remain the same - clusterNodeProperties.id = clusterId; + var util = __webpack_require__(13); - // 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; + var View = (function () { + function View(body, canvas) { + var _this = this; - // finally put the cluster node into global - this.body.nodes[clusterNodeProperties.id] = clusterNode; + _classCallCheck(this, View); - // create the new edges that will connect to the cluster - var newEdges = []; - this._createClusterEdges(childNodesObj, childEdgesObj, newEdges, clusterNodeProperties, options.clusterEdgeProperties); + this.body = body; + this.canvas = canvas; - // 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.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; - // 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; - } - } + this.viewFunction = undefined; - // 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(); - } + 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)); + } - // set ID to undefined so no duplicates arise - clusterNodeProperties.id = undefined; + _createClass(View, [{ + key: "setOptions", + value: function setOptions() { + var options = arguments[0] === undefined ? {} : arguments[0]; - // wrap up - if (refreshData === true) { - this.body.emitter.emit('_dataChanged'); - } + this.options = options; } }, { - key: 'isCluster', + key: "_getRange", /** - * 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; + * Find the center position of the network + * @private + */ + 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; + } + 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 { - console.log('Node does not exist.'); - return false; + 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 (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: '_getClusterPosition', + key: "_findCenter", /** - * 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) }; + * @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: 'openCluster', + key: "fit", /** - * 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, options) { - var refreshData = arguments[2] === undefined ? true : arguments[2]; - - // 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; + * 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]; - // allow the user to position the nodes after release. - if (options !== undefined && options.releaseFunction !== undefined && typeof options.releaseFunction === 'function') { - var positions = {}; - var clusterPosition = { x: clusterNode.x, y: clusterNode.y }; - for (var nodeId in containedNodes) { - if (containedNodes.hasOwnProperty(nodeId)) { - var containedNode = this.body.nodes[nodeId]; - positions[nodeId] = { x: containedNode.x, y: containedNode.y }; - } - } - var newPositions = options.releaseFunction(clusterPosition, positions); + var range; + var zoomLevel; - for (var nodeId in containedNodes) { - if (containedNodes.hasOwnProperty(nodeId)) { - var containedNode = this.body.nodes[nodeId]; - if (newPositions[nodeId] !== undefined) { - containedNode.x = newPositions[nodeId].x || clusterNode.x; - containedNode.y = newPositions[nodeId].y || clusterNode.y; + 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; } } } - } else { - // copy the position from the cluster - 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 (positionDefined > 0.5 * this.body.nodeIndices.length) { + this.fit(options, false); + return; } - } - // release nodes - for (var nodeId in containedNodes) { - if (containedNodes.hasOwnProperty(nodeId)) { - var containedNode = this.body.nodes[nodeId]; + range = this._getRange(options.nodes); - // inherit speed - containedNode.vx = clusterNode.vx; - containedNode.vy = clusterNode.vy; + 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. - containedNode.options.hidden = false; - containedNode.togglePhysics(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); - delete this.clusteredNodes[nodeId]; - } + var xDistance = Math.abs(range.maxX - range.minX) * 1.1; + var yDistance = Math.abs(range.maxY - range.minY) * 1.1; + + var xZoomLevel = this.canvas.frame.canvas.clientWidth / xDistance; + var yZoomLevel = this.canvas.frame.canvas.clientHeight / yDistance; + + zoomLevel = xZoomLevel <= yZoomLevel ? xZoomLevel : yZoomLevel; } - // 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; + if (zoomLevel > 1) { + zoomLevel = 1; + } else if (zoomLevel === 0) { + zoomLevel = 1; + } - if (this.clusteredNodes[edge.fromId] !== undefined) { - fromId = clusterId; - toId = edge.toId; - } else { - fromId = edge.fromId; - toId = clusterId; - } + var center = this._findCenter(range); + var animationOptions = { position: center, scale: zoomLevel, animation: options.animation }; + this.moveTo(animationOptions); + } + }, { + key: "focus", - // 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); + // 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 + + this.animateView(options); + } + }, { + key: "animateView", - this.body.edges[id] = newEdge; - this.body.edges[id].connect(); - } - } else { - edge.options.hidden = false; - edge.togglePhysics(true); - } - } - } + /** + * + * @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; } - // 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]; + // 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. } - // remove clusterNode - delete this.body.nodes[clusterNodeId]; + this.sourceScale = this.body.view.scale; + this.sourceTranslation = this.body.view.translation; + this.targetScale = options.scale; - 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); - } + // 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); + } 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; - return nodesArray; + this.viewFunction = this._transitionRedraw.bind(this); + this.body.emitter.on("initRedraw", this.viewFunction); + this.body.emitter.emit("_startRendering"); + } } }, { - key: 'findNode', + key: "_lockedRedraw", /** - * 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; + * 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.canvas.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 + }; - 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; + this.body.view.translation = targetTranslation; } }, { - key: '_getConnectedId', - - /** - * 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: "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: '_getHubSize', + key: "_transitionRedraw", /** - * 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; + * + * @param easingTime + * @private + */ + value: function _transitionRedraw() { + var finished = arguments[0] === undefined ? false : arguments[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; - } - average = average / hubCounter; - averageSquared = averageSquared / hubCounter; + this.easingTime += this.animationSpeed; + this.easingTime = finished === true ? 1 : this.easingTime; - var letiance = averageSquared - Math.pow(average, 2); - var standardDeviation = Math.sqrt(letiance); + var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime); - var hubThreshold = Math.floor(average + 2 * standardDeviation); + 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 + }; - // always have at least one to cluster - if (hubThreshold > largestHub) { - hubThreshold = largestHub; + // 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"); } - - return hubThreshold; + } + }, { + 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 ClusterEngine; + return View; })(); - exports['default'] = ClusterEngine; - module.exports = exports['default']; + exports["default"] = View; + module.exports = exports["default"]; /***/ }, -/* 100 */ +/* 103 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -35778,2427 +36270,1948 @@ return /******/ (function(modules) { // webpackBootstrap value: 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); } } }; + 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'); } } - 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__(67); - - var _Node3 = _interopRequireDefault(_Node2); - - /** - * - */ - - var Cluster = (function (_Node) { - function Cluster(options, body, imagelist, grouplist, globalOptions) { - _classCallCheck(this, Cluster); - - _get(Object.getPrototypeOf(Cluster.prototype), 'constructor', this).call(this, options, body, imagelist, grouplist, globalOptions); - - this.isCluster = true; - this.containedNodes = {}; - this.containedEdges = {}; - } - - _inherits(Cluster, _Node); - - return Cluster; - })(_Node3['default']); - - exports['default'] = Cluster; - module.exports = exports['default']; - -/***/ }, -/* 101 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); + var _componentsNavigationHandler = __webpack_require__(104); - 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 _componentsNavigationHandler2 = _interopRequireDefault(_componentsNavigationHandler); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + var _componentsPopup = __webpack_require__(105); - if (typeof window !== 'undefined') { - window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; - } + var _componentsPopup2 = _interopRequireDefault(_componentsPopup); - var util = __webpack_require__(14); + var util = __webpack_require__(13); - var CanvasRenderer = (function () { - function CanvasRenderer(body, canvas) { - _classCallCheck(this, CanvasRenderer); + 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); - this.redrawRequested = false; - this.renderTimer = undefined; - this.requiresTimeout = true; - this.renderingActive = false; - this.renderRequests = 0; - this.pixelRatio = undefined; - this.allowRedraw = true; + // 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); - this.dragging = false; this.options = {}; this.defaultOptions = { - hideEdgesOnDrag: false, - hideNodesOnDrag: false + 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._determineBrowserMethod(); this.bindEventListeners(); } - _createClass(CanvasRenderer, [{ + _createClass(InteractionHandler, [{ 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('_blockRedraw', function () { - _this.allowRedraw = false; - }); - this.body.emitter.on('_allowRedraw', function () { - _this.allowRedraw = true;_this.redrawRequested = false; - }); - 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(); + clearTimeout(_this.popupTimer); + delete _this.body.functions.getPointer; }); } }, { key: 'setOptions', value: function setOptions(options) { if (options !== undefined) { - var fields = ['hideEdgesOnDrag', 'hideNodesOnDrag']; - util.selectiveDeepExtend(fields, this.options, options); + // extend all but the values in fields + var fields = ['hideEdgesOnDrag', 'hideNodesOnDrag', 'keyboard', 'multiselect', 'selectable', 'selectConnectedEdges']; + util.selectiveNotDeepExtend(fields, this.options, options); + + // merge the keyboard options in. + util.mergeOptions(this.options, options, 'keyboard'); + + if (options.tooltip) { + util.extend(this.options.tooltip, options.tooltip); + if (options.tooltip.color) { + this.options.tooltip.color = util.parseColor(options.tooltip.color); + } + } } + + this.navigationHandler.setOptions(this.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: '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) + }; + } + }, { + 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(); } } }, { - key: '_renderStep', - value: function _renderStep() { - if (this.renderingActive === true) { - // reset the renderTimer so a new scheduled animation step can be set - this.renderTimer = undefined; + key: 'onTap', - if (this.requiresTimeout === true) { - // this schedules a new simulation step - this._startRendering(); - } + /** + * 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', + + /** + * handle doubletap event + * @private + */ + value: function onDoubleTap(event) { + var pointer = this.getPointer(event.center); + this.selectionHandler._generateClickEvent('doubleClick', event, pointer); + } + }, { + key: 'onHold', + + /** + * handle long tap event: multi select nodes + * @private + */ + value: function onHold(event) { + var pointer = this.getPointer(event.center); + var multiselect = this.selectionHandler.options.multiselect; + + this.checkSelectionChanges(pointer, event, multiselect); + + this.selectionHandler._generateClickEvent('click', event, pointer); + this.selectionHandler._generateClickEvent('hold', event, pointer); + } + }, { + key: 'onRelease', + + /** + * 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', + + /** + * + * @param pointer + * @param add + */ + 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(); - this._redraw(); + var _determineIfDifferent2 = this._determineIfDifferent(previousSelection, currentSelection); - if (this.requiresTimeout === false) { - // this schedules a new simulation step - this._startRendering(); - } + var nodesChanges = _determineIfDifferent2.nodesChanges; + var edgesChanges = _determineIfDifferent2.edgesChanges; + + 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; } - } - }, { - key: 'redraw', - /** - * Redraw the network with the current data - * chart will be resized too. - */ - value: function redraw() { - this.body.emitter.emit('setSize'); - this._redraw(); + 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: '_requestRedraw', + key: '_determineIfDifferent', /** - * 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 function checks if the nodes and edges previously selected have changed. + * @param previousSelection + * @param currentSelection + * @returns {{nodesChanges: boolean, edgesChanges: boolean}} * @private */ - value: function _requestRedraw() { - var _this2 = this; + value: function _determineIfDifferent(previousSelection, currentSelection) { + var nodesChanges = false; + var edgesChanges = false; - if (this.redrawRequested !== true && this.renderingActive === false && this.allowRedraw === true) { - this.redrawRequested = true; - if (this.requiresTimeout === true) { - window.setTimeout(function () { - _this2._redraw(false); - }, 0); - } else { - window.requestAnimationFrame(function () { - _this2._redraw(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; + } + } + + return { nodesChanges: nodesChanges, edgesChanges: edgesChanges }; } }, { - key: '_redraw', - value: function _redraw() { - var hidden = arguments[0] === undefined ? false : arguments[0]; + key: 'onDragStart', - if (this.allowRedraw === true) { - this.body.emitter.emit('initRedraw'); + /** + * 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); + } - this.redrawRequested = false; - var ctx = this.canvas.frame.canvas.getContext('2d'); + // note: drag.pointer is set in onTouch to get the initial touch location + var node = this.selectionHandler.getNodeAt(this.drag.pointer); - // 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.drag.dragging = true; + this.drag.selection = []; + this.drag.translation = util.extend({}, this.body.view.translation); // copy the object + this.drag.nodeId = undefined; - if (this.pixelRatio === undefined) { - this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1); + 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); } - ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); + // after select to contain the node + this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer); - // clear the canvas - var w = this.canvas.frame.canvas.clientWidth; - var h = this.canvas.frame.canvas.clientHeight; - ctx.clearRect(0, 0, w, h); + 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, - // 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); + // 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 + }; - ctx.beginPath(); - this.body.emitter.emit('beforeDrawing', ctx); - ctx.closePath(); + object.options.fixed.x = true; + object.options.fixed.y = true; - if (hidden === false) { - if (this.dragging === false || this.dragging === true && this.options.hideEdgesOnDrag === false) { - this._drawEdges(ctx); + this.drag.selection.push(s); } } - - if (this.dragging === false || this.dragging === true && this.options.hideNodesOnDrag === false) { - this._drawNodes(ctx, hidden); - } - - if (this.controlNodesActive === true) { - this._drawControlNodes(ctx); - } - - 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); - } + } else { + // fallback if no node is selected and thus the view is dragged. + this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer, undefined, true); } } }, { - key: '_resizeNodes', + key: 'onDrag', /** - * Redraw all nodes - * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); - * @param {CanvasRenderingContext2D} ctx - * @param {Boolean} [alwaysShow] + * handle drag event * @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); + value: function onDrag(event) { + var _this2 = this; + + if (this.drag.pinched === true) { + return; } - 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; + // remove the focus on node if it is focussed on by the focusOnNode + this.body.emitter.emit('unlockNode'); - // resize all nodes - for (var nodeId in nodes) { - if (nodes.hasOwnProperty(nodeId)) { - node = nodes[nodeId]; - node.resize(ctx); - node.updateBoundingBox(ctx); - } - } + var pointer = this.getPointer(event.center); - // restore original scaling and translation - ctx.restore(); - } - }, { - key: '_drawNodes', + var selection = this.drag.selection; + if (selection && selection.length && this.options.dragNodes === true) { + (function () { + _this2.selectionHandler._generateClickEvent('dragging', event, pointer); - /** - * 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]; + // calculate delta's and new location + var deltaX = pointer.x - _this2.drag.pointer.x; + var deltaY = pointer.y - _this2.drag.pointer.y; - 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 }; + // 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); + } + }); - // 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); + // start the simulation of the physics + _this2.body.emitter.emit('startSimulation'); + })(); + } else { + // move the network + if (this.options.dragView === true) { + this.selectionHandler._generateClickEvent('dragging', event, pointer, undefined, 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; - // draw the selected nodes on top - for (var i = 0; i < selected.length; i++) { - node = nodes[selected[i]]; - node.draw(ctx); + this.body.view.translation = { x: this.drag.translation.x + diffX, y: this.drag.translation.y + diffY }; + this.body.emitter.emit('_redraw'); + } } } }, { - key: '_drawEdges', + key: 'onDragEnd', /** - * Redraw all edges - * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); - * @param {CanvasRenderingContext2D} ctx + * handle drag start event * @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); - } + 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.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center)); + this.body.emitter.emit('startSimulation'); + } else { + this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center), undefined, true); + this.body.emitter.emit('_requestRedraw'); } } }, { - key: '_drawControlNodes', + key: 'onPinch', /** - * Redraw all edges - * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); - * @param {CanvasRenderingContext2D} ctx + * Handle pinch event + * @param event * @private */ - value: function _drawControlNodes(ctx) { - var edges = this.body.edges; - var edgeIndices = this.body.edgeIndices; - var edge = undefined; + value: function onPinch(event) { + var pointer = this.getPointer(event.center); - for (var i = 0; i < edgeIndices.length; i++) { - edge = edges[edgeIndices[i]]; - edge._drawControlNodes(ctx); + this.drag.pinched = true; + if (this.pinch['scale'] === undefined) { + this.pinch.scale = 1; } + + // TODO: enabled moving while pinching? + var scale = this.pinch.scale * event.scale; + this.zoom(scale, pointer); } }, { - key: '_determineBrowserMethod', + key: 'zoom', /** - * Determine if the browser requires a setTimeout or a requestAnimationFrame. This was required because - * some implementations (safari and IE9) did not support requestAnimationFrame + * 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 _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; - } + value: function zoom(scale, pointer) { + if (this.options.zoomView === true) { + var scaleOld = this.body.view.scale; + if (scale < 0.00001) { + scale = 0.00001; } - } else { - this.requiresTimeout = true; - } - } - }]); - - return CanvasRenderer; - })(); - - exports['default'] = CanvasRenderer; - 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; }; })(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - var Hammer = __webpack_require__(10); - var hammerUtil = __webpack_require__(36); - - var util = __webpack_require__(14); - - /** - * 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 (scale > 10) { + scale = 10; } - if (obj.height !== 0) { - _this.body.view.translation.y = obj.height * 0.5; + + var preScaleDragPointer = undefined; + if (this.drag !== undefined) { + if (this.drag.dragging === true) { + preScaleDragPointer = this.canvas.DOMtoCanvas(this.drag.pointer); + } } - }); - 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.canvas.frame.canvas.clientHeight / 2 + var translation = this.body.view.translation; - if (options !== undefined) { - var fields = ['width', 'height', 'autoResize']; - util.selectiveDeepExtend(fields, this.options, options); - } + var scaleFrac = scale / scaleOld; + var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac; + var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac; - if (this.options.autoResize === true) { - // automatically adapt to a changing size of the browser. - this._cleanUp(); - this.resizeTimer = setInterval(function () { - var changed = _this2.setSize(); - if (changed === true) { - _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'; + 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 (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 }); } } - throw new Error('Could not use the value supplie for width or height:' + value); } }, { - key: '_create', + key: 'onMouseWheel', /** - * Create the HTML + * 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 _create() { - // remove all elements from the container element. - while (this.body.container.hasChildNodes()) { - this.body.container.removeChild(this.body.container.firstChild); + 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; } - 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 - - ////////////////////////////////////////////////////////////////// + // 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) { - this.frame.canvas = document.createElement('canvas'); - this.frame.canvas.style.position = 'relative'; - this.frame.appendChild(this.frame.canvas); + // calculate the new scale + var scale = this.body.view.scale; + var zoom = delta / 10; + if (delta < 0) { + zoom = zoom / (1 - zoom); + } + scale *= 1 + zoom; - 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); + // calculate the pointer location + var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); - this.frame.canvas.getContext('2d').setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0); + // apply the new scale + this.zoom(scale, pointer); } - // 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(); + // Prevent default actions caused by mouse wheel. + event.preventDefault(); } }, { - key: '_bindHammer', + key: 'onMouseMove', /** - * This function binds hammer, it can be repeated over and over due to the uniqueness check. + * Mouse move handler for checking whether the title moves over a node with a title. + * @param {Event} event * @private */ - value: function _bindHammer() { + value: function onMouseMove(event) { var _this3 = this; - if (this.hammer !== undefined) { - this.hammer.destroy(); - } - this.drag = {}; - this.pinch = {}; + var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); + var popupVisible = false; - // 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: 5, direction: 30 }); // 30 is ALL_DIRECTIONS in hammer. + // check if the previously selected node is still selected + if (this.popup !== undefined) { + if (this.popup.hidden === false) { + this._checkHidePopup(pointer); + } - 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); - }); + // 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(); + } + } - // 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); - }); + // 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(); + } - this.frame.canvas.addEventListener('mousemove', function (event) { - _this3.body.eventListeners.onMouseMove(event); - }); - this.frame.canvas.addEventListener('contextmenu', function (event) { - _this3.body.eventListeners.onContext(event); - }); + // 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); + } + } - this.hammerFrame = new Hammer(this.frame); - hammerUtil.onRelease(this.hammerFrame, function (event) { - _this3.body.eventListeners.onRelease(event); - }); + /** + * 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: 'setSize', + key: '_checkShowPopup', /** - * 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%') + * 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 setSize() { - var width = arguments[0] === undefined ? this.options.width : arguments[0]; - var height = arguments[1] === undefined ? this.options.height : arguments[1]; + 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 + }; - width = this._prepareValue(width); - height = this._prepareValue(height); + var previousPopupObjId = this.popupObj === undefined ? undefined : this.popupObj.id; + var nodeUnderCursor = false; + var popupType = 'node'; - var emitEvent = false; - var oldWidth = this.frame.canvas.width; - var oldHeight = this.frame.canvas.height; + // 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]); + } + } + } - 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; + 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.frame.canvas.style.width = '100%'; - this.frame.canvas.style.height = '100%'; + 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.frame.canvas.width = Math.round(this.frame.canvas.clientWidth * this.pixelRatio); - this.frame.canvas.height = Math.round(this.frame.canvas.clientHeight * this.pixelRatio); + if (overlappingEdges.length > 0) { + this.popupObj = edges[overlappingEdges[overlappingEdges.length - 1]]; + popupType = 'edge'; + } + } - this.options.width = width; - this.options.height = height; + 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); + } - emitEvent = true; - } else { - // this would adapt the width of the canvas to the width from 100% if and only if - // there is a change. + this.popup.popupTargetType = popupType; + this.popup.popupTargetId = this.popupObj.id; - if (this.frame.canvas.width != Math.round(this.frame.canvas.clientWidth * this.pixelRatio)) { - this.frame.canvas.width = Math.round(this.frame.canvas.clientWidth * this.pixelRatio); - emitEvent = true; + // 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); } - if (this.frame.canvas.height != Math.round(this.frame.canvas.clientHeight * this.pixelRatio)) { - this.frame.canvas.height = Math.round(this.frame.canvas.clientHeight * this.pixelRatio); - emitEvent = true; + } else { + if (this.popup !== undefined) { + this.popup.hide(); + this.body.emitter.emit('hidePopup'); } } - - if (emitEvent === true) { - this.body.emitter.emit('resize', { - width: Math.round(this.frame.canvas.width / this.pixelRatio), - height: Math.round(this.frame.canvas.height / this.pixelRatio), - oldWidth: Math.round(oldWidth / this.pixelRatio), - oldHeight: Math.round(oldHeight / this.pixelRatio) - }); - } - - return emitEvent; - } - }, { - 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', - - /** - * 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', + key: '_checkHidePopup', /** - * 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} + * 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 _YconvertDOMtoCanvas(y) { - return (y - this.body.view.translation.y) / this.body.view.scale; - } - }, { - key: '_YconvertCanvasToDOM', + value: function _checkHidePopup(pointer) { + var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); - /** - * 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', + 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); - /** - * - * @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 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); + } + } + } - /** - * - * @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) }; + if (stillOnObj === false) { + this.popupObj = undefined; + this.popup.hide(); + this.body.emitter.emit('hidePopup'); + } } }]); - return Canvas; + return InteractionHandler; })(); - exports['default'] = Canvas; + exports['default'] = InteractionHandler; module.exports = exports['default']; /***/ }, -/* 103 */ +/* 104 */ /***/ 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - var util = __webpack_require__(14); + var util = __webpack_require__(13); + var Hammer = __webpack_require__(7); + var hammerUtil = __webpack_require__(35); + var keycharm = __webpack_require__(48); - var View = (function () { - function View(body, canvas) { + var NavigationHandler = (function () { + function NavigationHandler(body, canvas) { var _this = this; - _classCallCheck(this, View); + _classCallCheck(this, NavigationHandler); this.body = body; 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.iconsCreated = false; + this.navigationHammers = []; + this.boundFunctions = {}; this.touchTime = 0; + this.activated = false; - 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('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.body.emitter.on("unlockNode", this.releaseNode.bind(this)); - } - - _createClass(View, [{ - key: "setOptions", - value: function setOptions() { - var options = arguments[0] === undefined ? {} : arguments[0]; - - this.options = options; - } - }, { - key: "_getRange", - - /** - * Find the center position of the network - * @private - */ - 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; - } - 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) { + this.options = {}; + } - 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 - } + _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(); } - 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.configureKeyboardBindings(); } }, { - key: "_findCenter", + 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 = []; + } - /** - * @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) }; + // clean up previous navigation items + if (this.navigationDOM && this.navigationDOM['wrapper'] && this.navigationDOM['wrapper'].parentNode) { + this.navigationDOM['wrapper'].parentNode.removeChild(this.navigationDOM['wrapper']); + } + + this.iconsCreated = false; } }, { - key: "fit", + key: 'loadNavigationElements', /** - * 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; + * 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 fit() { - var options = arguments[0] === undefined ? { nodes: [] } : arguments[0]; - var initialZoom = arguments[1] === undefined ? false : arguments[1]; + value: function loadNavigationElements() { + var _this2 = this; - var range; - var zoomLevel; + this.cleanNavigation(); - 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; - } + this.navigationDOM = {}; + var navigationDivs = ['up', 'down', 'left', 'right', 'zoomIn', 'zoomOut', 'zoomExtends']; + var navigationDivActions = ['_moveUp', '_moveDown', '_moveLeft', '_moveRight', '_zoomIn', '_zoomOut', '_fit']; - range = this._getRange(options.nodes); + this.navigationDOM['wrapper'] = document.createElement('div'); + this.navigationDOM['wrapper'].className = 'vis-navigation'; + this.canvas.frame.appendChild(this.navigationDOM['wrapper']); - 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. + 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]]); - // 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 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])); + } - var xDistance = Math.abs(range.maxX - range.minX) * 1.1; - var yDistance = Math.abs(range.maxY - range.minY) * 1.1; + this.navigationHammers.push(hammer); + } - var xZoomLevel = this.canvas.frame.canvas.clientWidth / xDistance; - var yZoomLevel = this.canvas.frame.canvas.clientHeight / yDistance; + // use a hammer for the release so we do not require the one used in the rest of the network + // the one the rest uses can be overloaded by the manipulation system. + var hammerFrame = new Hammer(this.canvas.frame); + hammerUtil.onRelease(hammerFrame, function () { + _this2._stopMovement(); + }); + this.navigationHammers.push(hammerFrame); - zoomLevel = xZoomLevel <= yZoomLevel ? xZoomLevel : yZoomLevel; + 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'); } - - if (zoomLevel > 1) { - zoomLevel = 1; - } else if (zoomLevel === 0) { - zoomLevel = 1; + } + }, { + 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]; } - - var center = this._findCenter(range); - var animationOptions = { position: center, scale: zoomLevel, animation: options.animation }; - this.moveTo(animationOptions); } }, { - key: "focus", - - // animation + key: '_fit', /** - * Center a node in view. + * this stops all movement induced by the navigation buttons * - * @param {Number} nodeId - * @param {Number} [options] + * @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 _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: "moveTo", + key: '_stopMovement', /** + * this stops all movement induced by the navigation buttons * - * @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 + * @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 _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'); + } } - 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); + this.boundFunctions = {}; } }, { - key: "animateView", + 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; + this.body.emitter.emit('zoom', { direction: '+', scale: this.body.view.scale }); + } + }, { + key: '_zoomOut', + value: function _zoomOut() { + this.body.view.scale /= 1 + this.options.keyboard.speed.zoom; + this.body.emitter.emit('zoom', { direction: '-', scale: this.body.view.scale }); + } + }, { + key: 'configureKeyboardBindings', /** - * - * @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 + * bind all keys using keycharm. */ - 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; - } + value: function configureKeyboardBindings() { + var _this3 = this; - // 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. + if (this.keycharm !== undefined) { + this.keycharm.destroy(); } - this.sourceScale = this.body.view.scale; - this.sourceTranslation = this.body.view.translation; - this.targetScale = options.scale; + 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 }); + } - // 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 }); + this.keycharm.reset(); - 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 (this.activated === true) { + this.keycharm.bind('up', function () { + _this3.bindToRedraw('_moveUp'); + }, 'keydown'); + this.keycharm.bind('down', function () { + _this3.bindToRedraw('_moveDown'); + }, 'keydown'); + this.keycharm.bind('left', function () { + _this3.bindToRedraw('_moveLeft'); + }, 'keydown'); + this.keycharm.bind('right', function () { + _this3.bindToRedraw('_moveRight'); + }, 'keydown'); + this.keycharm.bind('=', function () { + _this3.bindToRedraw('_zoomIn'); + }, 'keydown'); + this.keycharm.bind('num+', function () { + _this3.bindToRedraw('_zoomIn'); + }, 'keydown'); + this.keycharm.bind('num-', function () { + _this3.bindToRedraw('_zoomOut'); + }, 'keydown'); + this.keycharm.bind('-', function () { + _this3.bindToRedraw('_zoomOut'); + }, 'keydown'); + this.keycharm.bind('[', function () { + _this3.bindToRedraw('_zoomOut'); + }, 'keydown'); + this.keycharm.bind(']', function () { + _this3.bindToRedraw('_zoomIn'); + }, 'keydown'); + this.keycharm.bind('pageup', function () { + _this3.bindToRedraw('_zoomIn'); + }, 'keydown'); + this.keycharm.bind('pagedown', function () { + _this3.bindToRedraw('_zoomOut'); + }, 'keydown'); - // 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"); + this.keycharm.bind('up', function () { + _this3.unbindFromRedraw('_moveUp'); + }, 'keyup'); + this.keycharm.bind('down', function () { + _this3.unbindFromRedraw('_moveDown'); + }, 'keyup'); + this.keycharm.bind('left', function () { + _this3.unbindFromRedraw('_moveLeft'); + }, 'keyup'); + this.keycharm.bind('right', function () { + _this3.unbindFromRedraw('_moveRight'); + }, 'keyup'); + this.keycharm.bind('=', function () { + _this3.unbindFromRedraw('_zoomIn'); + }, 'keyup'); + this.keycharm.bind('num+', function () { + _this3.unbindFromRedraw('_zoomIn'); + }, 'keyup'); + this.keycharm.bind('num-', function () { + _this3.unbindFromRedraw('_zoomOut'); + }, 'keyup'); + this.keycharm.bind('-', function () { + _this3.unbindFromRedraw('_zoomOut'); + }, 'keyup'); + this.keycharm.bind('[', function () { + _this3.unbindFromRedraw('_zoomOut'); + }, 'keyup'); + this.keycharm.bind(']', function () { + _this3.unbindFromRedraw('_zoomIn'); + }, 'keyup'); + this.keycharm.bind('pageup', function () { + _this3.unbindFromRedraw('_zoomIn'); + }, 'keyup'); + this.keycharm.bind('pagedown', function () { + _this3.unbindFromRedraw('_zoomOut'); + }, 'keyup'); } - } 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"); } } - }, { - key: "_lockedRedraw", + }]); + + return NavigationHandler; + })(); + + exports['default'] = NavigationHandler; + module.exports = exports['default']; + +/***/ }, +/* 105 */ +/***/ 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', { + 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 Popup = (function () { + function Popup(container) { + _classCallCheck(this, Popup); + + this.container = container; + + this.x = 0; + this.y = 0; + this.padding = 5; + this.hidden = false; + + // create the frame + this.frame = document.createElement('div'); + this.frame.className = 'vis-network-tooltip'; + this.container.appendChild(this.frame); + } + + _createClass(Popup, [{ + key: 'setPosition', /** - * used to animate smoothly by hijacking the redraw function. - * @private + * @param {number} x Horizontal position of the popup window + * @param {number} y Vertical position of the popup window */ - value: function _lockedRedraw() { - var nodePosition = { x: this.body.nodes[this.lockedOnNodeId].x, y: this.body.nodes[this.lockedOnNodeId].y }; - var viewCenter = this.canvas.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.body.view.translation = targetTranslation; + value: function setPosition(x, y) { + this.x = parseInt(x); + this.y = parseInt(y); } }, { - 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: 'setText', + + /** + * 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 } } }, { - key: "_transitionRedraw", + key: 'show', /** - * - * @param easingTime - * @private + * Show the popup window + * @param {boolean} [doShow] Show or hide the window */ - value: function _transitionRedraw() { - var finished = arguments[0] === undefined ? false : arguments[0]; - - this.easingTime += this.animationSpeed; - this.easingTime = finished === true ? 1 : this.easingTime; + value: function show(doShow) { + if (doShow === undefined) { + doShow = true; + } - var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime); + 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; - 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 - }; + var top = this.y - height; + if (top + height + this.padding > maxHeight) { + top = maxHeight - height - this.padding; + } + if (top < this.padding) { + top = this.padding; + } - // 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); + var left = this.x; + if (left + width + this.padding > maxWidth) { + left = maxWidth - width - this.padding; } - this.body.emitter.emit("animationFinished"); + if (left < this.padding) { + left = this.padding; + } + + this.frame.style.left = left + 'px'; + this.frame.style.top = top + 'px'; + this.frame.style.visibility = 'visible'; + this.hidden = false; + } else { + this.hide(); } } }, { - 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 }); + key: 'hide', + + /** + * Hide the popup window + */ + value: function hide() { + this.hidden = true; + this.frame.style.visibility = 'hidden'; } }]); - return View; + return Popup; })(); - exports["default"] = View; - module.exports = exports["default"]; + exports['default'] = Popup; + module.exports = exports['default']; /***/ }, -/* 104 */ +/* 106 */ /***/ 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 _componentsNavigationHandler = __webpack_require__(105); - - var _componentsNavigationHandler2 = _interopRequireDefault(_componentsNavigationHandler); + 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 _componentsPopup = __webpack_require__(106); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var _componentsPopup2 = _interopRequireDefault(_componentsPopup); + var Node = __webpack_require__(63); + var Edge = __webpack_require__(83); + var util = __webpack_require__(13); - var util = __webpack_require__(14); + var SelectionHandler = (function () { + function SelectionHandler(body, canvas) { + var _this = this; - var InteractionHandler = (function () { - function InteractionHandler(body, canvas, selectionHandler) { - _classCallCheck(this, InteractionHandler); + _classCallCheck(this, SelectionHandler); 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); + this.selectionObj = { nodes: [], edges: [] }; + this.hoverObj = { nodes: {}, edges: {} }; 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 + multiselect: false, + selectable: true, + selectConnectedEdges: true, + hoverConnectedEdges: true }; util.extend(this.options, this.defaultOptions); - this.bindEventListeners(); + this.body.emitter.on("_dataChanged", function () { + _this.updateSelection(); + }); } - _createClass(InteractionHandler, [{ - key: 'bindEventListeners', - value: function bindEventListeners() { - var _this = this; - - this.body.emitter.on('destroy', function () { - clearTimeout(_this.popupTimer); - delete _this.body.functions.getPointer; - }); - } - }, { - key: 'setOptions', + _createClass(SelectionHandler, [{ + 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); - - // merge the keyboard options in. - util.mergeOptions(this.options, options, 'keyboard'); - - if (options.tooltip) { - util.extend(this.options.tooltip, options.tooltip); - if (options.tooltip.color) { - this.options.tooltip.color = util.parseColor(options.tooltip.color); - } - } - } - - this.navigationHandler.setOptions(this.options); - } - }, { - 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) - }; - } - }, { - 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(); + var fields = ["multiselect", "hoverConnectedEdges", "selectable", "selectConnectedEdges"]; + util.selectiveDeepExtend(fields, this.options, options); } } }, { - key: 'onTap', + key: "selectOnPoint", /** - * handle tap/click event: select/unselect a node + * handles the selection part of the tap; + * + * @param {Object} pointer * @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); + value: function selectOnPoint(pointer) { + var selected = false; + if (this.options.selectable === true) { + var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer); - this.checkSelectionChanges(pointer, event, multiselect); - this.selectionHandler._generateClickEvent('click', event, pointer); - } - }, { - key: 'onDoubleTap', + // unselect after getting the objects in order to restore width and height. + this.unselectAll(); - /** - * handle doubletap event - * @private - */ - value: function onDoubleTap(event) { - var pointer = this.getPointer(event.center); - this.selectionHandler._generateClickEvent('doubleClick', event, pointer); + if (obj !== undefined) { + selected = this.selectObject(obj); + } + this.body.emitter.emit("_requestRedraw"); + } + return selected; } }, { - key: 'onHold', - - /** - * handle long tap event: multi select nodes - * @private - */ - value: function onHold(event) { - var pointer = this.getPointer(event.center); - var multiselect = this.selectionHandler.options.multiselect; - - this.checkSelectionChanges(pointer, event, multiselect); + key: "selectAdditionalOnPoint", + value: function selectAdditionalOnPoint(pointer) { + var selectionChanged = false; + if (this.options.selectable === true) { + var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer); - this.selectionHandler._generateClickEvent('click', event, pointer); - this.selectionHandler._generateClickEvent('hold', event, pointer); - } - }, { - key: 'onRelease', + if (obj !== undefined) { + selectionChanged = true; + if (obj.isSelected() === true) { + this.deselectObject(obj); + } else { + this.selectObject(obj); + } - /** - * 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(); + this.body.emitter.emit("_requestRedraw"); + } } + return selectionChanged; } }, { - key: 'onContext', - value: function onContext(event) { - var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); - this.selectionHandler._generateClickEvent('oncontext', event, pointer); - } - }, { - key: 'checkSelectionChanges', - - /** - * - * @param pointer - * @param add - */ - value: function checkSelectionChanges(pointer, event) { - var add = arguments[2] === undefined ? false : arguments[2]; + key: "_generateClickEvent", + value: function _generateClickEvent(eventType, event, pointer, oldSelection) { + var emptySelection = arguments[4] === undefined ? false : arguments[4]; - 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); + var properties = undefined; + if (emptySelection === true) { + properties = { nodes: [], edges: [] }; } else { - selected = this.selectionHandler.selectOnPoint(pointer); + properties = this.getSelection(); } - var selectedEdgesCount = this.selectionHandler._getSelectedEdgeCount(); - var selectedNodesCount = this.selectionHandler._getSelectedNodeCount(); - var currentSelection = this.selectionHandler.getSelection(); - - var _determineIfDifferent2 = this._determineIfDifferent(previousSelection, currentSelection); - - var nodesChanges = _determineIfDifferent2.nodesChanges; - var edgesChanges = _determineIfDifferent2.edgesChanges; + properties["pointer"] = { + DOM: { x: pointer.x, y: pointer.y }, + canvas: this.canvas.DOMtoCanvas(pointer) + }; + properties["event"] = event; - 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 (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 (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 (obj !== undefined) { + if (obj instanceof Node) { + if (highlightEdges === true) { + this._selectConnectedEdges(obj); + } + } + obj.select(); + this._addToSelection(obj); + return true; } - - if (selected === true) { - // select or unselect - this.selectionHandler._generateClickEvent('select', event, pointer); + return false; + } + }, { + key: "deselectObject", + value: function deselectObject(obj) { + if (obj.isSelected() === true) { + obj.selected = false; + this._removeFromSelection(obj); } } }, { - key: '_determineIfDifferent', + key: "_getAllNodesOverlappingWith", /** - * This function checks if the nodes and edges previously selected have changed. - * @param previousSelection - * @param currentSelection - * @returns {{nodesChanges: boolean, edgesChanges: boolean}} + * 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 _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; + 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 { nodesChanges: nodesChanges, edgesChanges: edgesChanges }; + return overlappingNodes; } }, { - key: 'onDragStart', + key: "_pointerToPositionObject", /** - * This function is called by onDragStart. - * It is separated out because we can then overload it for the datamanipulation system. + * 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 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); - } - - // note: drag.pointer is set in onTouch to get the initial touch location - var node = this.selectionHandler.getNodeAt(this.drag.pointer); - - this.drag.dragging = true; - this.drag.selection = []; - this.drag.translation = util.extend({}, this.body.view.translation); // copy the object - this.drag.nodeId = undefined; - - 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); - } - - // after select to contain the node - this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer); - - 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; - - this.drag.selection.push(s); - } - } - } else { - // fallback if no node is selected and thus the view is dragged. - this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer, undefined, true); - } + 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: 'onDrag', + key: "getNodeAt", /** - * handle drag event + * 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 onDrag(event) { - var _this2 = this; - - if (this.drag.pinched === true) { - return; - } - - // remove the focus on node if it is focussed on by the focusOnNode - this.body.emitter.emit('unlockNode'); - - var pointer = this.getPointer(event.center); - - var selection = this.drag.selection; - if (selection && selection.length && this.options.dragNodes === true) { - (function () { - _this2.selectionHandler._generateClickEvent('dragging', event, pointer); - - // calculate delta's and new location - var deltaX = pointer.x - _this2.drag.pointer.x; - var deltaY = pointer.y - _this2.drag.pointer.y; - - // 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); - } - }); - - // start the simulation of the physics - _this2.body.emitter.emit('startSimulation'); - })(); - } else { - // move the network - if (this.options.dragView === true) { - this.selectionHandler._generateClickEvent('dragging', event, pointer, undefined, 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; + */ + value: function getNodeAt(pointer) { + var returnNode = arguments[1] === undefined ? true : arguments[1]; - this.body.view.translation = { x: this.drag.translation.x + diffX, y: this.drag.translation.y + diffY }; - this.body.emitter.emit('_redraw'); + // 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: 'onDragEnd', + key: "_getEdgesOverlappingWith", /** - * handle drag start event + * 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 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.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center)); - this.body.emitter.emit('startSimulation'); - } else { - this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center), undefined, true); - this.body.emitter.emit('_requestRedraw'); + 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: 'onPinch', + key: "_getAllEdgesOverlappingWith", /** - * Handle pinch event - * @param event + * 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 onPinch(event) { - var pointer = this.getPointer(event.center); - - this.drag.pinched = true; - if (this.pinch['scale'] === undefined) { - this.pinch.scale = 1; - } - - // TODO: enabled moving while pinching? - var scale = this.pinch.scale * event.scale; - this.zoom(scale, pointer); + value: function _getAllEdgesOverlappingWith(object) { + var overlappingEdges = []; + this._getEdgesOverlappingWith(object, overlappingEdges); + return overlappingEdges; } }, { - key: 'zoom', + key: "getEdgeAt", /** - * 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 + * 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 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 getEdgeAt(pointer) { + var returnEdge = arguments[1] === undefined ? true : arguments[1]; - this.body.emitter.emit('_requestRedraw'); + var positionObject = this._pointerToPositionObject(pointer); + var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject); - if (scaleOld < scale) { - this.body.emitter.emit('zoom', { direction: '+', scale: this.body.view.scale }); + if (overlappingEdges.length > 0) { + if (returnEdge === true) { + return this.body.edges[overlappingEdges[overlappingEdges.length - 1]]; } else { - this.body.emitter.emit('zoom', { direction: '-', scale: this.body.view.scale }); + return overlappingEdges[overlappingEdges.length - 1]; } + } else { + return undefined; } } }, { - key: 'onMouseWheel', + key: "_addToSelection", /** - * 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 + * Add object to the selection array. + * + * @param obj * @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; - } - - // 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) { - - // calculate the new scale - var scale = this.body.view.scale; - var zoom = delta / 10; - if (delta < 0) { - zoom = zoom / (1 - zoom); - } - scale *= 1 + zoom; - - // calculate the pointer location - var pointer = this.getPointer({ x: event.clientX, y: event.clientY }); - - // apply the new scale - this.zoom(scale, pointer); + value: function _addToSelection(obj) { + if (obj instanceof Node) { + this.selectionObj.nodes[obj.id] = obj; + } else { + this.selectionObj.edges[obj.id] = obj; } - - // Prevent default actions caused by mouse wheel. - event.preventDefault(); } }, { - key: 'onMouseMove', + key: "_addToHover", /** - * Mouse move handler for checking whether the title moves over a node with a title. - * @param {Event} event + * Add object to the selection array. + * + * @param obj * @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); - } - - // 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(); - } + value: function _addToHover(obj) { + if (obj instanceof Node) { + this.hoverObj.nodes[obj.id] = obj; + } else { + this.hoverObj.edges[obj.id] = obj; } + } + }, { + key: "_removeFromSelection", - // 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(); + /** + * 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", - // 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); + /** + * 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(); } } - - /** - * 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); + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + this.selectionObj.edges[edgeId].unselect(); } - this.selectionHandler.hoverObject(obj); } + + this.selectionObj = { nodes: {}, edges: {} }; } }, { - key: '_checkShowPopup', + key: "_getSelectedNodeCount", /** - * 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. + * return the number of selected nodes * - * @param {{x:Number, y:Number}} pointer + * @returns {number} * @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 - }; - - var previousPopupObjId = this.popupObj === undefined ? undefined : this.popupObj.id; - var nodeUnderCursor = false; - var popupType = 'node'; - - // 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]); - } - } - } - - 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; + 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", - 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]); - } - } - } - - if (overlappingEdges.length > 0) { - this.popupObj = edges[overlappingEdges[overlappingEdges.length - 1]]; - popupType = 'edge'; + /** + * 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", - 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.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'); + /** + * 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: '_checkHidePopup', + key: "_getSelectedEdgeCount", /** - * 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 + * return the number of selected edges + * + * @returns {number} * @private */ - value: function _checkHidePopup(pointer) { - var pointerObj = this.selectionHandler._pointerToPositionObject(pointer); - - 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); - - // 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); - } + value: function _getSelectedEdgeCount() { + var count = 0; + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + count += 1; } } - - if (stillOnObj === false) { - this.popupObj = undefined; - this.popup.hide(); - this.body.emitter.emit('hidePopup'); - } + return count; } - }]); - - return InteractionHandler; - })(); - - exports['default'] = InteractionHandler; - 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; }; })(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - var util = __webpack_require__(14); - var Hammer = __webpack_require__(10); - var hammerUtil = __webpack_require__(36); - var keycharm = __webpack_require__(49); - - var NavigationHandler = (function () { - function NavigationHandler(body, canvas) { - var _this = this; - - _classCallCheck(this, NavigationHandler); - - this.body = body; - this.canvas = canvas; - - this.iconsCreated = false; - this.navigationHammers = []; - this.boundFunctions = {}; - this.touchTime = 0; - this.activated = false; - - 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.options = {}; - } + }, { + key: "_getSelectedObjectCount", - _createClass(NavigationHandler, [{ - key: 'setOptions', - value: function setOptions(options) { - if (options !== undefined) { - this.options = options; - this.create(); + /** + * 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; + } } - } - }, { - key: 'create', - value: function create() { - if (this.options.navigationButtons === true) { - if (this.iconsCreated === false) { - this.loadNavigationElements(); + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + count += 1; } - } else if (this.iconsCreated === true) { - this.cleanNavigation(); } - - this.configureKeyboardBindings(); + return count; } }, { - 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(); + 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; } - this.navigationHammers = []; } - - // clean up previous navigation items - if (this.navigationDOM && this.navigationDOM['wrapper'] && this.navigationDOM['wrapper'].parentNode) { - this.navigationDOM['wrapper'].parentNode.removeChild(this.navigationDOM['wrapper']); + for (var edgeId in this.selectionObj.edges) { + if (this.selectionObj.edges.hasOwnProperty(edgeId)) { + return false; + } } - - this.iconsCreated = false; + return true; } }, { - key: 'loadNavigationElements', + key: "_clusterInSelection", /** - * 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. + * check if one of the selected nodes is a cluster. * + * @returns {boolean} * @private */ - value: function loadNavigationElements() { - var _this2 = this; - - 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])); + 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; + } } - - this.navigationHammers.push(hammer); } - - // use a hammer for the release so we do not require the one used in the rest of the network - // the one the rest uses can be overloaded by the manipulation system. - var hammerFrame = new Hammer(this.canvas.frame); - hammerUtil.onRelease(hammerFrame, function () { - _this2._stopMovement(); - }); - this.navigationHammers.push(hammerFrame); - - this.iconsCreated = true; + return false; } }, { - 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: "_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: '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: "_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: '_fit', + key: "_unselectConnectedEdges", /** - * this stops all movement induced by the navigation buttons + * unselect the edges connected to the node that is being selected * + * @param {Node} node * @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(); + value: function _unselectConnectedEdges(node) { + for (var i = 0; i < node.edges.length; i++) { + var edge = node.edges[i]; + edge.unselect(); + this._removeFromSelection(edge); } } }, { - key: '_stopMovement', + key: "blurObject", /** - * this stops all movement induced by the navigation buttons + * 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 _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'); + value: function blurObject(object) { + if (object.hover === true) { + object.hover = false; + if (object instanceof Node) { + this.body.emitter.emit("blurNode", { node: object.id }); + } else { + this.body.emitter.emit("blurEdge", { edge: object.id }); } } - 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; - } - }, { - 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; - this.body.emitter.emit('zoom', { direction: '+', scale: this.body.view.scale }); - } - }, { - key: '_zoomOut', - value: function _zoomOut() { - this.body.view.scale /= 1 + this.options.keyboard.speed.zoom; - this.body.emitter.emit('zoom', { direction: '-', scale: this.body.view.scale }); } }, { - key: 'configureKeyboardBindings', + key: "hoverObject", /** - * bind all keys using keycharm. + * 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 configureKeyboardBindings() { - var _this3 = this; + 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]; + } + } + } - if (this.keycharm !== undefined) { - this.keycharm.destroy(); + // 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 (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 }); + 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 }); + } else { + this.body.emitter.emit("hoverEdge", { edge: object.id }); + } + } + if (object instanceof Node && this.options.hoverConnectedEdges === true) { + this._hoverConnectedEdges(object); } + } - this.keycharm.reset(); + if (hoverChanged === true) { + this.body.emitter.emit("_requestRedraw"); + } + } + }, { + key: "getSelection", - if (this.activated === true) { - this.keycharm.bind('up', function () { - _this3.bindToRedraw('_moveUp'); - }, 'keydown'); - this.keycharm.bind('down', function () { - _this3.bindToRedraw('_moveDown'); - }, 'keydown'); - this.keycharm.bind('left', function () { - _this3.bindToRedraw('_moveLeft'); - }, 'keydown'); - this.keycharm.bind('right', function () { - _this3.bindToRedraw('_moveRight'); - }, 'keydown'); - this.keycharm.bind('=', function () { - _this3.bindToRedraw('_zoomIn'); - }, 'keydown'); - this.keycharm.bind('num+', function () { - _this3.bindToRedraw('_zoomIn'); - }, 'keydown'); - this.keycharm.bind('num-', function () { - _this3.bindToRedraw('_zoomOut'); - }, 'keydown'); - this.keycharm.bind('-', function () { - _this3.bindToRedraw('_zoomOut'); - }, 'keydown'); - this.keycharm.bind('[', function () { - _this3.bindToRedraw('_zoomOut'); - }, 'keydown'); - this.keycharm.bind(']', function () { - _this3.bindToRedraw('_zoomIn'); - }, 'keydown'); - this.keycharm.bind('pageup', function () { - _this3.bindToRedraw('_zoomIn'); - }, 'keydown'); - this.keycharm.bind('pagedown', function () { - _this3.bindToRedraw('_zoomOut'); - }, 'keydown'); + /** + * + * 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", - this.keycharm.bind('up', function () { - _this3.unbindFromRedraw('_moveUp'); - }, 'keyup'); - this.keycharm.bind('down', function () { - _this3.unbindFromRedraw('_moveDown'); - }, 'keyup'); - this.keycharm.bind('left', function () { - _this3.unbindFromRedraw('_moveLeft'); - }, 'keyup'); - this.keycharm.bind('right', function () { - _this3.unbindFromRedraw('_moveRight'); - }, 'keyup'); - this.keycharm.bind('=', function () { - _this3.unbindFromRedraw('_zoomIn'); - }, 'keyup'); - this.keycharm.bind('num+', function () { - _this3.unbindFromRedraw('_zoomIn'); - }, 'keyup'); - this.keycharm.bind('num-', function () { - _this3.unbindFromRedraw('_zoomOut'); - }, 'keyup'); - this.keycharm.bind('-', function () { - _this3.unbindFromRedraw('_zoomOut'); - }, 'keyup'); - this.keycharm.bind('[', function () { - _this3.unbindFromRedraw('_zoomOut'); - }, 'keyup'); - this.keycharm.bind(']', function () { - _this3.unbindFromRedraw('_zoomIn'); - }, 'keyup'); - this.keycharm.bind('pageup', function () { - _this3.unbindFromRedraw('_zoomIn'); - }, 'keyup'); - this.keycharm.bind('pagedown', function () { - _this3.unbindFromRedraw('_zoomOut'); - }, 'keyup'); + /** + * + * 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; } - }]); - - return NavigationHandler; - })(); - - exports['default'] = NavigationHandler; - module.exports = exports['default']; - -/***/ }, -/* 106 */ -/***/ 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', { - 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 Popup = (function () { - function Popup(container) { - _classCallCheck(this, Popup); - - this.container = container; - - this.x = 0; - this.y = 0; - this.padding = 5; - this.hidden = false; - - // create the frame - this.frame = document.createElement('div'); - this.frame.className = 'vis-network-tooltip'; - this.container.appendChild(this.frame); - } - - _createClass(Popup, [{ - key: 'setPosition', + }, { + key: "getSelectedEdges", /** - * @param {number} x Horizontal position of the popup window - * @param {number} y Vertical position of the popup window + * + * retrieve the currently selected edges + * @return {Array} selection An array with the ids of the + * selected nodes. */ - value: function setPosition(x, y) { - this.x = parseInt(x); - this.y = parseInt(y); + 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: 'setText', + key: "selectNodes", /** - * Set the content for the popup window. This can be HTML code or text. - * @param {string | Element} content + * 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 setText(content) { - if (content instanceof Element) { - this.frame.innerHTML = ''; - this.frame.appendChild(content); - } else { - this.frame.innerHTML = content; // string containing text or HTML + value: function selectNodes(selection) { + var highlightEdges = arguments[1] === undefined ? true : arguments[1]; + + var i = undefined, + id = undefined; + + if (!selection || selection.length === undefined) throw "Selection must be an array with ids"; + + // first unselect any selected node + this.unselectAll(); + + for (i = 0; i < selection.length; i++) { + id = selection[i]; + + 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: 'show', + key: "selectEdges", /** - * Show the popup window - * @param {boolean} [doShow] Show or hide the window + * select zero or more edges + * @param {Number[] | String[]} selection An array with the ids of the + * selected nodes. */ - value: function show(doShow) { - if (doShow === undefined) { - doShow = true; - } + value: function selectEdges(selection) { + var i = undefined, + id = undefined; - 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; + if (!selection || selection.length === undefined) throw "Selection must be an array with ids"; - var top = this.y - height; - if (top + height + this.padding > maxHeight) { - top = maxHeight - height - this.padding; - } - if (top < this.padding) { - top = this.padding; - } + // first unselect any selected objects + this.unselectAll(); - var left = this.x; - if (left + width + this.padding > maxWidth) { - left = maxWidth - width - this.padding; - } - if (left < this.padding) { - left = this.padding; - } + for (i = 0; i < selection.length; i++) { + id = selection[i]; - this.frame.style.left = left + 'px'; - this.frame.style.top = top + 'px'; - this.frame.style.visibility = 'visible'; - this.hidden = false; - } else { - this.hide(); + 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: 'hide', + key: "updateSelection", /** - * Hide the popup window + * Validate the selection: remove ids of nodes which no longer exist + * @private */ - value: function hide() { - this.hidden = true; - this.frame.style.visibility = 'hidden'; + 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 Popup; + return SelectionHandler; })(); - exports['default'] = Popup; - module.exports = exports['default']; + exports["default"] = SelectionHandler; + module.exports = exports["default"]; /***/ }, /* 107 */ @@ -38214,7 +38227,7 @@ 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__(14); + var util = __webpack_require__(13); var LayoutEngine = (function () { function LayoutEngine(body) { @@ -38722,9 +38735,9 @@ 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__(14); - var Hammer = __webpack_require__(10); - var hammerUtil = __webpack_require__(36); + var util = __webpack_require__(13); + var Hammer = __webpack_require__(7); + var hammerUtil = __webpack_require__(35); /** * clears the toolbar div element of children diff --git a/docs/network/index.html b/docs/network/index.html index 16616f84..ca7ade2e 100644 --- a/docs/network/index.html +++ b/docs/network/index.html @@ -834,7 +834,7 @@ function releaseFunction (clusterPosition, containedNodesPositions) { Start the physics simulation. This is normally done whenever needed and is only really useful if you stop the simulation yourself and wish to continue it afterwards. - . + stopSimulation() @@ -1059,7 +1059,18 @@ function releaseFunction (clusterPosition, containedNodesPositions) { Returns: none Programatically release the focussed node. - + + Methods to use with the configurator module. + + + getOptionsFromConfigurator() + + + Returns: Object + If you use the configurator, you can call this method to get an options object that contains all differences from the default options + caused by users interacting with the configurator. + +
diff --git a/lib/network/Network.js b/lib/network/Network.js index 001d5f01..01101024 100644 --- a/lib/network/Network.js +++ b/lib/network/Network.js @@ -485,5 +485,12 @@ Network.prototype.fit = function() {return this.view.fit.apply(t 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);}; +Network.prototype.getOptionsFromConfigurator = function() { + let options = {}; + if (this.configurator) { + options = this.configurator.getOptions.apply(this.configurator); + } + return options; +}; module.exports = Network; \ No newline at end of file diff --git a/lib/shared/Configurator.js b/lib/shared/Configurator.js index a2e6b43b..79676f9f 100644 --- a/lib/shared/Configurator.js +++ b/lib/shared/Configurator.js @@ -599,11 +599,16 @@ class Configurator { } _printOptions() { + let options = this.getOptions(); + this.optionsContainer.innerHTML = '
var options = ' + JSON.stringify(options, null, 2) + '
'; + } + + getOptions() { let 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) + '
'; + return options; } }