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.

2102 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_VERTICAL});
  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. this.initialItemSetDrawn = true;
  571. // check if this component is resized
  572. resized = this._isResized() || resized;
  573. return resized;
  574. };
  575. /**
  576. * Get the first group, aligned with the axis
  577. * @return {Group | null} firstGroup
  578. * @private
  579. */
  580. ItemSet.prototype._firstGroup = function() {
  581. var firstGroupIndex = (this.options.orientation.item == 'top') ? 0 : (this.groupIds.length - 1);
  582. var firstGroupId = this.groupIds[firstGroupIndex];
  583. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  584. return firstGroup || null;
  585. };
  586. /**
  587. * Create or delete the group holding all ungrouped items. This group is used when
  588. * there are no groups specified.
  589. * @protected
  590. */
  591. ItemSet.prototype._updateUngrouped = function() {
  592. var ungrouped = this.groups[UNGROUPED];
  593. var background = this.groups[BACKGROUND];
  594. var item, itemId;
  595. if (this.groupsData) {
  596. // remove the group holding all ungrouped items
  597. if (ungrouped) {
  598. ungrouped.hide();
  599. delete this.groups[UNGROUPED];
  600. for (itemId in this.items) {
  601. if (this.items.hasOwnProperty(itemId)) {
  602. item = this.items[itemId];
  603. item.parent && item.parent.remove(item);
  604. var groupId = this._getGroupId(item.data);
  605. var group = this.groups[groupId];
  606. group && group.add(item) || item.hide();
  607. }
  608. }
  609. }
  610. }
  611. else {
  612. // create a group holding all (unfiltered) items
  613. if (!ungrouped) {
  614. var id = null;
  615. var data = null;
  616. ungrouped = new Group(id, data, this);
  617. this.groups[UNGROUPED] = ungrouped;
  618. for (itemId in this.items) {
  619. if (this.items.hasOwnProperty(itemId)) {
  620. item = this.items[itemId];
  621. ungrouped.add(item);
  622. }
  623. }
  624. ungrouped.show();
  625. }
  626. }
  627. };
  628. /**
  629. * Get the element for the labelset
  630. * @return {HTMLElement} labelSet
  631. */
  632. ItemSet.prototype.getLabelSet = function() {
  633. return this.dom.labelSet;
  634. };
  635. /**
  636. * Set items
  637. * @param {vis.DataSet | null} items
  638. */
  639. ItemSet.prototype.setItems = function(items) {
  640. var me = this,
  641. ids,
  642. oldItemsData = this.itemsData;
  643. // replace the dataset
  644. if (!items) {
  645. this.itemsData = null;
  646. }
  647. else if (items instanceof DataSet || items instanceof DataView) {
  648. this.itemsData = items;
  649. }
  650. else {
  651. throw new TypeError('Data must be an instance of DataSet or DataView');
  652. }
  653. if (oldItemsData) {
  654. // unsubscribe from old dataset
  655. util.forEach(this.itemListeners, function (callback, event) {
  656. oldItemsData.off(event, callback);
  657. });
  658. // remove all drawn items
  659. ids = oldItemsData.getIds();
  660. this._onRemove(ids);
  661. }
  662. if (this.itemsData) {
  663. // subscribe to new dataset
  664. var id = this.id;
  665. util.forEach(this.itemListeners, function (callback, event) {
  666. me.itemsData.on(event, callback, id);
  667. });
  668. // add all new items
  669. ids = this.itemsData.getIds();
  670. this._onAdd(ids);
  671. // update the group holding all ungrouped items
  672. this._updateUngrouped();
  673. }
  674. this.body.emitter.emit('_change', {queue: true});
  675. };
  676. /**
  677. * Get the current items
  678. * @returns {vis.DataSet | null}
  679. */
  680. ItemSet.prototype.getItems = function() {
  681. return this.itemsData;
  682. };
  683. /**
  684. * Set groups
  685. * @param {vis.DataSet} groups
  686. */
  687. ItemSet.prototype.setGroups = function(groups) {
  688. var me = this,
  689. ids;
  690. // unsubscribe from current dataset
  691. if (this.groupsData) {
  692. util.forEach(this.groupListeners, function (callback, event) {
  693. me.groupsData.off(event, callback);
  694. });
  695. // remove all drawn groups
  696. ids = this.groupsData.getIds();
  697. this.groupsData = null;
  698. this._onRemoveGroups(ids); // note: this will cause a redraw
  699. }
  700. // replace the dataset
  701. if (!groups) {
  702. this.groupsData = null;
  703. }
  704. else if (groups instanceof DataSet || groups instanceof DataView) {
  705. this.groupsData = groups;
  706. }
  707. else {
  708. throw new TypeError('Data must be an instance of DataSet or DataView');
  709. }
  710. if (this.groupsData) {
  711. // subscribe to new dataset
  712. var id = this.id;
  713. util.forEach(this.groupListeners, function (callback, event) {
  714. me.groupsData.on(event, callback, id);
  715. });
  716. // draw all ms
  717. ids = this.groupsData.getIds();
  718. this._onAddGroups(ids);
  719. }
  720. // update the group holding all ungrouped items
  721. this._updateUngrouped();
  722. // update the order of all items in each group
  723. this._order();
  724. this.body.emitter.emit('_change', {queue: true});
  725. };
  726. /**
  727. * Get the current groups
  728. * @returns {vis.DataSet | null} groups
  729. */
  730. ItemSet.prototype.getGroups = function() {
  731. return this.groupsData;
  732. };
  733. /**
  734. * Remove an item by its id
  735. * @param {String | Number} id
  736. */
  737. ItemSet.prototype.removeItem = function(id) {
  738. var item = this.itemsData.get(id),
  739. dataset = this.itemsData.getDataSet();
  740. if (item) {
  741. // confirm deletion
  742. this.options.onRemove(item, function (item) {
  743. if (item) {
  744. // remove by id here, it is possible that an item has no id defined
  745. // itself, so better not delete by the item itself
  746. dataset.remove(id);
  747. }
  748. });
  749. }
  750. };
  751. /**
  752. * Get the time of an item based on it's data and options.type
  753. * @param {Object} itemData
  754. * @returns {string} Returns the type
  755. * @private
  756. */
  757. ItemSet.prototype._getType = function (itemData) {
  758. return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
  759. };
  760. /**
  761. * Get the group id for an item
  762. * @param {Object} itemData
  763. * @returns {string} Returns the groupId
  764. * @private
  765. */
  766. ItemSet.prototype._getGroupId = function (itemData) {
  767. var type = this._getType(itemData);
  768. if (type == 'background' && itemData.group == undefined) {
  769. return BACKGROUND;
  770. }
  771. else {
  772. return this.groupsData ? itemData.group : UNGROUPED;
  773. }
  774. };
  775. /**
  776. * Handle updated items
  777. * @param {Number[]} ids
  778. * @protected
  779. */
  780. ItemSet.prototype._onUpdate = function(ids) {
  781. var me = this;
  782. ids.forEach(function (id) {
  783. var itemData = me.itemsData.get(id, me.itemOptions);
  784. var item = me.items[id];
  785. var type = itemData ? me._getType(itemData) : null;
  786. var constructor = ItemSet.types[type];
  787. var selected;
  788. if (item) {
  789. // update item
  790. if (!constructor || !(item instanceof constructor)) {
  791. // item type has changed, delete the item and recreate it
  792. selected = item.selected; // preserve selection of this item
  793. me._removeItem(item);
  794. item = null;
  795. }
  796. else {
  797. me._updateItem(item, itemData);
  798. }
  799. }
  800. if (!item && itemData) {
  801. // create item
  802. if (constructor) {
  803. item = new constructor(itemData, me.conversion, me.options);
  804. item.id = id; // TODO: not so nice setting id afterwards
  805. me._addItem(item);
  806. if (selected) {
  807. this.selection.push(id);
  808. item.select();
  809. }
  810. }
  811. else if (type == 'rangeoverflow') {
  812. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  813. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
  814. '.vis-item.vis-range .vis-item-content {overflow: visible;}');
  815. }
  816. else {
  817. throw new TypeError('Unknown item type "' + type + '"');
  818. }
  819. }
  820. }.bind(this));
  821. this._order();
  822. this.stackDirty = true; // force re-stacking of all items next redraw
  823. this.body.emitter.emit('_change', {queue: true});
  824. };
  825. /**
  826. * Handle added items
  827. * @param {Number[]} ids
  828. * @protected
  829. */
  830. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  831. /**
  832. * Handle removed items
  833. * @param {Number[]} ids
  834. * @protected
  835. */
  836. ItemSet.prototype._onRemove = function(ids) {
  837. var count = 0;
  838. var me = this;
  839. ids.forEach(function (id) {
  840. var item = me.items[id];
  841. if (item) {
  842. count++;
  843. me._removeItem(item);
  844. }
  845. });
  846. if (count) {
  847. // update order
  848. this._order();
  849. this.stackDirty = true; // force re-stacking of all items next redraw
  850. this.body.emitter.emit('_change', {queue: true});
  851. }
  852. };
  853. /**
  854. * Update the order of item in all groups
  855. * @private
  856. */
  857. ItemSet.prototype._order = function() {
  858. // reorder the items in all groups
  859. // TODO: optimization: only reorder groups affected by the changed items
  860. util.forEach(this.groups, function (group) {
  861. group.order();
  862. });
  863. };
  864. /**
  865. * Handle updated groups
  866. * @param {Number[]} ids
  867. * @private
  868. */
  869. ItemSet.prototype._onUpdateGroups = function(ids) {
  870. this._onAddGroups(ids);
  871. };
  872. /**
  873. * Handle changed groups (added or updated)
  874. * @param {Number[]} ids
  875. * @private
  876. */
  877. ItemSet.prototype._onAddGroups = function(ids) {
  878. var me = this;
  879. ids.forEach(function (id) {
  880. var groupData = me.groupsData.get(id);
  881. var group = me.groups[id];
  882. if (!group) {
  883. // check for reserved ids
  884. if (id == UNGROUPED || id == BACKGROUND) {
  885. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  886. }
  887. var groupOptions = Object.create(me.options);
  888. util.extend(groupOptions, {
  889. height: null
  890. });
  891. group = new Group(id, groupData, me);
  892. me.groups[id] = group;
  893. // add items with this groupId to the new group
  894. for (var itemId in me.items) {
  895. if (me.items.hasOwnProperty(itemId)) {
  896. var item = me.items[itemId];
  897. if (item.data.group == id) {
  898. group.add(item);
  899. }
  900. }
  901. }
  902. group.order();
  903. group.show();
  904. }
  905. else {
  906. // update group
  907. group.setData(groupData);
  908. }
  909. });
  910. this.body.emitter.emit('_change', {queue: true});
  911. };
  912. /**
  913. * Handle removed groups
  914. * @param {Number[]} ids
  915. * @private
  916. */
  917. ItemSet.prototype._onRemoveGroups = function(ids) {
  918. var groups = this.groups;
  919. ids.forEach(function (id) {
  920. var group = groups[id];
  921. if (group) {
  922. group.hide();
  923. delete groups[id];
  924. }
  925. });
  926. this.markDirty();
  927. this.body.emitter.emit('_change', {queue: true});
  928. };
  929. /**
  930. * Reorder the groups if needed
  931. * @return {boolean} changed
  932. * @private
  933. */
  934. ItemSet.prototype._orderGroups = function () {
  935. if (this.groupsData) {
  936. // reorder the groups
  937. var groupIds = this.groupsData.getIds({
  938. order: this.options.groupOrder
  939. });
  940. var changed = !util.equalArray(groupIds, this.groupIds);
  941. if (changed) {
  942. // hide all groups, removes them from the DOM
  943. var groups = this.groups;
  944. groupIds.forEach(function (groupId) {
  945. groups[groupId].hide();
  946. });
  947. // show the groups again, attach them to the DOM in correct order
  948. groupIds.forEach(function (groupId) {
  949. groups[groupId].show();
  950. });
  951. this.groupIds = groupIds;
  952. }
  953. return changed;
  954. }
  955. else {
  956. return false;
  957. }
  958. };
  959. /**
  960. * Add a new item
  961. * @param {Item} item
  962. * @private
  963. */
  964. ItemSet.prototype._addItem = function(item) {
  965. this.items[item.id] = item;
  966. // add to group
  967. var groupId = this._getGroupId(item.data);
  968. var group = this.groups[groupId];
  969. if (group) group.add(item);
  970. };
  971. /**
  972. * Update an existing item
  973. * @param {Item} item
  974. * @param {Object} itemData
  975. * @private
  976. */
  977. ItemSet.prototype._updateItem = function(item, itemData) {
  978. var oldGroupId = item.data.group;
  979. var oldSubGroupId = item.data.subgroup;
  980. // update the items data (will redraw the item when displayed)
  981. item.setData(itemData);
  982. // update group
  983. if (oldGroupId != item.data.group || oldSubGroupId != item.data.subgroup) {
  984. var oldGroup = this.groups[oldGroupId];
  985. if (oldGroup) oldGroup.remove(item);
  986. var groupId = this._getGroupId(item.data);
  987. var group = this.groups[groupId];
  988. if (group) group.add(item);
  989. }
  990. };
  991. /**
  992. * Delete an item from the ItemSet: remove it from the DOM, from the map
  993. * with items, and from the map with visible items, and from the selection
  994. * @param {Item} item
  995. * @private
  996. */
  997. ItemSet.prototype._removeItem = function(item) {
  998. // remove from DOM
  999. item.hide();
  1000. // remove from items
  1001. delete this.items[item.id];
  1002. // remove from selection
  1003. var index = this.selection.indexOf(item.id);
  1004. if (index != -1) this.selection.splice(index, 1);
  1005. // remove from group
  1006. item.parent && item.parent.remove(item);
  1007. };
  1008. /**
  1009. * Create an array containing all items being a range (having an end date)
  1010. * @param array
  1011. * @returns {Array}
  1012. * @private
  1013. */
  1014. ItemSet.prototype._constructByEndArray = function(array) {
  1015. var endArray = [];
  1016. for (var i = 0; i < array.length; i++) {
  1017. if (array[i] instanceof RangeItem) {
  1018. endArray.push(array[i]);
  1019. }
  1020. }
  1021. return endArray;
  1022. };
  1023. /**
  1024. * Register the clicked item on touch, before dragStart is initiated.
  1025. *
  1026. * dragStart is initiated from a mousemove event, AFTER the mouse/touch is
  1027. * already moving. Therefore, the mouse/touch can sometimes be above an other
  1028. * DOM element than the item itself.
  1029. *
  1030. * @param {Event} event
  1031. * @private
  1032. */
  1033. ItemSet.prototype._onTouch = function (event) {
  1034. // store the touched item, used in _onDragStart
  1035. this.touchParams.item = this.itemFromTarget(event);
  1036. this.touchParams.dragLeftItem = event.target.dragLeftItem || false;
  1037. this.touchParams.dragRightItem = event.target.dragRightItem || false;
  1038. this.touchParams.itemProps = null;
  1039. };
  1040. /**
  1041. * Given an group id, returns the index it has.
  1042. *
  1043. * @param {Number} groupID
  1044. * @private
  1045. */
  1046. ItemSet.prototype._getGroupIndex = function(groupId) {
  1047. for (var i = 0; i < this.groupIds.length; i++) {
  1048. if (groupId == this.groupIds[i])
  1049. return i;
  1050. }
  1051. };
  1052. /**
  1053. * Start dragging the selected events
  1054. * @param {Event} event
  1055. * @private
  1056. */
  1057. ItemSet.prototype._onDragStart = function (event) {
  1058. var item = this.touchParams.item || null;
  1059. var me = this;
  1060. var props;
  1061. if (item && (item.selected || this.options.itemsAlwaysDraggable)) {
  1062. if (this.options.editable.overrideItems &&
  1063. !this.options.editable.updateTime &&
  1064. !this.options.editable.updateGroup) {
  1065. return;
  1066. }
  1067. // override options.editable
  1068. if ((item.editable != null && !item.editable.updateTime && !item.editable.updateGroup)
  1069. && !this.options.editable.overrideItems) {
  1070. return;
  1071. }
  1072. var dragLeftItem = this.touchParams.dragLeftItem;
  1073. var dragRightItem = this.touchParams.dragRightItem;
  1074. this.touchParams.itemIsDragging = true;
  1075. if (dragLeftItem) {
  1076. props = {
  1077. item: dragLeftItem,
  1078. initialX: event.center.x,
  1079. dragLeft: true,
  1080. data: this._cloneItemData(item.data)
  1081. };
  1082. this.touchParams.itemProps = [props];
  1083. }
  1084. else if (dragRightItem) {
  1085. props = {
  1086. item: dragRightItem,
  1087. initialX: event.center.x,
  1088. dragRight: true,
  1089. data: this._cloneItemData(item.data)
  1090. };
  1091. this.touchParams.itemProps = [props];
  1092. }
  1093. else {
  1094. this.touchParams.selectedItem = item;
  1095. var baseGroupIndex = this._getGroupIndex(item.data.group);
  1096. var itemsToDrag = (this.options.itemsAlwaysDraggable && !item.selected) ? [item.id] : this.getSelection();
  1097. this.touchParams.itemProps = itemsToDrag.map(function (id) {
  1098. var item = me.items[id];
  1099. var groupIndex = me._getGroupIndex(item.data.group);
  1100. return {
  1101. item: item,
  1102. initialX: event.center.x,
  1103. groupOffset: baseGroupIndex-groupIndex,
  1104. data: this._cloneItemData(item.data)
  1105. };
  1106. }.bind(this));
  1107. }
  1108. event.stopPropagation();
  1109. }
  1110. else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  1111. // create a new range item when dragging with ctrl key down
  1112. this._onDragStartAddItem(event);
  1113. }
  1114. };
  1115. /**
  1116. * Start creating a new range item by dragging.
  1117. * @param {Event} event
  1118. * @private
  1119. */
  1120. ItemSet.prototype._onDragStartAddItem = function (event) {
  1121. var snap = this.options.snap || null;
  1122. if (this.options.rtl) {
  1123. var xAbs = util.getAbsoluteRight(this.dom.frame);
  1124. var x = xAbs - event.center.x + 10; // plus 10 to compensate for the drag starting as soon as you've moved 10px
  1125. } else {
  1126. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1127. var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  1128. }
  1129. var time = this.body.util.toTime(x);
  1130. var scale = this.body.util.getScale();
  1131. var step = this.body.util.getStep();
  1132. var start = snap ? snap(time, scale, step) : time;
  1133. var end = start;
  1134. var itemData = {
  1135. type: 'range',
  1136. start: start,
  1137. end: end,
  1138. content: 'new item'
  1139. };
  1140. var id = util.randomUUID();
  1141. itemData[this.itemsData._fieldId] = id;
  1142. var group = this.groupFromTarget(event);
  1143. if (group) {
  1144. itemData.group = group.groupId;
  1145. }
  1146. var newItem = new RangeItem(itemData, this.conversion, this.options);
  1147. newItem.id = id; // TODO: not so nice setting id afterwards
  1148. newItem.data = this._cloneItemData(itemData);
  1149. this._addItem(newItem);
  1150. var props = {
  1151. item: newItem,
  1152. initialX: event.center.x,
  1153. data: newItem.data
  1154. };
  1155. if (this.options.rtl) {
  1156. props.dragLeft = true;
  1157. } else {
  1158. props.dragRight = true;
  1159. }
  1160. this.touchParams.itemProps = [props];
  1161. event.stopPropagation();
  1162. };
  1163. /**
  1164. * Drag selected items
  1165. * @param {Event} event
  1166. * @private
  1167. */
  1168. ItemSet.prototype._onDrag = function (event) {
  1169. if (this.touchParams.itemProps) {
  1170. event.stopPropagation();
  1171. var me = this;
  1172. var snap = this.options.snap || null;
  1173. if (this.options.rtl) {
  1174. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.right.width;
  1175. } else {
  1176. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  1177. }
  1178. var scale = this.body.util.getScale();
  1179. var step = this.body.util.getStep();
  1180. //only calculate the new group for the item that's actually dragged
  1181. var selectedItem = this.touchParams.selectedItem;
  1182. var updateGroupAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateGroup) ||
  1183. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateGroup);
  1184. var newGroupBase = null;
  1185. if (updateGroupAllowed && selectedItem) {
  1186. if (selectedItem.data.group != undefined) {
  1187. // drag from one group to another
  1188. var group = me.groupFromTarget(event);
  1189. if (group) {
  1190. //we know the offset for all items, so the new group for all items
  1191. //will be relative to this one.
  1192. newGroupBase = this._getGroupIndex(group.groupId);
  1193. }
  1194. }
  1195. }
  1196. // move
  1197. this.touchParams.itemProps.forEach(function (props) {
  1198. var current = me.body.util.toTime(event.center.x - xOffset);
  1199. var initial = me.body.util.toTime(props.initialX - xOffset);
  1200. if (this.options.rtl) {
  1201. var offset = -(current - initial); // ms
  1202. } else {
  1203. var offset = (current - initial); // ms
  1204. }
  1205. var itemData = this._cloneItemData(props.item.data); // clone the data
  1206. if (props.item.editable != null
  1207. && !props.item.editable.updateTime
  1208. && !props.item.editable.updateGroup
  1209. && !me.options.editable.overrideItems) {
  1210. return;
  1211. }
  1212. var updateTimeAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateTime) ||
  1213. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateTime);
  1214. if (updateTimeAllowed) {
  1215. if (props.dragLeft) {
  1216. // drag left side of a range item
  1217. if (this.options.rtl) {
  1218. if (itemData.end != undefined) {
  1219. var initialEnd = util.convert(props.data.end, 'Date');
  1220. var end = new Date(initialEnd.valueOf() + offset);
  1221. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1222. itemData.end = snap ? snap(end, scale, step) : end;
  1223. }
  1224. } else {
  1225. if (itemData.start != undefined) {
  1226. var initialStart = util.convert(props.data.start, 'Date');
  1227. var start = new Date(initialStart.valueOf() + offset);
  1228. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1229. itemData.start = snap ? snap(start, scale, step) : start;
  1230. }
  1231. }
  1232. }
  1233. else if (props.dragRight) {
  1234. // drag right side of a range item
  1235. if (this.options.rtl) {
  1236. if (itemData.start != undefined) {
  1237. var initialStart = util.convert(props.data.start, 'Date');
  1238. var start = new Date(initialStart.valueOf() + offset);
  1239. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1240. itemData.start = snap ? snap(start, scale, step) : start;
  1241. }
  1242. } else {
  1243. if (itemData.end != undefined) {
  1244. var initialEnd = util.convert(props.data.end, 'Date');
  1245. var end = new Date(initialEnd.valueOf() + offset);
  1246. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1247. itemData.end = snap ? snap(end, scale, step) : end;
  1248. }
  1249. }
  1250. }
  1251. else {
  1252. // drag both start and end
  1253. if (itemData.start != undefined) {
  1254. var initialStart = util.convert(props.data.start, 'Date').valueOf();
  1255. var start = new Date(initialStart + offset);
  1256. if (itemData.end != undefined) {
  1257. var initialEnd = util.convert(props.data.end, 'Date');
  1258. var duration = initialEnd.valueOf() - initialStart.valueOf();
  1259. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1260. itemData.start = snap ? snap(start, scale, step) : start;
  1261. itemData.end = new Date(itemData.start.valueOf() + duration);
  1262. }
  1263. else {
  1264. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1265. itemData.start = snap ? snap(start, scale, step) : start;
  1266. }
  1267. }
  1268. }
  1269. }
  1270. if (updateGroupAllowed && (!props.dragLeft && !props.dragRight) && newGroupBase!=null) {
  1271. if (itemData.group != undefined) {
  1272. var newOffset = newGroupBase - props.groupOffset;
  1273. //make sure we stay in bounds
  1274. newOffset = Math.max(0, newOffset);
  1275. newOffset = Math.min(me.groupIds.length-1, newOffset);
  1276. itemData.group = me.groupIds[newOffset];
  1277. }
  1278. }
  1279. // confirm moving the item
  1280. itemData = this._cloneItemData(itemData); // convert start and end to the correct type
  1281. me.options.onMoving(itemData, function (itemData) {
  1282. if (itemData) {
  1283. props.item.setData(this._cloneItemData(itemData, 'Date'));
  1284. }
  1285. }.bind(this));
  1286. }.bind(this));
  1287. this.stackDirty = true; // force re-stacking of all items next redraw
  1288. this.body.emitter.emit('_change');
  1289. }
  1290. };
  1291. /**
  1292. * Move an item to another group
  1293. * @param {Item} item
  1294. * @param {String | Number} groupId
  1295. * @private
  1296. */
  1297. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1298. var group = this.groups[groupId];
  1299. if (group && group.groupId != item.data.group) {
  1300. var oldGroup = item.parent;
  1301. oldGroup.remove(item);
  1302. oldGroup.order();
  1303. group.add(item);
  1304. group.order();
  1305. item.data.group = group.groupId;
  1306. }
  1307. };
  1308. /**
  1309. * End of dragging selected items
  1310. * @param {Event} event
  1311. * @private
  1312. */
  1313. ItemSet.prototype._onDragEnd = function (event) {
  1314. if (this.touchParams.itemProps) {
  1315. event.stopPropagation();
  1316. var me = this;
  1317. var dataset = this.itemsData.getDataSet();
  1318. var itemProps = this.touchParams.itemProps ;
  1319. this.touchParams.itemProps = null;
  1320. this.touchParams.itemIsDragging = false;
  1321. itemProps.forEach(function (props) {
  1322. var id = props.item.id;
  1323. var exists = me.itemsData.get(id, me.itemOptions) != null;
  1324. if (!exists) {
  1325. // add a new item
  1326. me.options.onAdd(props.item.data, function (itemData) {
  1327. me._removeItem(props.item); // remove temporary item
  1328. if (itemData) {
  1329. me.itemsData.getDataSet().add(itemData);
  1330. }
  1331. // force re-stacking of all items next redraw
  1332. me.stackDirty = true;
  1333. me.body.emitter.emit('_change');
  1334. });
  1335. }
  1336. else {
  1337. // update existing item
  1338. var itemData = this._cloneItemData(props.item.data); // convert start and end to the correct type
  1339. me.options.onMove(itemData, function (itemData) {
  1340. if (itemData) {
  1341. // apply changes
  1342. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1343. dataset.update(itemData);
  1344. }
  1345. else {
  1346. // restore original values
  1347. props.item.setData(props.data);
  1348. me.stackDirty = true; // force re-stacking of all items next redraw
  1349. me.body.emitter.emit('_change');
  1350. }
  1351. });
  1352. }
  1353. }.bind(this));
  1354. }
  1355. };
  1356. ItemSet.prototype._onGroupDragStart = function (event) {
  1357. if (this.options.groupEditable.order) {
  1358. this.groupTouchParams.group = this.groupFromTarget(event);
  1359. if (this.groupTouchParams.group) {
  1360. event.stopPropagation();
  1361. this.groupTouchParams.originalOrder = this.groupsData.getIds({
  1362. order: this.options.groupOrder
  1363. });
  1364. }
  1365. }
  1366. }
  1367. ItemSet.prototype._onGroupDrag = function (event) {
  1368. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1369. event.stopPropagation();
  1370. var groupsData = this.groupsData;
  1371. if (this.groupsData instanceof DataView) {
  1372. groupsData = this.groupsData.getDataSet()
  1373. }
  1374. // drag from one group to another
  1375. var group = this.groupFromTarget(event);
  1376. // try to avoid toggling when groups differ in height
  1377. if (group && group.height != this.groupTouchParams.group.height) {
  1378. var movingUp = (group.top < this.groupTouchParams.group.top);
  1379. var clientY = event.center ? event.center.y : event.clientY;
  1380. var targetGroupTop = util.getAbsoluteTop(group.dom.foreground);
  1381. var draggedGroupHeight = this.groupTouchParams.group.height;
  1382. if (movingUp) {
  1383. // skip swapping the groups when the dragged group is not below clientY afterwards
  1384. if (targetGroupTop + draggedGroupHeight < clientY) {
  1385. return;
  1386. }
  1387. } else {
  1388. var targetGroupHeight = group.height;
  1389. // skip swapping the groups when the dragged group is not below clientY afterwards
  1390. if (targetGroupTop + targetGroupHeight - draggedGroupHeight > clientY) {
  1391. return;
  1392. }
  1393. }
  1394. }
  1395. if (group && group != this.groupTouchParams.group) {
  1396. var targetGroup = groupsData.get(group.groupId);
  1397. var draggedGroup = groupsData.get(this.groupTouchParams.group.groupId);
  1398. // switch groups
  1399. if (draggedGroup && targetGroup) {
  1400. this.options.groupOrderSwap(draggedGroup, targetGroup, this.groupsData);
  1401. groupsData.update(draggedGroup);
  1402. groupsData.update(targetGroup);
  1403. }
  1404. // fetch current order of groups
  1405. var newOrder = groupsData.getIds({
  1406. order: this.options.groupOrder
  1407. });
  1408. // in case of changes since _onGroupDragStart
  1409. if (!util.equalArray(newOrder, this.groupTouchParams.originalOrder)) {
  1410. var origOrder = this.groupTouchParams.originalOrder;
  1411. var draggedId = this.groupTouchParams.group.groupId;
  1412. var numGroups = Math.min(origOrder.length, newOrder.length);
  1413. var curPos = 0;
  1414. var newOffset = 0;
  1415. var orgOffset = 0;
  1416. while (curPos < numGroups) {
  1417. // as long as the groups are where they should be step down along the groups order
  1418. while ((curPos+newOffset) < numGroups
  1419. && (curPos+orgOffset) < numGroups
  1420. && newOrder[curPos+newOffset] == origOrder[curPos+orgOffset]) {
  1421. curPos++;
  1422. }
  1423. // all ok
  1424. if (curPos+newOffset >= numGroups) {
  1425. break;
  1426. }
  1427. // not all ok
  1428. // if dragged group was move upwards everything below should have an offset
  1429. if (newOrder[curPos+newOffset] == draggedId) {
  1430. newOffset = 1;
  1431. continue;
  1432. }
  1433. // if dragged group was move downwards everything above should have an offset
  1434. else if (origOrder[curPos+orgOffset] == draggedId) {
  1435. orgOffset = 1;
  1436. continue;
  1437. }
  1438. // found a group (apart from dragged group) that has the wrong position -> switch with the
  1439. // group at the position where other one should be, fix index arrays and continue
  1440. else {
  1441. var slippedPosition = newOrder.indexOf(origOrder[curPos+orgOffset])
  1442. var switchGroup = groupsData.get(newOrder[curPos+newOffset]);
  1443. var shouldBeGroup = groupsData.get(origOrder[curPos+orgOffset]);
  1444. this.options.groupOrderSwap(switchGroup, shouldBeGroup, groupsData);
  1445. groupsData.update(switchGroup);
  1446. groupsData.update(shouldBeGroup);
  1447. var switchGroupId = newOrder[curPos+newOffset];
  1448. newOrder[curPos+newOffset] = origOrder[curPos+orgOffset];
  1449. newOrder[slippedPosition] = switchGroupId;
  1450. curPos++;
  1451. }
  1452. }
  1453. }
  1454. }
  1455. }
  1456. }
  1457. ItemSet.prototype._onGroupDragEnd = function (event) {
  1458. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1459. event.stopPropagation();
  1460. // update existing group
  1461. var me = this;
  1462. var id = me.groupTouchParams.group.groupId;
  1463. var dataset = me.groupsData.getDataSet();
  1464. var groupData = util.extend({}, dataset.get(id)); // clone the data
  1465. me.options.onMoveGroup(groupData, function (groupData) {
  1466. if (groupData) {
  1467. // apply changes
  1468. groupData[dataset._fieldId] = id; // ensure the group contains its id (can be undefined)
  1469. dataset.update(groupData);
  1470. }
  1471. else {
  1472. // fetch current order of groups
  1473. var newOrder = dataset.getIds({
  1474. order: me.options.groupOrder
  1475. });
  1476. // restore original order
  1477. if (!util.equalArray(newOrder, me.groupTouchParams.originalOrder)) {
  1478. var origOrder = me.groupTouchParams.originalOrder;
  1479. var numGroups = Math.min(origOrder.length, newOrder.length);
  1480. var curPos = 0;
  1481. while (curPos < numGroups) {
  1482. // as long as the groups are where they should be step down along the groups order
  1483. while (curPos < numGroups && newOrder[curPos] == origOrder[curPos]) {
  1484. curPos++;
  1485. }
  1486. // all ok
  1487. if (curPos >= numGroups) {
  1488. break;
  1489. }
  1490. // found a group that has the wrong position -> switch with the
  1491. // group at the position where other one should be, fix index arrays and continue
  1492. var slippedPosition = newOrder.indexOf(origOrder[curPos])
  1493. var switchGroup = dataset.get(newOrder[curPos]);
  1494. var shouldBeGroup = dataset.get(origOrder[curPos]);
  1495. me.options.groupOrderSwap(switchGroup, shouldBeGroup, dataset);
  1496. groupsData.update(switchGroup);
  1497. groupsData.update(shouldBeGroup);
  1498. var switchGroupId = newOrder[curPos];
  1499. newOrder[curPos] = origOrder[curPos];
  1500. newOrder[slippedPosition] = switchGroupId;
  1501. curPos++;
  1502. }
  1503. }
  1504. }
  1505. });
  1506. me.body.emitter.emit('groupDragged', { groupId: id });
  1507. }
  1508. }
  1509. /**
  1510. * Handle selecting/deselecting an item when tapping it
  1511. * @param {Event} event
  1512. * @private
  1513. */
  1514. ItemSet.prototype._onSelectItem = function (event) {
  1515. if (!this.options.selectable) return;
  1516. var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey);
  1517. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  1518. if (ctrlKey || shiftKey) {
  1519. this._onMultiSelectItem(event);
  1520. return;
  1521. }
  1522. var oldSelection = this.getSelection();
  1523. var item = this.itemFromTarget(event);
  1524. var selection = item ? [item.id] : [];
  1525. this.setSelection(selection);
  1526. var newSelection = this.getSelection();
  1527. // emit a select event,
  1528. // except when old selection is empty and new selection is still empty
  1529. if (newSelection.length > 0 || oldSelection.length > 0) {
  1530. this.body.emitter.emit('select', {
  1531. items: newSelection,
  1532. event: event
  1533. });
  1534. }
  1535. };
  1536. /**
  1537. * Handle hovering an item
  1538. * @param {Event} event
  1539. * @private
  1540. */
  1541. ItemSet.prototype._onMouseOver = function (event) {
  1542. var item = this.itemFromTarget(event);
  1543. if (!item) return;
  1544. this.body.emitter.emit('itemover', {
  1545. item: item.id,
  1546. event: event
  1547. });
  1548. };
  1549. ItemSet.prototype._onMouseOut = function (event) {
  1550. var item = this.itemFromTarget(event);
  1551. if (!item) return;
  1552. this.body.emitter.emit('itemout', {
  1553. item: item.id,
  1554. event: event
  1555. });
  1556. };
  1557. /**
  1558. * Handle updates of an item on double tap
  1559. * @param event
  1560. * @private
  1561. */
  1562. ItemSet.prototype._onUpdateItem = function (item) {
  1563. if (!this.options.selectable) return;
  1564. if (!this.options.editable.add) return;
  1565. var me = this;
  1566. if (item) {
  1567. // execute async handler to update the item (or cancel it)
  1568. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  1569. this.options.onUpdate(itemData, function (itemData) {
  1570. if (itemData) {
  1571. me.itemsData.getDataSet().update(itemData);
  1572. }
  1573. });
  1574. }
  1575. }
  1576. /**
  1577. * Handle creation of an item on double tap
  1578. * @param event
  1579. * @private
  1580. */
  1581. ItemSet.prototype._onAddItem = function (event) {
  1582. if (!this.options.selectable) return;
  1583. if (!this.options.editable.add) return;
  1584. var me = this;
  1585. var snap = this.options.snap || null;
  1586. var item = this.itemFromTarget(event);
  1587. if (!item) {
  1588. // add item
  1589. if (this.options.rtl) {
  1590. var xAbs = util.getAbsoluteRight(this.dom.frame);
  1591. var x = xAbs - event.center.x;
  1592. } else {
  1593. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1594. var x = event.center.x - xAbs;
  1595. }
  1596. // var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1597. // var x = event.center.x - xAbs;
  1598. var start = this.body.util.toTime(x);
  1599. var scale = this.body.util.getScale();
  1600. var step = this.body.util.getStep();
  1601. var newItemData = {
  1602. start: snap ? snap(start, scale, step) : start,
  1603. content: 'new item'
  1604. };
  1605. if (event.type == 'drop') {
  1606. var itemData = JSON.parse(event.dataTransfer.getData("text/plain"))
  1607. newItemData.content = itemData.content; // content is required
  1608. newItemData.type = itemData.type || 'box';
  1609. newItemData[this.itemsData._fieldId] = itemData.id || util.randomUUID();
  1610. if (itemData.type == 'range' || (itemData.end && itemData.start)) {
  1611. if (!itemData.end) {
  1612. var end = this.body.util.toTime(x + this.props.width / 5);
  1613. newItemData.end = snap ? snap(end, scale, step) : end;
  1614. } else {
  1615. newItemData.end = new Date(newItemData.start._i).getTime() + new Date(itemData.end).getTime() - new Date(itemData.start).getTime();
  1616. }
  1617. }
  1618. } else {
  1619. newItemData[this.itemsData._fieldId] = util.randomUUID();
  1620. // when default type is a range, add a default end date to the new item
  1621. if (this.options.type === 'range') {
  1622. var end = this.body.util.toTime(x + this.props.width / 5);
  1623. newItemData.end = snap ? snap(end, scale, step) : end;
  1624. }
  1625. }
  1626. var group = this.groupFromTarget(event);
  1627. if (group) {
  1628. newItemData.group = group.groupId;
  1629. }
  1630. // execute async handler to customize (or cancel) adding an item
  1631. newItemData = this._cloneItemData(newItemData); // convert start and end to the correct type
  1632. this.options.onAdd(newItemData, function (item) {
  1633. if (item) {
  1634. me.itemsData.getDataSet().add(item);
  1635. if (event.type == 'drop') {
  1636. me.setSelection([item.id]);
  1637. }
  1638. // TODO: need to trigger a redraw?
  1639. }
  1640. });
  1641. }
  1642. };
  1643. /**
  1644. * Handle selecting/deselecting multiple items when holding an item
  1645. * @param {Event} event
  1646. * @private
  1647. */
  1648. ItemSet.prototype._onMultiSelectItem = function (event) {
  1649. if (!this.options.selectable) return;
  1650. var item = this.itemFromTarget(event);
  1651. if (item) {
  1652. // multi select items (if allowed)
  1653. var selection = this.options.multiselect
  1654. ? this.getSelection() // take current selection
  1655. : []; // deselect current selection
  1656. var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false;
  1657. if (shiftKey && this.options.multiselect) {
  1658. // select all items between the old selection and the tapped item
  1659. var itemGroup = this.itemsData.get(item.id).group;
  1660. // when filtering get the group of the last selected item
  1661. var lastSelectedGroup = undefined;
  1662. if (this.options.multiselectPerGroup) {
  1663. if (selection.length > 0) {
  1664. lastSelectedGroup = this.itemsData.get(selection[0]).group;
  1665. }
  1666. }
  1667. // determine the selection range
  1668. if (!this.options.multiselectPerGroup || lastSelectedGroup == undefined || lastSelectedGroup == itemGroup) {
  1669. selection.push(item.id);
  1670. }
  1671. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  1672. if (!this.options.multiselectPerGroup || lastSelectedGroup == itemGroup) {
  1673. // select all items within the selection range
  1674. selection = [];
  1675. for (var id in this.items) {
  1676. if (this.items.hasOwnProperty(id)) {
  1677. var _item = this.items[id];
  1678. var start = _item.data.start;
  1679. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  1680. if (start >= range.min &&
  1681. end <= range.max &&
  1682. (!this.options.multiselectPerGroup || lastSelectedGroup == this.itemsData.get(_item.id).group) &&
  1683. !(_item instanceof BackgroundItem)) {
  1684. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  1685. }
  1686. }
  1687. }
  1688. }
  1689. }
  1690. else {
  1691. // add/remove this item from the current selection
  1692. var index = selection.indexOf(item.id);
  1693. if (index == -1) {
  1694. // item is not yet selected -> select it
  1695. selection.push(item.id);
  1696. }
  1697. else {
  1698. // item is already selected -> deselect it
  1699. selection.splice(index, 1);
  1700. }
  1701. }
  1702. this.setSelection(selection);
  1703. this.body.emitter.emit('select', {
  1704. items: this.getSelection(),
  1705. event: event
  1706. });
  1707. }
  1708. };
  1709. /**
  1710. * Calculate the time range of a list of items
  1711. * @param {Array.<Object>} itemsData
  1712. * @return {{min: Date, max: Date}} Returns the range of the provided items
  1713. * @private
  1714. */
  1715. ItemSet._getItemRange = function(itemsData) {
  1716. var max = null;
  1717. var min = null;
  1718. itemsData.forEach(function (data) {
  1719. if (min == null || data.start < min) {
  1720. min = data.start;
  1721. }
  1722. if (data.end != undefined) {
  1723. if (max == null || data.end > max) {
  1724. max = data.end;
  1725. }
  1726. }
  1727. else {
  1728. if (max == null || data.start > max) {
  1729. max = data.start;
  1730. }
  1731. }
  1732. });
  1733. return {
  1734. min: min,
  1735. max: max
  1736. }
  1737. };
  1738. /**
  1739. * Find an item from an event target:
  1740. * searches for the attribute 'timeline-item' in the event target's element tree
  1741. * @param {Event} event
  1742. * @return {Item | null} item
  1743. */
  1744. ItemSet.prototype.itemFromTarget = function(event) {
  1745. var target = event.target;
  1746. while (target) {
  1747. if (target.hasOwnProperty('timeline-item')) {
  1748. return target['timeline-item'];
  1749. }
  1750. target = target.parentNode;
  1751. }
  1752. return null;
  1753. };
  1754. /**
  1755. * Find the Group from an event target:
  1756. * searches for the attribute 'timeline-group' in the event target's element tree
  1757. * @param {Event} event
  1758. * @return {Group | null} group
  1759. */
  1760. ItemSet.prototype.groupFromTarget = function(event) {
  1761. var clientY = event.center ? event.center.y : event.clientY;
  1762. for (var i = 0; i < this.groupIds.length; i++) {
  1763. var groupId = this.groupIds[i];
  1764. var group = this.groups[groupId];
  1765. var foreground = group.dom.foreground;
  1766. var top = util.getAbsoluteTop(foreground);
  1767. if (clientY > top && clientY < top + foreground.offsetHeight) {
  1768. return group;
  1769. }
  1770. if (this.options.orientation.item === 'top') {
  1771. if (i === this.groupIds.length - 1 && clientY > top) {
  1772. return group;
  1773. }
  1774. }
  1775. else {
  1776. if (i === 0 && clientY < top + foreground.offset) {
  1777. return group;
  1778. }
  1779. }
  1780. }
  1781. return null;
  1782. };
  1783. /**
  1784. * Find the ItemSet from an event target:
  1785. * searches for the attribute 'timeline-itemset' in the event target's element tree
  1786. * @param {Event} event
  1787. * @return {ItemSet | null} item
  1788. */
  1789. ItemSet.itemSetFromTarget = function(event) {
  1790. var target = event.target;
  1791. while (target) {
  1792. if (target.hasOwnProperty('timeline-itemset')) {
  1793. return target['timeline-itemset'];
  1794. }
  1795. target = target.parentNode;
  1796. }
  1797. return null;
  1798. };
  1799. /**
  1800. * Clone the data of an item, and "normalize" it: convert the start and end date
  1801. * to the type (Date, Moment, ...) configured in the DataSet. If not configured,
  1802. * start and end are converted to Date.
  1803. * @param {Object} itemData, typically `item.data`
  1804. * @param {string} [type] Optional Date type. If not provided, the type from the DataSet is taken
  1805. * @return {Object} The cloned object
  1806. * @private
  1807. */
  1808. ItemSet.prototype._cloneItemData = function (itemData, type) {
  1809. var clone = util.extend({}, itemData);
  1810. if (!type) {
  1811. // convert start and end date to the type (Date, Moment, ...) configured in the DataSet
  1812. type = this.itemsData.getDataSet()._options.type;
  1813. }
  1814. if (clone.start != undefined) {
  1815. clone.start = util.convert(clone.start, type && type.start || 'Date');
  1816. }
  1817. if (clone.end != undefined) {
  1818. clone.end = util.convert(clone.end , type && type.end || 'Date');
  1819. }
  1820. return clone;
  1821. };
  1822. module.exports = ItemSet;