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.

1658 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. // recalculate absolute position (before redrawing groups)
  450. this.props.top = this.body.domProps.top.height + this.body.domProps.border.top;
  451. this.props.left = this.body.domProps.left.width + this.body.domProps.border.left;
  452. // update class name
  453. frame.className = 'vis-itemset';
  454. // reorder the groups (if needed)
  455. resized = this._orderGroups() || resized;
  456. // check whether zoomed (in that case we need to re-stack everything)
  457. // TODO: would be nicer to get this as a trigger from Range
  458. var visibleInterval = range.end - range.start;
  459. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.props.width != this.props.lastWidth);
  460. if (zoomed) this.stackDirty = true;
  461. this.lastVisibleInterval = visibleInterval;
  462. this.props.lastWidth = this.props.width;
  463. var restack = this.stackDirty;
  464. var firstGroup = this._firstGroup();
  465. var firstMargin = {
  466. item: margin.item,
  467. axis: margin.axis
  468. };
  469. var nonFirstMargin = {
  470. item: margin.item,
  471. axis: margin.item.vertical / 2
  472. };
  473. var height = 0;
  474. var minHeight = margin.axis + margin.item.vertical;
  475. // redraw the background group
  476. this.groups[BACKGROUND].redraw(range, nonFirstMargin, restack);
  477. // redraw all regular groups
  478. util.forEach(this.groups, function (group) {
  479. var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
  480. var groupResized = group.redraw(range, groupMargin, restack);
  481. resized = groupResized || resized;
  482. height += group.height;
  483. });
  484. height = Math.max(height, minHeight);
  485. this.stackDirty = false;
  486. // update frame height
  487. frame.style.height = asSize(height);
  488. // calculate actual size
  489. this.props.width = frame.offsetWidth;
  490. this.props.height = height;
  491. // reposition axis
  492. this.dom.axis.style.top = asSize((orientation == 'top') ?
  493. (this.body.domProps.top.height + this.body.domProps.border.top) :
  494. (this.body.domProps.top.height + this.body.domProps.centerContainer.height));
  495. this.dom.axis.style.left = '0';
  496. // check if this component is resized
  497. resized = this._isResized() || resized;
  498. return resized;
  499. };
  500. /**
  501. * Get the first group, aligned with the axis
  502. * @return {Group | null} firstGroup
  503. * @private
  504. */
  505. ItemSet.prototype._firstGroup = function() {
  506. var firstGroupIndex = (this.options.orientation.item == 'top') ? 0 : (this.groupIds.length - 1);
  507. var firstGroupId = this.groupIds[firstGroupIndex];
  508. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  509. return firstGroup || null;
  510. };
  511. /**
  512. * Create or delete the group holding all ungrouped items. This group is used when
  513. * there are no groups specified.
  514. * @protected
  515. */
  516. ItemSet.prototype._updateUngrouped = function() {
  517. var ungrouped = this.groups[UNGROUPED];
  518. var background = this.groups[BACKGROUND];
  519. var item, itemId;
  520. if (this.groupsData) {
  521. // remove the group holding all ungrouped items
  522. if (ungrouped) {
  523. ungrouped.hide();
  524. delete this.groups[UNGROUPED];
  525. for (itemId in this.items) {
  526. if (this.items.hasOwnProperty(itemId)) {
  527. item = this.items[itemId];
  528. item.parent && item.parent.remove(item);
  529. var groupId = this._getGroupId(item.data);
  530. var group = this.groups[groupId];
  531. group && group.add(item) || item.hide();
  532. }
  533. }
  534. }
  535. }
  536. else {
  537. // create a group holding all (unfiltered) items
  538. if (!ungrouped) {
  539. var id = null;
  540. var data = null;
  541. ungrouped = new Group(id, data, this);
  542. this.groups[UNGROUPED] = ungrouped;
  543. for (itemId in this.items) {
  544. if (this.items.hasOwnProperty(itemId)) {
  545. item = this.items[itemId];
  546. ungrouped.add(item);
  547. }
  548. }
  549. ungrouped.show();
  550. }
  551. }
  552. };
  553. /**
  554. * Get the element for the labelset
  555. * @return {HTMLElement} labelSet
  556. */
  557. ItemSet.prototype.getLabelSet = function() {
  558. return this.dom.labelSet;
  559. };
  560. /**
  561. * Set items
  562. * @param {vis.DataSet | null} items
  563. */
  564. ItemSet.prototype.setItems = function(items) {
  565. var me = this,
  566. ids,
  567. oldItemsData = this.itemsData;
  568. // replace the dataset
  569. if (!items) {
  570. this.itemsData = null;
  571. }
  572. else if (items instanceof DataSet || items instanceof DataView) {
  573. this.itemsData = items;
  574. }
  575. else {
  576. throw new TypeError('Data must be an instance of DataSet or DataView');
  577. }
  578. if (oldItemsData) {
  579. // unsubscribe from old dataset
  580. util.forEach(this.itemListeners, function (callback, event) {
  581. oldItemsData.off(event, callback);
  582. });
  583. // remove all drawn items
  584. ids = oldItemsData.getIds();
  585. this._onRemove(ids);
  586. }
  587. if (this.itemsData) {
  588. // subscribe to new dataset
  589. var id = this.id;
  590. util.forEach(this.itemListeners, function (callback, event) {
  591. me.itemsData.on(event, callback, id);
  592. });
  593. // add all new items
  594. ids = this.itemsData.getIds();
  595. this._onAdd(ids);
  596. // update the group holding all ungrouped items
  597. this._updateUngrouped();
  598. }
  599. };
  600. /**
  601. * Get the current items
  602. * @returns {vis.DataSet | null}
  603. */
  604. ItemSet.prototype.getItems = function() {
  605. return this.itemsData;
  606. };
  607. /**
  608. * Set groups
  609. * @param {vis.DataSet} groups
  610. */
  611. ItemSet.prototype.setGroups = function(groups) {
  612. var me = this,
  613. ids;
  614. // unsubscribe from current dataset
  615. if (this.groupsData) {
  616. util.forEach(this.groupListeners, function (callback, event) {
  617. me.groupsData.off(event, callback);
  618. });
  619. // remove all drawn groups
  620. ids = this.groupsData.getIds();
  621. this.groupsData = null;
  622. this._onRemoveGroups(ids); // note: this will cause a redraw
  623. }
  624. // replace the dataset
  625. if (!groups) {
  626. this.groupsData = null;
  627. }
  628. else if (groups instanceof DataSet || groups instanceof DataView) {
  629. this.groupsData = groups;
  630. }
  631. else {
  632. throw new TypeError('Data must be an instance of DataSet or DataView');
  633. }
  634. if (this.groupsData) {
  635. // subscribe to new dataset
  636. var id = this.id;
  637. util.forEach(this.groupListeners, function (callback, event) {
  638. me.groupsData.on(event, callback, id);
  639. });
  640. // draw all ms
  641. ids = this.groupsData.getIds();
  642. this._onAddGroups(ids);
  643. }
  644. // update the group holding all ungrouped items
  645. this._updateUngrouped();
  646. // update the order of all items in each group
  647. this._order();
  648. this.body.emitter.emit('change', {queue: true});
  649. };
  650. /**
  651. * Get the current groups
  652. * @returns {vis.DataSet | null} groups
  653. */
  654. ItemSet.prototype.getGroups = function() {
  655. return this.groupsData;
  656. };
  657. /**
  658. * Remove an item by its id
  659. * @param {String | Number} id
  660. */
  661. ItemSet.prototype.removeItem = function(id) {
  662. var item = this.itemsData.get(id),
  663. dataset = this.itemsData.getDataSet();
  664. if (item) {
  665. // confirm deletion
  666. this.options.onRemove(item, function (item) {
  667. if (item) {
  668. // remove by id here, it is possible that an item has no id defined
  669. // itself, so better not delete by the item itself
  670. dataset.remove(id);
  671. }
  672. });
  673. }
  674. };
  675. /**
  676. * Get the time of an item based on it's data and options.type
  677. * @param {Object} itemData
  678. * @returns {string} Returns the type
  679. * @private
  680. */
  681. ItemSet.prototype._getType = function (itemData) {
  682. return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
  683. };
  684. /**
  685. * Get the group id for an item
  686. * @param {Object} itemData
  687. * @returns {string} Returns the groupId
  688. * @private
  689. */
  690. ItemSet.prototype._getGroupId = function (itemData) {
  691. var type = this._getType(itemData);
  692. if (type == 'background' && itemData.group == undefined) {
  693. return BACKGROUND;
  694. }
  695. else {
  696. return this.groupsData ? itemData.group : UNGROUPED;
  697. }
  698. };
  699. /**
  700. * Handle updated items
  701. * @param {Number[]} ids
  702. * @protected
  703. */
  704. ItemSet.prototype._onUpdate = function(ids) {
  705. var me = this;
  706. ids.forEach(function (id) {
  707. var itemData = me.itemsData.get(id, me.itemOptions);
  708. var item = me.items[id];
  709. var type = me._getType(itemData);
  710. var constructor = ItemSet.types[type];
  711. var selected;
  712. if (item) {
  713. // update item
  714. if (!constructor || !(item instanceof constructor)) {
  715. // item type has changed, delete the item and recreate it
  716. selected = item.selected; // preserve selection of this item
  717. me._removeItem(item);
  718. item = null;
  719. }
  720. else {
  721. me._updateItem(item, itemData);
  722. }
  723. }
  724. if (!item) {
  725. // create item
  726. if (constructor) {
  727. item = new constructor(itemData, me.conversion, me.options);
  728. item.id = id; // TODO: not so nice setting id afterwards
  729. me._addItem(item);
  730. if (selected) {
  731. this.selection.push(id);
  732. item.select();
  733. }
  734. }
  735. else if (type == 'rangeoverflow') {
  736. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  737. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
  738. '.vis-item.vis-range .vis-item-content {overflow: visible;}');
  739. }
  740. else {
  741. throw new TypeError('Unknown item type "' + type + '"');
  742. }
  743. }
  744. }.bind(this));
  745. this._order();
  746. this.stackDirty = true; // force re-stacking of all items next redraw
  747. this.body.emitter.emit('change', {queue: true});
  748. };
  749. /**
  750. * Handle added items
  751. * @param {Number[]} ids
  752. * @protected
  753. */
  754. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  755. /**
  756. * Handle removed items
  757. * @param {Number[]} ids
  758. * @protected
  759. */
  760. ItemSet.prototype._onRemove = function(ids) {
  761. var count = 0;
  762. var me = this;
  763. ids.forEach(function (id) {
  764. var item = me.items[id];
  765. if (item) {
  766. count++;
  767. me._removeItem(item);
  768. }
  769. });
  770. if (count) {
  771. // update order
  772. this._order();
  773. this.stackDirty = true; // force re-stacking of all items next redraw
  774. this.body.emitter.emit('change', {queue: true});
  775. }
  776. };
  777. /**
  778. * Update the order of item in all groups
  779. * @private
  780. */
  781. ItemSet.prototype._order = function() {
  782. // reorder the items in all groups
  783. // TODO: optimization: only reorder groups affected by the changed items
  784. util.forEach(this.groups, function (group) {
  785. group.order();
  786. });
  787. };
  788. /**
  789. * Handle updated groups
  790. * @param {Number[]} ids
  791. * @private
  792. */
  793. ItemSet.prototype._onUpdateGroups = function(ids) {
  794. this._onAddGroups(ids);
  795. };
  796. /**
  797. * Handle changed groups (added or updated)
  798. * @param {Number[]} ids
  799. * @private
  800. */
  801. ItemSet.prototype._onAddGroups = function(ids) {
  802. var me = this;
  803. ids.forEach(function (id) {
  804. var groupData = me.groupsData.get(id);
  805. var group = me.groups[id];
  806. if (!group) {
  807. // check for reserved ids
  808. if (id == UNGROUPED || id == BACKGROUND) {
  809. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  810. }
  811. var groupOptions = Object.create(me.options);
  812. util.extend(groupOptions, {
  813. height: null
  814. });
  815. group = new Group(id, groupData, me);
  816. me.groups[id] = group;
  817. // add items with this groupId to the new group
  818. for (var itemId in me.items) {
  819. if (me.items.hasOwnProperty(itemId)) {
  820. var item = me.items[itemId];
  821. if (item.data.group == id) {
  822. group.add(item);
  823. }
  824. }
  825. }
  826. group.order();
  827. group.show();
  828. }
  829. else {
  830. // update group
  831. group.setData(groupData);
  832. }
  833. });
  834. this.body.emitter.emit('change', {queue: true});
  835. };
  836. /**
  837. * Handle removed groups
  838. * @param {Number[]} ids
  839. * @private
  840. */
  841. ItemSet.prototype._onRemoveGroups = function(ids) {
  842. var groups = this.groups;
  843. ids.forEach(function (id) {
  844. var group = groups[id];
  845. if (group) {
  846. group.hide();
  847. delete groups[id];
  848. }
  849. });
  850. this.markDirty();
  851. this.body.emitter.emit('change', {queue: true});
  852. };
  853. /**
  854. * Reorder the groups if needed
  855. * @return {boolean} changed
  856. * @private
  857. */
  858. ItemSet.prototype._orderGroups = function () {
  859. if (this.groupsData) {
  860. // reorder the groups
  861. var groupIds = this.groupsData.getIds({
  862. order: this.options.groupOrder
  863. });
  864. var changed = !util.equalArray(groupIds, this.groupIds);
  865. if (changed) {
  866. // hide all groups, removes them from the DOM
  867. var groups = this.groups;
  868. groupIds.forEach(function (groupId) {
  869. groups[groupId].hide();
  870. });
  871. // show the groups again, attach them to the DOM in correct order
  872. groupIds.forEach(function (groupId) {
  873. groups[groupId].show();
  874. });
  875. this.groupIds = groupIds;
  876. }
  877. return changed;
  878. }
  879. else {
  880. return false;
  881. }
  882. };
  883. /**
  884. * Add a new item
  885. * @param {Item} item
  886. * @private
  887. */
  888. ItemSet.prototype._addItem = function(item) {
  889. this.items[item.id] = item;
  890. // add to group
  891. var groupId = this._getGroupId(item.data);
  892. var group = this.groups[groupId];
  893. if (group) group.add(item);
  894. };
  895. /**
  896. * Update an existing item
  897. * @param {Item} item
  898. * @param {Object} itemData
  899. * @private
  900. */
  901. ItemSet.prototype._updateItem = function(item, itemData) {
  902. var oldGroupId = item.data.group;
  903. var oldSubGroupId = item.data.subgroup;
  904. // update the items data (will redraw the item when displayed)
  905. item.setData(itemData);
  906. // update group
  907. if (oldGroupId != item.data.group || oldSubGroupId != item.data.subgroup) {
  908. var oldGroup = this.groups[oldGroupId];
  909. if (oldGroup) oldGroup.remove(item);
  910. var groupId = this._getGroupId(item.data);
  911. var group = this.groups[groupId];
  912. if (group) group.add(item);
  913. }
  914. };
  915. /**
  916. * Delete an item from the ItemSet: remove it from the DOM, from the map
  917. * with items, and from the map with visible items, and from the selection
  918. * @param {Item} item
  919. * @private
  920. */
  921. ItemSet.prototype._removeItem = function(item) {
  922. // remove from DOM
  923. item.hide();
  924. // remove from items
  925. delete this.items[item.id];
  926. // remove from selection
  927. var index = this.selection.indexOf(item.id);
  928. if (index != -1) this.selection.splice(index, 1);
  929. // remove from group
  930. item.parent && item.parent.remove(item);
  931. };
  932. /**
  933. * Create an array containing all items being a range (having an end date)
  934. * @param array
  935. * @returns {Array}
  936. * @private
  937. */
  938. ItemSet.prototype._constructByEndArray = function(array) {
  939. var endArray = [];
  940. for (var i = 0; i < array.length; i++) {
  941. if (array[i] instanceof RangeItem) {
  942. endArray.push(array[i]);
  943. }
  944. }
  945. return endArray;
  946. };
  947. /**
  948. * Register the clicked item on touch, before dragStart is initiated.
  949. *
  950. * dragStart is initiated from a mousemove event, AFTER the mouse/touch is
  951. * already moving. Therefore, the mouse/touch can sometimes be above an other
  952. * DOM element than the item itself.
  953. *
  954. * @param {Event} event
  955. * @private
  956. */
  957. ItemSet.prototype._onTouch = function (event) {
  958. // store the touched item, used in _onDragStart
  959. this.touchParams.item = this.itemFromTarget(event);
  960. this.touchParams.dragLeftItem = event.target.dragLeftItem || false;
  961. this.touchParams.dragRightItem = event.target.dragRightItem || false;
  962. this.touchParams.itemProps = null;
  963. };
  964. /**
  965. * Start dragging the selected events
  966. * @param {Event} event
  967. * @private
  968. */
  969. ItemSet.prototype._onDragStart = function (event) {
  970. var item = this.touchParams.item || null;
  971. var me = this;
  972. var props;
  973. if (item && item.selected) {
  974. if (!this.options.editable.updateTime &&
  975. !this.options.editable.updateGroup &&
  976. !item.editable) {
  977. return;
  978. }
  979. // override options.editable
  980. if (item.editable === false) {
  981. return;
  982. }
  983. var dragLeftItem = this.touchParams.dragLeftItem;
  984. var dragRightItem = this.touchParams.dragRightItem;
  985. if (dragLeftItem) {
  986. props = {
  987. item: dragLeftItem,
  988. initialX: event.center.x,
  989. dragLeft: true,
  990. data: util.extend({}, item.data) // clone the items data
  991. };
  992. this.touchParams.itemProps = [props];
  993. }
  994. else if (dragRightItem) {
  995. props = {
  996. item: dragRightItem,
  997. initialX: event.center.x,
  998. dragRight: true,
  999. data: util.extend({}, item.data) // clone the items data
  1000. };
  1001. this.touchParams.itemProps = [props];
  1002. }
  1003. else {
  1004. this.touchParams.itemProps = this.getSelection().map(function (id) {
  1005. var item = me.items[id];
  1006. var props = {
  1007. item: item,
  1008. initialX: event.center.x,
  1009. data: util.extend({}, item.data) // clone the items data
  1010. };
  1011. return props;
  1012. });
  1013. }
  1014. event.stopPropagation();
  1015. }
  1016. else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  1017. // create a new range item when dragging with ctrl key down
  1018. this._onDragStartAddItem(event);
  1019. }
  1020. };
  1021. /**
  1022. * Start creating a new range item by dragging.
  1023. * @param {Event} event
  1024. * @private
  1025. */
  1026. ItemSet.prototype._onDragStartAddItem = function (event) {
  1027. var snap = this.options.snap || null;
  1028. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1029. var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  1030. var time = this.body.util.toTime(x);
  1031. var scale = this.body.util.getScale();
  1032. var step = this.body.util.getStep();
  1033. var start = snap ? snap(time, scale, step) : start;
  1034. var end = start;
  1035. var itemData = {
  1036. type: 'range',
  1037. start: start,
  1038. end: end,
  1039. content: 'new item'
  1040. };
  1041. var id = util.randomUUID();
  1042. itemData[this.itemsData._fieldId] = id;
  1043. var group = this.groupFromTarget(event);
  1044. if (group) {
  1045. itemData.group = group.groupId;
  1046. }
  1047. var newItem = new RangeItem(itemData, this.conversion, this.options);
  1048. newItem.id = id; // TODO: not so nice setting id afterwards
  1049. newItem.data = itemData;
  1050. this._addItem(newItem);
  1051. var props = {
  1052. item: newItem,
  1053. dragRight: true,
  1054. initialX: event.center.x,
  1055. data: util.extend({}, itemData)
  1056. };
  1057. this.touchParams.itemProps = [props];
  1058. event.stopPropagation();
  1059. };
  1060. /**
  1061. * Drag selected items
  1062. * @param {Event} event
  1063. * @private
  1064. */
  1065. ItemSet.prototype._onDrag = function (event) {
  1066. if (this.touchParams.itemProps) {
  1067. event.stopPropagation();
  1068. var me = this;
  1069. var snap = this.options.snap || null;
  1070. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  1071. var scale = this.body.util.getScale();
  1072. var step = this.body.util.getStep();
  1073. // move
  1074. this.touchParams.itemProps.forEach(function (props) {
  1075. var newProps = {};
  1076. var current = me.body.util.toTime(event.center.x - xOffset);
  1077. var initial = me.body.util.toTime(props.initialX - xOffset);
  1078. var offset = current - initial;
  1079. var itemData = util.extend({}, props.item.data); // clone the data
  1080. if (props.item.editable === false) {
  1081. return;
  1082. }
  1083. var updateTimeAllowed = me.options.editable.updateTime ||
  1084. props.item.editable === true;
  1085. if (updateTimeAllowed) {
  1086. if (props.dragLeft) {
  1087. // drag left side of a range item
  1088. if (itemData.start != undefined) {
  1089. var initialStart = util.convert(props.data.start, 'Date');
  1090. var start = new Date(initialStart.valueOf() + offset);
  1091. itemData.start = snap ? snap(start, scale, step) : start;
  1092. }
  1093. }
  1094. else if (props.dragRight) {
  1095. // drag right side of a range item
  1096. if (itemData.end != undefined) {
  1097. var initialEnd = util.convert(props.data.end, 'Date');
  1098. var end = new Date(initialEnd.valueOf() + offset);
  1099. itemData.end = snap ? snap(end, scale, step) : end;
  1100. }
  1101. }
  1102. else {
  1103. // drag both start and end
  1104. if (itemData.start != undefined) {
  1105. var initialStart = util.convert(props.data.start, 'Date').valueOf();
  1106. var start = new Date(initialStart + offset);
  1107. if (itemData.end != undefined) {
  1108. var initialEnd = util.convert(props.data.end, 'Date');
  1109. var duration = initialEnd.valueOf() - initialStart.valueOf();
  1110. itemData.start = snap ? snap(start, scale, step) : start;
  1111. itemData.end = new Date(itemData.start.valueOf() + duration);
  1112. }
  1113. else {
  1114. itemData.start = snap ? snap(start, scale, step) : start;
  1115. }
  1116. }
  1117. }
  1118. }
  1119. var updateGroupAllowed = me.options.editable.updateGroup ||
  1120. props.item.editable === true;
  1121. if (updateGroupAllowed && (!props.dragLeft && !props.dragRight)) {
  1122. if (itemData.group != undefined) {
  1123. // drag from one group to another
  1124. var group = me.groupFromTarget(event);
  1125. if (group) {
  1126. itemData.group = group.groupId;
  1127. }
  1128. }
  1129. }
  1130. // confirm moving the item
  1131. me.options.onMoving(itemData, function (itemData) {
  1132. if (itemData) {
  1133. props.item.setData(itemData);
  1134. }
  1135. });
  1136. });
  1137. this.stackDirty = true; // force re-stacking of all items next redraw
  1138. this.body.emitter.emit('change');
  1139. }
  1140. };
  1141. /**
  1142. * Move an item to another group
  1143. * @param {Item} item
  1144. * @param {String | Number} groupId
  1145. * @private
  1146. */
  1147. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1148. var group = this.groups[groupId];
  1149. if (group && group.groupId != item.data.group) {
  1150. var oldGroup = item.parent;
  1151. oldGroup.remove(item);
  1152. oldGroup.order();
  1153. group.add(item);
  1154. group.order();
  1155. item.data.group = group.groupId;
  1156. }
  1157. };
  1158. /**
  1159. * End of dragging selected items
  1160. * @param {Event} event
  1161. * @private
  1162. */
  1163. ItemSet.prototype._onDragEnd = function (event) {
  1164. if (this.touchParams.itemProps) {
  1165. event.stopPropagation();
  1166. // prepare a change set for the changed items
  1167. var changes = [];
  1168. var me = this;
  1169. var dataset = this.itemsData.getDataSet();
  1170. var itemProps = this.touchParams.itemProps ;
  1171. this.touchParams.itemProps = null;
  1172. itemProps.forEach(function (props) {
  1173. var id = props.item.id;
  1174. var exists = me.itemsData.get(id, me.itemOptions) != null;
  1175. if (!exists) {
  1176. // add a new item
  1177. me.options.onAdd(props.item.data, function (itemData) {
  1178. me._removeItem(props.item); // remove temporary item
  1179. if (itemData) {
  1180. me.itemsData.getDataSet().add(itemData);
  1181. }
  1182. // force re-stacking of all items next redraw
  1183. me.stackDirty = true;
  1184. me.body.emitter.emit('change');
  1185. });
  1186. }
  1187. else {
  1188. // update existing item
  1189. var itemData = util.extend({}, props.item.data); // clone the data
  1190. me.options.onMove(itemData, function (itemData) {
  1191. if (itemData) {
  1192. // apply changes
  1193. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1194. changes.push(itemData);
  1195. }
  1196. else {
  1197. // restore original values
  1198. props.item.setData(props.data);
  1199. me.stackDirty = true; // force re-stacking of all items next redraw
  1200. me.body.emitter.emit('change');
  1201. }
  1202. });
  1203. }
  1204. });
  1205. // apply the changes to the data (if there are changes)
  1206. if (changes.length) {
  1207. dataset.update(changes);
  1208. }
  1209. }
  1210. };
  1211. /**
  1212. * Handle selecting/deselecting an item when tapping it
  1213. * @param {Event} event
  1214. * @private
  1215. */
  1216. ItemSet.prototype._onSelectItem = function (event) {
  1217. if (!this.options.selectable) return;
  1218. var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey);
  1219. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  1220. if (ctrlKey || shiftKey) {
  1221. this._onMultiSelectItem(event);
  1222. return;
  1223. }
  1224. var oldSelection = this.getSelection();
  1225. var item = this.itemFromTarget(event);
  1226. var selection = item ? [item.id] : [];
  1227. this.setSelection(selection);
  1228. var newSelection = this.getSelection();
  1229. // emit a select event,
  1230. // except when old selection is empty and new selection is still empty
  1231. if (newSelection.length > 0 || oldSelection.length > 0) {
  1232. this.body.emitter.emit('select', {
  1233. items: newSelection,
  1234. event: event
  1235. });
  1236. }
  1237. };
  1238. /**
  1239. * Handle creation and updates of an item on double tap
  1240. * @param event
  1241. * @private
  1242. */
  1243. ItemSet.prototype._onAddItem = function (event) {
  1244. if (!this.options.selectable) return;
  1245. if (!this.options.editable.add) return;
  1246. var me = this;
  1247. var snap = this.options.snap || null;
  1248. var item = this.itemFromTarget(event);
  1249. event.stopPropagation();
  1250. if (item) {
  1251. // update item
  1252. // execute async handler to update the item (or cancel it)
  1253. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  1254. this.options.onUpdate(itemData, function (itemData) {
  1255. if (itemData) {
  1256. me.itemsData.getDataSet().update(itemData);
  1257. }
  1258. });
  1259. }
  1260. else {
  1261. // add item
  1262. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1263. var x = event.center.x - xAbs;
  1264. var start = this.body.util.toTime(x);
  1265. var scale = this.body.util.getScale();
  1266. var step = this.body.util.getStep();
  1267. var newItem = {
  1268. start: snap ? snap(start, scale, step) : start,
  1269. content: 'new item'
  1270. };
  1271. // when default type is a range, add a default end date to the new item
  1272. if (this.options.type === 'range') {
  1273. var end = this.body.util.toTime(x + this.props.width / 5);
  1274. newItem.end = snap ? snap(end, scale, step) : end;
  1275. }
  1276. newItem[this.itemsData._fieldId] = util.randomUUID();
  1277. var group = this.groupFromTarget(event);
  1278. if (group) {
  1279. newItem.group = group.groupId;
  1280. }
  1281. // execute async handler to customize (or cancel) adding an item
  1282. this.options.onAdd(newItem, function (item) {
  1283. if (item) {
  1284. me.itemsData.getDataSet().add(item);
  1285. // TODO: need to trigger a redraw?
  1286. }
  1287. });
  1288. }
  1289. };
  1290. /**
  1291. * Handle selecting/deselecting multiple items when holding an item
  1292. * @param {Event} event
  1293. * @private
  1294. */
  1295. ItemSet.prototype._onMultiSelectItem = function (event) {
  1296. if (!this.options.selectable) return;
  1297. var item = this.itemFromTarget(event);
  1298. if (item) {
  1299. // multi select items (if allowed)
  1300. var selection = this.options.multiselect
  1301. ? this.getSelection() // take current selection
  1302. : []; // deselect current selection
  1303. var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false;
  1304. if (shiftKey && this.options.multiselect) {
  1305. // select all items between the old selection and the tapped item
  1306. // determine the selection range
  1307. selection.push(item.id);
  1308. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  1309. // select all items within the selection range
  1310. selection = [];
  1311. for (var id in this.items) {
  1312. if (this.items.hasOwnProperty(id)) {
  1313. var _item = this.items[id];
  1314. var start = _item.data.start;
  1315. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  1316. if (start >= range.min &&
  1317. end <= range.max &&
  1318. !(_item instanceof BackgroundItem)) {
  1319. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  1320. }
  1321. }
  1322. }
  1323. }
  1324. else {
  1325. // add/remove this item from the current selection
  1326. var index = selection.indexOf(item.id);
  1327. if (index == -1) {
  1328. // item is not yet selected -> select it
  1329. selection.push(item.id);
  1330. }
  1331. else {
  1332. // item is already selected -> deselect it
  1333. selection.splice(index, 1);
  1334. }
  1335. }
  1336. this.setSelection(selection);
  1337. this.body.emitter.emit('select', {
  1338. items: this.getSelection(),
  1339. event: event
  1340. });
  1341. }
  1342. };
  1343. /**
  1344. * Calculate the time range of a list of items
  1345. * @param {Array.<Object>} itemsData
  1346. * @return {{min: Date, max: Date}} Returns the range of the provided items
  1347. * @private
  1348. */
  1349. ItemSet._getItemRange = function(itemsData) {
  1350. var max = null;
  1351. var min = null;
  1352. itemsData.forEach(function (data) {
  1353. if (min == null || data.start < min) {
  1354. min = data.start;
  1355. }
  1356. if (data.end != undefined) {
  1357. if (max == null || data.end > max) {
  1358. max = data.end;
  1359. }
  1360. }
  1361. else {
  1362. if (max == null || data.start > max) {
  1363. max = data.start;
  1364. }
  1365. }
  1366. });
  1367. return {
  1368. min: min,
  1369. max: max
  1370. }
  1371. };
  1372. /**
  1373. * Find an item from an event target:
  1374. * searches for the attribute 'timeline-item' in the event target's element tree
  1375. * @param {Event} event
  1376. * @return {Item | null} item
  1377. */
  1378. ItemSet.prototype.itemFromTarget = function(event) {
  1379. var target = event.target;
  1380. while (target) {
  1381. if (target.hasOwnProperty('timeline-item')) {
  1382. return target['timeline-item'];
  1383. }
  1384. target = target.parentNode;
  1385. }
  1386. return null;
  1387. };
  1388. /**
  1389. * Find the Group from an event target:
  1390. * searches for the attribute 'timeline-group' in the event target's element tree
  1391. * @param {Event} event
  1392. * @return {Group | null} group
  1393. */
  1394. ItemSet.prototype.groupFromTarget = function(event) {
  1395. var clientY = event.center ? event.center.y : event.clientY;
  1396. for (var i = 0; i < this.groupIds.length; i++) {
  1397. var groupId = this.groupIds[i];
  1398. var group = this.groups[groupId];
  1399. var foreground = group.dom.foreground;
  1400. var top = util.getAbsoluteTop(foreground);
  1401. if (clientY > top && clientY < top + foreground.offsetHeight) {
  1402. return group;
  1403. }
  1404. if (this.options.orientation.item === 'top') {
  1405. if (i === this.groupIds.length - 1 && clientY > top) {
  1406. return group;
  1407. }
  1408. }
  1409. else {
  1410. if (i === 0 && clientY < top + foreground.offset) {
  1411. return group;
  1412. }
  1413. }
  1414. }
  1415. return null;
  1416. };
  1417. /**
  1418. * Find the ItemSet from an event target:
  1419. * searches for the attribute 'timeline-itemset' in the event target's element tree
  1420. * @param {Event} event
  1421. * @return {ItemSet | null} item
  1422. */
  1423. ItemSet.itemSetFromTarget = function(event) {
  1424. var target = event.target;
  1425. while (target) {
  1426. if (target.hasOwnProperty('timeline-itemset')) {
  1427. return target['timeline-itemset'];
  1428. }
  1429. target = target.parentNode;
  1430. }
  1431. return null;
  1432. };
  1433. module.exports = ItemSet;