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.

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