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.

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