vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1101 lines
35 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
  1. var util = require('../../util');
  2. var DOMutil = require('../../DOMutil');
  3. var DataSet = require('../../DataSet');
  4. var DataView = require('../../DataView');
  5. var Component = require('./Component');
  6. var DataAxis = require('./DataAxis');
  7. var GraphGroup = require('./GraphGroup');
  8. var Legend = require('./Legend');
  9. var Bars = require('./graph2d_types/bar');
  10. var Lines = require('./graph2d_types/line');
  11. var Points = require('./graph2d_types/points');
  12. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  13. /**
  14. * This is the constructor of the LineGraph. It requires a Timeline body and options.
  15. *
  16. * @param body
  17. * @param options
  18. * @constructor
  19. */
  20. function LineGraph(body, options) {
  21. this.id = util.randomUUID();
  22. this.body = body;
  23. this.defaultOptions = {
  24. yAxisOrientation: 'left',
  25. defaultGroup: 'default',
  26. sort: true,
  27. sampling: true,
  28. stack: false,
  29. graphHeight: '400px',
  30. shaded: {
  31. enabled: false,
  32. orientation: 'bottom' // top, bottom, zero
  33. },
  34. style: 'line', // line, bar
  35. barChart: {
  36. width: 50,
  37. sideBySide: false,
  38. align: 'center' // left, center, right
  39. },
  40. interpolation: {
  41. enabled: true,
  42. parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
  43. alpha: 0.5
  44. },
  45. drawPoints: {
  46. enabled: true,
  47. size: 6,
  48. style: 'square' // square, circle
  49. },
  50. dataAxis: {}, //Defaults are done on DataAxis level
  51. legend: {}, //Defaults are done on Legend level
  52. groups: {
  53. visibility: {}
  54. }
  55. };
  56. // options is shared by this lineGraph and all its items
  57. this.options = util.extend({}, this.defaultOptions);
  58. this.dom = {};
  59. this.props = {};
  60. this.hammer = null;
  61. this.groups = {};
  62. this.abortedGraphUpdate = false;
  63. this.updateSVGheight = false;
  64. this.updateSVGheightOnResize = false;
  65. this.forceGraphUpdate = true;
  66. var me = this;
  67. this.itemsData = null; // DataSet
  68. this.groupsData = null; // DataSet
  69. // listeners for the DataSet of the items
  70. this.itemListeners = {
  71. 'add': function (event, params, senderId) {
  72. me._onAdd(params.items);
  73. },
  74. 'update': function (event, params, senderId) {
  75. me._onUpdate(params.items);
  76. },
  77. 'remove': function (event, params, senderId) {
  78. me._onRemove(params.items);
  79. }
  80. };
  81. // listeners for the DataSet of the groups
  82. this.groupListeners = {
  83. 'add': function (event, params, senderId) {
  84. me._onAddGroups(params.items);
  85. },
  86. 'update': function (event, params, senderId) {
  87. me._onUpdateGroups(params.items);
  88. },
  89. 'remove': function (event, params, senderId) {
  90. me._onRemoveGroups(params.items);
  91. }
  92. };
  93. this.items = {}; // object with an Item for every data item
  94. this.selection = []; // list with the ids of all selected nodes
  95. this.lastStart = this.body.range.start;
  96. this.touchParams = {}; // stores properties while dragging
  97. this.svgElements = {};
  98. this.setOptions(options);
  99. this.groupsUsingDefaultStyles = [0];
  100. this.body.emitter.on('rangechanged', function () {
  101. me.lastStart = me.body.range.start;
  102. me.svg.style.left = util.option.asSize(-me.props.width);
  103. me.forceGraphUpdate = true;
  104. //Is this local redraw necessary? (Core also does a change event!)
  105. me.redraw.call(me);
  106. });
  107. // create the HTML DOM
  108. this._create();
  109. this.framework = {svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups};
  110. }
  111. LineGraph.prototype = new Component();
  112. /**
  113. * Create the HTML DOM for the ItemSet
  114. */
  115. LineGraph.prototype._create = function () {
  116. var frame = document.createElement('div');
  117. frame.className = 'vis-line-graph';
  118. this.dom.frame = frame;
  119. // create svg element for graph drawing.
  120. this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  121. this.svg.style.position = 'relative';
  122. this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px';
  123. this.svg.style.display = 'block';
  124. frame.appendChild(this.svg);
  125. // data axis
  126. this.options.dataAxis.orientation = 'left';
  127. this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  128. this.options.dataAxis.orientation = 'right';
  129. this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  130. delete this.options.dataAxis.orientation;
  131. // legends
  132. this.legendLeft = new Legend(this.body, this.options.legend, 'left', this.options.groups);
  133. this.legendRight = new Legend(this.body, this.options.legend, 'right', this.options.groups);
  134. this.show();
  135. };
  136. /**
  137. * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element.
  138. * @param {object} options
  139. */
  140. LineGraph.prototype.setOptions = function (options) {
  141. if (options) {
  142. var fields = ['sampling', 'defaultGroup', 'stack', 'height', 'graphHeight', 'yAxisOrientation', 'style', 'barChart', 'dataAxis', 'sort', 'groups'];
  143. if (options.graphHeight === undefined && options.height !== undefined) {
  144. this.updateSVGheight = true;
  145. this.updateSVGheightOnResize = true;
  146. }
  147. else if (this.body.domProps.centerContainer.height !== undefined && options.graphHeight !== undefined) {
  148. if (parseInt((options.graphHeight + '').replace("px", '')) < this.body.domProps.centerContainer.height) {
  149. this.updateSVGheight = true;
  150. }
  151. }
  152. util.selectiveDeepExtend(fields, this.options, options);
  153. util.mergeOptions(this.options, options, 'interpolation');
  154. util.mergeOptions(this.options, options, 'drawPoints');
  155. util.mergeOptions(this.options, options, 'shaded');
  156. util.mergeOptions(this.options, options, 'legend');
  157. if (options.interpolation) {
  158. if (typeof options.interpolation == 'object') {
  159. if (options.interpolation.parametrization) {
  160. if (options.interpolation.parametrization == 'uniform') {
  161. this.options.interpolation.alpha = 0;
  162. }
  163. else if (options.interpolation.parametrization == 'chordal') {
  164. this.options.interpolation.alpha = 1.0;
  165. }
  166. else {
  167. this.options.interpolation.parametrization = 'centripetal';
  168. this.options.interpolation.alpha = 0.5;
  169. }
  170. }
  171. }
  172. }
  173. if (this.yAxisLeft) {
  174. if (options.dataAxis !== undefined) {
  175. this.yAxisLeft.setOptions(this.options.dataAxis);
  176. this.yAxisRight.setOptions(this.options.dataAxis);
  177. }
  178. }
  179. if (this.legendLeft) {
  180. if (options.legend !== undefined) {
  181. this.legendLeft.setOptions(this.options.legend);
  182. this.legendRight.setOptions(this.options.legend);
  183. }
  184. }
  185. if (this.groups.hasOwnProperty(UNGROUPED)) {
  186. this.groups[UNGROUPED].setOptions(options);
  187. }
  188. }
  189. // this is used to redraw the graph if the visibility of the groups is changed.
  190. if (this.dom.frame) { //not on initial run?
  191. this.forceGraphUpdate=true;
  192. this.body.emitter.emit("_change",{queue: true});
  193. }
  194. };
  195. /**
  196. * Hide the component from the DOM
  197. */
  198. LineGraph.prototype.hide = function () {
  199. // remove the frame containing the items
  200. if (this.dom.frame.parentNode) {
  201. this.dom.frame.parentNode.removeChild(this.dom.frame);
  202. }
  203. };
  204. /**
  205. * Show the component in the DOM (when not already visible).
  206. * @return {Boolean} changed
  207. */
  208. LineGraph.prototype.show = function () {
  209. // show frame containing the items
  210. if (!this.dom.frame.parentNode) {
  211. this.body.dom.center.appendChild(this.dom.frame);
  212. }
  213. };
  214. /**
  215. * Set items
  216. * @param {vis.DataSet | null} items
  217. */
  218. LineGraph.prototype.setItems = function (items) {
  219. var me = this,
  220. ids,
  221. oldItemsData = this.itemsData;
  222. // replace the dataset
  223. if (!items) {
  224. this.itemsData = null;
  225. }
  226. else if (items instanceof DataSet || items instanceof DataView) {
  227. this.itemsData = items;
  228. }
  229. else {
  230. throw new TypeError('Data must be an instance of DataSet or DataView');
  231. }
  232. if (oldItemsData) {
  233. // unsubscribe from old dataset
  234. util.forEach(this.itemListeners, function (callback, event) {
  235. oldItemsData.off(event, callback);
  236. });
  237. // remove all drawn items
  238. ids = oldItemsData.getIds();
  239. this._onRemove(ids);
  240. }
  241. if (this.itemsData) {
  242. // subscribe to new dataset
  243. var id = this.id;
  244. util.forEach(this.itemListeners, function (callback, event) {
  245. me.itemsData.on(event, callback, id);
  246. });
  247. // add all new items
  248. ids = this.itemsData.getIds();
  249. this._onAdd(ids);
  250. }
  251. };
  252. /**
  253. * Set groups
  254. * @param {vis.DataSet} groups
  255. */
  256. LineGraph.prototype.setGroups = function (groups) {
  257. var me = this;
  258. var ids;
  259. // unsubscribe from current dataset
  260. if (this.groupsData) {
  261. util.forEach(this.groupListeners, function (callback, event) {
  262. me.groupsData.off(event, callback);
  263. });
  264. // remove all drawn groups
  265. ids = this.groupsData.getIds();
  266. this.groupsData = null;
  267. for (var i = 0; i < ids.length; i++) {
  268. this._removeGroup(ids[i]);
  269. }
  270. }
  271. // replace the dataset
  272. if (!groups) {
  273. this.groupsData = null;
  274. }
  275. else if (groups instanceof DataSet || groups instanceof DataView) {
  276. this.groupsData = groups;
  277. }
  278. else {
  279. throw new TypeError('Data must be an instance of DataSet or DataView');
  280. }
  281. if (this.groupsData) {
  282. // subscribe to new dataset
  283. var id = this.id;
  284. util.forEach(this.groupListeners, function (callback, event) {
  285. me.groupsData.on(event, callback, id);
  286. });
  287. // draw all ms
  288. ids = this.groupsData.getIds();
  289. this._onAddGroups(ids);
  290. }
  291. };
  292. LineGraph.prototype._onUpdate = function (ids) {
  293. this._updateAllGroupData(ids);
  294. };
  295. LineGraph.prototype._onAdd = function (ids) {
  296. this._onUpdate(ids);
  297. };
  298. LineGraph.prototype._onRemove = function (ids) {
  299. this._onUpdate(ids);
  300. };
  301. LineGraph.prototype._onUpdateGroups = function (groupIds) {
  302. this._updateAllGroupData(null, groupIds);
  303. };
  304. LineGraph.prototype._onAddGroups = function (groupIds) {
  305. this._onUpdateGroups(groupIds);
  306. };
  307. /**
  308. * this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph
  309. * @param {Array} groupIds
  310. * @private
  311. */
  312. LineGraph.prototype._onRemoveGroups = function (groupIds) {
  313. for (var i = 0; i < groupIds.length; i++) {
  314. this._removeGroup(groupIds[i]);
  315. }
  316. this.forceGraphUpdate = true;
  317. this.body.emitter.emit("_change",{queue: true});
  318. };
  319. /**
  320. * this cleans the group out off the legends and the dataaxis
  321. * @param groupId
  322. * @private
  323. */
  324. LineGraph.prototype._removeGroup = function (groupId) {
  325. if (this.groups.hasOwnProperty(groupId)) {
  326. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  327. this.yAxisRight.removeGroup(groupId);
  328. this.legendRight.removeGroup(groupId);
  329. this.legendRight.redraw();
  330. }
  331. else {
  332. this.yAxisLeft.removeGroup(groupId);
  333. this.legendLeft.removeGroup(groupId);
  334. this.legendLeft.redraw();
  335. }
  336. delete this.groups[groupId];
  337. }
  338. }
  339. /**
  340. * update a group object with the group dataset entree
  341. *
  342. * @param group
  343. * @param groupId
  344. * @private
  345. */
  346. LineGraph.prototype._updateGroup = function (group, groupId) {
  347. if (!this.groups.hasOwnProperty(groupId)) {
  348. this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles);
  349. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  350. this.yAxisRight.addGroup(groupId, this.groups[groupId]);
  351. this.legendRight.addGroup(groupId, this.groups[groupId]);
  352. }
  353. else {
  354. this.yAxisLeft.addGroup(groupId, this.groups[groupId]);
  355. this.legendLeft.addGroup(groupId, this.groups[groupId]);
  356. }
  357. }
  358. else {
  359. this.groups[groupId].update(group);
  360. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  361. this.yAxisRight.updateGroup(groupId, this.groups[groupId]);
  362. this.legendRight.updateGroup(groupId, this.groups[groupId]);
  363. //If yAxisOrientation changed, clean out the group from the other axis.
  364. this.yAxisLeft.removeGroup(groupId);
  365. this.legendLeft.removeGroup(groupId);
  366. }
  367. else {
  368. this.yAxisLeft.updateGroup(groupId, this.groups[groupId]);
  369. this.legendLeft.updateGroup(groupId, this.groups[groupId]);
  370. //If yAxisOrientation changed, clean out the group from the other axis.
  371. this.yAxisRight.removeGroup(groupId);
  372. this.legendRight.removeGroup(groupId);
  373. }
  374. }
  375. this.legendLeft.redraw();
  376. this.legendRight.redraw();
  377. };
  378. /**
  379. * this updates all groups, it is used when there is an update the the itemset.
  380. *
  381. * @param {Array} ids
  382. * @param {Array} groupIds
  383. * @private
  384. */
  385. LineGraph.prototype._updateAllGroupData = function (ids, groupIds) {
  386. if (this.itemsData != null) {
  387. var groupsContent = {};
  388. var items = this.itemsData.get();
  389. var fieldId = this.itemsData._fieldId;
  390. var idMap = {};
  391. if (ids){
  392. ids.map(function (id) {
  393. idMap[id] = id;
  394. });
  395. }
  396. //pre-Determine array sizes, for more efficient memory claim
  397. var groupCounts = {};
  398. for (var i = 0; i < items.length; i++) {
  399. var item = items[i];
  400. var groupId = item.group;
  401. if (groupId === null || groupId === undefined) {
  402. groupId = UNGROUPED;
  403. }
  404. groupCounts.hasOwnProperty(groupId) ? groupCounts[groupId]++ : groupCounts[groupId] = 1;
  405. }
  406. //Pre-load arrays from existing groups if items are not changed (not in ids)
  407. if (!groupIds && ids) {
  408. for (var groupId in this.groups) {
  409. if (this.groups.hasOwnProperty(groupId)) {
  410. var group = this.groups[groupId];
  411. var existing_items = group.getItems();
  412. groupsContent[groupId] = existing_items.filter(function (item) {
  413. return (item[fieldId] !== idMap[item[fieldId]]);
  414. });
  415. var newLength = groupCounts[groupId];
  416. groupCounts[groupId] -= groupsContent[groupId].length;
  417. if (groupsContent[groupId].length < newLength) {
  418. groupsContent[groupId][newLength - 1] = {};
  419. }
  420. }
  421. }
  422. }
  423. //Now insert data into the arrays.
  424. for (var i = 0; i < items.length; i++) {
  425. var item = items[i];
  426. var groupId = item.group;
  427. if (groupId === null || groupId === undefined) {
  428. groupId = UNGROUPED;
  429. }
  430. if (!groupIds && ids && (item[fieldId] !== idMap[item[fieldId]])) {
  431. continue;
  432. }
  433. if (!groupsContent.hasOwnProperty(groupId)) {
  434. groupsContent[groupId] = new Array(groupCounts[groupId]);
  435. }
  436. //Copy data (because of unmodifiable DataView input.
  437. var extended = util.bridgeObject(item);
  438. extended.x = util.convert(item.x, 'Date');
  439. extended.end = util.convert(item.end, 'Date');
  440. extended.orginalY = item.y; //real Y
  441. extended.y = Number(item.y);
  442. extended[fieldId] = item[fieldId];
  443. var index= groupsContent[groupId].length - groupCounts[groupId]--;
  444. groupsContent[groupId][index] = extended;
  445. }
  446. //Make sure all groups are present, to allow removal of old groups
  447. for (var groupId in this.groups){
  448. if (this.groups.hasOwnProperty(groupId)){
  449. if (!groupsContent.hasOwnProperty(groupId)) {
  450. groupsContent[groupId] = new Array(0);
  451. }
  452. }
  453. }
  454. //Update legendas, style and axis
  455. for (var groupId in groupsContent) {
  456. if (groupsContent.hasOwnProperty(groupId)) {
  457. if (groupsContent[groupId].length == 0) {
  458. if (this.groups.hasOwnProperty(groupId)) {
  459. this._removeGroup(groupId);
  460. }
  461. } else {
  462. var group = undefined;
  463. if (this.groupsData != undefined) {
  464. group = this.groupsData.get(groupId);
  465. }
  466. if (group == undefined) {
  467. group = {id: groupId, content: this.options.defaultGroup + groupId};
  468. }
  469. this._updateGroup(group, groupId);
  470. this.groups[groupId].setItems(groupsContent[groupId]);
  471. }
  472. }
  473. }
  474. this.forceGraphUpdate = true;
  475. this.body.emitter.emit("_change",{queue: true});
  476. }
  477. };
  478. /**
  479. * Redraw the component, mandatory function
  480. * @return {boolean} Returns true if the component is resized
  481. */
  482. LineGraph.prototype.redraw = function () {
  483. var resized = false;
  484. // calculate actual size and position
  485. this.props.width = this.dom.frame.offsetWidth;
  486. this.props.height = this.body.domProps.centerContainer.height
  487. - this.body.domProps.border.top
  488. - this.body.domProps.border.bottom;
  489. // check if this component is resized
  490. resized = this._isResized() || resized;
  491. // check whether zoomed (in that case we need to re-stack everything)
  492. var visibleInterval = this.body.range.end - this.body.range.start;
  493. var zoomed = (visibleInterval != this.lastVisibleInterval);
  494. this.lastVisibleInterval = visibleInterval;
  495. // the svg element is three times as big as the width, this allows for fully dragging left and right
  496. // without reloading the graph. the controls for this are bound to events in the constructor
  497. if (resized == true) {
  498. this.svg.style.width = util.option.asSize(3 * this.props.width);
  499. this.svg.style.left = util.option.asSize(-this.props.width);
  500. // if the height of the graph is set as proportional, change the height of the svg
  501. if ((this.options.height + '').indexOf("%") != -1 || this.updateSVGheightOnResize == true) {
  502. this.updateSVGheight = true;
  503. }
  504. }
  505. // update the height of the graph on each redraw of the graph.
  506. if (this.updateSVGheight == true) {
  507. if (this.options.graphHeight != this.props.height + 'px') {
  508. this.options.graphHeight = this.props.height + 'px';
  509. this.svg.style.height = this.props.height + 'px';
  510. }
  511. this.updateSVGheight = false;
  512. }
  513. else {
  514. this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px';
  515. }
  516. // zoomed is here to ensure that animations are shown correctly.
  517. if (resized == true || zoomed == true || this.abortedGraphUpdate == true || this.forceGraphUpdate == true) {
  518. resized = this._updateGraph() || resized;
  519. this.forceGraphUpdate = false;
  520. }
  521. else {
  522. // move the whole svg while dragging
  523. if (this.lastStart != 0) {
  524. var offset = this.body.range.start - this.lastStart;
  525. var range = this.body.range.end - this.body.range.start;
  526. if (this.props.width != 0) {
  527. var rangePerPixelInv = this.props.width / range;
  528. var xOffset = offset * rangePerPixelInv;
  529. this.svg.style.left = (-this.props.width - xOffset) + 'px';
  530. }
  531. }
  532. }
  533. this.legendLeft.redraw();
  534. this.legendRight.redraw();
  535. return resized;
  536. };
  537. LineGraph.prototype._getSortedGroupIds = function(){
  538. // getting group Ids
  539. var grouplist = [];
  540. for (var groupId in this.groups) {
  541. if (this.groups.hasOwnProperty(groupId)) {
  542. var group = this.groups[groupId];
  543. if (group.visible == true && (this.options.groups.visibility[groupId] === undefined || this.options.groups.visibility[groupId] == true)) {
  544. grouplist.push({id:groupId,zIndex:group.options.zIndex});
  545. }
  546. }
  547. }
  548. util.insertSort(grouplist,function(a,b){
  549. var az = a.zIndex;
  550. var bz = b.zIndex;
  551. if (az === undefined) az=0;
  552. if (bz === undefined) bz=0;
  553. return az==bz? 0: (az<bz ? -1: 1);
  554. });
  555. var groupIds = new Array(grouplist.length);
  556. for (var i=0; i< grouplist.length; i++){
  557. groupIds[i] = grouplist[i].id;
  558. }
  559. return groupIds;
  560. }
  561. /**
  562. * Update and redraw the graph.
  563. *
  564. */
  565. LineGraph.prototype._updateGraph = function () {
  566. // reset the svg elements
  567. DOMutil.prepareElements(this.svgElements);
  568. if (this.props.width != 0 && this.itemsData != null) {
  569. var group, i;
  570. var groupRanges = {};
  571. var changeCalled = false;
  572. // this is the range of the SVG canvas
  573. var minDate = this.body.util.toGlobalTime(-this.body.domProps.root.width);
  574. var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width);
  575. // getting group Ids
  576. var groupIds = this._getSortedGroupIds();
  577. if (groupIds.length > 0) {
  578. var groupsData = {};
  579. // fill groups data, this only loads the data we require based on the timewindow
  580. this._getRelevantData(groupIds, groupsData, minDate, maxDate);
  581. // apply sampling, if disabled, it will pass through this function.
  582. this._applySampling(groupIds, groupsData);
  583. // we transform the X coordinates to detect collisions
  584. for (i = 0; i < groupIds.length; i++) {
  585. this._convertXcoordinates(groupsData[groupIds[i]]);
  586. }
  587. // now all needed data has been collected we start the processing.
  588. this._getYRanges(groupIds, groupsData, groupRanges);
  589. // update the Y axis first, we use this data to draw at the correct Y points
  590. changeCalled = this._updateYAxis(groupIds, groupRanges);
  591. // at changeCalled, abort this update cycle as the graph needs another update with new Width input from the Redraw container.
  592. // Cleanup SVG elements on abort.
  593. if (changeCalled == true) {
  594. DOMutil.cleanupElements(this.svgElements);
  595. this.abortedGraphUpdate = true;
  596. return true;
  597. }
  598. this.abortedGraphUpdate = false;
  599. // With the yAxis scaled correctly, use this to get the Y values of the points.
  600. var below = undefined;
  601. for (i = 0; i < groupIds.length; i++) {
  602. group = this.groups[groupIds[i]];
  603. if (this.options.stack === true && this.options.style === 'line') {
  604. if (group.options.excludeFromStacking == undefined || !group.options.excludeFromStacking) {
  605. if (below != undefined) {
  606. this._stack(groupsData[group.id], groupsData[below.id]);
  607. if (group.options.shaded.enabled == true && group.options.shaded.orientation !== "group"){
  608. if (group.options.shaded.orientation == "top" && below.options.shaded.orientation !== "group"){
  609. below.options.shaded.orientation="group";
  610. below.options.shaded.groupId=group.id;
  611. } else {
  612. group.options.shaded.orientation="group";
  613. group.options.shaded.groupId=below.id;
  614. }
  615. }
  616. }
  617. below = group;
  618. }
  619. }
  620. this._convertYcoordinates(groupsData[groupIds[i]], group);
  621. }
  622. //Precalculate paths and draw shading if appropriate. This will make sure the shading is always behind any lines.
  623. var paths = {};
  624. for (i = 0; i < groupIds.length; i++) {
  625. group = this.groups[groupIds[i]];
  626. if (group.options.style === 'line' && group.options.shaded.enabled == true) {
  627. var dataset = groupsData[groupIds[i]];
  628. if (dataset == null || dataset.length == 0) {
  629. continue;
  630. }
  631. if (!paths.hasOwnProperty(groupIds[i])) {
  632. paths[groupIds[i]] = Lines.calcPath(dataset, group);
  633. }
  634. if (group.options.shaded.orientation === "group") {
  635. var subGroupId = group.options.shaded.groupId;
  636. if (groupIds.indexOf(subGroupId) === -1) {
  637. console.log(group.id + ": Unknown shading group target given:" + subGroupId);
  638. continue;
  639. }
  640. if (!paths.hasOwnProperty(subGroupId)) {
  641. paths[subGroupId] = Lines.calcPath(groupsData[subGroupId], this.groups[subGroupId]);
  642. }
  643. Lines.drawShading(paths[groupIds[i]], group, paths[subGroupId], this.framework);
  644. }
  645. else {
  646. Lines.drawShading(paths[groupIds[i]], group, undefined, this.framework);
  647. }
  648. }
  649. }
  650. // draw the groups, calculating paths if still necessary.
  651. Bars.draw(groupIds, groupsData, this.framework);
  652. for (i = 0; i < groupIds.length; i++) {
  653. group = this.groups[groupIds[i]];
  654. if (groupsData[groupIds[i]].length > 0) {
  655. switch (group.options.style) {
  656. case "line":
  657. if (!paths.hasOwnProperty(groupIds[i])) {
  658. paths[groupIds[i]] = Lines.calcPath(groupsData[groupIds[i]], group);
  659. }
  660. Lines.draw(paths[groupIds[i]], group, this.framework);
  661. //explicit no break;
  662. case "point":
  663. //explicit no break;
  664. case "points":
  665. if (group.options.style == "point" || group.options.style == "points" || group.options.drawPoints.enabled == true) {
  666. Points.draw(groupsData[groupIds[i]], group, this.framework);
  667. }
  668. break;
  669. case "bar":
  670. // bar needs to be drawn enmasse
  671. //explicit no break
  672. default:
  673. //do nothing...
  674. }
  675. }
  676. }
  677. }
  678. }
  679. // cleanup unused svg elements
  680. DOMutil.cleanupElements(this.svgElements);
  681. return false;
  682. };
  683. LineGraph.prototype._stack = function (data, subData) {
  684. var index, dx, dy, subPrevPoint, subNextPoint;
  685. index = 0;
  686. // for each data point we look for a matching on in the set below
  687. for (var j = 0; j < data.length; j++) {
  688. subPrevPoint = undefined;
  689. subNextPoint = undefined;
  690. // we look for time matches or a before-after point
  691. for (var k = index; k < subData.length; k++) {
  692. // if times match exactly
  693. if (subData[k].x === data[j].x) {
  694. subPrevPoint = subData[k];
  695. subNextPoint = subData[k];
  696. index = k;
  697. break;
  698. }
  699. else if (subData[k].x > data[j].x) { // overshoot
  700. subNextPoint = subData[k];
  701. if (k == 0) {
  702. subPrevPoint = subNextPoint;
  703. }
  704. else {
  705. subPrevPoint = subData[k - 1];
  706. }
  707. index = k;
  708. break;
  709. }
  710. }
  711. // in case the last data point has been used, we assume it stays like this.
  712. if (subNextPoint === undefined) {
  713. subPrevPoint = subData[subData.length - 1];
  714. subNextPoint = subData[subData.length - 1];
  715. }
  716. // linear interpolation
  717. dx = subNextPoint.x - subPrevPoint.x;
  718. dy = subNextPoint.y - subPrevPoint.y;
  719. if (dx == 0) {
  720. data[j].y = data[j].orginalY + subNextPoint.y;
  721. }
  722. else {
  723. data[j].y = data[j].orginalY + (dy / dx) * (data[j].x - subPrevPoint.x) + subPrevPoint.y; // ax + b where b is data[j].y
  724. }
  725. }
  726. }
  727. /**
  728. * first select and preprocess the data from the datasets.
  729. * the groups have their preselection of data, we now loop over this data to see
  730. * what data we need to draw. Sorted data is much faster.
  731. * more optimization is possible by doing the sampling before and using the binary search
  732. * to find the end date to determine the increment.
  733. *
  734. * @param {array} groupIds
  735. * @param {object} groupsData
  736. * @param {date} minDate
  737. * @param {date} maxDate
  738. * @private
  739. */
  740. LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) {
  741. var group, i, j, item;
  742. if (groupIds.length > 0) {
  743. for (i = 0; i < groupIds.length; i++) {
  744. group = this.groups[groupIds[i]];
  745. var itemsData = group.getItems();
  746. // optimization for sorted data
  747. if (group.options.sort == true) {
  748. var dateComparator = function (a, b) {
  749. return a.getTime() == b.getTime() ? 0 : a < b ? -1 : 1
  750. };
  751. var first = Math.max(0, util.binarySearchValue(itemsData, minDate, 'x', 'before', dateComparator));
  752. var last = Math.min(itemsData.length, util.binarySearchValue(itemsData, maxDate, 'x', 'after', dateComparator) + 1);
  753. if (last <= 0) {
  754. last = itemsData.length;
  755. }
  756. var dataContainer = new Array(last-first);
  757. for (j = first; j < last; j++) {
  758. item = group.itemsData[j];
  759. dataContainer[j-first] = item;
  760. }
  761. groupsData[groupIds[i]] = dataContainer;
  762. }
  763. else {
  764. // If unsorted data, all data is relevant, just returning entire structure
  765. groupsData[groupIds[i]] = group.itemsData;
  766. }
  767. }
  768. }
  769. };
  770. /**
  771. *
  772. * @param groupIds
  773. * @param groupsData
  774. * @private
  775. */
  776. LineGraph.prototype._applySampling = function (groupIds, groupsData) {
  777. var group;
  778. if (groupIds.length > 0) {
  779. for (var i = 0; i < groupIds.length; i++) {
  780. group = this.groups[groupIds[i]];
  781. if (group.options.sampling == true) {
  782. var dataContainer = groupsData[groupIds[i]];
  783. if (dataContainer.length > 0) {
  784. var increment = 1;
  785. var amountOfPoints = dataContainer.length;
  786. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  787. // of width changing of the yAxis.
  788. //TODO: This assumes sorted data, but that's not guaranteed!
  789. var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x);
  790. var pointsPerPixel = amountOfPoints / xDistance;
  791. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel)));
  792. var sampledData = new Array(amountOfPoints);
  793. for (var j = 0; j < amountOfPoints; j += increment) {
  794. var idx = Math.round(j/increment);
  795. sampledData[idx]=dataContainer[j];
  796. }
  797. groupsData[groupIds[i]] = sampledData.splice(0,Math.round(amountOfPoints/increment));
  798. }
  799. }
  800. }
  801. }
  802. };
  803. /**
  804. *
  805. *
  806. * @param {array} groupIds
  807. * @param {object} groupsData
  808. * @param {object} groupRanges | this is being filled here
  809. * @private
  810. */
  811. LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) {
  812. var groupData, group, i;
  813. var combinedDataLeft = [];
  814. var combinedDataRight = [];
  815. var options;
  816. if (groupIds.length > 0) {
  817. for (i = 0; i < groupIds.length; i++) {
  818. groupData = groupsData[groupIds[i]];
  819. options = this.groups[groupIds[i]].options;
  820. if (groupData.length > 0) {
  821. group = this.groups[groupIds[i]];
  822. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  823. if (options.stack === true && options.style === 'bar') {
  824. if (options.yAxisOrientation === 'left') {
  825. combinedDataLeft = combinedDataLeft.concat(groupData);
  826. }
  827. else {
  828. combinedDataRight = combinedDataRight.concat(groupData);
  829. }
  830. }
  831. else {
  832. groupRanges[groupIds[i]] = group.getYRange(groupData, groupIds[i]);
  833. }
  834. }
  835. }
  836. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  837. Bars.getStackedYRange(combinedDataLeft, groupRanges, groupIds, '__barStackLeft', 'left');
  838. Bars.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__barStackRight', 'right');
  839. }
  840. };
  841. /**
  842. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  843. * @param {Array} groupIds
  844. * @param {Object} groupRanges
  845. * @private
  846. */
  847. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  848. var resized = false;
  849. var yAxisLeftUsed = false;
  850. var yAxisRightUsed = false;
  851. var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal;
  852. // if groups are present
  853. if (groupIds.length > 0) {
  854. // 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.
  855. for (var i = 0; i < groupIds.length; i++) {
  856. var group = this.groups[groupIds[i]];
  857. if (group && group.options.yAxisOrientation != 'right') {
  858. yAxisLeftUsed = true;
  859. minLeft = 1e9;
  860. maxLeft = -1e9;
  861. }
  862. else if (group && group.options.yAxisOrientation) {
  863. yAxisRightUsed = true;
  864. minRight = 1e9;
  865. maxRight = -1e9;
  866. }
  867. }
  868. // if there are items:
  869. for (var i = 0; i < groupIds.length; i++) {
  870. if (groupRanges.hasOwnProperty(groupIds[i])) {
  871. if (groupRanges[groupIds[i]].ignore !== true) {
  872. minVal = groupRanges[groupIds[i]].min;
  873. maxVal = groupRanges[groupIds[i]].max;
  874. if (groupRanges[groupIds[i]].yAxisOrientation != 'right') {
  875. yAxisLeftUsed = true;
  876. minLeft = minLeft > minVal ? minVal : minLeft;
  877. maxLeft = maxLeft < maxVal ? maxVal : maxLeft;
  878. }
  879. else {
  880. yAxisRightUsed = true;
  881. minRight = minRight > minVal ? minVal : minRight;
  882. maxRight = maxRight < maxVal ? maxVal : maxRight;
  883. }
  884. }
  885. }
  886. }
  887. if (yAxisLeftUsed == true) {
  888. this.yAxisLeft.setRange(minLeft, maxLeft);
  889. }
  890. if (yAxisRightUsed == true) {
  891. this.yAxisRight.setRange(minRight, maxRight);
  892. }
  893. }
  894. resized = this._toggleAxisVisiblity(yAxisLeftUsed, this.yAxisLeft) || resized;
  895. resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized;
  896. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  897. this.yAxisLeft.drawIcons = true;
  898. this.yAxisRight.drawIcons = true;
  899. }
  900. else {
  901. this.yAxisLeft.drawIcons = false;
  902. this.yAxisRight.drawIcons = false;
  903. }
  904. this.yAxisRight.master = !yAxisLeftUsed;
  905. this.yAxisRight.masterAxis = this.yAxisLeft;
  906. if (this.yAxisRight.master == false) {
  907. if (yAxisRightUsed == true) {
  908. this.yAxisLeft.lineOffset = this.yAxisRight.width;
  909. }
  910. else {
  911. this.yAxisLeft.lineOffset = 0;
  912. }
  913. resized = this.yAxisLeft.redraw() || resized;
  914. resized = this.yAxisRight.redraw() || resized;
  915. }
  916. else {
  917. resized = this.yAxisRight.redraw() || resized;
  918. }
  919. // clean the accumulated lists
  920. var tempGroups = ['__barStackLeft', '__barStackRight', '__lineStackLeft', '__lineStackRight'];
  921. for (var i = 0; i < tempGroups.length; i++) {
  922. if (groupIds.indexOf(tempGroups[i]) != -1) {
  923. groupIds.splice(groupIds.indexOf(tempGroups[i]), 1);
  924. }
  925. }
  926. return resized;
  927. };
  928. /**
  929. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  930. *
  931. * @param {boolean} axisUsed
  932. * @returns {boolean}
  933. * @private
  934. * @param axis
  935. */
  936. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  937. var changed = false;
  938. if (axisUsed == false) {
  939. if (axis.dom.frame.parentNode && axis.hidden == false) {
  940. axis.hide();
  941. changed = true;
  942. }
  943. }
  944. else {
  945. if (!axis.dom.frame.parentNode && axis.hidden == true) {
  946. axis.show();
  947. changed = true;
  948. }
  949. }
  950. return changed;
  951. };
  952. /**
  953. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  954. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  955. * the yAxis.
  956. *
  957. * @param datapoints
  958. * @returns {Array}
  959. * @private
  960. */
  961. LineGraph.prototype._convertXcoordinates = function (datapoints) {
  962. var toScreen = this.body.util.toScreen;
  963. for (var i = 0; i < datapoints.length; i++) {
  964. datapoints[i].screen_x = toScreen(datapoints[i].x) + this.props.width;
  965. datapoints[i].screen_y = datapoints[i].y; //starting point for range calculations
  966. if (datapoints[i].end != undefined) {
  967. datapoints[i].screen_end = toScreen(datapoints[i].end) + this.props.width;
  968. }
  969. else {
  970. datapoints[i].screen_end = undefined;
  971. }
  972. }
  973. };
  974. /**
  975. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  976. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  977. * the yAxis.
  978. *
  979. * @param datapoints
  980. * @param group
  981. * @returns {Array}
  982. * @private
  983. */
  984. LineGraph.prototype._convertYcoordinates = function (datapoints, group) {
  985. var axis = this.yAxisLeft;
  986. var svgHeight = Number(this.svg.style.height.replace('px', ''));
  987. if (group.options.yAxisOrientation == 'right') {
  988. axis = this.yAxisRight;
  989. }
  990. for (var i = 0; i < datapoints.length; i++) {
  991. datapoints[i].screen_y = Math.round(axis.convertValue(datapoints[i].y));
  992. }
  993. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  994. };
  995. module.exports = LineGraph;