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.

1841 lines
52 KiB

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