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.

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