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.

570 lines
18 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. var Emitter = require('emitter-component');
  2. var Hammer = require('../module/hammer');
  3. var moment = require('../module/moment');
  4. var util = require('../util');
  5. var DataSet = require('../DataSet');
  6. var DataView = require('../DataView');
  7. var Range = require('./Range');
  8. var Core = require('./Core');
  9. var TimeAxis = require('./component/TimeAxis');
  10. var CurrentTime = require('./component/CurrentTime');
  11. var CustomTime = require('./component/CustomTime');
  12. var ItemSet = require('./component/ItemSet');
  13. var printStyle = require('../shared/Validator').printStyle;
  14. var allOptions = require('./optionsTimeline').allOptions;
  15. var configureOptions = require('./optionsTimeline').configureOptions;
  16. import Configurator from '../shared/Configurator';
  17. import Validator from '../shared/Validator';
  18. /**
  19. * Create a timeline visualization
  20. * @param {HTMLElement} container
  21. * @param {vis.DataSet | vis.DataView | Array} [items]
  22. * @param {vis.DataSet | vis.DataView | Array} [groups]
  23. * @param {Object} [options] See Timeline.setOptions for the available options.
  24. * @constructor
  25. * @extends Core
  26. */
  27. function Timeline (container, items, groups, options) {
  28. if (!(this instanceof Timeline)) {
  29. throw new SyntaxError('Constructor must be called with the new operator');
  30. }
  31. // if the third element is options, the forth is groups (optionally);
  32. if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) {
  33. var forthArgument = options;
  34. options = groups;
  35. groups = forthArgument;
  36. }
  37. var me = this;
  38. this.defaultOptions = {
  39. start: null,
  40. end: null,
  41. autoResize: true,
  42. orientation: {
  43. axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both'
  44. item: 'bottom' // not relevant
  45. },
  46. rtl: false,
  47. moment: moment,
  48. width: null,
  49. height: null,
  50. maxHeight: null,
  51. minHeight: null
  52. };
  53. this.options = util.deepExtend({}, this.defaultOptions);
  54. // Create the DOM, props, and emitter
  55. this._create(container);
  56. // all components listed here will be repainted automatically
  57. this.components = [];
  58. this.body = {
  59. dom: this.dom,
  60. domProps: this.props,
  61. emitter: {
  62. on: this.on.bind(this),
  63. off: this.off.bind(this),
  64. emit: this.emit.bind(this)
  65. },
  66. hiddenDates: [],
  67. util: {
  68. getScale: function () {
  69. return me.timeAxis.step.scale;
  70. },
  71. getStep: function () {
  72. return me.timeAxis.step.step;
  73. },
  74. toScreen: me._toScreen.bind(me),
  75. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  76. toTime: me._toTime.bind(me),
  77. toGlobalTime : me._toGlobalTime.bind(me)
  78. }
  79. };
  80. // range
  81. this.range = new Range(this.body);
  82. this.components.push(this.range);
  83. this.body.range = this.range;
  84. // time axis
  85. this.timeAxis = new TimeAxis(this.body);
  86. this.timeAxis2 = null; // used in case of orientation option 'both'
  87. this.components.push(this.timeAxis);
  88. // current time bar
  89. this.currentTime = new CurrentTime(this.body);
  90. this.components.push(this.currentTime);
  91. // item set
  92. this.itemSet = new ItemSet(this.body, this.options);
  93. this.components.push(this.itemSet);
  94. this.itemsData = null; // DataSet
  95. this.groupsData = null; // DataSet
  96. this.on('tap', function (event) {
  97. me.emit('click', me.getEventProperties(event))
  98. });
  99. this.on('doubletap', function (event) {
  100. me.emit('doubleClick', me.getEventProperties(event))
  101. });
  102. this.dom.root.oncontextmenu = function (event) {
  103. me.emit('contextmenu', me.getEventProperties(event))
  104. };
  105. //Single time autoscale/fit
  106. this.fitDone = false;
  107. this.on('changed', function (){
  108. if (this.itemsData == null) return;
  109. if (!me.fitDone) {
  110. me.fitDone = true;
  111. if (me.options.start != undefined || me.options.end != undefined) {
  112. if (me.options.start == undefined || me.options.end == undefined) {
  113. var range = me.getItemRange();
  114. }
  115. var start = me.options.start != undefined ? me.options.start : range.min;
  116. var end = me.options.end != undefined ? me.options.end : range.max;
  117. me.setWindow(start, end, {animation: false});
  118. }
  119. else {
  120. me.fit({animation: false});
  121. }
  122. }
  123. });
  124. // apply options
  125. if (options) {
  126. this.setOptions(options);
  127. }
  128. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  129. if (groups) {
  130. this.setGroups(groups);
  131. }
  132. // create itemset
  133. if (items) {
  134. this.setItems(items);
  135. }
  136. // draw for the first time
  137. this._redraw();
  138. }
  139. // Extend the functionality from Core
  140. Timeline.prototype = new Core();
  141. /**
  142. * Load a configurator
  143. * @return {Object}
  144. * @private
  145. */
  146. Timeline.prototype._createConfigurator = function () {
  147. return new Configurator(this, this.dom.container, configureOptions);
  148. };
  149. /**
  150. * Force a redraw. The size of all items will be recalculated.
  151. * Can be useful to manually redraw when option autoResize=false and the window
  152. * has been resized, or when the items CSS has been changed.
  153. *
  154. * Note: this function will be overridden on construction with a trottled version
  155. */
  156. Timeline.prototype.redraw = function() {
  157. this.itemSet && this.itemSet.markDirty({refreshItems: true});
  158. this._redraw();
  159. };
  160. Timeline.prototype.setOptions = function (options) {
  161. // validate options
  162. let errorFound = Validator.validate(options, allOptions);
  163. if (errorFound === true) {
  164. console.log('%cErrors have been found in the supplied options object.', printStyle);
  165. }
  166. Core.prototype.setOptions.call(this, options);
  167. if ('type' in options) {
  168. if (options.type !== this.options.type) {
  169. this.options.type = options.type;
  170. // force recreation of all items
  171. var itemsData = this.itemsData;
  172. if (itemsData) {
  173. var selection = this.getSelection();
  174. this.setItems(null); // remove all
  175. this.setItems(itemsData); // add all
  176. this.setSelection(selection); // restore selection
  177. }
  178. }
  179. }
  180. };
  181. /**
  182. * Set items
  183. * @param {vis.DataSet | Array | null} items
  184. */
  185. Timeline.prototype.setItems = function(items) {
  186. // convert to type DataSet when needed
  187. var newDataSet;
  188. if (!items) {
  189. newDataSet = null;
  190. }
  191. else if (items instanceof DataSet || items instanceof DataView) {
  192. newDataSet = items;
  193. }
  194. else {
  195. // turn an array into a dataset
  196. newDataSet = new DataSet(items, {
  197. type: {
  198. start: 'Date',
  199. end: 'Date'
  200. }
  201. });
  202. }
  203. // set items
  204. this.itemsData = newDataSet;
  205. this.itemSet && this.itemSet.setItems(newDataSet);
  206. };
  207. /**
  208. * Set groups
  209. * @param {vis.DataSet | Array} groups
  210. */
  211. Timeline.prototype.setGroups = function(groups) {
  212. // convert to type DataSet when needed
  213. var newDataSet;
  214. if (!groups) {
  215. newDataSet = null;
  216. }
  217. else if (groups instanceof DataSet || groups instanceof DataView) {
  218. newDataSet = groups;
  219. }
  220. else {
  221. // turn an array into a dataset
  222. newDataSet = new DataSet(groups);
  223. }
  224. this.groupsData = newDataSet;
  225. this.itemSet.setGroups(newDataSet);
  226. };
  227. /**
  228. * Set both items and groups in one go
  229. * @param {{items: Array | vis.DataSet, groups: Array | vis.DataSet}} data
  230. */
  231. Timeline.prototype.setData = function (data) {
  232. if (data && data.groups) {
  233. this.setGroups(data.groups);
  234. }
  235. if (data && data.items) {
  236. this.setItems(data.items);
  237. }
  238. };
  239. /**
  240. * Set selected items by their id. Replaces the current selection
  241. * Unknown id's are silently ignored.
  242. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  243. * selected. If ids is an empty array, all items will be
  244. * unselected.
  245. * @param {Object} [options] Available options:
  246. * `focus: boolean`
  247. * If true, focus will be set to the selected item(s)
  248. * `animation: boolean | {duration: number, easingFunction: string}`
  249. * If true (default), the range is animated
  250. * smoothly to the new window. An object can be
  251. * provided to specify duration and easing function.
  252. * Default duration is 500 ms, and default easing
  253. * function is 'easeInOutQuad'.
  254. * Only applicable when option focus is true.
  255. */
  256. Timeline.prototype.setSelection = function(ids, options) {
  257. this.itemSet && this.itemSet.setSelection(ids);
  258. if (options && options.focus) {
  259. this.focus(ids, options);
  260. }
  261. };
  262. /**
  263. * Get the selected items by their id
  264. * @return {Array} ids The ids of the selected items
  265. */
  266. Timeline.prototype.getSelection = function() {
  267. return this.itemSet && this.itemSet.getSelection() || [];
  268. };
  269. /**
  270. * Adjust the visible window such that the selected item (or multiple items)
  271. * are centered on screen.
  272. * @param {String | String[]} id An item id or array with item ids
  273. * @param {Object} [options] Available options:
  274. * `animation: boolean | {duration: number, easingFunction: string}`
  275. * If true (default), the range is animated
  276. * smoothly to the new window. An object can be
  277. * provided to specify duration and easing function.
  278. * Default duration is 500 ms, and default easing
  279. * function is 'easeInOutQuad'.
  280. */
  281. Timeline.prototype.focus = function(id, options) {
  282. if (!this.itemsData || id == undefined) return;
  283. var ids = Array.isArray(id) ? id : [id];
  284. // get the specified item(s)
  285. var itemsData = this.itemsData.getDataSet().get(ids, {
  286. type: {
  287. start: 'Date',
  288. end: 'Date'
  289. }
  290. });
  291. // calculate minimum start and maximum end of specified items
  292. var start = null;
  293. var end = null;
  294. itemsData.forEach(function (itemData) {
  295. var s = itemData.start.valueOf();
  296. var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf();
  297. if (start === null || s < start) {
  298. start = s;
  299. }
  300. if (end === null || e > end) {
  301. end = e;
  302. }
  303. });
  304. if (start !== null && end !== null) {
  305. // calculate the new middle and interval for the window
  306. var middle = (start + end) / 2;
  307. var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1);
  308. var animation = (options && options.animation !== undefined) ? options.animation : true;
  309. this.range.setRange(middle - interval / 2, middle + interval / 2, animation);
  310. }
  311. };
  312. /**
  313. * Set Timeline window such that it fits all items
  314. * @param {Object} [options] Available options:
  315. * `animation: boolean | {duration: number, easingFunction: string}`
  316. * If true (default), the range is animated
  317. * smoothly to the new window. An object can be
  318. * provided to specify duration and easing function.
  319. * Default duration is 500 ms, and default easing
  320. * function is 'easeInOutQuad'.
  321. */
  322. Timeline.prototype.fit = function (options) {
  323. var animation = (options && options.animation !== undefined) ? options.animation : true;
  324. var range;
  325. var dataset = this.itemsData && this.itemsData.getDataSet();
  326. if (dataset.length === 1 && dataset.get()[0].end === undefined) {
  327. // a single item -> don't fit, just show a range around the item from -4 to +3 days
  328. range = this.getDataRange();
  329. this.moveTo(range.min.valueOf(), {animation});
  330. }
  331. else {
  332. // exactly fit the items (plus a small margin)
  333. range = this.getItemRange();
  334. this.range.setRange(range.min, range.max, animation);
  335. }
  336. };
  337. /**
  338. * Determine the range of the items, taking into account their actual width
  339. * and a margin of 10 pixels on both sides.
  340. * @return {{min: Date | null, max: Date | null}}
  341. */
  342. Timeline.prototype.getItemRange = function () {
  343. // get a rough approximation for the range based on the items start and end dates
  344. var range = this.getDataRange();
  345. var min = range.min !== null ? range.min.valueOf() : null;
  346. var max = range.max !== null ? range.max.valueOf() : null;
  347. var minItem = null;
  348. var maxItem = null;
  349. if (min != null && max != null) {
  350. var interval = (max - min); // ms
  351. if (interval <= 0) {
  352. interval = 10;
  353. }
  354. var factor = interval / this.props.center.width;
  355. function getStart(item) {
  356. return util.convert(item.data.start, 'Date').valueOf()
  357. }
  358. function getEnd(item) {
  359. var end = item.data.end != undefined ? item.data.end : item.data.start;
  360. return util.convert(end, 'Date').valueOf();
  361. }
  362. // calculate the date of the left side and right side of the items given
  363. util.forEach(this.itemSet.items, function (item) {
  364. item.show();
  365. item.repositionX();
  366. var start = getStart(item);
  367. var end = getEnd(item);
  368. if (this.options.rtl) {
  369. var startSide = start - (item.getWidthRight() + 10) * factor;
  370. var endSide = end + (item.getWidthLeft() + 10) * factor;
  371. } else {
  372. var startSide = start - (item.getWidthLeft() + 10) * factor;
  373. var endSide = end + (item.getWidthRight() + 10) * factor;
  374. }
  375. if (startSide < min) {
  376. min = startSide;
  377. minItem = item;
  378. }
  379. if (endSide > max) {
  380. max = endSide;
  381. maxItem = item;
  382. }
  383. }.bind(this));
  384. if (minItem && maxItem) {
  385. var lhs = minItem.getWidthLeft() + 10;
  386. var rhs = maxItem.getWidthRight() + 10;
  387. var delta = this.props.center.width - lhs - rhs; // px
  388. if (delta > 0) {
  389. if (this.options.rtl) {
  390. min = getStart(minItem) - rhs * interval / delta; // ms
  391. max = getEnd(maxItem) + lhs * interval / delta; // ms
  392. } else {
  393. min = getStart(minItem) - lhs * interval / delta; // ms
  394. max = getEnd(maxItem) + rhs * interval / delta; // ms
  395. }
  396. }
  397. }
  398. }
  399. return {
  400. min: min != null ? new Date(min) : null,
  401. max: max != null ? new Date(max) : null
  402. }
  403. };
  404. /**
  405. * Calculate the data range of the items start and end dates
  406. * @returns {{min: Date | null, max: Date | null}}
  407. */
  408. Timeline.prototype.getDataRange = function() {
  409. var min = null;
  410. var max = null;
  411. var dataset = this.itemsData && this.itemsData.getDataSet();
  412. if (dataset) {
  413. dataset.forEach(function (item) {
  414. var start = util.convert(item.start, 'Date').valueOf();
  415. var end = util.convert(item.end != undefined ? item.end : item.start, 'Date').valueOf();
  416. if (min === null || start < min) {
  417. min = start;
  418. }
  419. if (max === null || end > max) {
  420. max = end;
  421. }
  422. });
  423. }
  424. return {
  425. min: min != null ? new Date(min) : null,
  426. max: max != null ? new Date(max) : null
  427. }
  428. };
  429. /**
  430. * Generate Timeline related information from an event
  431. * @param {Event} event
  432. * @return {Object} An object with related information, like on which area
  433. * The event happened, whether clicked on an item, etc.
  434. */
  435. Timeline.prototype.getEventProperties = function (event) {
  436. var clientX = event.center ? event.center.x : event.clientX;
  437. var clientY = event.center ? event.center.y : event.clientY;
  438. if (this.options.rtl) {
  439. var x = util.getAbsoluteRight(this.dom.centerContainer) - clientX;
  440. } else {
  441. var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
  442. }
  443. var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
  444. var item = this.itemSet.itemFromTarget(event);
  445. var group = this.itemSet.groupFromTarget(event);
  446. var customTime = CustomTime.customTimeFromTarget(event);
  447. var snap = this.itemSet.options.snap || null;
  448. var scale = this.body.util.getScale();
  449. var step = this.body.util.getStep();
  450. var time = this._toTime(x);
  451. var snappedTime = snap ? snap(time, scale, step) : time;
  452. var element = util.getTarget(event);
  453. var what = null;
  454. if (item != null) {what = 'item';}
  455. else if (customTime != null) {what = 'custom-time';}
  456. else if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
  457. else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
  458. else if (util.hasParent(element, this.itemSet.dom.labelSet)) {what = 'group-label';}
  459. else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
  460. else if (util.hasParent(element, this.dom.center)) {what = 'background';}
  461. return {
  462. event: event,
  463. item: item ? item.id : null,
  464. group: group ? group.groupId : null,
  465. what: what,
  466. pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
  467. pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
  468. x: x,
  469. y: y,
  470. time: time,
  471. snappedTime: snappedTime
  472. }
  473. };
  474. /**
  475. * Extend the drag event handler from Core, move the timeline vertically
  476. * @param {Event} event
  477. * @private
  478. */
  479. Timeline.prototype._onDrag = function (event) {
  480. // refuse to drag when we where pinching to prevent the timeline make a jump
  481. // when releasing the fingers in opposite order from the touch screen, and refuse
  482. // to drag when an item is already being dragged
  483. if (!this.touch.allowDragging || this.itemSet.touchParams.itemIsDragging) return;
  484. var delta = event.deltaY;
  485. var oldScrollTop = this._getScrollTop();
  486. var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
  487. if (newScrollTop != oldScrollTop) {
  488. this.emit("verticalDrag");
  489. }
  490. };
  491. module.exports = Timeline;