6 * Copyright 2016 Nick Downie
7 * Released under the MIT license
8 * https://github.com/chartjs/Chart.js/blob/master/LICENSE.md
12 * Description of import into Moodle:
14 * - Download Chart.bundle.js from https://github.com/chartjs/Chart.js/releases.
15 * - Copy Chart.bundle.js content to lib/amd/src/chartjs-lazy.js.
16 * - Convert line endings to LF-Unix format.
17 * - Keep these instructions to the file.
18 * - Visit lib/tests/other/chartjstestpage.php to see if the library still works after the update.
21 (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Chart = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
23 var colorNames = require(5);
35 rgbaString: rgbaString,
36 percentString: percentString,
37 percentaString: percentaString,
39 hslaString: hslaString,
44 function getRgba(string) {
48 var abbr = /^#([a-fA-F0-9]{3})$/i,
49 hex = /^#([a-fA-F0-9]{6})$/i,
50 rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
51 per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
56 match = string.match(abbr);
59 for (var i = 0; i < rgb.length; i++) {
60 rgb[i] = parseInt(match[i] + match[i], 16);
63 else if (match = string.match(hex)) {
65 for (var i = 0; i < rgb.length; i++) {
66 rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
69 else if (match = string.match(rgba)) {
70 for (var i = 0; i < rgb.length; i++) {
71 rgb[i] = parseInt(match[i + 1]);
73 a = parseFloat(match[4]);
75 else if (match = string.match(per)) {
76 for (var i = 0; i < rgb.length; i++) {
77 rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
79 a = parseFloat(match[4]);
81 else if (match = string.match(keyword)) {
82 if (match[1] == "transparent") {
85 rgb = colorNames[match[1]];
91 for (var i = 0; i < rgb.length; i++) {
92 rgb[i] = scale(rgb[i], 0, 255);
104 function getHsla(string) {
108 var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
109 var match = string.match(hsl);
111 var alpha = parseFloat(match[4]);
112 var h = scale(parseInt(match[1]), 0, 360),
113 s = scale(parseFloat(match[2]), 0, 100),
114 l = scale(parseFloat(match[3]), 0, 100),
115 a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
120 function getHwb(string) {
124 var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
125 var match = string.match(hwb);
127 var alpha = parseFloat(match[4]);
128 var h = scale(parseInt(match[1]), 0, 360),
129 w = scale(parseFloat(match[2]), 0, 100),
130 b = scale(parseFloat(match[3]), 0, 100),
131 a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
136 function getRgb(string) {
137 var rgba = getRgba(string);
138 return rgba && rgba.slice(0, 3);
141 function getHsl(string) {
142 var hsla = getHsla(string);
143 return hsla && hsla.slice(0, 3);
146 function getAlpha(string) {
147 var vals = getRgba(string);
151 else if (vals = getHsla(string)) {
154 else if (vals = getHwb(string)) {
160 function hexString(rgb) {
161 return "#" + hexDouble(rgb[0]) + hexDouble(rgb[1])
165 function rgbString(rgba, alpha) {
166 if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
167 return rgbaString(rgba, alpha);
169 return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
172 function rgbaString(rgba, alpha) {
173 if (alpha === undefined) {
174 alpha = (rgba[3] !== undefined ? rgba[3] : 1);
176 return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
177 + ", " + alpha + ")";
180 function percentString(rgba, alpha) {
181 if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
182 return percentaString(rgba, alpha);
184 var r = Math.round(rgba[0]/255 * 100),
185 g = Math.round(rgba[1]/255 * 100),
186 b = Math.round(rgba[2]/255 * 100);
188 return "rgb(" + r + "%, " + g + "%, " + b + "%)";
191 function percentaString(rgba, alpha) {
192 var r = Math.round(rgba[0]/255 * 100),
193 g = Math.round(rgba[1]/255 * 100),
194 b = Math.round(rgba[2]/255 * 100);
195 return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
198 function hslString(hsla, alpha) {
199 if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
200 return hslaString(hsla, alpha);
202 return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
205 function hslaString(hsla, alpha) {
206 if (alpha === undefined) {
207 alpha = (hsla[3] !== undefined ? hsla[3] : 1);
209 return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
213 // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
214 // (hwb have alpha optional & 1 is default value)
215 function hwbString(hwb, alpha) {
216 if (alpha === undefined) {
217 alpha = (hwb[3] !== undefined ? hwb[3] : 1);
219 return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
220 + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
223 function keyword(rgb) {
224 return reverseNames[rgb.slice(0, 3)];
228 function scale(num, min, max) {
229 return Math.min(Math.max(min, num), max);
232 function hexDouble(num) {
233 var str = num.toString(16).toUpperCase();
234 return (str.length < 2) ? "0" + str : str;
238 //create a list of reverse color names
239 var reverseNames = {};
240 for (var name in colorNames) {
241 reverseNames[colorNames[name]] = name;
244 },{"5":5}],2:[function(require,module,exports){
246 var convert = require(4);
247 var string = require(1);
249 var Color = function (obj) {
250 if (obj instanceof Color) {
253 if (!(this instanceof Color)) {
254 return new Color(obj);
267 // parse Color() argument
269 if (typeof obj === 'string') {
270 vals = string.getRgba(obj);
272 this.setValues('rgb', vals);
273 } else if (vals = string.getHsla(obj)) {
274 this.setValues('hsl', vals);
275 } else if (vals = string.getHwb(obj)) {
276 this.setValues('hwb', vals);
278 } else if (typeof obj === 'object') {
280 if (vals.r !== undefined || vals.red !== undefined) {
281 this.setValues('rgb', vals);
282 } else if (vals.l !== undefined || vals.lightness !== undefined) {
283 this.setValues('hsl', vals);
284 } else if (vals.v !== undefined || vals.value !== undefined) {
285 this.setValues('hsv', vals);
286 } else if (vals.w !== undefined || vals.whiteness !== undefined) {
287 this.setValues('hwb', vals);
288 } else if (vals.c !== undefined || vals.cyan !== undefined) {
289 this.setValues('cmyk', vals);
295 isValid: function () {
299 return this.setSpace('rgb', arguments);
302 return this.setSpace('hsl', arguments);
305 return this.setSpace('hsv', arguments);
308 return this.setSpace('hwb', arguments);
311 return this.setSpace('cmyk', arguments);
314 rgbArray: function () {
315 return this.values.rgb;
317 hslArray: function () {
318 return this.values.hsl;
320 hsvArray: function () {
321 return this.values.hsv;
323 hwbArray: function () {
324 var values = this.values;
325 if (values.alpha !== 1) {
326 return values.hwb.concat([values.alpha]);
330 cmykArray: function () {
331 return this.values.cmyk;
333 rgbaArray: function () {
334 var values = this.values;
335 return values.rgb.concat([values.alpha]);
337 hslaArray: function () {
338 var values = this.values;
339 return values.hsl.concat([values.alpha]);
341 alpha: function (val) {
342 if (val === undefined) {
343 return this.values.alpha;
345 this.setValues('alpha', val);
349 red: function (val) {
350 return this.setChannel('rgb', 0, val);
352 green: function (val) {
353 return this.setChannel('rgb', 1, val);
355 blue: function (val) {
356 return this.setChannel('rgb', 2, val);
358 hue: function (val) {
361 val = val < 0 ? 360 + val : val;
363 return this.setChannel('hsl', 0, val);
365 saturation: function (val) {
366 return this.setChannel('hsl', 1, val);
368 lightness: function (val) {
369 return this.setChannel('hsl', 2, val);
371 saturationv: function (val) {
372 return this.setChannel('hsv', 1, val);
374 whiteness: function (val) {
375 return this.setChannel('hwb', 1, val);
377 blackness: function (val) {
378 return this.setChannel('hwb', 2, val);
380 value: function (val) {
381 return this.setChannel('hsv', 2, val);
383 cyan: function (val) {
384 return this.setChannel('cmyk', 0, val);
386 magenta: function (val) {
387 return this.setChannel('cmyk', 1, val);
389 yellow: function (val) {
390 return this.setChannel('cmyk', 2, val);
392 black: function (val) {
393 return this.setChannel('cmyk', 3, val);
396 hexString: function () {
397 return string.hexString(this.values.rgb);
399 rgbString: function () {
400 return string.rgbString(this.values.rgb, this.values.alpha);
402 rgbaString: function () {
403 return string.rgbaString(this.values.rgb, this.values.alpha);
405 percentString: function () {
406 return string.percentString(this.values.rgb, this.values.alpha);
408 hslString: function () {
409 return string.hslString(this.values.hsl, this.values.alpha);
411 hslaString: function () {
412 return string.hslaString(this.values.hsl, this.values.alpha);
414 hwbString: function () {
415 return string.hwbString(this.values.hwb, this.values.alpha);
417 keyword: function () {
418 return string.keyword(this.values.rgb, this.values.alpha);
421 rgbNumber: function () {
422 var rgb = this.values.rgb;
423 return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
426 luminosity: function () {
427 // http://www.w3.org/TR/WCAG20/#relativeluminancedef
428 var rgb = this.values.rgb;
430 for (var i = 0; i < rgb.length; i++) {
431 var chan = rgb[i] / 255;
432 lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
434 return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
437 contrast: function (color2) {
438 // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
439 var lum1 = this.luminosity();
440 var lum2 = color2.luminosity();
442 return (lum1 + 0.05) / (lum2 + 0.05);
444 return (lum2 + 0.05) / (lum1 + 0.05);
447 level: function (color2) {
448 var contrastRatio = this.contrast(color2);
449 if (contrastRatio >= 7.1) {
453 return (contrastRatio >= 4.5) ? 'AA' : '';
457 // YIQ equation from http://24ways.org/2010/calculating-color-contrast
458 var rgb = this.values.rgb;
459 var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
467 negate: function () {
469 for (var i = 0; i < 3; i++) {
470 rgb[i] = 255 - this.values.rgb[i];
472 this.setValues('rgb', rgb);
476 lighten: function (ratio) {
477 var hsl = this.values.hsl;
478 hsl[2] += hsl[2] * ratio;
479 this.setValues('hsl', hsl);
483 darken: function (ratio) {
484 var hsl = this.values.hsl;
485 hsl[2] -= hsl[2] * ratio;
486 this.setValues('hsl', hsl);
490 saturate: function (ratio) {
491 var hsl = this.values.hsl;
492 hsl[1] += hsl[1] * ratio;
493 this.setValues('hsl', hsl);
497 desaturate: function (ratio) {
498 var hsl = this.values.hsl;
499 hsl[1] -= hsl[1] * ratio;
500 this.setValues('hsl', hsl);
504 whiten: function (ratio) {
505 var hwb = this.values.hwb;
506 hwb[1] += hwb[1] * ratio;
507 this.setValues('hwb', hwb);
511 blacken: function (ratio) {
512 var hwb = this.values.hwb;
513 hwb[2] += hwb[2] * ratio;
514 this.setValues('hwb', hwb);
518 greyscale: function () {
519 var rgb = this.values.rgb;
520 // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
521 var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
522 this.setValues('rgb', [val, val, val]);
526 clearer: function (ratio) {
527 var alpha = this.values.alpha;
528 this.setValues('alpha', alpha - (alpha * ratio));
532 opaquer: function (ratio) {
533 var alpha = this.values.alpha;
534 this.setValues('alpha', alpha + (alpha * ratio));
538 rotate: function (degrees) {
539 var hsl = this.values.hsl;
540 var hue = (hsl[0] + degrees) % 360;
541 hsl[0] = hue < 0 ? 360 + hue : hue;
542 this.setValues('hsl', hsl);
547 * Ported from sass implementation in C
548 * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
550 mix: function (mixinColor, weight) {
552 var color2 = mixinColor;
553 var p = weight === undefined ? 0.5 : weight;
556 var a = color1.alpha() - color2.alpha();
558 var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
563 w1 * color1.red() + w2 * color2.red(),
564 w1 * color1.green() + w2 * color2.green(),
565 w1 * color1.blue() + w2 * color2.blue()
567 .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
570 toJSON: function () {
575 // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
576 // making the final build way to big to embed in Chart.js. So let's do it manually,
577 // assuming that values to clone are 1 dimension arrays containing only numbers,
578 // except 'alpha' which is a number.
579 var result = new Color();
580 var source = this.values;
581 var target = result.values;
584 for (var prop in source) {
585 if (source.hasOwnProperty(prop)) {
586 value = source[prop];
587 type = ({}).toString.call(value);
588 if (type === '[object Array]') {
589 target[prop] = value.slice(0);
590 } else if (type === '[object Number]') {
591 target[prop] = value;
593 console.error('unexpected color value:', value);
602 Color.prototype.spaces = {
603 rgb: ['red', 'green', 'blue'],
604 hsl: ['hue', 'saturation', 'lightness'],
605 hsv: ['hue', 'saturation', 'value'],
606 hwb: ['hue', 'whiteness', 'blackness'],
607 cmyk: ['cyan', 'magenta', 'yellow', 'black']
610 Color.prototype.maxes = {
611 rgb: [255, 255, 255],
612 hsl: [360, 100, 100],
613 hsv: [360, 100, 100],
614 hwb: [360, 100, 100],
615 cmyk: [100, 100, 100, 100]
618 Color.prototype.getValues = function (space) {
619 var values = this.values;
622 for (var i = 0; i < space.length; i++) {
623 vals[space.charAt(i)] = values[space][i];
626 if (values.alpha !== 1) {
627 vals.a = values.alpha;
630 // {r: 255, g: 255, b: 255, a: 0.4}
634 Color.prototype.setValues = function (space, vals) {
635 var values = this.values;
636 var spaces = this.spaces;
637 var maxes = this.maxes;
643 if (space === 'alpha') {
645 } else if (vals.length) {
647 values[space] = vals.slice(0, space.length);
648 alpha = vals[space.length];
649 } else if (vals[space.charAt(0)] !== undefined) {
650 // {r: 10, g: 10, b: 10}
651 for (i = 0; i < space.length; i++) {
652 values[space][i] = vals[space.charAt(i)];
656 } else if (vals[spaces[space][0]] !== undefined) {
657 // {red: 10, green: 10, blue: 10}
658 var chans = spaces[space];
660 for (i = 0; i < space.length; i++) {
661 values[space][i] = vals[chans[i]];
667 values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
669 if (space === 'alpha') {
675 // cap values of the space prior converting all values
676 for (i = 0; i < space.length; i++) {
677 capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
678 values[space][i] = Math.round(capped);
681 // convert to all the other color spaces
682 for (var sname in spaces) {
683 if (sname !== space) {
684 values[sname] = convert[space][sname](values[space]);
691 Color.prototype.setSpace = function (space, args) {
694 if (vals === undefined) {
696 return this.getValues(space);
699 // color.rgb(10, 10, 10)
700 if (typeof vals === 'number') {
701 vals = Array.prototype.slice.call(args);
704 this.setValues(space, vals);
708 Color.prototype.setChannel = function (space, index, val) {
709 var svalues = this.values[space];
710 if (val === undefined) {
712 return svalues[index];
713 } else if (val === svalues[index]) {
714 // color.red(color.red())
719 svalues[index] = val;
720 this.setValues(space, svalues);
725 if (typeof window !== 'undefined') {
726 window.Color = Color;
729 module.exports = Color;
731 },{"1":1,"4":4}],3:[function(require,module,exports){
739 rgb2keyword: rgb2keyword,
748 hsl2keyword: hsl2keyword,
754 hsv2keyword: hsv2keyword,
760 hwb2keyword: hwb2keyword,
766 cmyk2keyword: cmyk2keyword,
768 keyword2rgb: keyword2rgb,
769 keyword2hsl: keyword2hsl,
770 keyword2hsv: keyword2hsv,
771 keyword2hwb: keyword2hwb,
772 keyword2cmyk: keyword2cmyk,
773 keyword2lab: keyword2lab,
774 keyword2xyz: keyword2xyz,
790 function rgb2hsl(rgb) {
794 min = Math.min(r, g, b),
795 max = Math.max(r, g, b),
804 h = 2 + (b - r) / delta;
806 h = 4 + (r - g)/ delta;
808 h = Math.min(h * 60, 360);
818 s = delta / (max + min);
820 s = delta / (2 - max - min);
822 return [h, s * 100, l * 100];
825 function rgb2hsv(rgb) {
829 min = Math.min(r, g, b),
830 max = Math.max(r, g, b),
837 s = (delta/max * 1000)/10;
844 h = 2 + (b - r) / delta;
846 h = 4 + (r - g) / delta;
848 h = Math.min(h * 60, 360);
853 v = ((max / 255) * 1000) / 10;
858 function rgb2hwb(rgb) {
863 w = 1/255 * Math.min(r, Math.min(g, b)),
864 b = 1 - 1/255 * Math.max(r, Math.max(g, b));
866 return [h, w * 100, b * 100];
869 function rgb2cmyk(rgb) {
870 var r = rgb[0] / 255,
875 k = Math.min(1 - r, 1 - g, 1 - b);
876 c = (1 - r - k) / (1 - k) || 0;
877 m = (1 - g - k) / (1 - k) || 0;
878 y = (1 - b - k) / (1 - k) || 0;
879 return [c * 100, m * 100, y * 100, k * 100];
882 function rgb2keyword(rgb) {
883 return reverseKeywords[JSON.stringify(rgb)];
886 function rgb2xyz(rgb) {
887 var r = rgb[0] / 255,
892 r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
893 g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
894 b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
896 var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
897 var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
898 var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
900 return [x * 100, y *100, z * 100];
903 function rgb2lab(rgb) {
904 var xyz = rgb2xyz(rgb),
914 x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
915 y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
916 z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
925 function rgb2lch(args) {
926 return lab2lch(rgb2lab(args));
929 function hsl2rgb(hsl) {
930 var h = hsl[0] / 360,
933 t1, t2, t3, rgb, val;
937 return [val, val, val];
947 for (var i = 0; i < 3; i++) {
948 t3 = h + 1 / 3 * - (i - 1);
953 val = t1 + (t2 - t1) * 6 * t3;
957 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
967 function hsl2hsv(hsl) {
974 // no need to do calc on black
975 // also avoids divide by 0 error
980 s *= (l <= 1) ? l : 2 - l;
982 sv = (2 * s) / (l + s);
983 return [h, sv * 100, v * 100];
986 function hsl2hwb(args) {
987 return rgb2hwb(hsl2rgb(args));
990 function hsl2cmyk(args) {
991 return rgb2cmyk(hsl2rgb(args));
994 function hsl2keyword(args) {
995 return rgb2keyword(hsl2rgb(args));
999 function hsv2rgb(hsv) {
1000 var h = hsv[0] / 60,
1003 hi = Math.floor(h) % 6;
1005 var f = h - Math.floor(h),
1006 p = 255 * v * (1 - s),
1007 q = 255 * v * (1 - (s * f)),
1008 t = 255 * v * (1 - (s * (1 - f))),
1027 function hsv2hsl(hsv) {
1035 sl /= (l <= 1) ? l : 2 - l;
1038 return [h, sl * 100, l * 100];
1041 function hsv2hwb(args) {
1042 return rgb2hwb(hsv2rgb(args))
1045 function hsv2cmyk(args) {
1046 return rgb2cmyk(hsv2rgb(args));
1049 function hsv2keyword(args) {
1050 return rgb2keyword(hsv2rgb(args));
1053 // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
1054 function hwb2rgb(hwb) {
1055 var h = hwb[0] / 360,
1061 // wh + bl cant be > 1
1067 i = Math.floor(6 * h);
1070 if ((i & 0x01) != 0) {
1073 n = wh + f * (v - wh); // linear interpolation
1078 case 0: r = v; g = n; b = wh; break;
1079 case 1: r = n; g = v; b = wh; break;
1080 case 2: r = wh; g = v; b = n; break;
1081 case 3: r = wh; g = n; b = v; break;
1082 case 4: r = n; g = wh; b = v; break;
1083 case 5: r = v; g = wh; b = n; break;
1086 return [r * 255, g * 255, b * 255];
1089 function hwb2hsl(args) {
1090 return rgb2hsl(hwb2rgb(args));
1093 function hwb2hsv(args) {
1094 return rgb2hsv(hwb2rgb(args));
1097 function hwb2cmyk(args) {
1098 return rgb2cmyk(hwb2rgb(args));
1101 function hwb2keyword(args) {
1102 return rgb2keyword(hwb2rgb(args));
1105 function cmyk2rgb(cmyk) {
1106 var c = cmyk[0] / 100,
1112 r = 1 - Math.min(1, c * (1 - k) + k);
1113 g = 1 - Math.min(1, m * (1 - k) + k);
1114 b = 1 - Math.min(1, y * (1 - k) + k);
1115 return [r * 255, g * 255, b * 255];
1118 function cmyk2hsl(args) {
1119 return rgb2hsl(cmyk2rgb(args));
1122 function cmyk2hsv(args) {
1123 return rgb2hsv(cmyk2rgb(args));
1126 function cmyk2hwb(args) {
1127 return rgb2hwb(cmyk2rgb(args));
1130 function cmyk2keyword(args) {
1131 return rgb2keyword(cmyk2rgb(args));
1135 function xyz2rgb(xyz) {
1136 var x = xyz[0] / 100,
1141 r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
1142 g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
1143 b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
1146 r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
1149 g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
1152 b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
1155 r = Math.min(Math.max(0, r), 1);
1156 g = Math.min(Math.max(0, g), 1);
1157 b = Math.min(Math.max(0, b), 1);
1159 return [r * 255, g * 255, b * 255];
1162 function xyz2lab(xyz) {
1172 x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
1173 y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
1174 z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
1183 function xyz2lch(args) {
1184 return lab2lch(xyz2lab(args));
1187 function lab2xyz(lab) {
1194 y = (l * 100) / 903.3;
1195 y2 = (7.787 * (y / 100)) + (16 / 116);
1197 y = 100 * Math.pow((l + 16) / 116, 3);
1198 y2 = Math.pow(y / 100, 1/3);
1201 x = x / 95.047 <= 0.008856 ? x = (95.047 * ((a / 500) + y2 - (16 / 116))) / 7.787 : 95.047 * Math.pow((a / 500) + y2, 3);
1203 z = z / 108.883 <= 0.008859 ? z = (108.883 * (y2 - (b / 200) - (16 / 116))) / 7.787 : 108.883 * Math.pow(y2 - (b / 200), 3);
1208 function lab2lch(lab) {
1214 hr = Math.atan2(b, a);
1215 h = hr * 360 / 2 / Math.PI;
1219 c = Math.sqrt(a * a + b * b);
1223 function lab2rgb(args) {
1224 return xyz2rgb(lab2xyz(args));
1227 function lch2lab(lch) {
1233 hr = h / 360 * 2 * Math.PI;
1234 a = c * Math.cos(hr);
1235 b = c * Math.sin(hr);
1239 function lch2xyz(args) {
1240 return lab2xyz(lch2lab(args));
1243 function lch2rgb(args) {
1244 return lab2rgb(lch2lab(args));
1247 function keyword2rgb(keyword) {
1248 return cssKeywords[keyword];
1251 function keyword2hsl(args) {
1252 return rgb2hsl(keyword2rgb(args));
1255 function keyword2hsv(args) {
1256 return rgb2hsv(keyword2rgb(args));
1259 function keyword2hwb(args) {
1260 return rgb2hwb(keyword2rgb(args));
1263 function keyword2cmyk(args) {
1264 return rgb2cmyk(keyword2rgb(args));
1267 function keyword2lab(args) {
1268 return rgb2lab(keyword2rgb(args));
1271 function keyword2xyz(args) {
1272 return rgb2xyz(keyword2rgb(args));
1276 aliceblue: [240,248,255],
1277 antiquewhite: [250,235,215],
1279 aquamarine: [127,255,212],
1280 azure: [240,255,255],
1281 beige: [245,245,220],
1282 bisque: [255,228,196],
1284 blanchedalmond: [255,235,205],
1286 blueviolet: [138,43,226],
1288 burlywood: [222,184,135],
1289 cadetblue: [95,158,160],
1290 chartreuse: [127,255,0],
1291 chocolate: [210,105,30],
1292 coral: [255,127,80],
1293 cornflowerblue: [100,149,237],
1294 cornsilk: [255,248,220],
1295 crimson: [220,20,60],
1297 darkblue: [0,0,139],
1298 darkcyan: [0,139,139],
1299 darkgoldenrod: [184,134,11],
1300 darkgray: [169,169,169],
1301 darkgreen: [0,100,0],
1302 darkgrey: [169,169,169],
1303 darkkhaki: [189,183,107],
1304 darkmagenta: [139,0,139],
1305 darkolivegreen: [85,107,47],
1306 darkorange: [255,140,0],
1307 darkorchid: [153,50,204],
1309 darksalmon: [233,150,122],
1310 darkseagreen: [143,188,143],
1311 darkslateblue: [72,61,139],
1312 darkslategray: [47,79,79],
1313 darkslategrey: [47,79,79],
1314 darkturquoise: [0,206,209],
1315 darkviolet: [148,0,211],
1316 deeppink: [255,20,147],
1317 deepskyblue: [0,191,255],
1318 dimgray: [105,105,105],
1319 dimgrey: [105,105,105],
1320 dodgerblue: [30,144,255],
1321 firebrick: [178,34,34],
1322 floralwhite: [255,250,240],
1323 forestgreen: [34,139,34],
1324 fuchsia: [255,0,255],
1325 gainsboro: [220,220,220],
1326 ghostwhite: [248,248,255],
1328 goldenrod: [218,165,32],
1329 gray: [128,128,128],
1331 greenyellow: [173,255,47],
1332 grey: [128,128,128],
1333 honeydew: [240,255,240],
1334 hotpink: [255,105,180],
1335 indianred: [205,92,92],
1337 ivory: [255,255,240],
1338 khaki: [240,230,140],
1339 lavender: [230,230,250],
1340 lavenderblush: [255,240,245],
1341 lawngreen: [124,252,0],
1342 lemonchiffon: [255,250,205],
1343 lightblue: [173,216,230],
1344 lightcoral: [240,128,128],
1345 lightcyan: [224,255,255],
1346 lightgoldenrodyellow: [250,250,210],
1347 lightgray: [211,211,211],
1348 lightgreen: [144,238,144],
1349 lightgrey: [211,211,211],
1350 lightpink: [255,182,193],
1351 lightsalmon: [255,160,122],
1352 lightseagreen: [32,178,170],
1353 lightskyblue: [135,206,250],
1354 lightslategray: [119,136,153],
1355 lightslategrey: [119,136,153],
1356 lightsteelblue: [176,196,222],
1357 lightyellow: [255,255,224],
1359 limegreen: [50,205,50],
1360 linen: [250,240,230],
1361 magenta: [255,0,255],
1363 mediumaquamarine: [102,205,170],
1364 mediumblue: [0,0,205],
1365 mediumorchid: [186,85,211],
1366 mediumpurple: [147,112,219],
1367 mediumseagreen: [60,179,113],
1368 mediumslateblue: [123,104,238],
1369 mediumspringgreen: [0,250,154],
1370 mediumturquoise: [72,209,204],
1371 mediumvioletred: [199,21,133],
1372 midnightblue: [25,25,112],
1373 mintcream: [245,255,250],
1374 mistyrose: [255,228,225],
1375 moccasin: [255,228,181],
1376 navajowhite: [255,222,173],
1378 oldlace: [253,245,230],
1380 olivedrab: [107,142,35],
1381 orange: [255,165,0],
1382 orangered: [255,69,0],
1383 orchid: [218,112,214],
1384 palegoldenrod: [238,232,170],
1385 palegreen: [152,251,152],
1386 paleturquoise: [175,238,238],
1387 palevioletred: [219,112,147],
1388 papayawhip: [255,239,213],
1389 peachpuff: [255,218,185],
1391 pink: [255,192,203],
1392 plum: [221,160,221],
1393 powderblue: [176,224,230],
1394 purple: [128,0,128],
1395 rebeccapurple: [102, 51, 153],
1397 rosybrown: [188,143,143],
1398 royalblue: [65,105,225],
1399 saddlebrown: [139,69,19],
1400 salmon: [250,128,114],
1401 sandybrown: [244,164,96],
1402 seagreen: [46,139,87],
1403 seashell: [255,245,238],
1404 sienna: [160,82,45],
1405 silver: [192,192,192],
1406 skyblue: [135,206,235],
1407 slateblue: [106,90,205],
1408 slategray: [112,128,144],
1409 slategrey: [112,128,144],
1410 snow: [255,250,250],
1411 springgreen: [0,255,127],
1412 steelblue: [70,130,180],
1415 thistle: [216,191,216],
1416 tomato: [255,99,71],
1417 turquoise: [64,224,208],
1418 violet: [238,130,238],
1419 wheat: [245,222,179],
1420 white: [255,255,255],
1421 whitesmoke: [245,245,245],
1422 yellow: [255,255,0],
1423 yellowgreen: [154,205,50]
1426 var reverseKeywords = {};
1427 for (var key in cssKeywords) {
1428 reverseKeywords[JSON.stringify(cssKeywords[key])] = key;
1431 },{}],4:[function(require,module,exports){
1432 var conversions = require(3);
1434 var convert = function() {
1435 return new Converter();
1438 for (var func in conversions) {
1439 // export Raw versions
1440 convert[func + "Raw"] = (function(func) {
1441 // accept array or plain args
1442 return function(arg) {
1443 if (typeof arg == "number")
1444 arg = Array.prototype.slice.call(arguments);
1445 return conversions[func](arg);
1449 var pair = /(\w+)2(\w+)/.exec(func),
1453 // export rgb2hsl and ["rgb"]["hsl"]
1454 convert[from] = convert[from] || {};
1456 convert[from][to] = convert[func] = (function(func) {
1457 return function(arg) {
1458 if (typeof arg == "number")
1459 arg = Array.prototype.slice.call(arguments);
1461 var val = conversions[func](arg);
1462 if (typeof val == "string" || val === undefined)
1463 return val; // keyword
1465 for (var i = 0; i < val.length; i++)
1466 val[i] = Math.round(val[i]);
1473 /* Converter does lazy conversion and caching */
1474 var Converter = function() {
1478 /* Either get the values for a space or
1479 set the values for a space, depending on args */
1480 Converter.prototype.routeSpace = function(space, args) {
1481 var values = args[0];
1482 if (values === undefined) {
1484 return this.getValues(space);
1486 // color.rgb(10, 10, 10)
1487 if (typeof values == "number") {
1488 values = Array.prototype.slice.call(args);
1491 return this.setValues(space, values);
1494 /* Set the values for a space, invalidating cache */
1495 Converter.prototype.setValues = function(space, values) {
1498 this.convs[space] = values;
1502 /* Get the values for a space. If there's already
1503 a conversion for the space, fetch it, otherwise
1505 Converter.prototype.getValues = function(space) {
1506 var vals = this.convs[space];
1508 var fspace = this.space,
1509 from = this.convs[fspace];
1510 vals = convert[fspace][space](from);
1512 this.convs[space] = vals;
1517 ["rgb", "hsl", "hsv", "cmyk", "keyword"].forEach(function(space) {
1518 Converter.prototype[space] = function(vals) {
1519 return this.routeSpace(space, arguments);
1523 module.exports = convert;
1524 },{"3":3}],5:[function(require,module,exports){
1528 "aliceblue": [240, 248, 255],
1529 "antiquewhite": [250, 235, 215],
1530 "aqua": [0, 255, 255],
1531 "aquamarine": [127, 255, 212],
1532 "azure": [240, 255, 255],
1533 "beige": [245, 245, 220],
1534 "bisque": [255, 228, 196],
1536 "blanchedalmond": [255, 235, 205],
1537 "blue": [0, 0, 255],
1538 "blueviolet": [138, 43, 226],
1539 "brown": [165, 42, 42],
1540 "burlywood": [222, 184, 135],
1541 "cadetblue": [95, 158, 160],
1542 "chartreuse": [127, 255, 0],
1543 "chocolate": [210, 105, 30],
1544 "coral": [255, 127, 80],
1545 "cornflowerblue": [100, 149, 237],
1546 "cornsilk": [255, 248, 220],
1547 "crimson": [220, 20, 60],
1548 "cyan": [0, 255, 255],
1549 "darkblue": [0, 0, 139],
1550 "darkcyan": [0, 139, 139],
1551 "darkgoldenrod": [184, 134, 11],
1552 "darkgray": [169, 169, 169],
1553 "darkgreen": [0, 100, 0],
1554 "darkgrey": [169, 169, 169],
1555 "darkkhaki": [189, 183, 107],
1556 "darkmagenta": [139, 0, 139],
1557 "darkolivegreen": [85, 107, 47],
1558 "darkorange": [255, 140, 0],
1559 "darkorchid": [153, 50, 204],
1560 "darkred": [139, 0, 0],
1561 "darksalmon": [233, 150, 122],
1562 "darkseagreen": [143, 188, 143],
1563 "darkslateblue": [72, 61, 139],
1564 "darkslategray": [47, 79, 79],
1565 "darkslategrey": [47, 79, 79],
1566 "darkturquoise": [0, 206, 209],
1567 "darkviolet": [148, 0, 211],
1568 "deeppink": [255, 20, 147],
1569 "deepskyblue": [0, 191, 255],
1570 "dimgray": [105, 105, 105],
1571 "dimgrey": [105, 105, 105],
1572 "dodgerblue": [30, 144, 255],
1573 "firebrick": [178, 34, 34],
1574 "floralwhite": [255, 250, 240],
1575 "forestgreen": [34, 139, 34],
1576 "fuchsia": [255, 0, 255],
1577 "gainsboro": [220, 220, 220],
1578 "ghostwhite": [248, 248, 255],
1579 "gold": [255, 215, 0],
1580 "goldenrod": [218, 165, 32],
1581 "gray": [128, 128, 128],
1582 "green": [0, 128, 0],
1583 "greenyellow": [173, 255, 47],
1584 "grey": [128, 128, 128],
1585 "honeydew": [240, 255, 240],
1586 "hotpink": [255, 105, 180],
1587 "indianred": [205, 92, 92],
1588 "indigo": [75, 0, 130],
1589 "ivory": [255, 255, 240],
1590 "khaki": [240, 230, 140],
1591 "lavender": [230, 230, 250],
1592 "lavenderblush": [255, 240, 245],
1593 "lawngreen": [124, 252, 0],
1594 "lemonchiffon": [255, 250, 205],
1595 "lightblue": [173, 216, 230],
1596 "lightcoral": [240, 128, 128],
1597 "lightcyan": [224, 255, 255],
1598 "lightgoldenrodyellow": [250, 250, 210],
1599 "lightgray": [211, 211, 211],
1600 "lightgreen": [144, 238, 144],
1601 "lightgrey": [211, 211, 211],
1602 "lightpink": [255, 182, 193],
1603 "lightsalmon": [255, 160, 122],
1604 "lightseagreen": [32, 178, 170],
1605 "lightskyblue": [135, 206, 250],
1606 "lightslategray": [119, 136, 153],
1607 "lightslategrey": [119, 136, 153],
1608 "lightsteelblue": [176, 196, 222],
1609 "lightyellow": [255, 255, 224],
1610 "lime": [0, 255, 0],
1611 "limegreen": [50, 205, 50],
1612 "linen": [250, 240, 230],
1613 "magenta": [255, 0, 255],
1614 "maroon": [128, 0, 0],
1615 "mediumaquamarine": [102, 205, 170],
1616 "mediumblue": [0, 0, 205],
1617 "mediumorchid": [186, 85, 211],
1618 "mediumpurple": [147, 112, 219],
1619 "mediumseagreen": [60, 179, 113],
1620 "mediumslateblue": [123, 104, 238],
1621 "mediumspringgreen": [0, 250, 154],
1622 "mediumturquoise": [72, 209, 204],
1623 "mediumvioletred": [199, 21, 133],
1624 "midnightblue": [25, 25, 112],
1625 "mintcream": [245, 255, 250],
1626 "mistyrose": [255, 228, 225],
1627 "moccasin": [255, 228, 181],
1628 "navajowhite": [255, 222, 173],
1629 "navy": [0, 0, 128],
1630 "oldlace": [253, 245, 230],
1631 "olive": [128, 128, 0],
1632 "olivedrab": [107, 142, 35],
1633 "orange": [255, 165, 0],
1634 "orangered": [255, 69, 0],
1635 "orchid": [218, 112, 214],
1636 "palegoldenrod": [238, 232, 170],
1637 "palegreen": [152, 251, 152],
1638 "paleturquoise": [175, 238, 238],
1639 "palevioletred": [219, 112, 147],
1640 "papayawhip": [255, 239, 213],
1641 "peachpuff": [255, 218, 185],
1642 "peru": [205, 133, 63],
1643 "pink": [255, 192, 203],
1644 "plum": [221, 160, 221],
1645 "powderblue": [176, 224, 230],
1646 "purple": [128, 0, 128],
1647 "rebeccapurple": [102, 51, 153],
1649 "rosybrown": [188, 143, 143],
1650 "royalblue": [65, 105, 225],
1651 "saddlebrown": [139, 69, 19],
1652 "salmon": [250, 128, 114],
1653 "sandybrown": [244, 164, 96],
1654 "seagreen": [46, 139, 87],
1655 "seashell": [255, 245, 238],
1656 "sienna": [160, 82, 45],
1657 "silver": [192, 192, 192],
1658 "skyblue": [135, 206, 235],
1659 "slateblue": [106, 90, 205],
1660 "slategray": [112, 128, 144],
1661 "slategrey": [112, 128, 144],
1662 "snow": [255, 250, 250],
1663 "springgreen": [0, 255, 127],
1664 "steelblue": [70, 130, 180],
1665 "tan": [210, 180, 140],
1666 "teal": [0, 128, 128],
1667 "thistle": [216, 191, 216],
1668 "tomato": [255, 99, 71],
1669 "turquoise": [64, 224, 208],
1670 "violet": [238, 130, 238],
1671 "wheat": [245, 222, 179],
1672 "white": [255, 255, 255],
1673 "whitesmoke": [245, 245, 245],
1674 "yellow": [255, 255, 0],
1675 "yellowgreen": [154, 205, 50]
1678 },{}],6:[function(require,module,exports){
1680 //! version : 2.18.1
1681 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
1685 ;(function (global, factory) {
1686 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
1687 typeof define === 'function' && define.amd ? define(factory) :
1688 global.moment = factory()
1689 }(this, (function () { 'use strict';
1694 return hookCallback.apply(null, arguments);
1697 // This is done to register the method called with moment()
1698 // without creating circular dependencies.
1699 function setHookCallback (callback) {
1700 hookCallback = callback;
1703 function isArray(input) {
1704 return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
1707 function isObject(input) {
1708 // IE8 will treat undefined and null as object if it wasn't for
1710 return input != null && Object.prototype.toString.call(input) === '[object Object]';
1713 function isObjectEmpty(obj) {
1716 // even if its not own property I'd still call it non-empty
1722 function isUndefined(input) {
1723 return input === void 0;
1726 function isNumber(input) {
1727 return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
1730 function isDate(input) {
1731 return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
1734 function map(arr, fn) {
1736 for (i = 0; i < arr.length; ++i) {
1737 res.push(fn(arr[i], i));
1742 function hasOwnProp(a, b) {
1743 return Object.prototype.hasOwnProperty.call(a, b);
1746 function extend(a, b) {
1748 if (hasOwnProp(b, i)) {
1753 if (hasOwnProp(b, 'toString')) {
1754 a.toString = b.toString;
1757 if (hasOwnProp(b, 'valueOf')) {
1758 a.valueOf = b.valueOf;
1764 function createUTC (input, format, locale, strict) {
1765 return createLocalOrUTC(input, format, locale, strict, true).utc();
1768 function defaultParsingFlags() {
1769 // We need to deep clone this object.
1777 invalidMonth : null,
1778 invalidFormat : false,
1779 userInvalidated : false,
1781 parsedDateParts : [],
1784 weekdayMismatch : false
1788 function getParsingFlags(m) {
1789 if (m._pf == null) {
1790 m._pf = defaultParsingFlags();
1796 if (Array.prototype.some) {
1797 some = Array.prototype.some;
1799 some = function (fun) {
1800 var t = Object(this);
1801 var len = t.length >>> 0;
1803 for (var i = 0; i < len; i++) {
1804 if (i in t && fun.call(this, t[i], i, t)) {
1815 function isValid(m) {
1816 if (m._isValid == null) {
1817 var flags = getParsingFlags(m);
1818 var parsedParts = some$1.call(flags.parsedDateParts, function (i) {
1821 var isNowValid = !isNaN(m._d.getTime()) &&
1822 flags.overflow < 0 &&
1824 !flags.invalidMonth &&
1825 !flags.invalidWeekday &&
1827 !flags.invalidFormat &&
1828 !flags.userInvalidated &&
1829 (!flags.meridiem || (flags.meridiem && parsedParts));
1832 isNowValid = isNowValid &&
1833 flags.charsLeftOver === 0 &&
1834 flags.unusedTokens.length === 0 &&
1835 flags.bigHour === undefined;
1838 if (Object.isFrozen == null || !Object.isFrozen(m)) {
1839 m._isValid = isNowValid;
1848 function createInvalid (flags) {
1849 var m = createUTC(NaN);
1850 if (flags != null) {
1851 extend(getParsingFlags(m), flags);
1854 getParsingFlags(m).userInvalidated = true;
1860 // Plugins that add properties should also add the key here (null value),
1861 // so we can properly clone ourselves.
1862 var momentProperties = hooks.momentProperties = [];
1864 function copyConfig(to, from) {
1867 if (!isUndefined(from._isAMomentObject)) {
1868 to._isAMomentObject = from._isAMomentObject;
1870 if (!isUndefined(from._i)) {
1873 if (!isUndefined(from._f)) {
1876 if (!isUndefined(from._l)) {
1879 if (!isUndefined(from._strict)) {
1880 to._strict = from._strict;
1882 if (!isUndefined(from._tzm)) {
1883 to._tzm = from._tzm;
1885 if (!isUndefined(from._isUTC)) {
1886 to._isUTC = from._isUTC;
1888 if (!isUndefined(from._offset)) {
1889 to._offset = from._offset;
1891 if (!isUndefined(from._pf)) {
1892 to._pf = getParsingFlags(from);
1894 if (!isUndefined(from._locale)) {
1895 to._locale = from._locale;
1898 if (momentProperties.length > 0) {
1899 for (i = 0; i < momentProperties.length; i++) {
1900 prop = momentProperties[i];
1902 if (!isUndefined(val)) {
1911 var updateInProgress = false;
1913 // Moment prototype object
1914 function Moment(config) {
1915 copyConfig(this, config);
1916 this._d = new Date(config._d != null ? config._d.getTime() : NaN);
1917 if (!this.isValid()) {
1918 this._d = new Date(NaN);
1920 // Prevent infinite loop in case updateOffset creates new moment
1922 if (updateInProgress === false) {
1923 updateInProgress = true;
1924 hooks.updateOffset(this);
1925 updateInProgress = false;
1929 function isMoment (obj) {
1930 return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
1933 function absFloor (number) {
1936 return Math.ceil(number) || 0;
1938 return Math.floor(number);
1942 function toInt(argumentForCoercion) {
1943 var coercedNumber = +argumentForCoercion,
1946 if (coercedNumber !== 0 && isFinite(coercedNumber)) {
1947 value = absFloor(coercedNumber);
1953 // compare two arrays, return the number of differences
1954 function compareArrays(array1, array2, dontConvert) {
1955 var len = Math.min(array1.length, array2.length),
1956 lengthDiff = Math.abs(array1.length - array2.length),
1959 for (i = 0; i < len; i++) {
1960 if ((dontConvert && array1[i] !== array2[i]) ||
1961 (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
1965 return diffs + lengthDiff;
1968 function warn(msg) {
1969 if (hooks.suppressDeprecationWarnings === false &&
1970 (typeof console !== 'undefined') && console.warn) {
1971 console.warn('Deprecation warning: ' + msg);
1975 function deprecate(msg, fn) {
1976 var firstTime = true;
1978 return extend(function () {
1979 if (hooks.deprecationHandler != null) {
1980 hooks.deprecationHandler(null, msg);
1985 for (var i = 0; i < arguments.length; i++) {
1987 if (typeof arguments[i] === 'object') {
1988 arg += '\n[' + i + '] ';
1989 for (var key in arguments[0]) {
1990 arg += key + ': ' + arguments[0][key] + ', ';
1992 arg = arg.slice(0, -2); // Remove trailing comma and space
1998 warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
2001 return fn.apply(this, arguments);
2005 var deprecations = {};
2007 function deprecateSimple(name, msg) {
2008 if (hooks.deprecationHandler != null) {
2009 hooks.deprecationHandler(name, msg);
2011 if (!deprecations[name]) {
2013 deprecations[name] = true;
2017 hooks.suppressDeprecationWarnings = false;
2018 hooks.deprecationHandler = null;
2020 function isFunction(input) {
2021 return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
2024 function set (config) {
2028 if (isFunction(prop)) {
2031 this['_' + i] = prop;
2034 this._config = config;
2035 // Lenient ordinal parsing accepts just a number in addition to
2036 // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
2037 // TODO: Remove "ordinalParse" fallback in next major release.
2038 this._dayOfMonthOrdinalParseLenient = new RegExp(
2039 (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
2040 '|' + (/\d{1,2}/).source);
2043 function mergeConfigs(parentConfig, childConfig) {
2044 var res = extend({}, parentConfig), prop;
2045 for (prop in childConfig) {
2046 if (hasOwnProp(childConfig, prop)) {
2047 if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
2049 extend(res[prop], parentConfig[prop]);
2050 extend(res[prop], childConfig[prop]);
2051 } else if (childConfig[prop] != null) {
2052 res[prop] = childConfig[prop];
2058 for (prop in parentConfig) {
2059 if (hasOwnProp(parentConfig, prop) &&
2060 !hasOwnProp(childConfig, prop) &&
2061 isObject(parentConfig[prop])) {
2062 // make sure changes to properties don't modify parent config
2063 res[prop] = extend({}, res[prop]);
2069 function Locale(config) {
2070 if (config != null) {
2080 keys = function (obj) {
2083 if (hasOwnProp(obj, i)) {
2093 var defaultCalendar = {
2094 sameDay : '[Today at] LT',
2095 nextDay : '[Tomorrow at] LT',
2096 nextWeek : 'dddd [at] LT',
2097 lastDay : '[Yesterday at] LT',
2098 lastWeek : '[Last] dddd [at] LT',
2102 function calendar (key, mom, now) {
2103 var output = this._calendar[key] || this._calendar['sameElse'];
2104 return isFunction(output) ? output.call(mom, now) : output;
2107 var defaultLongDateFormat = {
2111 LL : 'MMMM D, YYYY',
2112 LLL : 'MMMM D, YYYY h:mm A',
2113 LLLL : 'dddd, MMMM D, YYYY h:mm A'
2116 function longDateFormat (key) {
2117 var format = this._longDateFormat[key],
2118 formatUpper = this._longDateFormat[key.toUpperCase()];
2120 if (format || !formatUpper) {
2124 this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
2125 return val.slice(1);
2128 return this._longDateFormat[key];
2131 var defaultInvalidDate = 'Invalid date';
2133 function invalidDate () {
2134 return this._invalidDate;
2137 var defaultOrdinal = '%d';
2138 var defaultDayOfMonthOrdinalParse = /\d{1,2}/;
2140 function ordinal (number) {
2141 return this._ordinal.replace('%d', number);
2144 var defaultRelativeTime = {
2147 s : 'a few seconds',
2161 function relativeTime (number, withoutSuffix, string, isFuture) {
2162 var output = this._relativeTime[string];
2163 return (isFunction(output)) ?
2164 output(number, withoutSuffix, string, isFuture) :
2165 output.replace(/%d/i, number);
2168 function pastFuture (diff, output) {
2169 var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
2170 return isFunction(format) ? format(output) : format.replace(/%s/i, output);
2175 function addUnitAlias (unit, shorthand) {
2176 var lowerCase = unit.toLowerCase();
2177 aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
2180 function normalizeUnits(units) {
2181 return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
2184 function normalizeObjectUnits(inputObject) {
2185 var normalizedInput = {},
2189 for (prop in inputObject) {
2190 if (hasOwnProp(inputObject, prop)) {
2191 normalizedProp = normalizeUnits(prop);
2192 if (normalizedProp) {
2193 normalizedInput[normalizedProp] = inputObject[prop];
2198 return normalizedInput;
2201 var priorities = {};
2203 function addUnitPriority(unit, priority) {
2204 priorities[unit] = priority;
2207 function getPrioritizedUnits(unitsObj) {
2209 for (var u in unitsObj) {
2210 units.push({unit: u, priority: priorities[u]});
2212 units.sort(function (a, b) {
2213 return a.priority - b.priority;
2218 function makeGetSet (unit, keepTime) {
2219 return function (value) {
2220 if (value != null) {
2221 set$1(this, unit, value);
2222 hooks.updateOffset(this, keepTime);
2225 return get(this, unit);
2230 function get (mom, unit) {
2231 return mom.isValid() ?
2232 mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
2235 function set$1 (mom, unit, value) {
2236 if (mom.isValid()) {
2237 mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
2243 function stringGet (units) {
2244 units = normalizeUnits(units);
2245 if (isFunction(this[units])) {
2246 return this[units]();
2252 function stringSet (units, value) {
2253 if (typeof units === 'object') {
2254 units = normalizeObjectUnits(units);
2255 var prioritized = getPrioritizedUnits(units);
2256 for (var i = 0; i < prioritized.length; i++) {
2257 this[prioritized[i].unit](units[prioritized[i].unit]);
2260 units = normalizeUnits(units);
2261 if (isFunction(this[units])) {
2262 return this[units](value);
2268 function zeroFill(number, targetLength, forceSign) {
2269 var absNumber = '' + Math.abs(number),
2270 zerosToFill = targetLength - absNumber.length,
2272 return (sign ? (forceSign ? '+' : '') : '-') +
2273 Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
2276 var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
2278 var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
2280 var formatFunctions = {};
2282 var formatTokenFunctions = {};
2285 // padded: ['MM', 2]
2287 // callback: function () { this.month() + 1 }
2288 function addFormatToken (token, padded, ordinal, callback) {
2289 var func = callback;
2290 if (typeof callback === 'string') {
2291 func = function () {
2292 return this[callback]();
2296 formatTokenFunctions[token] = func;
2299 formatTokenFunctions[padded[0]] = function () {
2300 return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
2304 formatTokenFunctions[ordinal] = function () {
2305 return this.localeData().ordinal(func.apply(this, arguments), token);
2310 function removeFormattingTokens(input) {
2311 if (input.match(/\[[\s\S]/)) {
2312 return input.replace(/^\[|\]$/g, '');
2314 return input.replace(/\\/g, '');
2317 function makeFormatFunction(format) {
2318 var array = format.match(formattingTokens), i, length;
2320 for (i = 0, length = array.length; i < length; i++) {
2321 if (formatTokenFunctions[array[i]]) {
2322 array[i] = formatTokenFunctions[array[i]];
2324 array[i] = removeFormattingTokens(array[i]);
2328 return function (mom) {
2330 for (i = 0; i < length; i++) {
2331 output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
2337 // format date using native date object
2338 function formatMoment(m, format) {
2340 return m.localeData().invalidDate();
2343 format = expandFormat(format, m.localeData());
2344 formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
2346 return formatFunctions[format](m);
2349 function expandFormat(format, locale) {
2352 function replaceLongDateFormatTokens(input) {
2353 return locale.longDateFormat(input) || input;
2356 localFormattingTokens.lastIndex = 0;
2357 while (i >= 0 && localFormattingTokens.test(format)) {
2358 format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
2359 localFormattingTokens.lastIndex = 0;
2366 var match1 = /\d/; // 0 - 9
2367 var match2 = /\d\d/; // 00 - 99
2368 var match3 = /\d{3}/; // 000 - 999
2369 var match4 = /\d{4}/; // 0000 - 9999
2370 var match6 = /[+-]?\d{6}/; // -999999 - 999999
2371 var match1to2 = /\d\d?/; // 0 - 99
2372 var match3to4 = /\d\d\d\d?/; // 999 - 9999
2373 var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
2374 var match1to3 = /\d{1,3}/; // 0 - 999
2375 var match1to4 = /\d{1,4}/; // 0 - 9999
2376 var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
2378 var matchUnsigned = /\d+/; // 0 - inf
2379 var matchSigned = /[+-]?\d+/; // -inf - inf
2381 var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
2382 var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
2384 var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
2386 // any word (or two) characters or numbers including two/three word month in arabic.
2387 // includes scottish gaelic two word and hyphenated months
2388 var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;
2393 function addRegexToken (token, regex, strictRegex) {
2394 regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
2395 return (isStrict && strictRegex) ? strictRegex : regex;
2399 function getParseRegexForToken (token, config) {
2400 if (!hasOwnProp(regexes, token)) {
2401 return new RegExp(unescapeFormat(token));
2404 return regexes[token](config._strict, config._locale);
2407 // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
2408 function unescapeFormat(s) {
2409 return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
2410 return p1 || p2 || p3 || p4;
2414 function regexEscape(s) {
2415 return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
2420 function addParseToken (token, callback) {
2421 var i, func = callback;
2422 if (typeof token === 'string') {
2425 if (isNumber(callback)) {
2426 func = function (input, array) {
2427 array[callback] = toInt(input);
2430 for (i = 0; i < token.length; i++) {
2431 tokens[token[i]] = func;
2435 function addWeekParseToken (token, callback) {
2436 addParseToken(token, function (input, array, config, token) {
2437 config._w = config._w || {};
2438 callback(input, config._w, config, token);
2442 function addTimeToArrayFromToken(token, input, config) {
2443 if (input != null && hasOwnProp(tokens, token)) {
2444 tokens[token](input, config._a, config, token);
2454 var MILLISECOND = 6;
2460 if (Array.prototype.indexOf) {
2461 indexOf = Array.prototype.indexOf;
2463 indexOf = function (o) {
2466 for (i = 0; i < this.length; ++i) {
2467 if (this[i] === o) {
2475 var indexOf$1 = indexOf;
2477 function daysInMonth(year, month) {
2478 return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
2483 addFormatToken('M', ['MM', 2], 'Mo', function () {
2484 return this.month() + 1;
2487 addFormatToken('MMM', 0, 0, function (format) {
2488 return this.localeData().monthsShort(this, format);
2491 addFormatToken('MMMM', 0, 0, function (format) {
2492 return this.localeData().months(this, format);
2497 addUnitAlias('month', 'M');
2501 addUnitPriority('month', 8);
2505 addRegexToken('M', match1to2);
2506 addRegexToken('MM', match1to2, match2);
2507 addRegexToken('MMM', function (isStrict, locale) {
2508 return locale.monthsShortRegex(isStrict);
2510 addRegexToken('MMMM', function (isStrict, locale) {
2511 return locale.monthsRegex(isStrict);
2514 addParseToken(['M', 'MM'], function (input, array) {
2515 array[MONTH] = toInt(input) - 1;
2518 addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
2519 var month = config._locale.monthsParse(input, token, config._strict);
2520 // if we didn't find a month name, mark the date as invalid.
2521 if (month != null) {
2522 array[MONTH] = month;
2524 getParsingFlags(config).invalidMonth = input;
2530 var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
2531 var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
2532 function localeMonths (m, format) {
2534 return isArray(this._months) ? this._months :
2535 this._months['standalone'];
2537 return isArray(this._months) ? this._months[m.month()] :
2538 this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
2541 var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
2542 function localeMonthsShort (m, format) {
2544 return isArray(this._monthsShort) ? this._monthsShort :
2545 this._monthsShort['standalone'];
2547 return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
2548 this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
2551 function handleStrictParse(monthName, format, strict) {
2552 var i, ii, mom, llc = monthName.toLocaleLowerCase();
2553 if (!this._monthsParse) {
2555 this._monthsParse = [];
2556 this._longMonthsParse = [];
2557 this._shortMonthsParse = [];
2558 for (i = 0; i < 12; ++i) {
2559 mom = createUTC([2000, i]);
2560 this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
2561 this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
2566 if (format === 'MMM') {
2567 ii = indexOf$1.call(this._shortMonthsParse, llc);
2568 return ii !== -1 ? ii : null;
2570 ii = indexOf$1.call(this._longMonthsParse, llc);
2571 return ii !== -1 ? ii : null;
2574 if (format === 'MMM') {
2575 ii = indexOf$1.call(this._shortMonthsParse, llc);
2579 ii = indexOf$1.call(this._longMonthsParse, llc);
2580 return ii !== -1 ? ii : null;
2582 ii = indexOf$1.call(this._longMonthsParse, llc);
2586 ii = indexOf$1.call(this._shortMonthsParse, llc);
2587 return ii !== -1 ? ii : null;
2592 function localeMonthsParse (monthName, format, strict) {
2595 if (this._monthsParseExact) {
2596 return handleStrictParse.call(this, monthName, format, strict);
2599 if (!this._monthsParse) {
2600 this._monthsParse = [];
2601 this._longMonthsParse = [];
2602 this._shortMonthsParse = [];
2605 // TODO: add sorting
2606 // Sorting makes sure if one month (or abbr) is a prefix of another
2607 // see sorting in computeMonthsParse
2608 for (i = 0; i < 12; i++) {
2609 // make the regex if we don't have it already
2610 mom = createUTC([2000, i]);
2611 if (strict && !this._longMonthsParse[i]) {
2612 this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
2613 this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
2615 if (!strict && !this._monthsParse[i]) {
2616 regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
2617 this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
2620 if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
2622 } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
2624 } else if (!strict && this._monthsParse[i].test(monthName)) {
2632 function setMonth (mom, value) {
2635 if (!mom.isValid()) {
2640 if (typeof value === 'string') {
2641 if (/^\d+$/.test(value)) {
2642 value = toInt(value);
2644 value = mom.localeData().monthsParse(value);
2645 // TODO: Another silent failure?
2646 if (!isNumber(value)) {
2652 dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
2653 mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
2657 function getSetMonth (value) {
2658 if (value != null) {
2659 setMonth(this, value);
2660 hooks.updateOffset(this, true);
2663 return get(this, 'Month');
2667 function getDaysInMonth () {
2668 return daysInMonth(this.year(), this.month());
2671 var defaultMonthsShortRegex = matchWord;
2672 function monthsShortRegex (isStrict) {
2673 if (this._monthsParseExact) {
2674 if (!hasOwnProp(this, '_monthsRegex')) {
2675 computeMonthsParse.call(this);
2678 return this._monthsShortStrictRegex;
2680 return this._monthsShortRegex;
2683 if (!hasOwnProp(this, '_monthsShortRegex')) {
2684 this._monthsShortRegex = defaultMonthsShortRegex;
2686 return this._monthsShortStrictRegex && isStrict ?
2687 this._monthsShortStrictRegex : this._monthsShortRegex;
2691 var defaultMonthsRegex = matchWord;
2692 function monthsRegex (isStrict) {
2693 if (this._monthsParseExact) {
2694 if (!hasOwnProp(this, '_monthsRegex')) {
2695 computeMonthsParse.call(this);
2698 return this._monthsStrictRegex;
2700 return this._monthsRegex;
2703 if (!hasOwnProp(this, '_monthsRegex')) {
2704 this._monthsRegex = defaultMonthsRegex;
2706 return this._monthsStrictRegex && isStrict ?
2707 this._monthsStrictRegex : this._monthsRegex;
2711 function computeMonthsParse () {
2712 function cmpLenRev(a, b) {
2713 return b.length - a.length;
2716 var shortPieces = [], longPieces = [], mixedPieces = [],
2718 for (i = 0; i < 12; i++) {
2719 // make the regex if we don't have it already
2720 mom = createUTC([2000, i]);
2721 shortPieces.push(this.monthsShort(mom, ''));
2722 longPieces.push(this.months(mom, ''));
2723 mixedPieces.push(this.months(mom, ''));
2724 mixedPieces.push(this.monthsShort(mom, ''));
2726 // Sorting makes sure if one month (or abbr) is a prefix of another it
2727 // will match the longer piece.
2728 shortPieces.sort(cmpLenRev);
2729 longPieces.sort(cmpLenRev);
2730 mixedPieces.sort(cmpLenRev);
2731 for (i = 0; i < 12; i++) {
2732 shortPieces[i] = regexEscape(shortPieces[i]);
2733 longPieces[i] = regexEscape(longPieces[i]);
2735 for (i = 0; i < 24; i++) {
2736 mixedPieces[i] = regexEscape(mixedPieces[i]);
2739 this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
2740 this._monthsShortRegex = this._monthsRegex;
2741 this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
2742 this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
2747 addFormatToken('Y', 0, 0, function () {
2748 var y = this.year();
2749 return y <= 9999 ? '' + y : '+' + y;
2752 addFormatToken(0, ['YY', 2], 0, function () {
2753 return this.year() % 100;
2756 addFormatToken(0, ['YYYY', 4], 0, 'year');
2757 addFormatToken(0, ['YYYYY', 5], 0, 'year');
2758 addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
2762 addUnitAlias('year', 'y');
2766 addUnitPriority('year', 1);
2770 addRegexToken('Y', matchSigned);
2771 addRegexToken('YY', match1to2, match2);
2772 addRegexToken('YYYY', match1to4, match4);
2773 addRegexToken('YYYYY', match1to6, match6);
2774 addRegexToken('YYYYYY', match1to6, match6);
2776 addParseToken(['YYYYY', 'YYYYYY'], YEAR);
2777 addParseToken('YYYY', function (input, array) {
2778 array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
2780 addParseToken('YY', function (input, array) {
2781 array[YEAR] = hooks.parseTwoDigitYear(input);
2783 addParseToken('Y', function (input, array) {
2784 array[YEAR] = parseInt(input, 10);
2789 function daysInYear(year) {
2790 return isLeapYear(year) ? 366 : 365;
2793 function isLeapYear(year) {
2794 return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
2799 hooks.parseTwoDigitYear = function (input) {
2800 return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
2805 var getSetYear = makeGetSet('FullYear', true);
2807 function getIsLeapYear () {
2808 return isLeapYear(this.year());
2811 function createDate (y, m, d, h, M, s, ms) {
2812 // can't just apply() to create a date:
2813 // https://stackoverflow.com/q/181348
2814 var date = new Date(y, m, d, h, M, s, ms);
2816 // the date constructor remaps years 0-99 to 1900-1999
2817 if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
2818 date.setFullYear(y);
2823 function createUTCDate (y) {
2824 var date = new Date(Date.UTC.apply(null, arguments));
2826 // the Date.UTC function remaps years 0-99 to 1900-1999
2827 if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
2828 date.setUTCFullYear(y);
2833 // start-of-first-week - start-of-year
2834 function firstWeekOffset(year, dow, doy) {
2835 var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
2836 fwd = 7 + dow - doy,
2837 // first-week day local weekday -- which local weekday is fwd
2838 fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
2840 return -fwdlw + fwd - 1;
2843 // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
2844 function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
2845 var localWeekday = (7 + weekday - dow) % 7,
2846 weekOffset = firstWeekOffset(year, dow, doy),
2847 dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
2848 resYear, resDayOfYear;
2850 if (dayOfYear <= 0) {
2852 resDayOfYear = daysInYear(resYear) + dayOfYear;
2853 } else if (dayOfYear > daysInYear(year)) {
2855 resDayOfYear = dayOfYear - daysInYear(year);
2858 resDayOfYear = dayOfYear;
2863 dayOfYear: resDayOfYear
2867 function weekOfYear(mom, dow, doy) {
2868 var weekOffset = firstWeekOffset(mom.year(), dow, doy),
2869 week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
2873 resYear = mom.year() - 1;
2874 resWeek = week + weeksInYear(resYear, dow, doy);
2875 } else if (week > weeksInYear(mom.year(), dow, doy)) {
2876 resWeek = week - weeksInYear(mom.year(), dow, doy);
2877 resYear = mom.year() + 1;
2879 resYear = mom.year();
2889 function weeksInYear(year, dow, doy) {
2890 var weekOffset = firstWeekOffset(year, dow, doy),
2891 weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
2892 return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
2897 addFormatToken('w', ['ww', 2], 'wo', 'week');
2898 addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
2902 addUnitAlias('week', 'w');
2903 addUnitAlias('isoWeek', 'W');
2907 addUnitPriority('week', 5);
2908 addUnitPriority('isoWeek', 5);
2912 addRegexToken('w', match1to2);
2913 addRegexToken('ww', match1to2, match2);
2914 addRegexToken('W', match1to2);
2915 addRegexToken('WW', match1to2, match2);
2917 addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
2918 week[token.substr(0, 1)] = toInt(input);
2925 function localeWeek (mom) {
2926 return weekOfYear(mom, this._week.dow, this._week.doy).week;
2929 var defaultLocaleWeek = {
2930 dow : 0, // Sunday is the first day of the week.
2931 doy : 6 // The week that contains Jan 1st is the first week of the year.
2934 function localeFirstDayOfWeek () {
2935 return this._week.dow;
2938 function localeFirstDayOfYear () {
2939 return this._week.doy;
2944 function getSetWeek (input) {
2945 var week = this.localeData().week(this);
2946 return input == null ? week : this.add((input - week) * 7, 'd');
2949 function getSetISOWeek (input) {
2950 var week = weekOfYear(this, 1, 4).week;
2951 return input == null ? week : this.add((input - week) * 7, 'd');
2956 addFormatToken('d', 0, 'do', 'day');
2958 addFormatToken('dd', 0, 0, function (format) {
2959 return this.localeData().weekdaysMin(this, format);
2962 addFormatToken('ddd', 0, 0, function (format) {
2963 return this.localeData().weekdaysShort(this, format);
2966 addFormatToken('dddd', 0, 0, function (format) {
2967 return this.localeData().weekdays(this, format);
2970 addFormatToken('e', 0, 0, 'weekday');
2971 addFormatToken('E', 0, 0, 'isoWeekday');
2975 addUnitAlias('day', 'd');
2976 addUnitAlias('weekday', 'e');
2977 addUnitAlias('isoWeekday', 'E');
2980 addUnitPriority('day', 11);
2981 addUnitPriority('weekday', 11);
2982 addUnitPriority('isoWeekday', 11);
2986 addRegexToken('d', match1to2);
2987 addRegexToken('e', match1to2);
2988 addRegexToken('E', match1to2);
2989 addRegexToken('dd', function (isStrict, locale) {
2990 return locale.weekdaysMinRegex(isStrict);
2992 addRegexToken('ddd', function (isStrict, locale) {
2993 return locale.weekdaysShortRegex(isStrict);
2995 addRegexToken('dddd', function (isStrict, locale) {
2996 return locale.weekdaysRegex(isStrict);
2999 addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
3000 var weekday = config._locale.weekdaysParse(input, token, config._strict);
3001 // if we didn't get a weekday name, mark the date as invalid
3002 if (weekday != null) {
3005 getParsingFlags(config).invalidWeekday = input;
3009 addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
3010 week[token] = toInt(input);
3015 function parseWeekday(input, locale) {
3016 if (typeof input !== 'string') {
3020 if (!isNaN(input)) {
3021 return parseInt(input, 10);
3024 input = locale.weekdaysParse(input);
3025 if (typeof input === 'number') {
3032 function parseIsoWeekday(input, locale) {
3033 if (typeof input === 'string') {
3034 return locale.weekdaysParse(input) % 7 || 7;
3036 return isNaN(input) ? null : input;
3041 var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
3042 function localeWeekdays (m, format) {
3044 return isArray(this._weekdays) ? this._weekdays :
3045 this._weekdays['standalone'];
3047 return isArray(this._weekdays) ? this._weekdays[m.day()] :
3048 this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
3051 var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
3052 function localeWeekdaysShort (m) {
3053 return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
3056 var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
3057 function localeWeekdaysMin (m) {
3058 return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
3061 function handleStrictParse$1(weekdayName, format, strict) {
3062 var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
3063 if (!this._weekdaysParse) {
3064 this._weekdaysParse = [];
3065 this._shortWeekdaysParse = [];
3066 this._minWeekdaysParse = [];
3068 for (i = 0; i < 7; ++i) {
3069 mom = createUTC([2000, 1]).day(i);
3070 this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
3071 this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
3072 this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
3077 if (format === 'dddd') {
3078 ii = indexOf$1.call(this._weekdaysParse, llc);
3079 return ii !== -1 ? ii : null;
3080 } else if (format === 'ddd') {
3081 ii = indexOf$1.call(this._shortWeekdaysParse, llc);
3082 return ii !== -1 ? ii : null;
3084 ii = indexOf$1.call(this._minWeekdaysParse, llc);
3085 return ii !== -1 ? ii : null;
3088 if (format === 'dddd') {
3089 ii = indexOf$1.call(this._weekdaysParse, llc);
3093 ii = indexOf$1.call(this._shortWeekdaysParse, llc);
3097 ii = indexOf$1.call(this._minWeekdaysParse, llc);
3098 return ii !== -1 ? ii : null;
3099 } else if (format === 'ddd') {
3100 ii = indexOf$1.call(this._shortWeekdaysParse, llc);
3104 ii = indexOf$1.call(this._weekdaysParse, llc);
3108 ii = indexOf$1.call(this._minWeekdaysParse, llc);
3109 return ii !== -1 ? ii : null;
3111 ii = indexOf$1.call(this._minWeekdaysParse, llc);
3115 ii = indexOf$1.call(this._weekdaysParse, llc);
3119 ii = indexOf$1.call(this._shortWeekdaysParse, llc);
3120 return ii !== -1 ? ii : null;
3125 function localeWeekdaysParse (weekdayName, format, strict) {
3128 if (this._weekdaysParseExact) {
3129 return handleStrictParse$1.call(this, weekdayName, format, strict);
3132 if (!this._weekdaysParse) {
3133 this._weekdaysParse = [];
3134 this._minWeekdaysParse = [];
3135 this._shortWeekdaysParse = [];
3136 this._fullWeekdaysParse = [];
3139 for (i = 0; i < 7; i++) {
3140 // make the regex if we don't have it already
3142 mom = createUTC([2000, 1]).day(i);
3143 if (strict && !this._fullWeekdaysParse[i]) {
3144 this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i');
3145 this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i');
3146 this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i');
3148 if (!this._weekdaysParse[i]) {
3149 regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
3150 this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
3153 if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
3155 } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
3157 } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
3159 } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
3167 function getSetDayOfWeek (input) {
3168 if (!this.isValid()) {
3169 return input != null ? this : NaN;
3171 var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
3172 if (input != null) {
3173 input = parseWeekday(input, this.localeData());
3174 return this.add(input - day, 'd');
3180 function getSetLocaleDayOfWeek (input) {
3181 if (!this.isValid()) {
3182 return input != null ? this : NaN;
3184 var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
3185 return input == null ? weekday : this.add(input - weekday, 'd');
3188 function getSetISODayOfWeek (input) {
3189 if (!this.isValid()) {
3190 return input != null ? this : NaN;
3193 // behaves the same as moment#day except
3194 // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
3195 // as a setter, sunday should belong to the previous week.
3197 if (input != null) {
3198 var weekday = parseIsoWeekday(input, this.localeData());
3199 return this.day(this.day() % 7 ? weekday : weekday - 7);
3201 return this.day() || 7;
3205 var defaultWeekdaysRegex = matchWord;
3206 function weekdaysRegex (isStrict) {
3207 if (this._weekdaysParseExact) {
3208 if (!hasOwnProp(this, '_weekdaysRegex')) {
3209 computeWeekdaysParse.call(this);
3212 return this._weekdaysStrictRegex;
3214 return this._weekdaysRegex;
3217 if (!hasOwnProp(this, '_weekdaysRegex')) {
3218 this._weekdaysRegex = defaultWeekdaysRegex;
3220 return this._weekdaysStrictRegex && isStrict ?
3221 this._weekdaysStrictRegex : this._weekdaysRegex;
3225 var defaultWeekdaysShortRegex = matchWord;
3226 function weekdaysShortRegex (isStrict) {
3227 if (this._weekdaysParseExact) {
3228 if (!hasOwnProp(this, '_weekdaysRegex')) {
3229 computeWeekdaysParse.call(this);
3232 return this._weekdaysShortStrictRegex;
3234 return this._weekdaysShortRegex;
3237 if (!hasOwnProp(this, '_weekdaysShortRegex')) {
3238 this._weekdaysShortRegex = defaultWeekdaysShortRegex;
3240 return this._weekdaysShortStrictRegex && isStrict ?
3241 this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
3245 var defaultWeekdaysMinRegex = matchWord;
3246 function weekdaysMinRegex (isStrict) {
3247 if (this._weekdaysParseExact) {
3248 if (!hasOwnProp(this, '_weekdaysRegex')) {
3249 computeWeekdaysParse.call(this);
3252 return this._weekdaysMinStrictRegex;
3254 return this._weekdaysMinRegex;
3257 if (!hasOwnProp(this, '_weekdaysMinRegex')) {
3258 this._weekdaysMinRegex = defaultWeekdaysMinRegex;
3260 return this._weekdaysMinStrictRegex && isStrict ?
3261 this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
3266 function computeWeekdaysParse () {
3267 function cmpLenRev(a, b) {
3268 return b.length - a.length;
3271 var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
3272 i, mom, minp, shortp, longp;
3273 for (i = 0; i < 7; i++) {
3274 // make the regex if we don't have it already
3275 mom = createUTC([2000, 1]).day(i);
3276 minp = this.weekdaysMin(mom, '');
3277 shortp = this.weekdaysShort(mom, '');
3278 longp = this.weekdays(mom, '');
3279 minPieces.push(minp);
3280 shortPieces.push(shortp);
3281 longPieces.push(longp);
3282 mixedPieces.push(minp);
3283 mixedPieces.push(shortp);
3284 mixedPieces.push(longp);
3286 // Sorting makes sure if one weekday (or abbr) is a prefix of another it
3287 // will match the longer piece.
3288 minPieces.sort(cmpLenRev);
3289 shortPieces.sort(cmpLenRev);
3290 longPieces.sort(cmpLenRev);
3291 mixedPieces.sort(cmpLenRev);
3292 for (i = 0; i < 7; i++) {
3293 shortPieces[i] = regexEscape(shortPieces[i]);
3294 longPieces[i] = regexEscape(longPieces[i]);
3295 mixedPieces[i] = regexEscape(mixedPieces[i]);
3298 this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
3299 this._weekdaysShortRegex = this._weekdaysRegex;
3300 this._weekdaysMinRegex = this._weekdaysRegex;
3302 this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
3303 this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
3304 this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
3309 function hFormat() {
3310 return this.hours() % 12 || 12;
3313 function kFormat() {
3314 return this.hours() || 24;
3317 addFormatToken('H', ['HH', 2], 0, 'hour');
3318 addFormatToken('h', ['hh', 2], 0, hFormat);
3319 addFormatToken('k', ['kk', 2], 0, kFormat);
3321 addFormatToken('hmm', 0, 0, function () {
3322 return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
3325 addFormatToken('hmmss', 0, 0, function () {
3326 return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
3327 zeroFill(this.seconds(), 2);
3330 addFormatToken('Hmm', 0, 0, function () {
3331 return '' + this.hours() + zeroFill(this.minutes(), 2);
3334 addFormatToken('Hmmss', 0, 0, function () {
3335 return '' + this.hours() + zeroFill(this.minutes(), 2) +
3336 zeroFill(this.seconds(), 2);
3339 function meridiem (token, lowercase) {
3340 addFormatToken(token, 0, 0, function () {
3341 return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
3345 meridiem('a', true);
3346 meridiem('A', false);
3350 addUnitAlias('hour', 'h');
3353 addUnitPriority('hour', 13);
3357 function matchMeridiem (isStrict, locale) {
3358 return locale._meridiemParse;
3361 addRegexToken('a', matchMeridiem);
3362 addRegexToken('A', matchMeridiem);
3363 addRegexToken('H', match1to2);
3364 addRegexToken('h', match1to2);
3365 addRegexToken('k', match1to2);
3366 addRegexToken('HH', match1to2, match2);
3367 addRegexToken('hh', match1to2, match2);
3368 addRegexToken('kk', match1to2, match2);
3370 addRegexToken('hmm', match3to4);
3371 addRegexToken('hmmss', match5to6);
3372 addRegexToken('Hmm', match3to4);
3373 addRegexToken('Hmmss', match5to6);
3375 addParseToken(['H', 'HH'], HOUR);
3376 addParseToken(['k', 'kk'], function (input, array, config) {
3377 var kInput = toInt(input);
3378 array[HOUR] = kInput === 24 ? 0 : kInput;
3380 addParseToken(['a', 'A'], function (input, array, config) {
3381 config._isPm = config._locale.isPM(input);
3382 config._meridiem = input;
3384 addParseToken(['h', 'hh'], function (input, array, config) {
3385 array[HOUR] = toInt(input);
3386 getParsingFlags(config).bigHour = true;
3388 addParseToken('hmm', function (input, array, config) {
3389 var pos = input.length - 2;
3390 array[HOUR] = toInt(input.substr(0, pos));
3391 array[MINUTE] = toInt(input.substr(pos));
3392 getParsingFlags(config).bigHour = true;
3394 addParseToken('hmmss', function (input, array, config) {
3395 var pos1 = input.length - 4;
3396 var pos2 = input.length - 2;
3397 array[HOUR] = toInt(input.substr(0, pos1));
3398 array[MINUTE] = toInt(input.substr(pos1, 2));
3399 array[SECOND] = toInt(input.substr(pos2));
3400 getParsingFlags(config).bigHour = true;
3402 addParseToken('Hmm', function (input, array, config) {
3403 var pos = input.length - 2;
3404 array[HOUR] = toInt(input.substr(0, pos));
3405 array[MINUTE] = toInt(input.substr(pos));
3407 addParseToken('Hmmss', function (input, array, config) {
3408 var pos1 = input.length - 4;
3409 var pos2 = input.length - 2;
3410 array[HOUR] = toInt(input.substr(0, pos1));
3411 array[MINUTE] = toInt(input.substr(pos1, 2));
3412 array[SECOND] = toInt(input.substr(pos2));
3417 function localeIsPM (input) {
3418 // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
3419 // Using charAt should be more compatible.
3420 return ((input + '').toLowerCase().charAt(0) === 'p');
3423 var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
3424 function localeMeridiem (hours, minutes, isLower) {
3426 return isLower ? 'pm' : 'PM';
3428 return isLower ? 'am' : 'AM';
3435 // Setting the hour should keep the time, because the user explicitly
3436 // specified which hour he wants. So trying to maintain the same hour (in
3437 // a new timezone) makes sense. Adding/subtracting hours does not follow
3439 var getSetHour = makeGetSet('Hours', true);
3446 calendar: defaultCalendar,
3447 longDateFormat: defaultLongDateFormat,
3448 invalidDate: defaultInvalidDate,
3449 ordinal: defaultOrdinal,
3450 dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
3451 relativeTime: defaultRelativeTime,
3453 months: defaultLocaleMonths,
3454 monthsShort: defaultLocaleMonthsShort,
3456 week: defaultLocaleWeek,
3458 weekdays: defaultLocaleWeekdays,
3459 weekdaysMin: defaultLocaleWeekdaysMin,
3460 weekdaysShort: defaultLocaleWeekdaysShort,
3462 meridiemParse: defaultLocaleMeridiemParse
3465 // internal storage for locale config files
3467 var localeFamilies = {};
3470 function normalizeLocale(key) {
3471 return key ? key.toLowerCase().replace('_', '-') : key;
3474 // pick the locale from the array
3475 // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
3476 // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
3477 function chooseLocale(names) {
3478 var i = 0, j, next, locale, split;
3480 while (i < names.length) {
3481 split = normalizeLocale(names[i]).split('-');
3483 next = normalizeLocale(names[i + 1]);
3484 next = next ? next.split('-') : null;
3486 locale = loadLocale(split.slice(0, j).join('-'));
3490 if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
3491 //the next array item is better than a shallower substring of this one
3501 function loadLocale(name) {
3502 var oldLocale = null;
3503 // TODO: Find a better way to register and load all the locales in Node
3504 if (!locales[name] && (typeof module !== 'undefined') &&
3505 module && module.exports) {
3507 oldLocale = globalLocale._abbr;
3508 require('./locale/' + name);
3509 // because defineLocale currently also sets the global locale, we
3510 // want to undo that for lazy loaded locales
3511 getSetGlobalLocale(oldLocale);
3514 return locales[name];
3517 // This function will load locale and then set the global locale. If
3518 // no arguments are passed in, it will simply return the current global
3520 function getSetGlobalLocale (key, values) {
3523 if (isUndefined(values)) {
3524 data = getLocale(key);
3527 data = defineLocale(key, values);
3531 // moment.duration._locale = moment._locale = data;
3532 globalLocale = data;
3536 return globalLocale._abbr;
3539 function defineLocale (name, config) {
3540 if (config !== null) {
3541 var parentConfig = baseConfig;
3543 if (locales[name] != null) {
3544 deprecateSimple('defineLocaleOverride',
3545 'use moment.updateLocale(localeName, config) to change ' +
3546 'an existing locale. moment.defineLocale(localeName, ' +
3547 'config) should only be used for creating a new locale ' +
3548 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
3549 parentConfig = locales[name]._config;
3550 } else if (config.parentLocale != null) {
3551 if (locales[config.parentLocale] != null) {
3552 parentConfig = locales[config.parentLocale]._config;
3554 if (!localeFamilies[config.parentLocale]) {
3555 localeFamilies[config.parentLocale] = [];
3557 localeFamilies[config.parentLocale].push({
3564 locales[name] = new Locale(mergeConfigs(parentConfig, config));
3566 if (localeFamilies[name]) {
3567 localeFamilies[name].forEach(function (x) {
3568 defineLocale(x.name, x.config);
3572 // backwards compat for now: also set the locale
3573 // make sure we set the locale AFTER all child locales have been
3574 // created, so we won't end up with the child locale set.
3575 getSetGlobalLocale(name);
3578 return locales[name];
3580 // useful for testing
3581 delete locales[name];
3586 function updateLocale(name, config) {
3587 if (config != null) {
3588 var locale, parentConfig = baseConfig;
3590 if (locales[name] != null) {
3591 parentConfig = locales[name]._config;
3593 config = mergeConfigs(parentConfig, config);
3594 locale = new Locale(config);
3595 locale.parentLocale = locales[name];
3596 locales[name] = locale;
3598 // backwards compat for now: also set the locale
3599 getSetGlobalLocale(name);
3601 // pass null for config to unupdate, useful for tests
3602 if (locales[name] != null) {
3603 if (locales[name].parentLocale != null) {
3604 locales[name] = locales[name].parentLocale;
3605 } else if (locales[name] != null) {
3606 delete locales[name];
3610 return locales[name];
3613 // returns locale data
3614 function getLocale (key) {
3617 if (key && key._locale && key._locale._abbr) {
3618 key = key._locale._abbr;
3622 return globalLocale;
3625 if (!isArray(key)) {
3626 //short-circuit everything else
3627 locale = loadLocale(key);
3634 return chooseLocale(key);
3637 function listLocales() {
3638 return keys$1(locales);
3641 function checkOverflow (m) {
3645 if (a && getParsingFlags(m).overflow === -2) {
3647 a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
3648 a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
3649 a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
3650 a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
3651 a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
3652 a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
3655 if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
3658 if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
3661 if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
3665 getParsingFlags(m).overflow = overflow;
3672 // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
3673 var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
3674 var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
3676 var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
3679 ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
3680 ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
3681 ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
3682 ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
3683 ['YYYY-DDD', /\d{4}-\d{3}/],
3684 ['YYYY-MM', /\d{4}-\d\d/, false],
3685 ['YYYYYYMMDD', /[+-]\d{10}/],
3686 ['YYYYMMDD', /\d{8}/],
3687 // YYYYMM is NOT allowed by the standard
3688 ['GGGG[W]WWE', /\d{4}W\d{3}/],
3689 ['GGGG[W]WW', /\d{4}W\d{2}/, false],
3690 ['YYYYDDD', /\d{7}/]
3693 // iso time formats and regexes
3695 ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
3696 ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
3697 ['HH:mm:ss', /\d\d:\d\d:\d\d/],
3698 ['HH:mm', /\d\d:\d\d/],
3699 ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
3700 ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
3701 ['HHmmss', /\d\d\d\d\d\d/],
3702 ['HHmm', /\d\d\d\d/],
3706 var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
3708 // date from iso format
3709 function configFromISO(config) {
3712 match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
3713 allowTime, dateFormat, timeFormat, tzFormat;
3716 getParsingFlags(config).iso = true;
3718 for (i = 0, l = isoDates.length; i < l; i++) {
3719 if (isoDates[i][1].exec(match[1])) {
3720 dateFormat = isoDates[i][0];
3721 allowTime = isoDates[i][2] !== false;
3725 if (dateFormat == null) {
3726 config._isValid = false;
3730 for (i = 0, l = isoTimes.length; i < l; i++) {
3731 if (isoTimes[i][1].exec(match[3])) {
3732 // match[2] should be 'T' or space
3733 timeFormat = (match[2] || ' ') + isoTimes[i][0];
3737 if (timeFormat == null) {
3738 config._isValid = false;
3742 if (!allowTime && timeFormat != null) {
3743 config._isValid = false;
3747 if (tzRegex.exec(match[4])) {
3750 config._isValid = false;
3754 config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
3755 configFromStringAndFormat(config);
3757 config._isValid = false;
3761 // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
3762 var basicRfcRegex = /^((?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d?\d\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(?:\d\d)?\d\d\s)(\d\d:\d\d)(\:\d\d)?(\s(?:UT|GMT|[ECMP][SD]T|[A-IK-Za-ik-z]|[+-]\d{4}))$/;
3764 // date and time from ref 2822 format
3765 function configFromRFC2822(config) {
3766 var string, match, dayFormat,
3767 dateFormat, timeFormat, tzFormat;
3779 var military = 'YXWVUTSRQPONZABCDEFGHIKLM';
3780 var timezone, timezoneIndex;
3783 .replace(/\([^\)]*\)|[\n\t]/g, ' ') // Remove comments and folding whitespace
3784 .replace(/(\s\s+)/g, ' ') // Replace multiple-spaces with a single space
3785 .replace(/^\s|\s$/g, ''); // Remove leading and trailing spaces
3786 match = basicRfcRegex.exec(string);
3789 dayFormat = match[1] ? 'ddd' + ((match[1].length === 5) ? ', ' : ' ') : '';
3790 dateFormat = 'D MMM ' + ((match[2].length > 10) ? 'YYYY ' : 'YY ');
3791 timeFormat = 'HH:mm' + (match[4] ? ':ss' : '');
3793 // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
3794 if (match[1]) { // day of week given
3795 var momentDate = new Date(match[2]);
3796 var momentDay = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][momentDate.getDay()];
3798 if (match[1].substr(0,3) !== momentDay) {
3799 getParsingFlags(config).weekdayMismatch = true;
3800 config._isValid = false;
3805 switch (match[5].length) {
3807 if (timezoneIndex === 0) {
3808 timezone = ' +0000';
3810 timezoneIndex = military.indexOf(match[5][1].toUpperCase()) - 12;
3811 timezone = ((timezoneIndex < 0) ? ' -' : ' +') +
3812 (('' + timezoneIndex).replace(/^-?/, '0')).match(/..$/)[0] + '00';
3816 timezone = timezones[match[5]];
3818 default: // UT or +/-9999
3819 timezone = timezones[' GMT'];
3821 match[5] = timezone;
3822 config._i = match.splice(1).join('');
3824 config._f = dayFormat + dateFormat + timeFormat + tzFormat;
3825 configFromStringAndFormat(config);
3826 getParsingFlags(config).rfc2822 = true;
3828 config._isValid = false;
3832 // date from iso format or fallback
3833 function configFromString(config) {
3834 var matched = aspNetJsonRegex.exec(config._i);
3836 if (matched !== null) {
3837 config._d = new Date(+matched[1]);
3841 configFromISO(config);
3842 if (config._isValid === false) {
3843 delete config._isValid;
3848 configFromRFC2822(config);
3849 if (config._isValid === false) {
3850 delete config._isValid;
3855 // Final attempt, use Input Fallback
3856 hooks.createFromInputFallback(config);
3859 hooks.createFromInputFallback = deprecate(
3860 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
3861 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
3862 'discouraged and will be removed in an upcoming major release. Please refer to ' +
3863 'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
3865 config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
3869 // Pick the first defined of two or three arguments.
3870 function defaults(a, b, c) {
3880 function currentDateArray(config) {
3881 // hooks is actually the exported moment object
3882 var nowValue = new Date(hooks.now());
3883 if (config._useUTC) {
3884 return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
3886 return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
3889 // convert an array to a date.
3890 // the array should mirror the parameters below
3891 // note: all values past the year are optional and will default to the lowest possible value.
3892 // [year, month, day , hour, minute, second, millisecond]
3893 function configFromArray (config) {
3894 var i, date, input = [], currentDate, yearToUse;
3900 currentDate = currentDateArray(config);
3902 //compute day of the year from weeks and weekdays
3903 if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
3904 dayOfYearFromWeekInfo(config);
3907 //if the day of the year is set, figure out what it is
3908 if (config._dayOfYear != null) {
3909 yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
3911 if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
3912 getParsingFlags(config)._overflowDayOfYear = true;
3915 date = createUTCDate(yearToUse, 0, config._dayOfYear);
3916 config._a[MONTH] = date.getUTCMonth();
3917 config._a[DATE] = date.getUTCDate();
3920 // Default to current date.
3921 // * if no year, month, day of month are given, default to today
3922 // * if day of month is given, default month and year
3923 // * if month is given, default only year
3924 // * if year is given, don't default anything
3925 for (i = 0; i < 3 && config._a[i] == null; ++i) {
3926 config._a[i] = input[i] = currentDate[i];
3929 // Zero out whatever was not defaulted, including time
3930 for (; i < 7; i++) {
3931 config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
3934 // Check for 24:00:00.000
3935 if (config._a[HOUR] === 24 &&
3936 config._a[MINUTE] === 0 &&
3937 config._a[SECOND] === 0 &&
3938 config._a[MILLISECOND] === 0) {
3939 config._nextDay = true;
3940 config._a[HOUR] = 0;
3943 config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
3944 // Apply timezone offset from input. The actual utcOffset can be changed
3946 if (config._tzm != null) {
3947 config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
3950 if (config._nextDay) {
3951 config._a[HOUR] = 24;
3955 function dayOfYearFromWeekInfo(config) {
3956 var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
3959 if (w.GG != null || w.W != null || w.E != null) {
3963 // TODO: We need to take the current isoWeekYear, but that depends on
3964 // how we interpret now (local, utc, fixed offset). So create
3965 // a now version of current config (take local/utc/offset flags, and
3967 weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
3968 week = defaults(w.W, 1);
3969 weekday = defaults(w.E, 1);
3970 if (weekday < 1 || weekday > 7) {
3971 weekdayOverflow = true;
3974 dow = config._locale._week.dow;
3975 doy = config._locale._week.doy;
3977 var curWeek = weekOfYear(createLocal(), dow, doy);
3979 weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
3981 // Default to current week.
3982 week = defaults(w.w, curWeek.week);
3985 // weekday -- low day numbers are considered next week
3987 if (weekday < 0 || weekday > 6) {
3988 weekdayOverflow = true;
3990 } else if (w.e != null) {
3991 // local weekday -- counting starts from begining of week
3992 weekday = w.e + dow;
3993 if (w.e < 0 || w.e > 6) {
3994 weekdayOverflow = true;
3997 // default to begining of week
4001 if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
4002 getParsingFlags(config)._overflowWeeks = true;
4003 } else if (weekdayOverflow != null) {
4004 getParsingFlags(config)._overflowWeekday = true;
4006 temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
4007 config._a[YEAR] = temp.year;
4008 config._dayOfYear = temp.dayOfYear;
4012 // constant that refers to the ISO standard
4013 hooks.ISO_8601 = function () {};
4015 // constant that refers to the RFC 2822 form
4016 hooks.RFC_2822 = function () {};
4018 // date from string and format string
4019 function configFromStringAndFormat(config) {
4020 // TODO: Move this to another part of the creation flow to prevent circular deps
4021 if (config._f === hooks.ISO_8601) {
4022 configFromISO(config);
4025 if (config._f === hooks.RFC_2822) {
4026 configFromRFC2822(config);
4030 getParsingFlags(config).empty = true;
4032 // This array is used to make a Date, either with `new Date` or `Date.UTC`
4033 var string = '' + config._i,
4034 i, parsedInput, tokens, token, skipped,
4035 stringLength = string.length,
4036 totalParsedInputLength = 0;
4038 tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
4040 for (i = 0; i < tokens.length; i++) {
4042 parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
4043 // console.log('token', token, 'parsedInput', parsedInput,
4044 // 'regex', getParseRegexForToken(token, config));
4046 skipped = string.substr(0, string.indexOf(parsedInput));
4047 if (skipped.length > 0) {
4048 getParsingFlags(config).unusedInput.push(skipped);
4050 string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
4051 totalParsedInputLength += parsedInput.length;
4053 // don't parse if it's not a known token
4054 if (formatTokenFunctions[token]) {
4056 getParsingFlags(config).empty = false;
4059 getParsingFlags(config).unusedTokens.push(token);
4061 addTimeToArrayFromToken(token, parsedInput, config);
4063 else if (config._strict && !parsedInput) {
4064 getParsingFlags(config).unusedTokens.push(token);
4068 // add remaining unparsed input length to the string
4069 getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
4070 if (string.length > 0) {
4071 getParsingFlags(config).unusedInput.push(string);
4074 // clear _12h flag if hour is <= 12
4075 if (config._a[HOUR] <= 12 &&
4076 getParsingFlags(config).bigHour === true &&
4077 config._a[HOUR] > 0) {
4078 getParsingFlags(config).bigHour = undefined;
4081 getParsingFlags(config).parsedDateParts = config._a.slice(0);
4082 getParsingFlags(config).meridiem = config._meridiem;
4084 config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
4086 configFromArray(config);
4087 checkOverflow(config);
4091 function meridiemFixWrap (locale, hour, meridiem) {
4094 if (meridiem == null) {
4098 if (locale.meridiemHour != null) {
4099 return locale.meridiemHour(hour, meridiem);
4100 } else if (locale.isPM != null) {
4102 isPm = locale.isPM(meridiem);
4103 if (isPm && hour < 12) {
4106 if (!isPm && hour === 12) {
4111 // this is not supposed to happen
4116 // date from string and array of format strings
4117 function configFromStringAndArray(config) {
4125 if (config._f.length === 0) {
4126 getParsingFlags(config).invalidFormat = true;
4127 config._d = new Date(NaN);
4131 for (i = 0; i < config._f.length; i++) {
4133 tempConfig = copyConfig({}, config);
4134 if (config._useUTC != null) {
4135 tempConfig._useUTC = config._useUTC;
4137 tempConfig._f = config._f[i];
4138 configFromStringAndFormat(tempConfig);
4140 if (!isValid(tempConfig)) {
4144 // if there is any input that was not parsed add a penalty for that format
4145 currentScore += getParsingFlags(tempConfig).charsLeftOver;
4148 currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
4150 getParsingFlags(tempConfig).score = currentScore;
4152 if (scoreToBeat == null || currentScore < scoreToBeat) {
4153 scoreToBeat = currentScore;
4154 bestMoment = tempConfig;
4158 extend(config, bestMoment || tempConfig);
4161 function configFromObject(config) {
4166 var i = normalizeObjectUnits(config._i);
4167 config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
4168 return obj && parseInt(obj, 10);
4171 configFromArray(config);
4174 function createFromConfig (config) {
4175 var res = new Moment(checkOverflow(prepareConfig(config)));
4177 // Adding is smart enough around DST
4179 res._nextDay = undefined;
4185 function prepareConfig (config) {
4186 var input = config._i,
4189 config._locale = config._locale || getLocale(config._l);
4191 if (input === null || (format === undefined && input === '')) {
4192 return createInvalid({nullInput: true});
4195 if (typeof input === 'string') {
4196 config._i = input = config._locale.preparse(input);
4199 if (isMoment(input)) {
4200 return new Moment(checkOverflow(input));
4201 } else if (isDate(input)) {
4203 } else if (isArray(format)) {
4204 configFromStringAndArray(config);
4205 } else if (format) {
4206 configFromStringAndFormat(config);
4208 configFromInput(config);
4211 if (!isValid(config)) {
4218 function configFromInput(config) {
4219 var input = config._i;
4220 if (isUndefined(input)) {
4221 config._d = new Date(hooks.now());
4222 } else if (isDate(input)) {
4223 config._d = new Date(input.valueOf());
4224 } else if (typeof input === 'string') {
4225 configFromString(config);
4226 } else if (isArray(input)) {
4227 config._a = map(input.slice(0), function (obj) {
4228 return parseInt(obj, 10);
4230 configFromArray(config);
4231 } else if (isObject(input)) {
4232 configFromObject(config);
4233 } else if (isNumber(input)) {
4234 // from milliseconds
4235 config._d = new Date(input);
4237 hooks.createFromInputFallback(config);
4241 function createLocalOrUTC (input, format, locale, strict, isUTC) {
4244 if (locale === true || locale === false) {
4249 if ((isObject(input) && isObjectEmpty(input)) ||
4250 (isArray(input) && input.length === 0)) {
4253 // object construction must be done this way.
4254 // https://github.com/moment/moment/issues/1423
4255 c._isAMomentObject = true;
4256 c._useUTC = c._isUTC = isUTC;
4262 return createFromConfig(c);
4265 function createLocal (input, format, locale, strict) {
4266 return createLocalOrUTC(input, format, locale, strict, false);
4269 var prototypeMin = deprecate(
4270 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
4272 var other = createLocal.apply(null, arguments);
4273 if (this.isValid() && other.isValid()) {
4274 return other < this ? this : other;
4276 return createInvalid();
4281 var prototypeMax = deprecate(
4282 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
4284 var other = createLocal.apply(null, arguments);
4285 if (this.isValid() && other.isValid()) {
4286 return other > this ? this : other;
4288 return createInvalid();
4293 // Pick a moment m from moments so that m[fn](other) is true for all
4294 // other. This relies on the function fn to be transitive.
4296 // moments should either be an array of moment objects or an array, whose
4297 // first element is an array of moment objects.
4298 function pickBy(fn, moments) {
4300 if (moments.length === 1 && isArray(moments[0])) {
4301 moments = moments[0];
4303 if (!moments.length) {
4304 return createLocal();
4307 for (i = 1; i < moments.length; ++i) {
4308 if (!moments[i].isValid() || moments[i][fn](res)) {
4315 // TODO: Use [].sort instead?
4317 var args = [].slice.call(arguments, 0);
4319 return pickBy('isBefore', args);
4323 var args = [].slice.call(arguments, 0);
4325 return pickBy('isAfter', args);
4328 var now = function () {
4329 return Date.now ? Date.now() : +(new Date());
4332 var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
4334 function isDurationValid(m) {
4335 for (var key in m) {
4336 if (!(ordering.indexOf(key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
4341 var unitHasDecimal = false;
4342 for (var i = 0; i < ordering.length; ++i) {
4343 if (m[ordering[i]]) {
4344 if (unitHasDecimal) {
4345 return false; // only allow non-integers for smallest unit
4347 if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
4348 unitHasDecimal = true;
4356 function isValid$1() {
4357 return this._isValid;
4360 function createInvalid$1() {
4361 return createDuration(NaN);
4364 function Duration (duration) {
4365 var normalizedInput = normalizeObjectUnits(duration),
4366 years = normalizedInput.year || 0,
4367 quarters = normalizedInput.quarter || 0,
4368 months = normalizedInput.month || 0,
4369 weeks = normalizedInput.week || 0,
4370 days = normalizedInput.day || 0,
4371 hours = normalizedInput.hour || 0,
4372 minutes = normalizedInput.minute || 0,
4373 seconds = normalizedInput.second || 0,
4374 milliseconds = normalizedInput.millisecond || 0;
4376 this._isValid = isDurationValid(normalizedInput);
4378 // representation for dateAddRemove
4379 this._milliseconds = +milliseconds +
4380 seconds * 1e3 + // 1000
4381 minutes * 6e4 + // 1000 * 60
4382 hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
4383 // Because of dateAddRemove treats 24 hours as different from a
4384 // day when working around DST, we need to store them separately
4385 this._days = +days +
4387 // It is impossible translate months into days without knowing
4388 // which months you are are talking about, so we have to store
4390 this._months = +months +
4396 this._locale = getLocale();
4401 function isDuration (obj) {
4402 return obj instanceof Duration;
4405 function absRound (number) {
4407 return Math.round(-1 * number) * -1;
4409 return Math.round(number);
4415 function offset (token, separator) {
4416 addFormatToken(token, 0, 0, function () {
4417 var offset = this.utcOffset();
4423 return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
4432 addRegexToken('Z', matchShortOffset);
4433 addRegexToken('ZZ', matchShortOffset);
4434 addParseToken(['Z', 'ZZ'], function (input, array, config) {
4435 config._useUTC = true;
4436 config._tzm = offsetFromString(matchShortOffset, input);
4442 // '+10:00' > ['10', '00']
4443 // '-1530' > ['-15', '30']
4444 var chunkOffset = /([\+\-]|\d\d)/gi;
4446 function offsetFromString(matcher, string) {
4447 var matches = (string || '').match(matcher);
4449 if (matches === null) {
4453 var chunk = matches[matches.length - 1] || [];
4454 var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
4455 var minutes = +(parts[1] * 60) + toInt(parts[2]);
4457 return minutes === 0 ?
4459 parts[0] === '+' ? minutes : -minutes;
4462 // Return a moment from input, that is local/utc/zone equivalent to model.
4463 function cloneWithOffset(input, model) {
4466 res = model.clone();
4467 diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
4468 // Use low-level api, because this fn is low-level api.
4469 res._d.setTime(res._d.valueOf() + diff);
4470 hooks.updateOffset(res, false);
4473 return createLocal(input).local();
4477 function getDateOffset (m) {
4478 // On Firefox.24 Date#getTimezoneOffset returns a floating point.
4479 // https://github.com/moment/moment/pull/1871
4480 return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
4485 // This function will be called whenever a moment is mutated.
4486 // It is intended to keep the offset in sync with the timezone.
4487 hooks.updateOffset = function () {};
4491 // keepLocalTime = true means only change the timezone, without
4492 // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
4493 // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
4494 // +0200, so we adjust the time as needed, to be valid.
4496 // Keeping the time actually adds/subtracts (one hour)
4497 // from the actual represented time. That is why we call updateOffset
4498 // a second time. In case it wants us to change the offset again
4499 // _changeInProgress == true case, then we have to adjust, because
4500 // there is no such time in the given timezone.
4501 function getSetOffset (input, keepLocalTime, keepMinutes) {
4502 var offset = this._offset || 0,
4504 if (!this.isValid()) {
4505 return input != null ? this : NaN;
4507 if (input != null) {
4508 if (typeof input === 'string') {
4509 input = offsetFromString(matchShortOffset, input);
4510 if (input === null) {
4513 } else if (Math.abs(input) < 16 && !keepMinutes) {
4516 if (!this._isUTC && keepLocalTime) {
4517 localAdjust = getDateOffset(this);
4519 this._offset = input;
4521 if (localAdjust != null) {
4522 this.add(localAdjust, 'm');
4524 if (offset !== input) {
4525 if (!keepLocalTime || this._changeInProgress) {
4526 addSubtract(this, createDuration(input - offset, 'm'), 1, false);
4527 } else if (!this._changeInProgress) {
4528 this._changeInProgress = true;
4529 hooks.updateOffset(this, true);
4530 this._changeInProgress = null;
4535 return this._isUTC ? offset : getDateOffset(this);
4539 function getSetZone (input, keepLocalTime) {
4540 if (input != null) {
4541 if (typeof input !== 'string') {
4545 this.utcOffset(input, keepLocalTime);
4549 return -this.utcOffset();
4553 function setOffsetToUTC (keepLocalTime) {
4554 return this.utcOffset(0, keepLocalTime);
4557 function setOffsetToLocal (keepLocalTime) {
4559 this.utcOffset(0, keepLocalTime);
4560 this._isUTC = false;
4562 if (keepLocalTime) {
4563 this.subtract(getDateOffset(this), 'm');
4569 function setOffsetToParsedOffset () {
4570 if (this._tzm != null) {
4571 this.utcOffset(this._tzm, false, true);
4572 } else if (typeof this._i === 'string') {
4573 var tZone = offsetFromString(matchOffset, this._i);
4574 if (tZone != null) {
4575 this.utcOffset(tZone);
4578 this.utcOffset(0, true);
4584 function hasAlignedHourOffset (input) {
4585 if (!this.isValid()) {
4588 input = input ? createLocal(input).utcOffset() : 0;
4590 return (this.utcOffset() - input) % 60 === 0;
4593 function isDaylightSavingTime () {
4595 this.utcOffset() > this.clone().month(0).utcOffset() ||
4596 this.utcOffset() > this.clone().month(5).utcOffset()
4600 function isDaylightSavingTimeShifted () {
4601 if (!isUndefined(this._isDSTShifted)) {
4602 return this._isDSTShifted;
4607 copyConfig(c, this);
4608 c = prepareConfig(c);
4611 var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
4612 this._isDSTShifted = this.isValid() &&
4613 compareArrays(c._a, other.toArray()) > 0;
4615 this._isDSTShifted = false;
4618 return this._isDSTShifted;
4621 function isLocal () {
4622 return this.isValid() ? !this._isUTC : false;
4625 function isUtcOffset () {
4626 return this.isValid() ? this._isUTC : false;
4630 return this.isValid() ? this._isUTC && this._offset === 0 : false;
4633 // ASP.NET json date format regex
4634 var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;
4636 // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
4637 // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
4638 // and further modified to allow for strings containing both week and day
4639 var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;
4641 function createDuration (input, key) {
4642 var duration = input,
4643 // matching against regexp is expensive, do it on demand
4649 if (isDuration(input)) {
4651 ms : input._milliseconds,
4655 } else if (isNumber(input)) {
4658 duration[key] = input;
4660 duration.milliseconds = input;
4662 } else if (!!(match = aspNetRegex.exec(input))) {
4663 sign = (match[1] === '-') ? -1 : 1;
4666 d : toInt(match[DATE]) * sign,
4667 h : toInt(match[HOUR]) * sign,
4668 m : toInt(match[MINUTE]) * sign,
4669 s : toInt(match[SECOND]) * sign,
4670 ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
4672 } else if (!!(match = isoRegex.exec(input))) {
4673 sign = (match[1] === '-') ? -1 : 1;
4675 y : parseIso(match[2], sign),
4676 M : parseIso(match[3], sign),
4677 w : parseIso(match[4], sign),
4678 d : parseIso(match[5], sign),
4679 h : parseIso(match[6], sign),
4680 m : parseIso(match[7], sign),
4681 s : parseIso(match[8], sign)
4683 } else if (duration == null) {// checks for null or undefined
4685 } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
4686 diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
4689 duration.ms = diffRes.milliseconds;
4690 duration.M = diffRes.months;
4693 ret = new Duration(duration);
4695 if (isDuration(input) && hasOwnProp(input, '_locale')) {
4696 ret._locale = input._locale;
4702 createDuration.fn = Duration.prototype;
4703 createDuration.invalid = createInvalid$1;
4705 function parseIso (inp, sign) {
4706 // We'd normally use ~~inp for this, but unfortunately it also
4707 // converts floats to ints.
4708 // inp may be undefined, so careful calling replace on it.
4709 var res = inp && parseFloat(inp.replace(',', '.'));
4710 // apply sign while we're at it
4711 return (isNaN(res) ? 0 : res) * sign;
4714 function positiveMomentsDifference(base, other) {
4715 var res = {milliseconds: 0, months: 0};
4717 res.months = other.month() - base.month() +
4718 (other.year() - base.year()) * 12;
4719 if (base.clone().add(res.months, 'M').isAfter(other)) {
4723 res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
4728 function momentsDifference(base, other) {
4730 if (!(base.isValid() && other.isValid())) {
4731 return {milliseconds: 0, months: 0};
4734 other = cloneWithOffset(other, base);
4735 if (base.isBefore(other)) {
4736 res = positiveMomentsDifference(base, other);
4738 res = positiveMomentsDifference(other, base);
4739 res.milliseconds = -res.milliseconds;
4740 res.months = -res.months;
4746 // TODO: remove 'name' arg after deprecation is removed
4747 function createAdder(direction, name) {
4748 return function (val, period) {
4750 //invert the arguments, but complain about it
4751 if (period !== null && !isNaN(+period)) {
4752 deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
4753 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
4754 tmp = val; val = period; period = tmp;
4757 val = typeof val === 'string' ? +val : val;
4758 dur = createDuration(val, period);
4759 addSubtract(this, dur, direction);
4764 function addSubtract (mom, duration, isAdding, updateOffset) {
4765 var milliseconds = duration._milliseconds,
4766 days = absRound(duration._days),
4767 months = absRound(duration._months);
4769 if (!mom.isValid()) {
4774 updateOffset = updateOffset == null ? true : updateOffset;
4777 mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
4780 set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
4783 setMonth(mom, get(mom, 'Month') + months * isAdding);
4786 hooks.updateOffset(mom, days || months);
4790 var add = createAdder(1, 'add');
4791 var subtract = createAdder(-1, 'subtract');
4793 function getCalendarFormat(myMoment, now) {
4794 var diff = myMoment.diff(now, 'days', true);
4795 return diff < -6 ? 'sameElse' :
4796 diff < -1 ? 'lastWeek' :
4797 diff < 0 ? 'lastDay' :
4798 diff < 1 ? 'sameDay' :
4799 diff < 2 ? 'nextDay' :
4800 diff < 7 ? 'nextWeek' : 'sameElse';
4803 function calendar$1 (time, formats) {
4804 // We want to compare the start of today, vs this.
4805 // Getting start-of-today depends on whether we're local/utc/offset or not.
4806 var now = time || createLocal(),
4807 sod = cloneWithOffset(now, this).startOf('day'),
4808 format = hooks.calendarFormat(this, sod) || 'sameElse';
4810 var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
4812 return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
4816 return new Moment(this);
4819 function isAfter (input, units) {
4820 var localInput = isMoment(input) ? input : createLocal(input);
4821 if (!(this.isValid() && localInput.isValid())) {
4824 units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
4825 if (units === 'millisecond') {
4826 return this.valueOf() > localInput.valueOf();
4828 return localInput.valueOf() < this.clone().startOf(units).valueOf();
4832 function isBefore (input, units) {
4833 var localInput = isMoment(input) ? input : createLocal(input);
4834 if (!(this.isValid() && localInput.isValid())) {
4837 units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
4838 if (units === 'millisecond') {
4839 return this.valueOf() < localInput.valueOf();
4841 return this.clone().endOf(units).valueOf() < localInput.valueOf();
4845 function isBetween (from, to, units, inclusivity) {
4846 inclusivity = inclusivity || '()';
4847 return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
4848 (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units));
4851 function isSame (input, units) {
4852 var localInput = isMoment(input) ? input : createLocal(input),
4854 if (!(this.isValid() && localInput.isValid())) {
4857 units = normalizeUnits(units || 'millisecond');
4858 if (units === 'millisecond') {
4859 return this.valueOf() === localInput.valueOf();
4861 inputMs = localInput.valueOf();
4862 return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
4866 function isSameOrAfter (input, units) {
4867 return this.isSame(input, units) || this.isAfter(input,units);
4870 function isSameOrBefore (input, units) {
4871 return this.isSame(input, units) || this.isBefore(input,units);
4874 function diff (input, units, asFloat) {
4879 if (!this.isValid()) {
4883 that = cloneWithOffset(input, this);
4885 if (!that.isValid()) {
4889 zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
4891 units = normalizeUnits(units);
4893 if (units === 'year' || units === 'month' || units === 'quarter') {
4894 output = monthDiff(this, that);
4895 if (units === 'quarter') {
4896 output = output / 3;
4897 } else if (units === 'year') {
4898 output = output / 12;
4901 delta = this - that;
4902 output = units === 'second' ? delta / 1e3 : // 1000
4903 units === 'minute' ? delta / 6e4 : // 1000 * 60
4904 units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60
4905 units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
4906 units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
4909 return asFloat ? output : absFloor(output);
4912 function monthDiff (a, b) {
4913 // difference in months
4914 var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
4915 // b is in (anchor - 1 month, anchor + 1 month)
4916 anchor = a.clone().add(wholeMonthDiff, 'months'),
4919 if (b - anchor < 0) {
4920 anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
4921 // linear across the month
4922 adjust = (b - anchor) / (anchor - anchor2);
4924 anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
4925 // linear across the month
4926 adjust = (b - anchor) / (anchor2 - anchor);
4929 //check for negative zero, return zero if negative zero
4930 return -(wholeMonthDiff + adjust) || 0;
4933 hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
4934 hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
4936 function toString () {
4937 return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
4940 function toISOString() {
4941 if (!this.isValid()) {
4944 var m = this.clone().utc();
4945 if (m.year() < 0 || m.year() > 9999) {
4946 return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
4948 if (isFunction(Date.prototype.toISOString)) {
4949 // native implementation is ~50x faster, use it when we can
4950 return this.toDate().toISOString();
4952 return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
4956 * Return a human readable representation of a moment that can
4957 * also be evaluated to get a new moment which is the same
4959 * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
4961 function inspect () {
4962 if (!this.isValid()) {
4963 return 'moment.invalid(/* ' + this._i + ' */)';
4965 var func = 'moment';
4967 if (!this.isLocal()) {
4968 func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
4971 var prefix = '[' + func + '("]';
4972 var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
4973 var datetime = '-MM-DD[T]HH:mm:ss.SSS';
4974 var suffix = zone + '[")]';
4976 return this.format(prefix + year + datetime + suffix);
4979 function format (inputString) {
4981 inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
4983 var output = formatMoment(this, inputString);
4984 return this.localeData().postformat(output);
4987 function from (time, withoutSuffix) {
4988 if (this.isValid() &&
4989 ((isMoment(time) && time.isValid()) ||
4990 createLocal(time).isValid())) {
4991 return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
4993 return this.localeData().invalidDate();
4997 function fromNow (withoutSuffix) {
4998 return this.from(createLocal(), withoutSuffix);
5001 function to (time, withoutSuffix) {
5002 if (this.isValid() &&
5003 ((isMoment(time) && time.isValid()) ||
5004 createLocal(time).isValid())) {
5005 return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
5007 return this.localeData().invalidDate();
5011 function toNow (withoutSuffix) {
5012 return this.to(createLocal(), withoutSuffix);
5015 // If passed a locale key, it will set the locale for this
5016 // instance. Otherwise, it will return the locale configuration
5017 // variables for this instance.
5018 function locale (key) {
5021 if (key === undefined) {
5022 return this._locale._abbr;
5024 newLocaleData = getLocale(key);
5025 if (newLocaleData != null) {
5026 this._locale = newLocaleData;
5032 var lang = deprecate(
5033 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
5035 if (key === undefined) {
5036 return this.localeData();
5038 return this.locale(key);
5043 function localeData () {
5044 return this._locale;
5047 function startOf (units) {
5048 units = normalizeUnits(units);
5049 // the following switch intentionally omits break keywords
5050 // to utilize falling through the cases.
5072 this.milliseconds(0);
5075 // weeks are a special case
5076 if (units === 'week') {
5079 if (units === 'isoWeek') {
5083 // quarters are also special
5084 if (units === 'quarter') {
5085 this.month(Math.floor(this.month() / 3) * 3);
5091 function endOf (units) {
5092 units = normalizeUnits(units);
5093 if (units === undefined || units === 'millisecond') {
5097 // 'date' is an alias for 'day', so it should be considered as such.
5098 if (units === 'date') {
5102 return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
5105 function valueOf () {
5106 return this._d.valueOf() - ((this._offset || 0) * 60000);
5110 return Math.floor(this.valueOf() / 1000);
5113 function toDate () {
5114 return new Date(this.valueOf());
5117 function toArray () {
5119 return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
5122 function toObject () {
5129 minutes: m.minutes(),
5130 seconds: m.seconds(),
5131 milliseconds: m.milliseconds()
5135 function toJSON () {
5136 // new Date(NaN).toJSON() === null
5137 return this.isValid() ? this.toISOString() : null;
5140 function isValid$2 () {
5141 return isValid(this);
5144 function parsingFlags () {
5145 return extend({}, getParsingFlags(this));
5148 function invalidAt () {
5149 return getParsingFlags(this).overflow;
5152 function creationData() {
5156 locale: this._locale,
5158 strict: this._strict
5164 addFormatToken(0, ['gg', 2], 0, function () {
5165 return this.weekYear() % 100;
5168 addFormatToken(0, ['GG', 2], 0, function () {
5169 return this.isoWeekYear() % 100;
5172 function addWeekYearFormatToken (token, getter) {
5173 addFormatToken(0, [token, token.length], 0, getter);
5176 addWeekYearFormatToken('gggg', 'weekYear');
5177 addWeekYearFormatToken('ggggg', 'weekYear');
5178 addWeekYearFormatToken('GGGG', 'isoWeekYear');
5179 addWeekYearFormatToken('GGGGG', 'isoWeekYear');
5183 addUnitAlias('weekYear', 'gg');
5184 addUnitAlias('isoWeekYear', 'GG');
5188 addUnitPriority('weekYear', 1);
5189 addUnitPriority('isoWeekYear', 1);
5194 addRegexToken('G', matchSigned);
5195 addRegexToken('g', matchSigned);
5196 addRegexToken('GG', match1to2, match2);
5197 addRegexToken('gg', match1to2, match2);
5198 addRegexToken('GGGG', match1to4, match4);
5199 addRegexToken('gggg', match1to4, match4);
5200 addRegexToken('GGGGG', match1to6, match6);
5201 addRegexToken('ggggg', match1to6, match6);
5203 addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
5204 week[token.substr(0, 2)] = toInt(input);
5207 addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
5208 week[token] = hooks.parseTwoDigitYear(input);
5213 function getSetWeekYear (input) {
5214 return getSetWeekYearHelper.call(this,
5218 this.localeData()._week.dow,
5219 this.localeData()._week.doy);
5222 function getSetISOWeekYear (input) {
5223 return getSetWeekYearHelper.call(this,
5224 input, this.isoWeek(), this.isoWeekday(), 1, 4);
5227 function getISOWeeksInYear () {
5228 return weeksInYear(this.year(), 1, 4);
5231 function getWeeksInYear () {
5232 var weekInfo = this.localeData()._week;
5233 return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
5236 function getSetWeekYearHelper(input, week, weekday, dow, doy) {
5238 if (input == null) {
5239 return weekOfYear(this, dow, doy).year;
5241 weeksTarget = weeksInYear(input, dow, doy);
5242 if (week > weeksTarget) {
5245 return setWeekAll.call(this, input, week, weekday, dow, doy);
5249 function setWeekAll(weekYear, week, weekday, dow, doy) {
5250 var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
5251 date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
5253 this.year(date.getUTCFullYear());
5254 this.month(date.getUTCMonth());
5255 this.date(date.getUTCDate());
5261 addFormatToken('Q', 0, 'Qo', 'quarter');
5265 addUnitAlias('quarter', 'Q');
5269 addUnitPriority('quarter', 7);
5273 addRegexToken('Q', match1);
5274 addParseToken('Q', function (input, array) {
5275 array[MONTH] = (toInt(input) - 1) * 3;
5280 function getSetQuarter (input) {
5281 return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
5286 addFormatToken('D', ['DD', 2], 'Do', 'date');
5290 addUnitAlias('date', 'D');
5293 addUnitPriority('date', 9);
5297 addRegexToken('D', match1to2);
5298 addRegexToken('DD', match1to2, match2);
5299 addRegexToken('Do', function (isStrict, locale) {
5300 // TODO: Remove "ordinalParse" fallback in next major release.
5302 (locale._dayOfMonthOrdinalParse || locale._ordinalParse) :
5303 locale._dayOfMonthOrdinalParseLenient;
5306 addParseToken(['D', 'DD'], DATE);
5307 addParseToken('Do', function (input, array) {
5308 array[DATE] = toInt(input.match(match1to2)[0], 10);
5313 var getSetDayOfMonth = makeGetSet('Date', true);
5317 addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
5321 addUnitAlias('dayOfYear', 'DDD');
5324 addUnitPriority('dayOfYear', 4);
5328 addRegexToken('DDD', match1to3);
5329 addRegexToken('DDDD', match3);
5330 addParseToken(['DDD', 'DDDD'], function (input, array, config) {
5331 config._dayOfYear = toInt(input);
5338 function getSetDayOfYear (input) {
5339 var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
5340 return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
5345 addFormatToken('m', ['mm', 2], 0, 'minute');
5349 addUnitAlias('minute', 'm');
5353 addUnitPriority('minute', 14);
5357 addRegexToken('m', match1to2);
5358 addRegexToken('mm', match1to2, match2);
5359 addParseToken(['m', 'mm'], MINUTE);
5363 var getSetMinute = makeGetSet('Minutes', false);
5367 addFormatToken('s', ['ss', 2], 0, 'second');
5371 addUnitAlias('second', 's');
5375 addUnitPriority('second', 15);
5379 addRegexToken('s', match1to2);
5380 addRegexToken('ss', match1to2, match2);
5381 addParseToken(['s', 'ss'], SECOND);
5385 var getSetSecond = makeGetSet('Seconds', false);
5389 addFormatToken('S', 0, 0, function () {
5390 return ~~(this.millisecond() / 100);
5393 addFormatToken(0, ['SS', 2], 0, function () {
5394 return ~~(this.millisecond() / 10);
5397 addFormatToken(0, ['SSS', 3], 0, 'millisecond');
5398 addFormatToken(0, ['SSSS', 4], 0, function () {
5399 return this.millisecond() * 10;
5401 addFormatToken(0, ['SSSSS', 5], 0, function () {
5402 return this.millisecond() * 100;
5404 addFormatToken(0, ['SSSSSS', 6], 0, function () {
5405 return this.millisecond() * 1000;
5407 addFormatToken(0, ['SSSSSSS', 7], 0, function () {
5408 return this.millisecond() * 10000;
5410 addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
5411 return this.millisecond() * 100000;
5413 addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
5414 return this.millisecond() * 1000000;
5420 addUnitAlias('millisecond', 'ms');
5424 addUnitPriority('millisecond', 16);
5428 addRegexToken('S', match1to3, match1);
5429 addRegexToken('SS', match1to3, match2);
5430 addRegexToken('SSS', match1to3, match3);
5433 for (token = 'SSSS'; token.length <= 9; token += 'S') {
5434 addRegexToken(token, matchUnsigned);
5437 function parseMs(input, array) {
5438 array[MILLISECOND] = toInt(('0.' + input) * 1000);
5441 for (token = 'S'; token.length <= 9; token += 'S') {
5442 addParseToken(token, parseMs);
5446 var getSetMillisecond = makeGetSet('Milliseconds', false);
5450 addFormatToken('z', 0, 0, 'zoneAbbr');
5451 addFormatToken('zz', 0, 0, 'zoneName');
5455 function getZoneAbbr () {
5456 return this._isUTC ? 'UTC' : '';
5459 function getZoneName () {
5460 return this._isUTC ? 'Coordinated Universal Time' : '';
5463 var proto = Moment.prototype;
5466 proto.calendar = calendar$1;
5467 proto.clone = clone;
5469 proto.endOf = endOf;
5470 proto.format = format;
5472 proto.fromNow = fromNow;
5474 proto.toNow = toNow;
5475 proto.get = stringGet;
5476 proto.invalidAt = invalidAt;
5477 proto.isAfter = isAfter;
5478 proto.isBefore = isBefore;
5479 proto.isBetween = isBetween;
5480 proto.isSame = isSame;
5481 proto.isSameOrAfter = isSameOrAfter;
5482 proto.isSameOrBefore = isSameOrBefore;
5483 proto.isValid = isValid$2;
5485 proto.locale = locale;
5486 proto.localeData = localeData;
5487 proto.max = prototypeMax;
5488 proto.min = prototypeMin;
5489 proto.parsingFlags = parsingFlags;
5490 proto.set = stringSet;
5491 proto.startOf = startOf;
5492 proto.subtract = subtract;
5493 proto.toArray = toArray;
5494 proto.toObject = toObject;
5495 proto.toDate = toDate;
5496 proto.toISOString = toISOString;
5497 proto.inspect = inspect;
5498 proto.toJSON = toJSON;
5499 proto.toString = toString;
5501 proto.valueOf = valueOf;
5502 proto.creationData = creationData;
5505 proto.year = getSetYear;
5506 proto.isLeapYear = getIsLeapYear;
5509 proto.weekYear = getSetWeekYear;
5510 proto.isoWeekYear = getSetISOWeekYear;
5513 proto.quarter = proto.quarters = getSetQuarter;
5516 proto.month = getSetMonth;
5517 proto.daysInMonth = getDaysInMonth;
5520 proto.week = proto.weeks = getSetWeek;
5521 proto.isoWeek = proto.isoWeeks = getSetISOWeek;
5522 proto.weeksInYear = getWeeksInYear;
5523 proto.isoWeeksInYear = getISOWeeksInYear;
5526 proto.date = getSetDayOfMonth;
5527 proto.day = proto.days = getSetDayOfWeek;
5528 proto.weekday = getSetLocaleDayOfWeek;
5529 proto.isoWeekday = getSetISODayOfWeek;
5530 proto.dayOfYear = getSetDayOfYear;
5533 proto.hour = proto.hours = getSetHour;
5536 proto.minute = proto.minutes = getSetMinute;
5539 proto.second = proto.seconds = getSetSecond;
5542 proto.millisecond = proto.milliseconds = getSetMillisecond;
5545 proto.utcOffset = getSetOffset;
5546 proto.utc = setOffsetToUTC;
5547 proto.local = setOffsetToLocal;
5548 proto.parseZone = setOffsetToParsedOffset;
5549 proto.hasAlignedHourOffset = hasAlignedHourOffset;
5550 proto.isDST = isDaylightSavingTime;
5551 proto.isLocal = isLocal;
5552 proto.isUtcOffset = isUtcOffset;
5553 proto.isUtc = isUtc;
5554 proto.isUTC = isUtc;
5557 proto.zoneAbbr = getZoneAbbr;
5558 proto.zoneName = getZoneName;
5561 proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
5562 proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
5563 proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
5564 proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
5565 proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
5567 function createUnix (input) {
5568 return createLocal(input * 1000);
5571 function createInZone () {
5572 return createLocal.apply(null, arguments).parseZone();
5575 function preParsePostFormat (string) {
5579 var proto$1 = Locale.prototype;
5581 proto$1.calendar = calendar;
5582 proto$1.longDateFormat = longDateFormat;
5583 proto$1.invalidDate = invalidDate;
5584 proto$1.ordinal = ordinal;
5585 proto$1.preparse = preParsePostFormat;
5586 proto$1.postformat = preParsePostFormat;
5587 proto$1.relativeTime = relativeTime;
5588 proto$1.pastFuture = pastFuture;
5592 proto$1.months = localeMonths;
5593 proto$1.monthsShort = localeMonthsShort;
5594 proto$1.monthsParse = localeMonthsParse;
5595 proto$1.monthsRegex = monthsRegex;
5596 proto$1.monthsShortRegex = monthsShortRegex;
5599 proto$1.week = localeWeek;
5600 proto$1.firstDayOfYear = localeFirstDayOfYear;
5601 proto$1.firstDayOfWeek = localeFirstDayOfWeek;
5604 proto$1.weekdays = localeWeekdays;
5605 proto$1.weekdaysMin = localeWeekdaysMin;
5606 proto$1.weekdaysShort = localeWeekdaysShort;
5607 proto$1.weekdaysParse = localeWeekdaysParse;
5609 proto$1.weekdaysRegex = weekdaysRegex;
5610 proto$1.weekdaysShortRegex = weekdaysShortRegex;
5611 proto$1.weekdaysMinRegex = weekdaysMinRegex;
5614 proto$1.isPM = localeIsPM;
5615 proto$1.meridiem = localeMeridiem;
5617 function get$1 (format, index, field, setter) {
5618 var locale = getLocale();
5619 var utc = createUTC().set(setter, index);
5620 return locale[field](utc, format);
5623 function listMonthsImpl (format, index, field) {
5624 if (isNumber(format)) {
5629 format = format || '';
5631 if (index != null) {
5632 return get$1(format, index, field, 'month');
5637 for (i = 0; i < 12; i++) {
5638 out[i] = get$1(format, i, field, 'month');
5651 function listWeekdaysImpl (localeSorted, format, index, field) {
5652 if (typeof localeSorted === 'boolean') {
5653 if (isNumber(format)) {
5658 format = format || '';
5660 format = localeSorted;
5662 localeSorted = false;
5664 if (isNumber(format)) {
5669 format = format || '';
5672 var locale = getLocale(),
5673 shift = localeSorted ? locale._week.dow : 0;
5675 if (index != null) {
5676 return get$1(format, (index + shift) % 7, field, 'day');
5681 for (i = 0; i < 7; i++) {
5682 out[i] = get$1(format, (i + shift) % 7, field, 'day');
5687 function listMonths (format, index) {
5688 return listMonthsImpl(format, index, 'months');
5691 function listMonthsShort (format, index) {
5692 return listMonthsImpl(format, index, 'monthsShort');
5695 function listWeekdays (localeSorted, format, index) {
5696 return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
5699 function listWeekdaysShort (localeSorted, format, index) {
5700 return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
5703 function listWeekdaysMin (localeSorted, format, index) {
5704 return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
5707 getSetGlobalLocale('en', {
5708 dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
5709 ordinal : function (number) {
5710 var b = number % 10,
5711 output = (toInt(number % 100 / 10) === 1) ? 'th' :
5714 (b === 3) ? 'rd' : 'th';
5715 return number + output;
5719 // Side effect imports
5720 hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
5721 hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
5723 var mathAbs = Math.abs;
5726 var data = this._data;
5728 this._milliseconds = mathAbs(this._milliseconds);
5729 this._days = mathAbs(this._days);
5730 this._months = mathAbs(this._months);
5732 data.milliseconds = mathAbs(data.milliseconds);
5733 data.seconds = mathAbs(data.seconds);
5734 data.minutes = mathAbs(data.minutes);
5735 data.hours = mathAbs(data.hours);
5736 data.months = mathAbs(data.months);
5737 data.years = mathAbs(data.years);
5742 function addSubtract$1 (duration, input, value, direction) {
5743 var other = createDuration(input, value);
5745 duration._milliseconds += direction * other._milliseconds;
5746 duration._days += direction * other._days;
5747 duration._months += direction * other._months;
5749 return duration._bubble();
5752 // supports only 2.0-style add(1, 's') or add(duration)
5753 function add$1 (input, value) {
5754 return addSubtract$1(this, input, value, 1);
5757 // supports only 2.0-style subtract(1, 's') or subtract(duration)
5758 function subtract$1 (input, value) {
5759 return addSubtract$1(this, input, value, -1);
5762 function absCeil (number) {
5764 return Math.floor(number);
5766 return Math.ceil(number);
5770 function bubble () {
5771 var milliseconds = this._milliseconds;
5772 var days = this._days;
5773 var months = this._months;
5774 var data = this._data;
5775 var seconds, minutes, hours, years, monthsFromDays;
5777 // if we have a mix of positive and negative values, bubble down first
5778 // check: https://github.com/moment/moment/issues/2166
5779 if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
5780 (milliseconds <= 0 && days <= 0 && months <= 0))) {
5781 milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
5786 // The following code bubbles up values, see the tests for
5787 // examples of what that means.
5788 data.milliseconds = milliseconds % 1000;
5790 seconds = absFloor(milliseconds / 1000);
5791 data.seconds = seconds % 60;
5793 minutes = absFloor(seconds / 60);
5794 data.minutes = minutes % 60;
5796 hours = absFloor(minutes / 60);
5797 data.hours = hours % 24;
5799 days += absFloor(hours / 24);
5801 // convert days to months
5802 monthsFromDays = absFloor(daysToMonths(days));
5803 months += monthsFromDays;
5804 days -= absCeil(monthsToDays(monthsFromDays));
5806 // 12 months -> 1 year
5807 years = absFloor(months / 12);
5811 data.months = months;
5817 function daysToMonths (days) {
5818 // 400 years have 146097 days (taking into account leap year rules)
5819 // 400 years have 12 months === 4800
5820 return days * 4800 / 146097;
5823 function monthsToDays (months) {
5824 // the reverse of daysToMonths
5825 return months * 146097 / 4800;
5828 function as (units) {
5829 if (!this.isValid()) {
5834 var milliseconds = this._milliseconds;
5836 units = normalizeUnits(units);
5838 if (units === 'month' || units === 'year') {
5839 days = this._days + milliseconds / 864e5;
5840 months = this._months + daysToMonths(days);
5841 return units === 'month' ? months : months / 12;
5843 // handle milliseconds separately because of floating point math errors (issue #1867)
5844 days = this._days + Math.round(monthsToDays(this._months));
5846 case 'week' : return days / 7 + milliseconds / 6048e5;
5847 case 'day' : return days + milliseconds / 864e5;
5848 case 'hour' : return days * 24 + milliseconds / 36e5;
5849 case 'minute' : return days * 1440 + milliseconds / 6e4;
5850 case 'second' : return days * 86400 + milliseconds / 1000;
5851 // Math.floor prevents floating point math errors here
5852 case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
5853 default: throw new Error('Unknown unit ' + units);
5858 // TODO: Use this.as('ms')?
5859 function valueOf$1 () {
5860 if (!this.isValid()) {
5864 this._milliseconds +
5865 this._days * 864e5 +
5866 (this._months % 12) * 2592e6 +
5867 toInt(this._months / 12) * 31536e6
5871 function makeAs (alias) {
5872 return function () {
5873 return this.as(alias);
5877 var asMilliseconds = makeAs('ms');
5878 var asSeconds = makeAs('s');
5879 var asMinutes = makeAs('m');
5880 var asHours = makeAs('h');
5881 var asDays = makeAs('d');
5882 var asWeeks = makeAs('w');
5883 var asMonths = makeAs('M');
5884 var asYears = makeAs('y');
5886 function get$2 (units) {
5887 units = normalizeUnits(units);
5888 return this.isValid() ? this[units + 's']() : NaN;
5891 function makeGetter(name) {
5892 return function () {
5893 return this.isValid() ? this._data[name] : NaN;
5897 var milliseconds = makeGetter('milliseconds');
5898 var seconds = makeGetter('seconds');
5899 var minutes = makeGetter('minutes');
5900 var hours = makeGetter('hours');
5901 var days = makeGetter('days');
5902 var months = makeGetter('months');
5903 var years = makeGetter('years');
5906 return absFloor(this.days() / 7);
5909 var round = Math.round;
5911 ss: 44, // a few seconds to seconds
5912 s : 45, // seconds to minute
5913 m : 45, // minutes to hour
5914 h : 22, // hours to day
5915 d : 26, // days to month
5916 M : 11 // months to year
5919 // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
5920 function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
5921 return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
5924 function relativeTime$1 (posNegDuration, withoutSuffix, locale) {
5925 var duration = createDuration(posNegDuration).abs();
5926 var seconds = round(duration.as('s'));
5927 var minutes = round(duration.as('m'));
5928 var hours = round(duration.as('h'));
5929 var days = round(duration.as('d'));
5930 var months = round(duration.as('M'));
5931 var years = round(duration.as('y'));
5933 var a = seconds <= thresholds.ss && ['s', seconds] ||
5934 seconds < thresholds.s && ['ss', seconds] ||
5935 minutes <= 1 && ['m'] ||
5936 minutes < thresholds.m && ['mm', minutes] ||
5937 hours <= 1 && ['h'] ||
5938 hours < thresholds.h && ['hh', hours] ||
5939 days <= 1 && ['d'] ||
5940 days < thresholds.d && ['dd', days] ||
5941 months <= 1 && ['M'] ||
5942 months < thresholds.M && ['MM', months] ||
5943 years <= 1 && ['y'] || ['yy', years];
5945 a[2] = withoutSuffix;
5946 a[3] = +posNegDuration > 0;
5948 return substituteTimeAgo.apply(null, a);
5951 // This function allows you to set the rounding function for relative time strings
5952 function getSetRelativeTimeRounding (roundingFunction) {
5953 if (roundingFunction === undefined) {
5956 if (typeof(roundingFunction) === 'function') {
5957 round = roundingFunction;
5963 // This function allows you to set a threshold for relative time strings
5964 function getSetRelativeTimeThreshold (threshold, limit) {
5965 if (thresholds[threshold] === undefined) {
5968 if (limit === undefined) {
5969 return thresholds[threshold];
5971 thresholds[threshold] = limit;
5972 if (threshold === 's') {
5973 thresholds.ss = limit - 1;
5978 function humanize (withSuffix) {
5979 if (!this.isValid()) {
5980 return this.localeData().invalidDate();
5983 var locale = this.localeData();
5984 var output = relativeTime$1(this, !withSuffix, locale);
5987 output = locale.pastFuture(+this, output);
5990 return locale.postformat(output);
5993 var abs$1 = Math.abs;
5995 function toISOString$1() {
5996 // for ISO strings we do not use the normal bubbling rules:
5997 // * milliseconds bubble up until they become hours
5998 // * days do not bubble at all
5999 // * months bubble up until they become years
6000 // This is because there is no context-free conversion between hours and days
6001 // (think of clock changes)
6002 // and also not between days and months (28-31 days per month)
6003 if (!this.isValid()) {
6004 return this.localeData().invalidDate();
6007 var seconds = abs$1(this._milliseconds) / 1000;
6008 var days = abs$1(this._days);
6009 var months = abs$1(this._months);
6010 var minutes, hours, years;
6012 // 3600 seconds -> 60 minutes -> 1 hour
6013 minutes = absFloor(seconds / 60);
6014 hours = absFloor(minutes / 60);
6018 // 12 months -> 1 year
6019 years = absFloor(months / 12);
6023 // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
6030 var total = this.asSeconds();
6033 // this is the same as C#'s (Noda) and python (isodate)...
6034 // but not other JS (goog.date)
6038 return (total < 0 ? '-' : '') +
6040 (Y ? Y + 'Y' : '') +
6041 (M ? M + 'M' : '') +
6042 (D ? D + 'D' : '') +
6043 ((h || m || s) ? 'T' : '') +
6044 (h ? h + 'H' : '') +
6045 (m ? m + 'M' : '') +
6049 var proto$2 = Duration.prototype;
6051 proto$2.isValid = isValid$1;
6053 proto$2.add = add$1;
6054 proto$2.subtract = subtract$1;
6056 proto$2.asMilliseconds = asMilliseconds;
6057 proto$2.asSeconds = asSeconds;
6058 proto$2.asMinutes = asMinutes;
6059 proto$2.asHours = asHours;
6060 proto$2.asDays = asDays;
6061 proto$2.asWeeks = asWeeks;
6062 proto$2.asMonths = asMonths;
6063 proto$2.asYears = asYears;
6064 proto$2.valueOf = valueOf$1;
6065 proto$2._bubble = bubble;
6066 proto$2.get = get$2;
6067 proto$2.milliseconds = milliseconds;
6068 proto$2.seconds = seconds;
6069 proto$2.minutes = minutes;
6070 proto$2.hours = hours;
6071 proto$2.days = days;
6072 proto$2.weeks = weeks;
6073 proto$2.months = months;
6074 proto$2.years = years;
6075 proto$2.humanize = humanize;
6076 proto$2.toISOString = toISOString$1;
6077 proto$2.toString = toISOString$1;
6078 proto$2.toJSON = toISOString$1;
6079 proto$2.locale = locale;
6080 proto$2.localeData = localeData;
6083 proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
6084 proto$2.lang = lang;
6086 // Side effect imports
6090 addFormatToken('X', 0, 0, 'unix');
6091 addFormatToken('x', 0, 0, 'valueOf');
6095 addRegexToken('x', matchSigned);
6096 addRegexToken('X', matchTimestamp);
6097 addParseToken('X', function (input, array, config) {
6098 config._d = new Date(parseFloat(input, 10) * 1000);
6100 addParseToken('x', function (input, array, config) {
6101 config._d = new Date(toInt(input));
6104 // Side effect imports
6107 hooks.version = '2.18.1';
6109 setHookCallback(createLocal);
6115 hooks.utc = createUTC;
6116 hooks.unix = createUnix;
6117 hooks.months = listMonths;
6118 hooks.isDate = isDate;
6119 hooks.locale = getSetGlobalLocale;
6120 hooks.invalid = createInvalid;
6121 hooks.duration = createDuration;
6122 hooks.isMoment = isMoment;
6123 hooks.weekdays = listWeekdays;
6124 hooks.parseZone = createInZone;
6125 hooks.localeData = getLocale;
6126 hooks.isDuration = isDuration;
6127 hooks.monthsShort = listMonthsShort;
6128 hooks.weekdaysMin = listWeekdaysMin;
6129 hooks.defineLocale = defineLocale;
6130 hooks.updateLocale = updateLocale;
6131 hooks.locales = listLocales;
6132 hooks.weekdaysShort = listWeekdaysShort;
6133 hooks.normalizeUnits = normalizeUnits;
6134 hooks.relativeTimeRounding = getSetRelativeTimeRounding;
6135 hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
6136 hooks.calendarFormat = getCalendarFormat;
6137 hooks.prototype = proto;
6143 },{}],7:[function(require,module,exports){
6147 var Chart = require(29)();
6149 Chart.helpers = require(45);
6151 // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
6154 Chart.defaults = require(25);
6155 Chart.Element = require(26);
6156 Chart.elements = require(40);
6157 Chart.Interaction = require(28);
6158 Chart.platform = require(48);
6176 // Controllers must be loaded after elements
6177 // See Chart.core.datasetController.dataElementType
6194 // Loading built-it plugins
6203 Chart.plugins.register(plugins);
6205 Chart.platform.initialize();
6207 module.exports = Chart;
6208 if (typeof window !== 'undefined') {
6209 window.Chart = Chart;
6215 * Provided for backward compatibility, use Chart.helpers.canvas instead.
6216 * @namespace Chart.canvasHelpers
6217 * @deprecated since version 2.6.0
6218 * @todo remove at version 3
6221 Chart.canvasHelpers = Chart.helpers.canvas;
6223 },{"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":17,"18":18,"19":19,"20":20,"21":21,"22":22,"23":23,"24":24,"25":25,"26":26,"27":27,"28":28,"29":29,"30":30,"31":31,"32":32,"33":33,"35":35,"40":40,"45":45,"48":48,"49":49,"50":50,"51":51,"52":52,"53":53,"54":54,"55":55,"56":56,"57":57,"8":8,"9":9}],8:[function(require,module,exports){
6226 module.exports = function(Chart) {
6228 Chart.Bar = function(context, config) {
6229 config.type = 'bar';
6231 return new Chart(context, config);
6236 },{}],9:[function(require,module,exports){
6239 module.exports = function(Chart) {
6241 Chart.Bubble = function(context, config) {
6242 config.type = 'bubble';
6243 return new Chart(context, config);
6248 },{}],10:[function(require,module,exports){
6251 module.exports = function(Chart) {
6253 Chart.Doughnut = function(context, config) {
6254 config.type = 'doughnut';
6256 return new Chart(context, config);
6261 },{}],11:[function(require,module,exports){
6264 module.exports = function(Chart) {
6266 Chart.Line = function(context, config) {
6267 config.type = 'line';
6269 return new Chart(context, config);
6274 },{}],12:[function(require,module,exports){
6277 module.exports = function(Chart) {
6279 Chart.PolarArea = function(context, config) {
6280 config.type = 'polarArea';
6282 return new Chart(context, config);
6287 },{}],13:[function(require,module,exports){
6290 module.exports = function(Chart) {
6292 Chart.Radar = function(context, config) {
6293 config.type = 'radar';
6295 return new Chart(context, config);
6300 },{}],14:[function(require,module,exports){
6303 module.exports = function(Chart) {
6304 Chart.Scatter = function(context, config) {
6305 config.type = 'scatter';
6306 return new Chart(context, config);
6310 },{}],15:[function(require,module,exports){
6313 var defaults = require(25);
6314 var elements = require(40);
6315 var helpers = require(45);
6317 defaults._set('bar', {
6326 // Specific to Bar Controller
6327 categoryPercentage: 0.8,
6333 // grid line settings
6335 offsetGridLines: true
6345 defaults._set('horizontalBar', {
6361 // Specific to Horizontal Bar Controller
6362 categoryPercentage: 0.8,
6368 // grid line settings
6370 offsetGridLines: true
6377 borderSkipped: 'left'
6383 title: function(item, data) {
6384 // Pick first xLabel for now
6387 if (item.length > 0) {
6388 if (item[0].yLabel) {
6389 title = item[0].yLabel;
6390 } else if (data.labels.length > 0 && item[0].index < data.labels.length) {
6391 title = data.labels[item[0].index];
6398 label: function(item, data) {
6399 var datasetLabel = data.datasets[item.datasetIndex].label || '';
6400 return datasetLabel + ': ' + item.xLabel;
6408 module.exports = function(Chart) {
6410 Chart.controllers.bar = Chart.DatasetController.extend({
6412 dataElementType: elements.Rectangle,
6414 initialize: function() {
6418 Chart.DatasetController.prototype.initialize.apply(me, arguments);
6420 meta = me.getMeta();
6421 meta.stack = me.getDataset().stack;
6425 update: function(reset) {
6427 var rects = me.getMeta().data;
6430 me._ruler = me.getRuler();
6432 for (i = 0, ilen = rects.length; i < ilen; ++i) {
6433 me.updateElement(rects[i], i, reset);
6437 updateElement: function(rectangle, index, reset) {
6439 var chart = me.chart;
6440 var meta = me.getMeta();
6441 var dataset = me.getDataset();
6442 var custom = rectangle.custom || {};
6443 var rectangleOptions = chart.options.elements.rectangle;
6445 rectangle._xScale = me.getScaleForId(meta.xAxisID);
6446 rectangle._yScale = me.getScaleForId(meta.yAxisID);
6447 rectangle._datasetIndex = me.index;
6448 rectangle._index = index;
6450 rectangle._model = {
6451 datasetLabel: dataset.label,
6452 label: chart.data.labels[index],
6453 borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleOptions.borderSkipped,
6454 backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.backgroundColor, index, rectangleOptions.backgroundColor),
6455 borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.borderColor, index, rectangleOptions.borderColor),
6456 borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.borderWidth, index, rectangleOptions.borderWidth)
6459 me.updateElementGeometry(rectangle, index, reset);
6467 updateElementGeometry: function(rectangle, index, reset) {
6469 var model = rectangle._model;
6470 var vscale = me.getValueScale();
6471 var base = vscale.getBasePixel();
6472 var horizontal = vscale.isHorizontal();
6473 var ruler = me._ruler || me.getRuler();
6474 var vpixels = me.calculateBarValuePixels(me.index, index);
6475 var ipixels = me.calculateBarIndexPixels(me.index, index, ruler);
6477 model.horizontal = horizontal;
6478 model.base = reset ? base : vpixels.base;
6479 model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
6480 model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
6481 model.height = horizontal ? ipixels.size : undefined;
6482 model.width = horizontal ? undefined : ipixels.size;
6488 getValueScaleId: function() {
6489 return this.getMeta().yAxisID;
6495 getIndexScaleId: function() {
6496 return this.getMeta().xAxisID;
6502 getValueScale: function() {
6503 return this.getScaleForId(this.getValueScaleId());
6509 getIndexScale: function() {
6510 return this.getScaleForId(this.getIndexScaleId());
6514 * Returns the effective number of stacks based on groups and bar visibility.
6517 getStackCount: function(last) {
6519 var chart = me.chart;
6520 var scale = me.getIndexScale();
6521 var stacked = scale.options.stacked;
6522 var ilen = last === undefined ? chart.data.datasets.length : last + 1;
6526 for (i = 0; i < ilen; ++i) {
6527 meta = chart.getDatasetMeta(i);
6528 if (meta.bar && chart.isDatasetVisible(i) &&
6529 (stacked === false ||
6530 (stacked === true && stacks.indexOf(meta.stack) === -1) ||
6531 (stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) {
6532 stacks.push(meta.stack);
6536 return stacks.length;
6540 * Returns the stack index for the given dataset based on groups and bar visibility.
6543 getStackIndex: function(datasetIndex) {
6544 return this.getStackCount(datasetIndex) - 1;
6550 getRuler: function() {
6552 var scale = me.getIndexScale();
6553 var stackCount = me.getStackCount();
6554 var datasetIndex = me.index;
6556 var isHorizontal = scale.isHorizontal();
6557 var start = isHorizontal ? scale.left : scale.top;
6558 var end = start + (isHorizontal ? scale.width : scale.height);
6561 for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
6562 pixels.push(scale.getPixelForValue(null, i, datasetIndex));
6569 stackCount: stackCount,
6575 * Note: pixel values are not clamped to the scale area.
6578 calculateBarValuePixels: function(datasetIndex, index) {
6580 var chart = me.chart;
6581 var meta = me.getMeta();
6582 var scale = me.getValueScale();
6583 var datasets = chart.data.datasets;
6584 var value = scale.getRightValue(datasets[datasetIndex].data[index]);
6585 var stacked = scale.options.stacked;
6586 var stack = meta.stack;
6588 var i, imeta, ivalue, base, head, size;
6590 if (stacked || (stacked === undefined && stack !== undefined)) {
6591 for (i = 0; i < datasetIndex; ++i) {
6592 imeta = chart.getDatasetMeta(i);
6595 imeta.stack === stack &&
6596 imeta.controller.getValueScaleId() === scale.id &&
6597 chart.isDatasetVisible(i)) {
6599 ivalue = scale.getRightValue(datasets[i].data[index]);
6600 if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) {
6607 base = scale.getPixelForValue(start);
6608 head = scale.getPixelForValue(start + value);
6609 size = (head - base) / 2;
6615 center: head + size / 2
6622 calculateBarIndexPixels: function(datasetIndex, index, ruler) {
6624 var options = ruler.scale.options;
6625 var stackIndex = me.getStackIndex(datasetIndex);
6626 var pixels = ruler.pixels;
6627 var base = pixels[index];
6628 var length = pixels.length;
6629 var start = ruler.start;
6630 var end = ruler.end;
6631 var leftSampleSize, rightSampleSize, leftCategorySize, rightCategorySize, fullBarSize, size;
6634 leftSampleSize = base > start ? base - start : end - base;
6635 rightSampleSize = base < end ? end - base : base - start;
6638 leftSampleSize = (base - pixels[index - 1]) / 2;
6639 if (index === length - 1) {
6640 rightSampleSize = leftSampleSize;
6643 if (index < length - 1) {
6644 rightSampleSize = (pixels[index + 1] - base) / 2;
6646 leftSampleSize = rightSampleSize;
6651 leftCategorySize = leftSampleSize * options.categoryPercentage;
6652 rightCategorySize = rightSampleSize * options.categoryPercentage;
6653 fullBarSize = (leftCategorySize + rightCategorySize) / ruler.stackCount;
6654 size = fullBarSize * options.barPercentage;
6657 helpers.valueOrDefault(options.barThickness, size),
6658 helpers.valueOrDefault(options.maxBarThickness, Infinity));
6660 base -= leftCategorySize;
6661 base += fullBarSize * stackIndex;
6662 base += (fullBarSize - size) / 2;
6668 center: base + size / 2
6674 var chart = me.chart;
6675 var scale = me.getValueScale();
6676 var rects = me.getMeta().data;
6677 var dataset = me.getDataset();
6678 var ilen = rects.length;
6681 helpers.canvas.clipArea(chart.ctx, chart.chartArea);
6683 for (; i < ilen; ++i) {
6684 if (!isNaN(scale.getRightValue(dataset.data[i]))) {
6689 helpers.canvas.unclipArea(chart.ctx);
6692 setHoverStyle: function(rectangle) {
6693 var dataset = this.chart.data.datasets[rectangle._datasetIndex];
6694 var index = rectangle._index;
6695 var custom = rectangle.custom || {};
6696 var model = rectangle._model;
6698 model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.valueAtIndexOrDefault(dataset.hoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
6699 model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.valueAtIndexOrDefault(dataset.hoverBorderColor, index, helpers.getHoverColor(model.borderColor));
6700 model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.valueAtIndexOrDefault(dataset.hoverBorderWidth, index, model.borderWidth);
6703 removeHoverStyle: function(rectangle) {
6704 var dataset = this.chart.data.datasets[rectangle._datasetIndex];
6705 var index = rectangle._index;
6706 var custom = rectangle.custom || {};
6707 var model = rectangle._model;
6708 var rectangleElementOptions = this.chart.options.elements.rectangle;
6710 model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor);
6711 model.borderColor = custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor);
6712 model.borderWidth = custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.borderWidth, index, rectangleElementOptions.borderWidth);
6716 Chart.controllers.horizontalBar = Chart.controllers.bar.extend({
6720 getValueScaleId: function() {
6721 return this.getMeta().xAxisID;
6727 getIndexScaleId: function() {
6728 return this.getMeta().yAxisID;
6733 },{"25":25,"40":40,"45":45}],16:[function(require,module,exports){
6736 var defaults = require(25);
6737 var elements = require(40);
6738 var helpers = require(45);
6740 defaults._set('bubble', {
6747 type: 'linear', // bubble should probably use a linear scale by default
6749 id: 'x-axis-0' // need an ID so datasets can reference the scale
6761 // Title doesn't make sense for scatter since we format the data as a point
6764 label: function(item, data) {
6765 var datasetLabel = data.datasets[item.datasetIndex].label || '';
6766 var dataPoint = data.datasets[item.datasetIndex].data[item.index];
6767 return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
6774 module.exports = function(Chart) {
6776 Chart.controllers.bubble = Chart.DatasetController.extend({
6780 dataElementType: elements.Point,
6785 update: function(reset) {
6787 var meta = me.getMeta();
6788 var points = meta.data;
6791 helpers.each(points, function(point, index) {
6792 me.updateElement(point, index, reset);
6799 updateElement: function(point, index, reset) {
6801 var meta = me.getMeta();
6802 var custom = point.custom || {};
6803 var xScale = me.getScaleForId(meta.xAxisID);
6804 var yScale = me.getScaleForId(meta.yAxisID);
6805 var options = me._resolveElementOptions(point, index);
6806 var data = me.getDataset().data[index];
6807 var dsIndex = me.index;
6809 var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
6810 var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
6812 point._xScale = xScale;
6813 point._yScale = yScale;
6814 point._options = options;
6815 point._datasetIndex = dsIndex;
6816 point._index = index;
6818 backgroundColor: options.backgroundColor,
6819 borderColor: options.borderColor,
6820 borderWidth: options.borderWidth,
6821 hitRadius: options.hitRadius,
6822 pointStyle: options.pointStyle,
6823 radius: reset ? 0 : options.radius,
6824 skip: custom.skip || isNaN(x) || isNaN(y),
6835 setHoverStyle: function(point) {
6836 var model = point._model;
6837 var options = point._options;
6839 model.backgroundColor = helpers.valueOrDefault(options.hoverBackgroundColor, helpers.getHoverColor(options.backgroundColor));
6840 model.borderColor = helpers.valueOrDefault(options.hoverBorderColor, helpers.getHoverColor(options.borderColor));
6841 model.borderWidth = helpers.valueOrDefault(options.hoverBorderWidth, options.borderWidth);
6842 model.radius = options.radius + options.hoverRadius;
6848 removeHoverStyle: function(point) {
6849 var model = point._model;
6850 var options = point._options;
6852 model.backgroundColor = options.backgroundColor;
6853 model.borderColor = options.borderColor;
6854 model.borderWidth = options.borderWidth;
6855 model.radius = options.radius;
6861 _resolveElementOptions: function(point, index) {
6863 var chart = me.chart;
6864 var datasets = chart.data.datasets;
6865 var dataset = datasets[me.index];
6866 var custom = point.custom || {};
6867 var options = chart.options.elements.point;
6868 var resolve = helpers.options.resolve;
6869 var data = dataset.data[index];
6873 // Scriptable options
6878 datasetIndex: me.index
6885 'hoverBackgroundColor',
6893 for (i = 0, ilen = keys.length; i < ilen; ++i) {
6895 values[key] = resolve([
6902 // Custom radius resolution
6903 values.radius = resolve([
6905 data ? data.r : undefined,
6915 },{"25":25,"40":40,"45":45}],17:[function(require,module,exports){
6918 var defaults = require(25);
6919 var elements = require(40);
6920 var helpers = require(45);
6922 defaults._set('doughnut', {
6924 // Boolean - Whether we animate the rotation of the Doughnut
6925 animateRotate: true,
6926 // Boolean - Whether we animate scaling the Doughnut from the centre
6932 legendCallback: function(chart) {
6934 text.push('<ul class="' + chart.id + '-legend">');
6936 var data = chart.data;
6937 var datasets = data.datasets;
6938 var labels = data.labels;
6940 if (datasets.length) {
6941 for (var i = 0; i < datasets[0].data.length; ++i) {
6942 text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
6944 text.push(labels[i]);
6951 return text.join('');
6955 generateLabels: function(chart) {
6956 var data = chart.data;
6957 if (data.labels.length && data.datasets.length) {
6958 return data.labels.map(function(label, i) {
6959 var meta = chart.getDatasetMeta(0);
6960 var ds = data.datasets[0];
6961 var arc = meta.data[i];
6962 var custom = arc && arc.custom || {};
6963 var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
6964 var arcOpts = chart.options.elements.arc;
6965 var fill = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
6966 var stroke = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
6967 var bw = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
6972 strokeStyle: stroke,
6974 hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
6976 // Extra data used for toggling the correct item
6985 onClick: function(e, legendItem) {
6986 var index = legendItem.index;
6987 var chart = this.chart;
6990 for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
6991 meta = chart.getDatasetMeta(i);
6992 // toggle visibility of index if exists
6993 if (meta.data[index]) {
6994 meta.data[index].hidden = !meta.data[index].hidden;
7002 // The percentage of the chart that we cut out of the middle.
7003 cutoutPercentage: 50,
7005 // The rotation of the chart, where the first data arc begins.
7006 rotation: Math.PI * -0.5,
7008 // The total circumference of the chart.
7009 circumference: Math.PI * 2.0,
7011 // Need to override these to give a nice default
7017 label: function(tooltipItem, data) {
7018 var dataLabel = data.labels[tooltipItem.index];
7019 var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
7021 if (helpers.isArray(dataLabel)) {
7022 // show value on first line of multiline label
7023 // need to clone because we are changing the value
7024 dataLabel = dataLabel.slice();
7025 dataLabel[0] += value;
7036 defaults._set('pie', helpers.clone(defaults.doughnut));
7037 defaults._set('pie', {
7041 module.exports = function(Chart) {
7043 Chart.controllers.doughnut = Chart.controllers.pie = Chart.DatasetController.extend({
7045 dataElementType: elements.Arc,
7047 linkScales: helpers.noop,
7049 // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
7050 getRingIndex: function(datasetIndex) {
7053 for (var j = 0; j < datasetIndex; ++j) {
7054 if (this.chart.isDatasetVisible(j)) {
7062 update: function(reset) {
7064 var chart = me.chart;
7065 var chartArea = chart.chartArea;
7066 var opts = chart.options;
7067 var arcOpts = opts.elements.arc;
7068 var availableWidth = chartArea.right - chartArea.left - arcOpts.borderWidth;
7069 var availableHeight = chartArea.bottom - chartArea.top - arcOpts.borderWidth;
7070 var minSize = Math.min(availableWidth, availableHeight);
7071 var offset = {x: 0, y: 0};
7072 var meta = me.getMeta();
7073 var cutoutPercentage = opts.cutoutPercentage;
7074 var circumference = opts.circumference;
7076 // If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc
7077 if (circumference < Math.PI * 2.0) {
7078 var startAngle = opts.rotation % (Math.PI * 2.0);
7079 startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0);
7080 var endAngle = startAngle + circumference;
7081 var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)};
7082 var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)};
7083 var contains0 = (startAngle <= 0 && endAngle >= 0) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle);
7084 var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle);
7085 var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle);
7086 var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle);
7087 var cutout = cutoutPercentage / 100.0;
7088 var min = {x: contains180 ? -1 : Math.min(start.x * (start.x < 0 ? 1 : cutout), end.x * (end.x < 0 ? 1 : cutout)), y: contains270 ? -1 : Math.min(start.y * (start.y < 0 ? 1 : cutout), end.y * (end.y < 0 ? 1 : cutout))};
7089 var max = {x: contains0 ? 1 : Math.max(start.x * (start.x > 0 ? 1 : cutout), end.x * (end.x > 0 ? 1 : cutout)), y: contains90 ? 1 : Math.max(start.y * (start.y > 0 ? 1 : cutout), end.y * (end.y > 0 ? 1 : cutout))};
7090 var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5};
7091 minSize = Math.min(availableWidth / size.width, availableHeight / size.height);
7092 offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5};
7095 chart.borderWidth = me.getMaxBorderWidth(meta.data);
7096 chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0);
7097 chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0);
7098 chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
7099 chart.offsetX = offset.x * chart.outerRadius;
7100 chart.offsetY = offset.y * chart.outerRadius;
7102 meta.total = me.calculateTotal();
7104 me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index));
7105 me.innerRadius = Math.max(me.outerRadius - chart.radiusLength, 0);
7107 helpers.each(meta.data, function(arc, index) {
7108 me.updateElement(arc, index, reset);
7112 updateElement: function(arc, index, reset) {
7114 var chart = me.chart;
7115 var chartArea = chart.chartArea;
7116 var opts = chart.options;
7117 var animationOpts = opts.animation;
7118 var centerX = (chartArea.left + chartArea.right) / 2;
7119 var centerY = (chartArea.top + chartArea.bottom) / 2;
7120 var startAngle = opts.rotation; // non reset case handled later
7121 var endAngle = opts.rotation; // non reset case handled later
7122 var dataset = me.getDataset();
7123 var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI));
7124 var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
7125 var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
7126 var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
7128 helpers.extend(arc, {
7130 _datasetIndex: me.index,
7133 // Desired view properties
7135 x: centerX + chart.offsetX,
7136 y: centerY + chart.offsetY,
7137 startAngle: startAngle,
7139 circumference: circumference,
7140 outerRadius: outerRadius,
7141 innerRadius: innerRadius,
7142 label: valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
7146 var model = arc._model;
7147 // Resets the visual styles
7148 this.removeHoverStyle(arc);
7150 // Set correct angles if not resetting
7151 if (!reset || !animationOpts.animateRotate) {
7153 model.startAngle = opts.rotation;
7155 model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
7158 model.endAngle = model.startAngle + model.circumference;
7164 removeHoverStyle: function(arc) {
7165 Chart.DatasetController.prototype.removeHoverStyle.call(this, arc, this.chart.options.elements.arc);
7168 calculateTotal: function() {
7169 var dataset = this.getDataset();
7170 var meta = this.getMeta();
7174 helpers.each(meta.data, function(element, index) {
7175 value = dataset.data[index];
7176 if (!isNaN(value) && !element.hidden) {
7177 total += Math.abs(value);
7181 /* if (total === 0) {
7188 calculateCircumference: function(value) {
7189 var total = this.getMeta().total;
7190 if (total > 0 && !isNaN(value)) {
7191 return (Math.PI * 2.0) * (value / total);
7196 // gets the max border or hover width to properly scale pie charts
7197 getMaxBorderWidth: function(arcs) {
7199 var index = this.index;
7200 var length = arcs.length;
7204 for (var i = 0; i < length; i++) {
7205 borderWidth = arcs[i]._model ? arcs[i]._model.borderWidth : 0;
7206 hoverWidth = arcs[i]._chart ? arcs[i]._chart.config.data.datasets[index].hoverBorderWidth : 0;
7208 max = borderWidth > max ? borderWidth : max;
7209 max = hoverWidth > max ? hoverWidth : max;
7216 },{"25":25,"40":40,"45":45}],18:[function(require,module,exports){
7219 var defaults = require(25);
7220 var elements = require(40);
7221 var helpers = require(45);
7223 defaults._set('line', {
7243 module.exports = function(Chart) {
7245 function lineEnabled(dataset, options) {
7246 return helpers.valueOrDefault(dataset.showLine, options.showLines);
7249 Chart.controllers.line = Chart.DatasetController.extend({
7251 datasetElementType: elements.Line,
7253 dataElementType: elements.Point,
7255 update: function(reset) {
7257 var meta = me.getMeta();
7258 var line = meta.dataset;
7259 var points = meta.data || [];
7260 var options = me.chart.options;
7261 var lineElementOptions = options.elements.line;
7262 var scale = me.getScaleForId(meta.yAxisID);
7263 var i, ilen, custom;
7264 var dataset = me.getDataset();
7265 var showLine = lineEnabled(dataset, options);
7269 custom = line.custom || {};
7271 // Compatibility: If the properties are defined with only the old name, use those values
7272 if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
7273 dataset.lineTension = dataset.tension;
7277 line._scale = scale;
7278 line._datasetIndex = me.index;
7280 line._children = points;
7284 // The default behavior of lines is to break at null values, according
7285 // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
7286 // This option gives lines the ability to span gaps
7287 spanGaps: dataset.spanGaps ? dataset.spanGaps : options.spanGaps,
7288 tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension),
7289 backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),
7290 borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),
7291 borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),
7292 borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),
7293 borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),
7294 borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),
7295 borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),
7296 fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),
7297 steppedLine: custom.steppedLine ? custom.steppedLine : helpers.valueOrDefault(dataset.steppedLine, lineElementOptions.stepped),
7298 cubicInterpolationMode: custom.cubicInterpolationMode ? custom.cubicInterpolationMode : helpers.valueOrDefault(dataset.cubicInterpolationMode, lineElementOptions.cubicInterpolationMode),
7305 for (i = 0, ilen = points.length; i < ilen; ++i) {
7306 me.updateElement(points[i], i, reset);
7309 if (showLine && line._model.tension !== 0) {
7310 me.updateBezierControlPoints();
7313 // Now pivot the point for animation
7314 for (i = 0, ilen = points.length; i < ilen; ++i) {
7319 getPointBackgroundColor: function(point, index) {
7320 var backgroundColor = this.chart.options.elements.point.backgroundColor;
7321 var dataset = this.getDataset();
7322 var custom = point.custom || {};
7324 if (custom.backgroundColor) {
7325 backgroundColor = custom.backgroundColor;
7326 } else if (dataset.pointBackgroundColor) {
7327 backgroundColor = helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, backgroundColor);
7328 } else if (dataset.backgroundColor) {
7329 backgroundColor = dataset.backgroundColor;
7332 return backgroundColor;
7335 getPointBorderColor: function(point, index) {
7336 var borderColor = this.chart.options.elements.point.borderColor;
7337 var dataset = this.getDataset();
7338 var custom = point.custom || {};
7340 if (custom.borderColor) {
7341 borderColor = custom.borderColor;
7342 } else if (dataset.pointBorderColor) {
7343 borderColor = helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, borderColor);
7344 } else if (dataset.borderColor) {
7345 borderColor = dataset.borderColor;
7351 getPointBorderWidth: function(point, index) {
7352 var borderWidth = this.chart.options.elements.point.borderWidth;
7353 var dataset = this.getDataset();
7354 var custom = point.custom || {};
7356 if (!isNaN(custom.borderWidth)) {
7357 borderWidth = custom.borderWidth;
7358 } else if (!isNaN(dataset.pointBorderWidth) || helpers.isArray(dataset.pointBorderWidth)) {
7359 borderWidth = helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, borderWidth);
7360 } else if (!isNaN(dataset.borderWidth)) {
7361 borderWidth = dataset.borderWidth;
7367 updateElement: function(point, index, reset) {
7369 var meta = me.getMeta();
7370 var custom = point.custom || {};
7371 var dataset = me.getDataset();
7372 var datasetIndex = me.index;
7373 var value = dataset.data[index];
7374 var yScale = me.getScaleForId(meta.yAxisID);
7375 var xScale = me.getScaleForId(meta.xAxisID);
7376 var pointOptions = me.chart.options.elements.point;
7379 // Compatibility: If the properties are defined with only the old name, use those values
7380 if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
7381 dataset.pointRadius = dataset.radius;
7383 if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {
7384 dataset.pointHitRadius = dataset.hitRadius;
7387 x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
7388 y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
7391 point._xScale = xScale;
7392 point._yScale = yScale;
7393 point._datasetIndex = datasetIndex;
7394 point._index = index;
7396 // Desired view properties
7400 skip: custom.skip || isNaN(x) || isNaN(y),
7402 radius: custom.radius || helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointOptions.radius),
7403 pointStyle: custom.pointStyle || helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointOptions.pointStyle),
7404 backgroundColor: me.getPointBackgroundColor(point, index),
7405 borderColor: me.getPointBorderColor(point, index),
7406 borderWidth: me.getPointBorderWidth(point, index),
7407 tension: meta.dataset._model ? meta.dataset._model.tension : 0,
7408 steppedLine: meta.dataset._model ? meta.dataset._model.steppedLine : false,
7410 hitRadius: custom.hitRadius || helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointOptions.hitRadius)
7414 calculatePointY: function(value, index, datasetIndex) {
7416 var chart = me.chart;
7417 var meta = me.getMeta();
7418 var yScale = me.getScaleForId(meta.yAxisID);
7423 if (yScale.options.stacked) {
7424 for (i = 0; i < datasetIndex; i++) {
7425 ds = chart.data.datasets[i];
7426 dsMeta = chart.getDatasetMeta(i);
7427 if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) {
7428 var stackedRightValue = Number(yScale.getRightValue(ds.data[index]));
7429 if (stackedRightValue < 0) {
7430 sumNeg += stackedRightValue || 0;
7432 sumPos += stackedRightValue || 0;
7437 var rightValue = Number(yScale.getRightValue(value));
7438 if (rightValue < 0) {
7439 return yScale.getPixelForValue(sumNeg + rightValue);
7441 return yScale.getPixelForValue(sumPos + rightValue);
7444 return yScale.getPixelForValue(value);
7447 updateBezierControlPoints: function() {
7449 var meta = me.getMeta();
7450 var area = me.chart.chartArea;
7451 var points = (meta.data || []);
7452 var i, ilen, point, model, controlPoints;
7454 // Only consider points that are drawn in case the spanGaps option is used
7455 if (meta.dataset._model.spanGaps) {
7456 points = points.filter(function(pt) {
7457 return !pt._model.skip;
7461 function capControlPoint(pt, min, max) {
7462 return Math.max(Math.min(pt, max), min);
7465 if (meta.dataset._model.cubicInterpolationMode === 'monotone') {
7466 helpers.splineCurveMonotone(points);
7468 for (i = 0, ilen = points.length; i < ilen; ++i) {
7470 model = point._model;
7471 controlPoints = helpers.splineCurve(
7472 helpers.previousItem(points, i)._model,
7474 helpers.nextItem(points, i)._model,
7475 meta.dataset._model.tension
7477 model.controlPointPreviousX = controlPoints.previous.x;
7478 model.controlPointPreviousY = controlPoints.previous.y;
7479 model.controlPointNextX = controlPoints.next.x;
7480 model.controlPointNextY = controlPoints.next.y;
7484 if (me.chart.options.elements.line.capBezierPoints) {
7485 for (i = 0, ilen = points.length; i < ilen; ++i) {
7486 model = points[i]._model;
7487 model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
7488 model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
7489 model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
7490 model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
7497 var chart = me.chart;
7498 var meta = me.getMeta();
7499 var points = meta.data || [];
7500 var area = chart.chartArea;
7501 var ilen = points.length;
7504 helpers.canvas.clipArea(chart.ctx, area);
7506 if (lineEnabled(me.getDataset(), chart.options)) {
7507 meta.dataset.draw();
7510 helpers.canvas.unclipArea(chart.ctx);
7513 for (; i < ilen; ++i) {
7514 points[i].draw(area);
7518 setHoverStyle: function(point) {
7520 var dataset = this.chart.data.datasets[point._datasetIndex];
7521 var index = point._index;
7522 var custom = point.custom || {};
7523 var model = point._model;
7525 model.radius = custom.hoverRadius || helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);
7526 model.backgroundColor = custom.hoverBackgroundColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
7527 model.borderColor = custom.hoverBorderColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));
7528 model.borderWidth = custom.hoverBorderWidth || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);
7531 removeHoverStyle: function(point) {
7533 var dataset = me.chart.data.datasets[point._datasetIndex];
7534 var index = point._index;
7535 var custom = point.custom || {};
7536 var model = point._model;
7538 // Compatibility: If the properties are defined with only the old name, use those values
7539 if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
7540 dataset.pointRadius = dataset.radius;
7543 model.radius = custom.radius || helpers.valueAtIndexOrDefault(dataset.pointRadius, index, me.chart.options.elements.point.radius);
7544 model.backgroundColor = me.getPointBackgroundColor(point, index);
7545 model.borderColor = me.getPointBorderColor(point, index);
7546 model.borderWidth = me.getPointBorderWidth(point, index);
7551 },{"25":25,"40":40,"45":45}],19:[function(require,module,exports){
7554 var defaults = require(25);
7555 var elements = require(40);
7556 var helpers = require(45);
7558 defaults._set('polarArea', {
7560 type: 'radialLinear',
7575 // Boolean - Whether to animate the rotation of the chart
7577 animateRotate: true,
7581 startAngle: -0.5 * Math.PI,
7582 legendCallback: function(chart) {
7584 text.push('<ul class="' + chart.id + '-legend">');
7586 var data = chart.data;
7587 var datasets = data.datasets;
7588 var labels = data.labels;
7590 if (datasets.length) {
7591 for (var i = 0; i < datasets[0].data.length; ++i) {
7592 text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
7594 text.push(labels[i]);
7601 return text.join('');
7605 generateLabels: function(chart) {
7606 var data = chart.data;
7607 if (data.labels.length && data.datasets.length) {
7608 return data.labels.map(function(label, i) {
7609 var meta = chart.getDatasetMeta(0);
7610 var ds = data.datasets[0];
7611 var arc = meta.data[i];
7612 var custom = arc.custom || {};
7613 var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
7614 var arcOpts = chart.options.elements.arc;
7615 var fill = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
7616 var stroke = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
7617 var bw = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
7622 strokeStyle: stroke,
7624 hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
7626 // Extra data used for toggling the correct item
7635 onClick: function(e, legendItem) {
7636 var index = legendItem.index;
7637 var chart = this.chart;
7640 for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
7641 meta = chart.getDatasetMeta(i);
7642 meta.data[index].hidden = !meta.data[index].hidden;
7649 // Need to override these to give a nice default
7655 label: function(item, data) {
7656 return data.labels[item.index] + ': ' + item.yLabel;
7662 module.exports = function(Chart) {
7664 Chart.controllers.polarArea = Chart.DatasetController.extend({
7666 dataElementType: elements.Arc,
7668 linkScales: helpers.noop,
7670 update: function(reset) {
7672 var chart = me.chart;
7673 var chartArea = chart.chartArea;
7674 var meta = me.getMeta();
7675 var opts = chart.options;
7676 var arcOpts = opts.elements.arc;
7677 var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
7678 chart.outerRadius = Math.max((minSize - arcOpts.borderWidth / 2) / 2, 0);
7679 chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
7680 chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
7682 me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
7683 me.innerRadius = me.outerRadius - chart.radiusLength;
7685 meta.count = me.countVisibleElements();
7687 helpers.each(meta.data, function(arc, index) {
7688 me.updateElement(arc, index, reset);
7692 updateElement: function(arc, index, reset) {
7694 var chart = me.chart;
7695 var dataset = me.getDataset();
7696 var opts = chart.options;
7697 var animationOpts = opts.animation;
7698 var scale = chart.scale;
7699 var labels = chart.data.labels;
7701 var circumference = me.calculateCircumference(dataset.data[index]);
7702 var centerX = scale.xCenter;
7703 var centerY = scale.yCenter;
7705 // If there is NaN data before us, we need to calculate the starting angle correctly.
7706 // We could be way more efficient here, but its unlikely that the polar area chart will have a lot of data
7707 var visibleCount = 0;
7708 var meta = me.getMeta();
7709 for (var i = 0; i < index; ++i) {
7710 if (!isNaN(dataset.data[i]) && !meta.data[i].hidden) {
7715 // var negHalfPI = -0.5 * Math.PI;
7716 var datasetStartAngle = opts.startAngle;
7717 var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
7718 var startAngle = datasetStartAngle + (circumference * visibleCount);
7719 var endAngle = startAngle + (arc.hidden ? 0 : circumference);
7721 var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
7723 helpers.extend(arc, {
7725 _datasetIndex: me.index,
7729 // Desired view properties
7734 outerRadius: reset ? resetRadius : distance,
7735 startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
7736 endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
7737 label: helpers.valueAtIndexOrDefault(labels, index, labels[index])
7741 // Apply border and fill style
7742 me.removeHoverStyle(arc);
7747 removeHoverStyle: function(arc) {
7748 Chart.DatasetController.prototype.removeHoverStyle.call(this, arc, this.chart.options.elements.arc);
7751 countVisibleElements: function() {
7752 var dataset = this.getDataset();
7753 var meta = this.getMeta();
7756 helpers.each(meta.data, function(element, index) {
7757 if (!isNaN(dataset.data[index]) && !element.hidden) {
7765 calculateCircumference: function(value) {
7766 var count = this.getMeta().count;
7767 if (count > 0 && !isNaN(value)) {
7768 return (2 * Math.PI) / count;
7775 },{"25":25,"40":40,"45":45}],20:[function(require,module,exports){
7778 var defaults = require(25);
7779 var elements = require(40);
7780 var helpers = require(45);
7782 defaults._set('radar', {
7784 type: 'radialLinear'
7788 tension: 0 // no bezier in radar
7793 module.exports = function(Chart) {
7795 Chart.controllers.radar = Chart.DatasetController.extend({
7797 datasetElementType: elements.Line,
7799 dataElementType: elements.Point,
7801 linkScales: helpers.noop,
7803 update: function(reset) {
7805 var meta = me.getMeta();
7806 var line = meta.dataset;
7807 var points = meta.data;
7808 var custom = line.custom || {};
7809 var dataset = me.getDataset();
7810 var lineElementOptions = me.chart.options.elements.line;
7811 var scale = me.chart.scale;
7813 // Compatibility: If the properties are defined with only the old name, use those values
7814 if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
7815 dataset.lineTension = dataset.tension;
7818 helpers.extend(meta.dataset, {
7820 _datasetIndex: me.index,
7828 tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension),
7829 backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),
7830 borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),
7831 borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),
7832 fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),
7833 borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),
7834 borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),
7835 borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),
7836 borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),
7840 meta.dataset.pivot();
7843 helpers.each(points, function(point, index) {
7844 me.updateElement(point, index, reset);
7847 // Update bezier control points
7848 me.updateBezierControlPoints();
7850 updateElement: function(point, index, reset) {
7852 var custom = point.custom || {};
7853 var dataset = me.getDataset();
7854 var scale = me.chart.scale;
7855 var pointElementOptions = me.chart.options.elements.point;
7856 var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
7858 // Compatibility: If the properties are defined with only the old name, use those values
7859 if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
7860 dataset.pointRadius = dataset.radius;
7862 if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {
7863 dataset.pointHitRadius = dataset.hitRadius;
7866 helpers.extend(point, {
7868 _datasetIndex: me.index,
7872 // Desired view properties
7874 x: reset ? scale.xCenter : pointPosition.x, // value not used in dataset scale, but we want a consistent API between scales
7875 y: reset ? scale.yCenter : pointPosition.y,
7878 tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, me.chart.options.elements.line.tension),
7879 radius: custom.radius ? custom.radius : helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius),
7880 backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor),
7881 borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor),
7882 borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth),
7883 pointStyle: custom.pointStyle ? custom.pointStyle : helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointElementOptions.pointStyle),
7886 hitRadius: custom.hitRadius ? custom.hitRadius : helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointElementOptions.hitRadius)
7890 point._model.skip = custom.skip ? custom.skip : (isNaN(point._model.x) || isNaN(point._model.y));
7892 updateBezierControlPoints: function() {
7893 var chartArea = this.chart.chartArea;
7894 var meta = this.getMeta();
7896 helpers.each(meta.data, function(point, index) {
7897 var model = point._model;
7898 var controlPoints = helpers.splineCurve(
7899 helpers.previousItem(meta.data, index, true)._model,
7901 helpers.nextItem(meta.data, index, true)._model,
7905 // Prevent the bezier going outside of the bounds of the graph
7906 model.controlPointPreviousX = Math.max(Math.min(controlPoints.previous.x, chartArea.right), chartArea.left);
7907 model.controlPointPreviousY = Math.max(Math.min(controlPoints.previous.y, chartArea.bottom), chartArea.top);
7909 model.controlPointNextX = Math.max(Math.min(controlPoints.next.x, chartArea.right), chartArea.left);
7910 model.controlPointNextY = Math.max(Math.min(controlPoints.next.y, chartArea.bottom), chartArea.top);
7912 // Now pivot the point for animation
7917 setHoverStyle: function(point) {
7919 var dataset = this.chart.data.datasets[point._datasetIndex];
7920 var custom = point.custom || {};
7921 var index = point._index;
7922 var model = point._model;
7924 model.radius = custom.hoverRadius ? custom.hoverRadius : helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);
7925 model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
7926 model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));
7927 model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);
7930 removeHoverStyle: function(point) {
7931 var dataset = this.chart.data.datasets[point._datasetIndex];
7932 var custom = point.custom || {};
7933 var index = point._index;
7934 var model = point._model;
7935 var pointElementOptions = this.chart.options.elements.point;
7937 model.radius = custom.radius ? custom.radius : helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius);
7938 model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor);
7939 model.borderColor = custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor);
7940 model.borderWidth = custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth);
7945 },{"25":25,"40":40,"45":45}],21:[function(require,module,exports){
7948 var defaults = require(25);
7950 defaults._set('scatter', {
7957 id: 'x-axis-1', // need an ID so datasets can reference the scale
7958 type: 'linear', // scatter should not use a category axis
7973 return ''; // doesn't make sense for scatter since data are formatted as a point
7975 label: function(item) {
7976 return '(' + item.xLabel + ', ' + item.yLabel + ')';
7982 module.exports = function(Chart) {
7984 // Scatter charts use line controllers
7985 Chart.controllers.scatter = Chart.controllers.line;
7989 },{"25":25}],22:[function(require,module,exports){
7990 /* global window: false */
7993 var defaults = require(25);
7994 var Element = require(26);
7995 var helpers = require(45);
7997 defaults._set('global', {
8000 easing: 'easeOutQuart',
8001 onProgress: helpers.noop,
8002 onComplete: helpers.noop
8006 module.exports = function(Chart) {
8008 Chart.Animation = Element.extend({
8009 chart: null, // the animation associated chart instance
8010 currentStep: 0, // the current animation step
8011 numSteps: 60, // default number of steps
8012 easing: '', // the easing to use for this animation
8013 render: null, // render function used by the animation service
8015 onAnimationProgress: null, // user specified callback to fire on each step of the animation
8016 onAnimationComplete: null, // user specified callback to fire when the animation finishes
8019 Chart.animationService = {
8026 * @param {Chart} chart - The chart to animate.
8027 * @param {Chart.Animation} animation - The animation that we will animate.
8028 * @param {Number} duration - The animation duration in ms.
8029 * @param {Boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
8031 addAnimation: function(chart, animation, duration, lazy) {
8032 var animations = this.animations;
8035 animation.chart = chart;
8038 chart.animating = true;
8041 for (i = 0, ilen = animations.length; i < ilen; ++i) {
8042 if (animations[i].chart === chart) {
8043 animations[i] = animation;
8048 animations.push(animation);
8050 // If there are no animations queued, manually kickstart a digest, for lack of a better word
8051 if (animations.length === 1) {
8052 this.requestAnimationFrame();
8056 cancelAnimation: function(chart) {
8057 var index = helpers.findIndex(this.animations, function(animation) {
8058 return animation.chart === chart;
8062 this.animations.splice(index, 1);
8063 chart.animating = false;
8067 requestAnimationFrame: function() {
8069 if (me.request === null) {
8070 // Skip animation frame requests until the active one is executed.
8071 // This can happen when processing mouse events, e.g. 'mousemove'
8072 // and 'mouseout' events will trigger multiple renders.
8073 me.request = helpers.requestAnimFrame.call(window, function() {
8083 startDigest: function() {
8085 var startTime = Date.now();
8086 var framesToDrop = 0;
8088 if (me.dropFrames > 1) {
8089 framesToDrop = Math.floor(me.dropFrames);
8090 me.dropFrames = me.dropFrames % 1;
8093 me.advance(1 + framesToDrop);
8095 var endTime = Date.now();
8097 me.dropFrames += (endTime - startTime) / me.frameDuration;
8099 // Do we have more stuff to animate?
8100 if (me.animations.length > 0) {
8101 me.requestAnimationFrame();
8108 advance: function(count) {
8109 var animations = this.animations;
8110 var animation, chart;
8113 while (i < animations.length) {
8114 animation = animations[i];
8115 chart = animation.chart;
8117 animation.currentStep = (animation.currentStep || 0) + count;
8118 animation.currentStep = Math.min(animation.currentStep, animation.numSteps);
8120 helpers.callback(animation.render, [chart, animation], chart);
8121 helpers.callback(animation.onAnimationProgress, [animation], chart);
8123 if (animation.currentStep >= animation.numSteps) {
8124 helpers.callback(animation.onAnimationComplete, [animation], chart);
8125 chart.animating = false;
8126 animations.splice(i, 1);
8135 * Provided for backward compatibility, use Chart.Animation instead
8136 * @prop Chart.Animation#animationObject
8137 * @deprecated since version 2.6.0
8138 * @todo remove at version 3
8140 Object.defineProperty(Chart.Animation.prototype, 'animationObject', {
8147 * Provided for backward compatibility, use Chart.Animation#chart instead
8148 * @prop Chart.Animation#chartInstance
8149 * @deprecated since version 2.6.0
8150 * @todo remove at version 3
8152 Object.defineProperty(Chart.Animation.prototype, 'chartInstance', {
8156 set: function(value) {
8163 },{"25":25,"26":26,"45":45}],23:[function(require,module,exports){
8166 var defaults = require(25);
8167 var helpers = require(45);
8168 var Interaction = require(28);
8169 var platform = require(48);
8171 module.exports = function(Chart) {
8172 var plugins = Chart.plugins;
8174 // Create a dictionary of chart types, to allow for extension of existing types
8177 // Store a reference to each instance - allowing us to globally resize chart instances on window resize.
8178 // Destroy method on the chart will remove the instance of the chart from this reference.
8179 Chart.instances = {};
8181 // Controllers available for dataset visualization eg. bar, line, slice, etc.
8182 Chart.controllers = {};
8185 * Initializes the given config with global and chart default values.
8187 function initConfig(config) {
8188 config = config || {};
8190 // Do NOT use configMerge() for the data object because this method merges arrays
8191 // and so would change references to labels and datasets, preventing data updates.
8192 var data = config.data = config.data || {};
8193 data.datasets = data.datasets || [];
8194 data.labels = data.labels || [];
8196 config.options = helpers.configMerge(
8198 defaults[config.type],
8199 config.options || {});
8205 * Updates the config of the chart
8206 * @param chart {Chart} chart to update the options for
8208 function updateConfig(chart) {
8209 var newOptions = chart.options;
8211 // Update Scale(s) with options
8212 if (newOptions.scale) {
8213 chart.scale.options = newOptions.scale;
8214 } else if (newOptions.scales) {
8215 newOptions.scales.xAxes.concat(newOptions.scales.yAxes).forEach(function(scaleOptions) {
8216 chart.scales[scaleOptions.id].options = scaleOptions;
8221 chart.tooltip._options = newOptions.tooltips;
8224 function positionIsHorizontal(position) {
8225 return position === 'top' || position === 'bottom';
8228 helpers.extend(Chart.prototype, /** @lends Chart */ {
8232 construct: function(item, config) {
8235 config = initConfig(config);
8237 var context = platform.acquireContext(item, config);
8238 var canvas = context && context.canvas;
8239 var height = canvas && canvas.height;
8240 var width = canvas && canvas.width;
8242 me.id = helpers.uid();
8248 me.aspectRatio = height ? width / height : null;
8249 me.options = config.options;
8250 me._bufferedRender = false;
8253 * Provided for backward compatibility, Chart and Chart.Controller have been merged,
8254 * the "instance" still need to be defined since it might be called from plugins.
8256 * @deprecated since version 2.6.0
8257 * @todo remove at version 3
8261 me.controller = me; // chart.chart.controller #inception
8263 // Add the chart instance to the global namespace
8264 Chart.instances[me.id] = me;
8266 // Define alias to the config data: `chart.data === chart.config.data`
8267 Object.defineProperty(me, 'data', {
8269 return me.config.data;
8271 set: function(value) {
8272 me.config.data = value;
8276 if (!context || !canvas) {
8277 // The given item is not a compatible context2d element, let's return before finalizing
8278 // the chart initialization but after setting basic chart / controller properties that
8279 // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
8280 // https://github.com/chartjs/Chart.js/issues/2807
8281 console.error("Failed to create chart: can't acquire context from the given item");
8292 initialize: function() {
8295 // Before init plugin notification
8296 plugins.notify(me, 'beforeInit');
8298 helpers.retinaScale(me, me.options.devicePixelRatio);
8302 if (me.options.responsive) {
8303 // Initial resize before chart draws (must be silent to preserve initial animations).
8307 // Make sure scales have IDs and are built before we build any controllers.
8308 me.ensureScalesHaveIDs();
8312 // After init plugin notification
8313 plugins.notify(me, 'afterInit');
8319 helpers.canvas.clear(this);
8324 // Stops any current animation loop occurring
8325 Chart.animationService.cancelAnimation(this);
8329 resize: function(silent) {
8331 var options = me.options;
8332 var canvas = me.canvas;
8333 var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
8335 // the canvas render width and height will be casted to integers so make sure that
8336 // the canvas display style uses the same integer values to avoid blurring effect.
8338 // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collased
8339 var newWidth = Math.max(0, Math.floor(helpers.getMaximumWidth(canvas)));
8340 var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers.getMaximumHeight(canvas)));
8342 if (me.width === newWidth && me.height === newHeight) {
8346 canvas.width = me.width = newWidth;
8347 canvas.height = me.height = newHeight;
8348 canvas.style.width = newWidth + 'px';
8349 canvas.style.height = newHeight + 'px';
8351 helpers.retinaScale(me, options.devicePixelRatio);
8354 // Notify any plugins about the resize
8355 var newSize = {width: newWidth, height: newHeight};
8356 plugins.notify(me, 'resize', [newSize]);
8359 if (me.options.onResize) {
8360 me.options.onResize(me, newSize);
8364 me.update(me.options.responsiveAnimationDuration);
8368 ensureScalesHaveIDs: function() {
8369 var options = this.options;
8370 var scalesOptions = options.scales || {};
8371 var scaleOptions = options.scale;
8373 helpers.each(scalesOptions.xAxes, function(xAxisOptions, index) {
8374 xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index);
8377 helpers.each(scalesOptions.yAxes, function(yAxisOptions, index) {
8378 yAxisOptions.id = yAxisOptions.id || ('y-axis-' + index);
8382 scaleOptions.id = scaleOptions.id || 'scale';
8387 * Builds a map of scale ID to scale object for future lookup.
8389 buildScales: function() {
8391 var options = me.options;
8392 var scales = me.scales = {};
8395 if (options.scales) {
8396 items = items.concat(
8397 (options.scales.xAxes || []).map(function(xAxisOptions) {
8398 return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
8400 (options.scales.yAxes || []).map(function(yAxisOptions) {
8401 return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
8406 if (options.scale) {
8408 options: options.scale,
8409 dtype: 'radialLinear',
8411 dposition: 'chartArea'
8415 helpers.each(items, function(item) {
8416 var scaleOptions = item.options;
8417 var scaleType = helpers.valueOrDefault(scaleOptions.type, item.dtype);
8418 var scaleClass = Chart.scaleService.getScaleConstructor(scaleType);
8423 if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
8424 scaleOptions.position = item.dposition;
8427 var scale = new scaleClass({
8428 id: scaleOptions.id,
8429 options: scaleOptions,
8434 scales[scale.id] = scale;
8435 scale.mergeTicksOptions();
8437 // TODO(SB): I think we should be able to remove this custom case (options.scale)
8438 // and consider it as a regular scale part of the "scales"" map only! This would
8439 // make the logic easier and remove some useless? custom code.
8440 if (item.isDefault) {
8445 Chart.scaleService.addScalesToLayout(this);
8448 buildOrUpdateControllers: function() {
8451 var newControllers = [];
8453 helpers.each(me.data.datasets, function(dataset, datasetIndex) {
8454 var meta = me.getDatasetMeta(datasetIndex);
8455 var type = dataset.type || me.config.type;
8457 if (meta.type && meta.type !== type) {
8458 me.destroyDatasetMeta(datasetIndex);
8459 meta = me.getDatasetMeta(datasetIndex);
8463 types.push(meta.type);
8465 if (meta.controller) {
8466 meta.controller.updateIndex(datasetIndex);
8468 var ControllerClass = Chart.controllers[meta.type];
8469 if (ControllerClass === undefined) {
8470 throw new Error('"' + meta.type + '" is not a chart type.');
8473 meta.controller = new ControllerClass(me, datasetIndex);
8474 newControllers.push(meta.controller);
8478 return newControllers;
8482 * Reset the elements of all datasets
8485 resetElements: function() {
8487 helpers.each(me.data.datasets, function(dataset, datasetIndex) {
8488 me.getDatasetMeta(datasetIndex).controller.reset();
8493 * Resets the chart back to it's state before the initial animation
8496 this.resetElements();
8497 this.tooltip.initialize();
8500 update: function(config) {
8503 if (!config || typeof config !== 'object') {
8504 // backwards compatibility
8513 if (plugins.notify(me, 'beforeUpdate') === false) {
8517 // In case the entire data object changed
8518 me.tooltip._data = me.data;
8520 // Make sure dataset controllers are updated and new controllers are reset
8521 var newControllers = me.buildOrUpdateControllers();
8523 // Make sure all dataset controllers have correct meta data counts
8524 helpers.each(me.data.datasets, function(dataset, datasetIndex) {
8525 me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements();
8530 // Can only reset the new controllers after the scales have been updated
8531 helpers.each(newControllers, function(controller) {
8535 me.updateDatasets();
8537 // Do this before render so that any plugins that need final scale updates can use it
8538 plugins.notify(me, 'afterUpdate');
8540 if (me._bufferedRender) {
8541 me._bufferedRequest = {
8542 duration: config.duration,
8543 easing: config.easing,
8552 * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
8553 * hook, in which case, plugins will not be called on `afterLayout`.
8556 updateLayout: function() {
8559 if (plugins.notify(me, 'beforeLayout') === false) {
8563 Chart.layoutService.update(this, this.width, this.height);
8566 * Provided for backward compatibility, use `afterLayout` instead.
8567 * @method IPlugin#afterScaleUpdate
8568 * @deprecated since version 2.5.0
8569 * @todo remove at version 3
8572 plugins.notify(me, 'afterScaleUpdate');
8573 plugins.notify(me, 'afterLayout');
8577 * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
8578 * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
8581 updateDatasets: function() {
8584 if (plugins.notify(me, 'beforeDatasetsUpdate') === false) {
8588 for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
8589 me.updateDataset(i);
8592 plugins.notify(me, 'afterDatasetsUpdate');
8596 * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
8597 * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
8600 updateDataset: function(index) {
8602 var meta = me.getDatasetMeta(index);
8608 if (plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
8612 meta.controller.update();
8614 plugins.notify(me, 'afterDatasetUpdate', [args]);
8617 render: function(config) {
8620 if (!config || typeof config !== 'object') {
8621 // backwards compatibility
8628 var duration = config.duration;
8629 var lazy = config.lazy;
8631 if (plugins.notify(me, 'beforeRender') === false) {
8635 var animationOptions = me.options.animation;
8636 var onComplete = function(animation) {
8637 plugins.notify(me, 'afterRender');
8638 helpers.callback(animationOptions && animationOptions.onComplete, [animation], me);
8641 if (animationOptions && ((typeof duration !== 'undefined' && duration !== 0) || (typeof duration === 'undefined' && animationOptions.duration !== 0))) {
8642 var animation = new Chart.Animation({
8643 numSteps: (duration || animationOptions.duration) / 16.66, // 60 fps
8644 easing: config.easing || animationOptions.easing,
8646 render: function(chart, animationObject) {
8647 var easingFunction = helpers.easing.effects[animationObject.easing];
8648 var currentStep = animationObject.currentStep;
8649 var stepDecimal = currentStep / animationObject.numSteps;
8651 chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
8654 onAnimationProgress: animationOptions.onProgress,
8655 onAnimationComplete: onComplete
8658 Chart.animationService.addAnimation(me, animation, duration, lazy);
8662 // See https://github.com/chartjs/Chart.js/issues/3781
8663 onComplete(new Chart.Animation({numSteps: 0, chart: me}));
8669 draw: function(easingValue) {
8674 if (helpers.isNullOrUndef(easingValue)) {
8678 me.transition(easingValue);
8680 if (plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
8684 // Draw all the scales
8685 helpers.each(me.boxes, function(box) {
8686 box.draw(me.chartArea);
8693 me.drawDatasets(easingValue);
8695 // Finally draw the tooltip
8698 plugins.notify(me, 'afterDraw', [easingValue]);
8704 transition: function(easingValue) {
8707 for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
8708 if (me.isDatasetVisible(i)) {
8709 me.getDatasetMeta(i).controller.transition(easingValue);
8713 me.tooltip.transition(easingValue);
8717 * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
8718 * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
8721 drawDatasets: function(easingValue) {
8724 if (plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
8728 // Draw datasets reversed to support proper line stacking
8729 for (var i = (me.data.datasets || []).length - 1; i >= 0; --i) {
8730 if (me.isDatasetVisible(i)) {
8731 me.drawDataset(i, easingValue);
8735 plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
8739 * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
8740 * hook, in which case, plugins will not be called on `afterDatasetDraw`.
8743 drawDataset: function(index, easingValue) {
8745 var meta = me.getDatasetMeta(index);
8749 easingValue: easingValue
8752 if (plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
8756 meta.controller.draw(easingValue);
8758 plugins.notify(me, 'afterDatasetDraw', [args]);
8761 // Get the single element that was clicked on
8762 // @return : An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
8763 getElementAtEvent: function(e) {
8764 return Interaction.modes.single(this, e);
8767 getElementsAtEvent: function(e) {
8768 return Interaction.modes.label(this, e, {intersect: true});
8771 getElementsAtXAxis: function(e) {
8772 return Interaction.modes['x-axis'](this, e, {intersect: true});
8775 getElementsAtEventForMode: function(e, mode, options) {
8776 var method = Interaction.modes[mode];
8777 if (typeof method === 'function') {
8778 return method(this, e, options);
8784 getDatasetAtEvent: function(e) {
8785 return Interaction.modes.dataset(this, e, {intersect: true});
8788 getDatasetMeta: function(datasetIndex) {
8790 var dataset = me.data.datasets[datasetIndex];
8791 if (!dataset._meta) {
8795 var meta = dataset._meta[me.id];
8797 meta = dataset._meta[me.id] = {
8802 hidden: null, // See isDatasetVisible() comment
8811 getVisibleDatasetCount: function() {
8813 for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
8814 if (this.isDatasetVisible(i)) {
8821 isDatasetVisible: function(datasetIndex) {
8822 var meta = this.getDatasetMeta(datasetIndex);
8824 // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
8825 // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
8826 return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
8829 generateLegend: function() {
8830 return this.options.legendCallback(this);
8836 destroyDatasetMeta: function(datasetIndex) {
8838 var dataset = this.data.datasets[datasetIndex];
8839 var meta = dataset._meta && dataset._meta[id];
8842 meta.controller.destroy();
8843 delete dataset._meta[id];
8847 destroy: function() {
8849 var canvas = me.canvas;
8854 // dataset controllers need to cleanup associated data
8855 for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
8856 me.destroyDatasetMeta(i);
8861 helpers.canvas.clear(me);
8862 platform.releaseContext(me.ctx);
8867 plugins.notify(me, 'destroy');
8869 delete Chart.instances[me.id];
8872 toBase64Image: function() {
8873 return this.canvas.toDataURL.apply(this.canvas, arguments);
8876 initToolTip: function() {
8878 me.tooltip = new Chart.Tooltip({
8880 _chartInstance: me, // deprecated, backward compatibility
8882 _options: me.options.tooltips
8889 bindEvents: function() {
8891 var listeners = me._listeners = {};
8892 var listener = function() {
8893 me.eventHandler.apply(me, arguments);
8896 helpers.each(me.options.events, function(type) {
8897 platform.addEventListener(me, type, listener);
8898 listeners[type] = listener;
8901 // Elements used to detect size change should not be injected for non responsive charts.
8902 // See https://github.com/chartjs/Chart.js/issues/2210
8903 if (me.options.responsive) {
8904 listener = function() {
8908 platform.addEventListener(me, 'resize', listener);
8909 listeners.resize = listener;
8916 unbindEvents: function() {
8918 var listeners = me._listeners;
8923 delete me._listeners;
8924 helpers.each(listeners, function(listener, type) {
8925 platform.removeEventListener(me, type, listener);
8929 updateHoverStyle: function(elements, mode, enabled) {
8930 var method = enabled ? 'setHoverStyle' : 'removeHoverStyle';
8931 var element, i, ilen;
8933 for (i = 0, ilen = elements.length; i < ilen; ++i) {
8934 element = elements[i];
8936 this.getDatasetMeta(element._datasetIndex).controller[method](element);
8944 eventHandler: function(e) {
8946 var tooltip = me.tooltip;
8948 if (plugins.notify(me, 'beforeEvent', [e]) === false) {
8952 // Buffer any update calls so that renders do not occur
8953 me._bufferedRender = true;
8954 me._bufferedRequest = null;
8956 var changed = me.handleEvent(e);
8957 changed |= tooltip && tooltip.handleEvent(e);
8959 plugins.notify(me, 'afterEvent', [e]);
8961 var bufferedRequest = me._bufferedRequest;
8962 if (bufferedRequest) {
8963 // If we have an update that was triggered, we need to do a normal render
8964 me.render(bufferedRequest);
8965 } else if (changed && !me.animating) {
8966 // If entering, leaving, or changing elements, animate the change via pivot
8969 // We only need to render at this point. Updating will cause scales to be
8970 // recomputed generating flicker & using more memory than necessary.
8971 me.render(me.options.hover.animationDuration, true);
8974 me._bufferedRender = false;
8975 me._bufferedRequest = null;
8983 * @param {IEvent} event the event to handle
8984 * @return {Boolean} true if the chart needs to re-render
8986 handleEvent: function(e) {
8988 var options = me.options || {};
8989 var hoverOptions = options.hover;
8990 var changed = false;
8992 me.lastActive = me.lastActive || [];
8994 // Find Active Elements for hover and tooltips
8995 if (e.type === 'mouseout') {
8998 me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
9001 // Invoke onHover hook
9002 // Need to call with native event here to not break backwards compatibility
9003 helpers.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
9005 if (e.type === 'mouseup' || e.type === 'click') {
9006 if (options.onClick) {
9007 // Use e.native here for backwards compatibility
9008 options.onClick.call(me, e.native, me.active);
9012 // Remove styling for last active (even if it may still be active)
9013 if (me.lastActive.length) {
9014 me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
9017 // Built in hover styling
9018 if (me.active.length && hoverOptions.mode) {
9019 me.updateHoverStyle(me.active, hoverOptions.mode, true);
9022 changed = !helpers.arrayEquals(me.active, me.lastActive);
9024 // Remember Last Actives
9025 me.lastActive = me.active;
9032 * Provided for backward compatibility, use Chart instead.
9033 * @class Chart.Controller
9034 * @deprecated since version 2.6.0
9035 * @todo remove at version 3
9038 Chart.Controller = Chart;
9041 },{"25":25,"28":28,"45":45,"48":48}],24:[function(require,module,exports){
9044 var helpers = require(45);
9046 module.exports = function(Chart) {
9048 var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
9051 * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
9052 * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
9053 * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
9055 function listenArrayEvents(array, listener) {
9056 if (array._chartjs) {
9057 array._chartjs.listeners.push(listener);
9061 Object.defineProperty(array, '_chartjs', {
9065 listeners: [listener]
9069 arrayEvents.forEach(function(key) {
9070 var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
9071 var base = array[key];
9073 Object.defineProperty(array, key, {
9077 var args = Array.prototype.slice.call(arguments);
9078 var res = base.apply(this, args);
9080 helpers.each(array._chartjs.listeners, function(object) {
9081 if (typeof object[method] === 'function') {
9082 object[method].apply(object, args);
9093 * Removes the given array event listener and cleanup extra attached properties (such as
9094 * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
9096 function unlistenArrayEvents(array, listener) {
9097 var stub = array._chartjs;
9102 var listeners = stub.listeners;
9103 var index = listeners.indexOf(listener);
9105 listeners.splice(index, 1);
9108 if (listeners.length > 0) {
9112 arrayEvents.forEach(function(key) {
9116 delete array._chartjs;
9119 // Base class for all dataset controllers (line, bar, etc)
9120 Chart.DatasetController = function(chart, datasetIndex) {
9121 this.initialize(chart, datasetIndex);
9124 helpers.extend(Chart.DatasetController.prototype, {
9127 * Element type used to generate a meta dataset (e.g. Chart.element.Line).
9128 * @type {Chart.core.element}
9130 datasetElementType: null,
9133 * Element type used to generate a meta data (e.g. Chart.element.Point).
9134 * @type {Chart.core.element}
9136 dataElementType: null,
9138 initialize: function(chart, datasetIndex) {
9141 me.index = datasetIndex;
9146 updateIndex: function(datasetIndex) {
9147 this.index = datasetIndex;
9150 linkScales: function() {
9152 var meta = me.getMeta();
9153 var dataset = me.getDataset();
9155 if (meta.xAxisID === null) {
9156 meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id;
9158 if (meta.yAxisID === null) {
9159 meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id;
9163 getDataset: function() {
9164 return this.chart.data.datasets[this.index];
9167 getMeta: function() {
9168 return this.chart.getDatasetMeta(this.index);
9171 getScaleForId: function(scaleID) {
9172 return this.chart.scales[scaleID];
9182 destroy: function() {
9184 unlistenArrayEvents(this._data, this);
9188 createMetaDataset: function() {
9190 var type = me.datasetElementType;
9191 return type && new type({
9193 _datasetIndex: me.index
9197 createMetaData: function(index) {
9199 var type = me.dataElementType;
9200 return type && new type({
9202 _datasetIndex: me.index,
9207 addElements: function() {
9209 var meta = me.getMeta();
9210 var data = me.getDataset().data || [];
9211 var metaData = meta.data;
9214 for (i = 0, ilen = data.length; i < ilen; ++i) {
9215 metaData[i] = metaData[i] || me.createMetaData(i);
9218 meta.dataset = meta.dataset || me.createMetaDataset();
9221 addElementAndReset: function(index) {
9222 var element = this.createMetaData(index);
9223 this.getMeta().data.splice(index, 0, element);
9224 this.updateElement(element, index, true);
9227 buildOrUpdateElements: function() {
9229 var dataset = me.getDataset();
9230 var data = dataset.data || (dataset.data = []);
9232 // In order to correctly handle data addition/deletion animation (an thus simulate
9233 // real-time charts), we need to monitor these data modifications and synchronize
9234 // the internal meta data accordingly.
9235 if (me._data !== data) {
9237 // This case happens when the user replaced the data array instance.
9238 unlistenArrayEvents(me._data, me);
9241 listenArrayEvents(data, me);
9245 // Re-sync meta data in case the user replaced the data array or if we missed
9246 // any updates and so make sure that we handle number of datapoints changing.
9247 me.resyncElements();
9250 update: helpers.noop,
9252 transition: function(easingValue) {
9253 var meta = this.getMeta();
9254 var elements = meta.data || [];
9255 var ilen = elements.length;
9258 for (; i < ilen; ++i) {
9259 elements[i].transition(easingValue);
9263 meta.dataset.transition(easingValue);
9268 var meta = this.getMeta();
9269 var elements = meta.data || [];
9270 var ilen = elements.length;
9274 meta.dataset.draw();
9277 for (; i < ilen; ++i) {
9282 removeHoverStyle: function(element, elementOpts) {
9283 var dataset = this.chart.data.datasets[element._datasetIndex];
9284 var index = element._index;
9285 var custom = element.custom || {};
9286 var valueOrDefault = helpers.valueAtIndexOrDefault;
9287 var model = element._model;
9289 model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueOrDefault(dataset.backgroundColor, index, elementOpts.backgroundColor);
9290 model.borderColor = custom.borderColor ? custom.borderColor : valueOrDefault(dataset.borderColor, index, elementOpts.borderColor);
9291 model.borderWidth = custom.borderWidth ? custom.borderWidth : valueOrDefault(dataset.borderWidth, index, elementOpts.borderWidth);
9294 setHoverStyle: function(element) {
9295 var dataset = this.chart.data.datasets[element._datasetIndex];
9296 var index = element._index;
9297 var custom = element.custom || {};
9298 var valueOrDefault = helpers.valueAtIndexOrDefault;
9299 var getHoverColor = helpers.getHoverColor;
9300 var model = element._model;
9302 model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : valueOrDefault(dataset.hoverBackgroundColor, index, getHoverColor(model.backgroundColor));
9303 model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : valueOrDefault(dataset.hoverBorderColor, index, getHoverColor(model.borderColor));
9304 model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : valueOrDefault(dataset.hoverBorderWidth, index, model.borderWidth);
9310 resyncElements: function() {
9312 var meta = me.getMeta();
9313 var data = me.getDataset().data;
9314 var numMeta = meta.data.length;
9315 var numData = data.length;
9317 if (numData < numMeta) {
9318 meta.data.splice(numData, numMeta - numData);
9319 } else if (numData > numMeta) {
9320 me.insertElements(numMeta, numData - numMeta);
9327 insertElements: function(start, count) {
9328 for (var i = 0; i < count; ++i) {
9329 this.addElementAndReset(start + i);
9336 onDataPush: function() {
9337 this.insertElements(this.getDataset().data.length - 1, arguments.length);
9343 onDataPop: function() {
9344 this.getMeta().data.pop();
9350 onDataShift: function() {
9351 this.getMeta().data.shift();
9357 onDataSplice: function(start, count) {
9358 this.getMeta().data.splice(start, count);
9359 this.insertElements(start, arguments.length - 2);
9365 onDataUnshift: function() {
9366 this.insertElements(0, arguments.length);
9370 Chart.DatasetController.extend = helpers.inherits;
9373 },{"45":45}],25:[function(require,module,exports){
9376 var helpers = require(45);
9382 _set: function(scope, values) {
9383 return helpers.merge(this[scope] || (this[scope] = {}), values);
9387 },{"45":45}],26:[function(require,module,exports){
9390 var color = require(2);
9391 var helpers = require(45);
9393 function interpolate(start, view, model, ease) {
9394 var keys = Object.keys(model);
9395 var i, ilen, key, actual, origin, target, type, c0, c1;
9397 for (i = 0, ilen = keys.length; i < ilen; ++i) {
9400 target = model[key];
9402 // if a value is added to the model after pivot() has been called, the view
9403 // doesn't contain it, so let's initialize the view to the target value.
9404 if (!view.hasOwnProperty(key)) {
9410 if (actual === target || key[0] === '_') {
9414 if (!start.hasOwnProperty(key)) {
9415 start[key] = actual;
9418 origin = start[key];
9420 type = typeof target;
9422 if (type === typeof origin) {
9423 if (type === 'string') {
9428 view[key] = c1.mix(c0, ease).rgbString();
9432 } else if (type === 'number' && isFinite(origin) && isFinite(target)) {
9433 view[key] = origin + (target - origin) * ease;
9442 var Element = function(configuration) {
9443 helpers.extend(this, configuration);
9444 this.initialize.apply(this, arguments);
9447 helpers.extend(Element.prototype, {
9449 initialize: function() {
9450 this.hidden = false;
9456 me._view = helpers.clone(me._model);
9462 transition: function(ease) {
9464 var model = me._model;
9465 var start = me._start;
9466 var view = me._view;
9468 // No animation -> No Transition
9469 if (!model || ease === 1) {
9476 view = me._view = {};
9480 start = me._start = {};
9483 interpolate(start, view, model, ease);
9488 tooltipPosition: function() {
9495 hasValue: function() {
9496 return helpers.isNumber(this._model.x) && helpers.isNumber(this._model.y);
9500 Element.extend = helpers.inherits;
9502 module.exports = Element;
9504 },{"2":2,"45":45}],27:[function(require,module,exports){
9505 /* global window: false */
9506 /* global document: false */
9509 var color = require(2);
9510 var defaults = require(25);
9511 var helpers = require(45);
9513 module.exports = function(Chart) {
9515 // -- Basic js utility methods
9517 helpers.extend = function(base) {
9518 var setFn = function(value, key) {
9521 for (var i = 1, ilen = arguments.length; i < ilen; i++) {
9522 helpers.each(arguments[i], setFn);
9527 helpers.configMerge = function(/* objects ... */) {
9528 return helpers.merge(helpers.clone(arguments[0]), [].slice.call(arguments, 1), {
9529 merger: function(key, target, source, options) {
9530 var tval = target[key] || {};
9531 var sval = source[key];
9533 if (key === 'scales') {
9534 // scale config merging is complex. Add our own function here for that
9535 target[key] = helpers.scaleMerge(tval, sval);
9536 } else if (key === 'scale') {
9537 // used in polar area & radar charts since there is only one scale
9538 target[key] = helpers.merge(tval, [Chart.scaleService.getScaleDefaults(sval.type), sval]);
9540 helpers._merger(key, target, source, options);
9546 helpers.scaleMerge = function(/* objects ... */) {
9547 return helpers.merge(helpers.clone(arguments[0]), [].slice.call(arguments, 1), {
9548 merger: function(key, target, source, options) {
9549 if (key === 'xAxes' || key === 'yAxes') {
9550 var slen = source[key].length;
9557 for (i = 0; i < slen; ++i) {
9558 scale = source[key][i];
9559 type = helpers.valueOrDefault(scale.type, key === 'xAxes' ? 'category' : 'linear');
9561 if (i >= target[key].length) {
9562 target[key].push({});
9565 if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
9566 // new/untyped scale or type changed: let's apply the new defaults
9567 // then merge source scale to correctly overwrite the defaults.
9568 helpers.merge(target[key][i], [Chart.scaleService.getScaleDefaults(type), scale]);
9570 // scales type are the same
9571 helpers.merge(target[key][i], scale);
9575 helpers._merger(key, target, source, options);
9581 helpers.where = function(collection, filterCallback) {
9582 if (helpers.isArray(collection) && Array.prototype.filter) {
9583 return collection.filter(filterCallback);
9587 helpers.each(collection, function(item) {
9588 if (filterCallback(item)) {
9589 filtered.push(item);
9595 helpers.findIndex = Array.prototype.findIndex ?
9596 function(array, callback, scope) {
9597 return array.findIndex(callback, scope);
9599 function(array, callback, scope) {
9600 scope = scope === undefined ? array : scope;
9601 for (var i = 0, ilen = array.length; i < ilen; ++i) {
9602 if (callback.call(scope, array[i], i, array)) {
9608 helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
9609 // Default to start of the array
9610 if (helpers.isNullOrUndef(startIndex)) {
9613 for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
9614 var currentItem = arrayToSearch[i];
9615 if (filterCallback(currentItem)) {
9620 helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
9621 // Default to end of the array
9622 if (helpers.isNullOrUndef(startIndex)) {
9623 startIndex = arrayToSearch.length;
9625 for (var i = startIndex - 1; i >= 0; i--) {
9626 var currentItem = arrayToSearch[i];
9627 if (filterCallback(currentItem)) {
9632 helpers.inherits = function(extensions) {
9633 // Basic javascript inheritance based on the model created in Backbone.js
9635 var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
9636 return me.apply(this, arguments);
9639 var Surrogate = function() {
9640 this.constructor = ChartElement;
9642 Surrogate.prototype = me.prototype;
9643 ChartElement.prototype = new Surrogate();
9645 ChartElement.extend = helpers.inherits;
9648 helpers.extend(ChartElement.prototype, extensions);
9651 ChartElement.__super__ = me.prototype;
9653 return ChartElement;
9656 helpers.isNumber = function(n) {
9657 return !isNaN(parseFloat(n)) && isFinite(n);
9659 helpers.almostEquals = function(x, y, epsilon) {
9660 return Math.abs(x - y) < epsilon;
9662 helpers.almostWhole = function(x, epsilon) {
9663 var rounded = Math.round(x);
9664 return (((rounded - epsilon) < x) && ((rounded + epsilon) > x));
9666 helpers.max = function(array) {
9667 return array.reduce(function(max, value) {
9668 if (!isNaN(value)) {
9669 return Math.max(max, value);
9672 }, Number.NEGATIVE_INFINITY);
9674 helpers.min = function(array) {
9675 return array.reduce(function(min, value) {
9676 if (!isNaN(value)) {
9677 return Math.min(min, value);
9680 }, Number.POSITIVE_INFINITY);
9682 helpers.sign = Math.sign ?
9684 return Math.sign(x);
9687 x = +x; // convert to a number
9688 if (x === 0 || isNaN(x)) {
9691 return x > 0 ? 1 : -1;
9693 helpers.log10 = Math.log10 ?
9695 return Math.log10(x);
9698 return Math.log(x) / Math.LN10;
9700 helpers.toRadians = function(degrees) {
9701 return degrees * (Math.PI / 180);
9703 helpers.toDegrees = function(radians) {
9704 return radians * (180 / Math.PI);
9706 // Gets the angle from vertical upright to the point about a centre.
9707 helpers.getAngleFromPoint = function(centrePoint, anglePoint) {
9708 var distanceFromXCenter = anglePoint.x - centrePoint.x;
9709 var distanceFromYCenter = anglePoint.y - centrePoint.y;
9710 var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
9712 var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
9714 if (angle < (-0.5 * Math.PI)) {
9715 angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
9720 distance: radialDistanceFromCenter
9723 helpers.distanceBetweenPoints = function(pt1, pt2) {
9724 return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
9726 helpers.aliasPixel = function(pixelWidth) {
9727 return (pixelWidth % 2 === 0) ? 0 : 0.5;
9729 helpers.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
9730 // Props to Rob Spencer at scaled innovation for his post on splining between points
9731 // http://scaledinnovation.com/analytics/splines/aboutSplines.html
9733 // This function must also respect "skipped" points
9735 var previous = firstPoint.skip ? middlePoint : firstPoint;
9736 var current = middlePoint;
9737 var next = afterPoint.skip ? middlePoint : afterPoint;
9739 var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
9740 var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
9742 var s01 = d01 / (d01 + d12);
9743 var s12 = d12 / (d01 + d12);
9745 // If all points are the same, s01 & s02 will be inf
9746 s01 = isNaN(s01) ? 0 : s01;
9747 s12 = isNaN(s12) ? 0 : s12;
9749 var fa = t * s01; // scaling factor for triangle Ta
9754 x: current.x - fa * (next.x - previous.x),
9755 y: current.y - fa * (next.y - previous.y)
9758 x: current.x + fb * (next.x - previous.x),
9759 y: current.y + fb * (next.y - previous.y)
9763 helpers.EPSILON = Number.EPSILON || 1e-14;
9764 helpers.splineCurveMonotone = function(points) {
9765 // This function calculates Bézier control points in a similar way than |splineCurve|,
9766 // but preserves monotonicity of the provided data and ensures no local extremums are added
9767 // between the dataset discrete points due to the interpolation.
9768 // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
9770 var pointsWithTangents = (points || []).map(function(point) {
9772 model: point._model,
9778 // Calculate slopes (deltaK) and initialize tangents (mK)
9779 var pointsLen = pointsWithTangents.length;
9780 var i, pointBefore, pointCurrent, pointAfter;
9781 for (i = 0; i < pointsLen; ++i) {
9782 pointCurrent = pointsWithTangents[i];
9783 if (pointCurrent.model.skip) {
9787 pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
9788 pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
9789 if (pointAfter && !pointAfter.model.skip) {
9790 var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
9792 // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
9793 pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
9796 if (!pointBefore || pointBefore.model.skip) {
9797 pointCurrent.mK = pointCurrent.deltaK;
9798 } else if (!pointAfter || pointAfter.model.skip) {
9799 pointCurrent.mK = pointBefore.deltaK;
9800 } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
9801 pointCurrent.mK = 0;
9803 pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
9807 // Adjust tangents to ensure monotonic properties
9808 var alphaK, betaK, tauK, squaredMagnitude;
9809 for (i = 0; i < pointsLen - 1; ++i) {
9810 pointCurrent = pointsWithTangents[i];
9811 pointAfter = pointsWithTangents[i + 1];
9812 if (pointCurrent.model.skip || pointAfter.model.skip) {
9816 if (helpers.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
9817 pointCurrent.mK = pointAfter.mK = 0;
9821 alphaK = pointCurrent.mK / pointCurrent.deltaK;
9822 betaK = pointAfter.mK / pointCurrent.deltaK;
9823 squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
9824 if (squaredMagnitude <= 9) {
9828 tauK = 3 / Math.sqrt(squaredMagnitude);
9829 pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
9830 pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
9833 // Compute control points
9835 for (i = 0; i < pointsLen; ++i) {
9836 pointCurrent = pointsWithTangents[i];
9837 if (pointCurrent.model.skip) {
9841 pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
9842 pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
9843 if (pointBefore && !pointBefore.model.skip) {
9844 deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
9845 pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
9846 pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
9848 if (pointAfter && !pointAfter.model.skip) {
9849 deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
9850 pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
9851 pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
9855 helpers.nextItem = function(collection, index, loop) {
9857 return index >= collection.length - 1 ? collection[0] : collection[index + 1];
9859 return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
9861 helpers.previousItem = function(collection, index, loop) {
9863 return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
9865 return index <= 0 ? collection[0] : collection[index - 1];
9867 // Implementation of the nice number algorithm used in determining where axis labels will go
9868 helpers.niceNum = function(range, round) {
9869 var exponent = Math.floor(helpers.log10(range));
9870 var fraction = range / Math.pow(10, exponent);
9874 if (fraction < 1.5) {
9876 } else if (fraction < 3) {
9878 } else if (fraction < 7) {
9883 } else if (fraction <= 1.0) {
9885 } else if (fraction <= 2) {
9887 } else if (fraction <= 5) {
9893 return niceFraction * Math.pow(10, exponent);
9895 // Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
9896 helpers.requestAnimFrame = (function() {
9897 if (typeof window === 'undefined') {
9898 return function(callback) {
9902 return window.requestAnimationFrame ||
9903 window.webkitRequestAnimationFrame ||
9904 window.mozRequestAnimationFrame ||
9905 window.oRequestAnimationFrame ||
9906 window.msRequestAnimationFrame ||
9907 function(callback) {
9908 return window.setTimeout(callback, 1000 / 60);
9912 helpers.getRelativePosition = function(evt, chart) {
9914 var e = evt.originalEvent || evt;
9915 var canvas = evt.currentTarget || evt.srcElement;
9916 var boundingRect = canvas.getBoundingClientRect();
9918 var touches = e.touches;
9919 if (touches && touches.length > 0) {
9920 mouseX = touches[0].clientX;
9921 mouseY = touches[0].clientY;
9928 // Scale mouse coordinates into canvas coordinates
9929 // by following the pattern laid out by 'jerryj' in the comments of
9930 // http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
9931 var paddingLeft = parseFloat(helpers.getStyle(canvas, 'padding-left'));
9932 var paddingTop = parseFloat(helpers.getStyle(canvas, 'padding-top'));
9933 var paddingRight = parseFloat(helpers.getStyle(canvas, 'padding-right'));
9934 var paddingBottom = parseFloat(helpers.getStyle(canvas, 'padding-bottom'));
9935 var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
9936 var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
9938 // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
9939 // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
9940 mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
9941 mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
9950 // Private helper function to convert max-width/max-height values that may be percentages into a number
9951 function parseMaxStyle(styleValue, node, parentProperty) {
9953 if (typeof styleValue === 'string') {
9954 valueInPixels = parseInt(styleValue, 10);
9956 if (styleValue.indexOf('%') !== -1) {
9957 // percentage * size in dimension
9958 valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
9961 valueInPixels = styleValue;
9964 return valueInPixels;
9968 * Returns if the given value contains an effective constraint.
9971 function isConstrainedValue(value) {
9972 return value !== undefined && value !== null && value !== 'none';
9975 // Private helper to get a constraint dimension
9976 // @param domNode : the node to check the constraint on
9977 // @param maxStyle : the style that defines the maximum for the direction we are using (maxWidth / maxHeight)
9978 // @param percentageProperty : property of parent to use when calculating width as a percentage
9979 // @see http://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser
9980 function getConstraintDimension(domNode, maxStyle, percentageProperty) {
9981 var view = document.defaultView;
9982 var parentNode = domNode.parentNode;
9983 var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
9984 var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
9985 var hasCNode = isConstrainedValue(constrainedNode);
9986 var hasCContainer = isConstrainedValue(constrainedContainer);
9987 var infinity = Number.POSITIVE_INFINITY;
9989 if (hasCNode || hasCContainer) {
9991 hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
9992 hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
9997 // returns Number or undefined if no constraint
9998 helpers.getConstraintWidth = function(domNode) {
9999 return getConstraintDimension(domNode, 'max-width', 'clientWidth');
10001 // returns Number or undefined if no constraint
10002 helpers.getConstraintHeight = function(domNode) {
10003 return getConstraintDimension(domNode, 'max-height', 'clientHeight');
10005 helpers.getMaximumWidth = function(domNode) {
10006 var container = domNode.parentNode;
10008 return domNode.clientWidth;
10011 var paddingLeft = parseInt(helpers.getStyle(container, 'padding-left'), 10);
10012 var paddingRight = parseInt(helpers.getStyle(container, 'padding-right'), 10);
10013 var w = container.clientWidth - paddingLeft - paddingRight;
10014 var cw = helpers.getConstraintWidth(domNode);
10015 return isNaN(cw) ? w : Math.min(w, cw);
10017 helpers.getMaximumHeight = function(domNode) {
10018 var container = domNode.parentNode;
10020 return domNode.clientHeight;
10023 var paddingTop = parseInt(helpers.getStyle(container, 'padding-top'), 10);
10024 var paddingBottom = parseInt(helpers.getStyle(container, 'padding-bottom'), 10);
10025 var h = container.clientHeight - paddingTop - paddingBottom;
10026 var ch = helpers.getConstraintHeight(domNode);
10027 return isNaN(ch) ? h : Math.min(h, ch);
10029 helpers.getStyle = function(el, property) {
10030 return el.currentStyle ?
10031 el.currentStyle[property] :
10032 document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
10034 helpers.retinaScale = function(chart, forceRatio) {
10035 var pixelRatio = chart.currentDevicePixelRatio = forceRatio || window.devicePixelRatio || 1;
10036 if (pixelRatio === 1) {
10040 var canvas = chart.canvas;
10041 var height = chart.height;
10042 var width = chart.width;
10044 canvas.height = height * pixelRatio;
10045 canvas.width = width * pixelRatio;
10046 chart.ctx.scale(pixelRatio, pixelRatio);
10048 // If no style has been set on the canvas, the render size is used as display size,
10049 // making the chart visually bigger, so let's enforce it to the "correct" values.
10050 // See https://github.com/chartjs/Chart.js/issues/3575
10051 canvas.style.height = height + 'px';
10052 canvas.style.width = width + 'px';
10054 // -- Canvas methods
10055 helpers.fontString = function(pixelSize, fontStyle, fontFamily) {
10056 return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
10058 helpers.longestText = function(ctx, font, arrayOfThings, cache) {
10059 cache = cache || {};
10060 var data = cache.data = cache.data || {};
10061 var gc = cache.garbageCollect = cache.garbageCollect || [];
10063 if (cache.font !== font) {
10064 data = cache.data = {};
10065 gc = cache.garbageCollect = [];
10071 helpers.each(arrayOfThings, function(thing) {
10072 // Undefined strings and arrays should not be measured
10073 if (thing !== undefined && thing !== null && helpers.isArray(thing) !== true) {
10074 longest = helpers.measureText(ctx, data, gc, longest, thing);
10075 } else if (helpers.isArray(thing)) {
10076 // if it is an array lets measure each element
10077 // to do maybe simplify this function a bit so we can do this more recursively?
10078 helpers.each(thing, function(nestedThing) {
10079 // Undefined strings and arrays should not be measured
10080 if (nestedThing !== undefined && nestedThing !== null && !helpers.isArray(nestedThing)) {
10081 longest = helpers.measureText(ctx, data, gc, longest, nestedThing);
10087 var gcLen = gc.length / 2;
10088 if (gcLen > arrayOfThings.length) {
10089 for (var i = 0; i < gcLen; i++) {
10090 delete data[gc[i]];
10092 gc.splice(0, gcLen);
10096 helpers.measureText = function(ctx, data, gc, longest, string) {
10097 var textWidth = data[string];
10099 textWidth = data[string] = ctx.measureText(string).width;
10102 if (textWidth > longest) {
10103 longest = textWidth;
10107 helpers.numberOfLabelLines = function(arrayOfThings) {
10108 var numberOfLines = 1;
10109 helpers.each(arrayOfThings, function(thing) {
10110 if (helpers.isArray(thing)) {
10111 if (thing.length > numberOfLines) {
10112 numberOfLines = thing.length;
10116 return numberOfLines;
10119 helpers.color = !color ?
10121 console.error('Color.js not found!');
10125 /* global CanvasGradient */
10126 if (value instanceof CanvasGradient) {
10127 value = defaults.global.defaultColor;
10130 return color(value);
10133 helpers.getHoverColor = function(colorValue) {
10134 /* global CanvasPattern */
10135 return (colorValue instanceof CanvasPattern) ?
10137 helpers.color(colorValue).saturate(0.5).darken(0.1).rgbString();
10141 },{"2":2,"25":25,"45":45}],28:[function(require,module,exports){
10144 var helpers = require(45);
10147 * Helper function to get relative position for an event
10148 * @param {Event|IEvent} event - The event to get the position for
10149 * @param {Chart} chart - The chart
10150 * @returns {Point} the event position
10152 function getRelativePosition(e, chart) {
10160 return helpers.getRelativePosition(e, chart);
10164 * Helper function to traverse all of the visible elements in the chart
10165 * @param chart {chart} the chart
10166 * @param handler {Function} the callback to execute for each visible item
10168 function parseVisibleItems(chart, handler) {
10169 var datasets = chart.data.datasets;
10170 var meta, i, j, ilen, jlen;
10172 for (i = 0, ilen = datasets.length; i < ilen; ++i) {
10173 if (!chart.isDatasetVisible(i)) {
10177 meta = chart.getDatasetMeta(i);
10178 for (j = 0, jlen = meta.data.length; j < jlen; ++j) {
10179 var element = meta.data[j];
10180 if (!element._view.skip) {
10188 * Helper function to get the items that intersect the event position
10189 * @param items {ChartElement[]} elements to filter
10190 * @param position {Point} the point to be nearest to
10191 * @return {ChartElement[]} the nearest items
10193 function getIntersectItems(chart, position) {
10196 parseVisibleItems(chart, function(element) {
10197 if (element.inRange(position.x, position.y)) {
10198 elements.push(element);
10206 * Helper function to get the items nearest to the event position considering all visible items in teh chart
10207 * @param chart {Chart} the chart to look at elements from
10208 * @param position {Point} the point to be nearest to
10209 * @param intersect {Boolean} if true, only consider items that intersect the position
10210 * @param distanceMetric {Function} function to provide the distance between points
10211 * @return {ChartElement[]} the nearest items
10213 function getNearestItems(chart, position, intersect, distanceMetric) {
10214 var minDistance = Number.POSITIVE_INFINITY;
10215 var nearestItems = [];
10217 parseVisibleItems(chart, function(element) {
10218 if (intersect && !element.inRange(position.x, position.y)) {
10222 var center = element.getCenterPoint();
10223 var distance = distanceMetric(position, center);
10225 if (distance < minDistance) {
10226 nearestItems = [element];
10227 minDistance = distance;
10228 } else if (distance === minDistance) {
10229 // Can have multiple items at the same distance in which case we sort by size
10230 nearestItems.push(element);
10234 return nearestItems;
10238 * Get a distance metric function for two points based on the
10239 * axis mode setting
10240 * @param {String} axis the axis mode. x|y|xy
10242 function getDistanceMetricForAxis(axis) {
10243 var useX = axis.indexOf('x') !== -1;
10244 var useY = axis.indexOf('y') !== -1;
10246 return function(pt1, pt2) {
10247 var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
10248 var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
10249 return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
10253 function indexMode(chart, e, options) {
10254 var position = getRelativePosition(e, chart);
10255 // Default axis for index mode is 'x' to match old behaviour
10256 options.axis = options.axis || 'x';
10257 var distanceMetric = getDistanceMetricForAxis(options.axis);
10258 var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
10261 if (!items.length) {
10265 chart.data.datasets.forEach(function(dataset, datasetIndex) {
10266 if (chart.isDatasetVisible(datasetIndex)) {
10267 var meta = chart.getDatasetMeta(datasetIndex);
10268 var element = meta.data[items[0]._index];
10270 // don't count items that are skipped (null data)
10271 if (element && !element._view.skip) {
10272 elements.push(element);
10281 * @interface IInteractionOptions
10284 * If true, only consider items that intersect the point
10285 * @name IInterfaceOptions#boolean
10290 * Contains interaction related functions
10291 * @namespace Chart.Interaction
10294 // Helper function for different modes
10296 single: function(chart, e) {
10297 var position = getRelativePosition(e, chart);
10300 parseVisibleItems(chart, function(element) {
10301 if (element.inRange(position.x, position.y)) {
10302 elements.push(element);
10307 return elements.slice(0, 1);
10311 * @function Chart.Interaction.modes.label
10312 * @deprecated since version 2.4.0
10313 * @todo remove at version 3
10319 * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
10320 * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
10321 * @function Chart.Interaction.modes.index
10323 * @param chart {chart} the chart we are returning items from
10324 * @param e {Event} the event we are find things at
10325 * @param options {IInteractionOptions} options to use during interaction
10326 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
10331 * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
10332 * If the options.intersect is false, we find the nearest item and return the items in that dataset
10333 * @function Chart.Interaction.modes.dataset
10334 * @param chart {chart} the chart we are returning items from
10335 * @param e {Event} the event we are find things at
10336 * @param options {IInteractionOptions} options to use during interaction
10337 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
10339 dataset: function(chart, e, options) {
10340 var position = getRelativePosition(e, chart);
10341 options.axis = options.axis || 'xy';
10342 var distanceMetric = getDistanceMetricForAxis(options.axis);
10343 var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
10345 if (items.length > 0) {
10346 items = chart.getDatasetMeta(items[0]._datasetIndex).data;
10353 * @function Chart.Interaction.modes.x-axis
10354 * @deprecated since version 2.4.0. Use index mode and intersect == true
10355 * @todo remove at version 3
10358 'x-axis': function(chart, e) {
10359 return indexMode(chart, e, {intersect: true});
10363 * Point mode returns all elements that hit test based on the event position
10365 * @function Chart.Interaction.modes.intersect
10366 * @param chart {chart} the chart we are returning items from
10367 * @param e {Event} the event we are find things at
10368 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
10370 point: function(chart, e) {
10371 var position = getRelativePosition(e, chart);
10372 return getIntersectItems(chart, position);
10376 * nearest mode returns the element closest to the point
10377 * @function Chart.Interaction.modes.intersect
10378 * @param chart {chart} the chart we are returning items from
10379 * @param e {Event} the event we are find things at
10380 * @param options {IInteractionOptions} options to use
10381 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
10383 nearest: function(chart, e, options) {
10384 var position = getRelativePosition(e, chart);
10385 options.axis = options.axis || 'xy';
10386 var distanceMetric = getDistanceMetricForAxis(options.axis);
10387 var nearestItems = getNearestItems(chart, position, options.intersect, distanceMetric);
10389 // We have multiple items at the same distance from the event. Now sort by smallest
10390 if (nearestItems.length > 1) {
10391 nearestItems.sort(function(a, b) {
10392 var sizeA = a.getArea();
10393 var sizeB = b.getArea();
10394 var ret = sizeA - sizeB;
10397 // if equal sort by dataset index
10398 ret = a._datasetIndex - b._datasetIndex;
10405 // Return only 1 item
10406 return nearestItems.slice(0, 1);
10410 * x mode returns the elements that hit-test at the current x coordinate
10411 * @function Chart.Interaction.modes.x
10412 * @param chart {chart} the chart we are returning items from
10413 * @param e {Event} the event we are find things at
10414 * @param options {IInteractionOptions} options to use
10415 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
10417 x: function(chart, e, options) {
10418 var position = getRelativePosition(e, chart);
10420 var intersectsItem = false;
10422 parseVisibleItems(chart, function(element) {
10423 if (element.inXRange(position.x)) {
10424 items.push(element);
10427 if (element.inRange(position.x, position.y)) {
10428 intersectsItem = true;
10432 // If we want to trigger on an intersect and we don't have any items
10433 // that intersect the position, return nothing
10434 if (options.intersect && !intersectsItem) {
10441 * y mode returns the elements that hit-test at the current y coordinate
10442 * @function Chart.Interaction.modes.y
10443 * @param chart {chart} the chart we are returning items from
10444 * @param e {Event} the event we are find things at
10445 * @param options {IInteractionOptions} options to use
10446 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
10448 y: function(chart, e, options) {
10449 var position = getRelativePosition(e, chart);
10451 var intersectsItem = false;
10453 parseVisibleItems(chart, function(element) {
10454 if (element.inYRange(position.y)) {
10455 items.push(element);
10458 if (element.inRange(position.x, position.y)) {
10459 intersectsItem = true;
10463 // If we want to trigger on an intersect and we don't have any items
10464 // that intersect the position, return nothing
10465 if (options.intersect && !intersectsItem) {
10473 },{"45":45}],29:[function(require,module,exports){
10476 var defaults = require(25);
10478 defaults._set('global', {
10480 responsiveAnimationDuration: 0,
10481 maintainAspectRatio: true,
10482 events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
10487 animationDuration: 400
10490 defaultColor: 'rgba(0,0,0,0.1)',
10491 defaultFontColor: '#666',
10492 defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
10493 defaultFontSize: 12,
10494 defaultFontStyle: 'normal',
10497 // Element defaults defined in element extensions
10500 // Layout options such as padding
10511 module.exports = function() {
10513 // Occupy the global variable of Chart, and create a simple base class
10514 var Chart = function(item, config) {
10515 this.construct(item, config);
10519 Chart.Chart = Chart;
10524 },{"25":25}],30:[function(require,module,exports){
10527 var helpers = require(45);
10529 module.exports = function(Chart) {
10531 function filterByPosition(array, position) {
10532 return helpers.where(array, function(v) {
10533 return v.position === position;
10537 function sortByWeight(array, reverse) {
10538 array.forEach(function(v, i) {
10542 array.sort(function(a, b) {
10543 var v0 = reverse ? b : a;
10544 var v1 = reverse ? a : b;
10545 return v0.weight === v1.weight ?
10546 v0._tmpIndex_ - v1._tmpIndex_ :
10547 v0.weight - v1.weight;
10549 array.forEach(function(v) {
10550 delete v._tmpIndex_;
10555 * @interface ILayoutItem
10556 * @prop {String} position - The position of the item in the chart layout. Possible values are
10557 * 'left', 'top', 'right', 'bottom', and 'chartArea'
10558 * @prop {Number} weight - The weight used to sort the item. Higher weights are further away from the chart area
10559 * @prop {Boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
10560 * @prop {Function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
10561 * @prop {Function} update - Takes two parameters: width and height. Returns size of item
10562 * @prop {Function} getPadding - Returns an object with padding on the edges
10563 * @prop {Number} width - Width of item. Must be valid after update()
10564 * @prop {Number} height - Height of item. Must be valid after update()
10565 * @prop {Number} left - Left edge of the item. Set by layout system and cannot be used in update
10566 * @prop {Number} top - Top edge of the item. Set by layout system and cannot be used in update
10567 * @prop {Number} right - Right edge of the item. Set by layout system and cannot be used in update
10568 * @prop {Number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
10571 // The layout service is very self explanatory. It's responsible for the layout within a chart.
10572 // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
10573 // It is this service's responsibility of carrying out that layout.
10574 Chart.layoutService = {
10578 * Register a box to a chart.
10579 * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
10580 * @param {Chart} chart - the chart to use
10581 * @param {ILayoutItem} item - the item to add to be layed out
10583 addBox: function(chart, item) {
10584 if (!chart.boxes) {
10588 // initialize item with default values
10589 item.fullWidth = item.fullWidth || false;
10590 item.position = item.position || 'top';
10591 item.weight = item.weight || 0;
10593 chart.boxes.push(item);
10597 * Remove a layoutItem from a chart
10598 * @param {Chart} chart - the chart to remove the box from
10599 * @param {Object} layoutItem - the item to remove from the layout
10601 removeBox: function(chart, layoutItem) {
10602 var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
10603 if (index !== -1) {
10604 chart.boxes.splice(index, 1);
10609 * Sets (or updates) options on the given `item`.
10610 * @param {Chart} chart - the chart in which the item lives (or will be added to)
10611 * @param {Object} item - the item to configure with the given options
10612 * @param {Object} options - the new item options.
10614 configure: function(chart, item, options) {
10615 var props = ['fullWidth', 'position', 'weight'];
10616 var ilen = props.length;
10620 for (; i < ilen; ++i) {
10622 if (options.hasOwnProperty(prop)) {
10623 item[prop] = options[prop];
10629 * Fits boxes of the given chart into the given size by having each box measure itself
10630 * then running a fitting algorithm
10631 * @param {Chart} chart - the chart
10632 * @param {Number} width - the width to fit into
10633 * @param {Number} height - the height to fit into
10635 update: function(chart, width, height) {
10640 var layoutOptions = chart.options.layout || {};
10641 var padding = helpers.options.toPadding(layoutOptions.padding);
10642 var leftPadding = padding.left;
10643 var rightPadding = padding.right;
10644 var topPadding = padding.top;
10645 var bottomPadding = padding.bottom;
10647 var leftBoxes = filterByPosition(chart.boxes, 'left');
10648 var rightBoxes = filterByPosition(chart.boxes, 'right');
10649 var topBoxes = filterByPosition(chart.boxes, 'top');
10650 var bottomBoxes = filterByPosition(chart.boxes, 'bottom');
10651 var chartAreaBoxes = filterByPosition(chart.boxes, 'chartArea');
10653 // Sort boxes by weight. A higher weight is further away from the chart area
10654 sortByWeight(leftBoxes, true);
10655 sortByWeight(rightBoxes, false);
10656 sortByWeight(topBoxes, true);
10657 sortByWeight(bottomBoxes, false);
10659 // Essentially we now have any number of boxes on each of the 4 sides.
10660 // Our canvas looks like the following.
10661 // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
10662 // B1 is the bottom axis
10663 // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
10664 // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
10665 // an error will be thrown.
10667 // |----------------------------------------------------|
10668 // | T1 (Full Width) |
10669 // |----------------------------------------------------|
10671 // | |----|-------------------------------------|----|
10672 // | | | C1 | | C2 | |
10673 // | | |----| |----| |
10675 // | L1 | L2 | ChartArea (C0) | R1 |
10677 // | | |----| |----| |
10678 // | | | C3 | | C4 | |
10679 // | |----|-------------------------------------|----|
10681 // |----------------------------------------------------|
10682 // | B2 (Full Width) |
10683 // |----------------------------------------------------|
10685 // What we do to find the best sizing, we do the following
10686 // 1. Determine the minimum size of the chart area.
10687 // 2. Split the remaining width equally between each vertical axis
10688 // 3. Split the remaining height equally between each horizontal axis
10689 // 4. Give each layout the maximum size it can be. The layout will return it's minimum size
10690 // 5. Adjust the sizes of each axis based on it's minimum reported size.
10691 // 6. Refit each axis
10692 // 7. Position each axis in the final location
10693 // 8. Tell the chart the final location of the chart area
10694 // 9. Tell any axes that overlay the chart area the positions of the chart area
10697 var chartWidth = width - leftPadding - rightPadding;
10698 var chartHeight = height - topPadding - bottomPadding;
10699 var chartAreaWidth = chartWidth / 2; // min 50%
10700 var chartAreaHeight = chartHeight / 2; // min 50%
10703 var verticalBoxWidth = (width - chartAreaWidth) / (leftBoxes.length + rightBoxes.length);
10706 var horizontalBoxHeight = (height - chartAreaHeight) / (topBoxes.length + bottomBoxes.length);
10709 var maxChartAreaWidth = chartWidth;
10710 var maxChartAreaHeight = chartHeight;
10711 var minBoxSizes = [];
10713 function getMinimumBoxSize(box) {
10715 var isHorizontal = box.isHorizontal();
10717 if (isHorizontal) {
10718 minSize = box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, horizontalBoxHeight);
10719 maxChartAreaHeight -= minSize.height;
10721 minSize = box.update(verticalBoxWidth, chartAreaHeight);
10722 maxChartAreaWidth -= minSize.width;
10726 horizontal: isHorizontal,
10732 helpers.each(leftBoxes.concat(rightBoxes, topBoxes, bottomBoxes), getMinimumBoxSize);
10734 // If a horizontal box has padding, we move the left boxes over to avoid ugly charts (see issue #2478)
10735 var maxHorizontalLeftPadding = 0;
10736 var maxHorizontalRightPadding = 0;
10737 var maxVerticalTopPadding = 0;
10738 var maxVerticalBottomPadding = 0;
10740 helpers.each(topBoxes.concat(bottomBoxes), function(horizontalBox) {
10741 if (horizontalBox.getPadding) {
10742 var boxPadding = horizontalBox.getPadding();
10743 maxHorizontalLeftPadding = Math.max(maxHorizontalLeftPadding, boxPadding.left);
10744 maxHorizontalRightPadding = Math.max(maxHorizontalRightPadding, boxPadding.right);
10748 helpers.each(leftBoxes.concat(rightBoxes), function(verticalBox) {
10749 if (verticalBox.getPadding) {
10750 var boxPadding = verticalBox.getPadding();
10751 maxVerticalTopPadding = Math.max(maxVerticalTopPadding, boxPadding.top);
10752 maxVerticalBottomPadding = Math.max(maxVerticalBottomPadding, boxPadding.bottom);
10756 // At this point, maxChartAreaHeight and maxChartAreaWidth are the size the chart area could
10757 // be if the axes are drawn at their minimum sizes.
10759 var totalLeftBoxesWidth = leftPadding;
10760 var totalRightBoxesWidth = rightPadding;
10761 var totalTopBoxesHeight = topPadding;
10762 var totalBottomBoxesHeight = bottomPadding;
10764 // Function to fit a box
10765 function fitBox(box) {
10766 var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minBox) {
10767 return minBox.box === box;
10771 if (box.isHorizontal()) {
10772 var scaleMargin = {
10773 left: Math.max(totalLeftBoxesWidth, maxHorizontalLeftPadding),
10774 right: Math.max(totalRightBoxesWidth, maxHorizontalRightPadding),
10779 // Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends
10780 // on the margin. Sometimes they need to increase in size slightly
10781 box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin);
10783 box.update(minBoxSize.minSize.width, maxChartAreaHeight);
10788 // Update, and calculate the left and right margins for the horizontal boxes
10789 helpers.each(leftBoxes.concat(rightBoxes), fitBox);
10791 helpers.each(leftBoxes, function(box) {
10792 totalLeftBoxesWidth += box.width;
10795 helpers.each(rightBoxes, function(box) {
10796 totalRightBoxesWidth += box.width;
10799 // Set the Left and Right margins for the horizontal boxes
10800 helpers.each(topBoxes.concat(bottomBoxes), fitBox);
10802 // Figure out how much margin is on the top and bottom of the vertical boxes
10803 helpers.each(topBoxes, function(box) {
10804 totalTopBoxesHeight += box.height;
10807 helpers.each(bottomBoxes, function(box) {
10808 totalBottomBoxesHeight += box.height;
10811 function finalFitVerticalBox(box) {
10812 var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minSize) {
10813 return minSize.box === box;
10816 var scaleMargin = {
10819 top: totalTopBoxesHeight,
10820 bottom: totalBottomBoxesHeight
10824 box.update(minBoxSize.minSize.width, maxChartAreaHeight, scaleMargin);
10828 // Let the left layout know the final margin
10829 helpers.each(leftBoxes.concat(rightBoxes), finalFitVerticalBox);
10831 // Recalculate because the size of each layout might have changed slightly due to the margins (label rotation for instance)
10832 totalLeftBoxesWidth = leftPadding;
10833 totalRightBoxesWidth = rightPadding;
10834 totalTopBoxesHeight = topPadding;
10835 totalBottomBoxesHeight = bottomPadding;
10837 helpers.each(leftBoxes, function(box) {
10838 totalLeftBoxesWidth += box.width;
10841 helpers.each(rightBoxes, function(box) {
10842 totalRightBoxesWidth += box.width;
10845 helpers.each(topBoxes, function(box) {
10846 totalTopBoxesHeight += box.height;
10848 helpers.each(bottomBoxes, function(box) {
10849 totalBottomBoxesHeight += box.height;
10852 // We may be adding some padding to account for rotated x axis labels
10853 var leftPaddingAddition = Math.max(maxHorizontalLeftPadding - totalLeftBoxesWidth, 0);
10854 totalLeftBoxesWidth += leftPaddingAddition;
10855 totalRightBoxesWidth += Math.max(maxHorizontalRightPadding - totalRightBoxesWidth, 0);
10857 var topPaddingAddition = Math.max(maxVerticalTopPadding - totalTopBoxesHeight, 0);
10858 totalTopBoxesHeight += topPaddingAddition;
10859 totalBottomBoxesHeight += Math.max(maxVerticalBottomPadding - totalBottomBoxesHeight, 0);
10861 // Figure out if our chart area changed. This would occur if the dataset layout label rotation
10862 // changed due to the application of the margins in step 6. Since we can only get bigger, this is safe to do
10863 // without calling `fit` again
10864 var newMaxChartAreaHeight = height - totalTopBoxesHeight - totalBottomBoxesHeight;
10865 var newMaxChartAreaWidth = width - totalLeftBoxesWidth - totalRightBoxesWidth;
10867 if (newMaxChartAreaWidth !== maxChartAreaWidth || newMaxChartAreaHeight !== maxChartAreaHeight) {
10868 helpers.each(leftBoxes, function(box) {
10869 box.height = newMaxChartAreaHeight;
10872 helpers.each(rightBoxes, function(box) {
10873 box.height = newMaxChartAreaHeight;
10876 helpers.each(topBoxes, function(box) {
10877 if (!box.fullWidth) {
10878 box.width = newMaxChartAreaWidth;
10882 helpers.each(bottomBoxes, function(box) {
10883 if (!box.fullWidth) {
10884 box.width = newMaxChartAreaWidth;
10888 maxChartAreaHeight = newMaxChartAreaHeight;
10889 maxChartAreaWidth = newMaxChartAreaWidth;
10892 // Step 7 - Position the boxes
10893 var left = leftPadding + leftPaddingAddition;
10894 var top = topPadding + topPaddingAddition;
10896 function placeBox(box) {
10897 if (box.isHorizontal()) {
10898 box.left = box.fullWidth ? leftPadding : totalLeftBoxesWidth;
10899 box.right = box.fullWidth ? width - rightPadding : totalLeftBoxesWidth + maxChartAreaWidth;
10901 box.bottom = top + box.height;
10903 // Move to next point
10909 box.right = left + box.width;
10910 box.top = totalTopBoxesHeight;
10911 box.bottom = totalTopBoxesHeight + maxChartAreaHeight;
10913 // Move to next point
10918 helpers.each(leftBoxes.concat(topBoxes), placeBox);
10920 // Account for chart width and height
10921 left += maxChartAreaWidth;
10922 top += maxChartAreaHeight;
10924 helpers.each(rightBoxes, placeBox);
10925 helpers.each(bottomBoxes, placeBox);
10928 chart.chartArea = {
10929 left: totalLeftBoxesWidth,
10930 top: totalTopBoxesHeight,
10931 right: totalLeftBoxesWidth + maxChartAreaWidth,
10932 bottom: totalTopBoxesHeight + maxChartAreaHeight
10936 helpers.each(chartAreaBoxes, function(box) {
10937 box.left = chart.chartArea.left;
10938 box.top = chart.chartArea.top;
10939 box.right = chart.chartArea.right;
10940 box.bottom = chart.chartArea.bottom;
10942 box.update(maxChartAreaWidth, maxChartAreaHeight);
10948 },{"45":45}],31:[function(require,module,exports){
10951 var defaults = require(25);
10952 var Element = require(26);
10953 var helpers = require(45);
10955 defaults._set('global', {
10959 module.exports = function(Chart) {
10962 * The plugin service singleton
10963 * @namespace Chart.plugins
10968 * Globally registered plugins.
10974 * This identifier is used to invalidate the descriptors cache attached to each chart
10975 * when a global plugin is registered or unregistered. In this case, the cache ID is
10976 * incremented and descriptors are regenerated during following API calls.
10982 * Registers the given plugin(s) if not already registered.
10983 * @param {Array|Object} plugins plugin instance(s).
10985 register: function(plugins) {
10986 var p = this._plugins;
10987 ([]).concat(plugins).forEach(function(plugin) {
10988 if (p.indexOf(plugin) === -1) {
10997 * Unregisters the given plugin(s) only if registered.
10998 * @param {Array|Object} plugins plugin instance(s).
11000 unregister: function(plugins) {
11001 var p = this._plugins;
11002 ([]).concat(plugins).forEach(function(plugin) {
11003 var idx = p.indexOf(plugin);
11013 * Remove all registered plugins.
11016 clear: function() {
11017 this._plugins = [];
11022 * Returns the number of registered plugins?
11023 * @returns {Number}
11026 count: function() {
11027 return this._plugins.length;
11031 * Returns all registered plugin instances.
11032 * @returns {Array} array of plugin objects.
11035 getAll: function() {
11036 return this._plugins;
11040 * Calls enabled plugins for `chart` on the specified hook and with the given args.
11041 * This method immediately returns as soon as a plugin explicitly returns false. The
11042 * returned value can be used, for instance, to interrupt the current action.
11043 * @param {Object} chart - The chart instance for which plugins should be called.
11044 * @param {String} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
11045 * @param {Array} [args] - Extra arguments to apply to the hook call.
11046 * @returns {Boolean} false if any of the plugins return false, else returns true.
11048 notify: function(chart, hook, args) {
11049 var descriptors = this.descriptors(chart);
11050 var ilen = descriptors.length;
11051 var i, descriptor, plugin, params, method;
11053 for (i = 0; i < ilen; ++i) {
11054 descriptor = descriptors[i];
11055 plugin = descriptor.plugin;
11056 method = plugin[hook];
11057 if (typeof method === 'function') {
11058 params = [chart].concat(args || []);
11059 params.push(descriptor.options);
11060 if (method.apply(plugin, params) === false) {
11070 * Returns descriptors of enabled plugins for the given chart.
11071 * @returns {Array} [{ plugin, options }]
11074 descriptors: function(chart) {
11075 var cache = chart._plugins || (chart._plugins = {});
11076 if (cache.id === this._cacheId) {
11077 return cache.descriptors;
11081 var descriptors = [];
11082 var config = (chart && chart.config) || {};
11083 var options = (config.options && config.options.plugins) || {};
11085 this._plugins.concat(config.plugins || []).forEach(function(plugin) {
11086 var idx = plugins.indexOf(plugin);
11091 var id = plugin.id;
11092 var opts = options[id];
11093 if (opts === false) {
11097 if (opts === true) {
11098 opts = helpers.clone(defaults.global.plugins[id]);
11101 plugins.push(plugin);
11104 options: opts || {}
11108 cache.descriptors = descriptors;
11109 cache.id = this._cacheId;
11110 return descriptors;
11115 * Plugin extension hooks.
11116 * @interface IPlugin
11120 * @method IPlugin#beforeInit
11121 * @desc Called before initializing `chart`.
11122 * @param {Chart.Controller} chart - The chart instance.
11123 * @param {Object} options - The plugin options.
11126 * @method IPlugin#afterInit
11127 * @desc Called after `chart` has been initialized and before the first update.
11128 * @param {Chart.Controller} chart - The chart instance.
11129 * @param {Object} options - The plugin options.
11132 * @method IPlugin#beforeUpdate
11133 * @desc Called before updating `chart`. If any plugin returns `false`, the update
11134 * is cancelled (and thus subsequent render(s)) until another `update` is triggered.
11135 * @param {Chart.Controller} chart - The chart instance.
11136 * @param {Object} options - The plugin options.
11137 * @returns {Boolean} `false` to cancel the chart update.
11140 * @method IPlugin#afterUpdate
11141 * @desc Called after `chart` has been updated and before rendering. Note that this
11142 * hook will not be called if the chart update has been previously cancelled.
11143 * @param {Chart.Controller} chart - The chart instance.
11144 * @param {Object} options - The plugin options.
11147 * @method IPlugin#beforeDatasetsUpdate
11148 * @desc Called before updating the `chart` datasets. If any plugin returns `false`,
11149 * the datasets update is cancelled until another `update` is triggered.
11150 * @param {Chart.Controller} chart - The chart instance.
11151 * @param {Object} options - The plugin options.
11152 * @returns {Boolean} false to cancel the datasets update.
11153 * @since version 2.1.5
11156 * @method IPlugin#afterDatasetsUpdate
11157 * @desc Called after the `chart` datasets have been updated. Note that this hook
11158 * will not be called if the datasets update has been previously cancelled.
11159 * @param {Chart.Controller} chart - The chart instance.
11160 * @param {Object} options - The plugin options.
11161 * @since version 2.1.5
11164 * @method IPlugin#beforeDatasetUpdate
11165 * @desc Called before updating the `chart` dataset at the given `args.index`. If any plugin
11166 * returns `false`, the datasets update is cancelled until another `update` is triggered.
11167 * @param {Chart} chart - The chart instance.
11168 * @param {Object} args - The call arguments.
11169 * @param {Number} args.index - The dataset index.
11170 * @param {Object} args.meta - The dataset metadata.
11171 * @param {Object} options - The plugin options.
11172 * @returns {Boolean} `false` to cancel the chart datasets drawing.
11175 * @method IPlugin#afterDatasetUpdate
11176 * @desc Called after the `chart` datasets at the given `args.index` has been updated. Note
11177 * that this hook will not be called if the datasets update has been previously cancelled.
11178 * @param {Chart} chart - The chart instance.
11179 * @param {Object} args - The call arguments.
11180 * @param {Number} args.index - The dataset index.
11181 * @param {Object} args.meta - The dataset metadata.
11182 * @param {Object} options - The plugin options.
11185 * @method IPlugin#beforeLayout
11186 * @desc Called before laying out `chart`. If any plugin returns `false`,
11187 * the layout update is cancelled until another `update` is triggered.
11188 * @param {Chart.Controller} chart - The chart instance.
11189 * @param {Object} options - The plugin options.
11190 * @returns {Boolean} `false` to cancel the chart layout.
11193 * @method IPlugin#afterLayout
11194 * @desc Called after the `chart` has been layed out. Note that this hook will not
11195 * be called if the layout update has been previously cancelled.
11196 * @param {Chart.Controller} chart - The chart instance.
11197 * @param {Object} options - The plugin options.
11200 * @method IPlugin#beforeRender
11201 * @desc Called before rendering `chart`. If any plugin returns `false`,
11202 * the rendering is cancelled until another `render` is triggered.
11203 * @param {Chart.Controller} chart - The chart instance.
11204 * @param {Object} options - The plugin options.
11205 * @returns {Boolean} `false` to cancel the chart rendering.
11208 * @method IPlugin#afterRender
11209 * @desc Called after the `chart` has been fully rendered (and animation completed). Note
11210 * that this hook will not be called if the rendering has been previously cancelled.
11211 * @param {Chart.Controller} chart - The chart instance.
11212 * @param {Object} options - The plugin options.
11215 * @method IPlugin#beforeDraw
11216 * @desc Called before drawing `chart` at every animation frame specified by the given
11217 * easing value. If any plugin returns `false`, the frame drawing is cancelled until
11218 * another `render` is triggered.
11219 * @param {Chart.Controller} chart - The chart instance.
11220 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
11221 * @param {Object} options - The plugin options.
11222 * @returns {Boolean} `false` to cancel the chart drawing.
11225 * @method IPlugin#afterDraw
11226 * @desc Called after the `chart` has been drawn for the specific easing value. Note
11227 * that this hook will not be called if the drawing has been previously cancelled.
11228 * @param {Chart.Controller} chart - The chart instance.
11229 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
11230 * @param {Object} options - The plugin options.
11233 * @method IPlugin#beforeDatasetsDraw
11234 * @desc Called before drawing the `chart` datasets. If any plugin returns `false`,
11235 * the datasets drawing is cancelled until another `render` is triggered.
11236 * @param {Chart.Controller} chart - The chart instance.
11237 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
11238 * @param {Object} options - The plugin options.
11239 * @returns {Boolean} `false` to cancel the chart datasets drawing.
11242 * @method IPlugin#afterDatasetsDraw
11243 * @desc Called after the `chart` datasets have been drawn. Note that this hook
11244 * will not be called if the datasets drawing has been previously cancelled.
11245 * @param {Chart.Controller} chart - The chart instance.
11246 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
11247 * @param {Object} options - The plugin options.
11250 * @method IPlugin#beforeDatasetDraw
11251 * @desc Called before drawing the `chart` dataset at the given `args.index` (datasets
11252 * are drawn in the reverse order). If any plugin returns `false`, the datasets drawing
11253 * is cancelled until another `render` is triggered.
11254 * @param {Chart} chart - The chart instance.
11255 * @param {Object} args - The call arguments.
11256 * @param {Number} args.index - The dataset index.
11257 * @param {Object} args.meta - The dataset metadata.
11258 * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
11259 * @param {Object} options - The plugin options.
11260 * @returns {Boolean} `false` to cancel the chart datasets drawing.
11263 * @method IPlugin#afterDatasetDraw
11264 * @desc Called after the `chart` datasets at the given `args.index` have been drawn
11265 * (datasets are drawn in the reverse order). Note that this hook will not be called
11266 * if the datasets drawing has been previously cancelled.
11267 * @param {Chart} chart - The chart instance.
11268 * @param {Object} args - The call arguments.
11269 * @param {Number} args.index - The dataset index.
11270 * @param {Object} args.meta - The dataset metadata.
11271 * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
11272 * @param {Object} options - The plugin options.
11275 * @method IPlugin#beforeEvent
11276 * @desc Called before processing the specified `event`. If any plugin returns `false`,
11277 * the event will be discarded.
11278 * @param {Chart.Controller} chart - The chart instance.
11279 * @param {IEvent} event - The event object.
11280 * @param {Object} options - The plugin options.
11283 * @method IPlugin#afterEvent
11284 * @desc Called after the `event` has been consumed. Note that this hook
11285 * will not be called if the `event` has been previously discarded.
11286 * @param {Chart.Controller} chart - The chart instance.
11287 * @param {IEvent} event - The event object.
11288 * @param {Object} options - The plugin options.
11291 * @method IPlugin#resize
11292 * @desc Called after the chart as been resized.
11293 * @param {Chart.Controller} chart - The chart instance.
11294 * @param {Number} size - The new canvas display size (eq. canvas.style width & height).
11295 * @param {Object} options - The plugin options.
11298 * @method IPlugin#destroy
11299 * @desc Called after the chart as been destroyed.
11300 * @param {Chart.Controller} chart - The chart instance.
11301 * @param {Object} options - The plugin options.
11305 * Provided for backward compatibility, use Chart.plugins instead
11306 * @namespace Chart.pluginService
11307 * @deprecated since version 2.1.5
11308 * @todo remove at version 3
11311 Chart.pluginService = Chart.plugins;
11314 * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
11315 * effect, instead simply create/register plugins via plain JavaScript objects.
11316 * @interface Chart.PluginBase
11317 * @deprecated since version 2.5.0
11318 * @todo remove at version 3
11321 Chart.PluginBase = Element.extend({});
11324 },{"25":25,"26":26,"45":45}],32:[function(require,module,exports){
11327 var defaults = require(25);
11328 var Element = require(26);
11329 var helpers = require(45);
11330 var Ticks = require(34);
11332 defaults._set('scale', {
11337 // grid line settings
11340 color: 'rgba(0, 0, 0, 0.1)',
11343 drawOnChartArea: true,
11345 tickMarkLength: 10,
11347 zeroLineColor: 'rgba(0,0,0,0.25)',
11348 zeroLineBorderDash: [],
11349 zeroLineBorderDashOffset: 0.0,
11350 offsetGridLines: false,
11352 borderDashOffset: 0.0
11357 // display property
11366 // top/bottom padding
11375 beginAtZero: false,
11383 autoSkipPadding: 0,
11385 // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
11386 callback: Ticks.formatters.values,
11392 function labelsFromTicks(ticks) {
11396 for (i = 0, ilen = ticks.length; i < ilen; ++i) {
11397 labels.push(ticks[i].label);
11403 function getLineValue(scale, index, offsetGridLines) {
11404 var lineValue = scale.getPixelForTick(index);
11406 if (offsetGridLines) {
11408 lineValue -= (scale.getPixelForTick(1) - lineValue) / 2;
11410 lineValue -= (lineValue - scale.getPixelForTick(index - 1)) / 2;
11416 module.exports = function(Chart) {
11418 function computeTextSize(context, tick, font) {
11419 return helpers.isArray(tick) ?
11420 helpers.longestText(context, font, tick) :
11421 context.measureText(tick).width;
11424 function parseFontOptions(options) {
11425 var valueOrDefault = helpers.valueOrDefault;
11426 var globalDefaults = defaults.global;
11427 var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
11428 var style = valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle);
11429 var family = valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily);
11435 font: helpers.fontString(size, style, family)
11439 function parseLineHeight(options) {
11440 return helpers.options.toLineHeight(
11441 helpers.valueOrDefault(options.lineHeight, 1.2),
11442 helpers.valueOrDefault(options.fontSize, defaults.global.defaultFontSize));
11445 Chart.Scale = Element.extend({
11447 * Get the padding needed for the scale
11448 * @method getPadding
11450 * @returns {Padding} the necessary padding
11452 getPadding: function() {
11455 left: me.paddingLeft || 0,
11456 top: me.paddingTop || 0,
11457 right: me.paddingRight || 0,
11458 bottom: me.paddingBottom || 0
11463 * Returns the scale tick objects ({label, major})
11466 getTicks: function() {
11467 return this._ticks;
11470 // These methods are ordered by lifecyle. Utilities then follow.
11471 // Any function defined here is inherited by all scale types.
11472 // Any function can be extended by the scale type
11474 mergeTicksOptions: function() {
11475 var ticks = this.options.ticks;
11476 if (ticks.minor === false) {
11481 if (ticks.major === false) {
11486 for (var key in ticks) {
11487 if (key !== 'major' && key !== 'minor') {
11488 if (typeof ticks.minor[key] === 'undefined') {
11489 ticks.minor[key] = ticks[key];
11491 if (typeof ticks.major[key] === 'undefined') {
11492 ticks.major[key] = ticks[key];
11497 beforeUpdate: function() {
11498 helpers.callback(this.options.beforeUpdate, [this]);
11500 update: function(maxWidth, maxHeight, margins) {
11502 var i, ilen, labels, label, ticks, tick;
11504 // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
11507 // Absorb the master measurements
11508 me.maxWidth = maxWidth;
11509 me.maxHeight = maxHeight;
11510 me.margins = helpers.extend({
11516 me.longestTextCache = me.longestTextCache || {};
11519 me.beforeSetDimensions();
11520 me.setDimensions();
11521 me.afterSetDimensions();
11524 me.beforeDataLimits();
11525 me.determineDataLimits();
11526 me.afterDataLimits();
11528 // Ticks - `this.ticks` is now DEPRECATED!
11529 // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
11530 // and must not be accessed directly from outside this class. `this.ticks` being
11531 // around for long time and not marked as private, we can't change its structure
11532 // without unexpected breaking changes. If you need to access the scale ticks,
11533 // use scale.getTicks() instead.
11535 me.beforeBuildTicks();
11537 // New implementations should return an array of objects but for BACKWARD COMPAT,
11538 // we still support no return (`this.ticks` internally set by calling this method).
11539 ticks = me.buildTicks() || [];
11541 me.afterBuildTicks();
11543 me.beforeTickToLabelConversion();
11545 // New implementations should return the formatted tick labels but for BACKWARD
11546 // COMPAT, we still support no return (`this.ticks` internally changed by calling
11547 // this method and supposed to contain only string values).
11548 labels = me.convertTicksToLabels(ticks) || me.ticks;
11550 me.afterTickToLabelConversion();
11552 me.ticks = labels; // BACKWARD COMPATIBILITY
11554 // IMPORTANT: from this point, we consider that `this.ticks` will NEVER change!
11556 // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
11557 for (i = 0, ilen = labels.length; i < ilen; ++i) {
11561 ticks.push(tick = {
11566 tick.label = label;
11573 me.beforeCalculateTickRotation();
11574 me.calculateTickRotation();
11575 me.afterCalculateTickRotation();
11586 afterUpdate: function() {
11587 helpers.callback(this.options.afterUpdate, [this]);
11592 beforeSetDimensions: function() {
11593 helpers.callback(this.options.beforeSetDimensions, [this]);
11595 setDimensions: function() {
11597 // Set the unconstrained dimension before label rotation
11598 if (me.isHorizontal()) {
11599 // Reset position before calculating rotation
11600 me.width = me.maxWidth;
11602 me.right = me.width;
11604 me.height = me.maxHeight;
11606 // Reset position before calculating rotation
11608 me.bottom = me.height;
11612 me.paddingLeft = 0;
11614 me.paddingRight = 0;
11615 me.paddingBottom = 0;
11617 afterSetDimensions: function() {
11618 helpers.callback(this.options.afterSetDimensions, [this]);
11622 beforeDataLimits: function() {
11623 helpers.callback(this.options.beforeDataLimits, [this]);
11625 determineDataLimits: helpers.noop,
11626 afterDataLimits: function() {
11627 helpers.callback(this.options.afterDataLimits, [this]);
11631 beforeBuildTicks: function() {
11632 helpers.callback(this.options.beforeBuildTicks, [this]);
11634 buildTicks: helpers.noop,
11635 afterBuildTicks: function() {
11636 helpers.callback(this.options.afterBuildTicks, [this]);
11639 beforeTickToLabelConversion: function() {
11640 helpers.callback(this.options.beforeTickToLabelConversion, [this]);
11642 convertTicksToLabels: function() {
11644 // Convert ticks to strings
11645 var tickOpts = me.options.ticks;
11646 me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
11648 afterTickToLabelConversion: function() {
11649 helpers.callback(this.options.afterTickToLabelConversion, [this]);
11654 beforeCalculateTickRotation: function() {
11655 helpers.callback(this.options.beforeCalculateTickRotation, [this]);
11657 calculateTickRotation: function() {
11659 var context = me.ctx;
11660 var tickOpts = me.options.ticks;
11661 var labels = labelsFromTicks(me._ticks);
11663 // Get the width of each grid by calculating the difference
11664 // between x offsets between 0 and 1.
11665 var tickFont = parseFontOptions(tickOpts);
11666 context.font = tickFont.font;
11668 var labelRotation = tickOpts.minRotation || 0;
11670 if (labels.length && me.options.display && me.isHorizontal()) {
11671 var originalLabelWidth = helpers.longestText(context, tickFont.font, labels, me.longestTextCache);
11672 var labelWidth = originalLabelWidth;
11673 var cosRotation, sinRotation;
11675 // Allow 3 pixels x2 padding either side for label readability
11676 var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6;
11678 // Max label rotation can be set or default to 90 - also act as a loop counter
11679 while (labelWidth > tickWidth && labelRotation < tickOpts.maxRotation) {
11680 var angleRadians = helpers.toRadians(labelRotation);
11681 cosRotation = Math.cos(angleRadians);
11682 sinRotation = Math.sin(angleRadians);
11684 if (sinRotation * originalLabelWidth > me.maxHeight) {
11685 // go back one step
11691 labelWidth = cosRotation * originalLabelWidth;
11695 me.labelRotation = labelRotation;
11697 afterCalculateTickRotation: function() {
11698 helpers.callback(this.options.afterCalculateTickRotation, [this]);
11703 beforeFit: function() {
11704 helpers.callback(this.options.beforeFit, [this]);
11709 var minSize = me.minSize = {
11714 var labels = labelsFromTicks(me._ticks);
11716 var opts = me.options;
11717 var tickOpts = opts.ticks;
11718 var scaleLabelOpts = opts.scaleLabel;
11719 var gridLineOpts = opts.gridLines;
11720 var display = opts.display;
11721 var isHorizontal = me.isHorizontal();
11723 var tickFont = parseFontOptions(tickOpts);
11724 var tickMarkLength = opts.gridLines.tickMarkLength;
11727 if (isHorizontal) {
11728 // subtract the margins to line up with the chartArea if we are a full width scale
11729 minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth;
11731 minSize.width = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
11735 if (isHorizontal) {
11736 minSize.height = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
11738 minSize.height = me.maxHeight; // fill all the height
11741 // Are we showing a title for the scale?
11742 if (scaleLabelOpts.display && display) {
11743 var scaleLabelLineHeight = parseLineHeight(scaleLabelOpts);
11744 var scaleLabelPadding = helpers.options.toPadding(scaleLabelOpts.padding);
11745 var deltaHeight = scaleLabelLineHeight + scaleLabelPadding.height;
11747 if (isHorizontal) {
11748 minSize.height += deltaHeight;
11750 minSize.width += deltaHeight;
11754 // Don't bother fitting the ticks if we are not showing them
11755 if (tickOpts.display && display) {
11756 var largestTextWidth = helpers.longestText(me.ctx, tickFont.font, labels, me.longestTextCache);
11757 var tallestLabelHeightInLines = helpers.numberOfLabelLines(labels);
11758 var lineSpace = tickFont.size * 0.5;
11759 var tickPadding = me.options.ticks.padding;
11761 if (isHorizontal) {
11762 // A horizontal axis is more constrained by the height.
11763 me.longestLabelWidth = largestTextWidth;
11765 var angleRadians = helpers.toRadians(me.labelRotation);
11766 var cosRotation = Math.cos(angleRadians);
11767 var sinRotation = Math.sin(angleRadians);
11769 // TODO - improve this calculation
11770 var labelHeight = (sinRotation * largestTextWidth)
11771 + (tickFont.size * tallestLabelHeightInLines)
11772 + (lineSpace * (tallestLabelHeightInLines - 1))
11773 + lineSpace; // padding
11775 minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
11777 me.ctx.font = tickFont.font;
11778 var firstLabelWidth = computeTextSize(me.ctx, labels[0], tickFont.font);
11779 var lastLabelWidth = computeTextSize(me.ctx, labels[labels.length - 1], tickFont.font);
11781 // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
11782 // which means that the right padding is dominated by the font height
11783 if (me.labelRotation !== 0) {
11784 me.paddingLeft = opts.position === 'bottom' ? (cosRotation * firstLabelWidth) + 3 : (cosRotation * lineSpace) + 3; // add 3 px to move away from canvas edges
11785 me.paddingRight = opts.position === 'bottom' ? (cosRotation * lineSpace) + 3 : (cosRotation * lastLabelWidth) + 3;
11787 me.paddingLeft = firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges
11788 me.paddingRight = lastLabelWidth / 2 + 3;
11791 // A vertical axis is more constrained by the width. Labels are the
11792 // dominant factor here, so get that length first and account for padding
11793 if (tickOpts.mirror) {
11794 largestTextWidth = 0;
11796 // use lineSpace for consistency with horizontal axis
11797 // tickPadding is not implemented for horizontal
11798 largestTextWidth += tickPadding + lineSpace;
11801 minSize.width = Math.min(me.maxWidth, minSize.width + largestTextWidth);
11803 me.paddingTop = tickFont.size / 2;
11804 me.paddingBottom = tickFont.size / 2;
11808 me.handleMargins();
11810 me.width = minSize.width;
11811 me.height = minSize.height;
11815 * Handle margins and padding interactions
11818 handleMargins: function() {
11821 me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0);
11822 me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0);
11823 me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0);
11824 me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0);
11828 afterFit: function() {
11829 helpers.callback(this.options.afterFit, [this]);
11833 isHorizontal: function() {
11834 return this.options.position === 'top' || this.options.position === 'bottom';
11836 isFullWidth: function() {
11837 return (this.options.fullWidth);
11840 // Get the correct value. NaN bad inputs, If the value type is object get the x or y based on whether we are horizontal or not
11841 getRightValue: function(rawValue) {
11842 // Null and undefined values first
11843 if (helpers.isNullOrUndef(rawValue)) {
11846 // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
11847 if (typeof rawValue === 'number' && !isFinite(rawValue)) {
11850 // If it is in fact an object, dive in one more level
11852 if (this.isHorizontal()) {
11853 if (rawValue.x !== undefined) {
11854 return this.getRightValue(rawValue.x);
11856 } else if (rawValue.y !== undefined) {
11857 return this.getRightValue(rawValue.y);
11861 // Value is good, return it
11865 // Used to get the value to display in the tooltip for the data at the given index
11866 // function getLabelForIndex(index, datasetIndex)
11867 getLabelForIndex: helpers.noop,
11869 // Used to get data value locations. Value can either be an index or a numerical value
11870 getPixelForValue: helpers.noop,
11872 // Used to get the data value from a given pixel. This is the inverse of getPixelForValue
11873 getValueForPixel: helpers.noop,
11875 // Used for tick location, should
11876 getPixelForTick: function(index) {
11878 var offset = me.options.offset;
11879 if (me.isHorizontal()) {
11880 var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
11881 var tickWidth = innerWidth / Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
11882 var pixel = (tickWidth * index) + me.paddingLeft;
11885 pixel += tickWidth / 2;
11888 var finalVal = me.left + Math.round(pixel);
11889 finalVal += me.isFullWidth() ? me.margins.left : 0;
11892 var innerHeight = me.height - (me.paddingTop + me.paddingBottom);
11893 return me.top + (index * (innerHeight / (me._ticks.length - 1)));
11896 // Utility for getting the pixel location of a percentage of scale
11897 getPixelForDecimal: function(decimal) {
11899 if (me.isHorizontal()) {
11900 var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
11901 var valueOffset = (innerWidth * decimal) + me.paddingLeft;
11903 var finalVal = me.left + Math.round(valueOffset);
11904 finalVal += me.isFullWidth() ? me.margins.left : 0;
11907 return me.top + (decimal * me.height);
11910 getBasePixel: function() {
11911 return this.getPixelForValue(this.getBaseValue());
11914 getBaseValue: function() {
11919 return me.beginAtZero ? 0 :
11920 min < 0 && max < 0 ? max :
11921 min > 0 && max > 0 ? min :
11926 * Returns a subset of ticks to be plotted to avoid overlapping labels.
11929 _autoSkip: function(ticks) {
11932 var isHorizontal = me.isHorizontal();
11933 var optionTicks = me.options.ticks.minor;
11934 var tickCount = ticks.length;
11935 var labelRotationRadians = helpers.toRadians(me.labelRotation);
11936 var cosRotation = Math.cos(labelRotationRadians);
11937 var longestRotatedLabel = me.longestLabelWidth * cosRotation;
11939 var i, tick, shouldSkip;
11941 // figure out the maximum number of gridlines to show
11943 if (optionTicks.maxTicksLimit) {
11944 maxTicks = optionTicks.maxTicksLimit;
11947 if (isHorizontal) {
11950 if ((longestRotatedLabel + optionTicks.autoSkipPadding) * tickCount > (me.width - (me.paddingLeft + me.paddingRight))) {
11951 skipRatio = 1 + Math.floor(((longestRotatedLabel + optionTicks.autoSkipPadding) * tickCount) / (me.width - (me.paddingLeft + me.paddingRight)));
11954 // if they defined a max number of optionTicks,
11955 // increase skipRatio until that number is met
11956 if (maxTicks && tickCount > maxTicks) {
11957 skipRatio = Math.max(skipRatio, Math.floor(tickCount / maxTicks));
11961 for (i = 0; i < tickCount; i++) {
11964 // Since we always show the last tick,we need may need to hide the last shown one before
11965 shouldSkip = (skipRatio > 1 && i % skipRatio > 0) || (i % skipRatio === 0 && i + skipRatio >= tickCount);
11966 if (shouldSkip && i !== tickCount - 1 || helpers.isNullOrUndef(tick.label)) {
11967 // leave tick in place but make sure it's not displayed (#4635)
11975 // Actually draw the scale on the canvas
11976 // @param {rectangle} chartArea : the area of the chart to draw full grid lines on
11977 draw: function(chartArea) {
11979 var options = me.options;
11980 if (!options.display) {
11984 var context = me.ctx;
11985 var globalDefaults = defaults.global;
11986 var optionTicks = options.ticks.minor;
11987 var optionMajorTicks = options.ticks.major || optionTicks;
11988 var gridLines = options.gridLines;
11989 var scaleLabel = options.scaleLabel;
11991 var isRotated = me.labelRotation !== 0;
11992 var isHorizontal = me.isHorizontal();
11994 var ticks = optionTicks.autoSkip ? me._autoSkip(me.getTicks()) : me.getTicks();
11995 var tickFontColor = helpers.valueOrDefault(optionTicks.fontColor, globalDefaults.defaultFontColor);
11996 var tickFont = parseFontOptions(optionTicks);
11997 var majorTickFontColor = helpers.valueOrDefault(optionMajorTicks.fontColor, globalDefaults.defaultFontColor);
11998 var majorTickFont = parseFontOptions(optionMajorTicks);
12000 var tl = gridLines.drawTicks ? gridLines.tickMarkLength : 0;
12002 var scaleLabelFontColor = helpers.valueOrDefault(scaleLabel.fontColor, globalDefaults.defaultFontColor);
12003 var scaleLabelFont = parseFontOptions(scaleLabel);
12004 var scaleLabelPadding = helpers.options.toPadding(scaleLabel.padding);
12005 var labelRotationRadians = helpers.toRadians(me.labelRotation);
12007 var itemsToDraw = [];
12009 var xTickStart = options.position === 'right' ? me.left : me.right - tl;
12010 var xTickEnd = options.position === 'right' ? me.left + tl : me.right;
12011 var yTickStart = options.position === 'bottom' ? me.top : me.bottom - tl;
12012 var yTickEnd = options.position === 'bottom' ? me.top + tl : me.bottom;
12014 helpers.each(ticks, function(tick, index) {
12015 // autoskipper skipped this tick (#4635)
12016 if (tick.label === undefined) {
12020 var label = tick.label;
12021 var lineWidth, lineColor, borderDash, borderDashOffset;
12022 if (index === me.zeroLineIndex && options.offset === gridLines.offsetGridLines) {
12023 // Draw the first index specially
12024 lineWidth = gridLines.zeroLineWidth;
12025 lineColor = gridLines.zeroLineColor;
12026 borderDash = gridLines.zeroLineBorderDash;
12027 borderDashOffset = gridLines.zeroLineBorderDashOffset;
12029 lineWidth = helpers.valueAtIndexOrDefault(gridLines.lineWidth, index);
12030 lineColor = helpers.valueAtIndexOrDefault(gridLines.color, index);
12031 borderDash = helpers.valueOrDefault(gridLines.borderDash, globalDefaults.borderDash);
12032 borderDashOffset = helpers.valueOrDefault(gridLines.borderDashOffset, globalDefaults.borderDashOffset);
12035 // Common properties
12036 var tx1, ty1, tx2, ty2, x1, y1, x2, y2, labelX, labelY;
12037 var textAlign = 'middle';
12038 var textBaseline = 'middle';
12039 var tickPadding = optionTicks.padding;
12041 if (isHorizontal) {
12042 var labelYOffset = tl + tickPadding;
12044 if (options.position === 'bottom') {
12046 textBaseline = !isRotated ? 'top' : 'middle';
12047 textAlign = !isRotated ? 'center' : 'right';
12048 labelY = me.top + labelYOffset;
12051 textBaseline = !isRotated ? 'bottom' : 'middle';
12052 textAlign = !isRotated ? 'center' : 'left';
12053 labelY = me.bottom - labelYOffset;
12056 var xLineValue = getLineValue(me, index, gridLines.offsetGridLines && ticks.length > 1);
12057 if (xLineValue < me.left) {
12058 lineColor = 'rgba(0,0,0,0)';
12060 xLineValue += helpers.aliasPixel(lineWidth);
12062 labelX = me.getPixelForTick(index) + optionTicks.labelOffset; // x values for optionTicks (need to consider offsetLabel option)
12064 tx1 = tx2 = x1 = x2 = xLineValue;
12067 y1 = chartArea.top;
12068 y2 = chartArea.bottom;
12070 var isLeft = options.position === 'left';
12073 if (optionTicks.mirror) {
12074 textAlign = isLeft ? 'left' : 'right';
12075 labelXOffset = tickPadding;
12077 textAlign = isLeft ? 'right' : 'left';
12078 labelXOffset = tl + tickPadding;
12081 labelX = isLeft ? me.right - labelXOffset : me.left + labelXOffset;
12083 var yLineValue = getLineValue(me, index, gridLines.offsetGridLines && ticks.length > 1);
12084 if (yLineValue < me.top) {
12085 lineColor = 'rgba(0,0,0,0)';
12087 yLineValue += helpers.aliasPixel(lineWidth);
12089 labelY = me.getPixelForTick(index) + optionTicks.labelOffset;
12093 x1 = chartArea.left;
12094 x2 = chartArea.right;
12095 ty1 = ty2 = y1 = y2 = yLineValue;
12109 glWidth: lineWidth,
12110 glColor: lineColor,
12111 glBorderDash: borderDash,
12112 glBorderDashOffset: borderDashOffset,
12113 rotation: -1 * labelRotationRadians,
12116 textBaseline: textBaseline,
12117 textAlign: textAlign
12121 // Draw all of the tick labels, tick marks, and grid lines at the correct places
12122 helpers.each(itemsToDraw, function(itemToDraw) {
12123 if (gridLines.display) {
12125 context.lineWidth = itemToDraw.glWidth;
12126 context.strokeStyle = itemToDraw.glColor;
12127 if (context.setLineDash) {
12128 context.setLineDash(itemToDraw.glBorderDash);
12129 context.lineDashOffset = itemToDraw.glBorderDashOffset;
12132 context.beginPath();
12134 if (gridLines.drawTicks) {
12135 context.moveTo(itemToDraw.tx1, itemToDraw.ty1);
12136 context.lineTo(itemToDraw.tx2, itemToDraw.ty2);
12139 if (gridLines.drawOnChartArea) {
12140 context.moveTo(itemToDraw.x1, itemToDraw.y1);
12141 context.lineTo(itemToDraw.x2, itemToDraw.y2);
12148 if (optionTicks.display) {
12149 // Make sure we draw text in the correct color and font
12151 context.translate(itemToDraw.labelX, itemToDraw.labelY);
12152 context.rotate(itemToDraw.rotation);
12153 context.font = itemToDraw.major ? majorTickFont.font : tickFont.font;
12154 context.fillStyle = itemToDraw.major ? majorTickFontColor : tickFontColor;
12155 context.textBaseline = itemToDraw.textBaseline;
12156 context.textAlign = itemToDraw.textAlign;
12158 var label = itemToDraw.label;
12159 if (helpers.isArray(label)) {
12160 for (var i = 0, y = 0; i < label.length; ++i) {
12161 // We just make sure the multiline element is a string here..
12162 context.fillText('' + label[i], 0, y);
12163 // apply same lineSpacing as calculated @ L#320
12164 y += (tickFont.size * 1.5);
12167 context.fillText(label, 0, 0);
12173 if (scaleLabel.display) {
12174 // Draw the scale label
12178 var halfLineHeight = parseLineHeight(scaleLabel) / 2;
12180 if (isHorizontal) {
12181 scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width
12182 scaleLabelY = options.position === 'bottom'
12183 ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
12184 : me.top + halfLineHeight + scaleLabelPadding.top;
12186 var isLeft = options.position === 'left';
12187 scaleLabelX = isLeft
12188 ? me.left + halfLineHeight + scaleLabelPadding.top
12189 : me.right - halfLineHeight - scaleLabelPadding.top;
12190 scaleLabelY = me.top + ((me.bottom - me.top) / 2);
12191 rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
12195 context.translate(scaleLabelX, scaleLabelY);
12196 context.rotate(rotation);
12197 context.textAlign = 'center';
12198 context.textBaseline = 'middle';
12199 context.fillStyle = scaleLabelFontColor; // render in correct colour
12200 context.font = scaleLabelFont.font;
12201 context.fillText(scaleLabel.labelString, 0, 0);
12205 if (gridLines.drawBorder) {
12206 // Draw the line at the edge of the axis
12207 context.lineWidth = helpers.valueAtIndexOrDefault(gridLines.lineWidth, 0);
12208 context.strokeStyle = helpers.valueAtIndexOrDefault(gridLines.color, 0);
12212 var y2 = me.bottom;
12214 var aliasPixel = helpers.aliasPixel(context.lineWidth);
12215 if (isHorizontal) {
12216 y1 = y2 = options.position === 'top' ? me.bottom : me.top;
12220 x1 = x2 = options.position === 'left' ? me.right : me.left;
12225 context.beginPath();
12226 context.moveTo(x1, y1);
12227 context.lineTo(x2, y2);
12234 },{"25":25,"26":26,"34":34,"45":45}],33:[function(require,module,exports){
12237 var defaults = require(25);
12238 var helpers = require(45);
12240 module.exports = function(Chart) {
12242 Chart.scaleService = {
12243 // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
12244 // use the new chart options to grab the correct scale
12246 // Use a registration function so that we can move to an ES6 map when we no longer need to support
12249 // Scale config defaults
12251 registerScaleType: function(type, scaleConstructor, scaleDefaults) {
12252 this.constructors[type] = scaleConstructor;
12253 this.defaults[type] = helpers.clone(scaleDefaults);
12255 getScaleConstructor: function(type) {
12256 return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
12258 getScaleDefaults: function(type) {
12259 // Return the scale defaults merged with the global settings so that we always use the latest ones
12260 return this.defaults.hasOwnProperty(type) ? helpers.merge({}, [defaults.scale, this.defaults[type]]) : {};
12262 updateScaleDefaults: function(type, additions) {
12264 if (me.defaults.hasOwnProperty(type)) {
12265 me.defaults[type] = helpers.extend(me.defaults[type], additions);
12268 addScalesToLayout: function(chart) {
12269 // Adds each scale to the chart.boxes array to be sized accordingly
12270 helpers.each(chart.scales, function(scale) {
12271 // Set ILayoutItem parameters for backwards compatibility
12272 scale.fullWidth = scale.options.fullWidth;
12273 scale.position = scale.options.position;
12274 scale.weight = scale.options.weight;
12275 Chart.layoutService.addBox(chart, scale);
12281 },{"25":25,"45":45}],34:[function(require,module,exports){
12284 var helpers = require(45);
12287 * Namespace to hold static tick generation functions
12288 * @namespace Chart.Ticks
12292 * Namespace to hold generators for different types of ticks
12293 * @namespace Chart.Ticks.generators
12297 * Interface for the options provided to the numeric tick generator
12298 * @interface INumericTickGenerationOptions
12301 * The maximum number of ticks to display
12302 * @name INumericTickGenerationOptions#maxTicks
12306 * The distance between each tick.
12307 * @name INumericTickGenerationOptions#stepSize
12312 * Forced minimum for the ticks. If not specified, the minimum of the data range is used to calculate the tick minimum
12313 * @name INumericTickGenerationOptions#min
12318 * The maximum value of the ticks. If not specified, the maximum of the data range is used to calculate the tick maximum
12319 * @name INumericTickGenerationOptions#max
12325 * Generate a set of linear ticks
12326 * @method Chart.Ticks.generators.linear
12327 * @param generationOptions {INumericTickGenerationOptions} the options used to generate the ticks
12328 * @param dataRange {IRange} the range of the data
12329 * @returns {Array<Number>} array of tick values
12331 linear: function(generationOptions, dataRange) {
12333 // To get a "nice" value for the tick spacing, we will use the appropriately named
12334 // "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
12338 if (generationOptions.stepSize && generationOptions.stepSize > 0) {
12339 spacing = generationOptions.stepSize;
12341 var niceRange = helpers.niceNum(dataRange.max - dataRange.min, false);
12342 spacing = helpers.niceNum(niceRange / (generationOptions.maxTicks - 1), true);
12344 var niceMin = Math.floor(dataRange.min / spacing) * spacing;
12345 var niceMax = Math.ceil(dataRange.max / spacing) * spacing;
12347 // If min, max and stepSize is set and they make an evenly spaced scale use it.
12348 if (generationOptions.min && generationOptions.max && generationOptions.stepSize) {
12349 // If very close to our whole number, use it.
12350 if (helpers.almostWhole((generationOptions.max - generationOptions.min) / generationOptions.stepSize, spacing / 1000)) {
12351 niceMin = generationOptions.min;
12352 niceMax = generationOptions.max;
12356 var numSpaces = (niceMax - niceMin) / spacing;
12357 // If very close to our rounded value, use it.
12358 if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
12359 numSpaces = Math.round(numSpaces);
12361 numSpaces = Math.ceil(numSpaces);
12364 // Put the values into the ticks array
12365 ticks.push(generationOptions.min !== undefined ? generationOptions.min : niceMin);
12366 for (var j = 1; j < numSpaces; ++j) {
12367 ticks.push(niceMin + (j * spacing));
12369 ticks.push(generationOptions.max !== undefined ? generationOptions.max : niceMax);
12375 * Generate a set of logarithmic ticks
12376 * @method Chart.Ticks.generators.logarithmic
12377 * @param generationOptions {INumericTickGenerationOptions} the options used to generate the ticks
12378 * @param dataRange {IRange} the range of the data
12379 * @returns {Array<Number>} array of tick values
12381 logarithmic: function(generationOptions, dataRange) {
12383 var valueOrDefault = helpers.valueOrDefault;
12385 // Figure out what the max number of ticks we can support it is based on the size of
12386 // the axis area. For now, we say that the minimum tick spacing in pixels must be 50
12387 // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
12389 var tickVal = valueOrDefault(generationOptions.min, Math.pow(10, Math.floor(helpers.log10(dataRange.min))));
12391 var endExp = Math.floor(helpers.log10(dataRange.max));
12392 var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
12393 var exp, significand;
12395 if (tickVal === 0) {
12396 exp = Math.floor(helpers.log10(dataRange.minNotZero));
12397 significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
12399 ticks.push(tickVal);
12400 tickVal = significand * Math.pow(10, exp);
12402 exp = Math.floor(helpers.log10(tickVal));
12403 significand = Math.floor(tickVal / Math.pow(10, exp));
12407 ticks.push(tickVal);
12410 if (significand === 10) {
12415 tickVal = significand * Math.pow(10, exp);
12416 } while (exp < endExp || (exp === endExp && significand < endSignificand));
12418 var lastTick = valueOrDefault(generationOptions.max, tickVal);
12419 ticks.push(lastTick);
12426 * Namespace to hold formatters for different types of ticks
12427 * @namespace Chart.Ticks.formatters
12431 * Formatter for value labels
12432 * @method Chart.Ticks.formatters.values
12433 * @param value the value to display
12434 * @return {String|Array} the label to display
12436 values: function(value) {
12437 return helpers.isArray(value) ? value : '' + value;
12441 * Formatter for linear numeric ticks
12442 * @method Chart.Ticks.formatters.linear
12443 * @param tickValue {Number} the value to be formatted
12444 * @param index {Number} the position of the tickValue parameter in the ticks array
12445 * @param ticks {Array<Number>} the list of ticks being converted
12446 * @return {String} string representation of the tickValue parameter
12448 linear: function(tickValue, index, ticks) {
12449 // If we have lots of ticks, don't use the ones
12450 var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
12452 // If we have a number like 2.5 as the delta, figure out how many decimal places we need
12453 if (Math.abs(delta) > 1) {
12454 if (tickValue !== Math.floor(tickValue)) {
12456 delta = tickValue - Math.floor(tickValue);
12460 var logDelta = helpers.log10(Math.abs(delta));
12461 var tickString = '';
12463 if (tickValue !== 0) {
12464 var numDecimal = -1 * Math.floor(logDelta);
12465 numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
12466 tickString = tickValue.toFixed(numDecimal);
12468 tickString = '0'; // never show decimal places for 0
12474 logarithmic: function(tickValue, index, ticks) {
12475 var remain = tickValue / (Math.pow(10, Math.floor(helpers.log10(tickValue))));
12477 if (tickValue === 0) {
12479 } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
12480 return tickValue.toExponential();
12487 },{"45":45}],35:[function(require,module,exports){
12490 var defaults = require(25);
12491 var Element = require(26);
12492 var helpers = require(45);
12494 defaults._set('global', {
12499 position: 'average',
12501 backgroundColor: 'rgba(0,0,0,0.8)',
12502 titleFontStyle: 'bold',
12504 titleMarginBottom: 6,
12505 titleFontColor: '#fff',
12506 titleAlign: 'left',
12508 bodyFontColor: '#fff',
12510 footerFontStyle: 'bold',
12512 footerMarginTop: 6,
12513 footerFontColor: '#fff',
12514 footerAlign: 'left',
12520 multiKeyBackground: '#fff',
12521 displayColors: true,
12522 borderColor: 'rgba(0,0,0,0)',
12525 // Args are: (tooltipItems, data)
12526 beforeTitle: helpers.noop,
12527 title: function(tooltipItems, data) {
12528 // Pick first xLabel for now
12530 var labels = data.labels;
12531 var labelCount = labels ? labels.length : 0;
12533 if (tooltipItems.length > 0) {
12534 var item = tooltipItems[0];
12537 title = item.xLabel;
12538 } else if (labelCount > 0 && item.index < labelCount) {
12539 title = labels[item.index];
12545 afterTitle: helpers.noop,
12547 // Args are: (tooltipItems, data)
12548 beforeBody: helpers.noop,
12550 // Args are: (tooltipItem, data)
12551 beforeLabel: helpers.noop,
12552 label: function(tooltipItem, data) {
12553 var label = data.datasets[tooltipItem.datasetIndex].label || '';
12558 label += tooltipItem.yLabel;
12561 labelColor: function(tooltipItem, chart) {
12562 var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
12563 var activeElement = meta.data[tooltipItem.index];
12564 var view = activeElement._view;
12566 borderColor: view.borderColor,
12567 backgroundColor: view.backgroundColor
12570 labelTextColor: function() {
12571 return this._options.bodyFontColor;
12573 afterLabel: helpers.noop,
12575 // Args are: (tooltipItems, data)
12576 afterBody: helpers.noop,
12578 // Args are: (tooltipItems, data)
12579 beforeFooter: helpers.noop,
12580 footer: helpers.noop,
12581 afterFooter: helpers.noop
12586 module.exports = function(Chart) {
12589 * Helper method to merge the opacity into a color
12591 function mergeOpacity(colorString, opacity) {
12592 var color = helpers.color(colorString);
12593 return color.alpha(opacity * color.alpha()).rgbaString();
12596 // Helper to push or concat based on if the 2nd parameter is an array or not
12597 function pushOrConcat(base, toPush) {
12599 if (helpers.isArray(toPush)) {
12600 // base = base.concat(toPush);
12601 Array.prototype.push.apply(base, toPush);
12610 // Private helper to create a tooltip item model
12611 // @param element : the chart element (point, arc, bar) to create the tooltip item for
12612 // @return : new tooltip item
12613 function createTooltipItem(element) {
12614 var xScale = element._xScale;
12615 var yScale = element._yScale || element._scale; // handle radar || polarArea charts
12616 var index = element._index;
12617 var datasetIndex = element._datasetIndex;
12620 xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
12621 yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
12623 datasetIndex: datasetIndex,
12624 x: element._model.x,
12625 y: element._model.y
12630 * Helper to get the reset model for the tooltip
12631 * @param tooltipOpts {Object} the tooltip options
12633 function getBaseModel(tooltipOpts) {
12634 var globalDefaults = defaults.global;
12635 var valueOrDefault = helpers.valueOrDefault;
12639 xPadding: tooltipOpts.xPadding,
12640 yPadding: tooltipOpts.yPadding,
12641 xAlign: tooltipOpts.xAlign,
12642 yAlign: tooltipOpts.yAlign,
12645 bodyFontColor: tooltipOpts.bodyFontColor,
12646 _bodyFontFamily: valueOrDefault(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
12647 _bodyFontStyle: valueOrDefault(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
12648 _bodyAlign: tooltipOpts.bodyAlign,
12649 bodyFontSize: valueOrDefault(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
12650 bodySpacing: tooltipOpts.bodySpacing,
12653 titleFontColor: tooltipOpts.titleFontColor,
12654 _titleFontFamily: valueOrDefault(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
12655 _titleFontStyle: valueOrDefault(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
12656 titleFontSize: valueOrDefault(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
12657 _titleAlign: tooltipOpts.titleAlign,
12658 titleSpacing: tooltipOpts.titleSpacing,
12659 titleMarginBottom: tooltipOpts.titleMarginBottom,
12662 footerFontColor: tooltipOpts.footerFontColor,
12663 _footerFontFamily: valueOrDefault(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
12664 _footerFontStyle: valueOrDefault(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
12665 footerFontSize: valueOrDefault(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
12666 _footerAlign: tooltipOpts.footerAlign,
12667 footerSpacing: tooltipOpts.footerSpacing,
12668 footerMarginTop: tooltipOpts.footerMarginTop,
12671 caretSize: tooltipOpts.caretSize,
12672 cornerRadius: tooltipOpts.cornerRadius,
12673 backgroundColor: tooltipOpts.backgroundColor,
12675 legendColorBackground: tooltipOpts.multiKeyBackground,
12676 displayColors: tooltipOpts.displayColors,
12677 borderColor: tooltipOpts.borderColor,
12678 borderWidth: tooltipOpts.borderWidth
12683 * Get the size of the tooltip
12685 function getTooltipSize(tooltip, model) {
12686 var ctx = tooltip._chart.ctx;
12688 var height = model.yPadding * 2; // Tooltip Padding
12691 // Count of all lines in the body
12692 var body = model.body;
12693 var combinedBodyLength = body.reduce(function(count, bodyItem) {
12694 return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
12696 combinedBodyLength += model.beforeBody.length + model.afterBody.length;
12698 var titleLineCount = model.title.length;
12699 var footerLineCount = model.footer.length;
12700 var titleFontSize = model.titleFontSize;
12701 var bodyFontSize = model.bodyFontSize;
12702 var footerFontSize = model.footerFontSize;
12704 height += titleLineCount * titleFontSize; // Title Lines
12705 height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
12706 height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
12707 height += combinedBodyLength * bodyFontSize; // Body Lines
12708 height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
12709 height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
12710 height += footerLineCount * (footerFontSize); // Footer Lines
12711 height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
12714 var widthPadding = 0;
12715 var maxLineWidth = function(line) {
12716 width = Math.max(width, ctx.measureText(line).width + widthPadding);
12719 ctx.font = helpers.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
12720 helpers.each(model.title, maxLineWidth);
12723 ctx.font = helpers.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
12724 helpers.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
12726 // Body lines may include some extra width due to the color box
12727 widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
12728 helpers.each(body, function(bodyItem) {
12729 helpers.each(bodyItem.before, maxLineWidth);
12730 helpers.each(bodyItem.lines, maxLineWidth);
12731 helpers.each(bodyItem.after, maxLineWidth);
12738 ctx.font = helpers.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
12739 helpers.each(model.footer, maxLineWidth);
12742 width += 2 * model.xPadding;
12751 * Helper to get the alignment of a tooltip given the size
12753 function determineAlignment(tooltip, size) {
12754 var model = tooltip._model;
12755 var chart = tooltip._chart;
12756 var chartArea = tooltip._chart.chartArea;
12757 var xAlign = 'center';
12758 var yAlign = 'center';
12760 if (model.y < size.height) {
12762 } else if (model.y > (chart.height - size.height)) {
12766 var lf, rf; // functions to determine left, right alignment
12767 var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
12768 var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
12769 var midX = (chartArea.left + chartArea.right) / 2;
12770 var midY = (chartArea.top + chartArea.bottom) / 2;
12772 if (yAlign === 'center') {
12781 return x <= (size.width / 2);
12784 return x >= (chart.width - (size.width / 2));
12788 olf = function(x) {
12789 return x + size.width > chart.width;
12791 orf = function(x) {
12792 return x - size.width < 0;
12795 return y <= midY ? 'top' : 'bottom';
12801 // Is tooltip too wide and goes over the right side of the chart.?
12802 if (olf(model.x)) {
12804 yAlign = yf(model.y);
12806 } else if (rf(model.x)) {
12809 // Is tooltip too wide and goes outside left edge of canvas?
12810 if (orf(model.x)) {
12812 yAlign = yf(model.y);
12816 var opts = tooltip._options;
12818 xAlign: opts.xAlign ? opts.xAlign : xAlign,
12819 yAlign: opts.yAlign ? opts.yAlign : yAlign
12824 * @Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
12826 function getBackgroundPoint(vm, size, alignment) {
12827 // Background Position
12831 var caretSize = vm.caretSize;
12832 var caretPadding = vm.caretPadding;
12833 var cornerRadius = vm.cornerRadius;
12834 var xAlign = alignment.xAlign;
12835 var yAlign = alignment.yAlign;
12836 var paddingAndSize = caretSize + caretPadding;
12837 var radiusAndPadding = cornerRadius + caretPadding;
12839 if (xAlign === 'right') {
12841 } else if (xAlign === 'center') {
12842 x -= (size.width / 2);
12845 if (yAlign === 'top') {
12846 y += paddingAndSize;
12847 } else if (yAlign === 'bottom') {
12848 y -= size.height + paddingAndSize;
12850 y -= (size.height / 2);
12853 if (yAlign === 'center') {
12854 if (xAlign === 'left') {
12855 x += paddingAndSize;
12856 } else if (xAlign === 'right') {
12857 x -= paddingAndSize;
12859 } else if (xAlign === 'left') {
12860 x -= radiusAndPadding;
12861 } else if (xAlign === 'right') {
12862 x += radiusAndPadding;
12871 Chart.Tooltip = Element.extend({
12872 initialize: function() {
12873 this._model = getBaseModel(this._options);
12877 // Args are: (tooltipItem, data)
12878 getTitle: function() {
12880 var opts = me._options;
12881 var callbacks = opts.callbacks;
12883 var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
12884 var title = callbacks.title.apply(me, arguments);
12885 var afterTitle = callbacks.afterTitle.apply(me, arguments);
12888 lines = pushOrConcat(lines, beforeTitle);
12889 lines = pushOrConcat(lines, title);
12890 lines = pushOrConcat(lines, afterTitle);
12895 // Args are: (tooltipItem, data)
12896 getBeforeBody: function() {
12897 var lines = this._options.callbacks.beforeBody.apply(this, arguments);
12898 return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : [];
12901 // Args are: (tooltipItem, data)
12902 getBody: function(tooltipItems, data) {
12904 var callbacks = me._options.callbacks;
12905 var bodyItems = [];
12907 helpers.each(tooltipItems, function(tooltipItem) {
12913 pushOrConcat(bodyItem.before, callbacks.beforeLabel.call(me, tooltipItem, data));
12914 pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
12915 pushOrConcat(bodyItem.after, callbacks.afterLabel.call(me, tooltipItem, data));
12917 bodyItems.push(bodyItem);
12923 // Args are: (tooltipItem, data)
12924 getAfterBody: function() {
12925 var lines = this._options.callbacks.afterBody.apply(this, arguments);
12926 return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : [];
12929 // Get the footer and beforeFooter and afterFooter lines
12930 // Args are: (tooltipItem, data)
12931 getFooter: function() {
12933 var callbacks = me._options.callbacks;
12935 var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
12936 var footer = callbacks.footer.apply(me, arguments);
12937 var afterFooter = callbacks.afterFooter.apply(me, arguments);
12940 lines = pushOrConcat(lines, beforeFooter);
12941 lines = pushOrConcat(lines, footer);
12942 lines = pushOrConcat(lines, afterFooter);
12947 update: function(changed) {
12949 var opts = me._options;
12951 // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
12952 // that does _view = _model if ease === 1. This causes the 2nd tooltip update to set properties in both the view and model at the same time
12953 // which breaks any animations.
12954 var existingModel = me._model;
12955 var model = me._model = getBaseModel(opts);
12956 var active = me._active;
12958 var data = me._data;
12960 // In the case where active.length === 0 we need to keep these at existing values for good animations
12962 xAlign: existingModel.xAlign,
12963 yAlign: existingModel.yAlign
12965 var backgroundPoint = {
12966 x: existingModel.x,
12969 var tooltipSize = {
12970 width: existingModel.width,
12971 height: existingModel.height
12973 var tooltipPosition = {
12974 x: existingModel.caretX,
12975 y: existingModel.caretY
12980 if (active.length) {
12983 var labelColors = [];
12984 var labelTextColors = [];
12985 tooltipPosition = Chart.Tooltip.positioners[opts.position](active, me._eventPosition);
12987 var tooltipItems = [];
12988 for (i = 0, len = active.length; i < len; ++i) {
12989 tooltipItems.push(createTooltipItem(active[i]));
12992 // If the user provided a filter function, use it to modify the tooltip items
12994 tooltipItems = tooltipItems.filter(function(a) {
12995 return opts.filter(a, data);
12999 // If the user provided a sorting function, use it to modify the tooltip items
13000 if (opts.itemSort) {
13001 tooltipItems = tooltipItems.sort(function(a, b) {
13002 return opts.itemSort(a, b, data);
13006 // Determine colors for boxes
13007 helpers.each(tooltipItems, function(tooltipItem) {
13008 labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
13009 labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
13013 // Build the Text Lines
13014 model.title = me.getTitle(tooltipItems, data);
13015 model.beforeBody = me.getBeforeBody(tooltipItems, data);
13016 model.body = me.getBody(tooltipItems, data);
13017 model.afterBody = me.getAfterBody(tooltipItems, data);
13018 model.footer = me.getFooter(tooltipItems, data);
13020 // Initial positioning and colors
13021 model.x = Math.round(tooltipPosition.x);
13022 model.y = Math.round(tooltipPosition.y);
13023 model.caretPadding = opts.caretPadding;
13024 model.labelColors = labelColors;
13025 model.labelTextColors = labelTextColors;
13028 model.dataPoints = tooltipItems;
13030 // We need to determine alignment of the tooltip
13031 tooltipSize = getTooltipSize(this, model);
13032 alignment = determineAlignment(this, tooltipSize);
13033 // Final Size and Position
13034 backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment);
13039 model.xAlign = alignment.xAlign;
13040 model.yAlign = alignment.yAlign;
13041 model.x = backgroundPoint.x;
13042 model.y = backgroundPoint.y;
13043 model.width = tooltipSize.width;
13044 model.height = tooltipSize.height;
13046 // Point where the caret on the tooltip points to
13047 model.caretX = tooltipPosition.x;
13048 model.caretY = tooltipPosition.y;
13052 if (changed && opts.custom) {
13053 opts.custom.call(me, model);
13058 drawCaret: function(tooltipPoint, size) {
13059 var ctx = this._chart.ctx;
13060 var vm = this._view;
13061 var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
13063 ctx.lineTo(caretPosition.x1, caretPosition.y1);
13064 ctx.lineTo(caretPosition.x2, caretPosition.y2);
13065 ctx.lineTo(caretPosition.x3, caretPosition.y3);
13067 getCaretPosition: function(tooltipPoint, size, vm) {
13068 var x1, x2, x3, y1, y2, y3;
13069 var caretSize = vm.caretSize;
13070 var cornerRadius = vm.cornerRadius;
13071 var xAlign = vm.xAlign;
13072 var yAlign = vm.yAlign;
13073 var ptX = tooltipPoint.x;
13074 var ptY = tooltipPoint.y;
13075 var width = size.width;
13076 var height = size.height;
13078 if (yAlign === 'center') {
13079 y2 = ptY + (height / 2);
13081 if (xAlign === 'left') {
13083 x2 = x1 - caretSize;
13086 y1 = y2 + caretSize;
13087 y3 = y2 - caretSize;
13090 x2 = x1 + caretSize;
13093 y1 = y2 - caretSize;
13094 y3 = y2 + caretSize;
13097 if (xAlign === 'left') {
13098 x2 = ptX + cornerRadius + (caretSize);
13099 x1 = x2 - caretSize;
13100 x3 = x2 + caretSize;
13101 } else if (xAlign === 'right') {
13102 x2 = ptX + width - cornerRadius - caretSize;
13103 x1 = x2 - caretSize;
13104 x3 = x2 + caretSize;
13106 x2 = ptX + (width / 2);
13107 x1 = x2 - caretSize;
13108 x3 = x2 + caretSize;
13110 if (yAlign === 'top') {
13112 y2 = y1 - caretSize;
13116 y2 = y1 + caretSize;
13118 // invert drawing order
13124 return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
13126 drawTitle: function(pt, vm, ctx, opacity) {
13127 var title = vm.title;
13129 if (title.length) {
13130 ctx.textAlign = vm._titleAlign;
13131 ctx.textBaseline = 'top';
13133 var titleFontSize = vm.titleFontSize;
13134 var titleSpacing = vm.titleSpacing;
13136 ctx.fillStyle = mergeOpacity(vm.titleFontColor, opacity);
13137 ctx.font = helpers.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
13140 for (i = 0, len = title.length; i < len; ++i) {
13141 ctx.fillText(title[i], pt.x, pt.y);
13142 pt.y += titleFontSize + titleSpacing; // Line Height and spacing
13144 if (i + 1 === title.length) {
13145 pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
13150 drawBody: function(pt, vm, ctx, opacity) {
13151 var bodyFontSize = vm.bodyFontSize;
13152 var bodySpacing = vm.bodySpacing;
13153 var body = vm.body;
13155 ctx.textAlign = vm._bodyAlign;
13156 ctx.textBaseline = 'top';
13157 ctx.font = helpers.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
13160 var xLinePadding = 0;
13161 var fillLineOfText = function(line) {
13162 ctx.fillText(line, pt.x + xLinePadding, pt.y);
13163 pt.y += bodyFontSize + bodySpacing;
13166 // Before body lines
13167 helpers.each(vm.beforeBody, fillLineOfText);
13169 var drawColorBoxes = vm.displayColors;
13170 xLinePadding = drawColorBoxes ? (bodyFontSize + 2) : 0;
13172 // Draw body lines now
13173 helpers.each(body, function(bodyItem, i) {
13174 helpers.each(bodyItem.before, fillLineOfText);
13176 helpers.each(bodyItem.lines, function(line) {
13177 // Draw Legend-like boxes if needed
13178 if (drawColorBoxes) {
13179 // Fill a white rect so that colours merge nicely if the opacity is < 1
13180 ctx.fillStyle = mergeOpacity(vm.legendColorBackground, opacity);
13181 ctx.fillRect(pt.x, pt.y, bodyFontSize, bodyFontSize);
13185 ctx.strokeStyle = mergeOpacity(vm.labelColors[i].borderColor, opacity);
13186 ctx.strokeRect(pt.x, pt.y, bodyFontSize, bodyFontSize);
13189 ctx.fillStyle = mergeOpacity(vm.labelColors[i].backgroundColor, opacity);
13190 ctx.fillRect(pt.x + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
13191 var textColor = mergeOpacity(vm.labelTextColors[i], opacity);
13192 ctx.fillStyle = textColor;
13195 fillLineOfText(line);
13198 helpers.each(bodyItem.after, fillLineOfText);
13201 // Reset back to 0 for after body
13204 // After body lines
13205 helpers.each(vm.afterBody, fillLineOfText);
13206 pt.y -= bodySpacing; // Remove last body spacing
13208 drawFooter: function(pt, vm, ctx, opacity) {
13209 var footer = vm.footer;
13211 if (footer.length) {
13212 pt.y += vm.footerMarginTop;
13214 ctx.textAlign = vm._footerAlign;
13215 ctx.textBaseline = 'top';
13217 ctx.fillStyle = mergeOpacity(vm.footerFontColor, opacity);
13218 ctx.font = helpers.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
13220 helpers.each(footer, function(line) {
13221 ctx.fillText(line, pt.x, pt.y);
13222 pt.y += vm.footerFontSize + vm.footerSpacing;
13226 drawBackground: function(pt, vm, ctx, tooltipSize, opacity) {
13227 ctx.fillStyle = mergeOpacity(vm.backgroundColor, opacity);
13228 ctx.strokeStyle = mergeOpacity(vm.borderColor, opacity);
13229 ctx.lineWidth = vm.borderWidth;
13230 var xAlign = vm.xAlign;
13231 var yAlign = vm.yAlign;
13234 var width = tooltipSize.width;
13235 var height = tooltipSize.height;
13236 var radius = vm.cornerRadius;
13239 ctx.moveTo(x + radius, y);
13240 if (yAlign === 'top') {
13241 this.drawCaret(pt, tooltipSize);
13243 ctx.lineTo(x + width - radius, y);
13244 ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
13245 if (yAlign === 'center' && xAlign === 'right') {
13246 this.drawCaret(pt, tooltipSize);
13248 ctx.lineTo(x + width, y + height - radius);
13249 ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
13250 if (yAlign === 'bottom') {
13251 this.drawCaret(pt, tooltipSize);
13253 ctx.lineTo(x + radius, y + height);
13254 ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
13255 if (yAlign === 'center' && xAlign === 'left') {
13256 this.drawCaret(pt, tooltipSize);
13258 ctx.lineTo(x, y + radius);
13259 ctx.quadraticCurveTo(x, y, x + radius, y);
13264 if (vm.borderWidth > 0) {
13269 var ctx = this._chart.ctx;
13270 var vm = this._view;
13272 if (vm.opacity === 0) {
13276 var tooltipSize = {
13285 // IE11/Edge does not like very small opacities, so snap to 0
13286 var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
13288 // Truthy/falsey value for empty tooltip
13289 var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
13291 if (this._options.enabled && hasTooltipContent) {
13293 this.drawBackground(pt, vm, ctx, tooltipSize, opacity);
13295 // Draw Title, Body, and Footer
13296 pt.x += vm.xPadding;
13297 pt.y += vm.yPadding;
13300 this.drawTitle(pt, vm, ctx, opacity);
13303 this.drawBody(pt, vm, ctx, opacity);
13306 this.drawFooter(pt, vm, ctx, opacity);
13313 * @param {IEvent} event - The event to handle
13314 * @returns {Boolean} true if the tooltip changed
13316 handleEvent: function(e) {
13318 var options = me._options;
13319 var changed = false;
13321 me._lastActive = me._lastActive || [];
13323 // Find Active Elements for tooltips
13324 if (e.type === 'mouseout') {
13327 me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
13330 // Remember Last Actives
13331 changed = !helpers.arrayEquals(me._active, me._lastActive);
13333 // If tooltip didn't change, do not handle the target event
13338 me._lastActive = me._active;
13340 if (options.enabled || options.custom) {
13341 me._eventPosition = {
13346 var model = me._model;
13350 // See if our tooltip position changed
13351 changed |= (model.x !== me._model.x) || (model.y !== me._model.y);
13359 * @namespace Chart.Tooltip.positioners
13361 Chart.Tooltip.positioners = {
13363 * Average mode places the tooltip at the average position of the elements shown
13364 * @function Chart.Tooltip.positioners.average
13365 * @param elements {ChartElement[]} the elements being displayed in the tooltip
13366 * @returns {Point} tooltip position
13368 average: function(elements) {
13369 if (!elements.length) {
13378 for (i = 0, len = elements.length; i < len; ++i) {
13379 var el = elements[i];
13380 if (el && el.hasValue()) {
13381 var pos = el.tooltipPosition();
13389 x: Math.round(x / count),
13390 y: Math.round(y / count)
13395 * Gets the tooltip position nearest of the item nearest to the event position
13396 * @function Chart.Tooltip.positioners.nearest
13397 * @param elements {Chart.Element[]} the tooltip elements
13398 * @param eventPosition {Point} the position of the event in canvas coordinates
13399 * @returns {Point} the tooltip position
13401 nearest: function(elements, eventPosition) {
13402 var x = eventPosition.x;
13403 var y = eventPosition.y;
13404 var minDistance = Number.POSITIVE_INFINITY;
13405 var i, len, nearestElement;
13407 for (i = 0, len = elements.length; i < len; ++i) {
13408 var el = elements[i];
13409 if (el && el.hasValue()) {
13410 var center = el.getCenterPoint();
13411 var d = helpers.distanceBetweenPoints(eventPosition, center);
13413 if (d < minDistance) {
13415 nearestElement = el;
13420 if (nearestElement) {
13421 var tp = nearestElement.tooltipPosition();
13434 },{"25":25,"26":26,"45":45}],36:[function(require,module,exports){
13437 var defaults = require(25);
13438 var Element = require(26);
13439 var helpers = require(45);
13441 defaults._set('global', {
13444 backgroundColor: defaults.global.defaultColor,
13445 borderColor: '#fff',
13451 module.exports = Element.extend({
13452 inLabelRange: function(mouseX) {
13453 var vm = this._view;
13456 return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
13461 inRange: function(chartX, chartY) {
13462 var vm = this._view;
13465 var pointRelativePosition = helpers.getAngleFromPoint(vm, {x: chartX, y: chartY});
13466 var angle = pointRelativePosition.angle;
13467 var distance = pointRelativePosition.distance;
13469 // Sanitise angle range
13470 var startAngle = vm.startAngle;
13471 var endAngle = vm.endAngle;
13472 while (endAngle < startAngle) {
13473 endAngle += 2.0 * Math.PI;
13475 while (angle > endAngle) {
13476 angle -= 2.0 * Math.PI;
13478 while (angle < startAngle) {
13479 angle += 2.0 * Math.PI;
13482 // Check if within the range of the open/close angle
13483 var betweenAngles = (angle >= startAngle && angle <= endAngle);
13484 var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
13486 return (betweenAngles && withinRadius);
13491 getCenterPoint: function() {
13492 var vm = this._view;
13493 var halfAngle = (vm.startAngle + vm.endAngle) / 2;
13494 var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
13496 x: vm.x + Math.cos(halfAngle) * halfRadius,
13497 y: vm.y + Math.sin(halfAngle) * halfRadius
13501 getArea: function() {
13502 var vm = this._view;
13503 return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
13506 tooltipPosition: function() {
13507 var vm = this._view;
13508 var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
13509 var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
13512 x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
13513 y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
13518 var ctx = this._chart.ctx;
13519 var vm = this._view;
13520 var sA = vm.startAngle;
13521 var eA = vm.endAngle;
13525 ctx.arc(vm.x, vm.y, vm.outerRadius, sA, eA);
13526 ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
13529 ctx.strokeStyle = vm.borderColor;
13530 ctx.lineWidth = vm.borderWidth;
13532 ctx.fillStyle = vm.backgroundColor;
13535 ctx.lineJoin = 'bevel';
13537 if (vm.borderWidth) {
13543 },{"25":25,"26":26,"45":45}],37:[function(require,module,exports){
13546 var defaults = require(25);
13547 var Element = require(26);
13548 var helpers = require(45);
13550 var globalDefaults = defaults.global;
13552 defaults._set('global', {
13556 backgroundColor: globalDefaults.defaultColor,
13558 borderColor: globalDefaults.defaultColor,
13559 borderCapStyle: 'butt',
13561 borderDashOffset: 0.0,
13562 borderJoinStyle: 'miter',
13563 capBezierPoints: true,
13564 fill: true, // do we fill in the area between the line and its base axis
13569 module.exports = Element.extend({
13573 var ctx = me._chart.ctx;
13574 var spanGaps = vm.spanGaps;
13575 var points = me._children.slice(); // clone array
13576 var globalOptionLineElements = globalDefaults.elements.line;
13577 var lastDrawnIndex = -1;
13578 var index, current, previous, currentVM;
13580 // If we are looping, adding the first point again
13581 if (me._loop && points.length) {
13582 points.push(points[0]);
13587 // Stroke Line Options
13588 ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
13590 // IE 9 and 10 do not support line dash
13591 if (ctx.setLineDash) {
13592 ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
13595 ctx.lineDashOffset = vm.borderDashOffset || globalOptionLineElements.borderDashOffset;
13596 ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
13597 ctx.lineWidth = vm.borderWidth || globalOptionLineElements.borderWidth;
13598 ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
13602 lastDrawnIndex = -1;
13604 for (index = 0; index < points.length; ++index) {
13605 current = points[index];
13606 previous = helpers.previousItem(points, index);
13607 currentVM = current._view;
13609 // First point moves to it's starting position no matter what
13611 if (!currentVM.skip) {
13612 ctx.moveTo(currentVM.x, currentVM.y);
13613 lastDrawnIndex = index;
13616 previous = lastDrawnIndex === -1 ? previous : points[lastDrawnIndex];
13618 if (!currentVM.skip) {
13619 if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
13620 // There was a gap and this is the first point after the gap
13621 ctx.moveTo(currentVM.x, currentVM.y);
13623 // Line to next point
13624 helpers.canvas.lineTo(ctx, previous._view, current._view);
13626 lastDrawnIndex = index;
13636 },{"25":25,"26":26,"45":45}],38:[function(require,module,exports){
13639 var defaults = require(25);
13640 var Element = require(26);
13641 var helpers = require(45);
13643 var defaultColor = defaults.global.defaultColor;
13645 defaults._set('global', {
13649 pointStyle: 'circle',
13650 backgroundColor: defaultColor,
13651 borderColor: defaultColor,
13656 hoverBorderWidth: 1
13661 function xRange(mouseX) {
13662 var vm = this._view;
13663 return vm ? (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hitRadius, 2)) : false;
13666 function yRange(mouseY) {
13667 var vm = this._view;
13668 return vm ? (Math.pow(mouseY - vm.y, 2) < Math.pow(vm.radius + vm.hitRadius, 2)) : false;
13671 module.exports = Element.extend({
13672 inRange: function(mouseX, mouseY) {
13673 var vm = this._view;
13674 return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
13677 inLabelRange: xRange,
13681 getCenterPoint: function() {
13682 var vm = this._view;
13689 getArea: function() {
13690 return Math.PI * Math.pow(this._view.radius, 2);
13693 tooltipPosition: function() {
13694 var vm = this._view;
13698 padding: vm.radius + vm.borderWidth
13702 draw: function(chartArea) {
13703 var vm = this._view;
13704 var model = this._model;
13705 var ctx = this._chart.ctx;
13706 var pointStyle = vm.pointStyle;
13707 var radius = vm.radius;
13710 var color = helpers.color;
13711 var errMargin = 1.01; // 1.01 is margin for Accumulated error. (Especially Edge, IE.)
13718 ctx.strokeStyle = vm.borderColor || defaultColor;
13719 ctx.lineWidth = helpers.valueOrDefault(vm.borderWidth, defaults.global.elements.point.borderWidth);
13720 ctx.fillStyle = vm.backgroundColor || defaultColor;
13722 // Cliping for Points.
13723 // going out from inner charArea?
13724 if ((chartArea !== undefined) && ((model.x < chartArea.left) || (chartArea.right * errMargin < model.x) || (model.y < chartArea.top) || (chartArea.bottom * errMargin < model.y))) {
13726 if (model.x < chartArea.left) {
13727 ratio = (x - model.x) / (chartArea.left - model.x);
13728 } else if (chartArea.right * errMargin < model.x) {
13729 ratio = (model.x - x) / (model.x - chartArea.right);
13730 } else if (model.y < chartArea.top) {
13731 ratio = (y - model.y) / (chartArea.top - model.y);
13732 } else if (chartArea.bottom * errMargin < model.y) {
13733 ratio = (model.y - y) / (model.y - chartArea.bottom);
13735 ratio = Math.round(ratio * 100) / 100;
13736 ctx.strokeStyle = color(ctx.strokeStyle).alpha(ratio).rgbString();
13737 ctx.fillStyle = color(ctx.fillStyle).alpha(ratio).rgbString();
13740 helpers.canvas.drawPoint(ctx, pointStyle, radius, x, y);
13744 },{"25":25,"26":26,"45":45}],39:[function(require,module,exports){
13747 var defaults = require(25);
13748 var Element = require(26);
13750 defaults._set('global', {
13753 backgroundColor: defaults.global.defaultColor,
13754 borderColor: defaults.global.defaultColor,
13755 borderSkipped: 'bottom',
13761 function isVertical(bar) {
13762 return bar._view.width !== undefined;
13766 * Helper function to get the bounds of the bar regardless of the orientation
13767 * @param bar {Chart.Element.Rectangle} the bar
13768 * @return {Bounds} bounds of the bar
13771 function getBarBounds(bar) {
13772 var vm = bar._view;
13773 var x1, x2, y1, y2;
13775 if (isVertical(bar)) {
13777 var halfWidth = vm.width / 2;
13778 x1 = vm.x - halfWidth;
13779 x2 = vm.x + halfWidth;
13780 y1 = Math.min(vm.y, vm.base);
13781 y2 = Math.max(vm.y, vm.base);
13784 var halfHeight = vm.height / 2;
13785 x1 = Math.min(vm.x, vm.base);
13786 x2 = Math.max(vm.x, vm.base);
13787 y1 = vm.y - halfHeight;
13788 y2 = vm.y + halfHeight;
13799 module.exports = Element.extend({
13801 var ctx = this._chart.ctx;
13802 var vm = this._view;
13803 var left, right, top, bottom, signX, signY, borderSkipped;
13804 var borderWidth = vm.borderWidth;
13806 if (!vm.horizontal) {
13808 left = vm.x - vm.width / 2;
13809 right = vm.x + vm.width / 2;
13813 signY = bottom > top ? 1 : -1;
13814 borderSkipped = vm.borderSkipped || 'bottom';
13819 top = vm.y - vm.height / 2;
13820 bottom = vm.y + vm.height / 2;
13821 signX = right > left ? 1 : -1;
13823 borderSkipped = vm.borderSkipped || 'left';
13826 // Canvas doesn't allow us to stroke inside the width so we can
13827 // adjust the sizes to fit if we're setting a stroke on the line
13829 // borderWidth shold be less than bar width and bar height.
13830 var barSize = Math.min(Math.abs(left - right), Math.abs(top - bottom));
13831 borderWidth = borderWidth > barSize ? barSize : borderWidth;
13832 var halfStroke = borderWidth / 2;
13833 // Adjust borderWidth when bar top position is near vm.base(zero).
13834 var borderLeft = left + (borderSkipped !== 'left' ? halfStroke * signX : 0);
13835 var borderRight = right + (borderSkipped !== 'right' ? -halfStroke * signX : 0);
13836 var borderTop = top + (borderSkipped !== 'top' ? halfStroke * signY : 0);
13837 var borderBottom = bottom + (borderSkipped !== 'bottom' ? -halfStroke * signY : 0);
13838 // not become a vertical line?
13839 if (borderLeft !== borderRight) {
13841 bottom = borderBottom;
13843 // not become a horizontal line?
13844 if (borderTop !== borderBottom) {
13846 right = borderRight;
13851 ctx.fillStyle = vm.backgroundColor;
13852 ctx.strokeStyle = vm.borderColor;
13853 ctx.lineWidth = borderWidth;
13855 // Corner points, from bottom-left to bottom-right clockwise
13865 // Find first (starting) corner with fallback to 'bottom'
13866 var borders = ['bottom', 'left', 'top', 'right'];
13867 var startCorner = borders.indexOf(borderSkipped, 0);
13868 if (startCorner === -1) {
13872 function cornerAt(index) {
13873 return corners[(startCorner + index) % 4];
13876 // Draw rectangle from 'startCorner'
13877 var corner = cornerAt(0);
13878 ctx.moveTo(corner[0], corner[1]);
13880 for (var i = 1; i < 4; i++) {
13881 corner = cornerAt(i);
13882 ctx.lineTo(corner[0], corner[1]);
13891 height: function() {
13892 var vm = this._view;
13893 return vm.base - vm.y;
13896 inRange: function(mouseX, mouseY) {
13897 var inRange = false;
13900 var bounds = getBarBounds(this);
13901 inRange = mouseX >= bounds.left && mouseX <= bounds.right && mouseY >= bounds.top && mouseY <= bounds.bottom;
13907 inLabelRange: function(mouseX, mouseY) {
13913 var inRange = false;
13914 var bounds = getBarBounds(me);
13916 if (isVertical(me)) {
13917 inRange = mouseX >= bounds.left && mouseX <= bounds.right;
13919 inRange = mouseY >= bounds.top && mouseY <= bounds.bottom;
13925 inXRange: function(mouseX) {
13926 var bounds = getBarBounds(this);
13927 return mouseX >= bounds.left && mouseX <= bounds.right;
13930 inYRange: function(mouseY) {
13931 var bounds = getBarBounds(this);
13932 return mouseY >= bounds.top && mouseY <= bounds.bottom;
13935 getCenterPoint: function() {
13936 var vm = this._view;
13938 if (isVertical(this)) {
13940 y = (vm.y + vm.base) / 2;
13942 x = (vm.x + vm.base) / 2;
13946 return {x: x, y: y};
13949 getArea: function() {
13950 var vm = this._view;
13951 return vm.width * Math.abs(vm.y - vm.base);
13954 tooltipPosition: function() {
13955 var vm = this._view;
13963 },{"25":25,"26":26}],40:[function(require,module,exports){
13966 module.exports = {};
13967 module.exports.Arc = require(36);
13968 module.exports.Line = require(37);
13969 module.exports.Point = require(38);
13970 module.exports.Rectangle = require(39);
13972 },{"36":36,"37":37,"38":38,"39":39}],41:[function(require,module,exports){
13975 var helpers = require(42);
13978 * @namespace Chart.helpers.canvas
13980 var exports = module.exports = {
13982 * Clears the entire canvas associated to the given `chart`.
13983 * @param {Chart} chart - The chart for which to clear the canvas.
13985 clear: function(chart) {
13986 chart.ctx.clearRect(0, 0, chart.width, chart.height);
13990 * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
13991 * given size (width, height) and the same `radius` for all corners.
13992 * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
13993 * @param {Number} x - The x axis of the coordinate for the rectangle starting point.
13994 * @param {Number} y - The y axis of the coordinate for the rectangle starting point.
13995 * @param {Number} width - The rectangle's width.
13996 * @param {Number} height - The rectangle's height.
13997 * @param {Number} radius - The rounded amount (in pixels) for the four corners.
13998 * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
14000 roundedRect: function(ctx, x, y, width, height, radius) {
14002 var rx = Math.min(radius, width / 2);
14003 var ry = Math.min(radius, height / 2);
14005 ctx.moveTo(x + rx, y);
14006 ctx.lineTo(x + width - rx, y);
14007 ctx.quadraticCurveTo(x + width, y, x + width, y + ry);
14008 ctx.lineTo(x + width, y + height - ry);
14009 ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height);
14010 ctx.lineTo(x + rx, y + height);
14011 ctx.quadraticCurveTo(x, y + height, x, y + height - ry);
14012 ctx.lineTo(x, y + ry);
14013 ctx.quadraticCurveTo(x, y, x + rx, y);
14015 ctx.rect(x, y, width, height);
14019 drawPoint: function(ctx, style, radius, x, y) {
14020 var type, edgeLength, xOffset, yOffset, height, size;
14022 if (typeof style === 'object') {
14023 type = style.toString();
14024 if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
14025 ctx.drawImage(style, x - style.width / 2, y - style.height / 2, style.width, style.height);
14030 if (isNaN(radius) || radius <= 0) {
14035 // Default includes circle
14038 ctx.arc(x, y, radius, 0, Math.PI * 2);
14044 edgeLength = 3 * radius / Math.sqrt(3);
14045 height = edgeLength * Math.sqrt(3) / 2;
14046 ctx.moveTo(x - edgeLength / 2, y + height / 3);
14047 ctx.lineTo(x + edgeLength / 2, y + height / 3);
14048 ctx.lineTo(x, y - 2 * height / 3);
14053 size = 1 / Math.SQRT2 * radius;
14055 ctx.fillRect(x - size, y - size, 2 * size, 2 * size);
14056 ctx.strokeRect(x - size, y - size, 2 * size, 2 * size);
14058 case 'rectRounded':
14059 var offset = radius / Math.SQRT2;
14060 var leftX = x - offset;
14061 var topY = y - offset;
14062 var sideSize = Math.SQRT2 * radius;
14064 this.roundedRect(ctx, leftX, topY, sideSize, sideSize, radius / 2);
14069 size = 1 / Math.SQRT2 * radius;
14071 ctx.moveTo(x - size, y);
14072 ctx.lineTo(x, y + size);
14073 ctx.lineTo(x + size, y);
14074 ctx.lineTo(x, y - size);
14080 ctx.moveTo(x, y + radius);
14081 ctx.lineTo(x, y - radius);
14082 ctx.moveTo(x - radius, y);
14083 ctx.lineTo(x + radius, y);
14088 xOffset = Math.cos(Math.PI / 4) * radius;
14089 yOffset = Math.sin(Math.PI / 4) * radius;
14090 ctx.moveTo(x - xOffset, y - yOffset);
14091 ctx.lineTo(x + xOffset, y + yOffset);
14092 ctx.moveTo(x - xOffset, y + yOffset);
14093 ctx.lineTo(x + xOffset, y - yOffset);
14098 ctx.moveTo(x, y + radius);
14099 ctx.lineTo(x, y - radius);
14100 ctx.moveTo(x - radius, y);
14101 ctx.lineTo(x + radius, y);
14102 xOffset = Math.cos(Math.PI / 4) * radius;
14103 yOffset = Math.sin(Math.PI / 4) * radius;
14104 ctx.moveTo(x - xOffset, y - yOffset);
14105 ctx.lineTo(x + xOffset, y + yOffset);
14106 ctx.moveTo(x - xOffset, y + yOffset);
14107 ctx.lineTo(x + xOffset, y - yOffset);
14112 ctx.moveTo(x - radius, y);
14113 ctx.lineTo(x + radius, y);
14119 ctx.lineTo(x + radius, y);
14127 clipArea: function(ctx, area) {
14130 ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
14134 unclipArea: function(ctx) {
14138 lineTo: function(ctx, previous, target, flip) {
14139 if (target.steppedLine) {
14140 if ((target.steppedLine === 'after' && !flip) || (target.steppedLine !== 'after' && flip)) {
14141 ctx.lineTo(previous.x, target.y);
14143 ctx.lineTo(target.x, previous.y);
14145 ctx.lineTo(target.x, target.y);
14149 if (!target.tension) {
14150 ctx.lineTo(target.x, target.y);
14155 flip ? previous.controlPointPreviousX : previous.controlPointNextX,
14156 flip ? previous.controlPointPreviousY : previous.controlPointNextY,
14157 flip ? target.controlPointNextX : target.controlPointPreviousX,
14158 flip ? target.controlPointNextY : target.controlPointPreviousY,
14167 * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
14168 * @namespace Chart.helpers.clear
14169 * @deprecated since version 2.7.0
14170 * @todo remove at version 3
14173 helpers.clear = exports.clear;
14176 * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
14177 * @namespace Chart.helpers.drawRoundedRectangle
14178 * @deprecated since version 2.7.0
14179 * @todo remove at version 3
14182 helpers.drawRoundedRectangle = function(ctx) {
14184 exports.roundedRect.apply(exports, arguments);
14188 },{"42":42}],42:[function(require,module,exports){
14192 * @namespace Chart.helpers
14196 * An empty function that can be used, for example, for optional callback.
14198 noop: function() {},
14201 * Returns a unique id, sequentially generated from a global variable.
14202 * @returns {Number}
14207 return function() {
14213 * Returns true if `value` is neither null nor undefined, else returns false.
14214 * @param {*} value - The value to test.
14215 * @returns {Boolean}
14218 isNullOrUndef: function(value) {
14219 return value === null || typeof value === 'undefined';
14223 * Returns true if `value` is an array, else returns false.
14224 * @param {*} value - The value to test.
14225 * @returns {Boolean}
14228 isArray: Array.isArray ? Array.isArray : function(value) {
14229 return Object.prototype.toString.call(value) === '[object Array]';
14233 * Returns true if `value` is an object (excluding null), else returns false.
14234 * @param {*} value - The value to test.
14235 * @returns {Boolean}
14238 isObject: function(value) {
14239 return value !== null && Object.prototype.toString.call(value) === '[object Object]';
14243 * Returns `value` if defined, else returns `defaultValue`.
14244 * @param {*} value - The value to return if defined.
14245 * @param {*} defaultValue - The value to return if `value` is undefined.
14248 valueOrDefault: function(value, defaultValue) {
14249 return typeof value === 'undefined' ? defaultValue : value;
14253 * Returns value at the given `index` in array if defined, else returns `defaultValue`.
14254 * @param {Array} value - The array to lookup for value at `index`.
14255 * @param {Number} index - The index in `value` to lookup for value.
14256 * @param {*} defaultValue - The value to return if `value[index]` is undefined.
14259 valueAtIndexOrDefault: function(value, index, defaultValue) {
14260 return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
14264 * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
14265 * value returned by `fn`. If `fn` is not a function, this method returns undefined.
14266 * @param {Function} fn - The function to call.
14267 * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
14268 * @param {Object} [thisArg] - The value of `this` provided for the call to `fn`.
14271 callback: function(fn, args, thisArg) {
14272 if (fn && typeof fn.call === 'function') {
14273 return fn.apply(thisArg, args);
14278 * Note(SB) for performance sake, this method should only be used when loopable type
14279 * is unknown or in none intensive code (not called often and small loopable). Else
14280 * it's preferable to use a regular for() loop and save extra function calls.
14281 * @param {Object|Array} loopable - The object or array to be iterated.
14282 * @param {Function} fn - The function to call for each item.
14283 * @param {Object} [thisArg] - The value of `this` provided for the call to `fn`.
14284 * @param {Boolean} [reverse] - If true, iterates backward on the loopable.
14286 each: function(loopable, fn, thisArg, reverse) {
14288 if (helpers.isArray(loopable)) {
14289 len = loopable.length;
14291 for (i = len - 1; i >= 0; i--) {
14292 fn.call(thisArg, loopable[i], i);
14295 for (i = 0; i < len; i++) {
14296 fn.call(thisArg, loopable[i], i);
14299 } else if (helpers.isObject(loopable)) {
14300 keys = Object.keys(loopable);
14302 for (i = 0; i < len; i++) {
14303 fn.call(thisArg, loopable[keys[i]], keys[i]);
14309 * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
14310 * @see http://stackoverflow.com/a/14853974
14311 * @param {Array} a0 - The array to compare
14312 * @param {Array} a1 - The array to compare
14313 * @returns {Boolean}
14315 arrayEquals: function(a0, a1) {
14316 var i, ilen, v0, v1;
14318 if (!a0 || !a1 || a0.length !== a1.length) {
14322 for (i = 0, ilen = a0.length; i < ilen; ++i) {
14326 if (v0 instanceof Array && v1 instanceof Array) {
14327 if (!helpers.arrayEquals(v0, v1)) {
14330 } else if (v0 !== v1) {
14331 // NOTE: two different object instances will never be equal: {x:20} != {x:20}
14340 * Returns a deep copy of `source` without keeping references on objects and arrays.
14341 * @param {*} source - The value to clone.
14344 clone: function(source) {
14345 if (helpers.isArray(source)) {
14346 return source.map(helpers.clone);
14349 if (helpers.isObject(source)) {
14351 var keys = Object.keys(source);
14352 var klen = keys.length;
14355 for (; k < klen; ++k) {
14356 target[keys[k]] = helpers.clone(source[keys[k]]);
14366 * The default merger when Chart.helpers.merge is called without merger option.
14367 * Note(SB): this method is also used by configMerge and scaleMerge as fallback.
14370 _merger: function(key, target, source, options) {
14371 var tval = target[key];
14372 var sval = source[key];
14374 if (helpers.isObject(tval) && helpers.isObject(sval)) {
14375 helpers.merge(tval, sval, options);
14377 target[key] = helpers.clone(sval);
14382 * Merges source[key] in target[key] only if target[key] is undefined.
14385 _mergerIf: function(key, target, source) {
14386 var tval = target[key];
14387 var sval = source[key];
14389 if (helpers.isObject(tval) && helpers.isObject(sval)) {
14390 helpers.mergeIf(tval, sval);
14391 } else if (!target.hasOwnProperty(key)) {
14392 target[key] = helpers.clone(sval);
14397 * Recursively deep copies `source` properties into `target` with the given `options`.
14398 * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
14399 * @param {Object} target - The target object in which all sources are merged into.
14400 * @param {Object|Array(Object)} source - Object(s) to merge into `target`.
14401 * @param {Object} [options] - Merging options:
14402 * @param {Function} [options.merger] - The merge method (key, target, source, options)
14403 * @returns {Object} The `target` object.
14405 merge: function(target, source, options) {
14406 var sources = helpers.isArray(source) ? source : [source];
14407 var ilen = sources.length;
14408 var merge, i, keys, klen, k;
14410 if (!helpers.isObject(target)) {
14414 options = options || {};
14415 merge = options.merger || helpers._merger;
14417 for (i = 0; i < ilen; ++i) {
14418 source = sources[i];
14419 if (!helpers.isObject(source)) {
14423 keys = Object.keys(source);
14424 for (k = 0, klen = keys.length; k < klen; ++k) {
14425 merge(keys[k], target, source, options);
14433 * Recursively deep copies `source` properties into `target` *only* if not defined in target.
14434 * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
14435 * @param {Object} target - The target object in which all sources are merged into.
14436 * @param {Object|Array(Object)} source - Object(s) to merge into `target`.
14437 * @returns {Object} The `target` object.
14439 mergeIf: function(target, source) {
14440 return helpers.merge(target, source, {merger: helpers._mergerIf});
14444 module.exports = helpers;
14449 * Provided for backward compatibility, use Chart.helpers.callback instead.
14450 * @function Chart.helpers.callCallback
14451 * @deprecated since version 2.6.0
14452 * @todo remove at version 3
14455 helpers.callCallback = helpers.callback;
14458 * Provided for backward compatibility, use Array.prototype.indexOf instead.
14459 * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
14460 * @function Chart.helpers.indexOf
14461 * @deprecated since version 2.7.0
14462 * @todo remove at version 3
14465 helpers.indexOf = function(array, item, fromIndex) {
14466 return Array.prototype.indexOf.call(array, item, fromIndex);
14470 * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
14471 * @function Chart.helpers.getValueOrDefault
14472 * @deprecated since version 2.7.0
14473 * @todo remove at version 3
14476 helpers.getValueOrDefault = helpers.valueOrDefault;
14479 * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
14480 * @function Chart.helpers.getValueAtIndexOrDefault
14481 * @deprecated since version 2.7.0
14482 * @todo remove at version 3
14485 helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
14487 },{}],43:[function(require,module,exports){
14490 var helpers = require(42);
14493 * Easing functions adapted from Robert Penner's easing equations.
14494 * @namespace Chart.helpers.easingEffects
14495 * @see http://www.robertpenner.com/easing/
14498 linear: function(t) {
14502 easeInQuad: function(t) {
14506 easeOutQuad: function(t) {
14507 return -t * (t - 2);
14510 easeInOutQuad: function(t) {
14511 if ((t /= 0.5) < 1) {
14512 return 0.5 * t * t;
14514 return -0.5 * ((--t) * (t - 2) - 1);
14517 easeInCubic: function(t) {
14521 easeOutCubic: function(t) {
14522 return (t = t - 1) * t * t + 1;
14525 easeInOutCubic: function(t) {
14526 if ((t /= 0.5) < 1) {
14527 return 0.5 * t * t * t;
14529 return 0.5 * ((t -= 2) * t * t + 2);
14532 easeInQuart: function(t) {
14533 return t * t * t * t;
14536 easeOutQuart: function(t) {
14537 return -((t = t - 1) * t * t * t - 1);
14540 easeInOutQuart: function(t) {
14541 if ((t /= 0.5) < 1) {
14542 return 0.5 * t * t * t * t;
14544 return -0.5 * ((t -= 2) * t * t * t - 2);
14547 easeInQuint: function(t) {
14548 return t * t * t * t * t;
14551 easeOutQuint: function(t) {
14552 return (t = t - 1) * t * t * t * t + 1;
14555 easeInOutQuint: function(t) {
14556 if ((t /= 0.5) < 1) {
14557 return 0.5 * t * t * t * t * t;
14559 return 0.5 * ((t -= 2) * t * t * t * t + 2);
14562 easeInSine: function(t) {
14563 return -Math.cos(t * (Math.PI / 2)) + 1;
14566 easeOutSine: function(t) {
14567 return Math.sin(t * (Math.PI / 2));
14570 easeInOutSine: function(t) {
14571 return -0.5 * (Math.cos(Math.PI * t) - 1);
14574 easeInExpo: function(t) {
14575 return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
14578 easeOutExpo: function(t) {
14579 return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
14582 easeInOutExpo: function(t) {
14589 if ((t /= 0.5) < 1) {
14590 return 0.5 * Math.pow(2, 10 * (t - 1));
14592 return 0.5 * (-Math.pow(2, -10 * --t) + 2);
14595 easeInCirc: function(t) {
14599 return -(Math.sqrt(1 - t * t) - 1);
14602 easeOutCirc: function(t) {
14603 return Math.sqrt(1 - (t = t - 1) * t);
14606 easeInOutCirc: function(t) {
14607 if ((t /= 0.5) < 1) {
14608 return -0.5 * (Math.sqrt(1 - t * t) - 1);
14610 return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
14613 easeInElastic: function(t) {
14630 s = p / (2 * Math.PI) * Math.asin(1 / a);
14632 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
14635 easeOutElastic: function(t) {
14652 s = p / (2 * Math.PI) * Math.asin(1 / a);
14654 return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
14657 easeInOutElastic: function(t) {
14664 if ((t /= 0.5) === 2) {
14674 s = p / (2 * Math.PI) * Math.asin(1 / a);
14677 return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
14679 return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
14681 easeInBack: function(t) {
14683 return t * t * ((s + 1) * t - s);
14686 easeOutBack: function(t) {
14688 return (t = t - 1) * t * ((s + 1) * t + s) + 1;
14691 easeInOutBack: function(t) {
14693 if ((t /= 0.5) < 1) {
14694 return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
14696 return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
14699 easeInBounce: function(t) {
14700 return 1 - effects.easeOutBounce(1 - t);
14703 easeOutBounce: function(t) {
14704 if (t < (1 / 2.75)) {
14705 return 7.5625 * t * t;
14707 if (t < (2 / 2.75)) {
14708 return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
14710 if (t < (2.5 / 2.75)) {
14711 return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
14713 return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
14716 easeInOutBounce: function(t) {
14718 return effects.easeInBounce(t * 2) * 0.5;
14720 return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
14731 * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
14732 * @function Chart.helpers.easingEffects
14733 * @deprecated since version 2.7.0
14734 * @todo remove at version 3
14737 helpers.easingEffects = effects;
14739 },{"42":42}],44:[function(require,module,exports){
14742 var helpers = require(42);
14745 * @alias Chart.helpers.options
14750 * Converts the given line height `value` in pixels for a specific font `size`.
14751 * @param {Number|String} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
14752 * @param {Number} size - The font size (in pixels) used to resolve relative `value`.
14753 * @returns {Number} The effective line height in pixels (size * 1.2 if value is invalid).
14754 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
14757 toLineHeight: function(value, size) {
14758 var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
14759 if (!matches || matches[1] === 'normal') {
14763 value = +matches[2];
14765 switch (matches[3]) {
14775 return size * value;
14779 * Converts the given value into a padding object with pre-computed width/height.
14780 * @param {Number|Object} value - If a number, set the value to all TRBL component,
14781 * else, if and object, use defined properties and sets undefined ones to 0.
14782 * @returns {Object} The padding values (top, right, bottom, left, width, height)
14785 toPadding: function(value) {
14788 if (helpers.isObject(value)) {
14789 t = +value.top || 0;
14790 r = +value.right || 0;
14791 b = +value.bottom || 0;
14792 l = +value.left || 0;
14794 t = r = b = l = +value || 0;
14808 * Evaluates the given `inputs` sequentially and returns the first defined value.
14809 * @param {Array[]} inputs - An array of values, falling back to the last value.
14810 * @param {Object} [context] - If defined and the current value is a function, the value
14811 * is called with `context` as first argument and the result becomes the new input.
14812 * @param {Number} [index] - If defined and the current value is an array, the value
14813 * at `index` become the new input.
14816 resolve: function(inputs, context, index) {
14817 var i, ilen, value;
14819 for (i = 0, ilen = inputs.length; i < ilen; ++i) {
14821 if (value === undefined) {
14824 if (context !== undefined && typeof value === 'function') {
14825 value = value(context);
14827 if (index !== undefined && helpers.isArray(value)) {
14828 value = value[index];
14830 if (value !== undefined) {
14837 },{"42":42}],45:[function(require,module,exports){
14840 module.exports = require(42);
14841 module.exports.easing = require(43);
14842 module.exports.canvas = require(41);
14843 module.exports.options = require(44);
14845 },{"41":41,"42":42,"43":43,"44":44}],46:[function(require,module,exports){
14847 * Platform fallback implementation (minimal).
14848 * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
14852 acquireContext: function(item) {
14853 if (item && item.canvas) {
14854 // Support for any object associated to a canvas (including a context2d)
14855 item = item.canvas;
14858 return item && item.getContext('2d') || null;
14862 },{}],47:[function(require,module,exports){
14864 * Chart.Platform implementation for targeting a web browser
14869 var helpers = require(45);
14871 var EXPANDO_KEY = '$chartjs';
14872 var CSS_PREFIX = 'chartjs-';
14873 var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
14874 var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
14875 var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
14878 * DOM event types -> Chart.js event types.
14879 * Note: only events with different types are mapped.
14880 * @see https://developer.mozilla.org/en-US/docs/Web/Events
14882 var EVENT_TYPES = {
14883 touchstart: 'mousedown',
14884 touchmove: 'mousemove',
14885 touchend: 'mouseup',
14886 pointerenter: 'mouseenter',
14887 pointerdown: 'mousedown',
14888 pointermove: 'mousemove',
14889 pointerup: 'mouseup',
14890 pointerleave: 'mouseout',
14891 pointerout: 'mouseout'
14895 * The "used" size is the final value of a dimension property after all calculations have
14896 * been performed. This method uses the computed style of `element` but returns undefined
14897 * if the computed style is not expressed in pixels. That can happen in some cases where
14898 * `element` has a size relative to its parent and this last one is not yet displayed,
14899 * for example because of `display: none` on a parent node.
14900 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
14901 * @returns {Number} Size in pixels or undefined if unknown.
14903 function readUsedSize(element, property) {
14904 var value = helpers.getStyle(element, property);
14905 var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
14906 return matches ? Number(matches[1]) : undefined;
14910 * Initializes the canvas style and render size without modifying the canvas display size,
14911 * since responsiveness is handled by the controller.resize() method. The config is used
14912 * to determine the aspect ratio to apply in case no explicit height has been specified.
14914 function initCanvas(canvas, config) {
14915 var style = canvas.style;
14917 // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
14918 // returns null or '' if no explicit value has been set to the canvas attribute.
14919 var renderHeight = canvas.getAttribute('height');
14920 var renderWidth = canvas.getAttribute('width');
14922 // Chart.js modifies some canvas values that we want to restore on destroy
14923 canvas[EXPANDO_KEY] = {
14925 height: renderHeight,
14926 width: renderWidth,
14928 display: style.display,
14929 height: style.height,
14935 // Force canvas to display as block to avoid extra space caused by inline
14936 // elements, which would interfere with the responsive resize process.
14937 // https://github.com/chartjs/Chart.js/issues/2538
14938 style.display = style.display || 'block';
14940 if (renderWidth === null || renderWidth === '') {
14941 var displayWidth = readUsedSize(canvas, 'width');
14942 if (displayWidth !== undefined) {
14943 canvas.width = displayWidth;
14947 if (renderHeight === null || renderHeight === '') {
14948 if (canvas.style.height === '') {
14949 // If no explicit render height and style height, let's apply the aspect ratio,
14950 // which one can be specified by the user but also by charts as default option
14951 // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
14952 canvas.height = canvas.width / (config.options.aspectRatio || 2);
14954 var displayHeight = readUsedSize(canvas, 'height');
14955 if (displayWidth !== undefined) {
14956 canvas.height = displayHeight;
14965 * Detects support for options object argument in addEventListener.
14966 * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
14969 var supportsEventListenerOptions = (function() {
14970 var supports = false;
14972 var options = Object.defineProperty({}, 'passive', {
14977 window.addEventListener('e', null, options);
14979 // continue regardless of error
14984 // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
14985 // https://github.com/chartjs/Chart.js/issues/4287
14986 var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
14988 function addEventListener(node, type, listener) {
14989 node.addEventListener(type, listener, eventListenerOptions);
14992 function removeEventListener(node, type, listener) {
14993 node.removeEventListener(type, listener, eventListenerOptions);
14996 function createEvent(type, chart, x, y, nativeEvent) {
15000 native: nativeEvent || null,
15001 x: x !== undefined ? x : null,
15002 y: y !== undefined ? y : null,
15006 function fromNativeEvent(event, chart) {
15007 var type = EVENT_TYPES[event.type] || event.type;
15008 var pos = helpers.getRelativePosition(event, chart);
15009 return createEvent(type, chart, pos.x, pos.y, event);
15012 function throttled(fn, thisArg) {
15013 var ticking = false;
15016 return function() {
15017 args = Array.prototype.slice.call(arguments);
15018 thisArg = thisArg || this;
15022 helpers.requestAnimFrame.call(window, function() {
15024 fn.apply(thisArg, args);
15030 // Implementation based on https://github.com/marcj/css-element-queries
15031 function createResizer(handler) {
15032 var resizer = document.createElement('div');
15033 var cls = CSS_PREFIX + 'size-monitor';
15034 var maxSize = 1000000;
15036 'position:absolute;' +
15041 'overflow:hidden;' +
15042 'pointer-events:none;' +
15043 'visibility:hidden;' +
15046 resizer.style.cssText = style;
15047 resizer.className = cls;
15048 resizer.innerHTML =
15049 '<div class="' + cls + '-expand" style="' + style + '">' +
15051 'position:absolute;' +
15052 'width:' + maxSize + 'px;' +
15053 'height:' + maxSize + 'px;' +
15058 '<div class="' + cls + '-shrink" style="' + style + '">' +
15060 'position:absolute;' +
15068 var expand = resizer.childNodes[0];
15069 var shrink = resizer.childNodes[1];
15071 resizer._reset = function() {
15072 expand.scrollLeft = maxSize;
15073 expand.scrollTop = maxSize;
15074 shrink.scrollLeft = maxSize;
15075 shrink.scrollTop = maxSize;
15077 var onScroll = function() {
15082 addEventListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
15083 addEventListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
15088 // https://davidwalsh.name/detect-node-insertion
15089 function watchForRender(node, handler) {
15090 var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
15091 var proxy = expando.renderProxy = function(e) {
15092 if (e.animationName === CSS_RENDER_ANIMATION) {
15097 helpers.each(ANIMATION_START_EVENTS, function(type) {
15098 addEventListener(node, type, proxy);
15101 node.classList.add(CSS_RENDER_MONITOR);
15104 function unwatchForRender(node) {
15105 var expando = node[EXPANDO_KEY] || {};
15106 var proxy = expando.renderProxy;
15109 helpers.each(ANIMATION_START_EVENTS, function(type) {
15110 removeEventListener(node, type, proxy);
15113 delete expando.renderProxy;
15116 node.classList.remove(CSS_RENDER_MONITOR);
15119 function addResizeListener(node, listener, chart) {
15120 var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
15122 // Let's keep track of this added resizer and thus avoid DOM query when removing it.
15123 var resizer = expando.resizer = createResizer(throttled(function() {
15124 if (expando.resizer) {
15125 return listener(createEvent('resize', chart));
15129 // The resizer needs to be attached to the node parent, so we first need to be
15130 // sure that `node` is attached to the DOM before injecting the resizer element.
15131 watchForRender(node, function() {
15132 if (expando.resizer) {
15133 var container = node.parentNode;
15134 if (container && container !== resizer.parentNode) {
15135 container.insertBefore(resizer, container.firstChild);
15138 // The container size might have changed, let's reset the resizer state.
15144 function removeResizeListener(node) {
15145 var expando = node[EXPANDO_KEY] || {};
15146 var resizer = expando.resizer;
15148 delete expando.resizer;
15149 unwatchForRender(node);
15151 if (resizer && resizer.parentNode) {
15152 resizer.parentNode.removeChild(resizer);
15156 function injectCSS(platform, css) {
15157 // http://stackoverflow.com/q/3922139
15158 var style = platform._style || document.createElement('style');
15159 if (!platform._style) {
15160 platform._style = style;
15161 css = '/* Chart.js */\n' + css;
15162 style.setAttribute('type', 'text/css');
15163 document.getElementsByTagName('head')[0].appendChild(style);
15166 style.appendChild(document.createTextNode(css));
15171 * This property holds whether this platform is enabled for the current environment.
15172 * Currently used by platform.js to select the proper implementation.
15175 _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
15177 initialize: function() {
15178 var keyframes = 'from{opacity:0.99}to{opacity:1}';
15181 // DOM rendering detection
15182 // https://davidwalsh.name/detect-node-insertion
15183 '@-webkit-keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' +
15184 '@keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' +
15185 '.' + CSS_RENDER_MONITOR + '{' +
15186 '-webkit-animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' +
15187 'animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' +
15192 acquireContext: function(item, config) {
15193 if (typeof item === 'string') {
15194 item = document.getElementById(item);
15195 } else if (item.length) {
15196 // Support for array based queries (such as jQuery)
15200 if (item && item.canvas) {
15201 // Support for any object associated to a canvas (including a context2d)
15202 item = item.canvas;
15205 // To prevent canvas fingerprinting, some add-ons undefine the getContext
15206 // method, for example: https://github.com/kkapsner/CanvasBlocker
15207 // https://github.com/chartjs/Chart.js/issues/2807
15208 var context = item && item.getContext && item.getContext('2d');
15210 // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
15211 // inside an iframe or when running in a protected environment. We could guess the
15212 // types from their toString() value but let's keep things flexible and assume it's
15213 // a sufficient condition if the item has a context2D which has item as `canvas`.
15214 // https://github.com/chartjs/Chart.js/issues/3887
15215 // https://github.com/chartjs/Chart.js/issues/4102
15216 // https://github.com/chartjs/Chart.js/issues/4152
15217 if (context && context.canvas === item) {
15218 initCanvas(item, config);
15225 releaseContext: function(context) {
15226 var canvas = context.canvas;
15227 if (!canvas[EXPANDO_KEY]) {
15231 var initial = canvas[EXPANDO_KEY].initial;
15232 ['height', 'width'].forEach(function(prop) {
15233 var value = initial[prop];
15234 if (helpers.isNullOrUndef(value)) {
15235 canvas.removeAttribute(prop);
15237 canvas.setAttribute(prop, value);
15241 helpers.each(initial.style || {}, function(value, key) {
15242 canvas.style[key] = value;
15245 // The canvas render size might have been changed (and thus the state stack discarded),
15246 // we can't use save() and restore() to restore the initial state. So make sure that at
15247 // least the canvas context is reset to the default state by setting the canvas width.
15248 // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
15249 canvas.width = canvas.width;
15251 delete canvas[EXPANDO_KEY];
15254 addEventListener: function(chart, type, listener) {
15255 var canvas = chart.canvas;
15256 if (type === 'resize') {
15257 // Note: the resize event is not supported on all browsers.
15258 addResizeListener(canvas, listener, chart);
15262 var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
15263 var proxies = expando.proxies || (expando.proxies = {});
15264 var proxy = proxies[chart.id + '_' + type] = function(event) {
15265 listener(fromNativeEvent(event, chart));
15268 addEventListener(canvas, type, proxy);
15271 removeEventListener: function(chart, type, listener) {
15272 var canvas = chart.canvas;
15273 if (type === 'resize') {
15274 // Note: the resize event is not supported on all browsers.
15275 removeResizeListener(canvas, listener);
15279 var expando = listener[EXPANDO_KEY] || {};
15280 var proxies = expando.proxies || {};
15281 var proxy = proxies[chart.id + '_' + type];
15286 removeEventListener(canvas, type, proxy);
15293 * Provided for backward compatibility, use EventTarget.addEventListener instead.
15294 * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
15295 * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
15296 * @function Chart.helpers.addEvent
15297 * @deprecated since version 2.7.0
15298 * @todo remove at version 3
15301 helpers.addEvent = addEventListener;
15304 * Provided for backward compatibility, use EventTarget.removeEventListener instead.
15305 * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
15306 * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
15307 * @function Chart.helpers.removeEvent
15308 * @deprecated since version 2.7.0
15309 * @todo remove at version 3
15312 helpers.removeEvent = removeEventListener;
15314 },{"45":45}],48:[function(require,module,exports){
15317 var helpers = require(45);
15318 var basic = require(46);
15319 var dom = require(47);
15321 // @TODO Make possible to select another platform at build time.
15322 var implementation = dom._enabled ? dom : basic;
15325 * @namespace Chart.platform
15326 * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
15329 module.exports = helpers.extend({
15333 initialize: function() {},
15336 * Called at chart construction time, returns a context2d instance implementing
15337 * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
15338 * @param {*} item - The native item from which to acquire context (platform specific)
15339 * @param {Object} options - The chart options
15340 * @returns {CanvasRenderingContext2D} context2d instance
15342 acquireContext: function() {},
15345 * Called at chart destruction time, releases any resources associated to the context
15346 * previously returned by the acquireContext() method.
15347 * @param {CanvasRenderingContext2D} context - The context2d instance
15348 * @returns {Boolean} true if the method succeeded, else false
15350 releaseContext: function() {},
15353 * Registers the specified listener on the given chart.
15354 * @param {Chart} chart - Chart from which to listen for event
15355 * @param {String} type - The ({@link IEvent}) type to listen for
15356 * @param {Function} listener - Receives a notification (an object that implements
15357 * the {@link IEvent} interface) when an event of the specified type occurs.
15359 addEventListener: function() {},
15362 * Removes the specified listener previously registered with addEventListener.
15363 * @param {Chart} chart -Chart from which to remove the listener
15364 * @param {String} type - The ({@link IEvent}) type to remove
15365 * @param {Function} listener - The listener function to remove from the event target.
15367 removeEventListener: function() {}
15369 }, implementation);
15372 * @interface IPlatform
15373 * Allows abstracting platform dependencies away from the chart
15374 * @borrows Chart.platform.acquireContext as acquireContext
15375 * @borrows Chart.platform.releaseContext as releaseContext
15376 * @borrows Chart.platform.addEventListener as addEventListener
15377 * @borrows Chart.platform.removeEventListener as removeEventListener
15381 * @interface IEvent
15382 * @prop {String} type - The event type name, possible values are:
15383 * 'contextmenu', 'mouseenter', 'mousedown', 'mousemove', 'mouseup', 'mouseout',
15384 * 'click', 'dblclick', 'keydown', 'keypress', 'keyup' and 'resize'
15385 * @prop {*} native - The original native event (null for emulated events, e.g. 'resize')
15386 * @prop {Number} x - The mouse x position, relative to the canvas (null for incompatible events)
15387 * @prop {Number} y - The mouse y position, relative to the canvas (null for incompatible events)
15390 },{"45":45,"46":46,"47":47}],49:[function(require,module,exports){
15392 * Plugin based on discussion from the following Chart.js issues:
15393 * @see https://github.com/chartjs/Chart.js/issues/2380#issuecomment-279961569
15394 * @see https://github.com/chartjs/Chart.js/issues/2440#issuecomment-256461897
15399 var defaults = require(25);
15400 var elements = require(40);
15401 var helpers = require(45);
15403 defaults._set('global', {
15411 module.exports = function() {
15414 dataset: function(source) {
15415 var index = source.fill;
15416 var chart = source.chart;
15417 var meta = chart.getDatasetMeta(index);
15418 var visible = meta && chart.isDatasetVisible(index);
15419 var points = (visible && meta.dataset._children) || [];
15420 var length = points.length || 0;
15422 return !length ? null : function(point, i) {
15423 return (i < length && points[i]._view) || null;
15427 boundary: function(source) {
15428 var boundary = source.boundary;
15429 var x = boundary ? boundary.x : null;
15430 var y = boundary ? boundary.y : null;
15432 return function(point) {
15434 x: x === null ? point.x : x,
15435 y: y === null ? point.y : y,
15441 // @todo if (fill[0] === '#')
15442 function decodeFill(el, index, count) {
15443 var model = el._model || {};
15444 var fill = model.fill;
15447 if (fill === undefined) {
15448 fill = !!model.backgroundColor;
15451 if (fill === false || fill === null) {
15455 if (fill === true) {
15459 target = parseFloat(fill, 10);
15460 if (isFinite(target) && Math.floor(target) === target) {
15461 if (fill[0] === '-' || fill[0] === '+') {
15462 target = index + target;
15465 if (target === index || target < 0 || target >= count) {
15480 // supported boundaries
15485 // invalid fill values
15491 function computeBoundary(source) {
15492 var model = source.el._model || {};
15493 var scale = source.el._scale || {};
15494 var fill = source.fill;
15498 if (isFinite(fill)) {
15502 // Backward compatibility: until v3, we still need to support boundary values set on
15503 // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
15504 // controllers might still use it (e.g. the Smith chart).
15506 if (fill === 'start') {
15507 target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
15508 } else if (fill === 'end') {
15509 target = model.scaleTop === undefined ? scale.top : model.scaleTop;
15510 } else if (model.scaleZero !== undefined) {
15511 target = model.scaleZero;
15512 } else if (scale.getBasePosition) {
15513 target = scale.getBasePosition();
15514 } else if (scale.getBasePixel) {
15515 target = scale.getBasePixel();
15518 if (target !== undefined && target !== null) {
15519 if (target.x !== undefined && target.y !== undefined) {
15523 if (typeof target === 'number' && isFinite(target)) {
15524 horizontal = scale.isHorizontal();
15526 x: horizontal ? target : null,
15527 y: horizontal ? null : target
15535 function resolveTarget(sources, index, propagate) {
15536 var source = sources[index];
15537 var fill = source.fill;
15538 var visited = [index];
15545 while (fill !== false && visited.indexOf(fill) === -1) {
15546 if (!isFinite(fill)) {
15550 target = sources[fill];
15555 if (target.visible) {
15559 visited.push(fill);
15560 fill = target.fill;
15566 function createMapper(source) {
15567 var fill = source.fill;
15568 var type = 'dataset';
15570 if (fill === false) {
15574 if (!isFinite(fill)) {
15578 return mappers[type](source);
15581 function isDrawable(point) {
15582 return point && !point.skip;
15585 function drawArea(ctx, curve0, curve1, len0, len1) {
15588 if (!len0 || !len1) {
15592 // building first area curve (normal)
15593 ctx.moveTo(curve0[0].x, curve0[0].y);
15594 for (i = 1; i < len0; ++i) {
15595 helpers.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
15598 // joining the two area curves
15599 ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
15601 // building opposite area curve (reverse)
15602 for (i = len1 - 1; i > 0; --i) {
15603 helpers.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
15607 function doFill(ctx, points, mapper, view, color, loop) {
15608 var count = points.length;
15609 var span = view.spanGaps;
15614 var i, ilen, index, p0, p1, d0, d1;
15618 for (i = 0, ilen = (count + !!loop); i < ilen; ++i) {
15620 p0 = points[index]._view;
15621 p1 = mapper(p0, index, view);
15622 d0 = isDrawable(p0);
15623 d1 = isDrawable(p1);
15626 len0 = curve0.push(p0);
15627 len1 = curve1.push(p1);
15628 } else if (len0 && len1) {
15630 drawArea(ctx, curve0, curve1, len0, len1);
15645 drawArea(ctx, curve0, curve1, len0, len1);
15648 ctx.fillStyle = color;
15655 afterDatasetsUpdate: function(chart, options) {
15656 var count = (chart.data.datasets || []).length;
15657 var propagate = options.propagate;
15659 var meta, i, el, source;
15661 for (i = 0; i < count; ++i) {
15662 meta = chart.getDatasetMeta(i);
15666 if (el && el._model && el instanceof elements.Line) {
15668 visible: chart.isDatasetVisible(i),
15669 fill: decodeFill(el, i, count),
15675 meta.$filler = source;
15676 sources.push(source);
15679 for (i = 0; i < count; ++i) {
15680 source = sources[i];
15685 source.fill = resolveTarget(sources, i, propagate);
15686 source.boundary = computeBoundary(source);
15687 source.mapper = createMapper(source);
15691 beforeDatasetDraw: function(chart, args) {
15692 var meta = args.meta.$filler;
15697 var ctx = chart.ctx;
15699 var view = el._view;
15700 var points = el._children || [];
15701 var mapper = meta.mapper;
15702 var color = view.backgroundColor || defaults.global.defaultColor;
15704 if (mapper && color && points.length) {
15705 helpers.canvas.clipArea(ctx, chart.chartArea);
15706 doFill(ctx, points, mapper, view, color, el._loop);
15707 helpers.canvas.unclipArea(ctx);
15713 },{"25":25,"40":40,"45":45}],50:[function(require,module,exports){
15716 var defaults = require(25);
15717 var Element = require(26);
15718 var helpers = require(45);
15720 defaults._set('global', {
15728 // a callback that will handle
15729 onClick: function(e, legendItem) {
15730 var index = legendItem.datasetIndex;
15731 var ci = this.chart;
15732 var meta = ci.getDatasetMeta(index);
15734 // See controller.isDatasetVisible comment
15735 meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
15737 // We hid a dataset ... rerender the chart
15746 // Generates labels shown in the legend
15747 // Valid properties to return:
15748 // text : text to display
15749 // fillStyle : fill of coloured box
15750 // strokeStyle: stroke of coloured box
15751 // hidden : if this legend item refers to a hidden item
15752 // lineCap : cap style for line
15754 // lineDashOffset :
15757 generateLabels: function(chart) {
15758 var data = chart.data;
15759 return helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {
15761 text: dataset.label,
15762 fillStyle: (!helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
15763 hidden: !chart.isDatasetVisible(i),
15764 lineCap: dataset.borderCapStyle,
15765 lineDash: dataset.borderDash,
15766 lineDashOffset: dataset.borderDashOffset,
15767 lineJoin: dataset.borderJoinStyle,
15768 lineWidth: dataset.borderWidth,
15769 strokeStyle: dataset.borderColor,
15770 pointStyle: dataset.pointStyle,
15772 // Below is extra data used for toggling the datasets
15780 legendCallback: function(chart) {
15782 text.push('<ul class="' + chart.id + '-legend">');
15783 for (var i = 0; i < chart.data.datasets.length; i++) {
15784 text.push('<li><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"></span>');
15785 if (chart.data.datasets[i].label) {
15786 text.push(chart.data.datasets[i].label);
15788 text.push('</li>');
15790 text.push('</ul>');
15791 return text.join('');
15795 module.exports = function(Chart) {
15797 var layout = Chart.layoutService;
15798 var noop = helpers.noop;
15801 * Helper function to get the box width based on the usePointStyle option
15802 * @param labelopts {Object} the label options on the legend
15803 * @param fontSize {Number} the label font size
15804 * @return {Number} width of the color box area
15806 function getBoxWidth(labelOpts, fontSize) {
15807 return labelOpts.usePointStyle ?
15808 fontSize * Math.SQRT2 :
15809 labelOpts.boxWidth;
15812 Chart.Legend = Element.extend({
15814 initialize: function(config) {
15815 helpers.extend(this, config);
15817 // Contains hit boxes for each dataset (in dataset order)
15818 this.legendHitBoxes = [];
15820 // Are we in doughnut mode which has a different data type
15821 this.doughnutMode = false;
15824 // These methods are ordered by lifecycle. Utilities then follow.
15825 // Any function defined here is inherited by all legend types.
15826 // Any function can be extended by the legend type
15828 beforeUpdate: noop,
15829 update: function(maxWidth, maxHeight, margins) {
15832 // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
15835 // Absorb the master measurements
15836 me.maxWidth = maxWidth;
15837 me.maxHeight = maxHeight;
15838 me.margins = margins;
15841 me.beforeSetDimensions();
15842 me.setDimensions();
15843 me.afterSetDimensions();
15845 me.beforeBuildLabels();
15847 me.afterBuildLabels();
15862 beforeSetDimensions: noop,
15863 setDimensions: function() {
15865 // Set the unconstrained dimension before label rotation
15866 if (me.isHorizontal()) {
15867 // Reset position before calculating rotation
15868 me.width = me.maxWidth;
15870 me.right = me.width;
15872 me.height = me.maxHeight;
15874 // Reset position before calculating rotation
15876 me.bottom = me.height;
15880 me.paddingLeft = 0;
15882 me.paddingRight = 0;
15883 me.paddingBottom = 0;
15891 afterSetDimensions: noop,
15895 beforeBuildLabels: noop,
15896 buildLabels: function() {
15898 var labelOpts = me.options.labels || {};
15899 var legendItems = helpers.callback(labelOpts.generateLabels, [me.chart], me) || [];
15901 if (labelOpts.filter) {
15902 legendItems = legendItems.filter(function(item) {
15903 return labelOpts.filter(item, me.chart.data);
15907 if (me.options.reverse) {
15908 legendItems.reverse();
15911 me.legendItems = legendItems;
15913 afterBuildLabels: noop,
15920 var opts = me.options;
15921 var labelOpts = opts.labels;
15922 var display = opts.display;
15926 var globalDefault = defaults.global;
15927 var valueOrDefault = helpers.valueOrDefault;
15928 var fontSize = valueOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize);
15929 var fontStyle = valueOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle);
15930 var fontFamily = valueOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily);
15931 var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily);
15934 var hitboxes = me.legendHitBoxes = [];
15936 var minSize = me.minSize;
15937 var isHorizontal = me.isHorizontal();
15939 if (isHorizontal) {
15940 minSize.width = me.maxWidth; // fill all the width
15941 minSize.height = display ? 10 : 0;
15943 minSize.width = display ? 10 : 0;
15944 minSize.height = me.maxHeight; // fill all the height
15947 // Increase sizes here
15949 ctx.font = labelFont;
15951 if (isHorizontal) {
15954 // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
15955 var lineWidths = me.lineWidths = [0];
15956 var totalHeight = me.legendItems.length ? fontSize + (labelOpts.padding) : 0;
15958 ctx.textAlign = 'left';
15959 ctx.textBaseline = 'top';
15961 helpers.each(me.legendItems, function(legendItem, i) {
15962 var boxWidth = getBoxWidth(labelOpts, fontSize);
15963 var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
15965 if (lineWidths[lineWidths.length - 1] + width + labelOpts.padding >= me.width) {
15966 totalHeight += fontSize + (labelOpts.padding);
15967 lineWidths[lineWidths.length] = me.left;
15970 // Store the hitbox width and height here. Final position will be updated in `draw`
15978 lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
15981 minSize.height += totalHeight;
15984 var vPadding = labelOpts.padding;
15985 var columnWidths = me.columnWidths = [];
15986 var totalWidth = labelOpts.padding;
15987 var currentColWidth = 0;
15988 var currentColHeight = 0;
15989 var itemHeight = fontSize + vPadding;
15991 helpers.each(me.legendItems, function(legendItem, i) {
15992 var boxWidth = getBoxWidth(labelOpts, fontSize);
15993 var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
15995 // If too tall, go to new column
15996 if (currentColHeight + itemHeight > minSize.height) {
15997 totalWidth += currentColWidth + labelOpts.padding;
15998 columnWidths.push(currentColWidth); // previous column width
16000 currentColWidth = 0;
16001 currentColHeight = 0;
16005 currentColWidth = Math.max(currentColWidth, itemWidth);
16006 currentColHeight += itemHeight;
16008 // Store the hitbox width and height here. Final position will be updated in `draw`
16017 totalWidth += currentColWidth;
16018 columnWidths.push(currentColWidth);
16019 minSize.width += totalWidth;
16023 me.width = minSize.width;
16024 me.height = minSize.height;
16029 isHorizontal: function() {
16030 return this.options.position === 'top' || this.options.position === 'bottom';
16033 // Actually draw the legend on the canvas
16036 var opts = me.options;
16037 var labelOpts = opts.labels;
16038 var globalDefault = defaults.global;
16039 var lineDefault = globalDefault.elements.line;
16040 var legendWidth = me.width;
16041 var lineWidths = me.lineWidths;
16043 if (opts.display) {
16045 var valueOrDefault = helpers.valueOrDefault;
16046 var fontColor = valueOrDefault(labelOpts.fontColor, globalDefault.defaultFontColor);
16047 var fontSize = valueOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize);
16048 var fontStyle = valueOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle);
16049 var fontFamily = valueOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily);
16050 var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily);
16054 ctx.textAlign = 'left';
16055 ctx.textBaseline = 'middle';
16056 ctx.lineWidth = 0.5;
16057 ctx.strokeStyle = fontColor; // for strikethrough effect
16058 ctx.fillStyle = fontColor; // render in correct colour
16059 ctx.font = labelFont;
16061 var boxWidth = getBoxWidth(labelOpts, fontSize);
16062 var hitboxes = me.legendHitBoxes;
16064 // current position
16065 var drawLegendBox = function(x, y, legendItem) {
16066 if (isNaN(boxWidth) || boxWidth <= 0) {
16070 // Set the ctx for the box
16073 ctx.fillStyle = valueOrDefault(legendItem.fillStyle, globalDefault.defaultColor);
16074 ctx.lineCap = valueOrDefault(legendItem.lineCap, lineDefault.borderCapStyle);
16075 ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, lineDefault.borderDashOffset);
16076 ctx.lineJoin = valueOrDefault(legendItem.lineJoin, lineDefault.borderJoinStyle);
16077 ctx.lineWidth = valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth);
16078 ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, globalDefault.defaultColor);
16079 var isLineWidthZero = (valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth) === 0);
16081 if (ctx.setLineDash) {
16082 // IE 9 and 10 do not support line dash
16083 ctx.setLineDash(valueOrDefault(legendItem.lineDash, lineDefault.borderDash));
16086 if (opts.labels && opts.labels.usePointStyle) {
16087 // Recalculate x and y for drawPoint() because its expecting
16088 // x and y to be center of figure (instead of top left)
16089 var radius = fontSize * Math.SQRT2 / 2;
16090 var offSet = radius / Math.SQRT2;
16091 var centerX = x + offSet;
16092 var centerY = y + offSet;
16094 // Draw pointStyle as legend symbol
16095 helpers.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY);
16097 // Draw box as legend symbol
16098 if (!isLineWidthZero) {
16099 ctx.strokeRect(x, y, boxWidth, fontSize);
16101 ctx.fillRect(x, y, boxWidth, fontSize);
16106 var fillText = function(x, y, legendItem, textWidth) {
16107 var halfFontSize = fontSize / 2;
16108 var xLeft = boxWidth + halfFontSize + x;
16109 var yMiddle = y + halfFontSize;
16111 ctx.fillText(legendItem.text, xLeft, yMiddle);
16113 if (legendItem.hidden) {
16114 // Strikethrough the text if hidden
16117 ctx.moveTo(xLeft, yMiddle);
16118 ctx.lineTo(xLeft + textWidth, yMiddle);
16124 var isHorizontal = me.isHorizontal();
16125 if (isHorizontal) {
16127 x: me.left + ((legendWidth - lineWidths[0]) / 2),
16128 y: me.top + labelOpts.padding,
16133 x: me.left + labelOpts.padding,
16134 y: me.top + labelOpts.padding,
16139 var itemHeight = fontSize + labelOpts.padding;
16140 helpers.each(me.legendItems, function(legendItem, i) {
16141 var textWidth = ctx.measureText(legendItem.text).width;
16142 var width = boxWidth + (fontSize / 2) + textWidth;
16146 if (isHorizontal) {
16147 if (x + width >= legendWidth) {
16148 y = cursor.y += itemHeight;
16150 x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2);
16152 } else if (y + itemHeight > me.bottom) {
16153 x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
16154 y = cursor.y = me.top + labelOpts.padding;
16158 drawLegendBox(x, y, legendItem);
16160 hitboxes[i].left = x;
16161 hitboxes[i].top = y;
16163 // Fill the actual label
16164 fillText(x, y, legendItem, textWidth);
16166 if (isHorizontal) {
16167 cursor.x += width + (labelOpts.padding);
16169 cursor.y += itemHeight;
16179 * @param {IEvent} event - The event to handle
16180 * @return {Boolean} true if a change occured
16182 handleEvent: function(e) {
16184 var opts = me.options;
16185 var type = e.type === 'mouseup' ? 'click' : e.type;
16186 var changed = false;
16188 if (type === 'mousemove') {
16189 if (!opts.onHover) {
16192 } else if (type === 'click') {
16193 if (!opts.onClick) {
16200 // Chart event already has relative position in it
16204 if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
16205 // See if we are touching one of the dataset boxes
16206 var lh = me.legendHitBoxes;
16207 for (var i = 0; i < lh.length; ++i) {
16208 var hitBox = lh[i];
16210 if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
16211 // Touching an element
16212 if (type === 'click') {
16213 // use e.native for backwards compatibility
16214 opts.onClick.call(me, e.native, me.legendItems[i]);
16217 } else if (type === 'mousemove') {
16218 // use e.native for backwards compatibility
16219 opts.onHover.call(me, e.native, me.legendItems[i]);
16231 function createNewLegendAndAttach(chart, legendOpts) {
16232 var legend = new Chart.Legend({
16234 options: legendOpts,
16238 layout.configure(chart, legend, legendOpts);
16239 layout.addBox(chart, legend);
16240 chart.legend = legend;
16246 beforeInit: function(chart) {
16247 var legendOpts = chart.options.legend;
16250 createNewLegendAndAttach(chart, legendOpts);
16254 beforeUpdate: function(chart) {
16255 var legendOpts = chart.options.legend;
16256 var legend = chart.legend;
16259 helpers.mergeIf(legendOpts, defaults.global.legend);
16262 layout.configure(chart, legend, legendOpts);
16263 legend.options = legendOpts;
16265 createNewLegendAndAttach(chart, legendOpts);
16267 } else if (legend) {
16268 layout.removeBox(chart, legend);
16269 delete chart.legend;
16273 afterEvent: function(chart, e) {
16274 var legend = chart.legend;
16276 legend.handleEvent(e);
16282 },{"25":25,"26":26,"45":45}],51:[function(require,module,exports){
16285 var defaults = require(25);
16286 var Element = require(26);
16287 var helpers = require(45);
16289 defaults._set('global', {
16298 weight: 2000 // by default greater than legend (1000) to be above
16302 module.exports = function(Chart) {
16304 var layout = Chart.layoutService;
16305 var noop = helpers.noop;
16307 Chart.Title = Element.extend({
16308 initialize: function(config) {
16310 helpers.extend(me, config);
16312 // Contains hit boxes for each dataset (in dataset order)
16313 me.legendHitBoxes = [];
16316 // These methods are ordered by lifecycle. Utilities then follow.
16318 beforeUpdate: noop,
16319 update: function(maxWidth, maxHeight, margins) {
16322 // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
16325 // Absorb the master measurements
16326 me.maxWidth = maxWidth;
16327 me.maxHeight = maxHeight;
16328 me.margins = margins;
16331 me.beforeSetDimensions();
16332 me.setDimensions();
16333 me.afterSetDimensions();
16335 me.beforeBuildLabels();
16337 me.afterBuildLabels();
16353 beforeSetDimensions: noop,
16354 setDimensions: function() {
16356 // Set the unconstrained dimension before label rotation
16357 if (me.isHorizontal()) {
16358 // Reset position before calculating rotation
16359 me.width = me.maxWidth;
16361 me.right = me.width;
16363 me.height = me.maxHeight;
16365 // Reset position before calculating rotation
16367 me.bottom = me.height;
16371 me.paddingLeft = 0;
16373 me.paddingRight = 0;
16374 me.paddingBottom = 0;
16382 afterSetDimensions: noop,
16386 beforeBuildLabels: noop,
16388 afterBuildLabels: noop,
16395 var valueOrDefault = helpers.valueOrDefault;
16396 var opts = me.options;
16397 var display = opts.display;
16398 var fontSize = valueOrDefault(opts.fontSize, defaults.global.defaultFontSize);
16399 var minSize = me.minSize;
16400 var lineCount = helpers.isArray(opts.text) ? opts.text.length : 1;
16401 var lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize);
16402 var textSize = display ? (lineCount * lineHeight) + (opts.padding * 2) : 0;
16404 if (me.isHorizontal()) {
16405 minSize.width = me.maxWidth; // fill all the width
16406 minSize.height = textSize;
16408 minSize.width = textSize;
16409 minSize.height = me.maxHeight; // fill all the height
16412 me.width = minSize.width;
16413 me.height = minSize.height;
16419 isHorizontal: function() {
16420 var pos = this.options.position;
16421 return pos === 'top' || pos === 'bottom';
16424 // Actually draw the title block on the canvas
16428 var valueOrDefault = helpers.valueOrDefault;
16429 var opts = me.options;
16430 var globalDefaults = defaults.global;
16432 if (opts.display) {
16433 var fontSize = valueOrDefault(opts.fontSize, globalDefaults.defaultFontSize);
16434 var fontStyle = valueOrDefault(opts.fontStyle, globalDefaults.defaultFontStyle);
16435 var fontFamily = valueOrDefault(opts.fontFamily, globalDefaults.defaultFontFamily);
16436 var titleFont = helpers.fontString(fontSize, fontStyle, fontFamily);
16437 var lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize);
16438 var offset = lineHeight / 2 + opts.padding;
16441 var left = me.left;
16442 var bottom = me.bottom;
16443 var right = me.right;
16444 var maxWidth, titleX, titleY;
16446 ctx.fillStyle = valueOrDefault(opts.fontColor, globalDefaults.defaultFontColor); // render in correct colour
16447 ctx.font = titleFont;
16450 if (me.isHorizontal()) {
16451 titleX = left + ((right - left) / 2); // midpoint of the width
16452 titleY = top + offset;
16453 maxWidth = right - left;
16455 titleX = opts.position === 'left' ? left + offset : right - offset;
16456 titleY = top + ((bottom - top) / 2);
16457 maxWidth = bottom - top;
16458 rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
16462 ctx.translate(titleX, titleY);
16463 ctx.rotate(rotation);
16464 ctx.textAlign = 'center';
16465 ctx.textBaseline = 'middle';
16467 var text = opts.text;
16468 if (helpers.isArray(text)) {
16470 for (var i = 0; i < text.length; ++i) {
16471 ctx.fillText(text[i], 0, y, maxWidth);
16475 ctx.fillText(text, 0, 0, maxWidth);
16483 function createNewTitleBlockAndAttach(chart, titleOpts) {
16484 var title = new Chart.Title({
16486 options: titleOpts,
16490 layout.configure(chart, title, titleOpts);
16491 layout.addBox(chart, title);
16492 chart.titleBlock = title;
16498 beforeInit: function(chart) {
16499 var titleOpts = chart.options.title;
16502 createNewTitleBlockAndAttach(chart, titleOpts);
16506 beforeUpdate: function(chart) {
16507 var titleOpts = chart.options.title;
16508 var titleBlock = chart.titleBlock;
16511 helpers.mergeIf(titleOpts, defaults.global.title);
16514 layout.configure(chart, titleBlock, titleOpts);
16515 titleBlock.options = titleOpts;
16517 createNewTitleBlockAndAttach(chart, titleOpts);
16519 } else if (titleBlock) {
16520 Chart.layoutService.removeBox(chart, titleBlock);
16521 delete chart.titleBlock;
16527 },{"25":25,"26":26,"45":45}],52:[function(require,module,exports){
16530 module.exports = function(Chart) {
16532 // Default config for a category scale
16533 var defaultConfig = {
16537 var DatasetScale = Chart.Scale.extend({
16539 * Internal function to get the correct labels. If data.xLabels or data.yLabels are defined, use those
16540 * else fall back to data.labels
16543 getLabels: function() {
16544 var data = this.chart.data;
16545 return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels;
16548 determineDataLimits: function() {
16550 var labels = me.getLabels();
16552 me.maxIndex = labels.length - 1;
16555 if (me.options.ticks.min !== undefined) {
16556 // user specified min value
16557 findIndex = labels.indexOf(me.options.ticks.min);
16558 me.minIndex = findIndex !== -1 ? findIndex : me.minIndex;
16561 if (me.options.ticks.max !== undefined) {
16562 // user specified max value
16563 findIndex = labels.indexOf(me.options.ticks.max);
16564 me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex;
16567 me.min = labels[me.minIndex];
16568 me.max = labels[me.maxIndex];
16571 buildTicks: function() {
16573 var labels = me.getLabels();
16574 // If we are viewing some subset of labels, slice the original array
16575 me.ticks = (me.minIndex === 0 && me.maxIndex === labels.length - 1) ? labels : labels.slice(me.minIndex, me.maxIndex + 1);
16578 getLabelForIndex: function(index, datasetIndex) {
16580 var data = me.chart.data;
16581 var isHorizontal = me.isHorizontal();
16583 if (data.yLabels && !isHorizontal) {
16584 return me.getRightValue(data.datasets[datasetIndex].data[index]);
16586 return me.ticks[index - me.minIndex];
16589 // Used to get data value locations. Value can either be an index or a numerical value
16590 getPixelForValue: function(value, index) {
16592 var offset = me.options.offset;
16593 // 1 is added because we need the length but we have the indexes
16594 var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - (offset ? 0 : 1)), 1);
16596 // If value is a data object, then index is the index in the data array,
16597 // not the index of the scale. We need to change that.
16599 if (value !== undefined && value !== null) {
16600 valueCategory = me.isHorizontal() ? value.x : value.y;
16602 if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
16603 var labels = me.getLabels();
16604 value = valueCategory || value;
16605 var idx = labels.indexOf(value);
16606 index = idx !== -1 ? idx : index;
16609 if (me.isHorizontal()) {
16610 var valueWidth = me.width / offsetAmt;
16611 var widthOffset = (valueWidth * (index - me.minIndex));
16614 widthOffset += (valueWidth / 2);
16617 return me.left + Math.round(widthOffset);
16619 var valueHeight = me.height / offsetAmt;
16620 var heightOffset = (valueHeight * (index - me.minIndex));
16623 heightOffset += (valueHeight / 2);
16626 return me.top + Math.round(heightOffset);
16628 getPixelForTick: function(index) {
16629 return this.getPixelForValue(this.ticks[index], index + this.minIndex, null);
16631 getValueForPixel: function(pixel) {
16633 var offset = me.options.offset;
16635 var offsetAmt = Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
16636 var horz = me.isHorizontal();
16637 var valueDimension = (horz ? me.width : me.height) / offsetAmt;
16639 pixel -= horz ? me.left : me.top;
16642 pixel -= (valueDimension / 2);
16648 value = Math.round(pixel / valueDimension);
16651 return value + me.minIndex;
16653 getBasePixel: function() {
16654 return this.bottom;
16658 Chart.scaleService.registerScaleType('category', DatasetScale, defaultConfig);
16662 },{}],53:[function(require,module,exports){
16665 var defaults = require(25);
16666 var helpers = require(45);
16667 var Ticks = require(34);
16669 module.exports = function(Chart) {
16671 var defaultConfig = {
16674 callback: Ticks.formatters.linear
16678 var LinearScale = Chart.LinearScaleBase.extend({
16680 determineDataLimits: function() {
16682 var opts = me.options;
16683 var chart = me.chart;
16684 var data = chart.data;
16685 var datasets = data.datasets;
16686 var isHorizontal = me.isHorizontal();
16687 var DEFAULT_MIN = 0;
16688 var DEFAULT_MAX = 1;
16690 function IDMatches(meta) {
16691 return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
16694 // First Calculate the range
16698 var hasStacks = opts.stacked;
16699 if (hasStacks === undefined) {
16700 helpers.each(datasets, function(dataset, datasetIndex) {
16705 var meta = chart.getDatasetMeta(datasetIndex);
16706 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
16707 meta.stack !== undefined) {
16713 if (opts.stacked || hasStacks) {
16714 var valuesPerStack = {};
16716 helpers.each(datasets, function(dataset, datasetIndex) {
16717 var meta = chart.getDatasetMeta(datasetIndex);
16720 // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
16721 ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
16725 if (valuesPerStack[key] === undefined) {
16726 valuesPerStack[key] = {
16727 positiveValues: [],
16732 // Store these per type
16733 var positiveValues = valuesPerStack[key].positiveValues;
16734 var negativeValues = valuesPerStack[key].negativeValues;
16736 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
16737 helpers.each(dataset.data, function(rawValue, index) {
16738 var value = +me.getRightValue(rawValue);
16739 if (isNaN(value) || meta.data[index].hidden) {
16743 positiveValues[index] = positiveValues[index] || 0;
16744 negativeValues[index] = negativeValues[index] || 0;
16746 if (opts.relativePoints) {
16747 positiveValues[index] = 100;
16748 } else if (value < 0) {
16749 negativeValues[index] += value;
16751 positiveValues[index] += value;
16757 helpers.each(valuesPerStack, function(valuesForType) {
16758 var values = valuesForType.positiveValues.concat(valuesForType.negativeValues);
16759 var minVal = helpers.min(values);
16760 var maxVal = helpers.max(values);
16761 me.min = me.min === null ? minVal : Math.min(me.min, minVal);
16762 me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
16766 helpers.each(datasets, function(dataset, datasetIndex) {
16767 var meta = chart.getDatasetMeta(datasetIndex);
16768 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
16769 helpers.each(dataset.data, function(rawValue, index) {
16770 var value = +me.getRightValue(rawValue);
16771 if (isNaN(value) || meta.data[index].hidden) {
16775 if (me.min === null) {
16777 } else if (value < me.min) {
16781 if (me.max === null) {
16783 } else if (value > me.max) {
16791 me.min = isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
16792 me.max = isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
16794 // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
16795 this.handleTickRangeOptions();
16797 getTickLimit: function() {
16800 var tickOpts = me.options.ticks;
16802 if (me.isHorizontal()) {
16803 maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.width / 50));
16805 // The factor of 2 used to scale the font size has been experimentally determined.
16806 var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, defaults.global.defaultFontSize);
16807 maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.height / (2 * tickFontSize)));
16812 // Called after the ticks are built. We need
16813 handleDirectionalChanges: function() {
16814 if (!this.isHorizontal()) {
16815 // We are in a vertical orientation. The top value is the highest. So reverse the array
16816 this.ticks.reverse();
16819 getLabelForIndex: function(index, datasetIndex) {
16820 return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
16823 getPixelForValue: function(value) {
16824 // This must be called after fit has been run so that
16825 // this.left, this.top, this.right, and this.bottom have been defined
16827 var start = me.start;
16829 var rightValue = +me.getRightValue(value);
16831 var range = me.end - start;
16833 if (me.isHorizontal()) {
16834 pixel = me.left + (me.width / range * (rightValue - start));
16835 return Math.round(pixel);
16838 pixel = me.bottom - (me.height / range * (rightValue - start));
16839 return Math.round(pixel);
16841 getValueForPixel: function(pixel) {
16843 var isHorizontal = me.isHorizontal();
16844 var innerDimension = isHorizontal ? me.width : me.height;
16845 var offset = (isHorizontal ? pixel - me.left : me.bottom - pixel) / innerDimension;
16846 return me.start + ((me.end - me.start) * offset);
16848 getPixelForTick: function(index) {
16849 return this.getPixelForValue(this.ticksAsNumbers[index]);
16852 Chart.scaleService.registerScaleType('linear', LinearScale, defaultConfig);
16856 },{"25":25,"34":34,"45":45}],54:[function(require,module,exports){
16859 var helpers = require(45);
16860 var Ticks = require(34);
16862 module.exports = function(Chart) {
16864 var noop = helpers.noop;
16866 Chart.LinearScaleBase = Chart.Scale.extend({
16867 getRightValue: function(value) {
16868 if (typeof value === 'string') {
16871 return Chart.Scale.prototype.getRightValue.call(this, value);
16874 handleTickRangeOptions: function() {
16876 var opts = me.options;
16877 var tickOpts = opts.ticks;
16879 // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
16880 // do nothing since that would make the chart weird. If the user really wants a weird chart
16881 // axis, they can manually override it
16882 if (tickOpts.beginAtZero) {
16883 var minSign = helpers.sign(me.min);
16884 var maxSign = helpers.sign(me.max);
16886 if (minSign < 0 && maxSign < 0) {
16887 // move the top up to 0
16889 } else if (minSign > 0 && maxSign > 0) {
16890 // move the bottom down to 0
16895 var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
16896 var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
16898 if (tickOpts.min !== undefined) {
16899 me.min = tickOpts.min;
16900 } else if (tickOpts.suggestedMin !== undefined) {
16901 if (me.min === null) {
16902 me.min = tickOpts.suggestedMin;
16904 me.min = Math.min(me.min, tickOpts.suggestedMin);
16908 if (tickOpts.max !== undefined) {
16909 me.max = tickOpts.max;
16910 } else if (tickOpts.suggestedMax !== undefined) {
16911 if (me.max === null) {
16912 me.max = tickOpts.suggestedMax;
16914 me.max = Math.max(me.max, tickOpts.suggestedMax);
16918 if (setMin !== setMax) {
16919 // We set the min or the max but not both.
16920 // So ensure that our range is good
16921 // Inverted or 0 length range can happen when
16922 // ticks.min is set, and no datasets are visible
16923 if (me.min >= me.max) {
16925 me.max = me.min + 1;
16927 me.min = me.max - 1;
16932 if (me.min === me.max) {
16935 if (!tickOpts.beginAtZero) {
16940 getTickLimit: noop,
16941 handleDirectionalChanges: noop,
16943 buildTicks: function() {
16945 var opts = me.options;
16946 var tickOpts = opts.ticks;
16948 // Figure out what the max number of ticks we can support it is based on the size of
16949 // the axis area. For now, we say that the minimum tick spacing in pixels must be 50
16950 // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
16951 // the graph. Make sure we always have at least 2 ticks
16952 var maxTicks = me.getTickLimit();
16953 maxTicks = Math.max(2, maxTicks);
16955 var numericGeneratorOptions = {
16956 maxTicks: maxTicks,
16959 stepSize: helpers.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
16961 var ticks = me.ticks = Ticks.generators.linear(numericGeneratorOptions, me);
16963 me.handleDirectionalChanges();
16965 // At this point, we need to update our max and min given the tick values since we have expanded the
16966 // range of the scale
16967 me.max = helpers.max(ticks);
16968 me.min = helpers.min(ticks);
16970 if (tickOpts.reverse) {
16980 convertTicksToLabels: function() {
16982 me.ticksAsNumbers = me.ticks.slice();
16983 me.zeroLineIndex = me.ticks.indexOf(0);
16985 Chart.Scale.prototype.convertTicksToLabels.call(me);
16990 },{"34":34,"45":45}],55:[function(require,module,exports){
16993 var helpers = require(45);
16994 var Ticks = require(34);
16996 module.exports = function(Chart) {
16998 var defaultConfig = {
17003 callback: Ticks.formatters.logarithmic
17007 var LogarithmicScale = Chart.Scale.extend({
17008 determineDataLimits: function() {
17010 var opts = me.options;
17011 var tickOpts = opts.ticks;
17012 var chart = me.chart;
17013 var data = chart.data;
17014 var datasets = data.datasets;
17015 var valueOrDefault = helpers.valueOrDefault;
17016 var isHorizontal = me.isHorizontal();
17017 function IDMatches(meta) {
17018 return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
17024 me.minNotZero = null;
17026 var hasStacks = opts.stacked;
17027 if (hasStacks === undefined) {
17028 helpers.each(datasets, function(dataset, datasetIndex) {
17033 var meta = chart.getDatasetMeta(datasetIndex);
17034 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
17035 meta.stack !== undefined) {
17041 if (opts.stacked || hasStacks) {
17042 var valuesPerStack = {};
17044 helpers.each(datasets, function(dataset, datasetIndex) {
17045 var meta = chart.getDatasetMeta(datasetIndex);
17048 // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
17049 ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
17053 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
17054 if (valuesPerStack[key] === undefined) {
17055 valuesPerStack[key] = [];
17058 helpers.each(dataset.data, function(rawValue, index) {
17059 var values = valuesPerStack[key];
17060 var value = +me.getRightValue(rawValue);
17061 if (isNaN(value) || meta.data[index].hidden) {
17065 values[index] = values[index] || 0;
17067 if (opts.relativePoints) {
17068 values[index] = 100;
17070 // Don't need to split positive and negative since the log scale can't handle a 0 crossing
17071 values[index] += value;
17077 helpers.each(valuesPerStack, function(valuesForType) {
17078 var minVal = helpers.min(valuesForType);
17079 var maxVal = helpers.max(valuesForType);
17080 me.min = me.min === null ? minVal : Math.min(me.min, minVal);
17081 me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
17085 helpers.each(datasets, function(dataset, datasetIndex) {
17086 var meta = chart.getDatasetMeta(datasetIndex);
17087 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
17088 helpers.each(dataset.data, function(rawValue, index) {
17089 var value = +me.getRightValue(rawValue);
17090 if (isNaN(value) || meta.data[index].hidden) {
17094 if (me.min === null) {
17096 } else if (value < me.min) {
17100 if (me.max === null) {
17102 } else if (value > me.max) {
17106 if (value !== 0 && (me.minNotZero === null || value < me.minNotZero)) {
17107 me.minNotZero = value;
17114 me.min = valueOrDefault(tickOpts.min, me.min);
17115 me.max = valueOrDefault(tickOpts.max, me.max);
17117 if (me.min === me.max) {
17118 if (me.min !== 0 && me.min !== null) {
17119 me.min = Math.pow(10, Math.floor(helpers.log10(me.min)) - 1);
17120 me.max = Math.pow(10, Math.floor(helpers.log10(me.max)) + 1);
17127 buildTicks: function() {
17129 var opts = me.options;
17130 var tickOpts = opts.ticks;
17132 var generationOptions = {
17136 var ticks = me.ticks = Ticks.generators.logarithmic(generationOptions, me);
17138 if (!me.isHorizontal()) {
17139 // We are in a vertical orientation. The top value is the highest. So reverse the array
17143 // At this point, we need to update our max and min given the tick values since we have expanded the
17144 // range of the scale
17145 me.max = helpers.max(ticks);
17146 me.min = helpers.min(ticks);
17148 if (tickOpts.reverse) {
17158 convertTicksToLabels: function() {
17159 this.tickValues = this.ticks.slice();
17161 Chart.Scale.prototype.convertTicksToLabels.call(this);
17163 // Get the correct tooltip label
17164 getLabelForIndex: function(index, datasetIndex) {
17165 return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
17167 getPixelForTick: function(index) {
17168 return this.getPixelForValue(this.tickValues[index]);
17170 getPixelForValue: function(value) {
17172 var start = me.start;
17173 var newVal = +me.getRightValue(value);
17174 var opts = me.options;
17175 var tickOpts = opts.ticks;
17176 var innerDimension, pixel, range;
17178 if (me.isHorizontal()) {
17179 range = helpers.log10(me.end) - helpers.log10(start); // todo: if start === 0
17180 if (newVal === 0) {
17183 innerDimension = me.width;
17184 pixel = me.left + (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start)));
17187 // Bottom - top since pixels increase downward on a screen
17188 innerDimension = me.height;
17189 if (start === 0 && !tickOpts.reverse) {
17190 range = helpers.log10(me.end) - helpers.log10(me.minNotZero);
17191 if (newVal === start) {
17193 } else if (newVal === me.minNotZero) {
17194 pixel = me.bottom - innerDimension * 0.02;
17196 pixel = me.bottom - innerDimension * 0.02 - (innerDimension * 0.98 / range * (helpers.log10(newVal) - helpers.log10(me.minNotZero)));
17198 } else if (me.end === 0 && tickOpts.reverse) {
17199 range = helpers.log10(me.start) - helpers.log10(me.minNotZero);
17200 if (newVal === me.end) {
17202 } else if (newVal === me.minNotZero) {
17203 pixel = me.top + innerDimension * 0.02;
17205 pixel = me.top + innerDimension * 0.02 + (innerDimension * 0.98 / range * (helpers.log10(newVal) - helpers.log10(me.minNotZero)));
17207 } else if (newVal === 0) {
17208 pixel = tickOpts.reverse ? me.top : me.bottom;
17210 range = helpers.log10(me.end) - helpers.log10(start);
17211 innerDimension = me.height;
17212 pixel = me.bottom - (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start)));
17217 getValueForPixel: function(pixel) {
17219 var range = helpers.log10(me.end) - helpers.log10(me.start);
17220 var value, innerDimension;
17222 if (me.isHorizontal()) {
17223 innerDimension = me.width;
17224 value = me.start * Math.pow(10, (pixel - me.left) * range / innerDimension);
17225 } else { // todo: if start === 0
17226 innerDimension = me.height;
17227 value = Math.pow(10, (me.bottom - pixel) * range / innerDimension) / me.start;
17232 Chart.scaleService.registerScaleType('logarithmic', LogarithmicScale, defaultConfig);
17236 },{"34":34,"45":45}],56:[function(require,module,exports){
17239 var defaults = require(25);
17240 var helpers = require(45);
17241 var Ticks = require(34);
17243 module.exports = function(Chart) {
17245 var globalDefaults = defaults.global;
17247 var defaultConfig = {
17250 // Boolean - Whether to animate scaling the chart from the centre
17252 position: 'chartArea',
17256 color: 'rgba(0, 0, 0, 0.1)',
17266 // Boolean - Show a backdrop to the scale label
17267 showLabelBackdrop: true,
17269 // String - The colour of the label backdrop
17270 backdropColor: 'rgba(255,255,255,0.75)',
17272 // Number - The backdrop padding above & below the label in pixels
17273 backdropPaddingY: 2,
17275 // Number - The backdrop padding to the side of the label in pixels
17276 backdropPaddingX: 2,
17278 callback: Ticks.formatters.linear
17282 // Boolean - if true, show point labels
17285 // Number - Point label font size in pixels
17288 // Function - Used to convert point labels
17289 callback: function(label) {
17295 function getValueCount(scale) {
17296 var opts = scale.options;
17297 return opts.angleLines.display || opts.pointLabels.display ? scale.chart.data.labels.length : 0;
17300 function getPointLabelFontOptions(scale) {
17301 var pointLabelOptions = scale.options.pointLabels;
17302 var fontSize = helpers.valueOrDefault(pointLabelOptions.fontSize, globalDefaults.defaultFontSize);
17303 var fontStyle = helpers.valueOrDefault(pointLabelOptions.fontStyle, globalDefaults.defaultFontStyle);
17304 var fontFamily = helpers.valueOrDefault(pointLabelOptions.fontFamily, globalDefaults.defaultFontFamily);
17305 var font = helpers.fontString(fontSize, fontStyle, fontFamily);
17310 family: fontFamily,
17315 function measureLabelSize(ctx, fontSize, label) {
17316 if (helpers.isArray(label)) {
17318 w: helpers.longestText(ctx, ctx.font, label),
17319 h: (label.length * fontSize) + ((label.length - 1) * 1.5 * fontSize)
17324 w: ctx.measureText(label).width,
17329 function determineLimits(angle, pos, size, min, max) {
17330 if (angle === min || angle === max) {
17332 start: pos - (size / 2),
17333 end: pos + (size / 2)
17335 } else if (angle < min || angle > max) {
17337 start: pos - size - 5,
17344 end: pos + size + 5
17349 * Helper function to fit a radial linear scale with point labels
17351 function fitWithPointLabels(scale) {
17353 * Right, this is really confusing and there is a lot of maths going on here
17354 * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
17356 * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
17360 * We assume the radius of the polygon is half the size of the canvas at first
17361 * at each index we check if the text overlaps.
17363 * Where it does, we store that angle and that index.
17365 * After finding the largest index and angle we calculate how much we need to remove
17366 * from the shape radius to move the point inwards by that x.
17368 * We average the left and right distances to get the maximum shape radius that can fit in the box
17369 * along with labels.
17371 * Once we have that, we can find the centre point for the chart, by taking the x text protrusion
17372 * on each side, removing that from the size, halving it and adding the left x protrusion width.
17374 * This will mean we have a shape fitted to the canvas, as large as it can be with the labels
17375 * and position it in the most space efficient manner
17377 * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
17380 var plFont = getPointLabelFontOptions(scale);
17382 // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
17383 // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
17384 var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2);
17385 var furthestLimits = {
17391 var furthestAngles = {};
17392 var i, textSize, pointPosition;
17394 scale.ctx.font = plFont.font;
17395 scale._pointLabelSizes = [];
17397 var valueCount = getValueCount(scale);
17398 for (i = 0; i < valueCount; i++) {
17399 pointPosition = scale.getPointPosition(i, largestPossibleRadius);
17400 textSize = measureLabelSize(scale.ctx, plFont.size, scale.pointLabels[i] || '');
17401 scale._pointLabelSizes[i] = textSize;
17403 // Add quarter circle to make degree 0 mean top of circle
17404 var angleRadians = scale.getIndexAngle(i);
17405 var angle = helpers.toDegrees(angleRadians) % 360;
17406 var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
17407 var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
17409 if (hLimits.start < furthestLimits.l) {
17410 furthestLimits.l = hLimits.start;
17411 furthestAngles.l = angleRadians;
17414 if (hLimits.end > furthestLimits.r) {
17415 furthestLimits.r = hLimits.end;
17416 furthestAngles.r = angleRadians;
17419 if (vLimits.start < furthestLimits.t) {
17420 furthestLimits.t = vLimits.start;
17421 furthestAngles.t = angleRadians;
17424 if (vLimits.end > furthestLimits.b) {
17425 furthestLimits.b = vLimits.end;
17426 furthestAngles.b = angleRadians;
17430 scale.setReductions(largestPossibleRadius, furthestLimits, furthestAngles);
17434 * Helper function to fit a radial linear scale with no point labels
17436 function fit(scale) {
17437 var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2);
17438 scale.drawingArea = Math.round(largestPossibleRadius);
17439 scale.setCenterPoint(0, 0, 0, 0);
17442 function getTextAlignForAngle(angle) {
17443 if (angle === 0 || angle === 180) {
17445 } else if (angle < 180) {
17452 function fillText(ctx, text, position, fontSize) {
17453 if (helpers.isArray(text)) {
17454 var y = position.y;
17455 var spacing = 1.5 * fontSize;
17457 for (var i = 0; i < text.length; ++i) {
17458 ctx.fillText(text[i], position.x, y);
17462 ctx.fillText(text, position.x, position.y);
17466 function adjustPointPositionForLabelHeight(angle, textSize, position) {
17467 if (angle === 90 || angle === 270) {
17468 position.y -= (textSize.h / 2);
17469 } else if (angle > 270 || angle < 90) {
17470 position.y -= textSize.h;
17474 function drawPointLabels(scale) {
17475 var ctx = scale.ctx;
17476 var valueOrDefault = helpers.valueOrDefault;
17477 var opts = scale.options;
17478 var angleLineOpts = opts.angleLines;
17479 var pointLabelOpts = opts.pointLabels;
17481 ctx.lineWidth = angleLineOpts.lineWidth;
17482 ctx.strokeStyle = angleLineOpts.color;
17484 var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
17486 // Point Label Font
17487 var plFont = getPointLabelFontOptions(scale);
17489 ctx.textBaseline = 'top';
17491 for (var i = getValueCount(scale) - 1; i >= 0; i--) {
17492 if (angleLineOpts.display) {
17493 var outerPosition = scale.getPointPosition(i, outerDistance);
17495 ctx.moveTo(scale.xCenter, scale.yCenter);
17496 ctx.lineTo(outerPosition.x, outerPosition.y);
17501 if (pointLabelOpts.display) {
17502 // Extra 3px out for some label spacing
17503 var pointLabelPosition = scale.getPointPosition(i, outerDistance + 5);
17505 // Keep this in loop since we may support array properties here
17506 var pointLabelFontColor = valueOrDefault(pointLabelOpts.fontColor, globalDefaults.defaultFontColor);
17507 ctx.font = plFont.font;
17508 ctx.fillStyle = pointLabelFontColor;
17510 var angleRadians = scale.getIndexAngle(i);
17511 var angle = helpers.toDegrees(angleRadians);
17512 ctx.textAlign = getTextAlignForAngle(angle);
17513 adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
17514 fillText(ctx, scale.pointLabels[i] || '', pointLabelPosition, plFont.size);
17519 function drawRadiusLine(scale, gridLineOpts, radius, index) {
17520 var ctx = scale.ctx;
17521 ctx.strokeStyle = helpers.valueAtIndexOrDefault(gridLineOpts.color, index - 1);
17522 ctx.lineWidth = helpers.valueAtIndexOrDefault(gridLineOpts.lineWidth, index - 1);
17524 if (scale.options.gridLines.circular) {
17525 // Draw circular arcs between the points
17527 ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
17531 // Draw straight lines connecting each index
17532 var valueCount = getValueCount(scale);
17534 if (valueCount === 0) {
17539 var pointPosition = scale.getPointPosition(0, radius);
17540 ctx.moveTo(pointPosition.x, pointPosition.y);
17542 for (var i = 1; i < valueCount; i++) {
17543 pointPosition = scale.getPointPosition(i, radius);
17544 ctx.lineTo(pointPosition.x, pointPosition.y);
17552 function numberOrZero(param) {
17553 return helpers.isNumber(param) ? param : 0;
17556 var LinearRadialScale = Chart.LinearScaleBase.extend({
17557 setDimensions: function() {
17559 var opts = me.options;
17560 var tickOpts = opts.ticks;
17561 // Set the unconstrained dimension before label rotation
17562 me.width = me.maxWidth;
17563 me.height = me.maxHeight;
17564 me.xCenter = Math.round(me.width / 2);
17565 me.yCenter = Math.round(me.height / 2);
17567 var minSize = helpers.min([me.height, me.width]);
17568 var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
17569 me.drawingArea = opts.display ? (minSize / 2) - (tickFontSize / 2 + tickOpts.backdropPaddingY) : (minSize / 2);
17571 determineDataLimits: function() {
17573 var chart = me.chart;
17574 var min = Number.POSITIVE_INFINITY;
17575 var max = Number.NEGATIVE_INFINITY;
17577 helpers.each(chart.data.datasets, function(dataset, datasetIndex) {
17578 if (chart.isDatasetVisible(datasetIndex)) {
17579 var meta = chart.getDatasetMeta(datasetIndex);
17581 helpers.each(dataset.data, function(rawValue, index) {
17582 var value = +me.getRightValue(rawValue);
17583 if (isNaN(value) || meta.data[index].hidden) {
17587 min = Math.min(value, min);
17588 max = Math.max(value, max);
17593 me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
17594 me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
17596 // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
17597 me.handleTickRangeOptions();
17599 getTickLimit: function() {
17600 var tickOpts = this.options.ticks;
17601 var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
17602 return Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(this.drawingArea / (1.5 * tickFontSize)));
17604 convertTicksToLabels: function() {
17607 Chart.LinearScaleBase.prototype.convertTicksToLabels.call(me);
17610 me.pointLabels = me.chart.data.labels.map(me.options.pointLabels.callback, me);
17612 getLabelForIndex: function(index, datasetIndex) {
17613 return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
17616 if (this.options.pointLabels.display) {
17617 fitWithPointLabels(this);
17623 * Set radius reductions and determine new radius and center point
17626 setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
17628 var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
17629 var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
17630 var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
17631 var radiusReductionBottom = -Math.max(furthestLimits.b - me.height, 0) / Math.cos(furthestAngles.b);
17633 radiusReductionLeft = numberOrZero(radiusReductionLeft);
17634 radiusReductionRight = numberOrZero(radiusReductionRight);
17635 radiusReductionTop = numberOrZero(radiusReductionTop);
17636 radiusReductionBottom = numberOrZero(radiusReductionBottom);
17638 me.drawingArea = Math.min(
17639 Math.round(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
17640 Math.round(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
17641 me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
17643 setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
17645 var maxRight = me.width - rightMovement - me.drawingArea;
17646 var maxLeft = leftMovement + me.drawingArea;
17647 var maxTop = topMovement + me.drawingArea;
17648 var maxBottom = me.height - bottomMovement - me.drawingArea;
17650 me.xCenter = Math.round(((maxLeft + maxRight) / 2) + me.left);
17651 me.yCenter = Math.round(((maxTop + maxBottom) / 2) + me.top);
17654 getIndexAngle: function(index) {
17655 var angleMultiplier = (Math.PI * 2) / getValueCount(this);
17656 var startAngle = this.chart.options && this.chart.options.startAngle ?
17657 this.chart.options.startAngle :
17660 var startAngleRadians = startAngle * Math.PI * 2 / 360;
17662 // Start from the top instead of right, so remove a quarter of the circle
17663 return index * angleMultiplier + startAngleRadians;
17665 getDistanceFromCenterForValue: function(value) {
17668 if (value === null) {
17669 return 0; // null always in center
17672 // Take into account half font size + the yPadding of the top value
17673 var scalingFactor = me.drawingArea / (me.max - me.min);
17674 if (me.options.ticks.reverse) {
17675 return (me.max - value) * scalingFactor;
17677 return (value - me.min) * scalingFactor;
17679 getPointPosition: function(index, distanceFromCenter) {
17681 var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
17683 x: Math.round(Math.cos(thisAngle) * distanceFromCenter) + me.xCenter,
17684 y: Math.round(Math.sin(thisAngle) * distanceFromCenter) + me.yCenter
17687 getPointPositionForValue: function(index, value) {
17688 return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
17691 getBasePosition: function() {
17696 return me.getPointPositionForValue(0,
17697 me.beginAtZero ? 0 :
17698 min < 0 && max < 0 ? max :
17699 min > 0 && max > 0 ? min :
17705 var opts = me.options;
17706 var gridLineOpts = opts.gridLines;
17707 var tickOpts = opts.ticks;
17708 var valueOrDefault = helpers.valueOrDefault;
17710 if (opts.display) {
17712 var startAngle = this.getIndexAngle(0);
17715 var tickFontSize = valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
17716 var tickFontStyle = valueOrDefault(tickOpts.fontStyle, globalDefaults.defaultFontStyle);
17717 var tickFontFamily = valueOrDefault(tickOpts.fontFamily, globalDefaults.defaultFontFamily);
17718 var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
17720 helpers.each(me.ticks, function(label, index) {
17721 // Don't draw a centre value (if it is minimum)
17722 if (index > 0 || tickOpts.reverse) {
17723 var yCenterOffset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
17725 // Draw circular lines around the scale
17726 if (gridLineOpts.display && index !== 0) {
17727 drawRadiusLine(me, gridLineOpts, yCenterOffset, index);
17730 if (tickOpts.display) {
17731 var tickFontColor = valueOrDefault(tickOpts.fontColor, globalDefaults.defaultFontColor);
17732 ctx.font = tickLabelFont;
17735 ctx.translate(me.xCenter, me.yCenter);
17736 ctx.rotate(startAngle);
17738 if (tickOpts.showLabelBackdrop) {
17739 var labelWidth = ctx.measureText(label).width;
17740 ctx.fillStyle = tickOpts.backdropColor;
17742 -labelWidth / 2 - tickOpts.backdropPaddingX,
17743 -yCenterOffset - tickFontSize / 2 - tickOpts.backdropPaddingY,
17744 labelWidth + tickOpts.backdropPaddingX * 2,
17745 tickFontSize + tickOpts.backdropPaddingY * 2
17749 ctx.textAlign = 'center';
17750 ctx.textBaseline = 'middle';
17751 ctx.fillStyle = tickFontColor;
17752 ctx.fillText(label, 0, -yCenterOffset);
17758 if (opts.angleLines.display || opts.pointLabels.display) {
17759 drawPointLabels(me);
17764 Chart.scaleService.registerScaleType('radialLinear', LinearRadialScale, defaultConfig);
17768 },{"25":25,"34":34,"45":45}],57:[function(require,module,exports){
17769 /* global window: false */
17772 var moment = require(6);
17773 moment = typeof moment === 'function' ? moment : window.moment;
17775 var defaults = require(25);
17776 var helpers = require(45);
17778 // Integer constants are from the ES6 spec.
17779 var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
17780 var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
17786 steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]
17791 steps: [1, 2, 5, 10, 30]
17796 steps: [1, 2, 5, 10, 30]
17801 steps: [1, 2, 3, 6, 12]
17811 steps: [1, 2, 3, 4]
17821 steps: [1, 2, 3, 4]
17829 var UNITS = Object.keys(INTERVALS);
17831 function sorter(a, b) {
17835 function arrayUnique(items) {
17840 for (i = 0, ilen = items.length; i < ilen; ++i) {
17852 * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
17853 * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
17854 * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
17855 * extremity (left + width or top + height). Note that it would be more optimized to directly
17856 * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
17857 * to create the lookup table. The table ALWAYS contains at least two items: min and max.
17859 * @param {Number[]} timestamps - timestamps sorted from lowest to highest.
17860 * @param {String} distribution - If 'linear', timestamps will be spread linearly along the min
17861 * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
17862 * If 'series', timestamps will be positioned at the same distance from each other. In this
17863 * case, only timestamps that break the time linearity are registered, meaning that in the
17864 * best case, all timestamps are linear, the table contains only min and max.
17866 function buildLookupTable(timestamps, min, max, distribution) {
17867 if (distribution === 'linear' || !timestamps.length) {
17869 {time: min, pos: 0},
17870 {time: max, pos: 1}
17876 var i, ilen, prev, curr, next;
17878 for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
17879 curr = timestamps[i];
17880 if (curr > min && curr < max) {
17887 for (i = 0, ilen = items.length; i < ilen; ++i) {
17888 next = items[i + 1];
17889 prev = items[i - 1];
17892 // only add points that breaks the scale linearity
17893 if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
17894 table.push({time: curr, pos: i / (ilen - 1)});
17901 // @see adapted from http://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
17902 function lookup(table, key, value) {
17904 var hi = table.length - 1;
17907 while (lo >= 0 && lo <= hi) {
17908 mid = (lo + hi) >> 1;
17909 i0 = table[mid - 1] || null;
17913 // given value is outside table (before first item)
17914 return {lo: null, hi: i1};
17915 } else if (i1[key] < value) {
17917 } else if (i0[key] > value) {
17920 return {lo: i0, hi: i1};
17924 // given value is outside table (after last item)
17925 return {lo: i1, hi: null};
17929 * Linearly interpolates the given source `value` using the table items `skey` values and
17930 * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
17931 * returns the position for a timestamp equal to 42. If value is out of bounds, values at
17932 * index [0, 1] or [n - 1, n] are used for the interpolation.
17934 function interpolate(table, skey, sval, tkey) {
17935 var range = lookup(table, skey, sval);
17937 // Note: the lookup table ALWAYS contains at least 2 items (min and max)
17938 var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
17939 var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
17941 var span = next[skey] - prev[skey];
17942 var ratio = span ? (sval - prev[skey]) / span : 0;
17943 var offset = (next[tkey] - prev[tkey]) * ratio;
17945 return prev[tkey] + offset;
17949 * Convert the given value to a moment object using the given time options.
17950 * @see http://momentjs.com/docs/#/parsing/
17952 function momentify(value, options) {
17953 var parser = options.parser;
17954 var format = options.parser || options.format;
17956 if (typeof parser === 'function') {
17957 return parser(value);
17960 if (typeof value === 'string' && typeof format === 'string') {
17961 return moment(value, format);
17964 if (!(value instanceof moment)) {
17965 value = moment(value);
17968 if (value.isValid()) {
17972 // Labels are in an incompatible moment format and no `parser` has been provided.
17973 // The user might still use the deprecated `format` option to convert his inputs.
17974 if (typeof format === 'function') {
17975 return format(value);
17981 function parse(input, scale) {
17982 if (helpers.isNullOrUndef(input)) {
17986 var options = scale.options.time;
17987 var value = momentify(scale.getRightValue(input), options);
17988 if (!value.isValid()) {
17992 if (options.round) {
17993 value.startOf(options.round);
17996 return value.valueOf();
18000 * Returns the number of unit to skip to be able to display up to `capacity` number of ticks
18001 * in `unit` for the given `min` / `max` range and respecting the interval steps constraints.
18003 function determineStepSize(min, max, unit, capacity) {
18004 var range = max - min;
18005 var interval = INTERVALS[unit];
18006 var milliseconds = interval.size;
18007 var steps = interval.steps;
18008 var i, ilen, factor;
18011 return Math.ceil(range / ((capacity || 1) * milliseconds));
18014 for (i = 0, ilen = steps.length; i < ilen; ++i) {
18016 if (Math.ceil(range / (milliseconds * factor)) <= capacity) {
18024 function determineUnit(minUnit, min, max, capacity) {
18025 var ilen = UNITS.length;
18026 var i, interval, factor;
18028 for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
18029 interval = INTERVALS[UNITS[i]];
18030 factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER;
18032 if (Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
18037 return UNITS[ilen - 1];
18040 function determineMajorUnit(unit) {
18041 for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
18042 if (INTERVALS[UNITS[i]].major) {
18049 * Generates a maximum of `capacity` timestamps between min and max, rounded to the
18050 * `minor` unit, aligned on the `major` unit and using the given scale time `options`.
18051 * Important: this method can return ticks outside the min and max range, it's the
18052 * responsibility of the calling code to clamp values if needed.
18054 function generate(min, max, minor, major, capacity, options) {
18055 var timeOpts = options.time;
18056 var stepSize = helpers.valueOrDefault(timeOpts.stepSize, timeOpts.unitStepSize);
18057 var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
18058 var majorTicksEnabled = options.ticks.major.enabled;
18059 var interval = INTERVALS[minor];
18060 var first = moment(min);
18061 var last = moment(max);
18066 stepSize = determineStepSize(min, max, minor, capacity);
18069 // For 'week' unit, handle the first day of week option
18071 first = first.isoWeekday(weekday);
18072 last = last.isoWeekday(weekday);
18075 // Align first/last ticks on unit
18076 first = first.startOf(weekday ? 'day' : minor);
18077 last = last.startOf(weekday ? 'day' : minor);
18079 // Make sure that the last tick include max
18081 last.add(1, minor);
18084 time = moment(first);
18086 if (majorTicksEnabled && major && !weekday && !timeOpts.round) {
18087 // Align the first tick on the previous `minor` unit aligned on the `major` unit:
18088 // we first aligned time on the previous `major` unit then add the number of full
18089 // stepSize there is between first and the previous major time.
18090 time.startOf(major);
18091 time.add(~~((first - time) / (interval.size * stepSize)) * stepSize, minor);
18094 for (; time < last; time.add(stepSize, minor)) {
18104 * Returns the right and left offsets from edges in the form of {left, right}.
18105 * Offsets are added when the `offset` option is true.
18107 function computeOffsets(table, ticks, min, max, options) {
18112 if (options.offset && ticks.length) {
18113 if (!options.time.min) {
18114 upper = ticks.length > 1 ? ticks[1] : max;
18117 interpolate(table, 'time', upper, 'pos') -
18118 interpolate(table, 'time', lower, 'pos')
18121 if (!options.time.max) {
18122 upper = ticks[ticks.length - 1];
18123 lower = ticks.length > 1 ? ticks[ticks.length - 2] : min;
18125 interpolate(table, 'time', upper, 'pos') -
18126 interpolate(table, 'time', lower, 'pos')
18131 return {left: left, right: right};
18134 function ticksFromTimestamps(values, majorUnit) {
18136 var i, ilen, value, major;
18138 for (i = 0, ilen = values.length; i < ilen; ++i) {
18140 major = majorUnit ? value === +moment(value).startOf(majorUnit) : false;
18151 module.exports = function(Chart) {
18153 var defaultConfig = {
18154 position: 'bottom',
18157 * Data distribution along the scale:
18158 * - 'linear': data are spread according to their time (distances can vary),
18159 * - 'series': data are spread at the same distance from each other.
18160 * @see https://github.com/chartjs/Chart.js/pull/4507
18163 distribution: 'linear',
18166 * Scale boundary strategy (bypassed by min/max time options)
18167 * - `data`: make sure data are fully visible, ticks outside are removed
18168 * - `ticks`: make sure ticks are fully visible, data outside are truncated
18169 * @see https://github.com/chartjs/Chart.js/pull/4556
18175 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
18176 format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from http://momentjs.com/docs/#/parsing/string-format/
18177 unit: false, // false == automatic or override with week, month, year, etc.
18178 round: false, // none, or override with week, month, year, etc.
18179 displayFormat: false, // DEPRECATED
18180 isoWeekday: false, // override week start day - see http://momentjs.com/docs/#/get-set/iso-weekday/
18181 minUnit: 'millisecond',
18183 // defaults to unit's corresponding unitFormat below or override using pattern string from http://momentjs.com/docs/#/displaying/format/
18185 millisecond: 'h:mm:ss.SSS a', // 11:20:01.123 AM,
18186 second: 'h:mm:ss a', // 11:20:01 AM
18187 minute: 'h:mm a', // 11:20 AM
18189 day: 'MMM D', // Sep 4
18190 week: 'll', // Week 46, or maybe "[W]WW - YYYY" ?
18191 month: 'MMM YYYY', // Sept 2015
18192 quarter: '[Q]Q - YYYY', // Q3
18193 year: 'YYYY' // 2015
18200 * Ticks generation input values:
18201 * - 'auto': generates "optimal" ticks based on scale size and time options.
18202 * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
18203 * - 'labels': generates ticks from user given `data.labels` values ONLY.
18204 * @see https://github.com/chartjs/Chart.js/pull/4507
18215 var TimeScale = Chart.Scale.extend({
18216 initialize: function() {
18218 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');
18221 this.mergeTicksOptions();
18223 Chart.Scale.prototype.initialize.call(this);
18226 update: function() {
18228 var options = me.options;
18230 // DEPRECATIONS: output a message only one time per update
18231 if (options.time && options.time.format) {
18232 console.warn('options.time.format is deprecated and replaced by options.time.parser.');
18235 return Chart.Scale.prototype.update.apply(me, arguments);
18239 * Allows data to be referenced via 't' attribute
18241 getRightValue: function(rawValue) {
18242 if (rawValue && rawValue.t !== undefined) {
18243 rawValue = rawValue.t;
18245 return Chart.Scale.prototype.getRightValue.call(this, rawValue);
18248 determineDataLimits: function() {
18250 var chart = me.chart;
18251 var timeOpts = me.options.time;
18252 var min = parse(timeOpts.min, me) || MAX_INTEGER;
18253 var max = parse(timeOpts.max, me) || MIN_INTEGER;
18254 var timestamps = [];
18257 var i, j, ilen, jlen, data, timestamp;
18259 // Convert labels to timestamps
18260 for (i = 0, ilen = chart.data.labels.length; i < ilen; ++i) {
18261 labels.push(parse(chart.data.labels[i], me));
18264 // Convert data to timestamps
18265 for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
18266 if (chart.isDatasetVisible(i)) {
18267 data = chart.data.datasets[i].data;
18269 // Let's consider that all data have the same format.
18270 if (helpers.isObject(data[0])) {
18273 for (j = 0, jlen = data.length; j < jlen; ++j) {
18274 timestamp = parse(data[j], me);
18275 timestamps.push(timestamp);
18276 datasets[i][j] = timestamp;
18279 timestamps.push.apply(timestamps, labels);
18280 datasets[i] = labels.slice(0);
18287 if (labels.length) {
18288 // Sort labels **after** data have been converted
18289 labels = arrayUnique(labels).sort(sorter);
18290 min = Math.min(min, labels[0]);
18291 max = Math.max(max, labels[labels.length - 1]);
18294 if (timestamps.length) {
18295 timestamps = arrayUnique(timestamps).sort(sorter);
18296 min = Math.min(min, timestamps[0]);
18297 max = Math.max(max, timestamps[timestamps.length - 1]);
18300 // In case there is no valid min/max, let's use today limits
18301 min = min === MAX_INTEGER ? +moment().startOf('day') : min;
18302 max = max === MIN_INTEGER ? +moment().endOf('day') + 1 : max;
18304 // Make sure that max is strictly higher than min (required by the lookup table)
18305 me.min = Math.min(min, max);
18306 me.max = Math.max(min + 1, max);
18309 me._horizontal = me.isHorizontal();
18313 datasets: datasets,
18318 buildTicks: function() {
18322 var options = me.options;
18323 var timeOpts = options.time;
18324 var formats = timeOpts.displayFormats;
18325 var capacity = me.getLabelCapacity(min);
18326 var unit = timeOpts.unit || determineUnit(timeOpts.minUnit, min, max, capacity);
18327 var majorUnit = determineMajorUnit(unit);
18328 var timestamps = [];
18330 var i, ilen, timestamp;
18332 switch (options.ticks.source) {
18334 timestamps = me._timestamps.data;
18337 timestamps = me._timestamps.labels;
18341 timestamps = generate(min, max, unit, majorUnit, capacity, options);
18344 if (options.bounds === 'ticks' && timestamps.length) {
18345 min = timestamps[0];
18346 max = timestamps[timestamps.length - 1];
18349 // Enforce limits with user min/max options
18350 min = parse(timeOpts.min, me) || min;
18351 max = parse(timeOpts.max, me) || max;
18353 // Remove ticks outside the min/max range
18354 for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
18355 timestamp = timestamps[i];
18356 if (timestamp >= min && timestamp <= max) {
18357 ticks.push(timestamp);
18366 me._majorUnit = majorUnit;
18367 me._minorFormat = formats[unit];
18368 me._majorFormat = formats[majorUnit];
18369 me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);
18370 me._offsets = computeOffsets(me._table, ticks, min, max, options);
18372 return ticksFromTimestamps(ticks, majorUnit);
18375 getLabelForIndex: function(index, datasetIndex) {
18377 var data = me.chart.data;
18378 var timeOpts = me.options.time;
18379 var label = data.labels && index < data.labels.length ? data.labels[index] : '';
18380 var value = data.datasets[datasetIndex].data[index];
18382 if (helpers.isObject(value)) {
18383 label = me.getRightValue(value);
18385 if (timeOpts.tooltipFormat) {
18386 label = momentify(label, timeOpts).format(timeOpts.tooltipFormat);
18393 * Function to format an individual tick mark
18396 tickFormatFunction: function(tick, index, ticks) {
18398 var options = me.options;
18399 var time = tick.valueOf();
18400 var majorUnit = me._majorUnit;
18401 var majorFormat = me._majorFormat;
18402 var majorTime = tick.clone().startOf(me._majorUnit).valueOf();
18403 var majorTickOpts = options.ticks.major;
18404 var major = majorTickOpts.enabled && majorUnit && majorFormat && time === majorTime;
18405 var label = tick.format(major ? majorFormat : me._minorFormat);
18406 var tickOpts = major ? majorTickOpts : options.ticks.minor;
18407 var formatter = helpers.valueOrDefault(tickOpts.callback, tickOpts.userCallback);
18409 return formatter ? formatter(label, index, ticks) : label;
18412 convertTicksToLabels: function(ticks) {
18416 for (i = 0, ilen = ticks.length; i < ilen; ++i) {
18417 labels.push(this.tickFormatFunction(moment(ticks[i].value), i, ticks));
18426 getPixelForOffset: function(time) {
18428 var size = me._horizontal ? me.width : me.height;
18429 var start = me._horizontal ? me.left : me.top;
18430 var pos = interpolate(me._table, 'time', time, 'pos');
18432 return start + size * (me._offsets.left + pos) / (me._offsets.left + 1 + me._offsets.right);
18435 getPixelForValue: function(value, index, datasetIndex) {
18439 if (index !== undefined && datasetIndex !== undefined) {
18440 time = me._timestamps.datasets[datasetIndex][index];
18443 if (time === null) {
18444 time = parse(value, me);
18447 if (time !== null) {
18448 return me.getPixelForOffset(time);
18452 getPixelForTick: function(index) {
18453 var ticks = this.getTicks();
18454 return index >= 0 && index < ticks.length ?
18455 this.getPixelForOffset(ticks[index].value) :
18459 getValueForPixel: function(pixel) {
18461 var size = me._horizontal ? me.width : me.height;
18462 var start = me._horizontal ? me.left : me.top;
18463 var pos = (size ? (pixel - start) / size : 0) * (me._offsets.left + 1 + me._offsets.left) - me._offsets.right;
18464 var time = interpolate(me._table, 'pos', pos, 'time');
18466 return moment(time);
18470 * Crude approximation of what the label width might be
18473 getLabelWidth: function(label) {
18475 var ticksOpts = me.options.ticks;
18476 var tickLabelWidth = me.ctx.measureText(label).width;
18477 var angle = helpers.toRadians(ticksOpts.maxRotation);
18478 var cosRotation = Math.cos(angle);
18479 var sinRotation = Math.sin(angle);
18480 var tickFontSize = helpers.valueOrDefault(ticksOpts.fontSize, defaults.global.defaultFontSize);
18482 return (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation);
18488 getLabelCapacity: function(exampleTime) {
18491 me._minorFormat = me.options.time.displayFormats.millisecond; // Pick the longest format for guestimation
18493 var exampleLabel = me.tickFormatFunction(moment(exampleTime), 0, []);
18494 var tickLabelWidth = me.getLabelWidth(exampleLabel);
18495 var innerWidth = me.isHorizontal() ? me.width : me.height;
18497 return Math.floor(innerWidth / tickLabelWidth);
18501 Chart.scaleService.registerScaleType('time', TimeScale, defaultConfig);
18504 },{"25":25,"45":45,"6":6}]},{},[7])(7)