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.

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