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.

1703 lines
48 KiB

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