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