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.

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