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.

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