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.

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