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.

2290 lines
67 KiB

10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. var Hammer = require('../../module/hammer');
  2. var util = require('../../util');
  3. var DataSet = require('../../DataSet');
  4. var DataView = require('../../DataView');
  5. var TimeStep = require('../TimeStep');
  6. var Component = require('./Component');
  7. var Group = require('./Group');
  8. var BackgroundGroup = require('./BackgroundGroup');
  9. var BoxItem = require('./item/BoxItem');
  10. var PointItem = require('./item/PointItem');
  11. var RangeItem = require('./item/RangeItem');
  12. var BackgroundItem = require('./item/BackgroundItem');
  13. var Popup = require('../../shared/Popup').default;
  14. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  15. var BACKGROUND = '__background__'; // reserved group id for background items without group
  16. /**
  17. * An ItemSet holds a set of items and ranges which can be displayed in a
  18. * range. The width is determined by the parent of the ItemSet, and the height
  19. * is determined by the size of the items.
  20. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  21. * @param {Object} [options] See ItemSet.setOptions for the available options.
  22. * @constructor ItemSet
  23. * @extends Component
  24. */
  25. function ItemSet(body, options) {
  26. this.body = body;
  27. this.defaultOptions = {
  28. type: null, // 'box', 'point', 'range', 'background'
  29. orientation: {
  30. item: 'bottom' // item orientation: 'top' or 'bottom'
  31. },
  32. align: 'auto', // alignment of box items
  33. stack: true,
  34. stackSubgroups: true,
  35. groupOrderSwap: function(fromGroup, toGroup, groups) {
  36. var targetOrder = toGroup.order;
  37. toGroup.order = fromGroup.order;
  38. fromGroup.order = targetOrder;
  39. },
  40. groupOrder: 'order',
  41. selectable: true,
  42. multiselect: false,
  43. itemsAlwaysDraggable: false,
  44. editable: {
  45. updateTime: false,
  46. updateGroup: false,
  47. add: false,
  48. remove: false,
  49. overrideItems: false
  50. },
  51. groupEditable: {
  52. order: false,
  53. add: false,
  54. remove: false
  55. },
  56. snap: TimeStep.snap,
  57. onAdd: function (item, callback) {
  58. callback(item);
  59. },
  60. onUpdate: function (item, callback) {
  61. callback(item);
  62. },
  63. onMove: function (item, callback) {
  64. callback(item);
  65. },
  66. onRemove: function (item, callback) {
  67. callback(item);
  68. },
  69. onMoving: function (item, callback) {
  70. callback(item);
  71. },
  72. onAddGroup: function (item, callback) {
  73. callback(item);
  74. },
  75. onMoveGroup: function (item, callback) {
  76. callback(item);
  77. },
  78. onRemoveGroup: function (item, callback) {
  79. callback(item);
  80. },
  81. margin: {
  82. item: {
  83. horizontal: 10,
  84. vertical: 10
  85. },
  86. axis: 20
  87. },
  88. showTooltips: true,
  89. tooltip: {
  90. followMouse: false,
  91. overflowMethod: 'flip'
  92. },
  93. tooltipOnItemUpdateTime: false
  94. };
  95. // options is shared by this ItemSet and all its items
  96. this.options = util.extend({}, this.defaultOptions);
  97. this.options.rtl = options.rtl;
  98. // options for getting items from the DataSet with the correct type
  99. this.itemOptions = {
  100. type: {start: 'Date', end: 'Date'}
  101. };
  102. this.conversion = {
  103. toScreen: body.util.toScreen,
  104. toTime: body.util.toTime
  105. };
  106. this.dom = {};
  107. this.props = {};
  108. this.hammer = null;
  109. var me = this;
  110. this.itemsData = null; // DataSet
  111. this.groupsData = null; // DataSet
  112. // listeners for the DataSet of the items
  113. this.itemListeners = {
  114. 'add': function (event, params, senderId) {
  115. me._onAdd(params.items);
  116. },
  117. 'update': function (event, params, senderId) {
  118. me._onUpdate(params.items);
  119. },
  120. 'remove': function (event, params, senderId) {
  121. me._onRemove(params.items);
  122. }
  123. };
  124. // listeners for the DataSet of the groups
  125. this.groupListeners = {
  126. 'add': function (event, params, senderId) {
  127. me._onAddGroups(params.items);
  128. },
  129. 'update': function (event, params, senderId) {
  130. me._onUpdateGroups(params.items);
  131. },
  132. 'remove': function (event, params, senderId) {
  133. me._onRemoveGroups(params.items);
  134. }
  135. };
  136. this.items = {}; // object with an Item for every data item
  137. this.groups = {}; // Group object for every group
  138. this.groupIds = [];
  139. this.selection = []; // list with the ids of all selected nodes
  140. this.popup = null;
  141. this.touchParams = {}; // stores properties while dragging
  142. this.groupTouchParams = {};
  143. // create the HTML DOM
  144. this._create();
  145. this.setOptions(options);
  146. }
  147. ItemSet.prototype = new Component();
  148. // available item types will be registered here
  149. ItemSet.types = {
  150. background: BackgroundItem,
  151. box: BoxItem,
  152. range: RangeItem,
  153. point: PointItem
  154. };
  155. /**
  156. * Create the HTML DOM for the ItemSet
  157. */
  158. ItemSet.prototype._create = function(){
  159. var frame = document.createElement('div');
  160. frame.className = 'vis-itemset';
  161. frame['timeline-itemset'] = this;
  162. this.dom.frame = frame;
  163. // create background panel
  164. var background = document.createElement('div');
  165. background.className = 'vis-background';
  166. frame.appendChild(background);
  167. this.dom.background = background;
  168. // create foreground panel
  169. var foreground = document.createElement('div');
  170. foreground.className = 'vis-foreground';
  171. frame.appendChild(foreground);
  172. this.dom.foreground = foreground;
  173. // create axis panel
  174. var axis = document.createElement('div');
  175. axis.className = 'vis-axis';
  176. this.dom.axis = axis;
  177. // create labelset
  178. var labelSet = document.createElement('div');
  179. labelSet.className = 'vis-labelset';
  180. this.dom.labelSet = labelSet;
  181. // create ungrouped Group
  182. this._updateUngrouped();
  183. // create background Group
  184. var backgroundGroup = new BackgroundGroup(BACKGROUND, null, this);
  185. backgroundGroup.show();
  186. this.groups[BACKGROUND] = backgroundGroup;
  187. // attach event listeners
  188. // Note: we bind to the centerContainer for the case where the height
  189. // of the center container is larger than of the ItemSet, so we
  190. // can click in the empty area to create a new item or deselect an item.
  191. this.hammer = new Hammer(this.body.dom.centerContainer);
  192. // drag items when selected
  193. this.hammer.on('hammer.input', function (event) {
  194. if (event.isFirst) {
  195. this._onTouch(event);
  196. }
  197. }.bind(this));
  198. this.hammer.on('panstart', this._onDragStart.bind(this));
  199. this.hammer.on('panmove', this._onDrag.bind(this));
  200. this.hammer.on('panend', this._onDragEnd.bind(this));
  201. this.hammer.get('pan').set({threshold:5, direction: Hammer.DIRECTION_HORIZONTAL});
  202. // single select (or unselect) when tapping an item
  203. this.hammer.on('tap', this._onSelectItem.bind(this));
  204. // multi select when holding mouse/touch, or on ctrl+click
  205. this.hammer.on('press', this._onMultiSelectItem.bind(this));
  206. // add item on doubletap
  207. this.hammer.on('doubletap', this._onAddItem.bind(this));
  208. if (this.options.rtl) {
  209. this.groupHammer = new Hammer(this.body.dom.rightContainer);
  210. } else {
  211. this.groupHammer = new Hammer(this.body.dom.leftContainer);
  212. }
  213. this.groupHammer.on('tap', this._onGroupClick.bind(this));
  214. this.groupHammer.on('panstart', this._onGroupDragStart.bind(this));
  215. this.groupHammer.on('panmove', this._onGroupDrag.bind(this));
  216. this.groupHammer.on('panend', this._onGroupDragEnd.bind(this));
  217. this.groupHammer.get('pan').set({threshold:5, direction: Hammer.DIRECTION_VERTICAL});
  218. this.body.dom.centerContainer.addEventListener('mouseover', this._onMouseOver.bind(this));
  219. this.body.dom.centerContainer.addEventListener('mouseout', this._onMouseOut.bind(this));
  220. this.body.dom.centerContainer.addEventListener('mousemove', this._onMouseMove.bind(this));
  221. // right-click on timeline
  222. this.body.dom.centerContainer.addEventListener('contextmenu', this._onDragEnd.bind(this));
  223. this.body.dom.centerContainer.addEventListener('mousewheel', this._onMouseWheel.bind(this));
  224. // attach to the DOM
  225. this.show();
  226. };
  227. /**
  228. * Set options for the ItemSet. Existing options will be extended/overwritten.
  229. * @param {Object} [options] The following options are available:
  230. * {String} type
  231. * Default type for the items. Choose from 'box'
  232. * (default), 'point', 'range', or 'background'.
  233. * The default style can be overwritten by
  234. * individual items.
  235. * {String} align
  236. * Alignment for the items, only applicable for
  237. * BoxItem. Choose 'center' (default), 'left', or
  238. * 'right'.
  239. * {String} orientation.item
  240. * Orientation of the item set. Choose 'top' or
  241. * 'bottom' (default).
  242. * {Function} groupOrder
  243. * A sorting function for ordering groups
  244. * {Boolean} stack
  245. * If true (default), items will be stacked on
  246. * top of each other.
  247. * {Number} margin.axis
  248. * Margin between the axis and the items in pixels.
  249. * Default is 20.
  250. * {Number} margin.item.horizontal
  251. * Horizontal margin between items in pixels.
  252. * Default is 10.
  253. * {Number} margin.item.vertical
  254. * Vertical Margin between items in pixels.
  255. * Default is 10.
  256. * {Number} margin.item
  257. * Margin between items in pixels in both horizontal
  258. * and vertical direction. Default is 10.
  259. * {Number} margin
  260. * Set margin for both axis and items in pixels.
  261. * {Boolean} selectable
  262. * If true (default), items can be selected.
  263. * {Boolean} multiselect
  264. * If true, multiple items can be selected.
  265. * False by default.
  266. * {Boolean} editable
  267. * Set all editable options to true or false
  268. * {Boolean} editable.updateTime
  269. * Allow dragging an item to an other moment in time
  270. * {Boolean} editable.updateGroup
  271. * Allow dragging an item to an other group
  272. * {Boolean} editable.add
  273. * Allow creating new items on double tap
  274. * {Boolean} editable.remove
  275. * Allow removing items by clicking the delete button
  276. * top right of a selected item.
  277. * {Function(item: Item, callback: Function)} onAdd
  278. * Callback function triggered when an item is about to be added:
  279. * when the user double taps an empty space in the Timeline.
  280. * {Function(item: Item, callback: Function)} onUpdate
  281. * Callback function fired when an item is about to be updated.
  282. * This function typically has to show a dialog where the user
  283. * change the item. If not implemented, nothing happens.
  284. * {Function(item: Item, callback: Function)} onMove
  285. * Fired when an item has been moved. If not implemented,
  286. * the move action will be accepted.
  287. * {Function(item: Item, callback: Function)} onRemove
  288. * Fired when an item is about to be deleted.
  289. * If not implemented, the item will be always removed.
  290. */
  291. ItemSet.prototype.setOptions = function(options) {
  292. if (options) {
  293. // copy all options that we know
  294. var fields = [
  295. 'type', 'rtl', 'align', 'order', 'stack', 'stackSubgroups', 'selectable', 'multiselect', 'itemsAlwaysDraggable',
  296. 'multiselectPerGroup', 'groupOrder', 'dataAttributes', 'template', 'groupTemplate', 'visibleFrameTemplate',
  297. 'hide', 'snap', 'groupOrderSwap', 'showTooltips', 'tooltip', 'tooltipOnItemUpdateTime'
  298. ];
  299. util.selectiveExtend(fields, this.options, options);
  300. if ('orientation' in options) {
  301. if (typeof options.orientation === 'string') {
  302. this.options.orientation.item = options.orientation === 'top' ? 'top' : 'bottom';
  303. }
  304. else if (typeof options.orientation === 'object' && 'item' in options.orientation) {
  305. this.options.orientation.item = options.orientation.item;
  306. }
  307. }
  308. if ('margin' in options) {
  309. if (typeof options.margin === 'number') {
  310. this.options.margin.axis = options.margin;
  311. this.options.margin.item.horizontal = options.margin;
  312. this.options.margin.item.vertical = options.margin;
  313. }
  314. else if (typeof options.margin === 'object') {
  315. util.selectiveExtend(['axis'], this.options.margin, options.margin);
  316. if ('item' in options.margin) {
  317. if (typeof options.margin.item === 'number') {
  318. this.options.margin.item.horizontal = options.margin.item;
  319. this.options.margin.item.vertical = options.margin.item;
  320. }
  321. else if (typeof options.margin.item === 'object') {
  322. util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item);
  323. }
  324. }
  325. }
  326. }
  327. if ('editable' in options) {
  328. if (typeof options.editable === 'boolean') {
  329. this.options.editable.updateTime = options.editable;
  330. this.options.editable.updateGroup = options.editable;
  331. this.options.editable.add = options.editable;
  332. this.options.editable.remove = options.editable;
  333. this.options.editable.overrideItems = false;
  334. }
  335. else if (typeof options.editable === 'object') {
  336. util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove', 'overrideItems'], this.options.editable, options.editable);
  337. }
  338. }
  339. if ('groupEditable' in options) {
  340. if (typeof options.groupEditable === 'boolean') {
  341. this.options.groupEditable.order = options.groupEditable;
  342. this.options.groupEditable.add = options.groupEditable;
  343. this.options.groupEditable.remove = options.groupEditable;
  344. }
  345. else if (typeof options.groupEditable === 'object') {
  346. util.selectiveExtend(['order', 'add', 'remove'], this.options.groupEditable, options.groupEditable);
  347. }
  348. }
  349. // callback functions
  350. var addCallback = (function (name) {
  351. var fn = options[name];
  352. if (fn) {
  353. if (!(fn instanceof Function)) {
  354. throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)');
  355. }
  356. this.options[name] = fn;
  357. }
  358. }).bind(this);
  359. ['onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving', 'onAddGroup', 'onMoveGroup', 'onRemoveGroup'].forEach(addCallback);
  360. // force the itemSet to refresh: options like orientation and margins may be changed
  361. this.markDirty();
  362. }
  363. };
  364. /**
  365. * Mark the ItemSet dirty so it will refresh everything with next redraw.
  366. * Optionally, all items can be marked as dirty and be refreshed.
  367. * @param {{refreshItems: boolean}} [options]
  368. */
  369. ItemSet.prototype.markDirty = function(options) {
  370. this.groupIds = [];
  371. if (options && options.refreshItems) {
  372. util.forEach(this.items, function (item) {
  373. item.dirty = true;
  374. if (item.displayed) item.redraw();
  375. });
  376. }
  377. };
  378. /**
  379. * Destroy the ItemSet
  380. */
  381. ItemSet.prototype.destroy = function() {
  382. this.hide();
  383. this.setItems(null);
  384. this.setGroups(null);
  385. this.hammer = null;
  386. this.body = null;
  387. this.conversion = null;
  388. };
  389. /**
  390. * Hide the component from the DOM
  391. */
  392. ItemSet.prototype.hide = function() {
  393. // remove the frame containing the items
  394. if (this.dom.frame.parentNode) {
  395. this.dom.frame.parentNode.removeChild(this.dom.frame);
  396. }
  397. // remove the axis with dots
  398. if (this.dom.axis.parentNode) {
  399. this.dom.axis.parentNode.removeChild(this.dom.axis);
  400. }
  401. // remove the labelset containing all group labels
  402. if (this.dom.labelSet.parentNode) {
  403. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  404. }
  405. };
  406. /**
  407. * Show the component in the DOM (when not already visible).
  408. * @return {Boolean} changed
  409. */
  410. ItemSet.prototype.show = function() {
  411. // show frame containing the items
  412. if (!this.dom.frame.parentNode) {
  413. this.body.dom.center.appendChild(this.dom.frame);
  414. }
  415. // show axis with dots
  416. if (!this.dom.axis.parentNode) {
  417. this.body.dom.backgroundVertical.appendChild(this.dom.axis);
  418. }
  419. // show labelset containing labels
  420. if (!this.dom.labelSet.parentNode) {
  421. if (this.options.rtl) {
  422. this.body.dom.right.appendChild(this.dom.labelSet);
  423. } else {
  424. this.body.dom.left.appendChild(this.dom.labelSet);
  425. }
  426. }
  427. };
  428. /**
  429. * Set selected items by their id. Replaces the current selection
  430. * Unknown id's are silently ignored.
  431. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  432. * selected, or a single item id. If ids is undefined
  433. * or an empty array, all items will be unselected.
  434. */
  435. ItemSet.prototype.setSelection = function(ids) {
  436. var i, ii, id, item;
  437. if (ids == undefined) ids = [];
  438. if (!Array.isArray(ids)) ids = [ids];
  439. // unselect currently selected items
  440. for (i = 0, ii = this.selection.length; i < ii; i++) {
  441. id = this.selection[i];
  442. item = this.items[id];
  443. if (item) item.unselect();
  444. }
  445. // select items
  446. this.selection = [];
  447. for (i = 0, ii = ids.length; i < ii; i++) {
  448. id = ids[i];
  449. item = this.items[id];
  450. if (item) {
  451. this.selection.push(id);
  452. item.select();
  453. }
  454. }
  455. };
  456. /**
  457. * Get the selected items by their id
  458. * @return {Array} ids The ids of the selected items
  459. */
  460. ItemSet.prototype.getSelection = function() {
  461. return this.selection.concat([]);
  462. };
  463. /**
  464. * Get the id's of the currently visible items.
  465. * @returns {Array} The ids of the visible items
  466. */
  467. ItemSet.prototype.getVisibleItems = function() {
  468. var range = this.body.range.getRange();
  469. if (this.options.rtl) {
  470. var right = this.body.util.toScreen(range.start);
  471. var left = this.body.util.toScreen(range.end);
  472. } else {
  473. var left = this.body.util.toScreen(range.start);
  474. var right = this.body.util.toScreen(range.end);
  475. }
  476. var ids = [];
  477. for (var groupId in this.groups) {
  478. if (this.groups.hasOwnProperty(groupId)) {
  479. var group = this.groups[groupId];
  480. var rawVisibleItems = group.isVisible ? group.visibleItems : [];
  481. // filter the "raw" set with visibleItems into a set which is really
  482. // visible by pixels
  483. for (var i = 0; i < rawVisibleItems.length; i++) {
  484. var item = rawVisibleItems[i];
  485. // TODO: also check whether visible vertically
  486. if (this.options.rtl) {
  487. if ((item.right < left) && (item.right + item.width > right)) {
  488. ids.push(item.id);
  489. }
  490. } else {
  491. if ((item.left < right) && (item.left + item.width > left)) {
  492. ids.push(item.id);
  493. }
  494. }
  495. }
  496. }
  497. }
  498. return ids;
  499. };
  500. /**
  501. * Deselect a selected item
  502. * @param {String | Number} id
  503. * @private
  504. */
  505. ItemSet.prototype._deselect = function(id) {
  506. var selection = this.selection;
  507. for (var i = 0, ii = selection.length; i < ii; i++) {
  508. if (selection[i] == id) { // non-strict comparison!
  509. selection.splice(i, 1);
  510. break;
  511. }
  512. }
  513. };
  514. /**
  515. * Repaint the component
  516. * @return {boolean} Returns true if the component is resized
  517. */
  518. ItemSet.prototype.redraw = function() {
  519. var margin = this.options.margin,
  520. range = this.body.range,
  521. asSize = util.option.asSize,
  522. options = this.options,
  523. orientation = options.orientation.item,
  524. resized = false,
  525. frame = this.dom.frame;
  526. // recalculate absolute position (before redrawing groups)
  527. this.props.top = this.body.domProps.top.height + this.body.domProps.border.top;
  528. if (this.options.rtl) {
  529. this.props.right = this.body.domProps.right.width + this.body.domProps.border.right;
  530. } else {
  531. this.props.left = this.body.domProps.left.width + this.body.domProps.border.left;
  532. }
  533. // update class name
  534. frame.className = 'vis-itemset';
  535. // reorder the groups (if needed)
  536. resized = this._orderGroups() || resized;
  537. // check whether zoomed (in that case we need to re-stack everything)
  538. // TODO: would be nicer to get this as a trigger from Range
  539. var visibleInterval = range.end - range.start;
  540. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.props.width != this.props.lastWidth);
  541. var scrolled = range.start != this.lastRangeStart;
  542. var forceRestack = (zoomed || scrolled);
  543. this.lastVisibleInterval = visibleInterval;
  544. this.lastRangeStart = range.start;
  545. this.props.lastWidth = this.props.width;
  546. var firstGroup = this._firstGroup();
  547. var firstMargin = {
  548. item: margin.item,
  549. axis: margin.axis
  550. };
  551. var nonFirstMargin = {
  552. item: margin.item,
  553. axis: margin.item.vertical / 2
  554. };
  555. var height = 0;
  556. var minHeight = margin.axis + margin.item.vertical;
  557. // redraw the background group
  558. this.groups[BACKGROUND].redraw(range, nonFirstMargin, forceRestack);
  559. // redraw all regular groups
  560. util.forEach(this.groups, function (group) {
  561. var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
  562. var groupResized = group.redraw(range, groupMargin, forceRestack);
  563. resized = groupResized || resized;
  564. height += group.height;
  565. });
  566. height = Math.max(height, minHeight);
  567. // update frame height
  568. frame.style.height = asSize(height);
  569. // calculate actual size
  570. this.props.width = frame.offsetWidth;
  571. this.props.height = height;
  572. // reposition axis
  573. this.dom.axis.style.top = asSize((orientation == 'top') ?
  574. (this.body.domProps.top.height + this.body.domProps.border.top) :
  575. (this.body.domProps.top.height + this.body.domProps.centerContainer.height));
  576. if (this.options.rtl) {
  577. this.dom.axis.style.right = '0';
  578. } else {
  579. this.dom.axis.style.left = '0';
  580. }
  581. this.initialItemSetDrawn = true;
  582. // check if this component is resized
  583. resized = this._isResized() || resized;
  584. return resized;
  585. };
  586. /**
  587. * Get the first group, aligned with the axis
  588. * @return {Group | null} firstGroup
  589. * @private
  590. */
  591. ItemSet.prototype._firstGroup = function() {
  592. var firstGroupIndex = (this.options.orientation.item == 'top') ? 0 : (this.groupIds.length - 1);
  593. var firstGroupId = this.groupIds[firstGroupIndex];
  594. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  595. return firstGroup || null;
  596. };
  597. /**
  598. * Create or delete the group holding all ungrouped items. This group is used when
  599. * there are no groups specified.
  600. * @protected
  601. */
  602. ItemSet.prototype._updateUngrouped = function() {
  603. var ungrouped = this.groups[UNGROUPED];
  604. var background = this.groups[BACKGROUND];
  605. var item, itemId;
  606. if (this.groupsData) {
  607. // remove the group holding all ungrouped items
  608. if (ungrouped) {
  609. ungrouped.hide();
  610. delete this.groups[UNGROUPED];
  611. for (itemId in this.items) {
  612. if (this.items.hasOwnProperty(itemId)) {
  613. item = this.items[itemId];
  614. item.parent && item.parent.remove(item);
  615. var groupId = this._getGroupId(item.data);
  616. var group = this.groups[groupId];
  617. group && group.add(item) || item.hide();
  618. }
  619. }
  620. }
  621. }
  622. else {
  623. // create a group holding all (unfiltered) items
  624. if (!ungrouped) {
  625. var id = null;
  626. var data = null;
  627. ungrouped = new Group(id, data, this);
  628. this.groups[UNGROUPED] = ungrouped;
  629. for (itemId in this.items) {
  630. if (this.items.hasOwnProperty(itemId)) {
  631. item = this.items[itemId];
  632. ungrouped.add(item);
  633. }
  634. }
  635. ungrouped.show();
  636. }
  637. }
  638. };
  639. /**
  640. * Get the element for the labelset
  641. * @return {HTMLElement} labelSet
  642. */
  643. ItemSet.prototype.getLabelSet = function() {
  644. return this.dom.labelSet;
  645. };
  646. /**
  647. * Set items
  648. * @param {vis.DataSet | null} items
  649. */
  650. ItemSet.prototype.setItems = function(items) {
  651. var me = this,
  652. ids,
  653. oldItemsData = this.itemsData;
  654. // replace the dataset
  655. if (!items) {
  656. this.itemsData = null;
  657. }
  658. else if (items instanceof DataSet || items instanceof DataView) {
  659. this.itemsData = items;
  660. }
  661. else {
  662. throw new TypeError('Data must be an instance of DataSet or DataView');
  663. }
  664. if (oldItemsData) {
  665. // unsubscribe from old dataset
  666. util.forEach(this.itemListeners, function (callback, event) {
  667. oldItemsData.off(event, callback);
  668. });
  669. // remove all drawn items
  670. ids = oldItemsData.getIds();
  671. this._onRemove(ids);
  672. }
  673. if (this.itemsData) {
  674. // subscribe to new dataset
  675. var id = this.id;
  676. util.forEach(this.itemListeners, function (callback, event) {
  677. me.itemsData.on(event, callback, id);
  678. });
  679. // add all new items
  680. ids = this.itemsData.getIds();
  681. this._onAdd(ids);
  682. // update the group holding all ungrouped items
  683. this._updateUngrouped();
  684. }
  685. this.body.emitter.emit('_change', {queue: true});
  686. };
  687. /**
  688. * Get the current items
  689. * @returns {vis.DataSet | null}
  690. */
  691. ItemSet.prototype.getItems = function() {
  692. return this.itemsData;
  693. };
  694. /**
  695. * Set groups
  696. * @param {vis.DataSet} groups
  697. */
  698. ItemSet.prototype.setGroups = function(groups) {
  699. var me = this,
  700. ids;
  701. // unsubscribe from current dataset
  702. if (this.groupsData) {
  703. util.forEach(this.groupListeners, function (callback, event) {
  704. me.groupsData.off(event, callback);
  705. });
  706. // remove all drawn groups
  707. ids = this.groupsData.getIds();
  708. this.groupsData = null;
  709. this._onRemoveGroups(ids); // note: this will cause a redraw
  710. }
  711. // replace the dataset
  712. if (!groups) {
  713. this.groupsData = null;
  714. }
  715. else if (groups instanceof DataSet || groups instanceof DataView) {
  716. this.groupsData = groups;
  717. }
  718. else {
  719. throw new TypeError('Data must be an instance of DataSet or DataView');
  720. }
  721. if (this.groupsData) {
  722. // go over all groups nesting
  723. var groupsData = this.groupsData;
  724. if (this.groupsData instanceof DataView) {
  725. groupsData = this.groupsData.getDataSet()
  726. }
  727. groupsData.get().forEach(function(group){
  728. if (group.nestedGroups) {
  729. group.nestedGroups.forEach(function(nestedGroupId) {
  730. var updatedNestedGroup = groupsData.get(nestedGroupId);
  731. updatedNestedGroup.nestedInGroup = group.id;
  732. if (group.showNested == false) {
  733. updatedNestedGroup.visible = false;
  734. }
  735. groupsData.update(updatedNestedGroup);
  736. })
  737. }
  738. })
  739. // subscribe to new dataset
  740. var id = this.id;
  741. util.forEach(this.groupListeners, function (callback, event) {
  742. me.groupsData.on(event, callback, id);
  743. });
  744. // draw all ms
  745. ids = this.groupsData.getIds();
  746. this._onAddGroups(ids);
  747. }
  748. // update the group holding all ungrouped items
  749. this._updateUngrouped();
  750. // update the order of all items in each group
  751. this._order();
  752. this.body.emitter.emit('_change', {queue: true});
  753. };
  754. /**
  755. * Get the current groups
  756. * @returns {vis.DataSet | null} groups
  757. */
  758. ItemSet.prototype.getGroups = function() {
  759. return this.groupsData;
  760. };
  761. /**
  762. * Remove an item by its id
  763. * @param {String | Number} id
  764. */
  765. ItemSet.prototype.removeItem = function(id) {
  766. var item = this.itemsData.get(id),
  767. dataset = this.itemsData.getDataSet(),
  768. itemObj = this.items[id];
  769. if (item) {
  770. // confirm deletion
  771. this.options.onRemove(item, function (item) {
  772. if (item) {
  773. // remove by id here, it is possible that an item has no id defined
  774. // itself, so better not delete by the item itself
  775. dataset.remove(id);
  776. }
  777. });
  778. }
  779. };
  780. /**
  781. * Get the time of an item based on it's data and options.type
  782. * @param {Object} itemData
  783. * @returns {string} Returns the type
  784. * @private
  785. */
  786. ItemSet.prototype._getType = function (itemData) {
  787. return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
  788. };
  789. /**
  790. * Get the group id for an item
  791. * @param {Object} itemData
  792. * @returns {string} Returns the groupId
  793. * @private
  794. */
  795. ItemSet.prototype._getGroupId = function (itemData) {
  796. var type = this._getType(itemData);
  797. if (type == 'background' && itemData.group == undefined) {
  798. return BACKGROUND;
  799. }
  800. else {
  801. return this.groupsData ? itemData.group : UNGROUPED;
  802. }
  803. };
  804. /**
  805. * Handle updated items
  806. * @param {Number[]} ids
  807. * @protected
  808. */
  809. ItemSet.prototype._onUpdate = function(ids) {
  810. var me = this;
  811. ids.forEach(function (id) {
  812. var itemData = me.itemsData.get(id, me.itemOptions);
  813. var item = me.items[id];
  814. var type = itemData ? me._getType(itemData) : null;
  815. var constructor = ItemSet.types[type];
  816. var selected;
  817. if (item) {
  818. // update item
  819. if (!constructor || !(item instanceof constructor)) {
  820. // item type has changed, delete the item and recreate it
  821. selected = item.selected; // preserve selection of this item
  822. me._removeItem(item);
  823. item = null;
  824. }
  825. else {
  826. me._updateItem(item, itemData);
  827. }
  828. }
  829. if (!item && itemData) {
  830. // create item
  831. if (constructor) {
  832. item = new constructor(itemData, me.conversion, me.options);
  833. item.id = id; // TODO: not so nice setting id afterwards
  834. me._addItem(item);
  835. if (selected) {
  836. this.selection.push(id);
  837. item.select();
  838. }
  839. }
  840. else if (type == 'rangeoverflow') {
  841. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  842. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
  843. '.vis-item.vis-range .vis-item-content {overflow: visible;}');
  844. }
  845. else {
  846. throw new TypeError('Unknown item type "' + type + '"');
  847. }
  848. }
  849. }.bind(this));
  850. this._order();
  851. this.body.emitter.emit('_change', {queue: true});
  852. };
  853. /**
  854. * Handle added items
  855. * @param {Number[]} ids
  856. * @protected
  857. */
  858. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  859. /**
  860. * Handle removed items
  861. * @param {Number[]} ids
  862. * @protected
  863. */
  864. ItemSet.prototype._onRemove = function(ids) {
  865. var count = 0;
  866. var me = this;
  867. ids.forEach(function (id) {
  868. var item = me.items[id];
  869. if (item) {
  870. count++;
  871. me._removeItem(item);
  872. }
  873. });
  874. if (count) {
  875. // update order
  876. this._order();
  877. this.body.emitter.emit('_change', {queue: true});
  878. }
  879. };
  880. /**
  881. * Update the order of item in all groups
  882. * @private
  883. */
  884. ItemSet.prototype._order = function() {
  885. // reorder the items in all groups
  886. // TODO: optimization: only reorder groups affected by the changed items
  887. util.forEach(this.groups, function (group) {
  888. group.order();
  889. });
  890. };
  891. /**
  892. * Handle updated groups
  893. * @param {Number[]} ids
  894. * @private
  895. */
  896. ItemSet.prototype._onUpdateGroups = function(ids) {
  897. this._onAddGroups(ids);
  898. };
  899. /**
  900. * Handle changed groups (added or updated)
  901. * @param {Number[]} ids
  902. * @private
  903. */
  904. ItemSet.prototype._onAddGroups = function(ids) {
  905. var me = this;
  906. ids.forEach(function (id) {
  907. var groupData = me.groupsData.get(id);
  908. var group = me.groups[id];
  909. if (!group) {
  910. // check for reserved ids
  911. if (id == UNGROUPED || id == BACKGROUND) {
  912. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  913. }
  914. var groupOptions = Object.create(me.options);
  915. util.extend(groupOptions, {
  916. height: null
  917. });
  918. group = new Group(id, groupData, me);
  919. me.groups[id] = group;
  920. // add items with this groupId to the new group
  921. for (var itemId in me.items) {
  922. if (me.items.hasOwnProperty(itemId)) {
  923. var item = me.items[itemId];
  924. if (item.data.group == id) {
  925. group.add(item);
  926. }
  927. }
  928. }
  929. group.order();
  930. group.show();
  931. }
  932. else {
  933. // update group
  934. group.setData(groupData);
  935. }
  936. });
  937. this.body.emitter.emit('_change', {queue: true});
  938. };
  939. /**
  940. * Handle removed groups
  941. * @param {Number[]} ids
  942. * @private
  943. */
  944. ItemSet.prototype._onRemoveGroups = function(ids) {
  945. var groups = this.groups;
  946. ids.forEach(function (id) {
  947. var group = groups[id];
  948. if (group) {
  949. group.hide();
  950. delete groups[id];
  951. }
  952. });
  953. this.markDirty();
  954. this.body.emitter.emit('_change', {queue: true});
  955. };
  956. /**
  957. * Reorder the groups if needed
  958. * @return {boolean} changed
  959. * @private
  960. */
  961. ItemSet.prototype._orderGroups = function () {
  962. if (this.groupsData) {
  963. // reorder the groups
  964. var groupIds = this.groupsData.getIds({
  965. order: this.options.groupOrder
  966. });
  967. groupIds = this._orderNestedGroups(groupIds);
  968. var changed = !util.equalArray(groupIds, this.groupIds);
  969. if (changed) {
  970. // hide all groups, removes them from the DOM
  971. var groups = this.groups;
  972. groupIds.forEach(function (groupId) {
  973. groups[groupId].hide();
  974. });
  975. // show the groups again, attach them to the DOM in correct order
  976. groupIds.forEach(function (groupId) {
  977. groups[groupId].show();
  978. });
  979. this.groupIds = groupIds;
  980. }
  981. return changed;
  982. }
  983. else {
  984. return false;
  985. }
  986. };
  987. /**
  988. * Reorder the nested groups
  989. * @return {boolean} changed
  990. * @private
  991. */
  992. ItemSet.prototype._orderNestedGroups = function(groupIds) {
  993. var newGroupIdsOrder = [];
  994. groupIds.forEach(function(groupId){
  995. var groupData = this.groupsData.get(groupId);
  996. if (!groupData.nestedInGroup) {
  997. newGroupIdsOrder.push(groupId)
  998. }
  999. if (groupData.nestedGroups) {
  1000. var nestedGroups = this.groupsData.get({
  1001. filter: function(nestedGroup) {
  1002. return nestedGroup.nestedInGroup == groupId;
  1003. },
  1004. order: this.options.groupOrder
  1005. });
  1006. var nestedGroupIds = nestedGroups.map(function(nestedGroup) { return nestedGroup.id })
  1007. newGroupIdsOrder = newGroupIdsOrder.concat(nestedGroupIds);
  1008. }
  1009. }, this)
  1010. return newGroupIdsOrder;
  1011. }
  1012. /**
  1013. * Add a new item
  1014. * @param {Item} item
  1015. * @private
  1016. */
  1017. ItemSet.prototype._addItem = function(item) {
  1018. this.items[item.id] = item;
  1019. // add to group
  1020. var groupId = this._getGroupId(item.data);
  1021. var group = this.groups[groupId];
  1022. if (!group) {
  1023. item.groupShowing = false;
  1024. } else if (group && group.data && group.data.showNested) {
  1025. item.groupShowing = true;
  1026. }
  1027. if (group) group.add(item);
  1028. };
  1029. /**
  1030. * Update an existing item
  1031. * @param {Item} item
  1032. * @param {Object} itemData
  1033. * @private
  1034. */
  1035. ItemSet.prototype._updateItem = function(item, itemData) {
  1036. // update the items data (will redraw the item when displayed)
  1037. item.setData(itemData);
  1038. var groupId = this._getGroupId(item.data);
  1039. var group = this.groups[groupId];
  1040. if (!group) {
  1041. item.groupShowing = false;
  1042. } else if (group && group.data && group.data.showNested) {
  1043. item.groupShowing = true;
  1044. }
  1045. };
  1046. /**
  1047. * Delete an item from the ItemSet: remove it from the DOM, from the map
  1048. * with items, and from the map with visible items, and from the selection
  1049. * @param {Item} item
  1050. * @private
  1051. */
  1052. ItemSet.prototype._removeItem = function(item) {
  1053. // remove from DOM
  1054. item.hide();
  1055. // remove from items
  1056. delete this.items[item.id];
  1057. // remove from selection
  1058. var index = this.selection.indexOf(item.id);
  1059. if (index != -1) this.selection.splice(index, 1);
  1060. // remove from group
  1061. item.parent && item.parent.remove(item);
  1062. };
  1063. /**
  1064. * Create an array containing all items being a range (having an end date)
  1065. * @param array
  1066. * @returns {Array}
  1067. * @private
  1068. */
  1069. ItemSet.prototype._constructByEndArray = function(array) {
  1070. var endArray = [];
  1071. for (var i = 0; i < array.length; i++) {
  1072. if (array[i] instanceof RangeItem) {
  1073. endArray.push(array[i]);
  1074. }
  1075. }
  1076. return endArray;
  1077. };
  1078. /**
  1079. * Register the clicked item on touch, before dragStart is initiated.
  1080. *
  1081. * dragStart is initiated from a mousemove event, AFTER the mouse/touch is
  1082. * already moving. Therefore, the mouse/touch can sometimes be above an other
  1083. * DOM element than the item itself.
  1084. *
  1085. * @param {Event} event
  1086. * @private
  1087. */
  1088. ItemSet.prototype._onTouch = function (event) {
  1089. // store the touched item, used in _onDragStart
  1090. this.touchParams.item = this.itemFromTarget(event);
  1091. this.touchParams.dragLeftItem = event.target.dragLeftItem || false;
  1092. this.touchParams.dragRightItem = event.target.dragRightItem || false;
  1093. this.touchParams.itemProps = null;
  1094. };
  1095. /**
  1096. * Given an group id, returns the index it has.
  1097. *
  1098. * @param {Number} groupID
  1099. * @private
  1100. */
  1101. ItemSet.prototype._getGroupIndex = function(groupId) {
  1102. for (var i = 0; i < this.groupIds.length; i++) {
  1103. if (groupId == this.groupIds[i])
  1104. return i;
  1105. }
  1106. };
  1107. /**
  1108. * Start dragging the selected events
  1109. * @param {Event} event
  1110. * @private
  1111. */
  1112. ItemSet.prototype._onDragStart = function (event) {
  1113. if (this.touchParams.itemIsDragging) { return; }
  1114. var item = this.touchParams.item || null;
  1115. var me = this;
  1116. var props;
  1117. if (item && (item.selected || this.options.itemsAlwaysDraggable)) {
  1118. if (this.options.editable.overrideItems &&
  1119. !this.options.editable.updateTime &&
  1120. !this.options.editable.updateGroup) {
  1121. return;
  1122. }
  1123. // override options.editable
  1124. if ((item.editable != null && !item.editable.updateTime && !item.editable.updateGroup)
  1125. && !this.options.editable.overrideItems) {
  1126. return;
  1127. }
  1128. var dragLeftItem = this.touchParams.dragLeftItem;
  1129. var dragRightItem = this.touchParams.dragRightItem;
  1130. this.touchParams.itemIsDragging = true;
  1131. this.touchParams.selectedItem = item;
  1132. if (dragLeftItem) {
  1133. props = {
  1134. item: dragLeftItem,
  1135. initialX: event.center.x,
  1136. dragLeft: true,
  1137. data: this._cloneItemData(item.data)
  1138. };
  1139. this.touchParams.itemProps = [props];
  1140. }
  1141. else if (dragRightItem) {
  1142. props = {
  1143. item: dragRightItem,
  1144. initialX: event.center.x,
  1145. dragRight: true,
  1146. data: this._cloneItemData(item.data)
  1147. };
  1148. this.touchParams.itemProps = [props];
  1149. }
  1150. else {
  1151. var baseGroupIndex = this._getGroupIndex(item.data.group);
  1152. var itemsToDrag = (this.options.itemsAlwaysDraggable && !item.selected) ? [item.id] : this.getSelection();
  1153. this.touchParams.itemProps = itemsToDrag.map(function (id) {
  1154. var item = me.items[id];
  1155. var groupIndex = me._getGroupIndex(item.data.group);
  1156. return {
  1157. item: item,
  1158. initialX: event.center.x,
  1159. groupOffset: baseGroupIndex-groupIndex,
  1160. data: this._cloneItemData(item.data)
  1161. };
  1162. }.bind(this));
  1163. }
  1164. event.stopPropagation();
  1165. }
  1166. else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  1167. // create a new range item when dragging with ctrl key down
  1168. this._onDragStartAddItem(event);
  1169. }
  1170. };
  1171. /**
  1172. * Start creating a new range item by dragging.
  1173. * @param {Event} event
  1174. * @private
  1175. */
  1176. ItemSet.prototype._onDragStartAddItem = function (event) {
  1177. var snap = this.options.snap || null;
  1178. if (this.options.rtl) {
  1179. var xAbs = util.getAbsoluteRight(this.dom.frame);
  1180. var x = xAbs - event.center.x + 10; // plus 10 to compensate for the drag starting as soon as you've moved 10px
  1181. } else {
  1182. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1183. var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  1184. }
  1185. var time = this.body.util.toTime(x);
  1186. var scale = this.body.util.getScale();
  1187. var step = this.body.util.getStep();
  1188. var start = snap ? snap(time, scale, step) : time;
  1189. var end = start;
  1190. var itemData = {
  1191. type: 'range',
  1192. start: start,
  1193. end: end,
  1194. content: 'new item'
  1195. };
  1196. var id = util.randomUUID();
  1197. itemData[this.itemsData._fieldId] = id;
  1198. var group = this.groupFromTarget(event);
  1199. if (group) {
  1200. itemData.group = group.groupId;
  1201. }
  1202. var newItem = new RangeItem(itemData, this.conversion, this.options);
  1203. newItem.id = id; // TODO: not so nice setting id afterwards
  1204. newItem.data = this._cloneItemData(itemData);
  1205. this._addItem(newItem);
  1206. this.touchParams.selectedItem = newItem;
  1207. var props = {
  1208. item: newItem,
  1209. initialX: event.center.x,
  1210. data: newItem.data
  1211. };
  1212. if (this.options.rtl) {
  1213. props.dragLeft = true;
  1214. } else {
  1215. props.dragRight = true;
  1216. }
  1217. this.touchParams.itemProps = [props];
  1218. event.stopPropagation();
  1219. };
  1220. /**
  1221. * Drag selected items
  1222. * @param {Event} event
  1223. * @private
  1224. */
  1225. ItemSet.prototype._onDrag = function (event) {
  1226. if (this.touchParams.itemProps) {
  1227. event.stopPropagation();
  1228. var me = this;
  1229. var snap = this.options.snap || null;
  1230. if (this.options.rtl) {
  1231. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.right.width;
  1232. } else {
  1233. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  1234. }
  1235. var scale = this.body.util.getScale();
  1236. var step = this.body.util.getStep();
  1237. //only calculate the new group for the item that's actually dragged
  1238. var selectedItem = this.touchParams.selectedItem;
  1239. var updateGroupAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateGroup) ||
  1240. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateGroup);
  1241. var newGroupBase = null;
  1242. if (updateGroupAllowed && selectedItem) {
  1243. if (selectedItem.data.group != undefined) {
  1244. // drag from one group to another
  1245. var group = me.groupFromTarget(event);
  1246. if (group) {
  1247. //we know the offset for all items, so the new group for all items
  1248. //will be relative to this one.
  1249. newGroupBase = this._getGroupIndex(group.groupId);
  1250. }
  1251. }
  1252. }
  1253. // move
  1254. this.touchParams.itemProps.forEach(function (props) {
  1255. var current = me.body.util.toTime(event.center.x - xOffset);
  1256. var initial = me.body.util.toTime(props.initialX - xOffset);
  1257. if (this.options.rtl) {
  1258. var offset = -(current - initial); // ms
  1259. } else {
  1260. var offset = (current - initial); // ms
  1261. }
  1262. var itemData = this._cloneItemData(props.item.data); // clone the data
  1263. if (props.item.editable != null
  1264. && !props.item.editable.updateTime
  1265. && !props.item.editable.updateGroup
  1266. && !me.options.editable.overrideItems) {
  1267. return;
  1268. }
  1269. var updateTimeAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateTime) ||
  1270. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateTime);
  1271. if (updateTimeAllowed) {
  1272. if (props.dragLeft) {
  1273. // drag left side of a range item
  1274. if (this.options.rtl) {
  1275. if (itemData.end != undefined) {
  1276. var initialEnd = util.convert(props.data.end, 'Date');
  1277. var end = new Date(initialEnd.valueOf() + offset);
  1278. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1279. itemData.end = snap ? snap(end, scale, step) : end;
  1280. }
  1281. } else {
  1282. if (itemData.start != undefined) {
  1283. var initialStart = util.convert(props.data.start, 'Date');
  1284. var start = new Date(initialStart.valueOf() + offset);
  1285. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1286. itemData.start = snap ? snap(start, scale, step) : start;
  1287. }
  1288. }
  1289. }
  1290. else if (props.dragRight) {
  1291. // drag right side of a range item
  1292. if (this.options.rtl) {
  1293. if (itemData.start != undefined) {
  1294. var initialStart = util.convert(props.data.start, 'Date');
  1295. var start = new Date(initialStart.valueOf() + offset);
  1296. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1297. itemData.start = snap ? snap(start, scale, step) : start;
  1298. }
  1299. } else {
  1300. if (itemData.end != undefined) {
  1301. var initialEnd = util.convert(props.data.end, 'Date');
  1302. var end = new Date(initialEnd.valueOf() + offset);
  1303. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1304. itemData.end = snap ? snap(end, scale, step) : end;
  1305. }
  1306. }
  1307. }
  1308. else {
  1309. // drag both start and end
  1310. if (itemData.start != undefined) {
  1311. var initialStart = util.convert(props.data.start, 'Date').valueOf();
  1312. var start = new Date(initialStart + offset);
  1313. if (itemData.end != undefined) {
  1314. var initialEnd = util.convert(props.data.end, 'Date');
  1315. var duration = initialEnd.valueOf() - initialStart.valueOf();
  1316. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1317. itemData.start = snap ? snap(start, scale, step) : start;
  1318. itemData.end = new Date(itemData.start.valueOf() + duration);
  1319. }
  1320. else {
  1321. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1322. itemData.start = snap ? snap(start, scale, step) : start;
  1323. }
  1324. }
  1325. }
  1326. }
  1327. if (updateGroupAllowed && (!props.dragLeft && !props.dragRight) && newGroupBase!=null) {
  1328. if (itemData.group != undefined) {
  1329. var newOffset = newGroupBase - props.groupOffset;
  1330. //make sure we stay in bounds
  1331. newOffset = Math.max(0, newOffset);
  1332. newOffset = Math.min(me.groupIds.length-1, newOffset);
  1333. itemData.group = me.groupIds[newOffset];
  1334. }
  1335. }
  1336. // confirm moving the item
  1337. itemData = this._cloneItemData(itemData); // convert start and end to the correct type
  1338. me.options.onMoving(itemData, function (itemData) {
  1339. if (itemData) {
  1340. props.item.setData(this._cloneItemData(itemData, 'Date'));
  1341. }
  1342. }.bind(this));
  1343. }.bind(this));
  1344. this.body.emitter.emit('_change');
  1345. }
  1346. };
  1347. /**
  1348. * Move an item to another group
  1349. * @param {Item} item
  1350. * @param {String | Number} groupId
  1351. * @private
  1352. */
  1353. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1354. var group = this.groups[groupId];
  1355. if (group && group.groupId != item.data.group) {
  1356. var oldGroup = item.parent;
  1357. oldGroup.remove(item);
  1358. oldGroup.order();
  1359. item.data.group = group.groupId;
  1360. group.add(item);
  1361. group.order();
  1362. }
  1363. };
  1364. /**
  1365. * End of dragging selected items
  1366. * @param {Event} event
  1367. * @private
  1368. */
  1369. ItemSet.prototype._onDragEnd = function (event) {
  1370. this.touchParams.itemIsDragging = false;
  1371. if (this.touchParams.itemProps) {
  1372. event.stopPropagation();
  1373. var me = this;
  1374. var dataset = this.itemsData.getDataSet();
  1375. var itemProps = this.touchParams.itemProps ;
  1376. this.touchParams.itemProps = null;
  1377. itemProps.forEach(function (props) {
  1378. var id = props.item.id;
  1379. var exists = me.itemsData.get(id, me.itemOptions) != null;
  1380. if (!exists) {
  1381. // add a new item
  1382. me.options.onAdd(props.item.data, function (itemData) {
  1383. me._removeItem(props.item); // remove temporary item
  1384. if (itemData) {
  1385. me.itemsData.getDataSet().add(itemData);
  1386. }
  1387. // force re-stacking of all items next redraw
  1388. me.body.emitter.emit('_change');
  1389. });
  1390. }
  1391. else {
  1392. // update existing item
  1393. var itemData = this._cloneItemData(props.item.data); // convert start and end to the correct type
  1394. me.options.onMove(itemData, function (itemData) {
  1395. if (itemData) {
  1396. // apply changes
  1397. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1398. dataset.update(itemData);
  1399. }
  1400. else {
  1401. // restore original values
  1402. props.item.setData(props.data);
  1403. me.body.emitter.emit('_change');
  1404. }
  1405. });
  1406. }
  1407. }.bind(this));
  1408. }
  1409. };
  1410. ItemSet.prototype._onGroupClick = function (event) {
  1411. var group = this.groupFromTarget(event);
  1412. if (!group || !group.nestedGroups) return;
  1413. var groupsData = this.groupsData;
  1414. if (this.groupsData instanceof DataView) {
  1415. groupsData = this.groupsData.getDataSet()
  1416. }
  1417. group.showNested = !group.showNested;
  1418. var nestedGroups = groupsData.get(group.nestedGroups).map(function(nestedGroup) {
  1419. if (nestedGroup.visible == undefined) { nestedGroup.visible = true; }
  1420. nestedGroup.visible = !!group.showNested;
  1421. return nestedGroup;
  1422. });
  1423. groupsData.update(nestedGroups);
  1424. if (group.showNested) {
  1425. util.removeClassName(group.dom.label, 'collapsed');
  1426. util.addClassName(group.dom.label, 'expanded');
  1427. } else {
  1428. util.removeClassName(group.dom.label, 'expanded');
  1429. var collapsedDirClassName = this.options.rtl ? 'collapsed-rtl' : 'collapsed'
  1430. util.addClassName(group.dom.label, collapsedDirClassName);
  1431. }
  1432. }
  1433. ItemSet.prototype._onGroupDragStart = function (event) {
  1434. if (this.options.groupEditable.order) {
  1435. this.groupTouchParams.group = this.groupFromTarget(event);
  1436. if (this.groupTouchParams.group) {
  1437. event.stopPropagation();
  1438. this.groupTouchParams.originalOrder = this.groupsData.getIds({
  1439. order: this.options.groupOrder
  1440. });
  1441. }
  1442. }
  1443. }
  1444. ItemSet.prototype._onGroupDrag = function (event) {
  1445. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1446. event.stopPropagation();
  1447. var groupsData = this.groupsData;
  1448. if (this.groupsData instanceof DataView) {
  1449. groupsData = this.groupsData.getDataSet()
  1450. }
  1451. // drag from one group to another
  1452. var group = this.groupFromTarget(event);
  1453. // try to avoid toggling when groups differ in height
  1454. if (group && group.height != this.groupTouchParams.group.height) {
  1455. var movingUp = (group.top < this.groupTouchParams.group.top);
  1456. var clientY = event.center ? event.center.y : event.clientY;
  1457. var targetGroupTop = util.getAbsoluteTop(group.dom.foreground);
  1458. var draggedGroupHeight = this.groupTouchParams.group.height;
  1459. if (movingUp) {
  1460. // skip swapping the groups when the dragged group is not below clientY afterwards
  1461. if (targetGroupTop + draggedGroupHeight < clientY) {
  1462. return;
  1463. }
  1464. } else {
  1465. var targetGroupHeight = group.height;
  1466. // skip swapping the groups when the dragged group is not below clientY afterwards
  1467. if (targetGroupTop + targetGroupHeight - draggedGroupHeight > clientY) {
  1468. return;
  1469. }
  1470. }
  1471. }
  1472. if (group && group != this.groupTouchParams.group) {
  1473. var targetGroup = groupsData.get(group.groupId);
  1474. var draggedGroup = groupsData.get(this.groupTouchParams.group.groupId);
  1475. // switch groups
  1476. if (draggedGroup && targetGroup) {
  1477. this.options.groupOrderSwap(draggedGroup, targetGroup, groupsData);
  1478. groupsData.update(draggedGroup);
  1479. groupsData.update(targetGroup);
  1480. }
  1481. // fetch current order of groups
  1482. var newOrder = groupsData.getIds({
  1483. order: this.options.groupOrder
  1484. });
  1485. // in case of changes since _onGroupDragStart
  1486. if (!util.equalArray(newOrder, this.groupTouchParams.originalOrder)) {
  1487. var origOrder = this.groupTouchParams.originalOrder;
  1488. var draggedId = this.groupTouchParams.group.groupId;
  1489. var numGroups = Math.min(origOrder.length, newOrder.length);
  1490. var curPos = 0;
  1491. var newOffset = 0;
  1492. var orgOffset = 0;
  1493. while (curPos < numGroups) {
  1494. // as long as the groups are where they should be step down along the groups order
  1495. while ((curPos+newOffset) < numGroups
  1496. && (curPos+orgOffset) < numGroups
  1497. && newOrder[curPos+newOffset] == origOrder[curPos+orgOffset]) {
  1498. curPos++;
  1499. }
  1500. // all ok
  1501. if (curPos+newOffset >= numGroups) {
  1502. break;
  1503. }
  1504. // not all ok
  1505. // if dragged group was move upwards everything below should have an offset
  1506. if (newOrder[curPos+newOffset] == draggedId) {
  1507. newOffset = 1;
  1508. continue;
  1509. }
  1510. // if dragged group was move downwards everything above should have an offset
  1511. else if (origOrder[curPos+orgOffset] == draggedId) {
  1512. orgOffset = 1;
  1513. continue;
  1514. }
  1515. // found a group (apart from dragged group) that has the wrong position -> switch with the
  1516. // group at the position where other one should be, fix index arrays and continue
  1517. else {
  1518. var slippedPosition = newOrder.indexOf(origOrder[curPos+orgOffset])
  1519. var switchGroup = groupsData.get(newOrder[curPos+newOffset]);
  1520. var shouldBeGroup = groupsData.get(origOrder[curPos+orgOffset]);
  1521. this.options.groupOrderSwap(switchGroup, shouldBeGroup, groupsData);
  1522. groupsData.update(switchGroup);
  1523. groupsData.update(shouldBeGroup);
  1524. var switchGroupId = newOrder[curPos+newOffset];
  1525. newOrder[curPos+newOffset] = origOrder[curPos+orgOffset];
  1526. newOrder[slippedPosition] = switchGroupId;
  1527. curPos++;
  1528. }
  1529. }
  1530. }
  1531. }
  1532. }
  1533. }
  1534. ItemSet.prototype._onGroupDragEnd = function (event) {
  1535. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1536. event.stopPropagation();
  1537. // update existing group
  1538. var me = this;
  1539. var id = me.groupTouchParams.group.groupId;
  1540. var dataset = me.groupsData.getDataSet();
  1541. var groupData = util.extend({}, dataset.get(id)); // clone the data
  1542. me.options.onMoveGroup(groupData, function (groupData) {
  1543. if (groupData) {
  1544. // apply changes
  1545. groupData[dataset._fieldId] = id; // ensure the group contains its id (can be undefined)
  1546. dataset.update(groupData);
  1547. }
  1548. else {
  1549. // fetch current order of groups
  1550. var newOrder = dataset.getIds({
  1551. order: me.options.groupOrder
  1552. });
  1553. // restore original order
  1554. if (!util.equalArray(newOrder, me.groupTouchParams.originalOrder)) {
  1555. var origOrder = me.groupTouchParams.originalOrder;
  1556. var numGroups = Math.min(origOrder.length, newOrder.length);
  1557. var curPos = 0;
  1558. while (curPos < numGroups) {
  1559. // as long as the groups are where they should be step down along the groups order
  1560. while (curPos < numGroups && newOrder[curPos] == origOrder[curPos]) {
  1561. curPos++;
  1562. }
  1563. // all ok
  1564. if (curPos >= numGroups) {
  1565. break;
  1566. }
  1567. // found a group that has the wrong position -> switch with the
  1568. // group at the position where other one should be, fix index arrays and continue
  1569. var slippedPosition = newOrder.indexOf(origOrder[curPos])
  1570. var switchGroup = dataset.get(newOrder[curPos]);
  1571. var shouldBeGroup = dataset.get(origOrder[curPos]);
  1572. me.options.groupOrderSwap(switchGroup, shouldBeGroup, dataset);
  1573. dataset.update(switchGroup);
  1574. dataset.update(shouldBeGroup);
  1575. var switchGroupId = newOrder[curPos];
  1576. newOrder[curPos] = origOrder[curPos];
  1577. newOrder[slippedPosition] = switchGroupId;
  1578. curPos++;
  1579. }
  1580. }
  1581. }
  1582. });
  1583. me.body.emitter.emit('groupDragged', { groupId: id });
  1584. }
  1585. }
  1586. /**
  1587. * Handle selecting/deselecting an item when tapping it
  1588. * @param {Event} event
  1589. * @private
  1590. */
  1591. ItemSet.prototype._onSelectItem = function (event) {
  1592. if (!this.options.selectable) return;
  1593. var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey);
  1594. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  1595. if (ctrlKey || shiftKey) {
  1596. this._onMultiSelectItem(event);
  1597. return;
  1598. }
  1599. var oldSelection = this.getSelection();
  1600. var item = this.itemFromTarget(event);
  1601. var selection = item ? [item.id] : [];
  1602. this.setSelection(selection);
  1603. var newSelection = this.getSelection();
  1604. // emit a select event,
  1605. // except when old selection is empty and new selection is still empty
  1606. if (newSelection.length > 0 || oldSelection.length > 0) {
  1607. this.body.emitter.emit('select', {
  1608. items: newSelection,
  1609. event: event
  1610. });
  1611. }
  1612. };
  1613. /**
  1614. * Handle hovering an item
  1615. * @param {Event} event
  1616. * @private
  1617. */
  1618. ItemSet.prototype._onMouseOver = function (event) {
  1619. var item = this.itemFromTarget(event);
  1620. if (!item) return;
  1621. // Item we just left
  1622. var related = this.itemFromRelatedTarget(event);
  1623. if (item === related) {
  1624. // We haven't changed item, just element in the item
  1625. return;
  1626. }
  1627. var title = item.getTitle();
  1628. if (this.options.showTooltips && title) {
  1629. if (this.popup == null) {
  1630. this.popup = new Popup(this.body.dom.root,
  1631. this.options.tooltip.overflowMethod || 'flip');
  1632. }
  1633. this.popup.setText(title);
  1634. var container = this.body.dom.centerContainer;
  1635. this.popup.setPosition(
  1636. event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft,
  1637. event.clientY - util.getAbsoluteTop(container) + container.offsetTop
  1638. );
  1639. this.popup.show();
  1640. } else {
  1641. // Hovering over item without a title, hide popup
  1642. // Needed instead of _just_ in _onMouseOut due to #2572
  1643. if (this.popup != null) {
  1644. this.popup.hide();
  1645. }
  1646. }
  1647. this.body.emitter.emit('itemover', {
  1648. item: item.id,
  1649. event: event
  1650. });
  1651. };
  1652. ItemSet.prototype._onMouseOut = function (event) {
  1653. var item = this.itemFromTarget(event);
  1654. if (!item) return;
  1655. // Item we are going to
  1656. var related = this.itemFromRelatedTarget(event);
  1657. if (item === related) {
  1658. // We aren't changing item, just element in the item
  1659. return;
  1660. }
  1661. if (this.popup != null) {
  1662. this.popup.hide();
  1663. }
  1664. this.body.emitter.emit('itemout', {
  1665. item: item.id,
  1666. event: event
  1667. });
  1668. };
  1669. ItemSet.prototype._onMouseMove = function (event) {
  1670. var item = this.itemFromTarget(event);
  1671. if (!item) return;
  1672. if (this.options.showTooltips && this.options.tooltip.followMouse) {
  1673. if (this.popup) {
  1674. if (!this.popup.hidden) {
  1675. var container = this.body.dom.centerContainer;
  1676. this.popup.setPosition(
  1677. event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft,
  1678. event.clientY - util.getAbsoluteTop(container) + container.offsetTop
  1679. );
  1680. this.popup.show(); // Redraw
  1681. }
  1682. }
  1683. }
  1684. };
  1685. /**
  1686. * Handle mousewheel
  1687. * @param event
  1688. * @private
  1689. */
  1690. ItemSet.prototype._onMouseWheel = function(event) {
  1691. if (this.touchParams.itemIsDragging) {
  1692. this._onDragEnd(event);
  1693. }
  1694. }
  1695. /**
  1696. * Handle updates of an item on double tap
  1697. * @param event
  1698. * @private
  1699. */
  1700. ItemSet.prototype._onUpdateItem = function (item) {
  1701. if (!this.options.selectable) return;
  1702. if (!this.options.editable.add) return;
  1703. var me = this;
  1704. if (item) {
  1705. // execute async handler to update the item (or cancel it)
  1706. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  1707. this.options.onUpdate(itemData, function (itemData) {
  1708. if (itemData) {
  1709. me.itemsData.getDataSet().update(itemData);
  1710. }
  1711. });
  1712. }
  1713. }
  1714. /**
  1715. * Handle creation of an item on double tap
  1716. * @param event
  1717. * @private
  1718. */
  1719. ItemSet.prototype._onAddItem = function (event) {
  1720. if (!this.options.selectable) return;
  1721. if (!this.options.editable.add) return;
  1722. var me = this;
  1723. var snap = this.options.snap || null;
  1724. var item = this.itemFromTarget(event);
  1725. if (!item) {
  1726. // add item
  1727. if (this.options.rtl) {
  1728. var xAbs = util.getAbsoluteRight(this.dom.frame);
  1729. var x = xAbs - event.center.x;
  1730. } else {
  1731. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1732. var x = event.center.x - xAbs;
  1733. }
  1734. // var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1735. // var x = event.center.x - xAbs;
  1736. var start = this.body.util.toTime(x);
  1737. var scale = this.body.util.getScale();
  1738. var step = this.body.util.getStep();
  1739. var newItemData;
  1740. if (event.type == 'drop') {
  1741. newItemData = JSON.parse(event.dataTransfer.getData("text"))
  1742. newItemData.content = newItemData.content ? newItemData.content : 'new item'
  1743. newItemData.start = newItemData.start ? newItemData.start : (snap ? snap(start, scale, step) : start)
  1744. newItemData.type = newItemData.type || 'box';
  1745. newItemData[this.itemsData._fieldId] = newItemData.id || util.randomUUID();
  1746. if (newItemData.type == 'range' && !newItemData.end) {
  1747. var end = this.body.util.toTime(x + this.props.width / 5);
  1748. newItemData.end = snap ? snap(end, scale, step) : end;
  1749. }
  1750. } else {
  1751. newItemData = {
  1752. start: snap ? snap(start, scale, step) : start,
  1753. content: 'new item'
  1754. };
  1755. newItemData[this.itemsData._fieldId] = util.randomUUID();
  1756. // when default type is a range, add a default end date to the new item
  1757. if (this.options.type === 'range') {
  1758. var end = this.body.util.toTime(x + this.props.width / 5);
  1759. newItemData.end = snap ? snap(end, scale, step) : end;
  1760. }
  1761. }
  1762. var group = this.groupFromTarget(event);
  1763. if (group) {
  1764. newItemData.group = group.groupId;
  1765. }
  1766. // execute async handler to customize (or cancel) adding an item
  1767. newItemData = this._cloneItemData(newItemData); // convert start and end to the correct type
  1768. this.options.onAdd(newItemData, function (item) {
  1769. if (item) {
  1770. me.itemsData.getDataSet().add(item);
  1771. if (event.type == 'drop') {
  1772. me.setSelection([item.id]);
  1773. }
  1774. // TODO: need to trigger a redraw?
  1775. }
  1776. });
  1777. }
  1778. };
  1779. /**
  1780. * Handle selecting/deselecting multiple items when holding an item
  1781. * @param {Event} event
  1782. * @private
  1783. */
  1784. ItemSet.prototype._onMultiSelectItem = function (event) {
  1785. if (!this.options.selectable) return;
  1786. var item = this.itemFromTarget(event);
  1787. if (item) {
  1788. // multi select items (if allowed)
  1789. var selection = this.options.multiselect
  1790. ? this.getSelection() // take current selection
  1791. : []; // deselect current selection
  1792. var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false;
  1793. if (shiftKey && this.options.multiselect) {
  1794. // select all items between the old selection and the tapped item
  1795. var itemGroup = this.itemsData.get(item.id).group;
  1796. // when filtering get the group of the last selected item
  1797. var lastSelectedGroup = undefined;
  1798. if (this.options.multiselectPerGroup) {
  1799. if (selection.length > 0) {
  1800. lastSelectedGroup = this.itemsData.get(selection[0]).group;
  1801. }
  1802. }
  1803. // determine the selection range
  1804. if (!this.options.multiselectPerGroup || lastSelectedGroup == undefined || lastSelectedGroup == itemGroup) {
  1805. selection.push(item.id);
  1806. }
  1807. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  1808. if (!this.options.multiselectPerGroup || lastSelectedGroup == itemGroup) {
  1809. // select all items within the selection range
  1810. selection = [];
  1811. for (var id in this.items) {
  1812. if (this.items.hasOwnProperty(id)) {
  1813. var _item = this.items[id];
  1814. var start = _item.data.start;
  1815. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  1816. if (start >= range.min &&
  1817. end <= range.max &&
  1818. (!this.options.multiselectPerGroup || lastSelectedGroup == this.itemsData.get(_item.id).group) &&
  1819. !(_item instanceof BackgroundItem)) {
  1820. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  1821. }
  1822. }
  1823. }
  1824. }
  1825. }
  1826. else {
  1827. // add/remove this item from the current selection
  1828. var index = selection.indexOf(item.id);
  1829. if (index == -1) {
  1830. // item is not yet selected -> select it
  1831. selection.push(item.id);
  1832. }
  1833. else {
  1834. // item is already selected -> deselect it
  1835. selection.splice(index, 1);
  1836. }
  1837. }
  1838. this.setSelection(selection);
  1839. this.body.emitter.emit('select', {
  1840. items: this.getSelection(),
  1841. event: event
  1842. });
  1843. }
  1844. };
  1845. /**
  1846. * Calculate the time range of a list of items
  1847. * @param {Array.<Object>} itemsData
  1848. * @return {{min: Date, max: Date}} Returns the range of the provided items
  1849. * @private
  1850. */
  1851. ItemSet._getItemRange = function(itemsData) {
  1852. var max = null;
  1853. var min = null;
  1854. itemsData.forEach(function (data) {
  1855. if (min == null || data.start < min) {
  1856. min = data.start;
  1857. }
  1858. if (data.end != undefined) {
  1859. if (max == null || data.end > max) {
  1860. max = data.end;
  1861. }
  1862. }
  1863. else {
  1864. if (max == null || data.start > max) {
  1865. max = data.start;
  1866. }
  1867. }
  1868. });
  1869. return {
  1870. min: min,
  1871. max: max
  1872. }
  1873. };
  1874. /**
  1875. * Find an item from an element:
  1876. * searches for the attribute 'timeline-item' in the element's tree
  1877. * @param {HTMLElement} element
  1878. * @return {Item | null} item
  1879. */
  1880. ItemSet.prototype.itemFromElement = function(element) {
  1881. var cur = element;
  1882. while (cur) {
  1883. if (cur.hasOwnProperty('timeline-item')) {
  1884. return cur['timeline-item'];
  1885. }
  1886. cur = cur.parentNode;
  1887. }
  1888. return null;
  1889. };
  1890. /**
  1891. * Find an item from an event target:
  1892. * searches for the attribute 'timeline-item' in the event target's element tree
  1893. * @param {Event} event
  1894. * @return {Item | null} item
  1895. */
  1896. ItemSet.prototype.itemFromTarget = function(event) {
  1897. return this.itemFromElement(event.target);
  1898. };
  1899. /**
  1900. * Find an item from an event's related target:
  1901. * searches for the attribute 'timeline-item' in the related target's element tree
  1902. * @param {Event} event
  1903. * @return {Item | null} item
  1904. */
  1905. ItemSet.prototype.itemFromRelatedTarget = function(event) {
  1906. return this.itemFromElement(event.relatedTarget);
  1907. };
  1908. /**
  1909. * Find the Group from an event target:
  1910. * searches for the attribute 'timeline-group' in the event target's element tree
  1911. * @param {Event} event
  1912. * @return {Group | null} group
  1913. */
  1914. ItemSet.prototype.groupFromTarget = function(event) {
  1915. var clientY = event.center ? event.center.y : event.clientY;
  1916. var groupIds = this.groupIds;
  1917. if (groupIds.length <= 0 && this.groupsData) {
  1918. groupIds = this.groupsData.getIds({
  1919. order: this.options.groupOrder
  1920. });
  1921. }
  1922. for (var i = 0; i < groupIds.length; i++) {
  1923. var groupId = groupIds[i];
  1924. var group = this.groups[groupId];
  1925. var foreground = group.dom.foreground;
  1926. var top = util.getAbsoluteTop(foreground);
  1927. if (clientY > top && clientY < top + foreground.offsetHeight) {
  1928. return group;
  1929. }
  1930. if (this.options.orientation.item === 'top') {
  1931. if (i === this.groupIds.length - 1 && clientY > top) {
  1932. return group;
  1933. }
  1934. }
  1935. else {
  1936. if (i === 0 && clientY < top + foreground.offset) {
  1937. return group;
  1938. }
  1939. }
  1940. }
  1941. return null;
  1942. };
  1943. /**
  1944. * Find the ItemSet from an event target:
  1945. * searches for the attribute 'timeline-itemset' in the event target's element tree
  1946. * @param {Event} event
  1947. * @return {ItemSet | null} item
  1948. */
  1949. ItemSet.itemSetFromTarget = function(event) {
  1950. var target = event.target;
  1951. while (target) {
  1952. if (target.hasOwnProperty('timeline-itemset')) {
  1953. return target['timeline-itemset'];
  1954. }
  1955. target = target.parentNode;
  1956. }
  1957. return null;
  1958. };
  1959. /**
  1960. * Clone the data of an item, and "normalize" it: convert the start and end date
  1961. * to the type (Date, Moment, ...) configured in the DataSet. If not configured,
  1962. * start and end are converted to Date.
  1963. * @param {Object} itemData, typically `item.data`
  1964. * @param {string} [type] Optional Date type. If not provided, the type from the DataSet is taken
  1965. * @return {Object} The cloned object
  1966. * @private
  1967. */
  1968. ItemSet.prototype._cloneItemData = function (itemData, type) {
  1969. var clone = util.extend({}, itemData);
  1970. if (!type) {
  1971. // convert start and end date to the type (Date, Moment, ...) configured in the DataSet
  1972. type = this.itemsData.getDataSet()._options.type;
  1973. }
  1974. if (clone.start != undefined) {
  1975. clone.start = util.convert(clone.start, type && type.start || 'Date');
  1976. }
  1977. if (clone.end != undefined) {
  1978. clone.end = util.convert(clone.end , type && type.end || 'Date');
  1979. }
  1980. return clone;
  1981. };
  1982. module.exports = ItemSet;