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.

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