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.

1595 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. event.preventDefault();
  1014. }
  1015. };
  1016. /**
  1017. * Drag selected items
  1018. * @param {Event} event
  1019. * @private
  1020. */
  1021. ItemSet.prototype._onDrag = function (event) {
  1022. event.preventDefault();
  1023. if (this.touchParams.itemProps) {
  1024. var me = this;
  1025. var snap = this.options.snap || null;
  1026. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  1027. var scale = this.body.util.getScale();
  1028. var step = this.body.util.getStep();
  1029. // move
  1030. this.touchParams.itemProps.forEach(function (props) {
  1031. var newProps = {};
  1032. var current = me.body.util.toTime(event.center.x - xOffset);
  1033. var initial = me.body.util.toTime(props.initialX - xOffset);
  1034. var offset = current - initial;
  1035. if ('start' in props) {
  1036. var start = new Date(props.start + offset);
  1037. newProps.start = snap ? snap(start, scale, step) : start;
  1038. }
  1039. if ('end' in props) {
  1040. var end = new Date(props.end + offset);
  1041. newProps.end = snap ? snap(end, scale, step) : end;
  1042. }
  1043. else if ('duration' in props) {
  1044. newProps.end = new Date(newProps.start.valueOf() + props.duration);
  1045. }
  1046. if ('group' in props) {
  1047. // drag from one group to another
  1048. var group = me.groupFromTarget(event);
  1049. newProps.group = group && group.groupId;
  1050. }
  1051. // confirm moving the item
  1052. var itemData = util.extend({}, props.item.data, newProps);
  1053. me.options.onMoving(itemData, function (itemData) {
  1054. if (itemData) {
  1055. me._updateItemProps(props.item, itemData);
  1056. }
  1057. });
  1058. });
  1059. this.stackDirty = true; // force re-stacking of all items next redraw
  1060. this.body.emitter.emit('change');
  1061. event.stopPropagation();
  1062. }
  1063. };
  1064. /**
  1065. * Update an items properties
  1066. * @param {Item} item
  1067. * @param {Object} props Can contain properties start, end, and group.
  1068. * @private
  1069. */
  1070. ItemSet.prototype._updateItemProps = function(item, props) {
  1071. // TODO: copy all properties from props to item? (also new ones)
  1072. if ('start' in props) {
  1073. item.data.start = props.start;
  1074. }
  1075. if ('end' in props) {
  1076. item.data.end = props.end;
  1077. }
  1078. else if ('duration' in props) {
  1079. item.data.end = new Date(props.start.valueOf() + props.duration);
  1080. }
  1081. if ('group' in props && item.data.group != props.group) {
  1082. this._moveToGroup(item, props.group)
  1083. }
  1084. };
  1085. /**
  1086. * Move an item to another group
  1087. * @param {Item} item
  1088. * @param {String | Number} groupId
  1089. * @private
  1090. */
  1091. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1092. var group = this.groups[groupId];
  1093. if (group && group.groupId != item.data.group) {
  1094. var oldGroup = item.parent;
  1095. oldGroup.remove(item);
  1096. oldGroup.order();
  1097. group.add(item);
  1098. group.order();
  1099. item.data.group = group.groupId;
  1100. }
  1101. };
  1102. /**
  1103. * End of dragging selected items
  1104. * @param {Event} event
  1105. * @private
  1106. */
  1107. ItemSet.prototype._onDragEnd = function (event) {
  1108. if (this.touchParams.itemProps) {
  1109. // prepare a change set for the changed items
  1110. var changes = [],
  1111. me = this,
  1112. dataset = this.itemsData.getDataSet();
  1113. var itemProps = this.touchParams.itemProps ;
  1114. this.touchParams.itemProps = null;
  1115. itemProps.forEach(function (props) {
  1116. var id = props.item.id,
  1117. itemData = me.itemsData.get(id, me.itemOptions);
  1118. var changed = false;
  1119. if ('start' in props.item.data) {
  1120. changed = (props.start != props.item.data.start.valueOf());
  1121. itemData.start = util.convert(props.item.data.start,
  1122. dataset._options.type && dataset._options.type.start || 'Date');
  1123. }
  1124. if ('end' in props.item.data) {
  1125. changed = changed || (props.end != props.item.data.end.valueOf());
  1126. itemData.end = util.convert(props.item.data.end,
  1127. dataset._options.type && dataset._options.type.end || 'Date');
  1128. }
  1129. if ('group' in props.item.data) {
  1130. changed = changed || (props.group != props.item.data.group);
  1131. itemData.group = props.item.data.group;
  1132. }
  1133. // only apply changes when start or end is actually changed
  1134. if (changed) {
  1135. me.options.onMove(itemData, function (itemData) {
  1136. if (itemData) {
  1137. // apply changes
  1138. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1139. changes.push(itemData);
  1140. }
  1141. else {
  1142. // restore original values
  1143. me._updateItemProps(props.item, props);
  1144. me.stackDirty = true; // force re-stacking of all items next redraw
  1145. me.body.emitter.emit('change');
  1146. }
  1147. });
  1148. }
  1149. });
  1150. // apply the changes to the data (if there are changes)
  1151. if (changes.length) {
  1152. dataset.update(changes);
  1153. }
  1154. event.stopPropagation();
  1155. }
  1156. };
  1157. /**
  1158. * Handle selecting/deselecting an item when tapping it
  1159. * @param {Event} event
  1160. * @private
  1161. */
  1162. ItemSet.prototype._onSelectItem = function (event) {
  1163. if (!this.options.selectable) return;
  1164. var ctrlKey = event.srcEvent && event.srcEvent.ctrlKey;
  1165. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  1166. if (ctrlKey || shiftKey) {
  1167. this._onMultiSelectItem(event);
  1168. return;
  1169. }
  1170. var oldSelection = this.getSelection();
  1171. var item = ItemSet.itemFromTarget(event);
  1172. var selection = item ? [item.id] : [];
  1173. this.setSelection(selection);
  1174. var newSelection = this.getSelection();
  1175. // emit a select event,
  1176. // except when old selection is empty and new selection is still empty
  1177. if (newSelection.length > 0 || oldSelection.length > 0) {
  1178. this.body.emitter.emit('select', {
  1179. items: newSelection
  1180. });
  1181. }
  1182. };
  1183. /**
  1184. * Handle creation and updates of an item on double tap
  1185. * @param event
  1186. * @private
  1187. */
  1188. ItemSet.prototype._onAddItem = function (event) {
  1189. if (!this.options.selectable) return;
  1190. if (!this.options.editable.add) return;
  1191. var me = this,
  1192. snap = this.options.snap || null,
  1193. item = ItemSet.itemFromTarget(event);
  1194. if (item) {
  1195. // update item
  1196. // execute async handler to update the item (or cancel it)
  1197. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  1198. this.options.onUpdate(itemData, function (itemData) {
  1199. if (itemData) {
  1200. me.itemsData.getDataSet().update(itemData);
  1201. }
  1202. });
  1203. }
  1204. else {
  1205. // add item
  1206. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1207. var x = event.center.x - xAbs;
  1208. var start = this.body.util.toTime(x);
  1209. var scale = this.body.util.getScale();
  1210. var step = this.body.util.getStep();
  1211. var newItem = {
  1212. start: snap ? snap(start, scale, step) : start,
  1213. content: 'new item'
  1214. };
  1215. // when default type is a range, add a default end date to the new item
  1216. if (this.options.type === 'range') {
  1217. var end = this.body.util.toTime(x + this.props.width / 5);
  1218. newItem.end = snap ? snap(end, scale, step) : end;
  1219. }
  1220. newItem[this.itemsData._fieldId] = util.randomUUID();
  1221. var group = this.groupFromTarget(event);
  1222. if (group) {
  1223. newItem.group = group.groupId;
  1224. }
  1225. // execute async handler to customize (or cancel) adding an item
  1226. this.options.onAdd(newItem, function (item) {
  1227. if (item) {
  1228. me.itemsData.getDataSet().add(item);
  1229. // TODO: need to trigger a redraw?
  1230. }
  1231. });
  1232. }
  1233. };
  1234. /**
  1235. * Handle selecting/deselecting multiple items when holding an item
  1236. * @param {Event} event
  1237. * @private
  1238. */
  1239. ItemSet.prototype._onMultiSelectItem = function (event) {
  1240. if (!this.options.selectable) return;
  1241. var selection,
  1242. item = ItemSet.itemFromTarget(event);
  1243. if (item) {
  1244. // multi select items
  1245. selection = this.getSelection(); // current selection
  1246. var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false;
  1247. if (shiftKey) {
  1248. // select all items between the old selection and the tapped item
  1249. // determine the selection range
  1250. selection.push(item.id);
  1251. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  1252. // select all items within the selection range
  1253. selection = [];
  1254. for (var id in this.items) {
  1255. if (this.items.hasOwnProperty(id)) {
  1256. var _item = this.items[id];
  1257. var start = _item.data.start;
  1258. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  1259. if (start >= range.min && end <= range.max) {
  1260. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  1261. }
  1262. }
  1263. }
  1264. }
  1265. else {
  1266. // add/remove this item from the current selection
  1267. var index = selection.indexOf(item.id);
  1268. if (index == -1) {
  1269. // item is not yet selected -> select it
  1270. selection.push(item.id);
  1271. }
  1272. else {
  1273. // item is already selected -> deselect it
  1274. selection.splice(index, 1);
  1275. }
  1276. }
  1277. this.setSelection(selection);
  1278. this.body.emitter.emit('select', {
  1279. items: this.getSelection()
  1280. });
  1281. }
  1282. };
  1283. /**
  1284. * Calculate the time range of a list of items
  1285. * @param {Array.<Object>} itemsData
  1286. * @return {{min: Date, max: Date}} Returns the range of the provided items
  1287. * @private
  1288. */
  1289. ItemSet._getItemRange = function(itemsData) {
  1290. var max = null;
  1291. var min = null;
  1292. itemsData.forEach(function (data) {
  1293. if (min == null || data.start < min) {
  1294. min = data.start;
  1295. }
  1296. if (data.end != undefined) {
  1297. if (max == null || data.end > max) {
  1298. max = data.end;
  1299. }
  1300. }
  1301. else {
  1302. if (max == null || data.start > max) {
  1303. max = data.start;
  1304. }
  1305. }
  1306. });
  1307. return {
  1308. min: min,
  1309. max: max
  1310. }
  1311. };
  1312. /**
  1313. * Find an item from an event target:
  1314. * searches for the attribute 'timeline-item' in the event target's element tree
  1315. * @param {Event} event
  1316. * @return {Item | null} item
  1317. */
  1318. ItemSet.itemFromTarget = function(event) {
  1319. var target = event.target;
  1320. while (target) {
  1321. if (target.hasOwnProperty('timeline-item')) {
  1322. return target['timeline-item'];
  1323. }
  1324. target = target.parentNode;
  1325. }
  1326. return null;
  1327. };
  1328. /**
  1329. * Find the Group from an event target:
  1330. * searches for the attribute 'timeline-group' in the event target's element tree
  1331. * @param {Event} event
  1332. * @return {Group | null} group
  1333. */
  1334. ItemSet.prototype.groupFromTarget = function(event) {
  1335. // TODO: cleanup when the new solution is stable (also on mobile)
  1336. //var target = event.target;
  1337. //while (target) {
  1338. // if (target.hasOwnProperty('timeline-group')) {
  1339. // return target['timeline-group'];
  1340. // }
  1341. // target = target.parentNode;
  1342. //}
  1343. //
  1344. var clientY = event.gesture.center.clientY;
  1345. for (var i = 0; i < this.groupIds.length; i++) {
  1346. var groupId = this.groupIds[i];
  1347. var group = this.groups[groupId];
  1348. var foreground = group.dom.foreground;
  1349. var top = util.getAbsoluteTop(foreground);
  1350. if (clientY > top && clientY < top + foreground.offsetHeight) {
  1351. return group;
  1352. }
  1353. if (this.options.orientation === 'top') {
  1354. if (i === this.groupIds.length - 1 && clientY > top) {
  1355. return group;
  1356. }
  1357. }
  1358. else {
  1359. if (i === 0 && clientY < top + foreground.offset) {
  1360. return group;
  1361. }
  1362. }
  1363. }
  1364. return null;
  1365. };
  1366. /**
  1367. * Find the ItemSet from an event target:
  1368. * searches for the attribute 'timeline-itemset' in the event target's element tree
  1369. * @param {Event} event
  1370. * @return {ItemSet | null} item
  1371. */
  1372. ItemSet.itemSetFromTarget = function(event) {
  1373. var target = event.target;
  1374. while (target) {
  1375. if (target.hasOwnProperty('timeline-itemset')) {
  1376. return target['timeline-itemset'];
  1377. }
  1378. target = target.parentNode;
  1379. }
  1380. return null;
  1381. };
  1382. module.exports = ItemSet;