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.

980 lines
29 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. /**
  4. * @param {number | string} groupId
  5. * @param {Object} data
  6. * @param {ItemSet} itemSet
  7. * @constructor Group
  8. */
  9. function Group (groupId, data, itemSet) {
  10. this.groupId = groupId;
  11. this.subgroups = {};
  12. this.subgroupStack = {};
  13. this.subgroupStackAll = false;
  14. this.doInnerStack = false;
  15. this.shouldBailStackItems = false;
  16. this.subgroupIndex = 0;
  17. this.subgroupOrderer = data && data.subgroupOrder;
  18. this.itemSet = itemSet;
  19. this.isVisible = null;
  20. this.stackDirty = true; // if true, items will be restacked on next redraw
  21. if (data && data.nestedGroups) {
  22. this.nestedGroups = data.nestedGroups;
  23. if (data.showNested == false) {
  24. this.showNested = false;
  25. } else {
  26. this.showNested = true;
  27. }
  28. }
  29. if (data && data.subgroupStack) {
  30. if (typeof data.subgroupStack === "boolean") {
  31. this.doInnerStack = data.subgroupStack;
  32. this.subgroupStackAll = data.subgroupStack;
  33. }
  34. else {
  35. // We might be doing stacking on specific sub groups, but only
  36. // if at least one is set to do stacking
  37. for(var key in data.subgroupStack) {
  38. this.subgroupStack[key] = data.subgroupStack[key];
  39. this.doInnerStack = this.doInnerStack || data.subgroupStack[key];
  40. }
  41. }
  42. }
  43. if (data && data.heightMode) {
  44. this.heightMode = data.heightMode;
  45. } else {
  46. this.heightMode = itemSet.options.groupHeightMode;
  47. }
  48. this.nestedInGroup = null;
  49. this.dom = {};
  50. this.props = {
  51. label: {
  52. width: 0,
  53. height: 0
  54. }
  55. };
  56. this.className = null;
  57. this.items = {}; // items filtered by groupId of this group
  58. this.visibleItems = []; // items currently visible in window
  59. this.itemsInRange = []; // items currently in range
  60. this.orderedItems = {
  61. byStart: [],
  62. byEnd: []
  63. };
  64. this.checkRangedItems = false; // needed to refresh the ranged items if the window is programatically changed with NO overlap.
  65. var me = this;
  66. this.itemSet.body.emitter.on("checkRangedItems", function () {
  67. me.checkRangedItems = true;
  68. })
  69. this._create();
  70. this.setData(data);
  71. }
  72. /**
  73. * Create DOM elements for the group
  74. * @private
  75. */
  76. Group.prototype._create = function() {
  77. var label = document.createElement('div');
  78. if (this.itemSet.options.groupEditable.order) {
  79. label.className = 'vis-label draggable';
  80. } else {
  81. label.className = 'vis-label';
  82. }
  83. this.dom.label = label;
  84. var inner = document.createElement('div');
  85. inner.className = 'vis-inner';
  86. label.appendChild(inner);
  87. this.dom.inner = inner;
  88. var foreground = document.createElement('div');
  89. foreground.className = 'vis-group';
  90. foreground['timeline-group'] = this;
  91. this.dom.foreground = foreground;
  92. this.dom.background = document.createElement('div');
  93. this.dom.background.className = 'vis-group';
  94. this.dom.axis = document.createElement('div');
  95. this.dom.axis.className = 'vis-group';
  96. // create a hidden marker to detect when the Timelines container is attached
  97. // to the DOM, or the style of a parent of the Timeline is changed from
  98. // display:none is changed to visible.
  99. this.dom.marker = document.createElement('div');
  100. this.dom.marker.style.visibility = 'hidden';
  101. this.dom.marker.style.position = 'absolute';
  102. this.dom.marker.innerHTML = '';
  103. this.dom.background.appendChild(this.dom.marker);
  104. };
  105. /**
  106. * Set the group data for this group
  107. * @param {Object} data Group data, can contain properties content and className
  108. */
  109. Group.prototype.setData = function(data) {
  110. // update contents
  111. var content;
  112. var templateFunction;
  113. if (this.itemSet.options && this.itemSet.options.groupTemplate) {
  114. templateFunction = this.itemSet.options.groupTemplate.bind(this);
  115. content = templateFunction(data, this.dom.inner);
  116. } else {
  117. content = data && data.content;
  118. }
  119. if (content instanceof Element) {
  120. this.dom.inner.appendChild(content);
  121. while (this.dom.inner.firstChild) {
  122. this.dom.inner.removeChild(this.dom.inner.firstChild);
  123. }
  124. this.dom.inner.appendChild(content);
  125. } else if (content instanceof Object) {
  126. templateFunction(data, this.dom.inner);
  127. } else if (content !== undefined && content !== null) {
  128. this.dom.inner.innerHTML = content;
  129. } else {
  130. this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null
  131. }
  132. // update title
  133. this.dom.label.title = data && data.title || '';
  134. if (!this.dom.inner.firstChild) {
  135. util.addClassName(this.dom.inner, 'vis-hidden');
  136. }
  137. else {
  138. util.removeClassName(this.dom.inner, 'vis-hidden');
  139. }
  140. if (data && data.nestedGroups) {
  141. if (!this.nestedGroups || this.nestedGroups != data.nestedGroups) {
  142. this.nestedGroups = data.nestedGroups;
  143. }
  144. if (data.showNested !== undefined || this.showNested === undefined) {
  145. if (data.showNested == false) {
  146. this.showNested = false;
  147. } else {
  148. this.showNested = true;
  149. }
  150. }
  151. util.addClassName(this.dom.label, 'vis-nesting-group');
  152. var collapsedDirClassName = this.itemSet.options.rtl ? 'collapsed-rtl' : 'collapsed'
  153. if (this.showNested) {
  154. util.removeClassName(this.dom.label, collapsedDirClassName);
  155. util.addClassName(this.dom.label, 'expanded');
  156. } else {
  157. util.removeClassName(this.dom.label, 'expanded');
  158. util.addClassName(this.dom.label, collapsedDirClassName);
  159. }
  160. } else if (this.nestedGroups) {
  161. this.nestedGroups = null;
  162. collapsedDirClassName = this.itemSet.options.rtl ? 'collapsed-rtl' : 'collapsed'
  163. util.removeClassName(this.dom.label, collapsedDirClassName);
  164. util.removeClassName(this.dom.label, 'expanded');
  165. util.removeClassName(this.dom.label, 'vis-nesting-group');
  166. }
  167. if (data && data.nestedInGroup) {
  168. util.addClassName(this.dom.label, 'vis-nested-group');
  169. if (this.itemSet.options && this.itemSet.options.rtl) {
  170. this.dom.inner.style.paddingRight = '30px';
  171. } else {
  172. this.dom.inner.style.paddingLeft = '30px';
  173. }
  174. }
  175. // update className
  176. var className = data && data.className || null;
  177. if (className != this.className) {
  178. if (this.className) {
  179. util.removeClassName(this.dom.label, this.className);
  180. util.removeClassName(this.dom.foreground, this.className);
  181. util.removeClassName(this.dom.background, this.className);
  182. util.removeClassName(this.dom.axis, this.className);
  183. }
  184. util.addClassName(this.dom.label, className);
  185. util.addClassName(this.dom.foreground, className);
  186. util.addClassName(this.dom.background, className);
  187. util.addClassName(this.dom.axis, className);
  188. this.className = className;
  189. }
  190. // update style
  191. if (this.style) {
  192. util.removeCssText(this.dom.label, this.style);
  193. this.style = null;
  194. }
  195. if (data && data.style) {
  196. util.addCssText(this.dom.label, data.style);
  197. this.style = data.style;
  198. }
  199. };
  200. /**
  201. * Get the width of the group label
  202. * @return {number} width
  203. */
  204. Group.prototype.getLabelWidth = function() {
  205. return this.props.label.width;
  206. };
  207. Group.prototype._didMarkerHeightChange = function() {
  208. var markerHeight = this.dom.marker.clientHeight;
  209. if (markerHeight != this.lastMarkerHeight) {
  210. this.lastMarkerHeight = markerHeight;
  211. var redrawQueue = {};
  212. var redrawQueueLength = 0;
  213. util.forEach(this.items, function (item, key) {
  214. item.dirty = true;
  215. if (item.displayed) {
  216. var returnQueue = true;
  217. redrawQueue[key] = item.redraw(returnQueue);
  218. redrawQueueLength = redrawQueue[key].length;
  219. }
  220. })
  221. var needRedraw = redrawQueueLength > 0;
  222. if (needRedraw) {
  223. // redraw all regular items
  224. for (var i = 0; i < redrawQueueLength; i++) {
  225. util.forEach(redrawQueue, function (fns) {
  226. fns[i]();
  227. });
  228. }
  229. }
  230. return true;
  231. }
  232. }
  233. Group.prototype._calculateGroupSizeAndPosition = function() {
  234. var offsetTop = this.dom.foreground.offsetTop
  235. var offsetLeft = this.dom.foreground.offsetLeft
  236. var offsetWidth = this.dom.foreground.offsetWidth
  237. this.top = offsetTop;
  238. this.right = offsetLeft;
  239. this.width = offsetWidth;
  240. }
  241. Group.prototype._shouldBailItemsRedraw = function() {
  242. var me = this;
  243. var timeoutOptions = this.itemSet.options.onTimeout;
  244. var bailOptions = {
  245. relativeBailingTime: this.itemSet.itemsSettingTime,
  246. bailTimeMs: timeoutOptions && timeoutOptions.timeoutMs,
  247. userBailFunction: timeoutOptions && timeoutOptions.callback,
  248. shouldBailStackItems: this.shouldBailStackItems
  249. };
  250. var bail = null;
  251. if (!this.itemSet.initialDrawDone) {
  252. if (bailOptions.shouldBailStackItems) { return true; }
  253. if (Math.abs(new Date() - new Date(bailOptions.relativeBailingTime)) > bailOptions.bailTimeMs) {
  254. if (bailOptions.userBailFunction && this.itemSet.userContinueNotBail == null) {
  255. bailOptions.userBailFunction(function(didUserContinue) {
  256. me.itemSet.userContinueNotBail = didUserContinue;
  257. bail = !didUserContinue;
  258. })
  259. } else if (me.itemSet.userContinueNotBail == false) {
  260. bail = true;
  261. } else {
  262. bail = false;
  263. }
  264. }
  265. }
  266. return bail;
  267. }
  268. Group.prototype._redrawItems = function(forceRestack, lastIsVisible, margin, range) {
  269. var restack = forceRestack || this.stackDirty || this.isVisible && !lastIsVisible;
  270. // if restacking, reposition visible items vertically
  271. if (restack) {
  272. var visibleSubgroups = {};
  273. var subgroup = null;
  274. if (typeof this.itemSet.options.order === 'function') {
  275. // a custom order function
  276. // brute force restack of all items
  277. // show all items
  278. var me = this;
  279. var limitSize = false;
  280. var redrawQueue = {};
  281. var redrawQueueLength = 0;
  282. util.forEach(this.items, function (item, key) {
  283. if (!item.displayed && (item.isVisible(range) || !item.dom)) {
  284. var returnQueue = true;
  285. redrawQueue[key] = item.show(returnQueue);
  286. redrawQueueLength = redrawQueue[key].length;
  287. me.visibleItems.push(item);
  288. }
  289. })
  290. var needRedraw = redrawQueueLength > 0;
  291. if (needRedraw) {
  292. // redraw all regular items
  293. for (var i = 0; i < redrawQueueLength; i++) {
  294. util.forEach(redrawQueue, function (fns) {
  295. fns[i]();
  296. });
  297. }
  298. }
  299. util.forEach(this.items, function (item) {
  300. if(item.displayed) {
  301. item.repositionX(limitSize);
  302. }
  303. });
  304. if (this.doInnerStack && this.itemSet.options.stackSubgroups) {
  305. // Order the items within each subgroup
  306. for(subgroup in this.subgroups) {
  307. visibleSubgroups[subgroup] = this.subgroups[subgroup].items.slice().sort(function (a, b) {
  308. return me.itemSet.options.order(a.data, b.data);
  309. });
  310. }
  311. stack.stackSubgroupsWithInnerStack(visibleSubgroups, margin, this.subgroups);
  312. }
  313. else {
  314. // order all items and force a restacking
  315. var customOrderedItems = this.orderedItems.byStart.slice().sort(function (a, b) {
  316. return me.itemSet.options.order(a.data, b.data);
  317. });
  318. this.shouldBailStackItems = stack.stack(customOrderedItems, margin, true, this._shouldBailItemsRedraw.bind(this));
  319. }
  320. this.visibleItems = this._updateItemsInRange(this.orderedItems, this.visibleItems, range);
  321. } else {
  322. // no custom order function, lazy stacking
  323. this.visibleItems = this._updateItemsInRange(this.orderedItems, this.visibleItems, range);
  324. if (this.itemSet.options.stack) {
  325. if (this.doInnerStack && this.itemSet.options.stackSubgroups) {
  326. for(subgroup in this.subgroups) {
  327. visibleSubgroups[subgroup] = this.subgroups[subgroup].items;
  328. }
  329. stack.stackSubgroupsWithInnerStack(visibleSubgroups, margin, this.subgroups);
  330. }
  331. else {
  332. // TODO: ugly way to access options...
  333. this.shouldBailStackItems = stack.stack(this.visibleItems, margin, true, this._shouldBailItemsRedraw.bind(this));
  334. }
  335. } else {
  336. // no stacking
  337. stack.nostack(this.visibleItems, margin, this.subgroups, this.itemSet.options.stackSubgroups);
  338. }
  339. }
  340. if (this.shouldBailStackItems) {
  341. this.itemSet.body.emitter.emit('destroyTimeline')
  342. }
  343. this.stackDirty = false;
  344. }
  345. }
  346. Group.prototype._didResize = function(resized, height) {
  347. resized = util.updateProperty(this, 'height', height) || resized;
  348. // recalculate size of label
  349. var labelWidth = this.dom.inner.clientWidth;
  350. var labelHeight = this.dom.inner.clientHeight;
  351. resized = util.updateProperty(this.props.label, 'width', labelWidth) || resized;
  352. resized = util.updateProperty(this.props.label, 'height', labelHeight) || resized;
  353. return resized;
  354. }
  355. Group.prototype._applyGroupHeight = function(height) {
  356. this.dom.background.style.height = height + 'px';
  357. this.dom.foreground.style.height = height + 'px';
  358. this.dom.label.style.height = height + 'px';
  359. }
  360. // update vertical position of items after they are re-stacked and the height of the group is calculated
  361. Group.prototype._updateItemsVerticalPosition = function(margin) {
  362. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  363. var item = this.visibleItems[i];
  364. item.repositionY(margin);
  365. if (!this.isVisible && this.groupId != "__background__") {
  366. if (item.displayed) item.hide();
  367. }
  368. }
  369. }
  370. /**
  371. * Repaint this group
  372. * @param {{start: number, end: number}} range
  373. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  374. * @param {boolean} [forceRestack=false] Force restacking of all items
  375. * @param {boolean} [returnQueue=false] return the queue or if the group resized
  376. * @return {boolean} Returns true if the group is resized or the redraw queue if returnQueue=true
  377. */
  378. Group.prototype.redraw = function(range, margin, forceRestack, returnQueue) {
  379. var resized = false;
  380. var lastIsVisible = this.isVisible;
  381. var height;
  382. var queue = [
  383. // force recalculation of the height of the items when the marker height changed
  384. // (due to the Timeline being attached to the DOM or changed from display:none to visible)
  385. (function () {
  386. forceRestack = this._didMarkerHeightChange.bind(this);
  387. }).bind(this),
  388. // recalculate the height of the subgroups
  389. this._updateSubGroupHeights.bind(this, margin),
  390. // calculate actual size and position
  391. this._calculateGroupSizeAndPosition.bind(this),
  392. // check if group is visible
  393. (function() {
  394. this.isVisible = this._isGroupVisible.bind(this)(range, margin);
  395. }).bind(this),
  396. // redraw Items if needed
  397. (function() {
  398. this._redrawItems.bind(this)(forceRestack, lastIsVisible, margin, range)
  399. }).bind(this),
  400. // update subgroups
  401. this._updateSubgroupsSizes.bind(this),
  402. // recalculate the height of the group
  403. (function() {
  404. height = this._calculateHeight.bind(this)(margin);
  405. }).bind(this),
  406. // calculate actual size and position again
  407. this._calculateGroupSizeAndPosition.bind(this),
  408. // check if resized
  409. (function() {
  410. resized = this._didResize.bind(this)(resized, height)
  411. }).bind(this),
  412. // apply group height
  413. (function() {
  414. this._applyGroupHeight.bind(this)(height)
  415. }).bind(this),
  416. // update vertical position of items after they are re-stacked and the height of the group is calculated
  417. (function() {
  418. this._updateItemsVerticalPosition.bind(this)(margin)
  419. }).bind(this),
  420. function() {
  421. if (!this.isVisible && this.height) {
  422. resized = false;
  423. }
  424. return resized
  425. }
  426. ]
  427. if (returnQueue) {
  428. return queue;
  429. } else {
  430. var result;
  431. queue.forEach(function (fn) {
  432. result = fn();
  433. });
  434. return result;
  435. }
  436. };
  437. /**
  438. * recalculate the height of the subgroups
  439. *
  440. * @param {{item: vis.Item}} margin
  441. * @private
  442. */
  443. Group.prototype._updateSubGroupHeights = function (margin) {
  444. if (Object.keys(this.subgroups).length > 0) {
  445. var me = this;
  446. this.resetSubgroups();
  447. util.forEach(this.visibleItems, function (item) {
  448. if (item.data.subgroup !== undefined) {
  449. me.subgroups[item.data.subgroup].height = Math.max(me.subgroups[item.data.subgroup].height, item.height + margin.item.vertical);
  450. me.subgroups[item.data.subgroup].visible = true;
  451. }
  452. });
  453. }
  454. };
  455. /**
  456. * check if group is visible
  457. *
  458. * @param {vis.Range} range
  459. * @param {{axis: vis.DataAxis}} margin
  460. * @returns {boolean} is visible
  461. * @private
  462. */
  463. Group.prototype._isGroupVisible = function (range, margin) {
  464. return (this.top <= range.body.domProps.centerContainer.height - range.body.domProps.scrollTop + margin.axis)
  465. && (this.top + this.height + margin.axis >= - range.body.domProps.scrollTop);
  466. };
  467. /**
  468. * recalculate the height of the group
  469. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  470. * @returns {number} Returns the height
  471. * @private
  472. */
  473. Group.prototype._calculateHeight = function (margin) {
  474. // recalculate the height of the group
  475. var height, items;
  476. if (this.heightMode === 'fixed') {
  477. items = util.toArray(this.items);
  478. } else {
  479. // default or 'auto'
  480. items = this.visibleItems;
  481. }
  482. if (items.length > 0) {
  483. var min = items[0].top;
  484. var max = items[0].top + items[0].height;
  485. util.forEach(items, function (item) {
  486. min = Math.min(min, item.top);
  487. max = Math.max(max, (item.top + item.height));
  488. });
  489. if (min > margin.axis) {
  490. // there is an empty gap between the lowest item and the axis
  491. var offset = min - margin.axis;
  492. max -= offset;
  493. util.forEach(items, function (item) {
  494. item.top -= offset;
  495. });
  496. }
  497. height = max + margin.item.vertical / 2;
  498. }
  499. else {
  500. height = 0;
  501. }
  502. height = Math.max(height, this.props.label.height);
  503. return height;
  504. };
  505. /**
  506. * Show this group: attach to the DOM
  507. */
  508. Group.prototype.show = function() {
  509. if (!this.dom.label.parentNode) {
  510. this.itemSet.dom.labelSet.appendChild(this.dom.label);
  511. }
  512. if (!this.dom.foreground.parentNode) {
  513. this.itemSet.dom.foreground.appendChild(this.dom.foreground);
  514. }
  515. if (!this.dom.background.parentNode) {
  516. this.itemSet.dom.background.appendChild(this.dom.background);
  517. }
  518. if (!this.dom.axis.parentNode) {
  519. this.itemSet.dom.axis.appendChild(this.dom.axis);
  520. }
  521. };
  522. /**
  523. * Hide this group: remove from the DOM
  524. */
  525. Group.prototype.hide = function() {
  526. var label = this.dom.label;
  527. if (label.parentNode) {
  528. label.parentNode.removeChild(label);
  529. }
  530. var foreground = this.dom.foreground;
  531. if (foreground.parentNode) {
  532. foreground.parentNode.removeChild(foreground);
  533. }
  534. var background = this.dom.background;
  535. if (background.parentNode) {
  536. background.parentNode.removeChild(background);
  537. }
  538. var axis = this.dom.axis;
  539. if (axis.parentNode) {
  540. axis.parentNode.removeChild(axis);
  541. }
  542. };
  543. /**
  544. * Add an item to the group
  545. * @param {Item} item
  546. */
  547. Group.prototype.add = function(item) {
  548. this.items[item.id] = item;
  549. item.setParent(this);
  550. this.stackDirty = true;
  551. // add to
  552. if (item.data.subgroup !== undefined) {
  553. this._addToSubgroup(item);
  554. this.orderSubgroups();
  555. }
  556. if (this.visibleItems.indexOf(item) == -1) {
  557. var range = this.itemSet.body.range; // TODO: not nice accessing the range like this
  558. this._checkIfVisible(item, this.visibleItems, range);
  559. }
  560. };
  561. Group.prototype._addToSubgroup = function(item, subgroupId) {
  562. subgroupId = subgroupId || item.data.subgroup;
  563. if (subgroupId != undefined && this.subgroups[subgroupId] === undefined) {
  564. this.subgroups[subgroupId] = {
  565. height:0,
  566. top: 0,
  567. start: item.data.start,
  568. end: item.data.end || item.data.start,
  569. visible: false,
  570. index:this.subgroupIndex,
  571. items: [],
  572. stack: this.subgroupStackAll || this.subgroupStack[subgroupId] || false
  573. };
  574. this.subgroupIndex++;
  575. }
  576. if (new Date(item.data.start) < new Date(this.subgroups[subgroupId].start)) {
  577. this.subgroups[subgroupId].start = item.data.start;
  578. }
  579. var itemEnd = item.data.end || item.data.start;
  580. if (new Date(itemEnd) > new Date(this.subgroups[subgroupId].end)) {
  581. this.subgroups[subgroupId].end = itemEnd;
  582. }
  583. this.subgroups[subgroupId].items.push(item);
  584. };
  585. Group.prototype._updateSubgroupsSizes = function () {
  586. var me = this;
  587. if (me.subgroups) {
  588. for (var subgroup in me.subgroups) {
  589. var initialEnd = me.subgroups[subgroup].items[0].data.end || me.subgroups[subgroup].items[0].data.start;
  590. var newStart = me.subgroups[subgroup].items[0].data.start;
  591. var newEnd = initialEnd - 1;
  592. me.subgroups[subgroup].items.forEach(function(item) {
  593. if (new Date(item.data.start) < new Date(newStart)) {
  594. newStart = item.data.start;
  595. }
  596. var itemEnd = item.data.end || item.data.start;
  597. if (new Date(itemEnd) > new Date(newEnd)) {
  598. newEnd = itemEnd;
  599. }
  600. })
  601. me.subgroups[subgroup].start = newStart;
  602. me.subgroups[subgroup].end = new Date(newEnd - 1) // -1 to compensate for colliding end to start subgroups;
  603. }
  604. }
  605. }
  606. Group.prototype.orderSubgroups = function() {
  607. if (this.subgroupOrderer !== undefined) {
  608. var sortArray = [];
  609. var subgroup;
  610. if (typeof this.subgroupOrderer == 'string') {
  611. for (subgroup in this.subgroups) {
  612. sortArray.push({subgroup: subgroup, sortField: this.subgroups[subgroup].items[0].data[this.subgroupOrderer]})
  613. }
  614. sortArray.sort(function (a, b) {
  615. return a.sortField - b.sortField;
  616. })
  617. }
  618. else if (typeof this.subgroupOrderer == 'function') {
  619. for (subgroup in this.subgroups) {
  620. sortArray.push(this.subgroups[subgroup].items[0].data);
  621. }
  622. sortArray.sort(this.subgroupOrderer);
  623. }
  624. if (sortArray.length > 0) {
  625. for (var i = 0; i < sortArray.length; i++) {
  626. this.subgroups[sortArray[i].subgroup].index = i;
  627. }
  628. }
  629. }
  630. };
  631. Group.prototype.resetSubgroups = function() {
  632. for (var subgroup in this.subgroups) {
  633. if (this.subgroups.hasOwnProperty(subgroup)) {
  634. this.subgroups[subgroup].visible = false;
  635. this.subgroups[subgroup].height = 0;
  636. }
  637. }
  638. };
  639. /**
  640. * Remove an item from the group
  641. * @param {Item} item
  642. */
  643. Group.prototype.remove = function(item) {
  644. delete this.items[item.id];
  645. item.setParent(null);
  646. this.stackDirty = true;
  647. // remove from visible items
  648. var index = this.visibleItems.indexOf(item);
  649. if (index != -1) this.visibleItems.splice(index, 1);
  650. if(item.data.subgroup !== undefined){
  651. this._removeFromSubgroup(item);
  652. this.orderSubgroups();
  653. }
  654. };
  655. Group.prototype._removeFromSubgroup = function(item, subgroupId) {
  656. subgroupId = subgroupId || item.data.subgroup;
  657. if (subgroupId != undefined) {
  658. var subgroup = this.subgroups[subgroupId];
  659. if (subgroup){
  660. var itemIndex = subgroup.items.indexOf(item);
  661. // Check the item is actually in this subgroup. How should items not in the group be handled?
  662. if (itemIndex >= 0) {
  663. subgroup.items.splice(itemIndex,1);
  664. if (!subgroup.items.length){
  665. delete this.subgroups[subgroupId];
  666. } else {
  667. this._updateSubgroupsSizes();
  668. }
  669. }
  670. }
  671. }
  672. };
  673. /**
  674. * Remove an item from the corresponding DataSet
  675. * @param {Item} item
  676. */
  677. Group.prototype.removeFromDataSet = function(item) {
  678. this.itemSet.removeItem(item.id);
  679. };
  680. /**
  681. * Reorder the items
  682. */
  683. Group.prototype.order = function() {
  684. var array = util.toArray(this.items);
  685. var startArray = [];
  686. var endArray = [];
  687. for (var i = 0; i < array.length; i++) {
  688. if (array[i].data.end !== undefined) {
  689. endArray.push(array[i]);
  690. }
  691. startArray.push(array[i]);
  692. }
  693. this.orderedItems = {
  694. byStart: startArray,
  695. byEnd: endArray
  696. };
  697. stack.orderByStart(this.orderedItems.byStart);
  698. stack.orderByEnd(this.orderedItems.byEnd);
  699. };
  700. /**
  701. * Update the visible items
  702. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  703. * @param {Item[]} oldVisibleItems The previously visible items.
  704. * @param {{start: number, end: number}} range Visible range
  705. * @return {Item[]} visibleItems The new visible items.
  706. * @private
  707. */
  708. Group.prototype._updateItemsInRange = function(orderedItems, oldVisibleItems, range) {
  709. var visibleItems = [];
  710. var visibleItemsLookup = {}; // we keep this to quickly look up if an item already exists in the list without using indexOf on visibleItems
  711. var interval = (range.end - range.start) / 4;
  712. var lowerBound = range.start - interval;
  713. var upperBound = range.end + interval;
  714. // this function is used to do the binary search.
  715. var searchFunction = function (value) {
  716. if (value < lowerBound) {return -1;}
  717. else if (value <= upperBound) {return 0;}
  718. else {return 1;}
  719. };
  720. // first check if the items that were in view previously are still in view.
  721. // IMPORTANT: this handles the case for the items with startdate before the window and enddate after the window!
  722. // also cleans up invisible items.
  723. if (oldVisibleItems.length > 0) {
  724. for (var i = 0; i < oldVisibleItems.length; i++) {
  725. this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range);
  726. }
  727. }
  728. // we do a binary search for the items that have only start values.
  729. var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data','start');
  730. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the start values.
  731. this._traceVisible(initialPosByStart, orderedItems.byStart, visibleItems, visibleItemsLookup, function (item) {
  732. return (item.data.start < lowerBound || item.data.start > upperBound);
  733. });
  734. // if the window has changed programmatically without overlapping the old window, the ranged items with start < lowerBound and end > upperbound are not shown.
  735. // We therefore have to brute force check all items in the byEnd list
  736. if (this.checkRangedItems == true) {
  737. this.checkRangedItems = false;
  738. for (i = 0; i < orderedItems.byEnd.length; i++) {
  739. this._checkIfVisibleWithReference(orderedItems.byEnd[i], visibleItems, visibleItemsLookup, range);
  740. }
  741. }
  742. else {
  743. // we do a binary search for the items that have defined end times.
  744. var initialPosByEnd = util.binarySearchCustom(orderedItems.byEnd, searchFunction, 'data','end');
  745. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the end values.
  746. this._traceVisible(initialPosByEnd, orderedItems.byEnd, visibleItems, visibleItemsLookup, function (item) {
  747. return (item.data.end < lowerBound || item.data.end > upperBound);
  748. });
  749. }
  750. var redrawQueue = {};
  751. var redrawQueueLength = 0;
  752. for (i = 0; i < visibleItems.length; i++) {
  753. var item = visibleItems[i];
  754. if (!item.displayed) {
  755. var returnQueue = true;
  756. redrawQueue[i] = item.redraw(returnQueue);
  757. redrawQueueLength = redrawQueue[i].length;
  758. }
  759. }
  760. var needRedraw = redrawQueueLength > 0;
  761. if (needRedraw) {
  762. // redraw all regular items
  763. for (var j = 0; j < redrawQueueLength; j++) {
  764. util.forEach(redrawQueue, function (fns) {
  765. fns[j]();
  766. });
  767. }
  768. }
  769. for (i = 0; i < visibleItems.length; i++) {
  770. visibleItems[i].repositionX();
  771. }
  772. return visibleItems;
  773. };
  774. Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) {
  775. if (initialPos != -1) {
  776. var i, item;
  777. for (i = initialPos; i >= 0; i--) {
  778. item = items[i];
  779. if (breakCondition(item)) {
  780. break;
  781. }
  782. else {
  783. if (visibleItemsLookup[item.id] === undefined) {
  784. visibleItemsLookup[item.id] = true;
  785. visibleItems.push(item);
  786. }
  787. }
  788. }
  789. for (i = initialPos + 1; i < items.length; i++) {
  790. item = items[i];
  791. if (breakCondition(item)) {
  792. break;
  793. }
  794. else {
  795. if (visibleItemsLookup[item.id] === undefined) {
  796. visibleItemsLookup[item.id] = true;
  797. visibleItems.push(item);
  798. }
  799. }
  800. }
  801. }
  802. }
  803. /**
  804. * this function is very similar to the _checkIfInvisible() but it does not
  805. * return booleans, hides the item if it should not be seen and always adds to
  806. * the visibleItems.
  807. * this one is for brute forcing and hiding.
  808. *
  809. * @param {Item} item
  810. * @param {Array} visibleItems
  811. * @param {{start:number, end:number}} range
  812. * @private
  813. */
  814. Group.prototype._checkIfVisible = function(item, visibleItems, range) {
  815. if (item.isVisible(range)) {
  816. if (!item.displayed) item.show();
  817. // reposition item horizontally
  818. item.repositionX();
  819. visibleItems.push(item);
  820. }
  821. else {
  822. if (item.displayed) item.hide();
  823. }
  824. };
  825. /**
  826. * this function is very similar to the _checkIfInvisible() but it does not
  827. * return booleans, hides the item if it should not be seen and always adds to
  828. * the visibleItems.
  829. * this one is for brute forcing and hiding.
  830. *
  831. * @param {Item} item
  832. * @param {Array.<vis.Item>} visibleItems
  833. * @param {Object<number, boolean>} visibleItemsLookup
  834. * @param {{start:number, end:number}} range
  835. * @private
  836. */
  837. Group.prototype._checkIfVisibleWithReference = function(item, visibleItems, visibleItemsLookup, range) {
  838. if (item.isVisible(range)) {
  839. if (visibleItemsLookup[item.id] === undefined) {
  840. visibleItemsLookup[item.id] = true;
  841. visibleItems.push(item);
  842. }
  843. }
  844. else {
  845. if (item.displayed) item.hide();
  846. }
  847. };
  848. Group.prototype.changeSubgroup = function(item, oldSubgroup, newSubgroup) {
  849. this._removeFromSubgroup(item, oldSubgroup);
  850. this._addToSubgroup(item, newSubgroup);
  851. this.orderSubgroups();
  852. };
  853. module.exports = Group;