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.

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