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.

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