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.

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