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.

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