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.

1551 lines
43 KiB

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