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.

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