· 8 years ago · Apr 03, 2018, 01:42 PM
1/*!
2 * Chart.js
3 * http://chartjs.org/
4 * Version: 2.7.2
5 *
6 * Copyright 2018 Chart.js Contributors
7 * Released under the MIT license
8 * https://github.com/chartjs/Chart.js/blob/master/LICENSE.md
9 */
10(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(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
11
12},{}],2:[function(require,module,exports){
13/* MIT license */
14var colorNames = require(6);
15
16module.exports = {
17 getRgba: getRgba,
18 getHsla: getHsla,
19 getRgb: getRgb,
20 getHsl: getHsl,
21 getHwb: getHwb,
22 getAlpha: getAlpha,
23
24 hexString: hexString,
25 rgbString: rgbString,
26 rgbaString: rgbaString,
27 percentString: percentString,
28 percentaString: percentaString,
29 hslString: hslString,
30 hslaString: hslaString,
31 hwbString: hwbString,
32 keyword: keyword
33}
34
35function getRgba(string) {
36 if (!string) {
37 return;
38 }
39 var abbr = /^#([a-fA-F0-9]{3})$/i,
40 hex = /^#([a-fA-F0-9]{6})$/i,
41 rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
42 per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
43 keyword = /(\w+)/;
44
45 var rgb = [0, 0, 0],
46 a = 1,
47 match = string.match(abbr);
48 if (match) {
49 match = match[1];
50 for (var i = 0; i < rgb.length; i++) {
51 rgb[i] = parseInt(match[i] + match[i], 16);
52 }
53 }
54 else if (match = string.match(hex)) {
55 match = match[1];
56 for (var i = 0; i < rgb.length; i++) {
57 rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
58 }
59 }
60 else if (match = string.match(rgba)) {
61 for (var i = 0; i < rgb.length; i++) {
62 rgb[i] = parseInt(match[i + 1]);
63 }
64 a = parseFloat(match[4]);
65 }
66 else if (match = string.match(per)) {
67 for (var i = 0; i < rgb.length; i++) {
68 rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
69 }
70 a = parseFloat(match[4]);
71 }
72 else if (match = string.match(keyword)) {
73 if (match[1] == "transparent") {
74 return [0, 0, 0, 0];
75 }
76 rgb = colorNames[match[1]];
77 if (!rgb) {
78 return;
79 }
80 }
81
82 for (var i = 0; i < rgb.length; i++) {
83 rgb[i] = scale(rgb[i], 0, 255);
84 }
85 if (!a && a != 0) {
86 a = 1;
87 }
88 else {
89 a = scale(a, 0, 1);
90 }
91 rgb[3] = a;
92 return rgb;
93}
94
95function getHsla(string) {
96 if (!string) {
97 return;
98 }
99 var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
100 var match = string.match(hsl);
101 if (match) {
102 var alpha = parseFloat(match[4]);
103 var h = scale(parseInt(match[1]), 0, 360),
104 s = scale(parseFloat(match[2]), 0, 100),
105 l = scale(parseFloat(match[3]), 0, 100),
106 a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
107 return [h, s, l, a];
108 }
109}
110
111function getHwb(string) {
112 if (!string) {
113 return;
114 }
115 var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
116 var match = string.match(hwb);
117 if (match) {
118 var alpha = parseFloat(match[4]);
119 var h = scale(parseInt(match[1]), 0, 360),
120 w = scale(parseFloat(match[2]), 0, 100),
121 b = scale(parseFloat(match[3]), 0, 100),
122 a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
123 return [h, w, b, a];
124 }
125}
126
127function getRgb(string) {
128 var rgba = getRgba(string);
129 return rgba && rgba.slice(0, 3);
130}
131
132function getHsl(string) {
133 var hsla = getHsla(string);
134 return hsla && hsla.slice(0, 3);
135}
136
137function getAlpha(string) {
138 var vals = getRgba(string);
139 if (vals) {
140 return vals[3];
141 }
142 else if (vals = getHsla(string)) {
143 return vals[3];
144 }
145 else if (vals = getHwb(string)) {
146 return vals[3];
147 }
148}
149
150// generators
151function hexString(rgb) {
152 return "#" + hexDouble(rgb[0]) + hexDouble(rgb[1])
153 + hexDouble(rgb[2]);
154}
155
156function rgbString(rgba, alpha) {
157 if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
158 return rgbaString(rgba, alpha);
159 }
160 return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
161}
162
163function rgbaString(rgba, alpha) {
164 if (alpha === undefined) {
165 alpha = (rgba[3] !== undefined ? rgba[3] : 1);
166 }
167 return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
168 + ", " + alpha + ")";
169}
170
171function percentString(rgba, alpha) {
172 if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
173 return percentaString(rgba, alpha);
174 }
175 var r = Math.round(rgba[0]/255 * 100),
176 g = Math.round(rgba[1]/255 * 100),
177 b = Math.round(rgba[2]/255 * 100);
178
179 return "rgb(" + r + "%, " + g + "%, " + b + "%)";
180}
181
182function percentaString(rgba, alpha) {
183 var r = Math.round(rgba[0]/255 * 100),
184 g = Math.round(rgba[1]/255 * 100),
185 b = Math.round(rgba[2]/255 * 100);
186 return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
187}
188
189function hslString(hsla, alpha) {
190 if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
191 return hslaString(hsla, alpha);
192 }
193 return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
194}
195
196function hslaString(hsla, alpha) {
197 if (alpha === undefined) {
198 alpha = (hsla[3] !== undefined ? hsla[3] : 1);
199 }
200 return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
201 + alpha + ")";
202}
203
204// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
205// (hwb have alpha optional & 1 is default value)
206function hwbString(hwb, alpha) {
207 if (alpha === undefined) {
208 alpha = (hwb[3] !== undefined ? hwb[3] : 1);
209 }
210 return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
211 + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
212}
213
214function keyword(rgb) {
215 return reverseNames[rgb.slice(0, 3)];
216}
217
218// helpers
219function scale(num, min, max) {
220 return Math.min(Math.max(min, num), max);
221}
222
223function hexDouble(num) {
224 var str = num.toString(16).toUpperCase();
225 return (str.length < 2) ? "0" + str : str;
226}
227
228
229//create a list of reverse color names
230var reverseNames = {};
231for (var name in colorNames) {
232 reverseNames[colorNames[name]] = name;
233}
234
235},{"6":6}],3:[function(require,module,exports){
236/* MIT license */
237var convert = require(5);
238var string = require(2);
239
240var Color = function (obj) {
241 if (obj instanceof Color) {
242 return obj;
243 }
244 if (!(this instanceof Color)) {
245 return new Color(obj);
246 }
247
248 this.valid = false;
249 this.values = {
250 rgb: [0, 0, 0],
251 hsl: [0, 0, 0],
252 hsv: [0, 0, 0],
253 hwb: [0, 0, 0],
254 cmyk: [0, 0, 0, 0],
255 alpha: 1
256 };
257
258 // parse Color() argument
259 var vals;
260 if (typeof obj === 'string') {
261 vals = string.getRgba(obj);
262 if (vals) {
263 this.setValues('rgb', vals);
264 } else if (vals = string.getHsla(obj)) {
265 this.setValues('hsl', vals);
266 } else if (vals = string.getHwb(obj)) {
267 this.setValues('hwb', vals);
268 }
269 } else if (typeof obj === 'object') {
270 vals = obj;
271 if (vals.r !== undefined || vals.red !== undefined) {
272 this.setValues('rgb', vals);
273 } else if (vals.l !== undefined || vals.lightness !== undefined) {
274 this.setValues('hsl', vals);
275 } else if (vals.v !== undefined || vals.value !== undefined) {
276 this.setValues('hsv', vals);
277 } else if (vals.w !== undefined || vals.whiteness !== undefined) {
278 this.setValues('hwb', vals);
279 } else if (vals.c !== undefined || vals.cyan !== undefined) {
280 this.setValues('cmyk', vals);
281 }
282 }
283};
284
285Color.prototype = {
286 isValid: function () {
287 return this.valid;
288 },
289 rgb: function () {
290 return this.setSpace('rgb', arguments);
291 },
292 hsl: function () {
293 return this.setSpace('hsl', arguments);
294 },
295 hsv: function () {
296 return this.setSpace('hsv', arguments);
297 },
298 hwb: function () {
299 return this.setSpace('hwb', arguments);
300 },
301 cmyk: function () {
302 return this.setSpace('cmyk', arguments);
303 },
304
305 rgbArray: function () {
306 return this.values.rgb;
307 },
308 hslArray: function () {
309 return this.values.hsl;
310 },
311 hsvArray: function () {
312 return this.values.hsv;
313 },
314 hwbArray: function () {
315 var values = this.values;
316 if (values.alpha !== 1) {
317 return values.hwb.concat([values.alpha]);
318 }
319 return values.hwb;
320 },
321 cmykArray: function () {
322 return this.values.cmyk;
323 },
324 rgbaArray: function () {
325 var values = this.values;
326 return values.rgb.concat([values.alpha]);
327 },
328 hslaArray: function () {
329 var values = this.values;
330 return values.hsl.concat([values.alpha]);
331 },
332 alpha: function (val) {
333 if (val === undefined) {
334 return this.values.alpha;
335 }
336 this.setValues('alpha', val);
337 return this;
338 },
339
340 red: function (val) {
341 return this.setChannel('rgb', 0, val);
342 },
343 green: function (val) {
344 return this.setChannel('rgb', 1, val);
345 },
346 blue: function (val) {
347 return this.setChannel('rgb', 2, val);
348 },
349 hue: function (val) {
350 if (val) {
351 val %= 360;
352 val = val < 0 ? 360 + val : val;
353 }
354 return this.setChannel('hsl', 0, val);
355 },
356 saturation: function (val) {
357 return this.setChannel('hsl', 1, val);
358 },
359 lightness: function (val) {
360 return this.setChannel('hsl', 2, val);
361 },
362 saturationv: function (val) {
363 return this.setChannel('hsv', 1, val);
364 },
365 whiteness: function (val) {
366 return this.setChannel('hwb', 1, val);
367 },
368 blackness: function (val) {
369 return this.setChannel('hwb', 2, val);
370 },
371 value: function (val) {
372 return this.setChannel('hsv', 2, val);
373 },
374 cyan: function (val) {
375 return this.setChannel('cmyk', 0, val);
376 },
377 magenta: function (val) {
378 return this.setChannel('cmyk', 1, val);
379 },
380 yellow: function (val) {
381 return this.setChannel('cmyk', 2, val);
382 },
383 black: function (val) {
384 return this.setChannel('cmyk', 3, val);
385 },
386
387 hexString: function () {
388 return string.hexString(this.values.rgb);
389 },
390 rgbString: function () {
391 return string.rgbString(this.values.rgb, this.values.alpha);
392 },
393 rgbaString: function () {
394 return string.rgbaString(this.values.rgb, this.values.alpha);
395 },
396 percentString: function () {
397 return string.percentString(this.values.rgb, this.values.alpha);
398 },
399 hslString: function () {
400 return string.hslString(this.values.hsl, this.values.alpha);
401 },
402 hslaString: function () {
403 return string.hslaString(this.values.hsl, this.values.alpha);
404 },
405 hwbString: function () {
406 return string.hwbString(this.values.hwb, this.values.alpha);
407 },
408 keyword: function () {
409 return string.keyword(this.values.rgb, this.values.alpha);
410 },
411
412 rgbNumber: function () {
413 var rgb = this.values.rgb;
414 return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
415 },
416
417 luminosity: function () {
418 // http://www.w3.org/TR/WCAG20/#relativeluminancedef
419 var rgb = this.values.rgb;
420 var lum = [];
421 for (var i = 0; i < rgb.length; i++) {
422 var chan = rgb[i] / 255;
423 lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
424 }
425 return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
426 },
427
428 contrast: function (color2) {
429 // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
430 var lum1 = this.luminosity();
431 var lum2 = color2.luminosity();
432 if (lum1 > lum2) {
433 return (lum1 + 0.05) / (lum2 + 0.05);
434 }
435 return (lum2 + 0.05) / (lum1 + 0.05);
436 },
437
438 level: function (color2) {
439 var contrastRatio = this.contrast(color2);
440 if (contrastRatio >= 7.1) {
441 return 'AAA';
442 }
443
444 return (contrastRatio >= 4.5) ? 'AA' : '';
445 },
446
447 dark: function () {
448 // YIQ equation from http://24ways.org/2010/calculating-color-contrast
449 var rgb = this.values.rgb;
450 var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
451 return yiq < 128;
452 },
453
454 light: function () {
455 return !this.dark();
456 },
457
458 negate: function () {
459 var rgb = [];
460 for (var i = 0; i < 3; i++) {
461 rgb[i] = 255 - this.values.rgb[i];
462 }
463 this.setValues('rgb', rgb);
464 return this;
465 },
466
467 lighten: function (ratio) {
468 var hsl = this.values.hsl;
469 hsl[2] += hsl[2] * ratio;
470 this.setValues('hsl', hsl);
471 return this;
472 },
473
474 darken: function (ratio) {
475 var hsl = this.values.hsl;
476 hsl[2] -= hsl[2] * ratio;
477 this.setValues('hsl', hsl);
478 return this;
479 },
480
481 saturate: function (ratio) {
482 var hsl = this.values.hsl;
483 hsl[1] += hsl[1] * ratio;
484 this.setValues('hsl', hsl);
485 return this;
486 },
487
488 desaturate: function (ratio) {
489 var hsl = this.values.hsl;
490 hsl[1] -= hsl[1] * ratio;
491 this.setValues('hsl', hsl);
492 return this;
493 },
494
495 whiten: function (ratio) {
496 var hwb = this.values.hwb;
497 hwb[1] += hwb[1] * ratio;
498 this.setValues('hwb', hwb);
499 return this;
500 },
501
502 blacken: function (ratio) {
503 var hwb = this.values.hwb;
504 hwb[2] += hwb[2] * ratio;
505 this.setValues('hwb', hwb);
506 return this;
507 },
508
509 greyscale: function () {
510 var rgb = this.values.rgb;
511 // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
512 var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
513 this.setValues('rgb', [val, val, val]);
514 return this;
515 },
516
517 clearer: function (ratio) {
518 var alpha = this.values.alpha;
519 this.setValues('alpha', alpha - (alpha * ratio));
520 return this;
521 },
522
523 opaquer: function (ratio) {
524 var alpha = this.values.alpha;
525 this.setValues('alpha', alpha + (alpha * ratio));
526 return this;
527 },
528
529 rotate: function (degrees) {
530 var hsl = this.values.hsl;
531 var hue = (hsl[0] + degrees) % 360;
532 hsl[0] = hue < 0 ? 360 + hue : hue;
533 this.setValues('hsl', hsl);
534 return this;
535 },
536
537 /**
538 * Ported from sass implementation in C
539 * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
540 */
541 mix: function (mixinColor, weight) {
542 var color1 = this;
543 var color2 = mixinColor;
544 var p = weight === undefined ? 0.5 : weight;
545
546 var w = 2 * p - 1;
547 var a = color1.alpha() - color2.alpha();
548
549 var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
550 var w2 = 1 - w1;
551
552 return this
553 .rgb(
554 w1 * color1.red() + w2 * color2.red(),
555 w1 * color1.green() + w2 * color2.green(),
556 w1 * color1.blue() + w2 * color2.blue()
557 )
558 .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
559 },
560
561 toJSON: function () {
562 return this.rgb();
563 },
564
565 clone: function () {
566 // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
567 // making the final build way to big to embed in Chart.js. So let's do it manually,
568 // assuming that values to clone are 1 dimension arrays containing only numbers,
569 // except 'alpha' which is a number.
570 var result = new Color();
571 var source = this.values;
572 var target = result.values;
573 var value, type;
574
575 for (var prop in source) {
576 if (source.hasOwnProperty(prop)) {
577 value = source[prop];
578 type = ({}).toString.call(value);
579 if (type === '[object Array]') {
580 target[prop] = value.slice(0);
581 } else if (type === '[object Number]') {
582 target[prop] = value;
583 } else {
584 console.error('unexpected color value:', value);
585 }
586 }
587 }
588
589 return result;
590 }
591};
592
593Color.prototype.spaces = {
594 rgb: ['red', 'green', 'blue'],
595 hsl: ['hue', 'saturation', 'lightness'],
596 hsv: ['hue', 'saturation', 'value'],
597 hwb: ['hue', 'whiteness', 'blackness'],
598 cmyk: ['cyan', 'magenta', 'yellow', 'black']
599};
600
601Color.prototype.maxes = {
602 rgb: [255, 255, 255],
603 hsl: [360, 100, 100],
604 hsv: [360, 100, 100],
605 hwb: [360, 100, 100],
606 cmyk: [100, 100, 100, 100]
607};
608
609Color.prototype.getValues = function (space) {
610 var values = this.values;
611 var vals = {};
612
613 for (var i = 0; i < space.length; i++) {
614 vals[space.charAt(i)] = values[space][i];
615 }
616
617 if (values.alpha !== 1) {
618 vals.a = values.alpha;
619 }
620
621 // {r: 255, g: 255, b: 255, a: 0.4}
622 return vals;
623};
624
625Color.prototype.setValues = function (space, vals) {
626 var values = this.values;
627 var spaces = this.spaces;
628 var maxes = this.maxes;
629 var alpha = 1;
630 var i;
631
632 this.valid = true;
633
634 if (space === 'alpha') {
635 alpha = vals;
636 } else if (vals.length) {
637 // [10, 10, 10]
638 values[space] = vals.slice(0, space.length);
639 alpha = vals[space.length];
640 } else if (vals[space.charAt(0)] !== undefined) {
641 // {r: 10, g: 10, b: 10}
642 for (i = 0; i < space.length; i++) {
643 values[space][i] = vals[space.charAt(i)];
644 }
645
646 alpha = vals.a;
647 } else if (vals[spaces[space][0]] !== undefined) {
648 // {red: 10, green: 10, blue: 10}
649 var chans = spaces[space];
650
651 for (i = 0; i < space.length; i++) {
652 values[space][i] = vals[chans[i]];
653 }
654
655 alpha = vals.alpha;
656 }
657
658 values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
659
660 if (space === 'alpha') {
661 return false;
662 }
663
664 var capped;
665
666 // cap values of the space prior converting all values
667 for (i = 0; i < space.length; i++) {
668 capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
669 values[space][i] = Math.round(capped);
670 }
671
672 // convert to all the other color spaces
673 for (var sname in spaces) {
674 if (sname !== space) {
675 values[sname] = convert[space][sname](values[space]);
676 }
677 }
678
679 return true;
680};
681
682Color.prototype.setSpace = function (space, args) {
683 var vals = args[0];
684
685 if (vals === undefined) {
686 // color.rgb()
687 return this.getValues(space);
688 }
689
690 // color.rgb(10, 10, 10)
691 if (typeof vals === 'number') {
692 vals = Array.prototype.slice.call(args);
693 }
694
695 this.setValues(space, vals);
696 return this;
697};
698
699Color.prototype.setChannel = function (space, index, val) {
700 var svalues = this.values[space];
701 if (val === undefined) {
702 // color.red()
703 return svalues[index];
704 } else if (val === svalues[index]) {
705 // color.red(color.red())
706 return this;
707 }
708
709 // color.red(100)
710 svalues[index] = val;
711 this.setValues(space, svalues);
712
713 return this;
714};
715
716if (typeof window !== 'undefined') {
717 window.Color = Color;
718}
719
720module.exports = Color;
721
722},{"2":2,"5":5}],4:[function(require,module,exports){
723/* MIT license */
724
725module.exports = {
726 rgb2hsl: rgb2hsl,
727 rgb2hsv: rgb2hsv,
728 rgb2hwb: rgb2hwb,
729 rgb2cmyk: rgb2cmyk,
730 rgb2keyword: rgb2keyword,
731 rgb2xyz: rgb2xyz,
732 rgb2lab: rgb2lab,
733 rgb2lch: rgb2lch,
734
735 hsl2rgb: hsl2rgb,
736 hsl2hsv: hsl2hsv,
737 hsl2hwb: hsl2hwb,
738 hsl2cmyk: hsl2cmyk,
739 hsl2keyword: hsl2keyword,
740
741 hsv2rgb: hsv2rgb,
742 hsv2hsl: hsv2hsl,
743 hsv2hwb: hsv2hwb,
744 hsv2cmyk: hsv2cmyk,
745 hsv2keyword: hsv2keyword,
746
747 hwb2rgb: hwb2rgb,
748 hwb2hsl: hwb2hsl,
749 hwb2hsv: hwb2hsv,
750 hwb2cmyk: hwb2cmyk,
751 hwb2keyword: hwb2keyword,
752
753 cmyk2rgb: cmyk2rgb,
754 cmyk2hsl: cmyk2hsl,
755 cmyk2hsv: cmyk2hsv,
756 cmyk2hwb: cmyk2hwb,
757 cmyk2keyword: cmyk2keyword,
758
759 keyword2rgb: keyword2rgb,
760 keyword2hsl: keyword2hsl,
761 keyword2hsv: keyword2hsv,
762 keyword2hwb: keyword2hwb,
763 keyword2cmyk: keyword2cmyk,
764 keyword2lab: keyword2lab,
765 keyword2xyz: keyword2xyz,
766
767 xyz2rgb: xyz2rgb,
768 xyz2lab: xyz2lab,
769 xyz2lch: xyz2lch,
770
771 lab2xyz: lab2xyz,
772 lab2rgb: lab2rgb,
773 lab2lch: lab2lch,
774
775 lch2lab: lch2lab,
776 lch2xyz: lch2xyz,
777 lch2rgb: lch2rgb
778}
779
780
781function rgb2hsl(rgb) {
782 var r = rgb[0]/255,
783 g = rgb[1]/255,
784 b = rgb[2]/255,
785 min = Math.min(r, g, b),
786 max = Math.max(r, g, b),
787 delta = max - min,
788 h, s, l;
789
790 if (max == min)
791 h = 0;
792 else if (r == max)
793 h = (g - b) / delta;
794 else if (g == max)
795 h = 2 + (b - r) / delta;
796 else if (b == max)
797 h = 4 + (r - g)/ delta;
798
799 h = Math.min(h * 60, 360);
800
801 if (h < 0)
802 h += 360;
803
804 l = (min + max) / 2;
805
806 if (max == min)
807 s = 0;
808 else if (l <= 0.5)
809 s = delta / (max + min);
810 else
811 s = delta / (2 - max - min);
812
813 return [h, s * 100, l * 100];
814}
815
816function rgb2hsv(rgb) {
817 var r = rgb[0],
818 g = rgb[1],
819 b = rgb[2],
820 min = Math.min(r, g, b),
821 max = Math.max(r, g, b),
822 delta = max - min,
823 h, s, v;
824
825 if (max == 0)
826 s = 0;
827 else
828 s = (delta/max * 1000)/10;
829
830 if (max == min)
831 h = 0;
832 else if (r == max)
833 h = (g - b) / delta;
834 else if (g == max)
835 h = 2 + (b - r) / delta;
836 else if (b == max)
837 h = 4 + (r - g) / delta;
838
839 h = Math.min(h * 60, 360);
840
841 if (h < 0)
842 h += 360;
843
844 v = ((max / 255) * 1000) / 10;
845
846 return [h, s, v];
847}
848
849function rgb2hwb(rgb) {
850 var r = rgb[0],
851 g = rgb[1],
852 b = rgb[2],
853 h = rgb2hsl(rgb)[0],
854 w = 1/255 * Math.min(r, Math.min(g, b)),
855 b = 1 - 1/255 * Math.max(r, Math.max(g, b));
856
857 return [h, w * 100, b * 100];
858}
859
860function rgb2cmyk(rgb) {
861 var r = rgb[0] / 255,
862 g = rgb[1] / 255,
863 b = rgb[2] / 255,
864 c, m, y, k;
865
866 k = Math.min(1 - r, 1 - g, 1 - b);
867 c = (1 - r - k) / (1 - k) || 0;
868 m = (1 - g - k) / (1 - k) || 0;
869 y = (1 - b - k) / (1 - k) || 0;
870 return [c * 100, m * 100, y * 100, k * 100];
871}
872
873function rgb2keyword(rgb) {
874 return reverseKeywords[JSON.stringify(rgb)];
875}
876
877function rgb2xyz(rgb) {
878 var r = rgb[0] / 255,
879 g = rgb[1] / 255,
880 b = rgb[2] / 255;
881
882 // assume sRGB
883 r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
884 g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
885 b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
886
887 var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
888 var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
889 var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
890
891 return [x * 100, y *100, z * 100];
892}
893
894function rgb2lab(rgb) {
895 var xyz = rgb2xyz(rgb),
896 x = xyz[0],
897 y = xyz[1],
898 z = xyz[2],
899 l, a, b;
900
901 x /= 95.047;
902 y /= 100;
903 z /= 108.883;
904
905 x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
906 y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
907 z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
908
909 l = (116 * y) - 16;
910 a = 500 * (x - y);
911 b = 200 * (y - z);
912
913 return [l, a, b];
914}
915
916function rgb2lch(args) {
917 return lab2lch(rgb2lab(args));
918}
919
920function hsl2rgb(hsl) {
921 var h = hsl[0] / 360,
922 s = hsl[1] / 100,
923 l = hsl[2] / 100,
924 t1, t2, t3, rgb, val;
925
926 if (s == 0) {
927 val = l * 255;
928 return [val, val, val];
929 }
930
931 if (l < 0.5)
932 t2 = l * (1 + s);
933 else
934 t2 = l + s - l * s;
935 t1 = 2 * l - t2;
936
937 rgb = [0, 0, 0];
938 for (var i = 0; i < 3; i++) {
939 t3 = h + 1 / 3 * - (i - 1);
940 t3 < 0 && t3++;
941 t3 > 1 && t3--;
942
943 if (6 * t3 < 1)
944 val = t1 + (t2 - t1) * 6 * t3;
945 else if (2 * t3 < 1)
946 val = t2;
947 else if (3 * t3 < 2)
948 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
949 else
950 val = t1;
951
952 rgb[i] = val * 255;
953 }
954
955 return rgb;
956}
957
958function hsl2hsv(hsl) {
959 var h = hsl[0],
960 s = hsl[1] / 100,
961 l = hsl[2] / 100,
962 sv, v;
963
964 if(l === 0) {
965 // no need to do calc on black
966 // also avoids divide by 0 error
967 return [0, 0, 0];
968 }
969
970 l *= 2;
971 s *= (l <= 1) ? l : 2 - l;
972 v = (l + s) / 2;
973 sv = (2 * s) / (l + s);
974 return [h, sv * 100, v * 100];
975}
976
977function hsl2hwb(args) {
978 return rgb2hwb(hsl2rgb(args));
979}
980
981function hsl2cmyk(args) {
982 return rgb2cmyk(hsl2rgb(args));
983}
984
985function hsl2keyword(args) {
986 return rgb2keyword(hsl2rgb(args));
987}
988
989
990function hsv2rgb(hsv) {
991 var h = hsv[0] / 60,
992 s = hsv[1] / 100,
993 v = hsv[2] / 100,
994 hi = Math.floor(h) % 6;
995
996 var f = h - Math.floor(h),
997 p = 255 * v * (1 - s),
998 q = 255 * v * (1 - (s * f)),
999 t = 255 * v * (1 - (s * (1 - f))),
1000 v = 255 * v;
1001
1002 switch(hi) {
1003 case 0:
1004 return [v, t, p];
1005 case 1:
1006 return [q, v, p];
1007 case 2:
1008 return [p, v, t];
1009 case 3:
1010 return [p, q, v];
1011 case 4:
1012 return [t, p, v];
1013 case 5:
1014 return [v, p, q];
1015 }
1016}
1017
1018function hsv2hsl(hsv) {
1019 var h = hsv[0],
1020 s = hsv[1] / 100,
1021 v = hsv[2] / 100,
1022 sl, l;
1023
1024 l = (2 - s) * v;
1025 sl = s * v;
1026 sl /= (l <= 1) ? l : 2 - l;
1027 sl = sl || 0;
1028 l /= 2;
1029 return [h, sl * 100, l * 100];
1030}
1031
1032function hsv2hwb(args) {
1033 return rgb2hwb(hsv2rgb(args))
1034}
1035
1036function hsv2cmyk(args) {
1037 return rgb2cmyk(hsv2rgb(args));
1038}
1039
1040function hsv2keyword(args) {
1041 return rgb2keyword(hsv2rgb(args));
1042}
1043
1044// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
1045function hwb2rgb(hwb) {
1046 var h = hwb[0] / 360,
1047 wh = hwb[1] / 100,
1048 bl = hwb[2] / 100,
1049 ratio = wh + bl,
1050 i, v, f, n;
1051
1052 // wh + bl cant be > 1
1053 if (ratio > 1) {
1054 wh /= ratio;
1055 bl /= ratio;
1056 }
1057
1058 i = Math.floor(6 * h);
1059 v = 1 - bl;
1060 f = 6 * h - i;
1061 if ((i & 0x01) != 0) {
1062 f = 1 - f;
1063 }
1064 n = wh + f * (v - wh); // linear interpolation
1065
1066 switch (i) {
1067 default:
1068 case 6:
1069 case 0: r = v; g = n; b = wh; break;
1070 case 1: r = n; g = v; b = wh; break;
1071 case 2: r = wh; g = v; b = n; break;
1072 case 3: r = wh; g = n; b = v; break;
1073 case 4: r = n; g = wh; b = v; break;
1074 case 5: r = v; g = wh; b = n; break;
1075 }
1076
1077 return [r * 255, g * 255, b * 255];
1078}
1079
1080function hwb2hsl(args) {
1081 return rgb2hsl(hwb2rgb(args));
1082}
1083
1084function hwb2hsv(args) {
1085 return rgb2hsv(hwb2rgb(args));
1086}
1087
1088function hwb2cmyk(args) {
1089 return rgb2cmyk(hwb2rgb(args));
1090}
1091
1092function hwb2keyword(args) {
1093 return rgb2keyword(hwb2rgb(args));
1094}
1095
1096function cmyk2rgb(cmyk) {
1097 var c = cmyk[0] / 100,
1098 m = cmyk[1] / 100,
1099 y = cmyk[2] / 100,
1100 k = cmyk[3] / 100,
1101 r, g, b;
1102
1103 r = 1 - Math.min(1, c * (1 - k) + k);
1104 g = 1 - Math.min(1, m * (1 - k) + k);
1105 b = 1 - Math.min(1, y * (1 - k) + k);
1106 return [r * 255, g * 255, b * 255];
1107}
1108
1109function cmyk2hsl(args) {
1110 return rgb2hsl(cmyk2rgb(args));
1111}
1112
1113function cmyk2hsv(args) {
1114 return rgb2hsv(cmyk2rgb(args));
1115}
1116
1117function cmyk2hwb(args) {
1118 return rgb2hwb(cmyk2rgb(args));
1119}
1120
1121function cmyk2keyword(args) {
1122 return rgb2keyword(cmyk2rgb(args));
1123}
1124
1125
1126function xyz2rgb(xyz) {
1127 var x = xyz[0] / 100,
1128 y = xyz[1] / 100,
1129 z = xyz[2] / 100,
1130 r, g, b;
1131
1132 r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
1133 g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
1134 b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
1135
1136 // assume sRGB
1137 r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
1138 : r = (r * 12.92);
1139
1140 g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
1141 : g = (g * 12.92);
1142
1143 b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
1144 : b = (b * 12.92);
1145
1146 r = Math.min(Math.max(0, r), 1);
1147 g = Math.min(Math.max(0, g), 1);
1148 b = Math.min(Math.max(0, b), 1);
1149
1150 return [r * 255, g * 255, b * 255];
1151}
1152
1153function xyz2lab(xyz) {
1154 var x = xyz[0],
1155 y = xyz[1],
1156 z = xyz[2],
1157 l, a, b;
1158
1159 x /= 95.047;
1160 y /= 100;
1161 z /= 108.883;
1162
1163 x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
1164 y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
1165 z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
1166
1167 l = (116 * y) - 16;
1168 a = 500 * (x - y);
1169 b = 200 * (y - z);
1170
1171 return [l, a, b];
1172}
1173
1174function xyz2lch(args) {
1175 return lab2lch(xyz2lab(args));
1176}
1177
1178function lab2xyz(lab) {
1179 var l = lab[0],
1180 a = lab[1],
1181 b = lab[2],
1182 x, y, z, y2;
1183
1184 if (l <= 8) {
1185 y = (l * 100) / 903.3;
1186 y2 = (7.787 * (y / 100)) + (16 / 116);
1187 } else {
1188 y = 100 * Math.pow((l + 16) / 116, 3);
1189 y2 = Math.pow(y / 100, 1/3);
1190 }
1191
1192 x = x / 95.047 <= 0.008856 ? x = (95.047 * ((a / 500) + y2 - (16 / 116))) / 7.787 : 95.047 * Math.pow((a / 500) + y2, 3);
1193
1194 z = z / 108.883 <= 0.008859 ? z = (108.883 * (y2 - (b / 200) - (16 / 116))) / 7.787 : 108.883 * Math.pow(y2 - (b / 200), 3);
1195
1196 return [x, y, z];
1197}
1198
1199function lab2lch(lab) {
1200 var l = lab[0],
1201 a = lab[1],
1202 b = lab[2],
1203 hr, h, c;
1204
1205 hr = Math.atan2(b, a);
1206 h = hr * 360 / 2 / Math.PI;
1207 if (h < 0) {
1208 h += 360;
1209 }
1210 c = Math.sqrt(a * a + b * b);
1211 return [l, c, h];
1212}
1213
1214function lab2rgb(args) {
1215 return xyz2rgb(lab2xyz(args));
1216}
1217
1218function lch2lab(lch) {
1219 var l = lch[0],
1220 c = lch[1],
1221 h = lch[2],
1222 a, b, hr;
1223
1224 hr = h / 360 * 2 * Math.PI;
1225 a = c * Math.cos(hr);
1226 b = c * Math.sin(hr);
1227 return [l, a, b];
1228}
1229
1230function lch2xyz(args) {
1231 return lab2xyz(lch2lab(args));
1232}
1233
1234function lch2rgb(args) {
1235 return lab2rgb(lch2lab(args));
1236}
1237
1238function keyword2rgb(keyword) {
1239 return cssKeywords[keyword];
1240}
1241
1242function keyword2hsl(args) {
1243 return rgb2hsl(keyword2rgb(args));
1244}
1245
1246function keyword2hsv(args) {
1247 return rgb2hsv(keyword2rgb(args));
1248}
1249
1250function keyword2hwb(args) {
1251 return rgb2hwb(keyword2rgb(args));
1252}
1253
1254function keyword2cmyk(args) {
1255 return rgb2cmyk(keyword2rgb(args));
1256}
1257
1258function keyword2lab(args) {
1259 return rgb2lab(keyword2rgb(args));
1260}
1261
1262function keyword2xyz(args) {
1263 return rgb2xyz(keyword2rgb(args));
1264}
1265
1266var cssKeywords = {
1267 aliceblue: [240,248,255],
1268 antiquewhite: [250,235,215],
1269 aqua: [0,255,255],
1270 aquamarine: [127,255,212],
1271 azure: [240,255,255],
1272 beige: [245,245,220],
1273 bisque: [255,228,196],
1274 black: [0,0,0],
1275 blanchedalmond: [255,235,205],
1276 blue: [0,0,255],
1277 blueviolet: [138,43,226],
1278 brown: [165,42,42],
1279 burlywood: [222,184,135],
1280 cadetblue: [95,158,160],
1281 chartreuse: [127,255,0],
1282 chocolate: [210,105,30],
1283 coral: [255,127,80],
1284 cornflowerblue: [100,149,237],
1285 cornsilk: [255,248,220],
1286 crimson: [220,20,60],
1287 cyan: [0,255,255],
1288 darkblue: [0,0,139],
1289 darkcyan: [0,139,139],
1290 darkgoldenrod: [184,134,11],
1291 darkgray: [169,169,169],
1292 darkgreen: [0,100,0],
1293 darkgrey: [169,169,169],
1294 darkkhaki: [189,183,107],
1295 darkmagenta: [139,0,139],
1296 darkolivegreen: [85,107,47],
1297 darkorange: [255,140,0],
1298 darkorchid: [153,50,204],
1299 darkred: [139,0,0],
1300 darksalmon: [233,150,122],
1301 darkseagreen: [143,188,143],
1302 darkslateblue: [72,61,139],
1303 darkslategray: [47,79,79],
1304 darkslategrey: [47,79,79],
1305 darkturquoise: [0,206,209],
1306 darkviolet: [148,0,211],
1307 deeppink: [255,20,147],
1308 deepskyblue: [0,191,255],
1309 dimgray: [105,105,105],
1310 dimgrey: [105,105,105],
1311 dodgerblue: [30,144,255],
1312 firebrick: [178,34,34],
1313 floralwhite: [255,250,240],
1314 forestgreen: [34,139,34],
1315 fuchsia: [255,0,255],
1316 gainsboro: [220,220,220],
1317 ghostwhite: [248,248,255],
1318 gold: [255,215,0],
1319 goldenrod: [218,165,32],
1320 gray: [128,128,128],
1321 green: [0,128,0],
1322 greenyellow: [173,255,47],
1323 grey: [128,128,128],
1324 honeydew: [240,255,240],
1325 hotpink: [255,105,180],
1326 indianred: [205,92,92],
1327 indigo: [75,0,130],
1328 ivory: [255,255,240],
1329 khaki: [240,230,140],
1330 lavender: [230,230,250],
1331 lavenderblush: [255,240,245],
1332 lawngreen: [124,252,0],
1333 lemonchiffon: [255,250,205],
1334 lightblue: [173,216,230],
1335 lightcoral: [240,128,128],
1336 lightcyan: [224,255,255],
1337 lightgoldenrodyellow: [250,250,210],
1338 lightgray: [211,211,211],
1339 lightgreen: [144,238,144],
1340 lightgrey: [211,211,211],
1341 lightpink: [255,182,193],
1342 lightsalmon: [255,160,122],
1343 lightseagreen: [32,178,170],
1344 lightskyblue: [135,206,250],
1345 lightslategray: [119,136,153],
1346 lightslategrey: [119,136,153],
1347 lightsteelblue: [176,196,222],
1348 lightyellow: [255,255,224],
1349 lime: [0,255,0],
1350 limegreen: [50,205,50],
1351 linen: [250,240,230],
1352 magenta: [255,0,255],
1353 maroon: [128,0,0],
1354 mediumaquamarine: [102,205,170],
1355 mediumblue: [0,0,205],
1356 mediumorchid: [186,85,211],
1357 mediumpurple: [147,112,219],
1358 mediumseagreen: [60,179,113],
1359 mediumslateblue: [123,104,238],
1360 mediumspringgreen: [0,250,154],
1361 mediumturquoise: [72,209,204],
1362 mediumvioletred: [199,21,133],
1363 midnightblue: [25,25,112],
1364 mintcream: [245,255,250],
1365 mistyrose: [255,228,225],
1366 moccasin: [255,228,181],
1367 navajowhite: [255,222,173],
1368 navy: [0,0,128],
1369 oldlace: [253,245,230],
1370 olive: [128,128,0],
1371 olivedrab: [107,142,35],
1372 orange: [255,165,0],
1373 orangered: [255,69,0],
1374 orchid: [218,112,214],
1375 palegoldenrod: [238,232,170],
1376 palegreen: [152,251,152],
1377 paleturquoise: [175,238,238],
1378 palevioletred: [219,112,147],
1379 papayawhip: [255,239,213],
1380 peachpuff: [255,218,185],
1381 peru: [205,133,63],
1382 pink: [255,192,203],
1383 plum: [221,160,221],
1384 powderblue: [176,224,230],
1385 purple: [128,0,128],
1386 rebeccapurple: [102, 51, 153],
1387 red: [255,0,0],
1388 rosybrown: [188,143,143],
1389 royalblue: [65,105,225],
1390 saddlebrown: [139,69,19],
1391 salmon: [250,128,114],
1392 sandybrown: [244,164,96],
1393 seagreen: [46,139,87],
1394 seashell: [255,245,238],
1395 sienna: [160,82,45],
1396 silver: [192,192,192],
1397 skyblue: [135,206,235],
1398 slateblue: [106,90,205],
1399 slategray: [112,128,144],
1400 slategrey: [112,128,144],
1401 snow: [255,250,250],
1402 springgreen: [0,255,127],
1403 steelblue: [70,130,180],
1404 tan: [210,180,140],
1405 teal: [0,128,128],
1406 thistle: [216,191,216],
1407 tomato: [255,99,71],
1408 turquoise: [64,224,208],
1409 violet: [238,130,238],
1410 wheat: [245,222,179],
1411 white: [255,255,255],
1412 whitesmoke: [245,245,245],
1413 yellow: [255,255,0],
1414 yellowgreen: [154,205,50]
1415};
1416
1417var reverseKeywords = {};
1418for (var key in cssKeywords) {
1419 reverseKeywords[JSON.stringify(cssKeywords[key])] = key;
1420}
1421
1422},{}],5:[function(require,module,exports){
1423var conversions = require(4);
1424
1425var convert = function() {
1426 return new Converter();
1427}
1428
1429for (var func in conversions) {
1430 // export Raw versions
1431 convert[func + "Raw"] = (function(func) {
1432 // accept array or plain args
1433 return function(arg) {
1434 if (typeof arg == "number")
1435 arg = Array.prototype.slice.call(arguments);
1436 return conversions[func](arg);
1437 }
1438 })(func);
1439
1440 var pair = /(\w+)2(\w+)/.exec(func),
1441 from = pair[1],
1442 to = pair[2];
1443
1444 // export rgb2hsl and ["rgb"]["hsl"]
1445 convert[from] = convert[from] || {};
1446
1447 convert[from][to] = convert[func] = (function(func) {
1448 return function(arg) {
1449 if (typeof arg == "number")
1450 arg = Array.prototype.slice.call(arguments);
1451
1452 var val = conversions[func](arg);
1453 if (typeof val == "string" || val === undefined)
1454 return val; // keyword
1455
1456 for (var i = 0; i < val.length; i++)
1457 val[i] = Math.round(val[i]);
1458 return val;
1459 }
1460 })(func);
1461}
1462
1463
1464/* Converter does lazy conversion and caching */
1465var Converter = function() {
1466 this.convs = {};
1467};
1468
1469/* Either get the values for a space or
1470 set the values for a space, depending on args */
1471Converter.prototype.routeSpace = function(space, args) {
1472 var values = args[0];
1473 if (values === undefined) {
1474 // color.rgb()
1475 return this.getValues(space);
1476 }
1477 // color.rgb(10, 10, 10)
1478 if (typeof values == "number") {
1479 values = Array.prototype.slice.call(args);
1480 }
1481
1482 return this.setValues(space, values);
1483};
1484
1485/* Set the values for a space, invalidating cache */
1486Converter.prototype.setValues = function(space, values) {
1487 this.space = space;
1488 this.convs = {};
1489 this.convs[space] = values;
1490 return this;
1491};
1492
1493/* Get the values for a space. If there's already
1494 a conversion for the space, fetch it, otherwise
1495 compute it */
1496Converter.prototype.getValues = function(space) {
1497 var vals = this.convs[space];
1498 if (!vals) {
1499 var fspace = this.space,
1500 from = this.convs[fspace];
1501 vals = convert[fspace][space](from);
1502
1503 this.convs[space] = vals;
1504 }
1505 return vals;
1506};
1507
1508["rgb", "hsl", "hsv", "cmyk", "keyword"].forEach(function(space) {
1509 Converter.prototype[space] = function(vals) {
1510 return this.routeSpace(space, arguments);
1511 }
1512});
1513
1514module.exports = convert;
1515},{"4":4}],6:[function(require,module,exports){
1516'use strict'
1517
1518module.exports = {
1519 "aliceblue": [240, 248, 255],
1520 "antiquewhite": [250, 235, 215],
1521 "aqua": [0, 255, 255],
1522 "aquamarine": [127, 255, 212],
1523 "azure": [240, 255, 255],
1524 "beige": [245, 245, 220],
1525 "bisque": [255, 228, 196],
1526 "black": [0, 0, 0],
1527 "blanchedalmond": [255, 235, 205],
1528 "blue": [0, 0, 255],
1529 "blueviolet": [138, 43, 226],
1530 "brown": [165, 42, 42],
1531 "burlywood": [222, 184, 135],
1532 "cadetblue": [95, 158, 160],
1533 "chartreuse": [127, 255, 0],
1534 "chocolate": [210, 105, 30],
1535 "coral": [255, 127, 80],
1536 "cornflowerblue": [100, 149, 237],
1537 "cornsilk": [255, 248, 220],
1538 "crimson": [220, 20, 60],
1539 "cyan": [0, 255, 255],
1540 "darkblue": [0, 0, 139],
1541 "darkcyan": [0, 139, 139],
1542 "darkgoldenrod": [184, 134, 11],
1543 "darkgray": [169, 169, 169],
1544 "darkgreen": [0, 100, 0],
1545 "darkgrey": [169, 169, 169],
1546 "darkkhaki": [189, 183, 107],
1547 "darkmagenta": [139, 0, 139],
1548 "darkolivegreen": [85, 107, 47],
1549 "darkorange": [255, 140, 0],
1550 "darkorchid": [153, 50, 204],
1551 "darkred": [139, 0, 0],
1552 "darksalmon": [233, 150, 122],
1553 "darkseagreen": [143, 188, 143],
1554 "darkslateblue": [72, 61, 139],
1555 "darkslategray": [47, 79, 79],
1556 "darkslategrey": [47, 79, 79],
1557 "darkturquoise": [0, 206, 209],
1558 "darkviolet": [148, 0, 211],
1559 "deeppink": [255, 20, 147],
1560 "deepskyblue": [0, 191, 255],
1561 "dimgray": [105, 105, 105],
1562 "dimgrey": [105, 105, 105],
1563 "dodgerblue": [30, 144, 255],
1564 "firebrick": [178, 34, 34],
1565 "floralwhite": [255, 250, 240],
1566 "forestgreen": [34, 139, 34],
1567 "fuchsia": [255, 0, 255],
1568 "gainsboro": [220, 220, 220],
1569 "ghostwhite": [248, 248, 255],
1570 "gold": [255, 215, 0],
1571 "goldenrod": [218, 165, 32],
1572 "gray": [128, 128, 128],
1573 "green": [0, 128, 0],
1574 "greenyellow": [173, 255, 47],
1575 "grey": [128, 128, 128],
1576 "honeydew": [240, 255, 240],
1577 "hotpink": [255, 105, 180],
1578 "indianred": [205, 92, 92],
1579 "indigo": [75, 0, 130],
1580 "ivory": [255, 255, 240],
1581 "khaki": [240, 230, 140],
1582 "lavender": [230, 230, 250],
1583 "lavenderblush": [255, 240, 245],
1584 "lawngreen": [124, 252, 0],
1585 "lemonchiffon": [255, 250, 205],
1586 "lightblue": [173, 216, 230],
1587 "lightcoral": [240, 128, 128],
1588 "lightcyan": [224, 255, 255],
1589 "lightgoldenrodyellow": [250, 250, 210],
1590 "lightgray": [211, 211, 211],
1591 "lightgreen": [144, 238, 144],
1592 "lightgrey": [211, 211, 211],
1593 "lightpink": [255, 182, 193],
1594 "lightsalmon": [255, 160, 122],
1595 "lightseagreen": [32, 178, 170],
1596 "lightskyblue": [135, 206, 250],
1597 "lightslategray": [119, 136, 153],
1598 "lightslategrey": [119, 136, 153],
1599 "lightsteelblue": [176, 196, 222],
1600 "lightyellow": [255, 255, 224],
1601 "lime": [0, 255, 0],
1602 "limegreen": [50, 205, 50],
1603 "linen": [250, 240, 230],
1604 "magenta": [255, 0, 255],
1605 "maroon": [128, 0, 0],
1606 "mediumaquamarine": [102, 205, 170],
1607 "mediumblue": [0, 0, 205],
1608 "mediumorchid": [186, 85, 211],
1609 "mediumpurple": [147, 112, 219],
1610 "mediumseagreen": [60, 179, 113],
1611 "mediumslateblue": [123, 104, 238],
1612 "mediumspringgreen": [0, 250, 154],
1613 "mediumturquoise": [72, 209, 204],
1614 "mediumvioletred": [199, 21, 133],
1615 "midnightblue": [25, 25, 112],
1616 "mintcream": [245, 255, 250],
1617 "mistyrose": [255, 228, 225],
1618 "moccasin": [255, 228, 181],
1619 "navajowhite": [255, 222, 173],
1620 "navy": [0, 0, 128],
1621 "oldlace": [253, 245, 230],
1622 "olive": [128, 128, 0],
1623 "olivedrab": [107, 142, 35],
1624 "orange": [255, 165, 0],
1625 "orangered": [255, 69, 0],
1626 "orchid": [218, 112, 214],
1627 "palegoldenrod": [238, 232, 170],
1628 "palegreen": [152, 251, 152],
1629 "paleturquoise": [175, 238, 238],
1630 "palevioletred": [219, 112, 147],
1631 "papayawhip": [255, 239, 213],
1632 "peachpuff": [255, 218, 185],
1633 "peru": [205, 133, 63],
1634 "pink": [255, 192, 203],
1635 "plum": [221, 160, 221],
1636 "powderblue": [176, 224, 230],
1637 "purple": [128, 0, 128],
1638 "rebeccapurple": [102, 51, 153],
1639 "red": [255, 0, 0],
1640 "rosybrown": [188, 143, 143],
1641 "royalblue": [65, 105, 225],
1642 "saddlebrown": [139, 69, 19],
1643 "salmon": [250, 128, 114],
1644 "sandybrown": [244, 164, 96],
1645 "seagreen": [46, 139, 87],
1646 "seashell": [255, 245, 238],
1647 "sienna": [160, 82, 45],
1648 "silver": [192, 192, 192],
1649 "skyblue": [135, 206, 235],
1650 "slateblue": [106, 90, 205],
1651 "slategray": [112, 128, 144],
1652 "slategrey": [112, 128, 144],
1653 "snow": [255, 250, 250],
1654 "springgreen": [0, 255, 127],
1655 "steelblue": [70, 130, 180],
1656 "tan": [210, 180, 140],
1657 "teal": [0, 128, 128],
1658 "thistle": [216, 191, 216],
1659 "tomato": [255, 99, 71],
1660 "turquoise": [64, 224, 208],
1661 "violet": [238, 130, 238],
1662 "wheat": [245, 222, 179],
1663 "white": [255, 255, 255],
1664 "whitesmoke": [245, 245, 245],
1665 "yellow": [255, 255, 0],
1666 "yellowgreen": [154, 205, 50]
1667};
1668
1669},{}],7:[function(require,module,exports){
1670/**
1671 * @namespace Chart
1672 */
1673var Chart = require(30)();
1674
1675Chart.helpers = require(46);
1676
1677// @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
1678require(28)(Chart);
1679
1680Chart.Animation = require(22);
1681Chart.animationService = require(23);
1682Chart.defaults = require(26);
1683Chart.Element = require(27);
1684Chart.elements = require(41);
1685Chart.Interaction = require(29);
1686Chart.layouts = require(31);
1687Chart.platform = require(49);
1688Chart.plugins = require(32);
1689Chart.Scale = require(33);
1690Chart.scaleService = require(34);
1691Chart.Ticks = require(35);
1692Chart.Tooltip = require(36);
1693
1694require(24)(Chart);
1695require(25)(Chart);
1696
1697require(56)(Chart);
1698require(54)(Chart);
1699require(55)(Chart);
1700require(57)(Chart);
1701require(58)(Chart);
1702require(59)(Chart);
1703
1704// Controllers must be loaded after elements
1705// See Chart.core.datasetController.dataElementType
1706require(15)(Chart);
1707require(16)(Chart);
1708require(17)(Chart);
1709require(18)(Chart);
1710require(19)(Chart);
1711require(20)(Chart);
1712require(21)(Chart);
1713
1714require(8)(Chart);
1715require(9)(Chart);
1716require(10)(Chart);
1717require(11)(Chart);
1718require(12)(Chart);
1719require(13)(Chart);
1720require(14)(Chart);
1721
1722// Loading built-in plugins
1723var plugins = require(50);
1724for (var k in plugins) {
1725 if (plugins.hasOwnProperty(k)) {
1726 Chart.plugins.register(plugins[k]);
1727 }
1728}
1729
1730Chart.platform.initialize();
1731
1732module.exports = Chart;
1733if (typeof window !== 'undefined') {
1734 window.Chart = Chart;
1735}
1736
1737// DEPRECATIONS
1738
1739/**
1740 * Provided for backward compatibility, not available anymore
1741 * @namespace Chart.Legend
1742 * @deprecated since version 2.1.5
1743 * @todo remove at version 3
1744 * @private
1745 */
1746Chart.Legend = plugins.legend._element;
1747
1748/**
1749 * Provided for backward compatibility, not available anymore
1750 * @namespace Chart.Title
1751 * @deprecated since version 2.1.5
1752 * @todo remove at version 3
1753 * @private
1754 */
1755Chart.Title = plugins.title._element;
1756
1757/**
1758 * Provided for backward compatibility, use Chart.plugins instead
1759 * @namespace Chart.pluginService
1760 * @deprecated since version 2.1.5
1761 * @todo remove at version 3
1762 * @private
1763 */
1764Chart.pluginService = Chart.plugins;
1765
1766/**
1767 * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
1768 * effect, instead simply create/register plugins via plain JavaScript objects.
1769 * @interface Chart.PluginBase
1770 * @deprecated since version 2.5.0
1771 * @todo remove at version 3
1772 * @private
1773 */
1774Chart.PluginBase = Chart.Element.extend({});
1775
1776/**
1777 * Provided for backward compatibility, use Chart.helpers.canvas instead.
1778 * @namespace Chart.canvasHelpers
1779 * @deprecated since version 2.6.0
1780 * @todo remove at version 3
1781 * @private
1782 */
1783Chart.canvasHelpers = Chart.helpers.canvas;
1784
1785/**
1786 * Provided for backward compatibility, use Chart.layouts instead.
1787 * @namespace Chart.layoutService
1788 * @deprecated since version 2.8.0
1789 * @todo remove at version 3
1790 * @private
1791 */
1792Chart.layoutService = Chart.layouts;
1793
1794},{"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,"34":34,"35":35,"36":36,"41":41,"46":46,"49":49,"50":50,"54":54,"55":55,"56":56,"57":57,"58":58,"59":59,"8":8,"9":9}],8:[function(require,module,exports){
1795'use strict';
1796
1797module.exports = function(Chart) {
1798
1799 Chart.Bar = function(context, config) {
1800 config.type = 'bar';
1801
1802 return new Chart(context, config);
1803 };
1804
1805};
1806
1807},{}],9:[function(require,module,exports){
1808'use strict';
1809
1810module.exports = function(Chart) {
1811
1812 Chart.Bubble = function(context, config) {
1813 config.type = 'bubble';
1814 return new Chart(context, config);
1815 };
1816
1817};
1818
1819},{}],10:[function(require,module,exports){
1820'use strict';
1821
1822module.exports = function(Chart) {
1823
1824 Chart.Doughnut = function(context, config) {
1825 config.type = 'doughnut';
1826
1827 return new Chart(context, config);
1828 };
1829
1830};
1831
1832},{}],11:[function(require,module,exports){
1833'use strict';
1834
1835module.exports = function(Chart) {
1836
1837 Chart.Line = function(context, config) {
1838 config.type = 'line';
1839
1840 return new Chart(context, config);
1841 };
1842
1843};
1844
1845},{}],12:[function(require,module,exports){
1846'use strict';
1847
1848module.exports = function(Chart) {
1849
1850 Chart.PolarArea = function(context, config) {
1851 config.type = 'polarArea';
1852
1853 return new Chart(context, config);
1854 };
1855
1856};
1857
1858},{}],13:[function(require,module,exports){
1859'use strict';
1860
1861module.exports = function(Chart) {
1862
1863 Chart.Radar = function(context, config) {
1864 config.type = 'radar';
1865
1866 return new Chart(context, config);
1867 };
1868
1869};
1870
1871},{}],14:[function(require,module,exports){
1872'use strict';
1873
1874module.exports = function(Chart) {
1875 Chart.Scatter = function(context, config) {
1876 config.type = 'scatter';
1877 return new Chart(context, config);
1878 };
1879};
1880
1881},{}],15:[function(require,module,exports){
1882'use strict';
1883
1884var defaults = require(26);
1885var elements = require(41);
1886var helpers = require(46);
1887
1888defaults._set('bar', {
1889 hover: {
1890 mode: 'label'
1891 },
1892
1893 scales: {
1894 xAxes: [{
1895 type: 'category',
1896
1897 // Specific to Bar Controller
1898 categoryPercentage: 0.8,
1899 barPercentage: 0.9,
1900
1901 // offset settings
1902 offset: true,
1903
1904 // grid line settings
1905 gridLines: {
1906 offsetGridLines: true
1907 }
1908 }],
1909
1910 yAxes: [{
1911 type: 'linear'
1912 }]
1913 }
1914});
1915
1916defaults._set('horizontalBar', {
1917 hover: {
1918 mode: 'index',
1919 axis: 'y'
1920 },
1921
1922 scales: {
1923 xAxes: [{
1924 type: 'linear',
1925 position: 'bottom'
1926 }],
1927
1928 yAxes: [{
1929 position: 'left',
1930 type: 'category',
1931
1932 // Specific to Horizontal Bar Controller
1933 categoryPercentage: 0.8,
1934 barPercentage: 0.9,
1935
1936 // offset settings
1937 offset: true,
1938
1939 // grid line settings
1940 gridLines: {
1941 offsetGridLines: true
1942 }
1943 }]
1944 },
1945
1946 elements: {
1947 rectangle: {
1948 borderSkipped: 'left'
1949 }
1950 },
1951
1952 tooltips: {
1953 callbacks: {
1954 title: function(item, data) {
1955 // Pick first xLabel for now
1956 var title = '';
1957
1958 if (item.length > 0) {
1959 if (item[0].yLabel) {
1960 title = item[0].yLabel;
1961 } else if (data.labels.length > 0 && item[0].index < data.labels.length) {
1962 title = data.labels[item[0].index];
1963 }
1964 }
1965
1966 return title;
1967 },
1968
1969 label: function(item, data) {
1970 var datasetLabel = data.datasets[item.datasetIndex].label || '';
1971 return datasetLabel + ': ' + item.xLabel;
1972 }
1973 },
1974 mode: 'index',
1975 axis: 'y'
1976 }
1977});
1978
1979/**
1980 * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
1981 * @private
1982 */
1983function computeMinSampleSize(scale, pixels) {
1984 var min = scale.isHorizontal() ? scale.width : scale.height;
1985 var ticks = scale.getTicks();
1986 var prev, curr, i, ilen;
1987
1988 for (i = 1, ilen = pixels.length; i < ilen; ++i) {
1989 min = Math.min(min, pixels[i] - pixels[i - 1]);
1990 }
1991
1992 for (i = 0, ilen = ticks.length; i < ilen; ++i) {
1993 curr = scale.getPixelForTick(i);
1994 min = i > 0 ? Math.min(min, curr - prev) : min;
1995 prev = curr;
1996 }
1997
1998 return min;
1999}
2000
2001/**
2002 * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
2003 * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
2004 * mode currently always generates bars equally sized (until we introduce scriptable options?).
2005 * @private
2006 */
2007function computeFitCategoryTraits(index, ruler, options) {
2008 var thickness = options.barThickness;
2009 var count = ruler.stackCount;
2010 var curr = ruler.pixels[index];
2011 var size, ratio;
2012
2013 if (helpers.isNullOrUndef(thickness)) {
2014 size = ruler.min * options.categoryPercentage;
2015 ratio = options.barPercentage;
2016 } else {
2017 // When bar thickness is enforced, category and bar percentages are ignored.
2018 // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
2019 // and deprecate barPercentage since this value is ignored when thickness is absolute.
2020 size = thickness * count;
2021 ratio = 1;
2022 }
2023
2024 return {
2025 chunk: size / count,
2026 ratio: ratio,
2027 start: curr - (size / 2)
2028 };
2029}
2030
2031/**
2032 * Computes an "optimal" category that globally arranges bars side by side (no gap when
2033 * percentage options are 1), based on the previous and following categories. This mode
2034 * generates bars with different widths when data are not evenly spaced.
2035 * @private
2036 */
2037function computeFlexCategoryTraits(index, ruler, options) {
2038 var pixels = ruler.pixels;
2039 var curr = pixels[index];
2040 var prev = index > 0 ? pixels[index - 1] : null;
2041 var next = index < pixels.length - 1 ? pixels[index + 1] : null;
2042 var percent = options.categoryPercentage;
2043 var start, size;
2044
2045 if (prev === null) {
2046 // first data: its size is double based on the next point or,
2047 // if it's also the last data, we use the scale end extremity.
2048 prev = curr - (next === null ? ruler.end - curr : next - curr);
2049 }
2050
2051 if (next === null) {
2052 // last data: its size is also double based on the previous point.
2053 next = curr + curr - prev;
2054 }
2055
2056 start = curr - ((curr - prev) / 2) * percent;
2057 size = ((next - prev) / 2) * percent;
2058
2059 return {
2060 chunk: size / ruler.stackCount,
2061 ratio: options.barPercentage,
2062 start: start
2063 };
2064}
2065
2066module.exports = function(Chart) {
2067
2068 Chart.controllers.bar = Chart.DatasetController.extend({
2069
2070 dataElementType: elements.Rectangle,
2071
2072 initialize: function() {
2073 var me = this;
2074 var meta;
2075
2076 Chart.DatasetController.prototype.initialize.apply(me, arguments);
2077
2078 meta = me.getMeta();
2079 meta.stack = me.getDataset().stack;
2080 meta.bar = true;
2081 },
2082
2083 update: function(reset) {
2084 var me = this;
2085 var rects = me.getMeta().data;
2086 var i, ilen;
2087
2088 me._ruler = me.getRuler();
2089
2090 for (i = 0, ilen = rects.length; i < ilen; ++i) {
2091 me.updateElement(rects[i], i, reset);
2092 }
2093 },
2094
2095 updateElement: function(rectangle, index, reset) {
2096 var me = this;
2097 var chart = me.chart;
2098 var meta = me.getMeta();
2099 var dataset = me.getDataset();
2100 var custom = rectangle.custom || {};
2101 var rectangleOptions = chart.options.elements.rectangle;
2102
2103 rectangle._xScale = me.getScaleForId(meta.xAxisID);
2104 rectangle._yScale = me.getScaleForId(meta.yAxisID);
2105 rectangle._datasetIndex = me.index;
2106 rectangle._index = index;
2107
2108 rectangle._model = {
2109 datasetLabel: dataset.label,
2110 label: chart.data.labels[index],
2111 borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleOptions.borderSkipped,
2112 backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.backgroundColor, index, rectangleOptions.backgroundColor),
2113 borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.borderColor, index, rectangleOptions.borderColor),
2114 borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.borderWidth, index, rectangleOptions.borderWidth)
2115 };
2116
2117 me.updateElementGeometry(rectangle, index, reset);
2118
2119 rectangle.pivot();
2120 },
2121
2122 /**
2123 * @private
2124 */
2125 updateElementGeometry: function(rectangle, index, reset) {
2126 var me = this;
2127 var model = rectangle._model;
2128 var vscale = me.getValueScale();
2129 var base = vscale.getBasePixel();
2130 var horizontal = vscale.isHorizontal();
2131 var ruler = me._ruler || me.getRuler();
2132 var vpixels = me.calculateBarValuePixels(me.index, index);
2133 var ipixels = me.calculateBarIndexPixels(me.index, index, ruler);
2134
2135 model.horizontal = horizontal;
2136 model.base = reset ? base : vpixels.base;
2137 model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
2138 model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
2139 model.height = horizontal ? ipixels.size : undefined;
2140 model.width = horizontal ? undefined : ipixels.size;
2141 },
2142
2143 /**
2144 * @private
2145 */
2146 getValueScaleId: function() {
2147 return this.getMeta().yAxisID;
2148 },
2149
2150 /**
2151 * @private
2152 */
2153 getIndexScaleId: function() {
2154 return this.getMeta().xAxisID;
2155 },
2156
2157 /**
2158 * @private
2159 */
2160 getValueScale: function() {
2161 return this.getScaleForId(this.getValueScaleId());
2162 },
2163
2164 /**
2165 * @private
2166 */
2167 getIndexScale: function() {
2168 return this.getScaleForId(this.getIndexScaleId());
2169 },
2170
2171 /**
2172 * Returns the stacks based on groups and bar visibility.
2173 * @param {Number} [last] - The dataset index
2174 * @returns {Array} The stack list
2175 * @private
2176 */
2177 _getStacks: function(last) {
2178 var me = this;
2179 var chart = me.chart;
2180 var scale = me.getIndexScale();
2181 var stacked = scale.options.stacked;
2182 var ilen = last === undefined ? chart.data.datasets.length : last + 1;
2183 var stacks = [];
2184 var i, meta;
2185
2186 for (i = 0; i < ilen; ++i) {
2187 meta = chart.getDatasetMeta(i);
2188 if (meta.bar && chart.isDatasetVisible(i) &&
2189 (stacked === false ||
2190 (stacked === true && stacks.indexOf(meta.stack) === -1) ||
2191 (stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) {
2192 stacks.push(meta.stack);
2193 }
2194 }
2195
2196 return stacks;
2197 },
2198
2199 /**
2200 * Returns the effective number of stacks based on groups and bar visibility.
2201 * @private
2202 */
2203 getStackCount: function() {
2204 return this._getStacks().length;
2205 },
2206
2207 /**
2208 * Returns the stack index for the given dataset based on groups and bar visibility.
2209 * @param {Number} [datasetIndex] - The dataset index
2210 * @param {String} [name] - The stack name to find
2211 * @returns {Number} The stack index
2212 * @private
2213 */
2214 getStackIndex: function(datasetIndex, name) {
2215 var stacks = this._getStacks(datasetIndex);
2216 var index = (name !== undefined)
2217 ? stacks.indexOf(name)
2218 : -1; // indexOf returns -1 if element is not present
2219
2220 return (index === -1)
2221 ? stacks.length - 1
2222 : index;
2223 },
2224
2225 /**
2226 * @private
2227 */
2228 getRuler: function() {
2229 var me = this;
2230 var scale = me.getIndexScale();
2231 var stackCount = me.getStackCount();
2232 var datasetIndex = me.index;
2233 var isHorizontal = scale.isHorizontal();
2234 var start = isHorizontal ? scale.left : scale.top;
2235 var end = start + (isHorizontal ? scale.width : scale.height);
2236 var pixels = [];
2237 var i, ilen, min;
2238
2239 for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
2240 pixels.push(scale.getPixelForValue(null, i, datasetIndex));
2241 }
2242
2243 min = helpers.isNullOrUndef(scale.options.barThickness)
2244 ? computeMinSampleSize(scale, pixels)
2245 : -1;
2246
2247 return {
2248 min: min,
2249 pixels: pixels,
2250 start: start,
2251 end: end,
2252 stackCount: stackCount,
2253 scale: scale
2254 };
2255 },
2256
2257 /**
2258 * Note: pixel values are not clamped to the scale area.
2259 * @private
2260 */
2261 calculateBarValuePixels: function(datasetIndex, index) {
2262 var me = this;
2263 var chart = me.chart;
2264 var meta = me.getMeta();
2265 var scale = me.getValueScale();
2266 var datasets = chart.data.datasets;
2267 var value = scale.getRightValue(datasets[datasetIndex].data[index]);
2268 var stacked = scale.options.stacked;
2269 var stack = meta.stack;
2270 var start = 0;
2271 var i, imeta, ivalue, base, head, size;
2272
2273 if (stacked || (stacked === undefined && stack !== undefined)) {
2274 for (i = 0; i < datasetIndex; ++i) {
2275 imeta = chart.getDatasetMeta(i);
2276
2277 if (imeta.bar &&
2278 imeta.stack === stack &&
2279 imeta.controller.getValueScaleId() === scale.id &&
2280 chart.isDatasetVisible(i)) {
2281
2282 ivalue = scale.getRightValue(datasets[i].data[index]);
2283 if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) {
2284 start += ivalue;
2285 }
2286 }
2287 }
2288 }
2289
2290 base = scale.getPixelForValue(start);
2291 head = scale.getPixelForValue(start + value);
2292 size = (head - base) / 2;
2293
2294 return {
2295 size: size,
2296 base: base,
2297 head: head,
2298 center: head + size / 2
2299 };
2300 },
2301
2302 /**
2303 * @private
2304 */
2305 calculateBarIndexPixels: function(datasetIndex, index, ruler) {
2306 var me = this;
2307 var options = ruler.scale.options;
2308 var range = options.barThickness === 'flex'
2309 ? computeFlexCategoryTraits(index, ruler, options)
2310 : computeFitCategoryTraits(index, ruler, options);
2311
2312 var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
2313 var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
2314 var size = Math.min(
2315 helpers.valueOrDefault(options.maxBarThickness, Infinity),
2316 range.chunk * range.ratio);
2317
2318 return {
2319 base: center - size / 2,
2320 head: center + size / 2,
2321 center: center,
2322 size: size
2323 };
2324 },
2325
2326 draw: function() {
2327 var me = this;
2328 var chart = me.chart;
2329 var scale = me.getValueScale();
2330 var rects = me.getMeta().data;
2331 var dataset = me.getDataset();
2332 var ilen = rects.length;
2333 var i = 0;
2334
2335 helpers.canvas.clipArea(chart.ctx, chart.chartArea);
2336
2337 for (; i < ilen; ++i) {
2338 if (!isNaN(scale.getRightValue(dataset.data[i]))) {
2339 rects[i].draw();
2340 }
2341 }
2342
2343 helpers.canvas.unclipArea(chart.ctx);
2344 },
2345
2346 setHoverStyle: function(rectangle) {
2347 var dataset = this.chart.data.datasets[rectangle._datasetIndex];
2348 var index = rectangle._index;
2349 var custom = rectangle.custom || {};
2350 var model = rectangle._model;
2351
2352 model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.valueAtIndexOrDefault(dataset.hoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
2353 model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.valueAtIndexOrDefault(dataset.hoverBorderColor, index, helpers.getHoverColor(model.borderColor));
2354 model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.valueAtIndexOrDefault(dataset.hoverBorderWidth, index, model.borderWidth);
2355 },
2356
2357 removeHoverStyle: function(rectangle) {
2358 var dataset = this.chart.data.datasets[rectangle._datasetIndex];
2359 var index = rectangle._index;
2360 var custom = rectangle.custom || {};
2361 var model = rectangle._model;
2362 var rectangleElementOptions = this.chart.options.elements.rectangle;
2363
2364 model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor);
2365 model.borderColor = custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor);
2366 model.borderWidth = custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.borderWidth, index, rectangleElementOptions.borderWidth);
2367 }
2368 });
2369
2370 Chart.controllers.horizontalBar = Chart.controllers.bar.extend({
2371 /**
2372 * @private
2373 */
2374 getValueScaleId: function() {
2375 return this.getMeta().xAxisID;
2376 },
2377
2378 /**
2379 * @private
2380 */
2381 getIndexScaleId: function() {
2382 return this.getMeta().yAxisID;
2383 }
2384 });
2385};
2386
2387},{"26":26,"41":41,"46":46}],16:[function(require,module,exports){
2388'use strict';
2389
2390var defaults = require(26);
2391var elements = require(41);
2392var helpers = require(46);
2393
2394defaults._set('bubble', {
2395 hover: {
2396 mode: 'single'
2397 },
2398
2399 scales: {
2400 xAxes: [{
2401 type: 'linear', // bubble should probably use a linear scale by default
2402 position: 'bottom',
2403 id: 'x-axis-0' // need an ID so datasets can reference the scale
2404 }],
2405 yAxes: [{
2406 type: 'linear',
2407 position: 'left',
2408 id: 'y-axis-0'
2409 }]
2410 },
2411
2412 tooltips: {
2413 callbacks: {
2414 title: function() {
2415 // Title doesn't make sense for scatter since we format the data as a point
2416 return '';
2417 },
2418 label: function(item, data) {
2419 var datasetLabel = data.datasets[item.datasetIndex].label || '';
2420 var dataPoint = data.datasets[item.datasetIndex].data[item.index];
2421 return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
2422 }
2423 }
2424 }
2425});
2426
2427
2428module.exports = function(Chart) {
2429
2430 Chart.controllers.bubble = Chart.DatasetController.extend({
2431 /**
2432 * @protected
2433 */
2434 dataElementType: elements.Point,
2435
2436 /**
2437 * @protected
2438 */
2439 update: function(reset) {
2440 var me = this;
2441 var meta = me.getMeta();
2442 var points = meta.data;
2443
2444 // Update Points
2445 helpers.each(points, function(point, index) {
2446 me.updateElement(point, index, reset);
2447 });
2448 },
2449
2450 /**
2451 * @protected
2452 */
2453 updateElement: function(point, index, reset) {
2454 var me = this;
2455 var meta = me.getMeta();
2456 var custom = point.custom || {};
2457 var xScale = me.getScaleForId(meta.xAxisID);
2458 var yScale = me.getScaleForId(meta.yAxisID);
2459 var options = me._resolveElementOptions(point, index);
2460 var data = me.getDataset().data[index];
2461 var dsIndex = me.index;
2462
2463 var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
2464 var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
2465
2466 point._xScale = xScale;
2467 point._yScale = yScale;
2468 point._options = options;
2469 point._datasetIndex = dsIndex;
2470 point._index = index;
2471 point._model = {
2472 backgroundColor: options.backgroundColor,
2473 borderColor: options.borderColor,
2474 borderWidth: options.borderWidth,
2475 hitRadius: options.hitRadius,
2476 pointStyle: options.pointStyle,
2477 radius: reset ? 0 : options.radius,
2478 skip: custom.skip || isNaN(x) || isNaN(y),
2479 x: x,
2480 y: y,
2481 };
2482
2483 point.pivot();
2484 },
2485
2486 /**
2487 * @protected
2488 */
2489 setHoverStyle: function(point) {
2490 var model = point._model;
2491 var options = point._options;
2492
2493 model.backgroundColor = helpers.valueOrDefault(options.hoverBackgroundColor, helpers.getHoverColor(options.backgroundColor));
2494 model.borderColor = helpers.valueOrDefault(options.hoverBorderColor, helpers.getHoverColor(options.borderColor));
2495 model.borderWidth = helpers.valueOrDefault(options.hoverBorderWidth, options.borderWidth);
2496 model.radius = options.radius + options.hoverRadius;
2497 },
2498
2499 /**
2500 * @protected
2501 */
2502 removeHoverStyle: function(point) {
2503 var model = point._model;
2504 var options = point._options;
2505
2506 model.backgroundColor = options.backgroundColor;
2507 model.borderColor = options.borderColor;
2508 model.borderWidth = options.borderWidth;
2509 model.radius = options.radius;
2510 },
2511
2512 /**
2513 * @private
2514 */
2515 _resolveElementOptions: function(point, index) {
2516 var me = this;
2517 var chart = me.chart;
2518 var datasets = chart.data.datasets;
2519 var dataset = datasets[me.index];
2520 var custom = point.custom || {};
2521 var options = chart.options.elements.point;
2522 var resolve = helpers.options.resolve;
2523 var data = dataset.data[index];
2524 var values = {};
2525 var i, ilen, key;
2526
2527 // Scriptable options
2528 var context = {
2529 chart: chart,
2530 dataIndex: index,
2531 dataset: dataset,
2532 datasetIndex: me.index
2533 };
2534
2535 var keys = [
2536 'backgroundColor',
2537 'borderColor',
2538 'borderWidth',
2539 'hoverBackgroundColor',
2540 'hoverBorderColor',
2541 'hoverBorderWidth',
2542 'hoverRadius',
2543 'hitRadius',
2544 'pointStyle'
2545 ];
2546
2547 for (i = 0, ilen = keys.length; i < ilen; ++i) {
2548 key = keys[i];
2549 values[key] = resolve([
2550 custom[key],
2551 dataset[key],
2552 options[key]
2553 ], context, index);
2554 }
2555
2556 // Custom radius resolution
2557 values.radius = resolve([
2558 custom.radius,
2559 data ? data.r : undefined,
2560 dataset.radius,
2561 options.radius
2562 ], context, index);
2563
2564 return values;
2565 }
2566 });
2567};
2568
2569},{"26":26,"41":41,"46":46}],17:[function(require,module,exports){
2570'use strict';
2571
2572var defaults = require(26);
2573var elements = require(41);
2574var helpers = require(46);
2575
2576defaults._set('doughnut', {
2577 animation: {
2578 // Boolean - Whether we animate the rotation of the Doughnut
2579 animateRotate: true,
2580 // Boolean - Whether we animate scaling the Doughnut from the centre
2581 animateScale: false
2582 },
2583 hover: {
2584 mode: 'single'
2585 },
2586 legendCallback: function(chart) {
2587 var text = [];
2588 text.push('<ul class="' + chart.id + '-legend">');
2589
2590 var data = chart.data;
2591 var datasets = data.datasets;
2592 var labels = data.labels;
2593
2594 if (datasets.length) {
2595 for (var i = 0; i < datasets[0].data.length; ++i) {
2596 text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
2597 if (labels[i]) {
2598 text.push(labels[i]);
2599 }
2600 text.push('</li>');
2601 }
2602 }
2603
2604 text.push('</ul>');
2605 return text.join('');
2606 },
2607 legend: {
2608 labels: {
2609 generateLabels: function(chart) {
2610 var data = chart.data;
2611 if (data.labels.length && data.datasets.length) {
2612 return data.labels.map(function(label, i) {
2613 var meta = chart.getDatasetMeta(0);
2614 var ds = data.datasets[0];
2615 var arc = meta.data[i];
2616 var custom = arc && arc.custom || {};
2617 var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
2618 var arcOpts = chart.options.elements.arc;
2619 var fill = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
2620 var stroke = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
2621 var bw = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
2622
2623 return {
2624 text: label,
2625 fillStyle: fill,
2626 strokeStyle: stroke,
2627 lineWidth: bw,
2628 hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
2629
2630 // Extra data used for toggling the correct item
2631 index: i
2632 };
2633 });
2634 }
2635 return [];
2636 }
2637 },
2638
2639 onClick: function(e, legendItem) {
2640 var index = legendItem.index;
2641 var chart = this.chart;
2642 var i, ilen, meta;
2643
2644 for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
2645 meta = chart.getDatasetMeta(i);
2646 // toggle visibility of index if exists
2647 if (meta.data[index]) {
2648 meta.data[index].hidden = !meta.data[index].hidden;
2649 }
2650 }
2651
2652 chart.update();
2653 }
2654 },
2655
2656 // The percentage of the chart that we cut out of the middle.
2657 cutoutPercentage: 50,
2658
2659 // The rotation of the chart, where the first data arc begins.
2660 rotation: Math.PI * -0.5,
2661
2662 // The total circumference of the chart.
2663 circumference: Math.PI * 2.0,
2664
2665 // Need to override these to give a nice default
2666 tooltips: {
2667 callbacks: {
2668 title: function() {
2669 return '';
2670 },
2671 label: function(tooltipItem, data) {
2672 var dataLabel = data.labels[tooltipItem.index];
2673 var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
2674
2675 if (helpers.isArray(dataLabel)) {
2676 // show value on first line of multiline label
2677 // need to clone because we are changing the value
2678 dataLabel = dataLabel.slice();
2679 dataLabel[0] += value;
2680 } else {
2681 dataLabel += value;
2682 }
2683
2684 return dataLabel;
2685 }
2686 }
2687 }
2688});
2689
2690defaults._set('pie', helpers.clone(defaults.doughnut));
2691defaults._set('pie', {
2692 cutoutPercentage: 0
2693});
2694
2695module.exports = function(Chart) {
2696
2697 Chart.controllers.doughnut = Chart.controllers.pie = Chart.DatasetController.extend({
2698
2699 dataElementType: elements.Arc,
2700
2701 linkScales: helpers.noop,
2702
2703 // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
2704 getRingIndex: function(datasetIndex) {
2705 var ringIndex = 0;
2706
2707 for (var j = 0; j < datasetIndex; ++j) {
2708 if (this.chart.isDatasetVisible(j)) {
2709 ++ringIndex;
2710 }
2711 }
2712
2713 return ringIndex;
2714 },
2715
2716 update: function(reset) {
2717 var me = this;
2718 var chart = me.chart;
2719 var chartArea = chart.chartArea;
2720 var opts = chart.options;
2721 var arcOpts = opts.elements.arc;
2722 var availableWidth = chartArea.right - chartArea.left - arcOpts.borderWidth;
2723 var availableHeight = chartArea.bottom - chartArea.top - arcOpts.borderWidth;
2724 var minSize = Math.min(availableWidth, availableHeight);
2725 var offset = {x: 0, y: 0};
2726 var meta = me.getMeta();
2727 var cutoutPercentage = opts.cutoutPercentage;
2728 var circumference = opts.circumference;
2729
2730 // If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc
2731 if (circumference < Math.PI * 2.0) {
2732 var startAngle = opts.rotation % (Math.PI * 2.0);
2733 startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0);
2734 var endAngle = startAngle + circumference;
2735 var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)};
2736 var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)};
2737 var contains0 = (startAngle <= 0 && endAngle >= 0) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle);
2738 var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle);
2739 var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle);
2740 var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle);
2741 var cutout = cutoutPercentage / 100.0;
2742 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))};
2743 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))};
2744 var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5};
2745 minSize = Math.min(availableWidth / size.width, availableHeight / size.height);
2746 offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5};
2747 }
2748
2749 chart.borderWidth = me.getMaxBorderWidth(meta.data);
2750 chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0);
2751 chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0);
2752 chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
2753 chart.offsetX = offset.x * chart.outerRadius;
2754 chart.offsetY = offset.y * chart.outerRadius;
2755
2756 meta.total = me.calculateTotal();
2757
2758 me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index));
2759 me.innerRadius = Math.max(me.outerRadius - chart.radiusLength, 0);
2760
2761 helpers.each(meta.data, function(arc, index) {
2762 me.updateElement(arc, index, reset);
2763 });
2764 },
2765
2766 updateElement: function(arc, index, reset) {
2767 var me = this;
2768 var chart = me.chart;
2769 var chartArea = chart.chartArea;
2770 var opts = chart.options;
2771 var animationOpts = opts.animation;
2772 var centerX = (chartArea.left + chartArea.right) / 2;
2773 var centerY = (chartArea.top + chartArea.bottom) / 2;
2774 var startAngle = opts.rotation; // non reset case handled later
2775 var endAngle = opts.rotation; // non reset case handled later
2776 var dataset = me.getDataset();
2777 var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI));
2778 var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
2779 var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
2780 var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
2781
2782 helpers.extend(arc, {
2783 // Utility
2784 _datasetIndex: me.index,
2785 _index: index,
2786
2787 // Desired view properties
2788 _model: {
2789 x: centerX + chart.offsetX,
2790 y: centerY + chart.offsetY,
2791 startAngle: startAngle,
2792 endAngle: endAngle,
2793 circumference: circumference,
2794 outerRadius: outerRadius,
2795 innerRadius: innerRadius,
2796 label: valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
2797 }
2798 });
2799
2800 var model = arc._model;
2801 // Resets the visual styles
2802 this.removeHoverStyle(arc);
2803
2804 // Set correct angles if not resetting
2805 if (!reset || !animationOpts.animateRotate) {
2806 if (index === 0) {
2807 model.startAngle = opts.rotation;
2808 } else {
2809 model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
2810 }
2811
2812 model.endAngle = model.startAngle + model.circumference;
2813 }
2814
2815 arc.pivot();
2816 },
2817
2818 removeHoverStyle: function(arc) {
2819 Chart.DatasetController.prototype.removeHoverStyle.call(this, arc, this.chart.options.elements.arc);
2820 },
2821
2822 calculateTotal: function() {
2823 var dataset = this.getDataset();
2824 var meta = this.getMeta();
2825 var total = 0;
2826 var value;
2827
2828 helpers.each(meta.data, function(element, index) {
2829 value = dataset.data[index];
2830 if (!isNaN(value) && !element.hidden) {
2831 total += Math.abs(value);
2832 }
2833 });
2834
2835 /* if (total === 0) {
2836 total = NaN;
2837 }*/
2838
2839 return total;
2840 },
2841
2842 calculateCircumference: function(value) {
2843 var total = this.getMeta().total;
2844 if (total > 0 && !isNaN(value)) {
2845 return (Math.PI * 2.0) * (Math.abs(value) / total);
2846 }
2847 return 0;
2848 },
2849
2850 // gets the max border or hover width to properly scale pie charts
2851 getMaxBorderWidth: function(arcs) {
2852 var max = 0;
2853 var index = this.index;
2854 var length = arcs.length;
2855 var borderWidth;
2856 var hoverWidth;
2857
2858 for (var i = 0; i < length; i++) {
2859 borderWidth = arcs[i]._model ? arcs[i]._model.borderWidth : 0;
2860 hoverWidth = arcs[i]._chart ? arcs[i]._chart.config.data.datasets[index].hoverBorderWidth : 0;
2861
2862 max = borderWidth > max ? borderWidth : max;
2863 max = hoverWidth > max ? hoverWidth : max;
2864 }
2865 return max;
2866 }
2867 });
2868};
2869
2870},{"26":26,"41":41,"46":46}],18:[function(require,module,exports){
2871'use strict';
2872
2873var defaults = require(26);
2874var elements = require(41);
2875var helpers = require(46);
2876
2877defaults._set('line', {
2878 showLines: true,
2879 spanGaps: false,
2880
2881 hover: {
2882 mode: 'label'
2883 },
2884
2885 scales: {
2886 xAxes: [{
2887 type: 'category',
2888 id: 'x-axis-0'
2889 }],
2890 yAxes: [{
2891 type: 'linear',
2892 id: 'y-axis-0'
2893 }]
2894 }
2895});
2896
2897module.exports = function(Chart) {
2898
2899 function lineEnabled(dataset, options) {
2900 return helpers.valueOrDefault(dataset.showLine, options.showLines);
2901 }
2902
2903 Chart.controllers.line = Chart.DatasetController.extend({
2904
2905 datasetElementType: elements.Line,
2906
2907 dataElementType: elements.Point,
2908
2909 update: function(reset) {
2910 var me = this;
2911 var meta = me.getMeta();
2912 var line = meta.dataset;
2913 var points = meta.data || [];
2914 var options = me.chart.options;
2915 var lineElementOptions = options.elements.line;
2916 var scale = me.getScaleForId(meta.yAxisID);
2917 var i, ilen, custom;
2918 var dataset = me.getDataset();
2919 var showLine = lineEnabled(dataset, options);
2920
2921 // Update Line
2922 if (showLine) {
2923 custom = line.custom || {};
2924
2925 // Compatibility: If the properties are defined with only the old name, use those values
2926 if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
2927 dataset.lineTension = dataset.tension;
2928 }
2929
2930 // Utility
2931 line._scale = scale;
2932 line._datasetIndex = me.index;
2933 // Data
2934 line._children = points;
2935 // Model
2936 line._model = {
2937 // Appearance
2938 // The default behavior of lines is to break at null values, according
2939 // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
2940 // This option gives lines the ability to span gaps
2941 spanGaps: dataset.spanGaps ? dataset.spanGaps : options.spanGaps,
2942 tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension),
2943 backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),
2944 borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),
2945 borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),
2946 borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),
2947 borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),
2948 borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),
2949 borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),
2950 fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),
2951 steppedLine: custom.steppedLine ? custom.steppedLine : helpers.valueOrDefault(dataset.steppedLine, lineElementOptions.stepped),
2952 cubicInterpolationMode: custom.cubicInterpolationMode ? custom.cubicInterpolationMode : helpers.valueOrDefault(dataset.cubicInterpolationMode, lineElementOptions.cubicInterpolationMode),
2953 };
2954
2955 line.pivot();
2956 }
2957
2958 // Update Points
2959 for (i = 0, ilen = points.length; i < ilen; ++i) {
2960 me.updateElement(points[i], i, reset);
2961 }
2962
2963 if (showLine && line._model.tension !== 0) {
2964 me.updateBezierControlPoints();
2965 }
2966
2967 // Now pivot the point for animation
2968 for (i = 0, ilen = points.length; i < ilen; ++i) {
2969 points[i].pivot();
2970 }
2971 },
2972
2973 getPointBackgroundColor: function(point, index) {
2974 var backgroundColor = this.chart.options.elements.point.backgroundColor;
2975 var dataset = this.getDataset();
2976 var custom = point.custom || {};
2977
2978 if (custom.backgroundColor) {
2979 backgroundColor = custom.backgroundColor;
2980 } else if (dataset.pointBackgroundColor) {
2981 backgroundColor = helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, backgroundColor);
2982 } else if (dataset.backgroundColor) {
2983 backgroundColor = dataset.backgroundColor;
2984 }
2985
2986 return backgroundColor;
2987 },
2988
2989 getPointBorderColor: function(point, index) {
2990 var borderColor = this.chart.options.elements.point.borderColor;
2991 var dataset = this.getDataset();
2992 var custom = point.custom || {};
2993
2994 if (custom.borderColor) {
2995 borderColor = custom.borderColor;
2996 } else if (dataset.pointBorderColor) {
2997 borderColor = helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, borderColor);
2998 } else if (dataset.borderColor) {
2999 borderColor = dataset.borderColor;
3000 }
3001
3002 return borderColor;
3003 },
3004
3005 getPointBorderWidth: function(point, index) {
3006 var borderWidth = this.chart.options.elements.point.borderWidth;
3007 var dataset = this.getDataset();
3008 var custom = point.custom || {};
3009
3010 if (!isNaN(custom.borderWidth)) {
3011 borderWidth = custom.borderWidth;
3012 } else if (!isNaN(dataset.pointBorderWidth) || helpers.isArray(dataset.pointBorderWidth)) {
3013 borderWidth = helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, borderWidth);
3014 } else if (!isNaN(dataset.borderWidth)) {
3015 borderWidth = dataset.borderWidth;
3016 }
3017
3018 return borderWidth;
3019 },
3020
3021 updateElement: function(point, index, reset) {
3022 var me = this;
3023 var meta = me.getMeta();
3024 var custom = point.custom || {};
3025 var dataset = me.getDataset();
3026 var datasetIndex = me.index;
3027 var value = dataset.data[index];
3028 var yScale = me.getScaleForId(meta.yAxisID);
3029 var xScale = me.getScaleForId(meta.xAxisID);
3030 var pointOptions = me.chart.options.elements.point;
3031 var x, y;
3032
3033 // Compatibility: If the properties are defined with only the old name, use those values
3034 if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
3035 dataset.pointRadius = dataset.radius;
3036 }
3037 if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {
3038 dataset.pointHitRadius = dataset.hitRadius;
3039 }
3040
3041 x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
3042 y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
3043
3044 // Utility
3045 point._xScale = xScale;
3046 point._yScale = yScale;
3047 point._datasetIndex = datasetIndex;
3048 point._index = index;
3049
3050 // Desired view properties
3051 point._model = {
3052 x: x,
3053 y: y,
3054 skip: custom.skip || isNaN(x) || isNaN(y),
3055 // Appearance
3056 radius: custom.radius || helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointOptions.radius),
3057 pointStyle: custom.pointStyle || helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointOptions.pointStyle),
3058 backgroundColor: me.getPointBackgroundColor(point, index),
3059 borderColor: me.getPointBorderColor(point, index),
3060 borderWidth: me.getPointBorderWidth(point, index),
3061 tension: meta.dataset._model ? meta.dataset._model.tension : 0,
3062 steppedLine: meta.dataset._model ? meta.dataset._model.steppedLine : false,
3063 // Tooltip
3064 hitRadius: custom.hitRadius || helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointOptions.hitRadius)
3065 };
3066 },
3067
3068 calculatePointY: function(value, index, datasetIndex) {
3069 var me = this;
3070 var chart = me.chart;
3071 var meta = me.getMeta();
3072 var yScale = me.getScaleForId(meta.yAxisID);
3073 var sumPos = 0;
3074 var sumNeg = 0;
3075 var i, ds, dsMeta;
3076
3077 if (yScale.options.stacked) {
3078 for (i = 0; i < datasetIndex; i++) {
3079 ds = chart.data.datasets[i];
3080 dsMeta = chart.getDatasetMeta(i);
3081 if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) {
3082 var stackedRightValue = Number(yScale.getRightValue(ds.data[index]));
3083 if (stackedRightValue < 0) {
3084 sumNeg += stackedRightValue || 0;
3085 } else {
3086 sumPos += stackedRightValue || 0;
3087 }
3088 }
3089 }
3090
3091 var rightValue = Number(yScale.getRightValue(value));
3092 if (rightValue < 0) {
3093 return yScale.getPixelForValue(sumNeg + rightValue);
3094 }
3095 return yScale.getPixelForValue(sumPos + rightValue);
3096 }
3097
3098 return yScale.getPixelForValue(value);
3099 },
3100
3101 updateBezierControlPoints: function() {
3102 var me = this;
3103 var meta = me.getMeta();
3104 var area = me.chart.chartArea;
3105 var points = (meta.data || []);
3106 var i, ilen, point, model, controlPoints;
3107
3108 // Only consider points that are drawn in case the spanGaps option is used
3109 if (meta.dataset._model.spanGaps) {
3110 points = points.filter(function(pt) {
3111 return !pt._model.skip;
3112 });
3113 }
3114
3115 function capControlPoint(pt, min, max) {
3116 return Math.max(Math.min(pt, max), min);
3117 }
3118
3119 if (meta.dataset._model.cubicInterpolationMode === 'monotone') {
3120 helpers.splineCurveMonotone(points);
3121 } else {
3122 for (i = 0, ilen = points.length; i < ilen; ++i) {
3123 point = points[i];
3124 model = point._model;
3125 controlPoints = helpers.splineCurve(
3126 helpers.previousItem(points, i)._model,
3127 model,
3128 helpers.nextItem(points, i)._model,
3129 meta.dataset._model.tension
3130 );
3131 model.controlPointPreviousX = controlPoints.previous.x;
3132 model.controlPointPreviousY = controlPoints.previous.y;
3133 model.controlPointNextX = controlPoints.next.x;
3134 model.controlPointNextY = controlPoints.next.y;
3135 }
3136 }
3137
3138 if (me.chart.options.elements.line.capBezierPoints) {
3139 for (i = 0, ilen = points.length; i < ilen; ++i) {
3140 model = points[i]._model;
3141 model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
3142 model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
3143 model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
3144 model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
3145 }
3146 }
3147 },
3148
3149 draw: function() {
3150 var me = this;
3151 var chart = me.chart;
3152 var meta = me.getMeta();
3153 var points = meta.data || [];
3154 var area = chart.chartArea;
3155 var ilen = points.length;
3156 var halfBorderWidth;
3157 var i = 0;
3158
3159 if (lineEnabled(me.getDataset(), chart.options)) {
3160 halfBorderWidth = (meta.dataset._model.borderWidth || 0) / 2;
3161
3162 helpers.canvas.clipArea(chart.ctx, {
3163 left: area.left,
3164 right: area.right,
3165 top: area.top - halfBorderWidth,
3166 bottom: area.bottom + halfBorderWidth
3167 });
3168
3169 meta.dataset.draw();
3170
3171 helpers.canvas.unclipArea(chart.ctx);
3172 }
3173
3174 // Draw the points
3175 for (; i < ilen; ++i) {
3176 points[i].draw(area);
3177 }
3178 },
3179
3180 setHoverStyle: function(point) {
3181 // Point
3182 var dataset = this.chart.data.datasets[point._datasetIndex];
3183 var index = point._index;
3184 var custom = point.custom || {};
3185 var model = point._model;
3186
3187 model.radius = custom.hoverRadius || helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);
3188 model.backgroundColor = custom.hoverBackgroundColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
3189 model.borderColor = custom.hoverBorderColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));
3190 model.borderWidth = custom.hoverBorderWidth || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);
3191 },
3192
3193 removeHoverStyle: function(point) {
3194 var me = this;
3195 var dataset = me.chart.data.datasets[point._datasetIndex];
3196 var index = point._index;
3197 var custom = point.custom || {};
3198 var model = point._model;
3199
3200 // Compatibility: If the properties are defined with only the old name, use those values
3201 if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
3202 dataset.pointRadius = dataset.radius;
3203 }
3204
3205 model.radius = custom.radius || helpers.valueAtIndexOrDefault(dataset.pointRadius, index, me.chart.options.elements.point.radius);
3206 model.backgroundColor = me.getPointBackgroundColor(point, index);
3207 model.borderColor = me.getPointBorderColor(point, index);
3208 model.borderWidth = me.getPointBorderWidth(point, index);
3209 }
3210 });
3211};
3212
3213},{"26":26,"41":41,"46":46}],19:[function(require,module,exports){
3214'use strict';
3215
3216var defaults = require(26);
3217var elements = require(41);
3218var helpers = require(46);
3219
3220defaults._set('polarArea', {
3221 scale: {
3222 type: 'radialLinear',
3223 angleLines: {
3224 display: false
3225 },
3226 gridLines: {
3227 circular: true
3228 },
3229 pointLabels: {
3230 display: false
3231 },
3232 ticks: {
3233 beginAtZero: true
3234 }
3235 },
3236
3237 // Boolean - Whether to animate the rotation of the chart
3238 animation: {
3239 animateRotate: true,
3240 animateScale: true
3241 },
3242
3243 startAngle: -0.5 * Math.PI,
3244 legendCallback: function(chart) {
3245 var text = [];
3246 text.push('<ul class="' + chart.id + '-legend">');
3247
3248 var data = chart.data;
3249 var datasets = data.datasets;
3250 var labels = data.labels;
3251
3252 if (datasets.length) {
3253 for (var i = 0; i < datasets[0].data.length; ++i) {
3254 text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
3255 if (labels[i]) {
3256 text.push(labels[i]);
3257 }
3258 text.push('</li>');
3259 }
3260 }
3261
3262 text.push('</ul>');
3263 return text.join('');
3264 },
3265 legend: {
3266 labels: {
3267 generateLabels: function(chart) {
3268 var data = chart.data;
3269 if (data.labels.length && data.datasets.length) {
3270 return data.labels.map(function(label, i) {
3271 var meta = chart.getDatasetMeta(0);
3272 var ds = data.datasets[0];
3273 var arc = meta.data[i];
3274 var custom = arc.custom || {};
3275 var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
3276 var arcOpts = chart.options.elements.arc;
3277 var fill = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
3278 var stroke = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
3279 var bw = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
3280
3281 return {
3282 text: label,
3283 fillStyle: fill,
3284 strokeStyle: stroke,
3285 lineWidth: bw,
3286 hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
3287
3288 // Extra data used for toggling the correct item
3289 index: i
3290 };
3291 });
3292 }
3293 return [];
3294 }
3295 },
3296
3297 onClick: function(e, legendItem) {
3298 var index = legendItem.index;
3299 var chart = this.chart;
3300 var i, ilen, meta;
3301
3302 for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
3303 meta = chart.getDatasetMeta(i);
3304 meta.data[index].hidden = !meta.data[index].hidden;
3305 }
3306
3307 chart.update();
3308 }
3309 },
3310
3311 // Need to override these to give a nice default
3312 tooltips: {
3313 callbacks: {
3314 title: function() {
3315 return '';
3316 },
3317 label: function(item, data) {
3318 return data.labels[item.index] + ': ' + item.yLabel;
3319 }
3320 }
3321 }
3322});
3323
3324module.exports = function(Chart) {
3325
3326 Chart.controllers.polarArea = Chart.DatasetController.extend({
3327
3328 dataElementType: elements.Arc,
3329
3330 linkScales: helpers.noop,
3331
3332 update: function(reset) {
3333 var me = this;
3334 var chart = me.chart;
3335 var chartArea = chart.chartArea;
3336 var meta = me.getMeta();
3337 var opts = chart.options;
3338 var arcOpts = opts.elements.arc;
3339 var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
3340 chart.outerRadius = Math.max((minSize - arcOpts.borderWidth / 2) / 2, 0);
3341 chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
3342 chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
3343
3344 me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
3345 me.innerRadius = me.outerRadius - chart.radiusLength;
3346
3347 meta.count = me.countVisibleElements();
3348
3349 helpers.each(meta.data, function(arc, index) {
3350 me.updateElement(arc, index, reset);
3351 });
3352 },
3353
3354 updateElement: function(arc, index, reset) {
3355 var me = this;
3356 var chart = me.chart;
3357 var dataset = me.getDataset();
3358 var opts = chart.options;
3359 var animationOpts = opts.animation;
3360 var scale = chart.scale;
3361 var labels = chart.data.labels;
3362
3363 var circumference = me.calculateCircumference(dataset.data[index]);
3364 var centerX = scale.xCenter;
3365 var centerY = scale.yCenter;
3366
3367 // If there is NaN data before us, we need to calculate the starting angle correctly.
3368 // We could be way more efficient here, but its unlikely that the polar area chart will have a lot of data
3369 var visibleCount = 0;
3370 var meta = me.getMeta();
3371 for (var i = 0; i < index; ++i) {
3372 if (!isNaN(dataset.data[i]) && !meta.data[i].hidden) {
3373 ++visibleCount;
3374 }
3375 }
3376
3377 // var negHalfPI = -0.5 * Math.PI;
3378 var datasetStartAngle = opts.startAngle;
3379 var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
3380 var startAngle = datasetStartAngle + (circumference * visibleCount);
3381 var endAngle = startAngle + (arc.hidden ? 0 : circumference);
3382
3383 var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
3384
3385 helpers.extend(arc, {
3386 // Utility
3387 _datasetIndex: me.index,
3388 _index: index,
3389 _scale: scale,
3390
3391 // Desired view properties
3392 _model: {
3393 x: centerX,
3394 y: centerY,
3395 innerRadius: 0,
3396 outerRadius: reset ? resetRadius : distance,
3397 startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
3398 endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
3399 label: helpers.valueAtIndexOrDefault(labels, index, labels[index])
3400 }
3401 });
3402
3403 // Apply border and fill style
3404 me.removeHoverStyle(arc);
3405
3406 arc.pivot();
3407 },
3408
3409 removeHoverStyle: function(arc) {
3410 Chart.DatasetController.prototype.removeHoverStyle.call(this, arc, this.chart.options.elements.arc);
3411 },
3412
3413 countVisibleElements: function() {
3414 var dataset = this.getDataset();
3415 var meta = this.getMeta();
3416 var count = 0;
3417
3418 helpers.each(meta.data, function(element, index) {
3419 if (!isNaN(dataset.data[index]) && !element.hidden) {
3420 count++;
3421 }
3422 });
3423
3424 return count;
3425 },
3426
3427 calculateCircumference: function(value) {
3428 var count = this.getMeta().count;
3429 if (count > 0 && !isNaN(value)) {
3430 return (2 * Math.PI) / count;
3431 }
3432 return 0;
3433 }
3434 });
3435};
3436
3437},{"26":26,"41":41,"46":46}],20:[function(require,module,exports){
3438'use strict';
3439
3440var defaults = require(26);
3441var elements = require(41);
3442var helpers = require(46);
3443
3444defaults._set('radar', {
3445 scale: {
3446 type: 'radialLinear'
3447 },
3448 elements: {
3449 line: {
3450 tension: 0 // no bezier in radar
3451 }
3452 }
3453});
3454
3455module.exports = function(Chart) {
3456
3457 Chart.controllers.radar = Chart.DatasetController.extend({
3458
3459 datasetElementType: elements.Line,
3460
3461 dataElementType: elements.Point,
3462
3463 linkScales: helpers.noop,
3464
3465 update: function(reset) {
3466 var me = this;
3467 var meta = me.getMeta();
3468 var line = meta.dataset;
3469 var points = meta.data;
3470 var custom = line.custom || {};
3471 var dataset = me.getDataset();
3472 var lineElementOptions = me.chart.options.elements.line;
3473 var scale = me.chart.scale;
3474
3475 // Compatibility: If the properties are defined with only the old name, use those values
3476 if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
3477 dataset.lineTension = dataset.tension;
3478 }
3479
3480 helpers.extend(meta.dataset, {
3481 // Utility
3482 _datasetIndex: me.index,
3483 _scale: scale,
3484 // Data
3485 _children: points,
3486 _loop: true,
3487 // Model
3488 _model: {
3489 // Appearance
3490 tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension),
3491 backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),
3492 borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),
3493 borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),
3494 fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),
3495 borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),
3496 borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),
3497 borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),
3498 borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),
3499 }
3500 });
3501
3502 meta.dataset.pivot();
3503
3504 // Update Points
3505 helpers.each(points, function(point, index) {
3506 me.updateElement(point, index, reset);
3507 }, me);
3508
3509 // Update bezier control points
3510 me.updateBezierControlPoints();
3511 },
3512 updateElement: function(point, index, reset) {
3513 var me = this;
3514 var custom = point.custom || {};
3515 var dataset = me.getDataset();
3516 var scale = me.chart.scale;
3517 var pointElementOptions = me.chart.options.elements.point;
3518 var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
3519
3520 // Compatibility: If the properties are defined with only the old name, use those values
3521 if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
3522 dataset.pointRadius = dataset.radius;
3523 }
3524 if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {
3525 dataset.pointHitRadius = dataset.hitRadius;
3526 }
3527
3528 helpers.extend(point, {
3529 // Utility
3530 _datasetIndex: me.index,
3531 _index: index,
3532 _scale: scale,
3533
3534 // Desired view properties
3535 _model: {
3536 x: reset ? scale.xCenter : pointPosition.x, // value not used in dataset scale, but we want a consistent API between scales
3537 y: reset ? scale.yCenter : pointPosition.y,
3538
3539 // Appearance
3540 tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, me.chart.options.elements.line.tension),
3541 radius: custom.radius ? custom.radius : helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius),
3542 backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor),
3543 borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor),
3544 borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth),
3545 pointStyle: custom.pointStyle ? custom.pointStyle : helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointElementOptions.pointStyle),
3546
3547 // Tooltip
3548 hitRadius: custom.hitRadius ? custom.hitRadius : helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointElementOptions.hitRadius)
3549 }
3550 });
3551
3552 point._model.skip = custom.skip ? custom.skip : (isNaN(point._model.x) || isNaN(point._model.y));
3553 },
3554 updateBezierControlPoints: function() {
3555 var chartArea = this.chart.chartArea;
3556 var meta = this.getMeta();
3557
3558 helpers.each(meta.data, function(point, index) {
3559 var model = point._model;
3560 var controlPoints = helpers.splineCurve(
3561 helpers.previousItem(meta.data, index, true)._model,
3562 model,
3563 helpers.nextItem(meta.data, index, true)._model,
3564 model.tension
3565 );
3566
3567 // Prevent the bezier going outside of the bounds of the graph
3568 model.controlPointPreviousX = Math.max(Math.min(controlPoints.previous.x, chartArea.right), chartArea.left);
3569 model.controlPointPreviousY = Math.max(Math.min(controlPoints.previous.y, chartArea.bottom), chartArea.top);
3570
3571 model.controlPointNextX = Math.max(Math.min(controlPoints.next.x, chartArea.right), chartArea.left);
3572 model.controlPointNextY = Math.max(Math.min(controlPoints.next.y, chartArea.bottom), chartArea.top);
3573
3574 // Now pivot the point for animation
3575 point.pivot();
3576 });
3577 },
3578
3579 setHoverStyle: function(point) {
3580 // Point
3581 var dataset = this.chart.data.datasets[point._datasetIndex];
3582 var custom = point.custom || {};
3583 var index = point._index;
3584 var model = point._model;
3585
3586 model.radius = custom.hoverRadius ? custom.hoverRadius : helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);
3587 model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
3588 model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));
3589 model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);
3590 },
3591
3592 removeHoverStyle: function(point) {
3593 var dataset = this.chart.data.datasets[point._datasetIndex];
3594 var custom = point.custom || {};
3595 var index = point._index;
3596 var model = point._model;
3597 var pointElementOptions = this.chart.options.elements.point;
3598
3599 model.radius = custom.radius ? custom.radius : helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius);
3600 model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor);
3601 model.borderColor = custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor);
3602 model.borderWidth = custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth);
3603 }
3604 });
3605};
3606
3607},{"26":26,"41":41,"46":46}],21:[function(require,module,exports){
3608'use strict';
3609
3610var defaults = require(26);
3611
3612defaults._set('scatter', {
3613 hover: {
3614 mode: 'single'
3615 },
3616
3617 scales: {
3618 xAxes: [{
3619 id: 'x-axis-1', // need an ID so datasets can reference the scale
3620 type: 'linear', // scatter should not use a category axis
3621 position: 'bottom'
3622 }],
3623 yAxes: [{
3624 id: 'y-axis-1',
3625 type: 'linear',
3626 position: 'left'
3627 }]
3628 },
3629
3630 showLines: false,
3631
3632 tooltips: {
3633 callbacks: {
3634 title: function() {
3635 return ''; // doesn't make sense for scatter since data are formatted as a point
3636 },
3637 label: function(item) {
3638 return '(' + item.xLabel + ', ' + item.yLabel + ')';
3639 }
3640 }
3641 }
3642});
3643
3644module.exports = function(Chart) {
3645
3646 // Scatter charts use line controllers
3647 Chart.controllers.scatter = Chart.controllers.line;
3648
3649};
3650
3651},{"26":26}],22:[function(require,module,exports){
3652'use strict';
3653
3654var Element = require(27);
3655
3656var exports = module.exports = Element.extend({
3657 chart: null, // the animation associated chart instance
3658 currentStep: 0, // the current animation step
3659 numSteps: 60, // default number of steps
3660 easing: '', // the easing to use for this animation
3661 render: null, // render function used by the animation service
3662
3663 onAnimationProgress: null, // user specified callback to fire on each step of the animation
3664 onAnimationComplete: null, // user specified callback to fire when the animation finishes
3665});
3666
3667// DEPRECATIONS
3668
3669/**
3670 * Provided for backward compatibility, use Chart.Animation instead
3671 * @prop Chart.Animation#animationObject
3672 * @deprecated since version 2.6.0
3673 * @todo remove at version 3
3674 */
3675Object.defineProperty(exports.prototype, 'animationObject', {
3676 get: function() {
3677 return this;
3678 }
3679});
3680
3681/**
3682 * Provided for backward compatibility, use Chart.Animation#chart instead
3683 * @prop Chart.Animation#chartInstance
3684 * @deprecated since version 2.6.0
3685 * @todo remove at version 3
3686 */
3687Object.defineProperty(exports.prototype, 'chartInstance', {
3688 get: function() {
3689 return this.chart;
3690 },
3691 set: function(value) {
3692 this.chart = value;
3693 }
3694});
3695
3696},{"27":27}],23:[function(require,module,exports){
3697/* global window: false */
3698'use strict';
3699
3700var defaults = require(26);
3701var helpers = require(46);
3702
3703defaults._set('global', {
3704 animation: {
3705 duration: 1000,
3706 easing: 'easeOutQuart',
3707 onProgress: helpers.noop,
3708 onComplete: helpers.noop
3709 }
3710});
3711
3712module.exports = {
3713 frameDuration: 17,
3714 animations: [],
3715 dropFrames: 0,
3716 request: null,
3717
3718 /**
3719 * @param {Chart} chart - The chart to animate.
3720 * @param {Chart.Animation} animation - The animation that we will animate.
3721 * @param {Number} duration - The animation duration in ms.
3722 * @param {Boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
3723 */
3724 addAnimation: function(chart, animation, duration, lazy) {
3725 var animations = this.animations;
3726 var i, ilen;
3727
3728 animation.chart = chart;
3729
3730 if (!lazy) {
3731 chart.animating = true;
3732 }
3733
3734 for (i = 0, ilen = animations.length; i < ilen; ++i) {
3735 if (animations[i].chart === chart) {
3736 animations[i] = animation;
3737 return;
3738 }
3739 }
3740
3741 animations.push(animation);
3742
3743 // If there are no animations queued, manually kickstart a digest, for lack of a better word
3744 if (animations.length === 1) {
3745 this.requestAnimationFrame();
3746 }
3747 },
3748
3749 cancelAnimation: function(chart) {
3750 var index = helpers.findIndex(this.animations, function(animation) {
3751 return animation.chart === chart;
3752 });
3753
3754 if (index !== -1) {
3755 this.animations.splice(index, 1);
3756 chart.animating = false;
3757 }
3758 },
3759
3760 requestAnimationFrame: function() {
3761 var me = this;
3762 if (me.request === null) {
3763 // Skip animation frame requests until the active one is executed.
3764 // This can happen when processing mouse events, e.g. 'mousemove'
3765 // and 'mouseout' events will trigger multiple renders.
3766 me.request = helpers.requestAnimFrame.call(window, function() {
3767 me.request = null;
3768 me.startDigest();
3769 });
3770 }
3771 },
3772
3773 /**
3774 * @private
3775 */
3776 startDigest: function() {
3777 var me = this;
3778 var startTime = Date.now();
3779 var framesToDrop = 0;
3780
3781 if (me.dropFrames > 1) {
3782 framesToDrop = Math.floor(me.dropFrames);
3783 me.dropFrames = me.dropFrames % 1;
3784 }
3785
3786 me.advance(1 + framesToDrop);
3787
3788 var endTime = Date.now();
3789
3790 me.dropFrames += (endTime - startTime) / me.frameDuration;
3791
3792 // Do we have more stuff to animate?
3793 if (me.animations.length > 0) {
3794 me.requestAnimationFrame();
3795 }
3796 },
3797
3798 /**
3799 * @private
3800 */
3801 advance: function(count) {
3802 var animations = this.animations;
3803 var animation, chart;
3804 var i = 0;
3805
3806 while (i < animations.length) {
3807 animation = animations[i];
3808 chart = animation.chart;
3809
3810 animation.currentStep = (animation.currentStep || 0) + count;
3811 animation.currentStep = Math.min(animation.currentStep, animation.numSteps);
3812
3813 helpers.callback(animation.render, [chart, animation], chart);
3814 helpers.callback(animation.onAnimationProgress, [animation], chart);
3815
3816 if (animation.currentStep >= animation.numSteps) {
3817 helpers.callback(animation.onAnimationComplete, [animation], chart);
3818 chart.animating = false;
3819 animations.splice(i, 1);
3820 } else {
3821 ++i;
3822 }
3823 }
3824 }
3825};
3826
3827},{"26":26,"46":46}],24:[function(require,module,exports){
3828'use strict';
3829
3830var Animation = require(22);
3831var animations = require(23);
3832var defaults = require(26);
3833var helpers = require(46);
3834var Interaction = require(29);
3835var layouts = require(31);
3836var platform = require(49);
3837var plugins = require(32);
3838var scaleService = require(34);
3839var Tooltip = require(36);
3840
3841module.exports = function(Chart) {
3842
3843 // Create a dictionary of chart types, to allow for extension of existing types
3844 Chart.types = {};
3845
3846 // Store a reference to each instance - allowing us to globally resize chart instances on window resize.
3847 // Destroy method on the chart will remove the instance of the chart from this reference.
3848 Chart.instances = {};
3849
3850 // Controllers available for dataset visualization eg. bar, line, slice, etc.
3851 Chart.controllers = {};
3852
3853 /**
3854 * Initializes the given config with global and chart default values.
3855 */
3856 function initConfig(config) {
3857 config = config || {};
3858
3859 // Do NOT use configMerge() for the data object because this method merges arrays
3860 // and so would change references to labels and datasets, preventing data updates.
3861 var data = config.data = config.data || {};
3862 data.datasets = data.datasets || [];
3863 data.labels = data.labels || [];
3864
3865 config.options = helpers.configMerge(
3866 defaults.global,
3867 defaults[config.type],
3868 config.options || {});
3869
3870 return config;
3871 }
3872
3873 /**
3874 * Updates the config of the chart
3875 * @param chart {Chart} chart to update the options for
3876 */
3877 function updateConfig(chart) {
3878 var newOptions = chart.options;
3879
3880 helpers.each(chart.scales, function(scale) {
3881 layouts.removeBox(chart, scale);
3882 });
3883
3884 newOptions = helpers.configMerge(
3885 Chart.defaults.global,
3886 Chart.defaults[chart.config.type],
3887 newOptions);
3888
3889 chart.options = chart.config.options = newOptions;
3890 chart.ensureScalesHaveIDs();
3891 chart.buildOrUpdateScales();
3892 // Tooltip
3893 chart.tooltip._options = newOptions.tooltips;
3894 chart.tooltip.initialize();
3895 }
3896
3897 function positionIsHorizontal(position) {
3898 return position === 'top' || position === 'bottom';
3899 }
3900
3901 helpers.extend(Chart.prototype, /** @lends Chart */ {
3902 /**
3903 * @private
3904 */
3905 construct: function(item, config) {
3906 var me = this;
3907
3908 config = initConfig(config);
3909
3910 var context = platform.acquireContext(item, config);
3911 var canvas = context && context.canvas;
3912 var height = canvas && canvas.height;
3913 var width = canvas && canvas.width;
3914
3915 me.id = helpers.uid();
3916 me.ctx = context;
3917 me.canvas = canvas;
3918 me.config = config;
3919 me.width = width;
3920 me.height = height;
3921 me.aspectRatio = height ? width / height : null;
3922 me.options = config.options;
3923 me._bufferedRender = false;
3924
3925 /**
3926 * Provided for backward compatibility, Chart and Chart.Controller have been merged,
3927 * the "instance" still need to be defined since it might be called from plugins.
3928 * @prop Chart#chart
3929 * @deprecated since version 2.6.0
3930 * @todo remove at version 3
3931 * @private
3932 */
3933 me.chart = me;
3934 me.controller = me; // chart.chart.controller #inception
3935
3936 // Add the chart instance to the global namespace
3937 Chart.instances[me.id] = me;
3938
3939 // Define alias to the config data: `chart.data === chart.config.data`
3940 Object.defineProperty(me, 'data', {
3941 get: function() {
3942 return me.config.data;
3943 },
3944 set: function(value) {
3945 me.config.data = value;
3946 }
3947 });
3948
3949 if (!context || !canvas) {
3950 // The given item is not a compatible context2d element, let's return before finalizing
3951 // the chart initialization but after setting basic chart / controller properties that
3952 // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
3953 // https://github.com/chartjs/Chart.js/issues/2807
3954 console.error("Failed to create chart: can't acquire context from the given item");
3955 return;
3956 }
3957
3958 me.initialize();
3959 me.update();
3960 },
3961
3962 /**
3963 * @private
3964 */
3965 initialize: function() {
3966 var me = this;
3967
3968 // Before init plugin notification
3969 plugins.notify(me, 'beforeInit');
3970
3971 helpers.retinaScale(me, me.options.devicePixelRatio);
3972
3973 me.bindEvents();
3974
3975 if (me.options.responsive) {
3976 // Initial resize before chart draws (must be silent to preserve initial animations).
3977 me.resize(true);
3978 }
3979
3980 // Make sure scales have IDs and are built before we build any controllers.
3981 me.ensureScalesHaveIDs();
3982 me.buildOrUpdateScales();
3983 me.initToolTip();
3984
3985 // After init plugin notification
3986 plugins.notify(me, 'afterInit');
3987
3988 return me;
3989 },
3990
3991 clear: function() {
3992 helpers.canvas.clear(this);
3993 return this;
3994 },
3995
3996 stop: function() {
3997 // Stops any current animation loop occurring
3998 animations.cancelAnimation(this);
3999 return this;
4000 },
4001
4002 resize: function(silent) {
4003 var me = this;
4004 var options = me.options;
4005 var canvas = me.canvas;
4006 var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
4007
4008 // the canvas render width and height will be casted to integers so make sure that
4009 // the canvas display style uses the same integer values to avoid blurring effect.
4010
4011 // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collased
4012 var newWidth = Math.max(0, Math.floor(helpers.getMaximumWidth(canvas)));
4013 var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers.getMaximumHeight(canvas)));
4014
4015 if (me.width === newWidth && me.height === newHeight) {
4016 return;
4017 }
4018
4019 canvas.width = me.width = newWidth;
4020 canvas.height = me.height = newHeight;
4021 canvas.style.width = newWidth + 'px';
4022 canvas.style.height = newHeight + 'px';
4023
4024 helpers.retinaScale(me, options.devicePixelRatio);
4025
4026 if (!silent) {
4027 // Notify any plugins about the resize
4028 var newSize = {width: newWidth, height: newHeight};
4029 plugins.notify(me, 'resize', [newSize]);
4030
4031 // Notify of resize
4032 if (me.options.onResize) {
4033 me.options.onResize(me, newSize);
4034 }
4035
4036 me.stop();
4037 me.update(me.options.responsiveAnimationDuration);
4038 }
4039 },
4040
4041 ensureScalesHaveIDs: function() {
4042 var options = this.options;
4043 var scalesOptions = options.scales || {};
4044 var scaleOptions = options.scale;
4045
4046 helpers.each(scalesOptions.xAxes, function(xAxisOptions, index) {
4047 xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index);
4048 });
4049
4050 helpers.each(scalesOptions.yAxes, function(yAxisOptions, index) {
4051 yAxisOptions.id = yAxisOptions.id || ('y-axis-' + index);
4052 });
4053
4054 if (scaleOptions) {
4055 scaleOptions.id = scaleOptions.id || 'scale';
4056 }
4057 },
4058
4059 /**
4060 * Builds a map of scale ID to scale object for future lookup.
4061 */
4062 buildOrUpdateScales: function() {
4063 var me = this;
4064 var options = me.options;
4065 var scales = me.scales || {};
4066 var items = [];
4067 var updated = Object.keys(scales).reduce(function(obj, id) {
4068 obj[id] = false;
4069 return obj;
4070 }, {});
4071
4072 if (options.scales) {
4073 items = items.concat(
4074 (options.scales.xAxes || []).map(function(xAxisOptions) {
4075 return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
4076 }),
4077 (options.scales.yAxes || []).map(function(yAxisOptions) {
4078 return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
4079 })
4080 );
4081 }
4082
4083 if (options.scale) {
4084 items.push({
4085 options: options.scale,
4086 dtype: 'radialLinear',
4087 isDefault: true,
4088 dposition: 'chartArea'
4089 });
4090 }
4091
4092 helpers.each(items, function(item) {
4093 var scaleOptions = item.options;
4094 var id = scaleOptions.id;
4095 var scaleType = helpers.valueOrDefault(scaleOptions.type, item.dtype);
4096
4097 if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
4098 scaleOptions.position = item.dposition;
4099 }
4100
4101 updated[id] = true;
4102 var scale = null;
4103 if (id in scales && scales[id].type === scaleType) {
4104 scale = scales[id];
4105 scale.options = scaleOptions;
4106 scale.ctx = me.ctx;
4107 scale.chart = me;
4108 } else {
4109 var scaleClass = scaleService.getScaleConstructor(scaleType);
4110 if (!scaleClass) {
4111 return;
4112 }
4113 scale = new scaleClass({
4114 id: id,
4115 type: scaleType,
4116 options: scaleOptions,
4117 ctx: me.ctx,
4118 chart: me
4119 });
4120 scales[scale.id] = scale;
4121 }
4122
4123 scale.mergeTicksOptions();
4124
4125 // TODO(SB): I think we should be able to remove this custom case (options.scale)
4126 // and consider it as a regular scale part of the "scales"" map only! This would
4127 // make the logic easier and remove some useless? custom code.
4128 if (item.isDefault) {
4129 me.scale = scale;
4130 }
4131 });
4132 // clear up discarded scales
4133 helpers.each(updated, function(hasUpdated, id) {
4134 if (!hasUpdated) {
4135 delete scales[id];
4136 }
4137 });
4138
4139 me.scales = scales;
4140
4141 scaleService.addScalesToLayout(this);
4142 },
4143
4144 buildOrUpdateControllers: function() {
4145 var me = this;
4146 var types = [];
4147 var newControllers = [];
4148
4149 helpers.each(me.data.datasets, function(dataset, datasetIndex) {
4150 var meta = me.getDatasetMeta(datasetIndex);
4151 var type = dataset.type || me.config.type;
4152
4153 if (meta.type && meta.type !== type) {
4154 me.destroyDatasetMeta(datasetIndex);
4155 meta = me.getDatasetMeta(datasetIndex);
4156 }
4157 meta.type = type;
4158
4159 types.push(meta.type);
4160
4161 if (meta.controller) {
4162 meta.controller.updateIndex(datasetIndex);
4163 meta.controller.linkScales();
4164 } else {
4165 var ControllerClass = Chart.controllers[meta.type];
4166 if (ControllerClass === undefined) {
4167 throw new Error('"' + meta.type + '" is not a chart type.');
4168 }
4169
4170 meta.controller = new ControllerClass(me, datasetIndex);
4171 newControllers.push(meta.controller);
4172 }
4173 }, me);
4174
4175 return newControllers;
4176 },
4177
4178 /**
4179 * Reset the elements of all datasets
4180 * @private
4181 */
4182 resetElements: function() {
4183 var me = this;
4184 helpers.each(me.data.datasets, function(dataset, datasetIndex) {
4185 me.getDatasetMeta(datasetIndex).controller.reset();
4186 }, me);
4187 },
4188
4189 /**
4190 * Resets the chart back to it's state before the initial animation
4191 */
4192 reset: function() {
4193 this.resetElements();
4194 this.tooltip.initialize();
4195 },
4196
4197 update: function(config) {
4198 var me = this;
4199
4200 if (!config || typeof config !== 'object') {
4201 // backwards compatibility
4202 config = {
4203 duration: config,
4204 lazy: arguments[1]
4205 };
4206 }
4207
4208 updateConfig(me);
4209
4210 // plugins options references might have change, let's invalidate the cache
4211 // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
4212 plugins._invalidate(me);
4213
4214 if (plugins.notify(me, 'beforeUpdate') === false) {
4215 return;
4216 }
4217
4218 // In case the entire data object changed
4219 me.tooltip._data = me.data;
4220
4221 // Make sure dataset controllers are updated and new controllers are reset
4222 var newControllers = me.buildOrUpdateControllers();
4223
4224 // Make sure all dataset controllers have correct meta data counts
4225 helpers.each(me.data.datasets, function(dataset, datasetIndex) {
4226 me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements();
4227 }, me);
4228
4229 me.updateLayout();
4230
4231 // Can only reset the new controllers after the scales have been updated
4232 if (me.options.animation && me.options.animation.duration) {
4233 helpers.each(newControllers, function(controller) {
4234 controller.reset();
4235 });
4236 }
4237
4238 me.updateDatasets();
4239
4240 // Need to reset tooltip in case it is displayed with elements that are removed
4241 // after update.
4242 me.tooltip.initialize();
4243
4244 // Last active contains items that were previously in the tooltip.
4245 // When we reset the tooltip, we need to clear it
4246 me.lastActive = [];
4247
4248 // Do this before render so that any plugins that need final scale updates can use it
4249 plugins.notify(me, 'afterUpdate');
4250
4251 if (me._bufferedRender) {
4252 me._bufferedRequest = {
4253 duration: config.duration,
4254 easing: config.easing,
4255 lazy: config.lazy
4256 };
4257 } else {
4258 me.render(config);
4259 }
4260 },
4261
4262 /**
4263 * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
4264 * hook, in which case, plugins will not be called on `afterLayout`.
4265 * @private
4266 */
4267 updateLayout: function() {
4268 var me = this;
4269
4270 if (plugins.notify(me, 'beforeLayout') === false) {
4271 return;
4272 }
4273
4274 layouts.update(this, this.width, this.height);
4275
4276 /**
4277 * Provided for backward compatibility, use `afterLayout` instead.
4278 * @method IPlugin#afterScaleUpdate
4279 * @deprecated since version 2.5.0
4280 * @todo remove at version 3
4281 * @private
4282 */
4283 plugins.notify(me, 'afterScaleUpdate');
4284 plugins.notify(me, 'afterLayout');
4285 },
4286
4287 /**
4288 * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
4289 * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
4290 * @private
4291 */
4292 updateDatasets: function() {
4293 var me = this;
4294
4295 if (plugins.notify(me, 'beforeDatasetsUpdate') === false) {
4296 return;
4297 }
4298
4299 for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
4300 me.updateDataset(i);
4301 }
4302
4303 plugins.notify(me, 'afterDatasetsUpdate');
4304 },
4305
4306 /**
4307 * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
4308 * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
4309 * @private
4310 */
4311 updateDataset: function(index) {
4312 var me = this;
4313 var meta = me.getDatasetMeta(index);
4314 var args = {
4315 meta: meta,
4316 index: index
4317 };
4318
4319 if (plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
4320 return;
4321 }
4322
4323 meta.controller.update();
4324
4325 plugins.notify(me, 'afterDatasetUpdate', [args]);
4326 },
4327
4328 render: function(config) {
4329 var me = this;
4330
4331 if (!config || typeof config !== 'object') {
4332 // backwards compatibility
4333 config = {
4334 duration: config,
4335 lazy: arguments[1]
4336 };
4337 }
4338
4339 var duration = config.duration;
4340 var lazy = config.lazy;
4341
4342 if (plugins.notify(me, 'beforeRender') === false) {
4343 return;
4344 }
4345
4346 var animationOptions = me.options.animation;
4347 var onComplete = function(animation) {
4348 plugins.notify(me, 'afterRender');
4349 helpers.callback(animationOptions && animationOptions.onComplete, [animation], me);
4350 };
4351
4352 if (animationOptions && ((typeof duration !== 'undefined' && duration !== 0) || (typeof duration === 'undefined' && animationOptions.duration !== 0))) {
4353 var animation = new Animation({
4354 numSteps: (duration || animationOptions.duration) / 16.66, // 60 fps
4355 easing: config.easing || animationOptions.easing,
4356
4357 render: function(chart, animationObject) {
4358 var easingFunction = helpers.easing.effects[animationObject.easing];
4359 var currentStep = animationObject.currentStep;
4360 var stepDecimal = currentStep / animationObject.numSteps;
4361
4362 chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
4363 },
4364
4365 onAnimationProgress: animationOptions.onProgress,
4366 onAnimationComplete: onComplete
4367 });
4368
4369 animations.addAnimation(me, animation, duration, lazy);
4370 } else {
4371 me.draw();
4372
4373 // See https://github.com/chartjs/Chart.js/issues/3781
4374 onComplete(new Animation({numSteps: 0, chart: me}));
4375 }
4376
4377 return me;
4378 },
4379
4380 draw: function(easingValue) {
4381 var me = this;
4382
4383 me.clear();
4384
4385 if (helpers.isNullOrUndef(easingValue)) {
4386 easingValue = 1;
4387 }
4388
4389 me.transition(easingValue);
4390
4391 if (plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
4392 return;
4393 }
4394
4395 // Draw all the scales
4396 helpers.each(me.boxes, function(box) {
4397 box.draw(me.chartArea);
4398 }, me);
4399
4400 if (me.scale) {
4401 me.scale.draw();
4402 }
4403
4404 me.drawDatasets(easingValue);
4405 me._drawTooltip(easingValue);
4406
4407 plugins.notify(me, 'afterDraw', [easingValue]);
4408 },
4409
4410 /**
4411 * @private
4412 */
4413 transition: function(easingValue) {
4414 var me = this;
4415
4416 for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
4417 if (me.isDatasetVisible(i)) {
4418 me.getDatasetMeta(i).controller.transition(easingValue);
4419 }
4420 }
4421
4422 me.tooltip.transition(easingValue);
4423 },
4424
4425 /**
4426 * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
4427 * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
4428 * @private
4429 */
4430 drawDatasets: function(easingValue) {
4431 var me = this;
4432
4433 if (plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
4434 return;
4435 }
4436
4437 // Draw datasets reversed to support proper line stacking
4438 for (var i = (me.data.datasets || []).length - 1; i >= 0; --i) {
4439 if (me.isDatasetVisible(i)) {
4440 me.drawDataset(i, easingValue);
4441 }
4442 }
4443
4444 plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
4445 },
4446
4447 /**
4448 * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
4449 * hook, in which case, plugins will not be called on `afterDatasetDraw`.
4450 * @private
4451 */
4452 drawDataset: function(index, easingValue) {
4453 var me = this;
4454 var meta = me.getDatasetMeta(index);
4455 var args = {
4456 meta: meta,
4457 index: index,
4458 easingValue: easingValue
4459 };
4460
4461 if (plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
4462 return;
4463 }
4464
4465 meta.controller.draw(easingValue);
4466
4467 plugins.notify(me, 'afterDatasetDraw', [args]);
4468 },
4469
4470 /**
4471 * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
4472 * hook, in which case, plugins will not be called on `afterTooltipDraw`.
4473 * @private
4474 */
4475 _drawTooltip: function(easingValue) {
4476 var me = this;
4477 var tooltip = me.tooltip;
4478 var args = {
4479 tooltip: tooltip,
4480 easingValue: easingValue
4481 };
4482
4483 if (plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
4484 return;
4485 }
4486
4487 tooltip.draw();
4488
4489 plugins.notify(me, 'afterTooltipDraw', [args]);
4490 },
4491
4492 // Get the single element that was clicked on
4493 // @return : An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
4494 getElementAtEvent: function(e) {
4495 return Interaction.modes.single(this, e);
4496 },
4497
4498 getElementsAtEvent: function(e) {
4499 return Interaction.modes.label(this, e, {intersect: true});
4500 },
4501
4502 getElementsAtXAxis: function(e) {
4503 return Interaction.modes['x-axis'](this, e, {intersect: true});
4504 },
4505
4506 getElementsAtEventForMode: function(e, mode, options) {
4507 var method = Interaction.modes[mode];
4508 if (typeof method === 'function') {
4509 return method(this, e, options);
4510 }
4511
4512 return [];
4513 },
4514
4515 getDatasetAtEvent: function(e) {
4516 return Interaction.modes.dataset(this, e, {intersect: true});
4517 },
4518
4519 getDatasetMeta: function(datasetIndex) {
4520 var me = this;
4521 var dataset = me.data.datasets[datasetIndex];
4522 if (!dataset._meta) {
4523 dataset._meta = {};
4524 }
4525
4526 var meta = dataset._meta[me.id];
4527 if (!meta) {
4528 meta = dataset._meta[me.id] = {
4529 type: null,
4530 data: [],
4531 dataset: null,
4532 controller: null,
4533 hidden: null, // See isDatasetVisible() comment
4534 xAxisID: null,
4535 yAxisID: null
4536 };
4537 }
4538
4539 return meta;
4540 },
4541
4542 getVisibleDatasetCount: function() {
4543 var count = 0;
4544 for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
4545 if (this.isDatasetVisible(i)) {
4546 count++;
4547 }
4548 }
4549 return count;
4550 },
4551
4552 isDatasetVisible: function(datasetIndex) {
4553 var meta = this.getDatasetMeta(datasetIndex);
4554
4555 // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
4556 // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
4557 return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
4558 },
4559
4560 generateLegend: function() {
4561 return this.options.legendCallback(this);
4562 },
4563
4564 /**
4565 * @private
4566 */
4567 destroyDatasetMeta: function(datasetIndex) {
4568 var id = this.id;
4569 var dataset = this.data.datasets[datasetIndex];
4570 var meta = dataset._meta && dataset._meta[id];
4571
4572 if (meta) {
4573 meta.controller.destroy();
4574 delete dataset._meta[id];
4575 }
4576 },
4577
4578 destroy: function() {
4579 var me = this;
4580 var canvas = me.canvas;
4581 var i, ilen;
4582
4583 me.stop();
4584
4585 // dataset controllers need to cleanup associated data
4586 for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
4587 me.destroyDatasetMeta(i);
4588 }
4589
4590 if (canvas) {
4591 me.unbindEvents();
4592 helpers.canvas.clear(me);
4593 platform.releaseContext(me.ctx);
4594 me.canvas = null;
4595 me.ctx = null;
4596 }
4597
4598 plugins.notify(me, 'destroy');
4599
4600 delete Chart.instances[me.id];
4601 },
4602
4603 toBase64Image: function() {
4604 return this.canvas.toDataURL.apply(this.canvas, arguments);
4605 },
4606
4607 initToolTip: function() {
4608 var me = this;
4609 me.tooltip = new Tooltip({
4610 _chart: me,
4611 _chartInstance: me, // deprecated, backward compatibility
4612 _data: me.data,
4613 _options: me.options.tooltips
4614 }, me);
4615 },
4616
4617 /**
4618 * @private
4619 */
4620 bindEvents: function() {
4621 var me = this;
4622 var listeners = me._listeners = {};
4623 var listener = function() {
4624 me.eventHandler.apply(me, arguments);
4625 };
4626
4627 helpers.each(me.options.events, function(type) {
4628 platform.addEventListener(me, type, listener);
4629 listeners[type] = listener;
4630 });
4631
4632 // Elements used to detect size change should not be injected for non responsive charts.
4633 // See https://github.com/chartjs/Chart.js/issues/2210
4634 if (me.options.responsive) {
4635 listener = function() {
4636 me.resize();
4637 };
4638
4639 platform.addEventListener(me, 'resize', listener);
4640 listeners.resize = listener;
4641 }
4642 },
4643
4644 /**
4645 * @private
4646 */
4647 unbindEvents: function() {
4648 var me = this;
4649 var listeners = me._listeners;
4650 if (!listeners) {
4651 return;
4652 }
4653
4654 delete me._listeners;
4655 helpers.each(listeners, function(listener, type) {
4656 platform.removeEventListener(me, type, listener);
4657 });
4658 },
4659
4660 updateHoverStyle: function(elements, mode, enabled) {
4661 var method = enabled ? 'setHoverStyle' : 'removeHoverStyle';
4662 var element, i, ilen;
4663
4664 for (i = 0, ilen = elements.length; i < ilen; ++i) {
4665 element = elements[i];
4666 if (element) {
4667 this.getDatasetMeta(element._datasetIndex).controller[method](element);
4668 }
4669 }
4670 },
4671
4672 /**
4673 * @private
4674 */
4675 eventHandler: function(e) {
4676 var me = this;
4677 var tooltip = me.tooltip;
4678
4679 if (plugins.notify(me, 'beforeEvent', [e]) === false) {
4680 return;
4681 }
4682
4683 // Buffer any update calls so that renders do not occur
4684 me._bufferedRender = true;
4685 me._bufferedRequest = null;
4686
4687 var changed = me.handleEvent(e);
4688 // for smooth tooltip animations issue #4989
4689 // the tooltip should be the source of change
4690 // Animation check workaround:
4691 // tooltip._start will be null when tooltip isn't animating
4692 if (tooltip) {
4693 changed = tooltip._start
4694 ? tooltip.handleEvent(e)
4695 : changed | tooltip.handleEvent(e);
4696 }
4697
4698 plugins.notify(me, 'afterEvent', [e]);
4699
4700 var bufferedRequest = me._bufferedRequest;
4701 if (bufferedRequest) {
4702 // If we have an update that was triggered, we need to do a normal render
4703 me.render(bufferedRequest);
4704 } else if (changed && !me.animating) {
4705 // If entering, leaving, or changing elements, animate the change via pivot
4706 me.stop();
4707
4708 // We only need to render at this point. Updating will cause scales to be
4709 // recomputed generating flicker & using more memory than necessary.
4710 me.render(me.options.hover.animationDuration, true);
4711 }
4712
4713 me._bufferedRender = false;
4714 me._bufferedRequest = null;
4715
4716 return me;
4717 },
4718
4719 /**
4720 * Handle an event
4721 * @private
4722 * @param {IEvent} event the event to handle
4723 * @return {Boolean} true if the chart needs to re-render
4724 */
4725 handleEvent: function(e) {
4726 var me = this;
4727 var options = me.options || {};
4728 var hoverOptions = options.hover;
4729 var changed = false;
4730
4731 me.lastActive = me.lastActive || [];
4732
4733 // Find Active Elements for hover and tooltips
4734 if (e.type === 'mouseout') {
4735 me.active = [];
4736 } else {
4737 me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
4738 }
4739
4740 // Invoke onHover hook
4741 // Need to call with native event here to not break backwards compatibility
4742 helpers.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
4743
4744 if (e.type === 'mouseup' || e.type === 'click') {
4745 if (options.onClick) {
4746 // Use e.native here for backwards compatibility
4747 options.onClick.call(me, e.native, me.active);
4748 }
4749 }
4750
4751 // Remove styling for last active (even if it may still be active)
4752 if (me.lastActive.length) {
4753 me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
4754 }
4755
4756 // Built in hover styling
4757 if (me.active.length && hoverOptions.mode) {
4758 me.updateHoverStyle(me.active, hoverOptions.mode, true);
4759 }
4760
4761 changed = !helpers.arrayEquals(me.active, me.lastActive);
4762
4763 // Remember Last Actives
4764 me.lastActive = me.active;
4765
4766 return changed;
4767 }
4768 });
4769
4770 /**
4771 * Provided for backward compatibility, use Chart instead.
4772 * @class Chart.Controller
4773 * @deprecated since version 2.6.0
4774 * @todo remove at version 3
4775 * @private
4776 */
4777 Chart.Controller = Chart;
4778};
4779
4780},{"22":22,"23":23,"26":26,"29":29,"31":31,"32":32,"34":34,"36":36,"46":46,"49":49}],25:[function(require,module,exports){
4781'use strict';
4782
4783var helpers = require(46);
4784
4785module.exports = function(Chart) {
4786
4787 var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
4788
4789 /**
4790 * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
4791 * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
4792 * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
4793 */
4794 function listenArrayEvents(array, listener) {
4795 if (array._chartjs) {
4796 array._chartjs.listeners.push(listener);
4797 return;
4798 }
4799
4800 Object.defineProperty(array, '_chartjs', {
4801 configurable: true,
4802 enumerable: false,
4803 value: {
4804 listeners: [listener]
4805 }
4806 });
4807
4808 arrayEvents.forEach(function(key) {
4809 var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
4810 var base = array[key];
4811
4812 Object.defineProperty(array, key, {
4813 configurable: true,
4814 enumerable: false,
4815 value: function() {
4816 var args = Array.prototype.slice.call(arguments);
4817 var res = base.apply(this, args);
4818
4819 helpers.each(array._chartjs.listeners, function(object) {
4820 if (typeof object[method] === 'function') {
4821 object[method].apply(object, args);
4822 }
4823 });
4824
4825 return res;
4826 }
4827 });
4828 });
4829 }
4830
4831 /**
4832 * Removes the given array event listener and cleanup extra attached properties (such as
4833 * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
4834 */
4835 function unlistenArrayEvents(array, listener) {
4836 var stub = array._chartjs;
4837 if (!stub) {
4838 return;
4839 }
4840
4841 var listeners = stub.listeners;
4842 var index = listeners.indexOf(listener);
4843 if (index !== -1) {
4844 listeners.splice(index, 1);
4845 }
4846
4847 if (listeners.length > 0) {
4848 return;
4849 }
4850
4851 arrayEvents.forEach(function(key) {
4852 delete array[key];
4853 });
4854
4855 delete array._chartjs;
4856 }
4857
4858 // Base class for all dataset controllers (line, bar, etc)
4859 Chart.DatasetController = function(chart, datasetIndex) {
4860 this.initialize(chart, datasetIndex);
4861 };
4862
4863 helpers.extend(Chart.DatasetController.prototype, {
4864
4865 /**
4866 * Element type used to generate a meta dataset (e.g. Chart.element.Line).
4867 * @type {Chart.core.element}
4868 */
4869 datasetElementType: null,
4870
4871 /**
4872 * Element type used to generate a meta data (e.g. Chart.element.Point).
4873 * @type {Chart.core.element}
4874 */
4875 dataElementType: null,
4876
4877 initialize: function(chart, datasetIndex) {
4878 var me = this;
4879 me.chart = chart;
4880 me.index = datasetIndex;
4881 me.linkScales();
4882 me.addElements();
4883 },
4884
4885 updateIndex: function(datasetIndex) {
4886 this.index = datasetIndex;
4887 },
4888
4889 linkScales: function() {
4890 var me = this;
4891 var meta = me.getMeta();
4892 var dataset = me.getDataset();
4893
4894 if (meta.xAxisID === null || !(meta.xAxisID in me.chart.scales)) {
4895 meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id;
4896 }
4897 if (meta.yAxisID === null || !(meta.yAxisID in me.chart.scales)) {
4898 meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id;
4899 }
4900 },
4901
4902 getDataset: function() {
4903 return this.chart.data.datasets[this.index];
4904 },
4905
4906 getMeta: function() {
4907 return this.chart.getDatasetMeta(this.index);
4908 },
4909
4910 getScaleForId: function(scaleID) {
4911 return this.chart.scales[scaleID];
4912 },
4913
4914 reset: function() {
4915 this.update(true);
4916 },
4917
4918 /**
4919 * @private
4920 */
4921 destroy: function() {
4922 if (this._data) {
4923 unlistenArrayEvents(this._data, this);
4924 }
4925 },
4926
4927 createMetaDataset: function() {
4928 var me = this;
4929 var type = me.datasetElementType;
4930 return type && new type({
4931 _chart: me.chart,
4932 _datasetIndex: me.index
4933 });
4934 },
4935
4936 createMetaData: function(index) {
4937 var me = this;
4938 var type = me.dataElementType;
4939 return type && new type({
4940 _chart: me.chart,
4941 _datasetIndex: me.index,
4942 _index: index
4943 });
4944 },
4945
4946 addElements: function() {
4947 var me = this;
4948 var meta = me.getMeta();
4949 var data = me.getDataset().data || [];
4950 var metaData = meta.data;
4951 var i, ilen;
4952
4953 for (i = 0, ilen = data.length; i < ilen; ++i) {
4954 metaData[i] = metaData[i] || me.createMetaData(i);
4955 }
4956
4957 meta.dataset = meta.dataset || me.createMetaDataset();
4958 },
4959
4960 addElementAndReset: function(index) {
4961 var element = this.createMetaData(index);
4962 this.getMeta().data.splice(index, 0, element);
4963 this.updateElement(element, index, true);
4964 },
4965
4966 buildOrUpdateElements: function() {
4967 var me = this;
4968 var dataset = me.getDataset();
4969 var data = dataset.data || (dataset.data = []);
4970
4971 // In order to correctly handle data addition/deletion animation (an thus simulate
4972 // real-time charts), we need to monitor these data modifications and synchronize
4973 // the internal meta data accordingly.
4974 if (me._data !== data) {
4975 if (me._data) {
4976 // This case happens when the user replaced the data array instance.
4977 unlistenArrayEvents(me._data, me);
4978 }
4979
4980 listenArrayEvents(data, me);
4981 me._data = data;
4982 }
4983
4984 // Re-sync meta data in case the user replaced the data array or if we missed
4985 // any updates and so make sure that we handle number of datapoints changing.
4986 me.resyncElements();
4987 },
4988
4989 update: helpers.noop,
4990
4991 transition: function(easingValue) {
4992 var meta = this.getMeta();
4993 var elements = meta.data || [];
4994 var ilen = elements.length;
4995 var i = 0;
4996
4997 for (; i < ilen; ++i) {
4998 elements[i].transition(easingValue);
4999 }
5000
5001 if (meta.dataset) {
5002 meta.dataset.transition(easingValue);
5003 }
5004 },
5005
5006 draw: function() {
5007 var meta = this.getMeta();
5008 var elements = meta.data || [];
5009 var ilen = elements.length;
5010 var i = 0;
5011
5012 if (meta.dataset) {
5013 meta.dataset.draw();
5014 }
5015
5016 for (; i < ilen; ++i) {
5017 elements[i].draw();
5018 }
5019 },
5020
5021 removeHoverStyle: function(element, elementOpts) {
5022 var dataset = this.chart.data.datasets[element._datasetIndex];
5023 var index = element._index;
5024 var custom = element.custom || {};
5025 var valueOrDefault = helpers.valueAtIndexOrDefault;
5026 var model = element._model;
5027
5028 model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueOrDefault(dataset.backgroundColor, index, elementOpts.backgroundColor);
5029 model.borderColor = custom.borderColor ? custom.borderColor : valueOrDefault(dataset.borderColor, index, elementOpts.borderColor);
5030 model.borderWidth = custom.borderWidth ? custom.borderWidth : valueOrDefault(dataset.borderWidth, index, elementOpts.borderWidth);
5031 },
5032
5033 setHoverStyle: function(element) {
5034 var dataset = this.chart.data.datasets[element._datasetIndex];
5035 var index = element._index;
5036 var custom = element.custom || {};
5037 var valueOrDefault = helpers.valueAtIndexOrDefault;
5038 var getHoverColor = helpers.getHoverColor;
5039 var model = element._model;
5040
5041 model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : valueOrDefault(dataset.hoverBackgroundColor, index, getHoverColor(model.backgroundColor));
5042 model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : valueOrDefault(dataset.hoverBorderColor, index, getHoverColor(model.borderColor));
5043 model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : valueOrDefault(dataset.hoverBorderWidth, index, model.borderWidth);
5044 },
5045
5046 /**
5047 * @private
5048 */
5049 resyncElements: function() {
5050 var me = this;
5051 var meta = me.getMeta();
5052 var data = me.getDataset().data;
5053 var numMeta = meta.data.length;
5054 var numData = data.length;
5055
5056 if (numData < numMeta) {
5057 meta.data.splice(numData, numMeta - numData);
5058 } else if (numData > numMeta) {
5059 me.insertElements(numMeta, numData - numMeta);
5060 }
5061 },
5062
5063 /**
5064 * @private
5065 */
5066 insertElements: function(start, count) {
5067 for (var i = 0; i < count; ++i) {
5068 this.addElementAndReset(start + i);
5069 }
5070 },
5071
5072 /**
5073 * @private
5074 */
5075 onDataPush: function() {
5076 this.insertElements(this.getDataset().data.length - 1, arguments.length);
5077 },
5078
5079 /**
5080 * @private
5081 */
5082 onDataPop: function() {
5083 this.getMeta().data.pop();
5084 },
5085
5086 /**
5087 * @private
5088 */
5089 onDataShift: function() {
5090 this.getMeta().data.shift();
5091 },
5092
5093 /**
5094 * @private
5095 */
5096 onDataSplice: function(start, count) {
5097 this.getMeta().data.splice(start, count);
5098 this.insertElements(start, arguments.length - 2);
5099 },
5100
5101 /**
5102 * @private
5103 */
5104 onDataUnshift: function() {
5105 this.insertElements(0, arguments.length);
5106 }
5107 });
5108
5109 Chart.DatasetController.extend = helpers.inherits;
5110};
5111
5112},{"46":46}],26:[function(require,module,exports){
5113'use strict';
5114
5115var helpers = require(46);
5116
5117module.exports = {
5118 /**
5119 * @private
5120 */
5121 _set: function(scope, values) {
5122 return helpers.merge(this[scope] || (this[scope] = {}), values);
5123 }
5124};
5125
5126},{"46":46}],27:[function(require,module,exports){
5127'use strict';
5128
5129var color = require(3);
5130var helpers = require(46);
5131
5132function interpolate(start, view, model, ease) {
5133 var keys = Object.keys(model);
5134 var i, ilen, key, actual, origin, target, type, c0, c1;
5135
5136 for (i = 0, ilen = keys.length; i < ilen; ++i) {
5137 key = keys[i];
5138
5139 target = model[key];
5140
5141 // if a value is added to the model after pivot() has been called, the view
5142 // doesn't contain it, so let's initialize the view to the target value.
5143 if (!view.hasOwnProperty(key)) {
5144 view[key] = target;
5145 }
5146
5147 actual = view[key];
5148
5149 if (actual === target || key[0] === '_') {
5150 continue;
5151 }
5152
5153 if (!start.hasOwnProperty(key)) {
5154 start[key] = actual;
5155 }
5156
5157 origin = start[key];
5158
5159 type = typeof target;
5160
5161 if (type === typeof origin) {
5162 if (type === 'string') {
5163 c0 = color(origin);
5164 if (c0.valid) {
5165 c1 = color(target);
5166 if (c1.valid) {
5167 view[key] = c1.mix(c0, ease).rgbString();
5168 continue;
5169 }
5170 }
5171 } else if (type === 'number' && isFinite(origin) && isFinite(target)) {
5172 view[key] = origin + (target - origin) * ease;
5173 continue;
5174 }
5175 }
5176
5177 view[key] = target;
5178 }
5179}
5180
5181var Element = function(configuration) {
5182 helpers.extend(this, configuration);
5183 this.initialize.apply(this, arguments);
5184};
5185
5186helpers.extend(Element.prototype, {
5187
5188 initialize: function() {
5189 this.hidden = false;
5190 },
5191
5192 pivot: function() {
5193 var me = this;
5194 if (!me._view) {
5195 me._view = helpers.clone(me._model);
5196 }
5197 me._start = {};
5198 return me;
5199 },
5200
5201 transition: function(ease) {
5202 var me = this;
5203 var model = me._model;
5204 var start = me._start;
5205 var view = me._view;
5206
5207 // No animation -> No Transition
5208 if (!model || ease === 1) {
5209 me._view = model;
5210 me._start = null;
5211 return me;
5212 }
5213
5214 if (!view) {
5215 view = me._view = {};
5216 }
5217
5218 if (!start) {
5219 start = me._start = {};
5220 }
5221
5222 interpolate(start, view, model, ease);
5223
5224 return me;
5225 },
5226
5227 tooltipPosition: function() {
5228 return {
5229 x: this._model.x,
5230 y: this._model.y
5231 };
5232 },
5233
5234 hasValue: function() {
5235 return helpers.isNumber(this._model.x) && helpers.isNumber(this._model.y);
5236 }
5237});
5238
5239Element.extend = helpers.inherits;
5240
5241module.exports = Element;
5242
5243},{"3":3,"46":46}],28:[function(require,module,exports){
5244/* global window: false */
5245/* global document: false */
5246'use strict';
5247
5248var color = require(3);
5249var defaults = require(26);
5250var helpers = require(46);
5251var scaleService = require(34);
5252
5253module.exports = function() {
5254
5255 // -- Basic js utility methods
5256
5257 helpers.configMerge = function(/* objects ... */) {
5258 return helpers.merge(helpers.clone(arguments[0]), [].slice.call(arguments, 1), {
5259 merger: function(key, target, source, options) {
5260 var tval = target[key] || {};
5261 var sval = source[key];
5262
5263 if (key === 'scales') {
5264 // scale config merging is complex. Add our own function here for that
5265 target[key] = helpers.scaleMerge(tval, sval);
5266 } else if (key === 'scale') {
5267 // used in polar area & radar charts since there is only one scale
5268 target[key] = helpers.merge(tval, [scaleService.getScaleDefaults(sval.type), sval]);
5269 } else {
5270 helpers._merger(key, target, source, options);
5271 }
5272 }
5273 });
5274 };
5275
5276 helpers.scaleMerge = function(/* objects ... */) {
5277 return helpers.merge(helpers.clone(arguments[0]), [].slice.call(arguments, 1), {
5278 merger: function(key, target, source, options) {
5279 if (key === 'xAxes' || key === 'yAxes') {
5280 var slen = source[key].length;
5281 var i, type, scale;
5282
5283 if (!target[key]) {
5284 target[key] = [];
5285 }
5286
5287 for (i = 0; i < slen; ++i) {
5288 scale = source[key][i];
5289 type = helpers.valueOrDefault(scale.type, key === 'xAxes' ? 'category' : 'linear');
5290
5291 if (i >= target[key].length) {
5292 target[key].push({});
5293 }
5294
5295 if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
5296 // new/untyped scale or type changed: let's apply the new defaults
5297 // then merge source scale to correctly overwrite the defaults.
5298 helpers.merge(target[key][i], [scaleService.getScaleDefaults(type), scale]);
5299 } else {
5300 // scales type are the same
5301 helpers.merge(target[key][i], scale);
5302 }
5303 }
5304 } else {
5305 helpers._merger(key, target, source, options);
5306 }
5307 }
5308 });
5309 };
5310
5311 helpers.where = function(collection, filterCallback) {
5312 if (helpers.isArray(collection) && Array.prototype.filter) {
5313 return collection.filter(filterCallback);
5314 }
5315 var filtered = [];
5316
5317 helpers.each(collection, function(item) {
5318 if (filterCallback(item)) {
5319 filtered.push(item);
5320 }
5321 });
5322
5323 return filtered;
5324 };
5325 helpers.findIndex = Array.prototype.findIndex ?
5326 function(array, callback, scope) {
5327 return array.findIndex(callback, scope);
5328 } :
5329 function(array, callback, scope) {
5330 scope = scope === undefined ? array : scope;
5331 for (var i = 0, ilen = array.length; i < ilen; ++i) {
5332 if (callback.call(scope, array[i], i, array)) {
5333 return i;
5334 }
5335 }
5336 return -1;
5337 };
5338 helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
5339 // Default to start of the array
5340 if (helpers.isNullOrUndef(startIndex)) {
5341 startIndex = -1;
5342 }
5343 for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
5344 var currentItem = arrayToSearch[i];
5345 if (filterCallback(currentItem)) {
5346 return currentItem;
5347 }
5348 }
5349 };
5350 helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
5351 // Default to end of the array
5352 if (helpers.isNullOrUndef(startIndex)) {
5353 startIndex = arrayToSearch.length;
5354 }
5355 for (var i = startIndex - 1; i >= 0; i--) {
5356 var currentItem = arrayToSearch[i];
5357 if (filterCallback(currentItem)) {
5358 return currentItem;
5359 }
5360 }
5361 };
5362
5363 // -- Math methods
5364 helpers.isNumber = function(n) {
5365 return !isNaN(parseFloat(n)) && isFinite(n);
5366 };
5367 helpers.almostEquals = function(x, y, epsilon) {
5368 return Math.abs(x - y) < epsilon;
5369 };
5370 helpers.almostWhole = function(x, epsilon) {
5371 var rounded = Math.round(x);
5372 return (((rounded - epsilon) < x) && ((rounded + epsilon) > x));
5373 };
5374 helpers.max = function(array) {
5375 return array.reduce(function(max, value) {
5376 if (!isNaN(value)) {
5377 return Math.max(max, value);
5378 }
5379 return max;
5380 }, Number.NEGATIVE_INFINITY);
5381 };
5382 helpers.min = function(array) {
5383 return array.reduce(function(min, value) {
5384 if (!isNaN(value)) {
5385 return Math.min(min, value);
5386 }
5387 return min;
5388 }, Number.POSITIVE_INFINITY);
5389 };
5390 helpers.sign = Math.sign ?
5391 function(x) {
5392 return Math.sign(x);
5393 } :
5394 function(x) {
5395 x = +x; // convert to a number
5396 if (x === 0 || isNaN(x)) {
5397 return x;
5398 }
5399 return x > 0 ? 1 : -1;
5400 };
5401 helpers.log10 = Math.log10 ?
5402 function(x) {
5403 return Math.log10(x);
5404 } :
5405 function(x) {
5406 var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
5407 // Check for whole powers of 10,
5408 // which due to floating point rounding error should be corrected.
5409 var powerOf10 = Math.round(exponent);
5410 var isPowerOf10 = x === Math.pow(10, powerOf10);
5411
5412 return isPowerOf10 ? powerOf10 : exponent;
5413 };
5414 helpers.toRadians = function(degrees) {
5415 return degrees * (Math.PI / 180);
5416 };
5417 helpers.toDegrees = function(radians) {
5418 return radians * (180 / Math.PI);
5419 };
5420 // Gets the angle from vertical upright to the point about a centre.
5421 helpers.getAngleFromPoint = function(centrePoint, anglePoint) {
5422 var distanceFromXCenter = anglePoint.x - centrePoint.x;
5423 var distanceFromYCenter = anglePoint.y - centrePoint.y;
5424 var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
5425
5426 var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
5427
5428 if (angle < (-0.5 * Math.PI)) {
5429 angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
5430 }
5431
5432 return {
5433 angle: angle,
5434 distance: radialDistanceFromCenter
5435 };
5436 };
5437 helpers.distanceBetweenPoints = function(pt1, pt2) {
5438 return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
5439 };
5440 helpers.aliasPixel = function(pixelWidth) {
5441 return (pixelWidth % 2 === 0) ? 0 : 0.5;
5442 };
5443 helpers.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
5444 // Props to Rob Spencer at scaled innovation for his post on splining between points
5445 // http://scaledinnovation.com/analytics/splines/aboutSplines.html
5446
5447 // This function must also respect "skipped" points
5448
5449 var previous = firstPoint.skip ? middlePoint : firstPoint;
5450 var current = middlePoint;
5451 var next = afterPoint.skip ? middlePoint : afterPoint;
5452
5453 var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
5454 var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
5455
5456 var s01 = d01 / (d01 + d12);
5457 var s12 = d12 / (d01 + d12);
5458
5459 // If all points are the same, s01 & s02 will be inf
5460 s01 = isNaN(s01) ? 0 : s01;
5461 s12 = isNaN(s12) ? 0 : s12;
5462
5463 var fa = t * s01; // scaling factor for triangle Ta
5464 var fb = t * s12;
5465
5466 return {
5467 previous: {
5468 x: current.x - fa * (next.x - previous.x),
5469 y: current.y - fa * (next.y - previous.y)
5470 },
5471 next: {
5472 x: current.x + fb * (next.x - previous.x),
5473 y: current.y + fb * (next.y - previous.y)
5474 }
5475 };
5476 };
5477 helpers.EPSILON = Number.EPSILON || 1e-14;
5478 helpers.splineCurveMonotone = function(points) {
5479 // This function calculates Bézier control points in a similar way than |splineCurve|,
5480 // but preserves monotonicity of the provided data and ensures no local extremums are added
5481 // between the dataset discrete points due to the interpolation.
5482 // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
5483
5484 var pointsWithTangents = (points || []).map(function(point) {
5485 return {
5486 model: point._model,
5487 deltaK: 0,
5488 mK: 0
5489 };
5490 });
5491
5492 // Calculate slopes (deltaK) and initialize tangents (mK)
5493 var pointsLen = pointsWithTangents.length;
5494 var i, pointBefore, pointCurrent, pointAfter;
5495 for (i = 0; i < pointsLen; ++i) {
5496 pointCurrent = pointsWithTangents[i];
5497 if (pointCurrent.model.skip) {
5498 continue;
5499 }
5500
5501 pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
5502 pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
5503 if (pointAfter && !pointAfter.model.skip) {
5504 var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
5505
5506 // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
5507 pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
5508 }
5509
5510 if (!pointBefore || pointBefore.model.skip) {
5511 pointCurrent.mK = pointCurrent.deltaK;
5512 } else if (!pointAfter || pointAfter.model.skip) {
5513 pointCurrent.mK = pointBefore.deltaK;
5514 } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
5515 pointCurrent.mK = 0;
5516 } else {
5517 pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
5518 }
5519 }
5520
5521 // Adjust tangents to ensure monotonic properties
5522 var alphaK, betaK, tauK, squaredMagnitude;
5523 for (i = 0; i < pointsLen - 1; ++i) {
5524 pointCurrent = pointsWithTangents[i];
5525 pointAfter = pointsWithTangents[i + 1];
5526 if (pointCurrent.model.skip || pointAfter.model.skip) {
5527 continue;
5528 }
5529
5530 if (helpers.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
5531 pointCurrent.mK = pointAfter.mK = 0;
5532 continue;
5533 }
5534
5535 alphaK = pointCurrent.mK / pointCurrent.deltaK;
5536 betaK = pointAfter.mK / pointCurrent.deltaK;
5537 squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
5538 if (squaredMagnitude <= 9) {
5539 continue;
5540 }
5541
5542 tauK = 3 / Math.sqrt(squaredMagnitude);
5543 pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
5544 pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
5545 }
5546
5547 // Compute control points
5548 var deltaX;
5549 for (i = 0; i < pointsLen; ++i) {
5550 pointCurrent = pointsWithTangents[i];
5551 if (pointCurrent.model.skip) {
5552 continue;
5553 }
5554
5555 pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
5556 pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
5557 if (pointBefore && !pointBefore.model.skip) {
5558 deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
5559 pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
5560 pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
5561 }
5562 if (pointAfter && !pointAfter.model.skip) {
5563 deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
5564 pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
5565 pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
5566 }
5567 }
5568 };
5569 helpers.nextItem = function(collection, index, loop) {
5570 if (loop) {
5571 return index >= collection.length - 1 ? collection[0] : collection[index + 1];
5572 }
5573 return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
5574 };
5575 helpers.previousItem = function(collection, index, loop) {
5576 if (loop) {
5577 return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
5578 }
5579 return index <= 0 ? collection[0] : collection[index - 1];
5580 };
5581 // Implementation of the nice number algorithm used in determining where axis labels will go
5582 helpers.niceNum = function(range, round) {
5583 var exponent = Math.floor(helpers.log10(range));
5584 var fraction = range / Math.pow(10, exponent);
5585 var niceFraction;
5586
5587 if (round) {
5588 if (fraction < 1.5) {
5589 niceFraction = 1;
5590 } else if (fraction < 3) {
5591 niceFraction = 2;
5592 } else if (fraction < 7) {
5593 niceFraction = 5;
5594 } else {
5595 niceFraction = 10;
5596 }
5597 } else if (fraction <= 1.0) {
5598 niceFraction = 1;
5599 } else if (fraction <= 2) {
5600 niceFraction = 2;
5601 } else if (fraction <= 5) {
5602 niceFraction = 5;
5603 } else {
5604 niceFraction = 10;
5605 }
5606
5607 return niceFraction * Math.pow(10, exponent);
5608 };
5609 // Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
5610 helpers.requestAnimFrame = (function() {
5611 if (typeof window === 'undefined') {
5612 return function(callback) {
5613 callback();
5614 };
5615 }
5616 return window.requestAnimationFrame ||
5617 window.webkitRequestAnimationFrame ||
5618 window.mozRequestAnimationFrame ||
5619 window.oRequestAnimationFrame ||
5620 window.msRequestAnimationFrame ||
5621 function(callback) {
5622 return window.setTimeout(callback, 1000 / 60);
5623 };
5624 }());
5625 // -- DOM methods
5626 helpers.getRelativePosition = function(evt, chart) {
5627 var mouseX, mouseY;
5628 var e = evt.originalEvent || evt;
5629 var canvas = evt.currentTarget || evt.srcElement;
5630 var boundingRect = canvas.getBoundingClientRect();
5631
5632 var touches = e.touches;
5633 if (touches && touches.length > 0) {
5634 mouseX = touches[0].clientX;
5635 mouseY = touches[0].clientY;
5636
5637 } else {
5638 mouseX = e.clientX;
5639 mouseY = e.clientY;
5640 }
5641
5642 // Scale mouse coordinates into canvas coordinates
5643 // by following the pattern laid out by 'jerryj' in the comments of
5644 // http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
5645 var paddingLeft = parseFloat(helpers.getStyle(canvas, 'padding-left'));
5646 var paddingTop = parseFloat(helpers.getStyle(canvas, 'padding-top'));
5647 var paddingRight = parseFloat(helpers.getStyle(canvas, 'padding-right'));
5648 var paddingBottom = parseFloat(helpers.getStyle(canvas, 'padding-bottom'));
5649 var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
5650 var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
5651
5652 // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
5653 // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
5654 mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
5655 mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
5656
5657 return {
5658 x: mouseX,
5659 y: mouseY
5660 };
5661
5662 };
5663
5664 // Private helper function to convert max-width/max-height values that may be percentages into a number
5665 function parseMaxStyle(styleValue, node, parentProperty) {
5666 var valueInPixels;
5667 if (typeof styleValue === 'string') {
5668 valueInPixels = parseInt(styleValue, 10);
5669
5670 if (styleValue.indexOf('%') !== -1) {
5671 // percentage * size in dimension
5672 valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
5673 }
5674 } else {
5675 valueInPixels = styleValue;
5676 }
5677
5678 return valueInPixels;
5679 }
5680
5681 /**
5682 * Returns if the given value contains an effective constraint.
5683 * @private
5684 */
5685 function isConstrainedValue(value) {
5686 return value !== undefined && value !== null && value !== 'none';
5687 }
5688
5689 // Private helper to get a constraint dimension
5690 // @param domNode : the node to check the constraint on
5691 // @param maxStyle : the style that defines the maximum for the direction we are using (maxWidth / maxHeight)
5692 // @param percentageProperty : property of parent to use when calculating width as a percentage
5693 // @see http://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser
5694 function getConstraintDimension(domNode, maxStyle, percentageProperty) {
5695 var view = document.defaultView;
5696 var parentNode = domNode.parentNode;
5697 var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
5698 var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
5699 var hasCNode = isConstrainedValue(constrainedNode);
5700 var hasCContainer = isConstrainedValue(constrainedContainer);
5701 var infinity = Number.POSITIVE_INFINITY;
5702
5703 if (hasCNode || hasCContainer) {
5704 return Math.min(
5705 hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
5706 hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
5707 }
5708
5709 return 'none';
5710 }
5711 // returns Number or undefined if no constraint
5712 helpers.getConstraintWidth = function(domNode) {
5713 return getConstraintDimension(domNode, 'max-width', 'clientWidth');
5714 };
5715 // returns Number or undefined if no constraint
5716 helpers.getConstraintHeight = function(domNode) {
5717 return getConstraintDimension(domNode, 'max-height', 'clientHeight');
5718 };
5719 helpers.getMaximumWidth = function(domNode) {
5720 var container = domNode.parentNode;
5721 if (!container) {
5722 return domNode.clientWidth;
5723 }
5724
5725 var paddingLeft = parseInt(helpers.getStyle(container, 'padding-left'), 10);
5726 var paddingRight = parseInt(helpers.getStyle(container, 'padding-right'), 10);
5727 var w = container.clientWidth - paddingLeft - paddingRight;
5728 var cw = helpers.getConstraintWidth(domNode);
5729 return isNaN(cw) ? w : Math.min(w, cw);
5730 };
5731 helpers.getMaximumHeight = function(domNode) {
5732 var container = domNode.parentNode;
5733 if (!container) {
5734 return domNode.clientHeight;
5735 }
5736
5737 var paddingTop = parseInt(helpers.getStyle(container, 'padding-top'), 10);
5738 var paddingBottom = parseInt(helpers.getStyle(container, 'padding-bottom'), 10);
5739 var h = container.clientHeight - paddingTop - paddingBottom;
5740 var ch = helpers.getConstraintHeight(domNode);
5741 return isNaN(ch) ? h : Math.min(h, ch);
5742 };
5743 helpers.getStyle = function(el, property) {
5744 return el.currentStyle ?
5745 el.currentStyle[property] :
5746 document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
5747 };
5748 helpers.retinaScale = function(chart, forceRatio) {
5749 var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
5750 if (pixelRatio === 1) {
5751 return;
5752 }
5753
5754 var canvas = chart.canvas;
5755 var height = chart.height;
5756 var width = chart.width;
5757
5758 canvas.height = height * pixelRatio;
5759 canvas.width = width * pixelRatio;
5760 chart.ctx.scale(pixelRatio, pixelRatio);
5761
5762 // If no style has been set on the canvas, the render size is used as display size,
5763 // making the chart visually bigger, so let's enforce it to the "correct" values.
5764 // See https://github.com/chartjs/Chart.js/issues/3575
5765 if (!canvas.style.height && !canvas.style.width) {
5766 canvas.style.height = height + 'px';
5767 canvas.style.width = width + 'px';
5768 }
5769 };
5770 // -- Canvas methods
5771 helpers.fontString = function(pixelSize, fontStyle, fontFamily) {
5772 return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
5773 };
5774 helpers.longestText = function(ctx, font, arrayOfThings, cache) {
5775 cache = cache || {};
5776 var data = cache.data = cache.data || {};
5777 var gc = cache.garbageCollect = cache.garbageCollect || [];
5778
5779 if (cache.font !== font) {
5780 data = cache.data = {};
5781 gc = cache.garbageCollect = [];
5782 cache.font = font;
5783 }
5784
5785 ctx.font = font;
5786 var longest = 0;
5787 helpers.each(arrayOfThings, function(thing) {
5788 // Undefined strings and arrays should not be measured
5789 if (thing !== undefined && thing !== null && helpers.isArray(thing) !== true) {
5790 longest = helpers.measureText(ctx, data, gc, longest, thing);
5791 } else if (helpers.isArray(thing)) {
5792 // if it is an array lets measure each element
5793 // to do maybe simplify this function a bit so we can do this more recursively?
5794 helpers.each(thing, function(nestedThing) {
5795 // Undefined strings and arrays should not be measured
5796 if (nestedThing !== undefined && nestedThing !== null && !helpers.isArray(nestedThing)) {
5797 longest = helpers.measureText(ctx, data, gc, longest, nestedThing);
5798 }
5799 });
5800 }
5801 });
5802
5803 var gcLen = gc.length / 2;
5804 if (gcLen > arrayOfThings.length) {
5805 for (var i = 0; i < gcLen; i++) {
5806 delete data[gc[i]];
5807 }
5808 gc.splice(0, gcLen);
5809 }
5810 return longest;
5811 };
5812 helpers.measureText = function(ctx, data, gc, longest, string) {
5813 var textWidth = data[string];
5814 if (!textWidth) {
5815 textWidth = data[string] = ctx.measureText(string).width;
5816 gc.push(string);
5817 }
5818 if (textWidth > longest) {
5819 longest = textWidth;
5820 }
5821 return longest;
5822 };
5823 helpers.numberOfLabelLines = function(arrayOfThings) {
5824 var numberOfLines = 1;
5825 helpers.each(arrayOfThings, function(thing) {
5826 if (helpers.isArray(thing)) {
5827 if (thing.length > numberOfLines) {
5828 numberOfLines = thing.length;
5829 }
5830 }
5831 });
5832 return numberOfLines;
5833 };
5834
5835 helpers.color = !color ?
5836 function(value) {
5837 console.error('Color.js not found!');
5838 return value;
5839 } :
5840 function(value) {
5841 /* global CanvasGradient */
5842 if (value instanceof CanvasGradient) {
5843 value = defaults.global.defaultColor;
5844 }
5845
5846 return color(value);
5847 };
5848
5849 helpers.getHoverColor = function(colorValue) {
5850 /* global CanvasPattern */
5851 return (colorValue instanceof CanvasPattern) ?
5852 colorValue :
5853 helpers.color(colorValue).saturate(0.5).darken(0.1).rgbString();
5854 };
5855};
5856
5857},{"26":26,"3":3,"34":34,"46":46}],29:[function(require,module,exports){
5858'use strict';
5859
5860var helpers = require(46);
5861
5862/**
5863 * Helper function to get relative position for an event
5864 * @param {Event|IEvent} event - The event to get the position for
5865 * @param {Chart} chart - The chart
5866 * @returns {Point} the event position
5867 */
5868function getRelativePosition(e, chart) {
5869 if (e.native) {
5870 return {
5871 x: e.x,
5872 y: e.y
5873 };
5874 }
5875
5876 return helpers.getRelativePosition(e, chart);
5877}
5878
5879/**
5880 * Helper function to traverse all of the visible elements in the chart
5881 * @param chart {chart} the chart
5882 * @param handler {Function} the callback to execute for each visible item
5883 */
5884function parseVisibleItems(chart, handler) {
5885 var datasets = chart.data.datasets;
5886 var meta, i, j, ilen, jlen;
5887
5888 for (i = 0, ilen = datasets.length; i < ilen; ++i) {
5889 if (!chart.isDatasetVisible(i)) {
5890 continue;
5891 }
5892
5893 meta = chart.getDatasetMeta(i);
5894 for (j = 0, jlen = meta.data.length; j < jlen; ++j) {
5895 var element = meta.data[j];
5896 if (!element._view.skip) {
5897 handler(element);
5898 }
5899 }
5900 }
5901}
5902
5903/**
5904 * Helper function to get the items that intersect the event position
5905 * @param items {ChartElement[]} elements to filter
5906 * @param position {Point} the point to be nearest to
5907 * @return {ChartElement[]} the nearest items
5908 */
5909function getIntersectItems(chart, position) {
5910 var elements = [];
5911
5912 parseVisibleItems(chart, function(element) {
5913 if (element.inRange(position.x, position.y)) {
5914 elements.push(element);
5915 }
5916 });
5917
5918 return elements;
5919}
5920
5921/**
5922 * Helper function to get the items nearest to the event position considering all visible items in teh chart
5923 * @param chart {Chart} the chart to look at elements from
5924 * @param position {Point} the point to be nearest to
5925 * @param intersect {Boolean} if true, only consider items that intersect the position
5926 * @param distanceMetric {Function} function to provide the distance between points
5927 * @return {ChartElement[]} the nearest items
5928 */
5929function getNearestItems(chart, position, intersect, distanceMetric) {
5930 var minDistance = Number.POSITIVE_INFINITY;
5931 var nearestItems = [];
5932
5933 parseVisibleItems(chart, function(element) {
5934 if (intersect && !element.inRange(position.x, position.y)) {
5935 return;
5936 }
5937
5938 var center = element.getCenterPoint();
5939 var distance = distanceMetric(position, center);
5940
5941 if (distance < minDistance) {
5942 nearestItems = [element];
5943 minDistance = distance;
5944 } else if (distance === minDistance) {
5945 // Can have multiple items at the same distance in which case we sort by size
5946 nearestItems.push(element);
5947 }
5948 });
5949
5950 return nearestItems;
5951}
5952
5953/**
5954 * Get a distance metric function for two points based on the
5955 * axis mode setting
5956 * @param {String} axis the axis mode. x|y|xy
5957 */
5958function getDistanceMetricForAxis(axis) {
5959 var useX = axis.indexOf('x') !== -1;
5960 var useY = axis.indexOf('y') !== -1;
5961
5962 return function(pt1, pt2) {
5963 var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
5964 var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
5965 return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
5966 };
5967}
5968
5969function indexMode(chart, e, options) {
5970 var position = getRelativePosition(e, chart);
5971 // Default axis for index mode is 'x' to match old behaviour
5972 options.axis = options.axis || 'x';
5973 var distanceMetric = getDistanceMetricForAxis(options.axis);
5974 var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
5975 var elements = [];
5976
5977 if (!items.length) {
5978 return [];
5979 }
5980
5981 chart.data.datasets.forEach(function(dataset, datasetIndex) {
5982 if (chart.isDatasetVisible(datasetIndex)) {
5983 var meta = chart.getDatasetMeta(datasetIndex);
5984 var element = meta.data[items[0]._index];
5985
5986 // don't count items that are skipped (null data)
5987 if (element && !element._view.skip) {
5988 elements.push(element);
5989 }
5990 }
5991 });
5992
5993 return elements;
5994}
5995
5996/**
5997 * @interface IInteractionOptions
5998 */
5999/**
6000 * If true, only consider items that intersect the point
6001 * @name IInterfaceOptions#boolean
6002 * @type Boolean
6003 */
6004
6005/**
6006 * Contains interaction related functions
6007 * @namespace Chart.Interaction
6008 */
6009module.exports = {
6010 // Helper function for different modes
6011 modes: {
6012 single: function(chart, e) {
6013 var position = getRelativePosition(e, chart);
6014 var elements = [];
6015
6016 parseVisibleItems(chart, function(element) {
6017 if (element.inRange(position.x, position.y)) {
6018 elements.push(element);
6019 return elements;
6020 }
6021 });
6022
6023 return elements.slice(0, 1);
6024 },
6025
6026 /**
6027 * @function Chart.Interaction.modes.label
6028 * @deprecated since version 2.4.0
6029 * @todo remove at version 3
6030 * @private
6031 */
6032 label: indexMode,
6033
6034 /**
6035 * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
6036 * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
6037 * @function Chart.Interaction.modes.index
6038 * @since v2.4.0
6039 * @param chart {chart} the chart we are returning items from
6040 * @param e {Event} the event we are find things at
6041 * @param options {IInteractionOptions} options to use during interaction
6042 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
6043 */
6044 index: indexMode,
6045
6046 /**
6047 * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
6048 * If the options.intersect is false, we find the nearest item and return the items in that dataset
6049 * @function Chart.Interaction.modes.dataset
6050 * @param chart {chart} the chart we are returning items from
6051 * @param e {Event} the event we are find things at
6052 * @param options {IInteractionOptions} options to use during interaction
6053 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
6054 */
6055 dataset: function(chart, e, options) {
6056 var position = getRelativePosition(e, chart);
6057 options.axis = options.axis || 'xy';
6058 var distanceMetric = getDistanceMetricForAxis(options.axis);
6059 var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
6060
6061 if (items.length > 0) {
6062 items = chart.getDatasetMeta(items[0]._datasetIndex).data;
6063 }
6064
6065 return items;
6066 },
6067
6068 /**
6069 * @function Chart.Interaction.modes.x-axis
6070 * @deprecated since version 2.4.0. Use index mode and intersect == true
6071 * @todo remove at version 3
6072 * @private
6073 */
6074 'x-axis': function(chart, e) {
6075 return indexMode(chart, e, {intersect: false});
6076 },
6077
6078 /**
6079 * Point mode returns all elements that hit test based on the event position
6080 * of the event
6081 * @function Chart.Interaction.modes.intersect
6082 * @param chart {chart} the chart we are returning items from
6083 * @param e {Event} the event we are find things at
6084 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
6085 */
6086 point: function(chart, e) {
6087 var position = getRelativePosition(e, chart);
6088 return getIntersectItems(chart, position);
6089 },
6090
6091 /**
6092 * nearest mode returns the element closest to the point
6093 * @function Chart.Interaction.modes.intersect
6094 * @param chart {chart} the chart we are returning items from
6095 * @param e {Event} the event we are find things at
6096 * @param options {IInteractionOptions} options to use
6097 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
6098 */
6099 nearest: function(chart, e, options) {
6100 var position = getRelativePosition(e, chart);
6101 options.axis = options.axis || 'xy';
6102 var distanceMetric = getDistanceMetricForAxis(options.axis);
6103 var nearestItems = getNearestItems(chart, position, options.intersect, distanceMetric);
6104
6105 // We have multiple items at the same distance from the event. Now sort by smallest
6106 if (nearestItems.length > 1) {
6107 nearestItems.sort(function(a, b) {
6108 var sizeA = a.getArea();
6109 var sizeB = b.getArea();
6110 var ret = sizeA - sizeB;
6111
6112 if (ret === 0) {
6113 // if equal sort by dataset index
6114 ret = a._datasetIndex - b._datasetIndex;
6115 }
6116
6117 return ret;
6118 });
6119 }
6120
6121 // Return only 1 item
6122 return nearestItems.slice(0, 1);
6123 },
6124
6125 /**
6126 * x mode returns the elements that hit-test at the current x coordinate
6127 * @function Chart.Interaction.modes.x
6128 * @param chart {chart} the chart we are returning items from
6129 * @param e {Event} the event we are find things at
6130 * @param options {IInteractionOptions} options to use
6131 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
6132 */
6133 x: function(chart, e, options) {
6134 var position = getRelativePosition(e, chart);
6135 var items = [];
6136 var intersectsItem = false;
6137
6138 parseVisibleItems(chart, function(element) {
6139 if (element.inXRange(position.x)) {
6140 items.push(element);
6141 }
6142
6143 if (element.inRange(position.x, position.y)) {
6144 intersectsItem = true;
6145 }
6146 });
6147
6148 // If we want to trigger on an intersect and we don't have any items
6149 // that intersect the position, return nothing
6150 if (options.intersect && !intersectsItem) {
6151 items = [];
6152 }
6153 return items;
6154 },
6155
6156 /**
6157 * y mode returns the elements that hit-test at the current y coordinate
6158 * @function Chart.Interaction.modes.y
6159 * @param chart {chart} the chart we are returning items from
6160 * @param e {Event} the event we are find things at
6161 * @param options {IInteractionOptions} options to use
6162 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
6163 */
6164 y: function(chart, e, options) {
6165 var position = getRelativePosition(e, chart);
6166 var items = [];
6167 var intersectsItem = false;
6168
6169 parseVisibleItems(chart, function(element) {
6170 if (element.inYRange(position.y)) {
6171 items.push(element);
6172 }
6173
6174 if (element.inRange(position.x, position.y)) {
6175 intersectsItem = true;
6176 }
6177 });
6178
6179 // If we want to trigger on an intersect and we don't have any items
6180 // that intersect the position, return nothing
6181 if (options.intersect && !intersectsItem) {
6182 items = [];
6183 }
6184 return items;
6185 }
6186 }
6187};
6188
6189},{"46":46}],30:[function(require,module,exports){
6190'use strict';
6191
6192var defaults = require(26);
6193
6194defaults._set('global', {
6195 responsive: true,
6196 responsiveAnimationDuration: 0,
6197 maintainAspectRatio: true,
6198 events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
6199 hover: {
6200 onHover: null,
6201 mode: 'nearest',
6202 intersect: true,
6203 animationDuration: 400
6204 },
6205 onClick: null,
6206 defaultColor: 'rgba(0,0,0,0.1)',
6207 defaultFontColor: '#666',
6208 defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
6209 defaultFontSize: 12,
6210 defaultFontStyle: 'normal',
6211 showLines: true,
6212
6213 // Element defaults defined in element extensions
6214 elements: {},
6215
6216 // Layout options such as padding
6217 layout: {
6218 padding: {
6219 top: 0,
6220 right: 0,
6221 bottom: 0,
6222 left: 0
6223 }
6224 }
6225});
6226
6227module.exports = function() {
6228
6229 // Occupy the global variable of Chart, and create a simple base class
6230 var Chart = function(item, config) {
6231 this.construct(item, config);
6232 return this;
6233 };
6234
6235 Chart.Chart = Chart;
6236
6237 return Chart;
6238};
6239
6240},{"26":26}],31:[function(require,module,exports){
6241'use strict';
6242
6243var helpers = require(46);
6244
6245function filterByPosition(array, position) {
6246 return helpers.where(array, function(v) {
6247 return v.position === position;
6248 });
6249}
6250
6251function sortByWeight(array, reverse) {
6252 array.forEach(function(v, i) {
6253 v._tmpIndex_ = i;
6254 return v;
6255 });
6256 array.sort(function(a, b) {
6257 var v0 = reverse ? b : a;
6258 var v1 = reverse ? a : b;
6259 return v0.weight === v1.weight ?
6260 v0._tmpIndex_ - v1._tmpIndex_ :
6261 v0.weight - v1.weight;
6262 });
6263 array.forEach(function(v) {
6264 delete v._tmpIndex_;
6265 });
6266}
6267
6268/**
6269 * @interface ILayoutItem
6270 * @prop {String} position - The position of the item in the chart layout. Possible values are
6271 * 'left', 'top', 'right', 'bottom', and 'chartArea'
6272 * @prop {Number} weight - The weight used to sort the item. Higher weights are further away from the chart area
6273 * @prop {Boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
6274 * @prop {Function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
6275 * @prop {Function} update - Takes two parameters: width and height. Returns size of item
6276 * @prop {Function} getPadding - Returns an object with padding on the edges
6277 * @prop {Number} width - Width of item. Must be valid after update()
6278 * @prop {Number} height - Height of item. Must be valid after update()
6279 * @prop {Number} left - Left edge of the item. Set by layout system and cannot be used in update
6280 * @prop {Number} top - Top edge of the item. Set by layout system and cannot be used in update
6281 * @prop {Number} right - Right edge of the item. Set by layout system and cannot be used in update
6282 * @prop {Number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
6283 */
6284
6285// The layout service is very self explanatory. It's responsible for the layout within a chart.
6286// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
6287// It is this service's responsibility of carrying out that layout.
6288module.exports = {
6289 defaults: {},
6290
6291 /**
6292 * Register a box to a chart.
6293 * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
6294 * @param {Chart} chart - the chart to use
6295 * @param {ILayoutItem} item - the item to add to be layed out
6296 */
6297 addBox: function(chart, item) {
6298 if (!chart.boxes) {
6299 chart.boxes = [];
6300 }
6301
6302 // initialize item with default values
6303 item.fullWidth = item.fullWidth || false;
6304 item.position = item.position || 'top';
6305 item.weight = item.weight || 0;
6306
6307 chart.boxes.push(item);
6308 },
6309
6310 /**
6311 * Remove a layoutItem from a chart
6312 * @param {Chart} chart - the chart to remove the box from
6313 * @param {Object} layoutItem - the item to remove from the layout
6314 */
6315 removeBox: function(chart, layoutItem) {
6316 var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
6317 if (index !== -1) {
6318 chart.boxes.splice(index, 1);
6319 }
6320 },
6321
6322 /**
6323 * Sets (or updates) options on the given `item`.
6324 * @param {Chart} chart - the chart in which the item lives (or will be added to)
6325 * @param {Object} item - the item to configure with the given options
6326 * @param {Object} options - the new item options.
6327 */
6328 configure: function(chart, item, options) {
6329 var props = ['fullWidth', 'position', 'weight'];
6330 var ilen = props.length;
6331 var i = 0;
6332 var prop;
6333
6334 for (; i < ilen; ++i) {
6335 prop = props[i];
6336 if (options.hasOwnProperty(prop)) {
6337 item[prop] = options[prop];
6338 }
6339 }
6340 },
6341
6342 /**
6343 * Fits boxes of the given chart into the given size by having each box measure itself
6344 * then running a fitting algorithm
6345 * @param {Chart} chart - the chart
6346 * @param {Number} width - the width to fit into
6347 * @param {Number} height - the height to fit into
6348 */
6349 update: function(chart, width, height) {
6350 if (!chart) {
6351 return;
6352 }
6353
6354 var layoutOptions = chart.options.layout || {};
6355 var padding = helpers.options.toPadding(layoutOptions.padding);
6356 var leftPadding = padding.left;
6357 var rightPadding = padding.right;
6358 var topPadding = padding.top;
6359 var bottomPadding = padding.bottom;
6360
6361 var leftBoxes = filterByPosition(chart.boxes, 'left');
6362 var rightBoxes = filterByPosition(chart.boxes, 'right');
6363 var topBoxes = filterByPosition(chart.boxes, 'top');
6364 var bottomBoxes = filterByPosition(chart.boxes, 'bottom');
6365 var chartAreaBoxes = filterByPosition(chart.boxes, 'chartArea');
6366
6367 // Sort boxes by weight. A higher weight is further away from the chart area
6368 sortByWeight(leftBoxes, true);
6369 sortByWeight(rightBoxes, false);
6370 sortByWeight(topBoxes, true);
6371 sortByWeight(bottomBoxes, false);
6372
6373 // Essentially we now have any number of boxes on each of the 4 sides.
6374 // Our canvas looks like the following.
6375 // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
6376 // B1 is the bottom axis
6377 // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
6378 // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
6379 // an error will be thrown.
6380 //
6381 // |----------------------------------------------------|
6382 // | T1 (Full Width) |
6383 // |----------------------------------------------------|
6384 // | | | T2 | |
6385 // | |----|-------------------------------------|----|
6386 // | | | C1 | | C2 | |
6387 // | | |----| |----| |
6388 // | | | | |
6389 // | L1 | L2 | ChartArea (C0) | R1 |
6390 // | | | | |
6391 // | | |----| |----| |
6392 // | | | C3 | | C4 | |
6393 // | |----|-------------------------------------|----|
6394 // | | | B1 | |
6395 // |----------------------------------------------------|
6396 // | B2 (Full Width) |
6397 // |----------------------------------------------------|
6398 //
6399 // What we do to find the best sizing, we do the following
6400 // 1. Determine the minimum size of the chart area.
6401 // 2. Split the remaining width equally between each vertical axis
6402 // 3. Split the remaining height equally between each horizontal axis
6403 // 4. Give each layout the maximum size it can be. The layout will return it's minimum size
6404 // 5. Adjust the sizes of each axis based on it's minimum reported size.
6405 // 6. Refit each axis
6406 // 7. Position each axis in the final location
6407 // 8. Tell the chart the final location of the chart area
6408 // 9. Tell any axes that overlay the chart area the positions of the chart area
6409
6410 // Step 1
6411 var chartWidth = width - leftPadding - rightPadding;
6412 var chartHeight = height - topPadding - bottomPadding;
6413 var chartAreaWidth = chartWidth / 2; // min 50%
6414 var chartAreaHeight = chartHeight / 2; // min 50%
6415
6416 // Step 2
6417 var verticalBoxWidth = (width - chartAreaWidth) / (leftBoxes.length + rightBoxes.length);
6418
6419 // Step 3
6420 var horizontalBoxHeight = (height - chartAreaHeight) / (topBoxes.length + bottomBoxes.length);
6421
6422 // Step 4
6423 var maxChartAreaWidth = chartWidth;
6424 var maxChartAreaHeight = chartHeight;
6425 var minBoxSizes = [];
6426
6427 function getMinimumBoxSize(box) {
6428 var minSize;
6429 var isHorizontal = box.isHorizontal();
6430
6431 if (isHorizontal) {
6432 minSize = box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, horizontalBoxHeight);
6433 maxChartAreaHeight -= minSize.height;
6434 } else {
6435 minSize = box.update(verticalBoxWidth, maxChartAreaHeight);
6436 maxChartAreaWidth -= minSize.width;
6437 }
6438
6439 minBoxSizes.push({
6440 horizontal: isHorizontal,
6441 minSize: minSize,
6442 box: box,
6443 });
6444 }
6445
6446 helpers.each(leftBoxes.concat(rightBoxes, topBoxes, bottomBoxes), getMinimumBoxSize);
6447
6448 // If a horizontal box has padding, we move the left boxes over to avoid ugly charts (see issue #2478)
6449 var maxHorizontalLeftPadding = 0;
6450 var maxHorizontalRightPadding = 0;
6451 var maxVerticalTopPadding = 0;
6452 var maxVerticalBottomPadding = 0;
6453
6454 helpers.each(topBoxes.concat(bottomBoxes), function(horizontalBox) {
6455 if (horizontalBox.getPadding) {
6456 var boxPadding = horizontalBox.getPadding();
6457 maxHorizontalLeftPadding = Math.max(maxHorizontalLeftPadding, boxPadding.left);
6458 maxHorizontalRightPadding = Math.max(maxHorizontalRightPadding, boxPadding.right);
6459 }
6460 });
6461
6462 helpers.each(leftBoxes.concat(rightBoxes), function(verticalBox) {
6463 if (verticalBox.getPadding) {
6464 var boxPadding = verticalBox.getPadding();
6465 maxVerticalTopPadding = Math.max(maxVerticalTopPadding, boxPadding.top);
6466 maxVerticalBottomPadding = Math.max(maxVerticalBottomPadding, boxPadding.bottom);
6467 }
6468 });
6469
6470 // At this point, maxChartAreaHeight and maxChartAreaWidth are the size the chart area could
6471 // be if the axes are drawn at their minimum sizes.
6472 // Steps 5 & 6
6473 var totalLeftBoxesWidth = leftPadding;
6474 var totalRightBoxesWidth = rightPadding;
6475 var totalTopBoxesHeight = topPadding;
6476 var totalBottomBoxesHeight = bottomPadding;
6477
6478 // Function to fit a box
6479 function fitBox(box) {
6480 var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minBox) {
6481 return minBox.box === box;
6482 });
6483
6484 if (minBoxSize) {
6485 if (box.isHorizontal()) {
6486 var scaleMargin = {
6487 left: Math.max(totalLeftBoxesWidth, maxHorizontalLeftPadding),
6488 right: Math.max(totalRightBoxesWidth, maxHorizontalRightPadding),
6489 top: 0,
6490 bottom: 0
6491 };
6492
6493 // Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends
6494 // on the margin. Sometimes they need to increase in size slightly
6495 box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin);
6496 } else {
6497 box.update(minBoxSize.minSize.width, maxChartAreaHeight);
6498 }
6499 }
6500 }
6501
6502 // Update, and calculate the left and right margins for the horizontal boxes
6503 helpers.each(leftBoxes.concat(rightBoxes), fitBox);
6504
6505 helpers.each(leftBoxes, function(box) {
6506 totalLeftBoxesWidth += box.width;
6507 });
6508
6509 helpers.each(rightBoxes, function(box) {
6510 totalRightBoxesWidth += box.width;
6511 });
6512
6513 // Set the Left and Right margins for the horizontal boxes
6514 helpers.each(topBoxes.concat(bottomBoxes), fitBox);
6515
6516 // Figure out how much margin is on the top and bottom of the vertical boxes
6517 helpers.each(topBoxes, function(box) {
6518 totalTopBoxesHeight += box.height;
6519 });
6520
6521 helpers.each(bottomBoxes, function(box) {
6522 totalBottomBoxesHeight += box.height;
6523 });
6524
6525 function finalFitVerticalBox(box) {
6526 var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minSize) {
6527 return minSize.box === box;
6528 });
6529
6530 var scaleMargin = {
6531 left: 0,
6532 right: 0,
6533 top: totalTopBoxesHeight,
6534 bottom: totalBottomBoxesHeight
6535 };
6536
6537 if (minBoxSize) {
6538 box.update(minBoxSize.minSize.width, maxChartAreaHeight, scaleMargin);
6539 }
6540 }
6541
6542 // Let the left layout know the final margin
6543 helpers.each(leftBoxes.concat(rightBoxes), finalFitVerticalBox);
6544
6545 // Recalculate because the size of each layout might have changed slightly due to the margins (label rotation for instance)
6546 totalLeftBoxesWidth = leftPadding;
6547 totalRightBoxesWidth = rightPadding;
6548 totalTopBoxesHeight = topPadding;
6549 totalBottomBoxesHeight = bottomPadding;
6550
6551 helpers.each(leftBoxes, function(box) {
6552 totalLeftBoxesWidth += box.width;
6553 });
6554
6555 helpers.each(rightBoxes, function(box) {
6556 totalRightBoxesWidth += box.width;
6557 });
6558
6559 helpers.each(topBoxes, function(box) {
6560 totalTopBoxesHeight += box.height;
6561 });
6562 helpers.each(bottomBoxes, function(box) {
6563 totalBottomBoxesHeight += box.height;
6564 });
6565
6566 // We may be adding some padding to account for rotated x axis labels
6567 var leftPaddingAddition = Math.max(maxHorizontalLeftPadding - totalLeftBoxesWidth, 0);
6568 totalLeftBoxesWidth += leftPaddingAddition;
6569 totalRightBoxesWidth += Math.max(maxHorizontalRightPadding - totalRightBoxesWidth, 0);
6570
6571 var topPaddingAddition = Math.max(maxVerticalTopPadding - totalTopBoxesHeight, 0);
6572 totalTopBoxesHeight += topPaddingAddition;
6573 totalBottomBoxesHeight += Math.max(maxVerticalBottomPadding - totalBottomBoxesHeight, 0);
6574
6575 // Figure out if our chart area changed. This would occur if the dataset layout label rotation
6576 // changed due to the application of the margins in step 6. Since we can only get bigger, this is safe to do
6577 // without calling `fit` again
6578 var newMaxChartAreaHeight = height - totalTopBoxesHeight - totalBottomBoxesHeight;
6579 var newMaxChartAreaWidth = width - totalLeftBoxesWidth - totalRightBoxesWidth;
6580
6581 if (newMaxChartAreaWidth !== maxChartAreaWidth || newMaxChartAreaHeight !== maxChartAreaHeight) {
6582 helpers.each(leftBoxes, function(box) {
6583 box.height = newMaxChartAreaHeight;
6584 });
6585
6586 helpers.each(rightBoxes, function(box) {
6587 box.height = newMaxChartAreaHeight;
6588 });
6589
6590 helpers.each(topBoxes, function(box) {
6591 if (!box.fullWidth) {
6592 box.width = newMaxChartAreaWidth;
6593 }
6594 });
6595
6596 helpers.each(bottomBoxes, function(box) {
6597 if (!box.fullWidth) {
6598 box.width = newMaxChartAreaWidth;
6599 }
6600 });
6601
6602 maxChartAreaHeight = newMaxChartAreaHeight;
6603 maxChartAreaWidth = newMaxChartAreaWidth;
6604 }
6605
6606 // Step 7 - Position the boxes
6607 var left = leftPadding + leftPaddingAddition;
6608 var top = topPadding + topPaddingAddition;
6609
6610 function placeBox(box) {
6611 if (box.isHorizontal()) {
6612 box.left = box.fullWidth ? leftPadding : totalLeftBoxesWidth;
6613 box.right = box.fullWidth ? width - rightPadding : totalLeftBoxesWidth + maxChartAreaWidth;
6614 box.top = top;
6615 box.bottom = top + box.height;
6616
6617 // Move to next point
6618 top = box.bottom;
6619
6620 } else {
6621
6622 box.left = left;
6623 box.right = left + box.width;
6624 box.top = totalTopBoxesHeight;
6625 box.bottom = totalTopBoxesHeight + maxChartAreaHeight;
6626
6627 // Move to next point
6628 left = box.right;
6629 }
6630 }
6631
6632 helpers.each(leftBoxes.concat(topBoxes), placeBox);
6633
6634 // Account for chart width and height
6635 left += maxChartAreaWidth;
6636 top += maxChartAreaHeight;
6637
6638 helpers.each(rightBoxes, placeBox);
6639 helpers.each(bottomBoxes, placeBox);
6640
6641 // Step 8
6642 chart.chartArea = {
6643 left: totalLeftBoxesWidth,
6644 top: totalTopBoxesHeight,
6645 right: totalLeftBoxesWidth + maxChartAreaWidth,
6646 bottom: totalTopBoxesHeight + maxChartAreaHeight
6647 };
6648
6649 // Step 9
6650 helpers.each(chartAreaBoxes, function(box) {
6651 box.left = chart.chartArea.left;
6652 box.top = chart.chartArea.top;
6653 box.right = chart.chartArea.right;
6654 box.bottom = chart.chartArea.bottom;
6655
6656 box.update(maxChartAreaWidth, maxChartAreaHeight);
6657 });
6658 }
6659};
6660
6661},{"46":46}],32:[function(require,module,exports){
6662'use strict';
6663
6664var defaults = require(26);
6665var helpers = require(46);
6666
6667defaults._set('global', {
6668 plugins: {}
6669});
6670
6671/**
6672 * The plugin service singleton
6673 * @namespace Chart.plugins
6674 * @since 2.1.0
6675 */
6676module.exports = {
6677 /**
6678 * Globally registered plugins.
6679 * @private
6680 */
6681 _plugins: [],
6682
6683 /**
6684 * This identifier is used to invalidate the descriptors cache attached to each chart
6685 * when a global plugin is registered or unregistered. In this case, the cache ID is
6686 * incremented and descriptors are regenerated during following API calls.
6687 * @private
6688 */
6689 _cacheId: 0,
6690
6691 /**
6692 * Registers the given plugin(s) if not already registered.
6693 * @param {Array|Object} plugins plugin instance(s).
6694 */
6695 register: function(plugins) {
6696 var p = this._plugins;
6697 ([]).concat(plugins).forEach(function(plugin) {
6698 if (p.indexOf(plugin) === -1) {
6699 p.push(plugin);
6700 }
6701 });
6702
6703 this._cacheId++;
6704 },
6705
6706 /**
6707 * Unregisters the given plugin(s) only if registered.
6708 * @param {Array|Object} plugins plugin instance(s).
6709 */
6710 unregister: function(plugins) {
6711 var p = this._plugins;
6712 ([]).concat(plugins).forEach(function(plugin) {
6713 var idx = p.indexOf(plugin);
6714 if (idx !== -1) {
6715 p.splice(idx, 1);
6716 }
6717 });
6718
6719 this._cacheId++;
6720 },
6721
6722 /**
6723 * Remove all registered plugins.
6724 * @since 2.1.5
6725 */
6726 clear: function() {
6727 this._plugins = [];
6728 this._cacheId++;
6729 },
6730
6731 /**
6732 * Returns the number of registered plugins?
6733 * @returns {Number}
6734 * @since 2.1.5
6735 */
6736 count: function() {
6737 return this._plugins.length;
6738 },
6739
6740 /**
6741 * Returns all registered plugin instances.
6742 * @returns {Array} array of plugin objects.
6743 * @since 2.1.5
6744 */
6745 getAll: function() {
6746 return this._plugins;
6747 },
6748
6749 /**
6750 * Calls enabled plugins for `chart` on the specified hook and with the given args.
6751 * This method immediately returns as soon as a plugin explicitly returns false. The
6752 * returned value can be used, for instance, to interrupt the current action.
6753 * @param {Object} chart - The chart instance for which plugins should be called.
6754 * @param {String} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
6755 * @param {Array} [args] - Extra arguments to apply to the hook call.
6756 * @returns {Boolean} false if any of the plugins return false, else returns true.
6757 */
6758 notify: function(chart, hook, args) {
6759 var descriptors = this.descriptors(chart);
6760 var ilen = descriptors.length;
6761 var i, descriptor, plugin, params, method;
6762
6763 for (i = 0; i < ilen; ++i) {
6764 descriptor = descriptors[i];
6765 plugin = descriptor.plugin;
6766 method = plugin[hook];
6767 if (typeof method === 'function') {
6768 params = [chart].concat(args || []);
6769 params.push(descriptor.options);
6770 if (method.apply(plugin, params) === false) {
6771 return false;
6772 }
6773 }
6774 }
6775
6776 return true;
6777 },
6778
6779 /**
6780 * Returns descriptors of enabled plugins for the given chart.
6781 * @returns {Array} [{ plugin, options }]
6782 * @private
6783 */
6784 descriptors: function(chart) {
6785 var cache = chart.$plugins || (chart.$plugins = {});
6786 if (cache.id === this._cacheId) {
6787 return cache.descriptors;
6788 }
6789
6790 var plugins = [];
6791 var descriptors = [];
6792 var config = (chart && chart.config) || {};
6793 var options = (config.options && config.options.plugins) || {};
6794
6795 this._plugins.concat(config.plugins || []).forEach(function(plugin) {
6796 var idx = plugins.indexOf(plugin);
6797 if (idx !== -1) {
6798 return;
6799 }
6800
6801 var id = plugin.id;
6802 var opts = options[id];
6803 if (opts === false) {
6804 return;
6805 }
6806
6807 if (opts === true) {
6808 opts = helpers.clone(defaults.global.plugins[id]);
6809 }
6810
6811 plugins.push(plugin);
6812 descriptors.push({
6813 plugin: plugin,
6814 options: opts || {}
6815 });
6816 });
6817
6818 cache.descriptors = descriptors;
6819 cache.id = this._cacheId;
6820 return descriptors;
6821 },
6822
6823 /**
6824 * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
6825 * but in some cases, this reference can be changed by the user when updating options.
6826 * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
6827 * @private
6828 */
6829 _invalidate: function(chart) {
6830 delete chart.$plugins;
6831 }
6832};
6833
6834/**
6835 * Plugin extension hooks.
6836 * @interface IPlugin
6837 * @since 2.1.0
6838 */
6839/**
6840 * @method IPlugin#beforeInit
6841 * @desc Called before initializing `chart`.
6842 * @param {Chart.Controller} chart - The chart instance.
6843 * @param {Object} options - The plugin options.
6844 */
6845/**
6846 * @method IPlugin#afterInit
6847 * @desc Called after `chart` has been initialized and before the first update.
6848 * @param {Chart.Controller} chart - The chart instance.
6849 * @param {Object} options - The plugin options.
6850 */
6851/**
6852 * @method IPlugin#beforeUpdate
6853 * @desc Called before updating `chart`. If any plugin returns `false`, the update
6854 * is cancelled (and thus subsequent render(s)) until another `update` is triggered.
6855 * @param {Chart.Controller} chart - The chart instance.
6856 * @param {Object} options - The plugin options.
6857 * @returns {Boolean} `false` to cancel the chart update.
6858 */
6859/**
6860 * @method IPlugin#afterUpdate
6861 * @desc Called after `chart` has been updated and before rendering. Note that this
6862 * hook will not be called if the chart update has been previously cancelled.
6863 * @param {Chart.Controller} chart - The chart instance.
6864 * @param {Object} options - The plugin options.
6865 */
6866/**
6867 * @method IPlugin#beforeDatasetsUpdate
6868 * @desc Called before updating the `chart` datasets. If any plugin returns `false`,
6869 * the datasets update is cancelled until another `update` is triggered.
6870 * @param {Chart.Controller} chart - The chart instance.
6871 * @param {Object} options - The plugin options.
6872 * @returns {Boolean} false to cancel the datasets update.
6873 * @since version 2.1.5
6874*/
6875/**
6876 * @method IPlugin#afterDatasetsUpdate
6877 * @desc Called after the `chart` datasets have been updated. Note that this hook
6878 * will not be called if the datasets update has been previously cancelled.
6879 * @param {Chart.Controller} chart - The chart instance.
6880 * @param {Object} options - The plugin options.
6881 * @since version 2.1.5
6882 */
6883/**
6884 * @method IPlugin#beforeDatasetUpdate
6885 * @desc Called before updating the `chart` dataset at the given `args.index`. If any plugin
6886 * returns `false`, the datasets update is cancelled until another `update` is triggered.
6887 * @param {Chart} chart - The chart instance.
6888 * @param {Object} args - The call arguments.
6889 * @param {Number} args.index - The dataset index.
6890 * @param {Object} args.meta - The dataset metadata.
6891 * @param {Object} options - The plugin options.
6892 * @returns {Boolean} `false` to cancel the chart datasets drawing.
6893 */
6894/**
6895 * @method IPlugin#afterDatasetUpdate
6896 * @desc Called after the `chart` datasets at the given `args.index` has been updated. Note
6897 * that this hook will not be called if the datasets update has been previously cancelled.
6898 * @param {Chart} chart - The chart instance.
6899 * @param {Object} args - The call arguments.
6900 * @param {Number} args.index - The dataset index.
6901 * @param {Object} args.meta - The dataset metadata.
6902 * @param {Object} options - The plugin options.
6903 */
6904/**
6905 * @method IPlugin#beforeLayout
6906 * @desc Called before laying out `chart`. If any plugin returns `false`,
6907 * the layout update is cancelled until another `update` is triggered.
6908 * @param {Chart.Controller} chart - The chart instance.
6909 * @param {Object} options - The plugin options.
6910 * @returns {Boolean} `false` to cancel the chart layout.
6911 */
6912/**
6913 * @method IPlugin#afterLayout
6914 * @desc Called after the `chart` has been layed out. Note that this hook will not
6915 * be called if the layout update has been previously cancelled.
6916 * @param {Chart.Controller} chart - The chart instance.
6917 * @param {Object} options - The plugin options.
6918 */
6919/**
6920 * @method IPlugin#beforeRender
6921 * @desc Called before rendering `chart`. If any plugin returns `false`,
6922 * the rendering is cancelled until another `render` is triggered.
6923 * @param {Chart.Controller} chart - The chart instance.
6924 * @param {Object} options - The plugin options.
6925 * @returns {Boolean} `false` to cancel the chart rendering.
6926 */
6927/**
6928 * @method IPlugin#afterRender
6929 * @desc Called after the `chart` has been fully rendered (and animation completed). Note
6930 * that this hook will not be called if the rendering has been previously cancelled.
6931 * @param {Chart.Controller} chart - The chart instance.
6932 * @param {Object} options - The plugin options.
6933 */
6934/**
6935 * @method IPlugin#beforeDraw
6936 * @desc Called before drawing `chart` at every animation frame specified by the given
6937 * easing value. If any plugin returns `false`, the frame drawing is cancelled until
6938 * another `render` is triggered.
6939 * @param {Chart.Controller} chart - The chart instance.
6940 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
6941 * @param {Object} options - The plugin options.
6942 * @returns {Boolean} `false` to cancel the chart drawing.
6943 */
6944/**
6945 * @method IPlugin#afterDraw
6946 * @desc Called after the `chart` has been drawn for the specific easing value. Note
6947 * that this hook will not be called if the drawing has been previously cancelled.
6948 * @param {Chart.Controller} chart - The chart instance.
6949 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
6950 * @param {Object} options - The plugin options.
6951 */
6952/**
6953 * @method IPlugin#beforeDatasetsDraw
6954 * @desc Called before drawing the `chart` datasets. If any plugin returns `false`,
6955 * the datasets drawing is cancelled until another `render` is triggered.
6956 * @param {Chart.Controller} chart - The chart instance.
6957 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
6958 * @param {Object} options - The plugin options.
6959 * @returns {Boolean} `false` to cancel the chart datasets drawing.
6960 */
6961/**
6962 * @method IPlugin#afterDatasetsDraw
6963 * @desc Called after the `chart` datasets have been drawn. Note that this hook
6964 * will not be called if the datasets drawing has been previously cancelled.
6965 * @param {Chart.Controller} chart - The chart instance.
6966 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
6967 * @param {Object} options - The plugin options.
6968 */
6969/**
6970 * @method IPlugin#beforeDatasetDraw
6971 * @desc Called before drawing the `chart` dataset at the given `args.index` (datasets
6972 * are drawn in the reverse order). If any plugin returns `false`, the datasets drawing
6973 * is cancelled until another `render` is triggered.
6974 * @param {Chart} chart - The chart instance.
6975 * @param {Object} args - The call arguments.
6976 * @param {Number} args.index - The dataset index.
6977 * @param {Object} args.meta - The dataset metadata.
6978 * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
6979 * @param {Object} options - The plugin options.
6980 * @returns {Boolean} `false` to cancel the chart datasets drawing.
6981 */
6982/**
6983 * @method IPlugin#afterDatasetDraw
6984 * @desc Called after the `chart` datasets at the given `args.index` have been drawn
6985 * (datasets are drawn in the reverse order). Note that this hook will not be called
6986 * if the datasets drawing has been previously cancelled.
6987 * @param {Chart} chart - The chart instance.
6988 * @param {Object} args - The call arguments.
6989 * @param {Number} args.index - The dataset index.
6990 * @param {Object} args.meta - The dataset metadata.
6991 * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
6992 * @param {Object} options - The plugin options.
6993 */
6994/**
6995 * @method IPlugin#beforeTooltipDraw
6996 * @desc Called before drawing the `tooltip`. If any plugin returns `false`,
6997 * the tooltip drawing is cancelled until another `render` is triggered.
6998 * @param {Chart} chart - The chart instance.
6999 * @param {Object} args - The call arguments.
7000 * @param {Object} args.tooltip - The tooltip.
7001 * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
7002 * @param {Object} options - The plugin options.
7003 * @returns {Boolean} `false` to cancel the chart tooltip drawing.
7004 */
7005/**
7006 * @method IPlugin#afterTooltipDraw
7007 * @desc Called after drawing the `tooltip`. Note that this hook will not
7008 * be called if the tooltip drawing has been previously cancelled.
7009 * @param {Chart} chart - The chart instance.
7010 * @param {Object} args - The call arguments.
7011 * @param {Object} args.tooltip - The tooltip.
7012 * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
7013 * @param {Object} options - The plugin options.
7014 */
7015/**
7016 * @method IPlugin#beforeEvent
7017 * @desc Called before processing the specified `event`. If any plugin returns `false`,
7018 * the event will be discarded.
7019 * @param {Chart.Controller} chart - The chart instance.
7020 * @param {IEvent} event - The event object.
7021 * @param {Object} options - The plugin options.
7022 */
7023/**
7024 * @method IPlugin#afterEvent
7025 * @desc Called after the `event` has been consumed. Note that this hook
7026 * will not be called if the `event` has been previously discarded.
7027 * @param {Chart.Controller} chart - The chart instance.
7028 * @param {IEvent} event - The event object.
7029 * @param {Object} options - The plugin options.
7030 */
7031/**
7032 * @method IPlugin#resize
7033 * @desc Called after the chart as been resized.
7034 * @param {Chart.Controller} chart - The chart instance.
7035 * @param {Number} size - The new canvas display size (eq. canvas.style width & height).
7036 * @param {Object} options - The plugin options.
7037 */
7038/**
7039 * @method IPlugin#destroy
7040 * @desc Called after the chart as been destroyed.
7041 * @param {Chart.Controller} chart - The chart instance.
7042 * @param {Object} options - The plugin options.
7043 */
7044
7045},{"26":26,"46":46}],33:[function(require,module,exports){
7046'use strict';
7047
7048var defaults = require(26);
7049var Element = require(27);
7050var helpers = require(46);
7051var Ticks = require(35);
7052
7053defaults._set('scale', {
7054 display: true,
7055 position: 'left',
7056 offset: false,
7057
7058 // grid line settings
7059 gridLines: {
7060 display: true,
7061 color: 'rgba(0, 0, 0, 0.1)',
7062 lineWidth: 1,
7063 drawBorder: true,
7064 drawOnChartArea: true,
7065 drawTicks: true,
7066 tickMarkLength: 10,
7067 zeroLineWidth: 1,
7068 zeroLineColor: 'rgba(0,0,0,0.25)',
7069 zeroLineBorderDash: [],
7070 zeroLineBorderDashOffset: 0.0,
7071 offsetGridLines: false,
7072 borderDash: [],
7073 borderDashOffset: 0.0
7074 },
7075
7076 // scale label
7077 scaleLabel: {
7078 // display property
7079 display: false,
7080
7081 // actual label
7082 labelString: '',
7083
7084 // line height
7085 lineHeight: 1.2,
7086
7087 // top/bottom padding
7088 padding: {
7089 top: 4,
7090 bottom: 4
7091 }
7092 },
7093
7094 // label settings
7095 ticks: {
7096 beginAtZero: false,
7097 minRotation: 0,
7098 maxRotation: 50,
7099 mirror: false,
7100 padding: 0,
7101 reverse: false,
7102 display: true,
7103 autoSkip: true,
7104 autoSkipPadding: 0,
7105 labelOffset: 0,
7106 // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
7107 callback: Ticks.formatters.values,
7108 minor: {},
7109 major: {}
7110 }
7111});
7112
7113function labelsFromTicks(ticks) {
7114 var labels = [];
7115 var i, ilen;
7116
7117 for (i = 0, ilen = ticks.length; i < ilen; ++i) {
7118 labels.push(ticks[i].label);
7119 }
7120
7121 return labels;
7122}
7123
7124function getLineValue(scale, index, offsetGridLines) {
7125 var lineValue = scale.getPixelForTick(index);
7126
7127 if (offsetGridLines) {
7128 if (index === 0) {
7129 lineValue -= (scale.getPixelForTick(1) - lineValue) / 2;
7130 } else {
7131 lineValue -= (lineValue - scale.getPixelForTick(index - 1)) / 2;
7132 }
7133 }
7134 return lineValue;
7135}
7136
7137function computeTextSize(context, tick, font) {
7138 return helpers.isArray(tick) ?
7139 helpers.longestText(context, font, tick) :
7140 context.measureText(tick).width;
7141}
7142
7143function parseFontOptions(options) {
7144 var valueOrDefault = helpers.valueOrDefault;
7145 var globalDefaults = defaults.global;
7146 var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
7147 var style = valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle);
7148 var family = valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily);
7149
7150 return {
7151 size: size,
7152 style: style,
7153 family: family,
7154 font: helpers.fontString(size, style, family)
7155 };
7156}
7157
7158function parseLineHeight(options) {
7159 return helpers.options.toLineHeight(
7160 helpers.valueOrDefault(options.lineHeight, 1.2),
7161 helpers.valueOrDefault(options.fontSize, defaults.global.defaultFontSize));
7162}
7163
7164module.exports = Element.extend({
7165 /**
7166 * Get the padding needed for the scale
7167 * @method getPadding
7168 * @private
7169 * @returns {Padding} the necessary padding
7170 */
7171 getPadding: function() {
7172 var me = this;
7173 return {
7174 left: me.paddingLeft || 0,
7175 top: me.paddingTop || 0,
7176 right: me.paddingRight || 0,
7177 bottom: me.paddingBottom || 0
7178 };
7179 },
7180
7181 /**
7182 * Returns the scale tick objects ({label, major})
7183 * @since 2.7
7184 */
7185 getTicks: function() {
7186 return this._ticks;
7187 },
7188
7189 // These methods are ordered by lifecyle. Utilities then follow.
7190 // Any function defined here is inherited by all scale types.
7191 // Any function can be extended by the scale type
7192
7193 mergeTicksOptions: function() {
7194 var ticks = this.options.ticks;
7195 if (ticks.minor === false) {
7196 ticks.minor = {
7197 display: false
7198 };
7199 }
7200 if (ticks.major === false) {
7201 ticks.major = {
7202 display: false
7203 };
7204 }
7205 for (var key in ticks) {
7206 if (key !== 'major' && key !== 'minor') {
7207 if (typeof ticks.minor[key] === 'undefined') {
7208 ticks.minor[key] = ticks[key];
7209 }
7210 if (typeof ticks.major[key] === 'undefined') {
7211 ticks.major[key] = ticks[key];
7212 }
7213 }
7214 }
7215 },
7216 beforeUpdate: function() {
7217 helpers.callback(this.options.beforeUpdate, [this]);
7218 },
7219
7220 update: function(maxWidth, maxHeight, margins) {
7221 var me = this;
7222 var i, ilen, labels, label, ticks, tick;
7223
7224 // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
7225 me.beforeUpdate();
7226
7227 // Absorb the master measurements
7228 me.maxWidth = maxWidth;
7229 me.maxHeight = maxHeight;
7230 me.margins = helpers.extend({
7231 left: 0,
7232 right: 0,
7233 top: 0,
7234 bottom: 0
7235 }, margins);
7236 me.longestTextCache = me.longestTextCache || {};
7237
7238 // Dimensions
7239 me.beforeSetDimensions();
7240 me.setDimensions();
7241 me.afterSetDimensions();
7242
7243 // Data min/max
7244 me.beforeDataLimits();
7245 me.determineDataLimits();
7246 me.afterDataLimits();
7247
7248 // Ticks - `this.ticks` is now DEPRECATED!
7249 // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
7250 // and must not be accessed directly from outside this class. `this.ticks` being
7251 // around for long time and not marked as private, we can't change its structure
7252 // without unexpected breaking changes. If you need to access the scale ticks,
7253 // use scale.getTicks() instead.
7254
7255 me.beforeBuildTicks();
7256
7257 // New implementations should return an array of objects but for BACKWARD COMPAT,
7258 // we still support no return (`this.ticks` internally set by calling this method).
7259 ticks = me.buildTicks() || [];
7260
7261 me.afterBuildTicks();
7262
7263 me.beforeTickToLabelConversion();
7264
7265 // New implementations should return the formatted tick labels but for BACKWARD
7266 // COMPAT, we still support no return (`this.ticks` internally changed by calling
7267 // this method and supposed to contain only string values).
7268 labels = me.convertTicksToLabels(ticks) || me.ticks;
7269
7270 me.afterTickToLabelConversion();
7271
7272 me.ticks = labels; // BACKWARD COMPATIBILITY
7273
7274 // IMPORTANT: from this point, we consider that `this.ticks` will NEVER change!
7275
7276 // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
7277 for (i = 0, ilen = labels.length; i < ilen; ++i) {
7278 label = labels[i];
7279 tick = ticks[i];
7280 if (!tick) {
7281 ticks.push(tick = {
7282 label: label,
7283 major: false
7284 });
7285 } else {
7286 tick.label = label;
7287 }
7288 }
7289
7290 me._ticks = ticks;
7291
7292 // Tick Rotation
7293 me.beforeCalculateTickRotation();
7294 me.calculateTickRotation();
7295 me.afterCalculateTickRotation();
7296 // Fit
7297 me.beforeFit();
7298 me.fit();
7299 me.afterFit();
7300 //
7301 me.afterUpdate();
7302
7303 return me.minSize;
7304
7305 },
7306 afterUpdate: function() {
7307 helpers.callback(this.options.afterUpdate, [this]);
7308 },
7309
7310 //
7311
7312 beforeSetDimensions: function() {
7313 helpers.callback(this.options.beforeSetDimensions, [this]);
7314 },
7315 setDimensions: function() {
7316 var me = this;
7317 // Set the unconstrained dimension before label rotation
7318 if (me.isHorizontal()) {
7319 // Reset position before calculating rotation
7320 me.width = me.maxWidth;
7321 me.left = 0;
7322 me.right = me.width;
7323 } else {
7324 me.height = me.maxHeight;
7325
7326 // Reset position before calculating rotation
7327 me.top = 0;
7328 me.bottom = me.height;
7329 }
7330
7331 // Reset padding
7332 me.paddingLeft = 0;
7333 me.paddingTop = 0;
7334 me.paddingRight = 0;
7335 me.paddingBottom = 0;
7336 },
7337 afterSetDimensions: function() {
7338 helpers.callback(this.options.afterSetDimensions, [this]);
7339 },
7340
7341 // Data limits
7342 beforeDataLimits: function() {
7343 helpers.callback(this.options.beforeDataLimits, [this]);
7344 },
7345 determineDataLimits: helpers.noop,
7346 afterDataLimits: function() {
7347 helpers.callback(this.options.afterDataLimits, [this]);
7348 },
7349
7350 //
7351 beforeBuildTicks: function() {
7352 helpers.callback(this.options.beforeBuildTicks, [this]);
7353 },
7354 buildTicks: helpers.noop,
7355 afterBuildTicks: function() {
7356 helpers.callback(this.options.afterBuildTicks, [this]);
7357 },
7358
7359 beforeTickToLabelConversion: function() {
7360 helpers.callback(this.options.beforeTickToLabelConversion, [this]);
7361 },
7362 convertTicksToLabels: function() {
7363 var me = this;
7364 // Convert ticks to strings
7365 var tickOpts = me.options.ticks;
7366 me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
7367 },
7368 afterTickToLabelConversion: function() {
7369 helpers.callback(this.options.afterTickToLabelConversion, [this]);
7370 },
7371
7372 //
7373
7374 beforeCalculateTickRotation: function() {
7375 helpers.callback(this.options.beforeCalculateTickRotation, [this]);
7376 },
7377 calculateTickRotation: function() {
7378 var me = this;
7379 var context = me.ctx;
7380 var tickOpts = me.options.ticks;
7381 var labels = labelsFromTicks(me._ticks);
7382
7383 // Get the width of each grid by calculating the difference
7384 // between x offsets between 0 and 1.
7385 var tickFont = parseFontOptions(tickOpts);
7386 context.font = tickFont.font;
7387
7388 var labelRotation = tickOpts.minRotation || 0;
7389
7390 if (labels.length && me.options.display && me.isHorizontal()) {
7391 var originalLabelWidth = helpers.longestText(context, tickFont.font, labels, me.longestTextCache);
7392 var labelWidth = originalLabelWidth;
7393 var cosRotation, sinRotation;
7394
7395 // Allow 3 pixels x2 padding either side for label readability
7396 var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6;
7397
7398 // Max label rotation can be set or default to 90 - also act as a loop counter
7399 while (labelWidth > tickWidth && labelRotation < tickOpts.maxRotation) {
7400 var angleRadians = helpers.toRadians(labelRotation);
7401 cosRotation = Math.cos(angleRadians);
7402 sinRotation = Math.sin(angleRadians);
7403
7404 if (sinRotation * originalLabelWidth > me.maxHeight) {
7405 // go back one step
7406 labelRotation--;
7407 break;
7408 }
7409
7410 labelRotation++;
7411 labelWidth = cosRotation * originalLabelWidth;
7412 }
7413 }
7414
7415 me.labelRotation = labelRotation;
7416 },
7417 afterCalculateTickRotation: function() {
7418 helpers.callback(this.options.afterCalculateTickRotation, [this]);
7419 },
7420
7421 //
7422
7423 beforeFit: function() {
7424 helpers.callback(this.options.beforeFit, [this]);
7425 },
7426 fit: function() {
7427 var me = this;
7428 // Reset
7429 var minSize = me.minSize = {
7430 width: 0,
7431 height: 0
7432 };
7433
7434 var labels = labelsFromTicks(me._ticks);
7435
7436 var opts = me.options;
7437 var tickOpts = opts.ticks;
7438 var scaleLabelOpts = opts.scaleLabel;
7439 var gridLineOpts = opts.gridLines;
7440 var display = opts.display;
7441 var isHorizontal = me.isHorizontal();
7442
7443 var tickFont = parseFontOptions(tickOpts);
7444 var tickMarkLength = opts.gridLines.tickMarkLength;
7445
7446 // Width
7447 if (isHorizontal) {
7448 // subtract the margins to line up with the chartArea if we are a full width scale
7449 minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth;
7450 } else {
7451 minSize.width = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
7452 }
7453
7454 // height
7455 if (isHorizontal) {
7456 minSize.height = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
7457 } else {
7458 minSize.height = me.maxHeight; // fill all the height
7459 }
7460
7461 // Are we showing a title for the scale?
7462 if (scaleLabelOpts.display && display) {
7463 var scaleLabelLineHeight = parseLineHeight(scaleLabelOpts);
7464 var scaleLabelPadding = helpers.options.toPadding(scaleLabelOpts.padding);
7465 var deltaHeight = scaleLabelLineHeight + scaleLabelPadding.height;
7466
7467 if (isHorizontal) {
7468 minSize.height += deltaHeight;
7469 } else {
7470 minSize.width += deltaHeight;
7471 }
7472 }
7473
7474 // Don't bother fitting the ticks if we are not showing them
7475 if (tickOpts.display && display) {
7476 var largestTextWidth = helpers.longestText(me.ctx, tickFont.font, labels, me.longestTextCache);
7477 var tallestLabelHeightInLines = helpers.numberOfLabelLines(labels);
7478 var lineSpace = tickFont.size * 0.5;
7479 var tickPadding = me.options.ticks.padding;
7480
7481 if (isHorizontal) {
7482 // A horizontal axis is more constrained by the height.
7483 me.longestLabelWidth = largestTextWidth;
7484
7485 var angleRadians = helpers.toRadians(me.labelRotation);
7486 var cosRotation = Math.cos(angleRadians);
7487 var sinRotation = Math.sin(angleRadians);
7488
7489 // TODO - improve this calculation
7490 var labelHeight = (sinRotation * largestTextWidth)
7491 + (tickFont.size * tallestLabelHeightInLines)
7492 + (lineSpace * (tallestLabelHeightInLines - 1))
7493 + lineSpace; // padding
7494
7495 minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
7496
7497 me.ctx.font = tickFont.font;
7498 var firstLabelWidth = computeTextSize(me.ctx, labels[0], tickFont.font);
7499 var lastLabelWidth = computeTextSize(me.ctx, labels[labels.length - 1], tickFont.font);
7500
7501 // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
7502 // which means that the right padding is dominated by the font height
7503 if (me.labelRotation !== 0) {
7504 me.paddingLeft = opts.position === 'bottom' ? (cosRotation * firstLabelWidth) + 3 : (cosRotation * lineSpace) + 3; // add 3 px to move away from canvas edges
7505 me.paddingRight = opts.position === 'bottom' ? (cosRotation * lineSpace) + 3 : (cosRotation * lastLabelWidth) + 3;
7506 } else {
7507 me.paddingLeft = firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges
7508 me.paddingRight = lastLabelWidth / 2 + 3;
7509 }
7510 } else {
7511 // A vertical axis is more constrained by the width. Labels are the
7512 // dominant factor here, so get that length first and account for padding
7513 if (tickOpts.mirror) {
7514 largestTextWidth = 0;
7515 } else {
7516 // use lineSpace for consistency with horizontal axis
7517 // tickPadding is not implemented for horizontal
7518 largestTextWidth += tickPadding + lineSpace;
7519 }
7520
7521 minSize.width = Math.min(me.maxWidth, minSize.width + largestTextWidth);
7522
7523 me.paddingTop = tickFont.size / 2;
7524 me.paddingBottom = tickFont.size / 2;
7525 }
7526 }
7527
7528 me.handleMargins();
7529
7530 me.width = minSize.width;
7531 me.height = minSize.height;
7532 },
7533
7534 /**
7535 * Handle margins and padding interactions
7536 * @private
7537 */
7538 handleMargins: function() {
7539 var me = this;
7540 if (me.margins) {
7541 me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0);
7542 me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0);
7543 me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0);
7544 me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0);
7545 }
7546 },
7547
7548 afterFit: function() {
7549 helpers.callback(this.options.afterFit, [this]);
7550 },
7551
7552 // Shared Methods
7553 isHorizontal: function() {
7554 return this.options.position === 'top' || this.options.position === 'bottom';
7555 },
7556 isFullWidth: function() {
7557 return (this.options.fullWidth);
7558 },
7559
7560 // 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
7561 getRightValue: function(rawValue) {
7562 // Null and undefined values first
7563 if (helpers.isNullOrUndef(rawValue)) {
7564 return NaN;
7565 }
7566 // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
7567 if (typeof rawValue === 'number' && !isFinite(rawValue)) {
7568 return NaN;
7569 }
7570 // If it is in fact an object, dive in one more level
7571 if (rawValue) {
7572 if (this.isHorizontal()) {
7573 if (rawValue.x !== undefined) {
7574 return this.getRightValue(rawValue.x);
7575 }
7576 } else if (rawValue.y !== undefined) {
7577 return this.getRightValue(rawValue.y);
7578 }
7579 }
7580
7581 // Value is good, return it
7582 return rawValue;
7583 },
7584
7585 /**
7586 * Used to get the value to display in the tooltip for the data at the given index
7587 * @param index
7588 * @param datasetIndex
7589 */
7590 getLabelForIndex: helpers.noop,
7591
7592 /**
7593 * Returns the location of the given data point. Value can either be an index or a numerical value
7594 * The coordinate (0, 0) is at the upper-left corner of the canvas
7595 * @param value
7596 * @param index
7597 * @param datasetIndex
7598 */
7599 getPixelForValue: helpers.noop,
7600
7601 /**
7602 * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
7603 * The coordinate (0, 0) is at the upper-left corner of the canvas
7604 * @param pixel
7605 */
7606 getValueForPixel: helpers.noop,
7607
7608 /**
7609 * Returns the location of the tick at the given index
7610 * The coordinate (0, 0) is at the upper-left corner of the canvas
7611 */
7612 getPixelForTick: function(index) {
7613 var me = this;
7614 var offset = me.options.offset;
7615 if (me.isHorizontal()) {
7616 var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
7617 var tickWidth = innerWidth / Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
7618 var pixel = (tickWidth * index) + me.paddingLeft;
7619
7620 if (offset) {
7621 pixel += tickWidth / 2;
7622 }
7623
7624 var finalVal = me.left + Math.round(pixel);
7625 finalVal += me.isFullWidth() ? me.margins.left : 0;
7626 return finalVal;
7627 }
7628 var innerHeight = me.height - (me.paddingTop + me.paddingBottom);
7629 return me.top + (index * (innerHeight / (me._ticks.length - 1)));
7630 },
7631
7632 /**
7633 * Utility for getting the pixel location of a percentage of scale
7634 * The coordinate (0, 0) is at the upper-left corner of the canvas
7635 */
7636 getPixelForDecimal: function(decimal) {
7637 var me = this;
7638 if (me.isHorizontal()) {
7639 var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
7640 var valueOffset = (innerWidth * decimal) + me.paddingLeft;
7641
7642 var finalVal = me.left + Math.round(valueOffset);
7643 finalVal += me.isFullWidth() ? me.margins.left : 0;
7644 return finalVal;
7645 }
7646 return me.top + (decimal * me.height);
7647 },
7648
7649 /**
7650 * Returns the pixel for the minimum chart value
7651 * The coordinate (0, 0) is at the upper-left corner of the canvas
7652 */
7653 getBasePixel: function() {
7654 return this.getPixelForValue(this.getBaseValue());
7655 },
7656
7657 getBaseValue: function() {
7658 var me = this;
7659 var min = me.min;
7660 var max = me.max;
7661
7662 return me.beginAtZero ? 0 :
7663 min < 0 && max < 0 ? max :
7664 min > 0 && max > 0 ? min :
7665 0;
7666 },
7667
7668 /**
7669 * Returns a subset of ticks to be plotted to avoid overlapping labels.
7670 * @private
7671 */
7672 _autoSkip: function(ticks) {
7673 var skipRatio;
7674 var me = this;
7675 var isHorizontal = me.isHorizontal();
7676 var optionTicks = me.options.ticks.minor;
7677 var tickCount = ticks.length;
7678 var labelRotationRadians = helpers.toRadians(me.labelRotation);
7679 var cosRotation = Math.cos(labelRotationRadians);
7680 var longestRotatedLabel = me.longestLabelWidth * cosRotation;
7681 var result = [];
7682 var i, tick, shouldSkip;
7683
7684 // figure out the maximum number of gridlines to show
7685 var maxTicks;
7686 if (optionTicks.maxTicksLimit) {
7687 maxTicks = optionTicks.maxTicksLimit;
7688 }
7689
7690 if (isHorizontal) {
7691 skipRatio = false;
7692
7693 if ((longestRotatedLabel + optionTicks.autoSkipPadding) * tickCount > (me.width - (me.paddingLeft + me.paddingRight))) {
7694 skipRatio = 1 + Math.floor(((longestRotatedLabel + optionTicks.autoSkipPadding) * tickCount) / (me.width - (me.paddingLeft + me.paddingRight)));
7695 }
7696
7697 // if they defined a max number of optionTicks,
7698 // increase skipRatio until that number is met
7699 if (maxTicks && tickCount > maxTicks) {
7700 skipRatio = Math.max(skipRatio, Math.floor(tickCount / maxTicks));
7701 }
7702 }
7703
7704 for (i = 0; i < tickCount; i++) {
7705 tick = ticks[i];
7706
7707 // Since we always show the last tick,we need may need to hide the last shown one before
7708 shouldSkip = (skipRatio > 1 && i % skipRatio > 0) || (i % skipRatio === 0 && i + skipRatio >= tickCount);
7709 if (shouldSkip && i !== tickCount - 1) {
7710 // leave tick in place but make sure it's not displayed (#4635)
7711 delete tick.label;
7712 }
7713 result.push(tick);
7714 }
7715 return result;
7716 },
7717
7718 // Actually draw the scale on the canvas
7719 // @param {rectangle} chartArea : the area of the chart to draw full grid lines on
7720 draw: function(chartArea) {
7721 var me = this;
7722 var options = me.options;
7723 if (!options.display) {
7724 return;
7725 }
7726
7727 var context = me.ctx;
7728 var globalDefaults = defaults.global;
7729 var optionTicks = options.ticks.minor;
7730 var optionMajorTicks = options.ticks.major || optionTicks;
7731 var gridLines = options.gridLines;
7732 var scaleLabel = options.scaleLabel;
7733
7734 var isRotated = me.labelRotation !== 0;
7735 var isHorizontal = me.isHorizontal();
7736
7737 var ticks = optionTicks.autoSkip ? me._autoSkip(me.getTicks()) : me.getTicks();
7738 var tickFontColor = helpers.valueOrDefault(optionTicks.fontColor, globalDefaults.defaultFontColor);
7739 var tickFont = parseFontOptions(optionTicks);
7740 var majorTickFontColor = helpers.valueOrDefault(optionMajorTicks.fontColor, globalDefaults.defaultFontColor);
7741 var majorTickFont = parseFontOptions(optionMajorTicks);
7742
7743 var tl = gridLines.drawTicks ? gridLines.tickMarkLength : 0;
7744
7745 var scaleLabelFontColor = helpers.valueOrDefault(scaleLabel.fontColor, globalDefaults.defaultFontColor);
7746 var scaleLabelFont = parseFontOptions(scaleLabel);
7747 var scaleLabelPadding = helpers.options.toPadding(scaleLabel.padding);
7748 var labelRotationRadians = helpers.toRadians(me.labelRotation);
7749
7750 var itemsToDraw = [];
7751
7752 var axisWidth = me.options.gridLines.lineWidth;
7753 var xTickStart = options.position === 'right' ? me.right : me.right - axisWidth - tl;
7754 var xTickEnd = options.position === 'right' ? me.right + tl : me.right;
7755 var yTickStart = options.position === 'bottom' ? me.top + axisWidth : me.bottom - tl - axisWidth;
7756 var yTickEnd = options.position === 'bottom' ? me.top + axisWidth + tl : me.bottom + axisWidth;
7757
7758 helpers.each(ticks, function(tick, index) {
7759 // autoskipper skipped this tick (#4635)
7760 if (helpers.isNullOrUndef(tick.label)) {
7761 return;
7762 }
7763
7764 var label = tick.label;
7765 var lineWidth, lineColor, borderDash, borderDashOffset;
7766 if (index === me.zeroLineIndex && options.offset === gridLines.offsetGridLines) {
7767 // Draw the first index specially
7768 lineWidth = gridLines.zeroLineWidth;
7769 lineColor = gridLines.zeroLineColor;
7770 borderDash = gridLines.zeroLineBorderDash;
7771 borderDashOffset = gridLines.zeroLineBorderDashOffset;
7772 } else {
7773 lineWidth = helpers.valueAtIndexOrDefault(gridLines.lineWidth, index);
7774 lineColor = helpers.valueAtIndexOrDefault(gridLines.color, index);
7775 borderDash = helpers.valueOrDefault(gridLines.borderDash, globalDefaults.borderDash);
7776 borderDashOffset = helpers.valueOrDefault(gridLines.borderDashOffset, globalDefaults.borderDashOffset);
7777 }
7778
7779 // Common properties
7780 var tx1, ty1, tx2, ty2, x1, y1, x2, y2, labelX, labelY;
7781 var textAlign = 'middle';
7782 var textBaseline = 'middle';
7783 var tickPadding = optionTicks.padding;
7784
7785 if (isHorizontal) {
7786 var labelYOffset = tl + tickPadding;
7787
7788 if (options.position === 'bottom') {
7789 // bottom
7790 textBaseline = !isRotated ? 'top' : 'middle';
7791 textAlign = !isRotated ? 'center' : 'right';
7792 labelY = me.top + labelYOffset;
7793 } else {
7794 // top
7795 textBaseline = !isRotated ? 'bottom' : 'middle';
7796 textAlign = !isRotated ? 'center' : 'left';
7797 labelY = me.bottom - labelYOffset;
7798 }
7799
7800 var xLineValue = getLineValue(me, index, gridLines.offsetGridLines && ticks.length > 1);
7801 if (xLineValue < me.left) {
7802 lineColor = 'rgba(0,0,0,0)';
7803 }
7804 xLineValue += helpers.aliasPixel(lineWidth);
7805
7806 labelX = me.getPixelForTick(index) + optionTicks.labelOffset; // x values for optionTicks (need to consider offsetLabel option)
7807
7808 tx1 = tx2 = x1 = x2 = xLineValue;
7809 ty1 = yTickStart;
7810 ty2 = yTickEnd;
7811 y1 = chartArea.top;
7812 y2 = chartArea.bottom + axisWidth;
7813 } else {
7814 var isLeft = options.position === 'left';
7815 var labelXOffset;
7816
7817 if (optionTicks.mirror) {
7818 textAlign = isLeft ? 'left' : 'right';
7819 labelXOffset = tickPadding;
7820 } else {
7821 textAlign = isLeft ? 'right' : 'left';
7822 labelXOffset = tl + tickPadding;
7823 }
7824
7825 labelX = isLeft ? me.right - labelXOffset : me.left + labelXOffset;
7826
7827 var yLineValue = getLineValue(me, index, gridLines.offsetGridLines && ticks.length > 1);
7828 if (yLineValue < me.top) {
7829 lineColor = 'rgba(0,0,0,0)';
7830 }
7831 yLineValue += helpers.aliasPixel(lineWidth);
7832
7833 labelY = me.getPixelForTick(index) + optionTicks.labelOffset;
7834
7835 tx1 = xTickStart;
7836 tx2 = xTickEnd;
7837 x1 = chartArea.left;
7838 x2 = chartArea.right + axisWidth;
7839 ty1 = ty2 = y1 = y2 = yLineValue;
7840 }
7841
7842 itemsToDraw.push({
7843 tx1: tx1,
7844 ty1: ty1,
7845 tx2: tx2,
7846 ty2: ty2,
7847 x1: x1,
7848 y1: y1,
7849 x2: x2,
7850 y2: y2,
7851 labelX: labelX,
7852 labelY: labelY,
7853 glWidth: lineWidth,
7854 glColor: lineColor,
7855 glBorderDash: borderDash,
7856 glBorderDashOffset: borderDashOffset,
7857 rotation: -1 * labelRotationRadians,
7858 label: label,
7859 major: tick.major,
7860 textBaseline: textBaseline,
7861 textAlign: textAlign
7862 });
7863 });
7864
7865 // Draw all of the tick labels, tick marks, and grid lines at the correct places
7866 helpers.each(itemsToDraw, function(itemToDraw) {
7867 if (gridLines.display) {
7868 context.save();
7869 context.lineWidth = itemToDraw.glWidth;
7870 context.strokeStyle = itemToDraw.glColor;
7871 if (context.setLineDash) {
7872 context.setLineDash(itemToDraw.glBorderDash);
7873 context.lineDashOffset = itemToDraw.glBorderDashOffset;
7874 }
7875
7876 context.beginPath();
7877
7878 if (gridLines.drawTicks) {
7879 context.moveTo(itemToDraw.tx1, itemToDraw.ty1);
7880 context.lineTo(itemToDraw.tx2, itemToDraw.ty2);
7881 }
7882
7883 if (gridLines.drawOnChartArea) {
7884 context.moveTo(itemToDraw.x1, itemToDraw.y1);
7885 context.lineTo(itemToDraw.x2, itemToDraw.y2);
7886 }
7887
7888 context.stroke();
7889 context.restore();
7890 }
7891
7892 if (optionTicks.display) {
7893 // Make sure we draw text in the correct color and font
7894 context.save();
7895 context.translate(itemToDraw.labelX, itemToDraw.labelY);
7896 context.rotate(itemToDraw.rotation);
7897 context.font = itemToDraw.major ? majorTickFont.font : tickFont.font;
7898 context.fillStyle = itemToDraw.major ? majorTickFontColor : tickFontColor;
7899 context.textBaseline = itemToDraw.textBaseline;
7900 context.textAlign = itemToDraw.textAlign;
7901
7902 var label = itemToDraw.label;
7903 if (helpers.isArray(label)) {
7904 var lineCount = label.length;
7905 var lineHeight = tickFont.size * 1.5;
7906 var y = me.isHorizontal() ? 0 : -lineHeight * (lineCount - 1) / 2;
7907
7908 for (var i = 0; i < lineCount; ++i) {
7909 // We just make sure the multiline element is a string here..
7910 context.fillText('' + label[i], 0, y);
7911 // apply same lineSpacing as calculated @ L#320
7912 y += lineHeight;
7913 }
7914 } else {
7915 context.fillText(label, 0, 0);
7916 }
7917 context.restore();
7918 }
7919 });
7920
7921 if (scaleLabel.display) {
7922 // Draw the scale label
7923 var scaleLabelX;
7924 var scaleLabelY;
7925 var rotation = 0;
7926 var halfLineHeight = parseLineHeight(scaleLabel) / 2;
7927
7928 if (isHorizontal) {
7929 scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width
7930 scaleLabelY = options.position === 'bottom'
7931 ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
7932 : me.top + halfLineHeight + scaleLabelPadding.top;
7933 } else {
7934 var isLeft = options.position === 'left';
7935 scaleLabelX = isLeft
7936 ? me.left + halfLineHeight + scaleLabelPadding.top
7937 : me.right - halfLineHeight - scaleLabelPadding.top;
7938 scaleLabelY = me.top + ((me.bottom - me.top) / 2);
7939 rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
7940 }
7941
7942 context.save();
7943 context.translate(scaleLabelX, scaleLabelY);
7944 context.rotate(rotation);
7945 context.textAlign = 'center';
7946 context.textBaseline = 'middle';
7947 context.fillStyle = scaleLabelFontColor; // render in correct colour
7948 context.font = scaleLabelFont.font;
7949 context.fillText(scaleLabel.labelString, 0, 0);
7950 context.restore();
7951 }
7952
7953 if (gridLines.drawBorder) {
7954 // Draw the line at the edge of the axis
7955 context.lineWidth = helpers.valueAtIndexOrDefault(gridLines.lineWidth, 0);
7956 context.strokeStyle = helpers.valueAtIndexOrDefault(gridLines.color, 0);
7957 var x1 = me.left;
7958 var x2 = me.right + axisWidth;
7959 var y1 = me.top;
7960 var y2 = me.bottom + axisWidth;
7961
7962 var aliasPixel = helpers.aliasPixel(context.lineWidth);
7963 if (isHorizontal) {
7964 y1 = y2 = options.position === 'top' ? me.bottom : me.top;
7965 y1 += aliasPixel;
7966 y2 += aliasPixel;
7967 } else {
7968 x1 = x2 = options.position === 'left' ? me.right : me.left;
7969 x1 += aliasPixel;
7970 x2 += aliasPixel;
7971 }
7972
7973 context.beginPath();
7974 context.moveTo(x1, y1);
7975 context.lineTo(x2, y2);
7976 context.stroke();
7977 }
7978 }
7979});
7980
7981},{"26":26,"27":27,"35":35,"46":46}],34:[function(require,module,exports){
7982'use strict';
7983
7984var defaults = require(26);
7985var helpers = require(46);
7986var layouts = require(31);
7987
7988module.exports = {
7989 // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
7990 // use the new chart options to grab the correct scale
7991 constructors: {},
7992 // Use a registration function so that we can move to an ES6 map when we no longer need to support
7993 // old browsers
7994
7995 // Scale config defaults
7996 defaults: {},
7997 registerScaleType: function(type, scaleConstructor, scaleDefaults) {
7998 this.constructors[type] = scaleConstructor;
7999 this.defaults[type] = helpers.clone(scaleDefaults);
8000 },
8001 getScaleConstructor: function(type) {
8002 return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
8003 },
8004 getScaleDefaults: function(type) {
8005 // Return the scale defaults merged with the global settings so that we always use the latest ones
8006 return this.defaults.hasOwnProperty(type) ? helpers.merge({}, [defaults.scale, this.defaults[type]]) : {};
8007 },
8008 updateScaleDefaults: function(type, additions) {
8009 var me = this;
8010 if (me.defaults.hasOwnProperty(type)) {
8011 me.defaults[type] = helpers.extend(me.defaults[type], additions);
8012 }
8013 },
8014 addScalesToLayout: function(chart) {
8015 // Adds each scale to the chart.boxes array to be sized accordingly
8016 helpers.each(chart.scales, function(scale) {
8017 // Set ILayoutItem parameters for backwards compatibility
8018 scale.fullWidth = scale.options.fullWidth;
8019 scale.position = scale.options.position;
8020 scale.weight = scale.options.weight;
8021 layouts.addBox(chart, scale);
8022 });
8023 }
8024};
8025
8026},{"26":26,"31":31,"46":46}],35:[function(require,module,exports){
8027'use strict';
8028
8029var helpers = require(46);
8030
8031/**
8032 * Namespace to hold static tick generation functions
8033 * @namespace Chart.Ticks
8034 */
8035module.exports = {
8036 /**
8037 * Namespace to hold formatters for different types of ticks
8038 * @namespace Chart.Ticks.formatters
8039 */
8040 formatters: {
8041 /**
8042 * Formatter for value labels
8043 * @method Chart.Ticks.formatters.values
8044 * @param value the value to display
8045 * @return {String|Array} the label to display
8046 */
8047 values: function(value) {
8048 return helpers.isArray(value) ? value : '' + value;
8049 },
8050
8051 /**
8052 * Formatter for linear numeric ticks
8053 * @method Chart.Ticks.formatters.linear
8054 * @param tickValue {Number} the value to be formatted
8055 * @param index {Number} the position of the tickValue parameter in the ticks array
8056 * @param ticks {Array<Number>} the list of ticks being converted
8057 * @return {String} string representation of the tickValue parameter
8058 */
8059 linear: function(tickValue, index, ticks) {
8060 // If we have lots of ticks, don't use the ones
8061 var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
8062
8063 // If we have a number like 2.5 as the delta, figure out how many decimal places we need
8064 if (Math.abs(delta) > 1) {
8065 if (tickValue !== Math.floor(tickValue)) {
8066 // not an integer
8067 delta = tickValue - Math.floor(tickValue);
8068 }
8069 }
8070
8071 var logDelta = helpers.log10(Math.abs(delta));
8072 var tickString = '';
8073
8074 if (tickValue !== 0) {
8075 var numDecimal = -1 * Math.floor(logDelta);
8076 numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
8077 tickString = tickValue.toFixed(numDecimal);
8078 } else {
8079 tickString = '0'; // never show decimal places for 0
8080 }
8081
8082 return tickString;
8083 },
8084
8085 logarithmic: function(tickValue, index, ticks) {
8086 var remain = tickValue / (Math.pow(10, Math.floor(helpers.log10(tickValue))));
8087
8088 if (tickValue === 0) {
8089 return '0';
8090 } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
8091 return tickValue.toExponential();
8092 }
8093 return '';
8094 }
8095 }
8096};
8097
8098},{"46":46}],36:[function(require,module,exports){
8099'use strict';
8100
8101var defaults = require(26);
8102var Element = require(27);
8103var helpers = require(46);
8104
8105defaults._set('global', {
8106 tooltips: {
8107 enabled: true,
8108 custom: null,
8109 mode: 'nearest',
8110 position: 'average',
8111 intersect: true,
8112 backgroundColor: 'rgba(0,0,0,0.8)',
8113 titleFontStyle: 'bold',
8114 titleSpacing: 2,
8115 titleMarginBottom: 6,
8116 titleFontColor: '#fff',
8117 titleAlign: 'left',
8118 bodySpacing: 2,
8119 bodyFontColor: '#fff',
8120 bodyAlign: 'left',
8121 footerFontStyle: 'bold',
8122 footerSpacing: 2,
8123 footerMarginTop: 6,
8124 footerFontColor: '#fff',
8125 footerAlign: 'left',
8126 yPadding: 6,
8127 xPadding: 6,
8128 caretPadding: 2,
8129 caretSize: 5,
8130 cornerRadius: 6,
8131 multiKeyBackground: '#fff',
8132 displayColors: true,
8133 borderColor: 'rgba(0,0,0,0)',
8134 borderWidth: 0,
8135 callbacks: {
8136 // Args are: (tooltipItems, data)
8137 beforeTitle: helpers.noop,
8138 title: function(tooltipItems, data) {
8139 // Pick first xLabel for now
8140 var title = '';
8141 var labels = data.labels;
8142 var labelCount = labels ? labels.length : 0;
8143
8144 if (tooltipItems.length > 0) {
8145 var item = tooltipItems[0];
8146
8147 if (item.xLabel) {
8148 title = item.xLabel;
8149 } else if (labelCount > 0 && item.index < labelCount) {
8150 title = labels[item.index];
8151 }
8152 }
8153
8154 return title;
8155 },
8156 afterTitle: helpers.noop,
8157
8158 // Args are: (tooltipItems, data)
8159 beforeBody: helpers.noop,
8160
8161 // Args are: (tooltipItem, data)
8162 beforeLabel: helpers.noop,
8163 label: function(tooltipItem, data) {
8164 var label = data.datasets[tooltipItem.datasetIndex].label || '';
8165
8166 if (label) {
8167 label += ': ';
8168 }
8169 label += tooltipItem.yLabel;
8170 return label;
8171 },
8172 labelColor: function(tooltipItem, chart) {
8173 var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
8174 var activeElement = meta.data[tooltipItem.index];
8175 var view = activeElement._view;
8176 return {
8177 borderColor: view.borderColor,
8178 backgroundColor: view.backgroundColor
8179 };
8180 },
8181 labelTextColor: function() {
8182 return this._options.bodyFontColor;
8183 },
8184 afterLabel: helpers.noop,
8185
8186 // Args are: (tooltipItems, data)
8187 afterBody: helpers.noop,
8188
8189 // Args are: (tooltipItems, data)
8190 beforeFooter: helpers.noop,
8191 footer: helpers.noop,
8192 afterFooter: helpers.noop
8193 }
8194 }
8195});
8196
8197var positioners = {
8198 /**
8199 * Average mode places the tooltip at the average position of the elements shown
8200 * @function Chart.Tooltip.positioners.average
8201 * @param elements {ChartElement[]} the elements being displayed in the tooltip
8202 * @returns {Point} tooltip position
8203 */
8204 average: function(elements) {
8205 if (!elements.length) {
8206 return false;
8207 }
8208
8209 var i, len;
8210 var x = 0;
8211 var y = 0;
8212 var count = 0;
8213
8214 for (i = 0, len = elements.length; i < len; ++i) {
8215 var el = elements[i];
8216 if (el && el.hasValue()) {
8217 var pos = el.tooltipPosition();
8218 x += pos.x;
8219 y += pos.y;
8220 ++count;
8221 }
8222 }
8223
8224 return {
8225 x: Math.round(x / count),
8226 y: Math.round(y / count)
8227 };
8228 },
8229
8230 /**
8231 * Gets the tooltip position nearest of the item nearest to the event position
8232 * @function Chart.Tooltip.positioners.nearest
8233 * @param elements {Chart.Element[]} the tooltip elements
8234 * @param eventPosition {Point} the position of the event in canvas coordinates
8235 * @returns {Point} the tooltip position
8236 */
8237 nearest: function(elements, eventPosition) {
8238 var x = eventPosition.x;
8239 var y = eventPosition.y;
8240 var minDistance = Number.POSITIVE_INFINITY;
8241 var i, len, nearestElement;
8242
8243 for (i = 0, len = elements.length; i < len; ++i) {
8244 var el = elements[i];
8245 if (el && el.hasValue()) {
8246 var center = el.getCenterPoint();
8247 var d = helpers.distanceBetweenPoints(eventPosition, center);
8248
8249 if (d < minDistance) {
8250 minDistance = d;
8251 nearestElement = el;
8252 }
8253 }
8254 }
8255
8256 if (nearestElement) {
8257 var tp = nearestElement.tooltipPosition();
8258 x = tp.x;
8259 y = tp.y;
8260 }
8261
8262 return {
8263 x: x,
8264 y: y
8265 };
8266 }
8267};
8268
8269/**
8270 * Helper method to merge the opacity into a color
8271 */
8272function mergeOpacity(colorString, opacity) {
8273 var color = helpers.color(colorString);
8274 return color.alpha(opacity * color.alpha()).rgbaString();
8275}
8276
8277// Helper to push or concat based on if the 2nd parameter is an array or not
8278function pushOrConcat(base, toPush) {
8279 if (toPush) {
8280 if (helpers.isArray(toPush)) {
8281 // base = base.concat(toPush);
8282 Array.prototype.push.apply(base, toPush);
8283 } else {
8284 base.push(toPush);
8285 }
8286 }
8287
8288 return base;
8289}
8290
8291// Private helper to create a tooltip item model
8292// @param element : the chart element (point, arc, bar) to create the tooltip item for
8293// @return : new tooltip item
8294function createTooltipItem(element) {
8295 var xScale = element._xScale;
8296 var yScale = element._yScale || element._scale; // handle radar || polarArea charts
8297 var index = element._index;
8298 var datasetIndex = element._datasetIndex;
8299
8300 return {
8301 xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
8302 yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
8303 index: index,
8304 datasetIndex: datasetIndex,
8305 x: element._model.x,
8306 y: element._model.y
8307 };
8308}
8309
8310/**
8311 * Helper to get the reset model for the tooltip
8312 * @param tooltipOpts {Object} the tooltip options
8313 */
8314function getBaseModel(tooltipOpts) {
8315 var globalDefaults = defaults.global;
8316 var valueOrDefault = helpers.valueOrDefault;
8317
8318 return {
8319 // Positioning
8320 xPadding: tooltipOpts.xPadding,
8321 yPadding: tooltipOpts.yPadding,
8322 xAlign: tooltipOpts.xAlign,
8323 yAlign: tooltipOpts.yAlign,
8324
8325 // Body
8326 bodyFontColor: tooltipOpts.bodyFontColor,
8327 _bodyFontFamily: valueOrDefault(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
8328 _bodyFontStyle: valueOrDefault(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
8329 _bodyAlign: tooltipOpts.bodyAlign,
8330 bodyFontSize: valueOrDefault(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
8331 bodySpacing: tooltipOpts.bodySpacing,
8332
8333 // Title
8334 titleFontColor: tooltipOpts.titleFontColor,
8335 _titleFontFamily: valueOrDefault(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
8336 _titleFontStyle: valueOrDefault(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
8337 titleFontSize: valueOrDefault(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
8338 _titleAlign: tooltipOpts.titleAlign,
8339 titleSpacing: tooltipOpts.titleSpacing,
8340 titleMarginBottom: tooltipOpts.titleMarginBottom,
8341
8342 // Footer
8343 footerFontColor: tooltipOpts.footerFontColor,
8344 _footerFontFamily: valueOrDefault(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
8345 _footerFontStyle: valueOrDefault(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
8346 footerFontSize: valueOrDefault(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
8347 _footerAlign: tooltipOpts.footerAlign,
8348 footerSpacing: tooltipOpts.footerSpacing,
8349 footerMarginTop: tooltipOpts.footerMarginTop,
8350
8351 // Appearance
8352 caretSize: tooltipOpts.caretSize,
8353 cornerRadius: tooltipOpts.cornerRadius,
8354 backgroundColor: tooltipOpts.backgroundColor,
8355 opacity: 0,
8356 legendColorBackground: tooltipOpts.multiKeyBackground,
8357 displayColors: tooltipOpts.displayColors,
8358 borderColor: tooltipOpts.borderColor,
8359 borderWidth: tooltipOpts.borderWidth
8360 };
8361}
8362
8363/**
8364 * Get the size of the tooltip
8365 */
8366function getTooltipSize(tooltip, model) {
8367 var ctx = tooltip._chart.ctx;
8368
8369 var height = model.yPadding * 2; // Tooltip Padding
8370 var width = 0;
8371
8372 // Count of all lines in the body
8373 var body = model.body;
8374 var combinedBodyLength = body.reduce(function(count, bodyItem) {
8375 return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
8376 }, 0);
8377 combinedBodyLength += model.beforeBody.length + model.afterBody.length;
8378
8379 var titleLineCount = model.title.length;
8380 var footerLineCount = model.footer.length;
8381 var titleFontSize = model.titleFontSize;
8382 var bodyFontSize = model.bodyFontSize;
8383 var footerFontSize = model.footerFontSize;
8384
8385 height += titleLineCount * titleFontSize; // Title Lines
8386 height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
8387 height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
8388 height += combinedBodyLength * bodyFontSize; // Body Lines
8389 height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
8390 height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
8391 height += footerLineCount * (footerFontSize); // Footer Lines
8392 height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
8393
8394 // Title width
8395 var widthPadding = 0;
8396 var maxLineWidth = function(line) {
8397 width = Math.max(width, ctx.measureText(line).width + widthPadding);
8398 };
8399
8400 ctx.font = helpers.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
8401 helpers.each(model.title, maxLineWidth);
8402
8403 // Body width
8404 ctx.font = helpers.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
8405 helpers.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
8406
8407 // Body lines may include some extra width due to the color box
8408 widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
8409 helpers.each(body, function(bodyItem) {
8410 helpers.each(bodyItem.before, maxLineWidth);
8411 helpers.each(bodyItem.lines, maxLineWidth);
8412 helpers.each(bodyItem.after, maxLineWidth);
8413 });
8414
8415 // Reset back to 0
8416 widthPadding = 0;
8417
8418 // Footer width
8419 ctx.font = helpers.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
8420 helpers.each(model.footer, maxLineWidth);
8421
8422 // Add padding
8423 width += 2 * model.xPadding;
8424
8425 return {
8426 width: width,
8427 height: height
8428 };
8429}
8430
8431/**
8432 * Helper to get the alignment of a tooltip given the size
8433 */
8434function determineAlignment(tooltip, size) {
8435 var model = tooltip._model;
8436 var chart = tooltip._chart;
8437 var chartArea = tooltip._chart.chartArea;
8438 var xAlign = 'center';
8439 var yAlign = 'center';
8440
8441 if (model.y < size.height) {
8442 yAlign = 'top';
8443 } else if (model.y > (chart.height - size.height)) {
8444 yAlign = 'bottom';
8445 }
8446
8447 var lf, rf; // functions to determine left, right alignment
8448 var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
8449 var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
8450 var midX = (chartArea.left + chartArea.right) / 2;
8451 var midY = (chartArea.top + chartArea.bottom) / 2;
8452
8453 if (yAlign === 'center') {
8454 lf = function(x) {
8455 return x <= midX;
8456 };
8457 rf = function(x) {
8458 return x > midX;
8459 };
8460 } else {
8461 lf = function(x) {
8462 return x <= (size.width / 2);
8463 };
8464 rf = function(x) {
8465 return x >= (chart.width - (size.width / 2));
8466 };
8467 }
8468
8469 olf = function(x) {
8470 return x + size.width + model.caretSize + model.caretPadding > chart.width;
8471 };
8472 orf = function(x) {
8473 return x - size.width - model.caretSize - model.caretPadding < 0;
8474 };
8475 yf = function(y) {
8476 return y <= midY ? 'top' : 'bottom';
8477 };
8478
8479 if (lf(model.x)) {
8480 xAlign = 'left';
8481
8482 // Is tooltip too wide and goes over the right side of the chart.?
8483 if (olf(model.x)) {
8484 xAlign = 'center';
8485 yAlign = yf(model.y);
8486 }
8487 } else if (rf(model.x)) {
8488 xAlign = 'right';
8489
8490 // Is tooltip too wide and goes outside left edge of canvas?
8491 if (orf(model.x)) {
8492 xAlign = 'center';
8493 yAlign = yf(model.y);
8494 }
8495 }
8496
8497 var opts = tooltip._options;
8498 return {
8499 xAlign: opts.xAlign ? opts.xAlign : xAlign,
8500 yAlign: opts.yAlign ? opts.yAlign : yAlign
8501 };
8502}
8503
8504/**
8505 * @Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
8506 */
8507function getBackgroundPoint(vm, size, alignment, chart) {
8508 // Background Position
8509 var x = vm.x;
8510 var y = vm.y;
8511
8512 var caretSize = vm.caretSize;
8513 var caretPadding = vm.caretPadding;
8514 var cornerRadius = vm.cornerRadius;
8515 var xAlign = alignment.xAlign;
8516 var yAlign = alignment.yAlign;
8517 var paddingAndSize = caretSize + caretPadding;
8518 var radiusAndPadding = cornerRadius + caretPadding;
8519
8520 if (xAlign === 'right') {
8521 x -= size.width;
8522 } else if (xAlign === 'center') {
8523 x -= (size.width / 2);
8524 if (x + size.width > chart.width) {
8525 x = chart.width - size.width;
8526 }
8527 if (x < 0) {
8528 x = 0;
8529 }
8530 }
8531
8532 if (yAlign === 'top') {
8533 y += paddingAndSize;
8534 } else if (yAlign === 'bottom') {
8535 y -= size.height + paddingAndSize;
8536 } else {
8537 y -= (size.height / 2);
8538 }
8539
8540 if (yAlign === 'center') {
8541 if (xAlign === 'left') {
8542 x += paddingAndSize;
8543 } else if (xAlign === 'right') {
8544 x -= paddingAndSize;
8545 }
8546 } else if (xAlign === 'left') {
8547 x -= radiusAndPadding;
8548 } else if (xAlign === 'right') {
8549 x += radiusAndPadding;
8550 }
8551
8552 return {
8553 x: x,
8554 y: y
8555 };
8556}
8557
8558var exports = module.exports = Element.extend({
8559 initialize: function() {
8560 this._model = getBaseModel(this._options);
8561 this._lastActive = [];
8562 },
8563
8564 // Get the title
8565 // Args are: (tooltipItem, data)
8566 getTitle: function() {
8567 var me = this;
8568 var opts = me._options;
8569 var callbacks = opts.callbacks;
8570
8571 var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
8572 var title = callbacks.title.apply(me, arguments);
8573 var afterTitle = callbacks.afterTitle.apply(me, arguments);
8574
8575 var lines = [];
8576 lines = pushOrConcat(lines, beforeTitle);
8577 lines = pushOrConcat(lines, title);
8578 lines = pushOrConcat(lines, afterTitle);
8579
8580 return lines;
8581 },
8582
8583 // Args are: (tooltipItem, data)
8584 getBeforeBody: function() {
8585 var lines = this._options.callbacks.beforeBody.apply(this, arguments);
8586 return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : [];
8587 },
8588
8589 // Args are: (tooltipItem, data)
8590 getBody: function(tooltipItems, data) {
8591 var me = this;
8592 var callbacks = me._options.callbacks;
8593 var bodyItems = [];
8594
8595 helpers.each(tooltipItems, function(tooltipItem) {
8596 var bodyItem = {
8597 before: [],
8598 lines: [],
8599 after: []
8600 };
8601 pushOrConcat(bodyItem.before, callbacks.beforeLabel.call(me, tooltipItem, data));
8602 pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
8603 pushOrConcat(bodyItem.after, callbacks.afterLabel.call(me, tooltipItem, data));
8604
8605 bodyItems.push(bodyItem);
8606 });
8607
8608 return bodyItems;
8609 },
8610
8611 // Args are: (tooltipItem, data)
8612 getAfterBody: function() {
8613 var lines = this._options.callbacks.afterBody.apply(this, arguments);
8614 return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : [];
8615 },
8616
8617 // Get the footer and beforeFooter and afterFooter lines
8618 // Args are: (tooltipItem, data)
8619 getFooter: function() {
8620 var me = this;
8621 var callbacks = me._options.callbacks;
8622
8623 var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
8624 var footer = callbacks.footer.apply(me, arguments);
8625 var afterFooter = callbacks.afterFooter.apply(me, arguments);
8626
8627 var lines = [];
8628 lines = pushOrConcat(lines, beforeFooter);
8629 lines = pushOrConcat(lines, footer);
8630 lines = pushOrConcat(lines, afterFooter);
8631
8632 return lines;
8633 },
8634
8635 update: function(changed) {
8636 var me = this;
8637 var opts = me._options;
8638
8639 // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
8640 // 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
8641 // which breaks any animations.
8642 var existingModel = me._model;
8643 var model = me._model = getBaseModel(opts);
8644 var active = me._active;
8645
8646 var data = me._data;
8647
8648 // In the case where active.length === 0 we need to keep these at existing values for good animations
8649 var alignment = {
8650 xAlign: existingModel.xAlign,
8651 yAlign: existingModel.yAlign
8652 };
8653 var backgroundPoint = {
8654 x: existingModel.x,
8655 y: existingModel.y
8656 };
8657 var tooltipSize = {
8658 width: existingModel.width,
8659 height: existingModel.height
8660 };
8661 var tooltipPosition = {
8662 x: existingModel.caretX,
8663 y: existingModel.caretY
8664 };
8665
8666 var i, len;
8667
8668 if (active.length) {
8669 model.opacity = 1;
8670
8671 var labelColors = [];
8672 var labelTextColors = [];
8673 tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
8674
8675 var tooltipItems = [];
8676 for (i = 0, len = active.length; i < len; ++i) {
8677 tooltipItems.push(createTooltipItem(active[i]));
8678 }
8679
8680 // If the user provided a filter function, use it to modify the tooltip items
8681 if (opts.filter) {
8682 tooltipItems = tooltipItems.filter(function(a) {
8683 return opts.filter(a, data);
8684 });
8685 }
8686
8687 // If the user provided a sorting function, use it to modify the tooltip items
8688 if (opts.itemSort) {
8689 tooltipItems = tooltipItems.sort(function(a, b) {
8690 return opts.itemSort(a, b, data);
8691 });
8692 }
8693
8694 // Determine colors for boxes
8695 helpers.each(tooltipItems, function(tooltipItem) {
8696 labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
8697 labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
8698 });
8699
8700
8701 // Build the Text Lines
8702 model.title = me.getTitle(tooltipItems, data);
8703 model.beforeBody = me.getBeforeBody(tooltipItems, data);
8704 model.body = me.getBody(tooltipItems, data);
8705 model.afterBody = me.getAfterBody(tooltipItems, data);
8706 model.footer = me.getFooter(tooltipItems, data);
8707
8708 // Initial positioning and colors
8709 model.x = Math.round(tooltipPosition.x);
8710 model.y = Math.round(tooltipPosition.y);
8711 model.caretPadding = opts.caretPadding;
8712 model.labelColors = labelColors;
8713 model.labelTextColors = labelTextColors;
8714
8715 // data points
8716 model.dataPoints = tooltipItems;
8717
8718 // We need to determine alignment of the tooltip
8719 tooltipSize = getTooltipSize(this, model);
8720 alignment = determineAlignment(this, tooltipSize);
8721 // Final Size and Position
8722 backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
8723 } else {
8724 model.opacity = 0;
8725 }
8726
8727 model.xAlign = alignment.xAlign;
8728 model.yAlign = alignment.yAlign;
8729 model.x = backgroundPoint.x;
8730 model.y = backgroundPoint.y;
8731 model.width = tooltipSize.width;
8732 model.height = tooltipSize.height;
8733
8734 // Point where the caret on the tooltip points to
8735 model.caretX = tooltipPosition.x;
8736 model.caretY = tooltipPosition.y;
8737
8738 me._model = model;
8739
8740 if (changed && opts.custom) {
8741 opts.custom.call(me, model);
8742 }
8743
8744 return me;
8745 },
8746
8747 drawCaret: function(tooltipPoint, size) {
8748 var ctx = this._chart.ctx;
8749 var vm = this._view;
8750 var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
8751
8752 ctx.lineTo(caretPosition.x1, caretPosition.y1);
8753 ctx.lineTo(caretPosition.x2, caretPosition.y2);
8754 ctx.lineTo(caretPosition.x3, caretPosition.y3);
8755 },
8756 getCaretPosition: function(tooltipPoint, size, vm) {
8757 var x1, x2, x3, y1, y2, y3;
8758 var caretSize = vm.caretSize;
8759 var cornerRadius = vm.cornerRadius;
8760 var xAlign = vm.xAlign;
8761 var yAlign = vm.yAlign;
8762 var ptX = tooltipPoint.x;
8763 var ptY = tooltipPoint.y;
8764 var width = size.width;
8765 var height = size.height;
8766
8767 if (yAlign === 'center') {
8768 y2 = ptY + (height / 2);
8769
8770 if (xAlign === 'left') {
8771 x1 = ptX;
8772 x2 = x1 - caretSize;
8773 x3 = x1;
8774
8775 y1 = y2 + caretSize;
8776 y3 = y2 - caretSize;
8777 } else {
8778 x1 = ptX + width;
8779 x2 = x1 + caretSize;
8780 x3 = x1;
8781
8782 y1 = y2 - caretSize;
8783 y3 = y2 + caretSize;
8784 }
8785 } else {
8786 if (xAlign === 'left') {
8787 x2 = ptX + cornerRadius + (caretSize);
8788 x1 = x2 - caretSize;
8789 x3 = x2 + caretSize;
8790 } else if (xAlign === 'right') {
8791 x2 = ptX + width - cornerRadius - caretSize;
8792 x1 = x2 - caretSize;
8793 x3 = x2 + caretSize;
8794 } else {
8795 x2 = vm.caretX;
8796 x1 = x2 - caretSize;
8797 x3 = x2 + caretSize;
8798 }
8799 if (yAlign === 'top') {
8800 y1 = ptY;
8801 y2 = y1 - caretSize;
8802 y3 = y1;
8803 } else {
8804 y1 = ptY + height;
8805 y2 = y1 + caretSize;
8806 y3 = y1;
8807 // invert drawing order
8808 var tmp = x3;
8809 x3 = x1;
8810 x1 = tmp;
8811 }
8812 }
8813 return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
8814 },
8815
8816 drawTitle: function(pt, vm, ctx, opacity) {
8817 var title = vm.title;
8818
8819 if (title.length) {
8820 ctx.textAlign = vm._titleAlign;
8821 ctx.textBaseline = 'top';
8822
8823 var titleFontSize = vm.titleFontSize;
8824 var titleSpacing = vm.titleSpacing;
8825
8826 ctx.fillStyle = mergeOpacity(vm.titleFontColor, opacity);
8827 ctx.font = helpers.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
8828
8829 var i, len;
8830 for (i = 0, len = title.length; i < len; ++i) {
8831 ctx.fillText(title[i], pt.x, pt.y);
8832 pt.y += titleFontSize + titleSpacing; // Line Height and spacing
8833
8834 if (i + 1 === title.length) {
8835 pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
8836 }
8837 }
8838 }
8839 },
8840
8841 drawBody: function(pt, vm, ctx, opacity) {
8842 var bodyFontSize = vm.bodyFontSize;
8843 var bodySpacing = vm.bodySpacing;
8844 var body = vm.body;
8845
8846 ctx.textAlign = vm._bodyAlign;
8847 ctx.textBaseline = 'top';
8848 ctx.font = helpers.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
8849
8850 // Before Body
8851 var xLinePadding = 0;
8852 var fillLineOfText = function(line) {
8853 ctx.fillText(line, pt.x + xLinePadding, pt.y);
8854 pt.y += bodyFontSize + bodySpacing;
8855 };
8856
8857 // Before body lines
8858 ctx.fillStyle = mergeOpacity(vm.bodyFontColor, opacity);
8859 helpers.each(vm.beforeBody, fillLineOfText);
8860
8861 var drawColorBoxes = vm.displayColors;
8862 xLinePadding = drawColorBoxes ? (bodyFontSize + 2) : 0;
8863
8864 // Draw body lines now
8865 helpers.each(body, function(bodyItem, i) {
8866 var textColor = mergeOpacity(vm.labelTextColors[i], opacity);
8867 ctx.fillStyle = textColor;
8868 helpers.each(bodyItem.before, fillLineOfText);
8869
8870 helpers.each(bodyItem.lines, function(line) {
8871 // Draw Legend-like boxes if needed
8872 if (drawColorBoxes) {
8873 // Fill a white rect so that colours merge nicely if the opacity is < 1
8874 ctx.fillStyle = mergeOpacity(vm.legendColorBackground, opacity);
8875 ctx.fillRect(pt.x, pt.y, bodyFontSize, bodyFontSize);
8876
8877 // Border
8878 ctx.lineWidth = 1;
8879 ctx.strokeStyle = mergeOpacity(vm.labelColors[i].borderColor, opacity);
8880 ctx.strokeRect(pt.x, pt.y, bodyFontSize, bodyFontSize);
8881
8882 // Inner square
8883 ctx.fillStyle = mergeOpacity(vm.labelColors[i].backgroundColor, opacity);
8884 ctx.fillRect(pt.x + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
8885 ctx.fillStyle = textColor;
8886 }
8887
8888 fillLineOfText(line);
8889 });
8890
8891 helpers.each(bodyItem.after, fillLineOfText);
8892 });
8893
8894 // Reset back to 0 for after body
8895 xLinePadding = 0;
8896
8897 // After body lines
8898 helpers.each(vm.afterBody, fillLineOfText);
8899 pt.y -= bodySpacing; // Remove last body spacing
8900 },
8901
8902 drawFooter: function(pt, vm, ctx, opacity) {
8903 var footer = vm.footer;
8904
8905 if (footer.length) {
8906 pt.y += vm.footerMarginTop;
8907
8908 ctx.textAlign = vm._footerAlign;
8909 ctx.textBaseline = 'top';
8910
8911 ctx.fillStyle = mergeOpacity(vm.footerFontColor, opacity);
8912 ctx.font = helpers.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
8913
8914 helpers.each(footer, function(line) {
8915 ctx.fillText(line, pt.x, pt.y);
8916 pt.y += vm.footerFontSize + vm.footerSpacing;
8917 });
8918 }
8919 },
8920
8921 drawBackground: function(pt, vm, ctx, tooltipSize, opacity) {
8922 ctx.fillStyle = mergeOpacity(vm.backgroundColor, opacity);
8923 ctx.strokeStyle = mergeOpacity(vm.borderColor, opacity);
8924 ctx.lineWidth = vm.borderWidth;
8925 var xAlign = vm.xAlign;
8926 var yAlign = vm.yAlign;
8927 var x = pt.x;
8928 var y = pt.y;
8929 var width = tooltipSize.width;
8930 var height = tooltipSize.height;
8931 var radius = vm.cornerRadius;
8932
8933 ctx.beginPath();
8934 ctx.moveTo(x + radius, y);
8935 if (yAlign === 'top') {
8936 this.drawCaret(pt, tooltipSize);
8937 }
8938 ctx.lineTo(x + width - radius, y);
8939 ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
8940 if (yAlign === 'center' && xAlign === 'right') {
8941 this.drawCaret(pt, tooltipSize);
8942 }
8943 ctx.lineTo(x + width, y + height - radius);
8944 ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
8945 if (yAlign === 'bottom') {
8946 this.drawCaret(pt, tooltipSize);
8947 }
8948 ctx.lineTo(x + radius, y + height);
8949 ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
8950 if (yAlign === 'center' && xAlign === 'left') {
8951 this.drawCaret(pt, tooltipSize);
8952 }
8953 ctx.lineTo(x, y + radius);
8954 ctx.quadraticCurveTo(x, y, x + radius, y);
8955 ctx.closePath();
8956
8957 ctx.fill();
8958
8959 if (vm.borderWidth > 0) {
8960 ctx.stroke();
8961 }
8962 },
8963
8964 draw: function() {
8965 var ctx = this._chart.ctx;
8966 var vm = this._view;
8967
8968 if (vm.opacity === 0) {
8969 return;
8970 }
8971
8972 var tooltipSize = {
8973 width: vm.width,
8974 height: vm.height
8975 };
8976 var pt = {
8977 x: vm.x,
8978 y: vm.y
8979 };
8980
8981 // IE11/Edge does not like very small opacities, so snap to 0
8982 var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
8983
8984 // Truthy/falsey value for empty tooltip
8985 var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
8986
8987 if (this._options.enabled && hasTooltipContent) {
8988 // Draw Background
8989 this.drawBackground(pt, vm, ctx, tooltipSize, opacity);
8990
8991 // Draw Title, Body, and Footer
8992 pt.x += vm.xPadding;
8993 pt.y += vm.yPadding;
8994
8995 // Titles
8996 this.drawTitle(pt, vm, ctx, opacity);
8997
8998 // Body
8999 this.drawBody(pt, vm, ctx, opacity);
9000
9001 // Footer
9002 this.drawFooter(pt, vm, ctx, opacity);
9003 }
9004 },
9005
9006 /**
9007 * Handle an event
9008 * @private
9009 * @param {IEvent} event - The event to handle
9010 * @returns {Boolean} true if the tooltip changed
9011 */
9012 handleEvent: function(e) {
9013 var me = this;
9014 var options = me._options;
9015 var changed = false;
9016
9017 me._lastActive = me._lastActive || [];
9018
9019 // Find Active Elements for tooltips
9020 if (e.type === 'mouseout') {
9021 me._active = [];
9022 } else {
9023 me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
9024 }
9025
9026 // Remember Last Actives
9027 changed = !helpers.arrayEquals(me._active, me._lastActive);
9028
9029 // Only handle target event on tooltip change
9030 if (changed) {
9031 me._lastActive = me._active;
9032
9033 if (options.enabled || options.custom) {
9034 me._eventPosition = {
9035 x: e.x,
9036 y: e.y
9037 };
9038
9039 me.update(true);
9040 me.pivot();
9041 }
9042 }
9043
9044 return changed;
9045 }
9046});
9047
9048/**
9049 * @namespace Chart.Tooltip.positioners
9050 */
9051exports.positioners = positioners;
9052
9053
9054},{"26":26,"27":27,"46":46}],37:[function(require,module,exports){
9055'use strict';
9056
9057var defaults = require(26);
9058var Element = require(27);
9059var helpers = require(46);
9060
9061defaults._set('global', {
9062 elements: {
9063 arc: {
9064 backgroundColor: defaults.global.defaultColor,
9065 borderColor: '#fff',
9066 borderWidth: 2
9067 }
9068 }
9069});
9070
9071module.exports = Element.extend({
9072 inLabelRange: function(mouseX) {
9073 var vm = this._view;
9074
9075 if (vm) {
9076 return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
9077 }
9078 return false;
9079 },
9080
9081 inRange: function(chartX, chartY) {
9082 var vm = this._view;
9083
9084 if (vm) {
9085 var pointRelativePosition = helpers.getAngleFromPoint(vm, {x: chartX, y: chartY});
9086 var angle = pointRelativePosition.angle;
9087 var distance = pointRelativePosition.distance;
9088
9089 // Sanitise angle range
9090 var startAngle = vm.startAngle;
9091 var endAngle = vm.endAngle;
9092 while (endAngle < startAngle) {
9093 endAngle += 2.0 * Math.PI;
9094 }
9095 while (angle > endAngle) {
9096 angle -= 2.0 * Math.PI;
9097 }
9098 while (angle < startAngle) {
9099 angle += 2.0 * Math.PI;
9100 }
9101
9102 // Check if within the range of the open/close angle
9103 var betweenAngles = (angle >= startAngle && angle <= endAngle);
9104 var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
9105
9106 return (betweenAngles && withinRadius);
9107 }
9108 return false;
9109 },
9110
9111 getCenterPoint: function() {
9112 var vm = this._view;
9113 var halfAngle = (vm.startAngle + vm.endAngle) / 2;
9114 var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
9115 return {
9116 x: vm.x + Math.cos(halfAngle) * halfRadius,
9117 y: vm.y + Math.sin(halfAngle) * halfRadius
9118 };
9119 },
9120
9121 getArea: function() {
9122 var vm = this._view;
9123 return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
9124 },
9125
9126 tooltipPosition: function() {
9127 var vm = this._view;
9128 var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
9129 var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
9130
9131 return {
9132 x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
9133 y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
9134 };
9135 },
9136
9137 draw: function() {
9138 var ctx = this._chart.ctx;
9139 var vm = this._view;
9140 var sA = vm.startAngle;
9141 var eA = vm.endAngle;
9142
9143 ctx.beginPath();
9144
9145 ctx.arc(vm.x, vm.y, vm.outerRadius, sA, eA);
9146 ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
9147
9148 ctx.closePath();
9149 ctx.strokeStyle = vm.borderColor;
9150 ctx.lineWidth = vm.borderWidth;
9151
9152 ctx.fillStyle = vm.backgroundColor;
9153
9154 ctx.fill();
9155 ctx.lineJoin = 'bevel';
9156
9157 if (vm.borderWidth) {
9158 ctx.stroke();
9159 }
9160 }
9161});
9162
9163},{"26":26,"27":27,"46":46}],38:[function(require,module,exports){
9164'use strict';
9165
9166var defaults = require(26);
9167var Element = require(27);
9168var helpers = require(46);
9169
9170var globalDefaults = defaults.global;
9171
9172defaults._set('global', {
9173 elements: {
9174 line: {
9175 tension: 0.4,
9176 backgroundColor: globalDefaults.defaultColor,
9177 borderWidth: 3,
9178 borderColor: globalDefaults.defaultColor,
9179 borderCapStyle: 'butt',
9180 borderDash: [],
9181 borderDashOffset: 0.0,
9182 borderJoinStyle: 'miter',
9183 capBezierPoints: true,
9184 fill: true, // do we fill in the area between the line and its base axis
9185 }
9186 }
9187});
9188
9189module.exports = Element.extend({
9190 draw: function() {
9191 var me = this;
9192 var vm = me._view;
9193 var ctx = me._chart.ctx;
9194 var spanGaps = vm.spanGaps;
9195 var points = me._children.slice(); // clone array
9196 var globalOptionLineElements = globalDefaults.elements.line;
9197 var lastDrawnIndex = -1;
9198 var index, current, previous, currentVM;
9199
9200 // If we are looping, adding the first point again
9201 if (me._loop && points.length) {
9202 points.push(points[0]);
9203 }
9204
9205 ctx.save();
9206
9207 // Stroke Line Options
9208 ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
9209
9210 // IE 9 and 10 do not support line dash
9211 if (ctx.setLineDash) {
9212 ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
9213 }
9214
9215 ctx.lineDashOffset = vm.borderDashOffset || globalOptionLineElements.borderDashOffset;
9216 ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
9217 ctx.lineWidth = vm.borderWidth || globalOptionLineElements.borderWidth;
9218 ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
9219
9220 // Stroke Line
9221 ctx.beginPath();
9222 lastDrawnIndex = -1;
9223
9224 for (index = 0; index < points.length; ++index) {
9225 current = points[index];
9226 previous = helpers.previousItem(points, index);
9227 currentVM = current._view;
9228
9229 // First point moves to it's starting position no matter what
9230 if (index === 0) {
9231 if (!currentVM.skip) {
9232 ctx.moveTo(currentVM.x, currentVM.y);
9233 lastDrawnIndex = index;
9234 }
9235 } else {
9236 previous = lastDrawnIndex === -1 ? previous : points[lastDrawnIndex];
9237
9238 if (!currentVM.skip) {
9239 if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
9240 // There was a gap and this is the first point after the gap
9241 ctx.moveTo(currentVM.x, currentVM.y);
9242 } else {
9243 // Line to next point
9244 helpers.canvas.lineTo(ctx, previous._view, current._view);
9245 }
9246 lastDrawnIndex = index;
9247 }
9248 }
9249 }
9250
9251 ctx.stroke();
9252 ctx.restore();
9253 }
9254});
9255
9256},{"26":26,"27":27,"46":46}],39:[function(require,module,exports){
9257'use strict';
9258
9259var defaults = require(26);
9260var Element = require(27);
9261var helpers = require(46);
9262
9263var defaultColor = defaults.global.defaultColor;
9264
9265defaults._set('global', {
9266 elements: {
9267 point: {
9268 radius: 3,
9269 pointStyle: 'circle',
9270 backgroundColor: defaultColor,
9271 borderColor: defaultColor,
9272 borderWidth: 1,
9273 // Hover
9274 hitRadius: 1,
9275 hoverRadius: 4,
9276 hoverBorderWidth: 1
9277 }
9278 }
9279});
9280
9281function xRange(mouseX) {
9282 var vm = this._view;
9283 return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
9284}
9285
9286function yRange(mouseY) {
9287 var vm = this._view;
9288 return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
9289}
9290
9291module.exports = Element.extend({
9292 inRange: function(mouseX, mouseY) {
9293 var vm = this._view;
9294 return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
9295 },
9296
9297 inLabelRange: xRange,
9298 inXRange: xRange,
9299 inYRange: yRange,
9300
9301 getCenterPoint: function() {
9302 var vm = this._view;
9303 return {
9304 x: vm.x,
9305 y: vm.y
9306 };
9307 },
9308
9309 getArea: function() {
9310 return Math.PI * Math.pow(this._view.radius, 2);
9311 },
9312
9313 tooltipPosition: function() {
9314 var vm = this._view;
9315 return {
9316 x: vm.x,
9317 y: vm.y,
9318 padding: vm.radius + vm.borderWidth
9319 };
9320 },
9321
9322 draw: function(chartArea) {
9323 var vm = this._view;
9324 var model = this._model;
9325 var ctx = this._chart.ctx;
9326 var pointStyle = vm.pointStyle;
9327 var radius = vm.radius;
9328 var x = vm.x;
9329 var y = vm.y;
9330 var color = helpers.color;
9331 var errMargin = 1.01; // 1.01 is margin for Accumulated error. (Especially Edge, IE.)
9332 var ratio = 0;
9333
9334 if (vm.skip) {
9335 return;
9336 }
9337
9338 ctx.strokeStyle = vm.borderColor || defaultColor;
9339 ctx.lineWidth = helpers.valueOrDefault(vm.borderWidth, defaults.global.elements.point.borderWidth);
9340 ctx.fillStyle = vm.backgroundColor || defaultColor;
9341
9342 // Cliping for Points.
9343 // going out from inner charArea?
9344 if ((chartArea !== undefined) && ((model.x < chartArea.left) || (chartArea.right * errMargin < model.x) || (model.y < chartArea.top) || (chartArea.bottom * errMargin < model.y))) {
9345 // Point fade out
9346 if (model.x < chartArea.left) {
9347 ratio = (x - model.x) / (chartArea.left - model.x);
9348 } else if (chartArea.right * errMargin < model.x) {
9349 ratio = (model.x - x) / (model.x - chartArea.right);
9350 } else if (model.y < chartArea.top) {
9351 ratio = (y - model.y) / (chartArea.top - model.y);
9352 } else if (chartArea.bottom * errMargin < model.y) {
9353 ratio = (model.y - y) / (model.y - chartArea.bottom);
9354 }
9355 ratio = Math.round(ratio * 100) / 100;
9356 ctx.strokeStyle = color(ctx.strokeStyle).alpha(ratio).rgbString();
9357 ctx.fillStyle = color(ctx.fillStyle).alpha(ratio).rgbString();
9358 }
9359
9360 helpers.canvas.drawPoint(ctx, pointStyle, radius, x, y);
9361 }
9362});
9363
9364},{"26":26,"27":27,"46":46}],40:[function(require,module,exports){
9365'use strict';
9366
9367var defaults = require(26);
9368var Element = require(27);
9369
9370defaults._set('global', {
9371 elements: {
9372 rectangle: {
9373 backgroundColor: defaults.global.defaultColor,
9374 borderColor: defaults.global.defaultColor,
9375 borderSkipped: 'bottom',
9376 borderWidth: 0
9377 }
9378 }
9379});
9380
9381function isVertical(bar) {
9382 return bar._view.width !== undefined;
9383}
9384
9385/**
9386 * Helper function to get the bounds of the bar regardless of the orientation
9387 * @param bar {Chart.Element.Rectangle} the bar
9388 * @return {Bounds} bounds of the bar
9389 * @private
9390 */
9391function getBarBounds(bar) {
9392 var vm = bar._view;
9393 var x1, x2, y1, y2;
9394
9395 if (isVertical(bar)) {
9396 // vertical
9397 var halfWidth = vm.width / 2;
9398 x1 = vm.x - halfWidth;
9399 x2 = vm.x + halfWidth;
9400 y1 = Math.min(vm.y, vm.base);
9401 y2 = Math.max(vm.y, vm.base);
9402 } else {
9403 // horizontal bar
9404 var halfHeight = vm.height / 2;
9405 x1 = Math.min(vm.x, vm.base);
9406 x2 = Math.max(vm.x, vm.base);
9407 y1 = vm.y - halfHeight;
9408 y2 = vm.y + halfHeight;
9409 }
9410
9411 return {
9412 left: x1,
9413 top: y1,
9414 right: x2,
9415 bottom: y2
9416 };
9417}
9418
9419module.exports = Element.extend({
9420 draw: function() {
9421 var ctx = this._chart.ctx;
9422 var vm = this._view;
9423 var left, right, top, bottom, signX, signY, borderSkipped;
9424 var borderWidth = vm.borderWidth;
9425
9426 if (!vm.horizontal) {
9427 // bar
9428 left = vm.x - vm.width / 2;
9429 right = vm.x + vm.width / 2;
9430 top = vm.y;
9431 bottom = vm.base;
9432 signX = 1;
9433 signY = bottom > top ? 1 : -1;
9434 borderSkipped = vm.borderSkipped || 'bottom';
9435 } else {
9436 // horizontal bar
9437 left = vm.base;
9438 right = vm.x;
9439 top = vm.y - vm.height / 2;
9440 bottom = vm.y + vm.height / 2;
9441 signX = right > left ? 1 : -1;
9442 signY = 1;
9443 borderSkipped = vm.borderSkipped || 'left';
9444 }
9445
9446 // Canvas doesn't allow us to stroke inside the width so we can
9447 // adjust the sizes to fit if we're setting a stroke on the line
9448 if (borderWidth) {
9449 // borderWidth shold be less than bar width and bar height.
9450 var barSize = Math.min(Math.abs(left - right), Math.abs(top - bottom));
9451 borderWidth = borderWidth > barSize ? barSize : borderWidth;
9452 var halfStroke = borderWidth / 2;
9453 // Adjust borderWidth when bar top position is near vm.base(zero).
9454 var borderLeft = left + (borderSkipped !== 'left' ? halfStroke * signX : 0);
9455 var borderRight = right + (borderSkipped !== 'right' ? -halfStroke * signX : 0);
9456 var borderTop = top + (borderSkipped !== 'top' ? halfStroke * signY : 0);
9457 var borderBottom = bottom + (borderSkipped !== 'bottom' ? -halfStroke * signY : 0);
9458 // not become a vertical line?
9459 if (borderLeft !== borderRight) {
9460 top = borderTop;
9461 bottom = borderBottom;
9462 }
9463 // not become a horizontal line?
9464 if (borderTop !== borderBottom) {
9465 left = borderLeft;
9466 right = borderRight;
9467 }
9468 }
9469
9470 ctx.beginPath();
9471 ctx.fillStyle = vm.backgroundColor;
9472 ctx.strokeStyle = vm.borderColor;
9473 ctx.lineWidth = borderWidth;
9474
9475 // Corner points, from bottom-left to bottom-right clockwise
9476 // | 1 2 |
9477 // | 0 3 |
9478 var corners = [
9479 [left, bottom],
9480 [left, top],
9481 [right, top],
9482 [right, bottom]
9483 ];
9484
9485 // Find first (starting) corner with fallback to 'bottom'
9486 var borders = ['bottom', 'left', 'top', 'right'];
9487 var startCorner = borders.indexOf(borderSkipped, 0);
9488 if (startCorner === -1) {
9489 startCorner = 0;
9490 }
9491
9492 function cornerAt(index) {
9493 return corners[(startCorner + index) % 4];
9494 }
9495
9496 // Draw rectangle from 'startCorner'
9497 var corner = cornerAt(0);
9498 ctx.moveTo(corner[0], corner[1]);
9499
9500 for (var i = 1; i < 4; i++) {
9501 corner = cornerAt(i);
9502 ctx.lineTo(corner[0], corner[1]);
9503 }
9504
9505 ctx.fill();
9506 if (borderWidth) {
9507 ctx.stroke();
9508 }
9509 },
9510
9511 height: function() {
9512 var vm = this._view;
9513 return vm.base - vm.y;
9514 },
9515
9516 inRange: function(mouseX, mouseY) {
9517 var inRange = false;
9518
9519 if (this._view) {
9520 var bounds = getBarBounds(this);
9521 inRange = mouseX >= bounds.left && mouseX <= bounds.right && mouseY >= bounds.top && mouseY <= bounds.bottom;
9522 }
9523
9524 return inRange;
9525 },
9526
9527 inLabelRange: function(mouseX, mouseY) {
9528 var me = this;
9529 if (!me._view) {
9530 return false;
9531 }
9532
9533 var inRange = false;
9534 var bounds = getBarBounds(me);
9535
9536 if (isVertical(me)) {
9537 inRange = mouseX >= bounds.left && mouseX <= bounds.right;
9538 } else {
9539 inRange = mouseY >= bounds.top && mouseY <= bounds.bottom;
9540 }
9541
9542 return inRange;
9543 },
9544
9545 inXRange: function(mouseX) {
9546 var bounds = getBarBounds(this);
9547 return mouseX >= bounds.left && mouseX <= bounds.right;
9548 },
9549
9550 inYRange: function(mouseY) {
9551 var bounds = getBarBounds(this);
9552 return mouseY >= bounds.top && mouseY <= bounds.bottom;
9553 },
9554
9555 getCenterPoint: function() {
9556 var vm = this._view;
9557 var x, y;
9558 if (isVertical(this)) {
9559 x = vm.x;
9560 y = (vm.y + vm.base) / 2;
9561 } else {
9562 x = (vm.x + vm.base) / 2;
9563 y = vm.y;
9564 }
9565
9566 return {x: x, y: y};
9567 },
9568
9569 getArea: function() {
9570 var vm = this._view;
9571 return vm.width * Math.abs(vm.y - vm.base);
9572 },
9573
9574 tooltipPosition: function() {
9575 var vm = this._view;
9576 return {
9577 x: vm.x,
9578 y: vm.y
9579 };
9580 }
9581});
9582
9583},{"26":26,"27":27}],41:[function(require,module,exports){
9584'use strict';
9585
9586module.exports = {};
9587module.exports.Arc = require(37);
9588module.exports.Line = require(38);
9589module.exports.Point = require(39);
9590module.exports.Rectangle = require(40);
9591
9592},{"37":37,"38":38,"39":39,"40":40}],42:[function(require,module,exports){
9593'use strict';
9594
9595var helpers = require(43);
9596
9597/**
9598 * @namespace Chart.helpers.canvas
9599 */
9600var exports = module.exports = {
9601 /**
9602 * Clears the entire canvas associated to the given `chart`.
9603 * @param {Chart} chart - The chart for which to clear the canvas.
9604 */
9605 clear: function(chart) {
9606 chart.ctx.clearRect(0, 0, chart.width, chart.height);
9607 },
9608
9609 /**
9610 * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
9611 * given size (width, height) and the same `radius` for all corners.
9612 * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
9613 * @param {Number} x - The x axis of the coordinate for the rectangle starting point.
9614 * @param {Number} y - The y axis of the coordinate for the rectangle starting point.
9615 * @param {Number} width - The rectangle's width.
9616 * @param {Number} height - The rectangle's height.
9617 * @param {Number} radius - The rounded amount (in pixels) for the four corners.
9618 * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
9619 */
9620 roundedRect: function(ctx, x, y, width, height, radius) {
9621 if (radius) {
9622 var rx = Math.min(radius, width / 2);
9623 var ry = Math.min(radius, height / 2);
9624
9625 ctx.moveTo(x + rx, y);
9626 ctx.lineTo(x + width - rx, y);
9627 ctx.quadraticCurveTo(x + width, y, x + width, y + ry);
9628 ctx.lineTo(x + width, y + height - ry);
9629 ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height);
9630 ctx.lineTo(x + rx, y + height);
9631 ctx.quadraticCurveTo(x, y + height, x, y + height - ry);
9632 ctx.lineTo(x, y + ry);
9633 ctx.quadraticCurveTo(x, y, x + rx, y);
9634 } else {
9635 ctx.rect(x, y, width, height);
9636 }
9637 },
9638
9639 drawPoint: function(ctx, style, radius, x, y) {
9640 var type, edgeLength, xOffset, yOffset, height, size;
9641
9642 if (style && typeof style === 'object') {
9643 type = style.toString();
9644 if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
9645 ctx.drawImage(style, x - style.width / 2, y - style.height / 2, style.width, style.height);
9646 return;
9647 }
9648 }
9649
9650 if (isNaN(radius) || radius <= 0) {
9651 return;
9652 }
9653
9654 switch (style) {
9655 // Default includes circle
9656 default:
9657 ctx.beginPath();
9658 ctx.arc(x, y, radius, 0, Math.PI * 2);
9659 ctx.closePath();
9660 ctx.fill();
9661 break;
9662 case 'triangle':
9663 ctx.beginPath();
9664 edgeLength = 3 * radius / Math.sqrt(3);
9665 height = edgeLength * Math.sqrt(3) / 2;
9666 ctx.moveTo(x - edgeLength / 2, y + height / 3);
9667 ctx.lineTo(x + edgeLength / 2, y + height / 3);
9668 ctx.lineTo(x, y - 2 * height / 3);
9669 ctx.closePath();
9670 ctx.fill();
9671 break;
9672 case 'rect':
9673 size = 1 / Math.SQRT2 * radius;
9674 ctx.beginPath();
9675 ctx.fillRect(x - size, y - size, 2 * size, 2 * size);
9676 ctx.strokeRect(x - size, y - size, 2 * size, 2 * size);
9677 break;
9678 case 'rectRounded':
9679 var offset = radius / Math.SQRT2;
9680 var leftX = x - offset;
9681 var topY = y - offset;
9682 var sideSize = Math.SQRT2 * radius;
9683 ctx.beginPath();
9684 this.roundedRect(ctx, leftX, topY, sideSize, sideSize, radius / 2);
9685 ctx.closePath();
9686 ctx.fill();
9687 break;
9688 case 'rectRot':
9689 size = 1 / Math.SQRT2 * radius;
9690 ctx.beginPath();
9691 ctx.moveTo(x - size, y);
9692 ctx.lineTo(x, y + size);
9693 ctx.lineTo(x + size, y);
9694 ctx.lineTo(x, y - size);
9695 ctx.closePath();
9696 ctx.fill();
9697 break;
9698 case 'cross':
9699 ctx.beginPath();
9700 ctx.moveTo(x, y + radius);
9701 ctx.lineTo(x, y - radius);
9702 ctx.moveTo(x - radius, y);
9703 ctx.lineTo(x + radius, y);
9704 ctx.closePath();
9705 break;
9706 case 'crossRot':
9707 ctx.beginPath();
9708 xOffset = Math.cos(Math.PI / 4) * radius;
9709 yOffset = Math.sin(Math.PI / 4) * radius;
9710 ctx.moveTo(x - xOffset, y - yOffset);
9711 ctx.lineTo(x + xOffset, y + yOffset);
9712 ctx.moveTo(x - xOffset, y + yOffset);
9713 ctx.lineTo(x + xOffset, y - yOffset);
9714 ctx.closePath();
9715 break;
9716 case 'star':
9717 ctx.beginPath();
9718 ctx.moveTo(x, y + radius);
9719 ctx.lineTo(x, y - radius);
9720 ctx.moveTo(x - radius, y);
9721 ctx.lineTo(x + radius, y);
9722 xOffset = Math.cos(Math.PI / 4) * radius;
9723 yOffset = Math.sin(Math.PI / 4) * radius;
9724 ctx.moveTo(x - xOffset, y - yOffset);
9725 ctx.lineTo(x + xOffset, y + yOffset);
9726 ctx.moveTo(x - xOffset, y + yOffset);
9727 ctx.lineTo(x + xOffset, y - yOffset);
9728 ctx.closePath();
9729 break;
9730 case 'line':
9731 ctx.beginPath();
9732 ctx.moveTo(x - radius, y);
9733 ctx.lineTo(x + radius, y);
9734 ctx.closePath();
9735 break;
9736 case 'dash':
9737 ctx.beginPath();
9738 ctx.moveTo(x, y);
9739 ctx.lineTo(x + radius, y);
9740 ctx.closePath();
9741 break;
9742 }
9743
9744 ctx.stroke();
9745 },
9746
9747 clipArea: function(ctx, area) {
9748 ctx.save();
9749 ctx.beginPath();
9750 ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
9751 ctx.clip();
9752 },
9753
9754 unclipArea: function(ctx) {
9755 ctx.restore();
9756 },
9757
9758 lineTo: function(ctx, previous, target, flip) {
9759 if (target.steppedLine) {
9760 if ((target.steppedLine === 'after' && !flip) || (target.steppedLine !== 'after' && flip)) {
9761 ctx.lineTo(previous.x, target.y);
9762 } else {
9763 ctx.lineTo(target.x, previous.y);
9764 }
9765 ctx.lineTo(target.x, target.y);
9766 return;
9767 }
9768
9769 if (!target.tension) {
9770 ctx.lineTo(target.x, target.y);
9771 return;
9772 }
9773
9774 ctx.bezierCurveTo(
9775 flip ? previous.controlPointPreviousX : previous.controlPointNextX,
9776 flip ? previous.controlPointPreviousY : previous.controlPointNextY,
9777 flip ? target.controlPointNextX : target.controlPointPreviousX,
9778 flip ? target.controlPointNextY : target.controlPointPreviousY,
9779 target.x,
9780 target.y);
9781 }
9782};
9783
9784// DEPRECATIONS
9785
9786/**
9787 * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
9788 * @namespace Chart.helpers.clear
9789 * @deprecated since version 2.7.0
9790 * @todo remove at version 3
9791 * @private
9792 */
9793helpers.clear = exports.clear;
9794
9795/**
9796 * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
9797 * @namespace Chart.helpers.drawRoundedRectangle
9798 * @deprecated since version 2.7.0
9799 * @todo remove at version 3
9800 * @private
9801 */
9802helpers.drawRoundedRectangle = function(ctx) {
9803 ctx.beginPath();
9804 exports.roundedRect.apply(exports, arguments);
9805 ctx.closePath();
9806};
9807
9808},{"43":43}],43:[function(require,module,exports){
9809'use strict';
9810
9811/**
9812 * @namespace Chart.helpers
9813 */
9814var helpers = {
9815 /**
9816 * An empty function that can be used, for example, for optional callback.
9817 */
9818 noop: function() {},
9819
9820 /**
9821 * Returns a unique id, sequentially generated from a global variable.
9822 * @returns {Number}
9823 * @function
9824 */
9825 uid: (function() {
9826 var id = 0;
9827 return function() {
9828 return id++;
9829 };
9830 }()),
9831
9832 /**
9833 * Returns true if `value` is neither null nor undefined, else returns false.
9834 * @param {*} value - The value to test.
9835 * @returns {Boolean}
9836 * @since 2.7.0
9837 */
9838 isNullOrUndef: function(value) {
9839 return value === null || typeof value === 'undefined';
9840 },
9841
9842 /**
9843 * Returns true if `value` is an array, else returns false.
9844 * @param {*} value - The value to test.
9845 * @returns {Boolean}
9846 * @function
9847 */
9848 isArray: Array.isArray ? Array.isArray : function(value) {
9849 return Object.prototype.toString.call(value) === '[object Array]';
9850 },
9851
9852 /**
9853 * Returns true if `value` is an object (excluding null), else returns false.
9854 * @param {*} value - The value to test.
9855 * @returns {Boolean}
9856 * @since 2.7.0
9857 */
9858 isObject: function(value) {
9859 return value !== null && Object.prototype.toString.call(value) === '[object Object]';
9860 },
9861
9862 /**
9863 * Returns `value` if defined, else returns `defaultValue`.
9864 * @param {*} value - The value to return if defined.
9865 * @param {*} defaultValue - The value to return if `value` is undefined.
9866 * @returns {*}
9867 */
9868 valueOrDefault: function(value, defaultValue) {
9869 return typeof value === 'undefined' ? defaultValue : value;
9870 },
9871
9872 /**
9873 * Returns value at the given `index` in array if defined, else returns `defaultValue`.
9874 * @param {Array} value - The array to lookup for value at `index`.
9875 * @param {Number} index - The index in `value` to lookup for value.
9876 * @param {*} defaultValue - The value to return if `value[index]` is undefined.
9877 * @returns {*}
9878 */
9879 valueAtIndexOrDefault: function(value, index, defaultValue) {
9880 return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
9881 },
9882
9883 /**
9884 * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
9885 * value returned by `fn`. If `fn` is not a function, this method returns undefined.
9886 * @param {Function} fn - The function to call.
9887 * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
9888 * @param {Object} [thisArg] - The value of `this` provided for the call to `fn`.
9889 * @returns {*}
9890 */
9891 callback: function(fn, args, thisArg) {
9892 if (fn && typeof fn.call === 'function') {
9893 return fn.apply(thisArg, args);
9894 }
9895 },
9896
9897 /**
9898 * Note(SB) for performance sake, this method should only be used when loopable type
9899 * is unknown or in none intensive code (not called often and small loopable). Else
9900 * it's preferable to use a regular for() loop and save extra function calls.
9901 * @param {Object|Array} loopable - The object or array to be iterated.
9902 * @param {Function} fn - The function to call for each item.
9903 * @param {Object} [thisArg] - The value of `this` provided for the call to `fn`.
9904 * @param {Boolean} [reverse] - If true, iterates backward on the loopable.
9905 */
9906 each: function(loopable, fn, thisArg, reverse) {
9907 var i, len, keys;
9908 if (helpers.isArray(loopable)) {
9909 len = loopable.length;
9910 if (reverse) {
9911 for (i = len - 1; i >= 0; i--) {
9912 fn.call(thisArg, loopable[i], i);
9913 }
9914 } else {
9915 for (i = 0; i < len; i++) {
9916 fn.call(thisArg, loopable[i], i);
9917 }
9918 }
9919 } else if (helpers.isObject(loopable)) {
9920 keys = Object.keys(loopable);
9921 len = keys.length;
9922 for (i = 0; i < len; i++) {
9923 fn.call(thisArg, loopable[keys[i]], keys[i]);
9924 }
9925 }
9926 },
9927
9928 /**
9929 * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
9930 * @see http://stackoverflow.com/a/14853974
9931 * @param {Array} a0 - The array to compare
9932 * @param {Array} a1 - The array to compare
9933 * @returns {Boolean}
9934 */
9935 arrayEquals: function(a0, a1) {
9936 var i, ilen, v0, v1;
9937
9938 if (!a0 || !a1 || a0.length !== a1.length) {
9939 return false;
9940 }
9941
9942 for (i = 0, ilen = a0.length; i < ilen; ++i) {
9943 v0 = a0[i];
9944 v1 = a1[i];
9945
9946 if (v0 instanceof Array && v1 instanceof Array) {
9947 if (!helpers.arrayEquals(v0, v1)) {
9948 return false;
9949 }
9950 } else if (v0 !== v1) {
9951 // NOTE: two different object instances will never be equal: {x:20} != {x:20}
9952 return false;
9953 }
9954 }
9955
9956 return true;
9957 },
9958
9959 /**
9960 * Returns a deep copy of `source` without keeping references on objects and arrays.
9961 * @param {*} source - The value to clone.
9962 * @returns {*}
9963 */
9964 clone: function(source) {
9965 if (helpers.isArray(source)) {
9966 return source.map(helpers.clone);
9967 }
9968
9969 if (helpers.isObject(source)) {
9970 var target = {};
9971 var keys = Object.keys(source);
9972 var klen = keys.length;
9973 var k = 0;
9974
9975 for (; k < klen; ++k) {
9976 target[keys[k]] = helpers.clone(source[keys[k]]);
9977 }
9978
9979 return target;
9980 }
9981
9982 return source;
9983 },
9984
9985 /**
9986 * The default merger when Chart.helpers.merge is called without merger option.
9987 * Note(SB): this method is also used by configMerge and scaleMerge as fallback.
9988 * @private
9989 */
9990 _merger: function(key, target, source, options) {
9991 var tval = target[key];
9992 var sval = source[key];
9993
9994 if (helpers.isObject(tval) && helpers.isObject(sval)) {
9995 helpers.merge(tval, sval, options);
9996 } else {
9997 target[key] = helpers.clone(sval);
9998 }
9999 },
10000
10001 /**
10002 * Merges source[key] in target[key] only if target[key] is undefined.
10003 * @private
10004 */
10005 _mergerIf: function(key, target, source) {
10006 var tval = target[key];
10007 var sval = source[key];
10008
10009 if (helpers.isObject(tval) && helpers.isObject(sval)) {
10010 helpers.mergeIf(tval, sval);
10011 } else if (!target.hasOwnProperty(key)) {
10012 target[key] = helpers.clone(sval);
10013 }
10014 },
10015
10016 /**
10017 * Recursively deep copies `source` properties into `target` with the given `options`.
10018 * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
10019 * @param {Object} target - The target object in which all sources are merged into.
10020 * @param {Object|Array(Object)} source - Object(s) to merge into `target`.
10021 * @param {Object} [options] - Merging options:
10022 * @param {Function} [options.merger] - The merge method (key, target, source, options)
10023 * @returns {Object} The `target` object.
10024 */
10025 merge: function(target, source, options) {
10026 var sources = helpers.isArray(source) ? source : [source];
10027 var ilen = sources.length;
10028 var merge, i, keys, klen, k;
10029
10030 if (!helpers.isObject(target)) {
10031 return target;
10032 }
10033
10034 options = options || {};
10035 merge = options.merger || helpers._merger;
10036
10037 for (i = 0; i < ilen; ++i) {
10038 source = sources[i];
10039 if (!helpers.isObject(source)) {
10040 continue;
10041 }
10042
10043 keys = Object.keys(source);
10044 for (k = 0, klen = keys.length; k < klen; ++k) {
10045 merge(keys[k], target, source, options);
10046 }
10047 }
10048
10049 return target;
10050 },
10051
10052 /**
10053 * Recursively deep copies `source` properties into `target` *only* if not defined in target.
10054 * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
10055 * @param {Object} target - The target object in which all sources are merged into.
10056 * @param {Object|Array(Object)} source - Object(s) to merge into `target`.
10057 * @returns {Object} The `target` object.
10058 */
10059 mergeIf: function(target, source) {
10060 return helpers.merge(target, source, {merger: helpers._mergerIf});
10061 },
10062
10063 /**
10064 * Applies the contents of two or more objects together into the first object.
10065 * @param {Object} target - The target object in which all objects are merged into.
10066 * @param {Object} arg1 - Object containing additional properties to merge in target.
10067 * @param {Object} argN - Additional objects containing properties to merge in target.
10068 * @returns {Object} The `target` object.
10069 */
10070 extend: function(target) {
10071 var setFn = function(value, key) {
10072 target[key] = value;
10073 };
10074 for (var i = 1, ilen = arguments.length; i < ilen; ++i) {
10075 helpers.each(arguments[i], setFn);
10076 }
10077 return target;
10078 },
10079
10080 /**
10081 * Basic javascript inheritance based on the model created in Backbone.js
10082 */
10083 inherits: function(extensions) {
10084 var me = this;
10085 var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
10086 return me.apply(this, arguments);
10087 };
10088
10089 var Surrogate = function() {
10090 this.constructor = ChartElement;
10091 };
10092
10093 Surrogate.prototype = me.prototype;
10094 ChartElement.prototype = new Surrogate();
10095 ChartElement.extend = helpers.inherits;
10096
10097 if (extensions) {
10098 helpers.extend(ChartElement.prototype, extensions);
10099 }
10100
10101 ChartElement.__super__ = me.prototype;
10102 return ChartElement;
10103 }
10104};
10105
10106module.exports = helpers;
10107
10108// DEPRECATIONS
10109
10110/**
10111 * Provided for backward compatibility, use Chart.helpers.callback instead.
10112 * @function Chart.helpers.callCallback
10113 * @deprecated since version 2.6.0
10114 * @todo remove at version 3
10115 * @private
10116 */
10117helpers.callCallback = helpers.callback;
10118
10119/**
10120 * Provided for backward compatibility, use Array.prototype.indexOf instead.
10121 * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
10122 * @function Chart.helpers.indexOf
10123 * @deprecated since version 2.7.0
10124 * @todo remove at version 3
10125 * @private
10126 */
10127helpers.indexOf = function(array, item, fromIndex) {
10128 return Array.prototype.indexOf.call(array, item, fromIndex);
10129};
10130
10131/**
10132 * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
10133 * @function Chart.helpers.getValueOrDefault
10134 * @deprecated since version 2.7.0
10135 * @todo remove at version 3
10136 * @private
10137 */
10138helpers.getValueOrDefault = helpers.valueOrDefault;
10139
10140/**
10141 * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
10142 * @function Chart.helpers.getValueAtIndexOrDefault
10143 * @deprecated since version 2.7.0
10144 * @todo remove at version 3
10145 * @private
10146 */
10147helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
10148
10149},{}],44:[function(require,module,exports){
10150'use strict';
10151
10152var helpers = require(43);
10153
10154/**
10155 * Easing functions adapted from Robert Penner's easing equations.
10156 * @namespace Chart.helpers.easingEffects
10157 * @see http://www.robertpenner.com/easing/
10158 */
10159var effects = {
10160 linear: function(t) {
10161 return t;
10162 },
10163
10164 easeInQuad: function(t) {
10165 return t * t;
10166 },
10167
10168 easeOutQuad: function(t) {
10169 return -t * (t - 2);
10170 },
10171
10172 easeInOutQuad: function(t) {
10173 if ((t /= 0.5) < 1) {
10174 return 0.5 * t * t;
10175 }
10176 return -0.5 * ((--t) * (t - 2) - 1);
10177 },
10178
10179 easeInCubic: function(t) {
10180 return t * t * t;
10181 },
10182
10183 easeOutCubic: function(t) {
10184 return (t = t - 1) * t * t + 1;
10185 },
10186
10187 easeInOutCubic: function(t) {
10188 if ((t /= 0.5) < 1) {
10189 return 0.5 * t * t * t;
10190 }
10191 return 0.5 * ((t -= 2) * t * t + 2);
10192 },
10193
10194 easeInQuart: function(t) {
10195 return t * t * t * t;
10196 },
10197
10198 easeOutQuart: function(t) {
10199 return -((t = t - 1) * t * t * t - 1);
10200 },
10201
10202 easeInOutQuart: function(t) {
10203 if ((t /= 0.5) < 1) {
10204 return 0.5 * t * t * t * t;
10205 }
10206 return -0.5 * ((t -= 2) * t * t * t - 2);
10207 },
10208
10209 easeInQuint: function(t) {
10210 return t * t * t * t * t;
10211 },
10212
10213 easeOutQuint: function(t) {
10214 return (t = t - 1) * t * t * t * t + 1;
10215 },
10216
10217 easeInOutQuint: function(t) {
10218 if ((t /= 0.5) < 1) {
10219 return 0.5 * t * t * t * t * t;
10220 }
10221 return 0.5 * ((t -= 2) * t * t * t * t + 2);
10222 },
10223
10224 easeInSine: function(t) {
10225 return -Math.cos(t * (Math.PI / 2)) + 1;
10226 },
10227
10228 easeOutSine: function(t) {
10229 return Math.sin(t * (Math.PI / 2));
10230 },
10231
10232 easeInOutSine: function(t) {
10233 return -0.5 * (Math.cos(Math.PI * t) - 1);
10234 },
10235
10236 easeInExpo: function(t) {
10237 return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
10238 },
10239
10240 easeOutExpo: function(t) {
10241 return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
10242 },
10243
10244 easeInOutExpo: function(t) {
10245 if (t === 0) {
10246 return 0;
10247 }
10248 if (t === 1) {
10249 return 1;
10250 }
10251 if ((t /= 0.5) < 1) {
10252 return 0.5 * Math.pow(2, 10 * (t - 1));
10253 }
10254 return 0.5 * (-Math.pow(2, -10 * --t) + 2);
10255 },
10256
10257 easeInCirc: function(t) {
10258 if (t >= 1) {
10259 return t;
10260 }
10261 return -(Math.sqrt(1 - t * t) - 1);
10262 },
10263
10264 easeOutCirc: function(t) {
10265 return Math.sqrt(1 - (t = t - 1) * t);
10266 },
10267
10268 easeInOutCirc: function(t) {
10269 if ((t /= 0.5) < 1) {
10270 return -0.5 * (Math.sqrt(1 - t * t) - 1);
10271 }
10272 return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
10273 },
10274
10275 easeInElastic: function(t) {
10276 var s = 1.70158;
10277 var p = 0;
10278 var a = 1;
10279 if (t === 0) {
10280 return 0;
10281 }
10282 if (t === 1) {
10283 return 1;
10284 }
10285 if (!p) {
10286 p = 0.3;
10287 }
10288 if (a < 1) {
10289 a = 1;
10290 s = p / 4;
10291 } else {
10292 s = p / (2 * Math.PI) * Math.asin(1 / a);
10293 }
10294 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
10295 },
10296
10297 easeOutElastic: function(t) {
10298 var s = 1.70158;
10299 var p = 0;
10300 var a = 1;
10301 if (t === 0) {
10302 return 0;
10303 }
10304 if (t === 1) {
10305 return 1;
10306 }
10307 if (!p) {
10308 p = 0.3;
10309 }
10310 if (a < 1) {
10311 a = 1;
10312 s = p / 4;
10313 } else {
10314 s = p / (2 * Math.PI) * Math.asin(1 / a);
10315 }
10316 return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
10317 },
10318
10319 easeInOutElastic: function(t) {
10320 var s = 1.70158;
10321 var p = 0;
10322 var a = 1;
10323 if (t === 0) {
10324 return 0;
10325 }
10326 if ((t /= 0.5) === 2) {
10327 return 1;
10328 }
10329 if (!p) {
10330 p = 0.45;
10331 }
10332 if (a < 1) {
10333 a = 1;
10334 s = p / 4;
10335 } else {
10336 s = p / (2 * Math.PI) * Math.asin(1 / a);
10337 }
10338 if (t < 1) {
10339 return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
10340 }
10341 return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
10342 },
10343 easeInBack: function(t) {
10344 var s = 1.70158;
10345 return t * t * ((s + 1) * t - s);
10346 },
10347
10348 easeOutBack: function(t) {
10349 var s = 1.70158;
10350 return (t = t - 1) * t * ((s + 1) * t + s) + 1;
10351 },
10352
10353 easeInOutBack: function(t) {
10354 var s = 1.70158;
10355 if ((t /= 0.5) < 1) {
10356 return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
10357 }
10358 return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
10359 },
10360
10361 easeInBounce: function(t) {
10362 return 1 - effects.easeOutBounce(1 - t);
10363 },
10364
10365 easeOutBounce: function(t) {
10366 if (t < (1 / 2.75)) {
10367 return 7.5625 * t * t;
10368 }
10369 if (t < (2 / 2.75)) {
10370 return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
10371 }
10372 if (t < (2.5 / 2.75)) {
10373 return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
10374 }
10375 return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
10376 },
10377
10378 easeInOutBounce: function(t) {
10379 if (t < 0.5) {
10380 return effects.easeInBounce(t * 2) * 0.5;
10381 }
10382 return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
10383 }
10384};
10385
10386module.exports = {
10387 effects: effects
10388};
10389
10390// DEPRECATIONS
10391
10392/**
10393 * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
10394 * @function Chart.helpers.easingEffects
10395 * @deprecated since version 2.7.0
10396 * @todo remove at version 3
10397 * @private
10398 */
10399helpers.easingEffects = effects;
10400
10401},{"43":43}],45:[function(require,module,exports){
10402'use strict';
10403
10404var helpers = require(43);
10405
10406/**
10407 * @alias Chart.helpers.options
10408 * @namespace
10409 */
10410module.exports = {
10411 /**
10412 * Converts the given line height `value` in pixels for a specific font `size`.
10413 * @param {Number|String} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
10414 * @param {Number} size - The font size (in pixels) used to resolve relative `value`.
10415 * @returns {Number} The effective line height in pixels (size * 1.2 if value is invalid).
10416 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
10417 * @since 2.7.0
10418 */
10419 toLineHeight: function(value, size) {
10420 var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
10421 if (!matches || matches[1] === 'normal') {
10422 return size * 1.2;
10423 }
10424
10425 value = +matches[2];
10426
10427 switch (matches[3]) {
10428 case 'px':
10429 return value;
10430 case '%':
10431 value /= 100;
10432 break;
10433 default:
10434 break;
10435 }
10436
10437 return size * value;
10438 },
10439
10440 /**
10441 * Converts the given value into a padding object with pre-computed width/height.
10442 * @param {Number|Object} value - If a number, set the value to all TRBL component,
10443 * else, if and object, use defined properties and sets undefined ones to 0.
10444 * @returns {Object} The padding values (top, right, bottom, left, width, height)
10445 * @since 2.7.0
10446 */
10447 toPadding: function(value) {
10448 var t, r, b, l;
10449
10450 if (helpers.isObject(value)) {
10451 t = +value.top || 0;
10452 r = +value.right || 0;
10453 b = +value.bottom || 0;
10454 l = +value.left || 0;
10455 } else {
10456 t = r = b = l = +value || 0;
10457 }
10458
10459 return {
10460 top: t,
10461 right: r,
10462 bottom: b,
10463 left: l,
10464 height: t + b,
10465 width: l + r
10466 };
10467 },
10468
10469 /**
10470 * Evaluates the given `inputs` sequentially and returns the first defined value.
10471 * @param {Array[]} inputs - An array of values, falling back to the last value.
10472 * @param {Object} [context] - If defined and the current value is a function, the value
10473 * is called with `context` as first argument and the result becomes the new input.
10474 * @param {Number} [index] - If defined and the current value is an array, the value
10475 * at `index` become the new input.
10476 * @since 2.7.0
10477 */
10478 resolve: function(inputs, context, index) {
10479 var i, ilen, value;
10480
10481 for (i = 0, ilen = inputs.length; i < ilen; ++i) {
10482 value = inputs[i];
10483 if (value === undefined) {
10484 continue;
10485 }
10486 if (context !== undefined && typeof value === 'function') {
10487 value = value(context);
10488 }
10489 if (index !== undefined && helpers.isArray(value)) {
10490 value = value[index];
10491 }
10492 if (value !== undefined) {
10493 return value;
10494 }
10495 }
10496 }
10497};
10498
10499},{"43":43}],46:[function(require,module,exports){
10500'use strict';
10501
10502module.exports = require(43);
10503module.exports.easing = require(44);
10504module.exports.canvas = require(42);
10505module.exports.options = require(45);
10506
10507},{"42":42,"43":43,"44":44,"45":45}],47:[function(require,module,exports){
10508/**
10509 * Platform fallback implementation (minimal).
10510 * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
10511 */
10512
10513module.exports = {
10514 acquireContext: function(item) {
10515 if (item && item.canvas) {
10516 // Support for any object associated to a canvas (including a context2d)
10517 item = item.canvas;
10518 }
10519
10520 return item && item.getContext('2d') || null;
10521 }
10522};
10523
10524},{}],48:[function(require,module,exports){
10525/**
10526 * Chart.Platform implementation for targeting a web browser
10527 */
10528
10529'use strict';
10530
10531var helpers = require(46);
10532
10533var EXPANDO_KEY = '$chartjs';
10534var CSS_PREFIX = 'chartjs-';
10535var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
10536var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
10537var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
10538
10539/**
10540 * DOM event types -> Chart.js event types.
10541 * Note: only events with different types are mapped.
10542 * @see https://developer.mozilla.org/en-US/docs/Web/Events
10543 */
10544var EVENT_TYPES = {
10545 touchstart: 'mousedown',
10546 touchmove: 'mousemove',
10547 touchend: 'mouseup',
10548 pointerenter: 'mouseenter',
10549 pointerdown: 'mousedown',
10550 pointermove: 'mousemove',
10551 pointerup: 'mouseup',
10552 pointerleave: 'mouseout',
10553 pointerout: 'mouseout'
10554};
10555
10556/**
10557 * The "used" size is the final value of a dimension property after all calculations have
10558 * been performed. This method uses the computed style of `element` but returns undefined
10559 * if the computed style is not expressed in pixels. That can happen in some cases where
10560 * `element` has a size relative to its parent and this last one is not yet displayed,
10561 * for example because of `display: none` on a parent node.
10562 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
10563 * @returns {Number} Size in pixels or undefined if unknown.
10564 */
10565function readUsedSize(element, property) {
10566 var value = helpers.getStyle(element, property);
10567 var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
10568 return matches ? Number(matches[1]) : undefined;
10569}
10570
10571/**
10572 * Initializes the canvas style and render size without modifying the canvas display size,
10573 * since responsiveness is handled by the controller.resize() method. The config is used
10574 * to determine the aspect ratio to apply in case no explicit height has been specified.
10575 */
10576function initCanvas(canvas, config) {
10577 var style = canvas.style;
10578
10579 // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
10580 // returns null or '' if no explicit value has been set to the canvas attribute.
10581 var renderHeight = canvas.getAttribute('height');
10582 var renderWidth = canvas.getAttribute('width');
10583
10584 // Chart.js modifies some canvas values that we want to restore on destroy
10585 canvas[EXPANDO_KEY] = {
10586 initial: {
10587 height: renderHeight,
10588 width: renderWidth,
10589 style: {
10590 display: style.display,
10591 height: style.height,
10592 width: style.width
10593 }
10594 }
10595 };
10596
10597 // Force canvas to display as block to avoid extra space caused by inline
10598 // elements, which would interfere with the responsive resize process.
10599 // https://github.com/chartjs/Chart.js/issues/2538
10600 style.display = style.display || 'block';
10601
10602 if (renderWidth === null || renderWidth === '') {
10603 var displayWidth = readUsedSize(canvas, 'width');
10604 if (displayWidth !== undefined) {
10605 canvas.width = displayWidth;
10606 }
10607 }
10608
10609 if (renderHeight === null || renderHeight === '') {
10610 if (canvas.style.height === '') {
10611 // If no explicit render height and style height, let's apply the aspect ratio,
10612 // which one can be specified by the user but also by charts as default option
10613 // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
10614 canvas.height = canvas.width / (config.options.aspectRatio || 2);
10615 } else {
10616 var displayHeight = readUsedSize(canvas, 'height');
10617 if (displayWidth !== undefined) {
10618 canvas.height = displayHeight;
10619 }
10620 }
10621 }
10622
10623 return canvas;
10624}
10625
10626/**
10627 * Detects support for options object argument in addEventListener.
10628 * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
10629 * @private
10630 */
10631var supportsEventListenerOptions = (function() {
10632 var supports = false;
10633 try {
10634 var options = Object.defineProperty({}, 'passive', {
10635 get: function() {
10636 supports = true;
10637 }
10638 });
10639 window.addEventListener('e', null, options);
10640 } catch (e) {
10641 // continue regardless of error
10642 }
10643 return supports;
10644}());
10645
10646// Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
10647// https://github.com/chartjs/Chart.js/issues/4287
10648var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
10649
10650function addEventListener(node, type, listener) {
10651 node.addEventListener(type, listener, eventListenerOptions);
10652}
10653
10654function removeEventListener(node, type, listener) {
10655 node.removeEventListener(type, listener, eventListenerOptions);
10656}
10657
10658function createEvent(type, chart, x, y, nativeEvent) {
10659 return {
10660 type: type,
10661 chart: chart,
10662 native: nativeEvent || null,
10663 x: x !== undefined ? x : null,
10664 y: y !== undefined ? y : null,
10665 };
10666}
10667
10668function fromNativeEvent(event, chart) {
10669 var type = EVENT_TYPES[event.type] || event.type;
10670 var pos = helpers.getRelativePosition(event, chart);
10671 return createEvent(type, chart, pos.x, pos.y, event);
10672}
10673
10674function throttled(fn, thisArg) {
10675 var ticking = false;
10676 var args = [];
10677
10678 return function() {
10679 args = Array.prototype.slice.call(arguments);
10680 thisArg = thisArg || this;
10681
10682 if (!ticking) {
10683 ticking = true;
10684 helpers.requestAnimFrame.call(window, function() {
10685 ticking = false;
10686 fn.apply(thisArg, args);
10687 });
10688 }
10689 };
10690}
10691
10692// Implementation based on https://github.com/marcj/css-element-queries
10693function createResizer(handler) {
10694 var resizer = document.createElement('div');
10695 var cls = CSS_PREFIX + 'size-monitor';
10696 var maxSize = 1000000;
10697 var style =
10698 'position:absolute;' +
10699 'left:0;' +
10700 'top:0;' +
10701 'right:0;' +
10702 'bottom:0;' +
10703 'overflow:hidden;' +
10704 'pointer-events:none;' +
10705 'visibility:hidden;' +
10706 'z-index:-1;';
10707
10708 resizer.style.cssText = style;
10709 resizer.className = cls;
10710 resizer.innerHTML =
10711 '<div class="' + cls + '-expand" style="' + style + '">' +
10712 '<div style="' +
10713 'position:absolute;' +
10714 'width:' + maxSize + 'px;' +
10715 'height:' + maxSize + 'px;' +
10716 'left:0;' +
10717 'top:0">' +
10718 '</div>' +
10719 '</div>' +
10720 '<div class="' + cls + '-shrink" style="' + style + '">' +
10721 '<div style="' +
10722 'position:absolute;' +
10723 'width:200%;' +
10724 'height:200%;' +
10725 'left:0; ' +
10726 'top:0">' +
10727 '</div>' +
10728 '</div>';
10729
10730 var expand = resizer.childNodes[0];
10731 var shrink = resizer.childNodes[1];
10732
10733 resizer._reset = function() {
10734 expand.scrollLeft = maxSize;
10735 expand.scrollTop = maxSize;
10736 shrink.scrollLeft = maxSize;
10737 shrink.scrollTop = maxSize;
10738 };
10739 var onScroll = function() {
10740 resizer._reset();
10741 handler();
10742 };
10743
10744 addEventListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
10745 addEventListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
10746
10747 return resizer;
10748}
10749
10750// https://davidwalsh.name/detect-node-insertion
10751function watchForRender(node, handler) {
10752 var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
10753 var proxy = expando.renderProxy = function(e) {
10754 if (e.animationName === CSS_RENDER_ANIMATION) {
10755 handler();
10756 }
10757 };
10758
10759 helpers.each(ANIMATION_START_EVENTS, function(type) {
10760 addEventListener(node, type, proxy);
10761 });
10762
10763 // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
10764 // is removed then added back immediately (same animation frame?). Accessing the
10765 // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
10766 // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
10767 // https://github.com/chartjs/Chart.js/issues/4737
10768 expando.reflow = !!node.offsetParent;
10769
10770 node.classList.add(CSS_RENDER_MONITOR);
10771}
10772
10773function unwatchForRender(node) {
10774 var expando = node[EXPANDO_KEY] || {};
10775 var proxy = expando.renderProxy;
10776
10777 if (proxy) {
10778 helpers.each(ANIMATION_START_EVENTS, function(type) {
10779 removeEventListener(node, type, proxy);
10780 });
10781
10782 delete expando.renderProxy;
10783 }
10784
10785 node.classList.remove(CSS_RENDER_MONITOR);
10786}
10787
10788function addResizeListener(node, listener, chart) {
10789 var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
10790
10791 // Let's keep track of this added resizer and thus avoid DOM query when removing it.
10792 var resizer = expando.resizer = createResizer(throttled(function() {
10793 if (expando.resizer) {
10794 return listener(createEvent('resize', chart));
10795 }
10796 }));
10797
10798 // The resizer needs to be attached to the node parent, so we first need to be
10799 // sure that `node` is attached to the DOM before injecting the resizer element.
10800 watchForRender(node, function() {
10801 if (expando.resizer) {
10802 var container = node.parentNode;
10803 if (container && container !== resizer.parentNode) {
10804 container.insertBefore(resizer, container.firstChild);
10805 }
10806
10807 // The container size might have changed, let's reset the resizer state.
10808 resizer._reset();
10809 }
10810 });
10811}
10812
10813function removeResizeListener(node) {
10814 var expando = node[EXPANDO_KEY] || {};
10815 var resizer = expando.resizer;
10816
10817 delete expando.resizer;
10818 unwatchForRender(node);
10819
10820 if (resizer && resizer.parentNode) {
10821 resizer.parentNode.removeChild(resizer);
10822 }
10823}
10824
10825function injectCSS(platform, css) {
10826 // http://stackoverflow.com/q/3922139
10827 var style = platform._style || document.createElement('style');
10828 if (!platform._style) {
10829 platform._style = style;
10830 css = '/* Chart.js */\n' + css;
10831 style.setAttribute('type', 'text/css');
10832 document.getElementsByTagName('head')[0].appendChild(style);
10833 }
10834
10835 style.appendChild(document.createTextNode(css));
10836}
10837
10838module.exports = {
10839 /**
10840 * This property holds whether this platform is enabled for the current environment.
10841 * Currently used by platform.js to select the proper implementation.
10842 * @private
10843 */
10844 _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
10845
10846 initialize: function() {
10847 var keyframes = 'from{opacity:0.99}to{opacity:1}';
10848
10849 injectCSS(this,
10850 // DOM rendering detection
10851 // https://davidwalsh.name/detect-node-insertion
10852 '@-webkit-keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' +
10853 '@keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' +
10854 '.' + CSS_RENDER_MONITOR + '{' +
10855 '-webkit-animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' +
10856 'animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' +
10857 '}'
10858 );
10859 },
10860
10861 acquireContext: function(item, config) {
10862 if (typeof item === 'string') {
10863 item = document.getElementById(item);
10864 } else if (item.length) {
10865 // Support for array based queries (such as jQuery)
10866 item = item[0];
10867 }
10868
10869 if (item && item.canvas) {
10870 // Support for any object associated to a canvas (including a context2d)
10871 item = item.canvas;
10872 }
10873
10874 // To prevent canvas fingerprinting, some add-ons undefine the getContext
10875 // method, for example: https://github.com/kkapsner/CanvasBlocker
10876 // https://github.com/chartjs/Chart.js/issues/2807
10877 var context = item && item.getContext && item.getContext('2d');
10878
10879 // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
10880 // inside an iframe or when running in a protected environment. We could guess the
10881 // types from their toString() value but let's keep things flexible and assume it's
10882 // a sufficient condition if the item has a context2D which has item as `canvas`.
10883 // https://github.com/chartjs/Chart.js/issues/3887
10884 // https://github.com/chartjs/Chart.js/issues/4102
10885 // https://github.com/chartjs/Chart.js/issues/4152
10886 if (context && context.canvas === item) {
10887 initCanvas(item, config);
10888 return context;
10889 }
10890
10891 return null;
10892 },
10893
10894 releaseContext: function(context) {
10895 var canvas = context.canvas;
10896 if (!canvas[EXPANDO_KEY]) {
10897 return;
10898 }
10899
10900 var initial = canvas[EXPANDO_KEY].initial;
10901 ['height', 'width'].forEach(function(prop) {
10902 var value = initial[prop];
10903 if (helpers.isNullOrUndef(value)) {
10904 canvas.removeAttribute(prop);
10905 } else {
10906 canvas.setAttribute(prop, value);
10907 }
10908 });
10909
10910 helpers.each(initial.style || {}, function(value, key) {
10911 canvas.style[key] = value;
10912 });
10913
10914 // The canvas render size might have been changed (and thus the state stack discarded),
10915 // we can't use save() and restore() to restore the initial state. So make sure that at
10916 // least the canvas context is reset to the default state by setting the canvas width.
10917 // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
10918 canvas.width = canvas.width;
10919
10920 delete canvas[EXPANDO_KEY];
10921 },
10922
10923 addEventListener: function(chart, type, listener) {
10924 var canvas = chart.canvas;
10925 if (type === 'resize') {
10926 // Note: the resize event is not supported on all browsers.
10927 addResizeListener(canvas, listener, chart);
10928 return;
10929 }
10930
10931 var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
10932 var proxies = expando.proxies || (expando.proxies = {});
10933 var proxy = proxies[chart.id + '_' + type] = function(event) {
10934 listener(fromNativeEvent(event, chart));
10935 };
10936
10937 addEventListener(canvas, type, proxy);
10938 },
10939
10940 removeEventListener: function(chart, type, listener) {
10941 var canvas = chart.canvas;
10942 if (type === 'resize') {
10943 // Note: the resize event is not supported on all browsers.
10944 removeResizeListener(canvas, listener);
10945 return;
10946 }
10947
10948 var expando = listener[EXPANDO_KEY] || {};
10949 var proxies = expando.proxies || {};
10950 var proxy = proxies[chart.id + '_' + type];
10951 if (!proxy) {
10952 return;
10953 }
10954
10955 removeEventListener(canvas, type, proxy);
10956 }
10957};
10958
10959// DEPRECATIONS
10960
10961/**
10962 * Provided for backward compatibility, use EventTarget.addEventListener instead.
10963 * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
10964 * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
10965 * @function Chart.helpers.addEvent
10966 * @deprecated since version 2.7.0
10967 * @todo remove at version 3
10968 * @private
10969 */
10970helpers.addEvent = addEventListener;
10971
10972/**
10973 * Provided for backward compatibility, use EventTarget.removeEventListener instead.
10974 * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
10975 * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
10976 * @function Chart.helpers.removeEvent
10977 * @deprecated since version 2.7.0
10978 * @todo remove at version 3
10979 * @private
10980 */
10981helpers.removeEvent = removeEventListener;
10982
10983},{"46":46}],49:[function(require,module,exports){
10984'use strict';
10985
10986var helpers = require(46);
10987var basic = require(47);
10988var dom = require(48);
10989
10990// @TODO Make possible to select another platform at build time.
10991var implementation = dom._enabled ? dom : basic;
10992
10993/**
10994 * @namespace Chart.platform
10995 * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
10996 * @since 2.4.0
10997 */
10998module.exports = helpers.extend({
10999 /**
11000 * @since 2.7.0
11001 */
11002 initialize: function() {},
11003
11004 /**
11005 * Called at chart construction time, returns a context2d instance implementing
11006 * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
11007 * @param {*} item - The native item from which to acquire context (platform specific)
11008 * @param {Object} options - The chart options
11009 * @returns {CanvasRenderingContext2D} context2d instance
11010 */
11011 acquireContext: function() {},
11012
11013 /**
11014 * Called at chart destruction time, releases any resources associated to the context
11015 * previously returned by the acquireContext() method.
11016 * @param {CanvasRenderingContext2D} context - The context2d instance
11017 * @returns {Boolean} true if the method succeeded, else false
11018 */
11019 releaseContext: function() {},
11020
11021 /**
11022 * Registers the specified listener on the given chart.
11023 * @param {Chart} chart - Chart from which to listen for event
11024 * @param {String} type - The ({@link IEvent}) type to listen for
11025 * @param {Function} listener - Receives a notification (an object that implements
11026 * the {@link IEvent} interface) when an event of the specified type occurs.
11027 */
11028 addEventListener: function() {},
11029
11030 /**
11031 * Removes the specified listener previously registered with addEventListener.
11032 * @param {Chart} chart -Chart from which to remove the listener
11033 * @param {String} type - The ({@link IEvent}) type to remove
11034 * @param {Function} listener - The listener function to remove from the event target.
11035 */
11036 removeEventListener: function() {}
11037
11038}, implementation);
11039
11040/**
11041 * @interface IPlatform
11042 * Allows abstracting platform dependencies away from the chart
11043 * @borrows Chart.platform.acquireContext as acquireContext
11044 * @borrows Chart.platform.releaseContext as releaseContext
11045 * @borrows Chart.platform.addEventListener as addEventListener
11046 * @borrows Chart.platform.removeEventListener as removeEventListener
11047 */
11048
11049/**
11050 * @interface IEvent
11051 * @prop {String} type - The event type name, possible values are:
11052 * 'contextmenu', 'mouseenter', 'mousedown', 'mousemove', 'mouseup', 'mouseout',
11053 * 'click', 'dblclick', 'keydown', 'keypress', 'keyup' and 'resize'
11054 * @prop {*} native - The original native event (null for emulated events, e.g. 'resize')
11055 * @prop {Number} x - The mouse x position, relative to the canvas (null for incompatible events)
11056 * @prop {Number} y - The mouse y position, relative to the canvas (null for incompatible events)
11057 */
11058
11059},{"46":46,"47":47,"48":48}],50:[function(require,module,exports){
11060'use strict';
11061
11062module.exports = {};
11063module.exports.filler = require(51);
11064module.exports.legend = require(52);
11065module.exports.title = require(53);
11066
11067},{"51":51,"52":52,"53":53}],51:[function(require,module,exports){
11068/**
11069 * Plugin based on discussion from the following Chart.js issues:
11070 * @see https://github.com/chartjs/Chart.js/issues/2380#issuecomment-279961569
11071 * @see https://github.com/chartjs/Chart.js/issues/2440#issuecomment-256461897
11072 */
11073
11074'use strict';
11075
11076var defaults = require(26);
11077var elements = require(41);
11078var helpers = require(46);
11079
11080defaults._set('global', {
11081 plugins: {
11082 filler: {
11083 propagate: true
11084 }
11085 }
11086});
11087
11088var mappers = {
11089 dataset: function(source) {
11090 var index = source.fill;
11091 var chart = source.chart;
11092 var meta = chart.getDatasetMeta(index);
11093 var visible = meta && chart.isDatasetVisible(index);
11094 var points = (visible && meta.dataset._children) || [];
11095 var length = points.length || 0;
11096
11097 return !length ? null : function(point, i) {
11098 return (i < length && points[i]._view) || null;
11099 };
11100 },
11101
11102 boundary: function(source) {
11103 var boundary = source.boundary;
11104 var x = boundary ? boundary.x : null;
11105 var y = boundary ? boundary.y : null;
11106
11107 return function(point) {
11108 return {
11109 x: x === null ? point.x : x,
11110 y: y === null ? point.y : y,
11111 };
11112 };
11113 }
11114};
11115
11116// @todo if (fill[0] === '#')
11117function decodeFill(el, index, count) {
11118 var model = el._model || {};
11119 var fill = model.fill;
11120 var target;
11121
11122 if (fill === undefined) {
11123 fill = !!model.backgroundColor;
11124 }
11125
11126 if (fill === false || fill === null) {
11127 return false;
11128 }
11129
11130 if (fill === true) {
11131 return 'origin';
11132 }
11133
11134 target = parseFloat(fill, 10);
11135 if (isFinite(target) && Math.floor(target) === target) {
11136 if (fill[0] === '-' || fill[0] === '+') {
11137 target = index + target;
11138 }
11139
11140 if (target === index || target < 0 || target >= count) {
11141 return false;
11142 }
11143
11144 return target;
11145 }
11146
11147 switch (fill) {
11148 // compatibility
11149 case 'bottom':
11150 return 'start';
11151 case 'top':
11152 return 'end';
11153 case 'zero':
11154 return 'origin';
11155 // supported boundaries
11156 case 'origin':
11157 case 'start':
11158 case 'end':
11159 return fill;
11160 // invalid fill values
11161 default:
11162 return false;
11163 }
11164}
11165
11166function computeBoundary(source) {
11167 var model = source.el._model || {};
11168 var scale = source.el._scale || {};
11169 var fill = source.fill;
11170 var target = null;
11171 var horizontal;
11172
11173 if (isFinite(fill)) {
11174 return null;
11175 }
11176
11177 // Backward compatibility: until v3, we still need to support boundary values set on
11178 // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
11179 // controllers might still use it (e.g. the Smith chart).
11180
11181 if (fill === 'start') {
11182 target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
11183 } else if (fill === 'end') {
11184 target = model.scaleTop === undefined ? scale.top : model.scaleTop;
11185 } else if (model.scaleZero !== undefined) {
11186 target = model.scaleZero;
11187 } else if (scale.getBasePosition) {
11188 target = scale.getBasePosition();
11189 } else if (scale.getBasePixel) {
11190 target = scale.getBasePixel();
11191 }
11192
11193 if (target !== undefined && target !== null) {
11194 if (target.x !== undefined && target.y !== undefined) {
11195 return target;
11196 }
11197
11198 if (typeof target === 'number' && isFinite(target)) {
11199 horizontal = scale.isHorizontal();
11200 return {
11201 x: horizontal ? target : null,
11202 y: horizontal ? null : target
11203 };
11204 }
11205 }
11206
11207 return null;
11208}
11209
11210function resolveTarget(sources, index, propagate) {
11211 var source = sources[index];
11212 var fill = source.fill;
11213 var visited = [index];
11214 var target;
11215
11216 if (!propagate) {
11217 return fill;
11218 }
11219
11220 while (fill !== false && visited.indexOf(fill) === -1) {
11221 if (!isFinite(fill)) {
11222 return fill;
11223 }
11224
11225 target = sources[fill];
11226 if (!target) {
11227 return false;
11228 }
11229
11230 if (target.visible) {
11231 return fill;
11232 }
11233
11234 visited.push(fill);
11235 fill = target.fill;
11236 }
11237
11238 return false;
11239}
11240
11241function createMapper(source) {
11242 var fill = source.fill;
11243 var type = 'dataset';
11244
11245 if (fill === false) {
11246 return null;
11247 }
11248
11249 if (!isFinite(fill)) {
11250 type = 'boundary';
11251 }
11252
11253 return mappers[type](source);
11254}
11255
11256function isDrawable(point) {
11257 return point && !point.skip;
11258}
11259
11260function drawArea(ctx, curve0, curve1, len0, len1) {
11261 var i;
11262
11263 if (!len0 || !len1) {
11264 return;
11265 }
11266
11267 // building first area curve (normal)
11268 ctx.moveTo(curve0[0].x, curve0[0].y);
11269 for (i = 1; i < len0; ++i) {
11270 helpers.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
11271 }
11272
11273 // joining the two area curves
11274 ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
11275
11276 // building opposite area curve (reverse)
11277 for (i = len1 - 1; i > 0; --i) {
11278 helpers.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
11279 }
11280}
11281
11282function doFill(ctx, points, mapper, view, color, loop) {
11283 var count = points.length;
11284 var span = view.spanGaps;
11285 var curve0 = [];
11286 var curve1 = [];
11287 var len0 = 0;
11288 var len1 = 0;
11289 var i, ilen, index, p0, p1, d0, d1;
11290
11291 ctx.beginPath();
11292
11293 for (i = 0, ilen = (count + !!loop); i < ilen; ++i) {
11294 index = i % count;
11295 p0 = points[index]._view;
11296 p1 = mapper(p0, index, view);
11297 d0 = isDrawable(p0);
11298 d1 = isDrawable(p1);
11299
11300 if (d0 && d1) {
11301 len0 = curve0.push(p0);
11302 len1 = curve1.push(p1);
11303 } else if (len0 && len1) {
11304 if (!span) {
11305 drawArea(ctx, curve0, curve1, len0, len1);
11306 len0 = len1 = 0;
11307 curve0 = [];
11308 curve1 = [];
11309 } else {
11310 if (d0) {
11311 curve0.push(p0);
11312 }
11313 if (d1) {
11314 curve1.push(p1);
11315 }
11316 }
11317 }
11318 }
11319
11320 drawArea(ctx, curve0, curve1, len0, len1);
11321
11322 ctx.closePath();
11323 ctx.fillStyle = color;
11324 ctx.fill();
11325}
11326
11327module.exports = {
11328 id: 'filler',
11329
11330 afterDatasetsUpdate: function(chart, options) {
11331 var count = (chart.data.datasets || []).length;
11332 var propagate = options.propagate;
11333 var sources = [];
11334 var meta, i, el, source;
11335
11336 for (i = 0; i < count; ++i) {
11337 meta = chart.getDatasetMeta(i);
11338 el = meta.dataset;
11339 source = null;
11340
11341 if (el && el._model && el instanceof elements.Line) {
11342 source = {
11343 visible: chart.isDatasetVisible(i),
11344 fill: decodeFill(el, i, count),
11345 chart: chart,
11346 el: el
11347 };
11348 }
11349
11350 meta.$filler = source;
11351 sources.push(source);
11352 }
11353
11354 for (i = 0; i < count; ++i) {
11355 source = sources[i];
11356 if (!source) {
11357 continue;
11358 }
11359
11360 source.fill = resolveTarget(sources, i, propagate);
11361 source.boundary = computeBoundary(source);
11362 source.mapper = createMapper(source);
11363 }
11364 },
11365
11366 beforeDatasetDraw: function(chart, args) {
11367 var meta = args.meta.$filler;
11368 if (!meta) {
11369 return;
11370 }
11371
11372 var ctx = chart.ctx;
11373 var el = meta.el;
11374 var view = el._view;
11375 var points = el._children || [];
11376 var mapper = meta.mapper;
11377 var color = view.backgroundColor || defaults.global.defaultColor;
11378
11379 if (mapper && color && points.length) {
11380 helpers.canvas.clipArea(ctx, chart.chartArea);
11381 doFill(ctx, points, mapper, view, color, el._loop);
11382 helpers.canvas.unclipArea(ctx);
11383 }
11384 }
11385};
11386
11387},{"26":26,"41":41,"46":46}],52:[function(require,module,exports){
11388'use strict';
11389
11390var defaults = require(26);
11391var Element = require(27);
11392var helpers = require(46);
11393var layouts = require(31);
11394
11395var noop = helpers.noop;
11396
11397defaults._set('global', {
11398 legend: {
11399 display: true,
11400 position: 'top',
11401 fullWidth: true,
11402 reverse: false,
11403 weight: 1000,
11404
11405 // a callback that will handle
11406 onClick: function(e, legendItem) {
11407 var index = legendItem.datasetIndex;
11408 var ci = this.chart;
11409 var meta = ci.getDatasetMeta(index);
11410
11411 // See controller.isDatasetVisible comment
11412 meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
11413
11414 // We hid a dataset ... rerender the chart
11415 ci.update();
11416 },
11417
11418 onHover: null,
11419
11420 labels: {
11421 boxWidth: 40,
11422 padding: 10,
11423 // Generates labels shown in the legend
11424 // Valid properties to return:
11425 // text : text to display
11426 // fillStyle : fill of coloured box
11427 // strokeStyle: stroke of coloured box
11428 // hidden : if this legend item refers to a hidden item
11429 // lineCap : cap style for line
11430 // lineDash
11431 // lineDashOffset :
11432 // lineJoin :
11433 // lineWidth :
11434 generateLabels: function(chart) {
11435 var data = chart.data;
11436 return helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {
11437 return {
11438 text: dataset.label,
11439 fillStyle: (!helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
11440 hidden: !chart.isDatasetVisible(i),
11441 lineCap: dataset.borderCapStyle,
11442 lineDash: dataset.borderDash,
11443 lineDashOffset: dataset.borderDashOffset,
11444 lineJoin: dataset.borderJoinStyle,
11445 lineWidth: dataset.borderWidth,
11446 strokeStyle: dataset.borderColor,
11447 pointStyle: dataset.pointStyle,
11448
11449 // Below is extra data used for toggling the datasets
11450 datasetIndex: i
11451 };
11452 }, this) : [];
11453 }
11454 }
11455 },
11456
11457 legendCallback: function(chart) {
11458 var text = [];
11459 text.push('<ul class="' + chart.id + '-legend">');
11460 for (var i = 0; i < chart.data.datasets.length; i++) {
11461 text.push('<li><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"></span>');
11462 if (chart.data.datasets[i].label) {
11463 text.push(chart.data.datasets[i].label);
11464 }
11465 text.push('</li>');
11466 }
11467 text.push('</ul>');
11468 return text.join('');
11469 }
11470});
11471
11472/**
11473 * Helper function to get the box width based on the usePointStyle option
11474 * @param labelopts {Object} the label options on the legend
11475 * @param fontSize {Number} the label font size
11476 * @return {Number} width of the color box area
11477 */
11478function getBoxWidth(labelOpts, fontSize) {
11479 return labelOpts.usePointStyle ?
11480 fontSize * Math.SQRT2 :
11481 labelOpts.boxWidth;
11482}
11483
11484/**
11485 * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
11486 */
11487var Legend = Element.extend({
11488
11489 initialize: function(config) {
11490 helpers.extend(this, config);
11491
11492 // Contains hit boxes for each dataset (in dataset order)
11493 this.legendHitBoxes = [];
11494
11495 // Are we in doughnut mode which has a different data type
11496 this.doughnutMode = false;
11497 },
11498
11499 // These methods are ordered by lifecycle. Utilities then follow.
11500 // Any function defined here is inherited by all legend types.
11501 // Any function can be extended by the legend type
11502
11503 beforeUpdate: noop,
11504 update: function(maxWidth, maxHeight, margins) {
11505 var me = this;
11506
11507 // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
11508 me.beforeUpdate();
11509
11510 // Absorb the master measurements
11511 me.maxWidth = maxWidth;
11512 me.maxHeight = maxHeight;
11513 me.margins = margins;
11514
11515 // Dimensions
11516 me.beforeSetDimensions();
11517 me.setDimensions();
11518 me.afterSetDimensions();
11519 // Labels
11520 me.beforeBuildLabels();
11521 me.buildLabels();
11522 me.afterBuildLabels();
11523
11524 // Fit
11525 me.beforeFit();
11526 me.fit();
11527 me.afterFit();
11528 //
11529 me.afterUpdate();
11530
11531 return me.minSize;
11532 },
11533 afterUpdate: noop,
11534
11535 //
11536
11537 beforeSetDimensions: noop,
11538 setDimensions: function() {
11539 var me = this;
11540 // Set the unconstrained dimension before label rotation
11541 if (me.isHorizontal()) {
11542 // Reset position before calculating rotation
11543 me.width = me.maxWidth;
11544 me.left = 0;
11545 me.right = me.width;
11546 } else {
11547 me.height = me.maxHeight;
11548
11549 // Reset position before calculating rotation
11550 me.top = 0;
11551 me.bottom = me.height;
11552 }
11553
11554 // Reset padding
11555 me.paddingLeft = 0;
11556 me.paddingTop = 0;
11557 me.paddingRight = 0;
11558 me.paddingBottom = 0;
11559
11560 // Reset minSize
11561 me.minSize = {
11562 width: 0,
11563 height: 0
11564 };
11565 },
11566 afterSetDimensions: noop,
11567
11568 //
11569
11570 beforeBuildLabels: noop,
11571 buildLabels: function() {
11572 var me = this;
11573 var labelOpts = me.options.labels || {};
11574 var legendItems = helpers.callback(labelOpts.generateLabels, [me.chart], me) || [];
11575
11576 if (labelOpts.filter) {
11577 legendItems = legendItems.filter(function(item) {
11578 return labelOpts.filter(item, me.chart.data);
11579 });
11580 }
11581
11582 if (me.options.reverse) {
11583 legendItems.reverse();
11584 }
11585
11586 me.legendItems = legendItems;
11587 },
11588 afterBuildLabels: noop,
11589
11590 //
11591
11592 beforeFit: noop,
11593 fit: function() {
11594 var me = this;
11595 var opts = me.options;
11596 var labelOpts = opts.labels;
11597 var display = opts.display;
11598
11599 var ctx = me.ctx;
11600
11601 var globalDefault = defaults.global;
11602 var valueOrDefault = helpers.valueOrDefault;
11603 var fontSize = valueOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize);
11604 var fontStyle = valueOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle);
11605 var fontFamily = valueOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily);
11606 var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily);
11607
11608 // Reset hit boxes
11609 var hitboxes = me.legendHitBoxes = [];
11610
11611 var minSize = me.minSize;
11612 var isHorizontal = me.isHorizontal();
11613
11614 if (isHorizontal) {
11615 minSize.width = me.maxWidth; // fill all the width
11616 minSize.height = display ? 10 : 0;
11617 } else {
11618 minSize.width = display ? 10 : 0;
11619 minSize.height = me.maxHeight; // fill all the height
11620 }
11621
11622 // Increase sizes here
11623 if (display) {
11624 ctx.font = labelFont;
11625
11626 if (isHorizontal) {
11627 // Labels
11628
11629 // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
11630 var lineWidths = me.lineWidths = [0];
11631 var totalHeight = me.legendItems.length ? fontSize + (labelOpts.padding) : 0;
11632
11633 ctx.textAlign = 'left';
11634 ctx.textBaseline = 'top';
11635
11636 helpers.each(me.legendItems, function(legendItem, i) {
11637 var boxWidth = getBoxWidth(labelOpts, fontSize);
11638 var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
11639
11640 if (lineWidths[lineWidths.length - 1] + width + labelOpts.padding >= me.width) {
11641 totalHeight += fontSize + (labelOpts.padding);
11642 lineWidths[lineWidths.length] = me.left;
11643 }
11644
11645 // Store the hitbox width and height here. Final position will be updated in `draw`
11646 hitboxes[i] = {
11647 left: 0,
11648 top: 0,
11649 width: width,
11650 height: fontSize
11651 };
11652
11653 lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
11654 });
11655
11656 minSize.height += totalHeight;
11657
11658 } else {
11659 var vPadding = labelOpts.padding;
11660 var columnWidths = me.columnWidths = [];
11661 var totalWidth = labelOpts.padding;
11662 var currentColWidth = 0;
11663 var currentColHeight = 0;
11664 var itemHeight = fontSize + vPadding;
11665
11666 helpers.each(me.legendItems, function(legendItem, i) {
11667 var boxWidth = getBoxWidth(labelOpts, fontSize);
11668 var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
11669
11670 // If too tall, go to new column
11671 if (currentColHeight + itemHeight > minSize.height) {
11672 totalWidth += currentColWidth + labelOpts.padding;
11673 columnWidths.push(currentColWidth); // previous column width
11674
11675 currentColWidth = 0;
11676 currentColHeight = 0;
11677 }
11678
11679 // Get max width
11680 currentColWidth = Math.max(currentColWidth, itemWidth);
11681 currentColHeight += itemHeight;
11682
11683 // Store the hitbox width and height here. Final position will be updated in `draw`
11684 hitboxes[i] = {
11685 left: 0,
11686 top: 0,
11687 width: itemWidth,
11688 height: fontSize
11689 };
11690 });
11691
11692 totalWidth += currentColWidth;
11693 columnWidths.push(currentColWidth);
11694 minSize.width += totalWidth;
11695 }
11696 }
11697
11698 me.width = minSize.width;
11699 me.height = minSize.height;
11700 },
11701 afterFit: noop,
11702
11703 // Shared Methods
11704 isHorizontal: function() {
11705 return this.options.position === 'top' || this.options.position === 'bottom';
11706 },
11707
11708 // Actually draw the legend on the canvas
11709 draw: function() {
11710 var me = this;
11711 var opts = me.options;
11712 var labelOpts = opts.labels;
11713 var globalDefault = defaults.global;
11714 var lineDefault = globalDefault.elements.line;
11715 var legendWidth = me.width;
11716 var lineWidths = me.lineWidths;
11717
11718 if (opts.display) {
11719 var ctx = me.ctx;
11720 var valueOrDefault = helpers.valueOrDefault;
11721 var fontColor = valueOrDefault(labelOpts.fontColor, globalDefault.defaultFontColor);
11722 var fontSize = valueOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize);
11723 var fontStyle = valueOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle);
11724 var fontFamily = valueOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily);
11725 var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily);
11726 var cursor;
11727
11728 // Canvas setup
11729 ctx.textAlign = 'left';
11730 ctx.textBaseline = 'middle';
11731 ctx.lineWidth = 0.5;
11732 ctx.strokeStyle = fontColor; // for strikethrough effect
11733 ctx.fillStyle = fontColor; // render in correct colour
11734 ctx.font = labelFont;
11735
11736 var boxWidth = getBoxWidth(labelOpts, fontSize);
11737 var hitboxes = me.legendHitBoxes;
11738
11739 // current position
11740 var drawLegendBox = function(x, y, legendItem) {
11741 if (isNaN(boxWidth) || boxWidth <= 0) {
11742 return;
11743 }
11744
11745 // Set the ctx for the box
11746 ctx.save();
11747
11748 ctx.fillStyle = valueOrDefault(legendItem.fillStyle, globalDefault.defaultColor);
11749 ctx.lineCap = valueOrDefault(legendItem.lineCap, lineDefault.borderCapStyle);
11750 ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, lineDefault.borderDashOffset);
11751 ctx.lineJoin = valueOrDefault(legendItem.lineJoin, lineDefault.borderJoinStyle);
11752 ctx.lineWidth = valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth);
11753 ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, globalDefault.defaultColor);
11754 var isLineWidthZero = (valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth) === 0);
11755
11756 if (ctx.setLineDash) {
11757 // IE 9 and 10 do not support line dash
11758 ctx.setLineDash(valueOrDefault(legendItem.lineDash, lineDefault.borderDash));
11759 }
11760
11761 if (opts.labels && opts.labels.usePointStyle) {
11762 // Recalculate x and y for drawPoint() because its expecting
11763 // x and y to be center of figure (instead of top left)
11764 var radius = fontSize * Math.SQRT2 / 2;
11765 var offSet = radius / Math.SQRT2;
11766 var centerX = x + offSet;
11767 var centerY = y + offSet;
11768
11769 // Draw pointStyle as legend symbol
11770 helpers.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY);
11771 } else {
11772 // Draw box as legend symbol
11773 if (!isLineWidthZero) {
11774 ctx.strokeRect(x, y, boxWidth, fontSize);
11775 }
11776 ctx.fillRect(x, y, boxWidth, fontSize);
11777 }
11778
11779 ctx.restore();
11780 };
11781 var fillText = function(x, y, legendItem, textWidth) {
11782 var halfFontSize = fontSize / 2;
11783 var xLeft = boxWidth + halfFontSize + x;
11784 var yMiddle = y + halfFontSize;
11785
11786 ctx.fillText(legendItem.text, xLeft, yMiddle);
11787
11788 if (legendItem.hidden) {
11789 // Strikethrough the text if hidden
11790 ctx.beginPath();
11791 ctx.lineWidth = 2;
11792 ctx.moveTo(xLeft, yMiddle);
11793 ctx.lineTo(xLeft + textWidth, yMiddle);
11794 ctx.stroke();
11795 }
11796 };
11797
11798 // Horizontal
11799 var isHorizontal = me.isHorizontal();
11800 if (isHorizontal) {
11801 cursor = {
11802 x: me.left + ((legendWidth - lineWidths[0]) / 2),
11803 y: me.top + labelOpts.padding,
11804 line: 0
11805 };
11806 } else {
11807 cursor = {
11808 x: me.left + labelOpts.padding,
11809 y: me.top + labelOpts.padding,
11810 line: 0
11811 };
11812 }
11813
11814 var itemHeight = fontSize + labelOpts.padding;
11815 helpers.each(me.legendItems, function(legendItem, i) {
11816 var textWidth = ctx.measureText(legendItem.text).width;
11817 var width = boxWidth + (fontSize / 2) + textWidth;
11818 var x = cursor.x;
11819 var y = cursor.y;
11820
11821 if (isHorizontal) {
11822 if (x + width >= legendWidth) {
11823 y = cursor.y += itemHeight;
11824 cursor.line++;
11825 x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2);
11826 }
11827 } else if (y + itemHeight > me.bottom) {
11828 x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
11829 y = cursor.y = me.top + labelOpts.padding;
11830 cursor.line++;
11831 }
11832
11833 drawLegendBox(x, y, legendItem);
11834
11835 hitboxes[i].left = x;
11836 hitboxes[i].top = y;
11837
11838 // Fill the actual label
11839 fillText(x, y, legendItem, textWidth);
11840
11841 if (isHorizontal) {
11842 cursor.x += width + (labelOpts.padding);
11843 } else {
11844 cursor.y += itemHeight;
11845 }
11846
11847 });
11848 }
11849 },
11850
11851 /**
11852 * Handle an event
11853 * @private
11854 * @param {IEvent} event - The event to handle
11855 * @return {Boolean} true if a change occured
11856 */
11857 handleEvent: function(e) {
11858 var me = this;
11859 var opts = me.options;
11860 var type = e.type === 'mouseup' ? 'click' : e.type;
11861 var changed = false;
11862
11863 if (type === 'mousemove') {
11864 if (!opts.onHover) {
11865 return;
11866 }
11867 } else if (type === 'click') {
11868 if (!opts.onClick) {
11869 return;
11870 }
11871 } else {
11872 return;
11873 }
11874
11875 // Chart event already has relative position in it
11876 var x = e.x;
11877 var y = e.y;
11878
11879 if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
11880 // See if we are touching one of the dataset boxes
11881 var lh = me.legendHitBoxes;
11882 for (var i = 0; i < lh.length; ++i) {
11883 var hitBox = lh[i];
11884
11885 if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
11886 // Touching an element
11887 if (type === 'click') {
11888 // use e.native for backwards compatibility
11889 opts.onClick.call(me, e.native, me.legendItems[i]);
11890 changed = true;
11891 break;
11892 } else if (type === 'mousemove') {
11893 // use e.native for backwards compatibility
11894 opts.onHover.call(me, e.native, me.legendItems[i]);
11895 changed = true;
11896 break;
11897 }
11898 }
11899 }
11900 }
11901
11902 return changed;
11903 }
11904});
11905
11906function createNewLegendAndAttach(chart, legendOpts) {
11907 var legend = new Legend({
11908 ctx: chart.ctx,
11909 options: legendOpts,
11910 chart: chart
11911 });
11912
11913 layouts.configure(chart, legend, legendOpts);
11914 layouts.addBox(chart, legend);
11915 chart.legend = legend;
11916}
11917
11918module.exports = {
11919 id: 'legend',
11920
11921 /**
11922 * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
11923 * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
11924 * the plugin, which one will be re-exposed in the chart.js file.
11925 * https://github.com/chartjs/Chart.js/pull/2640
11926 * @private
11927 */
11928 _element: Legend,
11929
11930 beforeInit: function(chart) {
11931 var legendOpts = chart.options.legend;
11932
11933 if (legendOpts) {
11934 createNewLegendAndAttach(chart, legendOpts);
11935 }
11936 },
11937
11938 beforeUpdate: function(chart) {
11939 var legendOpts = chart.options.legend;
11940 var legend = chart.legend;
11941
11942 if (legendOpts) {
11943 helpers.mergeIf(legendOpts, defaults.global.legend);
11944
11945 if (legend) {
11946 layouts.configure(chart, legend, legendOpts);
11947 legend.options = legendOpts;
11948 } else {
11949 createNewLegendAndAttach(chart, legendOpts);
11950 }
11951 } else if (legend) {
11952 layouts.removeBox(chart, legend);
11953 delete chart.legend;
11954 }
11955 },
11956
11957 afterEvent: function(chart, e) {
11958 var legend = chart.legend;
11959 if (legend) {
11960 legend.handleEvent(e);
11961 }
11962 }
11963};
11964
11965},{"26":26,"27":27,"31":31,"46":46}],53:[function(require,module,exports){
11966'use strict';
11967
11968var defaults = require(26);
11969var Element = require(27);
11970var helpers = require(46);
11971var layouts = require(31);
11972
11973var noop = helpers.noop;
11974
11975defaults._set('global', {
11976 title: {
11977 display: false,
11978 fontStyle: 'bold',
11979 fullWidth: true,
11980 lineHeight: 1.2,
11981 padding: 10,
11982 position: 'top',
11983 text: '',
11984 weight: 2000 // by default greater than legend (1000) to be above
11985 }
11986});
11987
11988/**
11989 * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
11990 */
11991var Title = Element.extend({
11992 initialize: function(config) {
11993 var me = this;
11994 helpers.extend(me, config);
11995
11996 // Contains hit boxes for each dataset (in dataset order)
11997 me.legendHitBoxes = [];
11998 },
11999
12000 // These methods are ordered by lifecycle. Utilities then follow.
12001
12002 beforeUpdate: noop,
12003 update: function(maxWidth, maxHeight, margins) {
12004 var me = this;
12005
12006 // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
12007 me.beforeUpdate();
12008
12009 // Absorb the master measurements
12010 me.maxWidth = maxWidth;
12011 me.maxHeight = maxHeight;
12012 me.margins = margins;
12013
12014 // Dimensions
12015 me.beforeSetDimensions();
12016 me.setDimensions();
12017 me.afterSetDimensions();
12018 // Labels
12019 me.beforeBuildLabels();
12020 me.buildLabels();
12021 me.afterBuildLabels();
12022
12023 // Fit
12024 me.beforeFit();
12025 me.fit();
12026 me.afterFit();
12027 //
12028 me.afterUpdate();
12029
12030 return me.minSize;
12031
12032 },
12033 afterUpdate: noop,
12034
12035 //
12036
12037 beforeSetDimensions: noop,
12038 setDimensions: function() {
12039 var me = this;
12040 // Set the unconstrained dimension before label rotation
12041 if (me.isHorizontal()) {
12042 // Reset position before calculating rotation
12043 me.width = me.maxWidth;
12044 me.left = 0;
12045 me.right = me.width;
12046 } else {
12047 me.height = me.maxHeight;
12048
12049 // Reset position before calculating rotation
12050 me.top = 0;
12051 me.bottom = me.height;
12052 }
12053
12054 // Reset padding
12055 me.paddingLeft = 0;
12056 me.paddingTop = 0;
12057 me.paddingRight = 0;
12058 me.paddingBottom = 0;
12059
12060 // Reset minSize
12061 me.minSize = {
12062 width: 0,
12063 height: 0
12064 };
12065 },
12066 afterSetDimensions: noop,
12067
12068 //
12069
12070 beforeBuildLabels: noop,
12071 buildLabels: noop,
12072 afterBuildLabels: noop,
12073
12074 //
12075
12076 beforeFit: noop,
12077 fit: function() {
12078 var me = this;
12079 var valueOrDefault = helpers.valueOrDefault;
12080 var opts = me.options;
12081 var display = opts.display;
12082 var fontSize = valueOrDefault(opts.fontSize, defaults.global.defaultFontSize);
12083 var minSize = me.minSize;
12084 var lineCount = helpers.isArray(opts.text) ? opts.text.length : 1;
12085 var lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize);
12086 var textSize = display ? (lineCount * lineHeight) + (opts.padding * 2) : 0;
12087
12088 if (me.isHorizontal()) {
12089 minSize.width = me.maxWidth; // fill all the width
12090 minSize.height = textSize;
12091 } else {
12092 minSize.width = textSize;
12093 minSize.height = me.maxHeight; // fill all the height
12094 }
12095
12096 me.width = minSize.width;
12097 me.height = minSize.height;
12098
12099 },
12100 afterFit: noop,
12101
12102 // Shared Methods
12103 isHorizontal: function() {
12104 var pos = this.options.position;
12105 return pos === 'top' || pos === 'bottom';
12106 },
12107
12108 // Actually draw the title block on the canvas
12109 draw: function() {
12110 var me = this;
12111 var ctx = me.ctx;
12112 var valueOrDefault = helpers.valueOrDefault;
12113 var opts = me.options;
12114 var globalDefaults = defaults.global;
12115
12116 if (opts.display) {
12117 var fontSize = valueOrDefault(opts.fontSize, globalDefaults.defaultFontSize);
12118 var fontStyle = valueOrDefault(opts.fontStyle, globalDefaults.defaultFontStyle);
12119 var fontFamily = valueOrDefault(opts.fontFamily, globalDefaults.defaultFontFamily);
12120 var titleFont = helpers.fontString(fontSize, fontStyle, fontFamily);
12121 var lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize);
12122 var offset = lineHeight / 2 + opts.padding;
12123 var rotation = 0;
12124 var top = me.top;
12125 var left = me.left;
12126 var bottom = me.bottom;
12127 var right = me.right;
12128 var maxWidth, titleX, titleY;
12129
12130 ctx.fillStyle = valueOrDefault(opts.fontColor, globalDefaults.defaultFontColor); // render in correct colour
12131 ctx.font = titleFont;
12132
12133 // Horizontal
12134 if (me.isHorizontal()) {
12135 titleX = left + ((right - left) / 2); // midpoint of the width
12136 titleY = top + offset;
12137 maxWidth = right - left;
12138 } else {
12139 titleX = opts.position === 'left' ? left + offset : right - offset;
12140 titleY = top + ((bottom - top) / 2);
12141 maxWidth = bottom - top;
12142 rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
12143 }
12144
12145 ctx.save();
12146 ctx.translate(titleX, titleY);
12147 ctx.rotate(rotation);
12148 ctx.textAlign = 'center';
12149 ctx.textBaseline = 'middle';
12150
12151 var text = opts.text;
12152 if (helpers.isArray(text)) {
12153 var y = 0;
12154 for (var i = 0; i < text.length; ++i) {
12155 ctx.fillText(text[i], 0, y, maxWidth);
12156 y += lineHeight;
12157 }
12158 } else {
12159 ctx.fillText(text, 0, 0, maxWidth);
12160 }
12161
12162 ctx.restore();
12163 }
12164 }
12165});
12166
12167function createNewTitleBlockAndAttach(chart, titleOpts) {
12168 var title = new Title({
12169 ctx: chart.ctx,
12170 options: titleOpts,
12171 chart: chart
12172 });
12173
12174 layouts.configure(chart, title, titleOpts);
12175 layouts.addBox(chart, title);
12176 chart.titleBlock = title;
12177}
12178
12179module.exports = {
12180 id: 'title',
12181
12182 /**
12183 * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
12184 * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
12185 * the plugin, which one will be re-exposed in the chart.js file.
12186 * https://github.com/chartjs/Chart.js/pull/2640
12187 * @private
12188 */
12189 _element: Title,
12190
12191 beforeInit: function(chart) {
12192 var titleOpts = chart.options.title;
12193
12194 if (titleOpts) {
12195 createNewTitleBlockAndAttach(chart, titleOpts);
12196 }
12197 },
12198
12199 beforeUpdate: function(chart) {
12200 var titleOpts = chart.options.title;
12201 var titleBlock = chart.titleBlock;
12202
12203 if (titleOpts) {
12204 helpers.mergeIf(titleOpts, defaults.global.title);
12205
12206 if (titleBlock) {
12207 layouts.configure(chart, titleBlock, titleOpts);
12208 titleBlock.options = titleOpts;
12209 } else {
12210 createNewTitleBlockAndAttach(chart, titleOpts);
12211 }
12212 } else if (titleBlock) {
12213 layouts.removeBox(chart, titleBlock);
12214 delete chart.titleBlock;
12215 }
12216 }
12217};
12218
12219},{"26":26,"27":27,"31":31,"46":46}],54:[function(require,module,exports){
12220'use strict';
12221
12222var Scale = require(33);
12223var scaleService = require(34);
12224
12225module.exports = function() {
12226
12227 // Default config for a category scale
12228 var defaultConfig = {
12229 position: 'bottom'
12230 };
12231
12232 var DatasetScale = Scale.extend({
12233 /**
12234 * Internal function to get the correct labels. If data.xLabels or data.yLabels are defined, use those
12235 * else fall back to data.labels
12236 * @private
12237 */
12238 getLabels: function() {
12239 var data = this.chart.data;
12240 return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels;
12241 },
12242
12243 determineDataLimits: function() {
12244 var me = this;
12245 var labels = me.getLabels();
12246 me.minIndex = 0;
12247 me.maxIndex = labels.length - 1;
12248 var findIndex;
12249
12250 if (me.options.ticks.min !== undefined) {
12251 // user specified min value
12252 findIndex = labels.indexOf(me.options.ticks.min);
12253 me.minIndex = findIndex !== -1 ? findIndex : me.minIndex;
12254 }
12255
12256 if (me.options.ticks.max !== undefined) {
12257 // user specified max value
12258 findIndex = labels.indexOf(me.options.ticks.max);
12259 me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex;
12260 }
12261
12262 me.min = labels[me.minIndex];
12263 me.max = labels[me.maxIndex];
12264 },
12265
12266 buildTicks: function() {
12267 var me = this;
12268 var labels = me.getLabels();
12269 // If we are viewing some subset of labels, slice the original array
12270 me.ticks = (me.minIndex === 0 && me.maxIndex === labels.length - 1) ? labels : labels.slice(me.minIndex, me.maxIndex + 1);
12271 },
12272
12273 getLabelForIndex: function(index, datasetIndex) {
12274 var me = this;
12275 var data = me.chart.data;
12276 var isHorizontal = me.isHorizontal();
12277
12278 if (data.yLabels && !isHorizontal) {
12279 return me.getRightValue(data.datasets[datasetIndex].data[index]);
12280 }
12281 return me.ticks[index - me.minIndex];
12282 },
12283
12284 // Used to get data value locations. Value can either be an index or a numerical value
12285 getPixelForValue: function(value, index) {
12286 var me = this;
12287 var offset = me.options.offset;
12288 // 1 is added because we need the length but we have the indexes
12289 var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - (offset ? 0 : 1)), 1);
12290
12291 // If value is a data object, then index is the index in the data array,
12292 // not the index of the scale. We need to change that.
12293 var valueCategory;
12294 if (value !== undefined && value !== null) {
12295 valueCategory = me.isHorizontal() ? value.x : value.y;
12296 }
12297 if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
12298 var labels = me.getLabels();
12299 value = valueCategory || value;
12300 var idx = labels.indexOf(value);
12301 index = idx !== -1 ? idx : index;
12302 }
12303
12304 if (me.isHorizontal()) {
12305 var valueWidth = me.width / offsetAmt;
12306 var widthOffset = (valueWidth * (index - me.minIndex));
12307
12308 if (offset) {
12309 widthOffset += (valueWidth / 2);
12310 }
12311
12312 return me.left + Math.round(widthOffset);
12313 }
12314 var valueHeight = me.height / offsetAmt;
12315 var heightOffset = (valueHeight * (index - me.minIndex));
12316
12317 if (offset) {
12318 heightOffset += (valueHeight / 2);
12319 }
12320
12321 return me.top + Math.round(heightOffset);
12322 },
12323 getPixelForTick: function(index) {
12324 return this.getPixelForValue(this.ticks[index], index + this.minIndex, null);
12325 },
12326 getValueForPixel: function(pixel) {
12327 var me = this;
12328 var offset = me.options.offset;
12329 var value;
12330 var offsetAmt = Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
12331 var horz = me.isHorizontal();
12332 var valueDimension = (horz ? me.width : me.height) / offsetAmt;
12333
12334 pixel -= horz ? me.left : me.top;
12335
12336 if (offset) {
12337 pixel -= (valueDimension / 2);
12338 }
12339
12340 if (pixel <= 0) {
12341 value = 0;
12342 } else {
12343 value = Math.round(pixel / valueDimension);
12344 }
12345
12346 return value + me.minIndex;
12347 },
12348 getBasePixel: function() {
12349 return this.bottom;
12350 }
12351 });
12352
12353 scaleService.registerScaleType('category', DatasetScale, defaultConfig);
12354};
12355
12356},{"33":33,"34":34}],55:[function(require,module,exports){
12357'use strict';
12358
12359var defaults = require(26);
12360var helpers = require(46);
12361var scaleService = require(34);
12362var Ticks = require(35);
12363
12364module.exports = function(Chart) {
12365
12366 var defaultConfig = {
12367 position: 'left',
12368 ticks: {
12369 callback: Ticks.formatters.linear
12370 }
12371 };
12372
12373 var LinearScale = Chart.LinearScaleBase.extend({
12374
12375 determineDataLimits: function() {
12376 var me = this;
12377 var opts = me.options;
12378 var chart = me.chart;
12379 var data = chart.data;
12380 var datasets = data.datasets;
12381 var isHorizontal = me.isHorizontal();
12382 var DEFAULT_MIN = 0;
12383 var DEFAULT_MAX = 1;
12384
12385 function IDMatches(meta) {
12386 return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
12387 }
12388
12389 // First Calculate the range
12390 me.min = null;
12391 me.max = null;
12392
12393 var hasStacks = opts.stacked;
12394 if (hasStacks === undefined) {
12395 helpers.each(datasets, function(dataset, datasetIndex) {
12396 if (hasStacks) {
12397 return;
12398 }
12399
12400 var meta = chart.getDatasetMeta(datasetIndex);
12401 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
12402 meta.stack !== undefined) {
12403 hasStacks = true;
12404 }
12405 });
12406 }
12407
12408 if (opts.stacked || hasStacks) {
12409 var valuesPerStack = {};
12410
12411 helpers.each(datasets, function(dataset, datasetIndex) {
12412 var meta = chart.getDatasetMeta(datasetIndex);
12413 var key = [
12414 meta.type,
12415 // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
12416 ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
12417 meta.stack
12418 ].join('.');
12419
12420 if (valuesPerStack[key] === undefined) {
12421 valuesPerStack[key] = {
12422 positiveValues: [],
12423 negativeValues: []
12424 };
12425 }
12426
12427 // Store these per type
12428 var positiveValues = valuesPerStack[key].positiveValues;
12429 var negativeValues = valuesPerStack[key].negativeValues;
12430
12431 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
12432 helpers.each(dataset.data, function(rawValue, index) {
12433 var value = +me.getRightValue(rawValue);
12434 if (isNaN(value) || meta.data[index].hidden) {
12435 return;
12436 }
12437
12438 positiveValues[index] = positiveValues[index] || 0;
12439 negativeValues[index] = negativeValues[index] || 0;
12440
12441 if (opts.relativePoints) {
12442 positiveValues[index] = 100;
12443 } else if (value < 0) {
12444 negativeValues[index] += value;
12445 } else {
12446 positiveValues[index] += value;
12447 }
12448 });
12449 }
12450 });
12451
12452 helpers.each(valuesPerStack, function(valuesForType) {
12453 var values = valuesForType.positiveValues.concat(valuesForType.negativeValues);
12454 var minVal = helpers.min(values);
12455 var maxVal = helpers.max(values);
12456 me.min = me.min === null ? minVal : Math.min(me.min, minVal);
12457 me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
12458 });
12459
12460 } else {
12461 helpers.each(datasets, function(dataset, datasetIndex) {
12462 var meta = chart.getDatasetMeta(datasetIndex);
12463 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
12464 helpers.each(dataset.data, function(rawValue, index) {
12465 var value = +me.getRightValue(rawValue);
12466 if (isNaN(value) || meta.data[index].hidden) {
12467 return;
12468 }
12469
12470 if (me.min === null) {
12471 me.min = value;
12472 } else if (value < me.min) {
12473 me.min = value;
12474 }
12475
12476 if (me.max === null) {
12477 me.max = value;
12478 } else if (value > me.max) {
12479 me.max = value;
12480 }
12481 });
12482 }
12483 });
12484 }
12485
12486 me.min = isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
12487 me.max = isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
12488
12489 // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
12490 this.handleTickRangeOptions();
12491 },
12492 getTickLimit: function() {
12493 var maxTicks;
12494 var me = this;
12495 var tickOpts = me.options.ticks;
12496
12497 if (me.isHorizontal()) {
12498 maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.width / 50));
12499 } else {
12500 // The factor of 2 used to scale the font size has been experimentally determined.
12501 var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, defaults.global.defaultFontSize);
12502 maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.height / (2 * tickFontSize)));
12503 }
12504
12505 return maxTicks;
12506 },
12507 // Called after the ticks are built. We need
12508 handleDirectionalChanges: function() {
12509 if (!this.isHorizontal()) {
12510 // We are in a vertical orientation. The top value is the highest. So reverse the array
12511 this.ticks.reverse();
12512 }
12513 },
12514 getLabelForIndex: function(index, datasetIndex) {
12515 return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
12516 },
12517 // Utils
12518 getPixelForValue: function(value) {
12519 // This must be called after fit has been run so that
12520 // this.left, this.top, this.right, and this.bottom have been defined
12521 var me = this;
12522 var start = me.start;
12523
12524 var rightValue = +me.getRightValue(value);
12525 var pixel;
12526 var range = me.end - start;
12527
12528 if (me.isHorizontal()) {
12529 pixel = me.left + (me.width / range * (rightValue - start));
12530 } else {
12531 pixel = me.bottom - (me.height / range * (rightValue - start));
12532 }
12533 return pixel;
12534 },
12535 getValueForPixel: function(pixel) {
12536 var me = this;
12537 var isHorizontal = me.isHorizontal();
12538 var innerDimension = isHorizontal ? me.width : me.height;
12539 var offset = (isHorizontal ? pixel - me.left : me.bottom - pixel) / innerDimension;
12540 return me.start + ((me.end - me.start) * offset);
12541 },
12542 getPixelForTick: function(index) {
12543 return this.getPixelForValue(this.ticksAsNumbers[index]);
12544 }
12545 });
12546
12547 scaleService.registerScaleType('linear', LinearScale, defaultConfig);
12548};
12549
12550},{"26":26,"34":34,"35":35,"46":46}],56:[function(require,module,exports){
12551'use strict';
12552
12553var helpers = require(46);
12554var Scale = require(33);
12555
12556/**
12557 * Generate a set of linear ticks
12558 * @param generationOptions the options used to generate the ticks
12559 * @param dataRange the range of the data
12560 * @returns {Array<Number>} array of tick values
12561 */
12562function generateTicks(generationOptions, dataRange) {
12563 var ticks = [];
12564 // To get a "nice" value for the tick spacing, we will use the appropriately named
12565 // "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
12566 // for details.
12567
12568 var factor;
12569 var precision;
12570 var spacing;
12571
12572 if (generationOptions.stepSize && generationOptions.stepSize > 0) {
12573 spacing = generationOptions.stepSize;
12574 } else {
12575 var niceRange = helpers.niceNum(dataRange.max - dataRange.min, false);
12576 spacing = helpers.niceNum(niceRange / (generationOptions.maxTicks - 1), true);
12577
12578 precision = generationOptions.precision;
12579 if (precision !== undefined) {
12580 // If the user specified a precision, round to that number of decimal places
12581 factor = Math.pow(10, precision);
12582 spacing = Math.ceil(spacing * factor) / factor;
12583 }
12584 }
12585 var niceMin = Math.floor(dataRange.min / spacing) * spacing;
12586 var niceMax = Math.ceil(dataRange.max / spacing) * spacing;
12587
12588 // If min, max and stepSize is set and they make an evenly spaced scale use it.
12589 if (generationOptions.min && generationOptions.max && generationOptions.stepSize) {
12590 // If very close to our whole number, use it.
12591 if (helpers.almostWhole((generationOptions.max - generationOptions.min) / generationOptions.stepSize, spacing / 1000)) {
12592 niceMin = generationOptions.min;
12593 niceMax = generationOptions.max;
12594 }
12595 }
12596
12597 var numSpaces = (niceMax - niceMin) / spacing;
12598 // If very close to our rounded value, use it.
12599 if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
12600 numSpaces = Math.round(numSpaces);
12601 } else {
12602 numSpaces = Math.ceil(numSpaces);
12603 }
12604
12605 precision = 1;
12606 if (spacing < 1) {
12607 precision = Math.pow(10, spacing.toString().length - 2);
12608 niceMin = Math.round(niceMin * precision) / precision;
12609 niceMax = Math.round(niceMax * precision) / precision;
12610 }
12611 ticks.push(generationOptions.min !== undefined ? generationOptions.min : niceMin);
12612 for (var j = 1; j < numSpaces; ++j) {
12613 ticks.push(Math.round((niceMin + j * spacing) * precision) / precision);
12614 }
12615 ticks.push(generationOptions.max !== undefined ? generationOptions.max : niceMax);
12616
12617 return ticks;
12618}
12619
12620module.exports = function(Chart) {
12621
12622 var noop = helpers.noop;
12623
12624 Chart.LinearScaleBase = Scale.extend({
12625 getRightValue: function(value) {
12626 if (typeof value === 'string') {
12627 return +value;
12628 }
12629 return Scale.prototype.getRightValue.call(this, value);
12630 },
12631
12632 handleTickRangeOptions: function() {
12633 var me = this;
12634 var opts = me.options;
12635 var tickOpts = opts.ticks;
12636
12637 // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
12638 // do nothing since that would make the chart weird. If the user really wants a weird chart
12639 // axis, they can manually override it
12640 if (tickOpts.beginAtZero) {
12641 var minSign = helpers.sign(me.min);
12642 var maxSign = helpers.sign(me.max);
12643
12644 if (minSign < 0 && maxSign < 0) {
12645 // move the top up to 0
12646 me.max = 0;
12647 } else if (minSign > 0 && maxSign > 0) {
12648 // move the bottom down to 0
12649 me.min = 0;
12650 }
12651 }
12652
12653 var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
12654 var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
12655
12656 if (tickOpts.min !== undefined) {
12657 me.min = tickOpts.min;
12658 } else if (tickOpts.suggestedMin !== undefined) {
12659 if (me.min === null) {
12660 me.min = tickOpts.suggestedMin;
12661 } else {
12662 me.min = Math.min(me.min, tickOpts.suggestedMin);
12663 }
12664 }
12665
12666 if (tickOpts.max !== undefined) {
12667 me.max = tickOpts.max;
12668 } else if (tickOpts.suggestedMax !== undefined) {
12669 if (me.max === null) {
12670 me.max = tickOpts.suggestedMax;
12671 } else {
12672 me.max = Math.max(me.max, tickOpts.suggestedMax);
12673 }
12674 }
12675
12676 if (setMin !== setMax) {
12677 // We set the min or the max but not both.
12678 // So ensure that our range is good
12679 // Inverted or 0 length range can happen when
12680 // ticks.min is set, and no datasets are visible
12681 if (me.min >= me.max) {
12682 if (setMin) {
12683 me.max = me.min + 1;
12684 } else {
12685 me.min = me.max - 1;
12686 }
12687 }
12688 }
12689
12690 if (me.min === me.max) {
12691 me.max++;
12692
12693 if (!tickOpts.beginAtZero) {
12694 me.min--;
12695 }
12696 }
12697 },
12698 getTickLimit: noop,
12699 handleDirectionalChanges: noop,
12700
12701 buildTicks: function() {
12702 var me = this;
12703 var opts = me.options;
12704 var tickOpts = opts.ticks;
12705
12706 // Figure out what the max number of ticks we can support it is based on the size of
12707 // the axis area. For now, we say that the minimum tick spacing in pixels must be 50
12708 // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
12709 // the graph. Make sure we always have at least 2 ticks
12710 var maxTicks = me.getTickLimit();
12711 maxTicks = Math.max(2, maxTicks);
12712
12713 var numericGeneratorOptions = {
12714 maxTicks: maxTicks,
12715 min: tickOpts.min,
12716 max: tickOpts.max,
12717 precision: tickOpts.precision,
12718 stepSize: helpers.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
12719 };
12720 var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
12721
12722 me.handleDirectionalChanges();
12723
12724 // At this point, we need to update our max and min given the tick values since we have expanded the
12725 // range of the scale
12726 me.max = helpers.max(ticks);
12727 me.min = helpers.min(ticks);
12728
12729 if (tickOpts.reverse) {
12730 ticks.reverse();
12731
12732 me.start = me.max;
12733 me.end = me.min;
12734 } else {
12735 me.start = me.min;
12736 me.end = me.max;
12737 }
12738 },
12739 convertTicksToLabels: function() {
12740 var me = this;
12741 me.ticksAsNumbers = me.ticks.slice();
12742 me.zeroLineIndex = me.ticks.indexOf(0);
12743
12744 Scale.prototype.convertTicksToLabels.call(me);
12745 }
12746 });
12747};
12748
12749},{"33":33,"46":46}],57:[function(require,module,exports){
12750'use strict';
12751
12752var helpers = require(46);
12753var Scale = require(33);
12754var scaleService = require(34);
12755var Ticks = require(35);
12756
12757/**
12758 * Generate a set of logarithmic ticks
12759 * @param generationOptions the options used to generate the ticks
12760 * @param dataRange the range of the data
12761 * @returns {Array<Number>} array of tick values
12762 */
12763function generateTicks(generationOptions, dataRange) {
12764 var ticks = [];
12765 var valueOrDefault = helpers.valueOrDefault;
12766
12767 // Figure out what the max number of ticks we can support it is based on the size of
12768 // the axis area. For now, we say that the minimum tick spacing in pixels must be 50
12769 // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
12770 // the graph
12771 var tickVal = valueOrDefault(generationOptions.min, Math.pow(10, Math.floor(helpers.log10(dataRange.min))));
12772
12773 var endExp = Math.floor(helpers.log10(dataRange.max));
12774 var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
12775 var exp, significand;
12776
12777 if (tickVal === 0) {
12778 exp = Math.floor(helpers.log10(dataRange.minNotZero));
12779 significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
12780
12781 ticks.push(tickVal);
12782 tickVal = significand * Math.pow(10, exp);
12783 } else {
12784 exp = Math.floor(helpers.log10(tickVal));
12785 significand = Math.floor(tickVal / Math.pow(10, exp));
12786 }
12787 var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
12788
12789 do {
12790 ticks.push(tickVal);
12791
12792 ++significand;
12793 if (significand === 10) {
12794 significand = 1;
12795 ++exp;
12796 precision = exp >= 0 ? 1 : precision;
12797 }
12798
12799 tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
12800 } while (exp < endExp || (exp === endExp && significand < endSignificand));
12801
12802 var lastTick = valueOrDefault(generationOptions.max, tickVal);
12803 ticks.push(lastTick);
12804
12805 return ticks;
12806}
12807
12808
12809module.exports = function(Chart) {
12810
12811 var defaultConfig = {
12812 position: 'left',
12813
12814 // label settings
12815 ticks: {
12816 callback: Ticks.formatters.logarithmic
12817 }
12818 };
12819
12820 var LogarithmicScale = Scale.extend({
12821 determineDataLimits: function() {
12822 var me = this;
12823 var opts = me.options;
12824 var chart = me.chart;
12825 var data = chart.data;
12826 var datasets = data.datasets;
12827 var isHorizontal = me.isHorizontal();
12828 function IDMatches(meta) {
12829 return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
12830 }
12831
12832 // Calculate Range
12833 me.min = null;
12834 me.max = null;
12835 me.minNotZero = null;
12836
12837 var hasStacks = opts.stacked;
12838 if (hasStacks === undefined) {
12839 helpers.each(datasets, function(dataset, datasetIndex) {
12840 if (hasStacks) {
12841 return;
12842 }
12843
12844 var meta = chart.getDatasetMeta(datasetIndex);
12845 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
12846 meta.stack !== undefined) {
12847 hasStacks = true;
12848 }
12849 });
12850 }
12851
12852 if (opts.stacked || hasStacks) {
12853 var valuesPerStack = {};
12854
12855 helpers.each(datasets, function(dataset, datasetIndex) {
12856 var meta = chart.getDatasetMeta(datasetIndex);
12857 var key = [
12858 meta.type,
12859 // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
12860 ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
12861 meta.stack
12862 ].join('.');
12863
12864 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
12865 if (valuesPerStack[key] === undefined) {
12866 valuesPerStack[key] = [];
12867 }
12868
12869 helpers.each(dataset.data, function(rawValue, index) {
12870 var values = valuesPerStack[key];
12871 var value = +me.getRightValue(rawValue);
12872 // invalid, hidden and negative values are ignored
12873 if (isNaN(value) || meta.data[index].hidden || value < 0) {
12874 return;
12875 }
12876 values[index] = values[index] || 0;
12877 values[index] += value;
12878 });
12879 }
12880 });
12881
12882 helpers.each(valuesPerStack, function(valuesForType) {
12883 if (valuesForType.length > 0) {
12884 var minVal = helpers.min(valuesForType);
12885 var maxVal = helpers.max(valuesForType);
12886 me.min = me.min === null ? minVal : Math.min(me.min, minVal);
12887 me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
12888 }
12889 });
12890
12891 } else {
12892 helpers.each(datasets, function(dataset, datasetIndex) {
12893 var meta = chart.getDatasetMeta(datasetIndex);
12894 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
12895 helpers.each(dataset.data, function(rawValue, index) {
12896 var value = +me.getRightValue(rawValue);
12897 // invalid, hidden and negative values are ignored
12898 if (isNaN(value) || meta.data[index].hidden || value < 0) {
12899 return;
12900 }
12901
12902 if (me.min === null) {
12903 me.min = value;
12904 } else if (value < me.min) {
12905 me.min = value;
12906 }
12907
12908 if (me.max === null) {
12909 me.max = value;
12910 } else if (value > me.max) {
12911 me.max = value;
12912 }
12913
12914 if (value !== 0 && (me.minNotZero === null || value < me.minNotZero)) {
12915 me.minNotZero = value;
12916 }
12917 });
12918 }
12919 });
12920 }
12921
12922 // Common base implementation to handle ticks.min, ticks.max
12923 this.handleTickRangeOptions();
12924 },
12925 handleTickRangeOptions: function() {
12926 var me = this;
12927 var opts = me.options;
12928 var tickOpts = opts.ticks;
12929 var valueOrDefault = helpers.valueOrDefault;
12930 var DEFAULT_MIN = 1;
12931 var DEFAULT_MAX = 10;
12932
12933 me.min = valueOrDefault(tickOpts.min, me.min);
12934 me.max = valueOrDefault(tickOpts.max, me.max);
12935
12936 if (me.min === me.max) {
12937 if (me.min !== 0 && me.min !== null) {
12938 me.min = Math.pow(10, Math.floor(helpers.log10(me.min)) - 1);
12939 me.max = Math.pow(10, Math.floor(helpers.log10(me.max)) + 1);
12940 } else {
12941 me.min = DEFAULT_MIN;
12942 me.max = DEFAULT_MAX;
12943 }
12944 }
12945 if (me.min === null) {
12946 me.min = Math.pow(10, Math.floor(helpers.log10(me.max)) - 1);
12947 }
12948 if (me.max === null) {
12949 me.max = me.min !== 0
12950 ? Math.pow(10, Math.floor(helpers.log10(me.min)) + 1)
12951 : DEFAULT_MAX;
12952 }
12953 if (me.minNotZero === null) {
12954 if (me.min > 0) {
12955 me.minNotZero = me.min;
12956 } else if (me.max < 1) {
12957 me.minNotZero = Math.pow(10, Math.floor(helpers.log10(me.max)));
12958 } else {
12959 me.minNotZero = DEFAULT_MIN;
12960 }
12961 }
12962 },
12963 buildTicks: function() {
12964 var me = this;
12965 var opts = me.options;
12966 var tickOpts = opts.ticks;
12967 var reverse = !me.isHorizontal();
12968
12969 var generationOptions = {
12970 min: tickOpts.min,
12971 max: tickOpts.max
12972 };
12973 var ticks = me.ticks = generateTicks(generationOptions, me);
12974
12975 // At this point, we need to update our max and min given the tick values since we have expanded the
12976 // range of the scale
12977 me.max = helpers.max(ticks);
12978 me.min = helpers.min(ticks);
12979
12980 if (tickOpts.reverse) {
12981 reverse = !reverse;
12982 me.start = me.max;
12983 me.end = me.min;
12984 } else {
12985 me.start = me.min;
12986 me.end = me.max;
12987 }
12988 if (reverse) {
12989 ticks.reverse();
12990 }
12991 },
12992 convertTicksToLabels: function() {
12993 this.tickValues = this.ticks.slice();
12994
12995 Scale.prototype.convertTicksToLabels.call(this);
12996 },
12997 // Get the correct tooltip label
12998 getLabelForIndex: function(index, datasetIndex) {
12999 return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
13000 },
13001 getPixelForTick: function(index) {
13002 return this.getPixelForValue(this.tickValues[index]);
13003 },
13004 /**
13005 * Returns the value of the first tick.
13006 * @param {Number} value - The minimum not zero value.
13007 * @return {Number} The first tick value.
13008 * @private
13009 */
13010 _getFirstTickValue: function(value) {
13011 var exp = Math.floor(helpers.log10(value));
13012 var significand = Math.floor(value / Math.pow(10, exp));
13013
13014 return significand * Math.pow(10, exp);
13015 },
13016 getPixelForValue: function(value) {
13017 var me = this;
13018 var reverse = me.options.ticks.reverse;
13019 var log10 = helpers.log10;
13020 var firstTickValue = me._getFirstTickValue(me.minNotZero);
13021 var offset = 0;
13022 var innerDimension, pixel, start, end, sign;
13023
13024 value = +me.getRightValue(value);
13025 if (reverse) {
13026 start = me.end;
13027 end = me.start;
13028 sign = -1;
13029 } else {
13030 start = me.start;
13031 end = me.end;
13032 sign = 1;
13033 }
13034 if (me.isHorizontal()) {
13035 innerDimension = me.width;
13036 pixel = reverse ? me.right : me.left;
13037 } else {
13038 innerDimension = me.height;
13039 sign *= -1; // invert, since the upper-left corner of the canvas is at pixel (0, 0)
13040 pixel = reverse ? me.top : me.bottom;
13041 }
13042 if (value !== start) {
13043 if (start === 0) { // include zero tick
13044 offset = helpers.getValueOrDefault(
13045 me.options.ticks.fontSize,
13046 Chart.defaults.global.defaultFontSize
13047 );
13048 innerDimension -= offset;
13049 start = firstTickValue;
13050 }
13051 if (value !== 0) {
13052 offset += innerDimension / (log10(end) - log10(start)) * (log10(value) - log10(start));
13053 }
13054 pixel += sign * offset;
13055 }
13056 return pixel;
13057 },
13058 getValueForPixel: function(pixel) {
13059 var me = this;
13060 var reverse = me.options.ticks.reverse;
13061 var log10 = helpers.log10;
13062 var firstTickValue = me._getFirstTickValue(me.minNotZero);
13063 var innerDimension, start, end, value;
13064
13065 if (reverse) {
13066 start = me.end;
13067 end = me.start;
13068 } else {
13069 start = me.start;
13070 end = me.end;
13071 }
13072 if (me.isHorizontal()) {
13073 innerDimension = me.width;
13074 value = reverse ? me.right - pixel : pixel - me.left;
13075 } else {
13076 innerDimension = me.height;
13077 value = reverse ? pixel - me.top : me.bottom - pixel;
13078 }
13079 if (value !== start) {
13080 if (start === 0) { // include zero tick
13081 var offset = helpers.getValueOrDefault(
13082 me.options.ticks.fontSize,
13083 Chart.defaults.global.defaultFontSize
13084 );
13085 value -= offset;
13086 innerDimension -= offset;
13087 start = firstTickValue;
13088 }
13089 value *= log10(end) - log10(start);
13090 value /= innerDimension;
13091 value = Math.pow(10, log10(start) + value);
13092 }
13093 return value;
13094 }
13095 });
13096
13097 scaleService.registerScaleType('logarithmic', LogarithmicScale, defaultConfig);
13098};
13099
13100},{"33":33,"34":34,"35":35,"46":46}],58:[function(require,module,exports){
13101'use strict';
13102
13103var defaults = require(26);
13104var helpers = require(46);
13105var scaleService = require(34);
13106var Ticks = require(35);
13107
13108module.exports = function(Chart) {
13109
13110 var globalDefaults = defaults.global;
13111
13112 var defaultConfig = {
13113 display: true,
13114
13115 // Boolean - Whether to animate scaling the chart from the centre
13116 animate: true,
13117 position: 'chartArea',
13118
13119 angleLines: {
13120 display: true,
13121 color: 'rgba(0, 0, 0, 0.1)',
13122 lineWidth: 1
13123 },
13124
13125 gridLines: {
13126 circular: false
13127 },
13128
13129 // label settings
13130 ticks: {
13131 // Boolean - Show a backdrop to the scale label
13132 showLabelBackdrop: true,
13133
13134 // String - The colour of the label backdrop
13135 backdropColor: 'rgba(255,255,255,0.75)',
13136
13137 // Number - The backdrop padding above & below the label in pixels
13138 backdropPaddingY: 2,
13139
13140 // Number - The backdrop padding to the side of the label in pixels
13141 backdropPaddingX: 2,
13142
13143 callback: Ticks.formatters.linear
13144 },
13145
13146 pointLabels: {
13147 // Boolean - if true, show point labels
13148 display: true,
13149
13150 // Number - Point label font size in pixels
13151 fontSize: 10,
13152
13153 // Function - Used to convert point labels
13154 callback: function(label) {
13155 return label;
13156 }
13157 }
13158 };
13159
13160 function getValueCount(scale) {
13161 var opts = scale.options;
13162 return opts.angleLines.display || opts.pointLabels.display ? scale.chart.data.labels.length : 0;
13163 }
13164
13165 function getPointLabelFontOptions(scale) {
13166 var pointLabelOptions = scale.options.pointLabels;
13167 var fontSize = helpers.valueOrDefault(pointLabelOptions.fontSize, globalDefaults.defaultFontSize);
13168 var fontStyle = helpers.valueOrDefault(pointLabelOptions.fontStyle, globalDefaults.defaultFontStyle);
13169 var fontFamily = helpers.valueOrDefault(pointLabelOptions.fontFamily, globalDefaults.defaultFontFamily);
13170 var font = helpers.fontString(fontSize, fontStyle, fontFamily);
13171
13172 return {
13173 size: fontSize,
13174 style: fontStyle,
13175 family: fontFamily,
13176 font: font
13177 };
13178 }
13179
13180 function measureLabelSize(ctx, fontSize, label) {
13181 if (helpers.isArray(label)) {
13182 return {
13183 w: helpers.longestText(ctx, ctx.font, label),
13184 h: (label.length * fontSize) + ((label.length - 1) * 1.5 * fontSize)
13185 };
13186 }
13187
13188 return {
13189 w: ctx.measureText(label).width,
13190 h: fontSize
13191 };
13192 }
13193
13194 function determineLimits(angle, pos, size, min, max) {
13195 if (angle === min || angle === max) {
13196 return {
13197 start: pos - (size / 2),
13198 end: pos + (size / 2)
13199 };
13200 } else if (angle < min || angle > max) {
13201 return {
13202 start: pos - size - 5,
13203 end: pos
13204 };
13205 }
13206
13207 return {
13208 start: pos,
13209 end: pos + size + 5
13210 };
13211 }
13212
13213 /**
13214 * Helper function to fit a radial linear scale with point labels
13215 */
13216 function fitWithPointLabels(scale) {
13217 /*
13218 * Right, this is really confusing and there is a lot of maths going on here
13219 * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
13220 *
13221 * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
13222 *
13223 * Solution:
13224 *
13225 * We assume the radius of the polygon is half the size of the canvas at first
13226 * at each index we check if the text overlaps.
13227 *
13228 * Where it does, we store that angle and that index.
13229 *
13230 * After finding the largest index and angle we calculate how much we need to remove
13231 * from the shape radius to move the point inwards by that x.
13232 *
13233 * We average the left and right distances to get the maximum shape radius that can fit in the box
13234 * along with labels.
13235 *
13236 * Once we have that, we can find the centre point for the chart, by taking the x text protrusion
13237 * on each side, removing that from the size, halving it and adding the left x protrusion width.
13238 *
13239 * This will mean we have a shape fitted to the canvas, as large as it can be with the labels
13240 * and position it in the most space efficient manner
13241 *
13242 * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
13243 */
13244
13245 var plFont = getPointLabelFontOptions(scale);
13246
13247 // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
13248 // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
13249 var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2);
13250 var furthestLimits = {
13251 r: scale.width,
13252 l: 0,
13253 t: scale.height,
13254 b: 0
13255 };
13256 var furthestAngles = {};
13257 var i, textSize, pointPosition;
13258
13259 scale.ctx.font = plFont.font;
13260 scale._pointLabelSizes = [];
13261
13262 var valueCount = getValueCount(scale);
13263 for (i = 0; i < valueCount; i++) {
13264 pointPosition = scale.getPointPosition(i, largestPossibleRadius);
13265 textSize = measureLabelSize(scale.ctx, plFont.size, scale.pointLabels[i] || '');
13266 scale._pointLabelSizes[i] = textSize;
13267
13268 // Add quarter circle to make degree 0 mean top of circle
13269 var angleRadians = scale.getIndexAngle(i);
13270 var angle = helpers.toDegrees(angleRadians) % 360;
13271 var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
13272 var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
13273
13274 if (hLimits.start < furthestLimits.l) {
13275 furthestLimits.l = hLimits.start;
13276 furthestAngles.l = angleRadians;
13277 }
13278
13279 if (hLimits.end > furthestLimits.r) {
13280 furthestLimits.r = hLimits.end;
13281 furthestAngles.r = angleRadians;
13282 }
13283
13284 if (vLimits.start < furthestLimits.t) {
13285 furthestLimits.t = vLimits.start;
13286 furthestAngles.t = angleRadians;
13287 }
13288
13289 if (vLimits.end > furthestLimits.b) {
13290 furthestLimits.b = vLimits.end;
13291 furthestAngles.b = angleRadians;
13292 }
13293 }
13294
13295 scale.setReductions(largestPossibleRadius, furthestLimits, furthestAngles);
13296 }
13297
13298 /**
13299 * Helper function to fit a radial linear scale with no point labels
13300 */
13301 function fit(scale) {
13302 var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2);
13303 scale.drawingArea = Math.round(largestPossibleRadius);
13304 scale.setCenterPoint(0, 0, 0, 0);
13305 }
13306
13307 function getTextAlignForAngle(angle) {
13308 if (angle === 0 || angle === 180) {
13309 return 'center';
13310 } else if (angle < 180) {
13311 return 'left';
13312 }
13313
13314 return 'right';
13315 }
13316
13317 function fillText(ctx, text, position, fontSize) {
13318 if (helpers.isArray(text)) {
13319 var y = position.y;
13320 var spacing = 1.5 * fontSize;
13321
13322 for (var i = 0; i < text.length; ++i) {
13323 ctx.fillText(text[i], position.x, y);
13324 y += spacing;
13325 }
13326 } else {
13327 ctx.fillText(text, position.x, position.y);
13328 }
13329 }
13330
13331 function adjustPointPositionForLabelHeight(angle, textSize, position) {
13332 if (angle === 90 || angle === 270) {
13333 position.y -= (textSize.h / 2);
13334 } else if (angle > 270 || angle < 90) {
13335 position.y -= textSize.h;
13336 }
13337 }
13338
13339 function drawPointLabels(scale) {
13340 var ctx = scale.ctx;
13341 var opts = scale.options;
13342 var angleLineOpts = opts.angleLines;
13343 var pointLabelOpts = opts.pointLabels;
13344
13345 ctx.lineWidth = angleLineOpts.lineWidth;
13346 ctx.strokeStyle = angleLineOpts.color;
13347
13348 var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
13349
13350 // Point Label Font
13351 var plFont = getPointLabelFontOptions(scale);
13352
13353 ctx.textBaseline = 'top';
13354
13355 for (var i = getValueCount(scale) - 1; i >= 0; i--) {
13356 if (angleLineOpts.display) {
13357 var outerPosition = scale.getPointPosition(i, outerDistance);
13358 ctx.beginPath();
13359 ctx.moveTo(scale.xCenter, scale.yCenter);
13360 ctx.lineTo(outerPosition.x, outerPosition.y);
13361 ctx.stroke();
13362 ctx.closePath();
13363 }
13364
13365 if (pointLabelOpts.display) {
13366 // Extra 3px out for some label spacing
13367 var pointLabelPosition = scale.getPointPosition(i, outerDistance + 5);
13368
13369 // Keep this in loop since we may support array properties here
13370 var pointLabelFontColor = helpers.valueAtIndexOrDefault(pointLabelOpts.fontColor, i, globalDefaults.defaultFontColor);
13371 ctx.font = plFont.font;
13372 ctx.fillStyle = pointLabelFontColor;
13373
13374 var angleRadians = scale.getIndexAngle(i);
13375 var angle = helpers.toDegrees(angleRadians);
13376 ctx.textAlign = getTextAlignForAngle(angle);
13377 adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
13378 fillText(ctx, scale.pointLabels[i] || '', pointLabelPosition, plFont.size);
13379 }
13380 }
13381 }
13382
13383 function drawRadiusLine(scale, gridLineOpts, radius, index) {
13384 var ctx = scale.ctx;
13385 ctx.strokeStyle = helpers.valueAtIndexOrDefault(gridLineOpts.color, index - 1);
13386 ctx.lineWidth = helpers.valueAtIndexOrDefault(gridLineOpts.lineWidth, index - 1);
13387
13388 if (scale.options.gridLines.circular) {
13389 // Draw circular arcs between the points
13390 ctx.beginPath();
13391 ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
13392 ctx.closePath();
13393 ctx.stroke();
13394 } else {
13395 // Draw straight lines connecting each index
13396 var valueCount = getValueCount(scale);
13397
13398 if (valueCount === 0) {
13399 return;
13400 }
13401
13402 ctx.beginPath();
13403 var pointPosition = scale.getPointPosition(0, radius);
13404 ctx.moveTo(pointPosition.x, pointPosition.y);
13405
13406 for (var i = 1; i < valueCount; i++) {
13407 pointPosition = scale.getPointPosition(i, radius);
13408 ctx.lineTo(pointPosition.x, pointPosition.y);
13409 }
13410
13411 ctx.closePath();
13412 ctx.stroke();
13413 }
13414 }
13415
13416 function numberOrZero(param) {
13417 return helpers.isNumber(param) ? param : 0;
13418 }
13419
13420 var LinearRadialScale = Chart.LinearScaleBase.extend({
13421 setDimensions: function() {
13422 var me = this;
13423 var opts = me.options;
13424 var tickOpts = opts.ticks;
13425 // Set the unconstrained dimension before label rotation
13426 me.width = me.maxWidth;
13427 me.height = me.maxHeight;
13428 me.xCenter = Math.round(me.width / 2);
13429 me.yCenter = Math.round(me.height / 2);
13430
13431 var minSize = helpers.min([me.height, me.width]);
13432 var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
13433 me.drawingArea = opts.display ? (minSize / 2) - (tickFontSize / 2 + tickOpts.backdropPaddingY) : (minSize / 2);
13434 },
13435 determineDataLimits: function() {
13436 var me = this;
13437 var chart = me.chart;
13438 var min = Number.POSITIVE_INFINITY;
13439 var max = Number.NEGATIVE_INFINITY;
13440
13441 helpers.each(chart.data.datasets, function(dataset, datasetIndex) {
13442 if (chart.isDatasetVisible(datasetIndex)) {
13443 var meta = chart.getDatasetMeta(datasetIndex);
13444
13445 helpers.each(dataset.data, function(rawValue, index) {
13446 var value = +me.getRightValue(rawValue);
13447 if (isNaN(value) || meta.data[index].hidden) {
13448 return;
13449 }
13450
13451 min = Math.min(value, min);
13452 max = Math.max(value, max);
13453 });
13454 }
13455 });
13456
13457 me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
13458 me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
13459
13460 // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
13461 me.handleTickRangeOptions();
13462 },
13463 getTickLimit: function() {
13464 var tickOpts = this.options.ticks;
13465 var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
13466 return Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(this.drawingArea / (1.5 * tickFontSize)));
13467 },
13468 convertTicksToLabels: function() {
13469 var me = this;
13470
13471 Chart.LinearScaleBase.prototype.convertTicksToLabels.call(me);
13472
13473 // Point labels
13474 me.pointLabels = me.chart.data.labels.map(me.options.pointLabels.callback, me);
13475 },
13476 getLabelForIndex: function(index, datasetIndex) {
13477 return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
13478 },
13479 fit: function() {
13480 if (this.options.pointLabels.display) {
13481 fitWithPointLabels(this);
13482 } else {
13483 fit(this);
13484 }
13485 },
13486 /**
13487 * Set radius reductions and determine new radius and center point
13488 * @private
13489 */
13490 setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
13491 var me = this;
13492 var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
13493 var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
13494 var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
13495 var radiusReductionBottom = -Math.max(furthestLimits.b - me.height, 0) / Math.cos(furthestAngles.b);
13496
13497 radiusReductionLeft = numberOrZero(radiusReductionLeft);
13498 radiusReductionRight = numberOrZero(radiusReductionRight);
13499 radiusReductionTop = numberOrZero(radiusReductionTop);
13500 radiusReductionBottom = numberOrZero(radiusReductionBottom);
13501
13502 me.drawingArea = Math.min(
13503 Math.round(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
13504 Math.round(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
13505 me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
13506 },
13507 setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
13508 var me = this;
13509 var maxRight = me.width - rightMovement - me.drawingArea;
13510 var maxLeft = leftMovement + me.drawingArea;
13511 var maxTop = topMovement + me.drawingArea;
13512 var maxBottom = me.height - bottomMovement - me.drawingArea;
13513
13514 me.xCenter = Math.round(((maxLeft + maxRight) / 2) + me.left);
13515 me.yCenter = Math.round(((maxTop + maxBottom) / 2) + me.top);
13516 },
13517
13518 getIndexAngle: function(index) {
13519 var angleMultiplier = (Math.PI * 2) / getValueCount(this);
13520 var startAngle = this.chart.options && this.chart.options.startAngle ?
13521 this.chart.options.startAngle :
13522 0;
13523
13524 var startAngleRadians = startAngle * Math.PI * 2 / 360;
13525
13526 // Start from the top instead of right, so remove a quarter of the circle
13527 return index * angleMultiplier + startAngleRadians;
13528 },
13529 getDistanceFromCenterForValue: function(value) {
13530 var me = this;
13531
13532 if (value === null) {
13533 return 0; // null always in center
13534 }
13535
13536 // Take into account half font size + the yPadding of the top value
13537 var scalingFactor = me.drawingArea / (me.max - me.min);
13538 if (me.options.ticks.reverse) {
13539 return (me.max - value) * scalingFactor;
13540 }
13541 return (value - me.min) * scalingFactor;
13542 },
13543 getPointPosition: function(index, distanceFromCenter) {
13544 var me = this;
13545 var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
13546 return {
13547 x: Math.round(Math.cos(thisAngle) * distanceFromCenter) + me.xCenter,
13548 y: Math.round(Math.sin(thisAngle) * distanceFromCenter) + me.yCenter
13549 };
13550 },
13551 getPointPositionForValue: function(index, value) {
13552 return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
13553 },
13554
13555 getBasePosition: function() {
13556 var me = this;
13557 var min = me.min;
13558 var max = me.max;
13559
13560 return me.getPointPositionForValue(0,
13561 me.beginAtZero ? 0 :
13562 min < 0 && max < 0 ? max :
13563 min > 0 && max > 0 ? min :
13564 0);
13565 },
13566
13567 draw: function() {
13568 var me = this;
13569 var opts = me.options;
13570 var gridLineOpts = opts.gridLines;
13571 var tickOpts = opts.ticks;
13572 var valueOrDefault = helpers.valueOrDefault;
13573
13574 if (opts.display) {
13575 var ctx = me.ctx;
13576 var startAngle = this.getIndexAngle(0);
13577
13578 // Tick Font
13579 var tickFontSize = valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
13580 var tickFontStyle = valueOrDefault(tickOpts.fontStyle, globalDefaults.defaultFontStyle);
13581 var tickFontFamily = valueOrDefault(tickOpts.fontFamily, globalDefaults.defaultFontFamily);
13582 var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
13583
13584 helpers.each(me.ticks, function(label, index) {
13585 // Don't draw a centre value (if it is minimum)
13586 if (index > 0 || tickOpts.reverse) {
13587 var yCenterOffset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
13588
13589 // Draw circular lines around the scale
13590 if (gridLineOpts.display && index !== 0) {
13591 drawRadiusLine(me, gridLineOpts, yCenterOffset, index);
13592 }
13593
13594 if (tickOpts.display) {
13595 var tickFontColor = valueOrDefault(tickOpts.fontColor, globalDefaults.defaultFontColor);
13596 ctx.font = tickLabelFont;
13597
13598 ctx.save();
13599 ctx.translate(me.xCenter, me.yCenter);
13600 ctx.rotate(startAngle);
13601
13602 if (tickOpts.showLabelBackdrop) {
13603 var labelWidth = ctx.measureText(label).width;
13604 ctx.fillStyle = tickOpts.backdropColor;
13605 ctx.fillRect(
13606 -labelWidth / 2 - tickOpts.backdropPaddingX,
13607 -yCenterOffset - tickFontSize / 2 - tickOpts.backdropPaddingY,
13608 labelWidth + tickOpts.backdropPaddingX * 2,
13609 tickFontSize + tickOpts.backdropPaddingY * 2
13610 );
13611 }
13612
13613 ctx.textAlign = 'center';
13614 ctx.textBaseline = 'middle';
13615 ctx.fillStyle = tickFontColor;
13616 ctx.fillText(label, 0, -yCenterOffset);
13617 ctx.restore();
13618 }
13619 }
13620 });
13621
13622 if (opts.angleLines.display || opts.pointLabels.display) {
13623 drawPointLabels(me);
13624 }
13625 }
13626 }
13627 });
13628
13629 scaleService.registerScaleType('radialLinear', LinearRadialScale, defaultConfig);
13630};
13631
13632},{"26":26,"34":34,"35":35,"46":46}],59:[function(require,module,exports){
13633/* global window: false */
13634'use strict';
13635
13636var moment = require(1);
13637moment = typeof moment === 'function' ? moment : window.moment;
13638
13639var defaults = require(26);
13640var helpers = require(46);
13641var Scale = require(33);
13642var scaleService = require(34);
13643
13644// Integer constants are from the ES6 spec.
13645var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
13646var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
13647
13648var INTERVALS = {
13649 millisecond: {
13650 common: true,
13651 size: 1,
13652 steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]
13653 },
13654 second: {
13655 common: true,
13656 size: 1000,
13657 steps: [1, 2, 5, 10, 30]
13658 },
13659 minute: {
13660 common: true,
13661 size: 60000,
13662 steps: [1, 2, 5, 10, 30]
13663 },
13664 hour: {
13665 common: true,
13666 size: 3600000,
13667 steps: [1, 2, 3, 6, 12]
13668 },
13669 day: {
13670 common: true,
13671 size: 86400000,
13672 steps: [1, 2, 5]
13673 },
13674 week: {
13675 common: false,
13676 size: 604800000,
13677 steps: [1, 2, 3, 4]
13678 },
13679 month: {
13680 common: true,
13681 size: 2.628e9,
13682 steps: [1, 2, 3]
13683 },
13684 quarter: {
13685 common: false,
13686 size: 7.884e9,
13687 steps: [1, 2, 3, 4]
13688 },
13689 year: {
13690 common: true,
13691 size: 3.154e10
13692 }
13693};
13694
13695var UNITS = Object.keys(INTERVALS);
13696
13697function sorter(a, b) {
13698 return a - b;
13699}
13700
13701function arrayUnique(items) {
13702 var hash = {};
13703 var out = [];
13704 var i, ilen, item;
13705
13706 for (i = 0, ilen = items.length; i < ilen; ++i) {
13707 item = items[i];
13708 if (!hash[item]) {
13709 hash[item] = true;
13710 out.push(item);
13711 }
13712 }
13713
13714 return out;
13715}
13716
13717/**
13718 * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
13719 * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
13720 * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
13721 * extremity (left + width or top + height). Note that it would be more optimized to directly
13722 * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
13723 * to create the lookup table. The table ALWAYS contains at least two items: min and max.
13724 *
13725 * @param {Number[]} timestamps - timestamps sorted from lowest to highest.
13726 * @param {String} distribution - If 'linear', timestamps will be spread linearly along the min
13727 * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
13728 * If 'series', timestamps will be positioned at the same distance from each other. In this
13729 * case, only timestamps that break the time linearity are registered, meaning that in the
13730 * best case, all timestamps are linear, the table contains only min and max.
13731 */
13732function buildLookupTable(timestamps, min, max, distribution) {
13733 if (distribution === 'linear' || !timestamps.length) {
13734 return [
13735 {time: min, pos: 0},
13736 {time: max, pos: 1}
13737 ];
13738 }
13739
13740 var table = [];
13741 var items = [min];
13742 var i, ilen, prev, curr, next;
13743
13744 for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
13745 curr = timestamps[i];
13746 if (curr > min && curr < max) {
13747 items.push(curr);
13748 }
13749 }
13750
13751 items.push(max);
13752
13753 for (i = 0, ilen = items.length; i < ilen; ++i) {
13754 next = items[i + 1];
13755 prev = items[i - 1];
13756 curr = items[i];
13757
13758 // only add points that breaks the scale linearity
13759 if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
13760 table.push({time: curr, pos: i / (ilen - 1)});
13761 }
13762 }
13763
13764 return table;
13765}
13766
13767// @see adapted from http://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
13768function lookup(table, key, value) {
13769 var lo = 0;
13770 var hi = table.length - 1;
13771 var mid, i0, i1;
13772
13773 while (lo >= 0 && lo <= hi) {
13774 mid = (lo + hi) >> 1;
13775 i0 = table[mid - 1] || null;
13776 i1 = table[mid];
13777
13778 if (!i0) {
13779 // given value is outside table (before first item)
13780 return {lo: null, hi: i1};
13781 } else if (i1[key] < value) {
13782 lo = mid + 1;
13783 } else if (i0[key] > value) {
13784 hi = mid - 1;
13785 } else {
13786 return {lo: i0, hi: i1};
13787 }
13788 }
13789
13790 // given value is outside table (after last item)
13791 return {lo: i1, hi: null};
13792}
13793
13794/**
13795 * Linearly interpolates the given source `value` using the table items `skey` values and
13796 * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
13797 * returns the position for a timestamp equal to 42. If value is out of bounds, values at
13798 * index [0, 1] or [n - 1, n] are used for the interpolation.
13799 */
13800function interpolate(table, skey, sval, tkey) {
13801 var range = lookup(table, skey, sval);
13802
13803 // Note: the lookup table ALWAYS contains at least 2 items (min and max)
13804 var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
13805 var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
13806
13807 var span = next[skey] - prev[skey];
13808 var ratio = span ? (sval - prev[skey]) / span : 0;
13809 var offset = (next[tkey] - prev[tkey]) * ratio;
13810
13811 return prev[tkey] + offset;
13812}
13813
13814/**
13815 * Convert the given value to a moment object using the given time options.
13816 * @see http://momentjs.com/docs/#/parsing/
13817 */
13818function momentify(value, options) {
13819 var parser = options.parser;
13820 var format = options.parser || options.format;
13821
13822 if (typeof parser === 'function') {
13823 return parser(value);
13824 }
13825
13826 if (typeof value === 'string' && typeof format === 'string') {
13827 return moment(value, format);
13828 }
13829
13830 if (!(value instanceof moment)) {
13831 value = moment(value);
13832 }
13833
13834 if (value.isValid()) {
13835 return value;
13836 }
13837
13838 // Labels are in an incompatible moment format and no `parser` has been provided.
13839 // The user might still use the deprecated `format` option to convert his inputs.
13840 if (typeof format === 'function') {
13841 return format(value);
13842 }
13843
13844 return value;
13845}
13846
13847function parse(input, scale) {
13848 if (helpers.isNullOrUndef(input)) {
13849 return null;
13850 }
13851
13852 var options = scale.options.time;
13853 var value = momentify(scale.getRightValue(input), options);
13854 if (!value.isValid()) {
13855 return null;
13856 }
13857
13858 if (options.round) {
13859 value.startOf(options.round);
13860 }
13861
13862 return value.valueOf();
13863}
13864
13865/**
13866 * Returns the number of unit to skip to be able to display up to `capacity` number of ticks
13867 * in `unit` for the given `min` / `max` range and respecting the interval steps constraints.
13868 */
13869function determineStepSize(min, max, unit, capacity) {
13870 var range = max - min;
13871 var interval = INTERVALS[unit];
13872 var milliseconds = interval.size;
13873 var steps = interval.steps;
13874 var i, ilen, factor;
13875
13876 if (!steps) {
13877 return Math.ceil(range / (capacity * milliseconds));
13878 }
13879
13880 for (i = 0, ilen = steps.length; i < ilen; ++i) {
13881 factor = steps[i];
13882 if (Math.ceil(range / (milliseconds * factor)) <= capacity) {
13883 break;
13884 }
13885 }
13886
13887 return factor;
13888}
13889
13890/**
13891 * Figures out what unit results in an appropriate number of auto-generated ticks
13892 */
13893function determineUnitForAutoTicks(minUnit, min, max, capacity) {
13894 var ilen = UNITS.length;
13895 var i, interval, factor;
13896
13897 for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
13898 interval = INTERVALS[UNITS[i]];
13899 factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER;
13900
13901 if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
13902 return UNITS[i];
13903 }
13904 }
13905
13906 return UNITS[ilen - 1];
13907}
13908
13909/**
13910 * Figures out what unit to format a set of ticks with
13911 */
13912function determineUnitForFormatting(ticks, minUnit, min, max) {
13913 var duration = moment.duration(moment(max).diff(moment(min)));
13914 var ilen = UNITS.length;
13915 var i, unit;
13916
13917 for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) {
13918 unit = UNITS[i];
13919 if (INTERVALS[unit].common && duration.as(unit) >= ticks.length) {
13920 return unit;
13921 }
13922 }
13923
13924 return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
13925}
13926
13927function determineMajorUnit(unit) {
13928 for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
13929 if (INTERVALS[UNITS[i]].common) {
13930 return UNITS[i];
13931 }
13932 }
13933}
13934
13935/**
13936 * Generates a maximum of `capacity` timestamps between min and max, rounded to the
13937 * `minor` unit, aligned on the `major` unit and using the given scale time `options`.
13938 * Important: this method can return ticks outside the min and max range, it's the
13939 * responsibility of the calling code to clamp values if needed.
13940 */
13941function generate(min, max, capacity, options) {
13942 var timeOpts = options.time;
13943 var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
13944 var major = determineMajorUnit(minor);
13945 var stepSize = helpers.valueOrDefault(timeOpts.stepSize, timeOpts.unitStepSize);
13946 var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
13947 var majorTicksEnabled = options.ticks.major.enabled;
13948 var interval = INTERVALS[minor];
13949 var first = moment(min);
13950 var last = moment(max);
13951 var ticks = [];
13952 var time;
13953
13954 if (!stepSize) {
13955 stepSize = determineStepSize(min, max, minor, capacity);
13956 }
13957
13958 // For 'week' unit, handle the first day of week option
13959 if (weekday) {
13960 first = first.isoWeekday(weekday);
13961 last = last.isoWeekday(weekday);
13962 }
13963
13964 // Align first/last ticks on unit
13965 first = first.startOf(weekday ? 'day' : minor);
13966 last = last.startOf(weekday ? 'day' : minor);
13967
13968 // Make sure that the last tick include max
13969 if (last < max) {
13970 last.add(1, minor);
13971 }
13972
13973 time = moment(first);
13974
13975 if (majorTicksEnabled && major && !weekday && !timeOpts.round) {
13976 // Align the first tick on the previous `minor` unit aligned on the `major` unit:
13977 // we first aligned time on the previous `major` unit then add the number of full
13978 // stepSize there is between first and the previous major time.
13979 time.startOf(major);
13980 time.add(~~((first - time) / (interval.size * stepSize)) * stepSize, minor);
13981 }
13982
13983 for (; time < last; time.add(stepSize, minor)) {
13984 ticks.push(+time);
13985 }
13986
13987 ticks.push(+time);
13988
13989 return ticks;
13990}
13991
13992/**
13993 * Returns the right and left offsets from edges in the form of {left, right}.
13994 * Offsets are added when the `offset` option is true.
13995 */
13996function computeOffsets(table, ticks, min, max, options) {
13997 var left = 0;
13998 var right = 0;
13999 var upper, lower;
14000
14001 if (options.offset && ticks.length) {
14002 if (!options.time.min) {
14003 upper = ticks.length > 1 ? ticks[1] : max;
14004 lower = ticks[0];
14005 left = (
14006 interpolate(table, 'time', upper, 'pos') -
14007 interpolate(table, 'time', lower, 'pos')
14008 ) / 2;
14009 }
14010 if (!options.time.max) {
14011 upper = ticks[ticks.length - 1];
14012 lower = ticks.length > 1 ? ticks[ticks.length - 2] : min;
14013 right = (
14014 interpolate(table, 'time', upper, 'pos') -
14015 interpolate(table, 'time', lower, 'pos')
14016 ) / 2;
14017 }
14018 }
14019
14020 return {left: left, right: right};
14021}
14022
14023function ticksFromTimestamps(values, majorUnit) {
14024 var ticks = [];
14025 var i, ilen, value, major;
14026
14027 for (i = 0, ilen = values.length; i < ilen; ++i) {
14028 value = values[i];
14029 major = majorUnit ? value === +moment(value).startOf(majorUnit) : false;
14030
14031 ticks.push({
14032 value: value,
14033 major: major
14034 });
14035 }
14036
14037 return ticks;
14038}
14039
14040function determineLabelFormat(data, timeOpts) {
14041 var i, momentDate, hasTime;
14042 var ilen = data.length;
14043
14044 // find the label with the most parts (milliseconds, minutes, etc.)
14045 // format all labels with the same level of detail as the most specific label
14046 for (i = 0; i < ilen; i++) {
14047 momentDate = momentify(data[i], timeOpts);
14048 if (momentDate.millisecond() !== 0) {
14049 return 'MMM D, YYYY h:mm:ss.SSS a';
14050 }
14051 if (momentDate.second() !== 0 || momentDate.minute() !== 0 || momentDate.hour() !== 0) {
14052 hasTime = true;
14053 }
14054 }
14055 if (hasTime) {
14056 return 'MMM D, YYYY h:mm:ss a';
14057 }
14058 return 'MMM D, YYYY';
14059}
14060
14061module.exports = function() {
14062
14063 var defaultConfig = {
14064 position: 'bottom',
14065
14066 /**
14067 * Data distribution along the scale:
14068 * - 'linear': data are spread according to their time (distances can vary),
14069 * - 'series': data are spread at the same distance from each other.
14070 * @see https://github.com/chartjs/Chart.js/pull/4507
14071 * @since 2.7.0
14072 */
14073 distribution: 'linear',
14074
14075 /**
14076 * Scale boundary strategy (bypassed by min/max time options)
14077 * - `data`: make sure data are fully visible, ticks outside are removed
14078 * - `ticks`: make sure ticks are fully visible, data outside are truncated
14079 * @see https://github.com/chartjs/Chart.js/pull/4556
14080 * @since 2.7.0
14081 */
14082 bounds: 'data',
14083
14084 time: {
14085 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
14086 format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from http://momentjs.com/docs/#/parsing/string-format/
14087 unit: false, // false == automatic or override with week, month, year, etc.
14088 round: false, // none, or override with week, month, year, etc.
14089 displayFormat: false, // DEPRECATED
14090 isoWeekday: false, // override week start day - see http://momentjs.com/docs/#/get-set/iso-weekday/
14091 minUnit: 'millisecond',
14092
14093 // defaults to unit's corresponding unitFormat below or override using pattern string from http://momentjs.com/docs/#/displaying/format/
14094 displayFormats: {
14095 millisecond: 'h:mm:ss.SSS a', // 11:20:01.123 AM,
14096 second: 'h:mm:ss a', // 11:20:01 AM
14097 minute: 'h:mm a', // 11:20 AM
14098 hour: 'hA', // 5PM
14099 day: 'MMM D', // Sep 4
14100 week: 'll', // Week 46, or maybe "[W]WW - YYYY" ?
14101 month: 'MMM YYYY', // Sept 2015
14102 quarter: '[Q]Q - YYYY', // Q3
14103 year: 'YYYY' // 2015
14104 },
14105 },
14106 ticks: {
14107 autoSkip: false,
14108
14109 /**
14110 * Ticks generation input values:
14111 * - 'auto': generates "optimal" ticks based on scale size and time options.
14112 * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
14113 * - 'labels': generates ticks from user given `data.labels` values ONLY.
14114 * @see https://github.com/chartjs/Chart.js/pull/4507
14115 * @since 2.7.0
14116 */
14117 source: 'auto',
14118
14119 major: {
14120 enabled: false
14121 }
14122 }
14123 };
14124
14125 var TimeScale = Scale.extend({
14126 initialize: function() {
14127 if (!moment) {
14128 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');
14129 }
14130
14131 this.mergeTicksOptions();
14132
14133 Scale.prototype.initialize.call(this);
14134 },
14135
14136 update: function() {
14137 var me = this;
14138 var options = me.options;
14139
14140 // DEPRECATIONS: output a message only one time per update
14141 if (options.time && options.time.format) {
14142 console.warn('options.time.format is deprecated and replaced by options.time.parser.');
14143 }
14144
14145 return Scale.prototype.update.apply(me, arguments);
14146 },
14147
14148 /**
14149 * Allows data to be referenced via 't' attribute
14150 */
14151 getRightValue: function(rawValue) {
14152 if (rawValue && rawValue.t !== undefined) {
14153 rawValue = rawValue.t;
14154 }
14155 return Scale.prototype.getRightValue.call(this, rawValue);
14156 },
14157
14158 determineDataLimits: function() {
14159 var me = this;
14160 var chart = me.chart;
14161 var timeOpts = me.options.time;
14162 var unit = timeOpts.unit || 'day';
14163 var min = MAX_INTEGER;
14164 var max = MIN_INTEGER;
14165 var timestamps = [];
14166 var datasets = [];
14167 var labels = [];
14168 var i, j, ilen, jlen, data, timestamp;
14169
14170 // Convert labels to timestamps
14171 for (i = 0, ilen = chart.data.labels.length; i < ilen; ++i) {
14172 labels.push(parse(chart.data.labels[i], me));
14173 }
14174
14175 // Convert data to timestamps
14176 for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
14177 if (chart.isDatasetVisible(i)) {
14178 data = chart.data.datasets[i].data;
14179
14180 // Let's consider that all data have the same format.
14181 if (helpers.isObject(data[0])) {
14182 datasets[i] = [];
14183
14184 for (j = 0, jlen = data.length; j < jlen; ++j) {
14185 timestamp = parse(data[j], me);
14186 timestamps.push(timestamp);
14187 datasets[i][j] = timestamp;
14188 }
14189 } else {
14190 timestamps.push.apply(timestamps, labels);
14191 datasets[i] = labels.slice(0);
14192 }
14193 } else {
14194 datasets[i] = [];
14195 }
14196 }
14197
14198 if (labels.length) {
14199 // Sort labels **after** data have been converted
14200 labels = arrayUnique(labels).sort(sorter);
14201 min = Math.min(min, labels[0]);
14202 max = Math.max(max, labels[labels.length - 1]);
14203 }
14204
14205 if (timestamps.length) {
14206 timestamps = arrayUnique(timestamps).sort(sorter);
14207 min = Math.min(min, timestamps[0]);
14208 max = Math.max(max, timestamps[timestamps.length - 1]);
14209 }
14210
14211 min = parse(timeOpts.min, me) || min;
14212 max = parse(timeOpts.max, me) || max;
14213
14214 // In case there is no valid min/max, set limits based on unit time option
14215 min = min === MAX_INTEGER ? +moment().startOf(unit) : min;
14216 max = max === MIN_INTEGER ? +moment().endOf(unit) + 1 : max;
14217
14218 // Make sure that max is strictly higher than min (required by the lookup table)
14219 me.min = Math.min(min, max);
14220 me.max = Math.max(min + 1, max);
14221
14222 // PRIVATE
14223 me._horizontal = me.isHorizontal();
14224 me._table = [];
14225 me._timestamps = {
14226 data: timestamps,
14227 datasets: datasets,
14228 labels: labels
14229 };
14230 },
14231
14232 buildTicks: function() {
14233 var me = this;
14234 var min = me.min;
14235 var max = me.max;
14236 var options = me.options;
14237 var timeOpts = options.time;
14238 var timestamps = [];
14239 var ticks = [];
14240 var i, ilen, timestamp;
14241
14242 switch (options.ticks.source) {
14243 case 'data':
14244 timestamps = me._timestamps.data;
14245 break;
14246 case 'labels':
14247 timestamps = me._timestamps.labels;
14248 break;
14249 case 'auto':
14250 default:
14251 timestamps = generate(min, max, me.getLabelCapacity(min), options);
14252 }
14253
14254 if (options.bounds === 'ticks' && timestamps.length) {
14255 min = timestamps[0];
14256 max = timestamps[timestamps.length - 1];
14257 }
14258
14259 // Enforce limits with user min/max options
14260 min = parse(timeOpts.min, me) || min;
14261 max = parse(timeOpts.max, me) || max;
14262
14263 // Remove ticks outside the min/max range
14264 for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
14265 timestamp = timestamps[i];
14266 if (timestamp >= min && timestamp <= max) {
14267 ticks.push(timestamp);
14268 }
14269 }
14270
14271 me.min = min;
14272 me.max = max;
14273
14274 // PRIVATE
14275 me._unit = timeOpts.unit || determineUnitForFormatting(ticks, timeOpts.minUnit, me.min, me.max);
14276 me._majorUnit = determineMajorUnit(me._unit);
14277 me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);
14278 me._offsets = computeOffsets(me._table, ticks, min, max, options);
14279 me._labelFormat = determineLabelFormat(me._timestamps.data, timeOpts);
14280
14281 return ticksFromTimestamps(ticks, me._majorUnit);
14282 },
14283
14284 getLabelForIndex: function(index, datasetIndex) {
14285 var me = this;
14286 var data = me.chart.data;
14287 var timeOpts = me.options.time;
14288 var label = data.labels && index < data.labels.length ? data.labels[index] : '';
14289 var value = data.datasets[datasetIndex].data[index];
14290
14291 if (helpers.isObject(value)) {
14292 label = me.getRightValue(value);
14293 }
14294 if (timeOpts.tooltipFormat) {
14295 return momentify(label, timeOpts).format(timeOpts.tooltipFormat);
14296 }
14297 if (typeof label === 'string') {
14298 return label;
14299 }
14300
14301 return momentify(label, timeOpts).format(me._labelFormat);
14302 },
14303
14304 /**
14305 * Function to format an individual tick mark
14306 * @private
14307 */
14308 tickFormatFunction: function(tick, index, ticks, formatOverride) {
14309 var me = this;
14310 var options = me.options;
14311 var time = tick.valueOf();
14312 var formats = options.time.displayFormats;
14313 var minorFormat = formats[me._unit];
14314 var majorUnit = me._majorUnit;
14315 var majorFormat = formats[majorUnit];
14316 var majorTime = tick.clone().startOf(majorUnit).valueOf();
14317 var majorTickOpts = options.ticks.major;
14318 var major = majorTickOpts.enabled && majorUnit && majorFormat && time === majorTime;
14319 var label = tick.format(formatOverride ? formatOverride : major ? majorFormat : minorFormat);
14320 var tickOpts = major ? majorTickOpts : options.ticks.minor;
14321 var formatter = helpers.valueOrDefault(tickOpts.callback, tickOpts.userCallback);
14322
14323 return formatter ? formatter(label, index, ticks) : label;
14324 },
14325
14326 convertTicksToLabels: function(ticks) {
14327 var labels = [];
14328 var i, ilen;
14329
14330 for (i = 0, ilen = ticks.length; i < ilen; ++i) {
14331 labels.push(this.tickFormatFunction(moment(ticks[i].value), i, ticks));
14332 }
14333
14334 return labels;
14335 },
14336
14337 /**
14338 * @private
14339 */
14340 getPixelForOffset: function(time) {
14341 var me = this;
14342 var size = me._horizontal ? me.width : me.height;
14343 var start = me._horizontal ? me.left : me.top;
14344 var pos = interpolate(me._table, 'time', time, 'pos');
14345
14346 return start + size * (me._offsets.left + pos) / (me._offsets.left + 1 + me._offsets.right);
14347 },
14348
14349 getPixelForValue: function(value, index, datasetIndex) {
14350 var me = this;
14351 var time = null;
14352
14353 if (index !== undefined && datasetIndex !== undefined) {
14354 time = me._timestamps.datasets[datasetIndex][index];
14355 }
14356
14357 if (time === null) {
14358 time = parse(value, me);
14359 }
14360
14361 if (time !== null) {
14362 return me.getPixelForOffset(time);
14363 }
14364 },
14365
14366 getPixelForTick: function(index) {
14367 var ticks = this.getTicks();
14368 return index >= 0 && index < ticks.length ?
14369 this.getPixelForOffset(ticks[index].value) :
14370 null;
14371 },
14372
14373 getValueForPixel: function(pixel) {
14374 var me = this;
14375 var size = me._horizontal ? me.width : me.height;
14376 var start = me._horizontal ? me.left : me.top;
14377 var pos = (size ? (pixel - start) / size : 0) * (me._offsets.left + 1 + me._offsets.left) - me._offsets.right;
14378 var time = interpolate(me._table, 'pos', pos, 'time');
14379
14380 return moment(time);
14381 },
14382
14383 /**
14384 * Crude approximation of what the label width might be
14385 * @private
14386 */
14387 getLabelWidth: function(label) {
14388 var me = this;
14389 var ticksOpts = me.options.ticks;
14390 var tickLabelWidth = me.ctx.measureText(label).width;
14391 var angle = helpers.toRadians(ticksOpts.maxRotation);
14392 var cosRotation = Math.cos(angle);
14393 var sinRotation = Math.sin(angle);
14394 var tickFontSize = helpers.valueOrDefault(ticksOpts.fontSize, defaults.global.defaultFontSize);
14395
14396 return (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation);
14397 },
14398
14399 /**
14400 * @private
14401 */
14402 getLabelCapacity: function(exampleTime) {
14403 var me = this;
14404
14405 var formatOverride = me.options.time.displayFormats.millisecond; // Pick the longest format for guestimation
14406
14407 var exampleLabel = me.tickFormatFunction(moment(exampleTime), 0, [], formatOverride);
14408 var tickLabelWidth = me.getLabelWidth(exampleLabel);
14409 var innerWidth = me.isHorizontal() ? me.width : me.height;
14410
14411 var capacity = Math.floor(innerWidth / tickLabelWidth);
14412 return capacity > 0 ? capacity : 1;
14413 }
14414 });
14415
14416 scaleService.registerScaleType('time', TimeScale, defaultConfig);
14417};
14418
14419},{"1":1,"26":26,"33":33,"34":34,"46":46}]},{},[7])(7)
14420});