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.

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