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.

432 lines
13 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 util = require('../util');
  4. var DataSet = require('../DataSet');
  5. var DataView = require('../DataView');
  6. var Range = require('./Range');
  7. var Core = require('./Core');
  8. var TimeAxis = require('./component/TimeAxis');
  9. var CurrentTime = require('./component/CurrentTime');
  10. var CustomTime = require('./component/CustomTime');
  11. var ItemSet = require('./component/ItemSet');
  12. var ConfigurationSystem = require('../network/modules/ConfigurationSystem');
  13. var Validator = require('../network/modules/Validator').default;
  14. var printStyle = require('../network/modules/Validator').printStyle;
  15. var allOptions = require('./options').allOptions;
  16. var configureOptions = require('./options').configureOptions;
  17. /**
  18. * Create a timeline visualization
  19. * @param {HTMLElement} container
  20. * @param {vis.DataSet | vis.DataView | Array} [items]
  21. * @param {vis.DataSet | vis.DataView | Array} [groups]
  22. * @param {Object} [options] See Timeline.setOptions for the available options.
  23. * @constructor
  24. * @extends Core
  25. */
  26. function Timeline (container, items, groups, options) {
  27. if (!(this instanceof Timeline)) {
  28. throw new SyntaxError('Constructor must be called with the new operator');
  29. }
  30. // if the third element is options, the forth is groups (optionally);
  31. if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) {
  32. var forthArgument = options;
  33. options = groups;
  34. groups = forthArgument;
  35. }
  36. var me = this;
  37. this.defaultOptions = {
  38. start: null,
  39. end: null,
  40. autoResize: true,
  41. orientation: {
  42. axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both'
  43. item: 'bottom' // not relevant
  44. },
  45. width: null,
  46. height: null,
  47. maxHeight: null,
  48. minHeight: null
  49. };
  50. this.options = util.deepExtend({}, this.defaultOptions);
  51. // Create the DOM, props, and emitter
  52. this._create(container);
  53. // all components listed here will be repainted automatically
  54. this.components = [];
  55. this.body = {
  56. dom: this.dom,
  57. domProps: this.props,
  58. emitter: {
  59. on: this.on.bind(this),
  60. off: this.off.bind(this),
  61. emit: this.emit.bind(this)
  62. },
  63. hiddenDates: [],
  64. util: {
  65. getScale: function () {
  66. return me.timeAxis.step.scale;
  67. },
  68. getStep: function () {
  69. return me.timeAxis.step.step;
  70. },
  71. toScreen: me._toScreen.bind(me),
  72. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  73. toTime: me._toTime.bind(me),
  74. toGlobalTime : me._toGlobalTime.bind(me)
  75. }
  76. };
  77. // range
  78. this.range = new Range(this.body);
  79. this.components.push(this.range);
  80. this.body.range = this.range;
  81. // time axis
  82. this.timeAxis = new TimeAxis(this.body);
  83. this.timeAxis2 = null; // used in case of orientation option 'both'
  84. this.components.push(this.timeAxis);
  85. // current time bar
  86. this.currentTime = new CurrentTime(this.body);
  87. this.components.push(this.currentTime);
  88. // item set
  89. this.itemSet = new ItemSet(this.body);
  90. this.components.push(this.itemSet);
  91. this.itemsData = null; // DataSet
  92. this.groupsData = null; // DataSet
  93. this.on('tap', function (event) {
  94. me.emit('click', me.getEventProperties(event))
  95. });
  96. this.on('doubletap', function (event) {
  97. me.emit('doubleClick', me.getEventProperties(event))
  98. });
  99. this.dom.root.oncontextmenu = function (event) {
  100. me.emit('contextmenu', me.getEventProperties(event))
  101. };
  102. // setup configuration system
  103. this.configurationSystem = new ConfigurationSystem(this, container, configureOptions);
  104. // apply options
  105. if (options) {
  106. this.setOptions(options);
  107. }
  108. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  109. if (groups) {
  110. this.setGroups(groups);
  111. }
  112. // create itemset
  113. if (items) {
  114. this.setItems(items);
  115. }
  116. else {
  117. this._redraw();
  118. }
  119. }
  120. // Extend the functionality from Core
  121. Timeline.prototype = new Core();
  122. /**
  123. * Force a redraw. The size of all items will be recalculated.
  124. * Can be useful to manually redraw when option autoResize=false and the window
  125. * has been resized, or when the items CSS has been changed.
  126. */
  127. Timeline.prototype.redraw = function() {
  128. this.itemSet && this.itemSet.markDirty({refreshItems: true});
  129. this._redraw();
  130. };
  131. Timeline.prototype.setOptions = function (options) {
  132. // validate options
  133. let errorFound = Validator.validate(options, allOptions);
  134. if (errorFound === true) {
  135. options = {};
  136. console.log('%cErrors have been found in the supplied options object. None of the options will be used.', printStyle);
  137. }
  138. Core.prototype.setOptions.call(this, options);
  139. if ('type' in options) {
  140. if (options.type !== this.options.type) {
  141. this.options.type = options.type;
  142. // force recreation of all items
  143. var itemsData = this.itemsData;
  144. if (itemsData) {
  145. this.setItems(null); // remove all
  146. this.setItems(itemsData); // add all
  147. }
  148. }
  149. }
  150. };
  151. /**
  152. * Set items
  153. * @param {vis.DataSet | Array | null} items
  154. */
  155. Timeline.prototype.setItems = function(items) {
  156. var initialLoad = (this.itemsData == null);
  157. // convert to type DataSet when needed
  158. var newDataSet;
  159. if (!items) {
  160. newDataSet = null;
  161. }
  162. else if (items instanceof DataSet || items instanceof DataView) {
  163. newDataSet = items;
  164. }
  165. else {
  166. // turn an array into a dataset
  167. newDataSet = new DataSet(items, {
  168. type: {
  169. start: 'Date',
  170. end: 'Date'
  171. }
  172. });
  173. }
  174. // set items
  175. this.itemsData = newDataSet;
  176. this.itemSet && this.itemSet.setItems(newDataSet);
  177. if (initialLoad) {
  178. if (this.options.start != undefined || this.options.end != undefined) {
  179. if (this.options.start == undefined || this.options.end == undefined) {
  180. var dataRange = this._getDataRange();
  181. }
  182. var start = this.options.start != undefined ? this.options.start : dataRange.start;
  183. var end = this.options.end != undefined ? this.options.end : dataRange.end;
  184. this.setWindow(start, end, {animation: false});
  185. }
  186. else {
  187. this.fit({animation: false});
  188. }
  189. }
  190. };
  191. /**
  192. * Set groups
  193. * @param {vis.DataSet | Array} groups
  194. */
  195. Timeline.prototype.setGroups = function(groups) {
  196. // convert to type DataSet when needed
  197. var newDataSet;
  198. if (!groups) {
  199. newDataSet = null;
  200. }
  201. else if (groups instanceof DataSet || groups instanceof DataView) {
  202. newDataSet = groups;
  203. }
  204. else {
  205. // turn an array into a dataset
  206. newDataSet = new DataSet(groups);
  207. }
  208. this.groupsData = newDataSet;
  209. this.itemSet.setGroups(newDataSet);
  210. };
  211. /**
  212. * Set both items and groups in one go
  213. * @param {{items: Array | vis.DataSet, groups: Array | vis.DataSet}} data
  214. */
  215. Timeline.prototype.setData = function (data) {
  216. if (data && data.groups) {
  217. this.setGroups(data.groups);
  218. }
  219. if (data && data.items) {
  220. this.setItems(data.items);
  221. }
  222. };
  223. /**
  224. * Set selected items by their id. Replaces the current selection
  225. * Unknown id's are silently ignored.
  226. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  227. * selected. If ids is an empty array, all items will be
  228. * unselected.
  229. * @param {Object} [options] Available options:
  230. * `focus: boolean`
  231. * If true, focus will be set to the selected item(s)
  232. * `animation: boolean | {duration: number, easingFunction: string}`
  233. * If true (default), the range is animated
  234. * smoothly to the new window. An object can be
  235. * provided to specify duration and easing function.
  236. * Default duration is 500 ms, and default easing
  237. * function is 'easeInOutQuad'.
  238. * Only applicable when option focus is true.
  239. */
  240. Timeline.prototype.setSelection = function(ids, options) {
  241. this.itemSet && this.itemSet.setSelection(ids);
  242. if (options && options.focus) {
  243. this.focus(ids, options);
  244. }
  245. };
  246. /**
  247. * Get the selected items by their id
  248. * @return {Array} ids The ids of the selected items
  249. */
  250. Timeline.prototype.getSelection = function() {
  251. return this.itemSet && this.itemSet.getSelection() || [];
  252. };
  253. /**
  254. * Adjust the visible window such that the selected item (or multiple items)
  255. * are centered on screen.
  256. * @param {String | String[]} id An item id or array with item ids
  257. * @param {Object} [options] Available options:
  258. * `animation: boolean | {duration: number, easingFunction: string}`
  259. * If true (default), the range is animated
  260. * smoothly to the new window. An object can be
  261. * provided to specify duration and easing function.
  262. * Default duration is 500 ms, and default easing
  263. * function is 'easeInOutQuad'.
  264. */
  265. Timeline.prototype.focus = function(id, options) {
  266. if (!this.itemsData || id == undefined) return;
  267. var ids = Array.isArray(id) ? id : [id];
  268. // get the specified item(s)
  269. var itemsData = this.itemsData.getDataSet().get(ids, {
  270. type: {
  271. start: 'Date',
  272. end: 'Date'
  273. }
  274. });
  275. // calculate minimum start and maximum end of specified items
  276. var start = null;
  277. var end = null;
  278. itemsData.forEach(function (itemData) {
  279. var s = itemData.start.valueOf();
  280. var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf();
  281. if (start === null || s < start) {
  282. start = s;
  283. }
  284. if (end === null || e > end) {
  285. end = e;
  286. }
  287. });
  288. if (start !== null && end !== null) {
  289. // calculate the new middle and interval for the window
  290. var middle = (start + end) / 2;
  291. var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1);
  292. var animation = (options && options.animation !== undefined) ? options.animation : true;
  293. this.range.setRange(middle - interval / 2, middle + interval / 2, animation);
  294. }
  295. };
  296. /**
  297. * Get the data range of the item set.
  298. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  299. * When no minimum is found, min==null
  300. * When no maximum is found, max==null
  301. */
  302. Timeline.prototype.getItemRange = function() {
  303. // calculate min from start filed
  304. var dataset = this.itemsData && this.itemsData.getDataSet();
  305. var min = null;
  306. var max = null;
  307. if (dataset) {
  308. // calculate the minimum value of the field 'start'
  309. var minItem = dataset.min('start');
  310. min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null;
  311. // Note: we convert first to Date and then to number because else
  312. // a conversion from ISODate to Number will fail
  313. // calculate maximum value of fields 'start' and 'end'
  314. var maxStartItem = dataset.max('start');
  315. if (maxStartItem) {
  316. max = util.convert(maxStartItem.start, 'Date').valueOf();
  317. }
  318. var maxEndItem = dataset.max('end');
  319. if (maxEndItem) {
  320. if (max == null) {
  321. max = util.convert(maxEndItem.end, 'Date').valueOf();
  322. }
  323. else {
  324. max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf());
  325. }
  326. }
  327. }
  328. return {
  329. min: (min != null) ? new Date(min) : null,
  330. max: (max != null) ? new Date(max) : null
  331. };
  332. };
  333. /**
  334. * Generate Timeline related information from an event
  335. * @param {Event} event
  336. * @return {Object} An object with related information, like on which area
  337. * The event happened, whether clicked on an item, etc.
  338. */
  339. Timeline.prototype.getEventProperties = function (event) {
  340. var pageX = event.center ? event.center.x : event.pageX;
  341. var pageY = event.center ? event.center.y : event.pageY;
  342. var x = pageX - util.getAbsoluteLeft(this.dom.centerContainer);
  343. var y = pageY - util.getAbsoluteTop(this.dom.centerContainer);
  344. var item = this.itemSet.itemFromTarget(event);
  345. var group = this.itemSet.groupFromTarget(event);
  346. var customTime = CustomTime.customTimeFromTarget(event);
  347. var snap = this.itemSet.options.snap || null;
  348. var scale = this.body.util.getScale();
  349. var step = this.body.util.getStep();
  350. var time = this._toTime(x);
  351. var snappedTime = snap ? snap(time, scale, step) : time;
  352. var element = util.getTarget(event);
  353. var what = null;
  354. if (item != null) {what = 'item';}
  355. else if (customTime != null) {what = 'custom-time';}
  356. else if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
  357. else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
  358. else if (util.hasParent(element, this.itemSet.dom.labelSet)) {what = 'group-label';}
  359. else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
  360. else if (util.hasParent(element, this.dom.center)) {what = 'background';}
  361. return {
  362. event: event,
  363. item: item ? item.id : null,
  364. group: group ? group.groupId : null,
  365. what: what,
  366. pageX: pageX,
  367. pageY: pageY,
  368. x: x,
  369. y: y,
  370. time: time,
  371. snappedTime: snappedTime
  372. }
  373. };
  374. module.exports = Timeline;