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.

1639 lines
46 KiB

10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. var Hammer = require('../../module/hammer');
  2. var util = require('../../util');
  3. var DataSet = require('../../DataSet');
  4. var DataView = require('../../DataView');
  5. var TimeStep = require('../TimeStep');
  6. var Component = require('./Component');
  7. var Group = require('./Group');
  8. var BackgroundGroup = require('./BackgroundGroup');
  9. var BoxItem = require('./item/BoxItem');
  10. var PointItem = require('./item/PointItem');
  11. var RangeItem = require('./item/RangeItem');
  12. var BackgroundItem = require('./item/BackgroundItem');
  13. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  14. var BACKGROUND = '__background__'; // reserved group id for background items without group
  15. /**
  16. * An ItemSet holds a set of items and ranges which can be displayed in a
  17. * range. The width is determined by the parent of the ItemSet, and the height
  18. * is determined by the size of the items.
  19. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  20. * @param {Object} [options] See ItemSet.setOptions for the available options.
  21. * @constructor ItemSet
  22. * @extends Component
  23. */
  24. function ItemSet(body, options) {
  25. this.body = body;
  26. this.defaultOptions = {
  27. type: null, // 'box', 'point', 'range', 'background'
  28. orientation: {
  29. item: 'bottom' // item orientation: 'top' or 'bottom'
  30. },
  31. align: 'auto', // alignment of box items
  32. stack: true,
  33. groupOrder: null,
  34. selectable: true,
  35. multiselect: false,
  36. editable: {
  37. updateTime: false,
  38. updateGroup: false,
  39. add: false,
  40. remove: false
  41. },
  42. snap: TimeStep.snap,
  43. onAdd: function (item, callback) {
  44. callback(item);
  45. },
  46. onUpdate: function (item, callback) {
  47. callback(item);
  48. },
  49. onMove: function (item, callback) {
  50. callback(item);
  51. },
  52. onRemove: function (item, callback) {
  53. callback(item);
  54. },
  55. onMoving: function (item, callback) {
  56. callback(item);
  57. },
  58. margin: {
  59. item: {
  60. horizontal: 10,
  61. vertical: 10
  62. },
  63. axis: 20
  64. }
  65. };
  66. // options is shared by this ItemSet and all its items
  67. this.options = util.extend({}, this.defaultOptions);
  68. // options for getting items from the DataSet with the correct type
  69. this.itemOptions = {
  70. type: {start: 'Date', end: 'Date'}
  71. };
  72. this.conversion = {
  73. toScreen: body.util.toScreen,
  74. toTime: body.util.toTime
  75. };
  76. this.dom = {};
  77. this.props = {};
  78. this.hammer = null;
  79. var me = this;
  80. this.itemsData = null; // DataSet
  81. this.groupsData = null; // DataSet
  82. // listeners for the DataSet of the items
  83. this.itemListeners = {
  84. 'add': function (event, params, senderId) {
  85. me._onAdd(params.items);
  86. },
  87. 'update': function (event, params, senderId) {
  88. me._onUpdate(params.items);
  89. },
  90. 'remove': function (event, params, senderId) {
  91. me._onRemove(params.items);
  92. }
  93. };
  94. // listeners for the DataSet of the groups
  95. this.groupListeners = {
  96. 'add': function (event, params, senderId) {
  97. me._onAddGroups(params.items);
  98. },
  99. 'update': function (event, params, senderId) {
  100. me._onUpdateGroups(params.items);
  101. },
  102. 'remove': function (event, params, senderId) {
  103. me._onRemoveGroups(params.items);
  104. }
  105. };
  106. this.items = {}; // object with an Item for every data item
  107. this.groups = {}; // Group object for every group
  108. this.groupIds = [];
  109. this.selection = []; // list with the ids of all selected nodes
  110. this.stackDirty = true; // if true, all items will be restacked on next redraw
  111. this.touchParams = {}; // stores properties while dragging
  112. // create the HTML DOM
  113. this._create();
  114. this.setOptions(options);
  115. }
  116. ItemSet.prototype = new Component();
  117. // available item types will be registered here
  118. ItemSet.types = {
  119. background: BackgroundItem,
  120. box: BoxItem,
  121. range: RangeItem,
  122. point: PointItem
  123. };
  124. /**
  125. * Create the HTML DOM for the ItemSet
  126. */
  127. ItemSet.prototype._create = function(){
  128. var frame = document.createElement('div');
  129. frame.className = 'vis-itemset';
  130. frame['timeline-itemset'] = this;
  131. this.dom.frame = frame;
  132. // create background panel
  133. var background = document.createElement('div');
  134. background.className = 'vis-background';
  135. frame.appendChild(background);
  136. this.dom.background = background;
  137. // create foreground panel
  138. var foreground = document.createElement('div');
  139. foreground.className = 'vis-foreground';
  140. frame.appendChild(foreground);
  141. this.dom.foreground = foreground;
  142. // create axis panel
  143. var axis = document.createElement('div');
  144. axis.className = 'vis-axis';
  145. this.dom.axis = axis;
  146. // create labelset
  147. var labelSet = document.createElement('div');
  148. labelSet.className = 'vis-labelset';
  149. this.dom.labelSet = labelSet;
  150. // create ungrouped Group
  151. this._updateUngrouped();
  152. // create background Group
  153. var backgroundGroup = new BackgroundGroup(BACKGROUND, null, this);
  154. backgroundGroup.show();
  155. this.groups[BACKGROUND] = backgroundGroup;
  156. // attach event listeners
  157. // Note: we bind to the centerContainer for the case where the height
  158. // of the center container is larger than of the ItemSet, so we
  159. // can click in the empty area to create a new item or deselect an item.
  160. this.hammer = new Hammer(this.body.dom.centerContainer);
  161. // drag items when selected
  162. this.hammer.on('hammer.input', function (event) {
  163. if (event.isFirst) {
  164. this._onTouch(event);
  165. }
  166. }.bind(this));
  167. this.hammer.on('panstart', this._onDragStart.bind(this));
  168. this.hammer.on('panmove', this._onDrag.bind(this));
  169. this.hammer.on('panend', this._onDragEnd.bind(this));
  170. // 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.off(event, callback);
  619. });
  620. // remove all drawn groups
  621. ids = this.groupsData.getIds();
  622. this.groupsData = null;
  623. this._onRemoveGroups(ids); // note: this will cause a redraw
  624. }
  625. // replace the dataset
  626. if (!groups) {
  627. this.groupsData = null;
  628. }
  629. else if (groups instanceof DataSet || groups instanceof DataView) {
  630. this.groupsData = groups;
  631. }
  632. else {
  633. throw new TypeError('Data must be an instance of DataSet or DataView');
  634. }
  635. if (this.groupsData) {
  636. // subscribe to new dataset
  637. var id = this.id;
  638. util.forEach(this.groupListeners, function (callback, event) {
  639. me.groupsData.on(event, callback, id);
  640. });
  641. // draw all ms
  642. ids = this.groupsData.getIds();
  643. this._onAddGroups(ids);
  644. }
  645. // update the group holding all ungrouped items
  646. this._updateUngrouped();
  647. // update the order of all items in each group
  648. this._order();
  649. this.body.emitter.emit('change', {queue: true});
  650. };
  651. /**
  652. * Get the current groups
  653. * @returns {vis.DataSet | null} groups
  654. */
  655. ItemSet.prototype.getGroups = function() {
  656. return this.groupsData;
  657. };
  658. /**
  659. * Remove an item by its id
  660. * @param {String | Number} id
  661. */
  662. ItemSet.prototype.removeItem = function(id) {
  663. var item = this.itemsData.get(id),
  664. dataset = this.itemsData.getDataSet();
  665. if (item) {
  666. // confirm deletion
  667. this.options.onRemove(item, function (item) {
  668. if (item) {
  669. // remove by id here, it is possible that an item has no id defined
  670. // itself, so better not delete by the item itself
  671. dataset.remove(id);
  672. }
  673. });
  674. }
  675. };
  676. /**
  677. * Get the time of an item based on it's data and options.type
  678. * @param {Object} itemData
  679. * @returns {string} Returns the type
  680. * @private
  681. */
  682. ItemSet.prototype._getType = function (itemData) {
  683. return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
  684. };
  685. /**
  686. * Get the group id for an item
  687. * @param {Object} itemData
  688. * @returns {string} Returns the groupId
  689. * @private
  690. */
  691. ItemSet.prototype._getGroupId = function (itemData) {
  692. var type = this._getType(itemData);
  693. if (type == 'background' && itemData.group == undefined) {
  694. return BACKGROUND;
  695. }
  696. else {
  697. return this.groupsData ? itemData.group : UNGROUPED;
  698. }
  699. };
  700. /**
  701. * Handle updated items
  702. * @param {Number[]} ids
  703. * @protected
  704. */
  705. ItemSet.prototype._onUpdate = function(ids) {
  706. var me = this;
  707. ids.forEach(function (id) {
  708. var itemData = me.itemsData.get(id, me.itemOptions);
  709. var item = me.items[id];
  710. var type = me._getType(itemData);
  711. var constructor = ItemSet.types[type];
  712. var selected;
  713. if (item) {
  714. // update item
  715. if (!constructor || !(item instanceof constructor)) {
  716. // item type has changed, delete the item and recreate it
  717. selected = item.selected; // preserve selection of this item
  718. me._removeItem(item);
  719. item = null;
  720. }
  721. else {
  722. me._updateItem(item, itemData);
  723. }
  724. }
  725. if (!item) {
  726. // create item
  727. if (constructor) {
  728. item = new constructor(itemData, me.conversion, me.options);
  729. item.id = id; // TODO: not so nice setting id afterwards
  730. me._addItem(item);
  731. if (selected) {
  732. this.selection.push(id);
  733. item.select();
  734. }
  735. }
  736. else if (type == 'rangeoverflow') {
  737. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  738. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
  739. '.vis-item.vis-range .vis-item-content {overflow: visible;}');
  740. }
  741. else {
  742. throw new TypeError('Unknown item type "' + type + '"');
  743. }
  744. }
  745. }.bind(this));
  746. this._order();
  747. this.stackDirty = true; // force re-stacking of all items next redraw
  748. this.body.emitter.emit('change', {queue: true});
  749. };
  750. /**
  751. * Handle added items
  752. * @param {Number[]} ids
  753. * @protected
  754. */
  755. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  756. /**
  757. * Handle removed items
  758. * @param {Number[]} ids
  759. * @protected
  760. */
  761. ItemSet.prototype._onRemove = function(ids) {
  762. var count = 0;
  763. var me = this;
  764. ids.forEach(function (id) {
  765. var item = me.items[id];
  766. if (item) {
  767. count++;
  768. me._removeItem(item);
  769. }
  770. });
  771. if (count) {
  772. // update order
  773. this._order();
  774. this.stackDirty = true; // force re-stacking of all items next redraw
  775. this.body.emitter.emit('change', {queue: true});
  776. }
  777. };
  778. /**
  779. * Update the order of item in all groups
  780. * @private
  781. */
  782. ItemSet.prototype._order = function() {
  783. // reorder the items in all groups
  784. // TODO: optimization: only reorder groups affected by the changed items
  785. util.forEach(this.groups, function (group) {
  786. group.order();
  787. });
  788. };
  789. /**
  790. * Handle updated groups
  791. * @param {Number[]} ids
  792. * @private
  793. */
  794. ItemSet.prototype._onUpdateGroups = function(ids) {
  795. this._onAddGroups(ids);
  796. };
  797. /**
  798. * Handle changed groups (added or updated)
  799. * @param {Number[]} ids
  800. * @private
  801. */
  802. ItemSet.prototype._onAddGroups = function(ids) {
  803. var me = this;
  804. ids.forEach(function (id) {
  805. var groupData = me.groupsData.get(id);
  806. var group = me.groups[id];
  807. if (!group) {
  808. // check for reserved ids
  809. if (id == UNGROUPED || id == BACKGROUND) {
  810. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  811. }
  812. var groupOptions = Object.create(me.options);
  813. util.extend(groupOptions, {
  814. height: null
  815. });
  816. group = new Group(id, groupData, me);
  817. me.groups[id] = group;
  818. // add items with this groupId to the new group
  819. for (var itemId in me.items) {
  820. if (me.items.hasOwnProperty(itemId)) {
  821. var item = me.items[itemId];
  822. if (item.data.group == id) {
  823. group.add(item);
  824. }
  825. }
  826. }
  827. group.order();
  828. group.show();
  829. }
  830. else {
  831. // update group
  832. group.setData(groupData);
  833. }
  834. });
  835. this.body.emitter.emit('change', {queue: true});
  836. };
  837. /**
  838. * Handle removed groups
  839. * @param {Number[]} ids
  840. * @private
  841. */
  842. ItemSet.prototype._onRemoveGroups = function(ids) {
  843. var groups = this.groups;
  844. ids.forEach(function (id) {
  845. var group = groups[id];
  846. if (group) {
  847. group.hide();
  848. delete groups[id];
  849. }
  850. });
  851. this.markDirty();
  852. this.body.emitter.emit('change', {queue: true});
  853. };
  854. /**
  855. * Reorder the groups if needed
  856. * @return {boolean} changed
  857. * @private
  858. */
  859. ItemSet.prototype._orderGroups = function () {
  860. if (this.groupsData) {
  861. // reorder the groups
  862. var groupIds = this.groupsData.getIds({
  863. order: this.options.groupOrder
  864. });
  865. var changed = !util.equalArray(groupIds, this.groupIds);
  866. if (changed) {
  867. // hide all groups, removes them from the DOM
  868. var groups = this.groups;
  869. groupIds.forEach(function (groupId) {
  870. groups[groupId].hide();
  871. });
  872. // show the groups again, attach them to the DOM in correct order
  873. groupIds.forEach(function (groupId) {
  874. groups[groupId].show();
  875. });
  876. this.groupIds = groupIds;
  877. }
  878. return changed;
  879. }
  880. else {
  881. return false;
  882. }
  883. };
  884. /**
  885. * Add a new item
  886. * @param {Item} item
  887. * @private
  888. */
  889. ItemSet.prototype._addItem = function(item) {
  890. this.items[item.id] = item;
  891. // add to group
  892. var groupId = this._getGroupId(item.data);
  893. var group = this.groups[groupId];
  894. if (group) group.add(item);
  895. };
  896. /**
  897. * Update an existing item
  898. * @param {Item} item
  899. * @param {Object} itemData
  900. * @private
  901. */
  902. ItemSet.prototype._updateItem = function(item, itemData) {
  903. var oldGroupId = item.data.group;
  904. var oldSubGroupId = item.data.subgroup;
  905. // update the items data (will redraw the item when displayed)
  906. item.setData(itemData);
  907. // update group
  908. if (oldGroupId != item.data.group || oldSubGroupId != item.data.subgroup) {
  909. var oldGroup = this.groups[oldGroupId];
  910. if (oldGroup) oldGroup.remove(item);
  911. var groupId = this._getGroupId(item.data);
  912. var group = this.groups[groupId];
  913. if (group) group.add(item);
  914. }
  915. };
  916. /**
  917. * Delete an item from the ItemSet: remove it from the DOM, from the map
  918. * with items, and from the map with visible items, and from the selection
  919. * @param {Item} item
  920. * @private
  921. */
  922. ItemSet.prototype._removeItem = function(item) {
  923. // remove from DOM
  924. item.hide();
  925. // remove from items
  926. delete this.items[item.id];
  927. // remove from selection
  928. var index = this.selection.indexOf(item.id);
  929. if (index != -1) this.selection.splice(index, 1);
  930. // remove from group
  931. item.parent && item.parent.remove(item);
  932. };
  933. /**
  934. * Create an array containing all items being a range (having an end date)
  935. * @param array
  936. * @returns {Array}
  937. * @private
  938. */
  939. ItemSet.prototype._constructByEndArray = function(array) {
  940. var endArray = [];
  941. for (var i = 0; i < array.length; i++) {
  942. if (array[i] instanceof RangeItem) {
  943. endArray.push(array[i]);
  944. }
  945. }
  946. return endArray;
  947. };
  948. /**
  949. * Register the clicked item on touch, before dragStart is initiated.
  950. *
  951. * dragStart is initiated from a mousemove event, AFTER the mouse/touch is
  952. * already moving. Therefore, the mouse/touch can sometimes be above an other
  953. * DOM element than the item itself.
  954. *
  955. * @param {Event} event
  956. * @private
  957. */
  958. ItemSet.prototype._onTouch = function (event) {
  959. // store the touched item, used in _onDragStart
  960. this.touchParams.item = this.itemFromTarget(event);
  961. this.touchParams.dragLeftItem = event.target.dragLeftItem || false;
  962. this.touchParams.dragRightItem = event.target.dragRightItem || false;
  963. this.touchParams.itemProps = null;
  964. };
  965. /**
  966. * Start dragging the selected events
  967. * @param {Event} event
  968. * @private
  969. */
  970. ItemSet.prototype._onDragStart = function (event) {
  971. if (!this.options.editable.updateTime && !this.options.editable.updateGroup) {
  972. return;
  973. }
  974. var item = this.touchParams.item || null;
  975. var me = this;
  976. var props;
  977. if (item && item.selected) {
  978. var dragLeftItem = this.touchParams.dragLeftItem;
  979. var dragRightItem = this.touchParams.dragRightItem;
  980. if (dragLeftItem) {
  981. props = {
  982. item: dragLeftItem,
  983. initialX: event.center.x,
  984. dragLeft: true,
  985. data: util.extend({}, item.data) // clone the items data
  986. };
  987. this.touchParams.itemProps = [props];
  988. }
  989. else if (dragRightItem) {
  990. props = {
  991. item: dragRightItem,
  992. initialX: event.center.x,
  993. dragRight: true,
  994. data: util.extend({}, item.data) // clone the items data
  995. };
  996. this.touchParams.itemProps = [props];
  997. }
  998. else {
  999. this.touchParams.itemProps = this.getSelection().map(function (id) {
  1000. var item = me.items[id];
  1001. var props = {
  1002. item: item,
  1003. initialX: event.center.x,
  1004. data: util.extend({}, item.data) // clone the items data
  1005. };
  1006. return props;
  1007. });
  1008. }
  1009. event.stopPropagation();
  1010. }
  1011. else if (this.options.editable.add && event.srcEvent.ctrlKey) {
  1012. // create a new range item when dragging with ctrl key down
  1013. this._onDragStartAddItem(event);
  1014. }
  1015. };
  1016. /**
  1017. * Start creating a new range item by dragging.
  1018. * @param {Event} event
  1019. * @private
  1020. */
  1021. ItemSet.prototype._onDragStartAddItem = function (event) {
  1022. var snap = this.options.snap || null;
  1023. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1024. var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  1025. var time = this.body.util.toTime(x);
  1026. var scale = this.body.util.getScale();
  1027. var step = this.body.util.getStep();
  1028. var start = snap ? snap(time, scale, step) : start;
  1029. var end = start;
  1030. var itemData = {
  1031. type: 'range',
  1032. start: start,
  1033. end: end,
  1034. content: 'new item'
  1035. };
  1036. var id = util.randomUUID();
  1037. itemData[this.itemsData._fieldId] = id;
  1038. var group = this.groupFromTarget(event);
  1039. if (group) {
  1040. itemData.group = group.groupId;
  1041. }
  1042. var newItem = new RangeItem(itemData, this.conversion, this.options);
  1043. newItem.id = id; // TODO: not so nice setting id afterwards
  1044. newItem.data = itemData;
  1045. this._addItem(newItem);
  1046. var props = {
  1047. item: newItem,
  1048. dragRight: true,
  1049. initialX: event.center.x,
  1050. data: util.extend({}, itemData)
  1051. };
  1052. this.touchParams.itemProps = [props];
  1053. event.stopPropagation();
  1054. };
  1055. /**
  1056. * Drag selected items
  1057. * @param {Event} event
  1058. * @private
  1059. */
  1060. ItemSet.prototype._onDrag = function (event) {
  1061. if (this.touchParams.itemProps) {
  1062. event.stopPropagation();
  1063. var me = this;
  1064. var snap = this.options.snap || null;
  1065. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  1066. var scale = this.body.util.getScale();
  1067. var step = this.body.util.getStep();
  1068. // move
  1069. this.touchParams.itemProps.forEach(function (props) {
  1070. var newProps = {};
  1071. var current = me.body.util.toTime(event.center.x - xOffset);
  1072. var initial = me.body.util.toTime(props.initialX - xOffset);
  1073. var offset = current - initial;
  1074. var itemData = util.extend({}, props.item.data); // clone the data
  1075. if (me.options.editable.updateTime) {
  1076. if (props.dragLeft) {
  1077. // drag left side of a range item
  1078. if (itemData.start != undefined) {
  1079. var initialStart = util.convert(props.data.start, 'Date');
  1080. var start = new Date(initialStart.valueOf() + offset);
  1081. itemData.start = snap ? snap(start, scale, step) : start;
  1082. }
  1083. }
  1084. else if (props.dragRight) {
  1085. // drag right side of a range item
  1086. if (itemData.end != undefined) {
  1087. var initialEnd = util.convert(props.data.end, 'Date');
  1088. var end = new Date(initialEnd.valueOf() + offset);
  1089. itemData.end = snap ? snap(end, scale, step) : end;
  1090. }
  1091. }
  1092. else {
  1093. // drag both start and end
  1094. if (itemData.start != undefined) {
  1095. var initialStart = util.convert(props.data.start, 'Date').valueOf();
  1096. var start = new Date(initialStart + offset);
  1097. if (itemData.end != undefined) {
  1098. var initialEnd = util.convert(props.data.end, 'Date');
  1099. var duration = initialEnd.valueOf() - initialStart.valueOf();
  1100. itemData.start = snap ? snap(start, scale, step) : start;
  1101. itemData.end = new Date(itemData.start.valueOf() + duration);
  1102. }
  1103. else {
  1104. itemData.start = snap ? snap(start, scale, step) : start;
  1105. }
  1106. }
  1107. }
  1108. }
  1109. if (me.options.editable.updateGroup && (!props.dragLeft && !props.dragRight)) {
  1110. if (itemData.group != undefined) {
  1111. // drag from one group to another
  1112. var group = me.groupFromTarget(event);
  1113. if (group) {
  1114. itemData.group = group.groupId;
  1115. }
  1116. }
  1117. }
  1118. // confirm moving the item
  1119. me.options.onMoving(itemData, function (itemData) {
  1120. if (itemData) {
  1121. props.item.setData(itemData);
  1122. }
  1123. });
  1124. });
  1125. this.stackDirty = true; // force re-stacking of all items next redraw
  1126. this.body.emitter.emit('change');
  1127. }
  1128. };
  1129. /**
  1130. * Move an item to another group
  1131. * @param {Item} item
  1132. * @param {String | Number} groupId
  1133. * @private
  1134. */
  1135. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1136. var group = this.groups[groupId];
  1137. if (group && group.groupId != item.data.group) {
  1138. var oldGroup = item.parent;
  1139. oldGroup.remove(item);
  1140. oldGroup.order();
  1141. group.add(item);
  1142. group.order();
  1143. item.data.group = group.groupId;
  1144. }
  1145. };
  1146. /**
  1147. * End of dragging selected items
  1148. * @param {Event} event
  1149. * @private
  1150. */
  1151. ItemSet.prototype._onDragEnd = function (event) {
  1152. if (this.touchParams.itemProps) {
  1153. event.stopPropagation();
  1154. // prepare a change set for the changed items
  1155. var changes = [];
  1156. var me = this;
  1157. var dataset = this.itemsData.getDataSet();
  1158. var itemProps = this.touchParams.itemProps ;
  1159. this.touchParams.itemProps = null;
  1160. itemProps.forEach(function (props) {
  1161. var id = props.item.id;
  1162. var exists = me.itemsData.get(id, me.itemOptions) != null;
  1163. if (!exists) {
  1164. // add a new item
  1165. me.options.onAdd(props.item.data, function (itemData) {
  1166. me._removeItem(props.item); // remove temporary item
  1167. if (itemData) {
  1168. me.itemsData.getDataSet().add(itemData);
  1169. }
  1170. // force re-stacking of all items next redraw
  1171. me.stackDirty = true;
  1172. me.body.emitter.emit('change');
  1173. });
  1174. }
  1175. else {
  1176. // update existing item
  1177. var itemData = util.extend({}, props.item.data); // clone the data
  1178. me.options.onMove(itemData, function (itemData) {
  1179. if (itemData) {
  1180. // apply changes
  1181. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1182. changes.push(itemData);
  1183. }
  1184. else {
  1185. // restore original values
  1186. props.item.setData(props.data);
  1187. me.stackDirty = true; // force re-stacking of all items next redraw
  1188. me.body.emitter.emit('change');
  1189. }
  1190. });
  1191. }
  1192. });
  1193. // apply the changes to the data (if there are changes)
  1194. if (changes.length) {
  1195. dataset.update(changes);
  1196. }
  1197. }
  1198. };
  1199. /**
  1200. * Handle selecting/deselecting an item when tapping it
  1201. * @param {Event} event
  1202. * @private
  1203. */
  1204. ItemSet.prototype._onSelectItem = function (event) {
  1205. if (!this.options.selectable) return;
  1206. var ctrlKey = event.srcEvent && event.srcEvent.ctrlKey;
  1207. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  1208. if (ctrlKey || shiftKey) {
  1209. this._onMultiSelectItem(event);
  1210. return;
  1211. }
  1212. var oldSelection = this.getSelection();
  1213. var item = this.itemFromTarget(event);
  1214. var selection = item ? [item.id] : [];
  1215. this.setSelection(selection);
  1216. var newSelection = this.getSelection();
  1217. // emit a select event,
  1218. // except when old selection is empty and new selection is still empty
  1219. if (newSelection.length > 0 || oldSelection.length > 0) {
  1220. this.body.emitter.emit('select', {
  1221. items: newSelection
  1222. });
  1223. }
  1224. };
  1225. /**
  1226. * Handle creation and updates of an item on double tap
  1227. * @param event
  1228. * @private
  1229. */
  1230. ItemSet.prototype._onAddItem = function (event) {
  1231. if (!this.options.selectable) return;
  1232. if (!this.options.editable.add) return;
  1233. var me = this;
  1234. var snap = this.options.snap || null;
  1235. var item = this.itemFromTarget(event);
  1236. event.stopPropagation();
  1237. if (item) {
  1238. // update item
  1239. // execute async handler to update the item (or cancel it)
  1240. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  1241. this.options.onUpdate(itemData, function (itemData) {
  1242. if (itemData) {
  1243. me.itemsData.getDataSet().update(itemData);
  1244. }
  1245. });
  1246. }
  1247. else {
  1248. // add item
  1249. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1250. var x = event.center.x - xAbs;
  1251. var start = this.body.util.toTime(x);
  1252. var scale = this.body.util.getScale();
  1253. var step = this.body.util.getStep();
  1254. var newItem = {
  1255. start: snap ? snap(start, scale, step) : start,
  1256. content: 'new item'
  1257. };
  1258. // when default type is a range, add a default end date to the new item
  1259. if (this.options.type === 'range') {
  1260. var end = this.body.util.toTime(x + this.props.width / 5);
  1261. newItem.end = snap ? snap(end, scale, step) : end;
  1262. }
  1263. newItem[this.itemsData._fieldId] = util.randomUUID();
  1264. var group = this.groupFromTarget(event);
  1265. if (group) {
  1266. newItem.group = group.groupId;
  1267. }
  1268. // execute async handler to customize (or cancel) adding an item
  1269. this.options.onAdd(newItem, function (item) {
  1270. if (item) {
  1271. me.itemsData.getDataSet().add(item);
  1272. // TODO: need to trigger a redraw?
  1273. }
  1274. });
  1275. }
  1276. };
  1277. /**
  1278. * Handle selecting/deselecting multiple items when holding an item
  1279. * @param {Event} event
  1280. * @private
  1281. */
  1282. ItemSet.prototype._onMultiSelectItem = function (event) {
  1283. if (!this.options.selectable) return;
  1284. var item = this.itemFromTarget(event);
  1285. if (item) {
  1286. // multi select items (if allowed)
  1287. var selection = this.options.multiselect
  1288. ? this.getSelection() // take current selection
  1289. : []; // deselect current selection
  1290. var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false;
  1291. if (shiftKey && this.options.multiselect) {
  1292. // select all items between the old selection and the tapped item
  1293. // determine the selection range
  1294. selection.push(item.id);
  1295. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  1296. // select all items within the selection range
  1297. selection = [];
  1298. for (var id in this.items) {
  1299. if (this.items.hasOwnProperty(id)) {
  1300. var _item = this.items[id];
  1301. var start = _item.data.start;
  1302. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  1303. if (start >= range.min &&
  1304. end <= range.max &&
  1305. !(_item instanceof BackgroundItem)) {
  1306. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  1307. }
  1308. }
  1309. }
  1310. }
  1311. else {
  1312. // add/remove this item from the current selection
  1313. var index = selection.indexOf(item.id);
  1314. if (index == -1) {
  1315. // item is not yet selected -> select it
  1316. selection.push(item.id);
  1317. }
  1318. else {
  1319. // item is already selected -> deselect it
  1320. selection.splice(index, 1);
  1321. }
  1322. }
  1323. this.setSelection(selection);
  1324. this.body.emitter.emit('select', {
  1325. items: this.getSelection()
  1326. });
  1327. }
  1328. };
  1329. /**
  1330. * Calculate the time range of a list of items
  1331. * @param {Array.<Object>} itemsData
  1332. * @return {{min: Date, max: Date}} Returns the range of the provided items
  1333. * @private
  1334. */
  1335. ItemSet._getItemRange = function(itemsData) {
  1336. var max = null;
  1337. var min = null;
  1338. itemsData.forEach(function (data) {
  1339. if (min == null || data.start < min) {
  1340. min = data.start;
  1341. }
  1342. if (data.end != undefined) {
  1343. if (max == null || data.end > max) {
  1344. max = data.end;
  1345. }
  1346. }
  1347. else {
  1348. if (max == null || data.start > max) {
  1349. max = data.start;
  1350. }
  1351. }
  1352. });
  1353. return {
  1354. min: min,
  1355. max: max
  1356. }
  1357. };
  1358. /**
  1359. * Find an item from an event target:
  1360. * searches for the attribute 'timeline-item' in the event target's element tree
  1361. * @param {Event} event
  1362. * @return {Item | null} item
  1363. */
  1364. ItemSet.prototype.itemFromTarget = function(event) {
  1365. var target = event.target;
  1366. while (target) {
  1367. if (target.hasOwnProperty('timeline-item')) {
  1368. return target['timeline-item'];
  1369. }
  1370. target = target.parentNode;
  1371. }
  1372. return null;
  1373. };
  1374. /**
  1375. * Find the Group from an event target:
  1376. * searches for the attribute 'timeline-group' in the event target's element tree
  1377. * @param {Event} event
  1378. * @return {Group | null} group
  1379. */
  1380. ItemSet.prototype.groupFromTarget = function(event) {
  1381. var clientY = event.center ? event.center.y : event.clientY;
  1382. for (var i = 0; i < this.groupIds.length; i++) {
  1383. var groupId = this.groupIds[i];
  1384. var group = this.groups[groupId];
  1385. var foreground = group.dom.foreground;
  1386. var top = util.getAbsoluteTop(foreground);
  1387. if (clientY > top && clientY < top + foreground.offsetHeight) {
  1388. return group;
  1389. }
  1390. if (this.options.orientation.item === 'top') {
  1391. if (i === this.groupIds.length - 1 && clientY > top) {
  1392. return group;
  1393. }
  1394. }
  1395. else {
  1396. if (i === 0 && clientY < top + foreground.offset) {
  1397. return group;
  1398. }
  1399. }
  1400. }
  1401. return null;
  1402. };
  1403. /**
  1404. * Find the ItemSet from an event target:
  1405. * searches for the attribute 'timeline-itemset' in the event target's element tree
  1406. * @param {Event} event
  1407. * @return {ItemSet | null} item
  1408. */
  1409. ItemSet.itemSetFromTarget = function(event) {
  1410. var target = event.target;
  1411. while (target) {
  1412. if (target.hasOwnProperty('timeline-itemset')) {
  1413. return target['timeline-itemset'];
  1414. }
  1415. target = target.parentNode;
  1416. }
  1417. return null;
  1418. };
  1419. module.exports = ItemSet;