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.

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