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.

1950 lines
57 KiB

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