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. this.body.emitter.emit('_change', {queue: true});
  637. };
  638. /**
  639. * Get the current items
  640. * @returns {vis.DataSet | null}
  641. */
  642. ItemSet.prototype.getItems = function() {
  643. return this.itemsData;
  644. };
  645. /**
  646. * Set groups
  647. * @param {vis.DataSet} groups
  648. */
  649. ItemSet.prototype.setGroups = function(groups) {
  650. var me = this,
  651. ids;
  652. // unsubscribe from current dataset
  653. if (this.groupsData) {
  654. util.forEach(this.groupListeners, function (callback, event) {
  655. me.groupsData.off(event, callback);
  656. });
  657. // remove all drawn groups
  658. ids = this.groupsData.getIds();
  659. this.groupsData = null;
  660. this._onRemoveGroups(ids); // note: this will cause a redraw
  661. }
  662. // replace the dataset
  663. if (!groups) {
  664. this.groupsData = null;
  665. }
  666. else if (groups instanceof DataSet || groups instanceof DataView) {
  667. this.groupsData = groups;
  668. }
  669. else {
  670. throw new TypeError('Data must be an instance of DataSet or DataView');
  671. }
  672. if (this.groupsData) {
  673. // subscribe to new dataset
  674. var id = this.id;
  675. util.forEach(this.groupListeners, function (callback, event) {
  676. me.groupsData.on(event, callback, id);
  677. });
  678. // draw all ms
  679. ids = this.groupsData.getIds();
  680. this._onAddGroups(ids);
  681. }
  682. // update the group holding all ungrouped items
  683. this._updateUngrouped();
  684. // update the order of all items in each group
  685. this._order();
  686. this.body.emitter.emit('_change', {queue: true});
  687. };
  688. /**
  689. * Get the current groups
  690. * @returns {vis.DataSet | null} groups
  691. */
  692. ItemSet.prototype.getGroups = function() {
  693. return this.groupsData;
  694. };
  695. /**
  696. * Remove an item by its id
  697. * @param {String | Number} id
  698. */
  699. ItemSet.prototype.removeItem = function(id) {
  700. var item = this.itemsData.get(id),
  701. dataset = this.itemsData.getDataSet();
  702. if (item) {
  703. // confirm deletion
  704. this.options.onRemove(item, function (item) {
  705. if (item) {
  706. // remove by id here, it is possible that an item has no id defined
  707. // itself, so better not delete by the item itself
  708. dataset.remove(id);
  709. }
  710. });
  711. }
  712. };
  713. /**
  714. * Get the time of an item based on it's data and options.type
  715. * @param {Object} itemData
  716. * @returns {string} Returns the type
  717. * @private
  718. */
  719. ItemSet.prototype._getType = function (itemData) {
  720. return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
  721. };
  722. /**
  723. * Get the group id for an item
  724. * @param {Object} itemData
  725. * @returns {string} Returns the groupId
  726. * @private
  727. */
  728. ItemSet.prototype._getGroupId = function (itemData) {
  729. var type = this._getType(itemData);
  730. if (type == 'background' && itemData.group == undefined) {
  731. return BACKGROUND;
  732. }
  733. else {
  734. return this.groupsData ? itemData.group : UNGROUPED;
  735. }
  736. };
  737. /**
  738. * Handle updated items
  739. * @param {Number[]} ids
  740. * @protected
  741. */
  742. ItemSet.prototype._onUpdate = function(ids) {
  743. var me = this;
  744. ids.forEach(function (id) {
  745. var itemData = me.itemsData.get(id, me.itemOptions);
  746. var item = me.items[id];
  747. var type = me._getType(itemData);
  748. var constructor = ItemSet.types[type];
  749. var selected;
  750. if (item) {
  751. // update item
  752. if (!constructor || !(item instanceof constructor)) {
  753. // item type has changed, delete the item and recreate it
  754. selected = item.selected; // preserve selection of this item
  755. me._removeItem(item);
  756. item = null;
  757. }
  758. else {
  759. me._updateItem(item, itemData);
  760. }
  761. }
  762. if (!item) {
  763. // create item
  764. if (constructor) {
  765. item = new constructor(itemData, me.conversion, me.options);
  766. item.id = id; // TODO: not so nice setting id afterwards
  767. me._addItem(item);
  768. if (selected) {
  769. this.selection.push(id);
  770. item.select();
  771. }
  772. }
  773. else if (type == 'rangeoverflow') {
  774. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  775. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
  776. '.vis-item.vis-range .vis-item-content {overflow: visible;}');
  777. }
  778. else {
  779. throw new TypeError('Unknown item type "' + type + '"');
  780. }
  781. }
  782. }.bind(this));
  783. this._order();
  784. this.stackDirty = true; // force re-stacking of all items next redraw
  785. this.body.emitter.emit('_change', {queue: true});
  786. };
  787. /**
  788. * Handle added items
  789. * @param {Number[]} ids
  790. * @protected
  791. */
  792. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  793. /**
  794. * Handle removed items
  795. * @param {Number[]} ids
  796. * @protected
  797. */
  798. ItemSet.prototype._onRemove = function(ids) {
  799. var count = 0;
  800. var me = this;
  801. ids.forEach(function (id) {
  802. var item = me.items[id];
  803. if (item) {
  804. count++;
  805. me._removeItem(item);
  806. }
  807. });
  808. if (count) {
  809. // update order
  810. this._order();
  811. this.stackDirty = true; // force re-stacking of all items next redraw
  812. this.body.emitter.emit('_change', {queue: true});
  813. }
  814. };
  815. /**
  816. * Update the order of item in all groups
  817. * @private
  818. */
  819. ItemSet.prototype._order = function() {
  820. // reorder the items in all groups
  821. // TODO: optimization: only reorder groups affected by the changed items
  822. util.forEach(this.groups, function (group) {
  823. group.order();
  824. });
  825. };
  826. /**
  827. * Handle updated groups
  828. * @param {Number[]} ids
  829. * @private
  830. */
  831. ItemSet.prototype._onUpdateGroups = function(ids) {
  832. this._onAddGroups(ids);
  833. };
  834. /**
  835. * Handle changed groups (added or updated)
  836. * @param {Number[]} ids
  837. * @private
  838. */
  839. ItemSet.prototype._onAddGroups = function(ids) {
  840. var me = this;
  841. ids.forEach(function (id) {
  842. var groupData = me.groupsData.get(id);
  843. var group = me.groups[id];
  844. if (!group) {
  845. // check for reserved ids
  846. if (id == UNGROUPED || id == BACKGROUND) {
  847. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  848. }
  849. var groupOptions = Object.create(me.options);
  850. util.extend(groupOptions, {
  851. height: null
  852. });
  853. group = new Group(id, groupData, me);
  854. me.groups[id] = group;
  855. // add items with this groupId to the new group
  856. for (var itemId in me.items) {
  857. if (me.items.hasOwnProperty(itemId)) {
  858. var item = me.items[itemId];
  859. if (item.data.group == id) {
  860. group.add(item);
  861. }
  862. }
  863. }
  864. group.order();
  865. group.show();
  866. }
  867. else {
  868. // update group
  869. group.setData(groupData);
  870. }
  871. });
  872. this.body.emitter.emit('_change', {queue: true});
  873. };
  874. /**
  875. * Handle removed groups
  876. * @param {Number[]} ids
  877. * @private
  878. */
  879. ItemSet.prototype._onRemoveGroups = function(ids) {
  880. var groups = this.groups;
  881. ids.forEach(function (id) {
  882. var group = groups[id];
  883. if (group) {
  884. group.hide();
  885. delete groups[id];
  886. }
  887. });
  888. this.markDirty();
  889. this.body.emitter.emit('_change', {queue: true});
  890. };
  891. /**
  892. * Reorder the groups if needed
  893. * @return {boolean} changed
  894. * @private
  895. */
  896. ItemSet.prototype._orderGroups = function () {
  897. if (this.groupsData) {
  898. // reorder the groups
  899. var groupIds = this.groupsData.getIds({
  900. order: this.options.groupOrder
  901. });
  902. var changed = !util.equalArray(groupIds, this.groupIds);
  903. if (changed) {
  904. // hide all groups, removes them from the DOM
  905. var groups = this.groups;
  906. groupIds.forEach(function (groupId) {
  907. groups[groupId].hide();
  908. });
  909. // show the groups again, attach them to the DOM in correct order
  910. groupIds.forEach(function (groupId) {
  911. groups[groupId].show();
  912. });
  913. this.groupIds = groupIds;
  914. }
  915. return changed;
  916. }
  917. else {
  918. return false;
  919. }
  920. };
  921. /**
  922. * Add a new item
  923. * @param {Item} item
  924. * @private
  925. */
  926. ItemSet.prototype._addItem = function(item) {
  927. this.items[item.id] = item;
  928. // add to group
  929. var groupId = this._getGroupId(item.data);
  930. var group = this.groups[groupId];
  931. if (group) group.add(item);
  932. };
  933. /**
  934. * Update an existing item
  935. * @param {Item} item
  936. * @param {Object} itemData
  937. * @private
  938. */
  939. ItemSet.prototype._updateItem = function(item, itemData) {
  940. var oldGroupId = item.data.group;
  941. var oldSubGroupId = item.data.subgroup;
  942. // update the items data (will redraw the item when displayed)
  943. item.setData(itemData);
  944. // update group
  945. if (oldGroupId != item.data.group || oldSubGroupId != item.data.subgroup) {
  946. var oldGroup = this.groups[oldGroupId];
  947. if (oldGroup) oldGroup.remove(item);
  948. var groupId = this._getGroupId(item.data);
  949. var group = this.groups[groupId];
  950. if (group) group.add(item);
  951. }
  952. };
  953. /**
  954. * Delete an item from the ItemSet: remove it from the DOM, from the map
  955. * with items, and from the map with visible items, and from the selection
  956. * @param {Item} item
  957. * @private
  958. */
  959. ItemSet.prototype._removeItem = function(item) {
  960. // remove from DOM
  961. item.hide();
  962. // remove from items
  963. delete this.items[item.id];
  964. // remove from selection
  965. var index = this.selection.indexOf(item.id);
  966. if (index != -1) this.selection.splice(index, 1);
  967. // remove from group
  968. item.parent && item.parent.remove(item);
  969. };
  970. /**
  971. * Create an array containing all items being a range (having an end date)
  972. * @param array
  973. * @returns {Array}
  974. * @private
  975. */
  976. ItemSet.prototype._constructByEndArray = function(array) {
  977. var endArray = [];
  978. for (var i = 0; i < array.length; i++) {
  979. if (array[i] instanceof RangeItem) {
  980. endArray.push(array[i]);
  981. }
  982. }
  983. return endArray;
  984. };
  985. /**
  986. * Register the clicked item on touch, before dragStart is initiated.
  987. *
  988. * dragStart is initiated from a mousemove event, AFTER the mouse/touch is
  989. * already moving. Therefore, the mouse/touch can sometimes be above an other
  990. * DOM element than the item itself.
  991. *
  992. * @param {Event} event
  993. * @private
  994. */
  995. ItemSet.prototype._onTouch = function (event) {
  996. // store the touched item, used in _onDragStart
  997. this.touchParams.item = this.itemFromTarget(event);
  998. this.touchParams.dragLeftItem = event.target.dragLeftItem || false;
  999. this.touchParams.dragRightItem = event.target.dragRightItem || false;
  1000. this.touchParams.itemProps = null;
  1001. };
  1002. /**
  1003. * Given an group id, returns the index it has.
  1004. *
  1005. * @param {Number} groupID
  1006. * @private
  1007. */
  1008. ItemSet.prototype._getGroupIndex = function(groupId) {
  1009. for (var i = 0; i < this.groupIds.length; i++) {
  1010. if (groupId == this.groupIds[i])
  1011. return i;
  1012. }
  1013. };
  1014. /**
  1015. * Start dragging the selected events
  1016. * @param {Event} event
  1017. * @private
  1018. */
  1019. ItemSet.prototype._onDragStart = function (event) {
  1020. var item = this.touchParams.item || null;
  1021. var me = this;
  1022. var props;
  1023. if (item && (item.selected || this.options.itemsAlwaysDraggable)) {
  1024. if (!this.options.editable.updateTime &&
  1025. !this.options.editable.updateGroup &&
  1026. !item.editable) {
  1027. return;
  1028. }
  1029. // override options.editable
  1030. if (item.editable === false) {
  1031. return;
  1032. }
  1033. var dragLeftItem = this.touchParams.dragLeftItem;
  1034. var dragRightItem = this.touchParams.dragRightItem;
  1035. if (dragLeftItem) {
  1036. props = {
  1037. item: dragLeftItem,
  1038. initialX: event.center.x,
  1039. dragLeft: true,
  1040. data: this._cloneItemData(item.data)
  1041. };
  1042. this.touchParams.itemProps = [props];
  1043. }
  1044. else if (dragRightItem) {
  1045. props = {
  1046. item: dragRightItem,
  1047. initialX: event.center.x,
  1048. dragRight: true,
  1049. data: this._cloneItemData(item.data)
  1050. };
  1051. this.touchParams.itemProps = [props];
  1052. }
  1053. else {
  1054. this.touchParams.selectedItem = item;
  1055. var baseGroupIndex = this._getGroupIndex(item.data.group);
  1056. var itemsToDrag = (this.options.itemsAlwaysDraggable && !item.selected) ? [item.id] : this.getSelection();
  1057. this.touchParams.itemProps = itemsToDrag.map(function (id) {
  1058. var item = me.items[id];
  1059. var groupIndex = me._getGroupIndex(item.data.group);
  1060. return {
  1061. item: item,
  1062. initialX: event.center.x,
  1063. groupOffset: baseGroupIndex-groupIndex,
  1064. data: this._cloneItemData(item.data)
  1065. };
  1066. }.bind(this));
  1067. }
  1068. event.stopPropagation();
  1069. }
  1070. else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  1071. // create a new range item when dragging with ctrl key down
  1072. this._onDragStartAddItem(event);
  1073. }
  1074. };
  1075. /**
  1076. * Start creating a new range item by dragging.
  1077. * @param {Event} event
  1078. * @private
  1079. */
  1080. ItemSet.prototype._onDragStartAddItem = function (event) {
  1081. var snap = this.options.snap || null;
  1082. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1083. var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  1084. var time = this.body.util.toTime(x);
  1085. var scale = this.body.util.getScale();
  1086. var step = this.body.util.getStep();
  1087. var start = snap ? snap(time, scale, step) : time;
  1088. var end = start;
  1089. var itemData = {
  1090. type: 'range',
  1091. start: start,
  1092. end: end,
  1093. content: 'new item'
  1094. };
  1095. var id = util.randomUUID();
  1096. itemData[this.itemsData._fieldId] = id;
  1097. var group = this.groupFromTarget(event);
  1098. if (group) {
  1099. itemData.group = group.groupId;
  1100. }
  1101. var newItem = new RangeItem(itemData, this.conversion, this.options);
  1102. newItem.id = id; // TODO: not so nice setting id afterwards
  1103. newItem.data = this._cloneItemData(itemData);
  1104. this._addItem(newItem);
  1105. var props = {
  1106. item: newItem,
  1107. dragRight: true,
  1108. initialX: event.center.x,
  1109. data: newItem.data
  1110. };
  1111. this.touchParams.itemProps = [props];
  1112. event.stopPropagation();
  1113. };
  1114. /**
  1115. * Drag selected items
  1116. * @param {Event} event
  1117. * @private
  1118. */
  1119. ItemSet.prototype._onDrag = function (event) {
  1120. if (this.touchParams.itemProps) {
  1121. event.stopPropagation();
  1122. var me = this;
  1123. var snap = this.options.snap || null;
  1124. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  1125. var scale = this.body.util.getScale();
  1126. var step = this.body.util.getStep();
  1127. //only calculate the new group for the item that's actually dragged
  1128. var selectedItem = this.touchParams.selectedItem;
  1129. var updateGroupAllowed = me.options.editable.updateGroup;
  1130. var newGroupBase = null;
  1131. if (updateGroupAllowed && selectedItem) {
  1132. if (selectedItem.data.group != undefined) {
  1133. // drag from one group to another
  1134. var group = me.groupFromTarget(event);
  1135. if (group) {
  1136. //we know the offset for all items, so the new group for all items
  1137. //will be relative to this one.
  1138. newGroupBase = this._getGroupIndex(group.groupId);
  1139. }
  1140. }
  1141. }
  1142. // move
  1143. this.touchParams.itemProps.forEach(function (props) {
  1144. var current = me.body.util.toTime(event.center.x - xOffset);
  1145. var initial = me.body.util.toTime(props.initialX - xOffset);
  1146. var offset = current - initial; // ms
  1147. var itemData = this._cloneItemData(props.item.data); // clone the data
  1148. if (props.item.editable === false) {
  1149. return;
  1150. }
  1151. var updateTimeAllowed = me.options.editable.updateTime ||
  1152. props.item.editable === true;
  1153. if (updateTimeAllowed) {
  1154. if (props.dragLeft) {
  1155. // drag left side of a range item
  1156. if (itemData.start != undefined) {
  1157. var initialStart = util.convert(props.data.start, 'Date');
  1158. var start = new Date(initialStart.valueOf() + offset);
  1159. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1160. itemData.start = snap ? snap(start, scale, step) : start;
  1161. }
  1162. }
  1163. else if (props.dragRight) {
  1164. // drag right side of a range item
  1165. if (itemData.end != undefined) {
  1166. var initialEnd = util.convert(props.data.end, 'Date');
  1167. var end = new Date(initialEnd.valueOf() + offset);
  1168. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1169. itemData.end = snap ? snap(end, scale, step) : end;
  1170. }
  1171. }
  1172. else {
  1173. // drag both start and end
  1174. if (itemData.start != undefined) {
  1175. var initialStart = util.convert(props.data.start, 'Date').valueOf();
  1176. var start = new Date(initialStart + offset);
  1177. if (itemData.end != undefined) {
  1178. var initialEnd = util.convert(props.data.end, 'Date');
  1179. var duration = initialEnd.valueOf() - initialStart.valueOf();
  1180. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1181. itemData.start = snap ? snap(start, scale, step) : start;
  1182. itemData.end = new Date(itemData.start.valueOf() + duration);
  1183. }
  1184. else {
  1185. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1186. itemData.start = snap ? snap(start, scale, step) : start;
  1187. }
  1188. }
  1189. }
  1190. }
  1191. var updateGroupAllowed = me.options.editable.updateGroup ||
  1192. props.item.editable === true;
  1193. if (updateGroupAllowed && (!props.dragLeft && !props.dragRight) && newGroupBase!=null) {
  1194. if (itemData.group != undefined) {
  1195. var newOffset = newGroupBase - props.groupOffset;
  1196. //make sure we stay in bounds
  1197. newOffset = Math.max(0, newOffset);
  1198. newOffset = Math.min(me.groupIds.length-1, newOffset);
  1199. itemData.group = me.groupIds[newOffset];
  1200. }
  1201. }
  1202. // confirm moving the item
  1203. itemData = this._cloneItemData(itemData); // convert start and end to the correct type
  1204. me.options.onMoving(itemData, function (itemData) {
  1205. if (itemData) {
  1206. props.item.setData(this._cloneItemData(itemData, 'Date'));
  1207. }
  1208. }.bind(this));
  1209. }.bind(this));
  1210. this.stackDirty = true; // force re-stacking of all items next redraw
  1211. this.body.emitter.emit('_change');
  1212. }
  1213. };
  1214. /**
  1215. * Move an item to another group
  1216. * @param {Item} item
  1217. * @param {String | Number} groupId
  1218. * @private
  1219. */
  1220. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1221. var group = this.groups[groupId];
  1222. if (group && group.groupId != item.data.group) {
  1223. var oldGroup = item.parent;
  1224. oldGroup.remove(item);
  1225. oldGroup.order();
  1226. group.add(item);
  1227. group.order();
  1228. item.data.group = group.groupId;
  1229. }
  1230. };
  1231. /**
  1232. * End of dragging selected items
  1233. * @param {Event} event
  1234. * @private
  1235. */
  1236. ItemSet.prototype._onDragEnd = function (event) {
  1237. if (this.touchParams.itemProps) {
  1238. event.stopPropagation();
  1239. var me = this;
  1240. var dataset = this.itemsData.getDataSet();
  1241. var itemProps = this.touchParams.itemProps ;
  1242. this.touchParams.itemProps = null;
  1243. itemProps.forEach(function (props) {
  1244. var id = props.item.id;
  1245. var exists = me.itemsData.get(id, me.itemOptions) != null;
  1246. if (!exists) {
  1247. // add a new item
  1248. me.options.onAdd(props.item.data, function (itemData) {
  1249. me._removeItem(props.item); // remove temporary item
  1250. if (itemData) {
  1251. me.itemsData.getDataSet().add(itemData);
  1252. }
  1253. // force re-stacking of all items next redraw
  1254. me.stackDirty = true;
  1255. me.body.emitter.emit('_change');
  1256. });
  1257. }
  1258. else {
  1259. // update existing item
  1260. var itemData = this._cloneItemData(props.item.data); // convert start and end to the correct type
  1261. me.options.onMove(itemData, function (itemData) {
  1262. if (itemData) {
  1263. // apply changes
  1264. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1265. dataset.update(itemData);
  1266. }
  1267. else {
  1268. // restore original values
  1269. props.item.setData(props.data);
  1270. me.stackDirty = true; // force re-stacking of all items next redraw
  1271. me.body.emitter.emit('_change');
  1272. }
  1273. });
  1274. }
  1275. }.bind(this));
  1276. }
  1277. };
  1278. ItemSet.prototype._onGroupDragStart = function (event) {
  1279. if (this.options.groupEditable.order) {
  1280. this.groupTouchParams.group = this.groupFromTarget(event);
  1281. if (this.groupTouchParams.group) {
  1282. event.stopPropagation();
  1283. this.groupTouchParams.originalOrder = this.groupsData.getIds({
  1284. order: this.options.groupOrder
  1285. });
  1286. }
  1287. }
  1288. }
  1289. ItemSet.prototype._onGroupDrag = function (event) {
  1290. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1291. event.stopPropagation();
  1292. // drag from one group to another
  1293. var group = this.groupFromTarget(event);
  1294. // try to avoid toggling when groups differ in height
  1295. if (group && group.height != this.groupTouchParams.group.height) {
  1296. var movingUp = (group.top < this.groupTouchParams.group.top);
  1297. var clientY = event.center ? event.center.y : event.clientY;
  1298. var targetGroupTop = util.getAbsoluteTop(group.dom.foreground);
  1299. var draggedGroupHeight = this.groupTouchParams.group.height;
  1300. if (movingUp) {
  1301. // skip swapping the groups when the dragged group is not below clientY afterwards
  1302. if (targetGroupTop + draggedGroupHeight < clientY) {
  1303. return;
  1304. }
  1305. } else {
  1306. var targetGroupHeight = group.height;
  1307. // skip swapping the groups when the dragged group is not below clientY afterwards
  1308. if (targetGroupTop + targetGroupHeight - draggedGroupHeight > clientY) {
  1309. return;
  1310. }
  1311. }
  1312. }
  1313. if (group && group != this.groupTouchParams.group) {
  1314. var groupsData = this.groupsData;
  1315. var targetGroup = groupsData.get(group.groupId);
  1316. var draggedGroup = groupsData.get(this.groupTouchParams.group.groupId);
  1317. // switch groups
  1318. if (draggedGroup && targetGroup) {
  1319. this.options.groupOrderSwap(draggedGroup, targetGroup, this.groupsData);
  1320. this.groupsData.update(draggedGroup);
  1321. this.groupsData.update(targetGroup);
  1322. }
  1323. // fetch current order of groups
  1324. var newOrder = this.groupsData.getIds({
  1325. order: this.options.groupOrder
  1326. });
  1327. // in case of changes since _onGroupDragStart
  1328. if (!util.equalArray(newOrder, this.groupTouchParams.originalOrder)) {
  1329. var groupsData = this.groupsData;
  1330. var origOrder = this.groupTouchParams.originalOrder;
  1331. var draggedId = this.groupTouchParams.group.groupId;
  1332. var numGroups = Math.min(origOrder.length, newOrder.length);
  1333. var curPos = 0;
  1334. var newOffset = 0;
  1335. var orgOffset = 0;
  1336. while (curPos < numGroups) {
  1337. // as long as the groups are where they should be step down along the groups order
  1338. while ((curPos+newOffset) < numGroups
  1339. && (curPos+orgOffset) < numGroups
  1340. && newOrder[curPos+newOffset] == origOrder[curPos+orgOffset]) {
  1341. curPos++;
  1342. }
  1343. // all ok
  1344. if (curPos+newOffset >= numGroups) {
  1345. break;
  1346. }
  1347. // not all ok
  1348. // if dragged group was move upwards everything below should have an offset
  1349. if (newOrder[curPos+newOffset] == draggedId) {
  1350. newOffset = 1;
  1351. continue;
  1352. }
  1353. // if dragged group was move downwards everything above should have an offset
  1354. else if (origOrder[curPos+orgOffset] == draggedId) {
  1355. orgOffset = 1;
  1356. continue;
  1357. }
  1358. // found a group (apart from dragged group) that has the wrong position -> switch with the
  1359. // group at the position where other one should be, fix index arrays and continue
  1360. else {
  1361. var slippedPosition = newOrder.indexOf(origOrder[curPos+orgOffset])
  1362. var switchGroup = groupsData.get(newOrder[curPos+newOffset]);
  1363. var shouldBeGroup = groupsData.get(origOrder[curPos+orgOffset]);
  1364. this.options.groupOrderSwap(switchGroup, shouldBeGroup, groupsData);
  1365. groupsData.update(switchGroup);
  1366. groupsData.update(shouldBeGroup);
  1367. var switchGroupId = newOrder[curPos+newOffset];
  1368. newOrder[curPos+newOffset] = origOrder[curPos+orgOffset];
  1369. newOrder[slippedPosition] = switchGroupId;
  1370. curPos++;
  1371. }
  1372. }
  1373. }
  1374. }
  1375. }
  1376. }
  1377. ItemSet.prototype._onGroupDragEnd = function (event) {
  1378. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1379. event.stopPropagation();
  1380. // update existing group
  1381. var me = this;
  1382. var id = me.groupTouchParams.group.groupId;
  1383. var dataset = me.groupsData.getDataSet();
  1384. var groupData = util.extend({}, dataset.get(id)); // clone the data
  1385. me.options.onMoveGroup(groupData, function (groupData) {
  1386. if (groupData) {
  1387. // apply changes
  1388. groupData[dataset._fieldId] = id; // ensure the group contains its id (can be undefined)
  1389. dataset.update(groupData);
  1390. }
  1391. else {
  1392. // fetch current order of groups
  1393. var newOrder = dataset.getIds({
  1394. order: me.options.groupOrder
  1395. });
  1396. // restore original order
  1397. if (!util.equalArray(newOrder, me.groupTouchParams.originalOrder)) {
  1398. var origOrder = me.groupTouchParams.originalOrder;
  1399. var numGroups = Math.min(origOrder.length, newOrder.length);
  1400. var curPos = 0;
  1401. while (curPos < numGroups) {
  1402. // as long as the groups are where they should be step down along the groups order
  1403. while (curPos < numGroups && newOrder[curPos] == origOrder[curPos]) {
  1404. curPos++;
  1405. }
  1406. // all ok
  1407. if (curPos >= numGroups) {
  1408. break;
  1409. }
  1410. // found a group that has the wrong position -> switch with the
  1411. // group at the position where other one should be, fix index arrays and continue
  1412. var slippedPosition = newOrder.indexOf(origOrder[curPos])
  1413. var switchGroup = dataset.get(newOrder[curPos]);
  1414. var shouldBeGroup = dataset.get(origOrder[curPos]);
  1415. me.options.groupOrderSwap(switchGroup, shouldBeGroup, dataset);
  1416. groupsData.update(switchGroup);
  1417. groupsData.update(shouldBeGroup);
  1418. var switchGroupId = newOrder[curPos];
  1419. newOrder[curPos] = origOrder[curPos];
  1420. newOrder[slippedPosition] = switchGroupId;
  1421. curPos++;
  1422. }
  1423. }
  1424. }
  1425. });
  1426. me.body.emitter.emit('groupDragged', { groupId: id });
  1427. }
  1428. }
  1429. /**
  1430. * Handle selecting/deselecting an item when tapping it
  1431. * @param {Event} event
  1432. * @private
  1433. */
  1434. ItemSet.prototype._onSelectItem = function (event) {
  1435. if (!this.options.selectable) return;
  1436. var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey);
  1437. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  1438. if (ctrlKey || shiftKey) {
  1439. this._onMultiSelectItem(event);
  1440. return;
  1441. }
  1442. var oldSelection = this.getSelection();
  1443. var item = this.itemFromTarget(event);
  1444. var selection = item ? [item.id] : [];
  1445. this.setSelection(selection);
  1446. var newSelection = this.getSelection();
  1447. // emit a select event,
  1448. // except when old selection is empty and new selection is still empty
  1449. if (newSelection.length > 0 || oldSelection.length > 0) {
  1450. this.body.emitter.emit('select', {
  1451. items: newSelection,
  1452. event: event
  1453. });
  1454. }
  1455. };
  1456. /**
  1457. * Handle creation and updates of an item on double tap
  1458. * @param event
  1459. * @private
  1460. */
  1461. ItemSet.prototype._onAddItem = function (event) {
  1462. if (!this.options.selectable) return;
  1463. if (!this.options.editable.add) return;
  1464. var me = this;
  1465. var snap = this.options.snap || null;
  1466. var item = this.itemFromTarget(event);
  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;