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.

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