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.

1060 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
  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. /**
  323. * Update the data
  324. * @param [ids]
  325. * @private
  326. */
  327. LineGraph.prototype._onUpdate = function (ids) {
  328. this._updateAllGroupData();
  329. this.redraw(true);
  330. };
  331. LineGraph.prototype._onAdd = function (ids) {
  332. this._onUpdate(ids);
  333. };
  334. LineGraph.prototype._onRemove = function (ids) {
  335. this._onUpdate(ids);
  336. };
  337. LineGraph.prototype._onUpdateGroups = function (groupIds) {
  338. this._updateAllGroupData();
  339. this.redraw(true);
  340. };
  341. LineGraph.prototype._onAddGroups = function (groupIds) {
  342. this._onUpdateGroups(groupIds);
  343. };
  344. /**
  345. * this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph
  346. * @param {Array} groupIds
  347. * @private
  348. */
  349. LineGraph.prototype._onRemoveGroups = function (groupIds) {
  350. for (var i = 0; i < groupIds.length; i++) {
  351. if (this.groups.hasOwnProperty(groupIds[i])) {
  352. if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') {
  353. this.yAxisRight.removeGroup(groupIds[i]);
  354. this.legendRight.removeGroup(groupIds[i]);
  355. this.legendRight.redraw();
  356. }
  357. else {
  358. this.yAxisLeft.removeGroup(groupIds[i]);
  359. this.legendLeft.removeGroup(groupIds[i]);
  360. this.legendLeft.redraw();
  361. }
  362. delete this.groups[groupIds[i]];
  363. }
  364. }
  365. this.redraw(true);
  366. };
  367. /**
  368. * update a group object with the group dataset entree
  369. *
  370. * @param group
  371. * @param groupId
  372. * @private
  373. */
  374. LineGraph.prototype._updateGroup = function (group, groupId) {
  375. if (!this.groups.hasOwnProperty(groupId)) {
  376. this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles);
  377. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  378. this.yAxisRight.addGroup(groupId, this.groups[groupId]);
  379. this.legendRight.addGroup(groupId, this.groups[groupId]);
  380. }
  381. else {
  382. this.yAxisLeft.addGroup(groupId, this.groups[groupId]);
  383. this.legendLeft.addGroup(groupId, this.groups[groupId]);
  384. }
  385. }
  386. else {
  387. this.groups[groupId].update(group);
  388. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  389. this.yAxisRight.updateGroup(groupId, this.groups[groupId]);
  390. this.legendRight.updateGroup(groupId, this.groups[groupId]);
  391. }
  392. else {
  393. this.yAxisLeft.updateGroup(groupId, this.groups[groupId]);
  394. this.legendLeft.updateGroup(groupId, this.groups[groupId]);
  395. }
  396. }
  397. this.legendLeft.redraw();
  398. this.legendRight.redraw();
  399. };
  400. /**
  401. * this updates all groups, it is used when there is an update the the itemset.
  402. *
  403. * @private
  404. */
  405. LineGraph.prototype._updateAllGroupData = function () {
  406. if (this.itemsData != null) {
  407. var groupsContent = {};
  408. var items = this.itemsData.get();
  409. //pre-Determine array sizes, for more efficient memory claim
  410. var groupCounts = {};
  411. for (var i = 0; i < items.length; i++) {
  412. var item = items[i];
  413. var groupId = item.group;
  414. if (groupId === null || groupId === undefined) {
  415. groupId = UNGROUPED;
  416. }
  417. groupCounts.hasOwnProperty(groupId) ? groupCounts[groupId]++ : groupCounts[groupId] = 1;
  418. }
  419. //Now insert data into the arrays.
  420. for (var i = 0; i < items.length; i++) {
  421. var item = items[i];
  422. var groupId = item.group;
  423. if (groupId === null || groupId === undefined) {
  424. groupId = UNGROUPED;
  425. }
  426. if (!groupsContent.hasOwnProperty(groupId)) {
  427. groupsContent[groupId] = new Array(groupCounts[groupId]);
  428. }
  429. //Copy data (because of unmodifiable DataView input.
  430. var extended = util.bridgeObject(item);
  431. extended.x = util.convert(item.x, 'Date');
  432. extended.orginalY = item.y; //real Y
  433. // typecast all items to numbers. Takes around 10ms for 500.000 items
  434. extended.y = Number(item.y);
  435. var index= groupsContent[groupId].length - groupCounts[groupId]--;
  436. groupsContent[groupId][index] = extended;
  437. }
  438. //Update legendas, style and axis
  439. for (var groupId in groupsContent) {
  440. if (groupsContent.hasOwnProperty(groupId)) {
  441. if (groupsContent[groupId].length == 0) {
  442. if (this.groups.hasOwnProperty(groupId)) {
  443. this._onRemoveGroups([groupId]);
  444. }
  445. } else {
  446. var group = undefined;
  447. if (this.groupsData != undefined) {
  448. group = this.groupsData.get(groupId);
  449. }
  450. if (group == undefined) {
  451. group = {id: groupId, content: this.options.defaultGroup + groupId};
  452. }
  453. this._updateGroup(group, groupId);
  454. this.groups[groupId].setItems(groupsContent[groupId]);
  455. }
  456. }
  457. }
  458. }
  459. };
  460. /**
  461. * Redraw the component, mandatory function
  462. * @return {boolean} Returns true if the component is resized
  463. */
  464. LineGraph.prototype.redraw = function (forceGraphUpdate) {
  465. var resized = false;
  466. // calculate actual size and position
  467. this.props.width = this.dom.frame.offsetWidth;
  468. this.props.height = this.body.domProps.centerContainer.height
  469. - this.body.domProps.border.top
  470. - this.body.domProps.border.bottom;
  471. // update the graph if there is no lastWidth or with, used for the initial draw
  472. if (this.lastWidth === undefined && this.props.width) {
  473. forceGraphUpdate = true;
  474. }
  475. // check if this component is resized
  476. resized = this._isResized() || resized;
  477. // check whether zoomed (in that case we need to re-stack everything)
  478. var visibleInterval = this.body.range.end - this.body.range.start;
  479. var zoomed = (visibleInterval != this.lastVisibleInterval);
  480. this.lastVisibleInterval = visibleInterval;
  481. // the svg element is three times as big as the width, this allows for fully dragging left and right
  482. // without reloading the graph. the controls for this are bound to events in the constructor
  483. if (resized == true) {
  484. this.svg.style.width = util.option.asSize(3 * this.props.width);
  485. this.svg.style.left = util.option.asSize(-this.props.width);
  486. // if the height of the graph is set as proportional, change the height of the svg
  487. if ((this.options.height + '').indexOf("%") != -1 || this.updateSVGheightOnResize == true) {
  488. this.updateSVGheight = true;
  489. }
  490. }
  491. // update the height of the graph on each redraw of the graph.
  492. if (this.updateSVGheight == true) {
  493. if (this.options.graphHeight != this.props.height + 'px') {
  494. this.options.graphHeight = this.props.height + 'px';
  495. this.svg.style.height = this.props.height + 'px';
  496. }
  497. this.updateSVGheight = false;
  498. }
  499. else {
  500. this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px';
  501. }
  502. // zoomed is here to ensure that animations are shown correctly.
  503. if (resized == true || zoomed == true || this.abortedGraphUpdate == true || forceGraphUpdate == true) {
  504. resized = this._updateGraph() || resized;
  505. }
  506. else {
  507. // move the whole svg while dragging
  508. if (this.lastStart != 0) {
  509. var offset = this.body.range.start - this.lastStart;
  510. var range = this.body.range.end - this.body.range.start;
  511. if (this.props.width != 0) {
  512. var rangePerPixelInv = this.props.width / range;
  513. var xOffset = offset * rangePerPixelInv;
  514. this.svg.style.left = (-this.props.width - xOffset) + 'px';
  515. }
  516. }
  517. }
  518. this.legendLeft.redraw();
  519. this.legendRight.redraw();
  520. return resized;
  521. };
  522. /**
  523. * Update and redraw the graph.
  524. *
  525. */
  526. LineGraph.prototype._updateGraph = function () {
  527. // reset the svg elements
  528. DOMutil.prepareElements(this.svgElements);
  529. if (this.props.width != 0 && this.itemsData != null) {
  530. var group, i;
  531. var groupRanges = {};
  532. var changeCalled = false;
  533. // this is the range of the SVG canvas
  534. var minDate = this.body.util.toGlobalTime(-this.body.domProps.root.width);
  535. var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width);
  536. // getting group Ids
  537. var groupIds = [];
  538. for (var groupId in this.groups) {
  539. if (this.groups.hasOwnProperty(groupId)) {
  540. group = this.groups[groupId];
  541. if (group.visible == true && (this.options.groups.visibility[groupId] === undefined || this.options.groups.visibility[groupId] == true)) {
  542. groupIds.push(groupId);
  543. }
  544. }
  545. }
  546. if (groupIds.length > 0) {
  547. var groupsData = {};
  548. // fill groups data, this only loads the data we require based on the timewindow
  549. this._getRelevantData(groupIds, groupsData, minDate, maxDate);
  550. // apply sampling, if disabled, it will pass through this function.
  551. this._applySampling(groupIds, groupsData);
  552. // we transform the X coordinates to detect collisions
  553. for (i = 0; i < groupIds.length; i++) {
  554. this._convertXcoordinates(groupsData[groupIds[i]]);
  555. }
  556. // now all needed data has been collected we start the processing.
  557. this._getYRanges(groupIds, groupsData, groupRanges);
  558. // update the Y axis first, we use this data to draw at the correct Y points
  559. // changeCalled is required to clean the SVG on a change emit.
  560. changeCalled = this._updateYAxis(groupIds, groupRanges);
  561. var MAX_CYCLES = 5;
  562. if (changeCalled == true && this.COUNTER < MAX_CYCLES) {
  563. DOMutil.cleanupElements(this.svgElements);
  564. this.abortedGraphUpdate = true;
  565. this.COUNTER++;
  566. this.body.emitter.emit('change');
  567. return true;
  568. }
  569. else {
  570. if (this.COUNTER > MAX_CYCLES) {
  571. console.log("WARNING: there may be an infinite loop in the _updateGraph emitter cycle.");
  572. }
  573. this.COUNTER = 0;
  574. this.abortedGraphUpdate = false;
  575. // With the yAxis scaled correctly, use this to get the Y values of the points.
  576. var below = undefined;
  577. for (i = 0; i < groupIds.length; i++) {
  578. group = this.groups[groupIds[i]];
  579. if (this.options.stack === true && this.options.style === 'line') {
  580. if (group.options.excludeFromStacking == undefined || !group.options.excludeFromStacking) {
  581. if (below != undefined) {
  582. this._stack(groupsData[group.id], groupsData[below.id]);
  583. if (group.options.shaded.enabled == true && group.options.shaded.orientation !== "group"){
  584. if (group.options.shaded.orientation == "top" && below.options.shaded.orientation !== "group"){
  585. below.options.shaded.orientation="group";
  586. below.options.shaded.groupId=group.id;
  587. } else {
  588. group.options.shaded.orientation="group";
  589. group.options.shaded.groupId=below.id;
  590. }
  591. }
  592. }
  593. below = group;
  594. }
  595. }
  596. this._convertYcoordinates(groupsData[groupIds[i]], group);
  597. }
  598. //Precalculate paths and draw shading if appropriate. This will make sure the shading is always behind any lines.
  599. var paths = {};
  600. for (i = 0; i < groupIds.length; i++) {
  601. group = this.groups[groupIds[i]];
  602. if (group.options.style === 'line' && group.options.shaded.enabled == true) {
  603. var dataset = groupsData[groupIds[i]];
  604. if (!paths.hasOwnProperty(groupIds[i])) {
  605. paths[groupIds[i]] = Lines.calcPath(dataset, group);
  606. }
  607. if (group.options.shaded.orientation === "group") {
  608. var subGroupId = group.options.shaded.groupId;
  609. if (groupIds.indexOf(subGroupId) === -1) {
  610. console.log("Unknown shading group target given:" + subGroupId);
  611. continue;
  612. }
  613. if (!paths.hasOwnProperty(subGroupId)) {
  614. paths[subGroupId] = Lines.calcPath(groupsData[subGroupId], this.groups[subGroupId]);
  615. }
  616. Lines.drawShading(paths[groupIds[i]], group, paths[subGroupId], this.framework);
  617. }
  618. else {
  619. Lines.drawShading(paths[groupIds[i]], group, undefined, this.framework);
  620. }
  621. }
  622. }
  623. // draw the groups, calculating paths if still necessary.
  624. Bars.draw(groupIds, groupsData, this.framework);
  625. for (i = 0; i < groupIds.length; i++) {
  626. group = this.groups[groupIds[i]];
  627. if (groupsData[groupIds[i]].length > 0) {
  628. switch (group.options.style) {
  629. case "line":
  630. if (!paths.hasOwnProperty(groupIds[i])) {
  631. paths[groupIds[i]] = Lines.calcPath(groupsData[groupIds[i]], group);
  632. }
  633. Lines.draw(paths[groupIds[i]], group, this.framework);
  634. //explicit no break;
  635. case "points":
  636. if (group.options.style == "points" || group.options.drawPoints.enabled == true) {
  637. Points.draw(groupsData[groupIds[i]], group, this.framework);
  638. }
  639. break;
  640. case "bar":
  641. // bar needs to be drawn enmasse
  642. //explicit no break
  643. default:
  644. //do nothing...
  645. }
  646. }
  647. }
  648. }
  649. }
  650. }
  651. // cleanup unused svg elements
  652. DOMutil.cleanupElements(this.svgElements);
  653. return false;
  654. };
  655. LineGraph.prototype._stack = function (data, subData) {
  656. var index, dx, dy, subPrevPoint, subNextPoint;
  657. index = 0;
  658. // for each data point we look for a matching on in the set below
  659. for (var j = 0; j < data.length; j++) {
  660. subPrevPoint = undefined;
  661. subNextPoint = undefined;
  662. // we look for time matches or a before-after point
  663. for (var k = index; k < subData.length; k++) {
  664. // if times match exactly
  665. if (subData[k].x === data[j].x) {
  666. subPrevPoint = subData[k];
  667. subNextPoint = subData[k];
  668. index = k;
  669. break;
  670. }
  671. else if (subData[k].x > data[j].x) { // overshoot
  672. subNextPoint = subData[k];
  673. if (k == 0) {
  674. subPrevPoint = subNextPoint;
  675. }
  676. else {
  677. subPrevPoint = subData[k - 1];
  678. }
  679. index = k;
  680. break;
  681. }
  682. }
  683. // in case the last data point has been used, we assume it stays like this.
  684. if (subNextPoint === undefined) {
  685. subPrevPoint = subData[subData.length - 1];
  686. subNextPoint = subData[subData.length - 1];
  687. }
  688. // linear interpolation
  689. dx = subNextPoint.x - subPrevPoint.x;
  690. dy = subNextPoint.y - subPrevPoint.y;
  691. if (dx == 0) {
  692. data[j].y = data[j].orginalY + subNextPoint.y;
  693. }
  694. else {
  695. data[j].y = data[j].orginalY + (dy / dx) * (data[j].x - subPrevPoint.x) + subPrevPoint.y; // ax + b where b is data[j].y
  696. }
  697. }
  698. }
  699. /**
  700. * first select and preprocess the data from the datasets.
  701. * the groups have their preselection of data, we now loop over this data to see
  702. * what data we need to draw. Sorted data is much faster.
  703. * more optimization is possible by doing the sampling before and using the binary search
  704. * to find the end date to determine the increment.
  705. *
  706. * @param {array} groupIds
  707. * @param {object} groupsData
  708. * @param {date} minDate
  709. * @param {date} maxDate
  710. * @private
  711. */
  712. LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) {
  713. var group, i, j, item;
  714. if (groupIds.length > 0) {
  715. for (i = 0; i < groupIds.length; i++) {
  716. group = this.groups[groupIds[i]];
  717. var itemsData = group.getItems();
  718. // optimization for sorted data
  719. if (group.options.sort == true) {
  720. var first = Math.max(0, util.binarySearchValue(itemsData, minDate, 'x', 'before'));
  721. var last = Math.min(itemsData.length, util.binarySearchValue(itemsData, maxDate, 'x', 'after')+1);
  722. if (last <= 0) {
  723. last = itemsData.length;
  724. }
  725. var dataContainer = new Array(last-first);
  726. for (j = first; j < last; j++) {
  727. item = group.itemsData[j];
  728. dataContainer[j-first] = item;
  729. }
  730. groupsData[groupIds[i]] = dataContainer;
  731. }
  732. else {
  733. // If unsorted data, all data is relevant, just returning entire structure
  734. groupsData[groupIds[i]] = group.itemsData;
  735. }
  736. }
  737. }
  738. };
  739. /**
  740. *
  741. * @param groupIds
  742. * @param groupsData
  743. * @private
  744. */
  745. LineGraph.prototype._applySampling = function (groupIds, groupsData) {
  746. var group;
  747. if (groupIds.length > 0) {
  748. for (var i = 0; i < groupIds.length; i++) {
  749. group = this.groups[groupIds[i]];
  750. if (group.options.sampling == true) {
  751. var dataContainer = groupsData[groupIds[i]];
  752. if (dataContainer.length > 0) {
  753. var increment = 1;
  754. var amountOfPoints = dataContainer.length;
  755. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  756. // of width changing of the yAxis.
  757. var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x);
  758. var pointsPerPixel = amountOfPoints / xDistance;
  759. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel)));
  760. var sampledData = new Array(amountOfPoints);
  761. for (var j = 0; j < amountOfPoints; j += increment) {
  762. var idx = Math.round(j/increment);
  763. sampledData[idx]=dataContainer[j];
  764. }
  765. groupsData[groupIds[i]] = sampledData.splice(0,Math.round(amountOfPoints/increment));
  766. }
  767. }
  768. }
  769. }
  770. };
  771. /**
  772. *
  773. *
  774. * @param {array} groupIds
  775. * @param {object} groupsData
  776. * @param {object} groupRanges | this is being filled here
  777. * @private
  778. */
  779. LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) {
  780. var groupData, group, i;
  781. var combinedDataLeft = [];
  782. var combinedDataRight = [];
  783. var options;
  784. if (groupIds.length > 0) {
  785. for (i = 0; i < groupIds.length; i++) {
  786. groupData = groupsData[groupIds[i]];
  787. options = this.groups[groupIds[i]].options;
  788. if (groupData.length > 0) {
  789. group = this.groups[groupIds[i]];
  790. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  791. if (options.stack === true && options.style === 'bar') {
  792. if (options.yAxisOrientation === 'left') {
  793. combinedDataLeft = combinedDataLeft.concat(group.getItems());
  794. }
  795. else {
  796. combinedDataRight = combinedDataRight.concat(group.getItems());
  797. }
  798. }
  799. else {
  800. groupRanges[groupIds[i]] = group.getYRange(groupData, groupIds[i]);
  801. }
  802. }
  803. }
  804. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  805. Bars.getStackedYRange(combinedDataLeft, groupRanges, groupIds, '__barStackLeft', 'left');
  806. Bars.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__barStackRight', 'right');
  807. }
  808. };
  809. /**
  810. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  811. * @param {Array} groupIds
  812. * @param {Object} groupRanges
  813. * @private
  814. */
  815. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  816. var resized = false;
  817. var yAxisLeftUsed = false;
  818. var yAxisRightUsed = false;
  819. var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal;
  820. // if groups are present
  821. if (groupIds.length > 0) {
  822. // 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.
  823. for (var i = 0; i < groupIds.length; i++) {
  824. var group = this.groups[groupIds[i]];
  825. if (group && group.options.yAxisOrientation != 'right') {
  826. yAxisLeftUsed = true;
  827. minLeft = 1e9;
  828. maxLeft = -1e9;
  829. }
  830. else if (group && group.options.yAxisOrientation) {
  831. yAxisRightUsed = true;
  832. minRight = 1e9;
  833. maxRight = -1e9;
  834. }
  835. }
  836. // if there are items:
  837. for (var i = 0; i < groupIds.length; i++) {
  838. if (groupRanges.hasOwnProperty(groupIds[i])) {
  839. if (groupRanges[groupIds[i]].ignore !== true) {
  840. minVal = groupRanges[groupIds[i]].min;
  841. maxVal = groupRanges[groupIds[i]].max;
  842. if (groupRanges[groupIds[i]].yAxisOrientation != 'right') {
  843. yAxisLeftUsed = true;
  844. minLeft = minLeft > minVal ? minVal : minLeft;
  845. maxLeft = maxLeft < maxVal ? maxVal : maxLeft;
  846. }
  847. else {
  848. yAxisRightUsed = true;
  849. minRight = minRight > minVal ? minVal : minRight;
  850. maxRight = maxRight < maxVal ? maxVal : maxRight;
  851. }
  852. }
  853. }
  854. }
  855. if (yAxisLeftUsed == true) {
  856. this.yAxisLeft.setRange(minLeft, maxLeft);
  857. }
  858. if (yAxisRightUsed == true) {
  859. this.yAxisRight.setRange(minRight, maxRight);
  860. }
  861. }
  862. resized = this._toggleAxisVisiblity(yAxisLeftUsed, this.yAxisLeft) || resized;
  863. resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized;
  864. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  865. this.yAxisLeft.drawIcons = true;
  866. this.yAxisRight.drawIcons = true;
  867. }
  868. else {
  869. this.yAxisLeft.drawIcons = false;
  870. this.yAxisRight.drawIcons = false;
  871. }
  872. this.yAxisRight.master = !yAxisLeftUsed;
  873. if (this.yAxisRight.master == false) {
  874. if (yAxisRightUsed == true) {
  875. this.yAxisLeft.lineOffset = this.yAxisRight.width;
  876. }
  877. else {
  878. this.yAxisLeft.lineOffset = 0;
  879. }
  880. resized = this.yAxisLeft.redraw() || resized;
  881. this.yAxisRight.stepPixels = this.yAxisLeft.stepPixels;
  882. this.yAxisRight.zeroCrossing = this.yAxisLeft.zeroCrossing;
  883. this.yAxisRight.amountOfSteps = this.yAxisLeft.amountOfSteps;
  884. resized = this.yAxisRight.redraw() || resized;
  885. }
  886. else {
  887. resized = this.yAxisRight.redraw() || resized;
  888. }
  889. // clean the accumulated lists
  890. var tempGroups = ['__barStackLeft', '__barStackRight', '__lineStackLeft', '__lineStackRight'];
  891. for (var i = 0; i < tempGroups.length; i++) {
  892. if (groupIds.indexOf(tempGroups[i]) != -1) {
  893. groupIds.splice(groupIds.indexOf(tempGroups[i]), 1);
  894. }
  895. }
  896. return resized;
  897. };
  898. /**
  899. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  900. *
  901. * @param {boolean} axisUsed
  902. * @returns {boolean}
  903. * @private
  904. * @param axis
  905. */
  906. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  907. var changed = false;
  908. if (axisUsed == false) {
  909. if (axis.dom.frame.parentNode && axis.hidden == false) {
  910. axis.hide();
  911. changed = true;
  912. }
  913. }
  914. else {
  915. if (!axis.dom.frame.parentNode && axis.hidden == true) {
  916. axis.show();
  917. changed = true;
  918. }
  919. }
  920. return changed;
  921. };
  922. /**
  923. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  924. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  925. * the yAxis.
  926. *
  927. * @param datapoints
  928. * @returns {Array}
  929. * @private
  930. */
  931. LineGraph.prototype._convertXcoordinates = function (datapoints) {
  932. var toScreen = this.body.util.toScreen;
  933. for (var i = 0; i < datapoints.length; i++) {
  934. datapoints[i].screen_x = toScreen(datapoints[i].x) + this.props.width;
  935. datapoints[i].screen_y = datapoints[i].y; //starting point for range calculations
  936. }
  937. };
  938. /**
  939. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  940. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  941. * the yAxis.
  942. *
  943. * @param datapoints
  944. * @param group
  945. * @returns {Array}
  946. * @private
  947. */
  948. LineGraph.prototype._convertYcoordinates = function (datapoints, group) {
  949. var axis = this.yAxisLeft;
  950. var svgHeight = Number(this.svg.style.height.replace('px', ''));
  951. if (group.options.yAxisOrientation == 'right') {
  952. axis = this.yAxisRight;
  953. }
  954. for (var i = 0; i < datapoints.length; i++) {
  955. datapoints[i].screen_y = Math.round(axis.convertValue(datapoints[i].y));
  956. }
  957. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  958. };
  959. module.exports = LineGraph;