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.

431 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('../shared/ConfigurationSystem');
  13. var Validator = require('../shared/Validator').default;
  14. var printStyle = require('../shared/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. console.log('%cErrors have been found in the supplied options object.', printStyle);
  136. }
  137. Core.prototype.setOptions.call(this, options);
  138. if ('type' in options) {
  139. if (options.type !== this.options.type) {
  140. this.options.type = options.type;
  141. // force recreation of all items
  142. var itemsData = this.itemsData;
  143. if (itemsData) {
  144. this.setItems(null); // remove all
  145. this.setItems(itemsData); // add all
  146. }
  147. }
  148. }
  149. };
  150. /**
  151. * Set items
  152. * @param {vis.DataSet | Array | null} items
  153. */
  154. Timeline.prototype.setItems = function(items) {
  155. var initialLoad = (this.itemsData == null);
  156. // convert to type DataSet when needed
  157. var newDataSet;
  158. if (!items) {
  159. newDataSet = null;
  160. }
  161. else if (items instanceof DataSet || items instanceof DataView) {
  162. newDataSet = items;
  163. }
  164. else {
  165. // turn an array into a dataset
  166. newDataSet = new DataSet(items, {
  167. type: {
  168. start: 'Date',
  169. end: 'Date'
  170. }
  171. });
  172. }
  173. // set items
  174. this.itemsData = newDataSet;
  175. this.itemSet && this.itemSet.setItems(newDataSet);
  176. if (initialLoad) {
  177. if (this.options.start != undefined || this.options.end != undefined) {
  178. if (this.options.start == undefined || this.options.end == undefined) {
  179. var dataRange = this._getDataRange();
  180. }
  181. var start = this.options.start != undefined ? this.options.start : dataRange.start;
  182. var end = this.options.end != undefined ? this.options.end : dataRange.end;
  183. this.setWindow(start, end, {animation: false});
  184. }
  185. else {
  186. this.fit({animation: false});
  187. }
  188. }
  189. };
  190. /**
  191. * Set groups
  192. * @param {vis.DataSet | Array} groups
  193. */
  194. Timeline.prototype.setGroups = function(groups) {
  195. // convert to type DataSet when needed
  196. var newDataSet;
  197. if (!groups) {
  198. newDataSet = null;
  199. }
  200. else if (groups instanceof DataSet || groups instanceof DataView) {
  201. newDataSet = groups;
  202. }
  203. else {
  204. // turn an array into a dataset
  205. newDataSet = new DataSet(groups);
  206. }
  207. this.groupsData = newDataSet;
  208. this.itemSet.setGroups(newDataSet);
  209. };
  210. /**
  211. * Set both items and groups in one go
  212. * @param {{items: Array | vis.DataSet, groups: Array | vis.DataSet}} data
  213. */
  214. Timeline.prototype.setData = function (data) {
  215. if (data && data.groups) {
  216. this.setGroups(data.groups);
  217. }
  218. if (data && data.items) {
  219. this.setItems(data.items);
  220. }
  221. };
  222. /**
  223. * Set selected items by their id. Replaces the current selection
  224. * Unknown id's are silently ignored.
  225. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  226. * selected. If ids is an empty array, all items will be
  227. * unselected.
  228. * @param {Object} [options] Available options:
  229. * `focus: boolean`
  230. * If true, focus will be set to the selected item(s)
  231. * `animation: boolean | {duration: number, easingFunction: string}`
  232. * If true (default), the range is animated
  233. * smoothly to the new window. An object can be
  234. * provided to specify duration and easing function.
  235. * Default duration is 500 ms, and default easing
  236. * function is 'easeInOutQuad'.
  237. * Only applicable when option focus is true.
  238. */
  239. Timeline.prototype.setSelection = function(ids, options) {
  240. this.itemSet && this.itemSet.setSelection(ids);
  241. if (options && options.focus) {
  242. this.focus(ids, options);
  243. }
  244. };
  245. /**
  246. * Get the selected items by their id
  247. * @return {Array} ids The ids of the selected items
  248. */
  249. Timeline.prototype.getSelection = function() {
  250. return this.itemSet && this.itemSet.getSelection() || [];
  251. };
  252. /**
  253. * Adjust the visible window such that the selected item (or multiple items)
  254. * are centered on screen.
  255. * @param {String | String[]} id An item id or array with item ids
  256. * @param {Object} [options] Available options:
  257. * `animation: boolean | {duration: number, easingFunction: string}`
  258. * If true (default), the range is animated
  259. * smoothly to the new window. An object can be
  260. * provided to specify duration and easing function.
  261. * Default duration is 500 ms, and default easing
  262. * function is 'easeInOutQuad'.
  263. */
  264. Timeline.prototype.focus = function(id, options) {
  265. if (!this.itemsData || id == undefined) return;
  266. var ids = Array.isArray(id) ? id : [id];
  267. // get the specified item(s)
  268. var itemsData = this.itemsData.getDataSet().get(ids, {
  269. type: {
  270. start: 'Date',
  271. end: 'Date'
  272. }
  273. });
  274. // calculate minimum start and maximum end of specified items
  275. var start = null;
  276. var end = null;
  277. itemsData.forEach(function (itemData) {
  278. var s = itemData.start.valueOf();
  279. var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf();
  280. if (start === null || s < start) {
  281. start = s;
  282. }
  283. if (end === null || e > end) {
  284. end = e;
  285. }
  286. });
  287. if (start !== null && end !== null) {
  288. // calculate the new middle and interval for the window
  289. var middle = (start + end) / 2;
  290. var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1);
  291. var animation = (options && options.animation !== undefined) ? options.animation : true;
  292. this.range.setRange(middle - interval / 2, middle + interval / 2, animation);
  293. }
  294. };
  295. /**
  296. * Get the data range of the item set.
  297. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  298. * When no minimum is found, min==null
  299. * When no maximum is found, max==null
  300. */
  301. Timeline.prototype.getItemRange = function() {
  302. // calculate min from start filed
  303. var dataset = this.itemsData && this.itemsData.getDataSet();
  304. var min = null;
  305. var max = null;
  306. if (dataset) {
  307. // calculate the minimum value of the field 'start'
  308. var minItem = dataset.min('start');
  309. min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null;
  310. // Note: we convert first to Date and then to number because else
  311. // a conversion from ISODate to Number will fail
  312. // calculate maximum value of fields 'start' and 'end'
  313. var maxStartItem = dataset.max('start');
  314. if (maxStartItem) {
  315. max = util.convert(maxStartItem.start, 'Date').valueOf();
  316. }
  317. var maxEndItem = dataset.max('end');
  318. if (maxEndItem) {
  319. if (max == null) {
  320. max = util.convert(maxEndItem.end, 'Date').valueOf();
  321. }
  322. else {
  323. max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf());
  324. }
  325. }
  326. }
  327. return {
  328. min: (min != null) ? new Date(min) : null,
  329. max: (max != null) ? new Date(max) : null
  330. };
  331. };
  332. /**
  333. * Generate Timeline related information from an event
  334. * @param {Event} event
  335. * @return {Object} An object with related information, like on which area
  336. * The event happened, whether clicked on an item, etc.
  337. */
  338. Timeline.prototype.getEventProperties = function (event) {
  339. var pageX = event.center ? event.center.x : event.pageX;
  340. var pageY = event.center ? event.center.y : event.pageY;
  341. var x = pageX - util.getAbsoluteLeft(this.dom.centerContainer);
  342. var y = pageY - util.getAbsoluteTop(this.dom.centerContainer);
  343. var item = this.itemSet.itemFromTarget(event);
  344. var group = this.itemSet.groupFromTarget(event);
  345. var customTime = CustomTime.customTimeFromTarget(event);
  346. var snap = this.itemSet.options.snap || null;
  347. var scale = this.body.util.getScale();
  348. var step = this.body.util.getStep();
  349. var time = this._toTime(x);
  350. var snappedTime = snap ? snap(time, scale, step) : time;
  351. var element = util.getTarget(event);
  352. var what = null;
  353. if (item != null) {what = 'item';}
  354. else if (customTime != null) {what = 'custom-time';}
  355. else if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
  356. else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
  357. else if (util.hasParent(element, this.itemSet.dom.labelSet)) {what = 'group-label';}
  358. else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
  359. else if (util.hasParent(element, this.dom.center)) {what = 'background';}
  360. return {
  361. event: event,
  362. item: item ? item.id : null,
  363. group: group ? group.groupId : null,
  364. what: what,
  365. pageX: pageX,
  366. pageY: pageY,
  367. x: x,
  368. y: y,
  369. time: time,
  370. snappedTime: snappedTime
  371. }
  372. };
  373. module.exports = Timeline;