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.

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