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.

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