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.

1465 lines
41 KiB

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