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.

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