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

1421 lines
39 KiB

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