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.

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