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.

2302 lines
67 KiB

10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. var Hammer = require('../../module/hammer');
  2. var util = require('../../util');
  3. var DataSet = require('../../DataSet');
  4. var DataView = require('../../DataView');
  5. var TimeStep = require('../TimeStep');
  6. var Component = require('./Component');
  7. var Group = require('./Group');
  8. var BackgroundGroup = require('./BackgroundGroup');
  9. var BoxItem = require('./item/BoxItem');
  10. var PointItem = require('./item/PointItem');
  11. var RangeItem = require('./item/RangeItem');
  12. var BackgroundItem = require('./item/BackgroundItem');
  13. import Popup from '../../shared/Popup';
  14. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  15. var BACKGROUND = '__background__'; // reserved group id for background items without group
  16. /**
  17. * An ItemSet holds a set of items and ranges which can be displayed in a
  18. * range. The width is determined by the parent of the ItemSet, and the height
  19. * is determined by the size of the items.
  20. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  21. * @param {Object} [options] See ItemSet.setOptions for the available options.
  22. * @constructor ItemSet
  23. * @extends Component
  24. */
  25. function ItemSet(body, options) {
  26. this.body = body;
  27. this.defaultOptions = {
  28. type: null, // 'box', 'point', 'range', 'background'
  29. orientation: {
  30. item: 'bottom' // item orientation: 'top' or 'bottom'
  31. },
  32. align: 'auto', // alignment of box items
  33. stack: true,
  34. stackSubgroups: true,
  35. groupOrderSwap: function(fromGroup, toGroup, groups) {
  36. var targetOrder = toGroup.order;
  37. toGroup.order = fromGroup.order;
  38. fromGroup.order = targetOrder;
  39. },
  40. groupOrder: 'order',
  41. selectable: true,
  42. multiselect: false,
  43. itemsAlwaysDraggable: false,
  44. editable: {
  45. updateTime: false,
  46. updateGroup: false,
  47. add: false,
  48. remove: false,
  49. overrideItems: false
  50. },
  51. groupEditable: {
  52. order: false,
  53. add: false,
  54. remove: false
  55. },
  56. snap: TimeStep.snap,
  57. onAdd: function (item, callback) {
  58. callback(item);
  59. },
  60. onUpdate: function (item, callback) {
  61. callback(item);
  62. },
  63. onMove: function (item, callback) {
  64. callback(item);
  65. },
  66. onRemove: function (item, callback) {
  67. callback(item);
  68. },
  69. onMoving: function (item, callback) {
  70. callback(item);
  71. },
  72. onAddGroup: function (item, callback) {
  73. callback(item);
  74. },
  75. onMoveGroup: function (item, callback) {
  76. callback(item);
  77. },
  78. onRemoveGroup: function (item, callback) {
  79. callback(item);
  80. },
  81. margin: {
  82. item: {
  83. horizontal: 10,
  84. vertical: 10
  85. },
  86. axis: 20
  87. },
  88. tooltip: {
  89. followMouse: false,
  90. overflowMethod: 'flip'
  91. },
  92. tooltipOnItemUpdateTime: false
  93. };
  94. // options is shared by this ItemSet and all its items
  95. this.options = util.extend({}, this.defaultOptions);
  96. this.options.rtl = options.rtl;
  97. // options for getting items from the DataSet with the correct type
  98. this.itemOptions = {
  99. type: {start: 'Date', end: 'Date'}
  100. };
  101. this.conversion = {
  102. toScreen: body.util.toScreen,
  103. toTime: body.util.toTime
  104. };
  105. this.dom = {};
  106. this.props = {};
  107. this.hammer = null;
  108. var me = this;
  109. this.itemsData = null; // DataSet
  110. this.groupsData = null; // DataSet
  111. // listeners for the DataSet of the items
  112. this.itemListeners = {
  113. 'add': function (event, params, senderId) {
  114. me._onAdd(params.items);
  115. },
  116. 'update': function (event, params, senderId) {
  117. me._onUpdate(params.items);
  118. },
  119. 'remove': function (event, params, senderId) {
  120. me._onRemove(params.items);
  121. }
  122. };
  123. // listeners for the DataSet of the groups
  124. this.groupListeners = {
  125. 'add': function (event, params, senderId) {
  126. me._onAddGroups(params.items);
  127. },
  128. 'update': function (event, params, senderId) {
  129. me._onUpdateGroups(params.items);
  130. },
  131. 'remove': function (event, params, senderId) {
  132. me._onRemoveGroups(params.items);
  133. }
  134. };
  135. this.items = {}; // object with an Item for every data item
  136. this.groups = {}; // Group object for every group
  137. this.groupIds = [];
  138. this.selection = []; // list with the ids of all selected nodes
  139. this.stackDirty = true; // if true, all items will be restacked on next redraw
  140. this.popup = null;
  141. this.touchParams = {}; // stores properties while dragging
  142. this.groupTouchParams = {};
  143. // create the HTML DOM
  144. this._create();
  145. this.setOptions(options);
  146. }
  147. ItemSet.prototype = new Component();
  148. // available item types will be registered here
  149. ItemSet.types = {
  150. background: BackgroundItem,
  151. box: BoxItem,
  152. range: RangeItem,
  153. point: PointItem
  154. };
  155. /**
  156. * Create the HTML DOM for the ItemSet
  157. */
  158. ItemSet.prototype._create = function(){
  159. var frame = document.createElement('div');
  160. frame.className = 'vis-itemset';
  161. frame['timeline-itemset'] = this;
  162. this.dom.frame = frame;
  163. // create background panel
  164. var background = document.createElement('div');
  165. background.className = 'vis-background';
  166. frame.appendChild(background);
  167. this.dom.background = background;
  168. // create foreground panel
  169. var foreground = document.createElement('div');
  170. foreground.className = 'vis-foreground';
  171. frame.appendChild(foreground);
  172. this.dom.foreground = foreground;
  173. // create axis panel
  174. var axis = document.createElement('div');
  175. axis.className = 'vis-axis';
  176. this.dom.axis = axis;
  177. // create labelset
  178. var labelSet = document.createElement('div');
  179. labelSet.className = 'vis-labelset';
  180. this.dom.labelSet = labelSet;
  181. // create ungrouped Group
  182. this._updateUngrouped();
  183. // create background Group
  184. var backgroundGroup = new BackgroundGroup(BACKGROUND, null, this);
  185. backgroundGroup.show();
  186. this.groups[BACKGROUND] = backgroundGroup;
  187. // attach event listeners
  188. // Note: we bind to the centerContainer for the case where the height
  189. // of the center container is larger than of the ItemSet, so we
  190. // can click in the empty area to create a new item or deselect an item.
  191. this.hammer = new Hammer(this.body.dom.centerContainer);
  192. // drag items when selected
  193. this.hammer.on('hammer.input', function (event) {
  194. if (event.isFirst) {
  195. this._onTouch(event);
  196. }
  197. }.bind(this));
  198. this.hammer.on('panstart', this._onDragStart.bind(this));
  199. this.hammer.on('panmove', this._onDrag.bind(this));
  200. this.hammer.on('panend', this._onDragEnd.bind(this));
  201. this.hammer.get('pan').set({threshold:5, direction: Hammer.DIRECTION_HORIZONTAL});
  202. // single select (or unselect) when tapping an item
  203. this.hammer.on('tap', this._onSelectItem.bind(this));
  204. // multi select when holding mouse/touch, or on ctrl+click
  205. this.hammer.on('press', this._onMultiSelectItem.bind(this));
  206. // add item on doubletap
  207. this.hammer.on('doubletap', this._onAddItem.bind(this));
  208. if (this.options.rtl) {
  209. this.groupHammer = new Hammer(this.body.dom.rightContainer);
  210. } else {
  211. this.groupHammer = new Hammer(this.body.dom.leftContainer);
  212. }
  213. this.groupHammer.on('tap', this._onGroupClick.bind(this));
  214. this.groupHammer.on('panstart', this._onGroupDragStart.bind(this));
  215. this.groupHammer.on('panmove', this._onGroupDrag.bind(this));
  216. this.groupHammer.on('panend', this._onGroupDragEnd.bind(this));
  217. this.groupHammer.get('pan').set({threshold:5, direction: Hammer.DIRECTION_VERTICAL});
  218. this.body.dom.centerContainer.addEventListener('mouseover', this._onMouseOver.bind(this));
  219. this.body.dom.centerContainer.addEventListener('mouseout', this._onMouseOut.bind(this));
  220. this.body.dom.centerContainer.addEventListener('mousemove', this._onMouseMove.bind(this));
  221. // right-click on timeline
  222. this.body.dom.centerContainer.addEventListener('contextmenu', this._onDragEnd.bind(this));
  223. this.body.dom.centerContainer.addEventListener('mousewheel', this._onMouseWheel.bind(this));
  224. // attach to the DOM
  225. this.show();
  226. };
  227. /**
  228. * Set options for the ItemSet. Existing options will be extended/overwritten.
  229. * @param {Object} [options] The following options are available:
  230. * {String} type
  231. * Default type for the items. Choose from 'box'
  232. * (default), 'point', 'range', or 'background'.
  233. * The default style can be overwritten by
  234. * individual items.
  235. * {String} align
  236. * Alignment for the items, only applicable for
  237. * BoxItem. Choose 'center' (default), 'left', or
  238. * 'right'.
  239. * {String} orientation.item
  240. * Orientation of the item set. Choose 'top' or
  241. * 'bottom' (default).
  242. * {Function} groupOrder
  243. * A sorting function for ordering groups
  244. * {Boolean} stack
  245. * If true (default), items will be stacked on
  246. * top of each other.
  247. * {Number} margin.axis
  248. * Margin between the axis and the items in pixels.
  249. * Default is 20.
  250. * {Number} margin.item.horizontal
  251. * Horizontal margin between items in pixels.
  252. * Default is 10.
  253. * {Number} margin.item.vertical
  254. * Vertical Margin between items in pixels.
  255. * Default is 10.
  256. * {Number} margin.item
  257. * Margin between items in pixels in both horizontal
  258. * and vertical direction. Default is 10.
  259. * {Number} margin
  260. * Set margin for both axis and items in pixels.
  261. * {Boolean} selectable
  262. * If true (default), items can be selected.
  263. * {Boolean} multiselect
  264. * If true, multiple items can be selected.
  265. * False by default.
  266. * {Boolean} editable
  267. * Set all editable options to true or false
  268. * {Boolean} editable.updateTime
  269. * Allow dragging an item to an other moment in time
  270. * {Boolean} editable.updateGroup
  271. * Allow dragging an item to an other group
  272. * {Boolean} editable.add
  273. * Allow creating new items on double tap
  274. * {Boolean} editable.remove
  275. * Allow removing items by clicking the delete button
  276. * top right of a selected item.
  277. * {Function(item: Item, callback: Function)} onAdd
  278. * Callback function triggered when an item is about to be added:
  279. * when the user double taps an empty space in the Timeline.
  280. * {Function(item: Item, callback: Function)} onUpdate
  281. * Callback function fired when an item is about to be updated.
  282. * This function typically has to show a dialog where the user
  283. * change the item. If not implemented, nothing happens.
  284. * {Function(item: Item, callback: Function)} onMove
  285. * Fired when an item has been moved. If not implemented,
  286. * the move action will be accepted.
  287. * {Function(item: Item, callback: Function)} onRemove
  288. * Fired when an item is about to be deleted.
  289. * If not implemented, the item will be always removed.
  290. */
  291. ItemSet.prototype.setOptions = function(options) {
  292. if (options) {
  293. // copy all options that we know
  294. var fields = [
  295. 'type', 'rtl', 'align', 'order', 'stack', 'stackSubgroups', 'selectable', 'multiselect', 'itemsAlwaysDraggable',
  296. 'multiselectPerGroup', 'groupOrder', 'dataAttributes', 'template', 'groupTemplate', 'visibleFrameTemplate',
  297. 'hide', 'snap', 'groupOrderSwap', 'tooltip', 'tooltipOnItemUpdateTime'
  298. ];
  299. util.selectiveExtend(fields, this.options, options);
  300. if ('orientation' in options) {
  301. if (typeof options.orientation === 'string') {
  302. this.options.orientation.item = options.orientation === 'top' ? 'top' : 'bottom';
  303. }
  304. else if (typeof options.orientation === 'object' && 'item' in options.orientation) {
  305. this.options.orientation.item = options.orientation.item;
  306. }
  307. }
  308. if ('margin' in options) {
  309. if (typeof options.margin === 'number') {
  310. this.options.margin.axis = options.margin;
  311. this.options.margin.item.horizontal = options.margin;
  312. this.options.margin.item.vertical = options.margin;
  313. }
  314. else if (typeof options.margin === 'object') {
  315. util.selectiveExtend(['axis'], this.options.margin, options.margin);
  316. if ('item' in options.margin) {
  317. if (typeof options.margin.item === 'number') {
  318. this.options.margin.item.horizontal = options.margin.item;
  319. this.options.margin.item.vertical = options.margin.item;
  320. }
  321. else if (typeof options.margin.item === 'object') {
  322. util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item);
  323. }
  324. }
  325. }
  326. }
  327. if ('editable' in options) {
  328. if (typeof options.editable === 'boolean') {
  329. this.options.editable.updateTime = options.editable;
  330. this.options.editable.updateGroup = options.editable;
  331. this.options.editable.add = options.editable;
  332. this.options.editable.remove = options.editable;
  333. this.options.editable.overrideItems = false;
  334. }
  335. else if (typeof options.editable === 'object') {
  336. util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove', 'overrideItems'], this.options.editable, options.editable);
  337. }
  338. }
  339. if ('groupEditable' in options) {
  340. if (typeof options.groupEditable === 'boolean') {
  341. this.options.groupEditable.order = options.groupEditable;
  342. this.options.groupEditable.add = options.groupEditable;
  343. this.options.groupEditable.remove = options.groupEditable;
  344. }
  345. else if (typeof options.groupEditable === 'object') {
  346. util.selectiveExtend(['order', 'add', 'remove'], this.options.groupEditable, options.groupEditable);
  347. }
  348. }
  349. // callback functions
  350. var addCallback = (function (name) {
  351. var fn = options[name];
  352. if (fn) {
  353. if (!(fn instanceof Function)) {
  354. throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)');
  355. }
  356. this.options[name] = fn;
  357. }
  358. }).bind(this);
  359. ['onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving', 'onAddGroup', 'onMoveGroup', 'onRemoveGroup'].forEach(addCallback);
  360. // force the itemSet to refresh: options like orientation and margins may be changed
  361. this.markDirty();
  362. }
  363. };
  364. /**
  365. * Mark the ItemSet dirty so it will refresh everything with next redraw.
  366. * Optionally, all items can be marked as dirty and be refreshed.
  367. * @param {{refreshItems: boolean}} [options]
  368. */
  369. ItemSet.prototype.markDirty = function(options) {
  370. this.groupIds = [];
  371. this.stackDirty = true;
  372. if (options && options.refreshItems) {
  373. util.forEach(this.items, function (item) {
  374. item.dirty = true;
  375. if (item.displayed) item.redraw();
  376. });
  377. }
  378. };
  379. /**
  380. * Destroy the ItemSet
  381. */
  382. ItemSet.prototype.destroy = function() {
  383. this.hide();
  384. this.setItems(null);
  385. this.setGroups(null);
  386. this.hammer = null;
  387. this.body = null;
  388. this.conversion = null;
  389. };
  390. /**
  391. * Hide the component from the DOM
  392. */
  393. ItemSet.prototype.hide = function() {
  394. // remove the frame containing the items
  395. if (this.dom.frame.parentNode) {
  396. this.dom.frame.parentNode.removeChild(this.dom.frame);
  397. }
  398. // remove the axis with dots
  399. if (this.dom.axis.parentNode) {
  400. this.dom.axis.parentNode.removeChild(this.dom.axis);
  401. }
  402. // remove the labelset containing all group labels
  403. if (this.dom.labelSet.parentNode) {
  404. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  405. }
  406. };
  407. /**
  408. * Show the component in the DOM (when not already visible).
  409. * @return {Boolean} changed
  410. */
  411. ItemSet.prototype.show = function() {
  412. // show frame containing the items
  413. if (!this.dom.frame.parentNode) {
  414. this.body.dom.center.appendChild(this.dom.frame);
  415. }
  416. // show axis with dots
  417. if (!this.dom.axis.parentNode) {
  418. this.body.dom.backgroundVertical.appendChild(this.dom.axis);
  419. }
  420. // show labelset containing labels
  421. if (!this.dom.labelSet.parentNode) {
  422. if (this.options.rtl) {
  423. this.body.dom.right.appendChild(this.dom.labelSet);
  424. } else {
  425. this.body.dom.left.appendChild(this.dom.labelSet);
  426. }
  427. }
  428. };
  429. /**
  430. * Set selected items by their id. Replaces the current selection
  431. * Unknown id's are silently ignored.
  432. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  433. * selected, or a single item id. If ids is undefined
  434. * or an empty array, all items will be unselected.
  435. */
  436. ItemSet.prototype.setSelection = function(ids) {
  437. var i, ii, id, item;
  438. if (ids == undefined) ids = [];
  439. if (!Array.isArray(ids)) ids = [ids];
  440. // unselect currently selected items
  441. for (i = 0, ii = this.selection.length; i < ii; i++) {
  442. id = this.selection[i];
  443. item = this.items[id];
  444. if (item) item.unselect();
  445. }
  446. // select items
  447. this.selection = [];
  448. for (i = 0, ii = ids.length; i < ii; i++) {
  449. id = ids[i];
  450. item = this.items[id];
  451. if (item) {
  452. this.selection.push(id);
  453. item.select();
  454. }
  455. }
  456. };
  457. /**
  458. * Get the selected items by their id
  459. * @return {Array} ids The ids of the selected items
  460. */
  461. ItemSet.prototype.getSelection = function() {
  462. return this.selection.concat([]);
  463. };
  464. /**
  465. * Get the id's of the currently visible items.
  466. * @returns {Array} The ids of the visible items
  467. */
  468. ItemSet.prototype.getVisibleItems = function() {
  469. var range = this.body.range.getRange();
  470. if (this.options.rtl) {
  471. var right = this.body.util.toScreen(range.start);
  472. var left = this.body.util.toScreen(range.end);
  473. } else {
  474. var left = this.body.util.toScreen(range.start);
  475. var right = this.body.util.toScreen(range.end);
  476. }
  477. var ids = [];
  478. for (var groupId in this.groups) {
  479. if (this.groups.hasOwnProperty(groupId)) {
  480. var group = this.groups[groupId];
  481. var rawVisibleItems = group.visibleItems;
  482. // filter the "raw" set with visibleItems into a set which is really
  483. // visible by pixels
  484. for (var i = 0; i < rawVisibleItems.length; i++) {
  485. var item = rawVisibleItems[i];
  486. // TODO: also check whether visible vertically
  487. if (this.options.rtl) {
  488. if ((item.right < left) && (item.right + item.width > right)) {
  489. ids.push(item.id);
  490. }
  491. } else {
  492. if ((item.left < right) && (item.left + item.width > left)) {
  493. ids.push(item.id);
  494. }
  495. }
  496. }
  497. }
  498. }
  499. return ids;
  500. };
  501. /**
  502. * Deselect a selected item
  503. * @param {String | Number} id
  504. * @private
  505. */
  506. ItemSet.prototype._deselect = function(id) {
  507. var selection = this.selection;
  508. for (var i = 0, ii = selection.length; i < ii; i++) {
  509. if (selection[i] == id) { // non-strict comparison!
  510. selection.splice(i, 1);
  511. break;
  512. }
  513. }
  514. };
  515. /**
  516. * Repaint the component
  517. * @return {boolean} Returns true if the component is resized
  518. */
  519. ItemSet.prototype.redraw = function() {
  520. var margin = this.options.margin,
  521. range = this.body.range,
  522. asSize = util.option.asSize,
  523. options = this.options,
  524. orientation = options.orientation.item,
  525. resized = false,
  526. frame = this.dom.frame;
  527. // recalculate absolute position (before redrawing groups)
  528. this.props.top = this.body.domProps.top.height + this.body.domProps.border.top;
  529. if (this.options.rtl) {
  530. this.props.right = this.body.domProps.right.width + this.body.domProps.border.right;
  531. } else {
  532. this.props.left = this.body.domProps.left.width + this.body.domProps.border.left;
  533. }
  534. // update class name
  535. frame.className = 'vis-itemset';
  536. // reorder the groups (if needed)
  537. resized = this._orderGroups() || resized;
  538. // check whether zoomed (in that case we need to re-stack everything)
  539. // TODO: would be nicer to get this as a trigger from Range
  540. var visibleInterval = range.end - range.start;
  541. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.props.width != this.props.lastWidth);
  542. 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. // update the items data (will redraw the item when displayed)
  1044. item.setData(itemData);
  1045. var groupId = this._getGroupId(item.data);
  1046. var group = this.groups[groupId];
  1047. if (!group) {
  1048. item.groupShowing = false;
  1049. } else if (group && group.data && group.data.showNested) {
  1050. item.groupShowing = true;
  1051. }
  1052. // update group
  1053. if (oldGroupId != item.data.group || oldSubGroupId != item.data.subgroup) {
  1054. var oldGroup = this.groups[oldGroupId];
  1055. if (oldGroup) oldGroup.remove(item);
  1056. if (group) group.add(item);
  1057. }
  1058. };
  1059. /**
  1060. * Delete an item from the ItemSet: remove it from the DOM, from the map
  1061. * with items, and from the map with visible items, and from the selection
  1062. * @param {Item} item
  1063. * @private
  1064. */
  1065. ItemSet.prototype._removeItem = function(item) {
  1066. // remove from DOM
  1067. item.hide();
  1068. // remove from items
  1069. delete this.items[item.id];
  1070. // remove from selection
  1071. var index = this.selection.indexOf(item.id);
  1072. if (index != -1) this.selection.splice(index, 1);
  1073. // remove from group
  1074. item.parent && item.parent.remove(item);
  1075. };
  1076. /**
  1077. * Create an array containing all items being a range (having an end date)
  1078. * @param array
  1079. * @returns {Array}
  1080. * @private
  1081. */
  1082. ItemSet.prototype._constructByEndArray = function(array) {
  1083. var endArray = [];
  1084. for (var i = 0; i < array.length; i++) {
  1085. if (array[i] instanceof RangeItem) {
  1086. endArray.push(array[i]);
  1087. }
  1088. }
  1089. return endArray;
  1090. };
  1091. /**
  1092. * Register the clicked item on touch, before dragStart is initiated.
  1093. *
  1094. * dragStart is initiated from a mousemove event, AFTER the mouse/touch is
  1095. * already moving. Therefore, the mouse/touch can sometimes be above an other
  1096. * DOM element than the item itself.
  1097. *
  1098. * @param {Event} event
  1099. * @private
  1100. */
  1101. ItemSet.prototype._onTouch = function (event) {
  1102. // store the touched item, used in _onDragStart
  1103. this.touchParams.item = this.itemFromTarget(event);
  1104. this.touchParams.dragLeftItem = event.target.dragLeftItem || false;
  1105. this.touchParams.dragRightItem = event.target.dragRightItem || false;
  1106. this.touchParams.itemProps = null;
  1107. };
  1108. /**
  1109. * Given an group id, returns the index it has.
  1110. *
  1111. * @param {Number} groupID
  1112. * @private
  1113. */
  1114. ItemSet.prototype._getGroupIndex = function(groupId) {
  1115. for (var i = 0; i < this.groupIds.length; i++) {
  1116. if (groupId == this.groupIds[i])
  1117. return i;
  1118. }
  1119. };
  1120. /**
  1121. * Start dragging the selected events
  1122. * @param {Event} event
  1123. * @private
  1124. */
  1125. ItemSet.prototype._onDragStart = function (event) {
  1126. if (this.touchParams.itemIsDragging) { return; }
  1127. var item = this.touchParams.item || null;
  1128. var me = this;
  1129. var props;
  1130. if (item && (item.selected || this.options.itemsAlwaysDraggable)) {
  1131. if (this.options.editable.overrideItems &&
  1132. !this.options.editable.updateTime &&
  1133. !this.options.editable.updateGroup) {
  1134. return;
  1135. }
  1136. // override options.editable
  1137. if ((item.editable != null && !item.editable.updateTime && !item.editable.updateGroup)
  1138. && !this.options.editable.overrideItems) {
  1139. return;
  1140. }
  1141. var dragLeftItem = this.touchParams.dragLeftItem;
  1142. var dragRightItem = this.touchParams.dragRightItem;
  1143. this.touchParams.itemIsDragging = true;
  1144. this.touchParams.selectedItem = item;
  1145. if (dragLeftItem) {
  1146. props = {
  1147. item: dragLeftItem,
  1148. initialX: event.center.x,
  1149. dragLeft: true,
  1150. data: this._cloneItemData(item.data)
  1151. };
  1152. this.touchParams.itemProps = [props];
  1153. }
  1154. else if (dragRightItem) {
  1155. props = {
  1156. item: dragRightItem,
  1157. initialX: event.center.x,
  1158. dragRight: true,
  1159. data: this._cloneItemData(item.data)
  1160. };
  1161. this.touchParams.itemProps = [props];
  1162. }
  1163. else {
  1164. var baseGroupIndex = this._getGroupIndex(item.data.group);
  1165. var itemsToDrag = (this.options.itemsAlwaysDraggable && !item.selected) ? [item.id] : this.getSelection();
  1166. this.touchParams.itemProps = itemsToDrag.map(function (id) {
  1167. var item = me.items[id];
  1168. var groupIndex = me._getGroupIndex(item.data.group);
  1169. return {
  1170. item: item,
  1171. initialX: event.center.x,
  1172. groupOffset: baseGroupIndex-groupIndex,
  1173. data: this._cloneItemData(item.data)
  1174. };
  1175. }.bind(this));
  1176. }
  1177. event.stopPropagation();
  1178. }
  1179. else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  1180. // create a new range item when dragging with ctrl key down
  1181. this._onDragStartAddItem(event);
  1182. }
  1183. };
  1184. /**
  1185. * Start creating a new range item by dragging.
  1186. * @param {Event} event
  1187. * @private
  1188. */
  1189. ItemSet.prototype._onDragStartAddItem = function (event) {
  1190. var snap = this.options.snap || null;
  1191. if (this.options.rtl) {
  1192. var xAbs = util.getAbsoluteRight(this.dom.frame);
  1193. var x = xAbs - event.center.x + 10; // plus 10 to compensate for the drag starting as soon as you've moved 10px
  1194. } else {
  1195. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1196. var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  1197. }
  1198. var time = this.body.util.toTime(x);
  1199. var scale = this.body.util.getScale();
  1200. var step = this.body.util.getStep();
  1201. var start = snap ? snap(time, scale, step) : time;
  1202. var end = start;
  1203. var itemData = {
  1204. type: 'range',
  1205. start: start,
  1206. end: end,
  1207. content: 'new item'
  1208. };
  1209. var id = util.randomUUID();
  1210. itemData[this.itemsData._fieldId] = id;
  1211. var group = this.groupFromTarget(event);
  1212. if (group) {
  1213. itemData.group = group.groupId;
  1214. }
  1215. var newItem = new RangeItem(itemData, this.conversion, this.options);
  1216. newItem.id = id; // TODO: not so nice setting id afterwards
  1217. newItem.data = this._cloneItemData(itemData);
  1218. this._addItem(newItem);
  1219. this.touchParams.selectedItem = newItem;
  1220. var props = {
  1221. item: newItem,
  1222. initialX: event.center.x,
  1223. data: newItem.data
  1224. };
  1225. if (this.options.rtl) {
  1226. props.dragLeft = true;
  1227. } else {
  1228. props.dragRight = true;
  1229. }
  1230. this.touchParams.itemProps = [props];
  1231. event.stopPropagation();
  1232. };
  1233. /**
  1234. * Drag selected items
  1235. * @param {Event} event
  1236. * @private
  1237. */
  1238. ItemSet.prototype._onDrag = function (event) {
  1239. if (this.touchParams.itemProps) {
  1240. event.stopPropagation();
  1241. var me = this;
  1242. var snap = this.options.snap || null;
  1243. if (this.options.rtl) {
  1244. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.right.width;
  1245. } else {
  1246. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  1247. }
  1248. var scale = this.body.util.getScale();
  1249. var step = this.body.util.getStep();
  1250. //only calculate the new group for the item that's actually dragged
  1251. var selectedItem = this.touchParams.selectedItem;
  1252. var updateGroupAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateGroup) ||
  1253. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateGroup);
  1254. var newGroupBase = null;
  1255. if (updateGroupAllowed && selectedItem) {
  1256. if (selectedItem.data.group != undefined) {
  1257. // drag from one group to another
  1258. var group = me.groupFromTarget(event);
  1259. if (group) {
  1260. //we know the offset for all items, so the new group for all items
  1261. //will be relative to this one.
  1262. newGroupBase = this._getGroupIndex(group.groupId);
  1263. }
  1264. }
  1265. }
  1266. // move
  1267. this.touchParams.itemProps.forEach(function (props) {
  1268. var current = me.body.util.toTime(event.center.x - xOffset);
  1269. var initial = me.body.util.toTime(props.initialX - xOffset);
  1270. if (this.options.rtl) {
  1271. var offset = -(current - initial); // ms
  1272. } else {
  1273. var offset = (current - initial); // ms
  1274. }
  1275. var itemData = this._cloneItemData(props.item.data); // clone the data
  1276. if (props.item.editable != null
  1277. && !props.item.editable.updateTime
  1278. && !props.item.editable.updateGroup
  1279. && !me.options.editable.overrideItems) {
  1280. return;
  1281. }
  1282. var updateTimeAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateTime) ||
  1283. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateTime);
  1284. if (updateTimeAllowed) {
  1285. if (props.dragLeft) {
  1286. // drag left side of a range item
  1287. if (this.options.rtl) {
  1288. if (itemData.end != undefined) {
  1289. var initialEnd = util.convert(props.data.end, 'Date');
  1290. var end = new Date(initialEnd.valueOf() + offset);
  1291. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1292. itemData.end = snap ? snap(end, scale, step) : end;
  1293. }
  1294. } else {
  1295. if (itemData.start != undefined) {
  1296. var initialStart = util.convert(props.data.start, 'Date');
  1297. var start = new Date(initialStart.valueOf() + offset);
  1298. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1299. itemData.start = snap ? snap(start, scale, step) : start;
  1300. }
  1301. }
  1302. }
  1303. else if (props.dragRight) {
  1304. // drag right side of a range item
  1305. if (this.options.rtl) {
  1306. if (itemData.start != undefined) {
  1307. var initialStart = util.convert(props.data.start, 'Date');
  1308. var start = new Date(initialStart.valueOf() + offset);
  1309. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1310. itemData.start = snap ? snap(start, scale, step) : start;
  1311. }
  1312. } else {
  1313. if (itemData.end != undefined) {
  1314. var initialEnd = util.convert(props.data.end, 'Date');
  1315. var end = new Date(initialEnd.valueOf() + offset);
  1316. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1317. itemData.end = snap ? snap(end, scale, step) : end;
  1318. }
  1319. }
  1320. }
  1321. else {
  1322. // drag both start and end
  1323. if (itemData.start != undefined) {
  1324. var initialStart = util.convert(props.data.start, 'Date').valueOf();
  1325. var start = new Date(initialStart + offset);
  1326. if (itemData.end != undefined) {
  1327. var initialEnd = util.convert(props.data.end, 'Date');
  1328. var duration = initialEnd.valueOf() - initialStart.valueOf();
  1329. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1330. itemData.start = snap ? snap(start, scale, step) : start;
  1331. itemData.end = new Date(itemData.start.valueOf() + duration);
  1332. }
  1333. else {
  1334. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1335. itemData.start = snap ? snap(start, scale, step) : start;
  1336. }
  1337. }
  1338. }
  1339. }
  1340. if (updateGroupAllowed && (!props.dragLeft && !props.dragRight) && newGroupBase!=null) {
  1341. if (itemData.group != undefined) {
  1342. var newOffset = newGroupBase - props.groupOffset;
  1343. //make sure we stay in bounds
  1344. newOffset = Math.max(0, newOffset);
  1345. newOffset = Math.min(me.groupIds.length-1, newOffset);
  1346. itemData.group = me.groupIds[newOffset];
  1347. }
  1348. }
  1349. // confirm moving the item
  1350. itemData = this._cloneItemData(itemData); // convert start and end to the correct type
  1351. me.options.onMoving(itemData, function (itemData) {
  1352. if (itemData) {
  1353. props.item.setData(this._cloneItemData(itemData, 'Date'));
  1354. }
  1355. }.bind(this));
  1356. }.bind(this));
  1357. this.stackDirty = true; // force re-stacking of all items next redraw
  1358. this.body.emitter.emit('_change');
  1359. }
  1360. };
  1361. /**
  1362. * Move an item to another group
  1363. * @param {Item} item
  1364. * @param {String | Number} groupId
  1365. * @private
  1366. */
  1367. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1368. var group = this.groups[groupId];
  1369. if (group && group.groupId != item.data.group) {
  1370. var oldGroup = item.parent;
  1371. oldGroup.remove(item);
  1372. oldGroup.order();
  1373. group.add(item);
  1374. group.order();
  1375. item.data.group = group.groupId;
  1376. }
  1377. };
  1378. /**
  1379. * End of dragging selected items
  1380. * @param {Event} event
  1381. * @private
  1382. */
  1383. ItemSet.prototype._onDragEnd = function (event) {
  1384. this.touchParams.itemIsDragging = false;
  1385. if (this.touchParams.itemProps) {
  1386. event.stopPropagation();
  1387. var me = this;
  1388. var dataset = this.itemsData.getDataSet();
  1389. var itemProps = this.touchParams.itemProps ;
  1390. this.touchParams.itemProps = null;
  1391. itemProps.forEach(function (props) {
  1392. var id = props.item.id;
  1393. var exists = me.itemsData.get(id, me.itemOptions) != null;
  1394. if (!exists) {
  1395. // add a new item
  1396. me.options.onAdd(props.item.data, function (itemData) {
  1397. me._removeItem(props.item); // remove temporary item
  1398. if (itemData) {
  1399. me.itemsData.getDataSet().add(itemData);
  1400. }
  1401. // force re-stacking of all items next redraw
  1402. me.stackDirty = true;
  1403. me.body.emitter.emit('_change');
  1404. });
  1405. }
  1406. else {
  1407. // update existing item
  1408. var itemData = this._cloneItemData(props.item.data); // convert start and end to the correct type
  1409. me.options.onMove(itemData, function (itemData) {
  1410. if (itemData) {
  1411. // apply changes
  1412. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1413. dataset.update(itemData);
  1414. }
  1415. else {
  1416. // restore original values
  1417. props.item.setData(props.data);
  1418. me.stackDirty = true; // force re-stacking of all items next redraw
  1419. me.body.emitter.emit('_change');
  1420. }
  1421. });
  1422. }
  1423. }.bind(this));
  1424. }
  1425. };
  1426. ItemSet.prototype._onGroupClick = function (event) {
  1427. var group = this.groupFromTarget(event);
  1428. if (!group.nestedGroups) return;
  1429. var groupsData = this.groupsData;
  1430. if (this.groupsData instanceof DataView) {
  1431. groupsData = this.groupsData.getDataSet()
  1432. }
  1433. group.showNested = !group.showNested;
  1434. var nestedGroups = groupsData.get(group.nestedGroups).map(function(nestedGroup) {
  1435. if (nestedGroup.visible == undefined) { nestedGroup.visible = true; }
  1436. nestedGroup.visible = !!group.showNested;
  1437. return nestedGroup;
  1438. });
  1439. groupsData.update(nestedGroups);
  1440. if (group.showNested) {
  1441. util.removeClassName(group.dom.label, 'collapsed');
  1442. util.addClassName(group.dom.label, 'expanded');
  1443. } else {
  1444. util.removeClassName(group.dom.label, 'expanded');
  1445. var collapsedDirClassName = this.options.rtl ? 'collapsed-rtl' : 'collapsed'
  1446. util.addClassName(group.dom.label, collapsedDirClassName);
  1447. }
  1448. }
  1449. ItemSet.prototype._onGroupDragStart = function (event) {
  1450. if (this.options.groupEditable.order) {
  1451. this.groupTouchParams.group = this.groupFromTarget(event);
  1452. if (this.groupTouchParams.group) {
  1453. event.stopPropagation();
  1454. this.groupTouchParams.originalOrder = this.groupsData.getIds({
  1455. order: this.options.groupOrder
  1456. });
  1457. }
  1458. }
  1459. }
  1460. ItemSet.prototype._onGroupDrag = function (event) {
  1461. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1462. event.stopPropagation();
  1463. var groupsData = this.groupsData;
  1464. if (this.groupsData instanceof DataView) {
  1465. groupsData = this.groupsData.getDataSet()
  1466. }
  1467. // drag from one group to another
  1468. var group = this.groupFromTarget(event);
  1469. // try to avoid toggling when groups differ in height
  1470. if (group && group.height != this.groupTouchParams.group.height) {
  1471. var movingUp = (group.top < this.groupTouchParams.group.top);
  1472. var clientY = event.center ? event.center.y : event.clientY;
  1473. var targetGroupTop = util.getAbsoluteTop(group.dom.foreground);
  1474. var draggedGroupHeight = this.groupTouchParams.group.height;
  1475. if (movingUp) {
  1476. // skip swapping the groups when the dragged group is not below clientY afterwards
  1477. if (targetGroupTop + draggedGroupHeight < clientY) {
  1478. return;
  1479. }
  1480. } else {
  1481. var targetGroupHeight = group.height;
  1482. // skip swapping the groups when the dragged group is not below clientY afterwards
  1483. if (targetGroupTop + targetGroupHeight - draggedGroupHeight > clientY) {
  1484. return;
  1485. }
  1486. }
  1487. }
  1488. if (group && group != this.groupTouchParams.group) {
  1489. var targetGroup = groupsData.get(group.groupId);
  1490. var draggedGroup = groupsData.get(this.groupTouchParams.group.groupId);
  1491. // switch groups
  1492. if (draggedGroup && targetGroup) {
  1493. this.options.groupOrderSwap(draggedGroup, targetGroup, groupsData);
  1494. groupsData.update(draggedGroup);
  1495. groupsData.update(targetGroup);
  1496. }
  1497. // fetch current order of groups
  1498. var newOrder = groupsData.getIds({
  1499. order: this.options.groupOrder
  1500. });
  1501. // in case of changes since _onGroupDragStart
  1502. if (!util.equalArray(newOrder, this.groupTouchParams.originalOrder)) {
  1503. var origOrder = this.groupTouchParams.originalOrder;
  1504. var draggedId = this.groupTouchParams.group.groupId;
  1505. var numGroups = Math.min(origOrder.length, newOrder.length);
  1506. var curPos = 0;
  1507. var newOffset = 0;
  1508. var orgOffset = 0;
  1509. while (curPos < numGroups) {
  1510. // as long as the groups are where they should be step down along the groups order
  1511. while ((curPos+newOffset) < numGroups
  1512. && (curPos+orgOffset) < numGroups
  1513. && newOrder[curPos+newOffset] == origOrder[curPos+orgOffset]) {
  1514. curPos++;
  1515. }
  1516. // all ok
  1517. if (curPos+newOffset >= numGroups) {
  1518. break;
  1519. }
  1520. // not all ok
  1521. // if dragged group was move upwards everything below should have an offset
  1522. if (newOrder[curPos+newOffset] == draggedId) {
  1523. newOffset = 1;
  1524. continue;
  1525. }
  1526. // if dragged group was move downwards everything above should have an offset
  1527. else if (origOrder[curPos+orgOffset] == draggedId) {
  1528. orgOffset = 1;
  1529. continue;
  1530. }
  1531. // found a group (apart from dragged group) that has the wrong position -> switch with the
  1532. // group at the position where other one should be, fix index arrays and continue
  1533. else {
  1534. var slippedPosition = newOrder.indexOf(origOrder[curPos+orgOffset])
  1535. var switchGroup = groupsData.get(newOrder[curPos+newOffset]);
  1536. var shouldBeGroup = groupsData.get(origOrder[curPos+orgOffset]);
  1537. this.options.groupOrderSwap(switchGroup, shouldBeGroup, groupsData);
  1538. groupsData.update(switchGroup);
  1539. groupsData.update(shouldBeGroup);
  1540. var switchGroupId = newOrder[curPos+newOffset];
  1541. newOrder[curPos+newOffset] = origOrder[curPos+orgOffset];
  1542. newOrder[slippedPosition] = switchGroupId;
  1543. curPos++;
  1544. }
  1545. }
  1546. }
  1547. }
  1548. }
  1549. }
  1550. ItemSet.prototype._onGroupDragEnd = function (event) {
  1551. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1552. event.stopPropagation();
  1553. // update existing group
  1554. var me = this;
  1555. var id = me.groupTouchParams.group.groupId;
  1556. var dataset = me.groupsData.getDataSet();
  1557. var groupData = util.extend({}, dataset.get(id)); // clone the data
  1558. me.options.onMoveGroup(groupData, function (groupData) {
  1559. if (groupData) {
  1560. // apply changes
  1561. groupData[dataset._fieldId] = id; // ensure the group contains its id (can be undefined)
  1562. dataset.update(groupData);
  1563. }
  1564. else {
  1565. // fetch current order of groups
  1566. var newOrder = dataset.getIds({
  1567. order: me.options.groupOrder
  1568. });
  1569. // restore original order
  1570. if (!util.equalArray(newOrder, me.groupTouchParams.originalOrder)) {
  1571. var origOrder = me.groupTouchParams.originalOrder;
  1572. var numGroups = Math.min(origOrder.length, newOrder.length);
  1573. var curPos = 0;
  1574. while (curPos < numGroups) {
  1575. // as long as the groups are where they should be step down along the groups order
  1576. while (curPos < numGroups && newOrder[curPos] == origOrder[curPos]) {
  1577. curPos++;
  1578. }
  1579. // all ok
  1580. if (curPos >= numGroups) {
  1581. break;
  1582. }
  1583. // found a group that has the wrong position -> switch with the
  1584. // group at the position where other one should be, fix index arrays and continue
  1585. var slippedPosition = newOrder.indexOf(origOrder[curPos])
  1586. var switchGroup = dataset.get(newOrder[curPos]);
  1587. var shouldBeGroup = dataset.get(origOrder[curPos]);
  1588. me.options.groupOrderSwap(switchGroup, shouldBeGroup, dataset);
  1589. dataset.update(switchGroup);
  1590. dataset.update(shouldBeGroup);
  1591. var switchGroupId = newOrder[curPos];
  1592. newOrder[curPos] = origOrder[curPos];
  1593. newOrder[slippedPosition] = switchGroupId;
  1594. curPos++;
  1595. }
  1596. }
  1597. }
  1598. });
  1599. me.body.emitter.emit('groupDragged', { groupId: id });
  1600. }
  1601. }
  1602. /**
  1603. * Handle selecting/deselecting an item when tapping it
  1604. * @param {Event} event
  1605. * @private
  1606. */
  1607. ItemSet.prototype._onSelectItem = function (event) {
  1608. if (!this.options.selectable) return;
  1609. var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey);
  1610. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  1611. if (ctrlKey || shiftKey) {
  1612. this._onMultiSelectItem(event);
  1613. return;
  1614. }
  1615. var oldSelection = this.getSelection();
  1616. var item = this.itemFromTarget(event);
  1617. var selection = item ? [item.id] : [];
  1618. this.setSelection(selection);
  1619. var newSelection = this.getSelection();
  1620. // emit a select event,
  1621. // except when old selection is empty and new selection is still empty
  1622. if (newSelection.length > 0 || oldSelection.length > 0) {
  1623. this.body.emitter.emit('select', {
  1624. items: newSelection,
  1625. event: event
  1626. });
  1627. }
  1628. };
  1629. /**
  1630. * Handle hovering an item
  1631. * @param {Event} event
  1632. * @private
  1633. */
  1634. ItemSet.prototype._onMouseOver = function (event) {
  1635. var item = this.itemFromTarget(event);
  1636. if (!item) return;
  1637. // Item we just left
  1638. var related = this.itemFromRelatedTarget(event);
  1639. if (item === related) {
  1640. // We haven't changed item, just element in the item
  1641. return;
  1642. }
  1643. var title = item.getTitle();
  1644. if (title) {
  1645. if (this.popup == null) {
  1646. this.popup = new Popup(this.body.dom.root,
  1647. this.options.tooltip.overflowMethod || 'flip');
  1648. }
  1649. this.popup.setText(title);
  1650. var container = this.body.dom.centerContainer;
  1651. this.popup.setPosition(
  1652. event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft,
  1653. event.clientY - util.getAbsoluteTop(container) + container.offsetTop
  1654. );
  1655. this.popup.show();
  1656. } else {
  1657. // Hovering over item without a title, hide popup
  1658. // Needed instead of _just_ in _onMouseOut due to #2572
  1659. if (this.popup != null) {
  1660. this.popup.hide();
  1661. }
  1662. }
  1663. this.body.emitter.emit('itemover', {
  1664. item: item.id,
  1665. event: event
  1666. });
  1667. };
  1668. ItemSet.prototype._onMouseOut = function (event) {
  1669. var item = this.itemFromTarget(event);
  1670. if (!item) return;
  1671. // Item we are going to
  1672. var related = this.itemFromRelatedTarget(event);
  1673. if (item === related) {
  1674. // We aren't changing item, just element in the item
  1675. return;
  1676. }
  1677. if (this.popup != null) {
  1678. this.popup.hide();
  1679. }
  1680. this.body.emitter.emit('itemout', {
  1681. item: item.id,
  1682. event: event
  1683. });
  1684. };
  1685. ItemSet.prototype._onMouseMove = function (event) {
  1686. var item = this.itemFromTarget(event);
  1687. if (!item) return;
  1688. if (this.options.tooltip.followMouse) {
  1689. if (this.popup) {
  1690. if (!this.popup.hidden) {
  1691. var container = this.body.dom.centerContainer;
  1692. this.popup.setPosition(
  1693. event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft,
  1694. event.clientY - util.getAbsoluteTop(container) + container.offsetTop
  1695. );
  1696. this.popup.show(); // Redraw
  1697. }
  1698. }
  1699. }
  1700. };
  1701. /**
  1702. * Handle mousewheel
  1703. * @param event
  1704. * @private
  1705. */
  1706. ItemSet.prototype._onMouseWheel = function(event) {
  1707. if (this.touchParams.itemIsDragging) {
  1708. this._onDragEnd(event);
  1709. }
  1710. }
  1711. /**
  1712. * Handle updates of an item on double tap
  1713. * @param event
  1714. * @private
  1715. */
  1716. ItemSet.prototype._onUpdateItem = function (item) {
  1717. if (!this.options.selectable) return;
  1718. if (!this.options.editable.add) return;
  1719. var me = this;
  1720. if (item) {
  1721. // execute async handler to update the item (or cancel it)
  1722. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  1723. this.options.onUpdate(itemData, function (itemData) {
  1724. if (itemData) {
  1725. me.itemsData.getDataSet().update(itemData);
  1726. }
  1727. });
  1728. }
  1729. }
  1730. /**
  1731. * Handle creation of an item on double tap
  1732. * @param event
  1733. * @private
  1734. */
  1735. ItemSet.prototype._onAddItem = function (event) {
  1736. if (!this.options.selectable) return;
  1737. if (!this.options.editable.add) return;
  1738. var me = this;
  1739. var snap = this.options.snap || null;
  1740. var item = this.itemFromTarget(event);
  1741. if (!item) {
  1742. // add item
  1743. if (this.options.rtl) {
  1744. var xAbs = util.getAbsoluteRight(this.dom.frame);
  1745. var x = xAbs - event.center.x;
  1746. } else {
  1747. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1748. var x = event.center.x - xAbs;
  1749. }
  1750. // var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1751. // var x = event.center.x - xAbs;
  1752. var start = this.body.util.toTime(x);
  1753. var scale = this.body.util.getScale();
  1754. var step = this.body.util.getStep();
  1755. var newItemData = {
  1756. start: snap ? snap(start, scale, step) : start,
  1757. content: 'new item'
  1758. };
  1759. if (event.type == 'drop') {
  1760. var itemData = JSON.parse(event.dataTransfer.getData("text"))
  1761. newItemData.content = itemData.content; // content is required
  1762. newItemData.type = itemData.type || 'box';
  1763. newItemData[this.itemsData._fieldId] = itemData.id || util.randomUUID();
  1764. if (itemData.type == 'range' || (itemData.end && itemData.start)) {
  1765. if (!itemData.end) {
  1766. var end = this.body.util.toTime(x + this.props.width / 5);
  1767. newItemData.end = snap ? snap(end, scale, step) : end;
  1768. } else {
  1769. newItemData.end = itemData.end;
  1770. newItemData.start = itemData.start;
  1771. }
  1772. }
  1773. } else {
  1774. newItemData[this.itemsData._fieldId] = util.randomUUID();
  1775. // when default type is a range, add a default end date to the new item
  1776. if (this.options.type === 'range') {
  1777. var end = this.body.util.toTime(x + this.props.width / 5);
  1778. newItemData.end = snap ? snap(end, scale, step) : end;
  1779. }
  1780. }
  1781. var group = this.groupFromTarget(event);
  1782. if (group) {
  1783. newItemData.group = group.groupId;
  1784. }
  1785. // execute async handler to customize (or cancel) adding an item
  1786. newItemData = this._cloneItemData(newItemData); // convert start and end to the correct type
  1787. this.options.onAdd(newItemData, function (item) {
  1788. if (item) {
  1789. me.itemsData.getDataSet().add(item);
  1790. if (event.type == 'drop') {
  1791. me.setSelection([item.id]);
  1792. }
  1793. // TODO: need to trigger a redraw?
  1794. }
  1795. });
  1796. }
  1797. };
  1798. /**
  1799. * Handle selecting/deselecting multiple items when holding an item
  1800. * @param {Event} event
  1801. * @private
  1802. */
  1803. ItemSet.prototype._onMultiSelectItem = function (event) {
  1804. if (!this.options.selectable) return;
  1805. var item = this.itemFromTarget(event);
  1806. if (item) {
  1807. // multi select items (if allowed)
  1808. var selection = this.options.multiselect
  1809. ? this.getSelection() // take current selection
  1810. : []; // deselect current selection
  1811. var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false;
  1812. if (shiftKey && this.options.multiselect) {
  1813. // select all items between the old selection and the tapped item
  1814. var itemGroup = this.itemsData.get(item.id).group;
  1815. // when filtering get the group of the last selected item
  1816. var lastSelectedGroup = undefined;
  1817. if (this.options.multiselectPerGroup) {
  1818. if (selection.length > 0) {
  1819. lastSelectedGroup = this.itemsData.get(selection[0]).group;
  1820. }
  1821. }
  1822. // determine the selection range
  1823. if (!this.options.multiselectPerGroup || lastSelectedGroup == undefined || lastSelectedGroup == itemGroup) {
  1824. selection.push(item.id);
  1825. }
  1826. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  1827. if (!this.options.multiselectPerGroup || lastSelectedGroup == itemGroup) {
  1828. // select all items within the selection range
  1829. selection = [];
  1830. for (var id in this.items) {
  1831. if (this.items.hasOwnProperty(id)) {
  1832. var _item = this.items[id];
  1833. var start = _item.data.start;
  1834. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  1835. if (start >= range.min &&
  1836. end <= range.max &&
  1837. (!this.options.multiselectPerGroup || lastSelectedGroup == this.itemsData.get(_item.id).group) &&
  1838. !(_item instanceof BackgroundItem)) {
  1839. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  1840. }
  1841. }
  1842. }
  1843. }
  1844. }
  1845. else {
  1846. // add/remove this item from the current selection
  1847. var index = selection.indexOf(item.id);
  1848. if (index == -1) {
  1849. // item is not yet selected -> select it
  1850. selection.push(item.id);
  1851. }
  1852. else {
  1853. // item is already selected -> deselect it
  1854. selection.splice(index, 1);
  1855. }
  1856. }
  1857. this.setSelection(selection);
  1858. this.body.emitter.emit('select', {
  1859. items: this.getSelection(),
  1860. event: event
  1861. });
  1862. }
  1863. };
  1864. /**
  1865. * Calculate the time range of a list of items
  1866. * @param {Array.<Object>} itemsData
  1867. * @return {{min: Date, max: Date}} Returns the range of the provided items
  1868. * @private
  1869. */
  1870. ItemSet._getItemRange = function(itemsData) {
  1871. var max = null;
  1872. var min = null;
  1873. itemsData.forEach(function (data) {
  1874. if (min == null || data.start < min) {
  1875. min = data.start;
  1876. }
  1877. if (data.end != undefined) {
  1878. if (max == null || data.end > max) {
  1879. max = data.end;
  1880. }
  1881. }
  1882. else {
  1883. if (max == null || data.start > max) {
  1884. max = data.start;
  1885. }
  1886. }
  1887. });
  1888. return {
  1889. min: min,
  1890. max: max
  1891. }
  1892. };
  1893. /**
  1894. * Find an item from an element:
  1895. * searches for the attribute 'timeline-item' in the element's tree
  1896. * @param {HTMLElement} element
  1897. * @return {Item | null} item
  1898. */
  1899. ItemSet.prototype.itemFromElement = function(element) {
  1900. var cur = element;
  1901. while (cur) {
  1902. if (cur.hasOwnProperty('timeline-item')) {
  1903. return cur['timeline-item'];
  1904. }
  1905. cur = cur.parentNode;
  1906. }
  1907. return null;
  1908. };
  1909. /**
  1910. * Find an item from an event target:
  1911. * searches for the attribute 'timeline-item' in the event target's element tree
  1912. * @param {Event} event
  1913. * @return {Item | null} item
  1914. */
  1915. ItemSet.prototype.itemFromTarget = function(event) {
  1916. return this.itemFromElement(event.target);
  1917. };
  1918. /**
  1919. * Find an item from an event's related target:
  1920. * searches for the attribute 'timeline-item' in the related target's element tree
  1921. * @param {Event} event
  1922. * @return {Item | null} item
  1923. */
  1924. ItemSet.prototype.itemFromRelatedTarget = function(event) {
  1925. return this.itemFromElement(event.relatedTarget);
  1926. };
  1927. /**
  1928. * Find the Group from an event target:
  1929. * searches for the attribute 'timeline-group' in the event target's element tree
  1930. * @param {Event} event
  1931. * @return {Group | null} group
  1932. */
  1933. ItemSet.prototype.groupFromTarget = function(event) {
  1934. var clientY = event.center ? event.center.y : event.clientY;
  1935. for (var i = 0; i < this.groupIds.length; i++) {
  1936. var groupId = this.groupIds[i];
  1937. var group = this.groups[groupId];
  1938. var foreground = group.dom.foreground;
  1939. var top = util.getAbsoluteTop(foreground);
  1940. if (clientY > top && clientY < top + foreground.offsetHeight) {
  1941. return group;
  1942. }
  1943. if (this.options.orientation.item === 'top') {
  1944. if (i === this.groupIds.length - 1 && clientY > top) {
  1945. return group;
  1946. }
  1947. }
  1948. else {
  1949. if (i === 0 && clientY < top + foreground.offset) {
  1950. return group;
  1951. }
  1952. }
  1953. }
  1954. return null;
  1955. };
  1956. /**
  1957. * Find the ItemSet from an event target:
  1958. * searches for the attribute 'timeline-itemset' in the event target's element tree
  1959. * @param {Event} event
  1960. * @return {ItemSet | null} item
  1961. */
  1962. ItemSet.itemSetFromTarget = function(event) {
  1963. var target = event.target;
  1964. while (target) {
  1965. if (target.hasOwnProperty('timeline-itemset')) {
  1966. return target['timeline-itemset'];
  1967. }
  1968. target = target.parentNode;
  1969. }
  1970. return null;
  1971. };
  1972. /**
  1973. * Clone the data of an item, and "normalize" it: convert the start and end date
  1974. * to the type (Date, Moment, ...) configured in the DataSet. If not configured,
  1975. * start and end are converted to Date.
  1976. * @param {Object} itemData, typically `item.data`
  1977. * @param {string} [type] Optional Date type. If not provided, the type from the DataSet is taken
  1978. * @return {Object} The cloned object
  1979. * @private
  1980. */
  1981. ItemSet.prototype._cloneItemData = function (itemData, type) {
  1982. var clone = util.extend({}, itemData);
  1983. if (!type) {
  1984. // convert start and end date to the type (Date, Moment, ...) configured in the DataSet
  1985. type = this.itemsData.getDataSet()._options.type;
  1986. }
  1987. if (clone.start != undefined) {
  1988. clone.start = util.convert(clone.start, type && type.start || 'Date');
  1989. }
  1990. if (clone.end != undefined) {
  1991. clone.end = util.convert(clone.end , type && type.end || 'Date');
  1992. }
  1993. return clone;
  1994. };
  1995. module.exports = ItemSet;