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.

2298 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
  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.isVisible ? 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. order: this.options.groupOrder
  1010. });
  1011. var nestedGroupIds = nestedGroups.map(function(nestedGroup) { return nestedGroup.id })
  1012. newGroupIdsOrder = newGroupIdsOrder.concat(nestedGroupIds);
  1013. }
  1014. }, this)
  1015. return newGroupIdsOrder;
  1016. }
  1017. /**
  1018. * Add a new item
  1019. * @param {Item} item
  1020. * @private
  1021. */
  1022. ItemSet.prototype._addItem = function(item) {
  1023. this.items[item.id] = item;
  1024. // add to group
  1025. var groupId = this._getGroupId(item.data);
  1026. var group = this.groups[groupId];
  1027. if (!group) {
  1028. item.groupShowing = false;
  1029. } else if (group && group.data && group.data.showNested) {
  1030. item.groupShowing = true;
  1031. }
  1032. if (group) group.add(item);
  1033. };
  1034. /**
  1035. * Update an existing item
  1036. * @param {Item} item
  1037. * @param {Object} itemData
  1038. * @private
  1039. */
  1040. ItemSet.prototype._updateItem = function(item, itemData) {
  1041. // update the items data (will redraw the item when displayed)
  1042. item.setData(itemData);
  1043. var groupId = this._getGroupId(item.data);
  1044. var group = this.groups[groupId];
  1045. if (!group) {
  1046. item.groupShowing = false;
  1047. } else if (group && group.data && group.data.showNested) {
  1048. item.groupShowing = true;
  1049. }
  1050. };
  1051. /**
  1052. * Delete an item from the ItemSet: remove it from the DOM, from the map
  1053. * with items, and from the map with visible items, and from the selection
  1054. * @param {Item} item
  1055. * @private
  1056. */
  1057. ItemSet.prototype._removeItem = function(item) {
  1058. // remove from DOM
  1059. item.hide();
  1060. // remove from items
  1061. delete this.items[item.id];
  1062. // remove from selection
  1063. var index = this.selection.indexOf(item.id);
  1064. if (index != -1) this.selection.splice(index, 1);
  1065. // remove from group
  1066. item.parent && item.parent.remove(item);
  1067. };
  1068. /**
  1069. * Create an array containing all items being a range (having an end date)
  1070. * @param array
  1071. * @returns {Array}
  1072. * @private
  1073. */
  1074. ItemSet.prototype._constructByEndArray = function(array) {
  1075. var endArray = [];
  1076. for (var i = 0; i < array.length; i++) {
  1077. if (array[i] instanceof RangeItem) {
  1078. endArray.push(array[i]);
  1079. }
  1080. }
  1081. return endArray;
  1082. };
  1083. /**
  1084. * Register the clicked item on touch, before dragStart is initiated.
  1085. *
  1086. * dragStart is initiated from a mousemove event, AFTER the mouse/touch is
  1087. * already moving. Therefore, the mouse/touch can sometimes be above an other
  1088. * DOM element than the item itself.
  1089. *
  1090. * @param {Event} event
  1091. * @private
  1092. */
  1093. ItemSet.prototype._onTouch = function (event) {
  1094. // store the touched item, used in _onDragStart
  1095. this.touchParams.item = this.itemFromTarget(event);
  1096. this.touchParams.dragLeftItem = event.target.dragLeftItem || false;
  1097. this.touchParams.dragRightItem = event.target.dragRightItem || false;
  1098. this.touchParams.itemProps = null;
  1099. };
  1100. /**
  1101. * Given an group id, returns the index it has.
  1102. *
  1103. * @param {Number} groupID
  1104. * @private
  1105. */
  1106. ItemSet.prototype._getGroupIndex = function(groupId) {
  1107. for (var i = 0; i < this.groupIds.length; i++) {
  1108. if (groupId == this.groupIds[i])
  1109. return i;
  1110. }
  1111. };
  1112. /**
  1113. * Start dragging the selected events
  1114. * @param {Event} event
  1115. * @private
  1116. */
  1117. ItemSet.prototype._onDragStart = function (event) {
  1118. if (this.touchParams.itemIsDragging) { return; }
  1119. var item = this.touchParams.item || null;
  1120. var me = this;
  1121. var props;
  1122. if (item && (item.selected || this.options.itemsAlwaysDraggable)) {
  1123. if (this.options.editable.overrideItems &&
  1124. !this.options.editable.updateTime &&
  1125. !this.options.editable.updateGroup) {
  1126. return;
  1127. }
  1128. // override options.editable
  1129. if ((item.editable != null && !item.editable.updateTime && !item.editable.updateGroup)
  1130. && !this.options.editable.overrideItems) {
  1131. return;
  1132. }
  1133. var dragLeftItem = this.touchParams.dragLeftItem;
  1134. var dragRightItem = this.touchParams.dragRightItem;
  1135. this.touchParams.itemIsDragging = true;
  1136. this.touchParams.selectedItem = item;
  1137. if (dragLeftItem) {
  1138. props = {
  1139. item: dragLeftItem,
  1140. initialX: event.center.x,
  1141. dragLeft: true,
  1142. data: this._cloneItemData(item.data)
  1143. };
  1144. this.touchParams.itemProps = [props];
  1145. }
  1146. else if (dragRightItem) {
  1147. props = {
  1148. item: dragRightItem,
  1149. initialX: event.center.x,
  1150. dragRight: true,
  1151. data: this._cloneItemData(item.data)
  1152. };
  1153. this.touchParams.itemProps = [props];
  1154. }
  1155. else {
  1156. var baseGroupIndex = this._getGroupIndex(item.data.group);
  1157. var itemsToDrag = (this.options.itemsAlwaysDraggable && !item.selected) ? [item.id] : this.getSelection();
  1158. this.touchParams.itemProps = itemsToDrag.map(function (id) {
  1159. var item = me.items[id];
  1160. var groupIndex = me._getGroupIndex(item.data.group);
  1161. return {
  1162. item: item,
  1163. initialX: event.center.x,
  1164. groupOffset: baseGroupIndex-groupIndex,
  1165. data: this._cloneItemData(item.data)
  1166. };
  1167. }.bind(this));
  1168. }
  1169. event.stopPropagation();
  1170. }
  1171. else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  1172. // create a new range item when dragging with ctrl key down
  1173. this._onDragStartAddItem(event);
  1174. }
  1175. };
  1176. /**
  1177. * Start creating a new range item by dragging.
  1178. * @param {Event} event
  1179. * @private
  1180. */
  1181. ItemSet.prototype._onDragStartAddItem = function (event) {
  1182. var snap = this.options.snap || null;
  1183. if (this.options.rtl) {
  1184. var xAbs = util.getAbsoluteRight(this.dom.frame);
  1185. var x = xAbs - event.center.x + 10; // plus 10 to compensate for the drag starting as soon as you've moved 10px
  1186. } else {
  1187. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1188. var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  1189. }
  1190. var time = this.body.util.toTime(x);
  1191. var scale = this.body.util.getScale();
  1192. var step = this.body.util.getStep();
  1193. var start = snap ? snap(time, scale, step) : time;
  1194. var end = start;
  1195. var itemData = {
  1196. type: 'range',
  1197. start: start,
  1198. end: end,
  1199. content: 'new item'
  1200. };
  1201. var id = util.randomUUID();
  1202. itemData[this.itemsData._fieldId] = id;
  1203. var group = this.groupFromTarget(event);
  1204. if (group) {
  1205. itemData.group = group.groupId;
  1206. }
  1207. var newItem = new RangeItem(itemData, this.conversion, this.options);
  1208. newItem.id = id; // TODO: not so nice setting id afterwards
  1209. newItem.data = this._cloneItemData(itemData);
  1210. this._addItem(newItem);
  1211. this.touchParams.selectedItem = newItem;
  1212. var props = {
  1213. item: newItem,
  1214. initialX: event.center.x,
  1215. data: newItem.data
  1216. };
  1217. if (this.options.rtl) {
  1218. props.dragLeft = true;
  1219. } else {
  1220. props.dragRight = true;
  1221. }
  1222. this.touchParams.itemProps = [props];
  1223. event.stopPropagation();
  1224. };
  1225. /**
  1226. * Drag selected items
  1227. * @param {Event} event
  1228. * @private
  1229. */
  1230. ItemSet.prototype._onDrag = function (event) {
  1231. if (this.touchParams.itemProps) {
  1232. event.stopPropagation();
  1233. var me = this;
  1234. var snap = this.options.snap || null;
  1235. if (this.options.rtl) {
  1236. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.right.width;
  1237. } else {
  1238. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  1239. }
  1240. var scale = this.body.util.getScale();
  1241. var step = this.body.util.getStep();
  1242. //only calculate the new group for the item that's actually dragged
  1243. var selectedItem = this.touchParams.selectedItem;
  1244. var updateGroupAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateGroup) ||
  1245. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateGroup);
  1246. var newGroupBase = null;
  1247. if (updateGroupAllowed && selectedItem) {
  1248. if (selectedItem.data.group != undefined) {
  1249. // drag from one group to another
  1250. var group = me.groupFromTarget(event);
  1251. if (group) {
  1252. //we know the offset for all items, so the new group for all items
  1253. //will be relative to this one.
  1254. newGroupBase = this._getGroupIndex(group.groupId);
  1255. }
  1256. }
  1257. }
  1258. // move
  1259. this.touchParams.itemProps.forEach(function (props) {
  1260. var current = me.body.util.toTime(event.center.x - xOffset);
  1261. var initial = me.body.util.toTime(props.initialX - xOffset);
  1262. if (this.options.rtl) {
  1263. var offset = -(current - initial); // ms
  1264. } else {
  1265. var offset = (current - initial); // ms
  1266. }
  1267. var itemData = this._cloneItemData(props.item.data); // clone the data
  1268. if (props.item.editable != null
  1269. && !props.item.editable.updateTime
  1270. && !props.item.editable.updateGroup
  1271. && !me.options.editable.overrideItems) {
  1272. return;
  1273. }
  1274. var updateTimeAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateTime) ||
  1275. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateTime);
  1276. if (updateTimeAllowed) {
  1277. if (props.dragLeft) {
  1278. // drag left side of a range item
  1279. if (this.options.rtl) {
  1280. if (itemData.end != undefined) {
  1281. var initialEnd = util.convert(props.data.end, 'Date');
  1282. var end = new Date(initialEnd.valueOf() + offset);
  1283. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1284. itemData.end = snap ? snap(end, scale, step) : end;
  1285. }
  1286. } else {
  1287. if (itemData.start != undefined) {
  1288. var initialStart = util.convert(props.data.start, 'Date');
  1289. var start = new Date(initialStart.valueOf() + offset);
  1290. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1291. itemData.start = snap ? snap(start, scale, step) : start;
  1292. }
  1293. }
  1294. }
  1295. else if (props.dragRight) {
  1296. // drag right side of a range item
  1297. if (this.options.rtl) {
  1298. if (itemData.start != undefined) {
  1299. var initialStart = util.convert(props.data.start, 'Date');
  1300. var start = new Date(initialStart.valueOf() + offset);
  1301. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1302. itemData.start = snap ? snap(start, scale, step) : start;
  1303. }
  1304. } else {
  1305. if (itemData.end != undefined) {
  1306. var initialEnd = util.convert(props.data.end, 'Date');
  1307. var end = new Date(initialEnd.valueOf() + offset);
  1308. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1309. itemData.end = snap ? snap(end, scale, step) : end;
  1310. }
  1311. }
  1312. }
  1313. else {
  1314. // drag both start and end
  1315. if (itemData.start != undefined) {
  1316. var initialStart = util.convert(props.data.start, 'Date').valueOf();
  1317. var start = new Date(initialStart + offset);
  1318. if (itemData.end != undefined) {
  1319. var initialEnd = util.convert(props.data.end, 'Date');
  1320. var duration = initialEnd.valueOf() - initialStart.valueOf();
  1321. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1322. itemData.start = snap ? snap(start, scale, step) : start;
  1323. itemData.end = new Date(itemData.start.valueOf() + duration);
  1324. }
  1325. else {
  1326. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1327. itemData.start = snap ? snap(start, scale, step) : start;
  1328. }
  1329. }
  1330. }
  1331. }
  1332. if (updateGroupAllowed && (!props.dragLeft && !props.dragRight) && newGroupBase!=null) {
  1333. if (itemData.group != undefined) {
  1334. var newOffset = newGroupBase - props.groupOffset;
  1335. //make sure we stay in bounds
  1336. newOffset = Math.max(0, newOffset);
  1337. newOffset = Math.min(me.groupIds.length-1, newOffset);
  1338. itemData.group = me.groupIds[newOffset];
  1339. }
  1340. }
  1341. // confirm moving the item
  1342. itemData = this._cloneItemData(itemData); // convert start and end to the correct type
  1343. me.options.onMoving(itemData, function (itemData) {
  1344. if (itemData) {
  1345. props.item.setData(this._cloneItemData(itemData, 'Date'));
  1346. }
  1347. }.bind(this));
  1348. }.bind(this));
  1349. this.stackDirty = true; // force re-stacking of all items next redraw
  1350. this.body.emitter.emit('_change');
  1351. }
  1352. };
  1353. /**
  1354. * Move an item to another group
  1355. * @param {Item} item
  1356. * @param {String | Number} groupId
  1357. * @private
  1358. */
  1359. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1360. var group = this.groups[groupId];
  1361. if (group && group.groupId != item.data.group) {
  1362. var oldGroup = item.parent;
  1363. oldGroup.remove(item);
  1364. oldGroup.order();
  1365. item.data.group = group.groupId;
  1366. group.add(item);
  1367. group.order();
  1368. }
  1369. };
  1370. /**
  1371. * End of dragging selected items
  1372. * @param {Event} event
  1373. * @private
  1374. */
  1375. ItemSet.prototype._onDragEnd = function (event) {
  1376. this.touchParams.itemIsDragging = false;
  1377. if (this.touchParams.itemProps) {
  1378. event.stopPropagation();
  1379. var me = this;
  1380. var dataset = this.itemsData.getDataSet();
  1381. var itemProps = this.touchParams.itemProps ;
  1382. this.touchParams.itemProps = null;
  1383. itemProps.forEach(function (props) {
  1384. var id = props.item.id;
  1385. var exists = me.itemsData.get(id, me.itemOptions) != null;
  1386. if (!exists) {
  1387. // add a new item
  1388. me.options.onAdd(props.item.data, function (itemData) {
  1389. me._removeItem(props.item); // remove temporary item
  1390. if (itemData) {
  1391. me.itemsData.getDataSet().add(itemData);
  1392. }
  1393. // force re-stacking of all items next redraw
  1394. me.stackDirty = true;
  1395. me.body.emitter.emit('_change');
  1396. });
  1397. }
  1398. else {
  1399. // update existing item
  1400. var itemData = this._cloneItemData(props.item.data); // convert start and end to the correct type
  1401. me.options.onMove(itemData, function (itemData) {
  1402. if (itemData) {
  1403. // apply changes
  1404. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1405. dataset.update(itemData);
  1406. }
  1407. else {
  1408. // restore original values
  1409. props.item.setData(props.data);
  1410. me.stackDirty = true; // force re-stacking of all items next redraw
  1411. me.body.emitter.emit('_change');
  1412. }
  1413. });
  1414. }
  1415. }.bind(this));
  1416. }
  1417. };
  1418. ItemSet.prototype._onGroupClick = function (event) {
  1419. var group = this.groupFromTarget(event);
  1420. if (!group || !group.nestedGroups) return;
  1421. var groupsData = this.groupsData;
  1422. if (this.groupsData instanceof DataView) {
  1423. groupsData = this.groupsData.getDataSet()
  1424. }
  1425. group.showNested = !group.showNested;
  1426. var nestedGroups = groupsData.get(group.nestedGroups).map(function(nestedGroup) {
  1427. if (nestedGroup.visible == undefined) { nestedGroup.visible = true; }
  1428. nestedGroup.visible = !!group.showNested;
  1429. return nestedGroup;
  1430. });
  1431. groupsData.update(nestedGroups);
  1432. if (group.showNested) {
  1433. util.removeClassName(group.dom.label, 'collapsed');
  1434. util.addClassName(group.dom.label, 'expanded');
  1435. } else {
  1436. util.removeClassName(group.dom.label, 'expanded');
  1437. var collapsedDirClassName = this.options.rtl ? 'collapsed-rtl' : 'collapsed'
  1438. util.addClassName(group.dom.label, collapsedDirClassName);
  1439. }
  1440. }
  1441. ItemSet.prototype._onGroupDragStart = function (event) {
  1442. if (this.options.groupEditable.order) {
  1443. this.groupTouchParams.group = this.groupFromTarget(event);
  1444. if (this.groupTouchParams.group) {
  1445. event.stopPropagation();
  1446. this.groupTouchParams.originalOrder = this.groupsData.getIds({
  1447. order: this.options.groupOrder
  1448. });
  1449. }
  1450. }
  1451. }
  1452. ItemSet.prototype._onGroupDrag = function (event) {
  1453. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1454. event.stopPropagation();
  1455. var groupsData = this.groupsData;
  1456. if (this.groupsData instanceof DataView) {
  1457. groupsData = this.groupsData.getDataSet()
  1458. }
  1459. // drag from one group to another
  1460. var group = this.groupFromTarget(event);
  1461. // try to avoid toggling when groups differ in height
  1462. if (group && group.height != this.groupTouchParams.group.height) {
  1463. var movingUp = (group.top < this.groupTouchParams.group.top);
  1464. var clientY = event.center ? event.center.y : event.clientY;
  1465. var targetGroupTop = util.getAbsoluteTop(group.dom.foreground);
  1466. var draggedGroupHeight = this.groupTouchParams.group.height;
  1467. if (movingUp) {
  1468. // skip swapping the groups when the dragged group is not below clientY afterwards
  1469. if (targetGroupTop + draggedGroupHeight < clientY) {
  1470. return;
  1471. }
  1472. } else {
  1473. var targetGroupHeight = group.height;
  1474. // skip swapping the groups when the dragged group is not below clientY afterwards
  1475. if (targetGroupTop + targetGroupHeight - draggedGroupHeight > clientY) {
  1476. return;
  1477. }
  1478. }
  1479. }
  1480. if (group && group != this.groupTouchParams.group) {
  1481. var targetGroup = groupsData.get(group.groupId);
  1482. var draggedGroup = groupsData.get(this.groupTouchParams.group.groupId);
  1483. // switch groups
  1484. if (draggedGroup && targetGroup) {
  1485. this.options.groupOrderSwap(draggedGroup, targetGroup, groupsData);
  1486. groupsData.update(draggedGroup);
  1487. groupsData.update(targetGroup);
  1488. }
  1489. // fetch current order of groups
  1490. var newOrder = groupsData.getIds({
  1491. order: this.options.groupOrder
  1492. });
  1493. // in case of changes since _onGroupDragStart
  1494. if (!util.equalArray(newOrder, this.groupTouchParams.originalOrder)) {
  1495. var origOrder = this.groupTouchParams.originalOrder;
  1496. var draggedId = this.groupTouchParams.group.groupId;
  1497. var numGroups = Math.min(origOrder.length, newOrder.length);
  1498. var curPos = 0;
  1499. var newOffset = 0;
  1500. var orgOffset = 0;
  1501. while (curPos < numGroups) {
  1502. // as long as the groups are where they should be step down along the groups order
  1503. while ((curPos+newOffset) < numGroups
  1504. && (curPos+orgOffset) < numGroups
  1505. && newOrder[curPos+newOffset] == origOrder[curPos+orgOffset]) {
  1506. curPos++;
  1507. }
  1508. // all ok
  1509. if (curPos+newOffset >= numGroups) {
  1510. break;
  1511. }
  1512. // not all ok
  1513. // if dragged group was move upwards everything below should have an offset
  1514. if (newOrder[curPos+newOffset] == draggedId) {
  1515. newOffset = 1;
  1516. continue;
  1517. }
  1518. // if dragged group was move downwards everything above should have an offset
  1519. else if (origOrder[curPos+orgOffset] == draggedId) {
  1520. orgOffset = 1;
  1521. continue;
  1522. }
  1523. // found a group (apart from dragged group) that has the wrong position -> switch with the
  1524. // group at the position where other one should be, fix index arrays and continue
  1525. else {
  1526. var slippedPosition = newOrder.indexOf(origOrder[curPos+orgOffset])
  1527. var switchGroup = groupsData.get(newOrder[curPos+newOffset]);
  1528. var shouldBeGroup = groupsData.get(origOrder[curPos+orgOffset]);
  1529. this.options.groupOrderSwap(switchGroup, shouldBeGroup, groupsData);
  1530. groupsData.update(switchGroup);
  1531. groupsData.update(shouldBeGroup);
  1532. var switchGroupId = newOrder[curPos+newOffset];
  1533. newOrder[curPos+newOffset] = origOrder[curPos+orgOffset];
  1534. newOrder[slippedPosition] = switchGroupId;
  1535. curPos++;
  1536. }
  1537. }
  1538. }
  1539. }
  1540. }
  1541. }
  1542. ItemSet.prototype._onGroupDragEnd = function (event) {
  1543. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1544. event.stopPropagation();
  1545. // update existing group
  1546. var me = this;
  1547. var id = me.groupTouchParams.group.groupId;
  1548. var dataset = me.groupsData.getDataSet();
  1549. var groupData = util.extend({}, dataset.get(id)); // clone the data
  1550. me.options.onMoveGroup(groupData, function (groupData) {
  1551. if (groupData) {
  1552. // apply changes
  1553. groupData[dataset._fieldId] = id; // ensure the group contains its id (can be undefined)
  1554. dataset.update(groupData);
  1555. }
  1556. else {
  1557. // fetch current order of groups
  1558. var newOrder = dataset.getIds({
  1559. order: me.options.groupOrder
  1560. });
  1561. // restore original order
  1562. if (!util.equalArray(newOrder, me.groupTouchParams.originalOrder)) {
  1563. var origOrder = me.groupTouchParams.originalOrder;
  1564. var numGroups = Math.min(origOrder.length, newOrder.length);
  1565. var curPos = 0;
  1566. while (curPos < numGroups) {
  1567. // as long as the groups are where they should be step down along the groups order
  1568. while (curPos < numGroups && newOrder[curPos] == origOrder[curPos]) {
  1569. curPos++;
  1570. }
  1571. // all ok
  1572. if (curPos >= numGroups) {
  1573. break;
  1574. }
  1575. // found a group that has the wrong position -> switch with the
  1576. // group at the position where other one should be, fix index arrays and continue
  1577. var slippedPosition = newOrder.indexOf(origOrder[curPos])
  1578. var switchGroup = dataset.get(newOrder[curPos]);
  1579. var shouldBeGroup = dataset.get(origOrder[curPos]);
  1580. me.options.groupOrderSwap(switchGroup, shouldBeGroup, dataset);
  1581. dataset.update(switchGroup);
  1582. dataset.update(shouldBeGroup);
  1583. var switchGroupId = newOrder[curPos];
  1584. newOrder[curPos] = origOrder[curPos];
  1585. newOrder[slippedPosition] = switchGroupId;
  1586. curPos++;
  1587. }
  1588. }
  1589. }
  1590. });
  1591. me.body.emitter.emit('groupDragged', { groupId: id });
  1592. }
  1593. }
  1594. /**
  1595. * Handle selecting/deselecting an item when tapping it
  1596. * @param {Event} event
  1597. * @private
  1598. */
  1599. ItemSet.prototype._onSelectItem = function (event) {
  1600. if (!this.options.selectable) return;
  1601. var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey);
  1602. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  1603. if (ctrlKey || shiftKey) {
  1604. this._onMultiSelectItem(event);
  1605. return;
  1606. }
  1607. var oldSelection = this.getSelection();
  1608. var item = this.itemFromTarget(event);
  1609. var selection = item ? [item.id] : [];
  1610. this.setSelection(selection);
  1611. var newSelection = this.getSelection();
  1612. // emit a select event,
  1613. // except when old selection is empty and new selection is still empty
  1614. if (newSelection.length > 0 || oldSelection.length > 0) {
  1615. this.body.emitter.emit('select', {
  1616. items: newSelection,
  1617. event: event
  1618. });
  1619. }
  1620. };
  1621. /**
  1622. * Handle hovering an item
  1623. * @param {Event} event
  1624. * @private
  1625. */
  1626. ItemSet.prototype._onMouseOver = function (event) {
  1627. var item = this.itemFromTarget(event);
  1628. if (!item) return;
  1629. // Item we just left
  1630. var related = this.itemFromRelatedTarget(event);
  1631. if (item === related) {
  1632. // We haven't changed item, just element in the item
  1633. return;
  1634. }
  1635. var title = item.getTitle();
  1636. if (title) {
  1637. if (this.popup == null) {
  1638. this.popup = new Popup(this.body.dom.root,
  1639. this.options.tooltip.overflowMethod || 'flip');
  1640. }
  1641. this.popup.setText(title);
  1642. var container = this.body.dom.centerContainer;
  1643. this.popup.setPosition(
  1644. event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft,
  1645. event.clientY - util.getAbsoluteTop(container) + container.offsetTop
  1646. );
  1647. this.popup.show();
  1648. } else {
  1649. // Hovering over item without a title, hide popup
  1650. // Needed instead of _just_ in _onMouseOut due to #2572
  1651. if (this.popup != null) {
  1652. this.popup.hide();
  1653. }
  1654. }
  1655. this.body.emitter.emit('itemover', {
  1656. item: item.id,
  1657. event: 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 (this.popup != null) {
  1670. this.popup.hide();
  1671. }
  1672. this.body.emitter.emit('itemout', {
  1673. item: item.id,
  1674. event: 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 (this.popup) {
  1682. if (!this.popup.hidden) {
  1683. var container = this.body.dom.centerContainer;
  1684. this.popup.setPosition(
  1685. event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft,
  1686. event.clientY - util.getAbsoluteTop(container) + container.offsetTop
  1687. );
  1688. this.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. if (event.type == 'drop') {
  1749. newItemData = JSON.parse(event.dataTransfer.getData("text"))
  1750. newItemData.content = newItemData.content ? newItemData.content : 'new item'
  1751. newItemData.start = newItemData.start ? newItemData.start : (snap ? snap(start, scale, step) : start)
  1752. newItemData.type = newItemData.type || 'box';
  1753. newItemData[this.itemsData._fieldId] = newItemData.id || util.randomUUID();
  1754. if (newItemData.type == 'range' && !newItemData.end) {
  1755. var end = this.body.util.toTime(x + this.props.width / 5);
  1756. newItemData.end = snap ? snap(end, scale, step) : end;
  1757. }
  1758. } else {
  1759. newItemData = {
  1760. start: snap ? snap(start, scale, step) : start,
  1761. content: 'new item'
  1762. };
  1763. newItemData[this.itemsData._fieldId] = util.randomUUID();
  1764. // when default type is a range, add a default end date to the new item
  1765. if (this.options.type === 'range') {
  1766. var end = this.body.util.toTime(x + this.props.width / 5);
  1767. newItemData.end = snap ? snap(end, scale, step) : end;
  1768. }
  1769. }
  1770. var group = this.groupFromTarget(event);
  1771. if (group) {
  1772. newItemData.group = group.groupId;
  1773. }
  1774. // execute async handler to customize (or cancel) adding an item
  1775. newItemData = this._cloneItemData(newItemData); // convert start and end to the correct type
  1776. this.options.onAdd(newItemData, function (item) {
  1777. if (item) {
  1778. me.itemsData.getDataSet().add(item);
  1779. if (event.type == 'drop') {
  1780. me.setSelection([item.id]);
  1781. }
  1782. // TODO: need to trigger a redraw?
  1783. }
  1784. });
  1785. }
  1786. };
  1787. /**
  1788. * Handle selecting/deselecting multiple items when holding an item
  1789. * @param {Event} event
  1790. * @private
  1791. */
  1792. ItemSet.prototype._onMultiSelectItem = function (event) {
  1793. if (!this.options.selectable) return;
  1794. var item = this.itemFromTarget(event);
  1795. if (item) {
  1796. // multi select items (if allowed)
  1797. var selection = this.options.multiselect
  1798. ? this.getSelection() // take current selection
  1799. : []; // deselect current selection
  1800. var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false;
  1801. if (shiftKey && this.options.multiselect) {
  1802. // select all items between the old selection and the tapped item
  1803. var itemGroup = this.itemsData.get(item.id).group;
  1804. // when filtering get the group of the last selected item
  1805. var lastSelectedGroup = undefined;
  1806. if (this.options.multiselectPerGroup) {
  1807. if (selection.length > 0) {
  1808. lastSelectedGroup = this.itemsData.get(selection[0]).group;
  1809. }
  1810. }
  1811. // determine the selection range
  1812. if (!this.options.multiselectPerGroup || lastSelectedGroup == undefined || lastSelectedGroup == itemGroup) {
  1813. selection.push(item.id);
  1814. }
  1815. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  1816. if (!this.options.multiselectPerGroup || lastSelectedGroup == itemGroup) {
  1817. // select all items within the selection range
  1818. selection = [];
  1819. for (var id in this.items) {
  1820. if (this.items.hasOwnProperty(id)) {
  1821. var _item = this.items[id];
  1822. var start = _item.data.start;
  1823. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  1824. if (start >= range.min &&
  1825. end <= range.max &&
  1826. (!this.options.multiselectPerGroup || lastSelectedGroup == this.itemsData.get(_item.id).group) &&
  1827. !(_item instanceof BackgroundItem)) {
  1828. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  1829. }
  1830. }
  1831. }
  1832. }
  1833. }
  1834. else {
  1835. // add/remove this item from the current selection
  1836. var index = selection.indexOf(item.id);
  1837. if (index == -1) {
  1838. // item is not yet selected -> select it
  1839. selection.push(item.id);
  1840. }
  1841. else {
  1842. // item is already selected -> deselect it
  1843. selection.splice(index, 1);
  1844. }
  1845. }
  1846. this.setSelection(selection);
  1847. this.body.emitter.emit('select', {
  1848. items: this.getSelection(),
  1849. event: event
  1850. });
  1851. }
  1852. };
  1853. /**
  1854. * Calculate the time range of a list of items
  1855. * @param {Array.<Object>} itemsData
  1856. * @return {{min: Date, max: Date}} Returns the range of the provided items
  1857. * @private
  1858. */
  1859. ItemSet._getItemRange = function(itemsData) {
  1860. var max = null;
  1861. var min = null;
  1862. itemsData.forEach(function (data) {
  1863. if (min == null || data.start < min) {
  1864. min = data.start;
  1865. }
  1866. if (data.end != undefined) {
  1867. if (max == null || data.end > max) {
  1868. max = data.end;
  1869. }
  1870. }
  1871. else {
  1872. if (max == null || data.start > max) {
  1873. max = data.start;
  1874. }
  1875. }
  1876. });
  1877. return {
  1878. min: min,
  1879. max: max
  1880. }
  1881. };
  1882. /**
  1883. * Find an item from an element:
  1884. * searches for the attribute 'timeline-item' in the element's tree
  1885. * @param {HTMLElement} element
  1886. * @return {Item | null} item
  1887. */
  1888. ItemSet.prototype.itemFromElement = function(element) {
  1889. var cur = element;
  1890. while (cur) {
  1891. if (cur.hasOwnProperty('timeline-item')) {
  1892. return cur['timeline-item'];
  1893. }
  1894. cur = cur.parentNode;
  1895. }
  1896. return null;
  1897. };
  1898. /**
  1899. * Find an item from an event target:
  1900. * searches for the attribute 'timeline-item' in the event target's element tree
  1901. * @param {Event} event
  1902. * @return {Item | null} item
  1903. */
  1904. ItemSet.prototype.itemFromTarget = function(event) {
  1905. return this.itemFromElement(event.target);
  1906. };
  1907. /**
  1908. * Find an item from an event's related target:
  1909. * searches for the attribute 'timeline-item' in the related target's element tree
  1910. * @param {Event} event
  1911. * @return {Item | null} item
  1912. */
  1913. ItemSet.prototype.itemFromRelatedTarget = function(event) {
  1914. return this.itemFromElement(event.relatedTarget);
  1915. };
  1916. /**
  1917. * Find the Group from an event target:
  1918. * searches for the attribute 'timeline-group' in the event target's element tree
  1919. * @param {Event} event
  1920. * @return {Group | null} group
  1921. */
  1922. ItemSet.prototype.groupFromTarget = function(event) {
  1923. var clientY = event.center ? event.center.y : event.clientY;
  1924. var groupIds = this.groupIds;
  1925. if (groupIds.length <= 0) {
  1926. groupIds = this.groupsData.getIds({
  1927. order: this.options.groupOrder
  1928. });
  1929. }
  1930. for (var i = 0; i < groupIds.length; i++) {
  1931. var groupId = groupIds[i];
  1932. var group = this.groups[groupId];
  1933. var foreground = group.dom.foreground;
  1934. var top = util.getAbsoluteTop(foreground);
  1935. if (clientY > top && clientY < top + foreground.offsetHeight) {
  1936. return group;
  1937. }
  1938. if (this.options.orientation.item === 'top') {
  1939. if (i === this.groupIds.length - 1 && clientY > top) {
  1940. return group;
  1941. }
  1942. }
  1943. else {
  1944. if (i === 0 && clientY < top + foreground.offset) {
  1945. return group;
  1946. }
  1947. }
  1948. }
  1949. return null;
  1950. };
  1951. /**
  1952. * Find the ItemSet from an event target:
  1953. * searches for the attribute 'timeline-itemset' in the event target's element tree
  1954. * @param {Event} event
  1955. * @return {ItemSet | null} item
  1956. */
  1957. ItemSet.itemSetFromTarget = function(event) {
  1958. var target = event.target;
  1959. while (target) {
  1960. if (target.hasOwnProperty('timeline-itemset')) {
  1961. return target['timeline-itemset'];
  1962. }
  1963. target = target.parentNode;
  1964. }
  1965. return null;
  1966. };
  1967. /**
  1968. * Clone the data of an item, and "normalize" it: convert the start and end date
  1969. * to the type (Date, Moment, ...) configured in the DataSet. If not configured,
  1970. * start and end are converted to Date.
  1971. * @param {Object} itemData, typically `item.data`
  1972. * @param {string} [type] Optional Date type. If not provided, the type from the DataSet is taken
  1973. * @return {Object} The cloned object
  1974. * @private
  1975. */
  1976. ItemSet.prototype._cloneItemData = function (itemData, type) {
  1977. var clone = util.extend({}, itemData);
  1978. if (!type) {
  1979. // convert start and end date to the type (Date, Moment, ...) configured in the DataSet
  1980. type = this.itemsData.getDataSet()._options.type;
  1981. }
  1982. if (clone.start != undefined) {
  1983. clone.start = util.convert(clone.start, type && type.start || 'Date');
  1984. }
  1985. if (clone.end != undefined) {
  1986. clone.end = util.convert(clone.end , type && type.end || 'Date');
  1987. }
  1988. return clone;
  1989. };
  1990. module.exports = ItemSet;