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.

523 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. throttleRedraw: 0, // ms
  43. orientation: {
  44. axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both'
  45. item: 'bottom' // not relevant
  46. },
  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);
  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. else {
  137. this._redraw();
  138. }
  139. }
  140. // Extend the functionality from Core
  141. Timeline.prototype = new Core();
  142. /**
  143. * Load a configurator
  144. * @return {Object}
  145. * @private
  146. */
  147. Timeline.prototype._createConfigurator = function () {
  148. return new Configurator(this, this.dom.container, configureOptions);
  149. };
  150. /**
  151. * Force a redraw. The size of all items will be recalculated.
  152. * Can be useful to manually redraw when option autoResize=false and the window
  153. * has been resized, or when the items CSS has been changed.
  154. *
  155. * Note: this function will be overridden on construction with a trottled version
  156. */
  157. Timeline.prototype.redraw = function() {
  158. this.itemSet && this.itemSet.markDirty({refreshItems: true});
  159. this._redraw();
  160. };
  161. Timeline.prototype.setOptions = function (options) {
  162. // validate options
  163. let errorFound = Validator.validate(options, allOptions);
  164. if (errorFound === true) {
  165. console.log('%cErrors have been found in the supplied options object.', printStyle);
  166. }
  167. Core.prototype.setOptions.call(this, options);
  168. if ('type' in options) {
  169. if (options.type !== this.options.type) {
  170. this.options.type = options.type;
  171. // force recreation of all items
  172. var itemsData = this.itemsData;
  173. if (itemsData) {
  174. var selection = this.getSelection();
  175. this.setItems(null); // remove all
  176. this.setItems(itemsData); // add all
  177. this.setSelection(selection); // restore selection
  178. }
  179. }
  180. }
  181. };
  182. /**
  183. * Set items
  184. * @param {vis.DataSet | Array | null} items
  185. */
  186. Timeline.prototype.setItems = function(items) {
  187. // convert to type DataSet when needed
  188. var newDataSet;
  189. if (!items) {
  190. newDataSet = null;
  191. }
  192. else if (items instanceof DataSet || items instanceof DataView) {
  193. newDataSet = items;
  194. }
  195. else {
  196. // turn an array into a dataset
  197. newDataSet = new DataSet(items, {
  198. type: {
  199. start: 'Date',
  200. end: 'Date'
  201. }
  202. });
  203. }
  204. // set items
  205. this.itemsData = newDataSet;
  206. this.itemSet && this.itemSet.setItems(newDataSet);
  207. this.body.emitter.emit('_change', {queue: true});
  208. };
  209. /**
  210. * Set groups
  211. * @param {vis.DataSet | Array} groups
  212. */
  213. Timeline.prototype.setGroups = function(groups) {
  214. // convert to type DataSet when needed
  215. var newDataSet;
  216. if (!groups) {
  217. newDataSet = null;
  218. }
  219. else if (groups instanceof DataSet || groups instanceof DataView) {
  220. newDataSet = groups;
  221. }
  222. else {
  223. // turn an array into a dataset
  224. newDataSet = new DataSet(groups);
  225. }
  226. this.groupsData = newDataSet;
  227. this.itemSet.setGroups(newDataSet);
  228. };
  229. /**
  230. * Set both items and groups in one go
  231. * @param {{items: Array | vis.DataSet, groups: Array | vis.DataSet}} data
  232. */
  233. Timeline.prototype.setData = function (data) {
  234. if (data && data.groups) {
  235. this.setGroups(data.groups);
  236. }
  237. if (data && data.items) {
  238. this.setItems(data.items);
  239. }
  240. };
  241. /**
  242. * Set selected items by their id. Replaces the current selection
  243. * Unknown id's are silently ignored.
  244. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  245. * selected. If ids is an empty array, all items will be
  246. * unselected.
  247. * @param {Object} [options] Available options:
  248. * `focus: boolean`
  249. * If true, focus will be set to the selected item(s)
  250. * `animation: boolean | {duration: number, easingFunction: string}`
  251. * If true (default), the range is animated
  252. * smoothly to the new window. An object can be
  253. * provided to specify duration and easing function.
  254. * Default duration is 500 ms, and default easing
  255. * function is 'easeInOutQuad'.
  256. * Only applicable when option focus is true.
  257. */
  258. Timeline.prototype.setSelection = function(ids, options) {
  259. this.itemSet && this.itemSet.setSelection(ids);
  260. if (options && options.focus) {
  261. this.focus(ids, options);
  262. }
  263. };
  264. /**
  265. * Get the selected items by their id
  266. * @return {Array} ids The ids of the selected items
  267. */
  268. Timeline.prototype.getSelection = function() {
  269. return this.itemSet && this.itemSet.getSelection() || [];
  270. };
  271. /**
  272. * Adjust the visible window such that the selected item (or multiple items)
  273. * are centered on screen.
  274. * @param {String | String[]} id An item id or array with item ids
  275. * @param {Object} [options] Available options:
  276. * `animation: boolean | {duration: number, easingFunction: string}`
  277. * If true (default), the range is animated
  278. * smoothly to the new window. An object can be
  279. * provided to specify duration and easing function.
  280. * Default duration is 500 ms, and default easing
  281. * function is 'easeInOutQuad'.
  282. */
  283. Timeline.prototype.focus = function(id, options) {
  284. if (!this.itemsData || id == undefined) return;
  285. var ids = Array.isArray(id) ? id : [id];
  286. // get the specified item(s)
  287. var itemsData = this.itemsData.getDataSet().get(ids, {
  288. type: {
  289. start: 'Date',
  290. end: 'Date'
  291. }
  292. });
  293. // calculate minimum start and maximum end of specified items
  294. var start = null;
  295. var end = null;
  296. itemsData.forEach(function (itemData) {
  297. var s = itemData.start.valueOf();
  298. var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf();
  299. if (start === null || s < start) {
  300. start = s;
  301. }
  302. if (end === null || e > end) {
  303. end = e;
  304. }
  305. });
  306. if (start !== null && end !== null) {
  307. // calculate the new middle and interval for the window
  308. var middle = (start + end) / 2;
  309. var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1);
  310. var animation = (options && options.animation !== undefined) ? options.animation : true;
  311. this.range.setRange(middle - interval / 2, middle + interval / 2, animation);
  312. }
  313. };
  314. /**
  315. * Set Timeline window such that it fits all items
  316. * @param {Object} [options] Available options:
  317. * `animation: boolean | {duration: number, easingFunction: string}`
  318. * If true (default), the range is animated
  319. * smoothly to the new window. An object can be
  320. * provided to specify duration and easing function.
  321. * Default duration is 500 ms, and default easing
  322. * function is 'easeInOutQuad'.
  323. */
  324. Timeline.prototype.fit = function (options) {
  325. var animation = (options && options.animation !== undefined) ? options.animation : true;
  326. var range = this.getItemRange();
  327. this.range.setRange(range.min, range.max, animation);
  328. };
  329. /**
  330. * Determine the range of the items, taking into account their actual width
  331. * and a margin of 10 pixels on both sides.
  332. * @return {{min: Date | null, max: Date | null}}
  333. */
  334. Timeline.prototype.getItemRange = function () {
  335. // get a rough approximation for the range based on the items start and end dates
  336. var range = this.getDataRange();
  337. var min = range.min !== null ? range.min.valueOf() : null;
  338. var max = range.max !== null ? range.max.valueOf() : null;
  339. var minItem = null;
  340. var maxItem = null;
  341. if (min != null && max != null) {
  342. var interval = (max - min); // ms
  343. if (interval <= 0) {
  344. interval = 10;
  345. }
  346. var factor = interval / this.props.center.width;
  347. function getStart(item) {
  348. return util.convert(item.data.start, 'Date').valueOf()
  349. }
  350. function getEnd(item) {
  351. var end = item.data.end != undefined ? item.data.end : item.data.start;
  352. return util.convert(end, 'Date').valueOf();
  353. }
  354. // calculate the date of the left side and right side of the items given
  355. util.forEach(this.itemSet.items, function (item) {
  356. item.show();
  357. item.repositionX();
  358. var start = getStart(item);
  359. var end = getEnd(item);
  360. var left = start - (item.getWidthLeft() + 10) * factor;
  361. var right = end + (item.getWidthRight() + 10) * factor;
  362. if (left < min) {
  363. min = left;
  364. minItem = item;
  365. }
  366. if (right > max) {
  367. max = right;
  368. maxItem = item;
  369. }
  370. }.bind(this));
  371. if (minItem && maxItem) {
  372. var lhs = minItem.getWidthLeft() + 10;
  373. var rhs = maxItem.getWidthRight() + 10;
  374. var delta = this.props.center.width - lhs - rhs; // px
  375. if (delta > 0) {
  376. min = getStart(minItem) - lhs * interval / delta; // ms
  377. max = getEnd(maxItem) + rhs * interval / delta; // ms
  378. }
  379. }
  380. }
  381. return {
  382. min: min != null ? new Date(min) : null,
  383. max: max != null ? new Date(max) : null
  384. }
  385. };
  386. /**
  387. * Calculate the data range of the items start and end dates
  388. * @returns {{min: Date | null, max: Date | null}}
  389. */
  390. Timeline.prototype.getDataRange = function() {
  391. var min = null;
  392. var max = null;
  393. var dataset = this.itemsData && this.itemsData.getDataSet();
  394. if (dataset) {
  395. dataset.forEach(function (item) {
  396. var start = util.convert(item.start, 'Date').valueOf();
  397. var end = util.convert(item.end != undefined ? item.end : item.start, 'Date').valueOf();
  398. if (min === null || start < min) {
  399. min = start;
  400. }
  401. if (max === null || end > max) {
  402. max = end;
  403. }
  404. });
  405. }
  406. return {
  407. min: min != null ? new Date(min) : null,
  408. max: max != null ? new Date(max) : null
  409. }
  410. };
  411. /**
  412. * Generate Timeline related information from an event
  413. * @param {Event} event
  414. * @return {Object} An object with related information, like on which area
  415. * The event happened, whether clicked on an item, etc.
  416. */
  417. Timeline.prototype.getEventProperties = function (event) {
  418. var clientX = event.center ? event.center.x : event.clientX;
  419. var clientY = event.center ? event.center.y : event.clientY;
  420. var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
  421. var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
  422. var item = this.itemSet.itemFromTarget(event);
  423. var group = this.itemSet.groupFromTarget(event);
  424. var customTime = CustomTime.customTimeFromTarget(event);
  425. var snap = this.itemSet.options.snap || null;
  426. var scale = this.body.util.getScale();
  427. var step = this.body.util.getStep();
  428. var time = this._toTime(x);
  429. var snappedTime = snap ? snap(time, scale, step) : time;
  430. var element = util.getTarget(event);
  431. var what = null;
  432. if (item != null) {what = 'item';}
  433. else if (customTime != null) {what = 'custom-time';}
  434. else if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
  435. else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
  436. else if (util.hasParent(element, this.itemSet.dom.labelSet)) {what = 'group-label';}
  437. else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
  438. else if (util.hasParent(element, this.dom.center)) {what = 'background';}
  439. return {
  440. event: event,
  441. item: item ? item.id : null,
  442. group: group ? group.groupId : null,
  443. what: what,
  444. pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
  445. pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
  446. x: x,
  447. y: y,
  448. time: time,
  449. snappedTime: snappedTime
  450. }
  451. };
  452. module.exports = Timeline;