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.

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