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.

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