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.

1394 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 {string[] | string} [ids] An array with zero or more id's of the items to be
  332. * selected, or a single item id. If ids is undefined
  333. * or an empty array, all items will be unselected.
  334. */
  335. ItemSet.prototype.setSelection = function(ids) {
  336. var i, ii, id, item;
  337. if (ids == undefined) ids = [];
  338. if (!Array.isArray(ids)) ids = [ids];
  339. // unselect currently selected items
  340. for (i = 0, ii = this.selection.length; i < ii; i++) {
  341. id = this.selection[i];
  342. item = this.items[id];
  343. if (item) item.unselect();
  344. }
  345. // select items
  346. this.selection = [];
  347. for (i = 0, ii = ids.length; i < ii; i++) {
  348. id = ids[i];
  349. item = this.items[id];
  350. if (item) {
  351. this.selection.push(id);
  352. item.select();
  353. }
  354. }
  355. };
  356. /**
  357. * Get the selected items by their id
  358. * @return {Array} ids The ids of the selected items
  359. */
  360. ItemSet.prototype.getSelection = function() {
  361. return this.selection.concat([]);
  362. };
  363. /**
  364. * Get the id's of the currently visible items.
  365. * @returns {Array} The ids of the visible items
  366. */
  367. ItemSet.prototype.getVisibleItems = function() {
  368. var range = this.body.range.getRange();
  369. var left = this.body.util.toScreen(range.start);
  370. var right = this.body.util.toScreen(range.end);
  371. var ids = [];
  372. for (var groupId in this.groups) {
  373. if (this.groups.hasOwnProperty(groupId)) {
  374. var group = this.groups[groupId];
  375. var rawVisibleItems = group.visibleItems;
  376. // filter the "raw" set with visibleItems into a set which is really
  377. // visible by pixels
  378. for (var i = 0; i < rawVisibleItems.length; i++) {
  379. var item = rawVisibleItems[i];
  380. // TODO: also check whether visible vertically
  381. if ((item.left < right) && (item.left + item.width > left)) {
  382. ids.push(item.id);
  383. }
  384. }
  385. }
  386. }
  387. return ids;
  388. };
  389. /**
  390. * Deselect a selected item
  391. * @param {String | Number} id
  392. * @private
  393. */
  394. ItemSet.prototype._deselect = function(id) {
  395. var selection = this.selection;
  396. for (var i = 0, ii = selection.length; i < ii; i++) {
  397. if (selection[i] == id) { // non-strict comparison!
  398. selection.splice(i, 1);
  399. break;
  400. }
  401. }
  402. };
  403. /**
  404. * Repaint the component
  405. * @return {boolean} Returns true if the component is resized
  406. */
  407. ItemSet.prototype.redraw = function() {
  408. var margin = this.options.margin,
  409. range = this.body.range,
  410. asSize = util.option.asSize,
  411. options = this.options,
  412. orientation = options.orientation,
  413. resized = false,
  414. frame = this.dom.frame,
  415. editable = options.editable.updateTime || options.editable.updateGroup;
  416. // update class name
  417. frame.className = 'itemset' + (editable ? ' editable' : '');
  418. // reorder the groups (if needed)
  419. resized = this._orderGroups() || resized;
  420. // check whether zoomed (in that case we need to re-stack everything)
  421. // TODO: would be nicer to get this as a trigger from Range
  422. var visibleInterval = range.end - range.start;
  423. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.props.width != this.props.lastWidth);
  424. if (zoomed) this.stackDirty = true;
  425. this.lastVisibleInterval = visibleInterval;
  426. this.props.lastWidth = this.props.width;
  427. // redraw all groups
  428. var restack = this.stackDirty,
  429. firstGroup = this._firstGroup(),
  430. firstMargin = {
  431. item: margin.item,
  432. axis: margin.axis
  433. },
  434. nonFirstMargin = {
  435. item: margin.item,
  436. axis: margin.item.vertical / 2
  437. },
  438. height = 0,
  439. minHeight = margin.axis + margin.item.vertical;
  440. util.forEach(this.groups, function (group) {
  441. var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
  442. var groupResized = group.redraw(range, groupMargin, restack);
  443. resized = groupResized || resized;
  444. height += group.height;
  445. });
  446. height = Math.max(height, minHeight);
  447. this.stackDirty = false;
  448. // update frame height
  449. frame.style.height = asSize(height);
  450. // calculate actual size and position
  451. this.props.top = frame.offsetTop;
  452. this.props.left = frame.offsetLeft;
  453. this.props.width = frame.offsetWidth;
  454. this.props.height = height;
  455. // reposition axis
  456. this.dom.axis.style.top = asSize((orientation == 'top') ?
  457. (this.body.domProps.top.height + this.body.domProps.border.top) :
  458. (this.body.domProps.top.height + this.body.domProps.centerContainer.height));
  459. this.dom.axis.style.left = '0';
  460. // check if this component is resized
  461. resized = this._isResized() || resized;
  462. return resized;
  463. };
  464. /**
  465. * Get the first group, aligned with the axis
  466. * @return {Group | null} firstGroup
  467. * @private
  468. */
  469. ItemSet.prototype._firstGroup = function() {
  470. var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1);
  471. var firstGroupId = this.groupIds[firstGroupIndex];
  472. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  473. return firstGroup || null;
  474. };
  475. /**
  476. * Create or delete the group holding all ungrouped items. This group is used when
  477. * there are no groups specified.
  478. * @protected
  479. */
  480. ItemSet.prototype._updateUngrouped = function() {
  481. var ungrouped = this.groups[UNGROUPED];
  482. if (this.groupsData) {
  483. // remove the group holding all ungrouped items
  484. if (ungrouped) {
  485. ungrouped.hide();
  486. delete this.groups[UNGROUPED];
  487. }
  488. }
  489. else {
  490. // create a group holding all (unfiltered) items
  491. if (!ungrouped) {
  492. var id = null;
  493. var data = null;
  494. ungrouped = new Group(id, data, this);
  495. this.groups[UNGROUPED] = ungrouped;
  496. for (var itemId in this.items) {
  497. if (this.items.hasOwnProperty(itemId)) {
  498. ungrouped.add(this.items[itemId]);
  499. }
  500. }
  501. ungrouped.show();
  502. }
  503. }
  504. };
  505. /**
  506. * Get the element for the labelset
  507. * @return {HTMLElement} labelSet
  508. */
  509. ItemSet.prototype.getLabelSet = function() {
  510. return this.dom.labelSet;
  511. };
  512. /**
  513. * Set items
  514. * @param {vis.DataSet | null} items
  515. */
  516. ItemSet.prototype.setItems = function(items) {
  517. var me = this,
  518. ids,
  519. oldItemsData = this.itemsData;
  520. // replace the dataset
  521. if (!items) {
  522. this.itemsData = null;
  523. }
  524. else if (items instanceof DataSet || items instanceof DataView) {
  525. this.itemsData = items;
  526. }
  527. else {
  528. throw new TypeError('Data must be an instance of DataSet or DataView');
  529. }
  530. if (oldItemsData) {
  531. // unsubscribe from old dataset
  532. util.forEach(this.itemListeners, function (callback, event) {
  533. oldItemsData.off(event, callback);
  534. });
  535. // remove all drawn items
  536. ids = oldItemsData.getIds();
  537. this._onRemove(ids);
  538. }
  539. if (this.itemsData) {
  540. // subscribe to new dataset
  541. var id = this.id;
  542. util.forEach(this.itemListeners, function (callback, event) {
  543. me.itemsData.on(event, callback, id);
  544. });
  545. // add all new items
  546. ids = this.itemsData.getIds();
  547. this._onAdd(ids);
  548. // update the group holding all ungrouped items
  549. this._updateUngrouped();
  550. }
  551. };
  552. /**
  553. * Get the current items
  554. * @returns {vis.DataSet | null}
  555. */
  556. ItemSet.prototype.getItems = function() {
  557. return this.itemsData;
  558. };
  559. /**
  560. * Set groups
  561. * @param {vis.DataSet} groups
  562. */
  563. ItemSet.prototype.setGroups = function(groups) {
  564. var me = this,
  565. ids;
  566. // unsubscribe from current dataset
  567. if (this.groupsData) {
  568. util.forEach(this.groupListeners, function (callback, event) {
  569. me.groupsData.unsubscribe(event, callback);
  570. });
  571. // remove all drawn groups
  572. ids = this.groupsData.getIds();
  573. this.groupsData = null;
  574. this._onRemoveGroups(ids); // note: this will cause a redraw
  575. }
  576. // replace the dataset
  577. if (!groups) {
  578. this.groupsData = null;
  579. }
  580. else if (groups instanceof DataSet || groups instanceof DataView) {
  581. this.groupsData = groups;
  582. }
  583. else {
  584. throw new TypeError('Data must be an instance of DataSet or DataView');
  585. }
  586. if (this.groupsData) {
  587. // subscribe to new dataset
  588. var id = this.id;
  589. util.forEach(this.groupListeners, function (callback, event) {
  590. me.groupsData.on(event, callback, id);
  591. });
  592. // draw all ms
  593. ids = this.groupsData.getIds();
  594. this._onAddGroups(ids);
  595. }
  596. // update the group holding all ungrouped items
  597. this._updateUngrouped();
  598. // update the order of all items in each group
  599. this._order();
  600. this.body.emitter.emit('change');
  601. };
  602. /**
  603. * Get the current groups
  604. * @returns {vis.DataSet | null} groups
  605. */
  606. ItemSet.prototype.getGroups = function() {
  607. return this.groupsData;
  608. };
  609. /**
  610. * Remove an item by its id
  611. * @param {String | Number} id
  612. */
  613. ItemSet.prototype.removeItem = function(id) {
  614. var item = this.itemsData.get(id),
  615. dataset = this.itemsData.getDataSet();
  616. if (item) {
  617. // confirm deletion
  618. this.options.onRemove(item, function (item) {
  619. if (item) {
  620. // remove by id here, it is possible that an item has no id defined
  621. // itself, so better not delete by the item itself
  622. dataset.remove(id);
  623. }
  624. });
  625. }
  626. };
  627. /**
  628. * Handle updated items
  629. * @param {Number[]} ids
  630. * @protected
  631. */
  632. ItemSet.prototype._onUpdate = function(ids) {
  633. var me = this;
  634. ids.forEach(function (id) {
  635. var itemData = me.itemsData.get(id, me.itemOptions),
  636. item = me.items[id],
  637. type = itemData.type || me.options.type || (itemData.end ? 'range' : 'box');
  638. var constructor = ItemSet.types[type];
  639. if (item) {
  640. // update item
  641. if (!constructor || !(item instanceof constructor)) {
  642. // item type has changed, delete the item and recreate it
  643. me._removeItem(item);
  644. item = null;
  645. }
  646. else {
  647. me._updateItem(item, itemData);
  648. }
  649. }
  650. if (!item) {
  651. // create item
  652. if (constructor) {
  653. item = new constructor(itemData, me.conversion, me.options);
  654. item.id = id; // TODO: not so nice setting id afterwards
  655. me._addItem(item);
  656. }
  657. else if (type == 'rangeoverflow') {
  658. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  659. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
  660. '.vis.timeline .item.range .content {overflow: visible;}');
  661. }
  662. else {
  663. throw new TypeError('Unknown item type "' + type + '"');
  664. }
  665. }
  666. });
  667. this._order();
  668. this.stackDirty = true; // force re-stacking of all items next redraw
  669. this.body.emitter.emit('change');
  670. };
  671. /**
  672. * Handle added items
  673. * @param {Number[]} ids
  674. * @protected
  675. */
  676. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  677. /**
  678. * Handle removed items
  679. * @param {Number[]} ids
  680. * @protected
  681. */
  682. ItemSet.prototype._onRemove = function(ids) {
  683. var count = 0;
  684. var me = this;
  685. ids.forEach(function (id) {
  686. var item = me.items[id];
  687. if (item) {
  688. count++;
  689. me._removeItem(item);
  690. }
  691. });
  692. if (count) {
  693. // update order
  694. this._order();
  695. this.stackDirty = true; // force re-stacking of all items next redraw
  696. this.body.emitter.emit('change');
  697. }
  698. };
  699. /**
  700. * Update the order of item in all groups
  701. * @private
  702. */
  703. ItemSet.prototype._order = function() {
  704. // reorder the items in all groups
  705. // TODO: optimization: only reorder groups affected by the changed items
  706. util.forEach(this.groups, function (group) {
  707. group.order();
  708. });
  709. };
  710. /**
  711. * Handle updated groups
  712. * @param {Number[]} ids
  713. * @private
  714. */
  715. ItemSet.prototype._onUpdateGroups = function(ids) {
  716. this._onAddGroups(ids);
  717. };
  718. /**
  719. * Handle changed groups
  720. * @param {Number[]} ids
  721. * @private
  722. */
  723. ItemSet.prototype._onAddGroups = function(ids) {
  724. var me = this;
  725. ids.forEach(function (id) {
  726. var groupData = me.groupsData.get(id);
  727. var group = me.groups[id];
  728. if (!group) {
  729. // check for reserved ids
  730. if (id == UNGROUPED) {
  731. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  732. }
  733. var groupOptions = Object.create(me.options);
  734. util.extend(groupOptions, {
  735. height: null
  736. });
  737. group = new Group(id, groupData, me);
  738. me.groups[id] = group;
  739. // add items with this groupId to the new group
  740. for (var itemId in me.items) {
  741. if (me.items.hasOwnProperty(itemId)) {
  742. var item = me.items[itemId];
  743. if (item.data.group == id) {
  744. group.add(item);
  745. }
  746. }
  747. }
  748. group.order();
  749. group.show();
  750. }
  751. else {
  752. // update group
  753. group.setData(groupData);
  754. }
  755. });
  756. this.body.emitter.emit('change');
  757. };
  758. /**
  759. * Handle removed groups
  760. * @param {Number[]} ids
  761. * @private
  762. */
  763. ItemSet.prototype._onRemoveGroups = function(ids) {
  764. var groups = this.groups;
  765. ids.forEach(function (id) {
  766. var group = groups[id];
  767. if (group) {
  768. group.hide();
  769. delete groups[id];
  770. }
  771. });
  772. this.markDirty();
  773. this.body.emitter.emit('change');
  774. };
  775. /**
  776. * Reorder the groups if needed
  777. * @return {boolean} changed
  778. * @private
  779. */
  780. ItemSet.prototype._orderGroups = function () {
  781. if (this.groupsData) {
  782. // reorder the groups
  783. var groupIds = this.groupsData.getIds({
  784. order: this.options.groupOrder
  785. });
  786. var changed = !util.equalArray(groupIds, this.groupIds);
  787. if (changed) {
  788. // hide all groups, removes them from the DOM
  789. var groups = this.groups;
  790. groupIds.forEach(function (groupId) {
  791. groups[groupId].hide();
  792. });
  793. // show the groups again, attach them to the DOM in correct order
  794. groupIds.forEach(function (groupId) {
  795. groups[groupId].show();
  796. });
  797. this.groupIds = groupIds;
  798. }
  799. return changed;
  800. }
  801. else {
  802. return false;
  803. }
  804. };
  805. /**
  806. * Add a new item
  807. * @param {Item} item
  808. * @private
  809. */
  810. ItemSet.prototype._addItem = function(item) {
  811. this.items[item.id] = item;
  812. // add to group
  813. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  814. var group = this.groups[groupId];
  815. if (group) group.add(item);
  816. };
  817. /**
  818. * Update an existing item
  819. * @param {Item} item
  820. * @param {Object} itemData
  821. * @private
  822. */
  823. ItemSet.prototype._updateItem = function(item, itemData) {
  824. var oldGroupId = item.data.group;
  825. item.data = itemData;
  826. if (item.displayed) {
  827. item.redraw();
  828. }
  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 ItemRange) {
  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 range = this.body.range,
  951. snap = this.body.util.snap || null,
  952. deltaX = event.gesture.deltaX,
  953. scale = (this.props.width / (range.end - range.start)),
  954. offset = deltaX / scale;
  955. // move
  956. this.touchParams.itemProps.forEach(function (props) {
  957. if ('start' in props) {
  958. var start = new Date(props.start + offset);
  959. props.item.data.start = snap ? snap(start) : start;
  960. }
  961. if ('end' in props) {
  962. var end = new Date(props.end + offset);
  963. props.item.data.end = snap ? snap(end) : end;
  964. }
  965. if ('group' in props) {
  966. // drag from one group to another
  967. var group = ItemSet.groupFromTarget(event);
  968. _moveToGroup(props.item, group);
  969. }
  970. });
  971. // TODO: implement onMoving handler
  972. this.stackDirty = true; // force re-stacking of all items next redraw
  973. this.body.emitter.emit('change');
  974. event.stopPropagation();
  975. }
  976. };
  977. /**
  978. * Move an item to another group
  979. * @param {Item} item
  980. * @param {Group} group
  981. * @private
  982. */
  983. function _moveToGroup (item, group) {
  984. if (group && group.groupId != item.data.group) {
  985. var oldGroup = item.parent;
  986. oldGroup.remove(item);
  987. oldGroup.order();
  988. group.add(item);
  989. group.order();
  990. item.data.group = group.groupId;
  991. }
  992. }
  993. /**
  994. * End of dragging selected items
  995. * @param {Event} event
  996. * @private
  997. */
  998. ItemSet.prototype._onDragEnd = function (event) {
  999. if (this.touchParams.itemProps) {
  1000. // prepare a change set for the changed items
  1001. var changes = [],
  1002. me = this,
  1003. dataset = this.itemsData.getDataSet();
  1004. var itemProps = this.touchParams.itemProps ;
  1005. this.touchParams.itemProps = null;
  1006. itemProps.forEach(function (props) {
  1007. var id = props.item.id,
  1008. itemData = me.itemsData.get(id, me.itemOptions);
  1009. var changed = false;
  1010. if ('start' in props.item.data) {
  1011. changed = (props.start != props.item.data.start.valueOf());
  1012. itemData.start = util.convert(props.item.data.start,
  1013. dataset._options.type && dataset._options.type.start || 'Date');
  1014. }
  1015. if ('end' in props.item.data) {
  1016. changed = changed || (props.end != props.item.data.end.valueOf());
  1017. itemData.end = util.convert(props.item.data.end,
  1018. dataset._options.type && dataset._options.type.end || 'Date');
  1019. }
  1020. if ('group' in props.item.data) {
  1021. changed = changed || (props.group != props.item.data.group);
  1022. itemData.group = props.item.data.group;
  1023. }
  1024. // only apply changes when start or end is actually changed
  1025. if (changed) {
  1026. me.options.onMove(itemData, function (itemData) {
  1027. if (itemData) {
  1028. // apply changes
  1029. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1030. changes.push(itemData);
  1031. }
  1032. else {
  1033. // restore original values
  1034. if ('start' in props) props.item.data.start = props.start;
  1035. if ('end' in props) props.item.data.end = props.end;
  1036. if ('group' in props && props.item.data.group != props.group) {
  1037. var group = me.groups[props.group];
  1038. _moveToGroup(props.item, group);
  1039. }
  1040. me.stackDirty = true; // force re-stacking of all items next redraw
  1041. me.body.emitter.emit('change');
  1042. }
  1043. });
  1044. }
  1045. });
  1046. // apply the changes to the data (if there are changes)
  1047. if (changes.length) {
  1048. dataset.update(changes);
  1049. }
  1050. event.stopPropagation();
  1051. }
  1052. };
  1053. /**
  1054. * Handle selecting/deselecting an item when tapping it
  1055. * @param {Event} event
  1056. * @private
  1057. */
  1058. ItemSet.prototype._onSelectItem = function (event) {
  1059. if (!this.options.selectable) return;
  1060. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  1061. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  1062. if (ctrlKey || shiftKey) {
  1063. this._onMultiSelectItem(event);
  1064. return;
  1065. }
  1066. var oldSelection = this.getSelection();
  1067. var item = ItemSet.itemFromTarget(event);
  1068. var selection = item ? [item.id] : [];
  1069. this.setSelection(selection);
  1070. var newSelection = this.getSelection();
  1071. // emit a select event,
  1072. // except when old selection is empty and new selection is still empty
  1073. if (newSelection.length > 0 || oldSelection.length > 0) {
  1074. this.body.emitter.emit('select', {
  1075. items: this.getSelection()
  1076. });
  1077. }
  1078. event.stopPropagation();
  1079. };
  1080. /**
  1081. * Handle creation and updates of an item on double tap
  1082. * @param event
  1083. * @private
  1084. */
  1085. ItemSet.prototype._onAddItem = function (event) {
  1086. if (!this.options.selectable) return;
  1087. if (!this.options.editable.add) return;
  1088. var me = this,
  1089. snap = this.body.util.snap || null,
  1090. item = ItemSet.itemFromTarget(event);
  1091. if (item) {
  1092. // update item
  1093. // execute async handler to update the item (or cancel it)
  1094. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  1095. this.options.onUpdate(itemData, function (itemData) {
  1096. if (itemData) {
  1097. me.itemsData.update(itemData);
  1098. }
  1099. });
  1100. }
  1101. else {
  1102. // add item
  1103. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1104. var x = event.gesture.center.pageX - xAbs;
  1105. var start = this.body.util.toTime(x);
  1106. var newItem = {
  1107. start: snap ? snap(start) : start,
  1108. content: 'new item'
  1109. };
  1110. // when default type is a range, add a default end date to the new item
  1111. if (this.options.type === 'range') {
  1112. var end = this.body.util.toTime(x + this.props.width / 5);
  1113. newItem.end = snap ? snap(end) : end;
  1114. }
  1115. newItem[this.itemsData.fieldId] = util.randomUUID();
  1116. var group = ItemSet.groupFromTarget(event);
  1117. if (group) {
  1118. newItem.group = group.groupId;
  1119. }
  1120. // execute async handler to customize (or cancel) adding an item
  1121. this.options.onAdd(newItem, function (item) {
  1122. if (item) {
  1123. me.itemsData.add(newItem);
  1124. // TODO: need to trigger a redraw?
  1125. }
  1126. });
  1127. }
  1128. };
  1129. /**
  1130. * Handle selecting/deselecting multiple items when holding an item
  1131. * @param {Event} event
  1132. * @private
  1133. */
  1134. ItemSet.prototype._onMultiSelectItem = function (event) {
  1135. if (!this.options.selectable) return;
  1136. var selection,
  1137. item = ItemSet.itemFromTarget(event);
  1138. if (item) {
  1139. // multi select items
  1140. selection = this.getSelection(); // current selection
  1141. var index = selection.indexOf(item.id);
  1142. if (index == -1) {
  1143. // item is not yet selected -> select it
  1144. selection.push(item.id);
  1145. }
  1146. else {
  1147. // item is already selected -> deselect it
  1148. selection.splice(index, 1);
  1149. }
  1150. this.setSelection(selection);
  1151. this.body.emitter.emit('select', {
  1152. items: this.getSelection()
  1153. });
  1154. event.stopPropagation();
  1155. }
  1156. };
  1157. /**
  1158. * Find an item from an event target:
  1159. * searches for the attribute 'timeline-item' in the event target's element tree
  1160. * @param {Event} event
  1161. * @return {Item | null} item
  1162. */
  1163. ItemSet.itemFromTarget = function(event) {
  1164. var target = event.target;
  1165. while (target) {
  1166. if (target.hasOwnProperty('timeline-item')) {
  1167. return target['timeline-item'];
  1168. }
  1169. target = target.parentNode;
  1170. }
  1171. return null;
  1172. };
  1173. /**
  1174. * Find the Group from an event target:
  1175. * searches for the attribute 'timeline-group' in the event target's element tree
  1176. * @param {Event} event
  1177. * @return {Group | null} group
  1178. */
  1179. ItemSet.groupFromTarget = function(event) {
  1180. var target = event.target;
  1181. while (target) {
  1182. if (target.hasOwnProperty('timeline-group')) {
  1183. return target['timeline-group'];
  1184. }
  1185. target = target.parentNode;
  1186. }
  1187. return null;
  1188. };
  1189. /**
  1190. * Find the ItemSet from an event target:
  1191. * searches for the attribute 'timeline-itemset' in the event target's element tree
  1192. * @param {Event} event
  1193. * @return {ItemSet | null} item
  1194. */
  1195. ItemSet.itemSetFromTarget = function(event) {
  1196. var target = event.target;
  1197. while (target) {
  1198. if (target.hasOwnProperty('timeline-itemset')) {
  1199. return target['timeline-itemset'];
  1200. }
  1201. target = target.parentNode;
  1202. }
  1203. return null;
  1204. };
  1205. module.exports = ItemSet;