scale.time.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /* global window: false */
  2. 'use strict';
  3. var moment = require('moment');
  4. moment = typeof(moment) === 'function' ? moment : window.moment;
  5. module.exports = function(Chart) {
  6. var helpers = Chart.helpers;
  7. var time = {
  8. units: [{
  9. name: 'millisecond',
  10. steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]
  11. }, {
  12. name: 'second',
  13. steps: [1, 2, 5, 10, 30]
  14. }, {
  15. name: 'minute',
  16. steps: [1, 2, 5, 10, 30]
  17. }, {
  18. name: 'hour',
  19. steps: [1, 2, 3, 6, 12]
  20. }, {
  21. name: 'day',
  22. steps: [1, 2, 5]
  23. }, {
  24. name: 'week',
  25. maxStep: 4
  26. }, {
  27. name: 'month',
  28. maxStep: 3
  29. }, {
  30. name: 'quarter',
  31. maxStep: 4
  32. }, {
  33. name: 'year',
  34. maxStep: false
  35. }]
  36. };
  37. var defaultConfig = {
  38. position: 'bottom',
  39. time: {
  40. parser: false, // false == a pattern string from http://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment
  41. format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from http://momentjs.com/docs/#/parsing/string-format/
  42. unit: false, // false == automatic or override with week, month, year, etc.
  43. round: false, // none, or override with week, month, year, etc.
  44. displayFormat: false, // DEPRECATED
  45. isoWeekday: false, // override week start day - see http://momentjs.com/docs/#/get-set/iso-weekday/
  46. minUnit: 'millisecond',
  47. // defaults to unit's corresponding unitFormat below or override using pattern string from http://momentjs.com/docs/#/displaying/format/
  48. displayFormats: {
  49. millisecond: 'h:mm:ss.SSS a', // 11:20:01.123 AM,
  50. second: 'h:mm:ss a', // 11:20:01 AM
  51. minute: 'h:mm:ss a', // 11:20:01 AM
  52. hour: 'MMM D, hA', // Sept 4, 5PM
  53. day: 'll', // Sep 4 2015
  54. week: 'll', // Week 46, or maybe "[W]WW - YYYY" ?
  55. month: 'MMM YYYY', // Sept 2015
  56. quarter: '[Q]Q - YYYY', // Q3
  57. year: 'YYYY' // 2015
  58. }
  59. },
  60. ticks: {
  61. autoSkip: false
  62. }
  63. };
  64. var TimeScale = Chart.Scale.extend({
  65. initialize: function() {
  66. if (!moment) {
  67. throw new Error('Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com');
  68. }
  69. Chart.Scale.prototype.initialize.call(this);
  70. },
  71. getLabelMoment: function(datasetIndex, index) {
  72. if (datasetIndex === null || index === null) {
  73. return null;
  74. }
  75. if (typeof this.labelMoments[datasetIndex] !== 'undefined') {
  76. return this.labelMoments[datasetIndex][index];
  77. }
  78. return null;
  79. },
  80. getLabelDiff: function(datasetIndex, index) {
  81. var me = this;
  82. if (datasetIndex === null || index === null) {
  83. return null;
  84. }
  85. if (me.labelDiffs === undefined) {
  86. me.buildLabelDiffs();
  87. }
  88. if (typeof me.labelDiffs[datasetIndex] !== 'undefined') {
  89. return me.labelDiffs[datasetIndex][index];
  90. }
  91. return null;
  92. },
  93. getMomentStartOf: function(tick) {
  94. var me = this;
  95. if (me.options.time.unit === 'week' && me.options.time.isoWeekday !== false) {
  96. return tick.clone().startOf('isoWeek').isoWeekday(me.options.time.isoWeekday);
  97. }
  98. return tick.clone().startOf(me.tickUnit);
  99. },
  100. determineDataLimits: function() {
  101. var me = this;
  102. me.labelMoments = [];
  103. // Only parse these once. If the dataset does not have data as x,y pairs, we will use
  104. // these
  105. var scaleLabelMoments = [];
  106. if (me.chart.data.labels && me.chart.data.labels.length > 0) {
  107. helpers.each(me.chart.data.labels, function(label) {
  108. var labelMoment = me.parseTime(label);
  109. if (labelMoment.isValid()) {
  110. if (me.options.time.round) {
  111. labelMoment.startOf(me.options.time.round);
  112. }
  113. scaleLabelMoments.push(labelMoment);
  114. }
  115. }, me);
  116. me.firstTick = moment.min.call(me, scaleLabelMoments);
  117. me.lastTick = moment.max.call(me, scaleLabelMoments);
  118. } else {
  119. me.firstTick = null;
  120. me.lastTick = null;
  121. }
  122. helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) {
  123. var momentsForDataset = [];
  124. var datasetVisible = me.chart.isDatasetVisible(datasetIndex);
  125. if (typeof dataset.data[0] === 'object' && dataset.data[0] !== null) {
  126. helpers.each(dataset.data, function(value) {
  127. var labelMoment = me.parseTime(me.getRightValue(value));
  128. if (labelMoment.isValid()) {
  129. if (me.options.time.round) {
  130. labelMoment.startOf(me.options.time.round);
  131. }
  132. momentsForDataset.push(labelMoment);
  133. if (datasetVisible) {
  134. // May have gone outside the scale ranges, make sure we keep the first and last ticks updated
  135. me.firstTick = me.firstTick !== null ? moment.min(me.firstTick, labelMoment) : labelMoment;
  136. me.lastTick = me.lastTick !== null ? moment.max(me.lastTick, labelMoment) : labelMoment;
  137. }
  138. }
  139. }, me);
  140. } else {
  141. // We have no labels. Use the ones from the scale
  142. momentsForDataset = scaleLabelMoments;
  143. }
  144. me.labelMoments.push(momentsForDataset);
  145. }, me);
  146. // Set these after we've done all the data
  147. if (me.options.time.min) {
  148. me.firstTick = me.parseTime(me.options.time.min);
  149. }
  150. if (me.options.time.max) {
  151. me.lastTick = me.parseTime(me.options.time.max);
  152. }
  153. // We will modify these, so clone for later
  154. me.firstTick = (me.firstTick || moment()).clone();
  155. me.lastTick = (me.lastTick || moment()).clone();
  156. },
  157. buildLabelDiffs: function() {
  158. var me = this;
  159. me.labelDiffs = [];
  160. var scaleLabelDiffs = [];
  161. // Parse common labels once
  162. if (me.chart.data.labels && me.chart.data.labels.length > 0) {
  163. helpers.each(me.chart.data.labels, function(label) {
  164. var labelMoment = me.parseTime(label);
  165. if (labelMoment.isValid()) {
  166. if (me.options.time.round) {
  167. labelMoment.startOf(me.options.time.round);
  168. }
  169. scaleLabelDiffs.push(labelMoment.diff(me.firstTick, me.tickUnit, true));
  170. }
  171. }, me);
  172. }
  173. helpers.each(me.chart.data.datasets, function(dataset) {
  174. var diffsForDataset = [];
  175. if (typeof dataset.data[0] === 'object' && dataset.data[0] !== null) {
  176. helpers.each(dataset.data, function(value) {
  177. var labelMoment = me.parseTime(me.getRightValue(value));
  178. if (labelMoment.isValid()) {
  179. if (me.options.time.round) {
  180. labelMoment.startOf(me.options.time.round);
  181. }
  182. diffsForDataset.push(labelMoment.diff(me.firstTick, me.tickUnit, true));
  183. }
  184. }, me);
  185. } else {
  186. // We have no labels. Use common ones
  187. diffsForDataset = scaleLabelDiffs;
  188. }
  189. me.labelDiffs.push(diffsForDataset);
  190. }, me);
  191. },
  192. buildTicks: function() {
  193. var me = this;
  194. me.ctx.save();
  195. var tickFontSize = helpers.getValueOrDefault(me.options.ticks.fontSize, Chart.defaults.global.defaultFontSize);
  196. var tickFontStyle = helpers.getValueOrDefault(me.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle);
  197. var tickFontFamily = helpers.getValueOrDefault(me.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily);
  198. var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
  199. me.ctx.font = tickLabelFont;
  200. me.ticks = [];
  201. me.unitScale = 1; // How much we scale the unit by, ie 2 means 2x unit per step
  202. me.scaleSizeInUnits = 0; // How large the scale is in the base unit (seconds, minutes, etc)
  203. // Set unit override if applicable
  204. if (me.options.time.unit) {
  205. me.tickUnit = me.options.time.unit || 'day';
  206. me.displayFormat = me.options.time.displayFormats[me.tickUnit];
  207. me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true);
  208. me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, 1);
  209. } else {
  210. // Determine the smallest needed unit of the time
  211. var innerWidth = me.isHorizontal() ? me.width : me.height;
  212. // Crude approximation of what the label length might be
  213. var tempFirstLabel = me.tickFormatFunction(me.firstTick, 0, []);
  214. var tickLabelWidth = me.ctx.measureText(tempFirstLabel).width;
  215. var cosRotation = Math.cos(helpers.toRadians(me.options.ticks.maxRotation));
  216. var sinRotation = Math.sin(helpers.toRadians(me.options.ticks.maxRotation));
  217. tickLabelWidth = (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation);
  218. var labelCapacity = innerWidth / (tickLabelWidth);
  219. // Start as small as possible
  220. me.tickUnit = me.options.time.minUnit;
  221. me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true);
  222. me.displayFormat = me.options.time.displayFormats[me.tickUnit];
  223. var unitDefinitionIndex = 0;
  224. var unitDefinition = time.units[unitDefinitionIndex];
  225. // While we aren't ideal and we don't have units left
  226. while (unitDefinitionIndex < time.units.length) {
  227. // Can we scale this unit. If `false` we can scale infinitely
  228. me.unitScale = 1;
  229. if (helpers.isArray(unitDefinition.steps) && Math.ceil(me.scaleSizeInUnits / labelCapacity) < helpers.max(unitDefinition.steps)) {
  230. // Use one of the predefined steps
  231. for (var idx = 0; idx < unitDefinition.steps.length; ++idx) {
  232. if (unitDefinition.steps[idx] >= Math.ceil(me.scaleSizeInUnits / labelCapacity)) {
  233. me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, unitDefinition.steps[idx]);
  234. break;
  235. }
  236. }
  237. break;
  238. } else if ((unitDefinition.maxStep === false) || (Math.ceil(me.scaleSizeInUnits / labelCapacity) < unitDefinition.maxStep)) {
  239. // We have a max step. Scale this unit
  240. me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, Math.ceil(me.scaleSizeInUnits / labelCapacity));
  241. break;
  242. } else {
  243. // Move to the next unit up
  244. ++unitDefinitionIndex;
  245. unitDefinition = time.units[unitDefinitionIndex];
  246. me.tickUnit = unitDefinition.name;
  247. var leadingUnitBuffer = me.firstTick.diff(me.getMomentStartOf(me.firstTick), me.tickUnit, true);
  248. var trailingUnitBuffer = me.getMomentStartOf(me.lastTick.clone().add(1, me.tickUnit)).diff(me.lastTick, me.tickUnit, true);
  249. me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true) + leadingUnitBuffer + trailingUnitBuffer;
  250. me.displayFormat = me.options.time.displayFormats[unitDefinition.name];
  251. }
  252. }
  253. }
  254. var roundedStart;
  255. // Only round the first tick if we have no hard minimum
  256. if (!me.options.time.min) {
  257. me.firstTick = me.getMomentStartOf(me.firstTick);
  258. roundedStart = me.firstTick;
  259. } else {
  260. roundedStart = me.getMomentStartOf(me.firstTick);
  261. }
  262. // Only round the last tick if we have no hard maximum
  263. if (!me.options.time.max) {
  264. var roundedEnd = me.getMomentStartOf(me.lastTick);
  265. var delta = roundedEnd.diff(me.lastTick, me.tickUnit, true);
  266. if (delta < 0) {
  267. // Do not use end of because we need me to be in the next time unit
  268. me.lastTick = me.getMomentStartOf(me.lastTick.add(1, me.tickUnit));
  269. } else if (delta >= 0) {
  270. me.lastTick = roundedEnd;
  271. }
  272. me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true);
  273. }
  274. // Tick displayFormat override
  275. if (me.options.time.displayFormat) {
  276. me.displayFormat = me.options.time.displayFormat;
  277. }
  278. // first tick. will have been rounded correctly if options.time.min is not specified
  279. me.ticks.push(me.firstTick.clone());
  280. // For every unit in between the first and last moment, create a moment and add it to the ticks tick
  281. for (var i = 1; i <= me.scaleSizeInUnits; ++i) {
  282. var newTick = roundedStart.clone().add(i, me.tickUnit);
  283. // Are we greater than the max time
  284. if (me.options.time.max && newTick.diff(me.lastTick, me.tickUnit, true) >= 0) {
  285. break;
  286. }
  287. if (i % me.unitScale === 0) {
  288. me.ticks.push(newTick);
  289. }
  290. }
  291. // Always show the right tick
  292. var diff = me.ticks[me.ticks.length - 1].diff(me.lastTick, me.tickUnit);
  293. if (diff !== 0 || me.scaleSizeInUnits === 0) {
  294. // this is a weird case. If the <max> option is the same as the end option, we can't just diff the times because the tick was created from the roundedStart
  295. // but the last tick was not rounded.
  296. if (me.options.time.max) {
  297. me.ticks.push(me.lastTick.clone());
  298. me.scaleSizeInUnits = me.lastTick.diff(me.ticks[0], me.tickUnit, true);
  299. } else {
  300. me.ticks.push(me.lastTick.clone());
  301. me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true);
  302. }
  303. }
  304. me.ctx.restore();
  305. // Invalidate label diffs cache
  306. me.labelDiffs = undefined;
  307. },
  308. // Get tooltip label
  309. getLabelForIndex: function(index, datasetIndex) {
  310. var me = this;
  311. var label = me.chart.data.labels && index < me.chart.data.labels.length ? me.chart.data.labels[index] : '';
  312. var value = me.chart.data.datasets[datasetIndex].data[index];
  313. if (value !== null && typeof value === 'object') {
  314. label = me.getRightValue(value);
  315. }
  316. // Format nicely
  317. if (me.options.time.tooltipFormat) {
  318. label = me.parseTime(label).format(me.options.time.tooltipFormat);
  319. }
  320. return label;
  321. },
  322. // Function to format an individual tick mark
  323. tickFormatFunction: function(tick, index, ticks) {
  324. var formattedTick = tick.format(this.displayFormat);
  325. var tickOpts = this.options.ticks;
  326. var callback = helpers.getValueOrDefault(tickOpts.callback, tickOpts.userCallback);
  327. if (callback) {
  328. return callback(formattedTick, index, ticks);
  329. }
  330. return formattedTick;
  331. },
  332. convertTicksToLabels: function() {
  333. var me = this;
  334. me.tickMoments = me.ticks;
  335. me.ticks = me.ticks.map(me.tickFormatFunction, me);
  336. },
  337. getPixelForValue: function(value, index, datasetIndex) {
  338. var me = this;
  339. var offset = null;
  340. if (index !== undefined && datasetIndex !== undefined) {
  341. offset = me.getLabelDiff(datasetIndex, index);
  342. }
  343. if (offset === null) {
  344. if (!value || !value.isValid) {
  345. // not already a moment object
  346. value = me.parseTime(me.getRightValue(value));
  347. }
  348. if (value && value.isValid && value.isValid()) {
  349. offset = value.diff(me.firstTick, me.tickUnit, true);
  350. }
  351. }
  352. if (offset !== null) {
  353. var decimal = offset !== 0 ? offset / me.scaleSizeInUnits : offset;
  354. if (me.isHorizontal()) {
  355. var valueOffset = (me.width * decimal);
  356. return me.left + Math.round(valueOffset);
  357. }
  358. var heightOffset = (me.height * decimal);
  359. return me.top + Math.round(heightOffset);
  360. }
  361. },
  362. getPixelForTick: function(index) {
  363. return this.getPixelForValue(this.tickMoments[index], null, null);
  364. },
  365. getValueForPixel: function(pixel) {
  366. var me = this;
  367. var innerDimension = me.isHorizontal() ? me.width : me.height;
  368. var offset = (pixel - (me.isHorizontal() ? me.left : me.top)) / innerDimension;
  369. offset *= me.scaleSizeInUnits;
  370. return me.firstTick.clone().add(moment.duration(offset, me.tickUnit).asSeconds(), 'seconds');
  371. },
  372. parseTime: function(label) {
  373. var me = this;
  374. if (typeof me.options.time.parser === 'string') {
  375. return moment(label, me.options.time.parser);
  376. }
  377. if (typeof me.options.time.parser === 'function') {
  378. return me.options.time.parser(label);
  379. }
  380. // Date objects
  381. if (typeof label.getMonth === 'function' || typeof label === 'number') {
  382. return moment(label);
  383. }
  384. // Moment support
  385. if (label.isValid && label.isValid()) {
  386. return label;
  387. }
  388. // Custom parsing (return an instance of moment)
  389. if (typeof me.options.time.format !== 'string' && me.options.time.format.call) {
  390. console.warn('options.time.format is deprecated and replaced by options.time.parser. See http://nnnick.github.io/Chart.js/docs-v2/#scales-time-scale');
  391. return me.options.time.format(label);
  392. }
  393. // Moment format parsing
  394. return moment(label, me.options.time.format);
  395. }
  396. });
  397. Chart.scaleService.registerScaleType('time', TimeScale, defaultConfig);
  398. };