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.

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