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.

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