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.

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