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.

1631 lines
45 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
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. // single select (or unselect) when tapping an item
  171. this.hammer.on('tap', this._onSelectItem.bind(this));
  172. // multi select when holding mouse/touch, or on ctrl+click
  173. this.hammer.on('press', this._onMultiSelectItem.bind(this));
  174. // add item on doubletap
  175. this.hammer.on('doubletap', this._onAddItem.bind(this));
  176. // attach to the DOM
  177. this.show();
  178. };
  179. /**
  180. * Set options for the ItemSet. Existing options will be extended/overwritten.
  181. * @param {Object} [options] The following options are available:
  182. * {String} type
  183. * Default type for the items. Choose from 'box'
  184. * (default), 'point', 'range', or 'background'.
  185. * The default style can be overwritten by
  186. * individual items.
  187. * {String} align
  188. * Alignment for the items, only applicable for
  189. * BoxItem. Choose 'center' (default), 'left', or
  190. * 'right'.
  191. * {String} orientation.item
  192. * Orientation of the item set. Choose 'top' or
  193. * 'bottom' (default).
  194. * {Function} groupOrder
  195. * A sorting function for ordering groups
  196. * {Boolean} stack
  197. * If true (default), items will be stacked on
  198. * top of each other.
  199. * {Number} margin.axis
  200. * Margin between the axis and the items in pixels.
  201. * Default is 20.
  202. * {Number} margin.item.horizontal
  203. * Horizontal margin between items in pixels.
  204. * Default is 10.
  205. * {Number} margin.item.vertical
  206. * Vertical Margin between items in pixels.
  207. * Default is 10.
  208. * {Number} margin.item
  209. * Margin between items in pixels in both horizontal
  210. * and vertical direction. Default is 10.
  211. * {Number} margin
  212. * Set margin for both axis and items in pixels.
  213. * {Boolean} selectable
  214. * If true (default), items can be selected.
  215. * {Boolean} multiselect
  216. * If true, multiple items can be selected.
  217. * False by default.
  218. * {Boolean} editable
  219. * Set all editable options to true or false
  220. * {Boolean} editable.updateTime
  221. * Allow dragging an item to an other moment in time
  222. * {Boolean} editable.updateGroup
  223. * Allow dragging an item to an other group
  224. * {Boolean} editable.add
  225. * Allow creating new items on double tap
  226. * {Boolean} editable.remove
  227. * Allow removing items by clicking the delete button
  228. * top right of a selected item.
  229. * {Function(item: Item, callback: Function)} onAdd
  230. * Callback function triggered when an item is about to be added:
  231. * when the user double taps an empty space in the Timeline.
  232. * {Function(item: Item, callback: Function)} onUpdate
  233. * Callback function fired when an item is about to be updated.
  234. * This function typically has to show a dialog where the user
  235. * change the item. If not implemented, nothing happens.
  236. * {Function(item: Item, callback: Function)} onMove
  237. * Fired when an item has been moved. If not implemented,
  238. * the move action will be accepted.
  239. * {Function(item: Item, callback: Function)} onRemove
  240. * Fired when an item is about to be deleted.
  241. * If not implemented, the item will be always removed.
  242. */
  243. ItemSet.prototype.setOptions = function(options) {
  244. if (options) {
  245. // copy all options that we know
  246. var fields = ['type', 'align', 'order', 'stack', 'selectable', 'multiselect', 'groupOrder', 'dataAttributes', 'template','hide', 'snap'];
  247. util.selectiveExtend(fields, this.options, options);
  248. if ('orientation' in options) {
  249. if (typeof options.orientation === 'string') {
  250. this.options.orientation.item = options.orientation === 'top' ? 'top' : 'bottom';
  251. }
  252. else if (typeof options.orientation === 'object' && 'item' in options.orientation) {
  253. this.options.orientation.item = options.orientation.item;
  254. }
  255. }
  256. if ('margin' in options) {
  257. if (typeof options.margin === 'number') {
  258. this.options.margin.axis = options.margin;
  259. this.options.margin.item.horizontal = options.margin;
  260. this.options.margin.item.vertical = options.margin;
  261. }
  262. else if (typeof options.margin === 'object') {
  263. util.selectiveExtend(['axis'], this.options.margin, options.margin);
  264. if ('item' in options.margin) {
  265. if (typeof options.margin.item === 'number') {
  266. this.options.margin.item.horizontal = options.margin.item;
  267. this.options.margin.item.vertical = options.margin.item;
  268. }
  269. else if (typeof options.margin.item === 'object') {
  270. util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item);
  271. }
  272. }
  273. }
  274. }
  275. if ('editable' in options) {
  276. if (typeof options.editable === 'boolean') {
  277. this.options.editable.updateTime = options.editable;
  278. this.options.editable.updateGroup = options.editable;
  279. this.options.editable.add = options.editable;
  280. this.options.editable.remove = options.editable;
  281. }
  282. else if (typeof options.editable === 'object') {
  283. util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable);
  284. }
  285. }
  286. // callback functions
  287. var addCallback = (function (name) {
  288. var fn = options[name];
  289. if (fn) {
  290. if (!(fn instanceof Function)) {
  291. throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)');
  292. }
  293. this.options[name] = fn;
  294. }
  295. }).bind(this);
  296. ['onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving'].forEach(addCallback);
  297. // force the itemSet to refresh: options like orientation and margins may be changed
  298. this.markDirty();
  299. }
  300. };
  301. /**
  302. * Mark the ItemSet dirty so it will refresh everything with next redraw.
  303. * Optionally, all items can be marked as dirty and be refreshed.
  304. * @param {{refreshItems: boolean}} [options]
  305. */
  306. ItemSet.prototype.markDirty = function(options) {
  307. this.groupIds = [];
  308. this.stackDirty = true;
  309. if (options && options.refreshItems) {
  310. util.forEach(this.items, function (item) {
  311. item.dirty = true;
  312. if (item.displayed) item.redraw();
  313. });
  314. }
  315. };
  316. /**
  317. * Destroy the ItemSet
  318. */
  319. ItemSet.prototype.destroy = function() {
  320. this.hide();
  321. this.setItems(null);
  322. this.setGroups(null);
  323. this.hammer = null;
  324. this.body = null;
  325. this.conversion = null;
  326. };
  327. /**
  328. * Hide the component from the DOM
  329. */
  330. ItemSet.prototype.hide = function() {
  331. // remove the frame containing the items
  332. if (this.dom.frame.parentNode) {
  333. this.dom.frame.parentNode.removeChild(this.dom.frame);
  334. }
  335. // remove the axis with dots
  336. if (this.dom.axis.parentNode) {
  337. this.dom.axis.parentNode.removeChild(this.dom.axis);
  338. }
  339. // remove the labelset containing all group labels
  340. if (this.dom.labelSet.parentNode) {
  341. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  342. }
  343. };
  344. /**
  345. * Show the component in the DOM (when not already visible).
  346. * @return {Boolean} changed
  347. */
  348. ItemSet.prototype.show = function() {
  349. // show frame containing the items
  350. if (!this.dom.frame.parentNode) {
  351. this.body.dom.center.appendChild(this.dom.frame);
  352. }
  353. // show axis with dots
  354. if (!this.dom.axis.parentNode) {
  355. this.body.dom.backgroundVertical.appendChild(this.dom.axis);
  356. }
  357. // show labelset containing labels
  358. if (!this.dom.labelSet.parentNode) {
  359. this.body.dom.left.appendChild(this.dom.labelSet);
  360. }
  361. };
  362. /**
  363. * Set selected items by their id. Replaces the current selection
  364. * Unknown id's are silently ignored.
  365. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  366. * selected, or a single item id. If ids is undefined
  367. * or an empty array, all items will be unselected.
  368. */
  369. ItemSet.prototype.setSelection = function(ids) {
  370. var i, ii, id, item;
  371. if (ids == undefined) ids = [];
  372. if (!Array.isArray(ids)) ids = [ids];
  373. // unselect currently selected items
  374. for (i = 0, ii = this.selection.length; i < ii; i++) {
  375. id = this.selection[i];
  376. item = this.items[id];
  377. if (item) item.unselect();
  378. }
  379. // select items
  380. this.selection = [];
  381. for (i = 0, ii = ids.length; i < ii; i++) {
  382. id = ids[i];
  383. item = this.items[id];
  384. if (item) {
  385. this.selection.push(id);
  386. item.select();
  387. }
  388. }
  389. };
  390. /**
  391. * Get the selected items by their id
  392. * @return {Array} ids The ids of the selected items
  393. */
  394. ItemSet.prototype.getSelection = function() {
  395. return this.selection.concat([]);
  396. };
  397. /**
  398. * Get the id's of the currently visible items.
  399. * @returns {Array} The ids of the visible items
  400. */
  401. ItemSet.prototype.getVisibleItems = function() {
  402. var range = this.body.range.getRange();
  403. var left = this.body.util.toScreen(range.start);
  404. var right = this.body.util.toScreen(range.end);
  405. var ids = [];
  406. for (var groupId in this.groups) {
  407. if (this.groups.hasOwnProperty(groupId)) {
  408. var group = this.groups[groupId];
  409. var rawVisibleItems = group.visibleItems;
  410. // filter the "raw" set with visibleItems into a set which is really
  411. // visible by pixels
  412. for (var i = 0; i < rawVisibleItems.length; i++) {
  413. var item = rawVisibleItems[i];
  414. // TODO: also check whether visible vertically
  415. if ((item.left < right) && (item.left + item.width > left)) {
  416. ids.push(item.id);
  417. }
  418. }
  419. }
  420. }
  421. return ids;
  422. };
  423. /**
  424. * Deselect a selected item
  425. * @param {String | Number} id
  426. * @private
  427. */
  428. ItemSet.prototype._deselect = function(id) {
  429. var selection = this.selection;
  430. for (var i = 0, ii = selection.length; i < ii; i++) {
  431. if (selection[i] == id) { // non-strict comparison!
  432. selection.splice(i, 1);
  433. break;
  434. }
  435. }
  436. };
  437. /**
  438. * Repaint the component
  439. * @return {boolean} Returns true if the component is resized
  440. */
  441. ItemSet.prototype.redraw = function() {
  442. var margin = this.options.margin,
  443. range = this.body.range,
  444. asSize = util.option.asSize,
  445. options = this.options,
  446. orientation = options.orientation.item,
  447. resized = false,
  448. frame = this.dom.frame,
  449. editable = options.editable.updateTime || options.editable.updateGroup;
  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' + (editable ? ' vis-editable' : '');
  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.unsubscribe(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. if (item) {
  713. // update item
  714. if (!constructor || !(item instanceof constructor)) {
  715. // item type has changed, delete the item and recreate it
  716. me._removeItem(item);
  717. item = null;
  718. }
  719. else {
  720. me._updateItem(item, itemData);
  721. }
  722. }
  723. if (!item) {
  724. // create item
  725. if (constructor) {
  726. item = new constructor(itemData, me.conversion, me.options);
  727. item.id = id; // TODO: not so nice setting id afterwards
  728. me._addItem(item);
  729. }
  730. else if (type == 'rangeoverflow') {
  731. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  732. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
  733. '.vis-item.vis-range .vis-item-content {overflow: visible;}');
  734. }
  735. else {
  736. throw new TypeError('Unknown item type "' + type + '"');
  737. }
  738. }
  739. });
  740. this._order();
  741. this.stackDirty = true; // force re-stacking of all items next redraw
  742. this.body.emitter.emit('change', {queue: true});
  743. };
  744. /**
  745. * Handle added items
  746. * @param {Number[]} ids
  747. * @protected
  748. */
  749. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  750. /**
  751. * Handle removed items
  752. * @param {Number[]} ids
  753. * @protected
  754. */
  755. ItemSet.prototype._onRemove = function(ids) {
  756. var count = 0;
  757. var me = this;
  758. ids.forEach(function (id) {
  759. var item = me.items[id];
  760. if (item) {
  761. count++;
  762. me._removeItem(item);
  763. }
  764. });
  765. if (count) {
  766. // update order
  767. this._order();
  768. this.stackDirty = true; // force re-stacking of all items next redraw
  769. this.body.emitter.emit('change', {queue: true});
  770. }
  771. };
  772. /**
  773. * Update the order of item in all groups
  774. * @private
  775. */
  776. ItemSet.prototype._order = function() {
  777. // reorder the items in all groups
  778. // TODO: optimization: only reorder groups affected by the changed items
  779. util.forEach(this.groups, function (group) {
  780. group.order();
  781. });
  782. };
  783. /**
  784. * Handle updated groups
  785. * @param {Number[]} ids
  786. * @private
  787. */
  788. ItemSet.prototype._onUpdateGroups = function(ids) {
  789. this._onAddGroups(ids);
  790. };
  791. /**
  792. * Handle changed groups (added or updated)
  793. * @param {Number[]} ids
  794. * @private
  795. */
  796. ItemSet.prototype._onAddGroups = function(ids) {
  797. var me = this;
  798. ids.forEach(function (id) {
  799. var groupData = me.groupsData.get(id);
  800. var group = me.groups[id];
  801. if (!group) {
  802. // check for reserved ids
  803. if (id == UNGROUPED || id == BACKGROUND) {
  804. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  805. }
  806. var groupOptions = Object.create(me.options);
  807. util.extend(groupOptions, {
  808. height: null
  809. });
  810. group = new Group(id, groupData, me);
  811. me.groups[id] = group;
  812. // add items with this groupId to the new group
  813. for (var itemId in me.items) {
  814. if (me.items.hasOwnProperty(itemId)) {
  815. var item = me.items[itemId];
  816. if (item.data.group == id) {
  817. group.add(item);
  818. }
  819. }
  820. }
  821. group.order();
  822. group.show();
  823. }
  824. else {
  825. // update group
  826. group.setData(groupData);
  827. }
  828. });
  829. this.body.emitter.emit('change', {queue: true});
  830. };
  831. /**
  832. * Handle removed groups
  833. * @param {Number[]} ids
  834. * @private
  835. */
  836. ItemSet.prototype._onRemoveGroups = function(ids) {
  837. var groups = this.groups;
  838. ids.forEach(function (id) {
  839. var group = groups[id];
  840. if (group) {
  841. group.hide();
  842. delete groups[id];
  843. }
  844. });
  845. this.markDirty();
  846. this.body.emitter.emit('change', {queue: true});
  847. };
  848. /**
  849. * Reorder the groups if needed
  850. * @return {boolean} changed
  851. * @private
  852. */
  853. ItemSet.prototype._orderGroups = function () {
  854. if (this.groupsData) {
  855. // reorder the groups
  856. var groupIds = this.groupsData.getIds({
  857. order: this.options.groupOrder
  858. });
  859. var changed = !util.equalArray(groupIds, this.groupIds);
  860. if (changed) {
  861. // hide all groups, removes them from the DOM
  862. var groups = this.groups;
  863. groupIds.forEach(function (groupId) {
  864. groups[groupId].hide();
  865. });
  866. // show the groups again, attach them to the DOM in correct order
  867. groupIds.forEach(function (groupId) {
  868. groups[groupId].show();
  869. });
  870. this.groupIds = groupIds;
  871. }
  872. return changed;
  873. }
  874. else {
  875. return false;
  876. }
  877. };
  878. /**
  879. * Add a new item
  880. * @param {Item} item
  881. * @private
  882. */
  883. ItemSet.prototype._addItem = function(item) {
  884. this.items[item.id] = item;
  885. // add to group
  886. var groupId = this._getGroupId(item.data);
  887. var group = this.groups[groupId];
  888. if (group) group.add(item);
  889. };
  890. /**
  891. * Update an existing item
  892. * @param {Item} item
  893. * @param {Object} itemData
  894. * @private
  895. */
  896. ItemSet.prototype._updateItem = function(item, itemData) {
  897. var oldGroupId = item.data.group;
  898. var oldSubGroupId = item.data.subgroup;
  899. // update the items data (will redraw the item when displayed)
  900. item.setData(itemData);
  901. // update group
  902. if (oldGroupId != item.data.group || oldSubGroupId != item.data.subgroup) {
  903. var oldGroup = this.groups[oldGroupId];
  904. if (oldGroup) oldGroup.remove(item);
  905. var groupId = this._getGroupId(item.data);
  906. var group = this.groups[groupId];
  907. if (group) group.add(item);
  908. }
  909. };
  910. /**
  911. * Delete an item from the ItemSet: remove it from the DOM, from the map
  912. * with items, and from the map with visible items, and from the selection
  913. * @param {Item} item
  914. * @private
  915. */
  916. ItemSet.prototype._removeItem = function(item) {
  917. // remove from DOM
  918. item.hide();
  919. // remove from items
  920. delete this.items[item.id];
  921. // remove from selection
  922. var index = this.selection.indexOf(item.id);
  923. if (index != -1) this.selection.splice(index, 1);
  924. // remove from group
  925. item.parent && item.parent.remove(item);
  926. };
  927. /**
  928. * Create an array containing all items being a range (having an end date)
  929. * @param array
  930. * @returns {Array}
  931. * @private
  932. */
  933. ItemSet.prototype._constructByEndArray = function(array) {
  934. var endArray = [];
  935. for (var i = 0; i < array.length; i++) {
  936. if (array[i] instanceof RangeItem) {
  937. endArray.push(array[i]);
  938. }
  939. }
  940. return endArray;
  941. };
  942. /**
  943. * Register the clicked item on touch, before dragStart is initiated.
  944. *
  945. * dragStart is initiated from a mousemove event, AFTER the mouse/touch is
  946. * already moving. Therefore, the mouse/touch can sometimes be above an other
  947. * DOM element than the item itself.
  948. *
  949. * @param {Event} event
  950. * @private
  951. */
  952. ItemSet.prototype._onTouch = function (event) {
  953. // store the touched item, used in _onDragStart
  954. this.touchParams.item = this.itemFromTarget(event);
  955. this.touchParams.dragLeftItem = event.target.dragLeftItem || false;
  956. this.touchParams.dragRightItem = event.target.dragRightItem || false;
  957. this.touchParams.itemProps = null;
  958. };
  959. /**
  960. * Start dragging the selected events
  961. * @param {Event} event
  962. * @private
  963. */
  964. ItemSet.prototype._onDragStart = function (event) {
  965. if (!this.options.editable.updateTime && !this.options.editable.updateGroup) {
  966. return;
  967. }
  968. var item = this.touchParams.item || null;
  969. var me = this;
  970. var props;
  971. if (item && item.selected) {
  972. var dragLeftItem = this.touchParams.dragLeftItem;
  973. var dragRightItem = this.touchParams.dragRightItem;
  974. if (dragLeftItem) {
  975. props = {
  976. item: dragLeftItem,
  977. initialX: event.center.x,
  978. dragLeft: true,
  979. data: util.extend({}, item.data) // clone the items data
  980. };
  981. this.touchParams.itemProps = [props];
  982. }
  983. else if (dragRightItem) {
  984. props = {
  985. item: dragRightItem,
  986. initialX: event.center.x,
  987. dragRight: true,
  988. data: util.extend({}, item.data) // clone the items data
  989. };
  990. this.touchParams.itemProps = [props];
  991. }
  992. else {
  993. this.touchParams.itemProps = this.getSelection().map(function (id) {
  994. var item = me.items[id];
  995. var props = {
  996. item: item,
  997. initialX: event.center.x,
  998. data: util.extend({}, item.data) // clone the items data
  999. };
  1000. return props;
  1001. });
  1002. }
  1003. event.stopPropagation();
  1004. }
  1005. else if (this.options.editable.add && event.srcEvent.ctrlKey) {
  1006. // create a new range item when dragging with ctrl key down
  1007. this._onDragStartAddItem(event);
  1008. }
  1009. };
  1010. /**
  1011. * Start creating a new range item by dragging.
  1012. * @param {Event} event
  1013. * @private
  1014. */
  1015. ItemSet.prototype._onDragStartAddItem = function (event) {
  1016. var snap = this.options.snap || null;
  1017. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1018. var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  1019. var time = this.body.util.toTime(x);
  1020. var scale = this.body.util.getScale();
  1021. var step = this.body.util.getStep();
  1022. var start = snap ? snap(time, scale, step) : start;
  1023. var end = start;
  1024. var itemData = {
  1025. type: 'range',
  1026. start: start,
  1027. end: end,
  1028. content: 'new item'
  1029. };
  1030. var id = util.randomUUID();
  1031. itemData[this.itemsData._fieldId] = id;
  1032. var group = this.groupFromTarget(event);
  1033. if (group) {
  1034. itemData.group = group.groupId;
  1035. }
  1036. var newItem = new RangeItem(itemData, this.conversion, this.options);
  1037. newItem.id = id; // TODO: not so nice setting id afterwards
  1038. newItem.data = itemData;
  1039. this._addItem(newItem);
  1040. var props = {
  1041. item: newItem,
  1042. dragRight: true,
  1043. initialX: event.center.x,
  1044. data: util.extend({}, itemData)
  1045. };
  1046. this.touchParams.itemProps = [props];
  1047. event.stopPropagation();
  1048. };
  1049. /**
  1050. * Drag selected items
  1051. * @param {Event} event
  1052. * @private
  1053. */
  1054. ItemSet.prototype._onDrag = function (event) {
  1055. if (this.touchParams.itemProps) {
  1056. event.stopPropagation();
  1057. var me = this;
  1058. var snap = this.options.snap || null;
  1059. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  1060. var scale = this.body.util.getScale();
  1061. var step = this.body.util.getStep();
  1062. // move
  1063. this.touchParams.itemProps.forEach(function (props) {
  1064. var newProps = {};
  1065. var current = me.body.util.toTime(event.center.x - xOffset);
  1066. var initial = me.body.util.toTime(props.initialX - xOffset);
  1067. var offset = current - initial;
  1068. var itemData = util.extend({}, props.item.data); // clone the data
  1069. if (me.options.editable.updateTime) {
  1070. if (props.dragLeft) {
  1071. // drag left side of a range item
  1072. if (itemData.start != undefined) {
  1073. var initialStart = util.convert(props.data.start, 'Date');
  1074. var start = new Date(initialStart.valueOf() + offset);
  1075. itemData.start = snap ? snap(start, scale, step) : start;
  1076. }
  1077. }
  1078. else if (props.dragRight) {
  1079. // drag right side of a range item
  1080. if (itemData.end != undefined) {
  1081. var initialEnd = util.convert(props.data.end, 'Date');
  1082. var end = new Date(initialEnd.valueOf() + offset);
  1083. itemData.end = snap ? snap(end, scale, step) : end;
  1084. }
  1085. }
  1086. else {
  1087. // drag both start and end
  1088. if (itemData.start != undefined) {
  1089. var initialStart = util.convert(props.data.start, 'Date').valueOf();
  1090. var start = new Date(initialStart + offset);
  1091. if (itemData.end != undefined) {
  1092. var initialEnd = util.convert(props.data.end, 'Date');
  1093. var duration = initialEnd.valueOf() - initialStart.valueOf();
  1094. itemData.start = snap ? snap(start, scale, step) : start;
  1095. itemData.end = new Date(itemData.start.valueOf() + duration);
  1096. }
  1097. else {
  1098. itemData.start = snap ? snap(start, scale, step) : start;
  1099. }
  1100. }
  1101. }
  1102. }
  1103. if (me.options.editable.updateGroup && (!props.dragLeft && !props.dragRight)) {
  1104. if (itemData.group != undefined) {
  1105. // drag from one group to another
  1106. var group = me.groupFromTarget(event);
  1107. if (group) {
  1108. itemData.group = group.groupId;
  1109. }
  1110. }
  1111. }
  1112. // confirm moving the item
  1113. me.options.onMoving(itemData, function (itemData) {
  1114. if (itemData) {
  1115. props.item.setData(itemData);
  1116. }
  1117. });
  1118. });
  1119. this.stackDirty = true; // force re-stacking of all items next redraw
  1120. this.body.emitter.emit('change');
  1121. }
  1122. };
  1123. /**
  1124. * Move an item to another group
  1125. * @param {Item} item
  1126. * @param {String | Number} groupId
  1127. * @private
  1128. */
  1129. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1130. var group = this.groups[groupId];
  1131. if (group && group.groupId != item.data.group) {
  1132. var oldGroup = item.parent;
  1133. oldGroup.remove(item);
  1134. oldGroup.order();
  1135. group.add(item);
  1136. group.order();
  1137. item.data.group = group.groupId;
  1138. }
  1139. };
  1140. /**
  1141. * End of dragging selected items
  1142. * @param {Event} event
  1143. * @private
  1144. */
  1145. ItemSet.prototype._onDragEnd = function (event) {
  1146. if (this.touchParams.itemProps) {
  1147. event.stopPropagation();
  1148. // prepare a change set for the changed items
  1149. var changes = [];
  1150. var me = this;
  1151. var dataset = this.itemsData.getDataSet();
  1152. var itemProps = this.touchParams.itemProps ;
  1153. this.touchParams.itemProps = null;
  1154. itemProps.forEach(function (props) {
  1155. var id = props.item.id;
  1156. var exists = me.itemsData.get(id, me.itemOptions) != null;
  1157. if (!exists) {
  1158. // add a new item
  1159. me.options.onAdd(props.item.data, function (itemData) {
  1160. me._removeItem(props.item); // remove temporary item
  1161. if (itemData) {
  1162. me.itemsData.getDataSet().add(itemData);
  1163. }
  1164. // force re-stacking of all items next redraw
  1165. me.stackDirty = true;
  1166. me.body.emitter.emit('change');
  1167. });
  1168. }
  1169. else {
  1170. // update existing item
  1171. var itemData = util.extend({}, props.item.data); // clone the data
  1172. me.options.onMove(itemData, function (itemData) {
  1173. if (itemData) {
  1174. // apply changes
  1175. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1176. changes.push(itemData);
  1177. }
  1178. else {
  1179. // restore original values
  1180. props.item.setData(props.data);
  1181. me.stackDirty = true; // force re-stacking of all items next redraw
  1182. me.body.emitter.emit('change');
  1183. }
  1184. });
  1185. }
  1186. });
  1187. // apply the changes to the data (if there are changes)
  1188. if (changes.length) {
  1189. dataset.update(changes);
  1190. }
  1191. }
  1192. };
  1193. /**
  1194. * Handle selecting/deselecting an item when tapping it
  1195. * @param {Event} event
  1196. * @private
  1197. */
  1198. ItemSet.prototype._onSelectItem = function (event) {
  1199. if (!this.options.selectable) return;
  1200. var ctrlKey = event.srcEvent && event.srcEvent.ctrlKey;
  1201. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  1202. if (ctrlKey || shiftKey) {
  1203. this._onMultiSelectItem(event);
  1204. return;
  1205. }
  1206. var oldSelection = this.getSelection();
  1207. var item = this.itemFromTarget(event);
  1208. var selection = item ? [item.id] : [];
  1209. this.setSelection(selection);
  1210. var newSelection = this.getSelection();
  1211. // emit a select event,
  1212. // except when old selection is empty and new selection is still empty
  1213. if (newSelection.length > 0 || oldSelection.length > 0) {
  1214. this.body.emitter.emit('select', {
  1215. items: newSelection
  1216. });
  1217. }
  1218. };
  1219. /**
  1220. * Handle creation and updates of an item on double tap
  1221. * @param event
  1222. * @private
  1223. */
  1224. ItemSet.prototype._onAddItem = function (event) {
  1225. if (!this.options.selectable) return;
  1226. if (!this.options.editable.add) return;
  1227. var me = this,
  1228. snap = this.options.snap || null,
  1229. item = this.itemFromTarget(event);
  1230. if (item) {
  1231. // update item
  1232. // execute async handler to update the item (or cancel it)
  1233. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  1234. this.options.onUpdate(itemData, function (itemData) {
  1235. if (itemData) {
  1236. me.itemsData.getDataSet().update(itemData);
  1237. }
  1238. });
  1239. }
  1240. else {
  1241. // add item
  1242. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1243. var x = event.center.x - xAbs;
  1244. var start = this.body.util.toTime(x);
  1245. var scale = this.body.util.getScale();
  1246. var step = this.body.util.getStep();
  1247. var newItem = {
  1248. start: snap ? snap(start, scale, step) : start,
  1249. content: 'new item'
  1250. };
  1251. // when default type is a range, add a default end date to the new item
  1252. if (this.options.type === 'range') {
  1253. var end = this.body.util.toTime(x + this.props.width / 5);
  1254. newItem.end = snap ? snap(end, scale, step) : end;
  1255. }
  1256. newItem[this.itemsData._fieldId] = util.randomUUID();
  1257. var group = this.groupFromTarget(event);
  1258. if (group) {
  1259. newItem.group = group.groupId;
  1260. }
  1261. // execute async handler to customize (or cancel) adding an item
  1262. this.options.onAdd(newItem, function (item) {
  1263. if (item) {
  1264. me.itemsData.getDataSet().add(item);
  1265. // TODO: need to trigger a redraw?
  1266. }
  1267. });
  1268. }
  1269. };
  1270. /**
  1271. * Handle selecting/deselecting multiple items when holding an item
  1272. * @param {Event} event
  1273. * @private
  1274. */
  1275. ItemSet.prototype._onMultiSelectItem = function (event) {
  1276. if (!this.options.selectable) return;
  1277. var item = this.itemFromTarget(event);
  1278. if (item) {
  1279. // multi select items (if allowed)
  1280. var selection = this.options.multiselect
  1281. ? this.getSelection() // take current selection
  1282. : []; // deselect current selection
  1283. var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false;
  1284. if (shiftKey && this.options.multiselect) {
  1285. // select all items between the old selection and the tapped item
  1286. // determine the selection range
  1287. selection.push(item.id);
  1288. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  1289. // select all items within the selection range
  1290. selection = [];
  1291. for (var id in this.items) {
  1292. if (this.items.hasOwnProperty(id)) {
  1293. var _item = this.items[id];
  1294. var start = _item.data.start;
  1295. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  1296. if (start >= range.min &&
  1297. end <= range.max &&
  1298. !(_item instanceof BackgroundItem)) {
  1299. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  1300. }
  1301. }
  1302. }
  1303. }
  1304. else {
  1305. // add/remove this item from the current selection
  1306. var index = selection.indexOf(item.id);
  1307. if (index == -1) {
  1308. // item is not yet selected -> select it
  1309. selection.push(item.id);
  1310. }
  1311. else {
  1312. // item is already selected -> deselect it
  1313. selection.splice(index, 1);
  1314. }
  1315. }
  1316. this.setSelection(selection);
  1317. this.body.emitter.emit('select', {
  1318. items: this.getSelection()
  1319. });
  1320. }
  1321. };
  1322. /**
  1323. * Calculate the time range of a list of items
  1324. * @param {Array.<Object>} itemsData
  1325. * @return {{min: Date, max: Date}} Returns the range of the provided items
  1326. * @private
  1327. */
  1328. ItemSet._getItemRange = function(itemsData) {
  1329. var max = null;
  1330. var min = null;
  1331. itemsData.forEach(function (data) {
  1332. if (min == null || data.start < min) {
  1333. min = data.start;
  1334. }
  1335. if (data.end != undefined) {
  1336. if (max == null || data.end > max) {
  1337. max = data.end;
  1338. }
  1339. }
  1340. else {
  1341. if (max == null || data.start > max) {
  1342. max = data.start;
  1343. }
  1344. }
  1345. });
  1346. return {
  1347. min: min,
  1348. max: max
  1349. }
  1350. };
  1351. /**
  1352. * Find an item from an event target:
  1353. * searches for the attribute 'timeline-item' in the event target's element tree
  1354. * @param {Event} event
  1355. * @return {Item | null} item
  1356. */
  1357. ItemSet.prototype.itemFromTarget = function(event) {
  1358. var target = event.target;
  1359. while (target) {
  1360. if (target.hasOwnProperty('timeline-item')) {
  1361. return target['timeline-item'];
  1362. }
  1363. target = target.parentNode;
  1364. }
  1365. return null;
  1366. };
  1367. /**
  1368. * Find the Group from an event target:
  1369. * searches for the attribute 'timeline-group' in the event target's element tree
  1370. * @param {Event} event
  1371. * @return {Group | null} group
  1372. */
  1373. ItemSet.prototype.groupFromTarget = function(event) {
  1374. var pageY = event.center ? event.center.y : event.pageY;
  1375. for (var i = 0; i < this.groupIds.length; i++) {
  1376. var groupId = this.groupIds[i];
  1377. var group = this.groups[groupId];
  1378. var foreground = group.dom.foreground;
  1379. var top = util.getAbsoluteTop(foreground);
  1380. if (pageY > top && pageY < top + foreground.offsetHeight) {
  1381. return group;
  1382. }
  1383. if (this.options.orientation.item === 'top') {
  1384. if (i === this.groupIds.length - 1 && pageY > top) {
  1385. return group;
  1386. }
  1387. }
  1388. else {
  1389. if (i === 0 && pageY < top + foreground.offset) {
  1390. return group;
  1391. }
  1392. }
  1393. }
  1394. return null;
  1395. };
  1396. /**
  1397. * Find the ItemSet from an event target:
  1398. * searches for the attribute 'timeline-itemset' in the event target's element tree
  1399. * @param {Event} event
  1400. * @return {ItemSet | null} item
  1401. */
  1402. ItemSet.itemSetFromTarget = function(event) {
  1403. var target = event.target;
  1404. while (target) {
  1405. if (target.hasOwnProperty('timeline-itemset')) {
  1406. return target['timeline-itemset'];
  1407. }
  1408. target = target.parentNode;
  1409. }
  1410. return null;
  1411. };
  1412. module.exports = ItemSet;