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.

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