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.

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