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.

2058 lines
60 KiB

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