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.

546 lines
17 KiB

11 years ago
11 years ago
11 years ago
8 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. if (options) {
  54. this.options.rtl = options.rtl
  55. }
  56. // Create the DOM, props, and emitter
  57. this._create(container);
  58. // all components listed here will be repainted automatically
  59. this.components = [];
  60. this.body = {
  61. dom: this.dom,
  62. domProps: this.props,
  63. emitter: {
  64. on: this.on.bind(this),
  65. off: this.off.bind(this),
  66. emit: this.emit.bind(this)
  67. },
  68. hiddenDates: [],
  69. util: {
  70. getScale: function () {
  71. return me.timeAxis.step.scale;
  72. },
  73. getStep: function () {
  74. return me.timeAxis.step.step;
  75. },
  76. toScreen: me._toScreen.bind(me),
  77. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  78. toTime: me._toTime.bind(me),
  79. toGlobalTime : me._toGlobalTime.bind(me)
  80. }
  81. };
  82. // range
  83. this.range = new Range(this.body);
  84. this.components.push(this.range);
  85. this.body.range = this.range;
  86. // time axis
  87. this.timeAxis = new TimeAxis(this.body);
  88. this.timeAxis2 = null; // used in case of orientation option 'both'
  89. this.components.push(this.timeAxis);
  90. // current time bar
  91. this.currentTime = new CurrentTime(this.body);
  92. this.components.push(this.currentTime);
  93. // item set
  94. this.itemSet = new ItemSet(this.body, this.options);
  95. this.components.push(this.itemSet);
  96. this.itemsData = null; // DataSet
  97. this.groupsData = null; // DataSet
  98. this.on('tap', function (event) {
  99. me.emit('click', me.getEventProperties(event))
  100. });
  101. this.on('doubletap', function (event) {
  102. me.emit('doubleClick', me.getEventProperties(event))
  103. });
  104. this.dom.root.oncontextmenu = function (event) {
  105. me.emit('contextmenu', me.getEventProperties(event))
  106. };
  107. //Single time autoscale/fit
  108. this.fitDone = false;
  109. this.on('changed', function (){
  110. if (this.itemsData == null) return;
  111. if (!me.fitDone) {
  112. me.fitDone = true;
  113. if (me.options.start != undefined || me.options.end != undefined) {
  114. if (me.options.start == undefined || me.options.end == undefined) {
  115. var range = me.getItemRange();
  116. }
  117. var start = me.options.start != undefined ? me.options.start : range.min;
  118. var end = me.options.end != undefined ? me.options.end : range.max;
  119. me.setWindow(start, end, {animation: false});
  120. }
  121. else {
  122. me.fit({animation: false});
  123. }
  124. }
  125. });
  126. // apply options
  127. if (options) {
  128. this.setOptions(options);
  129. }
  130. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  131. if (groups) {
  132. this.setGroups(groups);
  133. }
  134. // create itemset
  135. if (items) {
  136. this.setItems(items);
  137. }
  138. // draw for the first time
  139. this._redraw();
  140. }
  141. // Extend the functionality from Core
  142. Timeline.prototype = new Core();
  143. /**
  144. * Load a configurator
  145. * @return {Object}
  146. * @private
  147. */
  148. Timeline.prototype._createConfigurator = function () {
  149. return new Configurator(this, this.dom.container, configureOptions);
  150. };
  151. /**
  152. * Force a redraw. The size of all items will be recalculated.
  153. * Can be useful to manually redraw when option autoResize=false and the window
  154. * has been resized, or when the items CSS has been changed.
  155. *
  156. * Note: this function will be overridden on construction with a trottled version
  157. */
  158. Timeline.prototype.redraw = function() {
  159. this.itemSet && this.itemSet.markDirty({refreshItems: true});
  160. this._redraw();
  161. };
  162. Timeline.prototype.setOptions = function (options) {
  163. // validate options
  164. let errorFound = Validator.validate(options, allOptions);
  165. if (errorFound === true) {
  166. console.log('%cErrors have been found in the supplied options object.', printStyle);
  167. }
  168. Core.prototype.setOptions.call(this, options);
  169. if ('type' in options) {
  170. if (options.type !== this.options.type) {
  171. this.options.type = options.type;
  172. // force recreation of all items
  173. var itemsData = this.itemsData;
  174. if (itemsData) {
  175. var selection = this.getSelection();
  176. this.setItems(null); // remove all
  177. this.setItems(itemsData); // add all
  178. this.setSelection(selection); // restore selection
  179. }
  180. }
  181. }
  182. };
  183. /**
  184. * Set items
  185. * @param {vis.DataSet | Array | null} items
  186. */
  187. Timeline.prototype.setItems = function(items) {
  188. // convert to type DataSet when needed
  189. var newDataSet;
  190. if (!items) {
  191. newDataSet = null;
  192. }
  193. else if (items instanceof DataSet || items instanceof DataView) {
  194. newDataSet = items;
  195. }
  196. else {
  197. // turn an array into a dataset
  198. newDataSet = new DataSet(items, {
  199. type: {
  200. start: 'Date',
  201. end: 'Date'
  202. }
  203. });
  204. }
  205. // set items
  206. this.itemsData = newDataSet;
  207. this.itemSet && this.itemSet.setItems(newDataSet);
  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;
  327. var dataset = this.itemsData && this.itemsData.getDataSet();
  328. if (dataset.length === 1 && dataset.get()[0].end === undefined) {
  329. // a single item -> don't fit, just show a range around the item from -4 to +3 days
  330. range = this.getDataRange();
  331. this.moveTo(range.min.valueOf(), {animation});
  332. }
  333. else {
  334. // exactly fit the items (plus a small margin)
  335. range = this.getItemRange();
  336. this.range.setRange(range.min, range.max, animation);
  337. }
  338. };
  339. /**
  340. * Determine the range of the items, taking into account their actual width
  341. * and a margin of 10 pixels on both sides.
  342. * @return {{min: Date | null, max: Date | null}}
  343. */
  344. Timeline.prototype.getItemRange = function () {
  345. // get a rough approximation for the range based on the items start and end dates
  346. var range = this.getDataRange();
  347. var min = range.min !== null ? range.min.valueOf() : null;
  348. var max = range.max !== null ? range.max.valueOf() : null;
  349. var minItem = null;
  350. var maxItem = null;
  351. if (min != null && max != null) {
  352. var interval = (max - min); // ms
  353. if (interval <= 0) {
  354. interval = 10;
  355. }
  356. var factor = interval / this.props.center.width;
  357. function getStart(item) {
  358. return util.convert(item.data.start, 'Date').valueOf()
  359. }
  360. function getEnd(item) {
  361. var end = item.data.end != undefined ? item.data.end : item.data.start;
  362. return util.convert(end, 'Date').valueOf();
  363. }
  364. // calculate the date of the left side and right side of the items given
  365. util.forEach(this.itemSet.items, function (item) {
  366. item.show();
  367. item.repositionX();
  368. var start = getStart(item);
  369. var end = getEnd(item);
  370. if (this.options.rtl) {
  371. var startSide = start - (item.getWidthRight() + 10) * factor;
  372. var endSide = end + (item.getWidthLeft() + 10) * factor;
  373. } else {
  374. var startSide = start - (item.getWidthLeft() + 10) * factor;
  375. var endSide = end + (item.getWidthRight() + 10) * factor;
  376. }
  377. if (startSide < min) {
  378. min = startSide;
  379. minItem = item;
  380. }
  381. if (endSide > max) {
  382. max = endSide;
  383. maxItem = item;
  384. }
  385. }.bind(this));
  386. if (minItem && maxItem) {
  387. var lhs = minItem.getWidthLeft() + 10;
  388. var rhs = maxItem.getWidthRight() + 10;
  389. var delta = this.props.center.width - lhs - rhs; // px
  390. if (delta > 0) {
  391. if (this.options.rtl) {
  392. min = getStart(minItem) - rhs * interval / delta; // ms
  393. max = getEnd(maxItem) + lhs * interval / delta; // ms
  394. } else {
  395. min = getStart(minItem) - lhs * interval / delta; // ms
  396. max = getEnd(maxItem) + rhs * interval / delta; // ms
  397. }
  398. }
  399. }
  400. }
  401. return {
  402. min: min != null ? new Date(min) : null,
  403. max: max != null ? new Date(max) : null
  404. }
  405. };
  406. /**
  407. * Calculate the data range of the items start and end dates
  408. * @returns {{min: Date | null, max: Date | null}}
  409. */
  410. Timeline.prototype.getDataRange = function() {
  411. var min = null;
  412. var max = null;
  413. var dataset = this.itemsData && this.itemsData.getDataSet();
  414. if (dataset) {
  415. dataset.forEach(function (item) {
  416. var start = util.convert(item.start, 'Date').valueOf();
  417. var end = util.convert(item.end != undefined ? item.end : item.start, 'Date').valueOf();
  418. if (min === null || start < min) {
  419. min = start;
  420. }
  421. if (max === null || end > max) {
  422. max = end;
  423. }
  424. });
  425. }
  426. return {
  427. min: min != null ? new Date(min) : null,
  428. max: max != null ? new Date(max) : null
  429. }
  430. };
  431. /**
  432. * Generate Timeline related information from an event
  433. * @param {Event} event
  434. * @return {Object} An object with related information, like on which area
  435. * The event happened, whether clicked on an item, etc.
  436. */
  437. Timeline.prototype.getEventProperties = function (event) {
  438. var clientX = event.center ? event.center.x : event.clientX;
  439. var clientY = event.center ? event.center.y : event.clientY;
  440. if (this.options.rtl) {
  441. var x = util.getAbsoluteRight(this.dom.centerContainer) - clientX;
  442. } else {
  443. var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
  444. }
  445. var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
  446. var item = this.itemSet.itemFromTarget(event);
  447. var group = this.itemSet.groupFromTarget(event);
  448. var customTime = CustomTime.customTimeFromTarget(event);
  449. var snap = this.itemSet.options.snap || null;
  450. var scale = this.body.util.getScale();
  451. var step = this.body.util.getStep();
  452. var time = this._toTime(x);
  453. var snappedTime = snap ? snap(time, scale, step) : time;
  454. var element = util.getTarget(event);
  455. var what = null;
  456. if (item != null) {what = 'item';}
  457. else if (customTime != null) {what = 'custom-time';}
  458. else if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
  459. else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
  460. else if (util.hasParent(element, this.itemSet.dom.labelSet)) {what = 'group-label';}
  461. else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
  462. else if (util.hasParent(element, this.dom.center)) {what = 'background';}
  463. return {
  464. event: event,
  465. item: item ? item.id : null,
  466. group: group ? group.groupId : null,
  467. what: what,
  468. pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
  469. pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
  470. x: x,
  471. y: y,
  472. time: time,
  473. snappedTime: snappedTime
  474. }
  475. };
  476. module.exports = Timeline;