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.

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