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.

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