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.

556 lines
17 KiB

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