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.

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