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.

2410 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',
  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. var newGroupIdsOrder = [];
  1083. groupIds.forEach(function(groupId){
  1084. var groupData = this.groupsData.get(groupId);
  1085. if (!groupData.nestedInGroup) {
  1086. newGroupIdsOrder.push(groupId)
  1087. }
  1088. if (groupData.nestedGroups) {
  1089. var nestedGroups = this.groupsData.get({
  1090. filter: function(nestedGroup) {
  1091. return nestedGroup.nestedInGroup == groupId;
  1092. },
  1093. order: this.options.groupOrder
  1094. });
  1095. var nestedGroupIds = nestedGroups.map(function(nestedGroup) { return nestedGroup.id });
  1096. newGroupIdsOrder = newGroupIdsOrder.concat(nestedGroupIds);
  1097. }
  1098. }, this);
  1099. return newGroupIdsOrder;
  1100. };
  1101. /**
  1102. * Add a new item
  1103. * @param {Item} item
  1104. * @private
  1105. */
  1106. ItemSet.prototype._addItem = function(item) {
  1107. this.items[item.id] = item;
  1108. // add to group
  1109. var groupId = this._getGroupId(item.data);
  1110. var group = this.groups[groupId];
  1111. if (!group) {
  1112. item.groupShowing = false;
  1113. } else if (group && group.data && group.data.showNested) {
  1114. item.groupShowing = true;
  1115. }
  1116. if (group) group.add(item);
  1117. };
  1118. /**
  1119. * Update an existing item
  1120. * @param {Item} item
  1121. * @param {Object} itemData
  1122. * @private
  1123. */
  1124. ItemSet.prototype._updateItem = function(item, itemData) {
  1125. // update the items data (will redraw the item when displayed)
  1126. item.setData(itemData);
  1127. var groupId = this._getGroupId(item.data);
  1128. var group = this.groups[groupId];
  1129. if (!group) {
  1130. item.groupShowing = false;
  1131. } else if (group && group.data && group.data.showNested) {
  1132. item.groupShowing = true;
  1133. }
  1134. };
  1135. /**
  1136. * Delete an item from the ItemSet: remove it from the DOM, from the map
  1137. * with items, and from the map with visible items, and from the selection
  1138. * @param {Item} item
  1139. * @private
  1140. */
  1141. ItemSet.prototype._removeItem = function(item) {
  1142. // remove from DOM
  1143. item.hide();
  1144. // remove from items
  1145. delete this.items[item.id];
  1146. // remove from selection
  1147. var index = this.selection.indexOf(item.id);
  1148. if (index != -1) this.selection.splice(index, 1);
  1149. // remove from group
  1150. item.parent && item.parent.remove(item);
  1151. };
  1152. /**
  1153. * Create an array containing all items being a range (having an end date)
  1154. * @param {Array.<Object>} array
  1155. * @returns {Array}
  1156. * @private
  1157. */
  1158. ItemSet.prototype._constructByEndArray = function(array) {
  1159. var endArray = [];
  1160. for (var i = 0; i < array.length; i++) {
  1161. if (array[i] instanceof RangeItem) {
  1162. endArray.push(array[i]);
  1163. }
  1164. }
  1165. return endArray;
  1166. };
  1167. /**
  1168. * Register the clicked item on touch, before dragStart is initiated.
  1169. *
  1170. * dragStart is initiated from a mousemove event, AFTER the mouse/touch is
  1171. * already moving. Therefore, the mouse/touch can sometimes be above an other
  1172. * DOM element than the item itself.
  1173. *
  1174. * @param {Event} event
  1175. * @private
  1176. */
  1177. ItemSet.prototype._onTouch = function (event) {
  1178. // store the touched item, used in _onDragStart
  1179. this.touchParams.item = this.itemFromTarget(event);
  1180. this.touchParams.dragLeftItem = event.target.dragLeftItem || false;
  1181. this.touchParams.dragRightItem = event.target.dragRightItem || false;
  1182. this.touchParams.itemProps = null;
  1183. };
  1184. /**
  1185. * Given an group id, returns the index it has.
  1186. *
  1187. * @param {number} groupId
  1188. * @returns {number} index / groupId
  1189. * @private
  1190. */
  1191. ItemSet.prototype._getGroupIndex = function(groupId) {
  1192. for (var i = 0; i < this.groupIds.length; i++) {
  1193. if (groupId == this.groupIds[i])
  1194. return i;
  1195. }
  1196. };
  1197. /**
  1198. * Start dragging the selected events
  1199. * @param {Event} event
  1200. * @private
  1201. */
  1202. ItemSet.prototype._onDragStart = function (event) {
  1203. if (this.touchParams.itemIsDragging) { return; }
  1204. var item = this.touchParams.item || null;
  1205. var me = this;
  1206. var props;
  1207. if (item && (item.selected || this.options.itemsAlwaysDraggable.item)) {
  1208. if (this.options.editable.overrideItems &&
  1209. !this.options.editable.updateTime &&
  1210. !this.options.editable.updateGroup) {
  1211. return;
  1212. }
  1213. // override options.editable
  1214. if ((item.editable != null && !item.editable.updateTime && !item.editable.updateGroup)
  1215. && !this.options.editable.overrideItems) {
  1216. return;
  1217. }
  1218. var dragLeftItem = this.touchParams.dragLeftItem;
  1219. var dragRightItem = this.touchParams.dragRightItem;
  1220. this.touchParams.itemIsDragging = true;
  1221. this.touchParams.selectedItem = item;
  1222. if (dragLeftItem) {
  1223. props = {
  1224. item: dragLeftItem,
  1225. initialX: event.center.x,
  1226. dragLeft: true,
  1227. data: this._cloneItemData(item.data)
  1228. };
  1229. this.touchParams.itemProps = [props];
  1230. } else if (dragRightItem) {
  1231. props = {
  1232. item: dragRightItem,
  1233. initialX: event.center.x,
  1234. dragRight: true,
  1235. data: this._cloneItemData(item.data)
  1236. };
  1237. this.touchParams.itemProps = [props];
  1238. } else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  1239. // create a new range item when dragging with ctrl key down
  1240. this._onDragStartAddItem(event);
  1241. } else {
  1242. if(this.groupIds.length < 1) {
  1243. // Mitigates a race condition if _onDragStart() is
  1244. // called after markDirty() without redraw() being called between.
  1245. this.redraw();
  1246. }
  1247. var baseGroupIndex = this._getGroupIndex(item.data.group);
  1248. var itemsToDrag = (this.options.itemsAlwaysDraggable.item && !item.selected) ? [item.id] : this.getSelection();
  1249. this.touchParams.itemProps = itemsToDrag.map(function (id) {
  1250. var item = me.items[id];
  1251. var groupIndex = me._getGroupIndex(item.data.group);
  1252. return {
  1253. item: item,
  1254. initialX: event.center.x,
  1255. groupOffset: baseGroupIndex-groupIndex,
  1256. data: this._cloneItemData(item.data)
  1257. };
  1258. }.bind(this));
  1259. }
  1260. event.stopPropagation();
  1261. } else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  1262. // create a new range item when dragging with ctrl key down
  1263. this._onDragStartAddItem(event);
  1264. }
  1265. };
  1266. /**
  1267. * Start creating a new range item by dragging.
  1268. * @param {Event} event
  1269. * @private
  1270. */
  1271. ItemSet.prototype._onDragStartAddItem = function (event) {
  1272. var xAbs;
  1273. var x;
  1274. var snap = this.options.snap || null;
  1275. if (this.options.rtl) {
  1276. xAbs = util.getAbsoluteRight(this.dom.frame);
  1277. x = xAbs - event.center.x + 10; // plus 10 to compensate for the drag starting as soon as you've moved 10px
  1278. } else {
  1279. xAbs = util.getAbsoluteLeft(this.dom.frame);
  1280. x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  1281. }
  1282. var time = this.body.util.toTime(x);
  1283. var scale = this.body.util.getScale();
  1284. var step = this.body.util.getStep();
  1285. var start = snap ? snap(time, scale, step) : time;
  1286. var end = start;
  1287. var itemData = {
  1288. type: 'range',
  1289. start: start,
  1290. end: end,
  1291. content: 'new item'
  1292. };
  1293. var id = util.randomUUID();
  1294. itemData[this.itemsData._fieldId] = id;
  1295. var group = this.groupFromTarget(event);
  1296. if (group) {
  1297. itemData.group = group.groupId;
  1298. }
  1299. var newItem = new RangeItem(itemData, this.conversion, this.options);
  1300. newItem.id = id; // TODO: not so nice setting id afterwards
  1301. newItem.data = this._cloneItemData(itemData);
  1302. this._addItem(newItem);
  1303. this.touchParams.selectedItem = newItem;
  1304. var props = {
  1305. item: newItem,
  1306. initialX: event.center.x,
  1307. data: newItem.data
  1308. };
  1309. if (this.options.rtl) {
  1310. props.dragLeft = true;
  1311. } else {
  1312. props.dragRight = true;
  1313. }
  1314. this.touchParams.itemProps = [props];
  1315. event.stopPropagation();
  1316. };
  1317. /**
  1318. * Drag selected items
  1319. * @param {Event} event
  1320. * @private
  1321. */
  1322. ItemSet.prototype._onDrag = function (event) {
  1323. if (this.touchParams.itemProps) {
  1324. event.stopPropagation();
  1325. var me = this;
  1326. var snap = this.options.snap || null;
  1327. var xOffset;
  1328. if (this.options.rtl) {
  1329. xOffset = this.body.dom.root.offsetLeft + this.body.domProps.right.width;
  1330. } else {
  1331. xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  1332. }
  1333. var scale = this.body.util.getScale();
  1334. var step = this.body.util.getStep();
  1335. //only calculate the new group for the item that's actually dragged
  1336. var selectedItem = this.touchParams.selectedItem;
  1337. var updateGroupAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateGroup) ||
  1338. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateGroup);
  1339. var newGroupBase = null;
  1340. if (updateGroupAllowed && selectedItem) {
  1341. if (selectedItem.data.group != undefined) {
  1342. // drag from one group to another
  1343. var group = me.groupFromTarget(event);
  1344. if (group) {
  1345. //we know the offset for all items, so the new group for all items
  1346. //will be relative to this one.
  1347. newGroupBase = this._getGroupIndex(group.groupId);
  1348. }
  1349. }
  1350. }
  1351. // move
  1352. this.touchParams.itemProps.forEach(function (props) {
  1353. var current = me.body.util.toTime(event.center.x - xOffset);
  1354. var initial = me.body.util.toTime(props.initialX - xOffset);
  1355. var offset;
  1356. var initialStart;
  1357. var initialEnd;
  1358. var start;
  1359. var end;
  1360. if (this.options.rtl) {
  1361. offset = -(current - initial); // ms
  1362. } else {
  1363. offset = (current - initial); // ms
  1364. }
  1365. var itemData = this._cloneItemData(props.item.data); // clone the data
  1366. if (props.item.editable != null
  1367. && !props.item.editable.updateTime
  1368. && !props.item.editable.updateGroup
  1369. && !me.options.editable.overrideItems) {
  1370. return;
  1371. }
  1372. var updateTimeAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateTime) ||
  1373. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateTime);
  1374. if (updateTimeAllowed) {
  1375. if (props.dragLeft) {
  1376. // drag left side of a range item
  1377. if (this.options.rtl) {
  1378. if (itemData.end != undefined) {
  1379. initialEnd = util.convert(props.data.end, 'Date');
  1380. end = new Date(initialEnd.valueOf() + offset);
  1381. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1382. itemData.end = snap ? snap(end, scale, step) : end;
  1383. }
  1384. } else {
  1385. if (itemData.start != undefined) {
  1386. initialStart = util.convert(props.data.start, 'Date');
  1387. start = new Date(initialStart.valueOf() + offset);
  1388. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1389. itemData.start = snap ? snap(start, scale, step) : start;
  1390. }
  1391. }
  1392. }
  1393. else if (props.dragRight) {
  1394. // drag right side of a range item
  1395. if (this.options.rtl) {
  1396. if (itemData.start != undefined) {
  1397. initialStart = util.convert(props.data.start, 'Date');
  1398. start = new Date(initialStart.valueOf() + offset);
  1399. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1400. itemData.start = snap ? snap(start, scale, step) : start;
  1401. }
  1402. } else {
  1403. if (itemData.end != undefined) {
  1404. initialEnd = util.convert(props.data.end, 'Date');
  1405. end = new Date(initialEnd.valueOf() + offset);
  1406. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1407. itemData.end = snap ? snap(end, scale, step) : end;
  1408. }
  1409. }
  1410. }
  1411. else {
  1412. // drag both start and end
  1413. if (itemData.start != undefined) {
  1414. initialStart = util.convert(props.data.start, 'Date').valueOf();
  1415. start = new Date(initialStart + offset);
  1416. if (itemData.end != undefined) {
  1417. initialEnd = util.convert(props.data.end, 'Date');
  1418. var duration = initialEnd.valueOf() - initialStart.valueOf();
  1419. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1420. itemData.start = snap ? snap(start, scale, step) : start;
  1421. itemData.end = new Date(itemData.start.valueOf() + duration);
  1422. }
  1423. else {
  1424. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1425. itemData.start = snap ? snap(start, scale, step) : start;
  1426. }
  1427. }
  1428. }
  1429. }
  1430. if (updateGroupAllowed && (!props.dragLeft && !props.dragRight) && newGroupBase!=null) {
  1431. if (itemData.group != undefined) {
  1432. var newOffset = newGroupBase - props.groupOffset;
  1433. //make sure we stay in bounds
  1434. newOffset = Math.max(0, newOffset);
  1435. newOffset = Math.min(me.groupIds.length-1, newOffset);
  1436. itemData.group = me.groupIds[newOffset];
  1437. }
  1438. }
  1439. // confirm moving the item
  1440. itemData = this._cloneItemData(itemData); // convert start and end to the correct type
  1441. me.options.onMoving(itemData, function (itemData) {
  1442. if (itemData) {
  1443. props.item.setData(this._cloneItemData(itemData, 'Date'));
  1444. }
  1445. }.bind(this));
  1446. }.bind(this));
  1447. this.body.emitter.emit('_change');
  1448. }
  1449. };
  1450. /**
  1451. * Move an item to another group
  1452. * @param {Item} item
  1453. * @param {string | number} groupId
  1454. * @private
  1455. */
  1456. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1457. var group = this.groups[groupId];
  1458. if (group && group.groupId != item.data.group) {
  1459. var oldGroup = item.parent;
  1460. oldGroup.remove(item);
  1461. oldGroup.order();
  1462. item.data.group = group.groupId;
  1463. group.add(item);
  1464. group.order();
  1465. }
  1466. };
  1467. /**
  1468. * End of dragging selected items
  1469. * @param {Event} event
  1470. * @private
  1471. */
  1472. ItemSet.prototype._onDragEnd = function (event) {
  1473. this.touchParams.itemIsDragging = false;
  1474. if (this.touchParams.itemProps) {
  1475. event.stopPropagation();
  1476. var me = this;
  1477. var dataset = this.itemsData.getDataSet();
  1478. var itemProps = this.touchParams.itemProps ;
  1479. this.touchParams.itemProps = null;
  1480. itemProps.forEach(function (props) {
  1481. var id = props.item.id;
  1482. var exists = me.itemsData.get(id, me.itemOptions) != null;
  1483. if (!exists) {
  1484. // add a new item
  1485. me.options.onAdd(props.item.data, function (itemData) {
  1486. me._removeItem(props.item); // remove temporary item
  1487. if (itemData) {
  1488. me.itemsData.getDataSet().add(itemData);
  1489. }
  1490. // force re-stacking of all items next redraw
  1491. me.body.emitter.emit('_change');
  1492. });
  1493. }
  1494. else {
  1495. // update existing item
  1496. var itemData = this._cloneItemData(props.item.data); // convert start and end to the correct type
  1497. me.options.onMove(itemData, function (itemData) {
  1498. if (itemData) {
  1499. // apply changes
  1500. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1501. dataset.update(itemData);
  1502. }
  1503. else {
  1504. // restore original values
  1505. props.item.setData(props.data);
  1506. me.body.emitter.emit('_change');
  1507. }
  1508. });
  1509. }
  1510. }.bind(this));
  1511. }
  1512. };
  1513. ItemSet.prototype._onGroupClick = function (event) {
  1514. var group = this.groupFromTarget(event);
  1515. if (!group || !group.nestedGroups) return;
  1516. var groupsData = this.groupsData.getDataSet();
  1517. var nestingGroup = groupsData.get(group.groupId)
  1518. if (nestingGroup.showNested == undefined) { nestingGroup.showNested = true; }
  1519. nestingGroup.showNested = !nestingGroup.showNested;
  1520. var nestedGroups = groupsData.get(group.nestedGroups).map(function(nestedGroup) {
  1521. nestedGroup.visible = nestingGroup.showNested;
  1522. return nestedGroup;
  1523. });
  1524. groupsData.update(nestedGroups.concat(nestingGroup));
  1525. if (nestingGroup.showNested) {
  1526. util.removeClassName(group.dom.label, 'collapsed');
  1527. util.addClassName(group.dom.label, 'expanded');
  1528. } else {
  1529. util.removeClassName(group.dom.label, 'expanded');
  1530. var collapsedDirClassName = this.options.rtl ? 'collapsed-rtl' : 'collapsed';
  1531. util.addClassName(group.dom.label, collapsedDirClassName);
  1532. }
  1533. };
  1534. ItemSet.prototype._onGroupDragStart = function (event) {
  1535. if (this.options.groupEditable.order) {
  1536. this.groupTouchParams.group = this.groupFromTarget(event);
  1537. if (this.groupTouchParams.group) {
  1538. event.stopPropagation();
  1539. this.groupTouchParams.originalOrder = this.groupsData.getIds({
  1540. order: this.options.groupOrder
  1541. });
  1542. }
  1543. }
  1544. };
  1545. ItemSet.prototype._onGroupDrag = function (event) {
  1546. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1547. event.stopPropagation();
  1548. var groupsData = this.groupsData;
  1549. if (this.groupsData instanceof DataView) {
  1550. groupsData = this.groupsData.getDataSet()
  1551. }
  1552. // drag from one group to another
  1553. var group = this.groupFromTarget(event);
  1554. // try to avoid toggling when groups differ in height
  1555. if (group && group.height != this.groupTouchParams.group.height) {
  1556. var movingUp = (group.top < this.groupTouchParams.group.top);
  1557. var clientY = event.center ? event.center.y : event.clientY;
  1558. var targetGroupTop = util.getAbsoluteTop(group.dom.foreground);
  1559. var draggedGroupHeight = this.groupTouchParams.group.height;
  1560. if (movingUp) {
  1561. // skip swapping the groups when the dragged group is not below clientY afterwards
  1562. if (targetGroupTop + draggedGroupHeight < clientY) {
  1563. return;
  1564. }
  1565. } else {
  1566. var targetGroupHeight = group.height;
  1567. // skip swapping the groups when the dragged group is not below clientY afterwards
  1568. if (targetGroupTop + targetGroupHeight - draggedGroupHeight > clientY) {
  1569. return;
  1570. }
  1571. }
  1572. }
  1573. if (group && group != this.groupTouchParams.group) {
  1574. var targetGroup = groupsData.get(group.groupId);
  1575. var draggedGroup = groupsData.get(this.groupTouchParams.group.groupId);
  1576. // switch groups
  1577. if (draggedGroup && targetGroup) {
  1578. this.options.groupOrderSwap(draggedGroup, targetGroup, groupsData);
  1579. groupsData.update(draggedGroup);
  1580. groupsData.update(targetGroup);
  1581. }
  1582. // fetch current order of groups
  1583. var newOrder = groupsData.getIds({
  1584. order: this.options.groupOrder
  1585. });
  1586. // in case of changes since _onGroupDragStart
  1587. if (!util.equalArray(newOrder, this.groupTouchParams.originalOrder)) {
  1588. var origOrder = this.groupTouchParams.originalOrder;
  1589. var draggedId = this.groupTouchParams.group.groupId;
  1590. var numGroups = Math.min(origOrder.length, newOrder.length);
  1591. var curPos = 0;
  1592. var newOffset = 0;
  1593. var orgOffset = 0;
  1594. while (curPos < numGroups) {
  1595. // as long as the groups are where they should be step down along the groups order
  1596. while ((curPos+newOffset) < numGroups
  1597. && (curPos+orgOffset) < numGroups
  1598. && newOrder[curPos+newOffset] == origOrder[curPos+orgOffset]) {
  1599. curPos++;
  1600. }
  1601. // all ok
  1602. if (curPos+newOffset >= numGroups) {
  1603. break;
  1604. }
  1605. // not all ok
  1606. // if dragged group was move upwards everything below should have an offset
  1607. if (newOrder[curPos+newOffset] == draggedId) {
  1608. newOffset = 1;
  1609. }
  1610. // if dragged group was move downwards everything above should have an offset
  1611. else if (origOrder[curPos+orgOffset] == draggedId) {
  1612. orgOffset = 1;
  1613. }
  1614. // found a group (apart from dragged group) that has the wrong position -> switch with the
  1615. // group at the position where other one should be, fix index arrays and continue
  1616. else {
  1617. var slippedPosition = newOrder.indexOf(origOrder[curPos+orgOffset]);
  1618. var switchGroup = groupsData.get(newOrder[curPos+newOffset]);
  1619. var shouldBeGroup = groupsData.get(origOrder[curPos+orgOffset]);
  1620. this.options.groupOrderSwap(switchGroup, shouldBeGroup, groupsData);
  1621. groupsData.update(switchGroup);
  1622. groupsData.update(shouldBeGroup);
  1623. var switchGroupId = newOrder[curPos+newOffset];
  1624. newOrder[curPos+newOffset] = origOrder[curPos+orgOffset];
  1625. newOrder[slippedPosition] = switchGroupId;
  1626. curPos++;
  1627. }
  1628. }
  1629. }
  1630. }
  1631. }
  1632. };
  1633. ItemSet.prototype._onGroupDragEnd = function (event) {
  1634. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1635. event.stopPropagation();
  1636. // update existing group
  1637. var me = this;
  1638. var id = me.groupTouchParams.group.groupId;
  1639. var dataset = me.groupsData.getDataSet();
  1640. var groupData = util.extend({}, dataset.get(id)); // clone the data
  1641. me.options.onMoveGroup(groupData, function (groupData) {
  1642. if (groupData) {
  1643. // apply changes
  1644. groupData[dataset._fieldId] = id; // ensure the group contains its id (can be undefined)
  1645. dataset.update(groupData);
  1646. }
  1647. else {
  1648. // fetch current order of groups
  1649. var newOrder = dataset.getIds({
  1650. order: me.options.groupOrder
  1651. });
  1652. // restore original order
  1653. if (!util.equalArray(newOrder, me.groupTouchParams.originalOrder)) {
  1654. var origOrder = me.groupTouchParams.originalOrder;
  1655. var numGroups = Math.min(origOrder.length, newOrder.length);
  1656. var curPos = 0;
  1657. while (curPos < numGroups) {
  1658. // as long as the groups are where they should be step down along the groups order
  1659. while (curPos < numGroups && newOrder[curPos] == origOrder[curPos]) {
  1660. curPos++;
  1661. }
  1662. // all ok
  1663. if (curPos >= numGroups) {
  1664. break;
  1665. }
  1666. // found a group that has the wrong position -> switch with the
  1667. // group at the position where other one should be, fix index arrays and continue
  1668. var slippedPosition = newOrder.indexOf(origOrder[curPos]);
  1669. var switchGroup = dataset.get(newOrder[curPos]);
  1670. var shouldBeGroup = dataset.get(origOrder[curPos]);
  1671. me.options.groupOrderSwap(switchGroup, shouldBeGroup, dataset);
  1672. dataset.update(switchGroup);
  1673. dataset.update(shouldBeGroup);
  1674. var switchGroupId = newOrder[curPos];
  1675. newOrder[curPos] = origOrder[curPos];
  1676. newOrder[slippedPosition] = switchGroupId;
  1677. curPos++;
  1678. }
  1679. }
  1680. }
  1681. });
  1682. me.body.emitter.emit('groupDragged', { groupId: id });
  1683. }
  1684. };
  1685. /**
  1686. * Handle selecting/deselecting an item when tapping it
  1687. * @param {Event} event
  1688. * @private
  1689. */
  1690. ItemSet.prototype._onSelectItem = function (event) {
  1691. if (!this.options.selectable) return;
  1692. var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey);
  1693. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  1694. if (ctrlKey || shiftKey) {
  1695. this._onMultiSelectItem(event);
  1696. return;
  1697. }
  1698. var oldSelection = this.getSelection();
  1699. var item = this.itemFromTarget(event);
  1700. var selection = item ? [item.id] : [];
  1701. this.setSelection(selection);
  1702. var newSelection = this.getSelection();
  1703. // emit a select event,
  1704. // except when old selection is empty and new selection is still empty
  1705. if (newSelection.length > 0 || oldSelection.length > 0) {
  1706. this.body.emitter.emit('select', {
  1707. items: newSelection,
  1708. event: event
  1709. });
  1710. }
  1711. };
  1712. /**
  1713. * Handle hovering an item
  1714. * @param {Event} event
  1715. * @private
  1716. */
  1717. ItemSet.prototype._onMouseOver = function (event) {
  1718. var item = this.itemFromTarget(event);
  1719. if (!item) return;
  1720. // Item we just left
  1721. var related = this.itemFromRelatedTarget(event);
  1722. if (item === related) {
  1723. // We haven't changed item, just element in the item
  1724. return;
  1725. }
  1726. var title = item.getTitle();
  1727. if (this.options.showTooltips && title) {
  1728. if (this.popup == null) {
  1729. this.popup = new Popup(this.body.dom.root,
  1730. this.options.tooltip.overflowMethod || 'flip');
  1731. }
  1732. this.popup.setText(title);
  1733. var container = this.body.dom.centerContainer;
  1734. this.popup.setPosition(
  1735. event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft,
  1736. event.clientY - util.getAbsoluteTop(container) + container.offsetTop
  1737. );
  1738. this.popup.show();
  1739. } else {
  1740. // Hovering over item without a title, hide popup
  1741. // Needed instead of _just_ in _onMouseOut due to #2572
  1742. if (this.popup != null) {
  1743. this.popup.hide();
  1744. }
  1745. }
  1746. this.body.emitter.emit('itemover', {
  1747. item: item.id,
  1748. event: event
  1749. });
  1750. };
  1751. ItemSet.prototype._onMouseOut = function (event) {
  1752. var item = this.itemFromTarget(event);
  1753. if (!item) return;
  1754. // Item we are going to
  1755. var related = this.itemFromRelatedTarget(event);
  1756. if (item === related) {
  1757. // We aren't changing item, just element in the item
  1758. return;
  1759. }
  1760. if (this.popup != null) {
  1761. this.popup.hide();
  1762. }
  1763. this.body.emitter.emit('itemout', {
  1764. item: item.id,
  1765. event: event
  1766. });
  1767. };
  1768. ItemSet.prototype._onMouseMove = function (event) {
  1769. var item = this.itemFromTarget(event);
  1770. if (!item) return;
  1771. if (this.options.showTooltips && this.options.tooltip.followMouse) {
  1772. if (this.popup) {
  1773. if (!this.popup.hidden) {
  1774. var container = this.body.dom.centerContainer;
  1775. this.popup.setPosition(
  1776. event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft,
  1777. event.clientY - util.getAbsoluteTop(container) + container.offsetTop
  1778. );
  1779. this.popup.show(); // Redraw
  1780. }
  1781. }
  1782. }
  1783. };
  1784. /**
  1785. * Handle mousewheel
  1786. * @param {Event} event The event
  1787. * @private
  1788. */
  1789. ItemSet.prototype._onMouseWheel = function(event) {
  1790. if (this.touchParams.itemIsDragging) {
  1791. this._onDragEnd(event);
  1792. }
  1793. };
  1794. /**
  1795. * Handle updates of an item on double tap
  1796. * @param {vis.Item} item The item
  1797. * @private
  1798. */
  1799. ItemSet.prototype._onUpdateItem = function (item) {
  1800. if (!this.options.selectable) return;
  1801. if (!this.options.editable.add) return;
  1802. var me = this;
  1803. if (item) {
  1804. // execute async handler to update the item (or cancel it)
  1805. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  1806. this.options.onUpdate(itemData, function (itemData) {
  1807. if (itemData) {
  1808. me.itemsData.getDataSet().update(itemData);
  1809. }
  1810. });
  1811. }
  1812. };
  1813. /**
  1814. * Handle drop event of data on item
  1815. * Only called when `objectData.target === 'item'.
  1816. * @param {Event} event The event
  1817. * @private
  1818. */
  1819. ItemSet.prototype._onDropObjectOnItem = function(event) {
  1820. var item = this.itemFromTarget(event);
  1821. var objectData = JSON.parse(event.dataTransfer.getData("text"));
  1822. this.options.onDropObjectOnItem(objectData, item)
  1823. }
  1824. /**
  1825. * Handle creation of an item on double tap or drop of a drag event
  1826. * @param {Event} event The event
  1827. * @private
  1828. */
  1829. ItemSet.prototype._onAddItem = function (event) {
  1830. if (!this.options.selectable) return;
  1831. if (!this.options.editable.add) return;
  1832. var me = this;
  1833. var snap = this.options.snap || null;
  1834. var xAbs;
  1835. var x;
  1836. // add item
  1837. if (this.options.rtl) {
  1838. xAbs = util.getAbsoluteRight(this.dom.frame);
  1839. x = xAbs - event.center.x;
  1840. } else {
  1841. xAbs = util.getAbsoluteLeft(this.dom.frame);
  1842. x = event.center.x - xAbs;
  1843. }
  1844. // var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1845. // var x = event.center.x - xAbs;
  1846. var start = this.body.util.toTime(x);
  1847. var scale = this.body.util.getScale();
  1848. var step = this.body.util.getStep();
  1849. var end;
  1850. var newItemData;
  1851. if (event.type == 'drop') {
  1852. newItemData = JSON.parse(event.dataTransfer.getData("text"));
  1853. newItemData.content = newItemData.content ? newItemData.content : 'new item';
  1854. newItemData.start = newItemData.start ? newItemData.start : (snap ? snap(start, scale, step) : start);
  1855. newItemData.type = newItemData.type || 'box';
  1856. newItemData[this.itemsData._fieldId] = newItemData.id || util.randomUUID();
  1857. if (newItemData.type == 'range' && !newItemData.end) {
  1858. end = this.body.util.toTime(x + this.props.width / 5);
  1859. newItemData.end = snap ? snap(end, scale, step) : end;
  1860. }
  1861. } else {
  1862. newItemData = {
  1863. start: snap ? snap(start, scale, step) : start,
  1864. content: 'new item'
  1865. };
  1866. newItemData[this.itemsData._fieldId] = util.randomUUID();
  1867. // when default type is a range, add a default end date to the new item
  1868. if (this.options.type === 'range') {
  1869. end = this.body.util.toTime(x + this.props.width / 5);
  1870. newItemData.end = snap ? snap(end, scale, step) : end;
  1871. }
  1872. }
  1873. var group = this.groupFromTarget(event);
  1874. if (group) {
  1875. newItemData.group = group.groupId;
  1876. }
  1877. // execute async handler to customize (or cancel) adding an item
  1878. newItemData = this._cloneItemData(newItemData); // convert start and end to the correct type
  1879. this.options.onAdd(newItemData, function (item) {
  1880. if (item) {
  1881. me.itemsData.getDataSet().add(item);
  1882. if (event.type == 'drop') {
  1883. me.setSelection([item.id]);
  1884. }
  1885. // TODO: need to trigger a redraw?
  1886. }
  1887. });
  1888. };
  1889. /**
  1890. * Handle selecting/deselecting multiple items when holding an item
  1891. * @param {Event} event
  1892. * @private
  1893. */
  1894. ItemSet.prototype._onMultiSelectItem = function (event) {
  1895. if (!this.options.selectable) return;
  1896. var item = this.itemFromTarget(event);
  1897. if (item) {
  1898. // multi select items (if allowed)
  1899. var selection = this.options.multiselect
  1900. ? this.getSelection() // take current selection
  1901. : []; // deselect current selection
  1902. var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false;
  1903. if (shiftKey && this.options.multiselect) {
  1904. // select all items between the old selection and the tapped item
  1905. var itemGroup = this.itemsData.get(item.id).group;
  1906. // when filtering get the group of the last selected item
  1907. var lastSelectedGroup = undefined;
  1908. if (this.options.multiselectPerGroup) {
  1909. if (selection.length > 0) {
  1910. lastSelectedGroup = this.itemsData.get(selection[0]).group;
  1911. }
  1912. }
  1913. // determine the selection range
  1914. if (!this.options.multiselectPerGroup || lastSelectedGroup == undefined || lastSelectedGroup == itemGroup) {
  1915. selection.push(item.id);
  1916. }
  1917. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  1918. if (!this.options.multiselectPerGroup || lastSelectedGroup == itemGroup) {
  1919. // select all items within the selection range
  1920. selection = [];
  1921. for (var id in this.items) {
  1922. if (this.items.hasOwnProperty(id)) {
  1923. var _item = this.items[id];
  1924. var start = _item.data.start;
  1925. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  1926. if (start >= range.min &&
  1927. end <= range.max &&
  1928. (!this.options.multiselectPerGroup || lastSelectedGroup == this.itemsData.get(_item.id).group) &&
  1929. !(_item instanceof BackgroundItem)) {
  1930. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  1931. }
  1932. }
  1933. }
  1934. }
  1935. }
  1936. else {
  1937. // add/remove this item from the current selection
  1938. var index = selection.indexOf(item.id);
  1939. if (index == -1) {
  1940. // item is not yet selected -> select it
  1941. selection.push(item.id);
  1942. }
  1943. else {
  1944. // item is already selected -> deselect it
  1945. selection.splice(index, 1);
  1946. }
  1947. }
  1948. this.setSelection(selection);
  1949. this.body.emitter.emit('select', {
  1950. items: this.getSelection(),
  1951. event: event
  1952. });
  1953. }
  1954. };
  1955. /**
  1956. * Calculate the time range of a list of items
  1957. * @param {Array.<Object>} itemsData
  1958. * @return {{min: Date, max: Date}} Returns the range of the provided items
  1959. * @private
  1960. */
  1961. ItemSet._getItemRange = function(itemsData) {
  1962. var max = null;
  1963. var min = null;
  1964. itemsData.forEach(function (data) {
  1965. if (min == null || data.start < min) {
  1966. min = data.start;
  1967. }
  1968. if (data.end != undefined) {
  1969. if (max == null || data.end > max) {
  1970. max = data.end;
  1971. }
  1972. }
  1973. else {
  1974. if (max == null || data.start > max) {
  1975. max = data.start;
  1976. }
  1977. }
  1978. });
  1979. return {
  1980. min: min,
  1981. max: max
  1982. }
  1983. };
  1984. /**
  1985. * Find an item from an element:
  1986. * searches for the attribute 'timeline-item' in the element's tree
  1987. * @param {HTMLElement} element
  1988. * @return {Item | null} item
  1989. */
  1990. ItemSet.prototype.itemFromElement = function(element) {
  1991. var cur = element;
  1992. while (cur) {
  1993. if (cur.hasOwnProperty('timeline-item')) {
  1994. return cur['timeline-item'];
  1995. }
  1996. cur = cur.parentNode;
  1997. }
  1998. return null;
  1999. };
  2000. /**
  2001. * Find an item from an event target:
  2002. * searches for the attribute 'timeline-item' in the event target's element tree
  2003. * @param {Event} event
  2004. * @return {Item | null} item
  2005. */
  2006. ItemSet.prototype.itemFromTarget = function(event) {
  2007. return this.itemFromElement(event.target);
  2008. };
  2009. /**
  2010. * Find an item from an event's related target:
  2011. * searches for the attribute 'timeline-item' in the related target's element tree
  2012. * @param {Event} event
  2013. * @return {Item | null} item
  2014. */
  2015. ItemSet.prototype.itemFromRelatedTarget = function(event) {
  2016. return this.itemFromElement(event.relatedTarget);
  2017. };
  2018. /**
  2019. * Find the Group from an event target:
  2020. * searches for the attribute 'timeline-group' in the event target's element tree
  2021. * @param {Event} event
  2022. * @return {Group | null} group
  2023. */
  2024. ItemSet.prototype.groupFromTarget = function(event) {
  2025. var clientY = event.center ? event.center.y : event.clientY;
  2026. var groupIds = this.groupIds;
  2027. if (groupIds.length <= 0 && this.groupsData) {
  2028. groupIds = this.groupsData.getIds({
  2029. order: this.options.groupOrder
  2030. });
  2031. }
  2032. for (var i = 0; i < groupIds.length; i++) {
  2033. var groupId = groupIds[i];
  2034. var group = this.groups[groupId];
  2035. var foreground = group.dom.foreground;
  2036. var top = util.getAbsoluteTop(foreground);
  2037. if (clientY >= top && clientY < top + foreground.offsetHeight) {
  2038. return group;
  2039. }
  2040. if (this.options.orientation.item === 'top') {
  2041. if (i === this.groupIds.length - 1 && clientY > top) {
  2042. return group;
  2043. }
  2044. }
  2045. else {
  2046. if (i === 0 && clientY < top + foreground.offset) {
  2047. return group;
  2048. }
  2049. }
  2050. }
  2051. return null;
  2052. };
  2053. /**
  2054. * Find the ItemSet from an event target:
  2055. * searches for the attribute 'timeline-itemset' in the event target's element tree
  2056. * @param {Event} event
  2057. * @return {ItemSet | null} item
  2058. */
  2059. ItemSet.itemSetFromTarget = function(event) {
  2060. var target = event.target;
  2061. while (target) {
  2062. if (target.hasOwnProperty('timeline-itemset')) {
  2063. return target['timeline-itemset'];
  2064. }
  2065. target = target.parentNode;
  2066. }
  2067. return null;
  2068. };
  2069. /**
  2070. * Clone the data of an item, and "normalize" it: convert the start and end date
  2071. * to the type (Date, Moment, ...) configured in the DataSet. If not configured,
  2072. * start and end are converted to Date.
  2073. * @param {Object} itemData, typically `item.data`
  2074. * @param {string} [type] Optional Date type. If not provided, the type from the DataSet is taken
  2075. * @return {Object} The cloned object
  2076. * @private
  2077. */
  2078. ItemSet.prototype._cloneItemData = function (itemData, type) {
  2079. var clone = util.extend({}, itemData);
  2080. if (!type) {
  2081. // convert start and end date to the type (Date, Moment, ...) configured in the DataSet
  2082. type = this.itemsData.getDataSet()._options.type;
  2083. }
  2084. if (clone.start != undefined) {
  2085. clone.start = util.convert(clone.start, type && type.start || 'Date');
  2086. }
  2087. if (clone.end != undefined) {
  2088. clone.end = util.convert(clone.end , type && type.end || 'Date');
  2089. }
  2090. return clone;
  2091. };
  2092. module.exports = ItemSet;