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.

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