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.

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