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.

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