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.

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