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.

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