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.

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