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.

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