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.

656 lines
19 KiB

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