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.

2099 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 = false;
  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 != null && !item.editable.updateTime && !item.editable.updateGroup)
  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 = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateGroup) ||
  1182. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateGroup);
  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 != null
  1206. && !props.item.editable.updateTime
  1207. && !props.item.editable.updateGroup
  1208. && !me.options.editable.overrideItems) {
  1209. return;
  1210. }
  1211. var updateTimeAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateTime) ||
  1212. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateTime);
  1213. if (updateTimeAllowed) {
  1214. if (props.dragLeft) {
  1215. // drag left side of a range item
  1216. if (this.options.rtl) {
  1217. if (itemData.end != undefined) {
  1218. var initialEnd = util.convert(props.data.end, 'Date');
  1219. var end = new Date(initialEnd.valueOf() + offset);
  1220. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1221. itemData.end = snap ? snap(end, scale, step) : end;
  1222. }
  1223. } else {
  1224. if (itemData.start != undefined) {
  1225. var initialStart = util.convert(props.data.start, 'Date');
  1226. var start = new Date(initialStart.valueOf() + offset);
  1227. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1228. itemData.start = snap ? snap(start, scale, step) : start;
  1229. }
  1230. }
  1231. }
  1232. else if (props.dragRight) {
  1233. // drag right side of a range item
  1234. if (this.options.rtl) {
  1235. if (itemData.start != undefined) {
  1236. var initialStart = util.convert(props.data.start, 'Date');
  1237. var start = new Date(initialStart.valueOf() + offset);
  1238. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1239. itemData.start = snap ? snap(start, scale, step) : start;
  1240. }
  1241. } else {
  1242. if (itemData.end != undefined) {
  1243. var initialEnd = util.convert(props.data.end, 'Date');
  1244. var end = new Date(initialEnd.valueOf() + offset);
  1245. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1246. itemData.end = snap ? snap(end, scale, step) : end;
  1247. }
  1248. }
  1249. }
  1250. else {
  1251. // drag both start and end
  1252. if (itemData.start != undefined) {
  1253. var initialStart = util.convert(props.data.start, 'Date').valueOf();
  1254. var start = new Date(initialStart + offset);
  1255. if (itemData.end != undefined) {
  1256. var initialEnd = util.convert(props.data.end, 'Date');
  1257. var duration = initialEnd.valueOf() - initialStart.valueOf();
  1258. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1259. itemData.start = snap ? snap(start, scale, step) : start;
  1260. itemData.end = new Date(itemData.start.valueOf() + duration);
  1261. }
  1262. else {
  1263. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1264. itemData.start = snap ? snap(start, scale, step) : start;
  1265. }
  1266. }
  1267. }
  1268. }
  1269. if (updateGroupAllowed && (!props.dragLeft && !props.dragRight) && newGroupBase!=null) {
  1270. if (itemData.group != undefined) {
  1271. var newOffset = newGroupBase - props.groupOffset;
  1272. //make sure we stay in bounds
  1273. newOffset = Math.max(0, newOffset);
  1274. newOffset = Math.min(me.groupIds.length-1, newOffset);
  1275. itemData.group = me.groupIds[newOffset];
  1276. }
  1277. }
  1278. // confirm moving the item
  1279. itemData = this._cloneItemData(itemData); // convert start and end to the correct type
  1280. me.options.onMoving(itemData, function (itemData) {
  1281. if (itemData) {
  1282. props.item.setData(this._cloneItemData(itemData, 'Date'));
  1283. }
  1284. }.bind(this));
  1285. }.bind(this));
  1286. this.stackDirty = true; // force re-stacking of all items next redraw
  1287. this.body.emitter.emit('_change');
  1288. }
  1289. };
  1290. /**
  1291. * Move an item to another group
  1292. * @param {Item} item
  1293. * @param {String | Number} groupId
  1294. * @private
  1295. */
  1296. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1297. var group = this.groups[groupId];
  1298. if (group && group.groupId != item.data.group) {
  1299. var oldGroup = item.parent;
  1300. oldGroup.remove(item);
  1301. oldGroup.order();
  1302. group.add(item);
  1303. group.order();
  1304. item.data.group = group.groupId;
  1305. }
  1306. };
  1307. /**
  1308. * End of dragging selected items
  1309. * @param {Event} event
  1310. * @private
  1311. */
  1312. ItemSet.prototype._onDragEnd = function (event) {
  1313. if (this.touchParams.itemProps) {
  1314. event.stopPropagation();
  1315. var me = this;
  1316. var dataset = this.itemsData.getDataSet();
  1317. var itemProps = this.touchParams.itemProps ;
  1318. this.touchParams.itemProps = null;
  1319. this.touchParams.itemIsDragging = false;
  1320. itemProps.forEach(function (props) {
  1321. var id = props.item.id;
  1322. var exists = me.itemsData.get(id, me.itemOptions) != null;
  1323. if (!exists) {
  1324. // add a new item
  1325. me.options.onAdd(props.item.data, function (itemData) {
  1326. me._removeItem(props.item); // remove temporary item
  1327. if (itemData) {
  1328. me.itemsData.getDataSet().add(itemData);
  1329. }
  1330. // force re-stacking of all items next redraw
  1331. me.stackDirty = true;
  1332. me.body.emitter.emit('_change');
  1333. });
  1334. }
  1335. else {
  1336. // update existing item
  1337. var itemData = this._cloneItemData(props.item.data); // convert start and end to the correct type
  1338. me.options.onMove(itemData, function (itemData) {
  1339. if (itemData) {
  1340. // apply changes
  1341. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1342. dataset.update(itemData);
  1343. }
  1344. else {
  1345. // restore original values
  1346. props.item.setData(props.data);
  1347. me.stackDirty = true; // force re-stacking of all items next redraw
  1348. me.body.emitter.emit('_change');
  1349. }
  1350. });
  1351. }
  1352. }.bind(this));
  1353. }
  1354. };
  1355. ItemSet.prototype._onGroupDragStart = function (event) {
  1356. if (this.options.groupEditable.order) {
  1357. this.groupTouchParams.group = this.groupFromTarget(event);
  1358. if (this.groupTouchParams.group) {
  1359. event.stopPropagation();
  1360. this.groupTouchParams.originalOrder = this.groupsData.getIds({
  1361. order: this.options.groupOrder
  1362. });
  1363. }
  1364. }
  1365. }
  1366. ItemSet.prototype._onGroupDrag = function (event) {
  1367. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1368. event.stopPropagation();
  1369. // drag from one group to another
  1370. var group = this.groupFromTarget(event);
  1371. // try to avoid toggling when groups differ in height
  1372. if (group && group.height != this.groupTouchParams.group.height) {
  1373. var movingUp = (group.top < this.groupTouchParams.group.top);
  1374. var clientY = event.center ? event.center.y : event.clientY;
  1375. var targetGroupTop = util.getAbsoluteTop(group.dom.foreground);
  1376. var draggedGroupHeight = this.groupTouchParams.group.height;
  1377. if (movingUp) {
  1378. // skip swapping the groups when the dragged group is not below clientY afterwards
  1379. if (targetGroupTop + draggedGroupHeight < clientY) {
  1380. return;
  1381. }
  1382. } else {
  1383. var targetGroupHeight = group.height;
  1384. // skip swapping the groups when the dragged group is not below clientY afterwards
  1385. if (targetGroupTop + targetGroupHeight - draggedGroupHeight > clientY) {
  1386. return;
  1387. }
  1388. }
  1389. }
  1390. if (group && group != this.groupTouchParams.group) {
  1391. var groupsData = this.groupsData;
  1392. var targetGroup = groupsData.get(group.groupId);
  1393. var draggedGroup = groupsData.get(this.groupTouchParams.group.groupId);
  1394. // switch groups
  1395. if (draggedGroup && targetGroup) {
  1396. this.options.groupOrderSwap(draggedGroup, targetGroup, this.groupsData);
  1397. this.groupsData.update(draggedGroup);
  1398. this.groupsData.update(targetGroup);
  1399. }
  1400. // fetch current order of groups
  1401. var newOrder = this.groupsData.getIds({
  1402. order: this.options.groupOrder
  1403. });
  1404. // in case of changes since _onGroupDragStart
  1405. if (!util.equalArray(newOrder, this.groupTouchParams.originalOrder)) {
  1406. var groupsData = this.groupsData;
  1407. var origOrder = this.groupTouchParams.originalOrder;
  1408. var draggedId = this.groupTouchParams.group.groupId;
  1409. var numGroups = Math.min(origOrder.length, newOrder.length);
  1410. var curPos = 0;
  1411. var newOffset = 0;
  1412. var orgOffset = 0;
  1413. while (curPos < numGroups) {
  1414. // as long as the groups are where they should be step down along the groups order
  1415. while ((curPos+newOffset) < numGroups
  1416. && (curPos+orgOffset) < numGroups
  1417. && newOrder[curPos+newOffset] == origOrder[curPos+orgOffset]) {
  1418. curPos++;
  1419. }
  1420. // all ok
  1421. if (curPos+newOffset >= numGroups) {
  1422. break;
  1423. }
  1424. // not all ok
  1425. // if dragged group was move upwards everything below should have an offset
  1426. if (newOrder[curPos+newOffset] == draggedId) {
  1427. newOffset = 1;
  1428. continue;
  1429. }
  1430. // if dragged group was move downwards everything above should have an offset
  1431. else if (origOrder[curPos+orgOffset] == draggedId) {
  1432. orgOffset = 1;
  1433. continue;
  1434. }
  1435. // found a group (apart from dragged group) that has the wrong position -> switch with the
  1436. // group at the position where other one should be, fix index arrays and continue
  1437. else {
  1438. var slippedPosition = newOrder.indexOf(origOrder[curPos+orgOffset])
  1439. var switchGroup = groupsData.get(newOrder[curPos+newOffset]);
  1440. var shouldBeGroup = groupsData.get(origOrder[curPos+orgOffset]);
  1441. this.options.groupOrderSwap(switchGroup, shouldBeGroup, groupsData);
  1442. groupsData.update(switchGroup);
  1443. groupsData.update(shouldBeGroup);
  1444. var switchGroupId = newOrder[curPos+newOffset];
  1445. newOrder[curPos+newOffset] = origOrder[curPos+orgOffset];
  1446. newOrder[slippedPosition] = switchGroupId;
  1447. curPos++;
  1448. }
  1449. }
  1450. }
  1451. }
  1452. }
  1453. }
  1454. ItemSet.prototype._onGroupDragEnd = function (event) {
  1455. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1456. event.stopPropagation();
  1457. // update existing group
  1458. var me = this;
  1459. var id = me.groupTouchParams.group.groupId;
  1460. var dataset = me.groupsData.getDataSet();
  1461. var groupData = util.extend({}, dataset.get(id)); // clone the data
  1462. me.options.onMoveGroup(groupData, function (groupData) {
  1463. if (groupData) {
  1464. // apply changes
  1465. groupData[dataset._fieldId] = id; // ensure the group contains its id (can be undefined)
  1466. dataset.update(groupData);
  1467. }
  1468. else {
  1469. // fetch current order of groups
  1470. var newOrder = dataset.getIds({
  1471. order: me.options.groupOrder
  1472. });
  1473. // restore original order
  1474. if (!util.equalArray(newOrder, me.groupTouchParams.originalOrder)) {
  1475. var origOrder = me.groupTouchParams.originalOrder;
  1476. var numGroups = Math.min(origOrder.length, newOrder.length);
  1477. var curPos = 0;
  1478. while (curPos < numGroups) {
  1479. // as long as the groups are where they should be step down along the groups order
  1480. while (curPos < numGroups && newOrder[curPos] == origOrder[curPos]) {
  1481. curPos++;
  1482. }
  1483. // all ok
  1484. if (curPos >= numGroups) {
  1485. break;
  1486. }
  1487. // found a group that has the wrong position -> switch with the
  1488. // group at the position where other one should be, fix index arrays and continue
  1489. var slippedPosition = newOrder.indexOf(origOrder[curPos])
  1490. var switchGroup = dataset.get(newOrder[curPos]);
  1491. var shouldBeGroup = dataset.get(origOrder[curPos]);
  1492. me.options.groupOrderSwap(switchGroup, shouldBeGroup, dataset);
  1493. groupsData.update(switchGroup);
  1494. groupsData.update(shouldBeGroup);
  1495. var switchGroupId = newOrder[curPos];
  1496. newOrder[curPos] = origOrder[curPos];
  1497. newOrder[slippedPosition] = switchGroupId;
  1498. curPos++;
  1499. }
  1500. }
  1501. }
  1502. });
  1503. me.body.emitter.emit('groupDragged', { groupId: id });
  1504. }
  1505. }
  1506. /**
  1507. * Handle selecting/deselecting an item when tapping it
  1508. * @param {Event} event
  1509. * @private
  1510. */
  1511. ItemSet.prototype._onSelectItem = function (event) {
  1512. if (!this.options.selectable) return;
  1513. var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey);
  1514. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  1515. if (ctrlKey || shiftKey) {
  1516. this._onMultiSelectItem(event);
  1517. return;
  1518. }
  1519. var oldSelection = this.getSelection();
  1520. var item = this.itemFromTarget(event);
  1521. var selection = item ? [item.id] : [];
  1522. this.setSelection(selection);
  1523. var newSelection = this.getSelection();
  1524. // emit a select event,
  1525. // except when old selection is empty and new selection is still empty
  1526. if (newSelection.length > 0 || oldSelection.length > 0) {
  1527. this.body.emitter.emit('select', {
  1528. items: newSelection,
  1529. event: event
  1530. });
  1531. }
  1532. };
  1533. /**
  1534. * Handle hovering an item
  1535. * @param {Event} event
  1536. * @private
  1537. */
  1538. ItemSet.prototype._onMouseOver = function (event) {
  1539. var item = this.itemFromTarget(event);
  1540. if (!item) return;
  1541. this.body.emitter.emit('itemover', {
  1542. item: item.id,
  1543. event: event
  1544. });
  1545. };
  1546. ItemSet.prototype._onMouseOut = function (event) {
  1547. var item = this.itemFromTarget(event);
  1548. if (!item) return;
  1549. this.body.emitter.emit('itemout', {
  1550. item: item.id,
  1551. event: event
  1552. });
  1553. };
  1554. /**
  1555. * Handle updates of an item on double tap
  1556. * @param event
  1557. * @private
  1558. */
  1559. ItemSet.prototype._onUpdateItem = function (item) {
  1560. if (!this.options.selectable) return;
  1561. if (!this.options.editable.add) return;
  1562. var me = this;
  1563. if (item) {
  1564. // execute async handler to update the item (or cancel it)
  1565. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  1566. this.options.onUpdate(itemData, function (itemData) {
  1567. if (itemData) {
  1568. me.itemsData.getDataSet().update(itemData);
  1569. }
  1570. });
  1571. }
  1572. }
  1573. /**
  1574. * Handle creation of an item on double tap
  1575. * @param event
  1576. * @private
  1577. */
  1578. ItemSet.prototype._onAddItem = function (event) {
  1579. if (!this.options.selectable) return;
  1580. if (!this.options.editable.add) return;
  1581. var me = this;
  1582. var snap = this.options.snap || null;
  1583. var item = this.itemFromTarget(event);
  1584. if (!item) {
  1585. // add item
  1586. if (this.options.rtl) {
  1587. var xAbs = util.getAbsoluteRight(this.dom.frame);
  1588. var x = xAbs - event.center.x;
  1589. } else {
  1590. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1591. var x = event.center.x - xAbs;
  1592. }
  1593. // var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1594. // var x = event.center.x - xAbs;
  1595. var start = this.body.util.toTime(x);
  1596. var scale = this.body.util.getScale();
  1597. var step = this.body.util.getStep();
  1598. var newItemData = {
  1599. start: snap ? snap(start, scale, step) : start,
  1600. content: 'new item'
  1601. };
  1602. if (event.type == 'drop') {
  1603. var itemData = JSON.parse(event.dataTransfer.getData("text/plain"))
  1604. newItemData.content = itemData.content; // content is required
  1605. newItemData.type = itemData.type || 'box';
  1606. newItemData[this.itemsData._fieldId] = itemData.id || util.randomUUID();
  1607. if (itemData.type == 'range' || (itemData.end && itemData.start)) {
  1608. if (!itemData.end) {
  1609. var end = this.body.util.toTime(x + this.props.width / 5);
  1610. newItemData.end = snap ? snap(end, scale, step) : end;
  1611. } else {
  1612. newItemData.end = new Date(newItemData.start._i).getTime() + new Date(itemData.end).getTime() - new Date(itemData.start).getTime();
  1613. }
  1614. }
  1615. } else {
  1616. newItemData[this.itemsData._fieldId] = util.randomUUID();
  1617. // when default type is a range, add a default end date to the new item
  1618. if (this.options.type === 'range') {
  1619. var end = this.body.util.toTime(x + this.props.width / 5);
  1620. newItemData.end = snap ? snap(end, scale, step) : end;
  1621. }
  1622. }
  1623. var group = this.groupFromTarget(event);
  1624. if (group) {
  1625. newItemData.group = group.groupId;
  1626. }
  1627. // execute async handler to customize (or cancel) adding an item
  1628. newItemData = this._cloneItemData(newItemData); // convert start and end to the correct type
  1629. this.options.onAdd(newItemData, function (item) {
  1630. if (item) {
  1631. me.itemsData.getDataSet().add(item);
  1632. if (event.type == 'drop') {
  1633. me.setSelection([item.id]);
  1634. }
  1635. // TODO: need to trigger a redraw?
  1636. }
  1637. });
  1638. }
  1639. };
  1640. /**
  1641. * Handle selecting/deselecting multiple items when holding an item
  1642. * @param {Event} event
  1643. * @private
  1644. */
  1645. ItemSet.prototype._onMultiSelectItem = function (event) {
  1646. if (!this.options.selectable) return;
  1647. var item = this.itemFromTarget(event);
  1648. if (item) {
  1649. // multi select items (if allowed)
  1650. var selection = this.options.multiselect
  1651. ? this.getSelection() // take current selection
  1652. : []; // deselect current selection
  1653. var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false;
  1654. if (shiftKey && this.options.multiselect) {
  1655. // select all items between the old selection and the tapped item
  1656. var itemGroup = this.itemsData.get(item.id).group;
  1657. // when filtering get the group of the last selected item
  1658. var lastSelectedGroup = undefined;
  1659. if (this.options.multiselectPerGroup) {
  1660. if (selection.length > 0) {
  1661. lastSelectedGroup = this.itemsData.get(selection[0]).group;
  1662. }
  1663. }
  1664. // determine the selection range
  1665. if (!this.options.multiselectPerGroup || lastSelectedGroup == undefined || lastSelectedGroup == itemGroup) {
  1666. selection.push(item.id);
  1667. }
  1668. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  1669. if (!this.options.multiselectPerGroup || lastSelectedGroup == itemGroup) {
  1670. // select all items within the selection range
  1671. selection = [];
  1672. for (var id in this.items) {
  1673. if (this.items.hasOwnProperty(id)) {
  1674. var _item = this.items[id];
  1675. var start = _item.data.start;
  1676. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  1677. if (start >= range.min &&
  1678. end <= range.max &&
  1679. (!this.options.multiselectPerGroup || lastSelectedGroup == this.itemsData.get(_item.id).group) &&
  1680. !(_item instanceof BackgroundItem)) {
  1681. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  1682. }
  1683. }
  1684. }
  1685. }
  1686. }
  1687. else {
  1688. // add/remove this item from the current selection
  1689. var index = selection.indexOf(item.id);
  1690. if (index == -1) {
  1691. // item is not yet selected -> select it
  1692. selection.push(item.id);
  1693. }
  1694. else {
  1695. // item is already selected -> deselect it
  1696. selection.splice(index, 1);
  1697. }
  1698. }
  1699. this.setSelection(selection);
  1700. this.body.emitter.emit('select', {
  1701. items: this.getSelection(),
  1702. event: event
  1703. });
  1704. }
  1705. };
  1706. /**
  1707. * Calculate the time range of a list of items
  1708. * @param {Array.<Object>} itemsData
  1709. * @return {{min: Date, max: Date}} Returns the range of the provided items
  1710. * @private
  1711. */
  1712. ItemSet._getItemRange = function(itemsData) {
  1713. var max = null;
  1714. var min = null;
  1715. itemsData.forEach(function (data) {
  1716. if (min == null || data.start < min) {
  1717. min = data.start;
  1718. }
  1719. if (data.end != undefined) {
  1720. if (max == null || data.end > max) {
  1721. max = data.end;
  1722. }
  1723. }
  1724. else {
  1725. if (max == null || data.start > max) {
  1726. max = data.start;
  1727. }
  1728. }
  1729. });
  1730. return {
  1731. min: min,
  1732. max: max
  1733. }
  1734. };
  1735. /**
  1736. * Find an item from an event target:
  1737. * searches for the attribute 'timeline-item' in the event target's element tree
  1738. * @param {Event} event
  1739. * @return {Item | null} item
  1740. */
  1741. ItemSet.prototype.itemFromTarget = function(event) {
  1742. var target = event.target;
  1743. while (target) {
  1744. if (target.hasOwnProperty('timeline-item')) {
  1745. return target['timeline-item'];
  1746. }
  1747. target = target.parentNode;
  1748. }
  1749. return null;
  1750. };
  1751. /**
  1752. * Find the Group from an event target:
  1753. * searches for the attribute 'timeline-group' in the event target's element tree
  1754. * @param {Event} event
  1755. * @return {Group | null} group
  1756. */
  1757. ItemSet.prototype.groupFromTarget = function(event) {
  1758. var clientY = event.center ? event.center.y : event.clientY;
  1759. for (var i = 0; i < this.groupIds.length; i++) {
  1760. var groupId = this.groupIds[i];
  1761. var group = this.groups[groupId];
  1762. var foreground = group.dom.foreground;
  1763. var top = util.getAbsoluteTop(foreground);
  1764. if (clientY > top && clientY < top + foreground.offsetHeight) {
  1765. return group;
  1766. }
  1767. if (this.options.orientation.item === 'top') {
  1768. if (i === this.groupIds.length - 1 && clientY > top) {
  1769. return group;
  1770. }
  1771. }
  1772. else {
  1773. if (i === 0 && clientY < top + foreground.offset) {
  1774. return group;
  1775. }
  1776. }
  1777. }
  1778. return null;
  1779. };
  1780. /**
  1781. * Find the ItemSet from an event target:
  1782. * searches for the attribute 'timeline-itemset' in the event target's element tree
  1783. * @param {Event} event
  1784. * @return {ItemSet | null} item
  1785. */
  1786. ItemSet.itemSetFromTarget = function(event) {
  1787. var target = event.target;
  1788. while (target) {
  1789. if (target.hasOwnProperty('timeline-itemset')) {
  1790. return target['timeline-itemset'];
  1791. }
  1792. target = target.parentNode;
  1793. }
  1794. return null;
  1795. };
  1796. /**
  1797. * Clone the data of an item, and "normalize" it: convert the start and end date
  1798. * to the type (Date, Moment, ...) configured in the DataSet. If not configured,
  1799. * start and end are converted to Date.
  1800. * @param {Object} itemData, typically `item.data`
  1801. * @param {string} [type] Optional Date type. If not provided, the type from the DataSet is taken
  1802. * @return {Object} The cloned object
  1803. * @private
  1804. */
  1805. ItemSet.prototype._cloneItemData = function (itemData, type) {
  1806. var clone = util.extend({}, itemData);
  1807. if (!type) {
  1808. // convert start and end date to the type (Date, Moment, ...) configured in the DataSet
  1809. type = this.itemsData.getDataSet()._options.type;
  1810. }
  1811. if (clone.start != undefined) {
  1812. clone.start = util.convert(clone.start, type && type.start || 'Date');
  1813. }
  1814. if (clone.end != undefined) {
  1815. clone.end = util.convert(clone.end , type && type.end || 'Date');
  1816. }
  1817. return clone;
  1818. };
  1819. module.exports = ItemSet;