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.

564 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 {
  227. var filter = {
  228. filter : function(group){
  229. return group.visible !== false;
  230. }
  231. }
  232. if (groups instanceof DataSet || groups instanceof DataView) {
  233. newDataSet = new DataView(groups,filter);
  234. }
  235. else {
  236. // turn an array into a dataset
  237. newDataSet = new DataSet(groups.filter(filter));
  238. }
  239. }
  240. this.groupsData = newDataSet;
  241. this.itemSet.setGroups(newDataSet);
  242. };
  243. /**
  244. * Set both items and groups in one go
  245. * @param {{items: Array | vis.DataSet, groups: Array | vis.DataSet}} data
  246. */
  247. Timeline.prototype.setData = function (data) {
  248. if (data && data.groups) {
  249. this.setGroups(data.groups);
  250. }
  251. if (data && data.items) {
  252. this.setItems(data.items);
  253. }
  254. };
  255. /**
  256. * Set selected items by their id. Replaces the current selection
  257. * Unknown id's are silently ignored.
  258. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  259. * selected. If ids is an empty array, all items will be
  260. * unselected.
  261. * @param {Object} [options] Available options:
  262. * `focus: boolean`
  263. * If true, focus will be set to the selected item(s)
  264. * `animation: boolean | {duration: number, easingFunction: string}`
  265. * If true (default), the range is animated
  266. * smoothly to the new window. An object can be
  267. * provided to specify duration and easing function.
  268. * Default duration is 500 ms, and default easing
  269. * function is 'easeInOutQuad'.
  270. * Only applicable when option focus is true.
  271. */
  272. Timeline.prototype.setSelection = function(ids, options) {
  273. this.itemSet && this.itemSet.setSelection(ids);
  274. if (options && options.focus) {
  275. this.focus(ids, options);
  276. }
  277. };
  278. /**
  279. * Get the selected items by their id
  280. * @return {Array} ids The ids of the selected items
  281. */
  282. Timeline.prototype.getSelection = function() {
  283. return this.itemSet && this.itemSet.getSelection() || [];
  284. };
  285. /**
  286. * Adjust the visible window such that the selected item (or multiple items)
  287. * are centered on screen.
  288. * @param {String | String[]} id An item id or array with item ids
  289. * @param {Object} [options] Available options:
  290. * `animation: boolean | {duration: number, easingFunction: string}`
  291. * If true (default), the range is animated
  292. * smoothly to the new window. An object can be
  293. * provided to specify duration and easing function.
  294. * Default duration is 500 ms, and default easing
  295. * function is 'easeInOutQuad'.
  296. */
  297. Timeline.prototype.focus = function(id, options) {
  298. if (!this.itemsData || id == undefined) return;
  299. var ids = Array.isArray(id) ? id : [id];
  300. // get the specified item(s)
  301. var itemsData = this.itemsData.getDataSet().get(ids, {
  302. type: {
  303. start: 'Date',
  304. end: 'Date'
  305. }
  306. });
  307. // calculate minimum start and maximum end of specified items
  308. var start = null;
  309. var end = null;
  310. itemsData.forEach(function (itemData) {
  311. var s = itemData.start.valueOf();
  312. var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf();
  313. if (start === null || s < start) {
  314. start = s;
  315. }
  316. if (end === null || e > end) {
  317. end = e;
  318. }
  319. });
  320. if (start !== null && end !== null) {
  321. // calculate the new middle and interval for the window
  322. var middle = (start + end) / 2;
  323. var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1);
  324. var animation = (options && options.animation !== undefined) ? options.animation : true;
  325. this.range.setRange(middle - interval / 2, middle + interval / 2, animation);
  326. }
  327. };
  328. /**
  329. * Set Timeline window such that it fits all items
  330. * @param {Object} [options] Available options:
  331. * `animation: boolean | {duration: number, easingFunction: string}`
  332. * If true (default), the range is animated
  333. * smoothly to the new window. An object can be
  334. * provided to specify duration and easing function.
  335. * Default duration is 500 ms, and default easing
  336. * function is 'easeInOutQuad'.
  337. */
  338. Timeline.prototype.fit = function (options) {
  339. var animation = (options && options.animation !== undefined) ? options.animation : true;
  340. var range;
  341. var dataset = this.itemsData && this.itemsData.getDataSet();
  342. if (dataset.length === 1 && dataset.get()[0].end === undefined) {
  343. // a single item -> don't fit, just show a range around the item from -4 to +3 days
  344. range = this.getDataRange();
  345. this.moveTo(range.min.valueOf(), {animation});
  346. }
  347. else {
  348. // exactly fit the items (plus a small margin)
  349. range = this.getItemRange();
  350. this.range.setRange(range.min, range.max, animation);
  351. }
  352. };
  353. /**
  354. * Determine the range of the items, taking into account their actual width
  355. * and a margin of 10 pixels on both sides.
  356. * @return {{min: Date | null, max: Date | null}}
  357. */
  358. Timeline.prototype.getItemRange = function () {
  359. // get a rough approximation for the range based on the items start and end dates
  360. var range = this.getDataRange();
  361. var min = range.min !== null ? range.min.valueOf() : null;
  362. var max = range.max !== null ? range.max.valueOf() : null;
  363. var minItem = null;
  364. var maxItem = null;
  365. if (min != null && max != null) {
  366. var interval = (max - min); // ms
  367. if (interval <= 0) {
  368. interval = 10;
  369. }
  370. var factor = interval / this.props.center.width;
  371. function getStart(item) {
  372. return util.convert(item.data.start, 'Date').valueOf()
  373. }
  374. function getEnd(item) {
  375. var end = item.data.end != undefined ? item.data.end : item.data.start;
  376. return util.convert(end, 'Date').valueOf();
  377. }
  378. // calculate the date of the left side and right side of the items given
  379. util.forEach(this.itemSet.items, function (item) {
  380. item.show();
  381. item.repositionX();
  382. var start = getStart(item);
  383. var end = getEnd(item);
  384. if (this.options.rtl) {
  385. var startSide = start - (item.getWidthRight() + 10) * factor;
  386. var endSide = end + (item.getWidthLeft() + 10) * factor;
  387. } else {
  388. var startSide = start - (item.getWidthLeft() + 10) * factor;
  389. var endSide = end + (item.getWidthRight() + 10) * factor;
  390. }
  391. if (startSide < min) {
  392. min = startSide;
  393. minItem = item;
  394. }
  395. if (endSide > max) {
  396. max = endSide;
  397. maxItem = item;
  398. }
  399. }.bind(this));
  400. if (minItem && maxItem) {
  401. var lhs = minItem.getWidthLeft() + 10;
  402. var rhs = maxItem.getWidthRight() + 10;
  403. var delta = this.props.center.width - lhs - rhs; // px
  404. if (delta > 0) {
  405. if (this.options.rtl) {
  406. min = getStart(minItem) - rhs * interval / delta; // ms
  407. max = getEnd(maxItem) + lhs * interval / delta; // ms
  408. } else {
  409. min = getStart(minItem) - lhs * interval / delta; // ms
  410. max = getEnd(maxItem) + rhs * interval / delta; // ms
  411. }
  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. * Calculate the data range of the items start and end dates
  422. * @returns {{min: Date | null, max: Date | null}}
  423. */
  424. Timeline.prototype.getDataRange = function() {
  425. var min = null;
  426. var max = null;
  427. var dataset = this.itemsData && this.itemsData.getDataSet();
  428. if (dataset) {
  429. dataset.forEach(function (item) {
  430. var start = util.convert(item.start, 'Date').valueOf();
  431. var end = util.convert(item.end != undefined ? item.end : item.start, 'Date').valueOf();
  432. if (min === null || start < min) {
  433. min = start;
  434. }
  435. if (max === null || end > max) {
  436. max = end;
  437. }
  438. });
  439. }
  440. return {
  441. min: min != null ? new Date(min) : null,
  442. max: max != null ? new Date(max) : null
  443. }
  444. };
  445. /**
  446. * Generate Timeline related information from an event
  447. * @param {Event} event
  448. * @return {Object} An object with related information, like on which area
  449. * The event happened, whether clicked on an item, etc.
  450. */
  451. Timeline.prototype.getEventProperties = function (event) {
  452. var clientX = event.center ? event.center.x : event.clientX;
  453. var clientY = event.center ? event.center.y : event.clientY;
  454. if (this.options.rtl) {
  455. var x = util.getAbsoluteRight(this.dom.centerContainer) - clientX;
  456. } else {
  457. var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
  458. }
  459. var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
  460. var item = this.itemSet.itemFromTarget(event);
  461. var group = this.itemSet.groupFromTarget(event);
  462. var customTime = CustomTime.customTimeFromTarget(event);
  463. var snap = this.itemSet.options.snap || null;
  464. var scale = this.body.util.getScale();
  465. var step = this.body.util.getStep();
  466. var time = this._toTime(x);
  467. var snappedTime = snap ? snap(time, scale, step) : time;
  468. var element = util.getTarget(event);
  469. var what = null;
  470. if (item != null) {what = 'item';}
  471. else if (customTime != null) {what = 'custom-time';}
  472. else if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
  473. else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
  474. else if (util.hasParent(element, this.itemSet.dom.labelSet)) {what = 'group-label';}
  475. else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
  476. else if (util.hasParent(element, this.dom.center)) {what = 'background';}
  477. return {
  478. event: event,
  479. item: item ? item.id : null,
  480. group: group ? group.groupId : null,
  481. what: what,
  482. pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
  483. pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
  484. x: x,
  485. y: y,
  486. time: time,
  487. snappedTime: snappedTime
  488. }
  489. };
  490. module.exports = Timeline;