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.

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