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.

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