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.

565 lines
17 KiB

10 years ago
10 years ago
10 years ago
10 years ago
  1. var util = require('../../util');
  2. var stack = require('../Stack');
  3. var RangeItem = require('./item/RangeItem');
  4. /**
  5. * @constructor Group
  6. * @param {Number | String} groupId
  7. * @param {Object} data
  8. * @param {ItemSet} itemSet
  9. */
  10. function Group (groupId, data, itemSet) {
  11. this.groupId = groupId;
  12. this.subgroups = {};
  13. this.subgroupIndex = 0;
  14. this.subgroupOrderer = data && data.subgroupOrder;
  15. this.itemSet = itemSet;
  16. this.dom = {};
  17. this.props = {
  18. label: {
  19. width: 0,
  20. height: 0
  21. }
  22. };
  23. this.className = null;
  24. this.items = {}; // items filtered by groupId of this group
  25. this.visibleItems = []; // items currently visible in window
  26. this.orderedItems = {
  27. byStart: [],
  28. byEnd: []
  29. };
  30. this.checkRangedItems = false; // needed to refresh the ranged items if the window is programatically changed with NO overlap.
  31. var me = this;
  32. this.itemSet.body.emitter.on("checkRangedItems", function () {
  33. me.checkRangedItems = true;
  34. })
  35. this._create();
  36. this.setData(data);
  37. }
  38. /**
  39. * Create DOM elements for the group
  40. * @private
  41. */
  42. Group.prototype._create = function() {
  43. var label = document.createElement('div');
  44. label.className = 'vis-label';
  45. this.dom.label = label;
  46. var inner = document.createElement('div');
  47. inner.className = 'vis-inner';
  48. label.appendChild(inner);
  49. this.dom.inner = inner;
  50. var foreground = document.createElement('div');
  51. foreground.className = 'vis-group';
  52. foreground['timeline-group'] = this;
  53. this.dom.foreground = foreground;
  54. this.dom.background = document.createElement('div');
  55. this.dom.background.className = 'vis-group';
  56. this.dom.axis = document.createElement('div');
  57. this.dom.axis.className = 'vis-group';
  58. // create a hidden marker to detect when the Timelines container is attached
  59. // to the DOM, or the style of a parent of the Timeline is changed from
  60. // display:none is changed to visible.
  61. this.dom.marker = document.createElement('div');
  62. this.dom.marker.style.visibility = 'hidden';
  63. this.dom.marker.innerHTML = '?';
  64. this.dom.background.appendChild(this.dom.marker);
  65. };
  66. /**
  67. * Set the group data for this group
  68. * @param {Object} data Group data, can contain properties content and className
  69. */
  70. Group.prototype.setData = function(data) {
  71. // update contents
  72. var content = data && data.content;
  73. if (content instanceof Element) {
  74. this.dom.inner.appendChild(content);
  75. }
  76. else if (content !== undefined && content !== null) {
  77. this.dom.inner.innerHTML = content;
  78. }
  79. else {
  80. this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null
  81. }
  82. // update title
  83. this.dom.label.title = data && data.title || '';
  84. if (!this.dom.inner.firstChild) {
  85. util.addClassName(this.dom.inner, 'vis-hidden');
  86. }
  87. else {
  88. util.removeClassName(this.dom.inner, 'vis-hidden');
  89. }
  90. // update className
  91. var className = data && data.className || null;
  92. if (className != this.className) {
  93. if (this.className) {
  94. util.removeClassName(this.dom.label, this.className);
  95. util.removeClassName(this.dom.foreground, this.className);
  96. util.removeClassName(this.dom.background, this.className);
  97. util.removeClassName(this.dom.axis, this.className);
  98. }
  99. util.addClassName(this.dom.label, className);
  100. util.addClassName(this.dom.foreground, className);
  101. util.addClassName(this.dom.background, className);
  102. util.addClassName(this.dom.axis, className);
  103. this.className = className;
  104. }
  105. // update style
  106. if (this.style) {
  107. util.removeCssText(this.dom.label, 'vis-' + this.style);
  108. this.style = null;
  109. }
  110. if (data && data.style) {
  111. util.addCssText(this.dom.label, 'vis-' + data.style);
  112. this.style = data.style;
  113. }
  114. };
  115. /**
  116. * Get the width of the group label
  117. * @return {number} width
  118. */
  119. Group.prototype.getLabelWidth = function() {
  120. return this.props.label.width;
  121. };
  122. /**
  123. * Repaint this group
  124. * @param {{start: number, end: number}} range
  125. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  126. * @param {boolean} [restack=false] Force restacking of all items
  127. * @return {boolean} Returns true if the group is resized
  128. */
  129. Group.prototype.redraw = function(range, margin, restack) {
  130. var resized = false;
  131. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  132. // force recalculation of the height of the items when the marker height changed
  133. // (due to the Timeline being attached to the DOM or changed from display:none to visible)
  134. var markerHeight = this.dom.marker.clientHeight;
  135. if (markerHeight != this.lastMarkerHeight) {
  136. this.lastMarkerHeight = markerHeight;
  137. util.forEach(this.items, function (item) {
  138. item.dirty = true;
  139. if (item.displayed) item.redraw();
  140. });
  141. restack = true;
  142. }
  143. // reposition visible items vertically
  144. if (this.itemSet.options.stack) { // TODO: ugly way to access options...
  145. stack.stack(this.visibleItems, margin, restack);
  146. }
  147. else { // no stacking
  148. stack.nostack(this.visibleItems, margin, this.subgroups);
  149. }
  150. // recalculate the height of the group
  151. var height = this._calculateHeight(margin);
  152. // calculate actual size and position
  153. var foreground = this.dom.foreground;
  154. this.top = foreground.offsetTop;
  155. this.left = foreground.offsetLeft;
  156. this.width = foreground.offsetWidth;
  157. resized = util.updateProperty(this, 'height', height) || resized;
  158. // recalculate size of label
  159. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  160. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  161. // apply new height
  162. this.dom.background.style.height = height + 'px';
  163. this.dom.foreground.style.height = height + 'px';
  164. this.dom.label.style.height = height + 'px';
  165. // update vertical position of items after they are re-stacked and the height of the group is calculated
  166. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  167. var item = this.visibleItems[i];
  168. item.repositionY(margin);
  169. }
  170. return resized;
  171. };
  172. /**
  173. * recalculate the height of the group
  174. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  175. * @returns {number} Returns the height
  176. * @private
  177. */
  178. Group.prototype._calculateHeight = function (margin) {
  179. // recalculate the height of the group
  180. var height;
  181. var visibleItems = this.visibleItems;
  182. //var visibleSubgroups = [];
  183. //this.visibleSubgroups = 0;
  184. this.resetSubgroups();
  185. var me = this;
  186. if (visibleItems.length > 0) {
  187. var min = visibleItems[0].top;
  188. var max = visibleItems[0].top + visibleItems[0].height;
  189. util.forEach(visibleItems, function (item) {
  190. min = Math.min(min, item.top);
  191. max = Math.max(max, (item.top + item.height));
  192. if (item.data.subgroup !== undefined) {
  193. me.subgroups[item.data.subgroup].height = Math.max(me.subgroups[item.data.subgroup].height,item.height);
  194. me.subgroups[item.data.subgroup].visible = true;
  195. }
  196. });
  197. if (min > margin.axis) {
  198. // there is an empty gap between the lowest item and the axis
  199. var offset = min - margin.axis;
  200. max -= offset;
  201. util.forEach(visibleItems, function (item) {
  202. item.top -= offset;
  203. });
  204. }
  205. height = max + margin.item.vertical / 2;
  206. }
  207. else {
  208. height = margin.axis + margin.item.vertical;
  209. }
  210. height = Math.max(height, this.props.label.height);
  211. return height;
  212. };
  213. /**
  214. * Show this group: attach to the DOM
  215. */
  216. Group.prototype.show = function() {
  217. if (!this.dom.label.parentNode) {
  218. this.itemSet.dom.labelSet.appendChild(this.dom.label);
  219. }
  220. if (!this.dom.foreground.parentNode) {
  221. this.itemSet.dom.foreground.appendChild(this.dom.foreground);
  222. }
  223. if (!this.dom.background.parentNode) {
  224. this.itemSet.dom.background.appendChild(this.dom.background);
  225. }
  226. if (!this.dom.axis.parentNode) {
  227. this.itemSet.dom.axis.appendChild(this.dom.axis);
  228. }
  229. };
  230. /**
  231. * Hide this group: remove from the DOM
  232. */
  233. Group.prototype.hide = function() {
  234. var label = this.dom.label;
  235. if (label.parentNode) {
  236. label.parentNode.removeChild(label);
  237. }
  238. var foreground = this.dom.foreground;
  239. if (foreground.parentNode) {
  240. foreground.parentNode.removeChild(foreground);
  241. }
  242. var background = this.dom.background;
  243. if (background.parentNode) {
  244. background.parentNode.removeChild(background);
  245. }
  246. var axis = this.dom.axis;
  247. if (axis.parentNode) {
  248. axis.parentNode.removeChild(axis);
  249. }
  250. };
  251. /**
  252. * Add an item to the group
  253. * @param {Item} item
  254. */
  255. Group.prototype.add = function(item) {
  256. this.items[item.id] = item;
  257. item.setParent(this);
  258. // add to
  259. if (item.data.subgroup !== undefined) {
  260. if (this.subgroups[item.data.subgroup] === undefined) {
  261. this.subgroups[item.data.subgroup] = {height:0, visible: false, index:this.subgroupIndex, items: []};
  262. this.subgroupIndex++;
  263. }
  264. this.subgroups[item.data.subgroup].items.push(item);
  265. }
  266. this.orderSubgroups();
  267. if (this.visibleItems.indexOf(item) == -1) {
  268. var range = this.itemSet.body.range; // TODO: not nice accessing the range like this
  269. this._checkIfVisible(item, this.visibleItems, range);
  270. }
  271. };
  272. Group.prototype.orderSubgroups = function() {
  273. if (this.subgroupOrderer !== undefined) {
  274. var sortArray = [];
  275. if (typeof this.subgroupOrderer == 'string') {
  276. for (var subgroup in this.subgroups) {
  277. sortArray.push({subgroup: subgroup, sortField: this.subgroups[subgroup].items[0].data[this.subgroupOrderer]})
  278. }
  279. sortArray.sort(function (a, b) {
  280. return a.sortField - b.sortField;
  281. })
  282. }
  283. else if (typeof this.subgroupOrderer == 'function') {
  284. for (var subgroup in this.subgroups) {
  285. sortArray.push(this.subgroups[subgroup].items[0].data);
  286. }
  287. sortArray.sort(this.subgroupOrderer);
  288. }
  289. if (sortArray.length > 0) {
  290. for (var i = 0; i < sortArray.length; i++) {
  291. this.subgroups[sortArray[i].subgroup].index = i;
  292. }
  293. }
  294. }
  295. };
  296. Group.prototype.resetSubgroups = function() {
  297. for (var subgroup in this.subgroups) {
  298. if (this.subgroups.hasOwnProperty(subgroup)) {
  299. this.subgroups[subgroup].visible = false;
  300. }
  301. }
  302. };
  303. /**
  304. * Remove an item from the group
  305. * @param {Item} item
  306. */
  307. Group.prototype.remove = function(item) {
  308. delete this.items[item.id];
  309. item.setParent(null);
  310. // remove from visible items
  311. var index = this.visibleItems.indexOf(item);
  312. if (index != -1) this.visibleItems.splice(index, 1);
  313. // TODO: also remove from ordered items?
  314. };
  315. /**
  316. * Remove an item from the corresponding DataSet
  317. * @param {Item} item
  318. */
  319. Group.prototype.removeFromDataSet = function(item) {
  320. this.itemSet.removeItem(item.id);
  321. };
  322. /**
  323. * Reorder the items
  324. */
  325. Group.prototype.order = function() {
  326. var array = util.toArray(this.items);
  327. var startArray = [];
  328. var endArray = [];
  329. for (var i = 0; i < array.length; i++) {
  330. if (array[i].data.end !== undefined) {
  331. endArray.push(array[i]);
  332. }
  333. startArray.push(array[i]);
  334. }
  335. this.orderedItems = {
  336. byStart: startArray,
  337. byEnd: endArray
  338. };
  339. stack.orderByStart(this.orderedItems.byStart);
  340. stack.orderByEnd(this.orderedItems.byEnd);
  341. };
  342. /**
  343. * Update the visible items
  344. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  345. * @param {Item[]} visibleItems The previously visible items.
  346. * @param {{start: number, end: number}} range Visible range
  347. * @return {Item[]} visibleItems The new visible items.
  348. * @private
  349. */
  350. Group.prototype._updateVisibleItems = function(orderedItems, oldVisibleItems, range) {
  351. var visibleItems = [];
  352. var visibleItemsLookup = {}; // we keep this to quickly look up if an item already exists in the list without using indexOf on visibleItems
  353. var interval = (range.end - range.start) / 4;
  354. var lowerBound = range.start - interval;
  355. var upperBound = range.end + interval;
  356. var item, i;
  357. // this function is used to do the binary search.
  358. var searchFunction = function (value) {
  359. if (value < lowerBound) {return -1;}
  360. else if (value <= upperBound) {return 0;}
  361. else {return 1;}
  362. }
  363. // first check if the items that were in view previously are still in view.
  364. // IMPORTANT: this handles the case for the items with startdate before the window and enddate after the window!
  365. // also cleans up invisible items.
  366. if (oldVisibleItems.length > 0) {
  367. for (i = 0; i < oldVisibleItems.length; i++) {
  368. this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range);
  369. }
  370. }
  371. // we do a binary search for the items that have only start values.
  372. var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data','start');
  373. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the start values.
  374. this._traceVisible(initialPosByStart, orderedItems.byStart, visibleItems, visibleItemsLookup, function (item) {
  375. return (item.data.start < lowerBound || item.data.start > upperBound);
  376. });
  377. // if the window has changed programmatically without overlapping the old window, the ranged items with start < lowerBound and end > upperbound are not shown.
  378. // We therefore have to brute force check all items in the byEnd list
  379. if (this.checkRangedItems == true) {
  380. this.checkRangedItems = false;
  381. for (i = 0; i < orderedItems.byEnd.length; i++) {
  382. this._checkIfVisibleWithReference(orderedItems.byEnd[i], visibleItems, visibleItemsLookup, range);
  383. }
  384. }
  385. else {
  386. // we do a binary search for the items that have defined end times.
  387. var initialPosByEnd = util.binarySearchCustom(orderedItems.byEnd, searchFunction, 'data','end');
  388. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the end values.
  389. this._traceVisible(initialPosByEnd, orderedItems.byEnd, visibleItems, visibleItemsLookup, function (item) {
  390. return (item.data.end < lowerBound || item.data.end > upperBound);
  391. });
  392. }
  393. // finally, we reposition all the visible items.
  394. for (i = 0; i < visibleItems.length; i++) {
  395. item = visibleItems[i];
  396. if (!item.displayed) item.show();
  397. // reposition item horizontally
  398. item.repositionX();
  399. }
  400. // debug
  401. //console.log("new line")
  402. //if (this.groupId == null) {
  403. // for (i = 0; i < orderedItems.byStart.length; i++) {
  404. // item = orderedItems.byStart[i].data;
  405. // console.log('start',i,initialPosByStart, item.start.valueOf(), item.content, item.start >= lowerBound && item.start <= upperBound,i == initialPosByStart ? "<------------------- HEREEEE" : "")
  406. // }
  407. // for (i = 0; i < orderedItems.byEnd.length; i++) {
  408. // item = orderedItems.byEnd[i].data;
  409. // console.log('rangeEnd',i,initialPosByEnd, item.end.valueOf(), item.content, item.end >= range.start && item.end <= range.end,i == initialPosByEnd ? "<------------------- HEREEEE" : "")
  410. // }
  411. //}
  412. return visibleItems;
  413. };
  414. Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) {
  415. var item;
  416. var i;
  417. if (initialPos != -1) {
  418. for (i = initialPos; i >= 0; i--) {
  419. item = items[i];
  420. if (breakCondition(item)) {
  421. break;
  422. }
  423. else {
  424. if (visibleItemsLookup[item.id] === undefined) {
  425. visibleItemsLookup[item.id] = true;
  426. visibleItems.push(item);
  427. }
  428. }
  429. }
  430. for (i = initialPos + 1; i < items.length; i++) {
  431. item = items[i];
  432. if (breakCondition(item)) {
  433. break;
  434. }
  435. else {
  436. if (visibleItemsLookup[item.id] === undefined) {
  437. visibleItemsLookup[item.id] = true;
  438. visibleItems.push(item);
  439. }
  440. }
  441. }
  442. }
  443. }
  444. /**
  445. * this function is very similar to the _checkIfInvisible() but it does not
  446. * return booleans, hides the item if it should not be seen and always adds to
  447. * the visibleItems.
  448. * this one is for brute forcing and hiding.
  449. *
  450. * @param {Item} item
  451. * @param {Array} visibleItems
  452. * @param {{start:number, end:number}} range
  453. * @private
  454. */
  455. Group.prototype._checkIfVisible = function(item, visibleItems, range) {
  456. if (item.isVisible(range)) {
  457. if (!item.displayed) item.show();
  458. // reposition item horizontally
  459. item.repositionX();
  460. visibleItems.push(item);
  461. }
  462. else {
  463. if (item.displayed) item.hide();
  464. }
  465. };
  466. /**
  467. * this function is very similar to the _checkIfInvisible() but it does not
  468. * return booleans, hides the item if it should not be seen and always adds to
  469. * the visibleItems.
  470. * this one is for brute forcing and hiding.
  471. *
  472. * @param {Item} item
  473. * @param {Array} visibleItems
  474. * @param {{start:number, end:number}} range
  475. * @private
  476. */
  477. Group.prototype._checkIfVisibleWithReference = function(item, visibleItems, visibleItemsLookup, range) {
  478. if (item.isVisible(range)) {
  479. if (visibleItemsLookup[item.id] === undefined) {
  480. visibleItemsLookup[item.id] = true;
  481. visibleItems.push(item);
  482. }
  483. }
  484. else {
  485. if (item.displayed) item.hide();
  486. }
  487. };
  488. module.exports = Group;