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.

2282 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
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. import Popup from '../../shared/Popup';
  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.stackDirty = true; // if true, all items will be restacked on next redraw
  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. // attach to the DOM
  223. this.show();
  224. };
  225. /**
  226. * Set options for the ItemSet. Existing options will be extended/overwritten.
  227. * @param {Object} [options] The following options are available:
  228. * {String} type
  229. * Default type for the items. Choose from 'box'
  230. * (default), 'point', 'range', or 'background'.
  231. * The default style can be overwritten by
  232. * individual items.
  233. * {String} align
  234. * Alignment for the items, only applicable for
  235. * BoxItem. Choose 'center' (default), 'left', or
  236. * 'right'.
  237. * {String} orientation.item
  238. * Orientation of the item set. Choose 'top' or
  239. * 'bottom' (default).
  240. * {Function} groupOrder
  241. * A sorting function for ordering groups
  242. * {Boolean} stack
  243. * If true (default), items will be stacked on
  244. * top of each other.
  245. * {Number} margin.axis
  246. * Margin between the axis and the items in pixels.
  247. * Default is 20.
  248. * {Number} margin.item.horizontal
  249. * Horizontal margin between items in pixels.
  250. * Default is 10.
  251. * {Number} margin.item.vertical
  252. * Vertical Margin between items in pixels.
  253. * Default is 10.
  254. * {Number} margin.item
  255. * Margin between items in pixels in both horizontal
  256. * and vertical direction. Default is 10.
  257. * {Number} margin
  258. * Set margin for both axis and items in pixels.
  259. * {Boolean} selectable
  260. * If true (default), items can be selected.
  261. * {Boolean} multiselect
  262. * If true, multiple items can be selected.
  263. * False by default.
  264. * {Boolean} editable
  265. * Set all editable options to true or false
  266. * {Boolean} editable.updateTime
  267. * Allow dragging an item to an other moment in time
  268. * {Boolean} editable.updateGroup
  269. * Allow dragging an item to an other group
  270. * {Boolean} editable.add
  271. * Allow creating new items on double tap
  272. * {Boolean} editable.remove
  273. * Allow removing items by clicking the delete button
  274. * top right of a selected item.
  275. * {Function(item: Item, callback: Function)} onAdd
  276. * Callback function triggered when an item is about to be added:
  277. * when the user double taps an empty space in the Timeline.
  278. * {Function(item: Item, callback: Function)} onUpdate
  279. * Callback function fired when an item is about to be updated.
  280. * This function typically has to show a dialog where the user
  281. * change the item. If not implemented, nothing happens.
  282. * {Function(item: Item, callback: Function)} onMove
  283. * Fired when an item has been moved. If not implemented,
  284. * the move action will be accepted.
  285. * {Function(item: Item, callback: Function)} onRemove
  286. * Fired when an item is about to be deleted.
  287. * If not implemented, the item will be always removed.
  288. */
  289. ItemSet.prototype.setOptions = function(options) {
  290. if (options) {
  291. // copy all options that we know
  292. var fields = [
  293. 'type', 'rtl', 'align', 'order', 'stack', 'stackSubgroups', 'selectable', 'multiselect', 'itemsAlwaysDraggable',
  294. 'multiselectPerGroup', 'groupOrder', 'dataAttributes', 'template', 'groupTemplate', 'visibleFrameTemplate',
  295. 'hide', 'snap', 'groupOrderSwap', 'tooltip', 'tooltipOnItemUpdateTime'
  296. ];
  297. util.selectiveExtend(fields, this.options, options);
  298. if ('orientation' in options) {
  299. if (typeof options.orientation === 'string') {
  300. this.options.orientation.item = options.orientation === 'top' ? 'top' : 'bottom';
  301. }
  302. else if (typeof options.orientation === 'object' && 'item' in options.orientation) {
  303. this.options.orientation.item = options.orientation.item;
  304. }
  305. }
  306. if ('margin' in options) {
  307. if (typeof options.margin === 'number') {
  308. this.options.margin.axis = options.margin;
  309. this.options.margin.item.horizontal = options.margin;
  310. this.options.margin.item.vertical = options.margin;
  311. }
  312. else if (typeof options.margin === 'object') {
  313. util.selectiveExtend(['axis'], this.options.margin, options.margin);
  314. if ('item' in options.margin) {
  315. if (typeof options.margin.item === 'number') {
  316. this.options.margin.item.horizontal = options.margin.item;
  317. this.options.margin.item.vertical = options.margin.item;
  318. }
  319. else if (typeof options.margin.item === 'object') {
  320. util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item);
  321. }
  322. }
  323. }
  324. }
  325. if ('editable' in options) {
  326. if (typeof options.editable === 'boolean') {
  327. this.options.editable.updateTime = options.editable;
  328. this.options.editable.updateGroup = options.editable;
  329. this.options.editable.add = options.editable;
  330. this.options.editable.remove = options.editable;
  331. this.options.editable.overrideItems = false;
  332. }
  333. else if (typeof options.editable === 'object') {
  334. util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove', 'overrideItems'], this.options.editable, options.editable);
  335. }
  336. }
  337. if ('groupEditable' in options) {
  338. if (typeof options.groupEditable === 'boolean') {
  339. this.options.groupEditable.order = options.groupEditable;
  340. this.options.groupEditable.add = options.groupEditable;
  341. this.options.groupEditable.remove = options.groupEditable;
  342. }
  343. else if (typeof options.groupEditable === 'object') {
  344. util.selectiveExtend(['order', 'add', 'remove'], this.options.groupEditable, options.groupEditable);
  345. }
  346. }
  347. // callback functions
  348. var addCallback = (function (name) {
  349. var fn = options[name];
  350. if (fn) {
  351. if (!(fn instanceof Function)) {
  352. throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)');
  353. }
  354. this.options[name] = fn;
  355. }
  356. }).bind(this);
  357. ['onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving', 'onAddGroup', 'onMoveGroup', 'onRemoveGroup'].forEach(addCallback);
  358. // force the itemSet to refresh: options like orientation and margins may be changed
  359. this.markDirty();
  360. }
  361. };
  362. /**
  363. * Mark the ItemSet dirty so it will refresh everything with next redraw.
  364. * Optionally, all items can be marked as dirty and be refreshed.
  365. * @param {{refreshItems: boolean}} [options]
  366. */
  367. ItemSet.prototype.markDirty = function(options) {
  368. this.groupIds = [];
  369. this.stackDirty = true;
  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.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. if (zoomed) this.stackDirty = true;
  541. this.lastVisibleInterval = visibleInterval;
  542. this.props.lastWidth = this.props.width;
  543. var restack = this.stackDirty;
  544. var firstGroup = this._firstGroup();
  545. var firstMargin = {
  546. item: margin.item,
  547. axis: margin.axis
  548. };
  549. var nonFirstMargin = {
  550. item: margin.item,
  551. axis: margin.item.vertical / 2
  552. };
  553. var height = 0;
  554. var minHeight = margin.axis + margin.item.vertical;
  555. // redraw the background group
  556. this.groups[BACKGROUND].redraw(range, nonFirstMargin, restack);
  557. // redraw all regular groups
  558. util.forEach(this.groups, function (group) {
  559. var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
  560. var groupResized = group.redraw(range, groupMargin, restack);
  561. resized = groupResized || resized;
  562. height += group.height;
  563. });
  564. height = Math.max(height, minHeight);
  565. this.stackDirty = false;
  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. // Remove it's popup
  776. if (itemObj.popup) {
  777. itemObj.popup.destroy();
  778. itemObj.popup = null;
  779. }
  780. }
  781. });
  782. }
  783. };
  784. /**
  785. * Get the time of an item based on it's data and options.type
  786. * @param {Object} itemData
  787. * @returns {string} Returns the type
  788. * @private
  789. */
  790. ItemSet.prototype._getType = function (itemData) {
  791. return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
  792. };
  793. /**
  794. * Get the group id for an item
  795. * @param {Object} itemData
  796. * @returns {string} Returns the groupId
  797. * @private
  798. */
  799. ItemSet.prototype._getGroupId = function (itemData) {
  800. var type = this._getType(itemData);
  801. if (type == 'background' && itemData.group == undefined) {
  802. return BACKGROUND;
  803. }
  804. else {
  805. return this.groupsData ? itemData.group : UNGROUPED;
  806. }
  807. };
  808. /**
  809. * Handle updated items
  810. * @param {Number[]} ids
  811. * @protected
  812. */
  813. ItemSet.prototype._onUpdate = function(ids) {
  814. var me = this;
  815. ids.forEach(function (id) {
  816. var itemData = me.itemsData.get(id, me.itemOptions);
  817. var item = me.items[id];
  818. var type = itemData ? me._getType(itemData) : null;
  819. var constructor = ItemSet.types[type];
  820. var selected;
  821. if (item) {
  822. // update item
  823. if (!constructor || !(item instanceof constructor)) {
  824. // item type has changed, delete the item and recreate it
  825. selected = item.selected; // preserve selection of this item
  826. me._removeItem(item);
  827. item = null;
  828. }
  829. else {
  830. me._updateItem(item, itemData);
  831. }
  832. }
  833. if (!item && itemData) {
  834. // create item
  835. if (constructor) {
  836. item = new constructor(itemData, me.conversion, me.options);
  837. item.id = id; // TODO: not so nice setting id afterwards
  838. me._addItem(item);
  839. if (selected) {
  840. this.selection.push(id);
  841. item.select();
  842. }
  843. }
  844. else if (type == 'rangeoverflow') {
  845. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  846. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
  847. '.vis-item.vis-range .vis-item-content {overflow: visible;}');
  848. }
  849. else {
  850. throw new TypeError('Unknown item type "' + type + '"');
  851. }
  852. }
  853. }.bind(this));
  854. this._order();
  855. this.stackDirty = true; // force re-stacking of all items next redraw
  856. this.body.emitter.emit('_change', {queue: true});
  857. };
  858. /**
  859. * Handle added items
  860. * @param {Number[]} ids
  861. * @protected
  862. */
  863. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  864. /**
  865. * Handle removed items
  866. * @param {Number[]} ids
  867. * @protected
  868. */
  869. ItemSet.prototype._onRemove = function(ids) {
  870. var count = 0;
  871. var me = this;
  872. ids.forEach(function (id) {
  873. var item = me.items[id];
  874. if (item) {
  875. count++;
  876. me._removeItem(item);
  877. }
  878. });
  879. if (count) {
  880. // update order
  881. this._order();
  882. this.stackDirty = true; // force re-stacking of all items next redraw
  883. this.body.emitter.emit('_change', {queue: true});
  884. }
  885. };
  886. /**
  887. * Update the order of item in all groups
  888. * @private
  889. */
  890. ItemSet.prototype._order = function() {
  891. // reorder the items in all groups
  892. // TODO: optimization: only reorder groups affected by the changed items
  893. util.forEach(this.groups, function (group) {
  894. group.order();
  895. });
  896. };
  897. /**
  898. * Handle updated groups
  899. * @param {Number[]} ids
  900. * @private
  901. */
  902. ItemSet.prototype._onUpdateGroups = function(ids) {
  903. this._onAddGroups(ids);
  904. };
  905. /**
  906. * Handle changed groups (added or updated)
  907. * @param {Number[]} ids
  908. * @private
  909. */
  910. ItemSet.prototype._onAddGroups = function(ids) {
  911. var me = this;
  912. ids.forEach(function (id) {
  913. var groupData = me.groupsData.get(id);
  914. var group = me.groups[id];
  915. if (!group) {
  916. // check for reserved ids
  917. if (id == UNGROUPED || id == BACKGROUND) {
  918. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  919. }
  920. var groupOptions = Object.create(me.options);
  921. util.extend(groupOptions, {
  922. height: null
  923. });
  924. group = new Group(id, groupData, me);
  925. me.groups[id] = group;
  926. // add items with this groupId to the new group
  927. for (var itemId in me.items) {
  928. if (me.items.hasOwnProperty(itemId)) {
  929. var item = me.items[itemId];
  930. if (item.data.group == id) {
  931. group.add(item);
  932. }
  933. }
  934. }
  935. group.order();
  936. group.show();
  937. }
  938. else {
  939. // update group
  940. group.setData(groupData);
  941. }
  942. });
  943. this.body.emitter.emit('_change', {queue: true});
  944. };
  945. /**
  946. * Handle removed groups
  947. * @param {Number[]} ids
  948. * @private
  949. */
  950. ItemSet.prototype._onRemoveGroups = function(ids) {
  951. var groups = this.groups;
  952. ids.forEach(function (id) {
  953. var group = groups[id];
  954. if (group) {
  955. group.hide();
  956. delete groups[id];
  957. }
  958. });
  959. this.markDirty();
  960. this.body.emitter.emit('_change', {queue: true});
  961. };
  962. /**
  963. * Reorder the groups if needed
  964. * @return {boolean} changed
  965. * @private
  966. */
  967. ItemSet.prototype._orderGroups = function () {
  968. if (this.groupsData) {
  969. // reorder the groups
  970. var groupIds = this.groupsData.getIds({
  971. order: this.options.groupOrder
  972. });
  973. groupIds = this._orderNestedGroups(groupIds);
  974. var changed = !util.equalArray(groupIds, this.groupIds);
  975. if (changed) {
  976. // hide all groups, removes them from the DOM
  977. var groups = this.groups;
  978. groupIds.forEach(function (groupId) {
  979. groups[groupId].hide();
  980. });
  981. // show the groups again, attach them to the DOM in correct order
  982. groupIds.forEach(function (groupId) {
  983. groups[groupId].show();
  984. });
  985. this.groupIds = groupIds;
  986. }
  987. return changed;
  988. }
  989. else {
  990. return false;
  991. }
  992. };
  993. /**
  994. * Reorder the nested groups
  995. * @return {boolean} changed
  996. * @private
  997. */
  998. ItemSet.prototype._orderNestedGroups = function(groupIds) {
  999. var newGroupIdsOrder = [];
  1000. groupIds.forEach(function(groupId){
  1001. var groupData = this.groupsData.get(groupId);
  1002. if (!groupData.nestedInGroup) {
  1003. newGroupIdsOrder.push(groupId)
  1004. }
  1005. if (groupData.nestedGroups) {
  1006. var nestedGroups = this.groupsData.get({
  1007. filter: function(nestedGroup) {
  1008. return nestedGroup.nestedInGroup == groupId;
  1009. }
  1010. });
  1011. var nestedGroupIds = nestedGroups.map(function(nestedGroup) { return nestedGroup.id })
  1012. newGroupIdsOrder = newGroupIdsOrder.concat(nestedGroupIds);
  1013. }
  1014. }, this)
  1015. return newGroupIdsOrder;
  1016. }
  1017. /**
  1018. * Add a new item
  1019. * @param {Item} item
  1020. * @private
  1021. */
  1022. ItemSet.prototype._addItem = function(item) {
  1023. this.items[item.id] = item;
  1024. // add to group
  1025. var groupId = this._getGroupId(item.data);
  1026. var group = this.groups[groupId];
  1027. if (!group) {
  1028. item.groupShowing = false;
  1029. } else if (group && group.data && group.data.showNested) {
  1030. item.groupShowing = true;
  1031. }
  1032. if (group) group.add(item);
  1033. };
  1034. /**
  1035. * Update an existing item
  1036. * @param {Item} item
  1037. * @param {Object} itemData
  1038. * @private
  1039. */
  1040. ItemSet.prototype._updateItem = function(item, itemData) {
  1041. var oldGroupId = item.data.group;
  1042. var oldSubGroupId = item.data.subgroup;
  1043. // update the items data (will redraw the item when displayed)
  1044. item.setData(itemData);
  1045. var groupId = this._getGroupId(item.data);
  1046. var group = this.groups[groupId];
  1047. if (!group) {
  1048. item.groupShowing = false;
  1049. } else if (group && group.data && group.data.showNested) {
  1050. item.groupShowing = true;
  1051. }
  1052. // update group
  1053. if (oldGroupId != item.data.group || oldSubGroupId != item.data.subgroup) {
  1054. var oldGroup = this.groups[oldGroupId];
  1055. if (oldGroup) oldGroup.remove(item);
  1056. if (group) group.add(item);
  1057. }
  1058. };
  1059. /**
  1060. * Delete an item from the ItemSet: remove it from the DOM, from the map
  1061. * with items, and from the map with visible items, and from the selection
  1062. * @param {Item} item
  1063. * @private
  1064. */
  1065. ItemSet.prototype._removeItem = function(item) {
  1066. // remove from DOM
  1067. item.hide();
  1068. // remove from items
  1069. delete this.items[item.id];
  1070. // remove from selection
  1071. var index = this.selection.indexOf(item.id);
  1072. if (index != -1) this.selection.splice(index, 1);
  1073. // remove from group
  1074. item.parent && item.parent.remove(item);
  1075. };
  1076. /**
  1077. * Create an array containing all items being a range (having an end date)
  1078. * @param array
  1079. * @returns {Array}
  1080. * @private
  1081. */
  1082. ItemSet.prototype._constructByEndArray = function(array) {
  1083. var endArray = [];
  1084. for (var i = 0; i < array.length; i++) {
  1085. if (array[i] instanceof RangeItem) {
  1086. endArray.push(array[i]);
  1087. }
  1088. }
  1089. return endArray;
  1090. };
  1091. /**
  1092. * Register the clicked item on touch, before dragStart is initiated.
  1093. *
  1094. * dragStart is initiated from a mousemove event, AFTER the mouse/touch is
  1095. * already moving. Therefore, the mouse/touch can sometimes be above an other
  1096. * DOM element than the item itself.
  1097. *
  1098. * @param {Event} event
  1099. * @private
  1100. */
  1101. ItemSet.prototype._onTouch = function (event) {
  1102. // store the touched item, used in _onDragStart
  1103. this.touchParams.item = this.itemFromTarget(event);
  1104. this.touchParams.dragLeftItem = event.target.dragLeftItem || false;
  1105. this.touchParams.dragRightItem = event.target.dragRightItem || false;
  1106. this.touchParams.itemProps = null;
  1107. };
  1108. /**
  1109. * Given an group id, returns the index it has.
  1110. *
  1111. * @param {Number} groupID
  1112. * @private
  1113. */
  1114. ItemSet.prototype._getGroupIndex = function(groupId) {
  1115. for (var i = 0; i < this.groupIds.length; i++) {
  1116. if (groupId == this.groupIds[i])
  1117. return i;
  1118. }
  1119. };
  1120. /**
  1121. * Start dragging the selected events
  1122. * @param {Event} event
  1123. * @private
  1124. */
  1125. ItemSet.prototype._onDragStart = function (event) {
  1126. if (this.touchParams.itemIsDragging) { return; }
  1127. var item = this.touchParams.item || null;
  1128. var me = this;
  1129. var props;
  1130. if (item && (item.selected || this.options.itemsAlwaysDraggable)) {
  1131. if (this.options.editable.overrideItems &&
  1132. !this.options.editable.updateTime &&
  1133. !this.options.editable.updateGroup) {
  1134. return;
  1135. }
  1136. // override options.editable
  1137. if ((item.editable != null && !item.editable.updateTime && !item.editable.updateGroup)
  1138. && !this.options.editable.overrideItems) {
  1139. return;
  1140. }
  1141. var dragLeftItem = this.touchParams.dragLeftItem;
  1142. var dragRightItem = this.touchParams.dragRightItem;
  1143. this.touchParams.itemIsDragging = true;
  1144. this.touchParams.selectedItem = item;
  1145. if (dragLeftItem) {
  1146. props = {
  1147. item: dragLeftItem,
  1148. initialX: event.center.x,
  1149. dragLeft: true,
  1150. data: this._cloneItemData(item.data)
  1151. };
  1152. this.touchParams.itemProps = [props];
  1153. }
  1154. else if (dragRightItem) {
  1155. props = {
  1156. item: dragRightItem,
  1157. initialX: event.center.x,
  1158. dragRight: true,
  1159. data: this._cloneItemData(item.data)
  1160. };
  1161. this.touchParams.itemProps = [props];
  1162. }
  1163. else {
  1164. var baseGroupIndex = this._getGroupIndex(item.data.group);
  1165. var itemsToDrag = (this.options.itemsAlwaysDraggable && !item.selected) ? [item.id] : this.getSelection();
  1166. this.touchParams.itemProps = itemsToDrag.map(function (id) {
  1167. var item = me.items[id];
  1168. var groupIndex = me._getGroupIndex(item.data.group);
  1169. return {
  1170. item: item,
  1171. initialX: event.center.x,
  1172. groupOffset: baseGroupIndex-groupIndex,
  1173. data: this._cloneItemData(item.data)
  1174. };
  1175. }.bind(this));
  1176. }
  1177. event.stopPropagation();
  1178. }
  1179. else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  1180. // create a new range item when dragging with ctrl key down
  1181. this._onDragStartAddItem(event);
  1182. }
  1183. };
  1184. /**
  1185. * Start creating a new range item by dragging.
  1186. * @param {Event} event
  1187. * @private
  1188. */
  1189. ItemSet.prototype._onDragStartAddItem = function (event) {
  1190. var snap = this.options.snap || null;
  1191. if (this.options.rtl) {
  1192. var xAbs = util.getAbsoluteRight(this.dom.frame);
  1193. var x = xAbs - event.center.x + 10; // plus 10 to compensate for the drag starting as soon as you've moved 10px
  1194. } else {
  1195. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1196. var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  1197. }
  1198. var time = this.body.util.toTime(x);
  1199. var scale = this.body.util.getScale();
  1200. var step = this.body.util.getStep();
  1201. var start = snap ? snap(time, scale, step) : time;
  1202. var end = start;
  1203. var itemData = {
  1204. type: 'range',
  1205. start: start,
  1206. end: end,
  1207. content: 'new item'
  1208. };
  1209. var id = util.randomUUID();
  1210. itemData[this.itemsData._fieldId] = id;
  1211. var group = this.groupFromTarget(event);
  1212. if (group) {
  1213. itemData.group = group.groupId;
  1214. }
  1215. var newItem = new RangeItem(itemData, this.conversion, this.options);
  1216. newItem.id = id; // TODO: not so nice setting id afterwards
  1217. newItem.data = this._cloneItemData(itemData);
  1218. this._addItem(newItem);
  1219. this.touchParams.selectedItem = newItem;
  1220. var props = {
  1221. item: newItem,
  1222. initialX: event.center.x,
  1223. data: newItem.data
  1224. };
  1225. if (this.options.rtl) {
  1226. props.dragLeft = true;
  1227. } else {
  1228. props.dragRight = true;
  1229. }
  1230. this.touchParams.itemProps = [props];
  1231. event.stopPropagation();
  1232. };
  1233. /**
  1234. * Drag selected items
  1235. * @param {Event} event
  1236. * @private
  1237. */
  1238. ItemSet.prototype._onDrag = function (event) {
  1239. if (this.touchParams.itemProps) {
  1240. event.stopPropagation();
  1241. var me = this;
  1242. var snap = this.options.snap || null;
  1243. if (this.options.rtl) {
  1244. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.right.width;
  1245. } else {
  1246. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  1247. }
  1248. var scale = this.body.util.getScale();
  1249. var step = this.body.util.getStep();
  1250. //only calculate the new group for the item that's actually dragged
  1251. var selectedItem = this.touchParams.selectedItem;
  1252. var updateGroupAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateGroup) ||
  1253. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateGroup);
  1254. var newGroupBase = null;
  1255. if (updateGroupAllowed && selectedItem) {
  1256. if (selectedItem.data.group != undefined) {
  1257. // drag from one group to another
  1258. var group = me.groupFromTarget(event);
  1259. if (group) {
  1260. //we know the offset for all items, so the new group for all items
  1261. //will be relative to this one.
  1262. newGroupBase = this._getGroupIndex(group.groupId);
  1263. }
  1264. }
  1265. }
  1266. // move
  1267. this.touchParams.itemProps.forEach(function (props) {
  1268. var current = me.body.util.toTime(event.center.x - xOffset);
  1269. var initial = me.body.util.toTime(props.initialX - xOffset);
  1270. if (this.options.rtl) {
  1271. var offset = -(current - initial); // ms
  1272. } else {
  1273. var offset = (current - initial); // ms
  1274. }
  1275. var itemData = this._cloneItemData(props.item.data); // clone the data
  1276. if (props.item.editable != null
  1277. && !props.item.editable.updateTime
  1278. && !props.item.editable.updateGroup
  1279. && !me.options.editable.overrideItems) {
  1280. return;
  1281. }
  1282. var updateTimeAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateTime) ||
  1283. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateTime);
  1284. if (updateTimeAllowed) {
  1285. if (props.dragLeft) {
  1286. // drag left side of a range item
  1287. if (this.options.rtl) {
  1288. if (itemData.end != undefined) {
  1289. var initialEnd = util.convert(props.data.end, 'Date');
  1290. var end = new Date(initialEnd.valueOf() + offset);
  1291. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1292. itemData.end = snap ? snap(end, scale, step) : end;
  1293. }
  1294. } else {
  1295. if (itemData.start != undefined) {
  1296. var initialStart = util.convert(props.data.start, 'Date');
  1297. var start = new Date(initialStart.valueOf() + offset);
  1298. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1299. itemData.start = snap ? snap(start, scale, step) : start;
  1300. }
  1301. }
  1302. }
  1303. else if (props.dragRight) {
  1304. // drag right side of a range item
  1305. if (this.options.rtl) {
  1306. if (itemData.start != undefined) {
  1307. var initialStart = util.convert(props.data.start, 'Date');
  1308. var start = new Date(initialStart.valueOf() + offset);
  1309. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1310. itemData.start = snap ? snap(start, scale, step) : start;
  1311. }
  1312. } else {
  1313. if (itemData.end != undefined) {
  1314. var initialEnd = util.convert(props.data.end, 'Date');
  1315. var end = new Date(initialEnd.valueOf() + offset);
  1316. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1317. itemData.end = snap ? snap(end, scale, step) : end;
  1318. }
  1319. }
  1320. }
  1321. else {
  1322. // drag both start and end
  1323. if (itemData.start != undefined) {
  1324. var initialStart = util.convert(props.data.start, 'Date').valueOf();
  1325. var start = new Date(initialStart + offset);
  1326. if (itemData.end != undefined) {
  1327. var initialEnd = util.convert(props.data.end, 'Date');
  1328. var duration = initialEnd.valueOf() - initialStart.valueOf();
  1329. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1330. itemData.start = snap ? snap(start, scale, step) : start;
  1331. itemData.end = new Date(itemData.start.valueOf() + duration);
  1332. }
  1333. else {
  1334. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1335. itemData.start = snap ? snap(start, scale, step) : start;
  1336. }
  1337. }
  1338. }
  1339. }
  1340. if (updateGroupAllowed && (!props.dragLeft && !props.dragRight) && newGroupBase!=null) {
  1341. if (itemData.group != undefined) {
  1342. var newOffset = newGroupBase - props.groupOffset;
  1343. //make sure we stay in bounds
  1344. newOffset = Math.max(0, newOffset);
  1345. newOffset = Math.min(me.groupIds.length-1, newOffset);
  1346. itemData.group = me.groupIds[newOffset];
  1347. }
  1348. }
  1349. // confirm moving the item
  1350. itemData = this._cloneItemData(itemData); // convert start and end to the correct type
  1351. me.options.onMoving(itemData, function (itemData) {
  1352. if (itemData) {
  1353. props.item.setData(this._cloneItemData(itemData, 'Date'));
  1354. }
  1355. }.bind(this));
  1356. }.bind(this));
  1357. this.stackDirty = true; // force re-stacking of all items next redraw
  1358. this.body.emitter.emit('_change');
  1359. }
  1360. };
  1361. /**
  1362. * Move an item to another group
  1363. * @param {Item} item
  1364. * @param {String | Number} groupId
  1365. * @private
  1366. */
  1367. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1368. var group = this.groups[groupId];
  1369. if (group && group.groupId != item.data.group) {
  1370. var oldGroup = item.parent;
  1371. oldGroup.remove(item);
  1372. oldGroup.order();
  1373. group.add(item);
  1374. group.order();
  1375. item.data.group = group.groupId;
  1376. }
  1377. };
  1378. /**
  1379. * End of dragging selected items
  1380. * @param {Event} event
  1381. * @private
  1382. */
  1383. ItemSet.prototype._onDragEnd = function (event) {
  1384. this.touchParams.itemIsDragging = false;
  1385. if (this.touchParams.itemProps) {
  1386. event.stopPropagation();
  1387. var me = this;
  1388. var dataset = this.itemsData.getDataSet();
  1389. var itemProps = this.touchParams.itemProps ;
  1390. this.touchParams.itemProps = null;
  1391. itemProps.forEach(function (props) {
  1392. var id = props.item.id;
  1393. var exists = me.itemsData.get(id, me.itemOptions) != null;
  1394. if (!exists) {
  1395. // add a new item
  1396. me.options.onAdd(props.item.data, function (itemData) {
  1397. me._removeItem(props.item); // remove temporary item
  1398. if (itemData) {
  1399. me.itemsData.getDataSet().add(itemData);
  1400. }
  1401. // force re-stacking of all items next redraw
  1402. me.stackDirty = true;
  1403. me.body.emitter.emit('_change');
  1404. });
  1405. }
  1406. else {
  1407. // update existing item
  1408. var itemData = this._cloneItemData(props.item.data); // convert start and end to the correct type
  1409. me.options.onMove(itemData, function (itemData) {
  1410. if (itemData) {
  1411. // apply changes
  1412. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1413. dataset.update(itemData);
  1414. }
  1415. else {
  1416. // restore original values
  1417. props.item.setData(props.data);
  1418. me.stackDirty = true; // force re-stacking of all items next redraw
  1419. me.body.emitter.emit('_change');
  1420. }
  1421. });
  1422. }
  1423. }.bind(this));
  1424. }
  1425. };
  1426. ItemSet.prototype._onGroupClick = function (event) {
  1427. var group = this.groupFromTarget(event);
  1428. if (!group.nestedGroups) return;
  1429. var groupsData = this.groupsData;
  1430. if (this.groupsData instanceof DataView) {
  1431. groupsData = this.groupsData.getDataSet()
  1432. }
  1433. group.showNested = !group.showNested;
  1434. var nestedGroups = groupsData.get(group.nestedGroups).map(function(nestedGroup) {
  1435. if (nestedGroup.visible == undefined) { nestedGroup.visible = true; }
  1436. nestedGroup.visible = !!group.showNested;
  1437. return nestedGroup;
  1438. });
  1439. groupsData.update(nestedGroups);
  1440. if (group.showNested) {
  1441. util.removeClassName(group.dom.label, 'collapsed');
  1442. util.addClassName(group.dom.label, 'expanded');
  1443. } else {
  1444. util.removeClassName(group.dom.label, 'expanded');
  1445. var collapsedDirClassName = this.options.rtl ? 'collapsed-rtl' : 'collapsed'
  1446. util.addClassName(group.dom.label, collapsedDirClassName);
  1447. }
  1448. }
  1449. ItemSet.prototype._onGroupDragStart = function (event) {
  1450. if (this.options.groupEditable.order) {
  1451. this.groupTouchParams.group = this.groupFromTarget(event);
  1452. if (this.groupTouchParams.group) {
  1453. event.stopPropagation();
  1454. this.groupTouchParams.originalOrder = this.groupsData.getIds({
  1455. order: this.options.groupOrder
  1456. });
  1457. }
  1458. }
  1459. }
  1460. ItemSet.prototype._onGroupDrag = function (event) {
  1461. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1462. event.stopPropagation();
  1463. var groupsData = this.groupsData;
  1464. if (this.groupsData instanceof DataView) {
  1465. groupsData = this.groupsData.getDataSet()
  1466. }
  1467. // drag from one group to another
  1468. var group = this.groupFromTarget(event);
  1469. // try to avoid toggling when groups differ in height
  1470. if (group && group.height != this.groupTouchParams.group.height) {
  1471. var movingUp = (group.top < this.groupTouchParams.group.top);
  1472. var clientY = event.center ? event.center.y : event.clientY;
  1473. var targetGroupTop = util.getAbsoluteTop(group.dom.foreground);
  1474. var draggedGroupHeight = this.groupTouchParams.group.height;
  1475. if (movingUp) {
  1476. // skip swapping the groups when the dragged group is not below clientY afterwards
  1477. if (targetGroupTop + draggedGroupHeight < clientY) {
  1478. return;
  1479. }
  1480. } else {
  1481. var targetGroupHeight = group.height;
  1482. // skip swapping the groups when the dragged group is not below clientY afterwards
  1483. if (targetGroupTop + targetGroupHeight - draggedGroupHeight > clientY) {
  1484. return;
  1485. }
  1486. }
  1487. }
  1488. if (group && group != this.groupTouchParams.group) {
  1489. var targetGroup = groupsData.get(group.groupId);
  1490. var draggedGroup = groupsData.get(this.groupTouchParams.group.groupId);
  1491. // switch groups
  1492. if (draggedGroup && targetGroup) {
  1493. this.options.groupOrderSwap(draggedGroup, targetGroup, groupsData);
  1494. groupsData.update(draggedGroup);
  1495. groupsData.update(targetGroup);
  1496. }
  1497. // fetch current order of groups
  1498. var newOrder = groupsData.getIds({
  1499. order: this.options.groupOrder
  1500. });
  1501. // in case of changes since _onGroupDragStart
  1502. if (!util.equalArray(newOrder, this.groupTouchParams.originalOrder)) {
  1503. var origOrder = this.groupTouchParams.originalOrder;
  1504. var draggedId = this.groupTouchParams.group.groupId;
  1505. var numGroups = Math.min(origOrder.length, newOrder.length);
  1506. var curPos = 0;
  1507. var newOffset = 0;
  1508. var orgOffset = 0;
  1509. while (curPos < numGroups) {
  1510. // as long as the groups are where they should be step down along the groups order
  1511. while ((curPos+newOffset) < numGroups
  1512. && (curPos+orgOffset) < numGroups
  1513. && newOrder[curPos+newOffset] == origOrder[curPos+orgOffset]) {
  1514. curPos++;
  1515. }
  1516. // all ok
  1517. if (curPos+newOffset >= numGroups) {
  1518. break;
  1519. }
  1520. // not all ok
  1521. // if dragged group was move upwards everything below should have an offset
  1522. if (newOrder[curPos+newOffset] == draggedId) {
  1523. newOffset = 1;
  1524. continue;
  1525. }
  1526. // if dragged group was move downwards everything above should have an offset
  1527. else if (origOrder[curPos+orgOffset] == draggedId) {
  1528. orgOffset = 1;
  1529. continue;
  1530. }
  1531. // found a group (apart from dragged group) that has the wrong position -> switch with the
  1532. // group at the position where other one should be, fix index arrays and continue
  1533. else {
  1534. var slippedPosition = newOrder.indexOf(origOrder[curPos+orgOffset])
  1535. var switchGroup = groupsData.get(newOrder[curPos+newOffset]);
  1536. var shouldBeGroup = groupsData.get(origOrder[curPos+orgOffset]);
  1537. this.options.groupOrderSwap(switchGroup, shouldBeGroup, groupsData);
  1538. groupsData.update(switchGroup);
  1539. groupsData.update(shouldBeGroup);
  1540. var switchGroupId = newOrder[curPos+newOffset];
  1541. newOrder[curPos+newOffset] = origOrder[curPos+orgOffset];
  1542. newOrder[slippedPosition] = switchGroupId;
  1543. curPos++;
  1544. }
  1545. }
  1546. }
  1547. }
  1548. }
  1549. }
  1550. ItemSet.prototype._onGroupDragEnd = function (event) {
  1551. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1552. event.stopPropagation();
  1553. // update existing group
  1554. var me = this;
  1555. var id = me.groupTouchParams.group.groupId;
  1556. var dataset = me.groupsData.getDataSet();
  1557. var groupData = util.extend({}, dataset.get(id)); // clone the data
  1558. me.options.onMoveGroup(groupData, function (groupData) {
  1559. if (groupData) {
  1560. // apply changes
  1561. groupData[dataset._fieldId] = id; // ensure the group contains its id (can be undefined)
  1562. dataset.update(groupData);
  1563. }
  1564. else {
  1565. // fetch current order of groups
  1566. var newOrder = dataset.getIds({
  1567. order: me.options.groupOrder
  1568. });
  1569. // restore original order
  1570. if (!util.equalArray(newOrder, me.groupTouchParams.originalOrder)) {
  1571. var origOrder = me.groupTouchParams.originalOrder;
  1572. var numGroups = Math.min(origOrder.length, newOrder.length);
  1573. var curPos = 0;
  1574. while (curPos < numGroups) {
  1575. // as long as the groups are where they should be step down along the groups order
  1576. while (curPos < numGroups && newOrder[curPos] == origOrder[curPos]) {
  1577. curPos++;
  1578. }
  1579. // all ok
  1580. if (curPos >= numGroups) {
  1581. break;
  1582. }
  1583. // found a group that has the wrong position -> switch with the
  1584. // group at the position where other one should be, fix index arrays and continue
  1585. var slippedPosition = newOrder.indexOf(origOrder[curPos])
  1586. var switchGroup = dataset.get(newOrder[curPos]);
  1587. var shouldBeGroup = dataset.get(origOrder[curPos]);
  1588. me.options.groupOrderSwap(switchGroup, shouldBeGroup, dataset);
  1589. groupsData.update(switchGroup);
  1590. groupsData.update(shouldBeGroup);
  1591. var switchGroupId = newOrder[curPos];
  1592. newOrder[curPos] = origOrder[curPos];
  1593. newOrder[slippedPosition] = switchGroupId;
  1594. curPos++;
  1595. }
  1596. }
  1597. }
  1598. });
  1599. me.body.emitter.emit('groupDragged', { groupId: id });
  1600. }
  1601. }
  1602. /**
  1603. * Handle selecting/deselecting an item when tapping it
  1604. * @param {Event} event
  1605. * @private
  1606. */
  1607. ItemSet.prototype._onSelectItem = function (event) {
  1608. if (!this.options.selectable) return;
  1609. var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey);
  1610. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  1611. if (ctrlKey || shiftKey) {
  1612. this._onMultiSelectItem(event);
  1613. return;
  1614. }
  1615. var oldSelection = this.getSelection();
  1616. var item = this.itemFromTarget(event);
  1617. var selection = item ? [item.id] : [];
  1618. this.setSelection(selection);
  1619. var newSelection = this.getSelection();
  1620. // emit a select event,
  1621. // except when old selection is empty and new selection is still empty
  1622. if (newSelection.length > 0 || oldSelection.length > 0) {
  1623. this.body.emitter.emit('select', {
  1624. items: newSelection,
  1625. event: util.elementsCensor(event)
  1626. });
  1627. }
  1628. };
  1629. /**
  1630. * Handle hovering an item
  1631. * @param {Event} event
  1632. * @private
  1633. */
  1634. ItemSet.prototype._onMouseOver = function (event) {
  1635. var item = this.itemFromTarget(event);
  1636. if (!item) return;
  1637. // Item we just left
  1638. var related = this.itemFromRelatedTarget(event);
  1639. if (item === related) {
  1640. // We haven't changed item, just element in the item
  1641. return;
  1642. }
  1643. if (item.getTitle()) {
  1644. if (item.popup == null) {
  1645. item.setPopup(new Popup(this.body.dom.root, this.options.tooltip.overflowMethod || 'flip'));
  1646. }
  1647. var container = this.body.dom.centerContainer;
  1648. item.popup.setPosition(
  1649. event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft,
  1650. event.clientY - util.getAbsoluteTop(container) + container.offsetTop
  1651. );
  1652. item.popup.show();
  1653. }
  1654. this.body.emitter.emit('itemover', {
  1655. item: item.id,
  1656. event: util.elementsCensor(event)
  1657. });
  1658. };
  1659. ItemSet.prototype._onMouseOut = function (event) {
  1660. var item = this.itemFromTarget(event);
  1661. if (!item) return;
  1662. // Item we are going to
  1663. var related = this.itemFromRelatedTarget(event);
  1664. if (item === related) {
  1665. // We aren't changing item, just element in the item
  1666. return;
  1667. }
  1668. if (item.popup != null) {
  1669. item.popup.hide();
  1670. }
  1671. this.body.emitter.emit('itemout', {
  1672. item: item.id,
  1673. event: util.elementsCensor(event)
  1674. });
  1675. };
  1676. ItemSet.prototype._onMouseMove = function (event) {
  1677. var item = this.itemFromTarget(event);
  1678. if (!item) return;
  1679. if (this.options.tooltip.followMouse) {
  1680. if (item.popup) {
  1681. if (!item.popup.hidden) {
  1682. var container = this.body.dom.centerContainer;
  1683. item.popup.setPosition(
  1684. event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft,
  1685. event.clientY - util.getAbsoluteTop(container) + container.offsetTop
  1686. );
  1687. item.popup.show(); // Redraw
  1688. }
  1689. }
  1690. }
  1691. };
  1692. /**
  1693. * Handle updates of an item on double tap
  1694. * @param event
  1695. * @private
  1696. */
  1697. ItemSet.prototype._onUpdateItem = function (item) {
  1698. if (!this.options.selectable) return;
  1699. if (!this.options.editable.add) return;
  1700. var me = this;
  1701. if (item) {
  1702. // execute async handler to update the item (or cancel it)
  1703. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  1704. this.options.onUpdate(itemData, function (itemData) {
  1705. if (itemData) {
  1706. me.itemsData.getDataSet().update(itemData);
  1707. }
  1708. });
  1709. }
  1710. }
  1711. /**
  1712. * Handle creation of an item on double tap
  1713. * @param event
  1714. * @private
  1715. */
  1716. ItemSet.prototype._onAddItem = function (event) {
  1717. if (!this.options.selectable) return;
  1718. if (!this.options.editable.add) return;
  1719. var me = this;
  1720. var snap = this.options.snap || null;
  1721. var item = this.itemFromTarget(event);
  1722. if (!item) {
  1723. // add item
  1724. if (this.options.rtl) {
  1725. var xAbs = util.getAbsoluteRight(this.dom.frame);
  1726. var x = xAbs - event.center.x;
  1727. } else {
  1728. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1729. var x = event.center.x - xAbs;
  1730. }
  1731. // var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1732. // var x = event.center.x - xAbs;
  1733. var start = this.body.util.toTime(x);
  1734. var scale = this.body.util.getScale();
  1735. var step = this.body.util.getStep();
  1736. var newItemData = {
  1737. start: snap ? snap(start, scale, step) : start,
  1738. content: 'new item'
  1739. };
  1740. if (event.type == 'drop') {
  1741. var itemData = JSON.parse(event.dataTransfer.getData("text"))
  1742. newItemData.content = itemData.content; // content is required
  1743. newItemData.type = itemData.type || 'box';
  1744. newItemData[this.itemsData._fieldId] = itemData.id || util.randomUUID();
  1745. if (itemData.type == 'range' || (itemData.end && itemData.start)) {
  1746. if (!itemData.end) {
  1747. var end = this.body.util.toTime(x + this.props.width / 5);
  1748. newItemData.end = snap ? snap(end, scale, step) : end;
  1749. } else {
  1750. newItemData.end = itemData.end;
  1751. newItemData.start = itemData.start;
  1752. }
  1753. }
  1754. } else {
  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: util.elementsCensor(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. for (var i = 0; i < this.groupIds.length; i++) {
  1917. var groupId = this.groupIds[i];
  1918. var group = this.groups[groupId];
  1919. var foreground = group.dom.foreground;
  1920. var top = util.getAbsoluteTop(foreground);
  1921. if (clientY > top && clientY < top + foreground.offsetHeight) {
  1922. return group;
  1923. }
  1924. if (this.options.orientation.item === 'top') {
  1925. if (i === this.groupIds.length - 1 && clientY > top) {
  1926. return group;
  1927. }
  1928. }
  1929. else {
  1930. if (i === 0 && clientY < top + foreground.offset) {
  1931. return group;
  1932. }
  1933. }
  1934. }
  1935. return null;
  1936. };
  1937. /**
  1938. * Find the ItemSet from an event target:
  1939. * searches for the attribute 'timeline-itemset' in the event target's element tree
  1940. * @param {Event} event
  1941. * @return {ItemSet | null} item
  1942. */
  1943. ItemSet.itemSetFromTarget = function(event) {
  1944. var target = event.target;
  1945. while (target) {
  1946. if (target.hasOwnProperty('timeline-itemset')) {
  1947. return target['timeline-itemset'];
  1948. }
  1949. target = target.parentNode;
  1950. }
  1951. return null;
  1952. };
  1953. /**
  1954. * Clone the data of an item, and "normalize" it: convert the start and end date
  1955. * to the type (Date, Moment, ...) configured in the DataSet. If not configured,
  1956. * start and end are converted to Date.
  1957. * @param {Object} itemData, typically `item.data`
  1958. * @param {string} [type] Optional Date type. If not provided, the type from the DataSet is taken
  1959. * @return {Object} The cloned object
  1960. * @private
  1961. */
  1962. ItemSet.prototype._cloneItemData = function (itemData, type) {
  1963. var clone = util.extend({}, itemData);
  1964. if (!type) {
  1965. // convert start and end date to the type (Date, Moment, ...) configured in the DataSet
  1966. type = this.itemsData.getDataSet()._options.type;
  1967. }
  1968. if (clone.start != undefined) {
  1969. clone.start = util.convert(clone.start, type && type.start || 'Date');
  1970. }
  1971. if (clone.end != undefined) {
  1972. clone.end = util.convert(clone.end , type && type.end || 'Date');
  1973. }
  1974. return clone;
  1975. };
  1976. module.exports = ItemSet;