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.

593 lines
18 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 = 'vlabel';
  45. this.dom.label = label;
  46. var inner = document.createElement('div');
  47. inner.className = 'inner';
  48. label.appendChild(inner);
  49. this.dom.inner = inner;
  50. var foreground = document.createElement('div');
  51. foreground.className = 'group';
  52. foreground['timeline-group'] = this;
  53. this.dom.foreground = foreground;
  54. this.dom.background = document.createElement('div');
  55. this.dom.background.className = 'group';
  56. this.dom.axis = document.createElement('div');
  57. this.dom.axis.className = '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'; // TODO: ask jos why this is not none?
  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, 'hidden');
  86. }
  87. else {
  88. util.removeClassName(this.dom.inner, '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, this.style);
  108. this.style = null;
  109. }
  110. if (data && data.style) {
  111. util.addCssText(this.dom.label, 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. var customOrderedItems = null;
  145. if (this.itemSet.options.stack) { // TODO: ugly way to access options...
  146. if (typeof this.itemSet.options.order === 'function' || false) {
  147. customOrderedItems = this._getCustomOrderedItems();
  148. stack.stack(customOrderedItems, margin, true);
  149. }
  150. else {
  151. stack.stack(this.visibleItems, margin, restack);
  152. }
  153. }
  154. else { // no stacking
  155. stack.nostack(this.visibleItems, margin, this.subgroups);
  156. }
  157. // recalculate the height of the group
  158. var height = this._calculateHeight(margin);
  159. // calculate actual size and position
  160. var foreground = this.dom.foreground;
  161. this.top = foreground.offsetTop;
  162. this.left = foreground.offsetLeft;
  163. this.width = foreground.offsetWidth;
  164. resized = util.updateProperty(this, 'height', height) || resized;
  165. // recalculate size of label
  166. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  167. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  168. // apply new height
  169. this.dom.background.style.height = height + 'px';
  170. this.dom.foreground.style.height = height + 'px';
  171. this.dom.label.style.height = height + 'px';
  172. // update vertical position of items after they are re-stacked and the height of the group is calculated
  173. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  174. var item = this.visibleItems[i];
  175. item.repositionY(margin);
  176. }
  177. return resized;
  178. };
  179. /**
  180. * recalculate the height of the group
  181. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  182. * @returns {number} Returns the height
  183. * @private
  184. */
  185. Group.prototype._calculateHeight = function (margin) {
  186. // recalculate the height of the group
  187. var height;
  188. var visibleItems = this.visibleItems;
  189. //var visibleSubgroups = [];
  190. //this.visibleSubgroups = 0;
  191. this.resetSubgroups();
  192. var me = this;
  193. if (visibleItems.length) {
  194. var min = visibleItems[0].top;
  195. var max = visibleItems[0].top + visibleItems[0].height;
  196. util.forEach(visibleItems, function (item) {
  197. min = Math.min(min, item.top);
  198. max = Math.max(max, (item.top + item.height));
  199. if (item.data.subgroup !== undefined) {
  200. me.subgroups[item.data.subgroup].height = Math.max(me.subgroups[item.data.subgroup].height,item.height);
  201. me.subgroups[item.data.subgroup].visible = true;
  202. //if (visibleSubgroups.indexOf(item.data.subgroup) == -1){
  203. // visibleSubgroups.push(item.data.subgroup);
  204. // me.visibleSubgroups += 1;
  205. //}
  206. }
  207. });
  208. if (min > margin.axis) {
  209. // there is an empty gap between the lowest item and the axis
  210. var offset = min - margin.axis;
  211. max -= offset;
  212. util.forEach(visibleItems, function (item) {
  213. item.top -= offset;
  214. });
  215. }
  216. height = max + margin.item.vertical / 2;
  217. }
  218. else {
  219. height = margin.axis + margin.item.vertical;
  220. }
  221. height = Math.max(height, this.props.label.height);
  222. return height;
  223. };
  224. /**
  225. * Show this group: attach to the DOM
  226. */
  227. Group.prototype.show = function() {
  228. if (!this.dom.label.parentNode) {
  229. this.itemSet.dom.labelSet.appendChild(this.dom.label);
  230. }
  231. if (!this.dom.foreground.parentNode) {
  232. this.itemSet.dom.foreground.appendChild(this.dom.foreground);
  233. }
  234. if (!this.dom.background.parentNode) {
  235. this.itemSet.dom.background.appendChild(this.dom.background);
  236. }
  237. if (!this.dom.axis.parentNode) {
  238. this.itemSet.dom.axis.appendChild(this.dom.axis);
  239. }
  240. };
  241. /**
  242. * Hide this group: remove from the DOM
  243. */
  244. Group.prototype.hide = function() {
  245. var label = this.dom.label;
  246. if (label.parentNode) {
  247. label.parentNode.removeChild(label);
  248. }
  249. var foreground = this.dom.foreground;
  250. if (foreground.parentNode) {
  251. foreground.parentNode.removeChild(foreground);
  252. }
  253. var background = this.dom.background;
  254. if (background.parentNode) {
  255. background.parentNode.removeChild(background);
  256. }
  257. var axis = this.dom.axis;
  258. if (axis.parentNode) {
  259. axis.parentNode.removeChild(axis);
  260. }
  261. };
  262. /**
  263. * Add an item to the group
  264. * @param {Item} item
  265. */
  266. Group.prototype.add = function(item) {
  267. this.items[item.id] = item;
  268. item.setParent(this);
  269. // add to
  270. if (item.data.subgroup !== undefined) {
  271. if (this.subgroups[item.data.subgroup] === undefined) {
  272. this.subgroups[item.data.subgroup] = {height:0, visible: false, index:this.subgroupIndex, items: []};
  273. this.subgroupIndex++;
  274. }
  275. this.subgroups[item.data.subgroup].items.push(item);
  276. }
  277. this.orderSubgroups();
  278. if (this.visibleItems.indexOf(item) == -1) {
  279. var range = this.itemSet.body.range; // TODO: not nice accessing the range like this
  280. this._checkIfVisible(item, this.visibleItems, range);
  281. }
  282. };
  283. Group.prototype.orderSubgroups = function() {
  284. if (this.subgroupOrderer !== undefined) {
  285. var sortArray = [];
  286. if (typeof this.subgroupOrderer == 'string') {
  287. for (var subgroup in this.subgroups) {
  288. sortArray.push({subgroup: subgroup, sortField: this.subgroups[subgroup].items[0].data[this.subgroupOrderer]})
  289. }
  290. sortArray.sort(function (a, b) {
  291. return a.sortField - b.sortField;
  292. })
  293. }
  294. else if (typeof this.subgroupOrderer == 'function') {
  295. for (var subgroup in this.subgroups) {
  296. sortArray.push(this.subgroups[subgroup].items[0].data);
  297. }
  298. sortArray.sort(this.subgroupOrderer);
  299. }
  300. if (sortArray.length > 0) {
  301. for (var i = 0; i < sortArray.length; i++) {
  302. this.subgroups[sortArray[i].subgroup].index = i;
  303. }
  304. }
  305. }
  306. };
  307. Group.prototype.resetSubgroups = function() {
  308. for (var subgroup in this.subgroups) {
  309. if (this.subgroups.hasOwnProperty(subgroup)) {
  310. this.subgroups[subgroup].visible = false;
  311. }
  312. }
  313. };
  314. /**
  315. * Remove an item from the group
  316. * @param {Item} item
  317. */
  318. Group.prototype.remove = function(item) {
  319. delete this.items[item.id];
  320. item.setParent(null);
  321. // remove from visible items
  322. var index = this.visibleItems.indexOf(item);
  323. if (index != -1) this.visibleItems.splice(index, 1);
  324. // TODO: also remove from ordered items?
  325. };
  326. /**
  327. * Remove an item from the corresponding DataSet
  328. * @param {Item} item
  329. */
  330. Group.prototype.removeFromDataSet = function(item) {
  331. this.itemSet.removeItem(item.id);
  332. };
  333. /**
  334. * Reorder the items
  335. */
  336. Group.prototype.order = function() {
  337. var array = util.toArray(this.items);
  338. var startArray = [];
  339. var endArray = [];
  340. for (var i = 0; i < array.length; i++) {
  341. if (array[i].data.end !== undefined) {
  342. endArray.push(array[i]);
  343. }
  344. startArray.push(array[i]);
  345. }
  346. this.orderedItems = {
  347. byStart: startArray,
  348. byEnd: endArray
  349. };
  350. stack.orderByStart(this.orderedItems.byStart);
  351. stack.orderByEnd(this.orderedItems.byEnd);
  352. };
  353. /**
  354. * Update the visible items
  355. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  356. * @param {Item[]} visibleItems The previously visible items.
  357. * @param {{start: number, end: number}} range Visible range
  358. * @return {Item[]} visibleItems The new visible items.
  359. * @private
  360. */
  361. Group.prototype._updateVisibleItems = function(orderedItems, oldVisibleItems, range) {
  362. var visibleItems = [];
  363. var visibleItemsLookup = {}; // we keep this to quickly look up if an item already exists in the list without using indexOf on visibleItems
  364. var interval = (range.end - range.start) / 4;
  365. var lowerBound = range.start - interval;
  366. var upperBound = range.end + interval;
  367. var item, i;
  368. // this function is used to do the binary search.
  369. var searchFunction = function (value) {
  370. if (value < lowerBound) {return -1;}
  371. else if (value <= upperBound) {return 0;}
  372. else {return 1;}
  373. }
  374. // first check if the items that were in view previously are still in view.
  375. // IMPORTANT: this handles the case for the items with startdate before the window and enddate after the window!
  376. // also cleans up invisible items.
  377. if (oldVisibleItems.length > 0) {
  378. for (i = 0; i < oldVisibleItems.length; i++) {
  379. this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range);
  380. }
  381. }
  382. // we do a binary search for the items that have only start values.
  383. var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data','start');
  384. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the start values.
  385. this._traceVisible(initialPosByStart, orderedItems.byStart, visibleItems, visibleItemsLookup, function (item) {
  386. return (item.data.start < lowerBound || item.data.start > upperBound);
  387. });
  388. // if the window has changed programmatically without overlapping the old window, the ranged items with start < lowerBound and end > upperbound are not shown.
  389. // We therefore have to brute force check all items in the byEnd list
  390. if (this.checkRangedItems == true) {
  391. this.checkRangedItems = false;
  392. for (i = 0; i < orderedItems.byEnd.length; i++) {
  393. this._checkIfVisibleWithReference(orderedItems.byEnd[i], visibleItems, visibleItemsLookup, range);
  394. }
  395. }
  396. else {
  397. // we do a binary search for the items that have defined end times.
  398. var initialPosByEnd = util.binarySearchCustom(orderedItems.byEnd, searchFunction, 'data','end');
  399. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the end values.
  400. this._traceVisible(initialPosByEnd, orderedItems.byEnd, visibleItems, visibleItemsLookup, function (item) {
  401. return (item.data.end < lowerBound || item.data.end > upperBound);
  402. });
  403. }
  404. // finally, we reposition all the visible items.
  405. for (i = 0; i < visibleItems.length; i++) {
  406. item = visibleItems[i];
  407. if (!item.displayed) item.show();
  408. // reposition item horizontally
  409. item.repositionX();
  410. }
  411. // debug
  412. //console.log("new line")
  413. //if (this.groupId == null) {
  414. // for (i = 0; i < orderedItems.byStart.length; i++) {
  415. // item = orderedItems.byStart[i].data;
  416. // console.log('start',i,initialPosByStart, item.start.valueOf(), item.content, item.start >= lowerBound && item.start <= upperBound,i == initialPosByStart ? "<------------------- HEREEEE" : "")
  417. // }
  418. // for (i = 0; i < orderedItems.byEnd.length; i++) {
  419. // item = orderedItems.byEnd[i].data;
  420. // console.log('rangeEnd',i,initialPosByEnd, item.end.valueOf(), item.content, item.end >= range.start && item.end <= range.end,i == initialPosByEnd ? "<------------------- HEREEEE" : "")
  421. // }
  422. //}
  423. return visibleItems;
  424. };
  425. Group.prototype._getCustomOrderedItems = function () {
  426. var customOrderedItems = this.orderedItems.byStart.filter(function (item) {
  427. return item.height !== 0 || item.width !== 0;
  428. });
  429. var me = this;
  430. customOrderedItems.sort(function (a, b) {
  431. return me.itemSet.options.order(a.data, b.data);
  432. });
  433. customOrderedItems.forEach(function (item) {
  434. item.repositionX();
  435. });
  436. return customOrderedItems;
  437. };
  438. Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) {
  439. var item;
  440. var i;
  441. if (initialPos != -1) {
  442. for (i = initialPos; i >= 0; i--) {
  443. item = items[i];
  444. if (breakCondition(item)) {
  445. break;
  446. }
  447. else {
  448. if (visibleItemsLookup[item.id] === undefined) {
  449. visibleItemsLookup[item.id] = true;
  450. visibleItems.push(item);
  451. }
  452. }
  453. }
  454. for (i = initialPos + 1; i < items.length; i++) {
  455. item = items[i];
  456. if (breakCondition(item)) {
  457. break;
  458. }
  459. else {
  460. if (visibleItemsLookup[item.id] === undefined) {
  461. visibleItemsLookup[item.id] = true;
  462. visibleItems.push(item);
  463. }
  464. }
  465. }
  466. }
  467. }
  468. /**
  469. * this function is very similar to the _checkIfInvisible() but it does not
  470. * return booleans, hides the item if it should not be seen and always adds to
  471. * the visibleItems.
  472. * this one is for brute forcing and hiding.
  473. *
  474. * @param {Item} item
  475. * @param {Array} visibleItems
  476. * @param {{start:number, end:number}} range
  477. * @private
  478. */
  479. Group.prototype._checkIfVisible = function(item, visibleItems, range) {
  480. if (item.isVisible(range)) {
  481. if (!item.displayed) item.show();
  482. // reposition item horizontally
  483. item.repositionX();
  484. visibleItems.push(item);
  485. }
  486. else {
  487. if (item.displayed) item.hide();
  488. }
  489. };
  490. /**
  491. * this function is very similar to the _checkIfInvisible() but it does not
  492. * return booleans, hides the item if it should not be seen and always adds to
  493. * the visibleItems.
  494. * this one is for brute forcing and hiding.
  495. *
  496. * @param {Item} item
  497. * @param {Array} visibleItems
  498. * @param {{start:number, end:number}} range
  499. * @private
  500. */
  501. Group.prototype._checkIfVisibleWithReference = function(item, visibleItems, visibleItemsLookup, range) {
  502. if (item.isVisible(range)) {
  503. if (visibleItemsLookup[item.id] === undefined) {
  504. visibleItemsLookup[item.id] = true;
  505. visibleItems.push(item);
  506. }
  507. }
  508. else {
  509. if (item.displayed) item.hide();
  510. }
  511. };
  512. module.exports = Group;