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.

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