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.

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