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.

565 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. 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 && 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. if (item.groupShowing) {
  382. item.show();
  383. item.repositionX();
  384. }
  385. var start = getStart(item);
  386. var end = getEnd(item);
  387. if (this.options.rtl) {
  388. var startSide = start - (item.getWidthRight() + 10) * factor;
  389. var endSide = end + (item.getWidthLeft() + 10) * factor;
  390. } else {
  391. var startSide = start - (item.getWidthLeft() + 10) * factor;
  392. var endSide = end + (item.getWidthRight() + 10) * factor;
  393. }
  394. if (startSide < min) {
  395. min = startSide;
  396. minItem = item;
  397. }
  398. if (endSide > max) {
  399. max = endSide;
  400. maxItem = item;
  401. }
  402. }.bind(this));
  403. if (minItem && maxItem) {
  404. var lhs = minItem.getWidthLeft() + 10;
  405. var rhs = maxItem.getWidthRight() + 10;
  406. var delta = this.props.center.width - lhs - rhs; // px
  407. if (delta > 0) {
  408. if (this.options.rtl) {
  409. min = getStart(minItem) - rhs * interval / delta; // ms
  410. max = getEnd(maxItem) + lhs * interval / delta; // ms
  411. } else {
  412. min = getStart(minItem) - lhs * interval / delta; // ms
  413. max = getEnd(maxItem) + rhs * interval / delta; // ms
  414. }
  415. }
  416. }
  417. }
  418. return {
  419. min: min != null ? new Date(min) : null,
  420. max: max != null ? new Date(max) : null
  421. }
  422. };
  423. /**
  424. * Calculate the data range of the items start and end dates
  425. * @returns {{min: Date | null, max: Date | null}}
  426. */
  427. Timeline.prototype.getDataRange = function() {
  428. var min = null;
  429. var max = null;
  430. var dataset = this.itemsData && this.itemsData.getDataSet();
  431. if (dataset) {
  432. dataset.forEach(function (item) {
  433. var start = util.convert(item.start, 'Date').valueOf();
  434. var end = util.convert(item.end != undefined ? item.end : item.start, 'Date').valueOf();
  435. if (min === null || start < min) {
  436. min = start;
  437. }
  438. if (max === null || end > max) {
  439. max = end;
  440. }
  441. });
  442. }
  443. return {
  444. min: min != null ? new Date(min) : null,
  445. max: max != null ? new Date(max) : null
  446. }
  447. };
  448. /**
  449. * Generate Timeline related information from an event
  450. * @param {Event} event
  451. * @return {Object} An object with related information, like on which area
  452. * The event happened, whether clicked on an item, etc.
  453. */
  454. Timeline.prototype.getEventProperties = function (event) {
  455. var clientX = event.center ? event.center.x : event.clientX;
  456. var clientY = event.center ? event.center.y : event.clientY;
  457. if (this.options.rtl) {
  458. var x = util.getAbsoluteRight(this.dom.centerContainer) - clientX;
  459. } else {
  460. var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
  461. }
  462. var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
  463. var item = this.itemSet.itemFromTarget(event);
  464. var group = this.itemSet.groupFromTarget(event);
  465. var customTime = CustomTime.customTimeFromTarget(event);
  466. var snap = this.itemSet.options.snap || null;
  467. var scale = this.body.util.getScale();
  468. var step = this.body.util.getStep();
  469. var time = this._toTime(x);
  470. var snappedTime = snap ? snap(time, scale, step) : time;
  471. var element = util.getTarget(event);
  472. var what = null;
  473. if (item != null) {what = 'item';}
  474. else if (customTime != null) {what = 'custom-time';}
  475. else if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
  476. else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
  477. else if (util.hasParent(element, this.itemSet.dom.labelSet)) {what = 'group-label';}
  478. else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
  479. else if (util.hasParent(element, this.dom.center)) {what = 'background';}
  480. return {
  481. event: event,
  482. item: item ? item.id : null,
  483. group: group ? group.groupId : null,
  484. what: what,
  485. pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
  486. pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
  487. x: x,
  488. y: y,
  489. time: time,
  490. snappedTime: snappedTime
  491. }
  492. };
  493. module.exports = Timeline;