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.

1473 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
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. // redraw the background group
  443. this.groups[BACKGROUND].redraw(range, nonFirstMargin, restack);
  444. // redraw all regular groups
  445. var restack = this.stackDirty,
  446. firstGroup = this._firstGroup(),
  447. firstMargin = {
  448. item: margin.item,
  449. axis: margin.axis
  450. },
  451. nonFirstMargin = {
  452. item: margin.item,
  453. axis: margin.item.vertical / 2
  454. },
  455. height = 0,
  456. minHeight = margin.axis + margin.item.vertical;
  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. // reposition axis
  472. this.dom.axis.style.top = asSize((orientation == 'top') ?
  473. (this.body.domProps.top.height + this.body.domProps.border.top) :
  474. (this.body.domProps.top.height + this.body.domProps.centerContainer.height));
  475. this.dom.axis.style.left = '0';
  476. // check if this component is resized
  477. resized = this._isResized() || resized;
  478. return resized;
  479. };
  480. /**
  481. * Get the first group, aligned with the axis
  482. * @return {Group | null} firstGroup
  483. * @private
  484. */
  485. ItemSet.prototype._firstGroup = function() {
  486. var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1);
  487. var firstGroupId = this.groupIds[firstGroupIndex];
  488. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  489. return firstGroup || null;
  490. };
  491. /**
  492. * Create or delete the group holding all ungrouped items. This group is used when
  493. * there are no groups specified.
  494. * @protected
  495. */
  496. ItemSet.prototype._updateUngrouped = function() {
  497. var ungrouped = this.groups[UNGROUPED];
  498. var background = this.groups[BACKGROUND];
  499. var item, itemId;
  500. if (this.groupsData) {
  501. // remove the group holding all ungrouped items
  502. if (ungrouped) {
  503. ungrouped.hide();
  504. delete this.groups[UNGROUPED];
  505. for (itemId in this.items) {
  506. if (this.items.hasOwnProperty(itemId)) {
  507. item = this.items[itemId];
  508. item.parent && item.parent.remove(item);
  509. var groupId = this._getGroupId(item.data);
  510. var group = this.groups[groupId];
  511. group && group.add(item) || item.hide();
  512. }
  513. }
  514. }
  515. }
  516. else {
  517. // create a group holding all (unfiltered) items
  518. if (!ungrouped) {
  519. var id = null;
  520. var data = null;
  521. ungrouped = new Group(id, data, this);
  522. this.groups[UNGROUPED] = ungrouped;
  523. for (itemId in this.items) {
  524. if (this.items.hasOwnProperty(itemId)) {
  525. item = this.items[itemId];
  526. if (item instanceof BackgroundItem) {
  527. background.add(item);
  528. }
  529. else {
  530. ungrouped.add(item);
  531. }
  532. }
  533. }
  534. ungrouped.show();
  535. }
  536. }
  537. };
  538. /**
  539. * Get the element for the labelset
  540. * @return {HTMLElement} labelSet
  541. */
  542. ItemSet.prototype.getLabelSet = function() {
  543. return this.dom.labelSet;
  544. };
  545. /**
  546. * Set items
  547. * @param {vis.DataSet | null} items
  548. */
  549. ItemSet.prototype.setItems = function(items) {
  550. var me = this,
  551. ids,
  552. oldItemsData = this.itemsData;
  553. // replace the dataset
  554. if (!items) {
  555. this.itemsData = null;
  556. }
  557. else if (items instanceof DataSet || items instanceof DataView) {
  558. this.itemsData = items;
  559. }
  560. else {
  561. throw new TypeError('Data must be an instance of DataSet or DataView');
  562. }
  563. if (oldItemsData) {
  564. // unsubscribe from old dataset
  565. util.forEach(this.itemListeners, function (callback, event) {
  566. oldItemsData.off(event, callback);
  567. });
  568. // remove all drawn items
  569. ids = oldItemsData.getIds();
  570. this._onRemove(ids);
  571. }
  572. if (this.itemsData) {
  573. // subscribe to new dataset
  574. var id = this.id;
  575. util.forEach(this.itemListeners, function (callback, event) {
  576. me.itemsData.on(event, callback, id);
  577. });
  578. // add all new items
  579. ids = this.itemsData.getIds();
  580. this._onAdd(ids);
  581. // update the group holding all ungrouped items
  582. this._updateUngrouped();
  583. }
  584. };
  585. /**
  586. * Get the current items
  587. * @returns {vis.DataSet | null}
  588. */
  589. ItemSet.prototype.getItems = function() {
  590. return this.itemsData;
  591. };
  592. /**
  593. * Set groups
  594. * @param {vis.DataSet} groups
  595. */
  596. ItemSet.prototype.setGroups = function(groups) {
  597. var me = this,
  598. ids;
  599. // unsubscribe from current dataset
  600. if (this.groupsData) {
  601. util.forEach(this.groupListeners, function (callback, event) {
  602. me.groupsData.unsubscribe(event, callback);
  603. });
  604. // remove all drawn groups
  605. ids = this.groupsData.getIds();
  606. this.groupsData = null;
  607. this._onRemoveGroups(ids); // note: this will cause a redraw
  608. }
  609. // replace the dataset
  610. if (!groups) {
  611. this.groupsData = null;
  612. }
  613. else if (groups instanceof DataSet || groups instanceof DataView) {
  614. this.groupsData = groups;
  615. }
  616. else {
  617. throw new TypeError('Data must be an instance of DataSet or DataView');
  618. }
  619. if (this.groupsData) {
  620. // subscribe to new dataset
  621. var id = this.id;
  622. util.forEach(this.groupListeners, function (callback, event) {
  623. me.groupsData.on(event, callback, id);
  624. });
  625. // draw all ms
  626. ids = this.groupsData.getIds();
  627. this._onAddGroups(ids);
  628. }
  629. // update the group holding all ungrouped items
  630. this._updateUngrouped();
  631. // update the order of all items in each group
  632. this._order();
  633. this.body.emitter.emit('change');
  634. };
  635. /**
  636. * Get the current groups
  637. * @returns {vis.DataSet | null} groups
  638. */
  639. ItemSet.prototype.getGroups = function() {
  640. return this.groupsData;
  641. };
  642. /**
  643. * Remove an item by its id
  644. * @param {String | Number} id
  645. */
  646. ItemSet.prototype.removeItem = function(id) {
  647. var item = this.itemsData.get(id),
  648. dataset = this.itemsData.getDataSet();
  649. if (item) {
  650. // confirm deletion
  651. this.options.onRemove(item, function (item) {
  652. if (item) {
  653. // remove by id here, it is possible that an item has no id defined
  654. // itself, so better not delete by the item itself
  655. dataset.remove(id);
  656. }
  657. });
  658. }
  659. };
  660. /**
  661. * Get the time of an item based on it's data and options.type
  662. * @param {Object} itemData
  663. * @returns {string} Returns the type
  664. * @private
  665. */
  666. ItemSet.prototype._getType = function (itemData) {
  667. return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
  668. };
  669. /**
  670. * Get the group id for an item
  671. * @param {Object} itemData
  672. * @returns {string} Returns the groupId
  673. * @private
  674. */
  675. ItemSet.prototype._getGroupId = function (itemData) {
  676. var type = this._getType(itemData);
  677. if (type == 'background') {
  678. return this.groupsData && itemData.group != undefined ? itemData.group : BACKGROUND;
  679. }
  680. else {
  681. return this.groupsData ? itemData.group : UNGROUPED;
  682. }
  683. };
  684. /**
  685. * Handle updated items
  686. * @param {Number[]} ids
  687. * @protected
  688. */
  689. ItemSet.prototype._onUpdate = function(ids) {
  690. var me = this;
  691. ids.forEach(function (id) {
  692. var itemData = me.itemsData.get(id, me.itemOptions);
  693. var item = me.items[id];
  694. var type = me._getType(itemData);
  695. var constructor = ItemSet.types[type];
  696. if (item) {
  697. // update item
  698. if (!constructor || !(item instanceof constructor)) {
  699. // item type has changed, delete the item and recreate it
  700. me._removeItem(item);
  701. item = null;
  702. }
  703. else {
  704. me._updateItem(item, itemData);
  705. }
  706. }
  707. if (!item) {
  708. // create item
  709. if (constructor) {
  710. item = new constructor(itemData, me.conversion, me.options);
  711. item.id = id; // TODO: not so nice setting id afterwards
  712. me._addItem(item);
  713. }
  714. else if (type == 'rangeoverflow') {
  715. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  716. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
  717. '.vis.timeline .item.range .content {overflow: visible;}');
  718. }
  719. else {
  720. throw new TypeError('Unknown item type "' + type + '"');
  721. }
  722. }
  723. });
  724. this._order();
  725. this.stackDirty = true; // force re-stacking of all items next redraw
  726. this.body.emitter.emit('change');
  727. };
  728. /**
  729. * Handle added items
  730. * @param {Number[]} ids
  731. * @protected
  732. */
  733. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  734. /**
  735. * Handle removed items
  736. * @param {Number[]} ids
  737. * @protected
  738. */
  739. ItemSet.prototype._onRemove = function(ids) {
  740. var count = 0;
  741. var me = this;
  742. ids.forEach(function (id) {
  743. var item = me.items[id];
  744. if (item) {
  745. count++;
  746. me._removeItem(item);
  747. }
  748. });
  749. if (count) {
  750. // update order
  751. this._order();
  752. this.stackDirty = true; // force re-stacking of all items next redraw
  753. this.body.emitter.emit('change');
  754. }
  755. };
  756. /**
  757. * Update the order of item in all groups
  758. * @private
  759. */
  760. ItemSet.prototype._order = function() {
  761. // reorder the items in all groups
  762. // TODO: optimization: only reorder groups affected by the changed items
  763. util.forEach(this.groups, function (group) {
  764. group.order();
  765. });
  766. };
  767. /**
  768. * Handle updated groups
  769. * @param {Number[]} ids
  770. * @private
  771. */
  772. ItemSet.prototype._onUpdateGroups = function(ids) {
  773. this._onAddGroups(ids);
  774. };
  775. /**
  776. * Handle changed groups
  777. * @param {Number[]} ids
  778. * @private
  779. */
  780. ItemSet.prototype._onAddGroups = function(ids) {
  781. var me = this;
  782. ids.forEach(function (id) {
  783. var groupData = me.groupsData.get(id);
  784. var group = me.groups[id];
  785. if (!group) {
  786. // check for reserved ids
  787. if (id == UNGROUPED || id == BACKGROUND) {
  788. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  789. }
  790. var groupOptions = Object.create(me.options);
  791. util.extend(groupOptions, {
  792. height: null
  793. });
  794. group = new Group(id, groupData, me);
  795. me.groups[id] = group;
  796. // add items with this groupId to the new group
  797. for (var itemId in me.items) {
  798. if (me.items.hasOwnProperty(itemId)) {
  799. var item = me.items[itemId];
  800. if (item.data.group == id) {
  801. group.add(item);
  802. }
  803. }
  804. }
  805. group.order();
  806. group.show();
  807. }
  808. else {
  809. // update group
  810. group.setData(groupData);
  811. }
  812. });
  813. this.body.emitter.emit('change');
  814. };
  815. /**
  816. * Handle removed groups
  817. * @param {Number[]} ids
  818. * @private
  819. */
  820. ItemSet.prototype._onRemoveGroups = function(ids) {
  821. var groups = this.groups;
  822. ids.forEach(function (id) {
  823. var group = groups[id];
  824. if (group) {
  825. group.hide();
  826. delete groups[id];
  827. }
  828. });
  829. this.markDirty();
  830. this.body.emitter.emit('change');
  831. };
  832. /**
  833. * Reorder the groups if needed
  834. * @return {boolean} changed
  835. * @private
  836. */
  837. ItemSet.prototype._orderGroups = function () {
  838. if (this.groupsData) {
  839. // reorder the groups
  840. var groupIds = this.groupsData.getIds({
  841. order: this.options.groupOrder
  842. });
  843. var changed = !util.equalArray(groupIds, this.groupIds);
  844. if (changed) {
  845. // hide all groups, removes them from the DOM
  846. var groups = this.groups;
  847. groupIds.forEach(function (groupId) {
  848. groups[groupId].hide();
  849. });
  850. // show the groups again, attach them to the DOM in correct order
  851. groupIds.forEach(function (groupId) {
  852. groups[groupId].show();
  853. });
  854. this.groupIds = groupIds;
  855. }
  856. return changed;
  857. }
  858. else {
  859. return false;
  860. }
  861. };
  862. /**
  863. * Add a new item
  864. * @param {Item} item
  865. * @private
  866. */
  867. ItemSet.prototype._addItem = function(item) {
  868. this.items[item.id] = item;
  869. // add to group
  870. var groupId = this._getGroupId(item.data);
  871. var group = this.groups[groupId];
  872. if (group) group.add(item);
  873. };
  874. /**
  875. * Update an existing item
  876. * @param {Item} item
  877. * @param {Object} itemData
  878. * @private
  879. */
  880. ItemSet.prototype._updateItem = function(item, itemData) {
  881. var oldGroupId = item.data.group;
  882. // update the items data (will redraw the item when displayed)
  883. item.setData(itemData);
  884. // update group
  885. if (oldGroupId != item.data.group) {
  886. var oldGroup = this.groups[oldGroupId];
  887. if (oldGroup) oldGroup.remove(item);
  888. var groupId = this._getGroupId(item.data);
  889. var group = this.groups[groupId];
  890. if (group) group.add(item);
  891. }
  892. };
  893. /**
  894. * Delete an item from the ItemSet: remove it from the DOM, from the map
  895. * with items, and from the map with visible items, and from the selection
  896. * @param {Item} item
  897. * @private
  898. */
  899. ItemSet.prototype._removeItem = function(item) {
  900. // remove from DOM
  901. item.hide();
  902. // remove from items
  903. delete this.items[item.id];
  904. // remove from selection
  905. var index = this.selection.indexOf(item.id);
  906. if (index != -1) this.selection.splice(index, 1);
  907. // remove from group
  908. var groupId = this._getGroupId(item.data);
  909. var group = this.groups[groupId];
  910. if (group) group.remove(item);
  911. };
  912. /**
  913. * Create an array containing all items being a range (having an end date)
  914. * @param array
  915. * @returns {Array}
  916. * @private
  917. */
  918. ItemSet.prototype._constructByEndArray = function(array) {
  919. var endArray = [];
  920. for (var i = 0; i < array.length; i++) {
  921. if (array[i] instanceof RangeItem) {
  922. endArray.push(array[i]);
  923. }
  924. }
  925. return endArray;
  926. };
  927. /**
  928. * Register the clicked item on touch, before dragStart is initiated.
  929. *
  930. * dragStart is initiated from a mousemove event, which can have left the item
  931. * already resulting in an item == null
  932. *
  933. * @param {Event} event
  934. * @private
  935. */
  936. ItemSet.prototype._onTouch = function (event) {
  937. // store the touched item, used in _onDragStart
  938. this.touchParams.item = ItemSet.itemFromTarget(event);
  939. };
  940. /**
  941. * Start dragging the selected events
  942. * @param {Event} event
  943. * @private
  944. */
  945. ItemSet.prototype._onDragStart = function (event) {
  946. if (!this.options.editable.updateTime && !this.options.editable.updateGroup) {
  947. return;
  948. }
  949. var item = this.touchParams.item || null;
  950. var me = this;
  951. var props = {};
  952. props.initialX = event.gesture.center.clientX;
  953. if (item && item.selected) {
  954. var dragLeftItem = event.target.dragLeftItem;
  955. var dragRightItem = event.target.dragRightItem;
  956. if (dragLeftItem) {
  957. props.item = dragLeftItem;
  958. if (me.options.editable.updateTime) {
  959. props.start = item.data.start.valueOf();
  960. }
  961. if (me.options.editable.updateGroup) {
  962. if ('group' in item.data) props.group = item.data.group;
  963. }
  964. this.touchParams.itemProps = [props];
  965. }
  966. else if (dragRightItem) {
  967. props.item = dragRightItem;
  968. if (me.options.editable.updateTime) {
  969. props.end = item.data.end.valueOf();
  970. }
  971. if (me.options.editable.updateGroup) {
  972. if ('group' in item.data) props.group = item.data.group;
  973. }
  974. this.touchParams.itemProps = [props];
  975. }
  976. else {
  977. this.touchParams.itemProps = this.getSelection().map(function (id) {
  978. var item = me.items[id];
  979. props.item = item;
  980. if (me.options.editable.updateTime) {
  981. if ('start' in item.data) props.start = item.data.start.valueOf();
  982. if ('end' in item.data) props.end = item.data.end.valueOf();
  983. }
  984. if (me.options.editable.updateGroup) {
  985. if ('group' in item.data) props.group = item.data.group;
  986. }
  987. return props;
  988. });
  989. }
  990. event.stopPropagation();
  991. }
  992. };
  993. /**
  994. * Drag selected items
  995. * @param {Event} event
  996. * @private
  997. */
  998. ItemSet.prototype._onDrag = function (event) {
  999. if (this.touchParams.itemProps) {
  1000. var me = this;
  1001. var snap = this.body.util.snap || null;
  1002. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  1003. // move
  1004. this.touchParams.itemProps.forEach(function (props) {
  1005. var newProps = {};
  1006. if ('start' in props && !('end' in props)) { // only start in props
  1007. var start = me.body.util.toTime(event.gesture.center.clientX - xOffset);
  1008. newProps.start = snap ? snap(start) : start;
  1009. }
  1010. else if ('start' in props) { // start and end in props
  1011. var current = me.body.util.toTime(event.gesture.center.clientX - xOffset);
  1012. var initial = me.body.util.toTime(props.initialX - xOffset);
  1013. var offset = current - initial;
  1014. var start = new Date(props.start + offset);
  1015. var end = new Date(props.end + offset);
  1016. newProps.start = snap ? snap(start) : start;
  1017. newProps.end = snap ? snap(end) : end;
  1018. }
  1019. else if ('end' in props) { // only end in props
  1020. var end = me.body.util.toTime(event.gesture.center.clientX - xOffset);
  1021. newProps.end = snap ? snap(end) : end;
  1022. }
  1023. if ('group' in props) {
  1024. // drag from one group to another
  1025. var group = ItemSet.groupFromTarget(event);
  1026. newProps.group = group && group.groupId;
  1027. }
  1028. // confirm moving the item
  1029. var itemData = util.extend({}, props.item.data, newProps);
  1030. me.options.onMoving(itemData, function (itemData) {
  1031. if (itemData) {
  1032. me._updateItemProps(props.item, itemData);
  1033. }
  1034. });
  1035. });
  1036. this.stackDirty = true; // force re-stacking of all items next redraw
  1037. this.body.emitter.emit('change');
  1038. event.stopPropagation();
  1039. }
  1040. };
  1041. /**
  1042. * Update an items properties
  1043. * @param {Item} item
  1044. * @param {Object} props Can contain properties start, end, and group.
  1045. * @private
  1046. */
  1047. ItemSet.prototype._updateItemProps = function(item, props) {
  1048. // TODO: copy all properties from props to item? (also new ones)
  1049. if ('start' in props) item.data.start = props.start;
  1050. if ('end' in props) item.data.end = props.end;
  1051. if ('group' in props && item.data.group != props.group) {
  1052. this._moveToGroup(item, props.group)
  1053. }
  1054. };
  1055. /**
  1056. * Move an item to another group
  1057. * @param {Item} item
  1058. * @param {String | Number} groupId
  1059. * @private
  1060. */
  1061. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1062. var group = this.groups[groupId];
  1063. if (group && group.groupId != item.data.group) {
  1064. var oldGroup = item.parent;
  1065. oldGroup.remove(item);
  1066. oldGroup.order();
  1067. group.add(item);
  1068. group.order();
  1069. item.data.group = group.groupId;
  1070. }
  1071. };
  1072. /**
  1073. * End of dragging selected items
  1074. * @param {Event} event
  1075. * @private
  1076. */
  1077. ItemSet.prototype._onDragEnd = function (event) {
  1078. if (this.touchParams.itemProps) {
  1079. // prepare a change set for the changed items
  1080. var changes = [],
  1081. me = this,
  1082. dataset = this.itemsData.getDataSet();
  1083. var itemProps = this.touchParams.itemProps ;
  1084. this.touchParams.itemProps = null;
  1085. itemProps.forEach(function (props) {
  1086. var id = props.item.id,
  1087. itemData = me.itemsData.get(id, me.itemOptions);
  1088. var changed = false;
  1089. if ('start' in props.item.data) {
  1090. changed = (props.start != props.item.data.start.valueOf());
  1091. itemData.start = util.convert(props.item.data.start,
  1092. dataset._options.type && dataset._options.type.start || 'Date');
  1093. }
  1094. if ('end' in props.item.data) {
  1095. changed = changed || (props.end != props.item.data.end.valueOf());
  1096. itemData.end = util.convert(props.item.data.end,
  1097. dataset._options.type && dataset._options.type.end || 'Date');
  1098. }
  1099. if ('group' in props.item.data) {
  1100. changed = changed || (props.group != props.item.data.group);
  1101. itemData.group = props.item.data.group;
  1102. }
  1103. // only apply changes when start or end is actually changed
  1104. if (changed) {
  1105. me.options.onMove(itemData, function (itemData) {
  1106. if (itemData) {
  1107. // apply changes
  1108. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1109. changes.push(itemData);
  1110. }
  1111. else {
  1112. // restore original values
  1113. me._updateItemProps(props.item, props);
  1114. me.stackDirty = true; // force re-stacking of all items next redraw
  1115. me.body.emitter.emit('change');
  1116. }
  1117. });
  1118. }
  1119. });
  1120. // apply the changes to the data (if there are changes)
  1121. if (changes.length) {
  1122. dataset.update(changes);
  1123. }
  1124. event.stopPropagation();
  1125. }
  1126. };
  1127. /**
  1128. * Handle selecting/deselecting an item when tapping it
  1129. * @param {Event} event
  1130. * @private
  1131. */
  1132. ItemSet.prototype._onSelectItem = function (event) {
  1133. if (!this.options.selectable) return;
  1134. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  1135. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  1136. if (ctrlKey || shiftKey) {
  1137. this._onMultiSelectItem(event);
  1138. return;
  1139. }
  1140. var oldSelection = this.getSelection();
  1141. var item = ItemSet.itemFromTarget(event);
  1142. var selection = item ? [item.id] : [];
  1143. this.setSelection(selection);
  1144. var newSelection = this.getSelection();
  1145. // emit a select event,
  1146. // except when old selection is empty and new selection is still empty
  1147. if (newSelection.length > 0 || oldSelection.length > 0) {
  1148. this.body.emitter.emit('select', {
  1149. items: this.getSelection()
  1150. });
  1151. }
  1152. };
  1153. /**
  1154. * Handle creation and updates of an item on double tap
  1155. * @param event
  1156. * @private
  1157. */
  1158. ItemSet.prototype._onAddItem = function (event) {
  1159. if (!this.options.selectable) return;
  1160. if (!this.options.editable.add) return;
  1161. var me = this,
  1162. snap = this.body.util.snap || null,
  1163. item = ItemSet.itemFromTarget(event);
  1164. if (item) {
  1165. // update item
  1166. // execute async handler to update the item (or cancel it)
  1167. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  1168. this.options.onUpdate(itemData, function (itemData) {
  1169. if (itemData) {
  1170. me.itemsData.update(itemData);
  1171. }
  1172. });
  1173. }
  1174. else {
  1175. // add item
  1176. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1177. var x = event.gesture.center.pageX - xAbs;
  1178. var start = this.body.util.toTime(x);
  1179. var newItem = {
  1180. start: snap ? snap(start) : start,
  1181. content: 'new item'
  1182. };
  1183. // when default type is a range, add a default end date to the new item
  1184. if (this.options.type === 'range') {
  1185. var end = this.body.util.toTime(x + this.props.width / 5);
  1186. newItem.end = snap ? snap(end) : end;
  1187. }
  1188. newItem[this.itemsData._fieldId] = util.randomUUID();
  1189. var group = ItemSet.groupFromTarget(event);
  1190. if (group) {
  1191. newItem.group = group.groupId;
  1192. }
  1193. // execute async handler to customize (or cancel) adding an item
  1194. this.options.onAdd(newItem, function (item) {
  1195. if (item) {
  1196. me.itemsData.add(item);
  1197. // TODO: need to trigger a redraw?
  1198. }
  1199. });
  1200. }
  1201. };
  1202. /**
  1203. * Handle selecting/deselecting multiple items when holding an item
  1204. * @param {Event} event
  1205. * @private
  1206. */
  1207. ItemSet.prototype._onMultiSelectItem = function (event) {
  1208. if (!this.options.selectable) return;
  1209. var selection,
  1210. item = ItemSet.itemFromTarget(event);
  1211. if (item) {
  1212. // multi select items
  1213. selection = this.getSelection(); // current selection
  1214. var index = selection.indexOf(item.id);
  1215. if (index == -1) {
  1216. // item is not yet selected -> select it
  1217. selection.push(item.id);
  1218. }
  1219. else {
  1220. // item is already selected -> deselect it
  1221. selection.splice(index, 1);
  1222. }
  1223. this.setSelection(selection);
  1224. this.body.emitter.emit('select', {
  1225. items: this.getSelection()
  1226. });
  1227. }
  1228. };
  1229. /**
  1230. * Find an item from an event target:
  1231. * searches for the attribute 'timeline-item' in the event target's element tree
  1232. * @param {Event} event
  1233. * @return {Item | null} item
  1234. */
  1235. ItemSet.itemFromTarget = function(event) {
  1236. var target = event.target;
  1237. while (target) {
  1238. if (target.hasOwnProperty('timeline-item')) {
  1239. return target['timeline-item'];
  1240. }
  1241. target = target.parentNode;
  1242. }
  1243. return null;
  1244. };
  1245. /**
  1246. * Find the Group from an event target:
  1247. * searches for the attribute 'timeline-group' in the event target's element tree
  1248. * @param {Event} event
  1249. * @return {Group | null} group
  1250. */
  1251. ItemSet.groupFromTarget = function(event) {
  1252. var target = event.target;
  1253. while (target) {
  1254. if (target.hasOwnProperty('timeline-group')) {
  1255. return target['timeline-group'];
  1256. }
  1257. target = target.parentNode;
  1258. }
  1259. return null;
  1260. };
  1261. /**
  1262. * Find the ItemSet from an event target:
  1263. * searches for the attribute 'timeline-itemset' in the event target's element tree
  1264. * @param {Event} event
  1265. * @return {ItemSet | null} item
  1266. */
  1267. ItemSet.itemSetFromTarget = function(event) {
  1268. var target = event.target;
  1269. while (target) {
  1270. if (target.hasOwnProperty('timeline-itemset')) {
  1271. return target['timeline-itemset'];
  1272. }
  1273. target = target.parentNode;
  1274. }
  1275. return null;
  1276. };
  1277. module.exports = ItemSet;