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.

982 lines
29 KiB

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