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.

620 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. /**
  380. *
  381. * @param {vis.Item} item
  382. * @returns {Number}
  383. */
  384. function getStart(item) {
  385. return util.convert(item.data.start, 'Date').valueOf()
  386. }
  387. /**
  388. *
  389. * @param {vis.Item} item
  390. * @returns {Number}
  391. */
  392. function getEnd(item) {
  393. var end = item.data.end != undefined ? item.data.end : item.data.start;
  394. return util.convert(end, 'Date').valueOf();
  395. }
  396. /**
  397. * Determine the range of the items, taking into account their actual width
  398. * and a margin of 10 pixels on both sides.
  399. * @return {{min: Date | null, max: Date | null}}
  400. */
  401. Timeline.prototype.getItemRange = function () {
  402. // get a rough approximation for the range based on the items start and end dates
  403. var range = this.getDataRange();
  404. var min = range.min !== null ? range.min.valueOf() : null;
  405. var max = range.max !== null ? range.max.valueOf() : null;
  406. var minItem = null;
  407. var maxItem = null;
  408. if (min != null && max != null) {
  409. var interval = (max - min); // ms
  410. if (interval <= 0) {
  411. interval = 10;
  412. }
  413. var factor = interval / this.props.center.width;
  414. // calculate the date of the left side and right side of the items given
  415. util.forEach(this.itemSet.items, function (item) {
  416. if (item.groupShowing) {
  417. item.show();
  418. item.repositionX();
  419. }
  420. var start = getStart(item);
  421. var end = getEnd(item);
  422. var startSide;
  423. var endSide;
  424. if (this.options.rtl) {
  425. startSide = start - (item.getWidthRight() + 10) * factor;
  426. endSide = end + (item.getWidthLeft() + 10) * factor;
  427. } else {
  428. startSide = start - (item.getWidthLeft() + 10) * factor;
  429. endSide = end + (item.getWidthRight() + 10) * factor;
  430. }
  431. if (startSide < min) {
  432. min = startSide;
  433. minItem = item;
  434. }
  435. if (endSide > max) {
  436. max = endSide;
  437. maxItem = item;
  438. }
  439. }.bind(this));
  440. if (minItem && maxItem) {
  441. var lhs = minItem.getWidthLeft() + 10;
  442. var rhs = maxItem.getWidthRight() + 10;
  443. var delta = this.props.center.width - lhs - rhs; // px
  444. if (delta > 0) {
  445. if (this.options.rtl) {
  446. min = getStart(minItem) - rhs * interval / delta; // ms
  447. max = getEnd(maxItem) + lhs * interval / delta; // ms
  448. } else {
  449. min = getStart(minItem) - lhs * interval / delta; // ms
  450. max = getEnd(maxItem) + rhs * interval / delta; // ms
  451. }
  452. }
  453. }
  454. }
  455. return {
  456. min: min != null ? new Date(min) : null,
  457. max: max != null ? new Date(max) : null
  458. }
  459. };
  460. /**
  461. * Calculate the data range of the items start and end dates
  462. * @returns {{min: Date | null, max: Date | null}}
  463. */
  464. Timeline.prototype.getDataRange = function() {
  465. var min = null;
  466. var max = null;
  467. var dataset = this.itemsData && this.itemsData.getDataSet();
  468. if (dataset) {
  469. dataset.forEach(function (item) {
  470. var start = util.convert(item.start, 'Date').valueOf();
  471. var end = util.convert(item.end != undefined ? item.end : item.start, 'Date').valueOf();
  472. if (min === null || start < min) {
  473. min = start;
  474. }
  475. if (max === null || end > max) {
  476. max = end;
  477. }
  478. });
  479. }
  480. return {
  481. min: min != null ? new Date(min) : null,
  482. max: max != null ? new Date(max) : null
  483. }
  484. };
  485. /**
  486. * Generate Timeline related information from an event
  487. * @param {Event} event
  488. * @return {Object} An object with related information, like on which area
  489. * The event happened, whether clicked on an item, etc.
  490. */
  491. Timeline.prototype.getEventProperties = function (event) {
  492. var clientX = event.center ? event.center.x : event.clientX;
  493. var clientY = event.center ? event.center.y : event.clientY;
  494. var x;
  495. if (this.options.rtl) {
  496. x = util.getAbsoluteRight(this.dom.centerContainer) - clientX;
  497. } else {
  498. x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
  499. }
  500. var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
  501. var item = this.itemSet.itemFromTarget(event);
  502. var group = this.itemSet.groupFromTarget(event);
  503. var customTime = CustomTime.customTimeFromTarget(event);
  504. var snap = this.itemSet.options.snap || null;
  505. var scale = this.body.util.getScale();
  506. var step = this.body.util.getStep();
  507. var time = this._toTime(x);
  508. var snappedTime = snap ? snap(time, scale, step) : time;
  509. var element = util.getTarget(event);
  510. var what = null;
  511. if (item != null) {what = 'item';}
  512. else if (customTime != null) {what = 'custom-time';}
  513. else if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
  514. else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
  515. else if (util.hasParent(element, this.itemSet.dom.labelSet)) {what = 'group-label';}
  516. else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
  517. else if (util.hasParent(element, this.dom.center)) {what = 'background';}
  518. return {
  519. event: event,
  520. item: item ? item.id : null,
  521. group: group ? group.groupId : null,
  522. what: what,
  523. pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
  524. pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
  525. x: x,
  526. y: y,
  527. time: time,
  528. snappedTime: snappedTime
  529. }
  530. };
  531. /**
  532. * Toggle Timeline rolling mode
  533. */
  534. Timeline.prototype.toggleRollingMode = function () {
  535. if (this.range.rolling) {
  536. this.range.stopRolling();
  537. } else {
  538. if (this.options.rollingMode == undefined) {
  539. this.setOptions(this.options)
  540. }
  541. this.range.startRolling();
  542. }
  543. }
  544. module.exports = Timeline;