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.

2345 lines
69 KiB

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