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.

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