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.

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