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.

1866 lines
53 KiB

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