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.

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