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.

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