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.

549 lines
17 KiB

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