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.

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