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.

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