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.

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