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.

539 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 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. throttleRedraw: 0, // ms
  43. orientation: {
  44. axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both'
  45. item: 'bottom' // not relevant
  46. },
  47. rtl: false,
  48. moment: moment,
  49. width: null,
  50. height: null,
  51. maxHeight: null,
  52. minHeight: null
  53. };
  54. this.options = util.deepExtend({}, this.defaultOptions);
  55. // Create the DOM, props, and emitter
  56. this._create(container);
  57. // all components listed here will be repainted automatically
  58. this.components = [];
  59. this.body = {
  60. dom: this.dom,
  61. domProps: this.props,
  62. emitter: {
  63. on: this.on.bind(this),
  64. off: this.off.bind(this),
  65. emit: this.emit.bind(this)
  66. },
  67. hiddenDates: [],
  68. util: {
  69. getScale: function () {
  70. return me.timeAxis.step.scale;
  71. },
  72. getStep: function () {
  73. return me.timeAxis.step.step;
  74. },
  75. toScreen: me._toScreen.bind(me),
  76. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  77. toTime: me._toTime.bind(me),
  78. toGlobalTime : me._toGlobalTime.bind(me)
  79. }
  80. };
  81. // range
  82. this.range = new Range(this.body);
  83. this.components.push(this.range);
  84. this.body.range = this.range;
  85. // time axis
  86. this.timeAxis = new TimeAxis(this.body);
  87. this.timeAxis2 = null; // used in case of orientation option 'both'
  88. this.components.push(this.timeAxis);
  89. // current time bar
  90. this.currentTime = new CurrentTime(this.body);
  91. this.components.push(this.currentTime);
  92. // item set
  93. this.itemSet = new ItemSet(this.body, this.options);
  94. this.components.push(this.itemSet);
  95. this.itemsData = null; // DataSet
  96. this.groupsData = null; // DataSet
  97. this.on('tap', function (event) {
  98. me.emit('click', me.getEventProperties(event))
  99. });
  100. this.on('doubletap', function (event) {
  101. me.emit('doubleClick', me.getEventProperties(event))
  102. });
  103. this.dom.root.oncontextmenu = function (event) {
  104. me.emit('contextmenu', me.getEventProperties(event))
  105. };
  106. //Single time autoscale/fit
  107. this.fitDone = false;
  108. this.on('changed', function (){
  109. if (this.itemsData == null) return;
  110. if (!me.fitDone) {
  111. me.fitDone = true;
  112. if (me.options.start != undefined || me.options.end != undefined) {
  113. if (me.options.start == undefined || me.options.end == undefined) {
  114. var range = me.getItemRange();
  115. }
  116. var start = me.options.start != undefined ? me.options.start : range.min;
  117. var end = me.options.end != undefined ? me.options.end : range.max;
  118. me.setWindow(start, end, {animation: false});
  119. }
  120. else {
  121. me.fit({animation: false});
  122. }
  123. }
  124. });
  125. // apply options
  126. if (options) {
  127. this.setOptions(options);
  128. }
  129. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  130. if (groups) {
  131. this.setGroups(groups);
  132. }
  133. // create itemset
  134. if (items) {
  135. this.setItems(items);
  136. }
  137. // draw for the first time
  138. this._redraw();
  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. };
  208. /**
  209. * Set groups
  210. * @param {vis.DataSet | Array} groups
  211. */
  212. Timeline.prototype.setGroups = function(groups) {
  213. // convert to type DataSet when needed
  214. var newDataSet;
  215. if (!groups) {
  216. newDataSet = null;
  217. }
  218. else if (groups instanceof DataSet || groups instanceof DataView) {
  219. newDataSet = groups;
  220. }
  221. else {
  222. // turn an array into a dataset
  223. newDataSet = new DataSet(groups);
  224. }
  225. this.groupsData = newDataSet;
  226. this.itemSet.setGroups(newDataSet);
  227. };
  228. /**
  229. * Set both items and groups in one go
  230. * @param {{items: Array | vis.DataSet, groups: Array | vis.DataSet}} data
  231. */
  232. Timeline.prototype.setData = function (data) {
  233. if (data && data.groups) {
  234. this.setGroups(data.groups);
  235. }
  236. if (data && data.items) {
  237. this.setItems(data.items);
  238. }
  239. };
  240. /**
  241. * Set selected items by their id. Replaces the current selection
  242. * Unknown id's are silently ignored.
  243. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  244. * selected. If ids is an empty array, all items will be
  245. * unselected.
  246. * @param {Object} [options] Available options:
  247. * `focus: boolean`
  248. * If true, focus will be set to the selected item(s)
  249. * `animation: boolean | {duration: number, easingFunction: string}`
  250. * If true (default), the range is animated
  251. * smoothly to the new window. An object can be
  252. * provided to specify duration and easing function.
  253. * Default duration is 500 ms, and default easing
  254. * function is 'easeInOutQuad'.
  255. * Only applicable when option focus is true.
  256. */
  257. Timeline.prototype.setSelection = function(ids, options) {
  258. this.itemSet && this.itemSet.setSelection(ids);
  259. if (options && options.focus) {
  260. this.focus(ids, options);
  261. }
  262. };
  263. /**
  264. * Get the selected items by their id
  265. * @return {Array} ids The ids of the selected items
  266. */
  267. Timeline.prototype.getSelection = function() {
  268. return this.itemSet && this.itemSet.getSelection() || [];
  269. };
  270. /**
  271. * Adjust the visible window such that the selected item (or multiple items)
  272. * are centered on screen.
  273. * @param {String | String[]} id An item id or array with item ids
  274. * @param {Object} [options] Available options:
  275. * `animation: boolean | {duration: number, easingFunction: string}`
  276. * If true (default), the range is animated
  277. * smoothly to the new window. An object can be
  278. * provided to specify duration and easing function.
  279. * Default duration is 500 ms, and default easing
  280. * function is 'easeInOutQuad'.
  281. */
  282. Timeline.prototype.focus = function(id, options) {
  283. if (!this.itemsData || id == undefined) return;
  284. var ids = Array.isArray(id) ? id : [id];
  285. // get the specified item(s)
  286. var itemsData = this.itemsData.getDataSet().get(ids, {
  287. type: {
  288. start: 'Date',
  289. end: 'Date'
  290. }
  291. });
  292. // calculate minimum start and maximum end of specified items
  293. var start = null;
  294. var end = null;
  295. itemsData.forEach(function (itemData) {
  296. var s = itemData.start.valueOf();
  297. var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf();
  298. if (start === null || s < start) {
  299. start = s;
  300. }
  301. if (end === null || e > end) {
  302. end = e;
  303. }
  304. });
  305. if (start !== null && end !== null) {
  306. // calculate the new middle and interval for the window
  307. var middle = (start + end) / 2;
  308. var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1);
  309. var animation = (options && options.animation !== undefined) ? options.animation : true;
  310. this.range.setRange(middle - interval / 2, middle + interval / 2, animation);
  311. }
  312. };
  313. /**
  314. * Set Timeline window such that it fits all items
  315. * @param {Object} [options] Available options:
  316. * `animation: boolean | {duration: number, easingFunction: string}`
  317. * If true (default), the range is animated
  318. * smoothly to the new window. An object can be
  319. * provided to specify duration and easing function.
  320. * Default duration is 500 ms, and default easing
  321. * function is 'easeInOutQuad'.
  322. */
  323. Timeline.prototype.fit = function (options) {
  324. var animation = (options && options.animation !== undefined) ? options.animation : true;
  325. var range = this.getItemRange();
  326. this.range.setRange(range.min, range.max, animation);
  327. };
  328. /**
  329. * Determine the range of the items, taking into account their actual width
  330. * and a margin of 10 pixels on both sides.
  331. * @return {{min: Date | null, max: Date | null}}
  332. */
  333. Timeline.prototype.getItemRange = function () {
  334. // get a rough approximation for the range based on the items start and end dates
  335. var range = this.getDataRange();
  336. var min = range.min !== null ? range.min.valueOf() : null;
  337. var max = range.max !== null ? range.max.valueOf() : null;
  338. var minItem = null;
  339. var maxItem = null;
  340. if (min != null && max != null) {
  341. var interval = (max - min); // ms
  342. if (interval <= 0) {
  343. interval = 10;
  344. }
  345. var factor = interval / this.props.center.width;
  346. function getStart(item) {
  347. return util.convert(item.data.start, 'Date').valueOf()
  348. }
  349. function getEnd(item) {
  350. var end = item.data.end != undefined ? item.data.end : item.data.start;
  351. return util.convert(end, 'Date').valueOf();
  352. }
  353. // calculate the date of the left side and right side of the items given
  354. util.forEach(this.itemSet.items, function (item) {
  355. item.show();
  356. item.repositionX();
  357. var start = getStart(item);
  358. var end = getEnd(item);
  359. if (this.options.rtl) {
  360. var startSide = start - (item.getWidthRight() + 10) * factor;
  361. var endSide = end + (item.getWidthLeft() + 10) * factor;
  362. } else {
  363. var startSide = start - (item.getWidthLeft() + 10) * factor;
  364. var endSide = end + (item.getWidthRight() + 10) * factor;
  365. }
  366. if (startSide < min) {
  367. min = startSide;
  368. minItem = item;
  369. }
  370. if (endSide > max) {
  371. max = endSide;
  372. maxItem = item;
  373. }
  374. }.bind(this));
  375. if (minItem && maxItem) {
  376. var lhs = minItem.getWidthLeft() + 10;
  377. var rhs = maxItem.getWidthRight() + 10;
  378. var delta = this.props.center.width - lhs - rhs; // px
  379. if (delta > 0) {
  380. if (this.options.rtl) {
  381. min = getStart(minItem) - rhs * interval / delta; // ms
  382. max = getEnd(maxItem) + lhs * interval / delta; // ms
  383. } else {
  384. min = getStart(minItem) - lhs * interval / delta; // ms
  385. max = getEnd(maxItem) + rhs * interval / delta; // ms
  386. }
  387. }
  388. }
  389. }
  390. return {
  391. min: min != null ? new Date(min) : null,
  392. max: max != null ? new Date(max) : null
  393. }
  394. };
  395. /**
  396. * Calculate the data range of the items start and end dates
  397. * @returns {{min: Date | null, max: Date | null}}
  398. */
  399. Timeline.prototype.getDataRange = function() {
  400. var min = null;
  401. var max = null;
  402. var dataset = this.itemsData && this.itemsData.getDataSet();
  403. if (dataset) {
  404. dataset.forEach(function (item) {
  405. var start = util.convert(item.start, 'Date').valueOf();
  406. var end = util.convert(item.end != undefined ? item.end : item.start, 'Date').valueOf();
  407. if (min === null || start < min) {
  408. min = start;
  409. }
  410. if (max === null || end > max) {
  411. max = end;
  412. }
  413. });
  414. }
  415. return {
  416. min: min != null ? new Date(min) : null,
  417. max: max != null ? new Date(max) : null
  418. }
  419. };
  420. /**
  421. * Generate Timeline related information from an event
  422. * @param {Event} event
  423. * @return {Object} An object with related information, like on which area
  424. * The event happened, whether clicked on an item, etc.
  425. */
  426. Timeline.prototype.getEventProperties = function (event) {
  427. var clientX = event.center ? event.center.x : event.clientX;
  428. var clientY = event.center ? event.center.y : event.clientY;
  429. if (this.options.rtl) {
  430. var x = util.getAbsoluteRight(this.dom.centerContainer) - clientX;
  431. } else {
  432. var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
  433. }
  434. var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
  435. var item = this.itemSet.itemFromTarget(event);
  436. var group = this.itemSet.groupFromTarget(event);
  437. var customTime = CustomTime.customTimeFromTarget(event);
  438. var snap = this.itemSet.options.snap || null;
  439. var scale = this.body.util.getScale();
  440. var step = this.body.util.getStep();
  441. var time = this._toTime(x);
  442. var snappedTime = snap ? snap(time, scale, step) : time;
  443. var element = util.getTarget(event);
  444. var what = null;
  445. if (item != null) {what = 'item';}
  446. else if (customTime != null) {what = 'custom-time';}
  447. else if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
  448. else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
  449. else if (util.hasParent(element, this.itemSet.dom.labelSet)) {what = 'group-label';}
  450. else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
  451. else if (util.hasParent(element, this.dom.center)) {what = 'background';}
  452. return {
  453. event: event,
  454. item: item ? item.id : null,
  455. group: group ? group.groupId : null,
  456. what: what,
  457. pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
  458. pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
  459. x: x,
  460. y: y,
  461. time: time,
  462. snappedTime: snappedTime
  463. }
  464. };
  465. module.exports = Timeline;