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.

2288 lines
67 KiB

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