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.

2461 lines
72 KiB

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