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.

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