· 8 years ago · Jan 19, 2018, 04:18 PM
1/*!
2 * Chart.js
3 * http://chartjs.org/
4 * Version: 2.7.1
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 e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
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(29)();
1674
1675Chart.helpers = require(45);
1676
1677// @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
1678require(27)(Chart);
1679
1680Chart.defaults = require(25);
1681Chart.Element = require(26);
1682Chart.elements = require(40);
1683Chart.Interaction = require(28);
1684Chart.layouts = require(30);
1685Chart.platform = require(48);
1686Chart.plugins = require(31);
1687Chart.Ticks = require(34);
1688
1689require(22)(Chart);
1690require(23)(Chart);
1691require(24)(Chart);
1692require(33)(Chart);
1693require(32)(Chart);
1694require(35)(Chart);
1695
1696require(55)(Chart);
1697require(53)(Chart);
1698require(54)(Chart);
1699require(56)(Chart);
1700require(57)(Chart);
1701require(58)(Chart);
1702
1703// Controllers must be loaded after elements
1704// See Chart.core.datasetController.dataElementType
1705require(15)(Chart);
1706require(16)(Chart);
1707require(17)(Chart);
1708require(18)(Chart);
1709require(19)(Chart);
1710require(20)(Chart);
1711require(21)(Chart);
1712
1713require(8)(Chart);
1714require(9)(Chart);
1715require(10)(Chart);
1716require(11)(Chart);
1717require(12)(Chart);
1718require(13)(Chart);
1719require(14)(Chart);
1720
1721// Loading built-it plugins
1722var plugins = require(49);
1723for (var k in plugins) {
1724 if (plugins.hasOwnProperty(k)) {
1725 Chart.plugins.register(plugins[k]);
1726 }
1727}
1728
1729Chart.platform.initialize();
1730
1731module.exports = Chart;
1732if (typeof window !== 'undefined') {
1733 window.Chart = Chart;
1734}
1735
1736// DEPRECATIONS
1737
1738/**
1739 * Provided for backward compatibility, not available anymore
1740 * @namespace Chart.Legend
1741 * @deprecated since version 2.1.5
1742 * @todo remove at version 3
1743 * @private
1744 */
1745Chart.Legend = plugins.legend._element;
1746
1747/**
1748 * Provided for backward compatibility, not available anymore
1749 * @namespace Chart.Title
1750 * @deprecated since version 2.1.5
1751 * @todo remove at version 3
1752 * @private
1753 */
1754Chart.Title = plugins.title._element;
1755
1756/**
1757 * Provided for backward compatibility, use Chart.plugins instead
1758 * @namespace Chart.pluginService
1759 * @deprecated since version 2.1.5
1760 * @todo remove at version 3
1761 * @private
1762 */
1763Chart.pluginService = Chart.plugins;
1764
1765/**
1766 * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
1767 * effect, instead simply create/register plugins via plain JavaScript objects.
1768 * @interface Chart.PluginBase
1769 * @deprecated since version 2.5.0
1770 * @todo remove at version 3
1771 * @private
1772 */
1773Chart.PluginBase = Chart.Element.extend({});
1774
1775/**
1776 * Provided for backward compatibility, use Chart.helpers.canvas instead.
1777 * @namespace Chart.canvasHelpers
1778 * @deprecated since version 2.6.0
1779 * @todo remove at version 3
1780 * @private
1781 */
1782Chart.canvasHelpers = Chart.helpers.canvas;
1783
1784/**
1785 * Provided for backward compatibility, use Chart.layouts instead.
1786 * @namespace Chart.layoutService
1787 * @deprecated since version 2.8.0
1788 * @todo remove at version 3
1789 * @private
1790 */
1791Chart.layoutService = Chart.layouts;
1792
1793},{"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,"40":40,"45":45,"48":48,"49":49,"53":53,"54":54,"55":55,"56":56,"57":57,"58":58,"8":8,"9":9}],8:[function(require,module,exports){
1794'use strict';
1795
1796module.exports = function(Chart) {
1797
1798 Chart.Bar = function(context, config) {
1799 config.type = 'bar';
1800
1801 return new Chart(context, config);
1802 };
1803
1804};
1805
1806},{}],9:[function(require,module,exports){
1807'use strict';
1808
1809module.exports = function(Chart) {
1810
1811 Chart.Bubble = function(context, config) {
1812 config.type = 'bubble';
1813 return new Chart(context, config);
1814 };
1815
1816};
1817
1818},{}],10:[function(require,module,exports){
1819'use strict';
1820
1821module.exports = function(Chart) {
1822
1823 Chart.Doughnut = function(context, config) {
1824 config.type = 'doughnut';
1825
1826 return new Chart(context, config);
1827 };
1828
1829};
1830
1831},{}],11:[function(require,module,exports){
1832'use strict';
1833
1834module.exports = function(Chart) {
1835
1836 Chart.Line = function(context, config) {
1837 config.type = 'line';
1838
1839 return new Chart(context, config);
1840 };
1841
1842};
1843
1844},{}],12:[function(require,module,exports){
1845'use strict';
1846
1847module.exports = function(Chart) {
1848
1849 Chart.PolarArea = function(context, config) {
1850 config.type = 'polarArea';
1851
1852 return new Chart(context, config);
1853 };
1854
1855};
1856
1857},{}],13:[function(require,module,exports){
1858'use strict';
1859
1860module.exports = function(Chart) {
1861
1862 Chart.Radar = function(context, config) {
1863 config.type = 'radar';
1864
1865 return new Chart(context, config);
1866 };
1867
1868};
1869
1870},{}],14:[function(require,module,exports){
1871'use strict';
1872
1873module.exports = function(Chart) {
1874 Chart.Scatter = function(context, config) {
1875 config.type = 'scatter';
1876 return new Chart(context, config);
1877 };
1878};
1879
1880},{}],15:[function(require,module,exports){
1881'use strict';
1882
1883var defaults = require(25);
1884var elements = require(40);
1885var helpers = require(45);
1886
1887defaults._set('bar', {
1888 hover: {
1889 mode: 'label'
1890 },
1891
1892 scales: {
1893 xAxes: [{
1894 type: 'category',
1895
1896 // Specific to Bar Controller
1897 categoryPercentage: 0.8,
1898 barPercentage: 0.9,
1899
1900 // offset settings
1901 offset: true,
1902
1903 // grid line settings
1904 gridLines: {
1905 offsetGridLines: true
1906 }
1907 }],
1908
1909 yAxes: [{
1910 type: 'linear'
1911 }]
1912 }
1913});
1914
1915defaults._set('horizontalBar', {
1916 hover: {
1917 mode: 'index',
1918 axis: 'y'
1919 },
1920
1921 scales: {
1922 xAxes: [{
1923 type: 'linear',
1924 position: 'bottom'
1925 }],
1926
1927 yAxes: [{
1928 position: 'left',
1929 type: 'category',
1930
1931 // Specific to Horizontal Bar Controller
1932 categoryPercentage: 0.8,
1933 barPercentage: 0.9,
1934
1935 // offset settings
1936 offset: true,
1937
1938 // grid line settings
1939 gridLines: {
1940 offsetGridLines: true
1941 }
1942 }]
1943 },
1944
1945 elements: {
1946 rectangle: {
1947 borderSkipped: 'left'
1948 }
1949 },
1950
1951 tooltips: {
1952 callbacks: {
1953 title: function(item, data) {
1954 // Pick first xLabel for now
1955 var title = '';
1956
1957 if (item.length > 0) {
1958 if (item[0].yLabel) {
1959 title = item[0].yLabel;
1960 } else if (data.labels.length > 0 && item[0].index < data.labels.length) {
1961 title = data.labels[item[0].index];
1962 }
1963 }
1964
1965 return title;
1966 },
1967
1968 label: function(item, data) {
1969 var datasetLabel = data.datasets[item.datasetIndex].label || '';
1970 return datasetLabel + ': ' + item.xLabel;
1971 }
1972 },
1973 mode: 'index',
1974 axis: 'y'
1975 }
1976});
1977
1978/**
1979 * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
1980 * @private
1981 */
1982function computeMinSampleSize(scale, pixels) {
1983 var min = scale.isHorizontal() ? scale.width : scale.height;
1984 var ticks = scale.getTicks();
1985 var prev, curr, i, ilen;
1986
1987 for (i = 1, ilen = pixels.length; i < ilen; ++i) {
1988 min = Math.min(min, pixels[i] - pixels[i - 1]);
1989 }
1990
1991 for (i = 0, ilen = ticks.length; i < ilen; ++i) {
1992 curr = scale.getPixelForTick(i);
1993 min = i > 0 ? Math.min(min, curr - prev) : min;
1994 prev = curr;
1995 }
1996
1997 return min;
1998}
1999
2000/**
2001 * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
2002 * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
2003 * mode currently always generates bars equally sized (until we introduce scriptable options?).
2004 * @private
2005 */
2006function computeFitCategoryTraits(index, ruler, options) {
2007 var thickness = options.barThickness;
2008 var count = ruler.stackCount;
2009 var curr = ruler.pixels[index];
2010 var size, ratio;
2011
2012 if (helpers.isNullOrUndef(thickness)) {
2013 size = ruler.min * options.categoryPercentage;
2014 ratio = options.barPercentage;
2015 } else {
2016 // When bar thickness is enforced, category and bar percentages are ignored.
2017 // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
2018 // and deprecate barPercentage since this value is ignored when thickness is absolute.
2019 size = thickness * count;
2020 ratio = 1;
2021 }
2022
2023 return {
2024 chunk: size / count,
2025 ratio: ratio,
2026 start: curr - (size / 2)
2027 };
2028}
2029
2030/**
2031 * Computes an "optimal" category that globally arranges bars side by side (no gap when
2032 * percentage options are 1), based on the previous and following categories. This mode
2033 * generates bars with different widths when data are not evenly spaced.
2034 * @private
2035 */
2036function computeFlexCategoryTraits(index, ruler, options) {
2037 var pixels = ruler.pixels;
2038 var curr = pixels[index];
2039 var prev = index > 0 ? pixels[index - 1] : null;
2040 var next = index < pixels.length - 1 ? pixels[index + 1] : null;
2041 var percent = options.categoryPercentage;
2042 var start, size;
2043
2044 if (prev === null) {
2045 // first data: its size is double based on the next point or,
2046 // if it's also the last data, we use the scale end extremity.
2047 prev = curr - (next === null ? ruler.end - curr : next - curr);
2048 }
2049
2050 if (next === null) {
2051 // last data: its size is also double based on the previous point.
2052 next = curr + curr - prev;
2053 }
2054
2055 start = curr - ((curr - prev) / 2) * percent;
2056 size = ((next - prev) / 2) * percent;
2057
2058 return {
2059 chunk: size / ruler.stackCount,
2060 ratio: options.barPercentage,
2061 start: start
2062 };
2063}
2064
2065module.exports = function(Chart) {
2066
2067 Chart.controllers.bar = Chart.DatasetController.extend({
2068
2069 dataElementType: elements.Rectangle,
2070
2071 initialize: function() {
2072 var me = this;
2073 var meta;
2074
2075 Chart.DatasetController.prototype.initialize.apply(me, arguments);
2076
2077 meta = me.getMeta();
2078 meta.stack = me.getDataset().stack;
2079 meta.bar = true;
2080 },
2081
2082 update: function(reset) {
2083 var me = this;
2084 var rects = me.getMeta().data;
2085 var i, ilen;
2086
2087 me._ruler = me.getRuler();
2088
2089 for (i = 0, ilen = rects.length; i < ilen; ++i) {
2090 me.updateElement(rects[i], i, reset);
2091 }
2092 },
2093
2094 updateElement: function(rectangle, index, reset) {
2095 var me = this;
2096 var chart = me.chart;
2097 var meta = me.getMeta();
2098 var dataset = me.getDataset();
2099 var custom = rectangle.custom || {};
2100 var rectangleOptions = chart.options.elements.rectangle;
2101
2102 rectangle._xScale = me.getScaleForId(meta.xAxisID);
2103 rectangle._yScale = me.getScaleForId(meta.yAxisID);
2104 rectangle._datasetIndex = me.index;
2105 rectangle._index = index;
2106
2107 rectangle._model = {
2108 datasetLabel: dataset.label,
2109 label: chart.data.labels[index],
2110 borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleOptions.borderSkipped,
2111 backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.backgroundColor, index, rectangleOptions.backgroundColor),
2112 borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.borderColor, index, rectangleOptions.borderColor),
2113 borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.borderWidth, index, rectangleOptions.borderWidth)
2114 };
2115
2116 me.updateElementGeometry(rectangle, index, reset);
2117
2118 rectangle.pivot();
2119 },
2120
2121 /**
2122 * @private
2123 */
2124 updateElementGeometry: function(rectangle, index, reset) {
2125 var me = this;
2126 var model = rectangle._model;
2127 var vscale = me.getValueScale();
2128 var base = vscale.getBasePixel();
2129 var horizontal = vscale.isHorizontal();
2130 var ruler = me._ruler || me.getRuler();
2131 var vpixels = me.calculateBarValuePixels(me.index, index);
2132 var ipixels = me.calculateBarIndexPixels(me.index, index, ruler);
2133
2134 model.horizontal = horizontal;
2135 model.base = reset ? base : vpixels.base;
2136 model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
2137 model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
2138 model.height = horizontal ? ipixels.size : undefined;
2139 model.width = horizontal ? undefined : ipixels.size;
2140 },
2141
2142 /**
2143 * @private
2144 */
2145 getValueScaleId: function() {
2146 return this.getMeta().yAxisID;
2147 },
2148
2149 /**
2150 * @private
2151 */
2152 getIndexScaleId: function() {
2153 return this.getMeta().xAxisID;
2154 },
2155
2156 /**
2157 * @private
2158 */
2159 getValueScale: function() {
2160 return this.getScaleForId(this.getValueScaleId());
2161 },
2162
2163 /**
2164 * @private
2165 */
2166 getIndexScale: function() {
2167 return this.getScaleForId(this.getIndexScaleId());
2168 },
2169
2170 /**
2171 * Returns the stacks based on groups and bar visibility.
2172 * @param {Number} [last] - The dataset index
2173 * @returns {Array} The stack list
2174 * @private
2175 */
2176 _getStacks: function(last) {
2177 var me = this;
2178 var chart = me.chart;
2179 var scale = me.getIndexScale();
2180 var stacked = scale.options.stacked;
2181 var ilen = last === undefined ? chart.data.datasets.length : last + 1;
2182 var stacks = [];
2183 var i, meta;
2184
2185 for (i = 0; i < ilen; ++i) {
2186 meta = chart.getDatasetMeta(i);
2187 if (meta.bar && chart.isDatasetVisible(i) &&
2188 (stacked === false ||
2189 (stacked === true && stacks.indexOf(meta.stack) === -1) ||
2190 (stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) {
2191 stacks.push(meta.stack);
2192 }
2193 }
2194
2195 return stacks;
2196 },
2197
2198 /**
2199 * Returns the effective number of stacks based on groups and bar visibility.
2200 * @private
2201 */
2202 getStackCount: function() {
2203 return this._getStacks().length;
2204 },
2205
2206 /**
2207 * Returns the stack index for the given dataset based on groups and bar visibility.
2208 * @param {Number} [datasetIndex] - The dataset index
2209 * @param {String} [name] - The stack name to find
2210 * @returns {Number} The stack index
2211 * @private
2212 */
2213 getStackIndex: function(datasetIndex, name) {
2214 var stacks = this._getStacks(datasetIndex);
2215 var index = (name !== undefined)
2216 ? stacks.indexOf(name)
2217 : -1; // indexOf returns -1 if element is not present
2218
2219 return (index === -1)
2220 ? stacks.length - 1
2221 : index;
2222 },
2223
2224 /**
2225 * @private
2226 */
2227 getRuler: function() {
2228 var me = this;
2229 var scale = me.getIndexScale();
2230 var stackCount = me.getStackCount();
2231 var datasetIndex = me.index;
2232 var isHorizontal = scale.isHorizontal();
2233 var start = isHorizontal ? scale.left : scale.top;
2234 var end = start + (isHorizontal ? scale.width : scale.height);
2235 var pixels = [];
2236 var i, ilen, min;
2237
2238 for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
2239 pixels.push(scale.getPixelForValue(null, i, datasetIndex));
2240 }
2241
2242 min = helpers.isNullOrUndef(scale.options.barThickness)
2243 ? computeMinSampleSize(scale, pixels)
2244 : -1;
2245
2246 return {
2247 min: min,
2248 pixels: pixels,
2249 start: start,
2250 end: end,
2251 stackCount: stackCount,
2252 scale: scale
2253 };
2254 },
2255
2256 /**
2257 * Note: pixel values are not clamped to the scale area.
2258 * @private
2259 */
2260 calculateBarValuePixels: function(datasetIndex, index) {
2261 var me = this;
2262 var chart = me.chart;
2263 var meta = me.getMeta();
2264 var scale = me.getValueScale();
2265 var datasets = chart.data.datasets;
2266 var value = scale.getRightValue(datasets[datasetIndex].data[index]);
2267 var stacked = scale.options.stacked;
2268 var stack = meta.stack;
2269 var start = 0;
2270 var i, imeta, ivalue, base, head, size;
2271
2272 if (stacked || (stacked === undefined && stack !== undefined)) {
2273 for (i = 0; i < datasetIndex; ++i) {
2274 imeta = chart.getDatasetMeta(i);
2275
2276 if (imeta.bar &&
2277 imeta.stack === stack &&
2278 imeta.controller.getValueScaleId() === scale.id &&
2279 chart.isDatasetVisible(i)) {
2280
2281 ivalue = scale.getRightValue(datasets[i].data[index]);
2282 if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) {
2283 start += ivalue;
2284 }
2285 }
2286 }
2287 }
2288
2289 base = scale.getPixelForValue(start);
2290 head = scale.getPixelForValue(start + value);
2291 size = (head - base) / 2;
2292
2293 return {
2294 size: size,
2295 base: base,
2296 head: head,
2297 center: head + size / 2
2298 };
2299 },
2300
2301 /**
2302 * @private
2303 */
2304 calculateBarIndexPixels: function(datasetIndex, index, ruler) {
2305 var me = this;
2306 var options = ruler.scale.options;
2307 var range = options.barThickness === 'flex'
2308 ? computeFlexCategoryTraits(index, ruler, options)
2309 : computeFitCategoryTraits(index, ruler, options);
2310
2311 var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
2312 var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
2313 var size = Math.min(
2314 helpers.valueOrDefault(options.maxBarThickness, Infinity),
2315 range.chunk * range.ratio);
2316
2317 return {
2318 base: center - size / 2,
2319 head: center + size / 2,
2320 center: center,
2321 size: size
2322 };
2323 },
2324
2325 draw: function() {
2326 var me = this;
2327 var chart = me.chart;
2328 var scale = me.getValueScale();
2329 var rects = me.getMeta().data;
2330 var dataset = me.getDataset();
2331 var ilen = rects.length;
2332 var i = 0;
2333
2334 helpers.canvas.clipArea(chart.ctx, chart.chartArea);
2335
2336 for (; i < ilen; ++i) {
2337 if (!isNaN(scale.getRightValue(dataset.data[i]))) {
2338 rects[i].draw();
2339 }
2340 }
2341
2342 helpers.canvas.unclipArea(chart.ctx);
2343 },
2344
2345 setHoverStyle: function(rectangle) {
2346 var dataset = this.chart.data.datasets[rectangle._datasetIndex];
2347 var index = rectangle._index;
2348 var custom = rectangle.custom || {};
2349 var model = rectangle._model;
2350
2351 model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.valueAtIndexOrDefault(dataset.hoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
2352 model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.valueAtIndexOrDefault(dataset.hoverBorderColor, index, helpers.getHoverColor(model.borderColor));
2353 model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.valueAtIndexOrDefault(dataset.hoverBorderWidth, index, model.borderWidth);
2354 },
2355
2356 removeHoverStyle: function(rectangle) {
2357 var dataset = this.chart.data.datasets[rectangle._datasetIndex];
2358 var index = rectangle._index;
2359 var custom = rectangle.custom || {};
2360 var model = rectangle._model;
2361 var rectangleElementOptions = this.chart.options.elements.rectangle;
2362
2363 model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor);
2364 model.borderColor = custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor);
2365 model.borderWidth = custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.borderWidth, index, rectangleElementOptions.borderWidth);
2366 }
2367 });
2368
2369 Chart.controllers.horizontalBar = Chart.controllers.bar.extend({
2370 /**
2371 * @private
2372 */
2373 getValueScaleId: function() {
2374 return this.getMeta().xAxisID;
2375 },
2376
2377 /**
2378 * @private
2379 */
2380 getIndexScaleId: function() {
2381 return this.getMeta().yAxisID;
2382 }
2383 });
2384};
2385
2386},{"25":25,"40":40,"45":45}],16:[function(require,module,exports){
2387'use strict';
2388
2389var defaults = require(25);
2390var elements = require(40);
2391var helpers = require(45);
2392
2393defaults._set('bubble', {
2394 hover: {
2395 mode: 'single'
2396 },
2397
2398 scales: {
2399 xAxes: [{
2400 type: 'linear', // bubble should probably use a linear scale by default
2401 position: 'bottom',
2402 id: 'x-axis-0' // need an ID so datasets can reference the scale
2403 }],
2404 yAxes: [{
2405 type: 'linear',
2406 position: 'left',
2407 id: 'y-axis-0'
2408 }]
2409 },
2410
2411 tooltips: {
2412 callbacks: {
2413 title: function() {
2414 // Title doesn't make sense for scatter since we format the data as a point
2415 return '';
2416 },
2417 label: function(item, data) {
2418 var datasetLabel = data.datasets[item.datasetIndex].label || '';
2419 var dataPoint = data.datasets[item.datasetIndex].data[item.index];
2420 return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
2421 }
2422 }
2423 }
2424});
2425
2426
2427module.exports = function(Chart) {
2428
2429 Chart.controllers.bubble = Chart.DatasetController.extend({
2430 /**
2431 * @protected
2432 */
2433 dataElementType: elements.Point,
2434
2435 /**
2436 * @protected
2437 */
2438 update: function(reset) {
2439 var me = this;
2440 var meta = me.getMeta();
2441 var points = meta.data;
2442
2443 // Update Points
2444 helpers.each(points, function(point, index) {
2445 me.updateElement(point, index, reset);
2446 });
2447 },
2448
2449 /**
2450 * @protected
2451 */
2452 updateElement: function(point, index, reset) {
2453 var me = this;
2454 var meta = me.getMeta();
2455 var custom = point.custom || {};
2456 var xScale = me.getScaleForId(meta.xAxisID);
2457 var yScale = me.getScaleForId(meta.yAxisID);
2458 var options = me._resolveElementOptions(point, index);
2459 var data = me.getDataset().data[index];
2460 var dsIndex = me.index;
2461
2462 var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
2463 var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
2464
2465 point._xScale = xScale;
2466 point._yScale = yScale;
2467 point._options = options;
2468 point._datasetIndex = dsIndex;
2469 point._index = index;
2470 point._model = {
2471 backgroundColor: options.backgroundColor,
2472 borderColor: options.borderColor,
2473 borderWidth: options.borderWidth,
2474 hitRadius: options.hitRadius,
2475 pointStyle: options.pointStyle,
2476 radius: reset ? 0 : options.radius,
2477 skip: custom.skip || isNaN(x) || isNaN(y),
2478 x: x,
2479 y: y,
2480 };
2481
2482 point.pivot();
2483 },
2484
2485 /**
2486 * @protected
2487 */
2488 setHoverStyle: function(point) {
2489 var model = point._model;
2490 var options = point._options;
2491
2492 model.backgroundColor = helpers.valueOrDefault(options.hoverBackgroundColor, helpers.getHoverColor(options.backgroundColor));
2493 model.borderColor = helpers.valueOrDefault(options.hoverBorderColor, helpers.getHoverColor(options.borderColor));
2494 model.borderWidth = helpers.valueOrDefault(options.hoverBorderWidth, options.borderWidth);
2495 model.radius = options.radius + options.hoverRadius;
2496 },
2497
2498 /**
2499 * @protected
2500 */
2501 removeHoverStyle: function(point) {
2502 var model = point._model;
2503 var options = point._options;
2504
2505 model.backgroundColor = options.backgroundColor;
2506 model.borderColor = options.borderColor;
2507 model.borderWidth = options.borderWidth;
2508 model.radius = options.radius;
2509 },
2510
2511 /**
2512 * @private
2513 */
2514 _resolveElementOptions: function(point, index) {
2515 var me = this;
2516 var chart = me.chart;
2517 var datasets = chart.data.datasets;
2518 var dataset = datasets[me.index];
2519 var custom = point.custom || {};
2520 var options = chart.options.elements.point;
2521 var resolve = helpers.options.resolve;
2522 var data = dataset.data[index];
2523 var values = {};
2524 var i, ilen, key;
2525
2526 // Scriptable options
2527 var context = {
2528 chart: chart,
2529 dataIndex: index,
2530 dataset: dataset,
2531 datasetIndex: me.index
2532 };
2533
2534 var keys = [
2535 'backgroundColor',
2536 'borderColor',
2537 'borderWidth',
2538 'hoverBackgroundColor',
2539 'hoverBorderColor',
2540 'hoverBorderWidth',
2541 'hoverRadius',
2542 'hitRadius',
2543 'pointStyle'
2544 ];
2545
2546 for (i = 0, ilen = keys.length; i < ilen; ++i) {
2547 key = keys[i];
2548 values[key] = resolve([
2549 custom[key],
2550 dataset[key],
2551 options[key]
2552 ], context, index);
2553 }
2554
2555 // Custom radius resolution
2556 values.radius = resolve([
2557 custom.radius,
2558 data ? data.r : undefined,
2559 dataset.radius,
2560 options.radius
2561 ], context, index);
2562
2563 return values;
2564 }
2565 });
2566};
2567
2568},{"25":25,"40":40,"45":45}],17:[function(require,module,exports){
2569'use strict';
2570
2571var defaults = require(25);
2572var elements = require(40);
2573var helpers = require(45);
2574
2575defaults._set('doughnut', {
2576 animation: {
2577 // Boolean - Whether we animate the rotation of the Doughnut
2578 animateRotate: true,
2579 // Boolean - Whether we animate scaling the Doughnut from the centre
2580 animateScale: false
2581 },
2582 hover: {
2583 mode: 'single'
2584 },
2585 legendCallback: function(chart) {
2586 var text = [];
2587 text.push('<ul class="' + chart.id + '-legend">');
2588
2589 var data = chart.data;
2590 var datasets = data.datasets;
2591 var labels = data.labels;
2592
2593 if (datasets.length) {
2594 for (var i = 0; i < datasets[0].data.length; ++i) {
2595 text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
2596 if (labels[i]) {
2597 text.push(labels[i]);
2598 }
2599 text.push('</li>');
2600 }
2601 }
2602
2603 text.push('</ul>');
2604 return text.join('');
2605 },
2606 legend: {
2607 labels: {
2608 generateLabels: function(chart) {
2609 var data = chart.data;
2610 if (data.labels.length && data.datasets.length) {
2611 return data.labels.map(function(label, i) {
2612 var meta = chart.getDatasetMeta(0);
2613 var ds = data.datasets[0];
2614 var arc = meta.data[i];
2615 var custom = arc && arc.custom || {};
2616 var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
2617 var arcOpts = chart.options.elements.arc;
2618 var fill = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
2619 var stroke = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
2620 var bw = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
2621
2622 return {
2623 text: label,
2624 fillStyle: fill,
2625 strokeStyle: stroke,
2626 lineWidth: bw,
2627 hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
2628
2629 // Extra data used for toggling the correct item
2630 index: i
2631 };
2632 });
2633 }
2634 return [];
2635 }
2636 },
2637
2638 onClick: function(e, legendItem) {
2639 var index = legendItem.index;
2640 var chart = this.chart;
2641 var i, ilen, meta;
2642
2643 for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
2644 meta = chart.getDatasetMeta(i);
2645 // toggle visibility of index if exists
2646 if (meta.data[index]) {
2647 meta.data[index].hidden = !meta.data[index].hidden;
2648 }
2649 }
2650
2651 chart.update();
2652 }
2653 },
2654
2655 // The percentage of the chart that we cut out of the middle.
2656 cutoutPercentage: 50,
2657
2658 // The rotation of the chart, where the first data arc begins.
2659 rotation: Math.PI * -0.5,
2660
2661 // The total circumference of the chart.
2662 circumference: Math.PI * 2.0,
2663
2664 // Need to override these to give a nice default
2665 tooltips: {
2666 callbacks: {
2667 title: function() {
2668 return '';
2669 },
2670 label: function(tooltipItem, data) {
2671 var dataLabel = data.labels[tooltipItem.index];
2672 var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
2673
2674 if (helpers.isArray(dataLabel)) {
2675 // show value on first line of multiline label
2676 // need to clone because we are changing the value
2677 dataLabel = dataLabel.slice();
2678 dataLabel[0] += value;
2679 } else {
2680 dataLabel += value;
2681 }
2682
2683 return dataLabel;
2684 }
2685 }
2686 }
2687});
2688
2689defaults._set('pie', helpers.clone(defaults.doughnut));
2690defaults._set('pie', {
2691 cutoutPercentage: 0
2692});
2693
2694module.exports = function(Chart) {
2695
2696 Chart.controllers.doughnut = Chart.controllers.pie = Chart.DatasetController.extend({
2697
2698 dataElementType: elements.Arc,
2699
2700 linkScales: helpers.noop,
2701
2702 // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
2703 getRingIndex: function(datasetIndex) {
2704 var ringIndex = 0;
2705
2706 for (var j = 0; j < datasetIndex; ++j) {
2707 if (this.chart.isDatasetVisible(j)) {
2708 ++ringIndex;
2709 }
2710 }
2711
2712 return ringIndex;
2713 },
2714
2715 update: function(reset) {
2716 var me = this;
2717 var chart = me.chart;
2718 var chartArea = chart.chartArea;
2719 var opts = chart.options;
2720 var arcOpts = opts.elements.arc;
2721 var availableWidth = chartArea.right - chartArea.left - arcOpts.borderWidth;
2722 var availableHeight = chartArea.bottom - chartArea.top - arcOpts.borderWidth;
2723 var minSize = Math.min(availableWidth, availableHeight);
2724 var offset = {x: 0, y: 0};
2725 var meta = me.getMeta();
2726 var cutoutPercentage = opts.cutoutPercentage;
2727 var circumference = opts.circumference;
2728
2729 // If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc
2730 if (circumference < Math.PI * 2.0) {
2731 var startAngle = opts.rotation % (Math.PI * 2.0);
2732 startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0);
2733 var endAngle = startAngle + circumference;
2734 var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)};
2735 var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)};
2736 var contains0 = (startAngle <= 0 && endAngle >= 0) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle);
2737 var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle);
2738 var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle);
2739 var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle);
2740 var cutout = cutoutPercentage / 100.0;
2741 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))};
2742 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))};
2743 var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5};
2744 minSize = Math.min(availableWidth / size.width, availableHeight / size.height);
2745 offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5};
2746 }
2747
2748 chart.borderWidth = me.getMaxBorderWidth(meta.data);
2749 chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0);
2750 chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0);
2751 chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
2752 chart.offsetX = offset.x * chart.outerRadius;
2753 chart.offsetY = offset.y * chart.outerRadius;
2754
2755 meta.total = me.calculateTotal();
2756
2757 me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index));
2758 me.innerRadius = Math.max(me.outerRadius - chart.radiusLength, 0);
2759
2760 helpers.each(meta.data, function(arc, index) {
2761 me.updateElement(arc, index, reset);
2762 });
2763 },
2764
2765 updateElement: function(arc, index, reset) {
2766 var me = this;
2767 var chart = me.chart;
2768 var chartArea = chart.chartArea;
2769 var opts = chart.options;
2770 var animationOpts = opts.animation;
2771 var centerX = (chartArea.left + chartArea.right) / 2;
2772 var centerY = (chartArea.top + chartArea.bottom) / 2;
2773 var startAngle = opts.rotation; // non reset case handled later
2774 var endAngle = opts.rotation; // non reset case handled later
2775 var dataset = me.getDataset();
2776 var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI));
2777 var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
2778 var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
2779 var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
2780
2781 helpers.extend(arc, {
2782 // Utility
2783 _datasetIndex: me.index,
2784 _index: index,
2785
2786 // Desired view properties
2787 _model: {
2788 x: centerX + chart.offsetX,
2789 y: centerY + chart.offsetY,
2790 startAngle: startAngle,
2791 endAngle: endAngle,
2792 circumference: circumference,
2793 outerRadius: outerRadius,
2794 innerRadius: innerRadius,
2795 label: valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
2796 }
2797 });
2798
2799 var model = arc._model;
2800 // Resets the visual styles
2801 this.removeHoverStyle(arc);
2802
2803 // Set correct angles if not resetting
2804 if (!reset || !animationOpts.animateRotate) {
2805 if (index === 0) {
2806 model.startAngle = opts.rotation;
2807 } else {
2808 model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
2809 }
2810
2811 model.endAngle = model.startAngle + model.circumference;
2812 }
2813
2814 arc.pivot();
2815 },
2816
2817 removeHoverStyle: function(arc) {
2818 Chart.DatasetController.prototype.removeHoverStyle.call(this, arc, this.chart.options.elements.arc);
2819 },
2820
2821 calculateTotal: function() {
2822 var dataset = this.getDataset();
2823 var meta = this.getMeta();
2824 var total = 0;
2825 var value;
2826
2827 helpers.each(meta.data, function(element, index) {
2828 value = dataset.data[index];
2829 if (!isNaN(value) && !element.hidden) {
2830 total += Math.abs(value);
2831 }
2832 });
2833
2834 /* if (total === 0) {
2835 total = NaN;
2836 }*/
2837
2838 return total;
2839 },
2840
2841 calculateCircumference: function(value) {
2842 var total = this.getMeta().total;
2843 if (total > 0 && !isNaN(value)) {
2844 return (Math.PI * 2.0) * (value / total);
2845 }
2846 return 0;
2847 },
2848
2849 // gets the max border or hover width to properly scale pie charts
2850 getMaxBorderWidth: function(arcs) {
2851 var max = 0;
2852 var index = this.index;
2853 var length = arcs.length;
2854 var borderWidth;
2855 var hoverWidth;
2856
2857 for (var i = 0; i < length; i++) {
2858 borderWidth = arcs[i]._model ? arcs[i]._model.borderWidth : 0;
2859 hoverWidth = arcs[i]._chart ? arcs[i]._chart.config.data.datasets[index].hoverBorderWidth : 0;
2860
2861 max = borderWidth > max ? borderWidth : max;
2862 max = hoverWidth > max ? hoverWidth : max;
2863 }
2864 return max;
2865 }
2866 });
2867};
2868
2869},{"25":25,"40":40,"45":45}],18:[function(require,module,exports){
2870'use strict';
2871
2872var defaults = require(25);
2873var elements = require(40);
2874var helpers = require(45);
2875
2876defaults._set('line', {
2877 showLines: true,
2878 spanGaps: false,
2879
2880 hover: {
2881 mode: 'label'
2882 },
2883
2884 scales: {
2885 xAxes: [{
2886 type: 'category',
2887 id: 'x-axis-0'
2888 }],
2889 yAxes: [{
2890 type: 'linear',
2891 id: 'y-axis-0'
2892 }]
2893 }
2894});
2895
2896module.exports = function(Chart) {
2897
2898 function lineEnabled(dataset, options) {
2899 return helpers.valueOrDefault(dataset.showLine, options.showLines);
2900 }
2901
2902 Chart.controllers.line = Chart.DatasetController.extend({
2903
2904 datasetElementType: elements.Line,
2905
2906 dataElementType: elements.Point,
2907
2908 update: function(reset) {
2909 var me = this;
2910 var meta = me.getMeta();
2911 var line = meta.dataset;
2912 var points = meta.data || [];
2913 var options = me.chart.options;
2914 var lineElementOptions = options.elements.line;
2915 var scale = me.getScaleForId(meta.yAxisID);
2916 var i, ilen, custom;
2917 var dataset = me.getDataset();
2918 var showLine = lineEnabled(dataset, options);
2919
2920 // Update Line
2921 if (showLine) {
2922 custom = line.custom || {};
2923
2924 // Compatibility: If the properties are defined with only the old name, use those values
2925 if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
2926 dataset.lineTension = dataset.tension;
2927 }
2928
2929 // Utility
2930 line._scale = scale;
2931 line._datasetIndex = me.index;
2932 // Data
2933 line._children = points;
2934 // Model
2935 line._model = {
2936 // Appearance
2937 // The default behavior of lines is to break at null values, according
2938 // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
2939 // This option gives lines the ability to span gaps
2940 spanGaps: dataset.spanGaps ? dataset.spanGaps : options.spanGaps,
2941 tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension),
2942 backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),
2943 borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),
2944 borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),
2945 borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),
2946 borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),
2947 borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),
2948 borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),
2949 fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),
2950 steppedLine: custom.steppedLine ? custom.steppedLine : helpers.valueOrDefault(dataset.steppedLine, lineElementOptions.stepped),
2951 cubicInterpolationMode: custom.cubicInterpolationMode ? custom.cubicInterpolationMode : helpers.valueOrDefault(dataset.cubicInterpolationMode, lineElementOptions.cubicInterpolationMode),
2952 };
2953
2954 line.pivot();
2955 }
2956
2957 // Update Points
2958 for (i = 0, ilen = points.length; i < ilen; ++i) {
2959 me.updateElement(points[i], i, reset);
2960 }
2961
2962 if (showLine && line._model.tension !== 0) {
2963 me.updateBezierControlPoints();
2964 }
2965
2966 // Now pivot the point for animation
2967 for (i = 0, ilen = points.length; i < ilen; ++i) {
2968 points[i].pivot();
2969 }
2970 },
2971
2972 getPointBackgroundColor: function(point, index) {
2973 var backgroundColor = this.chart.options.elements.point.backgroundColor;
2974 var dataset = this.getDataset();
2975 var custom = point.custom || {};
2976
2977 if (custom.backgroundColor) {
2978 backgroundColor = custom.backgroundColor;
2979 } else if (dataset.pointBackgroundColor) {
2980 backgroundColor = helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, backgroundColor);
2981 } else if (dataset.backgroundColor) {
2982 backgroundColor = dataset.backgroundColor;
2983 }
2984
2985 return backgroundColor;
2986 },
2987
2988 getPointBorderColor: function(point, index) {
2989 var borderColor = this.chart.options.elements.point.borderColor;
2990 var dataset = this.getDataset();
2991 var custom = point.custom || {};
2992
2993 if (custom.borderColor) {
2994 borderColor = custom.borderColor;
2995 } else if (dataset.pointBorderColor) {
2996 borderColor = helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, borderColor);
2997 } else if (dataset.borderColor) {
2998 borderColor = dataset.borderColor;
2999 }
3000
3001 return borderColor;
3002 },
3003
3004 getPointBorderWidth: function(point, index) {
3005 var borderWidth = this.chart.options.elements.point.borderWidth;
3006 var dataset = this.getDataset();
3007 var custom = point.custom || {};
3008
3009 if (!isNaN(custom.borderWidth)) {
3010 borderWidth = custom.borderWidth;
3011 } else if (!isNaN(dataset.pointBorderWidth) || helpers.isArray(dataset.pointBorderWidth)) {
3012 borderWidth = helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, borderWidth);
3013 } else if (!isNaN(dataset.borderWidth)) {
3014 borderWidth = dataset.borderWidth;
3015 }
3016
3017 return borderWidth;
3018 },
3019
3020 updateElement: function(point, index, reset) {
3021 var me = this;
3022 var meta = me.getMeta();
3023 var custom = point.custom || {};
3024 var dataset = me.getDataset();
3025 var datasetIndex = me.index;
3026 var value = dataset.data[index];
3027 var yScale = me.getScaleForId(meta.yAxisID);
3028 var xScale = me.getScaleForId(meta.xAxisID);
3029 var pointOptions = me.chart.options.elements.point;
3030 var x, y;
3031
3032 // Compatibility: If the properties are defined with only the old name, use those values
3033 if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
3034 dataset.pointRadius = dataset.radius;
3035 }
3036 if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {
3037 dataset.pointHitRadius = dataset.hitRadius;
3038 }
3039
3040 x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
3041 y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
3042
3043 // Utility
3044 point._xScale = xScale;
3045 point._yScale = yScale;
3046 point._datasetIndex = datasetIndex;
3047 point._index = index;
3048
3049 // Desired view properties
3050 point._model = {
3051 x: x,
3052 y: y,
3053 skip: custom.skip || isNaN(x) || isNaN(y),
3054 // Appearance
3055 radius: custom.radius || helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointOptions.radius),
3056 pointStyle: custom.pointStyle || helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointOptions.pointStyle),
3057 backgroundColor: me.getPointBackgroundColor(point, index),
3058 borderColor: me.getPointBorderColor(point, index),
3059 borderWidth: me.getPointBorderWidth(point, index),
3060 tension: meta.dataset._model ? meta.dataset._model.tension : 0,
3061 steppedLine: meta.dataset._model ? meta.dataset._model.steppedLine : false,
3062 // Tooltip
3063 hitRadius: custom.hitRadius || helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointOptions.hitRadius)
3064 };
3065 },
3066
3067 calculatePointY: function(value, index, datasetIndex) {
3068 var me = this;
3069 var chart = me.chart;
3070 var meta = me.getMeta();
3071 var yScale = me.getScaleForId(meta.yAxisID);
3072 var sumPos = 0;
3073 var sumNeg = 0;
3074 var i, ds, dsMeta;
3075
3076 if (yScale.options.stacked) {
3077 for (i = 0; i < datasetIndex; i++) {
3078 ds = chart.data.datasets[i];
3079 dsMeta = chart.getDatasetMeta(i);
3080 if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) {
3081 var stackedRightValue = Number(yScale.getRightValue(ds.data[index]));
3082 if (stackedRightValue < 0) {
3083 sumNeg += stackedRightValue || 0;
3084 } else {
3085 sumPos += stackedRightValue || 0;
3086 }
3087 }
3088 }
3089
3090 var rightValue = Number(yScale.getRightValue(value));
3091 if (rightValue < 0) {
3092 return yScale.getPixelForValue(sumNeg + rightValue);
3093 }
3094 return yScale.getPixelForValue(sumPos + rightValue);
3095 }
3096
3097 return yScale.getPixelForValue(value);
3098 },
3099
3100 updateBezierControlPoints: function() {
3101 var me = this;
3102 var meta = me.getMeta();
3103 var area = me.chart.chartArea;
3104 var points = (meta.data || []);
3105 var i, ilen, point, model, controlPoints;
3106
3107 // Only consider points that are drawn in case the spanGaps option is used
3108 if (meta.dataset._model.spanGaps) {
3109 points = points.filter(function(pt) {
3110 return !pt._model.skip;
3111 });
3112 }
3113
3114 function capControlPoint(pt, min, max) {
3115 return Math.max(Math.min(pt, max), min);
3116 }
3117
3118 if (meta.dataset._model.cubicInterpolationMode === 'monotone') {
3119 helpers.splineCurveMonotone(points);
3120 } else {
3121 for (i = 0, ilen = points.length; i < ilen; ++i) {
3122 point = points[i];
3123 model = point._model;
3124 controlPoints = helpers.splineCurve(
3125 helpers.previousItem(points, i)._model,
3126 model,
3127 helpers.nextItem(points, i)._model,
3128 meta.dataset._model.tension
3129 );
3130 model.controlPointPreviousX = controlPoints.previous.x;
3131 model.controlPointPreviousY = controlPoints.previous.y;
3132 model.controlPointNextX = controlPoints.next.x;
3133 model.controlPointNextY = controlPoints.next.y;
3134 }
3135 }
3136
3137 if (me.chart.options.elements.line.capBezierPoints) {
3138 for (i = 0, ilen = points.length; i < ilen; ++i) {
3139 model = points[i]._model;
3140 model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
3141 model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
3142 model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
3143 model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
3144 }
3145 }
3146 },
3147
3148 draw: function() {
3149 var me = this;
3150 var chart = me.chart;
3151 var meta = me.getMeta();
3152 var points = meta.data || [];
3153 var area = chart.chartArea;
3154 var ilen = points.length;
3155 var i = 0;
3156
3157 helpers.canvas.clipArea(chart.ctx, area);
3158
3159 if (lineEnabled(me.getDataset(), chart.options)) {
3160 meta.dataset.draw();
3161 }
3162
3163 helpers.canvas.unclipArea(chart.ctx);
3164
3165 // Draw the points
3166 for (; i < ilen; ++i) {
3167 points[i].draw(area);
3168 }
3169 },
3170
3171 setHoverStyle: function(point) {
3172 // Point
3173 var dataset = this.chart.data.datasets[point._datasetIndex];
3174 var index = point._index;
3175 var custom = point.custom || {};
3176 var model = point._model;
3177
3178 model.radius = custom.hoverRadius || helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);
3179 model.backgroundColor = custom.hoverBackgroundColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
3180 model.borderColor = custom.hoverBorderColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));
3181 model.borderWidth = custom.hoverBorderWidth || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);
3182 },
3183
3184 removeHoverStyle: function(point) {
3185 var me = this;
3186 var dataset = me.chart.data.datasets[point._datasetIndex];
3187 var index = point._index;
3188 var custom = point.custom || {};
3189 var model = point._model;
3190
3191 // Compatibility: If the properties are defined with only the old name, use those values
3192 if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
3193 dataset.pointRadius = dataset.radius;
3194 }
3195
3196 model.radius = custom.radius || helpers.valueAtIndexOrDefault(dataset.pointRadius, index, me.chart.options.elements.point.radius);
3197 model.backgroundColor = me.getPointBackgroundColor(point, index);
3198 model.borderColor = me.getPointBorderColor(point, index);
3199 model.borderWidth = me.getPointBorderWidth(point, index);
3200 }
3201 });
3202};
3203
3204},{"25":25,"40":40,"45":45}],19:[function(require,module,exports){
3205'use strict';
3206
3207var defaults = require(25);
3208var elements = require(40);
3209var helpers = require(45);
3210
3211defaults._set('polarArea', {
3212 scale: {
3213 type: 'radialLinear',
3214 angleLines: {
3215 display: false
3216 },
3217 gridLines: {
3218 circular: true
3219 },
3220 pointLabels: {
3221 display: false
3222 },
3223 ticks: {
3224 beginAtZero: true
3225 }
3226 },
3227
3228 // Boolean - Whether to animate the rotation of the chart
3229 animation: {
3230 animateRotate: true,
3231 animateScale: true
3232 },
3233
3234 startAngle: -0.5 * Math.PI,
3235 legendCallback: function(chart) {
3236 var text = [];
3237 text.push('<ul class="' + chart.id + '-legend">');
3238
3239 var data = chart.data;
3240 var datasets = data.datasets;
3241 var labels = data.labels;
3242
3243 if (datasets.length) {
3244 for (var i = 0; i < datasets[0].data.length; ++i) {
3245 text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
3246 if (labels[i]) {
3247 text.push(labels[i]);
3248 }
3249 text.push('</li>');
3250 }
3251 }
3252
3253 text.push('</ul>');
3254 return text.join('');
3255 },
3256 legend: {
3257 labels: {
3258 generateLabels: function(chart) {
3259 var data = chart.data;
3260 if (data.labels.length && data.datasets.length) {
3261 return data.labels.map(function(label, i) {
3262 var meta = chart.getDatasetMeta(0);
3263 var ds = data.datasets[0];
3264 var arc = meta.data[i];
3265 var custom = arc.custom || {};
3266 var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
3267 var arcOpts = chart.options.elements.arc;
3268 var fill = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
3269 var stroke = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
3270 var bw = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
3271
3272 return {
3273 text: label,
3274 fillStyle: fill,
3275 strokeStyle: stroke,
3276 lineWidth: bw,
3277 hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
3278
3279 // Extra data used for toggling the correct item
3280 index: i
3281 };
3282 });
3283 }
3284 return [];
3285 }
3286 },
3287
3288 onClick: function(e, legendItem) {
3289 var index = legendItem.index;
3290 var chart = this.chart;
3291 var i, ilen, meta;
3292
3293 for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
3294 meta = chart.getDatasetMeta(i);
3295 meta.data[index].hidden = !meta.data[index].hidden;
3296 }
3297
3298 chart.update();
3299 }
3300 },
3301
3302 // Need to override these to give a nice default
3303 tooltips: {
3304 callbacks: {
3305 title: function() {
3306 return '';
3307 },
3308 label: function(item, data) {
3309 return data.labels[item.index] + ': ' + item.yLabel;
3310 }
3311 }
3312 }
3313});
3314
3315module.exports = function(Chart) {
3316
3317 Chart.controllers.polarArea = Chart.DatasetController.extend({
3318
3319 dataElementType: elements.Arc,
3320
3321 linkScales: helpers.noop,
3322
3323 update: function(reset) {
3324 var me = this;
3325 var chart = me.chart;
3326 var chartArea = chart.chartArea;
3327 var meta = me.getMeta();
3328 var opts = chart.options;
3329 var arcOpts = opts.elements.arc;
3330 var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
3331 chart.outerRadius = Math.max((minSize - arcOpts.borderWidth / 2) / 2, 0);
3332 chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
3333 chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
3334
3335 me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
3336 me.innerRadius = me.outerRadius - chart.radiusLength;
3337
3338 meta.count = me.countVisibleElements();
3339
3340 helpers.each(meta.data, function(arc, index) {
3341 me.updateElement(arc, index, reset);
3342 });
3343 },
3344
3345 updateElement: function(arc, index, reset) {
3346 var me = this;
3347 var chart = me.chart;
3348 var dataset = me.getDataset();
3349 var opts = chart.options;
3350 var animationOpts = opts.animation;
3351 var scale = chart.scale;
3352 var labels = chart.data.labels;
3353
3354 var circumference = me.calculateCircumference(dataset.data[index]);
3355 var centerX = scale.xCenter;
3356 var centerY = scale.yCenter;
3357
3358 // If there is NaN data before us, we need to calculate the starting angle correctly.
3359 // We could be way more efficient here, but its unlikely that the polar area chart will have a lot of data
3360 var visibleCount = 0;
3361 var meta = me.getMeta();
3362 for (var i = 0; i < index; ++i) {
3363 if (!isNaN(dataset.data[i]) && !meta.data[i].hidden) {
3364 ++visibleCount;
3365 }
3366 }
3367
3368 // var negHalfPI = -0.5 * Math.PI;
3369 var datasetStartAngle = opts.startAngle;
3370 var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
3371 var startAngle = datasetStartAngle + (circumference * visibleCount);
3372 var endAngle = startAngle + (arc.hidden ? 0 : circumference);
3373
3374 var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
3375
3376 helpers.extend(arc, {
3377 // Utility
3378 _datasetIndex: me.index,
3379 _index: index,
3380 _scale: scale,
3381
3382 // Desired view properties
3383 _model: {
3384 x: centerX,
3385 y: centerY,
3386 innerRadius: 0,
3387 outerRadius: reset ? resetRadius : distance,
3388 startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
3389 endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
3390 label: helpers.valueAtIndexOrDefault(labels, index, labels[index])
3391 }
3392 });
3393
3394 // Apply border and fill style
3395 me.removeHoverStyle(arc);
3396
3397 arc.pivot();
3398 },
3399
3400 removeHoverStyle: function(arc) {
3401 Chart.DatasetController.prototype.removeHoverStyle.call(this, arc, this.chart.options.elements.arc);
3402 },
3403
3404 countVisibleElements: function() {
3405 var dataset = this.getDataset();
3406 var meta = this.getMeta();
3407 var count = 0;
3408
3409 helpers.each(meta.data, function(element, index) {
3410 if (!isNaN(dataset.data[index]) && !element.hidden) {
3411 count++;
3412 }
3413 });
3414
3415 return count;
3416 },
3417
3418 calculateCircumference: function(value) {
3419 var count = this.getMeta().count;
3420 if (count > 0 && !isNaN(value)) {
3421 return (2 * Math.PI) / count;
3422 }
3423 return 0;
3424 }
3425 });
3426};
3427
3428},{"25":25,"40":40,"45":45}],20:[function(require,module,exports){
3429'use strict';
3430
3431var defaults = require(25);
3432var elements = require(40);
3433var helpers = require(45);
3434
3435defaults._set('radar', {
3436 scale: {
3437 type: 'radialLinear'
3438 },
3439 elements: {
3440 line: {
3441 tension: 0 // no bezier in radar
3442 }
3443 }
3444});
3445
3446module.exports = function(Chart) {
3447
3448 Chart.controllers.radar = Chart.DatasetController.extend({
3449
3450 datasetElementType: elements.Line,
3451
3452 dataElementType: elements.Point,
3453
3454 linkScales: helpers.noop,
3455
3456 update: function(reset) {
3457 var me = this;
3458 var meta = me.getMeta();
3459 var line = meta.dataset;
3460 var points = meta.data;
3461 var custom = line.custom || {};
3462 var dataset = me.getDataset();
3463 var lineElementOptions = me.chart.options.elements.line;
3464 var scale = me.chart.scale;
3465
3466 // Compatibility: If the properties are defined with only the old name, use those values
3467 if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
3468 dataset.lineTension = dataset.tension;
3469 }
3470
3471 helpers.extend(meta.dataset, {
3472 // Utility
3473 _datasetIndex: me.index,
3474 _scale: scale,
3475 // Data
3476 _children: points,
3477 _loop: true,
3478 // Model
3479 _model: {
3480 // Appearance
3481 tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension),
3482 backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),
3483 borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),
3484 borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),
3485 fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),
3486 borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),
3487 borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),
3488 borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),
3489 borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),
3490 }
3491 });
3492
3493 meta.dataset.pivot();
3494
3495 // Update Points
3496 helpers.each(points, function(point, index) {
3497 me.updateElement(point, index, reset);
3498 }, me);
3499
3500 // Update bezier control points
3501 me.updateBezierControlPoints();
3502 },
3503 updateElement: function(point, index, reset) {
3504 var me = this;
3505 var custom = point.custom || {};
3506 var dataset = me.getDataset();
3507 var scale = me.chart.scale;
3508 var pointElementOptions = me.chart.options.elements.point;
3509 var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
3510
3511 // Compatibility: If the properties are defined with only the old name, use those values
3512 if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
3513 dataset.pointRadius = dataset.radius;
3514 }
3515 if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {
3516 dataset.pointHitRadius = dataset.hitRadius;
3517 }
3518
3519 helpers.extend(point, {
3520 // Utility
3521 _datasetIndex: me.index,
3522 _index: index,
3523 _scale: scale,
3524
3525 // Desired view properties
3526 _model: {
3527 x: reset ? scale.xCenter : pointPosition.x, // value not used in dataset scale, but we want a consistent API between scales
3528 y: reset ? scale.yCenter : pointPosition.y,
3529
3530 // Appearance
3531 tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, me.chart.options.elements.line.tension),
3532 radius: custom.radius ? custom.radius : helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius),
3533 backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor),
3534 borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor),
3535 borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth),
3536 pointStyle: custom.pointStyle ? custom.pointStyle : helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointElementOptions.pointStyle),
3537
3538 // Tooltip
3539 hitRadius: custom.hitRadius ? custom.hitRadius : helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointElementOptions.hitRadius)
3540 }
3541 });
3542
3543 point._model.skip = custom.skip ? custom.skip : (isNaN(point._model.x) || isNaN(point._model.y));
3544 },
3545 updateBezierControlPoints: function() {
3546 var chartArea = this.chart.chartArea;
3547 var meta = this.getMeta();
3548
3549 helpers.each(meta.data, function(point, index) {
3550 var model = point._model;
3551 var controlPoints = helpers.splineCurve(
3552 helpers.previousItem(meta.data, index, true)._model,
3553 model,
3554 helpers.nextItem(meta.data, index, true)._model,
3555 model.tension
3556 );
3557
3558 // Prevent the bezier going outside of the bounds of the graph
3559 model.controlPointPreviousX = Math.max(Math.min(controlPoints.previous.x, chartArea.right), chartArea.left);
3560 model.controlPointPreviousY = Math.max(Math.min(controlPoints.previous.y, chartArea.bottom), chartArea.top);
3561
3562 model.controlPointNextX = Math.max(Math.min(controlPoints.next.x, chartArea.right), chartArea.left);
3563 model.controlPointNextY = Math.max(Math.min(controlPoints.next.y, chartArea.bottom), chartArea.top);
3564
3565 // Now pivot the point for animation
3566 point.pivot();
3567 });
3568 },
3569
3570 setHoverStyle: function(point) {
3571 // Point
3572 var dataset = this.chart.data.datasets[point._datasetIndex];
3573 var custom = point.custom || {};
3574 var index = point._index;
3575 var model = point._model;
3576
3577 model.radius = custom.hoverRadius ? custom.hoverRadius : helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);
3578 model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
3579 model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));
3580 model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);
3581 },
3582
3583 removeHoverStyle: function(point) {
3584 var dataset = this.chart.data.datasets[point._datasetIndex];
3585 var custom = point.custom || {};
3586 var index = point._index;
3587 var model = point._model;
3588 var pointElementOptions = this.chart.options.elements.point;
3589
3590 model.radius = custom.radius ? custom.radius : helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius);
3591 model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor);
3592 model.borderColor = custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor);
3593 model.borderWidth = custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth);
3594 }
3595 });
3596};
3597
3598},{"25":25,"40":40,"45":45}],21:[function(require,module,exports){
3599'use strict';
3600
3601var defaults = require(25);
3602
3603defaults._set('scatter', {
3604 hover: {
3605 mode: 'single'
3606 },
3607
3608 scales: {
3609 xAxes: [{
3610 id: 'x-axis-1', // need an ID so datasets can reference the scale
3611 type: 'linear', // scatter should not use a category axis
3612 position: 'bottom'
3613 }],
3614 yAxes: [{
3615 id: 'y-axis-1',
3616 type: 'linear',
3617 position: 'left'
3618 }]
3619 },
3620
3621 showLines: false,
3622
3623 tooltips: {
3624 callbacks: {
3625 title: function() {
3626 return ''; // doesn't make sense for scatter since data are formatted as a point
3627 },
3628 label: function(item) {
3629 return '(' + item.xLabel + ', ' + item.yLabel + ')';
3630 }
3631 }
3632 }
3633});
3634
3635module.exports = function(Chart) {
3636
3637 // Scatter charts use line controllers
3638 Chart.controllers.scatter = Chart.controllers.line;
3639
3640};
3641
3642},{"25":25}],22:[function(require,module,exports){
3643/* global window: false */
3644'use strict';
3645
3646var defaults = require(25);
3647var Element = require(26);
3648var helpers = require(45);
3649
3650defaults._set('global', {
3651 animation: {
3652 duration: 1000,
3653 easing: 'easeOutQuart',
3654 onProgress: helpers.noop,
3655 onComplete: helpers.noop
3656 }
3657});
3658
3659module.exports = function(Chart) {
3660
3661 Chart.Animation = Element.extend({
3662 chart: null, // the animation associated chart instance
3663 currentStep: 0, // the current animation step
3664 numSteps: 60, // default number of steps
3665 easing: '', // the easing to use for this animation
3666 render: null, // render function used by the animation service
3667
3668 onAnimationProgress: null, // user specified callback to fire on each step of the animation
3669 onAnimationComplete: null, // user specified callback to fire when the animation finishes
3670 });
3671
3672 Chart.animationService = {
3673 frameDuration: 17,
3674 animations: [],
3675 dropFrames: 0,
3676 request: null,
3677
3678 /**
3679 * @param {Chart} chart - The chart to animate.
3680 * @param {Chart.Animation} animation - The animation that we will animate.
3681 * @param {Number} duration - The animation duration in ms.
3682 * @param {Boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
3683 */
3684 addAnimation: function(chart, animation, duration, lazy) {
3685 var animations = this.animations;
3686 var i, ilen;
3687
3688 animation.chart = chart;
3689
3690 if (!lazy) {
3691 chart.animating = true;
3692 }
3693
3694 for (i = 0, ilen = animations.length; i < ilen; ++i) {
3695 if (animations[i].chart === chart) {
3696 animations[i] = animation;
3697 return;
3698 }
3699 }
3700
3701 animations.push(animation);
3702
3703 // If there are no animations queued, manually kickstart a digest, for lack of a better word
3704 if (animations.length === 1) {
3705 this.requestAnimationFrame();
3706 }
3707 },
3708
3709 cancelAnimation: function(chart) {
3710 var index = helpers.findIndex(this.animations, function(animation) {
3711 return animation.chart === chart;
3712 });
3713
3714 if (index !== -1) {
3715 this.animations.splice(index, 1);
3716 chart.animating = false;
3717 }
3718 },
3719
3720 requestAnimationFrame: function() {
3721 var me = this;
3722 if (me.request === null) {
3723 // Skip animation frame requests until the active one is executed.
3724 // This can happen when processing mouse events, e.g. 'mousemove'
3725 // and 'mouseout' events will trigger multiple renders.
3726 me.request = helpers.requestAnimFrame.call(window, function() {
3727 me.request = null;
3728 me.startDigest();
3729 });
3730 }
3731 },
3732
3733 /**
3734 * @private
3735 */
3736 startDigest: function() {
3737 var me = this;
3738 var startTime = Date.now();
3739 var framesToDrop = 0;
3740
3741 if (me.dropFrames > 1) {
3742 framesToDrop = Math.floor(me.dropFrames);
3743 me.dropFrames = me.dropFrames % 1;
3744 }
3745
3746 me.advance(1 + framesToDrop);
3747
3748 var endTime = Date.now();
3749
3750 me.dropFrames += (endTime - startTime) / me.frameDuration;
3751
3752 // Do we have more stuff to animate?
3753 if (me.animations.length > 0) {
3754 me.requestAnimationFrame();
3755 }
3756 },
3757
3758 /**
3759 * @private
3760 */
3761 advance: function(count) {
3762 var animations = this.animations;
3763 var animation, chart;
3764 var i = 0;
3765
3766 while (i < animations.length) {
3767 animation = animations[i];
3768 chart = animation.chart;
3769
3770 animation.currentStep = (animation.currentStep || 0) + count;
3771 animation.currentStep = Math.min(animation.currentStep, animation.numSteps);
3772
3773 helpers.callback(animation.render, [chart, animation], chart);
3774 helpers.callback(animation.onAnimationProgress, [animation], chart);
3775
3776 if (animation.currentStep >= animation.numSteps) {
3777 helpers.callback(animation.onAnimationComplete, [animation], chart);
3778 chart.animating = false;
3779 animations.splice(i, 1);
3780 } else {
3781 ++i;
3782 }
3783 }
3784 }
3785 };
3786
3787 /**
3788 * Provided for backward compatibility, use Chart.Animation instead
3789 * @prop Chart.Animation#animationObject
3790 * @deprecated since version 2.6.0
3791 * @todo remove at version 3
3792 */
3793 Object.defineProperty(Chart.Animation.prototype, 'animationObject', {
3794 get: function() {
3795 return this;
3796 }
3797 });
3798
3799 /**
3800 * Provided for backward compatibility, use Chart.Animation#chart instead
3801 * @prop Chart.Animation#chartInstance
3802 * @deprecated since version 2.6.0
3803 * @todo remove at version 3
3804 */
3805 Object.defineProperty(Chart.Animation.prototype, 'chartInstance', {
3806 get: function() {
3807 return this.chart;
3808 },
3809 set: function(value) {
3810 this.chart = value;
3811 }
3812 });
3813
3814};
3815
3816},{"25":25,"26":26,"45":45}],23:[function(require,module,exports){
3817'use strict';
3818
3819var defaults = require(25);
3820var helpers = require(45);
3821var Interaction = require(28);
3822var layouts = require(30);
3823var platform = require(48);
3824var plugins = require(31);
3825
3826module.exports = function(Chart) {
3827
3828 // Create a dictionary of chart types, to allow for extension of existing types
3829 Chart.types = {};
3830
3831 // Store a reference to each instance - allowing us to globally resize chart instances on window resize.
3832 // Destroy method on the chart will remove the instance of the chart from this reference.
3833 Chart.instances = {};
3834
3835 // Controllers available for dataset visualization eg. bar, line, slice, etc.
3836 Chart.controllers = {};
3837
3838 /**
3839 * Initializes the given config with global and chart default values.
3840 */
3841 function initConfig(config) {
3842 config = config || {};
3843
3844 // Do NOT use configMerge() for the data object because this method merges arrays
3845 // and so would change references to labels and datasets, preventing data updates.
3846 var data = config.data = config.data || {};
3847 data.datasets = data.datasets || [];
3848 data.labels = data.labels || [];
3849
3850 config.options = helpers.configMerge(
3851 defaults.global,
3852 defaults[config.type],
3853 config.options || {});
3854
3855 return config;
3856 }
3857
3858 /**
3859 * Updates the config of the chart
3860 * @param chart {Chart} chart to update the options for
3861 */
3862 function updateConfig(chart) {
3863 var newOptions = chart.options;
3864
3865 helpers.each(chart.scales, function(scale) {
3866 layouts.removeBox(chart, scale);
3867 });
3868
3869 newOptions = helpers.configMerge(
3870 Chart.defaults.global,
3871 Chart.defaults[chart.config.type],
3872 newOptions);
3873
3874 chart.options = chart.config.options = newOptions;
3875 chart.ensureScalesHaveIDs();
3876 chart.buildOrUpdateScales();
3877 // Tooltip
3878 chart.tooltip._options = newOptions.tooltips;
3879 chart.tooltip.initialize();
3880 }
3881
3882 function positionIsHorizontal(position) {
3883 return position === 'top' || position === 'bottom';
3884 }
3885
3886 helpers.extend(Chart.prototype, /** @lends Chart */ {
3887 /**
3888 * @private
3889 */
3890 construct: function(item, config) {
3891 var me = this;
3892
3893 config = initConfig(config);
3894
3895 var context = platform.acquireContext(item, config);
3896 var canvas = context && context.canvas;
3897 var height = canvas && canvas.height;
3898 var width = canvas && canvas.width;
3899
3900 me.id = helpers.uid();
3901 me.ctx = context;
3902 me.canvas = canvas;
3903 me.config = config;
3904 me.width = width;
3905 me.height = height;
3906 me.aspectRatio = height ? width / height : null;
3907 me.options = config.options;
3908 me._bufferedRender = false;
3909
3910 /**
3911 * Provided for backward compatibility, Chart and Chart.Controller have been merged,
3912 * the "instance" still need to be defined since it might be called from plugins.
3913 * @prop Chart#chart
3914 * @deprecated since version 2.6.0
3915 * @todo remove at version 3
3916 * @private
3917 */
3918 me.chart = me;
3919 me.controller = me; // chart.chart.controller #inception
3920
3921 // Add the chart instance to the global namespace
3922 Chart.instances[me.id] = me;
3923
3924 // Define alias to the config data: `chart.data === chart.config.data`
3925 Object.defineProperty(me, 'data', {
3926 get: function() {
3927 return me.config.data;
3928 },
3929 set: function(value) {
3930 me.config.data = value;
3931 }
3932 });
3933
3934 if (!context || !canvas) {
3935 // The given item is not a compatible context2d element, let's return before finalizing
3936 // the chart initialization but after setting basic chart / controller properties that
3937 // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
3938 // https://github.com/chartjs/Chart.js/issues/2807
3939 console.error("Failed to create chart: can't acquire context from the given item");
3940 return;
3941 }
3942
3943 me.initialize();
3944 me.update();
3945 },
3946
3947 /**
3948 * @private
3949 */
3950 initialize: function() {
3951 var me = this;
3952
3953 // Before init plugin notification
3954 plugins.notify(me, 'beforeInit');
3955
3956 helpers.retinaScale(me, me.options.devicePixelRatio);
3957
3958 me.bindEvents();
3959
3960 if (me.options.responsive) {
3961 // Initial resize before chart draws (must be silent to preserve initial animations).
3962 me.resize(true);
3963 }
3964
3965 // Make sure scales have IDs and are built before we build any controllers.
3966 me.ensureScalesHaveIDs();
3967 me.buildOrUpdateScales();
3968 me.initToolTip();
3969
3970 // After init plugin notification
3971 plugins.notify(me, 'afterInit');
3972
3973 return me;
3974 },
3975
3976 clear: function() {
3977 helpers.canvas.clear(this);
3978 return this;
3979 },
3980
3981 stop: function() {
3982 // Stops any current animation loop occurring
3983 Chart.animationService.cancelAnimation(this);
3984 return this;
3985 },
3986
3987 resize: function(silent) {
3988 var me = this;
3989 var options = me.options;
3990 var canvas = me.canvas;
3991 var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
3992
3993 // the canvas render width and height will be casted to integers so make sure that
3994 // the canvas display style uses the same integer values to avoid blurring effect.
3995
3996 // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collased
3997 var newWidth = Math.max(0, Math.floor(helpers.getMaximumWidth(canvas)));
3998 var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers.getMaximumHeight(canvas)));
3999
4000 if (me.width === newWidth && me.height === newHeight) {
4001 return;
4002 }
4003
4004 canvas.width = me.width = newWidth;
4005 canvas.height = me.height = newHeight;
4006 canvas.style.width = newWidth + 'px';
4007 canvas.style.height = newHeight + 'px';
4008
4009 helpers.retinaScale(me, options.devicePixelRatio);
4010
4011 if (!silent) {
4012 // Notify any plugins about the resize
4013 var newSize = {width: newWidth, height: newHeight};
4014 plugins.notify(me, 'resize', [newSize]);
4015
4016 // Notify of resize
4017 if (me.options.onResize) {
4018 me.options.onResize(me, newSize);
4019 }
4020
4021 me.stop();
4022 me.update(me.options.responsiveAnimationDuration);
4023 }
4024 },
4025
4026 ensureScalesHaveIDs: function() {
4027 var options = this.options;
4028 var scalesOptions = options.scales || {};
4029 var scaleOptions = options.scale;
4030
4031 helpers.each(scalesOptions.xAxes, function(xAxisOptions, index) {
4032 xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index);
4033 });
4034
4035 helpers.each(scalesOptions.yAxes, function(yAxisOptions, index) {
4036 yAxisOptions.id = yAxisOptions.id || ('y-axis-' + index);
4037 });
4038
4039 if (scaleOptions) {
4040 scaleOptions.id = scaleOptions.id || 'scale';
4041 }
4042 },
4043
4044 /**
4045 * Builds a map of scale ID to scale object for future lookup.
4046 */
4047 buildOrUpdateScales: function() {
4048 var me = this;
4049 var options = me.options;
4050 var scales = me.scales || {};
4051 var items = [];
4052 var updated = Object.keys(scales).reduce(function(obj, id) {
4053 obj[id] = false;
4054 return obj;
4055 }, {});
4056
4057 if (options.scales) {
4058 items = items.concat(
4059 (options.scales.xAxes || []).map(function(xAxisOptions) {
4060 return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
4061 }),
4062 (options.scales.yAxes || []).map(function(yAxisOptions) {
4063 return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
4064 })
4065 );
4066 }
4067
4068 if (options.scale) {
4069 items.push({
4070 options: options.scale,
4071 dtype: 'radialLinear',
4072 isDefault: true,
4073 dposition: 'chartArea'
4074 });
4075 }
4076
4077 helpers.each(items, function(item) {
4078 var scaleOptions = item.options;
4079 var id = scaleOptions.id;
4080 var scaleType = helpers.valueOrDefault(scaleOptions.type, item.dtype);
4081
4082 if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
4083 scaleOptions.position = item.dposition;
4084 }
4085
4086 updated[id] = true;
4087 var scale = null;
4088 if (id in scales && scales[id].type === scaleType) {
4089 scale = scales[id];
4090 scale.options = scaleOptions;
4091 scale.ctx = me.ctx;
4092 scale.chart = me;
4093 } else {
4094 var scaleClass = Chart.scaleService.getScaleConstructor(scaleType);
4095 if (!scaleClass) {
4096 return;
4097 }
4098 scale = new scaleClass({
4099 id: id,
4100 type: scaleType,
4101 options: scaleOptions,
4102 ctx: me.ctx,
4103 chart: me
4104 });
4105 scales[scale.id] = scale;
4106 }
4107
4108 scale.mergeTicksOptions();
4109
4110 // TODO(SB): I think we should be able to remove this custom case (options.scale)
4111 // and consider it as a regular scale part of the "scales"" map only! This would
4112 // make the logic easier and remove some useless? custom code.
4113 if (item.isDefault) {
4114 me.scale = scale;
4115 }
4116 });
4117 // clear up discarded scales
4118 helpers.each(updated, function(hasUpdated, id) {
4119 if (!hasUpdated) {
4120 delete scales[id];
4121 }
4122 });
4123
4124 me.scales = scales;
4125
4126 Chart.scaleService.addScalesToLayout(this);
4127 },
4128
4129 buildOrUpdateControllers: function() {
4130 var me = this;
4131 var types = [];
4132 var newControllers = [];
4133
4134 helpers.each(me.data.datasets, function(dataset, datasetIndex) {
4135 var meta = me.getDatasetMeta(datasetIndex);
4136 var type = dataset.type || me.config.type;
4137
4138 if (meta.type && meta.type !== type) {
4139 me.destroyDatasetMeta(datasetIndex);
4140 meta = me.getDatasetMeta(datasetIndex);
4141 }
4142 meta.type = type;
4143
4144 types.push(meta.type);
4145
4146 if (meta.controller) {
4147 meta.controller.updateIndex(datasetIndex);
4148 meta.controller.linkScales();
4149 } else {
4150 var ControllerClass = Chart.controllers[meta.type];
4151 if (ControllerClass === undefined) {
4152 throw new Error('"' + meta.type + '" is not a chart type.');
4153 }
4154
4155 meta.controller = new ControllerClass(me, datasetIndex);
4156 newControllers.push(meta.controller);
4157 }
4158 }, me);
4159
4160 return newControllers;
4161 },
4162
4163 /**
4164 * Reset the elements of all datasets
4165 * @private
4166 */
4167 resetElements: function() {
4168 var me = this;
4169 helpers.each(me.data.datasets, function(dataset, datasetIndex) {
4170 me.getDatasetMeta(datasetIndex).controller.reset();
4171 }, me);
4172 },
4173
4174 /**
4175 * Resets the chart back to it's state before the initial animation
4176 */
4177 reset: function() {
4178 this.resetElements();
4179 this.tooltip.initialize();
4180 },
4181
4182 update: function(config) {
4183 var me = this;
4184
4185 if (!config || typeof config !== 'object') {
4186 // backwards compatibility
4187 config = {
4188 duration: config,
4189 lazy: arguments[1]
4190 };
4191 }
4192
4193 updateConfig(me);
4194
4195 // plugins options references might have change, let's invalidate the cache
4196 // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
4197 plugins._invalidate(me);
4198
4199 if (plugins.notify(me, 'beforeUpdate') === false) {
4200 return;
4201 }
4202
4203 // In case the entire data object changed
4204 me.tooltip._data = me.data;
4205
4206 // Make sure dataset controllers are updated and new controllers are reset
4207 var newControllers = me.buildOrUpdateControllers();
4208
4209 // Make sure all dataset controllers have correct meta data counts
4210 helpers.each(me.data.datasets, function(dataset, datasetIndex) {
4211 me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements();
4212 }, me);
4213
4214 me.updateLayout();
4215
4216 // Can only reset the new controllers after the scales have been updated
4217 if (me.options.animation && me.options.animation.duration) {
4218 helpers.each(newControllers, function(controller) {
4219 controller.reset();
4220 });
4221 }
4222
4223 me.updateDatasets();
4224
4225 // Need to reset tooltip in case it is displayed with elements that are removed
4226 // after update.
4227 me.tooltip.initialize();
4228
4229 // Last active contains items that were previously in the tooltip.
4230 // When we reset the tooltip, we need to clear it
4231 me.lastActive = [];
4232
4233 // Do this before render so that any plugins that need final scale updates can use it
4234 plugins.notify(me, 'afterUpdate');
4235
4236 if (me._bufferedRender) {
4237 me._bufferedRequest = {
4238 duration: config.duration,
4239 easing: config.easing,
4240 lazy: config.lazy
4241 };
4242 } else {
4243 me.render(config);
4244 }
4245 },
4246
4247 /**
4248 * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
4249 * hook, in which case, plugins will not be called on `afterLayout`.
4250 * @private
4251 */
4252 updateLayout: function() {
4253 var me = this;
4254
4255 if (plugins.notify(me, 'beforeLayout') === false) {
4256 return;
4257 }
4258
4259 layouts.update(this, this.width, this.height);
4260
4261 /**
4262 * Provided for backward compatibility, use `afterLayout` instead.
4263 * @method IPlugin#afterScaleUpdate
4264 * @deprecated since version 2.5.0
4265 * @todo remove at version 3
4266 * @private
4267 */
4268 plugins.notify(me, 'afterScaleUpdate');
4269 plugins.notify(me, 'afterLayout');
4270 },
4271
4272 /**
4273 * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
4274 * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
4275 * @private
4276 */
4277 updateDatasets: function() {
4278 var me = this;
4279
4280 if (plugins.notify(me, 'beforeDatasetsUpdate') === false) {
4281 return;
4282 }
4283
4284 for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
4285 me.updateDataset(i);
4286 }
4287
4288 plugins.notify(me, 'afterDatasetsUpdate');
4289 },
4290
4291 /**
4292 * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
4293 * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
4294 * @private
4295 */
4296 updateDataset: function(index) {
4297 var me = this;
4298 var meta = me.getDatasetMeta(index);
4299 var args = {
4300 meta: meta,
4301 index: index
4302 };
4303
4304 if (plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
4305 return;
4306 }
4307
4308 meta.controller.update();
4309
4310 plugins.notify(me, 'afterDatasetUpdate', [args]);
4311 },
4312
4313 render: function(config) {
4314 var me = this;
4315
4316 if (!config || typeof config !== 'object') {
4317 // backwards compatibility
4318 config = {
4319 duration: config,
4320 lazy: arguments[1]
4321 };
4322 }
4323
4324 var duration = config.duration;
4325 var lazy = config.lazy;
4326
4327 if (plugins.notify(me, 'beforeRender') === false) {
4328 return;
4329 }
4330
4331 var animationOptions = me.options.animation;
4332 var onComplete = function(animation) {
4333 plugins.notify(me, 'afterRender');
4334 helpers.callback(animationOptions && animationOptions.onComplete, [animation], me);
4335 };
4336
4337 if (animationOptions && ((typeof duration !== 'undefined' && duration !== 0) || (typeof duration === 'undefined' && animationOptions.duration !== 0))) {
4338 var animation = new Chart.Animation({
4339 numSteps: (duration || animationOptions.duration) / 16.66, // 60 fps
4340 easing: config.easing || animationOptions.easing,
4341
4342 render: function(chart, animationObject) {
4343 var easingFunction = helpers.easing.effects[animationObject.easing];
4344 var currentStep = animationObject.currentStep;
4345 var stepDecimal = currentStep / animationObject.numSteps;
4346
4347 chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
4348 },
4349
4350 onAnimationProgress: animationOptions.onProgress,
4351 onAnimationComplete: onComplete
4352 });
4353
4354 Chart.animationService.addAnimation(me, animation, duration, lazy);
4355 } else {
4356 me.draw();
4357
4358 // See https://github.com/chartjs/Chart.js/issues/3781
4359 onComplete(new Chart.Animation({numSteps: 0, chart: me}));
4360 }
4361
4362 return me;
4363 },
4364
4365 draw: function(easingValue) {
4366 var me = this;
4367
4368 me.clear();
4369
4370 if (helpers.isNullOrUndef(easingValue)) {
4371 easingValue = 1;
4372 }
4373
4374 me.transition(easingValue);
4375
4376 if (plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
4377 return;
4378 }
4379
4380 // Draw all the scales
4381 helpers.each(me.boxes, function(box) {
4382 box.draw(me.chartArea);
4383 }, me);
4384
4385 if (me.scale) {
4386 me.scale.draw();
4387 }
4388
4389 me.drawDatasets(easingValue);
4390 me._drawTooltip(easingValue);
4391
4392 plugins.notify(me, 'afterDraw', [easingValue]);
4393 },
4394
4395 /**
4396 * @private
4397 */
4398 transition: function(easingValue) {
4399 var me = this;
4400
4401 for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
4402 if (me.isDatasetVisible(i)) {
4403 me.getDatasetMeta(i).controller.transition(easingValue);
4404 }
4405 }
4406
4407 me.tooltip.transition(easingValue);
4408 },
4409
4410 /**
4411 * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
4412 * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
4413 * @private
4414 */
4415 drawDatasets: function(easingValue) {
4416 var me = this;
4417
4418 if (plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
4419 return;
4420 }
4421
4422 // Draw datasets reversed to support proper line stacking
4423 for (var i = (me.data.datasets || []).length - 1; i >= 0; --i) {
4424 if (me.isDatasetVisible(i)) {
4425 me.drawDataset(i, easingValue);
4426 }
4427 }
4428
4429 plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
4430 },
4431
4432 /**
4433 * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
4434 * hook, in which case, plugins will not be called on `afterDatasetDraw`.
4435 * @private
4436 */
4437 drawDataset: function(index, easingValue) {
4438 var me = this;
4439 var meta = me.getDatasetMeta(index);
4440 var args = {
4441 meta: meta,
4442 index: index,
4443 easingValue: easingValue
4444 };
4445
4446 if (plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
4447 return;
4448 }
4449
4450 meta.controller.draw(easingValue);
4451
4452 plugins.notify(me, 'afterDatasetDraw', [args]);
4453 },
4454
4455 /**
4456 * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
4457 * hook, in which case, plugins will not be called on `afterTooltipDraw`.
4458 * @private
4459 */
4460 _drawTooltip: function(easingValue) {
4461 var me = this;
4462 var tooltip = me.tooltip;
4463 var args = {
4464 tooltip: tooltip,
4465 easingValue: easingValue
4466 };
4467
4468 if (plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
4469 return;
4470 }
4471
4472 tooltip.draw();
4473
4474 plugins.notify(me, 'afterTooltipDraw', [args]);
4475 },
4476
4477 // Get the single element that was clicked on
4478 // @return : An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
4479 getElementAtEvent: function(e) {
4480 return Interaction.modes.single(this, e);
4481 },
4482
4483 getElementsAtEvent: function(e) {
4484 return Interaction.modes.label(this, e, {intersect: true});
4485 },
4486
4487 getElementsAtXAxis: function(e) {
4488 return Interaction.modes['x-axis'](this, e, {intersect: true});
4489 },
4490
4491 getElementsAtEventForMode: function(e, mode, options) {
4492 var method = Interaction.modes[mode];
4493 if (typeof method === 'function') {
4494 return method(this, e, options);
4495 }
4496
4497 return [];
4498 },
4499
4500 getDatasetAtEvent: function(e) {
4501 return Interaction.modes.dataset(this, e, {intersect: true});
4502 },
4503
4504 getDatasetMeta: function(datasetIndex) {
4505 var me = this;
4506 var dataset = me.data.datasets[datasetIndex];
4507 if (!dataset._meta) {
4508 dataset._meta = {};
4509 }
4510
4511 var meta = dataset._meta[me.id];
4512 if (!meta) {
4513 meta = dataset._meta[me.id] = {
4514 type: null,
4515 data: [],
4516 dataset: null,
4517 controller: null,
4518 hidden: null, // See isDatasetVisible() comment
4519 xAxisID: null,
4520 yAxisID: null
4521 };
4522 }
4523
4524 return meta;
4525 },
4526
4527 getVisibleDatasetCount: function() {
4528 var count = 0;
4529 for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
4530 if (this.isDatasetVisible(i)) {
4531 count++;
4532 }
4533 }
4534 return count;
4535 },
4536
4537 isDatasetVisible: function(datasetIndex) {
4538 var meta = this.getDatasetMeta(datasetIndex);
4539
4540 // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
4541 // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
4542 return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
4543 },
4544
4545 generateLegend: function() {
4546 return this.options.legendCallback(this);
4547 },
4548
4549 /**
4550 * @private
4551 */
4552 destroyDatasetMeta: function(datasetIndex) {
4553 var id = this.id;
4554 var dataset = this.data.datasets[datasetIndex];
4555 var meta = dataset._meta && dataset._meta[id];
4556
4557 if (meta) {
4558 meta.controller.destroy();
4559 delete dataset._meta[id];
4560 }
4561 },
4562
4563 destroy: function() {
4564 var me = this;
4565 var canvas = me.canvas;
4566 var i, ilen;
4567
4568 me.stop();
4569
4570 // dataset controllers need to cleanup associated data
4571 for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
4572 me.destroyDatasetMeta(i);
4573 }
4574
4575 if (canvas) {
4576 me.unbindEvents();
4577 helpers.canvas.clear(me);
4578 platform.releaseContext(me.ctx);
4579 me.canvas = null;
4580 me.ctx = null;
4581 }
4582
4583 plugins.notify(me, 'destroy');
4584
4585 delete Chart.instances[me.id];
4586 },
4587
4588 toBase64Image: function() {
4589 return this.canvas.toDataURL.apply(this.canvas, arguments);
4590 },
4591
4592 initToolTip: function() {
4593 var me = this;
4594 me.tooltip = new Chart.Tooltip({
4595 _chart: me,
4596 _chartInstance: me, // deprecated, backward compatibility
4597 _data: me.data,
4598 _options: me.options.tooltips
4599 }, me);
4600 },
4601
4602 /**
4603 * @private
4604 */
4605 bindEvents: function() {
4606 var me = this;
4607 var listeners = me._listeners = {};
4608 var listener = function() {
4609 me.eventHandler.apply(me, arguments);
4610 };
4611
4612 helpers.each(me.options.events, function(type) {
4613 platform.addEventListener(me, type, listener);
4614 listeners[type] = listener;
4615 });
4616
4617 // Elements used to detect size change should not be injected for non responsive charts.
4618 // See https://github.com/chartjs/Chart.js/issues/2210
4619 if (me.options.responsive) {
4620 listener = function() {
4621 me.resize();
4622 };
4623
4624 platform.addEventListener(me, 'resize', listener);
4625 listeners.resize = listener;
4626 }
4627 },
4628
4629 /**
4630 * @private
4631 */
4632 unbindEvents: function() {
4633 var me = this;
4634 var listeners = me._listeners;
4635 if (!listeners) {
4636 return;
4637 }
4638
4639 delete me._listeners;
4640 helpers.each(listeners, function(listener, type) {
4641 platform.removeEventListener(me, type, listener);
4642 });
4643 },
4644
4645 updateHoverStyle: function(elements, mode, enabled) {
4646 var method = enabled ? 'setHoverStyle' : 'removeHoverStyle';
4647 var element, i, ilen;
4648
4649 for (i = 0, ilen = elements.length; i < ilen; ++i) {
4650 element = elements[i];
4651 if (element) {
4652 this.getDatasetMeta(element._datasetIndex).controller[method](element);
4653 }
4654 }
4655 },
4656
4657 /**
4658 * @private
4659 */
4660 eventHandler: function(e) {
4661 var me = this;
4662 var tooltip = me.tooltip;
4663
4664 if (plugins.notify(me, 'beforeEvent', [e]) === false) {
4665 return;
4666 }
4667
4668 // Buffer any update calls so that renders do not occur
4669 me._bufferedRender = true;
4670 me._bufferedRequest = null;
4671
4672 var changed = me.handleEvent(e);
4673 // for smooth tooltip animations issue #4989
4674 // the tooltip should be the source of change
4675 // Animation check workaround:
4676 // tooltip._start will be null when tooltip isn't animating
4677 if (tooltip) {
4678 changed = tooltip._start
4679 ? tooltip.handleEvent(e)
4680 : changed | tooltip.handleEvent(e);
4681 }
4682
4683 plugins.notify(me, 'afterEvent', [e]);
4684
4685 var bufferedRequest = me._bufferedRequest;
4686 if (bufferedRequest) {
4687 // If we have an update that was triggered, we need to do a normal render
4688 me.render(bufferedRequest);
4689 } else if (changed && !me.animating) {
4690 // If entering, leaving, or changing elements, animate the change via pivot
4691 me.stop();
4692
4693 // We only need to render at this point. Updating will cause scales to be
4694 // recomputed generating flicker & using more memory than necessary.
4695 me.render(me.options.hover.animationDuration, true);
4696 }
4697
4698 me._bufferedRender = false;
4699 me._bufferedRequest = null;
4700
4701 return me;
4702 },
4703
4704 /**
4705 * Handle an event
4706 * @private
4707 * @param {IEvent} event the event to handle
4708 * @return {Boolean} true if the chart needs to re-render
4709 */
4710 handleEvent: function(e) {
4711 var me = this;
4712 var options = me.options || {};
4713 var hoverOptions = options.hover;
4714 var changed = false;
4715
4716 me.lastActive = me.lastActive || [];
4717
4718 // Find Active Elements for hover and tooltips
4719 if (e.type === 'mouseout') {
4720 me.active = [];
4721 } else {
4722 me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
4723 }
4724
4725 // Invoke onHover hook
4726 // Need to call with native event here to not break backwards compatibility
4727 helpers.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
4728
4729 if (e.type === 'mouseup' || e.type === 'click') {
4730 if (options.onClick) {
4731 // Use e.native here for backwards compatibility
4732 options.onClick.call(me, e.native, me.active);
4733 }
4734 }
4735
4736 // Remove styling for last active (even if it may still be active)
4737 if (me.lastActive.length) {
4738 me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
4739 }
4740
4741 // Built in hover styling
4742 if (me.active.length && hoverOptions.mode) {
4743 me.updateHoverStyle(me.active, hoverOptions.mode, true);
4744 }
4745
4746 changed = !helpers.arrayEquals(me.active, me.lastActive);
4747
4748 // Remember Last Actives
4749 me.lastActive = me.active;
4750
4751 return changed;
4752 }
4753 });
4754
4755 /**
4756 * Provided for backward compatibility, use Chart instead.
4757 * @class Chart.Controller
4758 * @deprecated since version 2.6.0
4759 * @todo remove at version 3
4760 * @private
4761 */
4762 Chart.Controller = Chart;
4763};
4764
4765},{"25":25,"28":28,"30":30,"31":31,"45":45,"48":48}],24:[function(require,module,exports){
4766'use strict';
4767
4768var helpers = require(45);
4769
4770module.exports = function(Chart) {
4771
4772 var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
4773
4774 /**
4775 * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
4776 * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
4777 * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
4778 */
4779 function listenArrayEvents(array, listener) {
4780 if (array._chartjs) {
4781 array._chartjs.listeners.push(listener);
4782 return;
4783 }
4784
4785 Object.defineProperty(array, '_chartjs', {
4786 configurable: true,
4787 enumerable: false,
4788 value: {
4789 listeners: [listener]
4790 }
4791 });
4792
4793 arrayEvents.forEach(function(key) {
4794 var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
4795 var base = array[key];
4796
4797 Object.defineProperty(array, key, {
4798 configurable: true,
4799 enumerable: false,
4800 value: function() {
4801 var args = Array.prototype.slice.call(arguments);
4802 var res = base.apply(this, args);
4803
4804 helpers.each(array._chartjs.listeners, function(object) {
4805 if (typeof object[method] === 'function') {
4806 object[method].apply(object, args);
4807 }
4808 });
4809
4810 return res;
4811 }
4812 });
4813 });
4814 }
4815
4816 /**
4817 * Removes the given array event listener and cleanup extra attached properties (such as
4818 * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
4819 */
4820 function unlistenArrayEvents(array, listener) {
4821 var stub = array._chartjs;
4822 if (!stub) {
4823 return;
4824 }
4825
4826 var listeners = stub.listeners;
4827 var index = listeners.indexOf(listener);
4828 if (index !== -1) {
4829 listeners.splice(index, 1);
4830 }
4831
4832 if (listeners.length > 0) {
4833 return;
4834 }
4835
4836 arrayEvents.forEach(function(key) {
4837 delete array[key];
4838 });
4839
4840 delete array._chartjs;
4841 }
4842
4843 // Base class for all dataset controllers (line, bar, etc)
4844 Chart.DatasetController = function(chart, datasetIndex) {
4845 this.initialize(chart, datasetIndex);
4846 };
4847
4848 helpers.extend(Chart.DatasetController.prototype, {
4849
4850 /**
4851 * Element type used to generate a meta dataset (e.g. Chart.element.Line).
4852 * @type {Chart.core.element}
4853 */
4854 datasetElementType: null,
4855
4856 /**
4857 * Element type used to generate a meta data (e.g. Chart.element.Point).
4858 * @type {Chart.core.element}
4859 */
4860 dataElementType: null,
4861
4862 initialize: function(chart, datasetIndex) {
4863 var me = this;
4864 me.chart = chart;
4865 me.index = datasetIndex;
4866 me.linkScales();
4867 me.addElements();
4868 },
4869
4870 updateIndex: function(datasetIndex) {
4871 this.index = datasetIndex;
4872 },
4873
4874 linkScales: function() {
4875 var me = this;
4876 var meta = me.getMeta();
4877 var dataset = me.getDataset();
4878
4879 if (meta.xAxisID === null || !(meta.xAxisID in me.chart.scales)) {
4880 meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id;
4881 }
4882 if (meta.yAxisID === null || !(meta.yAxisID in me.chart.scales)) {
4883 meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id;
4884 }
4885 },
4886
4887 getDataset: function() {
4888 return this.chart.data.datasets[this.index];
4889 },
4890
4891 getMeta: function() {
4892 return this.chart.getDatasetMeta(this.index);
4893 },
4894
4895 getScaleForId: function(scaleID) {
4896 return this.chart.scales[scaleID];
4897 },
4898
4899 reset: function() {
4900 this.update(true);
4901 },
4902
4903 /**
4904 * @private
4905 */
4906 destroy: function() {
4907 if (this._data) {
4908 unlistenArrayEvents(this._data, this);
4909 }
4910 },
4911
4912 createMetaDataset: function() {
4913 var me = this;
4914 var type = me.datasetElementType;
4915 return type && new type({
4916 _chart: me.chart,
4917 _datasetIndex: me.index
4918 });
4919 },
4920
4921 createMetaData: function(index) {
4922 var me = this;
4923 var type = me.dataElementType;
4924 return type && new type({
4925 _chart: me.chart,
4926 _datasetIndex: me.index,
4927 _index: index
4928 });
4929 },
4930
4931 addElements: function() {
4932 var me = this;
4933 var meta = me.getMeta();
4934 var data = me.getDataset().data || [];
4935 var metaData = meta.data;
4936 var i, ilen;
4937
4938 for (i = 0, ilen = data.length; i < ilen; ++i) {
4939 metaData[i] = metaData[i] || me.createMetaData(i);
4940 }
4941
4942 meta.dataset = meta.dataset || me.createMetaDataset();
4943 },
4944
4945 addElementAndReset: function(index) {
4946 var element = this.createMetaData(index);
4947 this.getMeta().data.splice(index, 0, element);
4948 this.updateElement(element, index, true);
4949 },
4950
4951 buildOrUpdateElements: function() {
4952 var me = this;
4953 var dataset = me.getDataset();
4954 var data = dataset.data || (dataset.data = []);
4955
4956 // In order to correctly handle data addition/deletion animation (an thus simulate
4957 // real-time charts), we need to monitor these data modifications and synchronize
4958 // the internal meta data accordingly.
4959 if (me._data !== data) {
4960 if (me._data) {
4961 // This case happens when the user replaced the data array instance.
4962 unlistenArrayEvents(me._data, me);
4963 }
4964
4965 listenArrayEvents(data, me);
4966 me._data = data;
4967 }
4968
4969 // Re-sync meta data in case the user replaced the data array or if we missed
4970 // any updates and so make sure that we handle number of datapoints changing.
4971 me.resyncElements();
4972 },
4973
4974 update: helpers.noop,
4975
4976 transition: function(easingValue) {
4977 var meta = this.getMeta();
4978 var elements = meta.data || [];
4979 var ilen = elements.length;
4980 var i = 0;
4981
4982 for (; i < ilen; ++i) {
4983 elements[i].transition(easingValue);
4984 }
4985
4986 if (meta.dataset) {
4987 meta.dataset.transition(easingValue);
4988 }
4989 },
4990
4991 draw: function() {
4992 var meta = this.getMeta();
4993 var elements = meta.data || [];
4994 var ilen = elements.length;
4995 var i = 0;
4996
4997 if (meta.dataset) {
4998 meta.dataset.draw();
4999 }
5000
5001 for (; i < ilen; ++i) {
5002 elements[i].draw();
5003 }
5004 },
5005
5006 removeHoverStyle: function(element, elementOpts) {
5007 var dataset = this.chart.data.datasets[element._datasetIndex];
5008 var index = element._index;
5009 var custom = element.custom || {};
5010 var valueOrDefault = helpers.valueAtIndexOrDefault;
5011 var model = element._model;
5012
5013 model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueOrDefault(dataset.backgroundColor, index, elementOpts.backgroundColor);
5014 model.borderColor = custom.borderColor ? custom.borderColor : valueOrDefault(dataset.borderColor, index, elementOpts.borderColor);
5015 model.borderWidth = custom.borderWidth ? custom.borderWidth : valueOrDefault(dataset.borderWidth, index, elementOpts.borderWidth);
5016 },
5017
5018 setHoverStyle: function(element) {
5019 var dataset = this.chart.data.datasets[element._datasetIndex];
5020 var index = element._index;
5021 var custom = element.custom || {};
5022 var valueOrDefault = helpers.valueAtIndexOrDefault;
5023 var getHoverColor = helpers.getHoverColor;
5024 var model = element._model;
5025
5026 model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : valueOrDefault(dataset.hoverBackgroundColor, index, getHoverColor(model.backgroundColor));
5027 model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : valueOrDefault(dataset.hoverBorderColor, index, getHoverColor(model.borderColor));
5028 model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : valueOrDefault(dataset.hoverBorderWidth, index, model.borderWidth);
5029 },
5030
5031 /**
5032 * @private
5033 */
5034 resyncElements: function() {
5035 var me = this;
5036 var meta = me.getMeta();
5037 var data = me.getDataset().data;
5038 var numMeta = meta.data.length;
5039 var numData = data.length;
5040
5041 if (numData < numMeta) {
5042 meta.data.splice(numData, numMeta - numData);
5043 } else if (numData > numMeta) {
5044 me.insertElements(numMeta, numData - numMeta);
5045 }
5046 },
5047
5048 /**
5049 * @private
5050 */
5051 insertElements: function(start, count) {
5052 for (var i = 0; i < count; ++i) {
5053 this.addElementAndReset(start + i);
5054 }
5055 },
5056
5057 /**
5058 * @private
5059 */
5060 onDataPush: function() {
5061 this.insertElements(this.getDataset().data.length - 1, arguments.length);
5062 },
5063
5064 /**
5065 * @private
5066 */
5067 onDataPop: function() {
5068 this.getMeta().data.pop();
5069 },
5070
5071 /**
5072 * @private
5073 */
5074 onDataShift: function() {
5075 this.getMeta().data.shift();
5076 },
5077
5078 /**
5079 * @private
5080 */
5081 onDataSplice: function(start, count) {
5082 this.getMeta().data.splice(start, count);
5083 this.insertElements(start, arguments.length - 2);
5084 },
5085
5086 /**
5087 * @private
5088 */
5089 onDataUnshift: function() {
5090 this.insertElements(0, arguments.length);
5091 }
5092 });
5093
5094 Chart.DatasetController.extend = helpers.inherits;
5095};
5096
5097},{"45":45}],25:[function(require,module,exports){
5098'use strict';
5099
5100var helpers = require(45);
5101
5102module.exports = {
5103 /**
5104 * @private
5105 */
5106 _set: function(scope, values) {
5107 return helpers.merge(this[scope] || (this[scope] = {}), values);
5108 }
5109};
5110
5111},{"45":45}],26:[function(require,module,exports){
5112'use strict';
5113
5114var color = require(3);
5115var helpers = require(45);
5116
5117function interpolate(start, view, model, ease) {
5118 var keys = Object.keys(model);
5119 var i, ilen, key, actual, origin, target, type, c0, c1;
5120
5121 for (i = 0, ilen = keys.length; i < ilen; ++i) {
5122 key = keys[i];
5123
5124 target = model[key];
5125
5126 // if a value is added to the model after pivot() has been called, the view
5127 // doesn't contain it, so let's initialize the view to the target value.
5128 if (!view.hasOwnProperty(key)) {
5129 view[key] = target;
5130 }
5131
5132 actual = view[key];
5133
5134 if (actual === target || key[0] === '_') {
5135 continue;
5136 }
5137
5138 if (!start.hasOwnProperty(key)) {
5139 start[key] = actual;
5140 }
5141
5142 origin = start[key];
5143
5144 type = typeof target;
5145
5146 if (type === typeof origin) {
5147 if (type === 'string') {
5148 c0 = color(origin);
5149 if (c0.valid) {
5150 c1 = color(target);
5151 if (c1.valid) {
5152 view[key] = c1.mix(c0, ease).rgbString();
5153 continue;
5154 }
5155 }
5156 } else if (type === 'number' && isFinite(origin) && isFinite(target)) {
5157 view[key] = origin + (target - origin) * ease;
5158 continue;
5159 }
5160 }
5161
5162 view[key] = target;
5163 }
5164}
5165
5166var Element = function(configuration) {
5167 helpers.extend(this, configuration);
5168 this.initialize.apply(this, arguments);
5169};
5170
5171helpers.extend(Element.prototype, {
5172
5173 initialize: function() {
5174 this.hidden = false;
5175 },
5176
5177 pivot: function() {
5178 var me = this;
5179 if (!me._view) {
5180 me._view = helpers.clone(me._model);
5181 }
5182 me._start = {};
5183 return me;
5184 },
5185
5186 transition: function(ease) {
5187 var me = this;
5188 var model = me._model;
5189 var start = me._start;
5190 var view = me._view;
5191
5192 // No animation -> No Transition
5193 if (!model || ease === 1) {
5194 me._view = model;
5195 me._start = null;
5196 return me;
5197 }
5198
5199 if (!view) {
5200 view = me._view = {};
5201 }
5202
5203 if (!start) {
5204 start = me._start = {};
5205 }
5206
5207 interpolate(start, view, model, ease);
5208
5209 return me;
5210 },
5211
5212 tooltipPosition: function() {
5213 return {
5214 x: this._model.x,
5215 y: this._model.y
5216 };
5217 },
5218
5219 hasValue: function() {
5220 return helpers.isNumber(this._model.x) && helpers.isNumber(this._model.y);
5221 }
5222});
5223
5224Element.extend = helpers.inherits;
5225
5226module.exports = Element;
5227
5228},{"3":3,"45":45}],27:[function(require,module,exports){
5229/* global window: false */
5230/* global document: false */
5231'use strict';
5232
5233var color = require(3);
5234var defaults = require(25);
5235var helpers = require(45);
5236
5237module.exports = function(Chart) {
5238
5239 // -- Basic js utility methods
5240
5241 helpers.configMerge = function(/* objects ... */) {
5242 return helpers.merge(helpers.clone(arguments[0]), [].slice.call(arguments, 1), {
5243 merger: function(key, target, source, options) {
5244 var tval = target[key] || {};
5245 var sval = source[key];
5246
5247 if (key === 'scales') {
5248 // scale config merging is complex. Add our own function here for that
5249 target[key] = helpers.scaleMerge(tval, sval);
5250 } else if (key === 'scale') {
5251 // used in polar area & radar charts since there is only one scale
5252 target[key] = helpers.merge(tval, [Chart.scaleService.getScaleDefaults(sval.type), sval]);
5253 } else {
5254 helpers._merger(key, target, source, options);
5255 }
5256 }
5257 });
5258 };
5259
5260 helpers.scaleMerge = function(/* objects ... */) {
5261 return helpers.merge(helpers.clone(arguments[0]), [].slice.call(arguments, 1), {
5262 merger: function(key, target, source, options) {
5263 if (key === 'xAxes' || key === 'yAxes') {
5264 var slen = source[key].length;
5265 var i, type, scale;
5266
5267 if (!target[key]) {
5268 target[key] = [];
5269 }
5270
5271 for (i = 0; i < slen; ++i) {
5272 scale = source[key][i];
5273 type = helpers.valueOrDefault(scale.type, key === 'xAxes' ? 'category' : 'linear');
5274
5275 if (i >= target[key].length) {
5276 target[key].push({});
5277 }
5278
5279 if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
5280 // new/untyped scale or type changed: let's apply the new defaults
5281 // then merge source scale to correctly overwrite the defaults.
5282 helpers.merge(target[key][i], [Chart.scaleService.getScaleDefaults(type), scale]);
5283 } else {
5284 // scales type are the same
5285 helpers.merge(target[key][i], scale);
5286 }
5287 }
5288 } else {
5289 helpers._merger(key, target, source, options);
5290 }
5291 }
5292 });
5293 };
5294
5295 helpers.where = function(collection, filterCallback) {
5296 if (helpers.isArray(collection) && Array.prototype.filter) {
5297 return collection.filter(filterCallback);
5298 }
5299 var filtered = [];
5300
5301 helpers.each(collection, function(item) {
5302 if (filterCallback(item)) {
5303 filtered.push(item);
5304 }
5305 });
5306
5307 return filtered;
5308 };
5309 helpers.findIndex = Array.prototype.findIndex ?
5310 function(array, callback, scope) {
5311 return array.findIndex(callback, scope);
5312 } :
5313 function(array, callback, scope) {
5314 scope = scope === undefined ? array : scope;
5315 for (var i = 0, ilen = array.length; i < ilen; ++i) {
5316 if (callback.call(scope, array[i], i, array)) {
5317 return i;
5318 }
5319 }
5320 return -1;
5321 };
5322 helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
5323 // Default to start of the array
5324 if (helpers.isNullOrUndef(startIndex)) {
5325 startIndex = -1;
5326 }
5327 for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
5328 var currentItem = arrayToSearch[i];
5329 if (filterCallback(currentItem)) {
5330 return currentItem;
5331 }
5332 }
5333 };
5334 helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
5335 // Default to end of the array
5336 if (helpers.isNullOrUndef(startIndex)) {
5337 startIndex = arrayToSearch.length;
5338 }
5339 for (var i = startIndex - 1; i >= 0; i--) {
5340 var currentItem = arrayToSearch[i];
5341 if (filterCallback(currentItem)) {
5342 return currentItem;
5343 }
5344 }
5345 };
5346
5347 // -- Math methods
5348 helpers.isNumber = function(n) {
5349 return !isNaN(parseFloat(n)) && isFinite(n);
5350 };
5351 helpers.almostEquals = function(x, y, epsilon) {
5352 return Math.abs(x - y) < epsilon;
5353 };
5354 helpers.almostWhole = function(x, epsilon) {
5355 var rounded = Math.round(x);
5356 return (((rounded - epsilon) < x) && ((rounded + epsilon) > x));
5357 };
5358 helpers.max = function(array) {
5359 return array.reduce(function(max, value) {
5360 if (!isNaN(value)) {
5361 return Math.max(max, value);
5362 }
5363 return max;
5364 }, Number.NEGATIVE_INFINITY);
5365 };
5366 helpers.min = function(array) {
5367 return array.reduce(function(min, value) {
5368 if (!isNaN(value)) {
5369 return Math.min(min, value);
5370 }
5371 return min;
5372 }, Number.POSITIVE_INFINITY);
5373 };
5374 helpers.sign = Math.sign ?
5375 function(x) {
5376 return Math.sign(x);
5377 } :
5378 function(x) {
5379 x = +x; // convert to a number
5380 if (x === 0 || isNaN(x)) {
5381 return x;
5382 }
5383 return x > 0 ? 1 : -1;
5384 };
5385 helpers.log10 = Math.log10 ?
5386 function(x) {
5387 return Math.log10(x);
5388 } :
5389 function(x) {
5390 return Math.log(x) / Math.LN10;
5391 };
5392 helpers.toRadians = function(degrees) {
5393 return degrees * (Math.PI / 180);
5394 };
5395 helpers.toDegrees = function(radians) {
5396 return radians * (180 / Math.PI);
5397 };
5398 // Gets the angle from vertical upright to the point about a centre.
5399 helpers.getAngleFromPoint = function(centrePoint, anglePoint) {
5400 var distanceFromXCenter = anglePoint.x - centrePoint.x;
5401 var distanceFromYCenter = anglePoint.y - centrePoint.y;
5402 var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
5403
5404 var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
5405
5406 if (angle < (-0.5 * Math.PI)) {
5407 angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
5408 }
5409
5410 return {
5411 angle: angle,
5412 distance: radialDistanceFromCenter
5413 };
5414 };
5415 helpers.distanceBetweenPoints = function(pt1, pt2) {
5416 return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
5417 };
5418 helpers.aliasPixel = function(pixelWidth) {
5419 return (pixelWidth % 2 === 0) ? 0 : 0.5;
5420 };
5421 helpers.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
5422 // Props to Rob Spencer at scaled innovation for his post on splining between points
5423 // http://scaledinnovation.com/analytics/splines/aboutSplines.html
5424
5425 // This function must also respect "skipped" points
5426
5427 var previous = firstPoint.skip ? middlePoint : firstPoint;
5428 var current = middlePoint;
5429 var next = afterPoint.skip ? middlePoint : afterPoint;
5430
5431 var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
5432 var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
5433
5434 var s01 = d01 / (d01 + d12);
5435 var s12 = d12 / (d01 + d12);
5436
5437 // If all points are the same, s01 & s02 will be inf
5438 s01 = isNaN(s01) ? 0 : s01;
5439 s12 = isNaN(s12) ? 0 : s12;
5440
5441 var fa = t * s01; // scaling factor for triangle Ta
5442 var fb = t * s12;
5443
5444 return {
5445 previous: {
5446 x: current.x - fa * (next.x - previous.x),
5447 y: current.y - fa * (next.y - previous.y)
5448 },
5449 next: {
5450 x: current.x + fb * (next.x - previous.x),
5451 y: current.y + fb * (next.y - previous.y)
5452 }
5453 };
5454 };
5455 helpers.EPSILON = Number.EPSILON || 1e-14;
5456 helpers.splineCurveMonotone = function(points) {
5457 // This function calculates Bézier control points in a similar way than |splineCurve|,
5458 // but preserves monotonicity of the provided data and ensures no local extremums are added
5459 // between the dataset discrete points due to the interpolation.
5460 // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
5461
5462 var pointsWithTangents = (points || []).map(function(point) {
5463 return {
5464 model: point._model,
5465 deltaK: 0,
5466 mK: 0
5467 };
5468 });
5469
5470 // Calculate slopes (deltaK) and initialize tangents (mK)
5471 var pointsLen = pointsWithTangents.length;
5472 var i, pointBefore, pointCurrent, pointAfter;
5473 for (i = 0; i < pointsLen; ++i) {
5474 pointCurrent = pointsWithTangents[i];
5475 if (pointCurrent.model.skip) {
5476 continue;
5477 }
5478
5479 pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
5480 pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
5481 if (pointAfter && !pointAfter.model.skip) {
5482 var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
5483
5484 // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
5485 pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
5486 }
5487
5488 if (!pointBefore || pointBefore.model.skip) {
5489 pointCurrent.mK = pointCurrent.deltaK;
5490 } else if (!pointAfter || pointAfter.model.skip) {
5491 pointCurrent.mK = pointBefore.deltaK;
5492 } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
5493 pointCurrent.mK = 0;
5494 } else {
5495 pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
5496 }
5497 }
5498
5499 // Adjust tangents to ensure monotonic properties
5500 var alphaK, betaK, tauK, squaredMagnitude;
5501 for (i = 0; i < pointsLen - 1; ++i) {
5502 pointCurrent = pointsWithTangents[i];
5503 pointAfter = pointsWithTangents[i + 1];
5504 if (pointCurrent.model.skip || pointAfter.model.skip) {
5505 continue;
5506 }
5507
5508 if (helpers.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
5509 pointCurrent.mK = pointAfter.mK = 0;
5510 continue;
5511 }
5512
5513 alphaK = pointCurrent.mK / pointCurrent.deltaK;
5514 betaK = pointAfter.mK / pointCurrent.deltaK;
5515 squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
5516 if (squaredMagnitude <= 9) {
5517 continue;
5518 }
5519
5520 tauK = 3 / Math.sqrt(squaredMagnitude);
5521 pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
5522 pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
5523 }
5524
5525 // Compute control points
5526 var deltaX;
5527 for (i = 0; i < pointsLen; ++i) {
5528 pointCurrent = pointsWithTangents[i];
5529 if (pointCurrent.model.skip) {
5530 continue;
5531 }
5532
5533 pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
5534 pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
5535 if (pointBefore && !pointBefore.model.skip) {
5536 deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
5537 pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
5538 pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
5539 }
5540 if (pointAfter && !pointAfter.model.skip) {
5541 deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
5542 pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
5543 pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
5544 }
5545 }
5546 };
5547 helpers.nextItem = function(collection, index, loop) {
5548 if (loop) {
5549 return index >= collection.length - 1 ? collection[0] : collection[index + 1];
5550 }
5551 return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
5552 };
5553 helpers.previousItem = function(collection, index, loop) {
5554 if (loop) {
5555 return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
5556 }
5557 return index <= 0 ? collection[0] : collection[index - 1];
5558 };
5559 // Implementation of the nice number algorithm used in determining where axis labels will go
5560 helpers.niceNum = function(range, round) {
5561 var exponent = Math.floor(helpers.log10(range));
5562 var fraction = range / Math.pow(10, exponent);
5563 var niceFraction;
5564
5565 if (round) {
5566 if (fraction < 1.5) {
5567 niceFraction = 1;
5568 } else if (fraction < 3) {
5569 niceFraction = 2;
5570 } else if (fraction < 7) {
5571 niceFraction = 5;
5572 } else {
5573 niceFraction = 10;
5574 }
5575 } else if (fraction <= 1.0) {
5576 niceFraction = 1;
5577 } else if (fraction <= 2) {
5578 niceFraction = 2;
5579 } else if (fraction <= 5) {
5580 niceFraction = 5;
5581 } else {
5582 niceFraction = 10;
5583 }
5584
5585 return niceFraction * Math.pow(10, exponent);
5586 };
5587 // Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
5588 helpers.requestAnimFrame = (function() {
5589 if (typeof window === 'undefined') {
5590 return function(callback) {
5591 callback();
5592 };
5593 }
5594 return window.requestAnimationFrame ||
5595 window.webkitRequestAnimationFrame ||
5596 window.mozRequestAnimationFrame ||
5597 window.oRequestAnimationFrame ||
5598 window.msRequestAnimationFrame ||
5599 function(callback) {
5600 return window.setTimeout(callback, 1000 / 60);
5601 };
5602 }());
5603 // -- DOM methods
5604 helpers.getRelativePosition = function(evt, chart) {
5605 var mouseX, mouseY;
5606 var e = evt.originalEvent || evt;
5607 var canvas = evt.currentTarget || evt.srcElement;
5608 var boundingRect = canvas.getBoundingClientRect();
5609
5610 var touches = e.touches;
5611 if (touches && touches.length > 0) {
5612 mouseX = touches[0].clientX;
5613 mouseY = touches[0].clientY;
5614
5615 } else {
5616 mouseX = e.clientX;
5617 mouseY = e.clientY;
5618 }
5619
5620 // Scale mouse coordinates into canvas coordinates
5621 // by following the pattern laid out by 'jerryj' in the comments of
5622 // http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
5623 var paddingLeft = parseFloat(helpers.getStyle(canvas, 'padding-left'));
5624 var paddingTop = parseFloat(helpers.getStyle(canvas, 'padding-top'));
5625 var paddingRight = parseFloat(helpers.getStyle(canvas, 'padding-right'));
5626 var paddingBottom = parseFloat(helpers.getStyle(canvas, 'padding-bottom'));
5627 var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
5628 var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
5629
5630 // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
5631 // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
5632 mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
5633 mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
5634
5635 return {
5636 x: mouseX,
5637 y: mouseY
5638 };
5639
5640 };
5641
5642 // Private helper function to convert max-width/max-height values that may be percentages into a number
5643 function parseMaxStyle(styleValue, node, parentProperty) {
5644 var valueInPixels;
5645 if (typeof styleValue === 'string') {
5646 valueInPixels = parseInt(styleValue, 10);
5647
5648 if (styleValue.indexOf('%') !== -1) {
5649 // percentage * size in dimension
5650 valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
5651 }
5652 } else {
5653 valueInPixels = styleValue;
5654 }
5655
5656 return valueInPixels;
5657 }
5658
5659 /**
5660 * Returns if the given value contains an effective constraint.
5661 * @private
5662 */
5663 function isConstrainedValue(value) {
5664 return value !== undefined && value !== null && value !== 'none';
5665 }
5666
5667 // Private helper to get a constraint dimension
5668 // @param domNode : the node to check the constraint on
5669 // @param maxStyle : the style that defines the maximum for the direction we are using (maxWidth / maxHeight)
5670 // @param percentageProperty : property of parent to use when calculating width as a percentage
5671 // @see http://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser
5672 function getConstraintDimension(domNode, maxStyle, percentageProperty) {
5673 var view = document.defaultView;
5674 var parentNode = domNode.parentNode;
5675 var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
5676 var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
5677 var hasCNode = isConstrainedValue(constrainedNode);
5678 var hasCContainer = isConstrainedValue(constrainedContainer);
5679 var infinity = Number.POSITIVE_INFINITY;
5680
5681 if (hasCNode || hasCContainer) {
5682 return Math.min(
5683 hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
5684 hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
5685 }
5686
5687 return 'none';
5688 }
5689 // returns Number or undefined if no constraint
5690 helpers.getConstraintWidth = function(domNode) {
5691 return getConstraintDimension(domNode, 'max-width', 'clientWidth');
5692 };
5693 // returns Number or undefined if no constraint
5694 helpers.getConstraintHeight = function(domNode) {
5695 return getConstraintDimension(domNode, 'max-height', 'clientHeight');
5696 };
5697 helpers.getMaximumWidth = function(domNode) {
5698 var container = domNode.parentNode;
5699 if (!container) {
5700 return domNode.clientWidth;
5701 }
5702
5703 var paddingLeft = parseInt(helpers.getStyle(container, 'padding-left'), 10);
5704 var paddingRight = parseInt(helpers.getStyle(container, 'padding-right'), 10);
5705 var w = container.clientWidth - paddingLeft - paddingRight;
5706 var cw = helpers.getConstraintWidth(domNode);
5707 return isNaN(cw) ? w : Math.min(w, cw);
5708 };
5709 helpers.getMaximumHeight = function(domNode) {
5710 var container = domNode.parentNode;
5711 if (!container) {
5712 return domNode.clientHeight;
5713 }
5714
5715 var paddingTop = parseInt(helpers.getStyle(container, 'padding-top'), 10);
5716 var paddingBottom = parseInt(helpers.getStyle(container, 'padding-bottom'), 10);
5717 var h = container.clientHeight - paddingTop - paddingBottom;
5718 var ch = helpers.getConstraintHeight(domNode);
5719 return isNaN(ch) ? h : Math.min(h, ch);
5720 };
5721 helpers.getStyle = function(el, property) {
5722 return el.currentStyle ?
5723 el.currentStyle[property] :
5724 document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
5725 };
5726 helpers.retinaScale = function(chart, forceRatio) {
5727 var pixelRatio = chart.currentDevicePixelRatio = forceRatio || window.devicePixelRatio || 1;
5728 if (pixelRatio === 1) {
5729 return;
5730 }
5731
5732 var canvas = chart.canvas;
5733 var height = chart.height;
5734 var width = chart.width;
5735
5736 canvas.height = height * pixelRatio;
5737 canvas.width = width * pixelRatio;
5738 chart.ctx.scale(pixelRatio, pixelRatio);
5739
5740 // If no style has been set on the canvas, the render size is used as display size,
5741 // making the chart visually bigger, so let's enforce it to the "correct" values.
5742 // See https://github.com/chartjs/Chart.js/issues/3575
5743 if (!canvas.style.height && !canvas.style.width) {
5744 canvas.style.height = height + 'px';
5745 canvas.style.width = width + 'px';
5746 }
5747 };
5748 // -- Canvas methods
5749 helpers.fontString = function(pixelSize, fontStyle, fontFamily) {
5750 return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
5751 };
5752 helpers.longestText = function(ctx, font, arrayOfThings, cache) {
5753 cache = cache || {};
5754 var data = cache.data = cache.data || {};
5755 var gc = cache.garbageCollect = cache.garbageCollect || [];
5756
5757 if (cache.font !== font) {
5758 data = cache.data = {};
5759 gc = cache.garbageCollect = [];
5760 cache.font = font;
5761 }
5762
5763 ctx.font = font;
5764 var longest = 0;
5765 helpers.each(arrayOfThings, function(thing) {
5766 // Undefined strings and arrays should not be measured
5767 if (thing !== undefined && thing !== null && helpers.isArray(thing) !== true) {
5768 longest = helpers.measureText(ctx, data, gc, longest, thing);
5769 } else if (helpers.isArray(thing)) {
5770 // if it is an array lets measure each element
5771 // to do maybe simplify this function a bit so we can do this more recursively?
5772 helpers.each(thing, function(nestedThing) {
5773 // Undefined strings and arrays should not be measured
5774 if (nestedThing !== undefined && nestedThing !== null && !helpers.isArray(nestedThing)) {
5775 longest = helpers.measureText(ctx, data, gc, longest, nestedThing);
5776 }
5777 });
5778 }
5779 });
5780
5781 var gcLen = gc.length / 2;
5782 if (gcLen > arrayOfThings.length) {
5783 for (var i = 0; i < gcLen; i++) {
5784 delete data[gc[i]];
5785 }
5786 gc.splice(0, gcLen);
5787 }
5788 return longest;
5789 };
5790 helpers.measureText = function(ctx, data, gc, longest, string) {
5791 var textWidth = data[string];
5792 if (!textWidth) {
5793 textWidth = data[string] = ctx.measureText(string).width;
5794 gc.push(string);
5795 }
5796 if (textWidth > longest) {
5797 longest = textWidth;
5798 }
5799 return longest;
5800 };
5801 helpers.numberOfLabelLines = function(arrayOfThings) {
5802 var numberOfLines = 1;
5803 helpers.each(arrayOfThings, function(thing) {
5804 if (helpers.isArray(thing)) {
5805 if (thing.length > numberOfLines) {
5806 numberOfLines = thing.length;
5807 }
5808 }
5809 });
5810 return numberOfLines;
5811 };
5812
5813 helpers.color = !color ?
5814 function(value) {
5815 console.error('Color.js not found!');
5816 return value;
5817 } :
5818 function(value) {
5819 /* global CanvasGradient */
5820 if (value instanceof CanvasGradient) {
5821 value = defaults.global.defaultColor;
5822 }
5823
5824 return color(value);
5825 };
5826
5827 helpers.getHoverColor = function(colorValue) {
5828 /* global CanvasPattern */
5829 return (colorValue instanceof CanvasPattern) ?
5830 colorValue :
5831 helpers.color(colorValue).saturate(0.5).darken(0.1).rgbString();
5832 };
5833};
5834
5835},{"25":25,"3":3,"45":45}],28:[function(require,module,exports){
5836'use strict';
5837
5838var helpers = require(45);
5839
5840/**
5841 * Helper function to get relative position for an event
5842 * @param {Event|IEvent} event - The event to get the position for
5843 * @param {Chart} chart - The chart
5844 * @returns {Point} the event position
5845 */
5846function getRelativePosition(e, chart) {
5847 if (e.native) {
5848 return {
5849 x: e.x,
5850 y: e.y
5851 };
5852 }
5853
5854 return helpers.getRelativePosition(e, chart);
5855}
5856
5857/**
5858 * Helper function to traverse all of the visible elements in the chart
5859 * @param chart {chart} the chart
5860 * @param handler {Function} the callback to execute for each visible item
5861 */
5862function parseVisibleItems(chart, handler) {
5863 var datasets = chart.data.datasets;
5864 var meta, i, j, ilen, jlen;
5865
5866 for (i = 0, ilen = datasets.length; i < ilen; ++i) {
5867 if (!chart.isDatasetVisible(i)) {
5868 continue;
5869 }
5870
5871 meta = chart.getDatasetMeta(i);
5872 for (j = 0, jlen = meta.data.length; j < jlen; ++j) {
5873 var element = meta.data[j];
5874 if (!element._view.skip) {
5875 handler(element);
5876 }
5877 }
5878 }
5879}
5880
5881/**
5882 * Helper function to get the items that intersect the event position
5883 * @param items {ChartElement[]} elements to filter
5884 * @param position {Point} the point to be nearest to
5885 * @return {ChartElement[]} the nearest items
5886 */
5887function getIntersectItems(chart, position) {
5888 var elements = [];
5889
5890 parseVisibleItems(chart, function(element) {
5891 if (element.inRange(position.x, position.y)) {
5892 elements.push(element);
5893 }
5894 });
5895
5896 return elements;
5897}
5898
5899/**
5900 * Helper function to get the items nearest to the event position considering all visible items in teh chart
5901 * @param chart {Chart} the chart to look at elements from
5902 * @param position {Point} the point to be nearest to
5903 * @param intersect {Boolean} if true, only consider items that intersect the position
5904 * @param distanceMetric {Function} function to provide the distance between points
5905 * @return {ChartElement[]} the nearest items
5906 */
5907function getNearestItems(chart, position, intersect, distanceMetric) {
5908 var minDistance = Number.POSITIVE_INFINITY;
5909 var nearestItems = [];
5910
5911 parseVisibleItems(chart, function(element) {
5912 if (intersect && !element.inRange(position.x, position.y)) {
5913 return;
5914 }
5915
5916 var center = element.getCenterPoint();
5917 var distance = distanceMetric(position, center);
5918
5919 if (distance < minDistance) {
5920 nearestItems = [element];
5921 minDistance = distance;
5922 } else if (distance === minDistance) {
5923 // Can have multiple items at the same distance in which case we sort by size
5924 nearestItems.push(element);
5925 }
5926 });
5927
5928 return nearestItems;
5929}
5930
5931/**
5932 * Get a distance metric function for two points based on the
5933 * axis mode setting
5934 * @param {String} axis the axis mode. x|y|xy
5935 */
5936function getDistanceMetricForAxis(axis) {
5937 var useX = axis.indexOf('x') !== -1;
5938 var useY = axis.indexOf('y') !== -1;
5939
5940 return function(pt1, pt2) {
5941 var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
5942 var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
5943 return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
5944 };
5945}
5946
5947function indexMode(chart, e, options) {
5948 var position = getRelativePosition(e, chart);
5949 // Default axis for index mode is 'x' to match old behaviour
5950 options.axis = options.axis || 'x';
5951 var distanceMetric = getDistanceMetricForAxis(options.axis);
5952 var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
5953 var elements = [];
5954
5955 if (!items.length) {
5956 return [];
5957 }
5958
5959 chart.data.datasets.forEach(function(dataset, datasetIndex) {
5960 if (chart.isDatasetVisible(datasetIndex)) {
5961 var meta = chart.getDatasetMeta(datasetIndex);
5962 var element = meta.data[items[0]._index];
5963
5964 // don't count items that are skipped (null data)
5965 if (element && !element._view.skip) {
5966 elements.push(element);
5967 }
5968 }
5969 });
5970
5971 return elements;
5972}
5973
5974/**
5975 * @interface IInteractionOptions
5976 */
5977/**
5978 * If true, only consider items that intersect the point
5979 * @name IInterfaceOptions#boolean
5980 * @type Boolean
5981 */
5982
5983/**
5984 * Contains interaction related functions
5985 * @namespace Chart.Interaction
5986 */
5987module.exports = {
5988 // Helper function for different modes
5989 modes: {
5990 single: function(chart, e) {
5991 var position = getRelativePosition(e, chart);
5992 var elements = [];
5993
5994 parseVisibleItems(chart, function(element) {
5995 if (element.inRange(position.x, position.y)) {
5996 elements.push(element);
5997 return elements;
5998 }
5999 });
6000
6001 return elements.slice(0, 1);
6002 },
6003
6004 /**
6005 * @function Chart.Interaction.modes.label
6006 * @deprecated since version 2.4.0
6007 * @todo remove at version 3
6008 * @private
6009 */
6010 label: indexMode,
6011
6012 /**
6013 * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
6014 * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
6015 * @function Chart.Interaction.modes.index
6016 * @since v2.4.0
6017 * @param chart {chart} the chart we are returning items from
6018 * @param e {Event} the event we are find things at
6019 * @param options {IInteractionOptions} options to use during interaction
6020 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
6021 */
6022 index: indexMode,
6023
6024 /**
6025 * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
6026 * If the options.intersect is false, we find the nearest item and return the items in that dataset
6027 * @function Chart.Interaction.modes.dataset
6028 * @param chart {chart} the chart we are returning items from
6029 * @param e {Event} the event we are find things at
6030 * @param options {IInteractionOptions} options to use during interaction
6031 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
6032 */
6033 dataset: function(chart, e, options) {
6034 var position = getRelativePosition(e, chart);
6035 options.axis = options.axis || 'xy';
6036 var distanceMetric = getDistanceMetricForAxis(options.axis);
6037 var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
6038
6039 if (items.length > 0) {
6040 items = chart.getDatasetMeta(items[0]._datasetIndex).data;
6041 }
6042
6043 return items;
6044 },
6045
6046 /**
6047 * @function Chart.Interaction.modes.x-axis
6048 * @deprecated since version 2.4.0. Use index mode and intersect == true
6049 * @todo remove at version 3
6050 * @private
6051 */
6052 'x-axis': function(chart, e) {
6053 return indexMode(chart, e, {intersect: false});
6054 },
6055
6056 /**
6057 * Point mode returns all elements that hit test based on the event position
6058 * of the event
6059 * @function Chart.Interaction.modes.intersect
6060 * @param chart {chart} the chart we are returning items from
6061 * @param e {Event} the event we are find things at
6062 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
6063 */
6064 point: function(chart, e) {
6065 var position = getRelativePosition(e, chart);
6066 return getIntersectItems(chart, position);
6067 },
6068
6069 /**
6070 * nearest mode returns the element closest to the point
6071 * @function Chart.Interaction.modes.intersect
6072 * @param chart {chart} the chart we are returning items from
6073 * @param e {Event} the event we are find things at
6074 * @param options {IInteractionOptions} options to use
6075 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
6076 */
6077 nearest: function(chart, e, options) {
6078 var position = getRelativePosition(e, chart);
6079 options.axis = options.axis || 'xy';
6080 var distanceMetric = getDistanceMetricForAxis(options.axis);
6081 var nearestItems = getNearestItems(chart, position, options.intersect, distanceMetric);
6082
6083 // We have multiple items at the same distance from the event. Now sort by smallest
6084 if (nearestItems.length > 1) {
6085 nearestItems.sort(function(a, b) {
6086 var sizeA = a.getArea();
6087 var sizeB = b.getArea();
6088 var ret = sizeA - sizeB;
6089
6090 if (ret === 0) {
6091 // if equal sort by dataset index
6092 ret = a._datasetIndex - b._datasetIndex;
6093 }
6094
6095 return ret;
6096 });
6097 }
6098
6099 // Return only 1 item
6100 return nearestItems.slice(0, 1);
6101 },
6102
6103 /**
6104 * x mode returns the elements that hit-test at the current x coordinate
6105 * @function Chart.Interaction.modes.x
6106 * @param chart {chart} the chart we are returning items from
6107 * @param e {Event} the event we are find things at
6108 * @param options {IInteractionOptions} options to use
6109 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
6110 */
6111 x: function(chart, e, options) {
6112 var position = getRelativePosition(e, chart);
6113 var items = [];
6114 var intersectsItem = false;
6115
6116 parseVisibleItems(chart, function(element) {
6117 if (element.inXRange(position.x)) {
6118 items.push(element);
6119 }
6120
6121 if (element.inRange(position.x, position.y)) {
6122 intersectsItem = true;
6123 }
6124 });
6125
6126 // If we want to trigger on an intersect and we don't have any items
6127 // that intersect the position, return nothing
6128 if (options.intersect && !intersectsItem) {
6129 items = [];
6130 }
6131 return items;
6132 },
6133
6134 /**
6135 * y mode returns the elements that hit-test at the current y coordinate
6136 * @function Chart.Interaction.modes.y
6137 * @param chart {chart} the chart we are returning items from
6138 * @param e {Event} the event we are find things at
6139 * @param options {IInteractionOptions} options to use
6140 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
6141 */
6142 y: function(chart, e, options) {
6143 var position = getRelativePosition(e, chart);
6144 var items = [];
6145 var intersectsItem = false;
6146
6147 parseVisibleItems(chart, function(element) {
6148 if (element.inYRange(position.y)) {
6149 items.push(element);
6150 }
6151
6152 if (element.inRange(position.x, position.y)) {
6153 intersectsItem = true;
6154 }
6155 });
6156
6157 // If we want to trigger on an intersect and we don't have any items
6158 // that intersect the position, return nothing
6159 if (options.intersect && !intersectsItem) {
6160 items = [];
6161 }
6162 return items;
6163 }
6164 }
6165};
6166
6167},{"45":45}],29:[function(require,module,exports){
6168'use strict';
6169
6170var defaults = require(25);
6171
6172defaults._set('global', {
6173 responsive: true,
6174 responsiveAnimationDuration: 0,
6175 maintainAspectRatio: true,
6176 events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
6177 hover: {
6178 onHover: null,
6179 mode: 'nearest',
6180 intersect: true,
6181 animationDuration: 400
6182 },
6183 onClick: null,
6184 defaultColor: 'rgba(0,0,0,0.1)',
6185 defaultFontColor: '#666',
6186 defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
6187 defaultFontSize: 12,
6188 defaultFontStyle: 'normal',
6189 showLines: true,
6190
6191 // Element defaults defined in element extensions
6192 elements: {},
6193
6194 // Layout options such as padding
6195 layout: {
6196 padding: {
6197 top: 0,
6198 right: 0,
6199 bottom: 0,
6200 left: 0
6201 }
6202 }
6203});
6204
6205module.exports = function() {
6206
6207 // Occupy the global variable of Chart, and create a simple base class
6208 var Chart = function(item, config) {
6209 this.construct(item, config);
6210 return this;
6211 };
6212
6213 Chart.Chart = Chart;
6214
6215 return Chart;
6216};
6217
6218},{"25":25}],30:[function(require,module,exports){
6219'use strict';
6220
6221var helpers = require(45);
6222
6223function filterByPosition(array, position) {
6224 return helpers.where(array, function(v) {
6225 return v.position === position;
6226 });
6227}
6228
6229function sortByWeight(array, reverse) {
6230 array.forEach(function(v, i) {
6231 v._tmpIndex_ = i;
6232 return v;
6233 });
6234 array.sort(function(a, b) {
6235 var v0 = reverse ? b : a;
6236 var v1 = reverse ? a : b;
6237 return v0.weight === v1.weight ?
6238 v0._tmpIndex_ - v1._tmpIndex_ :
6239 v0.weight - v1.weight;
6240 });
6241 array.forEach(function(v) {
6242 delete v._tmpIndex_;
6243 });
6244}
6245
6246/**
6247 * @interface ILayoutItem
6248 * @prop {String} position - The position of the item in the chart layout. Possible values are
6249 * 'left', 'top', 'right', 'bottom', and 'chartArea'
6250 * @prop {Number} weight - The weight used to sort the item. Higher weights are further away from the chart area
6251 * @prop {Boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
6252 * @prop {Function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
6253 * @prop {Function} update - Takes two parameters: width and height. Returns size of item
6254 * @prop {Function} getPadding - Returns an object with padding on the edges
6255 * @prop {Number} width - Width of item. Must be valid after update()
6256 * @prop {Number} height - Height of item. Must be valid after update()
6257 * @prop {Number} left - Left edge of the item. Set by layout system and cannot be used in update
6258 * @prop {Number} top - Top edge of the item. Set by layout system and cannot be used in update
6259 * @prop {Number} right - Right edge of the item. Set by layout system and cannot be used in update
6260 * @prop {Number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
6261 */
6262
6263// The layout service is very self explanatory. It's responsible for the layout within a chart.
6264// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
6265// It is this service's responsibility of carrying out that layout.
6266module.exports = {
6267 defaults: {},
6268
6269 /**
6270 * Register a box to a chart.
6271 * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
6272 * @param {Chart} chart - the chart to use
6273 * @param {ILayoutItem} item - the item to add to be layed out
6274 */
6275 addBox: function(chart, item) {
6276 if (!chart.boxes) {
6277 chart.boxes = [];
6278 }
6279
6280 // initialize item with default values
6281 item.fullWidth = item.fullWidth || false;
6282 item.position = item.position || 'top';
6283 item.weight = item.weight || 0;
6284
6285 chart.boxes.push(item);
6286 },
6287
6288 /**
6289 * Remove a layoutItem from a chart
6290 * @param {Chart} chart - the chart to remove the box from
6291 * @param {Object} layoutItem - the item to remove from the layout
6292 */
6293 removeBox: function(chart, layoutItem) {
6294 var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
6295 if (index !== -1) {
6296 chart.boxes.splice(index, 1);
6297 }
6298 },
6299
6300 /**
6301 * Sets (or updates) options on the given `item`.
6302 * @param {Chart} chart - the chart in which the item lives (or will be added to)
6303 * @param {Object} item - the item to configure with the given options
6304 * @param {Object} options - the new item options.
6305 */
6306 configure: function(chart, item, options) {
6307 var props = ['fullWidth', 'position', 'weight'];
6308 var ilen = props.length;
6309 var i = 0;
6310 var prop;
6311
6312 for (; i < ilen; ++i) {
6313 prop = props[i];
6314 if (options.hasOwnProperty(prop)) {
6315 item[prop] = options[prop];
6316 }
6317 }
6318 },
6319
6320 /**
6321 * Fits boxes of the given chart into the given size by having each box measure itself
6322 * then running a fitting algorithm
6323 * @param {Chart} chart - the chart
6324 * @param {Number} width - the width to fit into
6325 * @param {Number} height - the height to fit into
6326 */
6327 update: function(chart, width, height) {
6328 if (!chart) {
6329 return;
6330 }
6331
6332 var layoutOptions = chart.options.layout || {};
6333 var padding = helpers.options.toPadding(layoutOptions.padding);
6334 var leftPadding = padding.left;
6335 var rightPadding = padding.right;
6336 var topPadding = padding.top;
6337 var bottomPadding = padding.bottom;
6338
6339 var leftBoxes = filterByPosition(chart.boxes, 'left');
6340 var rightBoxes = filterByPosition(chart.boxes, 'right');
6341 var topBoxes = filterByPosition(chart.boxes, 'top');
6342 var bottomBoxes = filterByPosition(chart.boxes, 'bottom');
6343 var chartAreaBoxes = filterByPosition(chart.boxes, 'chartArea');
6344
6345 // Sort boxes by weight. A higher weight is further away from the chart area
6346 sortByWeight(leftBoxes, true);
6347 sortByWeight(rightBoxes, false);
6348 sortByWeight(topBoxes, true);
6349 sortByWeight(bottomBoxes, false);
6350
6351 // Essentially we now have any number of boxes on each of the 4 sides.
6352 // Our canvas looks like the following.
6353 // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
6354 // B1 is the bottom axis
6355 // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
6356 // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
6357 // an error will be thrown.
6358 //
6359 // |----------------------------------------------------|
6360 // | T1 (Full Width) |
6361 // |----------------------------------------------------|
6362 // | | | T2 | |
6363 // | |----|-------------------------------------|----|
6364 // | | | C1 | | C2 | |
6365 // | | |----| |----| |
6366 // | | | | |
6367 // | L1 | L2 | ChartArea (C0) | R1 |
6368 // | | | | |
6369 // | | |----| |----| |
6370 // | | | C3 | | C4 | |
6371 // | |----|-------------------------------------|----|
6372 // | | | B1 | |
6373 // |----------------------------------------------------|
6374 // | B2 (Full Width) |
6375 // |----------------------------------------------------|
6376 //
6377 // What we do to find the best sizing, we do the following
6378 // 1. Determine the minimum size of the chart area.
6379 // 2. Split the remaining width equally between each vertical axis
6380 // 3. Split the remaining height equally between each horizontal axis
6381 // 4. Give each layout the maximum size it can be. The layout will return it's minimum size
6382 // 5. Adjust the sizes of each axis based on it's minimum reported size.
6383 // 6. Refit each axis
6384 // 7. Position each axis in the final location
6385 // 8. Tell the chart the final location of the chart area
6386 // 9. Tell any axes that overlay the chart area the positions of the chart area
6387
6388 // Step 1
6389 var chartWidth = width - leftPadding - rightPadding;
6390 var chartHeight = height - topPadding - bottomPadding;
6391 var chartAreaWidth = chartWidth / 2; // min 50%
6392 var chartAreaHeight = chartHeight / 2; // min 50%
6393
6394 // Step 2
6395 var verticalBoxWidth = (width - chartAreaWidth) / (leftBoxes.length + rightBoxes.length);
6396
6397 // Step 3
6398 var horizontalBoxHeight = (height - chartAreaHeight) / (topBoxes.length + bottomBoxes.length);
6399
6400 // Step 4
6401 var maxChartAreaWidth = chartWidth;
6402 var maxChartAreaHeight = chartHeight;
6403 var minBoxSizes = [];
6404
6405 function getMinimumBoxSize(box) {
6406 var minSize;
6407 var isHorizontal = box.isHorizontal();
6408
6409 if (isHorizontal) {
6410 minSize = box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, horizontalBoxHeight);
6411 maxChartAreaHeight -= minSize.height;
6412 } else {
6413 minSize = box.update(verticalBoxWidth, maxChartAreaHeight);
6414 maxChartAreaWidth -= minSize.width;
6415 }
6416
6417 minBoxSizes.push({
6418 horizontal: isHorizontal,
6419 minSize: minSize,
6420 box: box,
6421 });
6422 }
6423
6424 helpers.each(leftBoxes.concat(rightBoxes, topBoxes, bottomBoxes), getMinimumBoxSize);
6425
6426 // If a horizontal box has padding, we move the left boxes over to avoid ugly charts (see issue #2478)
6427 var maxHorizontalLeftPadding = 0;
6428 var maxHorizontalRightPadding = 0;
6429 var maxVerticalTopPadding = 0;
6430 var maxVerticalBottomPadding = 0;
6431
6432 helpers.each(topBoxes.concat(bottomBoxes), function(horizontalBox) {
6433 if (horizontalBox.getPadding) {
6434 var boxPadding = horizontalBox.getPadding();
6435 maxHorizontalLeftPadding = Math.max(maxHorizontalLeftPadding, boxPadding.left);
6436 maxHorizontalRightPadding = Math.max(maxHorizontalRightPadding, boxPadding.right);
6437 }
6438 });
6439
6440 helpers.each(leftBoxes.concat(rightBoxes), function(verticalBox) {
6441 if (verticalBox.getPadding) {
6442 var boxPadding = verticalBox.getPadding();
6443 maxVerticalTopPadding = Math.max(maxVerticalTopPadding, boxPadding.top);
6444 maxVerticalBottomPadding = Math.max(maxVerticalBottomPadding, boxPadding.bottom);
6445 }
6446 });
6447
6448 // At this point, maxChartAreaHeight and maxChartAreaWidth are the size the chart area could
6449 // be if the axes are drawn at their minimum sizes.
6450 // Steps 5 & 6
6451 var totalLeftBoxesWidth = leftPadding;
6452 var totalRightBoxesWidth = rightPadding;
6453 var totalTopBoxesHeight = topPadding;
6454 var totalBottomBoxesHeight = bottomPadding;
6455
6456 // Function to fit a box
6457 function fitBox(box) {
6458 var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minBox) {
6459 return minBox.box === box;
6460 });
6461
6462 if (minBoxSize) {
6463 if (box.isHorizontal()) {
6464 var scaleMargin = {
6465 left: Math.max(totalLeftBoxesWidth, maxHorizontalLeftPadding),
6466 right: Math.max(totalRightBoxesWidth, maxHorizontalRightPadding),
6467 top: 0,
6468 bottom: 0
6469 };
6470
6471 // Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends
6472 // on the margin. Sometimes they need to increase in size slightly
6473 box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin);
6474 } else {
6475 box.update(minBoxSize.minSize.width, maxChartAreaHeight);
6476 }
6477 }
6478 }
6479
6480 // Update, and calculate the left and right margins for the horizontal boxes
6481 helpers.each(leftBoxes.concat(rightBoxes), fitBox);
6482
6483 helpers.each(leftBoxes, function(box) {
6484 totalLeftBoxesWidth += box.width;
6485 });
6486
6487 helpers.each(rightBoxes, function(box) {
6488 totalRightBoxesWidth += box.width;
6489 });
6490
6491 // Set the Left and Right margins for the horizontal boxes
6492 helpers.each(topBoxes.concat(bottomBoxes), fitBox);
6493
6494 // Figure out how much margin is on the top and bottom of the vertical boxes
6495 helpers.each(topBoxes, function(box) {
6496 totalTopBoxesHeight += box.height;
6497 });
6498
6499 helpers.each(bottomBoxes, function(box) {
6500 totalBottomBoxesHeight += box.height;
6501 });
6502
6503 function finalFitVerticalBox(box) {
6504 var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minSize) {
6505 return minSize.box === box;
6506 });
6507
6508 var scaleMargin = {
6509 left: 0,
6510 right: 0,
6511 top: totalTopBoxesHeight,
6512 bottom: totalBottomBoxesHeight
6513 };
6514
6515 if (minBoxSize) {
6516 box.update(minBoxSize.minSize.width, maxChartAreaHeight, scaleMargin);
6517 }
6518 }
6519
6520 // Let the left layout know the final margin
6521 helpers.each(leftBoxes.concat(rightBoxes), finalFitVerticalBox);
6522
6523 // Recalculate because the size of each layout might have changed slightly due to the margins (label rotation for instance)
6524 totalLeftBoxesWidth = leftPadding;
6525 totalRightBoxesWidth = rightPadding;
6526 totalTopBoxesHeight = topPadding;
6527 totalBottomBoxesHeight = bottomPadding;
6528
6529 helpers.each(leftBoxes, function(box) {
6530 totalLeftBoxesWidth += box.width;
6531 });
6532
6533 helpers.each(rightBoxes, function(box) {
6534 totalRightBoxesWidth += box.width;
6535 });
6536
6537 helpers.each(topBoxes, function(box) {
6538 totalTopBoxesHeight += box.height;
6539 });
6540 helpers.each(bottomBoxes, function(box) {
6541 totalBottomBoxesHeight += box.height;
6542 });
6543
6544 // We may be adding some padding to account for rotated x axis labels
6545 var leftPaddingAddition = Math.max(maxHorizontalLeftPadding - totalLeftBoxesWidth, 0);
6546 totalLeftBoxesWidth += leftPaddingAddition;
6547 totalRightBoxesWidth += Math.max(maxHorizontalRightPadding - totalRightBoxesWidth, 0);
6548
6549 var topPaddingAddition = Math.max(maxVerticalTopPadding - totalTopBoxesHeight, 0);
6550 totalTopBoxesHeight += topPaddingAddition;
6551 totalBottomBoxesHeight += Math.max(maxVerticalBottomPadding - totalBottomBoxesHeight, 0);
6552
6553 // Figure out if our chart area changed. This would occur if the dataset layout label rotation
6554 // changed due to the application of the margins in step 6. Since we can only get bigger, this is safe to do
6555 // without calling `fit` again
6556 var newMaxChartAreaHeight = height - totalTopBoxesHeight - totalBottomBoxesHeight;
6557 var newMaxChartAreaWidth = width - totalLeftBoxesWidth - totalRightBoxesWidth;
6558
6559 if (newMaxChartAreaWidth !== maxChartAreaWidth || newMaxChartAreaHeight !== maxChartAreaHeight) {
6560 helpers.each(leftBoxes, function(box) {
6561 box.height = newMaxChartAreaHeight;
6562 });
6563
6564 helpers.each(rightBoxes, function(box) {
6565 box.height = newMaxChartAreaHeight;
6566 });
6567
6568 helpers.each(topBoxes, function(box) {
6569 if (!box.fullWidth) {
6570 box.width = newMaxChartAreaWidth;
6571 }
6572 });
6573
6574 helpers.each(bottomBoxes, function(box) {
6575 if (!box.fullWidth) {
6576 box.width = newMaxChartAreaWidth;
6577 }
6578 });
6579
6580 maxChartAreaHeight = newMaxChartAreaHeight;
6581 maxChartAreaWidth = newMaxChartAreaWidth;
6582 }
6583
6584 // Step 7 - Position the boxes
6585 var left = leftPadding + leftPaddingAddition;
6586 var top = topPadding + topPaddingAddition;
6587
6588 function placeBox(box) {
6589 if (box.isHorizontal()) {
6590 box.left = box.fullWidth ? leftPadding : totalLeftBoxesWidth;
6591 box.right = box.fullWidth ? width - rightPadding : totalLeftBoxesWidth + maxChartAreaWidth;
6592 box.top = top;
6593 box.bottom = top + box.height;
6594
6595 // Move to next point
6596 top = box.bottom;
6597
6598 } else {
6599
6600 box.left = left;
6601 box.right = left + box.width;
6602 box.top = totalTopBoxesHeight;
6603 box.bottom = totalTopBoxesHeight + maxChartAreaHeight;
6604
6605 // Move to next point
6606 left = box.right;
6607 }
6608 }
6609
6610 helpers.each(leftBoxes.concat(topBoxes), placeBox);
6611
6612 // Account for chart width and height
6613 left += maxChartAreaWidth;
6614 top += maxChartAreaHeight;
6615
6616 helpers.each(rightBoxes, placeBox);
6617 helpers.each(bottomBoxes, placeBox);
6618
6619 // Step 8
6620 chart.chartArea = {
6621 left: totalLeftBoxesWidth,
6622 top: totalTopBoxesHeight,
6623 right: totalLeftBoxesWidth + maxChartAreaWidth,
6624 bottom: totalTopBoxesHeight + maxChartAreaHeight
6625 };
6626
6627 // Step 9
6628 helpers.each(chartAreaBoxes, function(box) {
6629 box.left = chart.chartArea.left;
6630 box.top = chart.chartArea.top;
6631 box.right = chart.chartArea.right;
6632 box.bottom = chart.chartArea.bottom;
6633
6634 box.update(maxChartAreaWidth, maxChartAreaHeight);
6635 });
6636 }
6637};
6638
6639},{"45":45}],31:[function(require,module,exports){
6640'use strict';
6641
6642var defaults = require(25);
6643var helpers = require(45);
6644
6645defaults._set('global', {
6646 plugins: {}
6647});
6648
6649/**
6650 * The plugin service singleton
6651 * @namespace Chart.plugins
6652 * @since 2.1.0
6653 */
6654module.exports = {
6655 /**
6656 * Globally registered plugins.
6657 * @private
6658 */
6659 _plugins: [],
6660
6661 /**
6662 * This identifier is used to invalidate the descriptors cache attached to each chart
6663 * when a global plugin is registered or unregistered. In this case, the cache ID is
6664 * incremented and descriptors are regenerated during following API calls.
6665 * @private
6666 */
6667 _cacheId: 0,
6668
6669 /**
6670 * Registers the given plugin(s) if not already registered.
6671 * @param {Array|Object} plugins plugin instance(s).
6672 */
6673 register: function(plugins) {
6674 var p = this._plugins;
6675 ([]).concat(plugins).forEach(function(plugin) {
6676 if (p.indexOf(plugin) === -1) {
6677 p.push(plugin);
6678 }
6679 });
6680
6681 this._cacheId++;
6682 },
6683
6684 /**
6685 * Unregisters the given plugin(s) only if registered.
6686 * @param {Array|Object} plugins plugin instance(s).
6687 */
6688 unregister: function(plugins) {
6689 var p = this._plugins;
6690 ([]).concat(plugins).forEach(function(plugin) {
6691 var idx = p.indexOf(plugin);
6692 if (idx !== -1) {
6693 p.splice(idx, 1);
6694 }
6695 });
6696
6697 this._cacheId++;
6698 },
6699
6700 /**
6701 * Remove all registered plugins.
6702 * @since 2.1.5
6703 */
6704 clear: function() {
6705 this._plugins = [];
6706 this._cacheId++;
6707 },
6708
6709 /**
6710 * Returns the number of registered plugins?
6711 * @returns {Number}
6712 * @since 2.1.5
6713 */
6714 count: function() {
6715 return this._plugins.length;
6716 },
6717
6718 /**
6719 * Returns all registered plugin instances.
6720 * @returns {Array} array of plugin objects.
6721 * @since 2.1.5
6722 */
6723 getAll: function() {
6724 return this._plugins;
6725 },
6726
6727 /**
6728 * Calls enabled plugins for `chart` on the specified hook and with the given args.
6729 * This method immediately returns as soon as a plugin explicitly returns false. The
6730 * returned value can be used, for instance, to interrupt the current action.
6731 * @param {Object} chart - The chart instance for which plugins should be called.
6732 * @param {String} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
6733 * @param {Array} [args] - Extra arguments to apply to the hook call.
6734 * @returns {Boolean} false if any of the plugins return false, else returns true.
6735 */
6736 notify: function(chart, hook, args) {
6737 var descriptors = this.descriptors(chart);
6738 var ilen = descriptors.length;
6739 var i, descriptor, plugin, params, method;
6740
6741 for (i = 0; i < ilen; ++i) {
6742 descriptor = descriptors[i];
6743 plugin = descriptor.plugin;
6744 method = plugin[hook];
6745 if (typeof method === 'function') {
6746 params = [chart].concat(args || []);
6747 params.push(descriptor.options);
6748 if (method.apply(plugin, params) === false) {
6749 return false;
6750 }
6751 }
6752 }
6753
6754 return true;
6755 },
6756
6757 /**
6758 * Returns descriptors of enabled plugins for the given chart.
6759 * @returns {Array} [{ plugin, options }]
6760 * @private
6761 */
6762 descriptors: function(chart) {
6763 var cache = chart.$plugins || (chart.$plugins = {});
6764 if (cache.id === this._cacheId) {
6765 return cache.descriptors;
6766 }
6767
6768 var plugins = [];
6769 var descriptors = [];
6770 var config = (chart && chart.config) || {};
6771 var options = (config.options && config.options.plugins) || {};
6772
6773 this._plugins.concat(config.plugins || []).forEach(function(plugin) {
6774 var idx = plugins.indexOf(plugin);
6775 if (idx !== -1) {
6776 return;
6777 }
6778
6779 var id = plugin.id;
6780 var opts = options[id];
6781 if (opts === false) {
6782 return;
6783 }
6784
6785 if (opts === true) {
6786 opts = helpers.clone(defaults.global.plugins[id]);
6787 }
6788
6789 plugins.push(plugin);
6790 descriptors.push({
6791 plugin: plugin,
6792 options: opts || {}
6793 });
6794 });
6795
6796 cache.descriptors = descriptors;
6797 cache.id = this._cacheId;
6798 return descriptors;
6799 },
6800
6801 /**
6802 * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
6803 * but in some cases, this reference can be changed by the user when updating options.
6804 * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
6805 * @private
6806 */
6807 _invalidate: function(chart) {
6808 delete chart.$plugins;
6809 }
6810};
6811
6812/**
6813 * Plugin extension hooks.
6814 * @interface IPlugin
6815 * @since 2.1.0
6816 */
6817/**
6818 * @method IPlugin#beforeInit
6819 * @desc Called before initializing `chart`.
6820 * @param {Chart.Controller} chart - The chart instance.
6821 * @param {Object} options - The plugin options.
6822 */
6823/**
6824 * @method IPlugin#afterInit
6825 * @desc Called after `chart` has been initialized and before the first update.
6826 * @param {Chart.Controller} chart - The chart instance.
6827 * @param {Object} options - The plugin options.
6828 */
6829/**
6830 * @method IPlugin#beforeUpdate
6831 * @desc Called before updating `chart`. If any plugin returns `false`, the update
6832 * is cancelled (and thus subsequent render(s)) until another `update` is triggered.
6833 * @param {Chart.Controller} chart - The chart instance.
6834 * @param {Object} options - The plugin options.
6835 * @returns {Boolean} `false` to cancel the chart update.
6836 */
6837/**
6838 * @method IPlugin#afterUpdate
6839 * @desc Called after `chart` has been updated and before rendering. Note that this
6840 * hook will not be called if the chart update has been previously cancelled.
6841 * @param {Chart.Controller} chart - The chart instance.
6842 * @param {Object} options - The plugin options.
6843 */
6844/**
6845 * @method IPlugin#beforeDatasetsUpdate
6846 * @desc Called before updating the `chart` datasets. If any plugin returns `false`,
6847 * the datasets update is cancelled until another `update` is triggered.
6848 * @param {Chart.Controller} chart - The chart instance.
6849 * @param {Object} options - The plugin options.
6850 * @returns {Boolean} false to cancel the datasets update.
6851 * @since version 2.1.5
6852*/
6853/**
6854 * @method IPlugin#afterDatasetsUpdate
6855 * @desc Called after the `chart` datasets have been updated. Note that this hook
6856 * will not be called if the datasets update has been previously cancelled.
6857 * @param {Chart.Controller} chart - The chart instance.
6858 * @param {Object} options - The plugin options.
6859 * @since version 2.1.5
6860 */
6861/**
6862 * @method IPlugin#beforeDatasetUpdate
6863 * @desc Called before updating the `chart` dataset at the given `args.index`. If any plugin
6864 * returns `false`, the datasets update is cancelled until another `update` is triggered.
6865 * @param {Chart} chart - The chart instance.
6866 * @param {Object} args - The call arguments.
6867 * @param {Number} args.index - The dataset index.
6868 * @param {Object} args.meta - The dataset metadata.
6869 * @param {Object} options - The plugin options.
6870 * @returns {Boolean} `false` to cancel the chart datasets drawing.
6871 */
6872/**
6873 * @method IPlugin#afterDatasetUpdate
6874 * @desc Called after the `chart` datasets at the given `args.index` has been updated. Note
6875 * that this hook will not be called if the datasets update has been previously cancelled.
6876 * @param {Chart} chart - The chart instance.
6877 * @param {Object} args - The call arguments.
6878 * @param {Number} args.index - The dataset index.
6879 * @param {Object} args.meta - The dataset metadata.
6880 * @param {Object} options - The plugin options.
6881 */
6882/**
6883 * @method IPlugin#beforeLayout
6884 * @desc Called before laying out `chart`. If any plugin returns `false`,
6885 * the layout update is cancelled until another `update` is triggered.
6886 * @param {Chart.Controller} chart - The chart instance.
6887 * @param {Object} options - The plugin options.
6888 * @returns {Boolean} `false` to cancel the chart layout.
6889 */
6890/**
6891 * @method IPlugin#afterLayout
6892 * @desc Called after the `chart` has been layed out. Note that this hook will not
6893 * be called if the layout update has been previously cancelled.
6894 * @param {Chart.Controller} chart - The chart instance.
6895 * @param {Object} options - The plugin options.
6896 */
6897/**
6898 * @method IPlugin#beforeRender
6899 * @desc Called before rendering `chart`. If any plugin returns `false`,
6900 * the rendering is cancelled until another `render` is triggered.
6901 * @param {Chart.Controller} chart - The chart instance.
6902 * @param {Object} options - The plugin options.
6903 * @returns {Boolean} `false` to cancel the chart rendering.
6904 */
6905/**
6906 * @method IPlugin#afterRender
6907 * @desc Called after the `chart` has been fully rendered (and animation completed). Note
6908 * that this hook will not be called if the rendering has been previously cancelled.
6909 * @param {Chart.Controller} chart - The chart instance.
6910 * @param {Object} options - The plugin options.
6911 */
6912/**
6913 * @method IPlugin#beforeDraw
6914 * @desc Called before drawing `chart` at every animation frame specified by the given
6915 * easing value. If any plugin returns `false`, the frame drawing is cancelled until
6916 * another `render` is triggered.
6917 * @param {Chart.Controller} chart - The chart instance.
6918 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
6919 * @param {Object} options - The plugin options.
6920 * @returns {Boolean} `false` to cancel the chart drawing.
6921 */
6922/**
6923 * @method IPlugin#afterDraw
6924 * @desc Called after the `chart` has been drawn for the specific easing value. Note
6925 * that this hook will not be called if the drawing has been previously cancelled.
6926 * @param {Chart.Controller} chart - The chart instance.
6927 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
6928 * @param {Object} options - The plugin options.
6929 */
6930/**
6931 * @method IPlugin#beforeDatasetsDraw
6932 * @desc Called before drawing the `chart` datasets. If any plugin returns `false`,
6933 * the datasets drawing is cancelled until another `render` is triggered.
6934 * @param {Chart.Controller} chart - The chart instance.
6935 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
6936 * @param {Object} options - The plugin options.
6937 * @returns {Boolean} `false` to cancel the chart datasets drawing.
6938 */
6939/**
6940 * @method IPlugin#afterDatasetsDraw
6941 * @desc Called after the `chart` datasets have been drawn. Note that this hook
6942 * will not be called if the datasets drawing has been previously cancelled.
6943 * @param {Chart.Controller} chart - The chart instance.
6944 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
6945 * @param {Object} options - The plugin options.
6946 */
6947/**
6948 * @method IPlugin#beforeDatasetDraw
6949 * @desc Called before drawing the `chart` dataset at the given `args.index` (datasets
6950 * are drawn in the reverse order). If any plugin returns `false`, the datasets drawing
6951 * is cancelled until another `render` is triggered.
6952 * @param {Chart} chart - The chart instance.
6953 * @param {Object} args - The call arguments.
6954 * @param {Number} args.index - The dataset index.
6955 * @param {Object} args.meta - The dataset metadata.
6956 * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
6957 * @param {Object} options - The plugin options.
6958 * @returns {Boolean} `false` to cancel the chart datasets drawing.
6959 */
6960/**
6961 * @method IPlugin#afterDatasetDraw
6962 * @desc Called after the `chart` datasets at the given `args.index` have been drawn
6963 * (datasets are drawn in the reverse order). Note that this hook will not be called
6964 * if the datasets drawing has been previously cancelled.
6965 * @param {Chart} chart - The chart instance.
6966 * @param {Object} args - The call arguments.
6967 * @param {Number} args.index - The dataset index.
6968 * @param {Object} args.meta - The dataset metadata.
6969 * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
6970 * @param {Object} options - The plugin options.
6971 */
6972/**
6973 * @method IPlugin#beforeTooltipDraw
6974 * @desc Called before drawing the `tooltip`. If any plugin returns `false`,
6975 * the tooltip drawing is cancelled until another `render` is triggered.
6976 * @param {Chart} chart - The chart instance.
6977 * @param {Object} args - The call arguments.
6978 * @param {Object} args.tooltip - The tooltip.
6979 * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
6980 * @param {Object} options - The plugin options.
6981 * @returns {Boolean} `false` to cancel the chart tooltip drawing.
6982 */
6983/**
6984 * @method IPlugin#afterTooltipDraw
6985 * @desc Called after drawing the `tooltip`. Note that this hook will not
6986 * be called if the tooltip drawing has been previously cancelled.
6987 * @param {Chart} chart - The chart instance.
6988 * @param {Object} args - The call arguments.
6989 * @param {Object} args.tooltip - The tooltip.
6990 * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
6991 * @param {Object} options - The plugin options.
6992 */
6993/**
6994 * @method IPlugin#beforeEvent
6995 * @desc Called before processing the specified `event`. If any plugin returns `false`,
6996 * the event will be discarded.
6997 * @param {Chart.Controller} chart - The chart instance.
6998 * @param {IEvent} event - The event object.
6999 * @param {Object} options - The plugin options.
7000 */
7001/**
7002 * @method IPlugin#afterEvent
7003 * @desc Called after the `event` has been consumed. Note that this hook
7004 * will not be called if the `event` has been previously discarded.
7005 * @param {Chart.Controller} chart - The chart instance.
7006 * @param {IEvent} event - The event object.
7007 * @param {Object} options - The plugin options.
7008 */
7009/**
7010 * @method IPlugin#resize
7011 * @desc Called after the chart as been resized.
7012 * @param {Chart.Controller} chart - The chart instance.
7013 * @param {Number} size - The new canvas display size (eq. canvas.style width & height).
7014 * @param {Object} options - The plugin options.
7015 */
7016/**
7017 * @method IPlugin#destroy
7018 * @desc Called after the chart as been destroyed.
7019 * @param {Chart.Controller} chart - The chart instance.
7020 * @param {Object} options - The plugin options.
7021 */
7022
7023},{"25":25,"45":45}],32:[function(require,module,exports){
7024'use strict';
7025
7026var defaults = require(25);
7027var Element = require(26);
7028var helpers = require(45);
7029var Ticks = require(34);
7030
7031defaults._set('scale', {
7032 display: true,
7033 position: 'left',
7034 offset: false,
7035
7036 // grid line settings
7037 gridLines: {
7038 display: true,
7039 color: 'rgba(0, 0, 0, 0.1)',
7040 lineWidth: 1,
7041 drawBorder: true,
7042 drawOnChartArea: true,
7043 drawTicks: true,
7044 tickMarkLength: 10,
7045 zeroLineWidth: 1,
7046 zeroLineColor: 'rgba(0,0,0,0.25)',
7047 zeroLineBorderDash: [],
7048 zeroLineBorderDashOffset: 0.0,
7049 offsetGridLines: false,
7050 borderDash: [],
7051 borderDashOffset: 0.0
7052 },
7053
7054 // scale label
7055 scaleLabel: {
7056 // display property
7057 display: false,
7058
7059 // actual label
7060 labelString: '',
7061
7062 // line height
7063 lineHeight: 1.2,
7064
7065 // top/bottom padding
7066 padding: {
7067 top: 4,
7068 bottom: 4
7069 }
7070 },
7071
7072 // label settings
7073 ticks: {
7074 beginAtZero: false,
7075 minRotation: 0,
7076 maxRotation: 50,
7077 mirror: false,
7078 padding: 0,
7079 reverse: false,
7080 display: true,
7081 autoSkip: true,
7082 autoSkipPadding: 0,
7083 labelOffset: 0,
7084 // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
7085 callback: Ticks.formatters.values,
7086 minor: {},
7087 major: {}
7088 }
7089});
7090
7091function labelsFromTicks(ticks) {
7092 var labels = [];
7093 var i, ilen;
7094
7095 for (i = 0, ilen = ticks.length; i < ilen; ++i) {
7096 labels.push(ticks[i].label);
7097 }
7098
7099 return labels;
7100}
7101
7102function getLineValue(scale, index, offsetGridLines) {
7103 var lineValue = scale.getPixelForTick(index);
7104
7105 if (offsetGridLines) {
7106 if (index === 0) {
7107 lineValue -= (scale.getPixelForTick(1) - lineValue) / 2;
7108 } else {
7109 lineValue -= (lineValue - scale.getPixelForTick(index - 1)) / 2;
7110 }
7111 }
7112 return lineValue;
7113}
7114
7115module.exports = function(Chart) {
7116
7117 function computeTextSize(context, tick, font) {
7118 return helpers.isArray(tick) ?
7119 helpers.longestText(context, font, tick) :
7120 context.measureText(tick).width;
7121 }
7122
7123 function parseFontOptions(options) {
7124 var valueOrDefault = helpers.valueOrDefault;
7125 var globalDefaults = defaults.global;
7126 var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
7127 var style = valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle);
7128 var family = valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily);
7129
7130 return {
7131 size: size,
7132 style: style,
7133 family: family,
7134 font: helpers.fontString(size, style, family)
7135 };
7136 }
7137
7138 function parseLineHeight(options) {
7139 return helpers.options.toLineHeight(
7140 helpers.valueOrDefault(options.lineHeight, 1.2),
7141 helpers.valueOrDefault(options.fontSize, defaults.global.defaultFontSize));
7142 }
7143
7144 Chart.Scale = Element.extend({
7145 /**
7146 * Get the padding needed for the scale
7147 * @method getPadding
7148 * @private
7149 * @returns {Padding} the necessary padding
7150 */
7151 getPadding: function() {
7152 var me = this;
7153 return {
7154 left: me.paddingLeft || 0,
7155 top: me.paddingTop || 0,
7156 right: me.paddingRight || 0,
7157 bottom: me.paddingBottom || 0
7158 };
7159 },
7160
7161 /**
7162 * Returns the scale tick objects ({label, major})
7163 * @since 2.7
7164 */
7165 getTicks: function() {
7166 return this._ticks;
7167 },
7168
7169 // These methods are ordered by lifecyle. Utilities then follow.
7170 // Any function defined here is inherited by all scale types.
7171 // Any function can be extended by the scale type
7172
7173 mergeTicksOptions: function() {
7174 var ticks = this.options.ticks;
7175 if (ticks.minor === false) {
7176 ticks.minor = {
7177 display: false
7178 };
7179 }
7180 if (ticks.major === false) {
7181 ticks.major = {
7182 display: false
7183 };
7184 }
7185 for (var key in ticks) {
7186 if (key !== 'major' && key !== 'minor') {
7187 if (typeof ticks.minor[key] === 'undefined') {
7188 ticks.minor[key] = ticks[key];
7189 }
7190 if (typeof ticks.major[key] === 'undefined') {
7191 ticks.major[key] = ticks[key];
7192 }
7193 }
7194 }
7195 },
7196 beforeUpdate: function() {
7197 helpers.callback(this.options.beforeUpdate, [this]);
7198 },
7199 update: function(maxWidth, maxHeight, margins) {
7200 var me = this;
7201 var i, ilen, labels, label, ticks, tick;
7202
7203 // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
7204 me.beforeUpdate();
7205
7206 // Absorb the master measurements
7207 me.maxWidth = maxWidth;
7208 me.maxHeight = maxHeight;
7209 me.margins = helpers.extend({
7210 left: 0,
7211 right: 0,
7212 top: 0,
7213 bottom: 0
7214 }, margins);
7215 me.longestTextCache = me.longestTextCache || {};
7216
7217 // Dimensions
7218 me.beforeSetDimensions();
7219 me.setDimensions();
7220 me.afterSetDimensions();
7221
7222 // Data min/max
7223 me.beforeDataLimits();
7224 me.determineDataLimits();
7225 me.afterDataLimits();
7226
7227 // Ticks - `this.ticks` is now DEPRECATED!
7228 // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
7229 // and must not be accessed directly from outside this class. `this.ticks` being
7230 // around for long time and not marked as private, we can't change its structure
7231 // without unexpected breaking changes. If you need to access the scale ticks,
7232 // use scale.getTicks() instead.
7233
7234 me.beforeBuildTicks();
7235
7236 // New implementations should return an array of objects but for BACKWARD COMPAT,
7237 // we still support no return (`this.ticks` internally set by calling this method).
7238 ticks = me.buildTicks() || [];
7239
7240 me.afterBuildTicks();
7241
7242 me.beforeTickToLabelConversion();
7243
7244 // New implementations should return the formatted tick labels but for BACKWARD
7245 // COMPAT, we still support no return (`this.ticks` internally changed by calling
7246 // this method and supposed to contain only string values).
7247 labels = me.convertTicksToLabels(ticks) || me.ticks;
7248
7249 me.afterTickToLabelConversion();
7250
7251 me.ticks = labels; // BACKWARD COMPATIBILITY
7252
7253 // IMPORTANT: from this point, we consider that `this.ticks` will NEVER change!
7254
7255 // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
7256 for (i = 0, ilen = labels.length; i < ilen; ++i) {
7257 label = labels[i];
7258 tick = ticks[i];
7259 if (!tick) {
7260 ticks.push(tick = {
7261 label: label,
7262 major: false
7263 });
7264 } else {
7265 tick.label = label;
7266 }
7267 }
7268
7269 me._ticks = ticks;
7270
7271 // Tick Rotation
7272 me.beforeCalculateTickRotation();
7273 me.calculateTickRotation();
7274 me.afterCalculateTickRotation();
7275 // Fit
7276 me.beforeFit();
7277 me.fit();
7278 me.afterFit();
7279 //
7280 me.afterUpdate();
7281
7282 return me.minSize;
7283
7284 },
7285 afterUpdate: function() {
7286 helpers.callback(this.options.afterUpdate, [this]);
7287 },
7288
7289 //
7290
7291 beforeSetDimensions: function() {
7292 helpers.callback(this.options.beforeSetDimensions, [this]);
7293 },
7294 setDimensions: function() {
7295 var me = this;
7296 // Set the unconstrained dimension before label rotation
7297 if (me.isHorizontal()) {
7298 // Reset position before calculating rotation
7299 me.width = me.maxWidth;
7300 me.left = 0;
7301 me.right = me.width;
7302 } else {
7303 me.height = me.maxHeight;
7304
7305 // Reset position before calculating rotation
7306 me.top = 0;
7307 me.bottom = me.height;
7308 }
7309
7310 // Reset padding
7311 me.paddingLeft = 0;
7312 me.paddingTop = 0;
7313 me.paddingRight = 0;
7314 me.paddingBottom = 0;
7315 },
7316 afterSetDimensions: function() {
7317 helpers.callback(this.options.afterSetDimensions, [this]);
7318 },
7319
7320 // Data limits
7321 beforeDataLimits: function() {
7322 helpers.callback(this.options.beforeDataLimits, [this]);
7323 },
7324 determineDataLimits: helpers.noop,
7325 afterDataLimits: function() {
7326 helpers.callback(this.options.afterDataLimits, [this]);
7327 },
7328
7329 //
7330 beforeBuildTicks: function() {
7331 helpers.callback(this.options.beforeBuildTicks, [this]);
7332 },
7333 buildTicks: helpers.noop,
7334 afterBuildTicks: function() {
7335 helpers.callback(this.options.afterBuildTicks, [this]);
7336 },
7337
7338 beforeTickToLabelConversion: function() {
7339 helpers.callback(this.options.beforeTickToLabelConversion, [this]);
7340 },
7341 convertTicksToLabels: function() {
7342 var me = this;
7343 // Convert ticks to strings
7344 var tickOpts = me.options.ticks;
7345 me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
7346 },
7347 afterTickToLabelConversion: function() {
7348 helpers.callback(this.options.afterTickToLabelConversion, [this]);
7349 },
7350
7351 //
7352
7353 beforeCalculateTickRotation: function() {
7354 helpers.callback(this.options.beforeCalculateTickRotation, [this]);
7355 },
7356 calculateTickRotation: function() {
7357 var me = this;
7358 var context = me.ctx;
7359 var tickOpts = me.options.ticks;
7360 var labels = labelsFromTicks(me._ticks);
7361
7362 // Get the width of each grid by calculating the difference
7363 // between x offsets between 0 and 1.
7364 var tickFont = parseFontOptions(tickOpts);
7365 context.font = tickFont.font;
7366
7367 var labelRotation = tickOpts.minRotation || 0;
7368
7369 if (labels.length && me.options.display && me.isHorizontal()) {
7370 var originalLabelWidth = helpers.longestText(context, tickFont.font, labels, me.longestTextCache);
7371 var labelWidth = originalLabelWidth;
7372 var cosRotation, sinRotation;
7373
7374 // Allow 3 pixels x2 padding either side for label readability
7375 var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6;
7376
7377 // Max label rotation can be set or default to 90 - also act as a loop counter
7378 while (labelWidth > tickWidth && labelRotation < tickOpts.maxRotation) {
7379 var angleRadians = helpers.toRadians(labelRotation);
7380 cosRotation = Math.cos(angleRadians);
7381 sinRotation = Math.sin(angleRadians);
7382
7383 if (sinRotation * originalLabelWidth > me.maxHeight) {
7384 // go back one step
7385 labelRotation--;
7386 break;
7387 }
7388
7389 labelRotation++;
7390 labelWidth = cosRotation * originalLabelWidth;
7391 }
7392 }
7393
7394 me.labelRotation = labelRotation;
7395 },
7396 afterCalculateTickRotation: function() {
7397 helpers.callback(this.options.afterCalculateTickRotation, [this]);
7398 },
7399
7400 //
7401
7402 beforeFit: function() {
7403 helpers.callback(this.options.beforeFit, [this]);
7404 },
7405 fit: function() {
7406 var me = this;
7407 // Reset
7408 var minSize = me.minSize = {
7409 width: 0,
7410 height: 0
7411 };
7412
7413 var labels = labelsFromTicks(me._ticks);
7414
7415 var opts = me.options;
7416 var tickOpts = opts.ticks;
7417 var scaleLabelOpts = opts.scaleLabel;
7418 var gridLineOpts = opts.gridLines;
7419 var display = opts.display;
7420 var isHorizontal = me.isHorizontal();
7421
7422 var tickFont = parseFontOptions(tickOpts);
7423 var tickMarkLength = opts.gridLines.tickMarkLength;
7424
7425 // Width
7426 if (isHorizontal) {
7427 // subtract the margins to line up with the chartArea if we are a full width scale
7428 minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth;
7429 } else {
7430 minSize.width = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
7431 }
7432
7433 // height
7434 if (isHorizontal) {
7435 minSize.height = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
7436 } else {
7437 minSize.height = me.maxHeight; // fill all the height
7438 }
7439
7440 // Are we showing a title for the scale?
7441 if (scaleLabelOpts.display && display) {
7442 var scaleLabelLineHeight = parseLineHeight(scaleLabelOpts);
7443 var scaleLabelPadding = helpers.options.toPadding(scaleLabelOpts.padding);
7444 var deltaHeight = scaleLabelLineHeight + scaleLabelPadding.height;
7445
7446 if (isHorizontal) {
7447 minSize.height += deltaHeight;
7448 } else {
7449 minSize.width += deltaHeight;
7450 }
7451 }
7452
7453 // Don't bother fitting the ticks if we are not showing them
7454 if (tickOpts.display && display) {
7455 var largestTextWidth = helpers.longestText(me.ctx, tickFont.font, labels, me.longestTextCache);
7456 var tallestLabelHeightInLines = helpers.numberOfLabelLines(labels);
7457 var lineSpace = tickFont.size * 0.5;
7458 var tickPadding = me.options.ticks.padding;
7459
7460 if (isHorizontal) {
7461 // A horizontal axis is more constrained by the height.
7462 me.longestLabelWidth = largestTextWidth;
7463
7464 var angleRadians = helpers.toRadians(me.labelRotation);
7465 var cosRotation = Math.cos(angleRadians);
7466 var sinRotation = Math.sin(angleRadians);
7467
7468 // TODO - improve this calculation
7469 var labelHeight = (sinRotation * largestTextWidth)
7470 + (tickFont.size * tallestLabelHeightInLines)
7471 + (lineSpace * (tallestLabelHeightInLines - 1))
7472 + lineSpace; // padding
7473
7474 minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
7475
7476 me.ctx.font = tickFont.font;
7477 var firstLabelWidth = computeTextSize(me.ctx, labels[0], tickFont.font);
7478 var lastLabelWidth = computeTextSize(me.ctx, labels[labels.length - 1], tickFont.font);
7479
7480 // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
7481 // which means that the right padding is dominated by the font height
7482 if (me.labelRotation !== 0) {
7483 me.paddingLeft = opts.position === 'bottom' ? (cosRotation * firstLabelWidth) + 3 : (cosRotation * lineSpace) + 3; // add 3 px to move away from canvas edges
7484 me.paddingRight = opts.position === 'bottom' ? (cosRotation * lineSpace) + 3 : (cosRotation * lastLabelWidth) + 3;
7485 } else {
7486 me.paddingLeft = firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges
7487 me.paddingRight = lastLabelWidth / 2 + 3;
7488 }
7489 } else {
7490 // A vertical axis is more constrained by the width. Labels are the
7491 // dominant factor here, so get that length first and account for padding
7492 if (tickOpts.mirror) {
7493 largestTextWidth = 0;
7494 } else {
7495 // use lineSpace for consistency with horizontal axis
7496 // tickPadding is not implemented for horizontal
7497 largestTextWidth += tickPadding + lineSpace;
7498 }
7499
7500 minSize.width = Math.min(me.maxWidth, minSize.width + largestTextWidth);
7501
7502 me.paddingTop = tickFont.size / 2;
7503 me.paddingBottom = tickFont.size / 2;
7504 }
7505 }
7506
7507 me.handleMargins();
7508
7509 me.width = minSize.width;
7510 me.height = minSize.height;
7511 },
7512
7513 /**
7514 * Handle margins and padding interactions
7515 * @private
7516 */
7517 handleMargins: function() {
7518 var me = this;
7519 if (me.margins) {
7520 me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0);
7521 me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0);
7522 me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0);
7523 me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0);
7524 }
7525 },
7526
7527 afterFit: function() {
7528 helpers.callback(this.options.afterFit, [this]);
7529 },
7530
7531 // Shared Methods
7532 isHorizontal: function() {
7533 return this.options.position === 'top' || this.options.position === 'bottom';
7534 },
7535 isFullWidth: function() {
7536 return (this.options.fullWidth);
7537 },
7538
7539 // 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
7540 getRightValue: function(rawValue) {
7541 // Null and undefined values first
7542 if (helpers.isNullOrUndef(rawValue)) {
7543 return NaN;
7544 }
7545 // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
7546 if (typeof rawValue === 'number' && !isFinite(rawValue)) {
7547 return NaN;
7548 }
7549 // If it is in fact an object, dive in one more level
7550 if (rawValue) {
7551 if (this.isHorizontal()) {
7552 if (rawValue.x !== undefined) {
7553 return this.getRightValue(rawValue.x);
7554 }
7555 } else if (rawValue.y !== undefined) {
7556 return this.getRightValue(rawValue.y);
7557 }
7558 }
7559
7560 // Value is good, return it
7561 return rawValue;
7562 },
7563
7564 /**
7565 * Used to get the value to display in the tooltip for the data at the given index
7566 * @param index
7567 * @param datasetIndex
7568 */
7569 getLabelForIndex: helpers.noop,
7570
7571 /**
7572 * Returns the location of the given data point. Value can either be an index or a numerical value
7573 * The coordinate (0, 0) is at the upper-left corner of the canvas
7574 * @param value
7575 * @param index
7576 * @param datasetIndex
7577 */
7578 getPixelForValue: helpers.noop,
7579
7580 /**
7581 * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
7582 * The coordinate (0, 0) is at the upper-left corner of the canvas
7583 * @param pixel
7584 */
7585 getValueForPixel: helpers.noop,
7586
7587 /**
7588 * Returns the location of the tick at the given index
7589 * The coordinate (0, 0) is at the upper-left corner of the canvas
7590 */
7591 getPixelForTick: function(index) {
7592 var me = this;
7593 var offset = me.options.offset;
7594 if (me.isHorizontal()) {
7595 var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
7596 var tickWidth = innerWidth / Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
7597 var pixel = (tickWidth * index) + me.paddingLeft;
7598
7599 if (offset) {
7600 pixel += tickWidth / 2;
7601 }
7602
7603 var finalVal = me.left + Math.round(pixel);
7604 finalVal += me.isFullWidth() ? me.margins.left : 0;
7605 return finalVal;
7606 }
7607 var innerHeight = me.height - (me.paddingTop + me.paddingBottom);
7608 return me.top + (index * (innerHeight / (me._ticks.length - 1)));
7609 },
7610
7611 /**
7612 * Utility for getting the pixel location of a percentage of scale
7613 * The coordinate (0, 0) is at the upper-left corner of the canvas
7614 */
7615 getPixelForDecimal: function(decimal) {
7616 var me = this;
7617 if (me.isHorizontal()) {
7618 var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
7619 var valueOffset = (innerWidth * decimal) + me.paddingLeft;
7620
7621 var finalVal = me.left + Math.round(valueOffset);
7622 finalVal += me.isFullWidth() ? me.margins.left : 0;
7623 return finalVal;
7624 }
7625 return me.top + (decimal * me.height);
7626 },
7627
7628 /**
7629 * Returns the pixel for the minimum chart value
7630 * The coordinate (0, 0) is at the upper-left corner of the canvas
7631 */
7632 getBasePixel: function() {
7633 return this.getPixelForValue(this.getBaseValue());
7634 },
7635
7636 getBaseValue: function() {
7637 var me = this;
7638 var min = me.min;
7639 var max = me.max;
7640
7641 return me.beginAtZero ? 0 :
7642 min < 0 && max < 0 ? max :
7643 min > 0 && max > 0 ? min :
7644 0;
7645 },
7646
7647 /**
7648 * Returns a subset of ticks to be plotted to avoid overlapping labels.
7649 * @private
7650 */
7651 _autoSkip: function(ticks) {
7652 var skipRatio;
7653 var me = this;
7654 var isHorizontal = me.isHorizontal();
7655 var optionTicks = me.options.ticks.minor;
7656 var tickCount = ticks.length;
7657 var labelRotationRadians = helpers.toRadians(me.labelRotation);
7658 var cosRotation = Math.cos(labelRotationRadians);
7659 var longestRotatedLabel = me.longestLabelWidth * cosRotation;
7660 var result = [];
7661 var i, tick, shouldSkip;
7662
7663 // figure out the maximum number of gridlines to show
7664 var maxTicks;
7665 if (optionTicks.maxTicksLimit) {
7666 maxTicks = optionTicks.maxTicksLimit;
7667 }
7668
7669 if (isHorizontal) {
7670 skipRatio = false;
7671
7672 if ((longestRotatedLabel + optionTicks.autoSkipPadding) * tickCount > (me.width - (me.paddingLeft + me.paddingRight))) {
7673 skipRatio = 1 + Math.floor(((longestRotatedLabel + optionTicks.autoSkipPadding) * tickCount) / (me.width - (me.paddingLeft + me.paddingRight)));
7674 }
7675
7676 // if they defined a max number of optionTicks,
7677 // increase skipRatio until that number is met
7678 if (maxTicks && tickCount > maxTicks) {
7679 skipRatio = Math.max(skipRatio, Math.floor(tickCount / maxTicks));
7680 }
7681 }
7682
7683 for (i = 0; i < tickCount; i++) {
7684 tick = ticks[i];
7685
7686 // Since we always show the last tick,we need may need to hide the last shown one before
7687 shouldSkip = (skipRatio > 1 && i % skipRatio > 0) || (i % skipRatio === 0 && i + skipRatio >= tickCount);
7688 if (shouldSkip && i !== tickCount - 1) {
7689 // leave tick in place but make sure it's not displayed (#4635)
7690 delete tick.label;
7691 }
7692 result.push(tick);
7693 }
7694 return result;
7695 },
7696
7697 // Actually draw the scale on the canvas
7698 // @param {rectangle} chartArea : the area of the chart to draw full grid lines on
7699 draw: function(chartArea) {
7700 var me = this;
7701 var options = me.options;
7702 if (!options.display) {
7703 return;
7704 }
7705
7706 var context = me.ctx;
7707 var globalDefaults = defaults.global;
7708 var optionTicks = options.ticks.minor;
7709 var optionMajorTicks = options.ticks.major || optionTicks;
7710 var gridLines = options.gridLines;
7711 var scaleLabel = options.scaleLabel;
7712
7713 var isRotated = me.labelRotation !== 0;
7714 var isHorizontal = me.isHorizontal();
7715
7716 var ticks = optionTicks.autoSkip ? me._autoSkip(me.getTicks()) : me.getTicks();
7717 var tickFontColor = helpers.valueOrDefault(optionTicks.fontColor, globalDefaults.defaultFontColor);
7718 var tickFont = parseFontOptions(optionTicks);
7719 var majorTickFontColor = helpers.valueOrDefault(optionMajorTicks.fontColor, globalDefaults.defaultFontColor);
7720 var majorTickFont = parseFontOptions(optionMajorTicks);
7721
7722 var tl = gridLines.drawTicks ? gridLines.tickMarkLength : 0;
7723
7724 var scaleLabelFontColor = helpers.valueOrDefault(scaleLabel.fontColor, globalDefaults.defaultFontColor);
7725 var scaleLabelFont = parseFontOptions(scaleLabel);
7726 var scaleLabelPadding = helpers.options.toPadding(scaleLabel.padding);
7727 var labelRotationRadians = helpers.toRadians(me.labelRotation);
7728
7729 var itemsToDraw = [];
7730
7731 var xTickStart = options.position === 'right' ? me.left : me.right - tl;
7732 var xTickEnd = options.position === 'right' ? me.left + tl : me.right;
7733 var yTickStart = options.position === 'bottom' ? me.top : me.bottom - tl;
7734 var yTickEnd = options.position === 'bottom' ? me.top + tl : me.bottom;
7735
7736 helpers.each(ticks, function(tick, index) {
7737 // autoskipper skipped this tick (#4635)
7738 if (helpers.isNullOrUndef(tick.label)) {
7739 return;
7740 }
7741
7742 var label = tick.label;
7743 var lineWidth, lineColor, borderDash, borderDashOffset;
7744 if (index === me.zeroLineIndex && options.offset === gridLines.offsetGridLines) {
7745 // Draw the first index specially
7746 lineWidth = gridLines.zeroLineWidth;
7747 lineColor = gridLines.zeroLineColor;
7748 borderDash = gridLines.zeroLineBorderDash;
7749 borderDashOffset = gridLines.zeroLineBorderDashOffset;
7750 } else {
7751 lineWidth = helpers.valueAtIndexOrDefault(gridLines.lineWidth, index);
7752 lineColor = helpers.valueAtIndexOrDefault(gridLines.color, index);
7753 borderDash = helpers.valueOrDefault(gridLines.borderDash, globalDefaults.borderDash);
7754 borderDashOffset = helpers.valueOrDefault(gridLines.borderDashOffset, globalDefaults.borderDashOffset);
7755 }
7756
7757 // Common properties
7758 var tx1, ty1, tx2, ty2, x1, y1, x2, y2, labelX, labelY;
7759 var textAlign = 'middle';
7760 var textBaseline = 'middle';
7761 var tickPadding = optionTicks.padding;
7762
7763 if (isHorizontal) {
7764 var labelYOffset = tl + tickPadding;
7765
7766 if (options.position === 'bottom') {
7767 // bottom
7768 textBaseline = !isRotated ? 'top' : 'middle';
7769 textAlign = !isRotated ? 'center' : 'right';
7770 labelY = me.top + labelYOffset;
7771 } else {
7772 // top
7773 textBaseline = !isRotated ? 'bottom' : 'middle';
7774 textAlign = !isRotated ? 'center' : 'left';
7775 labelY = me.bottom - labelYOffset;
7776 }
7777
7778 var xLineValue = getLineValue(me, index, gridLines.offsetGridLines && ticks.length > 1);
7779 if (xLineValue < me.left) {
7780 lineColor = 'rgba(0,0,0,0)';
7781 }
7782 xLineValue += helpers.aliasPixel(lineWidth);
7783
7784 labelX = me.getPixelForTick(index) + optionTicks.labelOffset; // x values for optionTicks (need to consider offsetLabel option)
7785
7786 tx1 = tx2 = x1 = x2 = xLineValue;
7787 ty1 = yTickStart;
7788 ty2 = yTickEnd;
7789 y1 = chartArea.top;
7790 y2 = chartArea.bottom;
7791 } else {
7792 var isLeft = options.position === 'left';
7793 var labelXOffset;
7794
7795 if (optionTicks.mirror) {
7796 textAlign = isLeft ? 'left' : 'right';
7797 labelXOffset = tickPadding;
7798 } else {
7799 textAlign = isLeft ? 'right' : 'left';
7800 labelXOffset = tl + tickPadding;
7801 }
7802
7803 labelX = isLeft ? me.right - labelXOffset : me.left + labelXOffset;
7804
7805 var yLineValue = getLineValue(me, index, gridLines.offsetGridLines && ticks.length > 1);
7806 if (yLineValue < me.top) {
7807 lineColor = 'rgba(0,0,0,0)';
7808 }
7809 yLineValue += helpers.aliasPixel(lineWidth);
7810
7811 labelY = me.getPixelForTick(index) + optionTicks.labelOffset;
7812
7813 tx1 = xTickStart;
7814 tx2 = xTickEnd;
7815 x1 = chartArea.left;
7816 x2 = chartArea.right;
7817 ty1 = ty2 = y1 = y2 = yLineValue;
7818 }
7819
7820 itemsToDraw.push({
7821 tx1: tx1,
7822 ty1: ty1,
7823 tx2: tx2,
7824 ty2: ty2,
7825 x1: x1,
7826 y1: y1,
7827 x2: x2,
7828 y2: y2,
7829 labelX: labelX,
7830 labelY: labelY,
7831 glWidth: lineWidth,
7832 glColor: lineColor,
7833 glBorderDash: borderDash,
7834 glBorderDashOffset: borderDashOffset,
7835 rotation: -1 * labelRotationRadians,
7836 label: label,
7837 major: tick.major,
7838 textBaseline: textBaseline,
7839 textAlign: textAlign
7840 });
7841 });
7842
7843 // Draw all of the tick labels, tick marks, and grid lines at the correct places
7844 helpers.each(itemsToDraw, function(itemToDraw) {
7845 if (gridLines.display) {
7846 context.save();
7847 context.lineWidth = itemToDraw.glWidth;
7848 context.strokeStyle = itemToDraw.glColor;
7849 if (context.setLineDash) {
7850 context.setLineDash(itemToDraw.glBorderDash);
7851 context.lineDashOffset = itemToDraw.glBorderDashOffset;
7852 }
7853
7854 context.beginPath();
7855
7856 if (gridLines.drawTicks) {
7857 context.moveTo(itemToDraw.tx1, itemToDraw.ty1);
7858 context.lineTo(itemToDraw.tx2, itemToDraw.ty2);
7859 }
7860
7861 if (gridLines.drawOnChartArea) {
7862 context.moveTo(itemToDraw.x1, itemToDraw.y1);
7863 context.lineTo(itemToDraw.x2, itemToDraw.y2);
7864 }
7865
7866 context.stroke();
7867 context.restore();
7868 }
7869
7870 if (optionTicks.display) {
7871 // Make sure we draw text in the correct color and font
7872 context.save();
7873 context.translate(itemToDraw.labelX, itemToDraw.labelY);
7874 context.rotate(itemToDraw.rotation);
7875 context.font = itemToDraw.major ? majorTickFont.font : tickFont.font;
7876 context.fillStyle = itemToDraw.major ? majorTickFontColor : tickFontColor;
7877 context.textBaseline = itemToDraw.textBaseline;
7878 context.textAlign = itemToDraw.textAlign;
7879
7880 var label = itemToDraw.label;
7881 if (helpers.isArray(label)) {
7882 for (var i = 0, y = 0; i < label.length; ++i) {
7883 // We just make sure the multiline element is a string here..
7884 context.fillText('' + label[i], 0, y);
7885 // apply same lineSpacing as calculated @ L#320
7886 y += (tickFont.size * 1.5);
7887 }
7888 } else {
7889 context.fillText(label, 0, 0);
7890 }
7891 context.restore();
7892 }
7893 });
7894
7895 if (scaleLabel.display) {
7896 // Draw the scale label
7897 var scaleLabelX;
7898 var scaleLabelY;
7899 var rotation = 0;
7900 var halfLineHeight = parseLineHeight(scaleLabel) / 2;
7901
7902 if (isHorizontal) {
7903 scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width
7904 scaleLabelY = options.position === 'bottom'
7905 ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
7906 : me.top + halfLineHeight + scaleLabelPadding.top;
7907 } else {
7908 var isLeft = options.position === 'left';
7909 scaleLabelX = isLeft
7910 ? me.left + halfLineHeight + scaleLabelPadding.top
7911 : me.right - halfLineHeight - scaleLabelPadding.top;
7912 scaleLabelY = me.top + ((me.bottom - me.top) / 2);
7913 rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
7914 }
7915
7916 context.save();
7917 context.translate(scaleLabelX, scaleLabelY);
7918 context.rotate(rotation);
7919 context.textAlign = 'center';
7920 context.textBaseline = 'middle';
7921 context.fillStyle = scaleLabelFontColor; // render in correct colour
7922 context.font = scaleLabelFont.font;
7923 context.fillText(scaleLabel.labelString, 0, 0);
7924 context.restore();
7925 }
7926
7927 if (gridLines.drawBorder) {
7928 // Draw the line at the edge of the axis
7929 context.lineWidth = helpers.valueAtIndexOrDefault(gridLines.lineWidth, 0);
7930 context.strokeStyle = helpers.valueAtIndexOrDefault(gridLines.color, 0);
7931 var x1 = me.left;
7932 var x2 = me.right;
7933 var y1 = me.top;
7934 var y2 = me.bottom;
7935
7936 var aliasPixel = helpers.aliasPixel(context.lineWidth);
7937 if (isHorizontal) {
7938 y1 = y2 = options.position === 'top' ? me.bottom : me.top;
7939 y1 += aliasPixel;
7940 y2 += aliasPixel;
7941 } else {
7942 x1 = x2 = options.position === 'left' ? me.right : me.left;
7943 x1 += aliasPixel;
7944 x2 += aliasPixel;
7945 }
7946
7947 context.beginPath();
7948 context.moveTo(x1, y1);
7949 context.lineTo(x2, y2);
7950 context.stroke();
7951 }
7952 }
7953 });
7954};
7955
7956},{"25":25,"26":26,"34":34,"45":45}],33:[function(require,module,exports){
7957'use strict';
7958
7959var defaults = require(25);
7960var helpers = require(45);
7961var layouts = require(30);
7962
7963module.exports = function(Chart) {
7964
7965 Chart.scaleService = {
7966 // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
7967 // use the new chart options to grab the correct scale
7968 constructors: {},
7969 // Use a registration function so that we can move to an ES6 map when we no longer need to support
7970 // old browsers
7971
7972 // Scale config defaults
7973 defaults: {},
7974 registerScaleType: function(type, scaleConstructor, scaleDefaults) {
7975 this.constructors[type] = scaleConstructor;
7976 this.defaults[type] = helpers.clone(scaleDefaults);
7977 },
7978 getScaleConstructor: function(type) {
7979 return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
7980 },
7981 getScaleDefaults: function(type) {
7982 // Return the scale defaults merged with the global settings so that we always use the latest ones
7983 return this.defaults.hasOwnProperty(type) ? helpers.merge({}, [defaults.scale, this.defaults[type]]) : {};
7984 },
7985 updateScaleDefaults: function(type, additions) {
7986 var me = this;
7987 if (me.defaults.hasOwnProperty(type)) {
7988 me.defaults[type] = helpers.extend(me.defaults[type], additions);
7989 }
7990 },
7991 addScalesToLayout: function(chart) {
7992 // Adds each scale to the chart.boxes array to be sized accordingly
7993 helpers.each(chart.scales, function(scale) {
7994 // Set ILayoutItem parameters for backwards compatibility
7995 scale.fullWidth = scale.options.fullWidth;
7996 scale.position = scale.options.position;
7997 scale.weight = scale.options.weight;
7998 layouts.addBox(chart, scale);
7999 });
8000 }
8001 };
8002};
8003
8004},{"25":25,"30":30,"45":45}],34:[function(require,module,exports){
8005'use strict';
8006
8007var helpers = require(45);
8008
8009/**
8010 * Namespace to hold static tick generation functions
8011 * @namespace Chart.Ticks
8012 */
8013module.exports = {
8014 /**
8015 * Namespace to hold formatters for different types of ticks
8016 * @namespace Chart.Ticks.formatters
8017 */
8018 formatters: {
8019 /**
8020 * Formatter for value labels
8021 * @method Chart.Ticks.formatters.values
8022 * @param value the value to display
8023 * @return {String|Array} the label to display
8024 */
8025 values: function(value) {
8026 return helpers.isArray(value) ? value : '' + value;
8027 },
8028
8029 /**
8030 * Formatter for linear numeric ticks
8031 * @method Chart.Ticks.formatters.linear
8032 * @param tickValue {Number} the value to be formatted
8033 * @param index {Number} the position of the tickValue parameter in the ticks array
8034 * @param ticks {Array<Number>} the list of ticks being converted
8035 * @return {String} string representation of the tickValue parameter
8036 */
8037 linear: function(tickValue, index, ticks) {
8038 // If we have lots of ticks, don't use the ones
8039 var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
8040
8041 // If we have a number like 2.5 as the delta, figure out how many decimal places we need
8042 if (Math.abs(delta) > 1) {
8043 if (tickValue !== Math.floor(tickValue)) {
8044 // not an integer
8045 delta = tickValue - Math.floor(tickValue);
8046 }
8047 }
8048
8049 var logDelta = helpers.log10(Math.abs(delta));
8050 var tickString = '';
8051
8052 if (tickValue !== 0) {
8053 var numDecimal = -1 * Math.floor(logDelta);
8054 numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
8055 tickString = tickValue.toFixed(numDecimal);
8056 } else {
8057 tickString = '0'; // never show decimal places for 0
8058 }
8059
8060 return tickString;
8061 },
8062
8063 logarithmic: function(tickValue, index, ticks) {
8064 var remain = tickValue / (Math.pow(10, Math.floor(helpers.log10(tickValue))));
8065
8066 if (tickValue === 0) {
8067 return '0';
8068 } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
8069 return tickValue.toExponential();
8070 }
8071 return '';
8072 }
8073 }
8074};
8075
8076},{"45":45}],35:[function(require,module,exports){
8077'use strict';
8078
8079var defaults = require(25);
8080var Element = require(26);
8081var helpers = require(45);
8082
8083defaults._set('global', {
8084 tooltips: {
8085 enabled: true,
8086 custom: null,
8087 mode: 'nearest',
8088 position: 'average',
8089 intersect: true,
8090 backgroundColor: 'rgba(0,0,0,0.8)',
8091 titleFontStyle: 'bold',
8092 titleSpacing: 2,
8093 titleMarginBottom: 6,
8094 titleFontColor: '#fff',
8095 titleAlign: 'left',
8096 bodySpacing: 2,
8097 bodyFontColor: '#fff',
8098 bodyAlign: 'left',
8099 footerFontStyle: 'bold',
8100 footerSpacing: 2,
8101 footerMarginTop: 6,
8102 footerFontColor: '#fff',
8103 footerAlign: 'left',
8104 yPadding: 6,
8105 xPadding: 6,
8106 caretPadding: 2,
8107 caretSize: 5,
8108 cornerRadius: 6,
8109 multiKeyBackground: '#fff',
8110 displayColors: true,
8111 borderColor: 'rgba(0,0,0,0)',
8112 borderWidth: 0,
8113 callbacks: {
8114 // Args are: (tooltipItems, data)
8115 beforeTitle: helpers.noop,
8116 title: function(tooltipItems, data) {
8117 // Pick first xLabel for now
8118 var title = '';
8119 var labels = data.labels;
8120 var labelCount = labels ? labels.length : 0;
8121
8122 if (tooltipItems.length > 0) {
8123 var item = tooltipItems[0];
8124
8125 if (item.xLabel) {
8126 title = item.xLabel;
8127 } else if (labelCount > 0 && item.index < labelCount) {
8128 title = labels[item.index];
8129 }
8130 }
8131
8132 return title;
8133 },
8134 afterTitle: helpers.noop,
8135
8136 // Args are: (tooltipItems, data)
8137 beforeBody: helpers.noop,
8138
8139 // Args are: (tooltipItem, data)
8140 beforeLabel: helpers.noop,
8141 label: function(tooltipItem, data) {
8142 var label = data.datasets[tooltipItem.datasetIndex].label || '';
8143
8144 if (label) {
8145 label += ': ';
8146 }
8147 label += tooltipItem.yLabel;
8148 return label;
8149 },
8150 labelColor: function(tooltipItem, chart) {
8151 var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
8152 var activeElement = meta.data[tooltipItem.index];
8153 var view = activeElement._view;
8154 return {
8155 borderColor: view.borderColor,
8156 backgroundColor: view.backgroundColor
8157 };
8158 },
8159 labelTextColor: function() {
8160 return this._options.bodyFontColor;
8161 },
8162 afterLabel: helpers.noop,
8163
8164 // Args are: (tooltipItems, data)
8165 afterBody: helpers.noop,
8166
8167 // Args are: (tooltipItems, data)
8168 beforeFooter: helpers.noop,
8169 footer: helpers.noop,
8170 afterFooter: helpers.noop
8171 }
8172 }
8173});
8174
8175module.exports = function(Chart) {
8176
8177 /**
8178 * Helper method to merge the opacity into a color
8179 */
8180 function mergeOpacity(colorString, opacity) {
8181 var color = helpers.color(colorString);
8182 return color.alpha(opacity * color.alpha()).rgbaString();
8183 }
8184
8185 // Helper to push or concat based on if the 2nd parameter is an array or not
8186 function pushOrConcat(base, toPush) {
8187 if (toPush) {
8188 if (helpers.isArray(toPush)) {
8189 // base = base.concat(toPush);
8190 Array.prototype.push.apply(base, toPush);
8191 } else {
8192 base.push(toPush);
8193 }
8194 }
8195
8196 return base;
8197 }
8198
8199 // Private helper to create a tooltip item model
8200 // @param element : the chart element (point, arc, bar) to create the tooltip item for
8201 // @return : new tooltip item
8202 function createTooltipItem(element) {
8203 var xScale = element._xScale;
8204 var yScale = element._yScale || element._scale; // handle radar || polarArea charts
8205 var index = element._index;
8206 var datasetIndex = element._datasetIndex;
8207
8208 return {
8209 xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
8210 yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
8211 index: index,
8212 datasetIndex: datasetIndex,
8213 x: element._model.x,
8214 y: element._model.y
8215 };
8216 }
8217
8218 /**
8219 * Helper to get the reset model for the tooltip
8220 * @param tooltipOpts {Object} the tooltip options
8221 */
8222 function getBaseModel(tooltipOpts) {
8223 var globalDefaults = defaults.global;
8224 var valueOrDefault = helpers.valueOrDefault;
8225
8226 return {
8227 // Positioning
8228 xPadding: tooltipOpts.xPadding,
8229 yPadding: tooltipOpts.yPadding,
8230 xAlign: tooltipOpts.xAlign,
8231 yAlign: tooltipOpts.yAlign,
8232
8233 // Body
8234 bodyFontColor: tooltipOpts.bodyFontColor,
8235 _bodyFontFamily: valueOrDefault(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
8236 _bodyFontStyle: valueOrDefault(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
8237 _bodyAlign: tooltipOpts.bodyAlign,
8238 bodyFontSize: valueOrDefault(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
8239 bodySpacing: tooltipOpts.bodySpacing,
8240
8241 // Title
8242 titleFontColor: tooltipOpts.titleFontColor,
8243 _titleFontFamily: valueOrDefault(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
8244 _titleFontStyle: valueOrDefault(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
8245 titleFontSize: valueOrDefault(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
8246 _titleAlign: tooltipOpts.titleAlign,
8247 titleSpacing: tooltipOpts.titleSpacing,
8248 titleMarginBottom: tooltipOpts.titleMarginBottom,
8249
8250 // Footer
8251 footerFontColor: tooltipOpts.footerFontColor,
8252 _footerFontFamily: valueOrDefault(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
8253 _footerFontStyle: valueOrDefault(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
8254 footerFontSize: valueOrDefault(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
8255 _footerAlign: tooltipOpts.footerAlign,
8256 footerSpacing: tooltipOpts.footerSpacing,
8257 footerMarginTop: tooltipOpts.footerMarginTop,
8258
8259 // Appearance
8260 caretSize: tooltipOpts.caretSize,
8261 cornerRadius: tooltipOpts.cornerRadius,
8262 backgroundColor: tooltipOpts.backgroundColor,
8263 opacity: 0,
8264 legendColorBackground: tooltipOpts.multiKeyBackground,
8265 displayColors: tooltipOpts.displayColors,
8266 borderColor: tooltipOpts.borderColor,
8267 borderWidth: tooltipOpts.borderWidth
8268 };
8269 }
8270
8271 /**
8272 * Get the size of the tooltip
8273 */
8274 function getTooltipSize(tooltip, model) {
8275 var ctx = tooltip._chart.ctx;
8276
8277 var height = model.yPadding * 2; // Tooltip Padding
8278 var width = 0;
8279
8280 // Count of all lines in the body
8281 var body = model.body;
8282 var combinedBodyLength = body.reduce(function(count, bodyItem) {
8283 return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
8284 }, 0);
8285 combinedBodyLength += model.beforeBody.length + model.afterBody.length;
8286
8287 var titleLineCount = model.title.length;
8288 var footerLineCount = model.footer.length;
8289 var titleFontSize = model.titleFontSize;
8290 var bodyFontSize = model.bodyFontSize;
8291 var footerFontSize = model.footerFontSize;
8292
8293 height += titleLineCount * titleFontSize; // Title Lines
8294 height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
8295 height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
8296 height += combinedBodyLength * bodyFontSize; // Body Lines
8297 height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
8298 height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
8299 height += footerLineCount * (footerFontSize); // Footer Lines
8300 height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
8301
8302 // Title width
8303 var widthPadding = 0;
8304 var maxLineWidth = function(line) {
8305 width = Math.max(width, ctx.measureText(line).width + widthPadding);
8306 };
8307
8308 ctx.font = helpers.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
8309 helpers.each(model.title, maxLineWidth);
8310
8311 // Body width
8312 ctx.font = helpers.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
8313 helpers.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
8314
8315 // Body lines may include some extra width due to the color box
8316 widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
8317 helpers.each(body, function(bodyItem) {
8318 helpers.each(bodyItem.before, maxLineWidth);
8319 helpers.each(bodyItem.lines, maxLineWidth);
8320 helpers.each(bodyItem.after, maxLineWidth);
8321 });
8322
8323 // Reset back to 0
8324 widthPadding = 0;
8325
8326 // Footer width
8327 ctx.font = helpers.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
8328 helpers.each(model.footer, maxLineWidth);
8329
8330 // Add padding
8331 width += 2 * model.xPadding;
8332
8333 return {
8334 width: width,
8335 height: height
8336 };
8337 }
8338
8339 /**
8340 * Helper to get the alignment of a tooltip given the size
8341 */
8342 function determineAlignment(tooltip, size) {
8343 var model = tooltip._model;
8344 var chart = tooltip._chart;
8345 var chartArea = tooltip._chart.chartArea;
8346 var xAlign = 'center';
8347 var yAlign = 'center';
8348
8349 if (model.y < size.height) {
8350 yAlign = 'top';
8351 } else if (model.y > (chart.height - size.height)) {
8352 yAlign = 'bottom';
8353 }
8354
8355 var lf, rf; // functions to determine left, right alignment
8356 var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
8357 var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
8358 var midX = (chartArea.left + chartArea.right) / 2;
8359 var midY = (chartArea.top + chartArea.bottom) / 2;
8360
8361 if (yAlign === 'center') {
8362 lf = function(x) {
8363 return x <= midX;
8364 };
8365 rf = function(x) {
8366 return x > midX;
8367 };
8368 } else {
8369 lf = function(x) {
8370 return x <= (size.width / 2);
8371 };
8372 rf = function(x) {
8373 return x >= (chart.width - (size.width / 2));
8374 };
8375 }
8376
8377 olf = function(x) {
8378 return x + size.width + model.caretSize + model.caretPadding > chart.width;
8379 };
8380 orf = function(x) {
8381 return x - size.width - model.caretSize - model.caretPadding < 0;
8382 };
8383 yf = function(y) {
8384 return y <= midY ? 'top' : 'bottom';
8385 };
8386
8387 if (lf(model.x)) {
8388 xAlign = 'left';
8389
8390 // Is tooltip too wide and goes over the right side of the chart.?
8391 if (olf(model.x)) {
8392 xAlign = 'center';
8393 yAlign = yf(model.y);
8394 }
8395 } else if (rf(model.x)) {
8396 xAlign = 'right';
8397
8398 // Is tooltip too wide and goes outside left edge of canvas?
8399 if (orf(model.x)) {
8400 xAlign = 'center';
8401 yAlign = yf(model.y);
8402 }
8403 }
8404
8405 var opts = tooltip._options;
8406 return {
8407 xAlign: opts.xAlign ? opts.xAlign : xAlign,
8408 yAlign: opts.yAlign ? opts.yAlign : yAlign
8409 };
8410 }
8411
8412 /**
8413 * @Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
8414 */
8415 function getBackgroundPoint(vm, size, alignment, chart) {
8416 // Background Position
8417 var x = vm.x;
8418 var y = vm.y;
8419
8420 var caretSize = vm.caretSize;
8421 var caretPadding = vm.caretPadding;
8422 var cornerRadius = vm.cornerRadius;
8423 var xAlign = alignment.xAlign;
8424 var yAlign = alignment.yAlign;
8425 var paddingAndSize = caretSize + caretPadding;
8426 var radiusAndPadding = cornerRadius + caretPadding;
8427
8428 if (xAlign === 'right') {
8429 x -= size.width;
8430 } else if (xAlign === 'center') {
8431 x -= (size.width / 2);
8432 if (x + size.width > chart.width) {
8433 x = chart.width - size.width;
8434 }
8435 if (x < 0) {
8436 x = 0;
8437 }
8438 }
8439
8440 if (yAlign === 'top') {
8441 y += paddingAndSize;
8442 } else if (yAlign === 'bottom') {
8443 y -= size.height + paddingAndSize;
8444 } else {
8445 y -= (size.height / 2);
8446 }
8447
8448 if (yAlign === 'center') {
8449 if (xAlign === 'left') {
8450 x += paddingAndSize;
8451 } else if (xAlign === 'right') {
8452 x -= paddingAndSize;
8453 }
8454 } else if (xAlign === 'left') {
8455 x -= radiusAndPadding;
8456 } else if (xAlign === 'right') {
8457 x += radiusAndPadding;
8458 }
8459
8460 return {
8461 x: x,
8462 y: y
8463 };
8464 }
8465
8466 Chart.Tooltip = Element.extend({
8467 initialize: function() {
8468 this._model = getBaseModel(this._options);
8469 this._lastActive = [];
8470 },
8471
8472 // Get the title
8473 // Args are: (tooltipItem, data)
8474 getTitle: function() {
8475 var me = this;
8476 var opts = me._options;
8477 var callbacks = opts.callbacks;
8478
8479 var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
8480 var title = callbacks.title.apply(me, arguments);
8481 var afterTitle = callbacks.afterTitle.apply(me, arguments);
8482
8483 var lines = [];
8484 lines = pushOrConcat(lines, beforeTitle);
8485 lines = pushOrConcat(lines, title);
8486 lines = pushOrConcat(lines, afterTitle);
8487
8488 return lines;
8489 },
8490
8491 // Args are: (tooltipItem, data)
8492 getBeforeBody: function() {
8493 var lines = this._options.callbacks.beforeBody.apply(this, arguments);
8494 return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : [];
8495 },
8496
8497 // Args are: (tooltipItem, data)
8498 getBody: function(tooltipItems, data) {
8499 var me = this;
8500 var callbacks = me._options.callbacks;
8501 var bodyItems = [];
8502
8503 helpers.each(tooltipItems, function(tooltipItem) {
8504 var bodyItem = {
8505 before: [],
8506 lines: [],
8507 after: []
8508 };
8509 pushOrConcat(bodyItem.before, callbacks.beforeLabel.call(me, tooltipItem, data));
8510 pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
8511 pushOrConcat(bodyItem.after, callbacks.afterLabel.call(me, tooltipItem, data));
8512
8513 bodyItems.push(bodyItem);
8514 });
8515
8516 return bodyItems;
8517 },
8518
8519 // Args are: (tooltipItem, data)
8520 getAfterBody: function() {
8521 var lines = this._options.callbacks.afterBody.apply(this, arguments);
8522 return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : [];
8523 },
8524
8525 // Get the footer and beforeFooter and afterFooter lines
8526 // Args are: (tooltipItem, data)
8527 getFooter: function() {
8528 var me = this;
8529 var callbacks = me._options.callbacks;
8530
8531 var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
8532 var footer = callbacks.footer.apply(me, arguments);
8533 var afterFooter = callbacks.afterFooter.apply(me, arguments);
8534
8535 var lines = [];
8536 lines = pushOrConcat(lines, beforeFooter);
8537 lines = pushOrConcat(lines, footer);
8538 lines = pushOrConcat(lines, afterFooter);
8539
8540 return lines;
8541 },
8542
8543 update: function(changed) {
8544 var me = this;
8545 var opts = me._options;
8546
8547 // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
8548 // 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
8549 // which breaks any animations.
8550 var existingModel = me._model;
8551 var model = me._model = getBaseModel(opts);
8552 var active = me._active;
8553
8554 var data = me._data;
8555
8556 // In the case where active.length === 0 we need to keep these at existing values for good animations
8557 var alignment = {
8558 xAlign: existingModel.xAlign,
8559 yAlign: existingModel.yAlign
8560 };
8561 var backgroundPoint = {
8562 x: existingModel.x,
8563 y: existingModel.y
8564 };
8565 var tooltipSize = {
8566 width: existingModel.width,
8567 height: existingModel.height
8568 };
8569 var tooltipPosition = {
8570 x: existingModel.caretX,
8571 y: existingModel.caretY
8572 };
8573
8574 var i, len;
8575
8576 if (active.length) {
8577 model.opacity = 1;
8578
8579 var labelColors = [];
8580 var labelTextColors = [];
8581 tooltipPosition = Chart.Tooltip.positioners[opts.position].call(me, active, me._eventPosition);
8582
8583 var tooltipItems = [];
8584 for (i = 0, len = active.length; i < len; ++i) {
8585 tooltipItems.push(createTooltipItem(active[i]));
8586 }
8587
8588 // If the user provided a filter function, use it to modify the tooltip items
8589 if (opts.filter) {
8590 tooltipItems = tooltipItems.filter(function(a) {
8591 return opts.filter(a, data);
8592 });
8593 }
8594
8595 // If the user provided a sorting function, use it to modify the tooltip items
8596 if (opts.itemSort) {
8597 tooltipItems = tooltipItems.sort(function(a, b) {
8598 return opts.itemSort(a, b, data);
8599 });
8600 }
8601
8602 // Determine colors for boxes
8603 helpers.each(tooltipItems, function(tooltipItem) {
8604 labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
8605 labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
8606 });
8607
8608
8609 // Build the Text Lines
8610 model.title = me.getTitle(tooltipItems, data);
8611 model.beforeBody = me.getBeforeBody(tooltipItems, data);
8612 model.body = me.getBody(tooltipItems, data);
8613 model.afterBody = me.getAfterBody(tooltipItems, data);
8614 model.footer = me.getFooter(tooltipItems, data);
8615
8616 // Initial positioning and colors
8617 model.x = Math.round(tooltipPosition.x);
8618 model.y = Math.round(tooltipPosition.y);
8619 model.caretPadding = opts.caretPadding;
8620 model.labelColors = labelColors;
8621 model.labelTextColors = labelTextColors;
8622
8623 // data points
8624 model.dataPoints = tooltipItems;
8625
8626 // We need to determine alignment of the tooltip
8627 tooltipSize = getTooltipSize(this, model);
8628 alignment = determineAlignment(this, tooltipSize);
8629 // Final Size and Position
8630 backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
8631 } else {
8632 model.opacity = 0;
8633 }
8634
8635 model.xAlign = alignment.xAlign;
8636 model.yAlign = alignment.yAlign;
8637 model.x = backgroundPoint.x;
8638 model.y = backgroundPoint.y;
8639 model.width = tooltipSize.width;
8640 model.height = tooltipSize.height;
8641
8642 // Point where the caret on the tooltip points to
8643 model.caretX = tooltipPosition.x;
8644 model.caretY = tooltipPosition.y;
8645
8646 me._model = model;
8647
8648 if (changed && opts.custom) {
8649 opts.custom.call(me, model);
8650 }
8651
8652 return me;
8653 },
8654 drawCaret: function(tooltipPoint, size) {
8655 var ctx = this._chart.ctx;
8656 var vm = this._view;
8657 var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
8658
8659 ctx.lineTo(caretPosition.x1, caretPosition.y1);
8660 ctx.lineTo(caretPosition.x2, caretPosition.y2);
8661 ctx.lineTo(caretPosition.x3, caretPosition.y3);
8662 },
8663 getCaretPosition: function(tooltipPoint, size, vm) {
8664 var x1, x2, x3, y1, y2, y3;
8665 var caretSize = vm.caretSize;
8666 var cornerRadius = vm.cornerRadius;
8667 var xAlign = vm.xAlign;
8668 var yAlign = vm.yAlign;
8669 var ptX = tooltipPoint.x;
8670 var ptY = tooltipPoint.y;
8671 var width = size.width;
8672 var height = size.height;
8673
8674 if (yAlign === 'center') {
8675 y2 = ptY + (height / 2);
8676
8677 if (xAlign === 'left') {
8678 x1 = ptX;
8679 x2 = x1 - caretSize;
8680 x3 = x1;
8681
8682 y1 = y2 + caretSize;
8683 y3 = y2 - caretSize;
8684 } else {
8685 x1 = ptX + width;
8686 x2 = x1 + caretSize;
8687 x3 = x1;
8688
8689 y1 = y2 - caretSize;
8690 y3 = y2 + caretSize;
8691 }
8692 } else {
8693 if (xAlign === 'left') {
8694 x2 = ptX + cornerRadius + (caretSize);
8695 x1 = x2 - caretSize;
8696 x3 = x2 + caretSize;
8697 } else if (xAlign === 'right') {
8698 x2 = ptX + width - cornerRadius - caretSize;
8699 x1 = x2 - caretSize;
8700 x3 = x2 + caretSize;
8701 } else {
8702 x2 = vm.caretX;
8703 x1 = x2 - caretSize;
8704 x3 = x2 + caretSize;
8705 }
8706 if (yAlign === 'top') {
8707 y1 = ptY;
8708 y2 = y1 - caretSize;
8709 y3 = y1;
8710 } else {
8711 y1 = ptY + height;
8712 y2 = y1 + caretSize;
8713 y3 = y1;
8714 // invert drawing order
8715 var tmp = x3;
8716 x3 = x1;
8717 x1 = tmp;
8718 }
8719 }
8720 return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
8721 },
8722 drawTitle: function(pt, vm, ctx, opacity) {
8723 var title = vm.title;
8724
8725 if (title.length) {
8726 ctx.textAlign = vm._titleAlign;
8727 ctx.textBaseline = 'top';
8728
8729 var titleFontSize = vm.titleFontSize;
8730 var titleSpacing = vm.titleSpacing;
8731
8732 ctx.fillStyle = mergeOpacity(vm.titleFontColor, opacity);
8733 ctx.font = helpers.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
8734
8735 var i, len;
8736 for (i = 0, len = title.length; i < len; ++i) {
8737 ctx.fillText(title[i], pt.x, pt.y);
8738 pt.y += titleFontSize + titleSpacing; // Line Height and spacing
8739
8740 if (i + 1 === title.length) {
8741 pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
8742 }
8743 }
8744 }
8745 },
8746 drawBody: function(pt, vm, ctx, opacity) {
8747 var bodyFontSize = vm.bodyFontSize;
8748 var bodySpacing = vm.bodySpacing;
8749 var body = vm.body;
8750
8751 ctx.textAlign = vm._bodyAlign;
8752 ctx.textBaseline = 'top';
8753 ctx.font = helpers.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
8754
8755 // Before Body
8756 var xLinePadding = 0;
8757 var fillLineOfText = function(line) {
8758 ctx.fillText(line, pt.x + xLinePadding, pt.y);
8759 pt.y += bodyFontSize + bodySpacing;
8760 };
8761
8762 // Before body lines
8763 ctx.fillStyle = mergeOpacity(vm.bodyFontColor, opacity);
8764 helpers.each(vm.beforeBody, fillLineOfText);
8765
8766 var drawColorBoxes = vm.displayColors;
8767 xLinePadding = drawColorBoxes ? (bodyFontSize + 2) : 0;
8768
8769 // Draw body lines now
8770 helpers.each(body, function(bodyItem, i) {
8771 var textColor = mergeOpacity(vm.labelTextColors[i], opacity);
8772 ctx.fillStyle = textColor;
8773 helpers.each(bodyItem.before, fillLineOfText);
8774
8775 helpers.each(bodyItem.lines, function(line) {
8776 // Draw Legend-like boxes if needed
8777 if (drawColorBoxes) {
8778 // Fill a white rect so that colours merge nicely if the opacity is < 1
8779 ctx.fillStyle = mergeOpacity(vm.legendColorBackground, opacity);
8780 ctx.fillRect(pt.x, pt.y, bodyFontSize, bodyFontSize);
8781
8782 // Border
8783 ctx.lineWidth = 1;
8784 ctx.strokeStyle = mergeOpacity(vm.labelColors[i].borderColor, opacity);
8785 ctx.strokeRect(pt.x, pt.y, bodyFontSize, bodyFontSize);
8786
8787 // Inner square
8788 ctx.fillStyle = mergeOpacity(vm.labelColors[i].backgroundColor, opacity);
8789 ctx.fillRect(pt.x + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
8790 ctx.fillStyle = textColor;
8791 }
8792
8793 fillLineOfText(line);
8794 });
8795
8796 helpers.each(bodyItem.after, fillLineOfText);
8797 });
8798
8799 // Reset back to 0 for after body
8800 xLinePadding = 0;
8801
8802 // After body lines
8803 helpers.each(vm.afterBody, fillLineOfText);
8804 pt.y -= bodySpacing; // Remove last body spacing
8805 },
8806 drawFooter: function(pt, vm, ctx, opacity) {
8807 var footer = vm.footer;
8808
8809 if (footer.length) {
8810 pt.y += vm.footerMarginTop;
8811
8812 ctx.textAlign = vm._footerAlign;
8813 ctx.textBaseline = 'top';
8814
8815 ctx.fillStyle = mergeOpacity(vm.footerFontColor, opacity);
8816 ctx.font = helpers.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
8817
8818 helpers.each(footer, function(line) {
8819 ctx.fillText(line, pt.x, pt.y);
8820 pt.y += vm.footerFontSize + vm.footerSpacing;
8821 });
8822 }
8823 },
8824 drawBackground: function(pt, vm, ctx, tooltipSize, opacity) {
8825 ctx.fillStyle = mergeOpacity(vm.backgroundColor, opacity);
8826 ctx.strokeStyle = mergeOpacity(vm.borderColor, opacity);
8827 ctx.lineWidth = vm.borderWidth;
8828 var xAlign = vm.xAlign;
8829 var yAlign = vm.yAlign;
8830 var x = pt.x;
8831 var y = pt.y;
8832 var width = tooltipSize.width;
8833 var height = tooltipSize.height;
8834 var radius = vm.cornerRadius;
8835
8836 ctx.beginPath();
8837 ctx.moveTo(x + radius, y);
8838 if (yAlign === 'top') {
8839 this.drawCaret(pt, tooltipSize);
8840 }
8841 ctx.lineTo(x + width - radius, y);
8842 ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
8843 if (yAlign === 'center' && xAlign === 'right') {
8844 this.drawCaret(pt, tooltipSize);
8845 }
8846 ctx.lineTo(x + width, y + height - radius);
8847 ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
8848 if (yAlign === 'bottom') {
8849 this.drawCaret(pt, tooltipSize);
8850 }
8851 ctx.lineTo(x + radius, y + height);
8852 ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
8853 if (yAlign === 'center' && xAlign === 'left') {
8854 this.drawCaret(pt, tooltipSize);
8855 }
8856 ctx.lineTo(x, y + radius);
8857 ctx.quadraticCurveTo(x, y, x + radius, y);
8858 ctx.closePath();
8859
8860 ctx.fill();
8861
8862 if (vm.borderWidth > 0) {
8863 ctx.stroke();
8864 }
8865 },
8866 draw: function() {
8867 var ctx = this._chart.ctx;
8868 var vm = this._view;
8869
8870 if (vm.opacity === 0) {
8871 return;
8872 }
8873
8874 var tooltipSize = {
8875 width: vm.width,
8876 height: vm.height
8877 };
8878 var pt = {
8879 x: vm.x,
8880 y: vm.y
8881 };
8882
8883 // IE11/Edge does not like very small opacities, so snap to 0
8884 var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
8885
8886 // Truthy/falsey value for empty tooltip
8887 var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
8888
8889 if (this._options.enabled && hasTooltipContent) {
8890 // Draw Background
8891 this.drawBackground(pt, vm, ctx, tooltipSize, opacity);
8892
8893 // Draw Title, Body, and Footer
8894 pt.x += vm.xPadding;
8895 pt.y += vm.yPadding;
8896
8897 // Titles
8898 this.drawTitle(pt, vm, ctx, opacity);
8899
8900 // Body
8901 this.drawBody(pt, vm, ctx, opacity);
8902
8903 // Footer
8904 this.drawFooter(pt, vm, ctx, opacity);
8905 }
8906 },
8907
8908 /**
8909 * Handle an event
8910 * @private
8911 * @param {IEvent} event - The event to handle
8912 * @returns {Boolean} true if the tooltip changed
8913 */
8914 handleEvent: function(e) {
8915 var me = this;
8916 var options = me._options;
8917 var changed = false;
8918
8919 me._lastActive = me._lastActive || [];
8920
8921 // Find Active Elements for tooltips
8922 if (e.type === 'mouseout') {
8923 me._active = [];
8924 } else {
8925 me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
8926 }
8927
8928 // Remember Last Actives
8929 changed = !helpers.arrayEquals(me._active, me._lastActive);
8930
8931 // Only handle target event on tooltip change
8932 if (changed) {
8933 me._lastActive = me._active;
8934
8935 if (options.enabled || options.custom) {
8936 me._eventPosition = {
8937 x: e.x,
8938 y: e.y
8939 };
8940
8941 me.update(true);
8942 me.pivot();
8943 }
8944 }
8945
8946 return changed;
8947 }
8948 });
8949
8950 /**
8951 * @namespace Chart.Tooltip.positioners
8952 */
8953 Chart.Tooltip.positioners = {
8954 /**
8955 * Average mode places the tooltip at the average position of the elements shown
8956 * @function Chart.Tooltip.positioners.average
8957 * @param elements {ChartElement[]} the elements being displayed in the tooltip
8958 * @returns {Point} tooltip position
8959 */
8960 average: function(elements) {
8961 if (!elements.length) {
8962 return false;
8963 }
8964
8965 var i, len;
8966 var x = 0;
8967 var y = 0;
8968 var count = 0;
8969
8970 for (i = 0, len = elements.length; i < len; ++i) {
8971 var el = elements[i];
8972 if (el && el.hasValue()) {
8973 var pos = el.tooltipPosition();
8974 x += pos.x;
8975 y += pos.y;
8976 ++count;
8977 }
8978 }
8979
8980 return {
8981 x: Math.round(x / count),
8982 y: Math.round(y / count)
8983 };
8984 },
8985
8986 /**
8987 * Gets the tooltip position nearest of the item nearest to the event position
8988 * @function Chart.Tooltip.positioners.nearest
8989 * @param elements {Chart.Element[]} the tooltip elements
8990 * @param eventPosition {Point} the position of the event in canvas coordinates
8991 * @returns {Point} the tooltip position
8992 */
8993 nearest: function(elements, eventPosition) {
8994 var x = eventPosition.x;
8995 var y = eventPosition.y;
8996 var minDistance = Number.POSITIVE_INFINITY;
8997 var i, len, nearestElement;
8998
8999 for (i = 0, len = elements.length; i < len; ++i) {
9000 var el = elements[i];
9001 if (el && el.hasValue()) {
9002 var center = el.getCenterPoint();
9003 var d = helpers.distanceBetweenPoints(eventPosition, center);
9004
9005 if (d < minDistance) {
9006 minDistance = d;
9007 nearestElement = el;
9008 }
9009 }
9010 }
9011
9012 if (nearestElement) {
9013 var tp = nearestElement.tooltipPosition();
9014 x = tp.x;
9015 y = tp.y;
9016 }
9017
9018 return {
9019 x: x,
9020 y: y
9021 };
9022 }
9023 };
9024};
9025
9026},{"25":25,"26":26,"45":45}],36:[function(require,module,exports){
9027'use strict';
9028
9029var defaults = require(25);
9030var Element = require(26);
9031var helpers = require(45);
9032
9033defaults._set('global', {
9034 elements: {
9035 arc: {
9036 backgroundColor: defaults.global.defaultColor,
9037 borderColor: '#fff',
9038 borderWidth: 2
9039 }
9040 }
9041});
9042
9043module.exports = Element.extend({
9044 inLabelRange: function(mouseX) {
9045 var vm = this._view;
9046
9047 if (vm) {
9048 return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
9049 }
9050 return false;
9051 },
9052
9053 inRange: function(chartX, chartY) {
9054 var vm = this._view;
9055
9056 if (vm) {
9057 var pointRelativePosition = helpers.getAngleFromPoint(vm, {x: chartX, y: chartY});
9058 var angle = pointRelativePosition.angle;
9059 var distance = pointRelativePosition.distance;
9060
9061 // Sanitise angle range
9062 var startAngle = vm.startAngle;
9063 var endAngle = vm.endAngle;
9064 while (endAngle < startAngle) {
9065 endAngle += 2.0 * Math.PI;
9066 }
9067 while (angle > endAngle) {
9068 angle -= 2.0 * Math.PI;
9069 }
9070 while (angle < startAngle) {
9071 angle += 2.0 * Math.PI;
9072 }
9073
9074 // Check if within the range of the open/close angle
9075 var betweenAngles = (angle >= startAngle && angle <= endAngle);
9076 var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
9077
9078 return (betweenAngles && withinRadius);
9079 }
9080 return false;
9081 },
9082
9083 getCenterPoint: function() {
9084 var vm = this._view;
9085 var halfAngle = (vm.startAngle + vm.endAngle) / 2;
9086 var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
9087 return {
9088 x: vm.x + Math.cos(halfAngle) * halfRadius,
9089 y: vm.y + Math.sin(halfAngle) * halfRadius
9090 };
9091 },
9092
9093 getArea: function() {
9094 var vm = this._view;
9095 return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
9096 },
9097
9098 tooltipPosition: function() {
9099 var vm = this._view;
9100 var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
9101 var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
9102
9103 return {
9104 x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
9105 y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
9106 };
9107 },
9108
9109 draw: function() {
9110 var ctx = this._chart.ctx;
9111 var vm = this._view;
9112 var sA = vm.startAngle;
9113 var eA = vm.endAngle;
9114
9115 ctx.beginPath();
9116
9117 ctx.arc(vm.x, vm.y, vm.outerRadius, sA, eA);
9118 ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
9119
9120 ctx.closePath();
9121 ctx.strokeStyle = vm.borderColor;
9122 ctx.lineWidth = vm.borderWidth;
9123
9124 ctx.fillStyle = vm.backgroundColor;
9125
9126 ctx.fill();
9127 ctx.lineJoin = 'bevel';
9128
9129 if (vm.borderWidth) {
9130 ctx.stroke();
9131 }
9132 }
9133});
9134
9135},{"25":25,"26":26,"45":45}],37:[function(require,module,exports){
9136'use strict';
9137
9138var defaults = require(25);
9139var Element = require(26);
9140var helpers = require(45);
9141
9142var globalDefaults = defaults.global;
9143
9144defaults._set('global', {
9145 elements: {
9146 line: {
9147 tension: 0.4,
9148 backgroundColor: globalDefaults.defaultColor,
9149 borderWidth: 3,
9150 borderColor: globalDefaults.defaultColor,
9151 borderCapStyle: 'butt',
9152 borderDash: [],
9153 borderDashOffset: 0.0,
9154 borderJoinStyle: 'miter',
9155 capBezierPoints: true,
9156 fill: true, // do we fill in the area between the line and its base axis
9157 }
9158 }
9159});
9160
9161module.exports = Element.extend({
9162 draw: function() {
9163 var me = this;
9164 var vm = me._view;
9165 var ctx = me._chart.ctx;
9166 var spanGaps = vm.spanGaps;
9167 var points = me._children.slice(); // clone array
9168 var globalOptionLineElements = globalDefaults.elements.line;
9169 var lastDrawnIndex = -1;
9170 var index, current, previous, currentVM;
9171
9172 // If we are looping, adding the first point again
9173 if (me._loop && points.length) {
9174 points.push(points[0]);
9175 }
9176
9177 ctx.save();
9178
9179 // Stroke Line Options
9180 ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
9181
9182 // IE 9 and 10 do not support line dash
9183 if (ctx.setLineDash) {
9184 ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
9185 }
9186
9187 ctx.lineDashOffset = vm.borderDashOffset || globalOptionLineElements.borderDashOffset;
9188 ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
9189 ctx.lineWidth = vm.borderWidth || globalOptionLineElements.borderWidth;
9190 ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
9191
9192 // Stroke Line
9193 ctx.beginPath();
9194 lastDrawnIndex = -1;
9195
9196 for (index = 0; index < points.length; ++index) {
9197 current = points[index];
9198 previous = helpers.previousItem(points, index);
9199 currentVM = current._view;
9200
9201 // First point moves to it's starting position no matter what
9202 if (index === 0) {
9203 if (!currentVM.skip) {
9204 ctx.moveTo(currentVM.x, currentVM.y);
9205 lastDrawnIndex = index;
9206 }
9207 } else {
9208 previous = lastDrawnIndex === -1 ? previous : points[lastDrawnIndex];
9209
9210 if (!currentVM.skip) {
9211 if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
9212 // There was a gap and this is the first point after the gap
9213 ctx.moveTo(currentVM.x, currentVM.y);
9214 } else {
9215 // Line to next point
9216 helpers.canvas.lineTo(ctx, previous._view, current._view);
9217 }
9218 lastDrawnIndex = index;
9219 }
9220 }
9221 }
9222
9223 ctx.stroke();
9224 ctx.restore();
9225 }
9226});
9227
9228},{"25":25,"26":26,"45":45}],38:[function(require,module,exports){
9229'use strict';
9230
9231var defaults = require(25);
9232var Element = require(26);
9233var helpers = require(45);
9234
9235var defaultColor = defaults.global.defaultColor;
9236
9237defaults._set('global', {
9238 elements: {
9239 point: {
9240 radius: 3,
9241 pointStyle: 'circle',
9242 backgroundColor: defaultColor,
9243 borderColor: defaultColor,
9244 borderWidth: 1,
9245 // Hover
9246 hitRadius: 1,
9247 hoverRadius: 4,
9248 hoverBorderWidth: 1
9249 }
9250 }
9251});
9252
9253function xRange(mouseX) {
9254 var vm = this._view;
9255 return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
9256}
9257
9258function yRange(mouseY) {
9259 var vm = this._view;
9260 return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
9261}
9262
9263module.exports = Element.extend({
9264 inRange: function(mouseX, mouseY) {
9265 var vm = this._view;
9266 return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
9267 },
9268
9269 inLabelRange: xRange,
9270 inXRange: xRange,
9271 inYRange: yRange,
9272
9273 getCenterPoint: function() {
9274 var vm = this._view;
9275 return {
9276 x: vm.x,
9277 y: vm.y
9278 };
9279 },
9280
9281 getArea: function() {
9282 return Math.PI * Math.pow(this._view.radius, 2);
9283 },
9284
9285 tooltipPosition: function() {
9286 var vm = this._view;
9287 return {
9288 x: vm.x,
9289 y: vm.y,
9290 padding: vm.radius + vm.borderWidth
9291 };
9292 },
9293
9294 draw: function(chartArea) {
9295 var vm = this._view;
9296 var model = this._model;
9297 var ctx = this._chart.ctx;
9298 var pointStyle = vm.pointStyle;
9299 var radius = vm.radius;
9300 var x = vm.x;
9301 var y = vm.y;
9302 var color = helpers.color;
9303 var errMargin = 1.01; // 1.01 is margin for Accumulated error. (Especially Edge, IE.)
9304 var ratio = 0;
9305
9306 if (vm.skip) {
9307 return;
9308 }
9309
9310 ctx.strokeStyle = vm.borderColor || defaultColor;
9311 ctx.lineWidth = helpers.valueOrDefault(vm.borderWidth, defaults.global.elements.point.borderWidth);
9312 ctx.fillStyle = vm.backgroundColor || defaultColor;
9313
9314 // Cliping for Points.
9315 // going out from inner charArea?
9316 if ((chartArea !== undefined) && ((model.x < chartArea.left) || (chartArea.right * errMargin < model.x) || (model.y < chartArea.top) || (chartArea.bottom * errMargin < model.y))) {
9317 // Point fade out
9318 if (model.x < chartArea.left) {
9319 ratio = (x - model.x) / (chartArea.left - model.x);
9320 } else if (chartArea.right * errMargin < model.x) {
9321 ratio = (model.x - x) / (model.x - chartArea.right);
9322 } else if (model.y < chartArea.top) {
9323 ratio = (y - model.y) / (chartArea.top - model.y);
9324 } else if (chartArea.bottom * errMargin < model.y) {
9325 ratio = (model.y - y) / (model.y - chartArea.bottom);
9326 }
9327 ratio = Math.round(ratio * 100) / 100;
9328 ctx.strokeStyle = color(ctx.strokeStyle).alpha(ratio).rgbString();
9329 ctx.fillStyle = color(ctx.fillStyle).alpha(ratio).rgbString();
9330 }
9331
9332 helpers.canvas.drawPoint(ctx, pointStyle, radius, x, y);
9333 }
9334});
9335
9336},{"25":25,"26":26,"45":45}],39:[function(require,module,exports){
9337'use strict';
9338
9339var defaults = require(25);
9340var Element = require(26);
9341
9342defaults._set('global', {
9343 elements: {
9344 rectangle: {
9345 backgroundColor: defaults.global.defaultColor,
9346 borderColor: defaults.global.defaultColor,
9347 borderSkipped: 'bottom',
9348 borderWidth: 0
9349 }
9350 }
9351});
9352
9353function isVertical(bar) {
9354 return bar._view.width !== undefined;
9355}
9356
9357/**
9358 * Helper function to get the bounds of the bar regardless of the orientation
9359 * @param bar {Chart.Element.Rectangle} the bar
9360 * @return {Bounds} bounds of the bar
9361 * @private
9362 */
9363function getBarBounds(bar) {
9364 var vm = bar._view;
9365 var x1, x2, y1, y2;
9366
9367 if (isVertical(bar)) {
9368 // vertical
9369 var halfWidth = vm.width / 2;
9370 x1 = vm.x - halfWidth;
9371 x2 = vm.x + halfWidth;
9372 y1 = Math.min(vm.y, vm.base);
9373 y2 = Math.max(vm.y, vm.base);
9374 } else {
9375 // horizontal bar
9376 var halfHeight = vm.height / 2;
9377 x1 = Math.min(vm.x, vm.base);
9378 x2 = Math.max(vm.x, vm.base);
9379 y1 = vm.y - halfHeight;
9380 y2 = vm.y + halfHeight;
9381 }
9382
9383 return {
9384 left: x1,
9385 top: y1,
9386 right: x2,
9387 bottom: y2
9388 };
9389}
9390
9391module.exports = Element.extend({
9392 draw: function() {
9393 var ctx = this._chart.ctx;
9394 var vm = this._view;
9395 var left, right, top, bottom, signX, signY, borderSkipped;
9396 var borderWidth = vm.borderWidth;
9397
9398 if (!vm.horizontal) {
9399 // bar
9400 left = vm.x - vm.width / 2;
9401 right = vm.x + vm.width / 2;
9402 top = vm.y;
9403 bottom = vm.base;
9404 signX = 1;
9405 signY = bottom > top ? 1 : -1;
9406 borderSkipped = vm.borderSkipped || 'bottom';
9407 } else {
9408 // horizontal bar
9409 left = vm.base;
9410 right = vm.x;
9411 top = vm.y - vm.height / 2;
9412 bottom = vm.y + vm.height / 2;
9413 signX = right > left ? 1 : -1;
9414 signY = 1;
9415 borderSkipped = vm.borderSkipped || 'left';
9416 }
9417
9418 // Canvas doesn't allow us to stroke inside the width so we can
9419 // adjust the sizes to fit if we're setting a stroke on the line
9420 if (borderWidth) {
9421 // borderWidth shold be less than bar width and bar height.
9422 var barSize = Math.min(Math.abs(left - right), Math.abs(top - bottom));
9423 borderWidth = borderWidth > barSize ? barSize : borderWidth;
9424 var halfStroke = borderWidth / 2;
9425 // Adjust borderWidth when bar top position is near vm.base(zero).
9426 var borderLeft = left + (borderSkipped !== 'left' ? halfStroke * signX : 0);
9427 var borderRight = right + (borderSkipped !== 'right' ? -halfStroke * signX : 0);
9428 var borderTop = top + (borderSkipped !== 'top' ? halfStroke * signY : 0);
9429 var borderBottom = bottom + (borderSkipped !== 'bottom' ? -halfStroke * signY : 0);
9430 // not become a vertical line?
9431 if (borderLeft !== borderRight) {
9432 top = borderTop;
9433 bottom = borderBottom;
9434 }
9435 // not become a horizontal line?
9436 if (borderTop !== borderBottom) {
9437 left = borderLeft;
9438 right = borderRight;
9439 }
9440 }
9441
9442 ctx.beginPath();
9443 ctx.fillStyle = vm.backgroundColor;
9444 ctx.strokeStyle = vm.borderColor;
9445 ctx.lineWidth = borderWidth;
9446
9447 // Corner points, from bottom-left to bottom-right clockwise
9448 // | 1 2 |
9449 // | 0 3 |
9450 var corners = [
9451 [left, bottom],
9452 [left, top],
9453 [right, top],
9454 [right, bottom]
9455 ];
9456
9457 // Find first (starting) corner with fallback to 'bottom'
9458 var borders = ['bottom', 'left', 'top', 'right'];
9459 var startCorner = borders.indexOf(borderSkipped, 0);
9460 if (startCorner === -1) {
9461 startCorner = 0;
9462 }
9463
9464 function cornerAt(index) {
9465 return corners[(startCorner + index) % 4];
9466 }
9467
9468 // Draw rectangle from 'startCorner'
9469 var corner = cornerAt(0);
9470 ctx.moveTo(corner[0], corner[1]);
9471
9472 for (var i = 1; i < 4; i++) {
9473 corner = cornerAt(i);
9474 ctx.lineTo(corner[0], corner[1]);
9475 }
9476
9477 ctx.fill();
9478 if (borderWidth) {
9479 ctx.stroke();
9480 }
9481 },
9482
9483 height: function() {
9484 var vm = this._view;
9485 return vm.base - vm.y;
9486 },
9487
9488 inRange: function(mouseX, mouseY) {
9489 var inRange = false;
9490
9491 if (this._view) {
9492 var bounds = getBarBounds(this);
9493 inRange = mouseX >= bounds.left && mouseX <= bounds.right && mouseY >= bounds.top && mouseY <= bounds.bottom;
9494 }
9495
9496 return inRange;
9497 },
9498
9499 inLabelRange: function(mouseX, mouseY) {
9500 var me = this;
9501 if (!me._view) {
9502 return false;
9503 }
9504
9505 var inRange = false;
9506 var bounds = getBarBounds(me);
9507
9508 if (isVertical(me)) {
9509 inRange = mouseX >= bounds.left && mouseX <= bounds.right;
9510 } else {
9511 inRange = mouseY >= bounds.top && mouseY <= bounds.bottom;
9512 }
9513
9514 return inRange;
9515 },
9516
9517 inXRange: function(mouseX) {
9518 var bounds = getBarBounds(this);
9519 return mouseX >= bounds.left && mouseX <= bounds.right;
9520 },
9521
9522 inYRange: function(mouseY) {
9523 var bounds = getBarBounds(this);
9524 return mouseY >= bounds.top && mouseY <= bounds.bottom;
9525 },
9526
9527 getCenterPoint: function() {
9528 var vm = this._view;
9529 var x, y;
9530 if (isVertical(this)) {
9531 x = vm.x;
9532 y = (vm.y + vm.base) / 2;
9533 } else {
9534 x = (vm.x + vm.base) / 2;
9535 y = vm.y;
9536 }
9537
9538 return {x: x, y: y};
9539 },
9540
9541 getArea: function() {
9542 var vm = this._view;
9543 return vm.width * Math.abs(vm.y - vm.base);
9544 },
9545
9546 tooltipPosition: function() {
9547 var vm = this._view;
9548 return {
9549 x: vm.x,
9550 y: vm.y
9551 };
9552 }
9553});
9554
9555},{"25":25,"26":26}],40:[function(require,module,exports){
9556'use strict';
9557
9558module.exports = {};
9559module.exports.Arc = require(36);
9560module.exports.Line = require(37);
9561module.exports.Point = require(38);
9562module.exports.Rectangle = require(39);
9563
9564},{"36":36,"37":37,"38":38,"39":39}],41:[function(require,module,exports){
9565'use strict';
9566
9567var helpers = require(42);
9568
9569/**
9570 * @namespace Chart.helpers.canvas
9571 */
9572var exports = module.exports = {
9573 /**
9574 * Clears the entire canvas associated to the given `chart`.
9575 * @param {Chart} chart - The chart for which to clear the canvas.
9576 */
9577 clear: function(chart) {
9578 chart.ctx.clearRect(0, 0, chart.width, chart.height);
9579 },
9580
9581 /**
9582 * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
9583 * given size (width, height) and the same `radius` for all corners.
9584 * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
9585 * @param {Number} x - The x axis of the coordinate for the rectangle starting point.
9586 * @param {Number} y - The y axis of the coordinate for the rectangle starting point.
9587 * @param {Number} width - The rectangle's width.
9588 * @param {Number} height - The rectangle's height.
9589 * @param {Number} radius - The rounded amount (in pixels) for the four corners.
9590 * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
9591 */
9592 roundedRect: function(ctx, x, y, width, height, radius) {
9593 if (radius) {
9594 var rx = Math.min(radius, width / 2);
9595 var ry = Math.min(radius, height / 2);
9596
9597 ctx.moveTo(x + rx, y);
9598 ctx.lineTo(x + width - rx, y);
9599 ctx.quadraticCurveTo(x + width, y, x + width, y + ry);
9600 ctx.lineTo(x + width, y + height - ry);
9601 ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height);
9602 ctx.lineTo(x + rx, y + height);
9603 ctx.quadraticCurveTo(x, y + height, x, y + height - ry);
9604 ctx.lineTo(x, y + ry);
9605 ctx.quadraticCurveTo(x, y, x + rx, y);
9606 } else {
9607 ctx.rect(x, y, width, height);
9608 }
9609 },
9610
9611 drawPoint: function(ctx, style, radius, x, y) {
9612 var type, edgeLength, xOffset, yOffset, height, size;
9613
9614 if (style && typeof style === 'object') {
9615 type = style.toString();
9616 if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
9617 ctx.drawImage(style, x - style.width / 2, y - style.height / 2, style.width, style.height);
9618 return;
9619 }
9620 }
9621
9622 if (isNaN(radius) || radius <= 0) {
9623 return;
9624 }
9625
9626 switch (style) {
9627 // Default includes circle
9628 default:
9629 ctx.beginPath();
9630 ctx.arc(x, y, radius, 0, Math.PI * 2);
9631 ctx.closePath();
9632 ctx.fill();
9633 break;
9634 case 'triangle':
9635 ctx.beginPath();
9636 edgeLength = 3 * radius / Math.sqrt(3);
9637 height = edgeLength * Math.sqrt(3) / 2;
9638 ctx.moveTo(x - edgeLength / 2, y + height / 3);
9639 ctx.lineTo(x + edgeLength / 2, y + height / 3);
9640 ctx.lineTo(x, y - 2 * height / 3);
9641 ctx.closePath();
9642 ctx.fill();
9643 break;
9644 case 'rect':
9645 size = 1 / Math.SQRT2 * radius;
9646 ctx.beginPath();
9647 ctx.fillRect(x - size, y - size, 2 * size, 2 * size);
9648 ctx.strokeRect(x - size, y - size, 2 * size, 2 * size);
9649 break;
9650 case 'rectRounded':
9651 var offset = radius / Math.SQRT2;
9652 var leftX = x - offset;
9653 var topY = y - offset;
9654 var sideSize = Math.SQRT2 * radius;
9655 ctx.beginPath();
9656 this.roundedRect(ctx, leftX, topY, sideSize, sideSize, radius / 2);
9657 ctx.closePath();
9658 ctx.fill();
9659 break;
9660 case 'rectRot':
9661 size = 1 / Math.SQRT2 * radius;
9662 ctx.beginPath();
9663 ctx.moveTo(x - size, y);
9664 ctx.lineTo(x, y + size);
9665 ctx.lineTo(x + size, y);
9666 ctx.lineTo(x, y - size);
9667 ctx.closePath();
9668 ctx.fill();
9669 break;
9670 case 'cross':
9671 ctx.beginPath();
9672 ctx.moveTo(x, y + radius);
9673 ctx.lineTo(x, y - radius);
9674 ctx.moveTo(x - radius, y);
9675 ctx.lineTo(x + radius, y);
9676 ctx.closePath();
9677 break;
9678 case 'crossRot':
9679 ctx.beginPath();
9680 xOffset = Math.cos(Math.PI / 4) * radius;
9681 yOffset = Math.sin(Math.PI / 4) * radius;
9682 ctx.moveTo(x - xOffset, y - yOffset);
9683 ctx.lineTo(x + xOffset, y + yOffset);
9684 ctx.moveTo(x - xOffset, y + yOffset);
9685 ctx.lineTo(x + xOffset, y - yOffset);
9686 ctx.closePath();
9687 break;
9688 case 'star':
9689 ctx.beginPath();
9690 ctx.moveTo(x, y + radius);
9691 ctx.lineTo(x, y - radius);
9692 ctx.moveTo(x - radius, y);
9693 ctx.lineTo(x + radius, y);
9694 xOffset = Math.cos(Math.PI / 4) * radius;
9695 yOffset = Math.sin(Math.PI / 4) * radius;
9696 ctx.moveTo(x - xOffset, y - yOffset);
9697 ctx.lineTo(x + xOffset, y + yOffset);
9698 ctx.moveTo(x - xOffset, y + yOffset);
9699 ctx.lineTo(x + xOffset, y - yOffset);
9700 ctx.closePath();
9701 break;
9702 case 'line':
9703 ctx.beginPath();
9704 ctx.moveTo(x - radius, y);
9705 ctx.lineTo(x + radius, y);
9706 ctx.closePath();
9707 break;
9708 case 'dash':
9709 ctx.beginPath();
9710 ctx.moveTo(x, y);
9711 ctx.lineTo(x + radius, y);
9712 ctx.closePath();
9713 break;
9714 }
9715
9716 ctx.stroke();
9717 },
9718
9719 clipArea: function(ctx, area) {
9720 ctx.save();
9721 ctx.beginPath();
9722 ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
9723 ctx.clip();
9724 },
9725
9726 unclipArea: function(ctx) {
9727 ctx.restore();
9728 },
9729
9730 lineTo: function(ctx, previous, target, flip) {
9731 if (target.steppedLine) {
9732 if ((target.steppedLine === 'after' && !flip) || (target.steppedLine !== 'after' && flip)) {
9733 ctx.lineTo(previous.x, target.y);
9734 } else {
9735 ctx.lineTo(target.x, previous.y);
9736 }
9737 ctx.lineTo(target.x, target.y);
9738 return;
9739 }
9740
9741 if (!target.tension) {
9742 ctx.lineTo(target.x, target.y);
9743 return;
9744 }
9745
9746 ctx.bezierCurveTo(
9747 flip ? previous.controlPointPreviousX : previous.controlPointNextX,
9748 flip ? previous.controlPointPreviousY : previous.controlPointNextY,
9749 flip ? target.controlPointNextX : target.controlPointPreviousX,
9750 flip ? target.controlPointNextY : target.controlPointPreviousY,
9751 target.x,
9752 target.y);
9753 }
9754};
9755
9756// DEPRECATIONS
9757
9758/**
9759 * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
9760 * @namespace Chart.helpers.clear
9761 * @deprecated since version 2.7.0
9762 * @todo remove at version 3
9763 * @private
9764 */
9765helpers.clear = exports.clear;
9766
9767/**
9768 * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
9769 * @namespace Chart.helpers.drawRoundedRectangle
9770 * @deprecated since version 2.7.0
9771 * @todo remove at version 3
9772 * @private
9773 */
9774helpers.drawRoundedRectangle = function(ctx) {
9775 ctx.beginPath();
9776 exports.roundedRect.apply(exports, arguments);
9777 ctx.closePath();
9778};
9779
9780},{"42":42}],42:[function(require,module,exports){
9781'use strict';
9782
9783/**
9784 * @namespace Chart.helpers
9785 */
9786var helpers = {
9787 /**
9788 * An empty function that can be used, for example, for optional callback.
9789 */
9790 noop: function() {},
9791
9792 /**
9793 * Returns a unique id, sequentially generated from a global variable.
9794 * @returns {Number}
9795 * @function
9796 */
9797 uid: (function() {
9798 var id = 0;
9799 return function() {
9800 return id++;
9801 };
9802 }()),
9803
9804 /**
9805 * Returns true if `value` is neither null nor undefined, else returns false.
9806 * @param {*} value - The value to test.
9807 * @returns {Boolean}
9808 * @since 2.7.0
9809 */
9810 isNullOrUndef: function(value) {
9811 return value === null || typeof value === 'undefined';
9812 },
9813
9814 /**
9815 * Returns true if `value` is an array, else returns false.
9816 * @param {*} value - The value to test.
9817 * @returns {Boolean}
9818 * @function
9819 */
9820 isArray: Array.isArray ? Array.isArray : function(value) {
9821 return Object.prototype.toString.call(value) === '[object Array]';
9822 },
9823
9824 /**
9825 * Returns true if `value` is an object (excluding null), else returns false.
9826 * @param {*} value - The value to test.
9827 * @returns {Boolean}
9828 * @since 2.7.0
9829 */
9830 isObject: function(value) {
9831 return value !== null && Object.prototype.toString.call(value) === '[object Object]';
9832 },
9833
9834 /**
9835 * Returns `value` if defined, else returns `defaultValue`.
9836 * @param {*} value - The value to return if defined.
9837 * @param {*} defaultValue - The value to return if `value` is undefined.
9838 * @returns {*}
9839 */
9840 valueOrDefault: function(value, defaultValue) {
9841 return typeof value === 'undefined' ? defaultValue : value;
9842 },
9843
9844 /**
9845 * Returns value at the given `index` in array if defined, else returns `defaultValue`.
9846 * @param {Array} value - The array to lookup for value at `index`.
9847 * @param {Number} index - The index in `value` to lookup for value.
9848 * @param {*} defaultValue - The value to return if `value[index]` is undefined.
9849 * @returns {*}
9850 */
9851 valueAtIndexOrDefault: function(value, index, defaultValue) {
9852 return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
9853 },
9854
9855 /**
9856 * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
9857 * value returned by `fn`. If `fn` is not a function, this method returns undefined.
9858 * @param {Function} fn - The function to call.
9859 * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
9860 * @param {Object} [thisArg] - The value of `this` provided for the call to `fn`.
9861 * @returns {*}
9862 */
9863 callback: function(fn, args, thisArg) {
9864 if (fn && typeof fn.call === 'function') {
9865 return fn.apply(thisArg, args);
9866 }
9867 },
9868
9869 /**
9870 * Note(SB) for performance sake, this method should only be used when loopable type
9871 * is unknown or in none intensive code (not called often and small loopable). Else
9872 * it's preferable to use a regular for() loop and save extra function calls.
9873 * @param {Object|Array} loopable - The object or array to be iterated.
9874 * @param {Function} fn - The function to call for each item.
9875 * @param {Object} [thisArg] - The value of `this` provided for the call to `fn`.
9876 * @param {Boolean} [reverse] - If true, iterates backward on the loopable.
9877 */
9878 each: function(loopable, fn, thisArg, reverse) {
9879 var i, len, keys;
9880 if (helpers.isArray(loopable)) {
9881 len = loopable.length;
9882 if (reverse) {
9883 for (i = len - 1; i >= 0; i--) {
9884 fn.call(thisArg, loopable[i], i);
9885 }
9886 } else {
9887 for (i = 0; i < len; i++) {
9888 fn.call(thisArg, loopable[i], i);
9889 }
9890 }
9891 } else if (helpers.isObject(loopable)) {
9892 keys = Object.keys(loopable);
9893 len = keys.length;
9894 for (i = 0; i < len; i++) {
9895 fn.call(thisArg, loopable[keys[i]], keys[i]);
9896 }
9897 }
9898 },
9899
9900 /**
9901 * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
9902 * @see http://stackoverflow.com/a/14853974
9903 * @param {Array} a0 - The array to compare
9904 * @param {Array} a1 - The array to compare
9905 * @returns {Boolean}
9906 */
9907 arrayEquals: function(a0, a1) {
9908 var i, ilen, v0, v1;
9909
9910 if (!a0 || !a1 || a0.length !== a1.length) {
9911 return false;
9912 }
9913
9914 for (i = 0, ilen = a0.length; i < ilen; ++i) {
9915 v0 = a0[i];
9916 v1 = a1[i];
9917
9918 if (v0 instanceof Array && v1 instanceof Array) {
9919 if (!helpers.arrayEquals(v0, v1)) {
9920 return false;
9921 }
9922 } else if (v0 !== v1) {
9923 // NOTE: two different object instances will never be equal: {x:20} != {x:20}
9924 return false;
9925 }
9926 }
9927
9928 return true;
9929 },
9930
9931 /**
9932 * Returns a deep copy of `source` without keeping references on objects and arrays.
9933 * @param {*} source - The value to clone.
9934 * @returns {*}
9935 */
9936 clone: function(source) {
9937 if (helpers.isArray(source)) {
9938 return source.map(helpers.clone);
9939 }
9940
9941 if (helpers.isObject(source)) {
9942 var target = {};
9943 var keys = Object.keys(source);
9944 var klen = keys.length;
9945 var k = 0;
9946
9947 for (; k < klen; ++k) {
9948 target[keys[k]] = helpers.clone(source[keys[k]]);
9949 }
9950
9951 return target;
9952 }
9953
9954 return source;
9955 },
9956
9957 /**
9958 * The default merger when Chart.helpers.merge is called without merger option.
9959 * Note(SB): this method is also used by configMerge and scaleMerge as fallback.
9960 * @private
9961 */
9962 _merger: function(key, target, source, options) {
9963 var tval = target[key];
9964 var sval = source[key];
9965
9966 if (helpers.isObject(tval) && helpers.isObject(sval)) {
9967 helpers.merge(tval, sval, options);
9968 } else {
9969 target[key] = helpers.clone(sval);
9970 }
9971 },
9972
9973 /**
9974 * Merges source[key] in target[key] only if target[key] is undefined.
9975 * @private
9976 */
9977 _mergerIf: function(key, target, source) {
9978 var tval = target[key];
9979 var sval = source[key];
9980
9981 if (helpers.isObject(tval) && helpers.isObject(sval)) {
9982 helpers.mergeIf(tval, sval);
9983 } else if (!target.hasOwnProperty(key)) {
9984 target[key] = helpers.clone(sval);
9985 }
9986 },
9987
9988 /**
9989 * Recursively deep copies `source` properties into `target` with the given `options`.
9990 * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
9991 * @param {Object} target - The target object in which all sources are merged into.
9992 * @param {Object|Array(Object)} source - Object(s) to merge into `target`.
9993 * @param {Object} [options] - Merging options:
9994 * @param {Function} [options.merger] - The merge method (key, target, source, options)
9995 * @returns {Object} The `target` object.
9996 */
9997 merge: function(target, source, options) {
9998 var sources = helpers.isArray(source) ? source : [source];
9999 var ilen = sources.length;
10000 var merge, i, keys, klen, k;
10001
10002 if (!helpers.isObject(target)) {
10003 return target;
10004 }
10005
10006 options = options || {};
10007 merge = options.merger || helpers._merger;
10008
10009 for (i = 0; i < ilen; ++i) {
10010 source = sources[i];
10011 if (!helpers.isObject(source)) {
10012 continue;
10013 }
10014
10015 keys = Object.keys(source);
10016 for (k = 0, klen = keys.length; k < klen; ++k) {
10017 merge(keys[k], target, source, options);
10018 }
10019 }
10020
10021 return target;
10022 },
10023
10024 /**
10025 * Recursively deep copies `source` properties into `target` *only* if not defined in target.
10026 * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
10027 * @param {Object} target - The target object in which all sources are merged into.
10028 * @param {Object|Array(Object)} source - Object(s) to merge into `target`.
10029 * @returns {Object} The `target` object.
10030 */
10031 mergeIf: function(target, source) {
10032 return helpers.merge(target, source, {merger: helpers._mergerIf});
10033 },
10034
10035 /**
10036 * Applies the contents of two or more objects together into the first object.
10037 * @param {Object} target - The target object in which all objects are merged into.
10038 * @param {Object} arg1 - Object containing additional properties to merge in target.
10039 * @param {Object} argN - Additional objects containing properties to merge in target.
10040 * @returns {Object} The `target` object.
10041 */
10042 extend: function(target) {
10043 var setFn = function(value, key) {
10044 target[key] = value;
10045 };
10046 for (var i = 1, ilen = arguments.length; i < ilen; ++i) {
10047 helpers.each(arguments[i], setFn);
10048 }
10049 return target;
10050 },
10051
10052 /**
10053 * Basic javascript inheritance based on the model created in Backbone.js
10054 */
10055 inherits: function(extensions) {
10056 var me = this;
10057 var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
10058 return me.apply(this, arguments);
10059 };
10060
10061 var Surrogate = function() {
10062 this.constructor = ChartElement;
10063 };
10064
10065 Surrogate.prototype = me.prototype;
10066 ChartElement.prototype = new Surrogate();
10067 ChartElement.extend = helpers.inherits;
10068
10069 if (extensions) {
10070 helpers.extend(ChartElement.prototype, extensions);
10071 }
10072
10073 ChartElement.__super__ = me.prototype;
10074 return ChartElement;
10075 }
10076};
10077
10078module.exports = helpers;
10079
10080// DEPRECATIONS
10081
10082/**
10083 * Provided for backward compatibility, use Chart.helpers.callback instead.
10084 * @function Chart.helpers.callCallback
10085 * @deprecated since version 2.6.0
10086 * @todo remove at version 3
10087 * @private
10088 */
10089helpers.callCallback = helpers.callback;
10090
10091/**
10092 * Provided for backward compatibility, use Array.prototype.indexOf instead.
10093 * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
10094 * @function Chart.helpers.indexOf
10095 * @deprecated since version 2.7.0
10096 * @todo remove at version 3
10097 * @private
10098 */
10099helpers.indexOf = function(array, item, fromIndex) {
10100 return Array.prototype.indexOf.call(array, item, fromIndex);
10101};
10102
10103/**
10104 * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
10105 * @function Chart.helpers.getValueOrDefault
10106 * @deprecated since version 2.7.0
10107 * @todo remove at version 3
10108 * @private
10109 */
10110helpers.getValueOrDefault = helpers.valueOrDefault;
10111
10112/**
10113 * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
10114 * @function Chart.helpers.getValueAtIndexOrDefault
10115 * @deprecated since version 2.7.0
10116 * @todo remove at version 3
10117 * @private
10118 */
10119helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
10120
10121},{}],43:[function(require,module,exports){
10122'use strict';
10123
10124var helpers = require(42);
10125
10126/**
10127 * Easing functions adapted from Robert Penner's easing equations.
10128 * @namespace Chart.helpers.easingEffects
10129 * @see http://www.robertpenner.com/easing/
10130 */
10131var effects = {
10132 linear: function(t) {
10133 return t;
10134 },
10135
10136 easeInQuad: function(t) {
10137 return t * t;
10138 },
10139
10140 easeOutQuad: function(t) {
10141 return -t * (t - 2);
10142 },
10143
10144 easeInOutQuad: function(t) {
10145 if ((t /= 0.5) < 1) {
10146 return 0.5 * t * t;
10147 }
10148 return -0.5 * ((--t) * (t - 2) - 1);
10149 },
10150
10151 easeInCubic: function(t) {
10152 return t * t * t;
10153 },
10154
10155 easeOutCubic: function(t) {
10156 return (t = t - 1) * t * t + 1;
10157 },
10158
10159 easeInOutCubic: function(t) {
10160 if ((t /= 0.5) < 1) {
10161 return 0.5 * t * t * t;
10162 }
10163 return 0.5 * ((t -= 2) * t * t + 2);
10164 },
10165
10166 easeInQuart: function(t) {
10167 return t * t * t * t;
10168 },
10169
10170 easeOutQuart: function(t) {
10171 return -((t = t - 1) * t * t * t - 1);
10172 },
10173
10174 easeInOutQuart: function(t) {
10175 if ((t /= 0.5) < 1) {
10176 return 0.5 * t * t * t * t;
10177 }
10178 return -0.5 * ((t -= 2) * t * t * t - 2);
10179 },
10180
10181 easeInQuint: function(t) {
10182 return t * t * t * t * t;
10183 },
10184
10185 easeOutQuint: function(t) {
10186 return (t = t - 1) * t * t * t * t + 1;
10187 },
10188
10189 easeInOutQuint: function(t) {
10190 if ((t /= 0.5) < 1) {
10191 return 0.5 * t * t * t * t * t;
10192 }
10193 return 0.5 * ((t -= 2) * t * t * t * t + 2);
10194 },
10195
10196 easeInSine: function(t) {
10197 return -Math.cos(t * (Math.PI / 2)) + 1;
10198 },
10199
10200 easeOutSine: function(t) {
10201 return Math.sin(t * (Math.PI / 2));
10202 },
10203
10204 easeInOutSine: function(t) {
10205 return -0.5 * (Math.cos(Math.PI * t) - 1);
10206 },
10207
10208 easeInExpo: function(t) {
10209 return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
10210 },
10211
10212 easeOutExpo: function(t) {
10213 return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
10214 },
10215
10216 easeInOutExpo: function(t) {
10217 if (t === 0) {
10218 return 0;
10219 }
10220 if (t === 1) {
10221 return 1;
10222 }
10223 if ((t /= 0.5) < 1) {
10224 return 0.5 * Math.pow(2, 10 * (t - 1));
10225 }
10226 return 0.5 * (-Math.pow(2, -10 * --t) + 2);
10227 },
10228
10229 easeInCirc: function(t) {
10230 if (t >= 1) {
10231 return t;
10232 }
10233 return -(Math.sqrt(1 - t * t) - 1);
10234 },
10235
10236 easeOutCirc: function(t) {
10237 return Math.sqrt(1 - (t = t - 1) * t);
10238 },
10239
10240 easeInOutCirc: function(t) {
10241 if ((t /= 0.5) < 1) {
10242 return -0.5 * (Math.sqrt(1 - t * t) - 1);
10243 }
10244 return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
10245 },
10246
10247 easeInElastic: function(t) {
10248 var s = 1.70158;
10249 var p = 0;
10250 var a = 1;
10251 if (t === 0) {
10252 return 0;
10253 }
10254 if (t === 1) {
10255 return 1;
10256 }
10257 if (!p) {
10258 p = 0.3;
10259 }
10260 if (a < 1) {
10261 a = 1;
10262 s = p / 4;
10263 } else {
10264 s = p / (2 * Math.PI) * Math.asin(1 / a);
10265 }
10266 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
10267 },
10268
10269 easeOutElastic: function(t) {
10270 var s = 1.70158;
10271 var p = 0;
10272 var a = 1;
10273 if (t === 0) {
10274 return 0;
10275 }
10276 if (t === 1) {
10277 return 1;
10278 }
10279 if (!p) {
10280 p = 0.3;
10281 }
10282 if (a < 1) {
10283 a = 1;
10284 s = p / 4;
10285 } else {
10286 s = p / (2 * Math.PI) * Math.asin(1 / a);
10287 }
10288 return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
10289 },
10290
10291 easeInOutElastic: function(t) {
10292 var s = 1.70158;
10293 var p = 0;
10294 var a = 1;
10295 if (t === 0) {
10296 return 0;
10297 }
10298 if ((t /= 0.5) === 2) {
10299 return 1;
10300 }
10301 if (!p) {
10302 p = 0.45;
10303 }
10304 if (a < 1) {
10305 a = 1;
10306 s = p / 4;
10307 } else {
10308 s = p / (2 * Math.PI) * Math.asin(1 / a);
10309 }
10310 if (t < 1) {
10311 return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
10312 }
10313 return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
10314 },
10315 easeInBack: function(t) {
10316 var s = 1.70158;
10317 return t * t * ((s + 1) * t - s);
10318 },
10319
10320 easeOutBack: function(t) {
10321 var s = 1.70158;
10322 return (t = t - 1) * t * ((s + 1) * t + s) + 1;
10323 },
10324
10325 easeInOutBack: function(t) {
10326 var s = 1.70158;
10327 if ((t /= 0.5) < 1) {
10328 return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
10329 }
10330 return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
10331 },
10332
10333 easeInBounce: function(t) {
10334 return 1 - effects.easeOutBounce(1 - t);
10335 },
10336
10337 easeOutBounce: function(t) {
10338 if (t < (1 / 2.75)) {
10339 return 7.5625 * t * t;
10340 }
10341 if (t < (2 / 2.75)) {
10342 return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
10343 }
10344 if (t < (2.5 / 2.75)) {
10345 return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
10346 }
10347 return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
10348 },
10349
10350 easeInOutBounce: function(t) {
10351 if (t < 0.5) {
10352 return effects.easeInBounce(t * 2) * 0.5;
10353 }
10354 return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
10355 }
10356};
10357
10358module.exports = {
10359 effects: effects
10360};
10361
10362// DEPRECATIONS
10363
10364/**
10365 * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
10366 * @function Chart.helpers.easingEffects
10367 * @deprecated since version 2.7.0
10368 * @todo remove at version 3
10369 * @private
10370 */
10371helpers.easingEffects = effects;
10372
10373},{"42":42}],44:[function(require,module,exports){
10374'use strict';
10375
10376var helpers = require(42);
10377
10378/**
10379 * @alias Chart.helpers.options
10380 * @namespace
10381 */
10382module.exports = {
10383 /**
10384 * Converts the given line height `value` in pixels for a specific font `size`.
10385 * @param {Number|String} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
10386 * @param {Number} size - The font size (in pixels) used to resolve relative `value`.
10387 * @returns {Number} The effective line height in pixels (size * 1.2 if value is invalid).
10388 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
10389 * @since 2.7.0
10390 */
10391 toLineHeight: function(value, size) {
10392 var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
10393 if (!matches || matches[1] === 'normal') {
10394 return size * 1.2;
10395 }
10396
10397 value = +matches[2];
10398
10399 switch (matches[3]) {
10400 case 'px':
10401 return value;
10402 case '%':
10403 value /= 100;
10404 break;
10405 default:
10406 break;
10407 }
10408
10409 return size * value;
10410 },
10411
10412 /**
10413 * Converts the given value into a padding object with pre-computed width/height.
10414 * @param {Number|Object} value - If a number, set the value to all TRBL component,
10415 * else, if and object, use defined properties and sets undefined ones to 0.
10416 * @returns {Object} The padding values (top, right, bottom, left, width, height)
10417 * @since 2.7.0
10418 */
10419 toPadding: function(value) {
10420 var t, r, b, l;
10421
10422 if (helpers.isObject(value)) {
10423 t = +value.top || 0;
10424 r = +value.right || 0;
10425 b = +value.bottom || 0;
10426 l = +value.left || 0;
10427 } else {
10428 t = r = b = l = +value || 0;
10429 }
10430
10431 return {
10432 top: t,
10433 right: r,
10434 bottom: b,
10435 left: l,
10436 height: t + b,
10437 width: l + r
10438 };
10439 },
10440
10441 /**
10442 * Evaluates the given `inputs` sequentially and returns the first defined value.
10443 * @param {Array[]} inputs - An array of values, falling back to the last value.
10444 * @param {Object} [context] - If defined and the current value is a function, the value
10445 * is called with `context` as first argument and the result becomes the new input.
10446 * @param {Number} [index] - If defined and the current value is an array, the value
10447 * at `index` become the new input.
10448 * @since 2.7.0
10449 */
10450 resolve: function(inputs, context, index) {
10451 var i, ilen, value;
10452
10453 for (i = 0, ilen = inputs.length; i < ilen; ++i) {
10454 value = inputs[i];
10455 if (value === undefined) {
10456 continue;
10457 }
10458 if (context !== undefined && typeof value === 'function') {
10459 value = value(context);
10460 }
10461 if (index !== undefined && helpers.isArray(value)) {
10462 value = value[index];
10463 }
10464 if (value !== undefined) {
10465 return value;
10466 }
10467 }
10468 }
10469};
10470
10471},{"42":42}],45:[function(require,module,exports){
10472'use strict';
10473
10474module.exports = require(42);
10475module.exports.easing = require(43);
10476module.exports.canvas = require(41);
10477module.exports.options = require(44);
10478
10479},{"41":41,"42":42,"43":43,"44":44}],46:[function(require,module,exports){
10480/**
10481 * Platform fallback implementation (minimal).
10482 * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
10483 */
10484
10485module.exports = {
10486 acquireContext: function(item) {
10487 if (item && item.canvas) {
10488 // Support for any object associated to a canvas (including a context2d)
10489 item = item.canvas;
10490 }
10491
10492 return item && item.getContext('2d') || null;
10493 }
10494};
10495
10496},{}],47:[function(require,module,exports){
10497/**
10498 * Chart.Platform implementation for targeting a web browser
10499 */
10500
10501'use strict';
10502
10503var helpers = require(45);
10504
10505var EXPANDO_KEY = '$chartjs';
10506var CSS_PREFIX = 'chartjs-';
10507var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
10508var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
10509var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
10510
10511/**
10512 * DOM event types -> Chart.js event types.
10513 * Note: only events with different types are mapped.
10514 * @see https://developer.mozilla.org/en-US/docs/Web/Events
10515 */
10516var EVENT_TYPES = {
10517 touchstart: 'mousedown',
10518 touchmove: 'mousemove',
10519 touchend: 'mouseup',
10520 pointerenter: 'mouseenter',
10521 pointerdown: 'mousedown',
10522 pointermove: 'mousemove',
10523 pointerup: 'mouseup',
10524 pointerleave: 'mouseout',
10525 pointerout: 'mouseout'
10526};
10527
10528/**
10529 * The "used" size is the final value of a dimension property after all calculations have
10530 * been performed. This method uses the computed style of `element` but returns undefined
10531 * if the computed style is not expressed in pixels. That can happen in some cases where
10532 * `element` has a size relative to its parent and this last one is not yet displayed,
10533 * for example because of `display: none` on a parent node.
10534 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
10535 * @returns {Number} Size in pixels or undefined if unknown.
10536 */
10537function readUsedSize(element, property) {
10538 var value = helpers.getStyle(element, property);
10539 var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
10540 return matches ? Number(matches[1]) : undefined;
10541}
10542
10543/**
10544 * Initializes the canvas style and render size without modifying the canvas display size,
10545 * since responsiveness is handled by the controller.resize() method. The config is used
10546 * to determine the aspect ratio to apply in case no explicit height has been specified.
10547 */
10548function initCanvas(canvas, config) {
10549 var style = canvas.style;
10550
10551 // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
10552 // returns null or '' if no explicit value has been set to the canvas attribute.
10553 var renderHeight = canvas.getAttribute('height');
10554 var renderWidth = canvas.getAttribute('width');
10555
10556 // Chart.js modifies some canvas values that we want to restore on destroy
10557 canvas[EXPANDO_KEY] = {
10558 initial: {
10559 height: renderHeight,
10560 width: renderWidth,
10561 style: {
10562 display: style.display,
10563 height: style.height,
10564 width: style.width
10565 }
10566 }
10567 };
10568
10569 // Force canvas to display as block to avoid extra space caused by inline
10570 // elements, which would interfere with the responsive resize process.
10571 // https://github.com/chartjs/Chart.js/issues/2538
10572 style.display = style.display || 'block';
10573
10574 if (renderWidth === null || renderWidth === '') {
10575 var displayWidth = readUsedSize(canvas, 'width');
10576 if (displayWidth !== undefined) {
10577 canvas.width = displayWidth;
10578 }
10579 }
10580
10581 if (renderHeight === null || renderHeight === '') {
10582 if (canvas.style.height === '') {
10583 // If no explicit render height and style height, let's apply the aspect ratio,
10584 // which one can be specified by the user but also by charts as default option
10585 // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
10586 canvas.height = canvas.width / (config.options.aspectRatio || 2);
10587 } else {
10588 var displayHeight = readUsedSize(canvas, 'height');
10589 if (displayWidth !== undefined) {
10590 canvas.height = displayHeight;
10591 }
10592 }
10593 }
10594
10595 return canvas;
10596}
10597
10598/**
10599 * Detects support for options object argument in addEventListener.
10600 * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
10601 * @private
10602 */
10603var supportsEventListenerOptions = (function() {
10604 var supports = false;
10605 try {
10606 var options = Object.defineProperty({}, 'passive', {
10607 get: function() {
10608 supports = true;
10609 }
10610 });
10611 window.addEventListener('e', null, options);
10612 } catch (e) {
10613 // continue regardless of error
10614 }
10615 return supports;
10616}());
10617
10618// Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
10619// https://github.com/chartjs/Chart.js/issues/4287
10620var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
10621
10622function addEventListener(node, type, listener) {
10623 node.addEventListener(type, listener, eventListenerOptions);
10624}
10625
10626function removeEventListener(node, type, listener) {
10627 node.removeEventListener(type, listener, eventListenerOptions);
10628}
10629
10630function createEvent(type, chart, x, y, nativeEvent) {
10631 return {
10632 type: type,
10633 chart: chart,
10634 native: nativeEvent || null,
10635 x: x !== undefined ? x : null,
10636 y: y !== undefined ? y : null,
10637 };
10638}
10639
10640function fromNativeEvent(event, chart) {
10641 var type = EVENT_TYPES[event.type] || event.type;
10642 var pos = helpers.getRelativePosition(event, chart);
10643 return createEvent(type, chart, pos.x, pos.y, event);
10644}
10645
10646function throttled(fn, thisArg) {
10647 var ticking = false;
10648 var args = [];
10649
10650 return function() {
10651 args = Array.prototype.slice.call(arguments);
10652 thisArg = thisArg || this;
10653
10654 if (!ticking) {
10655 ticking = true;
10656 helpers.requestAnimFrame.call(window, function() {
10657 ticking = false;
10658 fn.apply(thisArg, args);
10659 });
10660 }
10661 };
10662}
10663
10664// Implementation based on https://github.com/marcj/css-element-queries
10665function createResizer(handler) {
10666 var resizer = document.createElement('div');
10667 var cls = CSS_PREFIX + 'size-monitor';
10668 var maxSize = 1000000;
10669 var style =
10670 'position:absolute;' +
10671 'left:0;' +
10672 'top:0;' +
10673 'right:0;' +
10674 'bottom:0;' +
10675 'overflow:hidden;' +
10676 'pointer-events:none;' +
10677 'visibility:hidden;' +
10678 'z-index:-1;';
10679
10680 resizer.style.cssText = style;
10681 resizer.className = cls;
10682 resizer.innerHTML =
10683 '<div class="' + cls + '-expand" style="' + style + '">' +
10684 '<div style="' +
10685 'position:absolute;' +
10686 'width:' + maxSize + 'px;' +
10687 'height:' + maxSize + 'px;' +
10688 'left:0;' +
10689 'top:0">' +
10690 '</div>' +
10691 '</div>' +
10692 '<div class="' + cls + '-shrink" style="' + style + '">' +
10693 '<div style="' +
10694 'position:absolute;' +
10695 'width:200%;' +
10696 'height:200%;' +
10697 'left:0; ' +
10698 'top:0">' +
10699 '</div>' +
10700 '</div>';
10701
10702 var expand = resizer.childNodes[0];
10703 var shrink = resizer.childNodes[1];
10704
10705 resizer._reset = function() {
10706 expand.scrollLeft = maxSize;
10707 expand.scrollTop = maxSize;
10708 shrink.scrollLeft = maxSize;
10709 shrink.scrollTop = maxSize;
10710 };
10711 var onScroll = function() {
10712 resizer._reset();
10713 handler();
10714 };
10715
10716 addEventListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
10717 addEventListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
10718
10719 return resizer;
10720}
10721
10722// https://davidwalsh.name/detect-node-insertion
10723function watchForRender(node, handler) {
10724 var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
10725 var proxy = expando.renderProxy = function(e) {
10726 if (e.animationName === CSS_RENDER_ANIMATION) {
10727 handler();
10728 }
10729 };
10730
10731 helpers.each(ANIMATION_START_EVENTS, function(type) {
10732 addEventListener(node, type, proxy);
10733 });
10734
10735 // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
10736 // is removed then added back immediately (same animation frame?). Accessing the
10737 // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
10738 // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
10739 // https://github.com/chartjs/Chart.js/issues/4737
10740 expando.reflow = !!node.offsetParent;
10741
10742 node.classList.add(CSS_RENDER_MONITOR);
10743}
10744
10745function unwatchForRender(node) {
10746 var expando = node[EXPANDO_KEY] || {};
10747 var proxy = expando.renderProxy;
10748
10749 if (proxy) {
10750 helpers.each(ANIMATION_START_EVENTS, function(type) {
10751 removeEventListener(node, type, proxy);
10752 });
10753
10754 delete expando.renderProxy;
10755 }
10756
10757 node.classList.remove(CSS_RENDER_MONITOR);
10758}
10759
10760function addResizeListener(node, listener, chart) {
10761 var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
10762
10763 // Let's keep track of this added resizer and thus avoid DOM query when removing it.
10764 var resizer = expando.resizer = createResizer(throttled(function() {
10765 if (expando.resizer) {
10766 return listener(createEvent('resize', chart));
10767 }
10768 }));
10769
10770 // The resizer needs to be attached to the node parent, so we first need to be
10771 // sure that `node` is attached to the DOM before injecting the resizer element.
10772 watchForRender(node, function() {
10773 if (expando.resizer) {
10774 var container = node.parentNode;
10775 if (container && container !== resizer.parentNode) {
10776 container.insertBefore(resizer, container.firstChild);
10777 }
10778
10779 // The container size might have changed, let's reset the resizer state.
10780 resizer._reset();
10781 }
10782 });
10783}
10784
10785function removeResizeListener(node) {
10786 var expando = node[EXPANDO_KEY] || {};
10787 var resizer = expando.resizer;
10788
10789 delete expando.resizer;
10790 unwatchForRender(node);
10791
10792 if (resizer && resizer.parentNode) {
10793 resizer.parentNode.removeChild(resizer);
10794 }
10795}
10796
10797function injectCSS(platform, css) {
10798 // http://stackoverflow.com/q/3922139
10799 var style = platform._style || document.createElement('style');
10800 if (!platform._style) {
10801 platform._style = style;
10802 css = '/* Chart.js */\n' + css;
10803 style.setAttribute('type', 'text/css');
10804 document.getElementsByTagName('head')[0].appendChild(style);
10805 }
10806
10807 style.appendChild(document.createTextNode(css));
10808}
10809
10810module.exports = {
10811 /**
10812 * This property holds whether this platform is enabled for the current environment.
10813 * Currently used by platform.js to select the proper implementation.
10814 * @private
10815 */
10816 _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
10817
10818 initialize: function() {
10819 var keyframes = 'from{opacity:0.99}to{opacity:1}';
10820
10821 injectCSS(this,
10822 // DOM rendering detection
10823 // https://davidwalsh.name/detect-node-insertion
10824 '@-webkit-keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' +
10825 '@keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' +
10826 '.' + CSS_RENDER_MONITOR + '{' +
10827 '-webkit-animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' +
10828 'animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' +
10829 '}'
10830 );
10831 },
10832
10833 acquireContext: function(item, config) {
10834 if (typeof item === 'string') {
10835 item = document.getElementById(item);
10836 } else if (item.length) {
10837 // Support for array based queries (such as jQuery)
10838 item = item[0];
10839 }
10840
10841 if (item && item.canvas) {
10842 // Support for any object associated to a canvas (including a context2d)
10843 item = item.canvas;
10844 }
10845
10846 // To prevent canvas fingerprinting, some add-ons undefine the getContext
10847 // method, for example: https://github.com/kkapsner/CanvasBlocker
10848 // https://github.com/chartjs/Chart.js/issues/2807
10849 var context = item && item.getContext && item.getContext('2d');
10850
10851 // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
10852 // inside an iframe or when running in a protected environment. We could guess the
10853 // types from their toString() value but let's keep things flexible and assume it's
10854 // a sufficient condition if the item has a context2D which has item as `canvas`.
10855 // https://github.com/chartjs/Chart.js/issues/3887
10856 // https://github.com/chartjs/Chart.js/issues/4102
10857 // https://github.com/chartjs/Chart.js/issues/4152
10858 if (context && context.canvas === item) {
10859 initCanvas(item, config);
10860 return context;
10861 }
10862
10863 return null;
10864 },
10865
10866 releaseContext: function(context) {
10867 var canvas = context.canvas;
10868 if (!canvas[EXPANDO_KEY]) {
10869 return;
10870 }
10871
10872 var initial = canvas[EXPANDO_KEY].initial;
10873 ['height', 'width'].forEach(function(prop) {
10874 var value = initial[prop];
10875 if (helpers.isNullOrUndef(value)) {
10876 canvas.removeAttribute(prop);
10877 } else {
10878 canvas.setAttribute(prop, value);
10879 }
10880 });
10881
10882 helpers.each(initial.style || {}, function(value, key) {
10883 canvas.style[key] = value;
10884 });
10885
10886 // The canvas render size might have been changed (and thus the state stack discarded),
10887 // we can't use save() and restore() to restore the initial state. So make sure that at
10888 // least the canvas context is reset to the default state by setting the canvas width.
10889 // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
10890 canvas.width = canvas.width;
10891
10892 delete canvas[EXPANDO_KEY];
10893 },
10894
10895 addEventListener: function(chart, type, listener) {
10896 var canvas = chart.canvas;
10897 if (type === 'resize') {
10898 // Note: the resize event is not supported on all browsers.
10899 addResizeListener(canvas, listener, chart);
10900 return;
10901 }
10902
10903 var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
10904 var proxies = expando.proxies || (expando.proxies = {});
10905 var proxy = proxies[chart.id + '_' + type] = function(event) {
10906 listener(fromNativeEvent(event, chart));
10907 };
10908
10909 addEventListener(canvas, type, proxy);
10910 },
10911
10912 removeEventListener: function(chart, type, listener) {
10913 var canvas = chart.canvas;
10914 if (type === 'resize') {
10915 // Note: the resize event is not supported on all browsers.
10916 removeResizeListener(canvas, listener);
10917 return;
10918 }
10919
10920 var expando = listener[EXPANDO_KEY] || {};
10921 var proxies = expando.proxies || {};
10922 var proxy = proxies[chart.id + '_' + type];
10923 if (!proxy) {
10924 return;
10925 }
10926
10927 removeEventListener(canvas, type, proxy);
10928 }
10929};
10930
10931// DEPRECATIONS
10932
10933/**
10934 * Provided for backward compatibility, use EventTarget.addEventListener instead.
10935 * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
10936 * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
10937 * @function Chart.helpers.addEvent
10938 * @deprecated since version 2.7.0
10939 * @todo remove at version 3
10940 * @private
10941 */
10942helpers.addEvent = addEventListener;
10943
10944/**
10945 * Provided for backward compatibility, use EventTarget.removeEventListener instead.
10946 * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
10947 * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
10948 * @function Chart.helpers.removeEvent
10949 * @deprecated since version 2.7.0
10950 * @todo remove at version 3
10951 * @private
10952 */
10953helpers.removeEvent = removeEventListener;
10954
10955},{"45":45}],48:[function(require,module,exports){
10956'use strict';
10957
10958var helpers = require(45);
10959var basic = require(46);
10960var dom = require(47);
10961
10962// @TODO Make possible to select another platform at build time.
10963var implementation = dom._enabled ? dom : basic;
10964
10965/**
10966 * @namespace Chart.platform
10967 * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
10968 * @since 2.4.0
10969 */
10970module.exports = helpers.extend({
10971 /**
10972 * @since 2.7.0
10973 */
10974 initialize: function() {},
10975
10976 /**
10977 * Called at chart construction time, returns a context2d instance implementing
10978 * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
10979 * @param {*} item - The native item from which to acquire context (platform specific)
10980 * @param {Object} options - The chart options
10981 * @returns {CanvasRenderingContext2D} context2d instance
10982 */
10983 acquireContext: function() {},
10984
10985 /**
10986 * Called at chart destruction time, releases any resources associated to the context
10987 * previously returned by the acquireContext() method.
10988 * @param {CanvasRenderingContext2D} context - The context2d instance
10989 * @returns {Boolean} true if the method succeeded, else false
10990 */
10991 releaseContext: function() {},
10992
10993 /**
10994 * Registers the specified listener on the given chart.
10995 * @param {Chart} chart - Chart from which to listen for event
10996 * @param {String} type - The ({@link IEvent}) type to listen for
10997 * @param {Function} listener - Receives a notification (an object that implements
10998 * the {@link IEvent} interface) when an event of the specified type occurs.
10999 */
11000 addEventListener: function() {},
11001
11002 /**
11003 * Removes the specified listener previously registered with addEventListener.
11004 * @param {Chart} chart -Chart from which to remove the listener
11005 * @param {String} type - The ({@link IEvent}) type to remove
11006 * @param {Function} listener - The listener function to remove from the event target.
11007 */
11008 removeEventListener: function() {}
11009
11010}, implementation);
11011
11012/**
11013 * @interface IPlatform
11014 * Allows abstracting platform dependencies away from the chart
11015 * @borrows Chart.platform.acquireContext as acquireContext
11016 * @borrows Chart.platform.releaseContext as releaseContext
11017 * @borrows Chart.platform.addEventListener as addEventListener
11018 * @borrows Chart.platform.removeEventListener as removeEventListener
11019 */
11020
11021/**
11022 * @interface IEvent
11023 * @prop {String} type - The event type name, possible values are:
11024 * 'contextmenu', 'mouseenter', 'mousedown', 'mousemove', 'mouseup', 'mouseout',
11025 * 'click', 'dblclick', 'keydown', 'keypress', 'keyup' and 'resize'
11026 * @prop {*} native - The original native event (null for emulated events, e.g. 'resize')
11027 * @prop {Number} x - The mouse x position, relative to the canvas (null for incompatible events)
11028 * @prop {Number} y - The mouse y position, relative to the canvas (null for incompatible events)
11029 */
11030
11031},{"45":45,"46":46,"47":47}],49:[function(require,module,exports){
11032'use strict';
11033
11034module.exports = {};
11035module.exports.filler = require(50);
11036module.exports.legend = require(51);
11037module.exports.title = require(52);
11038
11039},{"50":50,"51":51,"52":52}],50:[function(require,module,exports){
11040/**
11041 * Plugin based on discussion from the following Chart.js issues:
11042 * @see https://github.com/chartjs/Chart.js/issues/2380#issuecomment-279961569
11043 * @see https://github.com/chartjs/Chart.js/issues/2440#issuecomment-256461897
11044 */
11045
11046'use strict';
11047
11048var defaults = require(25);
11049var elements = require(40);
11050var helpers = require(45);
11051
11052defaults._set('global', {
11053 plugins: {
11054 filler: {
11055 propagate: true
11056 }
11057 }
11058});
11059
11060var mappers = {
11061 dataset: function(source) {
11062 var index = source.fill;
11063 var chart = source.chart;
11064 var meta = chart.getDatasetMeta(index);
11065 var visible = meta && chart.isDatasetVisible(index);
11066 var points = (visible && meta.dataset._children) || [];
11067 var length = points.length || 0;
11068
11069 return !length ? null : function(point, i) {
11070 return (i < length && points[i]._view) || null;
11071 };
11072 },
11073
11074 boundary: function(source) {
11075 var boundary = source.boundary;
11076 var x = boundary ? boundary.x : null;
11077 var y = boundary ? boundary.y : null;
11078
11079 return function(point) {
11080 return {
11081 x: x === null ? point.x : x,
11082 y: y === null ? point.y : y,
11083 };
11084 };
11085 }
11086};
11087
11088// @todo if (fill[0] === '#')
11089function decodeFill(el, index, count) {
11090 var model = el._model || {};
11091 var fill = model.fill;
11092 var target;
11093
11094 if (fill === undefined) {
11095 fill = !!model.backgroundColor;
11096 }
11097
11098 if (fill === false || fill === null) {
11099 return false;
11100 }
11101
11102 if (fill === true) {
11103 return 'origin';
11104 }
11105
11106 target = parseFloat(fill, 10);
11107 if (isFinite(target) && Math.floor(target) === target) {
11108 if (fill[0] === '-' || fill[0] === '+') {
11109 target = index + target;
11110 }
11111
11112 if (target === index || target < 0 || target >= count) {
11113 return false;
11114 }
11115
11116 return target;
11117 }
11118
11119 switch (fill) {
11120 // compatibility
11121 case 'bottom':
11122 return 'start';
11123 case 'top':
11124 return 'end';
11125 case 'zero':
11126 return 'origin';
11127 // supported boundaries
11128 case 'origin':
11129 case 'start':
11130 case 'end':
11131 return fill;
11132 // invalid fill values
11133 default:
11134 return false;
11135 }
11136}
11137
11138function computeBoundary(source) {
11139 var model = source.el._model || {};
11140 var scale = source.el._scale || {};
11141 var fill = source.fill;
11142 var target = null;
11143 var horizontal;
11144
11145 if (isFinite(fill)) {
11146 return null;
11147 }
11148
11149 // Backward compatibility: until v3, we still need to support boundary values set on
11150 // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
11151 // controllers might still use it (e.g. the Smith chart).
11152
11153 if (fill === 'start') {
11154 target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
11155 } else if (fill === 'end') {
11156 target = model.scaleTop === undefined ? scale.top : model.scaleTop;
11157 } else if (model.scaleZero !== undefined) {
11158 target = model.scaleZero;
11159 } else if (scale.getBasePosition) {
11160 target = scale.getBasePosition();
11161 } else if (scale.getBasePixel) {
11162 target = scale.getBasePixel();
11163 }
11164
11165 if (target !== undefined && target !== null) {
11166 if (target.x !== undefined && target.y !== undefined) {
11167 return target;
11168 }
11169
11170 if (typeof target === 'number' && isFinite(target)) {
11171 horizontal = scale.isHorizontal();
11172 return {
11173 x: horizontal ? target : null,
11174 y: horizontal ? null : target
11175 };
11176 }
11177 }
11178
11179 return null;
11180}
11181
11182function resolveTarget(sources, index, propagate) {
11183 var source = sources[index];
11184 var fill = source.fill;
11185 var visited = [index];
11186 var target;
11187
11188 if (!propagate) {
11189 return fill;
11190 }
11191
11192 while (fill !== false && visited.indexOf(fill) === -1) {
11193 if (!isFinite(fill)) {
11194 return fill;
11195 }
11196
11197 target = sources[fill];
11198 if (!target) {
11199 return false;
11200 }
11201
11202 if (target.visible) {
11203 return fill;
11204 }
11205
11206 visited.push(fill);
11207 fill = target.fill;
11208 }
11209
11210 return false;
11211}
11212
11213function createMapper(source) {
11214 var fill = source.fill;
11215 var type = 'dataset';
11216
11217 if (fill === false) {
11218 return null;
11219 }
11220
11221 if (!isFinite(fill)) {
11222 type = 'boundary';
11223 }
11224
11225 return mappers[type](source);
11226}
11227
11228function isDrawable(point) {
11229 return point && !point.skip;
11230}
11231
11232function drawArea(ctx, curve0, curve1, len0, len1) {
11233 var i;
11234
11235 if (!len0 || !len1) {
11236 return;
11237 }
11238
11239 // building first area curve (normal)
11240 ctx.moveTo(curve0[0].x, curve0[0].y);
11241 for (i = 1; i < len0; ++i) {
11242 helpers.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
11243 }
11244
11245 // joining the two area curves
11246 ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
11247
11248 // building opposite area curve (reverse)
11249 for (i = len1 - 1; i > 0; --i) {
11250 helpers.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
11251 }
11252}
11253
11254function doFill(ctx, points, mapper, view, color, loop) {
11255 var count = points.length;
11256 var span = view.spanGaps;
11257 var curve0 = [];
11258 var curve1 = [];
11259 var len0 = 0;
11260 var len1 = 0;
11261 var i, ilen, index, p0, p1, d0, d1;
11262
11263 ctx.beginPath();
11264
11265 for (i = 0, ilen = (count + !!loop); i < ilen; ++i) {
11266 index = i % count;
11267 p0 = points[index]._view;
11268 p1 = mapper(p0, index, view);
11269 d0 = isDrawable(p0);
11270 d1 = isDrawable(p1);
11271
11272 if (d0 && d1) {
11273 len0 = curve0.push(p0);
11274 len1 = curve1.push(p1);
11275 } else if (len0 && len1) {
11276 if (!span) {
11277 drawArea(ctx, curve0, curve1, len0, len1);
11278 len0 = len1 = 0;
11279 curve0 = [];
11280 curve1 = [];
11281 } else {
11282 if (d0) {
11283 curve0.push(p0);
11284 }
11285 if (d1) {
11286 curve1.push(p1);
11287 }
11288 }
11289 }
11290 }
11291
11292 drawArea(ctx, curve0, curve1, len0, len1);
11293
11294 ctx.closePath();
11295 ctx.fillStyle = color;
11296 ctx.fill();
11297}
11298
11299module.exports = {
11300 id: 'filler',
11301
11302 afterDatasetsUpdate: function(chart, options) {
11303 var count = (chart.data.datasets || []).length;
11304 var propagate = options.propagate;
11305 var sources = [];
11306 var meta, i, el, source;
11307
11308 for (i = 0; i < count; ++i) {
11309 meta = chart.getDatasetMeta(i);
11310 el = meta.dataset;
11311 source = null;
11312
11313 if (el && el._model && el instanceof elements.Line) {
11314 source = {
11315 visible: chart.isDatasetVisible(i),
11316 fill: decodeFill(el, i, count),
11317 chart: chart,
11318 el: el
11319 };
11320 }
11321
11322 meta.$filler = source;
11323 sources.push(source);
11324 }
11325
11326 for (i = 0; i < count; ++i) {
11327 source = sources[i];
11328 if (!source) {
11329 continue;
11330 }
11331
11332 source.fill = resolveTarget(sources, i, propagate);
11333 source.boundary = computeBoundary(source);
11334 source.mapper = createMapper(source);
11335 }
11336 },
11337
11338 beforeDatasetDraw: function(chart, args) {
11339 var meta = args.meta.$filler;
11340 if (!meta) {
11341 return;
11342 }
11343
11344 var ctx = chart.ctx;
11345 var el = meta.el;
11346 var view = el._view;
11347 var points = el._children || [];
11348 var mapper = meta.mapper;
11349 var color = view.backgroundColor || defaults.global.defaultColor;
11350
11351 if (mapper && color && points.length) {
11352 helpers.canvas.clipArea(ctx, chart.chartArea);
11353 doFill(ctx, points, mapper, view, color, el._loop);
11354 helpers.canvas.unclipArea(ctx);
11355 }
11356 }
11357};
11358
11359},{"25":25,"40":40,"45":45}],51:[function(require,module,exports){
11360'use strict';
11361
11362var defaults = require(25);
11363var Element = require(26);
11364var helpers = require(45);
11365var layouts = require(30);
11366
11367var noop = helpers.noop;
11368
11369defaults._set('global', {
11370 legend: {
11371 display: true,
11372 position: 'top',
11373 fullWidth: true,
11374 reverse: false,
11375 weight: 1000,
11376
11377 // a callback that will handle
11378 onClick: function(e, legendItem) {
11379 var index = legendItem.datasetIndex;
11380 var ci = this.chart;
11381 var meta = ci.getDatasetMeta(index);
11382
11383 // See controller.isDatasetVisible comment
11384 meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
11385
11386 // We hid a dataset ... rerender the chart
11387 ci.update();
11388 },
11389
11390 onHover: null,
11391
11392 labels: {
11393 boxWidth: 40,
11394 padding: 10,
11395 // Generates labels shown in the legend
11396 // Valid properties to return:
11397 // text : text to display
11398 // fillStyle : fill of coloured box
11399 // strokeStyle: stroke of coloured box
11400 // hidden : if this legend item refers to a hidden item
11401 // lineCap : cap style for line
11402 // lineDash
11403 // lineDashOffset :
11404 // lineJoin :
11405 // lineWidth :
11406 generateLabels: function(chart) {
11407 var data = chart.data;
11408 return helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {
11409 return {
11410 text: dataset.label,
11411 fillStyle: (!helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
11412 hidden: !chart.isDatasetVisible(i),
11413 lineCap: dataset.borderCapStyle,
11414 lineDash: dataset.borderDash,
11415 lineDashOffset: dataset.borderDashOffset,
11416 lineJoin: dataset.borderJoinStyle,
11417 lineWidth: dataset.borderWidth,
11418 strokeStyle: dataset.borderColor,
11419 pointStyle: dataset.pointStyle,
11420
11421 // Below is extra data used for toggling the datasets
11422 datasetIndex: i
11423 };
11424 }, this) : [];
11425 }
11426 }
11427 },
11428
11429 legendCallback: function(chart) {
11430 var text = [];
11431 text.push('<ul class="' + chart.id + '-legend">');
11432 for (var i = 0; i < chart.data.datasets.length; i++) {
11433 text.push('<li><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"></span>');
11434 if (chart.data.datasets[i].label) {
11435 text.push(chart.data.datasets[i].label);
11436 }
11437 text.push('</li>');
11438 }
11439 text.push('</ul>');
11440 return text.join('');
11441 }
11442});
11443
11444/**
11445 * Helper function to get the box width based on the usePointStyle option
11446 * @param labelopts {Object} the label options on the legend
11447 * @param fontSize {Number} the label font size
11448 * @return {Number} width of the color box area
11449 */
11450function getBoxWidth(labelOpts, fontSize) {
11451 return labelOpts.usePointStyle ?
11452 fontSize * Math.SQRT2 :
11453 labelOpts.boxWidth;
11454}
11455
11456/**
11457 * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
11458 */
11459var Legend = Element.extend({
11460
11461 initialize: function(config) {
11462 helpers.extend(this, config);
11463
11464 // Contains hit boxes for each dataset (in dataset order)
11465 this.legendHitBoxes = [];
11466
11467 // Are we in doughnut mode which has a different data type
11468 this.doughnutMode = false;
11469 },
11470
11471 // These methods are ordered by lifecycle. Utilities then follow.
11472 // Any function defined here is inherited by all legend types.
11473 // Any function can be extended by the legend type
11474
11475 beforeUpdate: noop,
11476 update: function(maxWidth, maxHeight, margins) {
11477 var me = this;
11478
11479 // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
11480 me.beforeUpdate();
11481
11482 // Absorb the master measurements
11483 me.maxWidth = maxWidth;
11484 me.maxHeight = maxHeight;
11485 me.margins = margins;
11486
11487 // Dimensions
11488 me.beforeSetDimensions();
11489 me.setDimensions();
11490 me.afterSetDimensions();
11491 // Labels
11492 me.beforeBuildLabels();
11493 me.buildLabels();
11494 me.afterBuildLabels();
11495
11496 // Fit
11497 me.beforeFit();
11498 me.fit();
11499 me.afterFit();
11500 //
11501 me.afterUpdate();
11502
11503 return me.minSize;
11504 },
11505 afterUpdate: noop,
11506
11507 //
11508
11509 beforeSetDimensions: noop,
11510 setDimensions: function() {
11511 var me = this;
11512 // Set the unconstrained dimension before label rotation
11513 if (me.isHorizontal()) {
11514 // Reset position before calculating rotation
11515 me.width = me.maxWidth;
11516 me.left = 0;
11517 me.right = me.width;
11518 } else {
11519 me.height = me.maxHeight;
11520
11521 // Reset position before calculating rotation
11522 me.top = 0;
11523 me.bottom = me.height;
11524 }
11525
11526 // Reset padding
11527 me.paddingLeft = 0;
11528 me.paddingTop = 0;
11529 me.paddingRight = 0;
11530 me.paddingBottom = 0;
11531
11532 // Reset minSize
11533 me.minSize = {
11534 width: 0,
11535 height: 0
11536 };
11537 },
11538 afterSetDimensions: noop,
11539
11540 //
11541
11542 beforeBuildLabels: noop,
11543 buildLabels: function() {
11544 var me = this;
11545 var labelOpts = me.options.labels || {};
11546 var legendItems = helpers.callback(labelOpts.generateLabels, [me.chart], me) || [];
11547
11548 if (labelOpts.filter) {
11549 legendItems = legendItems.filter(function(item) {
11550 return labelOpts.filter(item, me.chart.data);
11551 });
11552 }
11553
11554 if (me.options.reverse) {
11555 legendItems.reverse();
11556 }
11557
11558 me.legendItems = legendItems;
11559 },
11560 afterBuildLabels: noop,
11561
11562 //
11563
11564 beforeFit: noop,
11565 fit: function() {
11566 var me = this;
11567 var opts = me.options;
11568 var labelOpts = opts.labels;
11569 var display = opts.display;
11570
11571 var ctx = me.ctx;
11572
11573 var globalDefault = defaults.global;
11574 var valueOrDefault = helpers.valueOrDefault;
11575 var fontSize = valueOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize);
11576 var fontStyle = valueOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle);
11577 var fontFamily = valueOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily);
11578 var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily);
11579
11580 // Reset hit boxes
11581 var hitboxes = me.legendHitBoxes = [];
11582
11583 var minSize = me.minSize;
11584 var isHorizontal = me.isHorizontal();
11585
11586 if (isHorizontal) {
11587 minSize.width = me.maxWidth; // fill all the width
11588 minSize.height = display ? 10 : 0;
11589 } else {
11590 minSize.width = display ? 10 : 0;
11591 minSize.height = me.maxHeight; // fill all the height
11592 }
11593
11594 // Increase sizes here
11595 if (display) {
11596 ctx.font = labelFont;
11597
11598 if (isHorizontal) {
11599 // Labels
11600
11601 // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
11602 var lineWidths = me.lineWidths = [0];
11603 var totalHeight = me.legendItems.length ? fontSize + (labelOpts.padding) : 0;
11604
11605 ctx.textAlign = 'left';
11606 ctx.textBaseline = 'top';
11607
11608 helpers.each(me.legendItems, function(legendItem, i) {
11609 var boxWidth = getBoxWidth(labelOpts, fontSize);
11610 var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
11611
11612 if (lineWidths[lineWidths.length - 1] + width + labelOpts.padding >= me.width) {
11613 totalHeight += fontSize + (labelOpts.padding);
11614 lineWidths[lineWidths.length] = me.left;
11615 }
11616
11617 // Store the hitbox width and height here. Final position will be updated in `draw`
11618 hitboxes[i] = {
11619 left: 0,
11620 top: 0,
11621 width: width,
11622 height: fontSize
11623 };
11624
11625 lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
11626 });
11627
11628 minSize.height += totalHeight;
11629
11630 } else {
11631 var vPadding = labelOpts.padding;
11632 var columnWidths = me.columnWidths = [];
11633 var totalWidth = labelOpts.padding;
11634 var currentColWidth = 0;
11635 var currentColHeight = 0;
11636 var itemHeight = fontSize + vPadding;
11637
11638 helpers.each(me.legendItems, function(legendItem, i) {
11639 var boxWidth = getBoxWidth(labelOpts, fontSize);
11640 var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
11641
11642 // If too tall, go to new column
11643 if (currentColHeight + itemHeight > minSize.height) {
11644 totalWidth += currentColWidth + labelOpts.padding;
11645 columnWidths.push(currentColWidth); // previous column width
11646
11647 currentColWidth = 0;
11648 currentColHeight = 0;
11649 }
11650
11651 // Get max width
11652 currentColWidth = Math.max(currentColWidth, itemWidth);
11653 currentColHeight += itemHeight;
11654
11655 // Store the hitbox width and height here. Final position will be updated in `draw`
11656 hitboxes[i] = {
11657 left: 0,
11658 top: 0,
11659 width: itemWidth,
11660 height: fontSize
11661 };
11662 });
11663
11664 totalWidth += currentColWidth;
11665 columnWidths.push(currentColWidth);
11666 minSize.width += totalWidth;
11667 }
11668 }
11669
11670 me.width = minSize.width;
11671 me.height = minSize.height;
11672 },
11673 afterFit: noop,
11674
11675 // Shared Methods
11676 isHorizontal: function() {
11677 return this.options.position === 'top' || this.options.position === 'bottom';
11678 },
11679
11680 // Actually draw the legend on the canvas
11681 draw: function() {
11682 var me = this;
11683 var opts = me.options;
11684 var labelOpts = opts.labels;
11685 var globalDefault = defaults.global;
11686 var lineDefault = globalDefault.elements.line;
11687 var legendWidth = me.width;
11688 var lineWidths = me.lineWidths;
11689
11690 if (opts.display) {
11691 var ctx = me.ctx;
11692 var valueOrDefault = helpers.valueOrDefault;
11693 var fontColor = valueOrDefault(labelOpts.fontColor, globalDefault.defaultFontColor);
11694 var fontSize = valueOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize);
11695 var fontStyle = valueOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle);
11696 var fontFamily = valueOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily);
11697 var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily);
11698 var cursor;
11699
11700 // Canvas setup
11701 ctx.textAlign = 'left';
11702 ctx.textBaseline = 'middle';
11703 ctx.lineWidth = 0.5;
11704 ctx.strokeStyle = fontColor; // for strikethrough effect
11705 ctx.fillStyle = fontColor; // render in correct colour
11706 ctx.font = labelFont;
11707
11708 var boxWidth = getBoxWidth(labelOpts, fontSize);
11709 var hitboxes = me.legendHitBoxes;
11710
11711 // current position
11712 var drawLegendBox = function(x, y, legendItem) {
11713 if (isNaN(boxWidth) || boxWidth <= 0) {
11714 return;
11715 }
11716
11717 // Set the ctx for the box
11718 ctx.save();
11719
11720 ctx.fillStyle = valueOrDefault(legendItem.fillStyle, globalDefault.defaultColor);
11721 ctx.lineCap = valueOrDefault(legendItem.lineCap, lineDefault.borderCapStyle);
11722 ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, lineDefault.borderDashOffset);
11723 ctx.lineJoin = valueOrDefault(legendItem.lineJoin, lineDefault.borderJoinStyle);
11724 ctx.lineWidth = valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth);
11725 ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, globalDefault.defaultColor);
11726 var isLineWidthZero = (valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth) === 0);
11727
11728 if (ctx.setLineDash) {
11729 // IE 9 and 10 do not support line dash
11730 ctx.setLineDash(valueOrDefault(legendItem.lineDash, lineDefault.borderDash));
11731 }
11732
11733 if (opts.labels && opts.labels.usePointStyle) {
11734 // Recalculate x and y for drawPoint() because its expecting
11735 // x and y to be center of figure (instead of top left)
11736 var radius = fontSize * Math.SQRT2 / 2;
11737 var offSet = radius / Math.SQRT2;
11738 var centerX = x + offSet;
11739 var centerY = y + offSet;
11740
11741 // Draw pointStyle as legend symbol
11742 helpers.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY);
11743 } else {
11744 // Draw box as legend symbol
11745 if (!isLineWidthZero) {
11746 ctx.strokeRect(x, y, boxWidth, fontSize);
11747 }
11748 ctx.fillRect(x, y, boxWidth, fontSize);
11749 }
11750
11751 ctx.restore();
11752 };
11753 var fillText = function(x, y, legendItem, textWidth) {
11754 var halfFontSize = fontSize / 2;
11755 var xLeft = boxWidth + halfFontSize + x;
11756 var yMiddle = y + halfFontSize;
11757
11758 ctx.fillText(legendItem.text, xLeft, yMiddle);
11759
11760 if (legendItem.hidden) {
11761 // Strikethrough the text if hidden
11762 ctx.beginPath();
11763 ctx.lineWidth = 2;
11764 ctx.moveTo(xLeft, yMiddle);
11765 ctx.lineTo(xLeft + textWidth, yMiddle);
11766 ctx.stroke();
11767 }
11768 };
11769
11770 // Horizontal
11771 var isHorizontal = me.isHorizontal();
11772 if (isHorizontal) {
11773 cursor = {
11774 x: me.left + ((legendWidth - lineWidths[0]) / 2),
11775 y: me.top + labelOpts.padding,
11776 line: 0
11777 };
11778 } else {
11779 cursor = {
11780 x: me.left + labelOpts.padding,
11781 y: me.top + labelOpts.padding,
11782 line: 0
11783 };
11784 }
11785
11786 var itemHeight = fontSize + labelOpts.padding;
11787 helpers.each(me.legendItems, function(legendItem, i) {
11788 var textWidth = ctx.measureText(legendItem.text).width;
11789 var width = boxWidth + (fontSize / 2) + textWidth;
11790 var x = cursor.x;
11791 var y = cursor.y;
11792
11793 if (isHorizontal) {
11794 if (x + width >= legendWidth) {
11795 y = cursor.y += itemHeight;
11796 cursor.line++;
11797 x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2);
11798 }
11799 } else if (y + itemHeight > me.bottom) {
11800 x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
11801 y = cursor.y = me.top + labelOpts.padding;
11802 cursor.line++;
11803 }
11804
11805 drawLegendBox(x, y, legendItem);
11806
11807 hitboxes[i].left = x;
11808 hitboxes[i].top = y;
11809
11810 // Fill the actual label
11811 fillText(x, y, legendItem, textWidth);
11812
11813 if (isHorizontal) {
11814 cursor.x += width + (labelOpts.padding);
11815 } else {
11816 cursor.y += itemHeight;
11817 }
11818
11819 });
11820 }
11821 },
11822
11823 /**
11824 * Handle an event
11825 * @private
11826 * @param {IEvent} event - The event to handle
11827 * @return {Boolean} true if a change occured
11828 */
11829 handleEvent: function(e) {
11830 var me = this;
11831 var opts = me.options;
11832 var type = e.type === 'mouseup' ? 'click' : e.type;
11833 var changed = false;
11834
11835 if (type === 'mousemove') {
11836 if (!opts.onHover) {
11837 return;
11838 }
11839 } else if (type === 'click') {
11840 if (!opts.onClick) {
11841 return;
11842 }
11843 } else {
11844 return;
11845 }
11846
11847 // Chart event already has relative position in it
11848 var x = e.x;
11849 var y = e.y;
11850
11851 if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
11852 // See if we are touching one of the dataset boxes
11853 var lh = me.legendHitBoxes;
11854 for (var i = 0; i < lh.length; ++i) {
11855 var hitBox = lh[i];
11856
11857 if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
11858 // Touching an element
11859 if (type === 'click') {
11860 // use e.native for backwards compatibility
11861 opts.onClick.call(me, e.native, me.legendItems[i]);
11862 changed = true;
11863 break;
11864 } else if (type === 'mousemove') {
11865 // use e.native for backwards compatibility
11866 opts.onHover.call(me, e.native, me.legendItems[i]);
11867 changed = true;
11868 break;
11869 }
11870 }
11871 }
11872 }
11873
11874 return changed;
11875 }
11876});
11877
11878function createNewLegendAndAttach(chart, legendOpts) {
11879 var legend = new Legend({
11880 ctx: chart.ctx,
11881 options: legendOpts,
11882 chart: chart
11883 });
11884
11885 layouts.configure(chart, legend, legendOpts);
11886 layouts.addBox(chart, legend);
11887 chart.legend = legend;
11888}
11889
11890module.exports = {
11891 id: 'legend',
11892
11893 /**
11894 * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
11895 * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
11896 * the plugin, which one will be re-exposed in the chart.js file.
11897 * https://github.com/chartjs/Chart.js/pull/2640
11898 * @private
11899 */
11900 _element: Legend,
11901
11902 beforeInit: function(chart) {
11903 var legendOpts = chart.options.legend;
11904
11905 if (legendOpts) {
11906 createNewLegendAndAttach(chart, legendOpts);
11907 }
11908 },
11909
11910 beforeUpdate: function(chart) {
11911 var legendOpts = chart.options.legend;
11912 var legend = chart.legend;
11913
11914 if (legendOpts) {
11915 helpers.mergeIf(legendOpts, defaults.global.legend);
11916
11917 if (legend) {
11918 layouts.configure(chart, legend, legendOpts);
11919 legend.options = legendOpts;
11920 } else {
11921 createNewLegendAndAttach(chart, legendOpts);
11922 }
11923 } else if (legend) {
11924 layouts.removeBox(chart, legend);
11925 delete chart.legend;
11926 }
11927 },
11928
11929 afterEvent: function(chart, e) {
11930 var legend = chart.legend;
11931 if (legend) {
11932 legend.handleEvent(e);
11933 }
11934 }
11935};
11936
11937},{"25":25,"26":26,"30":30,"45":45}],52:[function(require,module,exports){
11938'use strict';
11939
11940var defaults = require(25);
11941var Element = require(26);
11942var helpers = require(45);
11943var layouts = require(30);
11944
11945var noop = helpers.noop;
11946
11947defaults._set('global', {
11948 title: {
11949 display: false,
11950 fontStyle: 'bold',
11951 fullWidth: true,
11952 lineHeight: 1.2,
11953 padding: 10,
11954 position: 'top',
11955 text: '',
11956 weight: 2000 // by default greater than legend (1000) to be above
11957 }
11958});
11959
11960/**
11961 * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
11962 */
11963var Title = Element.extend({
11964 initialize: function(config) {
11965 var me = this;
11966 helpers.extend(me, config);
11967
11968 // Contains hit boxes for each dataset (in dataset order)
11969 me.legendHitBoxes = [];
11970 },
11971
11972 // These methods are ordered by lifecycle. Utilities then follow.
11973
11974 beforeUpdate: noop,
11975 update: function(maxWidth, maxHeight, margins) {
11976 var me = this;
11977
11978 // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
11979 me.beforeUpdate();
11980
11981 // Absorb the master measurements
11982 me.maxWidth = maxWidth;
11983 me.maxHeight = maxHeight;
11984 me.margins = margins;
11985
11986 // Dimensions
11987 me.beforeSetDimensions();
11988 me.setDimensions();
11989 me.afterSetDimensions();
11990 // Labels
11991 me.beforeBuildLabels();
11992 me.buildLabels();
11993 me.afterBuildLabels();
11994
11995 // Fit
11996 me.beforeFit();
11997 me.fit();
11998 me.afterFit();
11999 //
12000 me.afterUpdate();
12001
12002 return me.minSize;
12003
12004 },
12005 afterUpdate: noop,
12006
12007 //
12008
12009 beforeSetDimensions: noop,
12010 setDimensions: function() {
12011 var me = this;
12012 // Set the unconstrained dimension before label rotation
12013 if (me.isHorizontal()) {
12014 // Reset position before calculating rotation
12015 me.width = me.maxWidth;
12016 me.left = 0;
12017 me.right = me.width;
12018 } else {
12019 me.height = me.maxHeight;
12020
12021 // Reset position before calculating rotation
12022 me.top = 0;
12023 me.bottom = me.height;
12024 }
12025
12026 // Reset padding
12027 me.paddingLeft = 0;
12028 me.paddingTop = 0;
12029 me.paddingRight = 0;
12030 me.paddingBottom = 0;
12031
12032 // Reset minSize
12033 me.minSize = {
12034 width: 0,
12035 height: 0
12036 };
12037 },
12038 afterSetDimensions: noop,
12039
12040 //
12041
12042 beforeBuildLabels: noop,
12043 buildLabels: noop,
12044 afterBuildLabels: noop,
12045
12046 //
12047
12048 beforeFit: noop,
12049 fit: function() {
12050 var me = this;
12051 var valueOrDefault = helpers.valueOrDefault;
12052 var opts = me.options;
12053 var display = opts.display;
12054 var fontSize = valueOrDefault(opts.fontSize, defaults.global.defaultFontSize);
12055 var minSize = me.minSize;
12056 var lineCount = helpers.isArray(opts.text) ? opts.text.length : 1;
12057 var lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize);
12058 var textSize = display ? (lineCount * lineHeight) + (opts.padding * 2) : 0;
12059
12060 if (me.isHorizontal()) {
12061 minSize.width = me.maxWidth; // fill all the width
12062 minSize.height = textSize;
12063 } else {
12064 minSize.width = textSize;
12065 minSize.height = me.maxHeight; // fill all the height
12066 }
12067
12068 me.width = minSize.width;
12069 me.height = minSize.height;
12070
12071 },
12072 afterFit: noop,
12073
12074 // Shared Methods
12075 isHorizontal: function() {
12076 var pos = this.options.position;
12077 return pos === 'top' || pos === 'bottom';
12078 },
12079
12080 // Actually draw the title block on the canvas
12081 draw: function() {
12082 var me = this;
12083 var ctx = me.ctx;
12084 var valueOrDefault = helpers.valueOrDefault;
12085 var opts = me.options;
12086 var globalDefaults = defaults.global;
12087
12088 if (opts.display) {
12089 var fontSize = valueOrDefault(opts.fontSize, globalDefaults.defaultFontSize);
12090 var fontStyle = valueOrDefault(opts.fontStyle, globalDefaults.defaultFontStyle);
12091 var fontFamily = valueOrDefault(opts.fontFamily, globalDefaults.defaultFontFamily);
12092 var titleFont = helpers.fontString(fontSize, fontStyle, fontFamily);
12093 var lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize);
12094 var offset = lineHeight / 2 + opts.padding;
12095 var rotation = 0;
12096 var top = me.top;
12097 var left = me.left;
12098 var bottom = me.bottom;
12099 var right = me.right;
12100 var maxWidth, titleX, titleY;
12101
12102 ctx.fillStyle = valueOrDefault(opts.fontColor, globalDefaults.defaultFontColor); // render in correct colour
12103 ctx.font = titleFont;
12104
12105 // Horizontal
12106 if (me.isHorizontal()) {
12107 titleX = left + ((right - left) / 2); // midpoint of the width
12108 titleY = top + offset;
12109 maxWidth = right - left;
12110 } else {
12111 titleX = opts.position === 'left' ? left + offset : right - offset;
12112 titleY = top + ((bottom - top) / 2);
12113 maxWidth = bottom - top;
12114 rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
12115 }
12116
12117 ctx.save();
12118 ctx.translate(titleX, titleY);
12119 ctx.rotate(rotation);
12120 ctx.textAlign = 'center';
12121 ctx.textBaseline = 'middle';
12122
12123 var text = opts.text;
12124 if (helpers.isArray(text)) {
12125 var y = 0;
12126 for (var i = 0; i < text.length; ++i) {
12127 ctx.fillText(text[i], 0, y, maxWidth);
12128 y += lineHeight;
12129 }
12130 } else {
12131 ctx.fillText(text, 0, 0, maxWidth);
12132 }
12133
12134 ctx.restore();
12135 }
12136 }
12137});
12138
12139function createNewTitleBlockAndAttach(chart, titleOpts) {
12140 var title = new Title({
12141 ctx: chart.ctx,
12142 options: titleOpts,
12143 chart: chart
12144 });
12145
12146 layouts.configure(chart, title, titleOpts);
12147 layouts.addBox(chart, title);
12148 chart.titleBlock = title;
12149}
12150
12151module.exports = {
12152 id: 'title',
12153
12154 /**
12155 * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
12156 * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
12157 * the plugin, which one will be re-exposed in the chart.js file.
12158 * https://github.com/chartjs/Chart.js/pull/2640
12159 * @private
12160 */
12161 _element: Title,
12162
12163 beforeInit: function(chart) {
12164 var titleOpts = chart.options.title;
12165
12166 if (titleOpts) {
12167 createNewTitleBlockAndAttach(chart, titleOpts);
12168 }
12169 },
12170
12171 beforeUpdate: function(chart) {
12172 var titleOpts = chart.options.title;
12173 var titleBlock = chart.titleBlock;
12174
12175 if (titleOpts) {
12176 helpers.mergeIf(titleOpts, defaults.global.title);
12177
12178 if (titleBlock) {
12179 layouts.configure(chart, titleBlock, titleOpts);
12180 titleBlock.options = titleOpts;
12181 } else {
12182 createNewTitleBlockAndAttach(chart, titleOpts);
12183 }
12184 } else if (titleBlock) {
12185 layouts.removeBox(chart, titleBlock);
12186 delete chart.titleBlock;
12187 }
12188 }
12189};
12190
12191},{"25":25,"26":26,"30":30,"45":45}],53:[function(require,module,exports){
12192'use strict';
12193
12194module.exports = function(Chart) {
12195
12196 // Default config for a category scale
12197 var defaultConfig = {
12198 position: 'bottom'
12199 };
12200
12201 var DatasetScale = Chart.Scale.extend({
12202 /**
12203 * Internal function to get the correct labels. If data.xLabels or data.yLabels are defined, use those
12204 * else fall back to data.labels
12205 * @private
12206 */
12207 getLabels: function() {
12208 var data = this.chart.data;
12209 return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels;
12210 },
12211
12212 determineDataLimits: function() {
12213 var me = this;
12214 var labels = me.getLabels();
12215 me.minIndex = 0;
12216 me.maxIndex = labels.length - 1;
12217 var findIndex;
12218
12219 if (me.options.ticks.min !== undefined) {
12220 // user specified min value
12221 findIndex = labels.indexOf(me.options.ticks.min);
12222 me.minIndex = findIndex !== -1 ? findIndex : me.minIndex;
12223 }
12224
12225 if (me.options.ticks.max !== undefined) {
12226 // user specified max value
12227 findIndex = labels.indexOf(me.options.ticks.max);
12228 me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex;
12229 }
12230
12231 me.min = labels[me.minIndex];
12232 me.max = labels[me.maxIndex];
12233 },
12234
12235 buildTicks: function() {
12236 var me = this;
12237 var labels = me.getLabels();
12238 // If we are viewing some subset of labels, slice the original array
12239 me.ticks = (me.minIndex === 0 && me.maxIndex === labels.length - 1) ? labels : labels.slice(me.minIndex, me.maxIndex + 1);
12240 },
12241
12242 getLabelForIndex: function(index, datasetIndex) {
12243 var me = this;
12244 var data = me.chart.data;
12245 var isHorizontal = me.isHorizontal();
12246
12247 if (data.yLabels && !isHorizontal) {
12248 return me.getRightValue(data.datasets[datasetIndex].data[index]);
12249 }
12250 return me.ticks[index - me.minIndex];
12251 },
12252
12253 // Used to get data value locations. Value can either be an index or a numerical value
12254 getPixelForValue: function(value, index) {
12255 var me = this;
12256 var offset = me.options.offset;
12257 // 1 is added because we need the length but we have the indexes
12258 var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - (offset ? 0 : 1)), 1);
12259
12260 // If value is a data object, then index is the index in the data array,
12261 // not the index of the scale. We need to change that.
12262 var valueCategory;
12263 if (value !== undefined && value !== null) {
12264 valueCategory = me.isHorizontal() ? value.x : value.y;
12265 }
12266 if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
12267 var labels = me.getLabels();
12268 value = valueCategory || value;
12269 var idx = labels.indexOf(value);
12270 index = idx !== -1 ? idx : index;
12271 }
12272
12273 if (me.isHorizontal()) {
12274 var valueWidth = me.width / offsetAmt;
12275 var widthOffset = (valueWidth * (index - me.minIndex));
12276
12277 if (offset) {
12278 widthOffset += (valueWidth / 2);
12279 }
12280
12281 return me.left + Math.round(widthOffset);
12282 }
12283 var valueHeight = me.height / offsetAmt;
12284 var heightOffset = (valueHeight * (index - me.minIndex));
12285
12286 if (offset) {
12287 heightOffset += (valueHeight / 2);
12288 }
12289
12290 return me.top + Math.round(heightOffset);
12291 },
12292 getPixelForTick: function(index) {
12293 return this.getPixelForValue(this.ticks[index], index + this.minIndex, null);
12294 },
12295 getValueForPixel: function(pixel) {
12296 var me = this;
12297 var offset = me.options.offset;
12298 var value;
12299 var offsetAmt = Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
12300 var horz = me.isHorizontal();
12301 var valueDimension = (horz ? me.width : me.height) / offsetAmt;
12302
12303 pixel -= horz ? me.left : me.top;
12304
12305 if (offset) {
12306 pixel -= (valueDimension / 2);
12307 }
12308
12309 if (pixel <= 0) {
12310 value = 0;
12311 } else {
12312 value = Math.round(pixel / valueDimension);
12313 }
12314
12315 return value + me.minIndex;
12316 },
12317 getBasePixel: function() {
12318 return this.bottom;
12319 }
12320 });
12321
12322 Chart.scaleService.registerScaleType('category', DatasetScale, defaultConfig);
12323
12324};
12325
12326},{}],54:[function(require,module,exports){
12327'use strict';
12328
12329var defaults = require(25);
12330var helpers = require(45);
12331var Ticks = require(34);
12332
12333module.exports = function(Chart) {
12334
12335 var defaultConfig = {
12336 position: 'left',
12337 ticks: {
12338 callback: Ticks.formatters.linear
12339 }
12340 };
12341
12342 var LinearScale = Chart.LinearScaleBase.extend({
12343
12344 determineDataLimits: function() {
12345 var me = this;
12346 var opts = me.options;
12347 var chart = me.chart;
12348 var data = chart.data;
12349 var datasets = data.datasets;
12350 var isHorizontal = me.isHorizontal();
12351 var DEFAULT_MIN = 0;
12352 var DEFAULT_MAX = 1;
12353
12354 function IDMatches(meta) {
12355 return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
12356 }
12357
12358 // First Calculate the range
12359 me.min = null;
12360 me.max = null;
12361
12362 var hasStacks = opts.stacked;
12363 if (hasStacks === undefined) {
12364 helpers.each(datasets, function(dataset, datasetIndex) {
12365 if (hasStacks) {
12366 return;
12367 }
12368
12369 var meta = chart.getDatasetMeta(datasetIndex);
12370 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
12371 meta.stack !== undefined) {
12372 hasStacks = true;
12373 }
12374 });
12375 }
12376
12377 if (opts.stacked || hasStacks) {
12378 var valuesPerStack = {};
12379
12380 helpers.each(datasets, function(dataset, datasetIndex) {
12381 var meta = chart.getDatasetMeta(datasetIndex);
12382 var key = [
12383 meta.type,
12384 // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
12385 ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
12386 meta.stack
12387 ].join('.');
12388
12389 if (valuesPerStack[key] === undefined) {
12390 valuesPerStack[key] = {
12391 positiveValues: [],
12392 negativeValues: []
12393 };
12394 }
12395
12396 // Store these per type
12397 var positiveValues = valuesPerStack[key].positiveValues;
12398 var negativeValues = valuesPerStack[key].negativeValues;
12399
12400 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
12401 helpers.each(dataset.data, function(rawValue, index) {
12402 var value = +me.getRightValue(rawValue);
12403 if (isNaN(value) || meta.data[index].hidden) {
12404 return;
12405 }
12406
12407 positiveValues[index] = positiveValues[index] || 0;
12408 negativeValues[index] = negativeValues[index] || 0;
12409
12410 if (opts.relativePoints) {
12411 positiveValues[index] = 100;
12412 } else if (value < 0) {
12413 negativeValues[index] += value;
12414 } else {
12415 positiveValues[index] += value;
12416 }
12417 });
12418 }
12419 });
12420
12421 helpers.each(valuesPerStack, function(valuesForType) {
12422 var values = valuesForType.positiveValues.concat(valuesForType.negativeValues);
12423 var minVal = helpers.min(values);
12424 var maxVal = helpers.max(values);
12425 me.min = me.min === null ? minVal : Math.min(me.min, minVal);
12426 me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
12427 });
12428
12429 } else {
12430 helpers.each(datasets, function(dataset, datasetIndex) {
12431 var meta = chart.getDatasetMeta(datasetIndex);
12432 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
12433 helpers.each(dataset.data, function(rawValue, index) {
12434 var value = +me.getRightValue(rawValue);
12435 if (isNaN(value) || meta.data[index].hidden) {
12436 return;
12437 }
12438
12439 if (me.min === null) {
12440 me.min = value;
12441 } else if (value < me.min) {
12442 me.min = value;
12443 }
12444
12445 if (me.max === null) {
12446 me.max = value;
12447 } else if (value > me.max) {
12448 me.max = value;
12449 }
12450 });
12451 }
12452 });
12453 }
12454
12455 me.min = isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
12456 me.max = isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
12457
12458 // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
12459 this.handleTickRangeOptions();
12460 },
12461 getTickLimit: function() {
12462 var maxTicks;
12463 var me = this;
12464 var tickOpts = me.options.ticks;
12465
12466 if (me.isHorizontal()) {
12467 maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.width / 50));
12468 } else {
12469 // The factor of 2 used to scale the font size has been experimentally determined.
12470 var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, defaults.global.defaultFontSize);
12471 maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.height / (2 * tickFontSize)));
12472 }
12473
12474 return maxTicks;
12475 },
12476 // Called after the ticks are built. We need
12477 handleDirectionalChanges: function() {
12478 if (!this.isHorizontal()) {
12479 // We are in a vertical orientation. The top value is the highest. So reverse the array
12480 this.ticks.reverse();
12481 }
12482 },
12483 getLabelForIndex: function(index, datasetIndex) {
12484 return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
12485 },
12486 // Utils
12487 getPixelForValue: function(value) {
12488 // This must be called after fit has been run so that
12489 // this.left, this.top, this.right, and this.bottom have been defined
12490 var me = this;
12491 var start = me.start;
12492
12493 var rightValue = +me.getRightValue(value);
12494 var pixel;
12495 var range = me.end - start;
12496
12497 if (me.isHorizontal()) {
12498 pixel = me.left + (me.width / range * (rightValue - start));
12499 } else {
12500 pixel = me.bottom - (me.height / range * (rightValue - start));
12501 }
12502 return pixel;
12503 },
12504 getValueForPixel: function(pixel) {
12505 var me = this;
12506 var isHorizontal = me.isHorizontal();
12507 var innerDimension = isHorizontal ? me.width : me.height;
12508 var offset = (isHorizontal ? pixel - me.left : me.bottom - pixel) / innerDimension;
12509 return me.start + ((me.end - me.start) * offset);
12510 },
12511 getPixelForTick: function(index) {
12512 return this.getPixelForValue(this.ticksAsNumbers[index]);
12513 }
12514 });
12515 Chart.scaleService.registerScaleType('linear', LinearScale, defaultConfig);
12516
12517};
12518
12519},{"25":25,"34":34,"45":45}],55:[function(require,module,exports){
12520'use strict';
12521
12522var helpers = require(45);
12523
12524/**
12525 * Generate a set of linear ticks
12526 * @param generationOptions the options used to generate the ticks
12527 * @param dataRange the range of the data
12528 * @returns {Array<Number>} array of tick values
12529 */
12530function generateTicks(generationOptions, dataRange) {
12531 var ticks = [];
12532 // To get a "nice" value for the tick spacing, we will use the appropriately named
12533 // "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
12534 // for details.
12535
12536 var spacing;
12537 if (generationOptions.stepSize && generationOptions.stepSize > 0) {
12538 spacing = generationOptions.stepSize;
12539 } else {
12540 var niceRange = helpers.niceNum(dataRange.max - dataRange.min, false);
12541 spacing = helpers.niceNum(niceRange / (generationOptions.maxTicks - 1), true);
12542 }
12543 var niceMin = Math.floor(dataRange.min / spacing) * spacing;
12544 var niceMax = Math.ceil(dataRange.max / spacing) * spacing;
12545
12546 // If min, max and stepSize is set and they make an evenly spaced scale use it.
12547 if (generationOptions.min && generationOptions.max && generationOptions.stepSize) {
12548 // If very close to our whole number, use it.
12549 if (helpers.almostWhole((generationOptions.max - generationOptions.min) / generationOptions.stepSize, spacing / 1000)) {
12550 niceMin = generationOptions.min;
12551 niceMax = generationOptions.max;
12552 }
12553 }
12554
12555 var numSpaces = (niceMax - niceMin) / spacing;
12556 // If very close to our rounded value, use it.
12557 if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
12558 numSpaces = Math.round(numSpaces);
12559 } else {
12560 numSpaces = Math.ceil(numSpaces);
12561 }
12562
12563 var precision = 1;
12564 if (spacing < 1) {
12565 precision = Math.pow(10, spacing.toString().length - 2);
12566 niceMin = Math.round(niceMin * precision) / precision;
12567 niceMax = Math.round(niceMax * precision) / precision;
12568 }
12569 ticks.push(generationOptions.min !== undefined ? generationOptions.min : niceMin);
12570 for (var j = 1; j < numSpaces; ++j) {
12571 ticks.push(Math.round((niceMin + j * spacing) * precision) / precision);
12572 }
12573 ticks.push(generationOptions.max !== undefined ? generationOptions.max : niceMax);
12574
12575 return ticks;
12576}
12577
12578
12579module.exports = function(Chart) {
12580
12581 var noop = helpers.noop;
12582
12583 Chart.LinearScaleBase = Chart.Scale.extend({
12584 getRightValue: function(value) {
12585 if (typeof value === 'string') {
12586 return +value;
12587 }
12588 return Chart.Scale.prototype.getRightValue.call(this, value);
12589 },
12590
12591 handleTickRangeOptions: function() {
12592 var me = this;
12593 var opts = me.options;
12594 var tickOpts = opts.ticks;
12595
12596 // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
12597 // do nothing since that would make the chart weird. If the user really wants a weird chart
12598 // axis, they can manually override it
12599 if (tickOpts.beginAtZero) {
12600 var minSign = helpers.sign(me.min);
12601 var maxSign = helpers.sign(me.max);
12602
12603 if (minSign < 0 && maxSign < 0) {
12604 // move the top up to 0
12605 me.max = 0;
12606 } else if (minSign > 0 && maxSign > 0) {
12607 // move the bottom down to 0
12608 me.min = 0;
12609 }
12610 }
12611
12612 var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
12613 var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
12614
12615 if (tickOpts.min !== undefined) {
12616 me.min = tickOpts.min;
12617 } else if (tickOpts.suggestedMin !== undefined) {
12618 if (me.min === null) {
12619 me.min = tickOpts.suggestedMin;
12620 } else {
12621 me.min = Math.min(me.min, tickOpts.suggestedMin);
12622 }
12623 }
12624
12625 if (tickOpts.max !== undefined) {
12626 me.max = tickOpts.max;
12627 } else if (tickOpts.suggestedMax !== undefined) {
12628 if (me.max === null) {
12629 me.max = tickOpts.suggestedMax;
12630 } else {
12631 me.max = Math.max(me.max, tickOpts.suggestedMax);
12632 }
12633 }
12634
12635 if (setMin !== setMax) {
12636 // We set the min or the max but not both.
12637 // So ensure that our range is good
12638 // Inverted or 0 length range can happen when
12639 // ticks.min is set, and no datasets are visible
12640 if (me.min >= me.max) {
12641 if (setMin) {
12642 me.max = me.min + 1;
12643 } else {
12644 me.min = me.max - 1;
12645 }
12646 }
12647 }
12648
12649 if (me.min === me.max) {
12650 me.max++;
12651
12652 if (!tickOpts.beginAtZero) {
12653 me.min--;
12654 }
12655 }
12656 },
12657 getTickLimit: noop,
12658 handleDirectionalChanges: noop,
12659
12660 buildTicks: function() {
12661 var me = this;
12662 var opts = me.options;
12663 var tickOpts = opts.ticks;
12664
12665 // Figure out what the max number of ticks we can support it is based on the size of
12666 // the axis area. For now, we say that the minimum tick spacing in pixels must be 50
12667 // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
12668 // the graph. Make sure we always have at least 2 ticks
12669 var maxTicks = me.getTickLimit();
12670 maxTicks = Math.max(2, maxTicks);
12671
12672 var numericGeneratorOptions = {
12673 maxTicks: maxTicks,
12674 min: tickOpts.min,
12675 max: tickOpts.max,
12676 stepSize: helpers.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
12677 };
12678 var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
12679
12680 me.handleDirectionalChanges();
12681
12682 // At this point, we need to update our max and min given the tick values since we have expanded the
12683 // range of the scale
12684 me.max = helpers.max(ticks);
12685 me.min = helpers.min(ticks);
12686
12687 if (tickOpts.reverse) {
12688 ticks.reverse();
12689
12690 me.start = me.max;
12691 me.end = me.min;
12692 } else {
12693 me.start = me.min;
12694 me.end = me.max;
12695 }
12696 },
12697 convertTicksToLabels: function() {
12698 var me = this;
12699 me.ticksAsNumbers = me.ticks.slice();
12700 me.zeroLineIndex = me.ticks.indexOf(0);
12701
12702 Chart.Scale.prototype.convertTicksToLabels.call(me);
12703 }
12704 });
12705};
12706
12707},{"45":45}],56:[function(require,module,exports){
12708'use strict';
12709
12710var helpers = require(45);
12711var Ticks = require(34);
12712
12713/**
12714 * Generate a set of logarithmic ticks
12715 * @param generationOptions the options used to generate the ticks
12716 * @param dataRange the range of the data
12717 * @returns {Array<Number>} array of tick values
12718 */
12719function generateTicks(generationOptions, dataRange) {
12720 var ticks = [];
12721 var valueOrDefault = helpers.valueOrDefault;
12722
12723 // Figure out what the max number of ticks we can support it is based on the size of
12724 // the axis area. For now, we say that the minimum tick spacing in pixels must be 50
12725 // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
12726 // the graph
12727 var tickVal = valueOrDefault(generationOptions.min, Math.pow(10, Math.floor(helpers.log10(dataRange.min))));
12728
12729 var endExp = Math.floor(helpers.log10(dataRange.max));
12730 var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
12731 var exp, significand;
12732
12733 if (tickVal === 0) {
12734 exp = Math.floor(helpers.log10(dataRange.minNotZero));
12735 significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
12736
12737 ticks.push(tickVal);
12738 tickVal = significand * Math.pow(10, exp);
12739 } else {
12740 exp = Math.floor(helpers.log10(tickVal));
12741 significand = Math.floor(tickVal / Math.pow(10, exp));
12742 }
12743 var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
12744
12745 do {
12746 ticks.push(tickVal);
12747
12748 ++significand;
12749 if (significand === 10) {
12750 significand = 1;
12751 ++exp;
12752 precision = exp >= 0 ? 1 : precision;
12753 }
12754
12755 tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
12756 } while (exp < endExp || (exp === endExp && significand < endSignificand));
12757
12758 var lastTick = valueOrDefault(generationOptions.max, tickVal);
12759 ticks.push(lastTick);
12760
12761 return ticks;
12762}
12763
12764
12765module.exports = function(Chart) {
12766
12767 var defaultConfig = {
12768 position: 'left',
12769
12770 // label settings
12771 ticks: {
12772 callback: Ticks.formatters.logarithmic
12773 }
12774 };
12775
12776 var LogarithmicScale = Chart.Scale.extend({
12777 determineDataLimits: function() {
12778 var me = this;
12779 var opts = me.options;
12780 var chart = me.chart;
12781 var data = chart.data;
12782 var datasets = data.datasets;
12783 var isHorizontal = me.isHorizontal();
12784 function IDMatches(meta) {
12785 return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
12786 }
12787
12788 // Calculate Range
12789 me.min = null;
12790 me.max = null;
12791 me.minNotZero = null;
12792
12793 var hasStacks = opts.stacked;
12794 if (hasStacks === undefined) {
12795 helpers.each(datasets, function(dataset, datasetIndex) {
12796 if (hasStacks) {
12797 return;
12798 }
12799
12800 var meta = chart.getDatasetMeta(datasetIndex);
12801 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
12802 meta.stack !== undefined) {
12803 hasStacks = true;
12804 }
12805 });
12806 }
12807
12808 if (opts.stacked || hasStacks) {
12809 var valuesPerStack = {};
12810
12811 helpers.each(datasets, function(dataset, datasetIndex) {
12812 var meta = chart.getDatasetMeta(datasetIndex);
12813 var key = [
12814 meta.type,
12815 // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
12816 ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
12817 meta.stack
12818 ].join('.');
12819
12820 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
12821 if (valuesPerStack[key] === undefined) {
12822 valuesPerStack[key] = [];
12823 }
12824
12825 helpers.each(dataset.data, function(rawValue, index) {
12826 var values = valuesPerStack[key];
12827 var value = +me.getRightValue(rawValue);
12828 // invalid, hidden and negative values are ignored
12829 if (isNaN(value) || meta.data[index].hidden || value < 0) {
12830 return;
12831 }
12832 values[index] = values[index] || 0;
12833 values[index] += value;
12834 });
12835 }
12836 });
12837
12838 helpers.each(valuesPerStack, function(valuesForType) {
12839 if (valuesForType.length > 0) {
12840 var minVal = helpers.min(valuesForType);
12841 var maxVal = helpers.max(valuesForType);
12842 me.min = me.min === null ? minVal : Math.min(me.min, minVal);
12843 me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
12844 }
12845 });
12846
12847 } else {
12848 helpers.each(datasets, function(dataset, datasetIndex) {
12849 var meta = chart.getDatasetMeta(datasetIndex);
12850 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
12851 helpers.each(dataset.data, function(rawValue, index) {
12852 var value = +me.getRightValue(rawValue);
12853 // invalid, hidden and negative values are ignored
12854 if (isNaN(value) || meta.data[index].hidden || value < 0) {
12855 return;
12856 }
12857
12858 if (me.min === null) {
12859 me.min = value;
12860 } else if (value < me.min) {
12861 me.min = value;
12862 }
12863
12864 if (me.max === null) {
12865 me.max = value;
12866 } else if (value > me.max) {
12867 me.max = value;
12868 }
12869
12870 if (value !== 0 && (me.minNotZero === null || value < me.minNotZero)) {
12871 me.minNotZero = value;
12872 }
12873 });
12874 }
12875 });
12876 }
12877
12878 // Common base implementation to handle ticks.min, ticks.max
12879 this.handleTickRangeOptions();
12880 },
12881 handleTickRangeOptions: function() {
12882 var me = this;
12883 var opts = me.options;
12884 var tickOpts = opts.ticks;
12885 var valueOrDefault = helpers.valueOrDefault;
12886 var DEFAULT_MIN = 1;
12887 var DEFAULT_MAX = 10;
12888
12889 me.min = valueOrDefault(tickOpts.min, me.min);
12890 me.max = valueOrDefault(tickOpts.max, me.max);
12891
12892 if (me.min === me.max) {
12893 if (me.min !== 0 && me.min !== null) {
12894 me.min = Math.pow(10, Math.floor(helpers.log10(me.min)) - 1);
12895 me.max = Math.pow(10, Math.floor(helpers.log10(me.max)) + 1);
12896 } else {
12897 me.min = DEFAULT_MIN;
12898 me.max = DEFAULT_MAX;
12899 }
12900 }
12901 if (me.min === null) {
12902 me.min = Math.pow(10, Math.floor(helpers.log10(me.max)) - 1);
12903 }
12904 if (me.max === null) {
12905 me.max = me.min !== 0
12906 ? Math.pow(10, Math.floor(helpers.log10(me.min)) + 1)
12907 : DEFAULT_MAX;
12908 }
12909 if (me.minNotZero === null) {
12910 if (me.min > 0) {
12911 me.minNotZero = me.min;
12912 } else if (me.max < 1) {
12913 me.minNotZero = Math.pow(10, Math.floor(helpers.log10(me.max)));
12914 } else {
12915 me.minNotZero = DEFAULT_MIN;
12916 }
12917 }
12918 },
12919 buildTicks: function() {
12920 var me = this;
12921 var opts = me.options;
12922 var tickOpts = opts.ticks;
12923 var reverse = !me.isHorizontal();
12924
12925 var generationOptions = {
12926 min: tickOpts.min,
12927 max: tickOpts.max
12928 };
12929 var ticks = me.ticks = generateTicks(generationOptions, me);
12930
12931 // At this point, we need to update our max and min given the tick values since we have expanded the
12932 // range of the scale
12933 me.max = helpers.max(ticks);
12934 me.min = helpers.min(ticks);
12935
12936 if (tickOpts.reverse) {
12937 reverse = !reverse;
12938 me.start = me.max;
12939 me.end = me.min;
12940 } else {
12941 me.start = me.min;
12942 me.end = me.max;
12943 }
12944 if (reverse) {
12945 ticks.reverse();
12946 }
12947 },
12948 convertTicksToLabels: function() {
12949 this.tickValues = this.ticks.slice();
12950
12951 Chart.Scale.prototype.convertTicksToLabels.call(this);
12952 },
12953 // Get the correct tooltip label
12954 getLabelForIndex: function(index, datasetIndex) {
12955 return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
12956 },
12957 getPixelForTick: function(index) {
12958 return this.getPixelForValue(this.tickValues[index]);
12959 },
12960 /**
12961 * Returns the value of the first tick.
12962 * @param {Number} value - The minimum not zero value.
12963 * @return {Number} The first tick value.
12964 * @private
12965 */
12966 _getFirstTickValue: function(value) {
12967 var exp = Math.floor(helpers.log10(value));
12968 var significand = Math.floor(value / Math.pow(10, exp));
12969
12970 return significand * Math.pow(10, exp);
12971 },
12972 getPixelForValue: function(value) {
12973 var me = this;
12974 var reverse = me.options.ticks.reverse;
12975 var log10 = helpers.log10;
12976 var firstTickValue = me._getFirstTickValue(me.minNotZero);
12977 var offset = 0;
12978 var innerDimension, pixel, start, end, sign;
12979
12980 value = +me.getRightValue(value);
12981 if (reverse) {
12982 start = me.end;
12983 end = me.start;
12984 sign = -1;
12985 } else {
12986 start = me.start;
12987 end = me.end;
12988 sign = 1;
12989 }
12990 if (me.isHorizontal()) {
12991 innerDimension = me.width;
12992 pixel = reverse ? me.right : me.left;
12993 } else {
12994 innerDimension = me.height;
12995 sign *= -1; // invert, since the upper-left corner of the canvas is at pixel (0, 0)
12996 pixel = reverse ? me.top : me.bottom;
12997 }
12998 if (value !== start) {
12999 if (start === 0) { // include zero tick
13000 offset = helpers.getValueOrDefault(
13001 me.options.ticks.fontSize,
13002 Chart.defaults.global.defaultFontSize
13003 );
13004 innerDimension -= offset;
13005 start = firstTickValue;
13006 }
13007 if (value !== 0) {
13008 offset += innerDimension / (log10(end) - log10(start)) * (log10(value) - log10(start));
13009 }
13010 pixel += sign * offset;
13011 }
13012 return pixel;
13013 },
13014 getValueForPixel: function(pixel) {
13015 var me = this;
13016 var reverse = me.options.ticks.reverse;
13017 var log10 = helpers.log10;
13018 var firstTickValue = me._getFirstTickValue(me.minNotZero);
13019 var innerDimension, start, end, value;
13020
13021 if (reverse) {
13022 start = me.end;
13023 end = me.start;
13024 } else {
13025 start = me.start;
13026 end = me.end;
13027 }
13028 if (me.isHorizontal()) {
13029 innerDimension = me.width;
13030 value = reverse ? me.right - pixel : pixel - me.left;
13031 } else {
13032 innerDimension = me.height;
13033 value = reverse ? pixel - me.top : me.bottom - pixel;
13034 }
13035 if (value !== start) {
13036 if (start === 0) { // include zero tick
13037 var offset = helpers.getValueOrDefault(
13038 me.options.ticks.fontSize,
13039 Chart.defaults.global.defaultFontSize
13040 );
13041 value -= offset;
13042 innerDimension -= offset;
13043 start = firstTickValue;
13044 }
13045 value *= log10(end) - log10(start);
13046 value /= innerDimension;
13047 value = Math.pow(10, log10(start) + value);
13048 }
13049 return value;
13050 }
13051 });
13052 Chart.scaleService.registerScaleType('logarithmic', LogarithmicScale, defaultConfig);
13053
13054};
13055
13056},{"34":34,"45":45}],57:[function(require,module,exports){
13057'use strict';
13058
13059var defaults = require(25);
13060var helpers = require(45);
13061var Ticks = require(34);
13062
13063module.exports = function(Chart) {
13064
13065 var globalDefaults = defaults.global;
13066
13067 var defaultConfig = {
13068 display: true,
13069
13070 // Boolean - Whether to animate scaling the chart from the centre
13071 animate: true,
13072 position: 'chartArea',
13073
13074 angleLines: {
13075 display: true,
13076 color: 'rgba(0, 0, 0, 0.1)',
13077 lineWidth: 1
13078 },
13079
13080 gridLines: {
13081 circular: false
13082 },
13083
13084 // label settings
13085 ticks: {
13086 // Boolean - Show a backdrop to the scale label
13087 showLabelBackdrop: true,
13088
13089 // String - The colour of the label backdrop
13090 backdropColor: 'rgba(255,255,255,0.75)',
13091
13092 // Number - The backdrop padding above & below the label in pixels
13093 backdropPaddingY: 2,
13094
13095 // Number - The backdrop padding to the side of the label in pixels
13096 backdropPaddingX: 2,
13097
13098 callback: Ticks.formatters.linear
13099 },
13100
13101 pointLabels: {
13102 // Boolean - if true, show point labels
13103 display: true,
13104
13105 // Number - Point label font size in pixels
13106 fontSize: 10,
13107
13108 // Function - Used to convert point labels
13109 callback: function(label) {
13110 return label;
13111 }
13112 }
13113 };
13114
13115 function getValueCount(scale) {
13116 var opts = scale.options;
13117 return opts.angleLines.display || opts.pointLabels.display ? scale.chart.data.labels.length : 0;
13118 }
13119
13120 function getPointLabelFontOptions(scale) {
13121 var pointLabelOptions = scale.options.pointLabels;
13122 var fontSize = helpers.valueOrDefault(pointLabelOptions.fontSize, globalDefaults.defaultFontSize);
13123 var fontStyle = helpers.valueOrDefault(pointLabelOptions.fontStyle, globalDefaults.defaultFontStyle);
13124 var fontFamily = helpers.valueOrDefault(pointLabelOptions.fontFamily, globalDefaults.defaultFontFamily);
13125 var font = helpers.fontString(fontSize, fontStyle, fontFamily);
13126
13127 return {
13128 size: fontSize,
13129 style: fontStyle,
13130 family: fontFamily,
13131 font: font
13132 };
13133 }
13134
13135 function measureLabelSize(ctx, fontSize, label) {
13136 if (helpers.isArray(label)) {
13137 return {
13138 w: helpers.longestText(ctx, ctx.font, label),
13139 h: (label.length * fontSize) + ((label.length - 1) * 1.5 * fontSize)
13140 };
13141 }
13142
13143 return {
13144 w: ctx.measureText(label).width,
13145 h: fontSize
13146 };
13147 }
13148
13149 function determineLimits(angle, pos, size, min, max) {
13150 if (angle === min || angle === max) {
13151 return {
13152 start: pos - (size / 2),
13153 end: pos + (size / 2)
13154 };
13155 } else if (angle < min || angle > max) {
13156 return {
13157 start: pos - size - 5,
13158 end: pos
13159 };
13160 }
13161
13162 return {
13163 start: pos,
13164 end: pos + size + 5
13165 };
13166 }
13167
13168 /**
13169 * Helper function to fit a radial linear scale with point labels
13170 */
13171 function fitWithPointLabels(scale) {
13172 /*
13173 * Right, this is really confusing and there is a lot of maths going on here
13174 * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
13175 *
13176 * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
13177 *
13178 * Solution:
13179 *
13180 * We assume the radius of the polygon is half the size of the canvas at first
13181 * at each index we check if the text overlaps.
13182 *
13183 * Where it does, we store that angle and that index.
13184 *
13185 * After finding the largest index and angle we calculate how much we need to remove
13186 * from the shape radius to move the point inwards by that x.
13187 *
13188 * We average the left and right distances to get the maximum shape radius that can fit in the box
13189 * along with labels.
13190 *
13191 * Once we have that, we can find the centre point for the chart, by taking the x text protrusion
13192 * on each side, removing that from the size, halving it and adding the left x protrusion width.
13193 *
13194 * This will mean we have a shape fitted to the canvas, as large as it can be with the labels
13195 * and position it in the most space efficient manner
13196 *
13197 * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
13198 */
13199
13200 var plFont = getPointLabelFontOptions(scale);
13201
13202 // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
13203 // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
13204 var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2);
13205 var furthestLimits = {
13206 r: scale.width,
13207 l: 0,
13208 t: scale.height,
13209 b: 0
13210 };
13211 var furthestAngles = {};
13212 var i, textSize, pointPosition;
13213
13214 scale.ctx.font = plFont.font;
13215 scale._pointLabelSizes = [];
13216
13217 var valueCount = getValueCount(scale);
13218 for (i = 0; i < valueCount; i++) {
13219 pointPosition = scale.getPointPosition(i, largestPossibleRadius);
13220 textSize = measureLabelSize(scale.ctx, plFont.size, scale.pointLabels[i] || '');
13221 scale._pointLabelSizes[i] = textSize;
13222
13223 // Add quarter circle to make degree 0 mean top of circle
13224 var angleRadians = scale.getIndexAngle(i);
13225 var angle = helpers.toDegrees(angleRadians) % 360;
13226 var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
13227 var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
13228
13229 if (hLimits.start < furthestLimits.l) {
13230 furthestLimits.l = hLimits.start;
13231 furthestAngles.l = angleRadians;
13232 }
13233
13234 if (hLimits.end > furthestLimits.r) {
13235 furthestLimits.r = hLimits.end;
13236 furthestAngles.r = angleRadians;
13237 }
13238
13239 if (vLimits.start < furthestLimits.t) {
13240 furthestLimits.t = vLimits.start;
13241 furthestAngles.t = angleRadians;
13242 }
13243
13244 if (vLimits.end > furthestLimits.b) {
13245 furthestLimits.b = vLimits.end;
13246 furthestAngles.b = angleRadians;
13247 }
13248 }
13249
13250 scale.setReductions(largestPossibleRadius, furthestLimits, furthestAngles);
13251 }
13252
13253 /**
13254 * Helper function to fit a radial linear scale with no point labels
13255 */
13256 function fit(scale) {
13257 var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2);
13258 scale.drawingArea = Math.round(largestPossibleRadius);
13259 scale.setCenterPoint(0, 0, 0, 0);
13260 }
13261
13262 function getTextAlignForAngle(angle) {
13263 if (angle === 0 || angle === 180) {
13264 return 'center';
13265 } else if (angle < 180) {
13266 return 'left';
13267 }
13268
13269 return 'right';
13270 }
13271
13272 function fillText(ctx, text, position, fontSize) {
13273 if (helpers.isArray(text)) {
13274 var y = position.y;
13275 var spacing = 1.5 * fontSize;
13276
13277 for (var i = 0; i < text.length; ++i) {
13278 ctx.fillText(text[i], position.x, y);
13279 y += spacing;
13280 }
13281 } else {
13282 ctx.fillText(text, position.x, position.y);
13283 }
13284 }
13285
13286 function adjustPointPositionForLabelHeight(angle, textSize, position) {
13287 if (angle === 90 || angle === 270) {
13288 position.y -= (textSize.h / 2);
13289 } else if (angle > 270 || angle < 90) {
13290 position.y -= textSize.h;
13291 }
13292 }
13293
13294 function drawPointLabels(scale) {
13295 var ctx = scale.ctx;
13296 var valueOrDefault = helpers.valueOrDefault;
13297 var opts = scale.options;
13298 var angleLineOpts = opts.angleLines;
13299 var pointLabelOpts = opts.pointLabels;
13300
13301 ctx.lineWidth = angleLineOpts.lineWidth;
13302 ctx.strokeStyle = angleLineOpts.color;
13303
13304 var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
13305
13306 // Point Label Font
13307 var plFont = getPointLabelFontOptions(scale);
13308
13309 ctx.textBaseline = 'top';
13310
13311 for (var i = getValueCount(scale) - 1; i >= 0; i--) {
13312 if (angleLineOpts.display) {
13313 var outerPosition = scale.getPointPosition(i, outerDistance);
13314 ctx.beginPath();
13315 ctx.moveTo(scale.xCenter, scale.yCenter);
13316 ctx.lineTo(outerPosition.x, outerPosition.y);
13317 ctx.stroke();
13318 ctx.closePath();
13319 }
13320
13321 if (pointLabelOpts.display) {
13322 // Extra 3px out for some label spacing
13323 var pointLabelPosition = scale.getPointPosition(i, outerDistance + 5);
13324
13325 // Keep this in loop since we may support array properties here
13326 var pointLabelFontColor = valueOrDefault(pointLabelOpts.fontColor, globalDefaults.defaultFontColor);
13327 ctx.font = plFont.font;
13328 ctx.fillStyle = pointLabelFontColor;
13329
13330 var angleRadians = scale.getIndexAngle(i);
13331 var angle = helpers.toDegrees(angleRadians);
13332 ctx.textAlign = getTextAlignForAngle(angle);
13333 adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
13334 fillText(ctx, scale.pointLabels[i] || '', pointLabelPosition, plFont.size);
13335 }
13336 }
13337 }
13338
13339 function drawRadiusLine(scale, gridLineOpts, radius, index) {
13340 var ctx = scale.ctx;
13341 ctx.strokeStyle = helpers.valueAtIndexOrDefault(gridLineOpts.color, index - 1);
13342 ctx.lineWidth = helpers.valueAtIndexOrDefault(gridLineOpts.lineWidth, index - 1);
13343
13344 if (scale.options.gridLines.circular) {
13345 // Draw circular arcs between the points
13346 ctx.beginPath();
13347 ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
13348 ctx.closePath();
13349 ctx.stroke();
13350 } else {
13351 // Draw straight lines connecting each index
13352 var valueCount = getValueCount(scale);
13353
13354 if (valueCount === 0) {
13355 return;
13356 }
13357
13358 ctx.beginPath();
13359 var pointPosition = scale.getPointPosition(0, radius);
13360 ctx.moveTo(pointPosition.x, pointPosition.y);
13361
13362 for (var i = 1; i < valueCount; i++) {
13363 pointPosition = scale.getPointPosition(i, radius);
13364 ctx.lineTo(pointPosition.x, pointPosition.y);
13365 }
13366
13367 ctx.closePath();
13368 ctx.stroke();
13369 }
13370 }
13371
13372 function numberOrZero(param) {
13373 return helpers.isNumber(param) ? param : 0;
13374 }
13375
13376 var LinearRadialScale = Chart.LinearScaleBase.extend({
13377 setDimensions: function() {
13378 var me = this;
13379 var opts = me.options;
13380 var tickOpts = opts.ticks;
13381 // Set the unconstrained dimension before label rotation
13382 me.width = me.maxWidth;
13383 me.height = me.maxHeight;
13384 me.xCenter = Math.round(me.width / 2);
13385 me.yCenter = Math.round(me.height / 2);
13386
13387 var minSize = helpers.min([me.height, me.width]);
13388 var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
13389 me.drawingArea = opts.display ? (minSize / 2) - (tickFontSize / 2 + tickOpts.backdropPaddingY) : (minSize / 2);
13390 },
13391 determineDataLimits: function() {
13392 var me = this;
13393 var chart = me.chart;
13394 var min = Number.POSITIVE_INFINITY;
13395 var max = Number.NEGATIVE_INFINITY;
13396
13397 helpers.each(chart.data.datasets, function(dataset, datasetIndex) {
13398 if (chart.isDatasetVisible(datasetIndex)) {
13399 var meta = chart.getDatasetMeta(datasetIndex);
13400
13401 helpers.each(dataset.data, function(rawValue, index) {
13402 var value = +me.getRightValue(rawValue);
13403 if (isNaN(value) || meta.data[index].hidden) {
13404 return;
13405 }
13406
13407 min = Math.min(value, min);
13408 max = Math.max(value, max);
13409 });
13410 }
13411 });
13412
13413 me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
13414 me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
13415
13416 // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
13417 me.handleTickRangeOptions();
13418 },
13419 getTickLimit: function() {
13420 var tickOpts = this.options.ticks;
13421 var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
13422 return Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(this.drawingArea / (1.5 * tickFontSize)));
13423 },
13424 convertTicksToLabels: function() {
13425 var me = this;
13426
13427 Chart.LinearScaleBase.prototype.convertTicksToLabels.call(me);
13428
13429 // Point labels
13430 me.pointLabels = me.chart.data.labels.map(me.options.pointLabels.callback, me);
13431 },
13432 getLabelForIndex: function(index, datasetIndex) {
13433 return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
13434 },
13435 fit: function() {
13436 if (this.options.pointLabels.display) {
13437 fitWithPointLabels(this);
13438 } else {
13439 fit(this);
13440 }
13441 },
13442 /**
13443 * Set radius reductions and determine new radius and center point
13444 * @private
13445 */
13446 setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
13447 var me = this;
13448 var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
13449 var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
13450 var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
13451 var radiusReductionBottom = -Math.max(furthestLimits.b - me.height, 0) / Math.cos(furthestAngles.b);
13452
13453 radiusReductionLeft = numberOrZero(radiusReductionLeft);
13454 radiusReductionRight = numberOrZero(radiusReductionRight);
13455 radiusReductionTop = numberOrZero(radiusReductionTop);
13456 radiusReductionBottom = numberOrZero(radiusReductionBottom);
13457
13458 me.drawingArea = Math.min(
13459 Math.round(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
13460 Math.round(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
13461 me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
13462 },
13463 setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
13464 var me = this;
13465 var maxRight = me.width - rightMovement - me.drawingArea;
13466 var maxLeft = leftMovement + me.drawingArea;
13467 var maxTop = topMovement + me.drawingArea;
13468 var maxBottom = me.height - bottomMovement - me.drawingArea;
13469
13470 me.xCenter = Math.round(((maxLeft + maxRight) / 2) + me.left);
13471 me.yCenter = Math.round(((maxTop + maxBottom) / 2) + me.top);
13472 },
13473
13474 getIndexAngle: function(index) {
13475 var angleMultiplier = (Math.PI * 2) / getValueCount(this);
13476 var startAngle = this.chart.options && this.chart.options.startAngle ?
13477 this.chart.options.startAngle :
13478 0;
13479
13480 var startAngleRadians = startAngle * Math.PI * 2 / 360;
13481
13482 // Start from the top instead of right, so remove a quarter of the circle
13483 return index * angleMultiplier + startAngleRadians;
13484 },
13485 getDistanceFromCenterForValue: function(value) {
13486 var me = this;
13487
13488 if (value === null) {
13489 return 0; // null always in center
13490 }
13491
13492 // Take into account half font size + the yPadding of the top value
13493 var scalingFactor = me.drawingArea / (me.max - me.min);
13494 if (me.options.ticks.reverse) {
13495 return (me.max - value) * scalingFactor;
13496 }
13497 return (value - me.min) * scalingFactor;
13498 },
13499 getPointPosition: function(index, distanceFromCenter) {
13500 var me = this;
13501 var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
13502 return {
13503 x: Math.round(Math.cos(thisAngle) * distanceFromCenter) + me.xCenter,
13504 y: Math.round(Math.sin(thisAngle) * distanceFromCenter) + me.yCenter
13505 };
13506 },
13507 getPointPositionForValue: function(index, value) {
13508 return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
13509 },
13510
13511 getBasePosition: function() {
13512 var me = this;
13513 var min = me.min;
13514 var max = me.max;
13515
13516 return me.getPointPositionForValue(0,
13517 me.beginAtZero ? 0 :
13518 min < 0 && max < 0 ? max :
13519 min > 0 && max > 0 ? min :
13520 0);
13521 },
13522
13523 draw: function() {
13524 var me = this;
13525 var opts = me.options;
13526 var gridLineOpts = opts.gridLines;
13527 var tickOpts = opts.ticks;
13528 var valueOrDefault = helpers.valueOrDefault;
13529
13530 if (opts.display) {
13531 var ctx = me.ctx;
13532 var startAngle = this.getIndexAngle(0);
13533
13534 // Tick Font
13535 var tickFontSize = valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
13536 var tickFontStyle = valueOrDefault(tickOpts.fontStyle, globalDefaults.defaultFontStyle);
13537 var tickFontFamily = valueOrDefault(tickOpts.fontFamily, globalDefaults.defaultFontFamily);
13538 var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
13539
13540 helpers.each(me.ticks, function(label, index) {
13541 // Don't draw a centre value (if it is minimum)
13542 if (index > 0 || tickOpts.reverse) {
13543 var yCenterOffset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
13544
13545 // Draw circular lines around the scale
13546 if (gridLineOpts.display && index !== 0) {
13547 drawRadiusLine(me, gridLineOpts, yCenterOffset, index);
13548 }
13549
13550 if (tickOpts.display) {
13551 var tickFontColor = valueOrDefault(tickOpts.fontColor, globalDefaults.defaultFontColor);
13552 ctx.font = tickLabelFont;
13553
13554 ctx.save();
13555 ctx.translate(me.xCenter, me.yCenter);
13556 ctx.rotate(startAngle);
13557
13558 if (tickOpts.showLabelBackdrop) {
13559 var labelWidth = ctx.measureText(label).width;
13560 ctx.fillStyle = tickOpts.backdropColor;
13561 ctx.fillRect(
13562 -labelWidth / 2 - tickOpts.backdropPaddingX,
13563 -yCenterOffset - tickFontSize / 2 - tickOpts.backdropPaddingY,
13564 labelWidth + tickOpts.backdropPaddingX * 2,
13565 tickFontSize + tickOpts.backdropPaddingY * 2
13566 );
13567 }
13568
13569 ctx.textAlign = 'center';
13570 ctx.textBaseline = 'middle';
13571 ctx.fillStyle = tickFontColor;
13572 ctx.fillText(label, 0, -yCenterOffset);
13573 ctx.restore();
13574 }
13575 }
13576 });
13577
13578 if (opts.angleLines.display || opts.pointLabels.display) {
13579 drawPointLabels(me);
13580 }
13581 }
13582 }
13583 });
13584 Chart.scaleService.registerScaleType('radialLinear', LinearRadialScale, defaultConfig);
13585
13586};
13587
13588},{"25":25,"34":34,"45":45}],58:[function(require,module,exports){
13589/* global window: false */
13590'use strict';
13591
13592var moment = require(1);
13593moment = typeof moment === 'function' ? moment : window.moment;
13594
13595var defaults = require(25);
13596var helpers = require(45);
13597
13598// Integer constants are from the ES6 spec.
13599var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
13600var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
13601
13602var INTERVALS = {
13603 millisecond: {
13604 common: true,
13605 size: 1,
13606 steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]
13607 },
13608 second: {
13609 common: true,
13610 size: 1000,
13611 steps: [1, 2, 5, 10, 30]
13612 },
13613 minute: {
13614 common: true,
13615 size: 60000,
13616 steps: [1, 2, 5, 10, 30]
13617 },
13618 hour: {
13619 common: true,
13620 size: 3600000,
13621 steps: [1, 2, 3, 6, 12]
13622 },
13623 day: {
13624 common: true,
13625 size: 86400000,
13626 steps: [1, 2, 5]
13627 },
13628 week: {
13629 common: false,
13630 size: 604800000,
13631 steps: [1, 2, 3, 4]
13632 },
13633 month: {
13634 common: true,
13635 size: 2.628e9,
13636 steps: [1, 2, 3]
13637 },
13638 quarter: {
13639 common: false,
13640 size: 7.884e9,
13641 steps: [1, 2, 3, 4]
13642 },
13643 year: {
13644 common: true,
13645 size: 3.154e10
13646 }
13647};
13648
13649var UNITS = Object.keys(INTERVALS);
13650
13651function sorter(a, b) {
13652 return a - b;
13653}
13654
13655function arrayUnique(items) {
13656 var hash = {};
13657 var out = [];
13658 var i, ilen, item;
13659
13660 for (i = 0, ilen = items.length; i < ilen; ++i) {
13661 item = items[i];
13662 if (!hash[item]) {
13663 hash[item] = true;
13664 out.push(item);
13665 }
13666 }
13667
13668 return out;
13669}
13670
13671/**
13672 * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
13673 * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
13674 * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
13675 * extremity (left + width or top + height). Note that it would be more optimized to directly
13676 * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
13677 * to create the lookup table. The table ALWAYS contains at least two items: min and max.
13678 *
13679 * @param {Number[]} timestamps - timestamps sorted from lowest to highest.
13680 * @param {String} distribution - If 'linear', timestamps will be spread linearly along the min
13681 * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
13682 * If 'series', timestamps will be positioned at the same distance from each other. In this
13683 * case, only timestamps that break the time linearity are registered, meaning that in the
13684 * best case, all timestamps are linear, the table contains only min and max.
13685 */
13686function buildLookupTable(timestamps, min, max, distribution) {
13687 if (distribution === 'linear' || !timestamps.length) {
13688 return [
13689 {time: min, pos: 0},
13690 {time: max, pos: 1}
13691 ];
13692 }
13693
13694 var table = [];
13695 var items = [min];
13696 var i, ilen, prev, curr, next;
13697
13698 for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
13699 curr = timestamps[i];
13700 if (curr > min && curr < max) {
13701 items.push(curr);
13702 }
13703 }
13704
13705 items.push(max);
13706
13707 for (i = 0, ilen = items.length; i < ilen; ++i) {
13708 next = items[i + 1];
13709 prev = items[i - 1];
13710 curr = items[i];
13711
13712 // only add points that breaks the scale linearity
13713 if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
13714 table.push({time: curr, pos: i / (ilen - 1)});
13715 }
13716 }
13717
13718 return table;
13719}
13720
13721// @see adapted from http://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
13722function lookup(table, key, value) {
13723 var lo = 0;
13724 var hi = table.length - 1;
13725 var mid, i0, i1;
13726
13727 while (lo >= 0 && lo <= hi) {
13728 mid = (lo + hi) >> 1;
13729 i0 = table[mid - 1] || null;
13730 i1 = table[mid];
13731
13732 if (!i0) {
13733 // given value is outside table (before first item)
13734 return {lo: null, hi: i1};
13735 } else if (i1[key] < value) {
13736 lo = mid + 1;
13737 } else if (i0[key] > value) {
13738 hi = mid - 1;
13739 } else {
13740 return {lo: i0, hi: i1};
13741 }
13742 }
13743
13744 // given value is outside table (after last item)
13745 return {lo: i1, hi: null};
13746}
13747
13748/**
13749 * Linearly interpolates the given source `value` using the table items `skey` values and
13750 * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
13751 * returns the position for a timestamp equal to 42. If value is out of bounds, values at
13752 * index [0, 1] or [n - 1, n] are used for the interpolation.
13753 */
13754function interpolate(table, skey, sval, tkey) {
13755 var range = lookup(table, skey, sval);
13756
13757 // Note: the lookup table ALWAYS contains at least 2 items (min and max)
13758 var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
13759 var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
13760
13761 var span = next[skey] - prev[skey];
13762 var ratio = span ? (sval - prev[skey]) / span : 0;
13763 var offset = (next[tkey] - prev[tkey]) * ratio;
13764
13765 return prev[tkey] + offset;
13766}
13767
13768/**
13769 * Convert the given value to a moment object using the given time options.
13770 * @see http://momentjs.com/docs/#/parsing/
13771 */
13772function momentify(value, options) {
13773 var parser = options.parser;
13774 var format = options.parser || options.format;
13775
13776 if (typeof parser === 'function') {
13777 return parser(value);
13778 }
13779
13780 if (typeof value === 'string' && typeof format === 'string') {
13781 return moment(value, format);
13782 }
13783
13784 if (!(value instanceof moment)) {
13785 value = moment(value);
13786 }
13787
13788 if (value.isValid()) {
13789 return value;
13790 }
13791
13792 // Labels are in an incompatible moment format and no `parser` has been provided.
13793 // The user might still use the deprecated `format` option to convert his inputs.
13794 if (typeof format === 'function') {
13795 return format(value);
13796 }
13797
13798 return value;
13799}
13800
13801function parse(input, scale) {
13802 if (helpers.isNullOrUndef(input)) {
13803 return null;
13804 }
13805
13806 var options = scale.options.time;
13807 var value = momentify(scale.getRightValue(input), options);
13808 if (!value.isValid()) {
13809 return null;
13810 }
13811
13812 if (options.round) {
13813 value.startOf(options.round);
13814 }
13815
13816 return value.valueOf();
13817}
13818
13819/**
13820 * Returns the number of unit to skip to be able to display up to `capacity` number of ticks
13821 * in `unit` for the given `min` / `max` range and respecting the interval steps constraints.
13822 */
13823function determineStepSize(min, max, unit, capacity) {
13824 var range = max - min;
13825 var interval = INTERVALS[unit];
13826 var milliseconds = interval.size;
13827 var steps = interval.steps;
13828 var i, ilen, factor;
13829
13830 if (!steps) {
13831 return Math.ceil(range / (capacity * milliseconds));
13832 }
13833
13834 for (i = 0, ilen = steps.length; i < ilen; ++i) {
13835 factor = steps[i];
13836 if (Math.ceil(range / (milliseconds * factor)) <= capacity) {
13837 break;
13838 }
13839 }
13840
13841 return factor;
13842}
13843
13844/**
13845 * Figures out what unit results in an appropriate number of auto-generated ticks
13846 */
13847function determineUnitForAutoTicks(minUnit, min, max, capacity) {
13848 var ilen = UNITS.length;
13849 var i, interval, factor;
13850
13851 for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
13852 interval = INTERVALS[UNITS[i]];
13853 factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER;
13854
13855 if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
13856 return UNITS[i];
13857 }
13858 }
13859
13860 return UNITS[ilen - 1];
13861}
13862
13863/**
13864 * Figures out what unit to format a set of ticks with
13865 */
13866function determineUnitForFormatting(ticks, minUnit, min, max) {
13867 var duration = moment.duration(moment(max).diff(moment(min)));
13868 var ilen = UNITS.length;
13869 var i, unit;
13870
13871 for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) {
13872 unit = UNITS[i];
13873 if (INTERVALS[unit].common && duration.as(unit) >= ticks.length) {
13874 return unit;
13875 }
13876 }
13877
13878 return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
13879}
13880
13881function determineMajorUnit(unit) {
13882 for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
13883 if (INTERVALS[UNITS[i]].common) {
13884 return UNITS[i];
13885 }
13886 }
13887}
13888
13889/**
13890 * Generates a maximum of `capacity` timestamps between min and max, rounded to the
13891 * `minor` unit, aligned on the `major` unit and using the given scale time `options`.
13892 * Important: this method can return ticks outside the min and max range, it's the
13893 * responsibility of the calling code to clamp values if needed.
13894 */
13895function generate(min, max, capacity, options) {
13896 var timeOpts = options.time;
13897 var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
13898 var major = determineMajorUnit(minor);
13899 var stepSize = helpers.valueOrDefault(timeOpts.stepSize, timeOpts.unitStepSize);
13900 var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
13901 var majorTicksEnabled = options.ticks.major.enabled;
13902 var interval = INTERVALS[minor];
13903 var first = moment(min);
13904 var last = moment(max);
13905 var ticks = [];
13906 var time;
13907
13908 if (!stepSize) {
13909 stepSize = determineStepSize(min, max, minor, capacity);
13910 }
13911
13912 // For 'week' unit, handle the first day of week option
13913 if (weekday) {
13914 first = first.isoWeekday(weekday);
13915 last = last.isoWeekday(weekday);
13916 }
13917
13918 // Align first/last ticks on unit
13919 first = first.startOf(weekday ? 'day' : minor);
13920 last = last.startOf(weekday ? 'day' : minor);
13921
13922 // Make sure that the last tick include max
13923 if (last < max) {
13924 last.add(1, minor);
13925 }
13926
13927 time = moment(first);
13928
13929 if (majorTicksEnabled && major && !weekday && !timeOpts.round) {
13930 // Align the first tick on the previous `minor` unit aligned on the `major` unit:
13931 // we first aligned time on the previous `major` unit then add the number of full
13932 // stepSize there is between first and the previous major time.
13933 time.startOf(major);
13934 time.add(~~((first - time) / (interval.size * stepSize)) * stepSize, minor);
13935 }
13936
13937 for (; time < last; time.add(stepSize, minor)) {
13938 ticks.push(+time);
13939 }
13940
13941 ticks.push(+time);
13942
13943 return ticks;
13944}
13945
13946/**
13947 * Returns the right and left offsets from edges in the form of {left, right}.
13948 * Offsets are added when the `offset` option is true.
13949 */
13950function computeOffsets(table, ticks, min, max, options) {
13951 var left = 0;
13952 var right = 0;
13953 var upper, lower;
13954
13955 if (options.offset && ticks.length) {
13956 if (!options.time.min) {
13957 upper = ticks.length > 1 ? ticks[1] : max;
13958 lower = ticks[0];
13959 left = (
13960 interpolate(table, 'time', upper, 'pos') -
13961 interpolate(table, 'time', lower, 'pos')
13962 ) / 2;
13963 }
13964 if (!options.time.max) {
13965 upper = ticks[ticks.length - 1];
13966 lower = ticks.length > 1 ? ticks[ticks.length - 2] : min;
13967 right = (
13968 interpolate(table, 'time', upper, 'pos') -
13969 interpolate(table, 'time', lower, 'pos')
13970 ) / 2;
13971 }
13972 }
13973
13974 return {left: left, right: right};
13975}
13976
13977function ticksFromTimestamps(values, majorUnit) {
13978 var ticks = [];
13979 var i, ilen, value, major;
13980
13981 for (i = 0, ilen = values.length; i < ilen; ++i) {
13982 value = values[i];
13983 major = majorUnit ? value === +moment(value).startOf(majorUnit) : false;
13984
13985 ticks.push({
13986 value: value,
13987 major: major
13988 });
13989 }
13990
13991 return ticks;
13992}
13993
13994function determineLabelFormat(data, timeOpts) {
13995 var i, momentDate, hasTime;
13996 var ilen = data.length;
13997
13998 // find the label with the most parts (milliseconds, minutes, etc.)
13999 // format all labels with the same level of detail as the most specific label
14000 for (i = 0; i < ilen; i++) {
14001 momentDate = momentify(data[i], timeOpts);
14002 if (momentDate.millisecond() !== 0) {
14003 return 'MMM D, YYYY h:mm:ss.SSS a';
14004 }
14005 if (momentDate.second() !== 0 || momentDate.minute() !== 0 || momentDate.hour() !== 0) {
14006 hasTime = true;
14007 }
14008 }
14009 if (hasTime) {
14010 return 'MMM D, YYYY h:mm:ss a';
14011 }
14012 return 'MMM D, YYYY';
14013}
14014
14015module.exports = function(Chart) {
14016
14017 var defaultConfig = {
14018 position: 'bottom',
14019
14020 /**
14021 * Data distribution along the scale:
14022 * - 'linear': data are spread according to their time (distances can vary),
14023 * - 'series': data are spread at the same distance from each other.
14024 * @see https://github.com/chartjs/Chart.js/pull/4507
14025 * @since 2.7.0
14026 */
14027 distribution: 'linear',
14028
14029 /**
14030 * Scale boundary strategy (bypassed by min/max time options)
14031 * - `data`: make sure data are fully visible, ticks outside are removed
14032 * - `ticks`: make sure ticks are fully visible, data outside are truncated
14033 * @see https://github.com/chartjs/Chart.js/pull/4556
14034 * @since 2.7.0
14035 */
14036 bounds: 'data',
14037
14038 time: {
14039 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
14040 format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from http://momentjs.com/docs/#/parsing/string-format/
14041 unit: false, // false == automatic or override with week, month, year, etc.
14042 round: false, // none, or override with week, month, year, etc.
14043 displayFormat: false, // DEPRECATED
14044 isoWeekday: false, // override week start day - see http://momentjs.com/docs/#/get-set/iso-weekday/
14045 minUnit: 'millisecond',
14046
14047 // defaults to unit's corresponding unitFormat below or override using pattern string from http://momentjs.com/docs/#/displaying/format/
14048 displayFormats: {
14049 millisecond: 'h:mm:ss.SSS a', // 11:20:01.123 AM,
14050 second: 'h:mm:ss a', // 11:20:01 AM
14051 minute: 'h:mm a', // 11:20 AM
14052 hour: 'hA', // 5PM
14053 day: 'MMM D', // Sep 4
14054 week: 'll', // Week 46, or maybe "[W]WW - YYYY" ?
14055 month: 'MMM YYYY', // Sept 2015
14056 quarter: '[Q]Q - YYYY', // Q3
14057 year: 'YYYY' // 2015
14058 },
14059 },
14060 ticks: {
14061 autoSkip: false,
14062
14063 /**
14064 * Ticks generation input values:
14065 * - 'auto': generates "optimal" ticks based on scale size and time options.
14066 * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
14067 * - 'labels': generates ticks from user given `data.labels` values ONLY.
14068 * @see https://github.com/chartjs/Chart.js/pull/4507
14069 * @since 2.7.0
14070 */
14071 source: 'auto',
14072
14073 major: {
14074 enabled: false
14075 }
14076 }
14077 };
14078
14079 var TimeScale = Chart.Scale.extend({
14080 initialize: function() {
14081 if (!moment) {
14082 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');
14083 }
14084
14085 this.mergeTicksOptions();
14086
14087 Chart.Scale.prototype.initialize.call(this);
14088 },
14089
14090 update: function() {
14091 var me = this;
14092 var options = me.options;
14093
14094 // DEPRECATIONS: output a message only one time per update
14095 if (options.time && options.time.format) {
14096 console.warn('options.time.format is deprecated and replaced by options.time.parser.');
14097 }
14098
14099 return Chart.Scale.prototype.update.apply(me, arguments);
14100 },
14101
14102 /**
14103 * Allows data to be referenced via 't' attribute
14104 */
14105 getRightValue: function(rawValue) {
14106 if (rawValue && rawValue.t !== undefined) {
14107 rawValue = rawValue.t;
14108 }
14109 return Chart.Scale.prototype.getRightValue.call(this, rawValue);
14110 },
14111
14112 determineDataLimits: function() {
14113 var me = this;
14114 var chart = me.chart;
14115 var timeOpts = me.options.time;
14116 var unit = timeOpts.unit || 'day';
14117 var min = MAX_INTEGER;
14118 var max = MIN_INTEGER;
14119 var timestamps = [];
14120 var datasets = [];
14121 var labels = [];
14122 var i, j, ilen, jlen, data, timestamp;
14123
14124 // Convert labels to timestamps
14125 for (i = 0, ilen = chart.data.labels.length; i < ilen; ++i) {
14126 labels.push(parse(chart.data.labels[i], me));
14127 }
14128
14129 // Convert data to timestamps
14130 for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
14131 if (chart.isDatasetVisible(i)) {
14132 data = chart.data.datasets[i].data;
14133
14134 // Let's consider that all data have the same format.
14135 if (helpers.isObject(data[0])) {
14136 datasets[i] = [];
14137
14138 for (j = 0, jlen = data.length; j < jlen; ++j) {
14139 timestamp = parse(data[j], me);
14140 timestamps.push(timestamp);
14141 datasets[i][j] = timestamp;
14142 }
14143 } else {
14144 timestamps.push.apply(timestamps, labels);
14145 datasets[i] = labels.slice(0);
14146 }
14147 } else {
14148 datasets[i] = [];
14149 }
14150 }
14151
14152 if (labels.length) {
14153 // Sort labels **after** data have been converted
14154 labels = arrayUnique(labels).sort(sorter);
14155 min = Math.min(min, labels[0]);
14156 max = Math.max(max, labels[labels.length - 1]);
14157 }
14158
14159 if (timestamps.length) {
14160 timestamps = arrayUnique(timestamps).sort(sorter);
14161 min = Math.min(min, timestamps[0]);
14162 max = Math.max(max, timestamps[timestamps.length - 1]);
14163 }
14164
14165 min = parse(timeOpts.min, me) || min;
14166 max = parse(timeOpts.max, me) || max;
14167
14168 // In case there is no valid min/max, set limits based on unit time option
14169 min = min === MAX_INTEGER ? +moment().startOf(unit) : min;
14170 max = max === MIN_INTEGER ? +moment().endOf(unit) + 1 : max;
14171
14172 // Make sure that max is strictly higher than min (required by the lookup table)
14173 me.min = Math.min(min, max);
14174 me.max = Math.max(min + 1, max);
14175
14176 // PRIVATE
14177 me._horizontal = me.isHorizontal();
14178 me._table = [];
14179 me._timestamps = {
14180 data: timestamps,
14181 datasets: datasets,
14182 labels: labels
14183 };
14184 },
14185
14186 buildTicks: function() {
14187 var me = this;
14188 var min = me.min;
14189 var max = me.max;
14190 var options = me.options;
14191 var timeOpts = options.time;
14192 var timestamps = [];
14193 var ticks = [];
14194 var i, ilen, timestamp;
14195
14196 switch (options.ticks.source) {
14197 case 'data':
14198 timestamps = me._timestamps.data;
14199 break;
14200 case 'labels':
14201 timestamps = me._timestamps.labels;
14202 break;
14203 case 'auto':
14204 default:
14205 timestamps = generate(min, max, me.getLabelCapacity(min), options);
14206 }
14207
14208 if (options.bounds === 'ticks' && timestamps.length) {
14209 min = timestamps[0];
14210 max = timestamps[timestamps.length - 1];
14211 }
14212
14213 // Enforce limits with user min/max options
14214 min = parse(timeOpts.min, me) || min;
14215 max = parse(timeOpts.max, me) || max;
14216
14217 // Remove ticks outside the min/max range
14218 for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
14219 timestamp = timestamps[i];
14220 if (timestamp >= min && timestamp <= max) {
14221 ticks.push(timestamp);
14222 }
14223 }
14224
14225 me.min = min;
14226 me.max = max;
14227
14228 // PRIVATE
14229 me._unit = timeOpts.unit || determineUnitForFormatting(ticks, timeOpts.minUnit, me.min, me.max);
14230 me._majorUnit = determineMajorUnit(me._unit);
14231 me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);
14232 me._offsets = computeOffsets(me._table, ticks, min, max, options);
14233 me._labelFormat = determineLabelFormat(me._timestamps.data, timeOpts);
14234
14235 return ticksFromTimestamps(ticks, me._majorUnit);
14236 },
14237
14238 getLabelForIndex: function(index, datasetIndex) {
14239 var me = this;
14240 var data = me.chart.data;
14241 var timeOpts = me.options.time;
14242 var label = data.labels && index < data.labels.length ? data.labels[index] : '';
14243 var value = data.datasets[datasetIndex].data[index];
14244
14245 if (helpers.isObject(value)) {
14246 label = me.getRightValue(value);
14247 }
14248 if (timeOpts.tooltipFormat) {
14249 return momentify(label, timeOpts).format(timeOpts.tooltipFormat);
14250 }
14251 if (typeof label === 'string') {
14252 return label;
14253 }
14254
14255 return momentify(label, timeOpts).format(me._labelFormat);
14256 },
14257
14258 /**
14259 * Function to format an individual tick mark
14260 * @private
14261 */
14262 tickFormatFunction: function(tick, index, ticks, formatOverride) {
14263 var me = this;
14264 var options = me.options;
14265 var time = tick.valueOf();
14266 var formats = options.time.displayFormats;
14267 var minorFormat = formats[me._unit];
14268 var majorUnit = me._majorUnit;
14269 var majorFormat = formats[majorUnit];
14270 var majorTime = tick.clone().startOf(majorUnit).valueOf();
14271 var majorTickOpts = options.ticks.major;
14272 var major = majorTickOpts.enabled && majorUnit && majorFormat && time === majorTime;
14273 var label = tick.format(formatOverride ? formatOverride : major ? majorFormat : minorFormat);
14274 var tickOpts = major ? majorTickOpts : options.ticks.minor;
14275 var formatter = helpers.valueOrDefault(tickOpts.callback, tickOpts.userCallback);
14276
14277 return formatter ? formatter(label, index, ticks) : label;
14278 },
14279
14280 convertTicksToLabels: function(ticks) {
14281 var labels = [];
14282 var i, ilen;
14283
14284 for (i = 0, ilen = ticks.length; i < ilen; ++i) {
14285 labels.push(this.tickFormatFunction(moment(ticks[i].value), i, ticks));
14286 }
14287
14288 return labels;
14289 },
14290
14291 /**
14292 * @private
14293 */
14294 getPixelForOffset: function(time) {
14295 var me = this;
14296 var size = me._horizontal ? me.width : me.height;
14297 var start = me._horizontal ? me.left : me.top;
14298 var pos = interpolate(me._table, 'time', time, 'pos');
14299
14300 return start + size * (me._offsets.left + pos) / (me._offsets.left + 1 + me._offsets.right);
14301 },
14302
14303 getPixelForValue: function(value, index, datasetIndex) {
14304 var me = this;
14305 var time = null;
14306
14307 if (index !== undefined && datasetIndex !== undefined) {
14308 time = me._timestamps.datasets[datasetIndex][index];
14309 }
14310
14311 if (time === null) {
14312 time = parse(value, me);
14313 }
14314
14315 if (time !== null) {
14316 return me.getPixelForOffset(time);
14317 }
14318 },
14319
14320 getPixelForTick: function(index) {
14321 var ticks = this.getTicks();
14322 return index >= 0 && index < ticks.length ?
14323 this.getPixelForOffset(ticks[index].value) :
14324 null;
14325 },
14326
14327 getValueForPixel: function(pixel) {
14328 var me = this;
14329 var size = me._horizontal ? me.width : me.height;
14330 var start = me._horizontal ? me.left : me.top;
14331 var pos = (size ? (pixel - start) / size : 0) * (me._offsets.left + 1 + me._offsets.left) - me._offsets.right;
14332 var time = interpolate(me._table, 'pos', pos, 'time');
14333
14334 return moment(time);
14335 },
14336
14337 /**
14338 * Crude approximation of what the label width might be
14339 * @private
14340 */
14341 getLabelWidth: function(label) {
14342 var me = this;
14343 var ticksOpts = me.options.ticks;
14344 var tickLabelWidth = me.ctx.measureText(label).width;
14345 var angle = helpers.toRadians(ticksOpts.maxRotation);
14346 var cosRotation = Math.cos(angle);
14347 var sinRotation = Math.sin(angle);
14348 var tickFontSize = helpers.valueOrDefault(ticksOpts.fontSize, defaults.global.defaultFontSize);
14349
14350 return (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation);
14351 },
14352
14353 /**
14354 * @private
14355 */
14356 getLabelCapacity: function(exampleTime) {
14357 var me = this;
14358
14359 var formatOverride = me.options.time.displayFormats.millisecond; // Pick the longest format for guestimation
14360
14361 var exampleLabel = me.tickFormatFunction(moment(exampleTime), 0, [], formatOverride);
14362 var tickLabelWidth = me.getLabelWidth(exampleLabel);
14363 var innerWidth = me.isHorizontal() ? me.width : me.height;
14364
14365 var capacity = Math.floor(innerWidth / tickLabelWidth);
14366 return capacity > 0 ? capacity : 1;
14367 }
14368 });
14369
14370 Chart.scaleService.registerScaleType('time', TimeScale, defaultConfig);
14371};
14372
14373},{"1":1,"25":25,"45":45}]},{},[7])(7)
14374});