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.

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