vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1422 lines
39 KiB

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