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.

520 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. // 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 = this.getItemRange();
  325. this.range.setRange(range.min, range.max, animation);
  326. };
  327. /**
  328. * Determine the range of the items, taking into account their actual width
  329. * and a margin of 10 pixels on both sides.
  330. * @return {{min: Date | null, max: Date | null}}
  331. */
  332. Timeline.prototype.getItemRange = function () {
  333. // get a rough approximation for the range based on the items start and end dates
  334. var range = this.getDataRange();
  335. var min = range.min !== null ? range.min.valueOf() : null;
  336. var max = range.max !== null ? range.max.valueOf() : null;
  337. var minItem = null;
  338. var maxItem = null;
  339. if (min != null && max != null) {
  340. var interval = (max - min); // ms
  341. if (interval <= 0) {
  342. interval = 10;
  343. }
  344. var factor = interval / this.props.center.width;
  345. function getStart(item) {
  346. return util.convert(item.data.start, 'Date').valueOf()
  347. }
  348. function getEnd(item) {
  349. var end = item.data.end != undefined ? item.data.end : item.data.start;
  350. return util.convert(end, 'Date').valueOf();
  351. }
  352. // calculate the date of the left side and right side of the items given
  353. util.forEach(this.itemSet.items, function (item) {
  354. item.show();
  355. item.repositionX();
  356. var start = getStart(item);
  357. var end = getEnd(item);
  358. var left = start - (item.getWidthLeft() + 10) * factor;
  359. var right = end + (item.getWidthRight() + 10) * factor;
  360. if (left < min) {
  361. min = left;
  362. minItem = item;
  363. }
  364. if (right > max) {
  365. max = right;
  366. maxItem = item;
  367. }
  368. }.bind(this));
  369. if (minItem && maxItem) {
  370. var lhs = minItem.getWidthLeft() + 10;
  371. var rhs = maxItem.getWidthRight() + 10;
  372. var delta = this.props.center.width - lhs - rhs; // px
  373. if (delta > 0) {
  374. min = getStart(minItem) - lhs * interval / delta; // ms
  375. max = getEnd(maxItem) + rhs * interval / delta; // ms
  376. }
  377. }
  378. }
  379. return {
  380. min: min != null ? new Date(min) : null,
  381. max: max != null ? new Date(max) : null
  382. }
  383. };
  384. /**
  385. * Calculate the data range of the items start and end dates
  386. * @returns {{min: Date | null, max: Date | null}}
  387. */
  388. Timeline.prototype.getDataRange = function() {
  389. var min = null;
  390. var max = null;
  391. var dataset = this.itemsData && this.itemsData.getDataSet();
  392. if (dataset) {
  393. dataset.forEach(function (item) {
  394. var start = util.convert(item.start, 'Date').valueOf();
  395. var end = util.convert(item.end != undefined ? item.end : item.start, 'Date').valueOf();
  396. if (min === null || start < min) {
  397. min = start;
  398. }
  399. if (max === null || end > max) {
  400. max = end;
  401. }
  402. });
  403. }
  404. return {
  405. min: min != null ? new Date(min) : null,
  406. max: max != null ? new Date(max) : null
  407. }
  408. };
  409. /**
  410. * Generate Timeline related information from an event
  411. * @param {Event} event
  412. * @return {Object} An object with related information, like on which area
  413. * The event happened, whether clicked on an item, etc.
  414. */
  415. Timeline.prototype.getEventProperties = function (event) {
  416. var clientX = event.center ? event.center.x : event.clientX;
  417. var clientY = event.center ? event.center.y : event.clientY;
  418. var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
  419. var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
  420. var item = this.itemSet.itemFromTarget(event);
  421. var group = this.itemSet.groupFromTarget(event);
  422. var customTime = CustomTime.customTimeFromTarget(event);
  423. var snap = this.itemSet.options.snap || null;
  424. var scale = this.body.util.getScale();
  425. var step = this.body.util.getStep();
  426. var time = this._toTime(x);
  427. var snappedTime = snap ? snap(time, scale, step) : time;
  428. var element = util.getTarget(event);
  429. var what = null;
  430. if (item != null) {what = 'item';}
  431. else if (customTime != null) {what = 'custom-time';}
  432. else if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
  433. else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
  434. else if (util.hasParent(element, this.itemSet.dom.labelSet)) {what = 'group-label';}
  435. else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
  436. else if (util.hasParent(element, this.dom.center)) {what = 'background';}
  437. return {
  438. event: event,
  439. item: item ? item.id : null,
  440. group: group ? group.groupId : null,
  441. what: what,
  442. pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
  443. pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
  444. x: x,
  445. y: y,
  446. time: time,
  447. snappedTime: snappedTime
  448. }
  449. };
  450. module.exports = Timeline;