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.

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