vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2103 lines
62 KiB

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