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.

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