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.

2313 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. if(this.groupIds.length < 1) {
  1168. // Mitigates a race condition if _onDragStart() is
  1169. // called after markDirty() without redraw() being called between.
  1170. this.redraw();
  1171. }
  1172. var baseGroupIndex = this._getGroupIndex(item.data.group);
  1173. var itemsToDrag = (this.options.itemsAlwaysDraggable.item && !item.selected) ? [item.id] : this.getSelection();
  1174. this.touchParams.itemProps = itemsToDrag.map(function (id) {
  1175. var item = me.items[id];
  1176. var groupIndex = me._getGroupIndex(item.data.group);
  1177. return {
  1178. item: item,
  1179. initialX: event.center.x,
  1180. groupOffset: baseGroupIndex-groupIndex,
  1181. data: this._cloneItemData(item.data)
  1182. };
  1183. }.bind(this));
  1184. }
  1185. event.stopPropagation();
  1186. }
  1187. else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  1188. // create a new range item when dragging with ctrl key down
  1189. this._onDragStartAddItem(event);
  1190. }
  1191. };
  1192. /**
  1193. * Start creating a new range item by dragging.
  1194. * @param {Event} event
  1195. * @private
  1196. */
  1197. ItemSet.prototype._onDragStartAddItem = function (event) {
  1198. var snap = this.options.snap || null;
  1199. if (this.options.rtl) {
  1200. var xAbs = util.getAbsoluteRight(this.dom.frame);
  1201. var x = xAbs - event.center.x + 10; // plus 10 to compensate for the drag starting as soon as you've moved 10px
  1202. } else {
  1203. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1204. var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  1205. }
  1206. var time = this.body.util.toTime(x);
  1207. var scale = this.body.util.getScale();
  1208. var step = this.body.util.getStep();
  1209. var start = snap ? snap(time, scale, step) : time;
  1210. var end = start;
  1211. var itemData = {
  1212. type: 'range',
  1213. start: start,
  1214. end: end,
  1215. content: 'new item'
  1216. };
  1217. var id = util.randomUUID();
  1218. itemData[this.itemsData._fieldId] = id;
  1219. var group = this.groupFromTarget(event);
  1220. if (group) {
  1221. itemData.group = group.groupId;
  1222. }
  1223. var newItem = new RangeItem(itemData, this.conversion, this.options);
  1224. newItem.id = id; // TODO: not so nice setting id afterwards
  1225. newItem.data = this._cloneItemData(itemData);
  1226. this._addItem(newItem);
  1227. this.touchParams.selectedItem = newItem;
  1228. var props = {
  1229. item: newItem,
  1230. initialX: event.center.x,
  1231. data: newItem.data
  1232. };
  1233. if (this.options.rtl) {
  1234. props.dragLeft = true;
  1235. } else {
  1236. props.dragRight = true;
  1237. }
  1238. this.touchParams.itemProps = [props];
  1239. event.stopPropagation();
  1240. };
  1241. /**
  1242. * Drag selected items
  1243. * @param {Event} event
  1244. * @private
  1245. */
  1246. ItemSet.prototype._onDrag = function (event) {
  1247. if (this.touchParams.itemProps) {
  1248. event.stopPropagation();
  1249. var me = this;
  1250. var snap = this.options.snap || null;
  1251. if (this.options.rtl) {
  1252. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.right.width;
  1253. } else {
  1254. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  1255. }
  1256. var scale = this.body.util.getScale();
  1257. var step = this.body.util.getStep();
  1258. //only calculate the new group for the item that's actually dragged
  1259. var selectedItem = this.touchParams.selectedItem;
  1260. var updateGroupAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateGroup) ||
  1261. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateGroup);
  1262. var newGroupBase = null;
  1263. if (updateGroupAllowed && selectedItem) {
  1264. if (selectedItem.data.group != undefined) {
  1265. // drag from one group to another
  1266. var group = me.groupFromTarget(event);
  1267. if (group) {
  1268. //we know the offset for all items, so the new group for all items
  1269. //will be relative to this one.
  1270. newGroupBase = this._getGroupIndex(group.groupId);
  1271. }
  1272. }
  1273. }
  1274. // move
  1275. this.touchParams.itemProps.forEach(function (props) {
  1276. var current = me.body.util.toTime(event.center.x - xOffset);
  1277. var initial = me.body.util.toTime(props.initialX - xOffset);
  1278. if (this.options.rtl) {
  1279. var offset = -(current - initial); // ms
  1280. } else {
  1281. var offset = (current - initial); // ms
  1282. }
  1283. var itemData = this._cloneItemData(props.item.data); // clone the data
  1284. if (props.item.editable != null
  1285. && !props.item.editable.updateTime
  1286. && !props.item.editable.updateGroup
  1287. && !me.options.editable.overrideItems) {
  1288. return;
  1289. }
  1290. var updateTimeAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateTime) ||
  1291. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateTime);
  1292. if (updateTimeAllowed) {
  1293. if (props.dragLeft) {
  1294. // drag left side of a range item
  1295. if (this.options.rtl) {
  1296. if (itemData.end != undefined) {
  1297. var initialEnd = util.convert(props.data.end, 'Date');
  1298. var end = new Date(initialEnd.valueOf() + offset);
  1299. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1300. itemData.end = snap ? snap(end, scale, step) : end;
  1301. }
  1302. } else {
  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. }
  1310. }
  1311. else if (props.dragRight) {
  1312. // drag right side of a range item
  1313. if (this.options.rtl) {
  1314. if (itemData.start != undefined) {
  1315. var initialStart = util.convert(props.data.start, 'Date');
  1316. var start = new Date(initialStart.valueOf() + offset);
  1317. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1318. itemData.start = snap ? snap(start, scale, step) : start;
  1319. }
  1320. } else {
  1321. if (itemData.end != undefined) {
  1322. var initialEnd = util.convert(props.data.end, 'Date');
  1323. var end = new Date(initialEnd.valueOf() + offset);
  1324. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1325. itemData.end = snap ? snap(end, scale, step) : end;
  1326. }
  1327. }
  1328. }
  1329. else {
  1330. // drag both start and end
  1331. if (itemData.start != undefined) {
  1332. var initialStart = util.convert(props.data.start, 'Date').valueOf();
  1333. var start = new Date(initialStart + offset);
  1334. if (itemData.end != undefined) {
  1335. var initialEnd = util.convert(props.data.end, 'Date');
  1336. var duration = initialEnd.valueOf() - initialStart.valueOf();
  1337. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1338. itemData.start = snap ? snap(start, scale, step) : start;
  1339. itemData.end = new Date(itemData.start.valueOf() + duration);
  1340. }
  1341. else {
  1342. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1343. itemData.start = snap ? snap(start, scale, step) : start;
  1344. }
  1345. }
  1346. }
  1347. }
  1348. if (updateGroupAllowed && (!props.dragLeft && !props.dragRight) && newGroupBase!=null) {
  1349. if (itemData.group != undefined) {
  1350. var newOffset = newGroupBase - props.groupOffset;
  1351. //make sure we stay in bounds
  1352. newOffset = Math.max(0, newOffset);
  1353. newOffset = Math.min(me.groupIds.length-1, newOffset);
  1354. itemData.group = me.groupIds[newOffset];
  1355. }
  1356. }
  1357. // confirm moving the item
  1358. itemData = this._cloneItemData(itemData); // convert start and end to the correct type
  1359. me.options.onMoving(itemData, function (itemData) {
  1360. if (itemData) {
  1361. props.item.setData(this._cloneItemData(itemData, 'Date'));
  1362. }
  1363. }.bind(this));
  1364. }.bind(this));
  1365. this.body.emitter.emit('_change');
  1366. }
  1367. };
  1368. /**
  1369. * Move an item to another group
  1370. * @param {Item} item
  1371. * @param {String | Number} groupId
  1372. * @private
  1373. */
  1374. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1375. var group = this.groups[groupId];
  1376. if (group && group.groupId != item.data.group) {
  1377. var oldGroup = item.parent;
  1378. oldGroup.remove(item);
  1379. oldGroup.order();
  1380. item.data.group = group.groupId;
  1381. group.add(item);
  1382. group.order();
  1383. }
  1384. };
  1385. /**
  1386. * End of dragging selected items
  1387. * @param {Event} event
  1388. * @private
  1389. */
  1390. ItemSet.prototype._onDragEnd = function (event) {
  1391. this.touchParams.itemIsDragging = false;
  1392. if (this.touchParams.itemProps) {
  1393. event.stopPropagation();
  1394. var me = this;
  1395. var dataset = this.itemsData.getDataSet();
  1396. var itemProps = this.touchParams.itemProps ;
  1397. this.touchParams.itemProps = null;
  1398. itemProps.forEach(function (props) {
  1399. var id = props.item.id;
  1400. var exists = me.itemsData.get(id, me.itemOptions) != null;
  1401. if (!exists) {
  1402. // add a new item
  1403. me.options.onAdd(props.item.data, function (itemData) {
  1404. me._removeItem(props.item); // remove temporary item
  1405. if (itemData) {
  1406. me.itemsData.getDataSet().add(itemData);
  1407. }
  1408. // force re-stacking of all items next redraw
  1409. me.body.emitter.emit('_change');
  1410. });
  1411. }
  1412. else {
  1413. // update existing item
  1414. var itemData = this._cloneItemData(props.item.data); // convert start and end to the correct type
  1415. me.options.onMove(itemData, function (itemData) {
  1416. if (itemData) {
  1417. // apply changes
  1418. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1419. dataset.update(itemData);
  1420. }
  1421. else {
  1422. // restore original values
  1423. props.item.setData(props.data);
  1424. me.body.emitter.emit('_change');
  1425. }
  1426. });
  1427. }
  1428. }.bind(this));
  1429. }
  1430. };
  1431. ItemSet.prototype._onGroupClick = function (event) {
  1432. var group = this.groupFromTarget(event);
  1433. if (!group || !group.nestedGroups) return;
  1434. var groupsData = this.groupsData;
  1435. if (this.groupsData instanceof DataView) {
  1436. groupsData = this.groupsData.getDataSet()
  1437. }
  1438. group.showNested = !group.showNested;
  1439. var nestedGroups = groupsData.get(group.nestedGroups).map(function(nestedGroup) {
  1440. if (nestedGroup.visible == undefined) { nestedGroup.visible = true; }
  1441. nestedGroup.visible = !!group.showNested;
  1442. return nestedGroup;
  1443. });
  1444. groupsData.update(nestedGroups);
  1445. if (group.showNested) {
  1446. util.removeClassName(group.dom.label, 'collapsed');
  1447. util.addClassName(group.dom.label, 'expanded');
  1448. } else {
  1449. util.removeClassName(group.dom.label, 'expanded');
  1450. var collapsedDirClassName = this.options.rtl ? 'collapsed-rtl' : 'collapsed'
  1451. util.addClassName(group.dom.label, collapsedDirClassName);
  1452. }
  1453. }
  1454. ItemSet.prototype._onGroupDragStart = function (event) {
  1455. if (this.options.groupEditable.order) {
  1456. this.groupTouchParams.group = this.groupFromTarget(event);
  1457. if (this.groupTouchParams.group) {
  1458. event.stopPropagation();
  1459. this.groupTouchParams.originalOrder = this.groupsData.getIds({
  1460. order: this.options.groupOrder
  1461. });
  1462. }
  1463. }
  1464. }
  1465. ItemSet.prototype._onGroupDrag = function (event) {
  1466. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1467. event.stopPropagation();
  1468. var groupsData = this.groupsData;
  1469. if (this.groupsData instanceof DataView) {
  1470. groupsData = this.groupsData.getDataSet()
  1471. }
  1472. // drag from one group to another
  1473. var group = this.groupFromTarget(event);
  1474. // try to avoid toggling when groups differ in height
  1475. if (group && group.height != this.groupTouchParams.group.height) {
  1476. var movingUp = (group.top < this.groupTouchParams.group.top);
  1477. var clientY = event.center ? event.center.y : event.clientY;
  1478. var targetGroupTop = util.getAbsoluteTop(group.dom.foreground);
  1479. var draggedGroupHeight = this.groupTouchParams.group.height;
  1480. if (movingUp) {
  1481. // skip swapping the groups when the dragged group is not below clientY afterwards
  1482. if (targetGroupTop + draggedGroupHeight < clientY) {
  1483. return;
  1484. }
  1485. } else {
  1486. var targetGroupHeight = group.height;
  1487. // skip swapping the groups when the dragged group is not below clientY afterwards
  1488. if (targetGroupTop + targetGroupHeight - draggedGroupHeight > clientY) {
  1489. return;
  1490. }
  1491. }
  1492. }
  1493. if (group && group != this.groupTouchParams.group) {
  1494. var targetGroup = groupsData.get(group.groupId);
  1495. var draggedGroup = groupsData.get(this.groupTouchParams.group.groupId);
  1496. // switch groups
  1497. if (draggedGroup && targetGroup) {
  1498. this.options.groupOrderSwap(draggedGroup, targetGroup, groupsData);
  1499. groupsData.update(draggedGroup);
  1500. groupsData.update(targetGroup);
  1501. }
  1502. // fetch current order of groups
  1503. var newOrder = groupsData.getIds({
  1504. order: this.options.groupOrder
  1505. });
  1506. // in case of changes since _onGroupDragStart
  1507. if (!util.equalArray(newOrder, this.groupTouchParams.originalOrder)) {
  1508. var origOrder = this.groupTouchParams.originalOrder;
  1509. var draggedId = this.groupTouchParams.group.groupId;
  1510. var numGroups = Math.min(origOrder.length, newOrder.length);
  1511. var curPos = 0;
  1512. var newOffset = 0;
  1513. var orgOffset = 0;
  1514. while (curPos < numGroups) {
  1515. // as long as the groups are where they should be step down along the groups order
  1516. while ((curPos+newOffset) < numGroups
  1517. && (curPos+orgOffset) < numGroups
  1518. && newOrder[curPos+newOffset] == origOrder[curPos+orgOffset]) {
  1519. curPos++;
  1520. }
  1521. // all ok
  1522. if (curPos+newOffset >= numGroups) {
  1523. break;
  1524. }
  1525. // not all ok
  1526. // if dragged group was move upwards everything below should have an offset
  1527. if (newOrder[curPos+newOffset] == draggedId) {
  1528. newOffset = 1;
  1529. continue;
  1530. }
  1531. // if dragged group was move downwards everything above should have an offset
  1532. else if (origOrder[curPos+orgOffset] == draggedId) {
  1533. orgOffset = 1;
  1534. continue;
  1535. }
  1536. // found a group (apart from dragged group) that has the wrong position -> switch with the
  1537. // group at the position where other one should be, fix index arrays and continue
  1538. else {
  1539. var slippedPosition = newOrder.indexOf(origOrder[curPos+orgOffset])
  1540. var switchGroup = groupsData.get(newOrder[curPos+newOffset]);
  1541. var shouldBeGroup = groupsData.get(origOrder[curPos+orgOffset]);
  1542. this.options.groupOrderSwap(switchGroup, shouldBeGroup, groupsData);
  1543. groupsData.update(switchGroup);
  1544. groupsData.update(shouldBeGroup);
  1545. var switchGroupId = newOrder[curPos+newOffset];
  1546. newOrder[curPos+newOffset] = origOrder[curPos+orgOffset];
  1547. newOrder[slippedPosition] = switchGroupId;
  1548. curPos++;
  1549. }
  1550. }
  1551. }
  1552. }
  1553. }
  1554. }
  1555. ItemSet.prototype._onGroupDragEnd = function (event) {
  1556. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1557. event.stopPropagation();
  1558. // update existing group
  1559. var me = this;
  1560. var id = me.groupTouchParams.group.groupId;
  1561. var dataset = me.groupsData.getDataSet();
  1562. var groupData = util.extend({}, dataset.get(id)); // clone the data
  1563. me.options.onMoveGroup(groupData, function (groupData) {
  1564. if (groupData) {
  1565. // apply changes
  1566. groupData[dataset._fieldId] = id; // ensure the group contains its id (can be undefined)
  1567. dataset.update(groupData);
  1568. }
  1569. else {
  1570. // fetch current order of groups
  1571. var newOrder = dataset.getIds({
  1572. order: me.options.groupOrder
  1573. });
  1574. // restore original order
  1575. if (!util.equalArray(newOrder, me.groupTouchParams.originalOrder)) {
  1576. var origOrder = me.groupTouchParams.originalOrder;
  1577. var numGroups = Math.min(origOrder.length, newOrder.length);
  1578. var curPos = 0;
  1579. while (curPos < numGroups) {
  1580. // as long as the groups are where they should be step down along the groups order
  1581. while (curPos < numGroups && newOrder[curPos] == origOrder[curPos]) {
  1582. curPos++;
  1583. }
  1584. // all ok
  1585. if (curPos >= numGroups) {
  1586. break;
  1587. }
  1588. // found a group that has the wrong position -> switch with the
  1589. // group at the position where other one should be, fix index arrays and continue
  1590. var slippedPosition = newOrder.indexOf(origOrder[curPos])
  1591. var switchGroup = dataset.get(newOrder[curPos]);
  1592. var shouldBeGroup = dataset.get(origOrder[curPos]);
  1593. me.options.groupOrderSwap(switchGroup, shouldBeGroup, dataset);
  1594. dataset.update(switchGroup);
  1595. dataset.update(shouldBeGroup);
  1596. var switchGroupId = newOrder[curPos];
  1597. newOrder[curPos] = origOrder[curPos];
  1598. newOrder[slippedPosition] = switchGroupId;
  1599. curPos++;
  1600. }
  1601. }
  1602. }
  1603. });
  1604. me.body.emitter.emit('groupDragged', { groupId: id });
  1605. }
  1606. }
  1607. /**
  1608. * Handle selecting/deselecting an item when tapping it
  1609. * @param {Event} event
  1610. * @private
  1611. */
  1612. ItemSet.prototype._onSelectItem = function (event) {
  1613. if (!this.options.selectable) return;
  1614. var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey);
  1615. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  1616. if (ctrlKey || shiftKey) {
  1617. this._onMultiSelectItem(event);
  1618. return;
  1619. }
  1620. var oldSelection = this.getSelection();
  1621. var item = this.itemFromTarget(event);
  1622. var selection = item ? [item.id] : [];
  1623. this.setSelection(selection);
  1624. var newSelection = this.getSelection();
  1625. // emit a select event,
  1626. // except when old selection is empty and new selection is still empty
  1627. if (newSelection.length > 0 || oldSelection.length > 0) {
  1628. this.body.emitter.emit('select', {
  1629. items: newSelection,
  1630. event: event
  1631. });
  1632. }
  1633. };
  1634. /**
  1635. * Handle hovering an item
  1636. * @param {Event} event
  1637. * @private
  1638. */
  1639. ItemSet.prototype._onMouseOver = function (event) {
  1640. var item = this.itemFromTarget(event);
  1641. if (!item) return;
  1642. // Item we just left
  1643. var related = this.itemFromRelatedTarget(event);
  1644. if (item === related) {
  1645. // We haven't changed item, just element in the item
  1646. return;
  1647. }
  1648. var title = item.getTitle();
  1649. if (this.options.showTooltips && title) {
  1650. if (this.popup == null) {
  1651. this.popup = new Popup(this.body.dom.root,
  1652. this.options.tooltip.overflowMethod || 'flip');
  1653. }
  1654. this.popup.setText(title);
  1655. var container = this.body.dom.centerContainer;
  1656. this.popup.setPosition(
  1657. event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft,
  1658. event.clientY - util.getAbsoluteTop(container) + container.offsetTop
  1659. );
  1660. this.popup.show();
  1661. } else {
  1662. // Hovering over item without a title, hide popup
  1663. // Needed instead of _just_ in _onMouseOut due to #2572
  1664. if (this.popup != null) {
  1665. this.popup.hide();
  1666. }
  1667. }
  1668. this.body.emitter.emit('itemover', {
  1669. item: item.id,
  1670. event: event
  1671. });
  1672. };
  1673. ItemSet.prototype._onMouseOut = function (event) {
  1674. var item = this.itemFromTarget(event);
  1675. if (!item) return;
  1676. // Item we are going to
  1677. var related = this.itemFromRelatedTarget(event);
  1678. if (item === related) {
  1679. // We aren't changing item, just element in the item
  1680. return;
  1681. }
  1682. if (this.popup != null) {
  1683. this.popup.hide();
  1684. }
  1685. this.body.emitter.emit('itemout', {
  1686. item: item.id,
  1687. event: event
  1688. });
  1689. };
  1690. ItemSet.prototype._onMouseMove = function (event) {
  1691. var item = this.itemFromTarget(event);
  1692. if (!item) return;
  1693. if (this.options.showTooltips && this.options.tooltip.followMouse) {
  1694. if (this.popup) {
  1695. if (!this.popup.hidden) {
  1696. var container = this.body.dom.centerContainer;
  1697. this.popup.setPosition(
  1698. event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft,
  1699. event.clientY - util.getAbsoluteTop(container) + container.offsetTop
  1700. );
  1701. this.popup.show(); // Redraw
  1702. }
  1703. }
  1704. }
  1705. };
  1706. /**
  1707. * Handle mousewheel
  1708. * @param event
  1709. * @private
  1710. */
  1711. ItemSet.prototype._onMouseWheel = function(event) {
  1712. if (this.touchParams.itemIsDragging) {
  1713. this._onDragEnd(event);
  1714. }
  1715. }
  1716. /**
  1717. * Handle updates of an item on double tap
  1718. * @param event
  1719. * @private
  1720. */
  1721. ItemSet.prototype._onUpdateItem = function (item) {
  1722. if (!this.options.selectable) return;
  1723. if (!this.options.editable.add) return;
  1724. var me = this;
  1725. if (item) {
  1726. // execute async handler to update the item (or cancel it)
  1727. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  1728. this.options.onUpdate(itemData, function (itemData) {
  1729. if (itemData) {
  1730. me.itemsData.getDataSet().update(itemData);
  1731. }
  1732. });
  1733. }
  1734. }
  1735. /**
  1736. * Handle creation of an item on double tap
  1737. * @param event
  1738. * @private
  1739. */
  1740. ItemSet.prototype._onAddItem = function (event) {
  1741. if (!this.options.selectable) return;
  1742. if (!this.options.editable.add) return;
  1743. var me = this;
  1744. var snap = this.options.snap || null;
  1745. var item = this.itemFromTarget(event);
  1746. if (!item) {
  1747. // add item
  1748. if (this.options.rtl) {
  1749. var xAbs = util.getAbsoluteRight(this.dom.frame);
  1750. var x = xAbs - event.center.x;
  1751. } else {
  1752. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1753. var x = event.center.x - xAbs;
  1754. }
  1755. // var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1756. // var x = event.center.x - xAbs;
  1757. var start = this.body.util.toTime(x);
  1758. var scale = this.body.util.getScale();
  1759. var step = this.body.util.getStep();
  1760. var newItemData;
  1761. if (event.type == 'drop') {
  1762. newItemData = JSON.parse(event.dataTransfer.getData("text"))
  1763. newItemData.content = newItemData.content ? newItemData.content : 'new item'
  1764. newItemData.start = newItemData.start ? newItemData.start : (snap ? snap(start, scale, step) : start)
  1765. newItemData.type = newItemData.type || 'box';
  1766. newItemData[this.itemsData._fieldId] = newItemData.id || util.randomUUID();
  1767. if (newItemData.type == 'range' && !newItemData.end) {
  1768. var end = this.body.util.toTime(x + this.props.width / 5);
  1769. newItemData.end = snap ? snap(end, scale, step) : end;
  1770. }
  1771. } else {
  1772. newItemData = {
  1773. start: snap ? snap(start, scale, step) : start,
  1774. content: 'new item'
  1775. };
  1776. newItemData[this.itemsData._fieldId] = util.randomUUID();
  1777. // when default type is a range, add a default end date to the new item
  1778. if (this.options.type === 'range') {
  1779. var end = this.body.util.toTime(x + this.props.width / 5);
  1780. newItemData.end = snap ? snap(end, scale, step) : end;
  1781. }
  1782. }
  1783. var group = this.groupFromTarget(event);
  1784. if (group) {
  1785. newItemData.group = group.groupId;
  1786. }
  1787. // execute async handler to customize (or cancel) adding an item
  1788. newItemData = this._cloneItemData(newItemData); // convert start and end to the correct type
  1789. this.options.onAdd(newItemData, function (item) {
  1790. if (item) {
  1791. me.itemsData.getDataSet().add(item);
  1792. if (event.type == 'drop') {
  1793. me.setSelection([item.id]);
  1794. }
  1795. // TODO: need to trigger a redraw?
  1796. }
  1797. });
  1798. }
  1799. };
  1800. /**
  1801. * Handle selecting/deselecting multiple items when holding an item
  1802. * @param {Event} event
  1803. * @private
  1804. */
  1805. ItemSet.prototype._onMultiSelectItem = function (event) {
  1806. if (!this.options.selectable) return;
  1807. var item = this.itemFromTarget(event);
  1808. if (item) {
  1809. // multi select items (if allowed)
  1810. var selection = this.options.multiselect
  1811. ? this.getSelection() // take current selection
  1812. : []; // deselect current selection
  1813. var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false;
  1814. if (shiftKey && this.options.multiselect) {
  1815. // select all items between the old selection and the tapped item
  1816. var itemGroup = this.itemsData.get(item.id).group;
  1817. // when filtering get the group of the last selected item
  1818. var lastSelectedGroup = undefined;
  1819. if (this.options.multiselectPerGroup) {
  1820. if (selection.length > 0) {
  1821. lastSelectedGroup = this.itemsData.get(selection[0]).group;
  1822. }
  1823. }
  1824. // determine the selection range
  1825. if (!this.options.multiselectPerGroup || lastSelectedGroup == undefined || lastSelectedGroup == itemGroup) {
  1826. selection.push(item.id);
  1827. }
  1828. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  1829. if (!this.options.multiselectPerGroup || lastSelectedGroup == itemGroup) {
  1830. // select all items within the selection range
  1831. selection = [];
  1832. for (var id in this.items) {
  1833. if (this.items.hasOwnProperty(id)) {
  1834. var _item = this.items[id];
  1835. var start = _item.data.start;
  1836. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  1837. if (start >= range.min &&
  1838. end <= range.max &&
  1839. (!this.options.multiselectPerGroup || lastSelectedGroup == this.itemsData.get(_item.id).group) &&
  1840. !(_item instanceof BackgroundItem)) {
  1841. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  1842. }
  1843. }
  1844. }
  1845. }
  1846. }
  1847. else {
  1848. // add/remove this item from the current selection
  1849. var index = selection.indexOf(item.id);
  1850. if (index == -1) {
  1851. // item is not yet selected -> select it
  1852. selection.push(item.id);
  1853. }
  1854. else {
  1855. // item is already selected -> deselect it
  1856. selection.splice(index, 1);
  1857. }
  1858. }
  1859. this.setSelection(selection);
  1860. this.body.emitter.emit('select', {
  1861. items: this.getSelection(),
  1862. event: event
  1863. });
  1864. }
  1865. };
  1866. /**
  1867. * Calculate the time range of a list of items
  1868. * @param {Array.<Object>} itemsData
  1869. * @return {{min: Date, max: Date}} Returns the range of the provided items
  1870. * @private
  1871. */
  1872. ItemSet._getItemRange = function(itemsData) {
  1873. var max = null;
  1874. var min = null;
  1875. itemsData.forEach(function (data) {
  1876. if (min == null || data.start < min) {
  1877. min = data.start;
  1878. }
  1879. if (data.end != undefined) {
  1880. if (max == null || data.end > max) {
  1881. max = data.end;
  1882. }
  1883. }
  1884. else {
  1885. if (max == null || data.start > max) {
  1886. max = data.start;
  1887. }
  1888. }
  1889. });
  1890. return {
  1891. min: min,
  1892. max: max
  1893. }
  1894. };
  1895. /**
  1896. * Find an item from an element:
  1897. * searches for the attribute 'timeline-item' in the element's tree
  1898. * @param {HTMLElement} element
  1899. * @return {Item | null} item
  1900. */
  1901. ItemSet.prototype.itemFromElement = function(element) {
  1902. var cur = element;
  1903. while (cur) {
  1904. if (cur.hasOwnProperty('timeline-item')) {
  1905. return cur['timeline-item'];
  1906. }
  1907. cur = cur.parentNode;
  1908. }
  1909. return null;
  1910. };
  1911. /**
  1912. * Find an item from an event target:
  1913. * searches for the attribute 'timeline-item' in the event target's element tree
  1914. * @param {Event} event
  1915. * @return {Item | null} item
  1916. */
  1917. ItemSet.prototype.itemFromTarget = function(event) {
  1918. return this.itemFromElement(event.target);
  1919. };
  1920. /**
  1921. * Find an item from an event's related target:
  1922. * searches for the attribute 'timeline-item' in the related target's element tree
  1923. * @param {Event} event
  1924. * @return {Item | null} item
  1925. */
  1926. ItemSet.prototype.itemFromRelatedTarget = function(event) {
  1927. return this.itemFromElement(event.relatedTarget);
  1928. };
  1929. /**
  1930. * Find the Group from an event target:
  1931. * searches for the attribute 'timeline-group' in the event target's element tree
  1932. * @param {Event} event
  1933. * @return {Group | null} group
  1934. */
  1935. ItemSet.prototype.groupFromTarget = function(event) {
  1936. var clientY = event.center ? event.center.y : event.clientY;
  1937. var groupIds = this.groupIds;
  1938. if (groupIds.length <= 0 && this.groupsData) {
  1939. groupIds = this.groupsData.getIds({
  1940. order: this.options.groupOrder
  1941. });
  1942. }
  1943. for (var i = 0; i < groupIds.length; i++) {
  1944. var groupId = groupIds[i];
  1945. var group = this.groups[groupId];
  1946. var foreground = group.dom.foreground;
  1947. var top = util.getAbsoluteTop(foreground);
  1948. if (clientY > top && clientY < top + foreground.offsetHeight) {
  1949. return group;
  1950. }
  1951. if (this.options.orientation.item === 'top') {
  1952. if (i === this.groupIds.length - 1 && clientY > top) {
  1953. return group;
  1954. }
  1955. }
  1956. else {
  1957. if (i === 0 && clientY < top + foreground.offset) {
  1958. return group;
  1959. }
  1960. }
  1961. }
  1962. return null;
  1963. };
  1964. /**
  1965. * Find the ItemSet from an event target:
  1966. * searches for the attribute 'timeline-itemset' in the event target's element tree
  1967. * @param {Event} event
  1968. * @return {ItemSet | null} item
  1969. */
  1970. ItemSet.itemSetFromTarget = function(event) {
  1971. var target = event.target;
  1972. while (target) {
  1973. if (target.hasOwnProperty('timeline-itemset')) {
  1974. return target['timeline-itemset'];
  1975. }
  1976. target = target.parentNode;
  1977. }
  1978. return null;
  1979. };
  1980. /**
  1981. * Clone the data of an item, and "normalize" it: convert the start and end date
  1982. * to the type (Date, Moment, ...) configured in the DataSet. If not configured,
  1983. * start and end are converted to Date.
  1984. * @param {Object} itemData, typically `item.data`
  1985. * @param {string} [type] Optional Date type. If not provided, the type from the DataSet is taken
  1986. * @return {Object} The cloned object
  1987. * @private
  1988. */
  1989. ItemSet.prototype._cloneItemData = function (itemData, type) {
  1990. var clone = util.extend({}, itemData);
  1991. if (!type) {
  1992. // convert start and end date to the type (Date, Moment, ...) configured in the DataSet
  1993. type = this.itemsData.getDataSet()._options.type;
  1994. }
  1995. if (clone.start != undefined) {
  1996. clone.start = util.convert(clone.start, type && type.start || 'Date');
  1997. }
  1998. if (clone.end != undefined) {
  1999. clone.end = util.convert(clone.end , type && type.end || 'Date');
  2000. }
  2001. return clone;
  2002. };
  2003. module.exports = ItemSet;