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.

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