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.

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