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.

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