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.

611 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. }
  354. }
  355. };
  356. /**
  357. * Remove an item from the corresponding DataSet
  358. * @param {Item} item
  359. */
  360. Group.prototype.removeFromDataSet = function(item) {
  361. this.itemSet.removeItem(item.id);
  362. };
  363. /**
  364. * Reorder the items
  365. */
  366. Group.prototype.order = function() {
  367. var array = util.toArray(this.items);
  368. var startArray = [];
  369. var endArray = [];
  370. for (var i = 0; i < array.length; i++) {
  371. if (array[i].data.end !== undefined) {
  372. endArray.push(array[i]);
  373. }
  374. startArray.push(array[i]);
  375. }
  376. this.orderedItems = {
  377. byStart: startArray,
  378. byEnd: endArray
  379. };
  380. stack.orderByStart(this.orderedItems.byStart);
  381. stack.orderByEnd(this.orderedItems.byEnd);
  382. };
  383. /**
  384. * Update the visible items
  385. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  386. * @param {Item[]} visibleItems The previously visible items.
  387. * @param {{start: number, end: number}} range Visible range
  388. * @return {Item[]} visibleItems The new visible items.
  389. * @private
  390. */
  391. Group.prototype._updateVisibleItems = function(orderedItems, oldVisibleItems, range) {
  392. var visibleItems = [];
  393. var visibleItemsLookup = {}; // we keep this to quickly look up if an item already exists in the list without using indexOf on visibleItems
  394. var interval = (range.end - range.start) / 4;
  395. var lowerBound = range.start - interval;
  396. var upperBound = range.end + interval;
  397. var item, i;
  398. // this function is used to do the binary search.
  399. var searchFunction = function (value) {
  400. if (value < lowerBound) {return -1;}
  401. else if (value <= upperBound) {return 0;}
  402. else {return 1;}
  403. }
  404. // first check if the items that were in view previously are still in view.
  405. // IMPORTANT: this handles the case for the items with startdate before the window and enddate after the window!
  406. // also cleans up invisible items.
  407. if (oldVisibleItems.length > 0) {
  408. for (i = 0; i < oldVisibleItems.length; i++) {
  409. this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range);
  410. }
  411. }
  412. // we do a binary search for the items that have only start values.
  413. var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data','start');
  414. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the start values.
  415. this._traceVisible(initialPosByStart, orderedItems.byStart, visibleItems, visibleItemsLookup, function (item) {
  416. return (item.data.start < lowerBound || item.data.start > upperBound);
  417. });
  418. // if the window has changed programmatically without overlapping the old window, the ranged items with start < lowerBound and end > upperbound are not shown.
  419. // We therefore have to brute force check all items in the byEnd list
  420. if (this.checkRangedItems == true) {
  421. this.checkRangedItems = false;
  422. for (i = 0; i < orderedItems.byEnd.length; i++) {
  423. this._checkIfVisibleWithReference(orderedItems.byEnd[i], visibleItems, visibleItemsLookup, range);
  424. }
  425. }
  426. else {
  427. // we do a binary search for the items that have defined end times.
  428. var initialPosByEnd = util.binarySearchCustom(orderedItems.byEnd, searchFunction, 'data','end');
  429. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the end values.
  430. this._traceVisible(initialPosByEnd, orderedItems.byEnd, visibleItems, visibleItemsLookup, function (item) {
  431. return (item.data.end < lowerBound || item.data.end > upperBound);
  432. });
  433. }
  434. // finally, we reposition all the visible items.
  435. for (i = 0; i < visibleItems.length; i++) {
  436. item = visibleItems[i];
  437. if (!item.displayed) item.show();
  438. // reposition item horizontally
  439. item.repositionX();
  440. }
  441. // debug
  442. //console.log("new line")
  443. //if (this.groupId == null) {
  444. // for (i = 0; i < orderedItems.byStart.length; i++) {
  445. // item = orderedItems.byStart[i].data;
  446. // console.log('start',i,initialPosByStart, item.start.valueOf(), item.content, item.start >= lowerBound && item.start <= upperBound,i == initialPosByStart ? "<------------------- HEREEEE" : "")
  447. // }
  448. // for (i = 0; i < orderedItems.byEnd.length; i++) {
  449. // item = orderedItems.byEnd[i].data;
  450. // console.log('rangeEnd',i,initialPosByEnd, item.end.valueOf(), item.content, item.end >= range.start && item.end <= range.end,i == initialPosByEnd ? "<------------------- HEREEEE" : "")
  451. // }
  452. //}
  453. return visibleItems;
  454. };
  455. Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) {
  456. var item;
  457. var i;
  458. if (initialPos != -1) {
  459. for (i = initialPos; i >= 0; i--) {
  460. item = items[i];
  461. if (breakCondition(item)) {
  462. break;
  463. }
  464. else {
  465. if (visibleItemsLookup[item.id] === undefined) {
  466. visibleItemsLookup[item.id] = true;
  467. visibleItems.push(item);
  468. }
  469. }
  470. }
  471. for (i = initialPos + 1; i < items.length; i++) {
  472. item = items[i];
  473. if (breakCondition(item)) {
  474. break;
  475. }
  476. else {
  477. if (visibleItemsLookup[item.id] === undefined) {
  478. visibleItemsLookup[item.id] = true;
  479. visibleItems.push(item);
  480. }
  481. }
  482. }
  483. }
  484. }
  485. /**
  486. * this function is very similar to the _checkIfInvisible() but it does not
  487. * return booleans, hides the item if it should not be seen and always adds to
  488. * the visibleItems.
  489. * this one is for brute forcing and hiding.
  490. *
  491. * @param {Item} item
  492. * @param {Array} visibleItems
  493. * @param {{start:number, end:number}} range
  494. * @private
  495. */
  496. Group.prototype._checkIfVisible = function(item, visibleItems, range) {
  497. if (item.isVisible(range)) {
  498. if (!item.displayed) item.show();
  499. // reposition item horizontally
  500. item.repositionX();
  501. visibleItems.push(item);
  502. }
  503. else {
  504. if (item.displayed) item.hide();
  505. }
  506. };
  507. /**
  508. * this function is very similar to the _checkIfInvisible() but it does not
  509. * return booleans, hides the item if it should not be seen and always adds to
  510. * the visibleItems.
  511. * this one is for brute forcing and hiding.
  512. *
  513. * @param {Item} item
  514. * @param {Array} visibleItems
  515. * @param {{start:number, end:number}} range
  516. * @private
  517. */
  518. Group.prototype._checkIfVisibleWithReference = function(item, visibleItems, visibleItemsLookup, range) {
  519. if (item.isVisible(range)) {
  520. if (visibleItemsLookup[item.id] === undefined) {
  521. visibleItemsLookup[item.id] = true;
  522. visibleItems.push(item);
  523. }
  524. }
  525. else {
  526. if (item.displayed) item.hide();
  527. }
  528. };
  529. module.exports = Group;