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.

1071 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
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. this.redraw(true);
  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. this._onRemoveGroups(ids); // note: this will cause a redraw
  299. }
  300. // replace the dataset
  301. if (!groups) {
  302. this.groupsData = null;
  303. }
  304. else if (groups instanceof DataSet || groups instanceof DataView) {
  305. this.groupsData = groups;
  306. }
  307. else {
  308. throw new TypeError('Data must be an instance of DataSet or DataView');
  309. }
  310. if (this.groupsData) {
  311. // subscribe to new dataset
  312. var id = this.id;
  313. util.forEach(this.groupListeners, function (callback, event) {
  314. me.groupsData.on(event, callback, id);
  315. });
  316. // draw all ms
  317. ids = this.groupsData.getIds();
  318. this._onAddGroups(ids);
  319. }
  320. this._onUpdate();
  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. /**
  534. * Update and redraw the graph.
  535. *
  536. */
  537. LineGraph.prototype._updateGraph = function () {
  538. // reset the svg elements
  539. DOMutil.prepareElements(this.svgElements);
  540. if (this.props.width != 0 && this.itemsData != null) {
  541. var group, i;
  542. var groupRanges = {};
  543. var changeCalled = false;
  544. // this is the range of the SVG canvas
  545. var minDate = this.body.util.toGlobalTime(-this.body.domProps.root.width);
  546. var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width);
  547. // getting group Ids
  548. var groupIds = [];
  549. for (var groupId in this.groups) {
  550. if (this.groups.hasOwnProperty(groupId)) {
  551. group = this.groups[groupId];
  552. if (group.visible == true && (this.options.groups.visibility[groupId] === undefined || this.options.groups.visibility[groupId] == true)) {
  553. groupIds.push(groupId);
  554. }
  555. }
  556. }
  557. if (groupIds.length > 0) {
  558. var groupsData = {};
  559. // fill groups data, this only loads the data we require based on the timewindow
  560. this._getRelevantData(groupIds, groupsData, minDate, maxDate);
  561. // apply sampling, if disabled, it will pass through this function.
  562. this._applySampling(groupIds, groupsData);
  563. // we transform the X coordinates to detect collisions
  564. for (i = 0; i < groupIds.length; i++) {
  565. this._convertXcoordinates(groupsData[groupIds[i]]);
  566. }
  567. // now all needed data has been collected we start the processing.
  568. this._getYRanges(groupIds, groupsData, groupRanges);
  569. // update the Y axis first, we use this data to draw at the correct Y points
  570. // changeCalled is required to clean the SVG on a change emit.
  571. changeCalled = this._updateYAxis(groupIds, groupRanges);
  572. var MAX_CYCLES = 5;
  573. if (changeCalled == true && this.COUNTER < MAX_CYCLES) {
  574. DOMutil.cleanupElements(this.svgElements);
  575. this.abortedGraphUpdate = true;
  576. this.COUNTER++;
  577. this.body.emitter.emit('change');
  578. return true;
  579. }
  580. else {
  581. if (this.COUNTER > MAX_CYCLES) {
  582. console.log("WARNING: there may be an infinite loop in the _updateGraph emitter cycle.");
  583. }
  584. this.COUNTER = 0;
  585. this.abortedGraphUpdate = false;
  586. // With the yAxis scaled correctly, use this to get the Y values of the points.
  587. var below = undefined;
  588. for (i = 0; i < groupIds.length; i++) {
  589. group = this.groups[groupIds[i]];
  590. if (this.options.stack === true && this.options.style === 'line') {
  591. if (group.options.excludeFromStacking == undefined || !group.options.excludeFromStacking) {
  592. if (below != undefined) {
  593. this._stack(groupsData[group.id], groupsData[below.id]);
  594. if (group.options.shaded.enabled == true && group.options.shaded.orientation !== "group"){
  595. if (group.options.shaded.orientation == "top" && below.options.shaded.orientation !== "group"){
  596. below.options.shaded.orientation="group";
  597. below.options.shaded.groupId=group.id;
  598. } else {
  599. group.options.shaded.orientation="group";
  600. group.options.shaded.groupId=below.id;
  601. }
  602. }
  603. }
  604. below = group;
  605. }
  606. }
  607. this._convertYcoordinates(groupsData[groupIds[i]], group);
  608. }
  609. //Precalculate paths and draw shading if appropriate. This will make sure the shading is always behind any lines.
  610. var paths = {};
  611. for (i = 0; i < groupIds.length; i++) {
  612. group = this.groups[groupIds[i]];
  613. if (group.options.style === 'line' && group.options.shaded.enabled == true) {
  614. var dataset = groupsData[groupIds[i]];
  615. if (!paths.hasOwnProperty(groupIds[i])) {
  616. paths[groupIds[i]] = Lines.calcPath(dataset, group);
  617. }
  618. if (group.options.shaded.orientation === "group") {
  619. var subGroupId = group.options.shaded.groupId;
  620. if (groupIds.indexOf(subGroupId) === -1) {
  621. console.log(group.id + ": Unknown shading group target given:" + subGroupId);
  622. continue;
  623. }
  624. if (!paths.hasOwnProperty(subGroupId)) {
  625. paths[subGroupId] = Lines.calcPath(groupsData[subGroupId], this.groups[subGroupId]);
  626. }
  627. Lines.drawShading(paths[groupIds[i]], group, paths[subGroupId], this.framework);
  628. }
  629. else {
  630. Lines.drawShading(paths[groupIds[i]], group, undefined, this.framework);
  631. }
  632. }
  633. }
  634. // draw the groups, calculating paths if still necessary.
  635. Bars.draw(groupIds, groupsData, this.framework);
  636. for (i = 0; i < groupIds.length; i++) {
  637. group = this.groups[groupIds[i]];
  638. if (groupsData[groupIds[i]].length > 0) {
  639. switch (group.options.style) {
  640. case "line":
  641. if (!paths.hasOwnProperty(groupIds[i])) {
  642. paths[groupIds[i]] = Lines.calcPath(groupsData[groupIds[i]], group);
  643. }
  644. Lines.draw(paths[groupIds[i]], group, this.framework);
  645. //explicit no break;
  646. case "points":
  647. if (group.options.style == "points" || group.options.drawPoints.enabled == true) {
  648. Points.draw(groupsData[groupIds[i]], group, this.framework);
  649. }
  650. break;
  651. case "bar":
  652. // bar needs to be drawn enmasse
  653. //explicit no break
  654. default:
  655. //do nothing...
  656. }
  657. }
  658. }
  659. }
  660. }
  661. }
  662. // cleanup unused svg elements
  663. DOMutil.cleanupElements(this.svgElements);
  664. return false;
  665. };
  666. LineGraph.prototype._stack = function (data, subData) {
  667. var index, dx, dy, subPrevPoint, subNextPoint;
  668. index = 0;
  669. // for each data point we look for a matching on in the set below
  670. for (var j = 0; j < data.length; j++) {
  671. subPrevPoint = undefined;
  672. subNextPoint = undefined;
  673. // we look for time matches or a before-after point
  674. for (var k = index; k < subData.length; k++) {
  675. // if times match exactly
  676. if (subData[k].x === data[j].x) {
  677. subPrevPoint = subData[k];
  678. subNextPoint = subData[k];
  679. index = k;
  680. break;
  681. }
  682. else if (subData[k].x > data[j].x) { // overshoot
  683. subNextPoint = subData[k];
  684. if (k == 0) {
  685. subPrevPoint = subNextPoint;
  686. }
  687. else {
  688. subPrevPoint = subData[k - 1];
  689. }
  690. index = k;
  691. break;
  692. }
  693. }
  694. // in case the last data point has been used, we assume it stays like this.
  695. if (subNextPoint === undefined) {
  696. subPrevPoint = subData[subData.length - 1];
  697. subNextPoint = subData[subData.length - 1];
  698. }
  699. // linear interpolation
  700. dx = subNextPoint.x - subPrevPoint.x;
  701. dy = subNextPoint.y - subPrevPoint.y;
  702. if (dx == 0) {
  703. data[j].y = data[j].orginalY + subNextPoint.y;
  704. }
  705. else {
  706. data[j].y = data[j].orginalY + (dy / dx) * (data[j].x - subPrevPoint.x) + subPrevPoint.y; // ax + b where b is data[j].y
  707. }
  708. }
  709. }
  710. /**
  711. * first select and preprocess the data from the datasets.
  712. * the groups have their preselection of data, we now loop over this data to see
  713. * what data we need to draw. Sorted data is much faster.
  714. * more optimization is possible by doing the sampling before and using the binary search
  715. * to find the end date to determine the increment.
  716. *
  717. * @param {array} groupIds
  718. * @param {object} groupsData
  719. * @param {date} minDate
  720. * @param {date} maxDate
  721. * @private
  722. */
  723. LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) {
  724. var group, i, j, item;
  725. if (groupIds.length > 0) {
  726. for (i = 0; i < groupIds.length; i++) {
  727. group = this.groups[groupIds[i]];
  728. var itemsData = group.getItems();
  729. // optimization for sorted data
  730. if (group.options.sort == true) {
  731. var first = Math.max(0, util.binarySearchValue(itemsData, minDate, 'x', 'before'));
  732. var last = Math.min(itemsData.length, util.binarySearchValue(itemsData, maxDate, 'x', 'after')+1);
  733. if (last <= 0) {
  734. last = itemsData.length;
  735. }
  736. var dataContainer = new Array(last-first);
  737. for (j = first; j < last; j++) {
  738. item = group.itemsData[j];
  739. dataContainer[j-first] = item;
  740. }
  741. groupsData[groupIds[i]] = dataContainer;
  742. }
  743. else {
  744. // If unsorted data, all data is relevant, just returning entire structure
  745. groupsData[groupIds[i]] = group.itemsData;
  746. }
  747. }
  748. }
  749. };
  750. /**
  751. *
  752. * @param groupIds
  753. * @param groupsData
  754. * @private
  755. */
  756. LineGraph.prototype._applySampling = function (groupIds, groupsData) {
  757. var group;
  758. if (groupIds.length > 0) {
  759. for (var i = 0; i < groupIds.length; i++) {
  760. group = this.groups[groupIds[i]];
  761. if (group.options.sampling == true) {
  762. var dataContainer = groupsData[groupIds[i]];
  763. if (dataContainer.length > 0) {
  764. var increment = 1;
  765. var amountOfPoints = dataContainer.length;
  766. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  767. // of width changing of the yAxis.
  768. var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x);
  769. var pointsPerPixel = amountOfPoints / xDistance;
  770. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel)));
  771. var sampledData = new Array(amountOfPoints);
  772. for (var j = 0; j < amountOfPoints; j += increment) {
  773. var idx = Math.round(j/increment);
  774. sampledData[idx]=dataContainer[j];
  775. }
  776. groupsData[groupIds[i]] = sampledData.splice(0,Math.round(amountOfPoints/increment));
  777. }
  778. }
  779. }
  780. }
  781. };
  782. /**
  783. *
  784. *
  785. * @param {array} groupIds
  786. * @param {object} groupsData
  787. * @param {object} groupRanges | this is being filled here
  788. * @private
  789. */
  790. LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) {
  791. var groupData, group, i;
  792. var combinedDataLeft = [];
  793. var combinedDataRight = [];
  794. var options;
  795. if (groupIds.length > 0) {
  796. for (i = 0; i < groupIds.length; i++) {
  797. groupData = groupsData[groupIds[i]];
  798. options = this.groups[groupIds[i]].options;
  799. if (groupData.length > 0) {
  800. group = this.groups[groupIds[i]];
  801. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  802. if (options.stack === true && options.style === 'bar') {
  803. if (options.yAxisOrientation === 'left') {
  804. combinedDataLeft = combinedDataLeft.concat(group.getItems());
  805. }
  806. else {
  807. combinedDataRight = combinedDataRight.concat(group.getItems());
  808. }
  809. }
  810. else {
  811. groupRanges[groupIds[i]] = group.getYRange(groupData, groupIds[i]);
  812. }
  813. }
  814. }
  815. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  816. Bars.getStackedYRange(combinedDataLeft, groupRanges, groupIds, '__barStackLeft', 'left');
  817. Bars.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__barStackRight', 'right');
  818. }
  819. };
  820. /**
  821. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  822. * @param {Array} groupIds
  823. * @param {Object} groupRanges
  824. * @private
  825. */
  826. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  827. var resized = false;
  828. var yAxisLeftUsed = false;
  829. var yAxisRightUsed = false;
  830. var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal;
  831. // if groups are present
  832. if (groupIds.length > 0) {
  833. // 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.
  834. for (var i = 0; i < groupIds.length; i++) {
  835. var group = this.groups[groupIds[i]];
  836. if (group && group.options.yAxisOrientation != 'right') {
  837. yAxisLeftUsed = true;
  838. minLeft = 1e9;
  839. maxLeft = -1e9;
  840. }
  841. else if (group && group.options.yAxisOrientation) {
  842. yAxisRightUsed = true;
  843. minRight = 1e9;
  844. maxRight = -1e9;
  845. }
  846. }
  847. // if there are items:
  848. for (var i = 0; i < groupIds.length; i++) {
  849. if (groupRanges.hasOwnProperty(groupIds[i])) {
  850. if (groupRanges[groupIds[i]].ignore !== true) {
  851. minVal = groupRanges[groupIds[i]].min;
  852. maxVal = groupRanges[groupIds[i]].max;
  853. if (groupRanges[groupIds[i]].yAxisOrientation != 'right') {
  854. yAxisLeftUsed = true;
  855. minLeft = minLeft > minVal ? minVal : minLeft;
  856. maxLeft = maxLeft < maxVal ? maxVal : maxLeft;
  857. }
  858. else {
  859. yAxisRightUsed = true;
  860. minRight = minRight > minVal ? minVal : minRight;
  861. maxRight = maxRight < maxVal ? maxVal : maxRight;
  862. }
  863. }
  864. }
  865. }
  866. if (yAxisLeftUsed == true) {
  867. this.yAxisLeft.setRange(minLeft, maxLeft);
  868. }
  869. if (yAxisRightUsed == true) {
  870. this.yAxisRight.setRange(minRight, maxRight);
  871. }
  872. }
  873. resized = this._toggleAxisVisiblity(yAxisLeftUsed, this.yAxisLeft) || resized;
  874. resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized;
  875. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  876. this.yAxisLeft.drawIcons = true;
  877. this.yAxisRight.drawIcons = true;
  878. }
  879. else {
  880. this.yAxisLeft.drawIcons = false;
  881. this.yAxisRight.drawIcons = false;
  882. }
  883. this.yAxisRight.master = !yAxisLeftUsed;
  884. if (this.yAxisRight.master == false) {
  885. if (yAxisRightUsed == true) {
  886. this.yAxisLeft.lineOffset = this.yAxisRight.width;
  887. }
  888. else {
  889. this.yAxisLeft.lineOffset = 0;
  890. }
  891. resized = this.yAxisLeft.redraw() || resized;
  892. this.yAxisRight.stepPixels = this.yAxisLeft.stepPixels;
  893. this.yAxisRight.zeroCrossing = this.yAxisLeft.zeroCrossing;
  894. this.yAxisRight.amountOfSteps = this.yAxisLeft.amountOfSteps;
  895. resized = this.yAxisRight.redraw() || resized;
  896. }
  897. else {
  898. resized = this.yAxisRight.redraw() || resized;
  899. }
  900. // clean the accumulated lists
  901. var tempGroups = ['__barStackLeft', '__barStackRight', '__lineStackLeft', '__lineStackRight'];
  902. for (var i = 0; i < tempGroups.length; i++) {
  903. if (groupIds.indexOf(tempGroups[i]) != -1) {
  904. groupIds.splice(groupIds.indexOf(tempGroups[i]), 1);
  905. }
  906. }
  907. return resized;
  908. };
  909. /**
  910. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  911. *
  912. * @param {boolean} axisUsed
  913. * @returns {boolean}
  914. * @private
  915. * @param axis
  916. */
  917. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  918. var changed = false;
  919. if (axisUsed == false) {
  920. if (axis.dom.frame.parentNode && axis.hidden == false) {
  921. axis.hide();
  922. changed = true;
  923. }
  924. }
  925. else {
  926. if (!axis.dom.frame.parentNode && axis.hidden == true) {
  927. axis.show();
  928. changed = true;
  929. }
  930. }
  931. return changed;
  932. };
  933. /**
  934. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  935. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  936. * the yAxis.
  937. *
  938. * @param datapoints
  939. * @returns {Array}
  940. * @private
  941. */
  942. LineGraph.prototype._convertXcoordinates = function (datapoints) {
  943. var toScreen = this.body.util.toScreen;
  944. for (var i = 0; i < datapoints.length; i++) {
  945. datapoints[i].screen_x = toScreen(datapoints[i].x) + this.props.width;
  946. datapoints[i].screen_y = datapoints[i].y; //starting point for range calculations
  947. }
  948. };
  949. /**
  950. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  951. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  952. * the yAxis.
  953. *
  954. * @param datapoints
  955. * @param group
  956. * @returns {Array}
  957. * @private
  958. */
  959. LineGraph.prototype._convertYcoordinates = function (datapoints, group) {
  960. var axis = this.yAxisLeft;
  961. var svgHeight = Number(this.svg.style.height.replace('px', ''));
  962. if (group.options.yAxisOrientation == 'right') {
  963. axis = this.yAxisRight;
  964. }
  965. for (var i = 0; i < datapoints.length; i++) {
  966. datapoints[i].screen_y = Math.round(axis.convertValue(datapoints[i].y));
  967. }
  968. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  969. };
  970. module.exports = LineGraph;