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.

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