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.

597 lines
18 KiB

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