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.

2081 lines
61 KiB

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