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.

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