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.

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