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.

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