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.

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