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.

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