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.

551 lines
17 KiB

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