· 7 years ago · Jan 15, 2019, 03:12 PM
1/*!
2 * Chart.js v2.7.3
3 * https://www.chartjs.org
4 * (c) 2019 Chart.js Contributors
5 * Released under the MIT License
6 * THIS VERSION IS THE MINIMAL VERSION: MOMENT JS ISN'T INCLUDED HERE, SEE BUNDLED VERSION INSTEAD I PUBLISHED BEFORE THIS DATE
7 */
8(function (global, factory) {
9typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('moment')) :
10typeof define === 'function' && define.amd ? define(['moment'], factory) :
11(global.Chart = factory(global.moment));
12}(this, (function (moment) { 'use strict';
13
14moment = moment && moment.hasOwnProperty('default') ? moment['default'] : moment;
15
16/* MIT license */
17
18var conversions = {
19 rgb2hsl: rgb2hsl,
20 rgb2hsv: rgb2hsv,
21 rgb2hwb: rgb2hwb,
22 rgb2cmyk: rgb2cmyk,
23 rgb2keyword: rgb2keyword,
24 rgb2xyz: rgb2xyz,
25 rgb2lab: rgb2lab,
26 rgb2lch: rgb2lch,
27
28 hsl2rgb: hsl2rgb,
29 hsl2hsv: hsl2hsv,
30 hsl2hwb: hsl2hwb,
31 hsl2cmyk: hsl2cmyk,
32 hsl2keyword: hsl2keyword,
33
34 hsv2rgb: hsv2rgb,
35 hsv2hsl: hsv2hsl,
36 hsv2hwb: hsv2hwb,
37 hsv2cmyk: hsv2cmyk,
38 hsv2keyword: hsv2keyword,
39
40 hwb2rgb: hwb2rgb,
41 hwb2hsl: hwb2hsl,
42 hwb2hsv: hwb2hsv,
43 hwb2cmyk: hwb2cmyk,
44 hwb2keyword: hwb2keyword,
45
46 cmyk2rgb: cmyk2rgb,
47 cmyk2hsl: cmyk2hsl,
48 cmyk2hsv: cmyk2hsv,
49 cmyk2hwb: cmyk2hwb,
50 cmyk2keyword: cmyk2keyword,
51
52 keyword2rgb: keyword2rgb,
53 keyword2hsl: keyword2hsl,
54 keyword2hsv: keyword2hsv,
55 keyword2hwb: keyword2hwb,
56 keyword2cmyk: keyword2cmyk,
57 keyword2lab: keyword2lab,
58 keyword2xyz: keyword2xyz,
59
60 xyz2rgb: xyz2rgb,
61 xyz2lab: xyz2lab,
62 xyz2lch: xyz2lch,
63
64 lab2xyz: lab2xyz,
65 lab2rgb: lab2rgb,
66 lab2lch: lab2lch,
67
68 lch2lab: lch2lab,
69 lch2xyz: lch2xyz,
70 lch2rgb: lch2rgb
71};
72
73
74function rgb2hsl(rgb) {
75 var r = rgb[0]/255,
76 g = rgb[1]/255,
77 b = rgb[2]/255,
78 min = Math.min(r, g, b),
79 max = Math.max(r, g, b),
80 delta = max - min,
81 h, s, l;
82
83 if (max == min)
84 h = 0;
85 else if (r == max)
86 h = (g - b) / delta;
87 else if (g == max)
88 h = 2 + (b - r) / delta;
89 else if (b == max)
90 h = 4 + (r - g)/ delta;
91
92 h = Math.min(h * 60, 360);
93
94 if (h < 0)
95 h += 360;
96
97 l = (min + max) / 2;
98
99 if (max == min)
100 s = 0;
101 else if (l <= 0.5)
102 s = delta / (max + min);
103 else
104 s = delta / (2 - max - min);
105
106 return [h, s * 100, l * 100];
107}
108
109function rgb2hsv(rgb) {
110 var r = rgb[0],
111 g = rgb[1],
112 b = rgb[2],
113 min = Math.min(r, g, b),
114 max = Math.max(r, g, b),
115 delta = max - min,
116 h, s, v;
117
118 if (max == 0)
119 s = 0;
120 else
121 s = (delta/max * 1000)/10;
122
123 if (max == min)
124 h = 0;
125 else if (r == max)
126 h = (g - b) / delta;
127 else if (g == max)
128 h = 2 + (b - r) / delta;
129 else if (b == max)
130 h = 4 + (r - g) / delta;
131
132 h = Math.min(h * 60, 360);
133
134 if (h < 0)
135 h += 360;
136
137 v = ((max / 255) * 1000) / 10;
138
139 return [h, s, v];
140}
141
142function rgb2hwb(rgb) {
143 var r = rgb[0],
144 g = rgb[1],
145 b = rgb[2],
146 h = rgb2hsl(rgb)[0],
147 w = 1/255 * Math.min(r, Math.min(g, b)),
148 b = 1 - 1/255 * Math.max(r, Math.max(g, b));
149
150 return [h, w * 100, b * 100];
151}
152
153function rgb2cmyk(rgb) {
154 var r = rgb[0] / 255,
155 g = rgb[1] / 255,
156 b = rgb[2] / 255,
157 c, m, y, k;
158
159 k = Math.min(1 - r, 1 - g, 1 - b);
160 c = (1 - r - k) / (1 - k) || 0;
161 m = (1 - g - k) / (1 - k) || 0;
162 y = (1 - b - k) / (1 - k) || 0;
163 return [c * 100, m * 100, y * 100, k * 100];
164}
165
166function rgb2keyword(rgb) {
167 return reverseKeywords[JSON.stringify(rgb)];
168}
169
170function rgb2xyz(rgb) {
171 var r = rgb[0] / 255,
172 g = rgb[1] / 255,
173 b = rgb[2] / 255;
174
175 // assume sRGB
176 r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
177 g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
178 b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
179
180 var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
181 var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
182 var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
183
184 return [x * 100, y *100, z * 100];
185}
186
187function rgb2lab(rgb) {
188 var xyz = rgb2xyz(rgb),
189 x = xyz[0],
190 y = xyz[1],
191 z = xyz[2],
192 l, a, b;
193
194 x /= 95.047;
195 y /= 100;
196 z /= 108.883;
197
198 x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
199 y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
200 z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
201
202 l = (116 * y) - 16;
203 a = 500 * (x - y);
204 b = 200 * (y - z);
205
206 return [l, a, b];
207}
208
209function rgb2lch(args) {
210 return lab2lch(rgb2lab(args));
211}
212
213function hsl2rgb(hsl) {
214 var h = hsl[0] / 360,
215 s = hsl[1] / 100,
216 l = hsl[2] / 100,
217 t1, t2, t3, rgb, val;
218
219 if (s == 0) {
220 val = l * 255;
221 return [val, val, val];
222 }
223
224 if (l < 0.5)
225 t2 = l * (1 + s);
226 else
227 t2 = l + s - l * s;
228 t1 = 2 * l - t2;
229
230 rgb = [0, 0, 0];
231 for (var i = 0; i < 3; i++) {
232 t3 = h + 1 / 3 * - (i - 1);
233 t3 < 0 && t3++;
234 t3 > 1 && t3--;
235
236 if (6 * t3 < 1)
237 val = t1 + (t2 - t1) * 6 * t3;
238 else if (2 * t3 < 1)
239 val = t2;
240 else if (3 * t3 < 2)
241 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
242 else
243 val = t1;
244
245 rgb[i] = val * 255;
246 }
247
248 return rgb;
249}
250
251function hsl2hsv(hsl) {
252 var h = hsl[0],
253 s = hsl[1] / 100,
254 l = hsl[2] / 100,
255 sv, v;
256
257 if(l === 0) {
258 // no need to do calc on black
259 // also avoids divide by 0 error
260 return [0, 0, 0];
261 }
262
263 l *= 2;
264 s *= (l <= 1) ? l : 2 - l;
265 v = (l + s) / 2;
266 sv = (2 * s) / (l + s);
267 return [h, sv * 100, v * 100];
268}
269
270function hsl2hwb(args) {
271 return rgb2hwb(hsl2rgb(args));
272}
273
274function hsl2cmyk(args) {
275 return rgb2cmyk(hsl2rgb(args));
276}
277
278function hsl2keyword(args) {
279 return rgb2keyword(hsl2rgb(args));
280}
281
282
283function hsv2rgb(hsv) {
284 var h = hsv[0] / 60,
285 s = hsv[1] / 100,
286 v = hsv[2] / 100,
287 hi = Math.floor(h) % 6;
288
289 var f = h - Math.floor(h),
290 p = 255 * v * (1 - s),
291 q = 255 * v * (1 - (s * f)),
292 t = 255 * v * (1 - (s * (1 - f))),
293 v = 255 * v;
294
295 switch(hi) {
296 case 0:
297 return [v, t, p];
298 case 1:
299 return [q, v, p];
300 case 2:
301 return [p, v, t];
302 case 3:
303 return [p, q, v];
304 case 4:
305 return [t, p, v];
306 case 5:
307 return [v, p, q];
308 }
309}
310
311function hsv2hsl(hsv) {
312 var h = hsv[0],
313 s = hsv[1] / 100,
314 v = hsv[2] / 100,
315 sl, l;
316
317 l = (2 - s) * v;
318 sl = s * v;
319 sl /= (l <= 1) ? l : 2 - l;
320 sl = sl || 0;
321 l /= 2;
322 return [h, sl * 100, l * 100];
323}
324
325function hsv2hwb(args) {
326 return rgb2hwb(hsv2rgb(args))
327}
328
329function hsv2cmyk(args) {
330 return rgb2cmyk(hsv2rgb(args));
331}
332
333function hsv2keyword(args) {
334 return rgb2keyword(hsv2rgb(args));
335}
336
337// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
338function hwb2rgb(hwb) {
339 var h = hwb[0] / 360,
340 wh = hwb[1] / 100,
341 bl = hwb[2] / 100,
342 ratio = wh + bl,
343 i, v, f, n;
344
345 // wh + bl cant be > 1
346 if (ratio > 1) {
347 wh /= ratio;
348 bl /= ratio;
349 }
350
351 i = Math.floor(6 * h);
352 v = 1 - bl;
353 f = 6 * h - i;
354 if ((i & 0x01) != 0) {
355 f = 1 - f;
356 }
357 n = wh + f * (v - wh); // linear interpolation
358
359 switch (i) {
360 default:
361 case 6:
362 case 0: r = v; g = n; b = wh; break;
363 case 1: r = n; g = v; b = wh; break;
364 case 2: r = wh; g = v; b = n; break;
365 case 3: r = wh; g = n; b = v; break;
366 case 4: r = n; g = wh; b = v; break;
367 case 5: r = v; g = wh; b = n; break;
368 }
369
370 return [r * 255, g * 255, b * 255];
371}
372
373function hwb2hsl(args) {
374 return rgb2hsl(hwb2rgb(args));
375}
376
377function hwb2hsv(args) {
378 return rgb2hsv(hwb2rgb(args));
379}
380
381function hwb2cmyk(args) {
382 return rgb2cmyk(hwb2rgb(args));
383}
384
385function hwb2keyword(args) {
386 return rgb2keyword(hwb2rgb(args));
387}
388
389function cmyk2rgb(cmyk) {
390 var c = cmyk[0] / 100,
391 m = cmyk[1] / 100,
392 y = cmyk[2] / 100,
393 k = cmyk[3] / 100,
394 r, g, b;
395
396 r = 1 - Math.min(1, c * (1 - k) + k);
397 g = 1 - Math.min(1, m * (1 - k) + k);
398 b = 1 - Math.min(1, y * (1 - k) + k);
399 return [r * 255, g * 255, b * 255];
400}
401
402function cmyk2hsl(args) {
403 return rgb2hsl(cmyk2rgb(args));
404}
405
406function cmyk2hsv(args) {
407 return rgb2hsv(cmyk2rgb(args));
408}
409
410function cmyk2hwb(args) {
411 return rgb2hwb(cmyk2rgb(args));
412}
413
414function cmyk2keyword(args) {
415 return rgb2keyword(cmyk2rgb(args));
416}
417
418
419function xyz2rgb(xyz) {
420 var x = xyz[0] / 100,
421 y = xyz[1] / 100,
422 z = xyz[2] / 100,
423 r, g, b;
424
425 r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
426 g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
427 b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
428
429 // assume sRGB
430 r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
431 : r = (r * 12.92);
432
433 g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
434 : g = (g * 12.92);
435
436 b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
437 : b = (b * 12.92);
438
439 r = Math.min(Math.max(0, r), 1);
440 g = Math.min(Math.max(0, g), 1);
441 b = Math.min(Math.max(0, b), 1);
442
443 return [r * 255, g * 255, b * 255];
444}
445
446function xyz2lab(xyz) {
447 var x = xyz[0],
448 y = xyz[1],
449 z = xyz[2],
450 l, a, b;
451
452 x /= 95.047;
453 y /= 100;
454 z /= 108.883;
455
456 x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
457 y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
458 z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
459
460 l = (116 * y) - 16;
461 a = 500 * (x - y);
462 b = 200 * (y - z);
463
464 return [l, a, b];
465}
466
467function xyz2lch(args) {
468 return lab2lch(xyz2lab(args));
469}
470
471function lab2xyz(lab) {
472 var l = lab[0],
473 a = lab[1],
474 b = lab[2],
475 x, y, z, y2;
476
477 if (l <= 8) {
478 y = (l * 100) / 903.3;
479 y2 = (7.787 * (y / 100)) + (16 / 116);
480 } else {
481 y = 100 * Math.pow((l + 16) / 116, 3);
482 y2 = Math.pow(y / 100, 1/3);
483 }
484
485 x = x / 95.047 <= 0.008856 ? x = (95.047 * ((a / 500) + y2 - (16 / 116))) / 7.787 : 95.047 * Math.pow((a / 500) + y2, 3);
486
487 z = z / 108.883 <= 0.008859 ? z = (108.883 * (y2 - (b / 200) - (16 / 116))) / 7.787 : 108.883 * Math.pow(y2 - (b / 200), 3);
488
489 return [x, y, z];
490}
491
492function lab2lch(lab) {
493 var l = lab[0],
494 a = lab[1],
495 b = lab[2],
496 hr, h, c;
497
498 hr = Math.atan2(b, a);
499 h = hr * 360 / 2 / Math.PI;
500 if (h < 0) {
501 h += 360;
502 }
503 c = Math.sqrt(a * a + b * b);
504 return [l, c, h];
505}
506
507function lab2rgb(args) {
508 return xyz2rgb(lab2xyz(args));
509}
510
511function lch2lab(lch) {
512 var l = lch[0],
513 c = lch[1],
514 h = lch[2],
515 a, b, hr;
516
517 hr = h / 360 * 2 * Math.PI;
518 a = c * Math.cos(hr);
519 b = c * Math.sin(hr);
520 return [l, a, b];
521}
522
523function lch2xyz(args) {
524 return lab2xyz(lch2lab(args));
525}
526
527function lch2rgb(args) {
528 return lab2rgb(lch2lab(args));
529}
530
531function keyword2rgb(keyword) {
532 return cssKeywords[keyword];
533}
534
535function keyword2hsl(args) {
536 return rgb2hsl(keyword2rgb(args));
537}
538
539function keyword2hsv(args) {
540 return rgb2hsv(keyword2rgb(args));
541}
542
543function keyword2hwb(args) {
544 return rgb2hwb(keyword2rgb(args));
545}
546
547function keyword2cmyk(args) {
548 return rgb2cmyk(keyword2rgb(args));
549}
550
551function keyword2lab(args) {
552 return rgb2lab(keyword2rgb(args));
553}
554
555function keyword2xyz(args) {
556 return rgb2xyz(keyword2rgb(args));
557}
558
559var cssKeywords = {
560 aliceblue: [240,248,255],
561 antiquewhite: [250,235,215],
562 aqua: [0,255,255],
563 aquamarine: [127,255,212],
564 azure: [240,255,255],
565 beige: [245,245,220],
566 bisque: [255,228,196],
567 black: [0,0,0],
568 blanchedalmond: [255,235,205],
569 blue: [0,0,255],
570 blueviolet: [138,43,226],
571 brown: [165,42,42],
572 burlywood: [222,184,135],
573 cadetblue: [95,158,160],
574 chartreuse: [127,255,0],
575 chocolate: [210,105,30],
576 coral: [255,127,80],
577 cornflowerblue: [100,149,237],
578 cornsilk: [255,248,220],
579 crimson: [220,20,60],
580 cyan: [0,255,255],
581 darkblue: [0,0,139],
582 darkcyan: [0,139,139],
583 darkgoldenrod: [184,134,11],
584 darkgray: [169,169,169],
585 darkgreen: [0,100,0],
586 darkgrey: [169,169,169],
587 darkkhaki: [189,183,107],
588 darkmagenta: [139,0,139],
589 darkolivegreen: [85,107,47],
590 darkorange: [255,140,0],
591 darkorchid: [153,50,204],
592 darkred: [139,0,0],
593 darksalmon: [233,150,122],
594 darkseagreen: [143,188,143],
595 darkslateblue: [72,61,139],
596 darkslategray: [47,79,79],
597 darkslategrey: [47,79,79],
598 darkturquoise: [0,206,209],
599 darkviolet: [148,0,211],
600 deeppink: [255,20,147],
601 deepskyblue: [0,191,255],
602 dimgray: [105,105,105],
603 dimgrey: [105,105,105],
604 dodgerblue: [30,144,255],
605 firebrick: [178,34,34],
606 floralwhite: [255,250,240],
607 forestgreen: [34,139,34],
608 fuchsia: [255,0,255],
609 gainsboro: [220,220,220],
610 ghostwhite: [248,248,255],
611 gold: [255,215,0],
612 goldenrod: [218,165,32],
613 gray: [128,128,128],
614 green: [0,128,0],
615 greenyellow: [173,255,47],
616 grey: [128,128,128],
617 honeydew: [240,255,240],
618 hotpink: [255,105,180],
619 indianred: [205,92,92],
620 indigo: [75,0,130],
621 ivory: [255,255,240],
622 khaki: [240,230,140],
623 lavender: [230,230,250],
624 lavenderblush: [255,240,245],
625 lawngreen: [124,252,0],
626 lemonchiffon: [255,250,205],
627 lightblue: [173,216,230],
628 lightcoral: [240,128,128],
629 lightcyan: [224,255,255],
630 lightgoldenrodyellow: [250,250,210],
631 lightgray: [211,211,211],
632 lightgreen: [144,238,144],
633 lightgrey: [211,211,211],
634 lightpink: [255,182,193],
635 lightsalmon: [255,160,122],
636 lightseagreen: [32,178,170],
637 lightskyblue: [135,206,250],
638 lightslategray: [119,136,153],
639 lightslategrey: [119,136,153],
640 lightsteelblue: [176,196,222],
641 lightyellow: [255,255,224],
642 lime: [0,255,0],
643 limegreen: [50,205,50],
644 linen: [250,240,230],
645 magenta: [255,0,255],
646 maroon: [128,0,0],
647 mediumaquamarine: [102,205,170],
648 mediumblue: [0,0,205],
649 mediumorchid: [186,85,211],
650 mediumpurple: [147,112,219],
651 mediumseagreen: [60,179,113],
652 mediumslateblue: [123,104,238],
653 mediumspringgreen: [0,250,154],
654 mediumturquoise: [72,209,204],
655 mediumvioletred: [199,21,133],
656 midnightblue: [25,25,112],
657 mintcream: [245,255,250],
658 mistyrose: [255,228,225],
659 moccasin: [255,228,181],
660 navajowhite: [255,222,173],
661 navy: [0,0,128],
662 oldlace: [253,245,230],
663 olive: [128,128,0],
664 olivedrab: [107,142,35],
665 orange: [255,165,0],
666 orangered: [255,69,0],
667 orchid: [218,112,214],
668 palegoldenrod: [238,232,170],
669 palegreen: [152,251,152],
670 paleturquoise: [175,238,238],
671 palevioletred: [219,112,147],
672 papayawhip: [255,239,213],
673 peachpuff: [255,218,185],
674 peru: [205,133,63],
675 pink: [255,192,203],
676 plum: [221,160,221],
677 powderblue: [176,224,230],
678 purple: [128,0,128],
679 rebeccapurple: [102, 51, 153],
680 red: [255,0,0],
681 rosybrown: [188,143,143],
682 royalblue: [65,105,225],
683 saddlebrown: [139,69,19],
684 salmon: [250,128,114],
685 sandybrown: [244,164,96],
686 seagreen: [46,139,87],
687 seashell: [255,245,238],
688 sienna: [160,82,45],
689 silver: [192,192,192],
690 skyblue: [135,206,235],
691 slateblue: [106,90,205],
692 slategray: [112,128,144],
693 slategrey: [112,128,144],
694 snow: [255,250,250],
695 springgreen: [0,255,127],
696 steelblue: [70,130,180],
697 tan: [210,180,140],
698 teal: [0,128,128],
699 thistle: [216,191,216],
700 tomato: [255,99,71],
701 turquoise: [64,224,208],
702 violet: [238,130,238],
703 wheat: [245,222,179],
704 white: [255,255,255],
705 whitesmoke: [245,245,245],
706 yellow: [255,255,0],
707 yellowgreen: [154,205,50]
708};
709
710var reverseKeywords = {};
711for (var key in cssKeywords) {
712 reverseKeywords[JSON.stringify(cssKeywords[key])] = key;
713}
714
715var convert = function() {
716 return new Converter();
717};
718
719for (var func in conversions) {
720 // export Raw versions
721 convert[func + "Raw"] = (function(func) {
722 // accept array or plain args
723 return function(arg) {
724 if (typeof arg == "number")
725 arg = Array.prototype.slice.call(arguments);
726 return conversions[func](arg);
727 }
728 })(func);
729
730 var pair = /(\w+)2(\w+)/.exec(func),
731 from = pair[1],
732 to = pair[2];
733
734 // export rgb2hsl and ["rgb"]["hsl"]
735 convert[from] = convert[from] || {};
736
737 convert[from][to] = convert[func] = (function(func) {
738 return function(arg) {
739 if (typeof arg == "number")
740 arg = Array.prototype.slice.call(arguments);
741
742 var val = conversions[func](arg);
743 if (typeof val == "string" || val === undefined)
744 return val; // keyword
745
746 for (var i = 0; i < val.length; i++)
747 val[i] = Math.round(val[i]);
748 return val;
749 }
750 })(func);
751}
752
753
754/* Converter does lazy conversion and caching */
755var Converter = function() {
756 this.convs = {};
757};
758
759/* Either get the values for a space or
760 set the values for a space, depending on args */
761Converter.prototype.routeSpace = function(space, args) {
762 var values = args[0];
763 if (values === undefined) {
764 // color.rgb()
765 return this.getValues(space);
766 }
767 // color.rgb(10, 10, 10)
768 if (typeof values == "number") {
769 values = Array.prototype.slice.call(args);
770 }
771
772 return this.setValues(space, values);
773};
774
775/* Set the values for a space, invalidating cache */
776Converter.prototype.setValues = function(space, values) {
777 this.space = space;
778 this.convs = {};
779 this.convs[space] = values;
780 return this;
781};
782
783/* Get the values for a space. If there's already
784 a conversion for the space, fetch it, otherwise
785 compute it */
786Converter.prototype.getValues = function(space) {
787 var vals = this.convs[space];
788 if (!vals) {
789 var fspace = this.space,
790 from = this.convs[fspace];
791 vals = convert[fspace][space](from);
792
793 this.convs[space] = vals;
794 }
795 return vals;
796};
797
798["rgb", "hsl", "hsv", "cmyk", "keyword"].forEach(function(space) {
799 Converter.prototype[space] = function(vals) {
800 return this.routeSpace(space, arguments);
801 };
802});
803
804var colorConvert = convert;
805
806var colorName = {
807 "aliceblue": [240, 248, 255],
808 "antiquewhite": [250, 235, 215],
809 "aqua": [0, 255, 255],
810 "aquamarine": [127, 255, 212],
811 "azure": [240, 255, 255],
812 "beige": [245, 245, 220],
813 "bisque": [255, 228, 196],
814 "black": [0, 0, 0],
815 "blanchedalmond": [255, 235, 205],
816 "blue": [0, 0, 255],
817 "blueviolet": [138, 43, 226],
818 "brown": [165, 42, 42],
819 "burlywood": [222, 184, 135],
820 "cadetblue": [95, 158, 160],
821 "chartreuse": [127, 255, 0],
822 "chocolate": [210, 105, 30],
823 "coral": [255, 127, 80],
824 "cornflowerblue": [100, 149, 237],
825 "cornsilk": [255, 248, 220],
826 "crimson": [220, 20, 60],
827 "cyan": [0, 255, 255],
828 "darkblue": [0, 0, 139],
829 "darkcyan": [0, 139, 139],
830 "darkgoldenrod": [184, 134, 11],
831 "darkgray": [169, 169, 169],
832 "darkgreen": [0, 100, 0],
833 "darkgrey": [169, 169, 169],
834 "darkkhaki": [189, 183, 107],
835 "darkmagenta": [139, 0, 139],
836 "darkolivegreen": [85, 107, 47],
837 "darkorange": [255, 140, 0],
838 "darkorchid": [153, 50, 204],
839 "darkred": [139, 0, 0],
840 "darksalmon": [233, 150, 122],
841 "darkseagreen": [143, 188, 143],
842 "darkslateblue": [72, 61, 139],
843 "darkslategray": [47, 79, 79],
844 "darkslategrey": [47, 79, 79],
845 "darkturquoise": [0, 206, 209],
846 "darkviolet": [148, 0, 211],
847 "deeppink": [255, 20, 147],
848 "deepskyblue": [0, 191, 255],
849 "dimgray": [105, 105, 105],
850 "dimgrey": [105, 105, 105],
851 "dodgerblue": [30, 144, 255],
852 "firebrick": [178, 34, 34],
853 "floralwhite": [255, 250, 240],
854 "forestgreen": [34, 139, 34],
855 "fuchsia": [255, 0, 255],
856 "gainsboro": [220, 220, 220],
857 "ghostwhite": [248, 248, 255],
858 "gold": [255, 215, 0],
859 "goldenrod": [218, 165, 32],
860 "gray": [128, 128, 128],
861 "green": [0, 128, 0],
862 "greenyellow": [173, 255, 47],
863 "grey": [128, 128, 128],
864 "honeydew": [240, 255, 240],
865 "hotpink": [255, 105, 180],
866 "indianred": [205, 92, 92],
867 "indigo": [75, 0, 130],
868 "ivory": [255, 255, 240],
869 "khaki": [240, 230, 140],
870 "lavender": [230, 230, 250],
871 "lavenderblush": [255, 240, 245],
872 "lawngreen": [124, 252, 0],
873 "lemonchiffon": [255, 250, 205],
874 "lightblue": [173, 216, 230],
875 "lightcoral": [240, 128, 128],
876 "lightcyan": [224, 255, 255],
877 "lightgoldenrodyellow": [250, 250, 210],
878 "lightgray": [211, 211, 211],
879 "lightgreen": [144, 238, 144],
880 "lightgrey": [211, 211, 211],
881 "lightpink": [255, 182, 193],
882 "lightsalmon": [255, 160, 122],
883 "lightseagreen": [32, 178, 170],
884 "lightskyblue": [135, 206, 250],
885 "lightslategray": [119, 136, 153],
886 "lightslategrey": [119, 136, 153],
887 "lightsteelblue": [176, 196, 222],
888 "lightyellow": [255, 255, 224],
889 "lime": [0, 255, 0],
890 "limegreen": [50, 205, 50],
891 "linen": [250, 240, 230],
892 "magenta": [255, 0, 255],
893 "maroon": [128, 0, 0],
894 "mediumaquamarine": [102, 205, 170],
895 "mediumblue": [0, 0, 205],
896 "mediumorchid": [186, 85, 211],
897 "mediumpurple": [147, 112, 219],
898 "mediumseagreen": [60, 179, 113],
899 "mediumslateblue": [123, 104, 238],
900 "mediumspringgreen": [0, 250, 154],
901 "mediumturquoise": [72, 209, 204],
902 "mediumvioletred": [199, 21, 133],
903 "midnightblue": [25, 25, 112],
904 "mintcream": [245, 255, 250],
905 "mistyrose": [255, 228, 225],
906 "moccasin": [255, 228, 181],
907 "navajowhite": [255, 222, 173],
908 "navy": [0, 0, 128],
909 "oldlace": [253, 245, 230],
910 "olive": [128, 128, 0],
911 "olivedrab": [107, 142, 35],
912 "orange": [255, 165, 0],
913 "orangered": [255, 69, 0],
914 "orchid": [218, 112, 214],
915 "palegoldenrod": [238, 232, 170],
916 "palegreen": [152, 251, 152],
917 "paleturquoise": [175, 238, 238],
918 "palevioletred": [219, 112, 147],
919 "papayawhip": [255, 239, 213],
920 "peachpuff": [255, 218, 185],
921 "peru": [205, 133, 63],
922 "pink": [255, 192, 203],
923 "plum": [221, 160, 221],
924 "powderblue": [176, 224, 230],
925 "purple": [128, 0, 128],
926 "rebeccapurple": [102, 51, 153],
927 "red": [255, 0, 0],
928 "rosybrown": [188, 143, 143],
929 "royalblue": [65, 105, 225],
930 "saddlebrown": [139, 69, 19],
931 "salmon": [250, 128, 114],
932 "sandybrown": [244, 164, 96],
933 "seagreen": [46, 139, 87],
934 "seashell": [255, 245, 238],
935 "sienna": [160, 82, 45],
936 "silver": [192, 192, 192],
937 "skyblue": [135, 206, 235],
938 "slateblue": [106, 90, 205],
939 "slategray": [112, 128, 144],
940 "slategrey": [112, 128, 144],
941 "snow": [255, 250, 250],
942 "springgreen": [0, 255, 127],
943 "steelblue": [70, 130, 180],
944 "tan": [210, 180, 140],
945 "teal": [0, 128, 128],
946 "thistle": [216, 191, 216],
947 "tomato": [255, 99, 71],
948 "turquoise": [64, 224, 208],
949 "violet": [238, 130, 238],
950 "wheat": [245, 222, 179],
951 "white": [255, 255, 255],
952 "whitesmoke": [245, 245, 245],
953 "yellow": [255, 255, 0],
954 "yellowgreen": [154, 205, 50]
955};
956
957/* MIT license */
958
959
960var colorString = {
961 getRgba: getRgba,
962 getHsla: getHsla,
963 getRgb: getRgb,
964 getHsl: getHsl,
965 getHwb: getHwb,
966 getAlpha: getAlpha,
967
968 hexString: hexString,
969 rgbString: rgbString,
970 rgbaString: rgbaString,
971 percentString: percentString,
972 percentaString: percentaString,
973 hslString: hslString,
974 hslaString: hslaString,
975 hwbString: hwbString,
976 keyword: keyword
977};
978
979function getRgba(string) {
980 if (!string) {
981 return;
982 }
983 var abbr = /^#([a-fA-F0-9]{3})$/i,
984 hex = /^#([a-fA-F0-9]{6})$/i,
985 rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
986 per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
987 keyword = /(\w+)/;
988
989 var rgb = [0, 0, 0],
990 a = 1,
991 match = string.match(abbr);
992 if (match) {
993 match = match[1];
994 for (var i = 0; i < rgb.length; i++) {
995 rgb[i] = parseInt(match[i] + match[i], 16);
996 }
997 }
998 else if (match = string.match(hex)) {
999 match = match[1];
1000 for (var i = 0; i < rgb.length; i++) {
1001 rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
1002 }
1003 }
1004 else if (match = string.match(rgba)) {
1005 for (var i = 0; i < rgb.length; i++) {
1006 rgb[i] = parseInt(match[i + 1]);
1007 }
1008 a = parseFloat(match[4]);
1009 }
1010 else if (match = string.match(per)) {
1011 for (var i = 0; i < rgb.length; i++) {
1012 rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
1013 }
1014 a = parseFloat(match[4]);
1015 }
1016 else if (match = string.match(keyword)) {
1017 if (match[1] == "transparent") {
1018 return [0, 0, 0, 0];
1019 }
1020 rgb = colorName[match[1]];
1021 if (!rgb) {
1022 return;
1023 }
1024 }
1025
1026 for (var i = 0; i < rgb.length; i++) {
1027 rgb[i] = scale(rgb[i], 0, 255);
1028 }
1029 if (!a && a != 0) {
1030 a = 1;
1031 }
1032 else {
1033 a = scale(a, 0, 1);
1034 }
1035 rgb[3] = a;
1036 return rgb;
1037}
1038
1039function getHsla(string) {
1040 if (!string) {
1041 return;
1042 }
1043 var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
1044 var match = string.match(hsl);
1045 if (match) {
1046 var alpha = parseFloat(match[4]);
1047 var h = scale(parseInt(match[1]), 0, 360),
1048 s = scale(parseFloat(match[2]), 0, 100),
1049 l = scale(parseFloat(match[3]), 0, 100),
1050 a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
1051 return [h, s, l, a];
1052 }
1053}
1054
1055function getHwb(string) {
1056 if (!string) {
1057 return;
1058 }
1059 var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
1060 var match = string.match(hwb);
1061 if (match) {
1062 var alpha = parseFloat(match[4]);
1063 var h = scale(parseInt(match[1]), 0, 360),
1064 w = scale(parseFloat(match[2]), 0, 100),
1065 b = scale(parseFloat(match[3]), 0, 100),
1066 a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
1067 return [h, w, b, a];
1068 }
1069}
1070
1071function getRgb(string) {
1072 var rgba = getRgba(string);
1073 return rgba && rgba.slice(0, 3);
1074}
1075
1076function getHsl(string) {
1077 var hsla = getHsla(string);
1078 return hsla && hsla.slice(0, 3);
1079}
1080
1081function getAlpha(string) {
1082 var vals = getRgba(string);
1083 if (vals) {
1084 return vals[3];
1085 }
1086 else if (vals = getHsla(string)) {
1087 return vals[3];
1088 }
1089 else if (vals = getHwb(string)) {
1090 return vals[3];
1091 }
1092}
1093
1094// generators
1095function hexString(rgb) {
1096 return "#" + hexDouble(rgb[0]) + hexDouble(rgb[1])
1097 + hexDouble(rgb[2]);
1098}
1099
1100function rgbString(rgba, alpha) {
1101 if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
1102 return rgbaString(rgba, alpha);
1103 }
1104 return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
1105}
1106
1107function rgbaString(rgba, alpha) {
1108 if (alpha === undefined) {
1109 alpha = (rgba[3] !== undefined ? rgba[3] : 1);
1110 }
1111 return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
1112 + ", " + alpha + ")";
1113}
1114
1115function percentString(rgba, alpha) {
1116 if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
1117 return percentaString(rgba, alpha);
1118 }
1119 var r = Math.round(rgba[0]/255 * 100),
1120 g = Math.round(rgba[1]/255 * 100),
1121 b = Math.round(rgba[2]/255 * 100);
1122
1123 return "rgb(" + r + "%, " + g + "%, " + b + "%)";
1124}
1125
1126function percentaString(rgba, alpha) {
1127 var r = Math.round(rgba[0]/255 * 100),
1128 g = Math.round(rgba[1]/255 * 100),
1129 b = Math.round(rgba[2]/255 * 100);
1130 return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
1131}
1132
1133function hslString(hsla, alpha) {
1134 if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
1135 return hslaString(hsla, alpha);
1136 }
1137 return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
1138}
1139
1140function hslaString(hsla, alpha) {
1141 if (alpha === undefined) {
1142 alpha = (hsla[3] !== undefined ? hsla[3] : 1);
1143 }
1144 return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
1145 + alpha + ")";
1146}
1147
1148// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
1149// (hwb have alpha optional & 1 is default value)
1150function hwbString(hwb, alpha) {
1151 if (alpha === undefined) {
1152 alpha = (hwb[3] !== undefined ? hwb[3] : 1);
1153 }
1154 return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
1155 + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
1156}
1157
1158function keyword(rgb) {
1159 return reverseNames[rgb.slice(0, 3)];
1160}
1161
1162// helpers
1163function scale(num, min, max) {
1164 return Math.min(Math.max(min, num), max);
1165}
1166
1167function hexDouble(num) {
1168 var str = num.toString(16).toUpperCase();
1169 return (str.length < 2) ? "0" + str : str;
1170}
1171
1172
1173//create a list of reverse color names
1174var reverseNames = {};
1175for (var name in colorName) {
1176 reverseNames[colorName[name]] = name;
1177}
1178
1179/* MIT license */
1180
1181
1182
1183var Color = function (obj) {
1184 if (obj instanceof Color) {
1185 return obj;
1186 }
1187 if (!(this instanceof Color)) {
1188 return new Color(obj);
1189 }
1190
1191 this.valid = false;
1192 this.values = {
1193 rgb: [0, 0, 0],
1194 hsl: [0, 0, 0],
1195 hsv: [0, 0, 0],
1196 hwb: [0, 0, 0],
1197 cmyk: [0, 0, 0, 0],
1198 alpha: 1
1199 };
1200
1201 // parse Color() argument
1202 var vals;
1203 if (typeof obj === 'string') {
1204 vals = colorString.getRgba(obj);
1205 if (vals) {
1206 this.setValues('rgb', vals);
1207 } else if (vals = colorString.getHsla(obj)) {
1208 this.setValues('hsl', vals);
1209 } else if (vals = colorString.getHwb(obj)) {
1210 this.setValues('hwb', vals);
1211 }
1212 } else if (typeof obj === 'object') {
1213 vals = obj;
1214 if (vals.r !== undefined || vals.red !== undefined) {
1215 this.setValues('rgb', vals);
1216 } else if (vals.l !== undefined || vals.lightness !== undefined) {
1217 this.setValues('hsl', vals);
1218 } else if (vals.v !== undefined || vals.value !== undefined) {
1219 this.setValues('hsv', vals);
1220 } else if (vals.w !== undefined || vals.whiteness !== undefined) {
1221 this.setValues('hwb', vals);
1222 } else if (vals.c !== undefined || vals.cyan !== undefined) {
1223 this.setValues('cmyk', vals);
1224 }
1225 }
1226};
1227
1228Color.prototype = {
1229 isValid: function () {
1230 return this.valid;
1231 },
1232 rgb: function () {
1233 return this.setSpace('rgb', arguments);
1234 },
1235 hsl: function () {
1236 return this.setSpace('hsl', arguments);
1237 },
1238 hsv: function () {
1239 return this.setSpace('hsv', arguments);
1240 },
1241 hwb: function () {
1242 return this.setSpace('hwb', arguments);
1243 },
1244 cmyk: function () {
1245 return this.setSpace('cmyk', arguments);
1246 },
1247
1248 rgbArray: function () {
1249 return this.values.rgb;
1250 },
1251 hslArray: function () {
1252 return this.values.hsl;
1253 },
1254 hsvArray: function () {
1255 return this.values.hsv;
1256 },
1257 hwbArray: function () {
1258 var values = this.values;
1259 if (values.alpha !== 1) {
1260 return values.hwb.concat([values.alpha]);
1261 }
1262 return values.hwb;
1263 },
1264 cmykArray: function () {
1265 return this.values.cmyk;
1266 },
1267 rgbaArray: function () {
1268 var values = this.values;
1269 return values.rgb.concat([values.alpha]);
1270 },
1271 hslaArray: function () {
1272 var values = this.values;
1273 return values.hsl.concat([values.alpha]);
1274 },
1275 alpha: function (val) {
1276 if (val === undefined) {
1277 return this.values.alpha;
1278 }
1279 this.setValues('alpha', val);
1280 return this;
1281 },
1282
1283 red: function (val) {
1284 return this.setChannel('rgb', 0, val);
1285 },
1286 green: function (val) {
1287 return this.setChannel('rgb', 1, val);
1288 },
1289 blue: function (val) {
1290 return this.setChannel('rgb', 2, val);
1291 },
1292 hue: function (val) {
1293 if (val) {
1294 val %= 360;
1295 val = val < 0 ? 360 + val : val;
1296 }
1297 return this.setChannel('hsl', 0, val);
1298 },
1299 saturation: function (val) {
1300 return this.setChannel('hsl', 1, val);
1301 },
1302 lightness: function (val) {
1303 return this.setChannel('hsl', 2, val);
1304 },
1305 saturationv: function (val) {
1306 return this.setChannel('hsv', 1, val);
1307 },
1308 whiteness: function (val) {
1309 return this.setChannel('hwb', 1, val);
1310 },
1311 blackness: function (val) {
1312 return this.setChannel('hwb', 2, val);
1313 },
1314 value: function (val) {
1315 return this.setChannel('hsv', 2, val);
1316 },
1317 cyan: function (val) {
1318 return this.setChannel('cmyk', 0, val);
1319 },
1320 magenta: function (val) {
1321 return this.setChannel('cmyk', 1, val);
1322 },
1323 yellow: function (val) {
1324 return this.setChannel('cmyk', 2, val);
1325 },
1326 black: function (val) {
1327 return this.setChannel('cmyk', 3, val);
1328 },
1329
1330 hexString: function () {
1331 return colorString.hexString(this.values.rgb);
1332 },
1333 rgbString: function () {
1334 return colorString.rgbString(this.values.rgb, this.values.alpha);
1335 },
1336 rgbaString: function () {
1337 return colorString.rgbaString(this.values.rgb, this.values.alpha);
1338 },
1339 percentString: function () {
1340 return colorString.percentString(this.values.rgb, this.values.alpha);
1341 },
1342 hslString: function () {
1343 return colorString.hslString(this.values.hsl, this.values.alpha);
1344 },
1345 hslaString: function () {
1346 return colorString.hslaString(this.values.hsl, this.values.alpha);
1347 },
1348 hwbString: function () {
1349 return colorString.hwbString(this.values.hwb, this.values.alpha);
1350 },
1351 keyword: function () {
1352 return colorString.keyword(this.values.rgb, this.values.alpha);
1353 },
1354
1355 rgbNumber: function () {
1356 var rgb = this.values.rgb;
1357 return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
1358 },
1359
1360 luminosity: function () {
1361 // http://www.w3.org/TR/WCAG20/#relativeluminancedef
1362 var rgb = this.values.rgb;
1363 var lum = [];
1364 for (var i = 0; i < rgb.length; i++) {
1365 var chan = rgb[i] / 255;
1366 lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
1367 }
1368 return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
1369 },
1370
1371 contrast: function (color2) {
1372 // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
1373 var lum1 = this.luminosity();
1374 var lum2 = color2.luminosity();
1375 if (lum1 > lum2) {
1376 return (lum1 + 0.05) / (lum2 + 0.05);
1377 }
1378 return (lum2 + 0.05) / (lum1 + 0.05);
1379 },
1380
1381 level: function (color2) {
1382 var contrastRatio = this.contrast(color2);
1383 if (contrastRatio >= 7.1) {
1384 return 'AAA';
1385 }
1386
1387 return (contrastRatio >= 4.5) ? 'AA' : '';
1388 },
1389
1390 dark: function () {
1391 // YIQ equation from http://24ways.org/2010/calculating-color-contrast
1392 var rgb = this.values.rgb;
1393 var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
1394 return yiq < 128;
1395 },
1396
1397 light: function () {
1398 return !this.dark();
1399 },
1400
1401 negate: function () {
1402 var rgb = [];
1403 for (var i = 0; i < 3; i++) {
1404 rgb[i] = 255 - this.values.rgb[i];
1405 }
1406 this.setValues('rgb', rgb);
1407 return this;
1408 },
1409
1410 lighten: function (ratio) {
1411 var hsl = this.values.hsl;
1412 hsl[2] += hsl[2] * ratio;
1413 this.setValues('hsl', hsl);
1414 return this;
1415 },
1416
1417 darken: function (ratio) {
1418 var hsl = this.values.hsl;
1419 hsl[2] -= hsl[2] * ratio;
1420 this.setValues('hsl', hsl);
1421 return this;
1422 },
1423
1424 saturate: function (ratio) {
1425 var hsl = this.values.hsl;
1426 hsl[1] += hsl[1] * ratio;
1427 this.setValues('hsl', hsl);
1428 return this;
1429 },
1430
1431 desaturate: function (ratio) {
1432 var hsl = this.values.hsl;
1433 hsl[1] -= hsl[1] * ratio;
1434 this.setValues('hsl', hsl);
1435 return this;
1436 },
1437
1438 whiten: function (ratio) {
1439 var hwb = this.values.hwb;
1440 hwb[1] += hwb[1] * ratio;
1441 this.setValues('hwb', hwb);
1442 return this;
1443 },
1444
1445 blacken: function (ratio) {
1446 var hwb = this.values.hwb;
1447 hwb[2] += hwb[2] * ratio;
1448 this.setValues('hwb', hwb);
1449 return this;
1450 },
1451
1452 greyscale: function () {
1453 var rgb = this.values.rgb;
1454 // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
1455 var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
1456 this.setValues('rgb', [val, val, val]);
1457 return this;
1458 },
1459
1460 clearer: function (ratio) {
1461 var alpha = this.values.alpha;
1462 this.setValues('alpha', alpha - (alpha * ratio));
1463 return this;
1464 },
1465
1466 opaquer: function (ratio) {
1467 var alpha = this.values.alpha;
1468 this.setValues('alpha', alpha + (alpha * ratio));
1469 return this;
1470 },
1471
1472 rotate: function (degrees) {
1473 var hsl = this.values.hsl;
1474 var hue = (hsl[0] + degrees) % 360;
1475 hsl[0] = hue < 0 ? 360 + hue : hue;
1476 this.setValues('hsl', hsl);
1477 return this;
1478 },
1479
1480 /**
1481 * Ported from sass implementation in C
1482 * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
1483 */
1484 mix: function (mixinColor, weight) {
1485 var color1 = this;
1486 var color2 = mixinColor;
1487 var p = weight === undefined ? 0.5 : weight;
1488
1489 var w = 2 * p - 1;
1490 var a = color1.alpha() - color2.alpha();
1491
1492 var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
1493 var w2 = 1 - w1;
1494
1495 return this
1496 .rgb(
1497 w1 * color1.red() + w2 * color2.red(),
1498 w1 * color1.green() + w2 * color2.green(),
1499 w1 * color1.blue() + w2 * color2.blue()
1500 )
1501 .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
1502 },
1503
1504 toJSON: function () {
1505 return this.rgb();
1506 },
1507
1508 clone: function () {
1509 // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
1510 // making the final build way to big to embed in Chart.js. So let's do it manually,
1511 // assuming that values to clone are 1 dimension arrays containing only numbers,
1512 // except 'alpha' which is a number.
1513 var result = new Color();
1514 var source = this.values;
1515 var target = result.values;
1516 var value, type;
1517
1518 for (var prop in source) {
1519 if (source.hasOwnProperty(prop)) {
1520 value = source[prop];
1521 type = ({}).toString.call(value);
1522 if (type === '[object Array]') {
1523 target[prop] = value.slice(0);
1524 } else if (type === '[object Number]') {
1525 target[prop] = value;
1526 } else {
1527 console.error('unexpected color value:', value);
1528 }
1529 }
1530 }
1531
1532 return result;
1533 }
1534};
1535
1536Color.prototype.spaces = {
1537 rgb: ['red', 'green', 'blue'],
1538 hsl: ['hue', 'saturation', 'lightness'],
1539 hsv: ['hue', 'saturation', 'value'],
1540 hwb: ['hue', 'whiteness', 'blackness'],
1541 cmyk: ['cyan', 'magenta', 'yellow', 'black']
1542};
1543
1544Color.prototype.maxes = {
1545 rgb: [255, 255, 255],
1546 hsl: [360, 100, 100],
1547 hsv: [360, 100, 100],
1548 hwb: [360, 100, 100],
1549 cmyk: [100, 100, 100, 100]
1550};
1551
1552Color.prototype.getValues = function (space) {
1553 var values = this.values;
1554 var vals = {};
1555
1556 for (var i = 0; i < space.length; i++) {
1557 vals[space.charAt(i)] = values[space][i];
1558 }
1559
1560 if (values.alpha !== 1) {
1561 vals.a = values.alpha;
1562 }
1563
1564 // {r: 255, g: 255, b: 255, a: 0.4}
1565 return vals;
1566};
1567
1568Color.prototype.setValues = function (space, vals) {
1569 var values = this.values;
1570 var spaces = this.spaces;
1571 var maxes = this.maxes;
1572 var alpha = 1;
1573 var i;
1574
1575 this.valid = true;
1576
1577 if (space === 'alpha') {
1578 alpha = vals;
1579 } else if (vals.length) {
1580 // [10, 10, 10]
1581 values[space] = vals.slice(0, space.length);
1582 alpha = vals[space.length];
1583 } else if (vals[space.charAt(0)] !== undefined) {
1584 // {r: 10, g: 10, b: 10}
1585 for (i = 0; i < space.length; i++) {
1586 values[space][i] = vals[space.charAt(i)];
1587 }
1588
1589 alpha = vals.a;
1590 } else if (vals[spaces[space][0]] !== undefined) {
1591 // {red: 10, green: 10, blue: 10}
1592 var chans = spaces[space];
1593
1594 for (i = 0; i < space.length; i++) {
1595 values[space][i] = vals[chans[i]];
1596 }
1597
1598 alpha = vals.alpha;
1599 }
1600
1601 values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
1602
1603 if (space === 'alpha') {
1604 return false;
1605 }
1606
1607 var capped;
1608
1609 // cap values of the space prior converting all values
1610 for (i = 0; i < space.length; i++) {
1611 capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
1612 values[space][i] = Math.round(capped);
1613 }
1614
1615 // convert to all the other color spaces
1616 for (var sname in spaces) {
1617 if (sname !== space) {
1618 values[sname] = colorConvert[space][sname](values[space]);
1619 }
1620 }
1621
1622 return true;
1623};
1624
1625Color.prototype.setSpace = function (space, args) {
1626 var vals = args[0];
1627
1628 if (vals === undefined) {
1629 // color.rgb()
1630 return this.getValues(space);
1631 }
1632
1633 // color.rgb(10, 10, 10)
1634 if (typeof vals === 'number') {
1635 vals = Array.prototype.slice.call(args);
1636 }
1637
1638 this.setValues(space, vals);
1639 return this;
1640};
1641
1642Color.prototype.setChannel = function (space, index, val) {
1643 var svalues = this.values[space];
1644 if (val === undefined) {
1645 // color.red()
1646 return svalues[index];
1647 } else if (val === svalues[index]) {
1648 // color.red(color.red())
1649 return this;
1650 }
1651
1652 // color.red(100)
1653 svalues[index] = val;
1654 this.setValues(space, svalues);
1655
1656 return this;
1657};
1658
1659if (typeof window !== 'undefined') {
1660 window.Color = Color;
1661}
1662
1663var chartjsColor = Color;
1664
1665/**
1666 * @namespace Chart.helpers
1667 */
1668var helpers = {
1669 /**
1670 * An empty function that can be used, for example, for optional callback.
1671 */
1672 noop: function() {},
1673
1674 /**
1675 * Returns a unique id, sequentially generated from a global variable.
1676 * @returns {Number}
1677 * @function
1678 */
1679 uid: (function() {
1680 var id = 0;
1681 return function() {
1682 return id++;
1683 };
1684 }()),
1685
1686 /**
1687 * Returns true if `value` is neither null nor undefined, else returns false.
1688 * @param {*} value - The value to test.
1689 * @returns {Boolean}
1690 * @since 2.7.0
1691 */
1692 isNullOrUndef: function(value) {
1693 return value === null || typeof value === 'undefined';
1694 },
1695
1696 /**
1697 * Returns true if `value` is an array (including typed arrays), else returns false.
1698 * @param {*} value - The value to test.
1699 * @returns {Boolean}
1700 * @function
1701 */
1702 isArray: function(value) {
1703 if (Array.isArray && Array.isArray(value)) {
1704 return true;
1705 }
1706 var type = Object.prototype.toString.call(value);
1707 if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
1708 return true;
1709 }
1710 return false;
1711 },
1712
1713 /**
1714 * Returns true if `value` is an object (excluding null), else returns false.
1715 * @param {*} value - The value to test.
1716 * @returns {Boolean}
1717 * @since 2.7.0
1718 */
1719 isObject: function(value) {
1720 return value !== null && Object.prototype.toString.call(value) === '[object Object]';
1721 },
1722
1723 /**
1724 * Returns true if `value` is a finite number, else returns false
1725 * @param {*} value - The value to test.
1726 * @returns {Boolean}
1727 */
1728 isFinite: function(value) {
1729 return (typeof value === 'number' || value instanceof Number) && isFinite(value);
1730 },
1731
1732 /**
1733 * Returns `value` if defined, else returns `defaultValue`.
1734 * @param {*} value - The value to return if defined.
1735 * @param {*} defaultValue - The value to return if `value` is undefined.
1736 * @returns {*}
1737 */
1738 valueOrDefault: function(value, defaultValue) {
1739 return typeof value === 'undefined' ? defaultValue : value;
1740 },
1741
1742 /**
1743 * Returns value at the given `index` in array if defined, else returns `defaultValue`.
1744 * @param {Array} value - The array to lookup for value at `index`.
1745 * @param {Number} index - The index in `value` to lookup for value.
1746 * @param {*} defaultValue - The value to return if `value[index]` is undefined.
1747 * @returns {*}
1748 */
1749 valueAtIndexOrDefault: function(value, index, defaultValue) {
1750 return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
1751 },
1752
1753 /**
1754 * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
1755 * value returned by `fn`. If `fn` is not a function, this method returns undefined.
1756 * @param {Function} fn - The function to call.
1757 * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
1758 * @param {Object} [thisArg] - The value of `this` provided for the call to `fn`.
1759 * @returns {*}
1760 */
1761 callback: function(fn, args, thisArg) {
1762 if (fn && typeof fn.call === 'function') {
1763 return fn.apply(thisArg, args);
1764 }
1765 },
1766
1767 /**
1768 * Note(SB) for performance sake, this method should only be used when loopable type
1769 * is unknown or in none intensive code (not called often and small loopable). Else
1770 * it's preferable to use a regular for() loop and save extra function calls.
1771 * @param {Object|Array} loopable - The object or array to be iterated.
1772 * @param {Function} fn - The function to call for each item.
1773 * @param {Object} [thisArg] - The value of `this` provided for the call to `fn`.
1774 * @param {Boolean} [reverse] - If true, iterates backward on the loopable.
1775 */
1776 each: function(loopable, fn, thisArg, reverse) {
1777 var i, len, keys;
1778 if (helpers.isArray(loopable)) {
1779 len = loopable.length;
1780 if (reverse) {
1781 for (i = len - 1; i >= 0; i--) {
1782 fn.call(thisArg, loopable[i], i);
1783 }
1784 } else {
1785 for (i = 0; i < len; i++) {
1786 fn.call(thisArg, loopable[i], i);
1787 }
1788 }
1789 } else if (helpers.isObject(loopable)) {
1790 keys = Object.keys(loopable);
1791 len = keys.length;
1792 for (i = 0; i < len; i++) {
1793 fn.call(thisArg, loopable[keys[i]], keys[i]);
1794 }
1795 }
1796 },
1797
1798 /**
1799 * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
1800 * @see https://stackoverflow.com/a/14853974
1801 * @param {Array} a0 - The array to compare
1802 * @param {Array} a1 - The array to compare
1803 * @returns {Boolean}
1804 */
1805 arrayEquals: function(a0, a1) {
1806 var i, ilen, v0, v1;
1807
1808 if (!a0 || !a1 || a0.length !== a1.length) {
1809 return false;
1810 }
1811
1812 for (i = 0, ilen = a0.length; i < ilen; ++i) {
1813 v0 = a0[i];
1814 v1 = a1[i];
1815
1816 if (v0 instanceof Array && v1 instanceof Array) {
1817 if (!helpers.arrayEquals(v0, v1)) {
1818 return false;
1819 }
1820 } else if (v0 !== v1) {
1821 // NOTE: two different object instances will never be equal: {x:20} != {x:20}
1822 return false;
1823 }
1824 }
1825
1826 return true;
1827 },
1828
1829 /**
1830 * Returns a deep copy of `source` without keeping references on objects and arrays.
1831 * @param {*} source - The value to clone.
1832 * @returns {*}
1833 */
1834 clone: function(source) {
1835 if (helpers.isArray(source)) {
1836 return source.map(helpers.clone);
1837 }
1838
1839 if (helpers.isObject(source)) {
1840 var target = {};
1841 var keys = Object.keys(source);
1842 var klen = keys.length;
1843 var k = 0;
1844
1845 for (; k < klen; ++k) {
1846 target[keys[k]] = helpers.clone(source[keys[k]]);
1847 }
1848
1849 return target;
1850 }
1851
1852 return source;
1853 },
1854
1855 /**
1856 * The default merger when Chart.helpers.merge is called without merger option.
1857 * Note(SB): this method is also used by configMerge and scaleMerge as fallback.
1858 * @private
1859 */
1860 _merger: function(key, target, source, options) {
1861 var tval = target[key];
1862 var sval = source[key];
1863
1864 if (helpers.isObject(tval) && helpers.isObject(sval)) {
1865 helpers.merge(tval, sval, options);
1866 } else {
1867 target[key] = helpers.clone(sval);
1868 }
1869 },
1870
1871 /**
1872 * Merges source[key] in target[key] only if target[key] is undefined.
1873 * @private
1874 */
1875 _mergerIf: function(key, target, source) {
1876 var tval = target[key];
1877 var sval = source[key];
1878
1879 if (helpers.isObject(tval) && helpers.isObject(sval)) {
1880 helpers.mergeIf(tval, sval);
1881 } else if (!target.hasOwnProperty(key)) {
1882 target[key] = helpers.clone(sval);
1883 }
1884 },
1885
1886 /**
1887 * Recursively deep copies `source` properties into `target` with the given `options`.
1888 * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
1889 * @param {Object} target - The target object in which all sources are merged into.
1890 * @param {Object|Array(Object)} source - Object(s) to merge into `target`.
1891 * @param {Object} [options] - Merging options:
1892 * @param {Function} [options.merger] - The merge method (key, target, source, options)
1893 * @returns {Object} The `target` object.
1894 */
1895 merge: function(target, source, options) {
1896 var sources = helpers.isArray(source) ? source : [source];
1897 var ilen = sources.length;
1898 var merge, i, keys, klen, k;
1899
1900 if (!helpers.isObject(target)) {
1901 return target;
1902 }
1903
1904 options = options || {};
1905 merge = options.merger || helpers._merger;
1906
1907 for (i = 0; i < ilen; ++i) {
1908 source = sources[i];
1909 if (!helpers.isObject(source)) {
1910 continue;
1911 }
1912
1913 keys = Object.keys(source);
1914 for (k = 0, klen = keys.length; k < klen; ++k) {
1915 merge(keys[k], target, source, options);
1916 }
1917 }
1918
1919 return target;
1920 },
1921
1922 /**
1923 * Recursively deep copies `source` properties into `target` *only* if not defined in target.
1924 * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
1925 * @param {Object} target - The target object in which all sources are merged into.
1926 * @param {Object|Array(Object)} source - Object(s) to merge into `target`.
1927 * @returns {Object} The `target` object.
1928 */
1929 mergeIf: function(target, source) {
1930 return helpers.merge(target, source, {merger: helpers._mergerIf});
1931 },
1932
1933 /**
1934 * Applies the contents of two or more objects together into the first object.
1935 * @param {Object} target - The target object in which all objects are merged into.
1936 * @param {Object} arg1 - Object containing additional properties to merge in target.
1937 * @param {Object} argN - Additional objects containing properties to merge in target.
1938 * @returns {Object} The `target` object.
1939 */
1940 extend: function(target) {
1941 var setFn = function(value, key) {
1942 target[key] = value;
1943 };
1944 for (var i = 1, ilen = arguments.length; i < ilen; ++i) {
1945 helpers.each(arguments[i], setFn);
1946 }
1947 return target;
1948 },
1949
1950 /**
1951 * Basic javascript inheritance based on the model created in Backbone.js
1952 */
1953 inherits: function(extensions) {
1954 var me = this;
1955 var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
1956 return me.apply(this, arguments);
1957 };
1958
1959 var Surrogate = function() {
1960 this.constructor = ChartElement;
1961 };
1962
1963 Surrogate.prototype = me.prototype;
1964 ChartElement.prototype = new Surrogate();
1965 ChartElement.extend = helpers.inherits;
1966
1967 if (extensions) {
1968 helpers.extend(ChartElement.prototype, extensions);
1969 }
1970
1971 ChartElement.__super__ = me.prototype;
1972 return ChartElement;
1973 }
1974};
1975
1976var helpers_core = helpers;
1977
1978// DEPRECATIONS
1979
1980/**
1981 * Provided for backward compatibility, use Chart.helpers.callback instead.
1982 * @function Chart.helpers.callCallback
1983 * @deprecated since version 2.6.0
1984 * @todo remove at version 3
1985 * @private
1986 */
1987helpers.callCallback = helpers.callback;
1988
1989/**
1990 * Provided for backward compatibility, use Array.prototype.indexOf instead.
1991 * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
1992 * @function Chart.helpers.indexOf
1993 * @deprecated since version 2.7.0
1994 * @todo remove at version 3
1995 * @private
1996 */
1997helpers.indexOf = function(array, item, fromIndex) {
1998 return Array.prototype.indexOf.call(array, item, fromIndex);
1999};
2000
2001/**
2002 * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
2003 * @function Chart.helpers.getValueOrDefault
2004 * @deprecated since version 2.7.0
2005 * @todo remove at version 3
2006 * @private
2007 */
2008helpers.getValueOrDefault = helpers.valueOrDefault;
2009
2010/**
2011 * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
2012 * @function Chart.helpers.getValueAtIndexOrDefault
2013 * @deprecated since version 2.7.0
2014 * @todo remove at version 3
2015 * @private
2016 */
2017helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
2018
2019/**
2020 * Easing functions adapted from Robert Penner's easing equations.
2021 * @namespace Chart.helpers.easingEffects
2022 * @see http://www.robertpenner.com/easing/
2023 */
2024var effects = {
2025 linear: function(t) {
2026 return t;
2027 },
2028
2029 easeInQuad: function(t) {
2030 return t * t;
2031 },
2032
2033 easeOutQuad: function(t) {
2034 return -t * (t - 2);
2035 },
2036
2037 easeInOutQuad: function(t) {
2038 if ((t /= 0.5) < 1) {
2039 return 0.5 * t * t;
2040 }
2041 return -0.5 * ((--t) * (t - 2) - 1);
2042 },
2043
2044 easeInCubic: function(t) {
2045 return t * t * t;
2046 },
2047
2048 easeOutCubic: function(t) {
2049 return (t = t - 1) * t * t + 1;
2050 },
2051
2052 easeInOutCubic: function(t) {
2053 if ((t /= 0.5) < 1) {
2054 return 0.5 * t * t * t;
2055 }
2056 return 0.5 * ((t -= 2) * t * t + 2);
2057 },
2058
2059 easeInQuart: function(t) {
2060 return t * t * t * t;
2061 },
2062
2063 easeOutQuart: function(t) {
2064 return -((t = t - 1) * t * t * t - 1);
2065 },
2066
2067 easeInOutQuart: function(t) {
2068 if ((t /= 0.5) < 1) {
2069 return 0.5 * t * t * t * t;
2070 }
2071 return -0.5 * ((t -= 2) * t * t * t - 2);
2072 },
2073
2074 easeInQuint: function(t) {
2075 return t * t * t * t * t;
2076 },
2077
2078 easeOutQuint: function(t) {
2079 return (t = t - 1) * t * t * t * t + 1;
2080 },
2081
2082 easeInOutQuint: function(t) {
2083 if ((t /= 0.5) < 1) {
2084 return 0.5 * t * t * t * t * t;
2085 }
2086 return 0.5 * ((t -= 2) * t * t * t * t + 2);
2087 },
2088
2089 easeInSine: function(t) {
2090 return -Math.cos(t * (Math.PI / 2)) + 1;
2091 },
2092
2093 easeOutSine: function(t) {
2094 return Math.sin(t * (Math.PI / 2));
2095 },
2096
2097 easeInOutSine: function(t) {
2098 return -0.5 * (Math.cos(Math.PI * t) - 1);
2099 },
2100
2101 easeInExpo: function(t) {
2102 return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
2103 },
2104
2105 easeOutExpo: function(t) {
2106 return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
2107 },
2108
2109 easeInOutExpo: function(t) {
2110 if (t === 0) {
2111 return 0;
2112 }
2113 if (t === 1) {
2114 return 1;
2115 }
2116 if ((t /= 0.5) < 1) {
2117 return 0.5 * Math.pow(2, 10 * (t - 1));
2118 }
2119 return 0.5 * (-Math.pow(2, -10 * --t) + 2);
2120 },
2121
2122 easeInCirc: function(t) {
2123 if (t >= 1) {
2124 return t;
2125 }
2126 return -(Math.sqrt(1 - t * t) - 1);
2127 },
2128
2129 easeOutCirc: function(t) {
2130 return Math.sqrt(1 - (t = t - 1) * t);
2131 },
2132
2133 easeInOutCirc: function(t) {
2134 if ((t /= 0.5) < 1) {
2135 return -0.5 * (Math.sqrt(1 - t * t) - 1);
2136 }
2137 return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
2138 },
2139
2140 easeInElastic: function(t) {
2141 var s = 1.70158;
2142 var p = 0;
2143 var a = 1;
2144 if (t === 0) {
2145 return 0;
2146 }
2147 if (t === 1) {
2148 return 1;
2149 }
2150 if (!p) {
2151 p = 0.3;
2152 }
2153 if (a < 1) {
2154 a = 1;
2155 s = p / 4;
2156 } else {
2157 s = p / (2 * Math.PI) * Math.asin(1 / a);
2158 }
2159 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
2160 },
2161
2162 easeOutElastic: function(t) {
2163 var s = 1.70158;
2164 var p = 0;
2165 var a = 1;
2166 if (t === 0) {
2167 return 0;
2168 }
2169 if (t === 1) {
2170 return 1;
2171 }
2172 if (!p) {
2173 p = 0.3;
2174 }
2175 if (a < 1) {
2176 a = 1;
2177 s = p / 4;
2178 } else {
2179 s = p / (2 * Math.PI) * Math.asin(1 / a);
2180 }
2181 return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
2182 },
2183
2184 easeInOutElastic: function(t) {
2185 var s = 1.70158;
2186 var p = 0;
2187 var a = 1;
2188 if (t === 0) {
2189 return 0;
2190 }
2191 if ((t /= 0.5) === 2) {
2192 return 1;
2193 }
2194 if (!p) {
2195 p = 0.45;
2196 }
2197 if (a < 1) {
2198 a = 1;
2199 s = p / 4;
2200 } else {
2201 s = p / (2 * Math.PI) * Math.asin(1 / a);
2202 }
2203 if (t < 1) {
2204 return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
2205 }
2206 return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
2207 },
2208 easeInBack: function(t) {
2209 var s = 1.70158;
2210 return t * t * ((s + 1) * t - s);
2211 },
2212
2213 easeOutBack: function(t) {
2214 var s = 1.70158;
2215 return (t = t - 1) * t * ((s + 1) * t + s) + 1;
2216 },
2217
2218 easeInOutBack: function(t) {
2219 var s = 1.70158;
2220 if ((t /= 0.5) < 1) {
2221 return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
2222 }
2223 return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
2224 },
2225
2226 easeInBounce: function(t) {
2227 return 1 - effects.easeOutBounce(1 - t);
2228 },
2229
2230 easeOutBounce: function(t) {
2231 if (t < (1 / 2.75)) {
2232 return 7.5625 * t * t;
2233 }
2234 if (t < (2 / 2.75)) {
2235 return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
2236 }
2237 if (t < (2.5 / 2.75)) {
2238 return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
2239 }
2240 return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
2241 },
2242
2243 easeInOutBounce: function(t) {
2244 if (t < 0.5) {
2245 return effects.easeInBounce(t * 2) * 0.5;
2246 }
2247 return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
2248 }
2249};
2250
2251var helpers_easing = {
2252 effects: effects
2253};
2254
2255// DEPRECATIONS
2256
2257/**
2258 * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
2259 * @function Chart.helpers.easingEffects
2260 * @deprecated since version 2.7.0
2261 * @todo remove at version 3
2262 * @private
2263 */
2264helpers_core.easingEffects = effects;
2265
2266var PI = Math.PI;
2267var RAD_PER_DEG = PI / 180;
2268var DOUBLE_PI = PI * 2;
2269var HALF_PI = PI / 2;
2270var QUARTER_PI = PI / 4;
2271var TWO_THIRDS_PI = PI * 2 / 3;
2272
2273/**
2274 * @namespace Chart.helpers.canvas
2275 */
2276var exports$1 = {
2277 /**
2278 * Clears the entire canvas associated to the given `chart`.
2279 * @param {Chart} chart - The chart for which to clear the canvas.
2280 */
2281 clear: function(chart) {
2282 chart.ctx.clearRect(0, 0, chart.width, chart.height);
2283 },
2284
2285 /**
2286 * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
2287 * given size (width, height) and the same `radius` for all corners.
2288 * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
2289 * @param {Number} x - The x axis of the coordinate for the rectangle starting point.
2290 * @param {Number} y - The y axis of the coordinate for the rectangle starting point.
2291 * @param {Number} width - The rectangle's width.
2292 * @param {Number} height - The rectangle's height.
2293 * @param {Number} radius - The rounded amount (in pixels) for the four corners.
2294 * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
2295 */
2296 roundedRect: function(ctx, x, y, width, height, radius) {
2297 if (radius) {
2298 var r = Math.min(radius, height / 2, width / 2);
2299 var left = x + r;
2300 var top = y + r;
2301 var right = x + width - r;
2302 var bottom = y + height - r;
2303
2304 ctx.moveTo(x, top);
2305 if (left < right && top < bottom) {
2306 ctx.arc(left, top, r, -PI, -HALF_PI);
2307 ctx.arc(right, top, r, -HALF_PI, 0);
2308 ctx.arc(right, bottom, r, 0, HALF_PI);
2309 ctx.arc(left, bottom, r, HALF_PI, PI);
2310 } else if (left < right) {
2311 ctx.moveTo(left, y);
2312 ctx.arc(right, top, r, -HALF_PI, HALF_PI);
2313 ctx.arc(left, top, r, HALF_PI, PI + HALF_PI);
2314 } else if (top < bottom) {
2315 ctx.arc(left, top, r, -PI, 0);
2316 ctx.arc(left, bottom, r, 0, PI);
2317 } else {
2318 ctx.arc(left, top, r, -PI, PI);
2319 }
2320 ctx.closePath();
2321 ctx.moveTo(x, y);
2322 } else {
2323 ctx.rect(x, y, width, height);
2324 }
2325 },
2326
2327 drawPoint: function(ctx, style, radius, x, y, rotation) {
2328 var type, xOffset, yOffset, size, cornerRadius;
2329 var rad = (rotation || 0) * RAD_PER_DEG;
2330
2331 if (style && typeof style === 'object') {
2332 type = style.toString();
2333 if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
2334 ctx.drawImage(style, x - style.width / 2, y - style.height / 2, style.width, style.height);
2335 return;
2336 }
2337 }
2338
2339 if (isNaN(radius) || radius <= 0) {
2340 return;
2341 }
2342
2343 ctx.beginPath();
2344
2345 switch (style) {
2346 // Default includes circle
2347 default:
2348 ctx.arc(x, y, radius, 0, DOUBLE_PI);
2349 ctx.closePath();
2350 break;
2351 case 'triangle':
2352 ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
2353 rad += TWO_THIRDS_PI;
2354 ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
2355 rad += TWO_THIRDS_PI;
2356 ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
2357 ctx.closePath();
2358 break;
2359 case 'rectRounded':
2360 // NOTE: the rounded rect implementation changed to use `arc` instead of
2361 // `quadraticCurveTo` since it generates better results when rect is
2362 // almost a circle. 0.516 (instead of 0.5) produces results with visually
2363 // closer proportion to the previous impl and it is inscribed in the
2364 // circle with `radius`. For more details, see the following PRs:
2365 // https://github.com/chartjs/Chart.js/issues/5597
2366 // https://github.com/chartjs/Chart.js/issues/5858
2367 cornerRadius = radius * 0.516;
2368 size = radius - cornerRadius;
2369 xOffset = Math.cos(rad + QUARTER_PI) * size;
2370 yOffset = Math.sin(rad + QUARTER_PI) * size;
2371 ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
2372 ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
2373 ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
2374 ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
2375 ctx.closePath();
2376 break;
2377 case 'rect':
2378 if (!rotation) {
2379 size = Math.SQRT1_2 * radius;
2380 ctx.rect(x - size, y - size, 2 * size, 2 * size);
2381 break;
2382 }
2383 rad += QUARTER_PI;
2384 /* falls through */
2385 case 'rectRot':
2386 xOffset = Math.cos(rad) * radius;
2387 yOffset = Math.sin(rad) * radius;
2388 ctx.moveTo(x - xOffset, y - yOffset);
2389 ctx.lineTo(x + yOffset, y - xOffset);
2390 ctx.lineTo(x + xOffset, y + yOffset);
2391 ctx.lineTo(x - yOffset, y + xOffset);
2392 ctx.closePath();
2393 break;
2394 case 'crossRot':
2395 rad += QUARTER_PI;
2396 /* falls through */
2397 case 'cross':
2398 xOffset = Math.cos(rad) * radius;
2399 yOffset = Math.sin(rad) * radius;
2400 ctx.moveTo(x - xOffset, y - yOffset);
2401 ctx.lineTo(x + xOffset, y + yOffset);
2402 ctx.moveTo(x + yOffset, y - xOffset);
2403 ctx.lineTo(x - yOffset, y + xOffset);
2404 break;
2405 case 'star':
2406 xOffset = Math.cos(rad) * radius;
2407 yOffset = Math.sin(rad) * radius;
2408 ctx.moveTo(x - xOffset, y - yOffset);
2409 ctx.lineTo(x + xOffset, y + yOffset);
2410 ctx.moveTo(x + yOffset, y - xOffset);
2411 ctx.lineTo(x - yOffset, y + xOffset);
2412 rad += QUARTER_PI;
2413 xOffset = Math.cos(rad) * radius;
2414 yOffset = Math.sin(rad) * radius;
2415 ctx.moveTo(x - xOffset, y - yOffset);
2416 ctx.lineTo(x + xOffset, y + yOffset);
2417 ctx.moveTo(x + yOffset, y - xOffset);
2418 ctx.lineTo(x - yOffset, y + xOffset);
2419 break;
2420 case 'line':
2421 xOffset = Math.cos(rad) * radius;
2422 yOffset = Math.sin(rad) * radius;
2423 ctx.moveTo(x - xOffset, y - yOffset);
2424 ctx.lineTo(x + xOffset, y + yOffset);
2425 break;
2426 case 'dash':
2427 ctx.moveTo(x, y);
2428 ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
2429 break;
2430 }
2431
2432 ctx.fill();
2433 ctx.stroke();
2434 },
2435
2436 /**
2437 * Returns true if the point is inside the rectangle
2438 * @param {Object} point - The point to test
2439 * @param {Object} area - The rectangle
2440 * @returns {Boolean}
2441 * @private
2442 */
2443 _isPointInArea: function(point, area) {
2444 var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
2445
2446 return point.x > area.left - epsilon && point.x < area.right + epsilon &&
2447 point.y > area.top - epsilon && point.y < area.bottom + epsilon;
2448 },
2449
2450 clipArea: function(ctx, area) {
2451 ctx.save();
2452 ctx.beginPath();
2453 ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
2454 ctx.clip();
2455 },
2456
2457 unclipArea: function(ctx) {
2458 ctx.restore();
2459 },
2460
2461 lineTo: function(ctx, previous, target, flip) {
2462 var stepped = target.steppedLine;
2463 if (stepped) {
2464 if (stepped === 'middle') {
2465 var midpoint = (previous.x + target.x) / 2.0;
2466 ctx.lineTo(midpoint, flip ? target.y : previous.y);
2467 ctx.lineTo(midpoint, flip ? previous.y : target.y);
2468 } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) {
2469 ctx.lineTo(previous.x, target.y);
2470 } else {
2471 ctx.lineTo(target.x, previous.y);
2472 }
2473 ctx.lineTo(target.x, target.y);
2474 return;
2475 }
2476
2477 if (!target.tension) {
2478 ctx.lineTo(target.x, target.y);
2479 return;
2480 }
2481
2482 ctx.bezierCurveTo(
2483 flip ? previous.controlPointPreviousX : previous.controlPointNextX,
2484 flip ? previous.controlPointPreviousY : previous.controlPointNextY,
2485 flip ? target.controlPointNextX : target.controlPointPreviousX,
2486 flip ? target.controlPointNextY : target.controlPointPreviousY,
2487 target.x,
2488 target.y);
2489 }
2490};
2491
2492var helpers_canvas = exports$1;
2493
2494// DEPRECATIONS
2495
2496/**
2497 * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
2498 * @namespace Chart.helpers.clear
2499 * @deprecated since version 2.7.0
2500 * @todo remove at version 3
2501 * @private
2502 */
2503helpers_core.clear = exports$1.clear;
2504
2505/**
2506 * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
2507 * @namespace Chart.helpers.drawRoundedRectangle
2508 * @deprecated since version 2.7.0
2509 * @todo remove at version 3
2510 * @private
2511 */
2512helpers_core.drawRoundedRectangle = function(ctx) {
2513 ctx.beginPath();
2514 exports$1.roundedRect.apply(exports$1, arguments);
2515};
2516
2517var defaults = {
2518 /**
2519 * @private
2520 */
2521 _set: function(scope, values) {
2522 return helpers_core.merge(this[scope] || (this[scope] = {}), values);
2523 }
2524};
2525
2526defaults._set('global', {
2527 defaultColor: 'rgba(0,0,0,0.1)',
2528 defaultFontColor: '#666',
2529 defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
2530 defaultFontSize: 12,
2531 defaultFontStyle: 'normal',
2532 defaultLineHeight: 1.2,
2533 showLines: true
2534});
2535
2536var core_defaults = defaults;
2537
2538var valueOrDefault = helpers_core.valueOrDefault;
2539
2540/**
2541 * Converts the given font object into a CSS font string.
2542 * @param {Object} font - A font object.
2543 * @return {String} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
2544 * @private
2545 */
2546function toFontString(font) {
2547 if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) {
2548 return null;
2549 }
2550
2551 return (font.style ? font.style + ' ' : '')
2552 + (font.weight ? font.weight + ' ' : '')
2553 + font.size + 'px '
2554 + font.family;
2555}
2556
2557/**
2558 * @alias Chart.helpers.options
2559 * @namespace
2560 */
2561var helpers_options = {
2562 /**
2563 * Converts the given line height `value` in pixels for a specific font `size`.
2564 * @param {Number|String} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
2565 * @param {Number} size - The font size (in pixels) used to resolve relative `value`.
2566 * @returns {Number} The effective line height in pixels (size * 1.2 if value is invalid).
2567 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
2568 * @since 2.7.0
2569 */
2570 toLineHeight: function(value, size) {
2571 var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
2572 if (!matches || matches[1] === 'normal') {
2573 return size * 1.2;
2574 }
2575
2576 value = +matches[2];
2577
2578 switch (matches[3]) {
2579 case 'px':
2580 return value;
2581 case '%':
2582 value /= 100;
2583 break;
2584 default:
2585 break;
2586 }
2587
2588 return size * value;
2589 },
2590
2591 /**
2592 * Converts the given value into a padding object with pre-computed width/height.
2593 * @param {Number|Object} value - If a number, set the value to all TRBL component,
2594 * else, if and object, use defined properties and sets undefined ones to 0.
2595 * @returns {Object} The padding values (top, right, bottom, left, width, height)
2596 * @since 2.7.0
2597 */
2598 toPadding: function(value) {
2599 var t, r, b, l;
2600
2601 if (helpers_core.isObject(value)) {
2602 t = +value.top || 0;
2603 r = +value.right || 0;
2604 b = +value.bottom || 0;
2605 l = +value.left || 0;
2606 } else {
2607 t = r = b = l = +value || 0;
2608 }
2609
2610 return {
2611 top: t,
2612 right: r,
2613 bottom: b,
2614 left: l,
2615 height: t + b,
2616 width: l + r
2617 };
2618 },
2619
2620 /**
2621 * Parses font options and returns the font object.
2622 * @param {Object} options - A object that contains font options to be parsed.
2623 * @return {Object} The font object.
2624 * @todo Support font.* options and renamed to toFont().
2625 * @private
2626 */
2627 _parseFont: function(options) {
2628 var globalDefaults = core_defaults.global;
2629 var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
2630 var font = {
2631 family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
2632 lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
2633 size: size,
2634 style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
2635 weight: null,
2636 string: ''
2637 };
2638
2639 font.string = toFontString(font);
2640 return font;
2641 },
2642
2643 /**
2644 * Evaluates the given `inputs` sequentially and returns the first defined value.
2645 * @param {Array[]} inputs - An array of values, falling back to the last value.
2646 * @param {Object} [context] - If defined and the current value is a function, the value
2647 * is called with `context` as first argument and the result becomes the new input.
2648 * @param {Number} [index] - If defined and the current value is an array, the value
2649 * at `index` become the new input.
2650 * @since 2.7.0
2651 */
2652 resolve: function(inputs, context, index) {
2653 var i, ilen, value;
2654
2655 for (i = 0, ilen = inputs.length; i < ilen; ++i) {
2656 value = inputs[i];
2657 if (value === undefined) {
2658 continue;
2659 }
2660 if (context !== undefined && typeof value === 'function') {
2661 value = value(context);
2662 }
2663 if (index !== undefined && helpers_core.isArray(value)) {
2664 value = value[index];
2665 }
2666 if (value !== undefined) {
2667 return value;
2668 }
2669 }
2670 }
2671};
2672
2673var helpers$1 = helpers_core;
2674var easing = helpers_easing;
2675var canvas = helpers_canvas;
2676var options = helpers_options;
2677helpers$1.easing = easing;
2678helpers$1.canvas = canvas;
2679helpers$1.options = options;
2680
2681function interpolate(start, view, model, ease) {
2682 var keys = Object.keys(model);
2683 var i, ilen, key, actual, origin, target, type, c0, c1;
2684
2685 for (i = 0, ilen = keys.length; i < ilen; ++i) {
2686 key = keys[i];
2687
2688 target = model[key];
2689
2690 // if a value is added to the model after pivot() has been called, the view
2691 // doesn't contain it, so let's initialize the view to the target value.
2692 if (!view.hasOwnProperty(key)) {
2693 view[key] = target;
2694 }
2695
2696 actual = view[key];
2697
2698 if (actual === target || key[0] === '_') {
2699 continue;
2700 }
2701
2702 if (!start.hasOwnProperty(key)) {
2703 start[key] = actual;
2704 }
2705
2706 origin = start[key];
2707
2708 type = typeof target;
2709
2710 if (type === typeof origin) {
2711 if (type === 'string') {
2712 c0 = chartjsColor(origin);
2713 if (c0.valid) {
2714 c1 = chartjsColor(target);
2715 if (c1.valid) {
2716 view[key] = c1.mix(c0, ease).rgbString();
2717 continue;
2718 }
2719 }
2720 } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) {
2721 view[key] = origin + (target - origin) * ease;
2722 continue;
2723 }
2724 }
2725
2726 view[key] = target;
2727 }
2728}
2729
2730var Element = function(configuration) {
2731 helpers$1.extend(this, configuration);
2732 this.initialize.apply(this, arguments);
2733};
2734
2735helpers$1.extend(Element.prototype, {
2736
2737 initialize: function() {
2738 this.hidden = false;
2739 },
2740
2741 pivot: function() {
2742 var me = this;
2743 if (!me._view) {
2744 me._view = helpers$1.clone(me._model);
2745 }
2746 me._start = {};
2747 return me;
2748 },
2749
2750 transition: function(ease) {
2751 var me = this;
2752 var model = me._model;
2753 var start = me._start;
2754 var view = me._view;
2755
2756 // No animation -> No Transition
2757 if (!model || ease === 1) {
2758 me._view = model;
2759 me._start = null;
2760 return me;
2761 }
2762
2763 if (!view) {
2764 view = me._view = {};
2765 }
2766
2767 if (!start) {
2768 start = me._start = {};
2769 }
2770
2771 interpolate(start, view, model, ease);
2772
2773 return me;
2774 },
2775
2776 tooltipPosition: function() {
2777 return {
2778 x: this._model.x,
2779 y: this._model.y
2780 };
2781 },
2782
2783 hasValue: function() {
2784 return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);
2785 }
2786});
2787
2788Element.extend = helpers$1.inherits;
2789
2790var core_element = Element;
2791
2792var exports$2 = core_element.extend({
2793 chart: null, // the animation associated chart instance
2794 currentStep: 0, // the current animation step
2795 numSteps: 60, // default number of steps
2796 easing: '', // the easing to use for this animation
2797 render: null, // render function used by the animation service
2798
2799 onAnimationProgress: null, // user specified callback to fire on each step of the animation
2800 onAnimationComplete: null, // user specified callback to fire when the animation finishes
2801});
2802
2803var core_animation = exports$2;
2804
2805// DEPRECATIONS
2806
2807/**
2808 * Provided for backward compatibility, use Chart.Animation instead
2809 * @prop Chart.Animation#animationObject
2810 * @deprecated since version 2.6.0
2811 * @todo remove at version 3
2812 */
2813Object.defineProperty(exports$2.prototype, 'animationObject', {
2814 get: function() {
2815 return this;
2816 }
2817});
2818
2819/**
2820 * Provided for backward compatibility, use Chart.Animation#chart instead
2821 * @prop Chart.Animation#chartInstance
2822 * @deprecated since version 2.6.0
2823 * @todo remove at version 3
2824 */
2825Object.defineProperty(exports$2.prototype, 'chartInstance', {
2826 get: function() {
2827 return this.chart;
2828 },
2829 set: function(value) {
2830 this.chart = value;
2831 }
2832});
2833
2834core_defaults._set('global', {
2835 animation: {
2836 duration: 1000,
2837 easing: 'easeOutQuart',
2838 onProgress: helpers$1.noop,
2839 onComplete: helpers$1.noop
2840 }
2841});
2842
2843var core_animations = {
2844 animations: [],
2845 request: null,
2846
2847 /**
2848 * @param {Chart} chart - The chart to animate.
2849 * @param {Chart.Animation} animation - The animation that we will animate.
2850 * @param {Number} duration - The animation duration in ms.
2851 * @param {Boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
2852 */
2853 addAnimation: function(chart, animation, duration, lazy) {
2854 var animations = this.animations;
2855 var i, ilen;
2856
2857 animation.chart = chart;
2858 animation.startTime = Date.now();
2859 animation.duration = duration;
2860
2861 if (!lazy) {
2862 chart.animating = true;
2863 }
2864
2865 for (i = 0, ilen = animations.length; i < ilen; ++i) {
2866 if (animations[i].chart === chart) {
2867 animations[i] = animation;
2868 return;
2869 }
2870 }
2871
2872 animations.push(animation);
2873
2874 // If there are no animations queued, manually kickstart a digest, for lack of a better word
2875 if (animations.length === 1) {
2876 this.requestAnimationFrame();
2877 }
2878 },
2879
2880 cancelAnimation: function(chart) {
2881 var index = helpers$1.findIndex(this.animations, function(animation) {
2882 return animation.chart === chart;
2883 });
2884
2885 if (index !== -1) {
2886 this.animations.splice(index, 1);
2887 chart.animating = false;
2888 }
2889 },
2890
2891 requestAnimationFrame: function() {
2892 var me = this;
2893 if (me.request === null) {
2894 // Skip animation frame requests until the active one is executed.
2895 // This can happen when processing mouse events, e.g. 'mousemove'
2896 // and 'mouseout' events will trigger multiple renders.
2897 me.request = helpers$1.requestAnimFrame.call(window, function() {
2898 me.request = null;
2899 me.startDigest();
2900 });
2901 }
2902 },
2903
2904 /**
2905 * @private
2906 */
2907 startDigest: function() {
2908 var me = this;
2909
2910 me.advance();
2911
2912 // Do we have more stuff to animate?
2913 if (me.animations.length > 0) {
2914 me.requestAnimationFrame();
2915 }
2916 },
2917
2918 /**
2919 * @private
2920 */
2921 advance: function() {
2922 var animations = this.animations;
2923 var animation, chart;
2924 var i = 0;
2925
2926 while (i < animations.length) {
2927 animation = animations[i];
2928 chart = animation.chart;
2929
2930 animation.currentStep = Math.floor((Date.now() - animation.startTime) / animation.duration * animation.numSteps);
2931 animation.currentStep = Math.min(animation.currentStep, animation.numSteps);
2932
2933 helpers$1.callback(animation.render, [chart, animation], chart);
2934 helpers$1.callback(animation.onAnimationProgress, [animation], chart);
2935
2936 if (animation.currentStep >= animation.numSteps) {
2937 helpers$1.callback(animation.onAnimationComplete, [animation], chart);
2938 chart.animating = false;
2939 animations.splice(i, 1);
2940 } else {
2941 ++i;
2942 }
2943 }
2944 }
2945};
2946
2947var resolve = helpers$1.options.resolve;
2948
2949var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
2950
2951/**
2952 * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
2953 * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
2954 * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
2955 */
2956function listenArrayEvents(array, listener) {
2957 if (array._chartjs) {
2958 array._chartjs.listeners.push(listener);
2959 return;
2960 }
2961
2962 Object.defineProperty(array, '_chartjs', {
2963 configurable: true,
2964 enumerable: false,
2965 value: {
2966 listeners: [listener]
2967 }
2968 });
2969
2970 arrayEvents.forEach(function(key) {
2971 var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
2972 var base = array[key];
2973
2974 Object.defineProperty(array, key, {
2975 configurable: true,
2976 enumerable: false,
2977 value: function() {
2978 var args = Array.prototype.slice.call(arguments);
2979 var res = base.apply(this, args);
2980
2981 helpers$1.each(array._chartjs.listeners, function(object) {
2982 if (typeof object[method] === 'function') {
2983 object[method].apply(object, args);
2984 }
2985 });
2986
2987 return res;
2988 }
2989 });
2990 });
2991}
2992
2993/**
2994 * Removes the given array event listener and cleanup extra attached properties (such as
2995 * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
2996 */
2997function unlistenArrayEvents(array, listener) {
2998 var stub = array._chartjs;
2999 if (!stub) {
3000 return;
3001 }
3002
3003 var listeners = stub.listeners;
3004 var index = listeners.indexOf(listener);
3005 if (index !== -1) {
3006 listeners.splice(index, 1);
3007 }
3008
3009 if (listeners.length > 0) {
3010 return;
3011 }
3012
3013 arrayEvents.forEach(function(key) {
3014 delete array[key];
3015 });
3016
3017 delete array._chartjs;
3018}
3019
3020// Base class for all dataset controllers (line, bar, etc)
3021var DatasetController = function(chart, datasetIndex) {
3022 this.initialize(chart, datasetIndex);
3023};
3024
3025helpers$1.extend(DatasetController.prototype, {
3026
3027 /**
3028 * Element type used to generate a meta dataset (e.g. Chart.element.Line).
3029 * @type {Chart.core.element}
3030 */
3031 datasetElementType: null,
3032
3033 /**
3034 * Element type used to generate a meta data (e.g. Chart.element.Point).
3035 * @type {Chart.core.element}
3036 */
3037 dataElementType: null,
3038
3039 initialize: function(chart, datasetIndex) {
3040 var me = this;
3041 me.chart = chart;
3042 me.index = datasetIndex;
3043 me.linkScales();
3044 me.addElements();
3045 },
3046
3047 updateIndex: function(datasetIndex) {
3048 this.index = datasetIndex;
3049 },
3050
3051 linkScales: function() {
3052 var me = this;
3053 var meta = me.getMeta();
3054 var dataset = me.getDataset();
3055
3056 if (meta.xAxisID === null || !(meta.xAxisID in me.chart.scales)) {
3057 meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id;
3058 }
3059 if (meta.yAxisID === null || !(meta.yAxisID in me.chart.scales)) {
3060 meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id;
3061 }
3062 },
3063
3064 getDataset: function() {
3065 return this.chart.data.datasets[this.index];
3066 },
3067
3068 getMeta: function() {
3069 return this.chart.getDatasetMeta(this.index);
3070 },
3071
3072 getScaleForId: function(scaleID) {
3073 return this.chart.scales[scaleID];
3074 },
3075
3076 reset: function() {
3077 this.update(true);
3078 },
3079
3080 /**
3081 * @private
3082 */
3083 destroy: function() {
3084 if (this._data) {
3085 unlistenArrayEvents(this._data, this);
3086 }
3087 },
3088
3089 createMetaDataset: function() {
3090 var me = this;
3091 var type = me.datasetElementType;
3092 return type && new type({
3093 _chart: me.chart,
3094 _datasetIndex: me.index
3095 });
3096 },
3097
3098 createMetaData: function(index) {
3099 var me = this;
3100 var type = me.dataElementType;
3101 return type && new type({
3102 _chart: me.chart,
3103 _datasetIndex: me.index,
3104 _index: index
3105 });
3106 },
3107
3108 addElements: function() {
3109 var me = this;
3110 var meta = me.getMeta();
3111 var data = me.getDataset().data || [];
3112 var metaData = meta.data;
3113 var i, ilen;
3114
3115 for (i = 0, ilen = data.length; i < ilen; ++i) {
3116 metaData[i] = metaData[i] || me.createMetaData(i);
3117 }
3118
3119 meta.dataset = meta.dataset || me.createMetaDataset();
3120 },
3121
3122 addElementAndReset: function(index) {
3123 var element = this.createMetaData(index);
3124 this.getMeta().data.splice(index, 0, element);
3125 this.updateElement(element, index, true);
3126 },
3127
3128 buildOrUpdateElements: function() {
3129 var me = this;
3130 var dataset = me.getDataset();
3131 var data = dataset.data || (dataset.data = []);
3132
3133 // In order to correctly handle data addition/deletion animation (an thus simulate
3134 // real-time charts), we need to monitor these data modifications and synchronize
3135 // the internal meta data accordingly.
3136 if (me._data !== data) {
3137 if (me._data) {
3138 // This case happens when the user replaced the data array instance.
3139 unlistenArrayEvents(me._data, me);
3140 }
3141
3142 listenArrayEvents(data, me);
3143 me._data = data;
3144 }
3145
3146 // Re-sync meta data in case the user replaced the data array or if we missed
3147 // any updates and so make sure that we handle number of datapoints changing.
3148 me.resyncElements();
3149 },
3150
3151 update: helpers$1.noop,
3152
3153 transition: function(easingValue) {
3154 var meta = this.getMeta();
3155 var elements = meta.data || [];
3156 var ilen = elements.length;
3157 var i = 0;
3158
3159 for (; i < ilen; ++i) {
3160 elements[i].transition(easingValue);
3161 }
3162
3163 if (meta.dataset) {
3164 meta.dataset.transition(easingValue);
3165 }
3166 },
3167
3168 draw: function() {
3169 var meta = this.getMeta();
3170 var elements = meta.data || [];
3171 var ilen = elements.length;
3172 var i = 0;
3173
3174 if (meta.dataset) {
3175 meta.dataset.draw();
3176 }
3177
3178 for (; i < ilen; ++i) {
3179 elements[i].draw();
3180 }
3181 },
3182
3183 removeHoverStyle: function(element) {
3184 helpers$1.merge(element._model, element.$previousStyle || {});
3185 delete element.$previousStyle;
3186 },
3187
3188 setHoverStyle: function(element) {
3189 var dataset = this.chart.data.datasets[element._datasetIndex];
3190 var index = element._index;
3191 var custom = element.custom || {};
3192 var model = element._model;
3193 var getHoverColor = helpers$1.getHoverColor;
3194
3195 element.$previousStyle = {
3196 backgroundColor: model.backgroundColor,
3197 borderColor: model.borderColor,
3198 borderWidth: model.borderWidth
3199 };
3200
3201 model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
3202 model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
3203 model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
3204 },
3205
3206 /**
3207 * @private
3208 */
3209 resyncElements: function() {
3210 var me = this;
3211 var meta = me.getMeta();
3212 var data = me.getDataset().data;
3213 var numMeta = meta.data.length;
3214 var numData = data.length;
3215
3216 if (numData < numMeta) {
3217 meta.data.splice(numData, numMeta - numData);
3218 } else if (numData > numMeta) {
3219 me.insertElements(numMeta, numData - numMeta);
3220 }
3221 },
3222
3223 /**
3224 * @private
3225 */
3226 insertElements: function(start, count) {
3227 for (var i = 0; i < count; ++i) {
3228 this.addElementAndReset(start + i);
3229 }
3230 },
3231
3232 /**
3233 * @private
3234 */
3235 onDataPush: function() {
3236 this.insertElements(this.getDataset().data.length - 1, arguments.length);
3237 },
3238
3239 /**
3240 * @private
3241 */
3242 onDataPop: function() {
3243 this.getMeta().data.pop();
3244 },
3245
3246 /**
3247 * @private
3248 */
3249 onDataShift: function() {
3250 this.getMeta().data.shift();
3251 },
3252
3253 /**
3254 * @private
3255 */
3256 onDataSplice: function(start, count) {
3257 this.getMeta().data.splice(start, count);
3258 this.insertElements(start, arguments.length - 2);
3259 },
3260
3261 /**
3262 * @private
3263 */
3264 onDataUnshift: function() {
3265 this.insertElements(0, arguments.length);
3266 }
3267});
3268
3269DatasetController.extend = helpers$1.inherits;
3270
3271var core_datasetController = DatasetController;
3272
3273core_defaults._set('global', {
3274 elements: {
3275 arc: {
3276 backgroundColor: core_defaults.global.defaultColor,
3277 borderColor: '#fff',
3278 borderWidth: 2,
3279 borderAlign: 'center'
3280 }
3281 }
3282});
3283
3284var element_arc = core_element.extend({
3285 inLabelRange: function(mouseX) {
3286 var vm = this._view;
3287
3288 if (vm) {
3289 return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
3290 }
3291 return false;
3292 },
3293
3294 inRange: function(chartX, chartY) {
3295 var vm = this._view;
3296
3297 if (vm) {
3298 var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY});
3299 var angle = pointRelativePosition.angle;
3300 var distance = pointRelativePosition.distance;
3301
3302 // Sanitise angle range
3303 var startAngle = vm.startAngle;
3304 var endAngle = vm.endAngle;
3305 while (endAngle < startAngle) {
3306 endAngle += 2.0 * Math.PI;
3307 }
3308 while (angle > endAngle) {
3309 angle -= 2.0 * Math.PI;
3310 }
3311 while (angle < startAngle) {
3312 angle += 2.0 * Math.PI;
3313 }
3314
3315 // Check if within the range of the open/close angle
3316 var betweenAngles = (angle >= startAngle && angle <= endAngle);
3317 var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
3318
3319 return (betweenAngles && withinRadius);
3320 }
3321 return false;
3322 },
3323
3324 getCenterPoint: function() {
3325 var vm = this._view;
3326 var halfAngle = (vm.startAngle + vm.endAngle) / 2;
3327 var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
3328 return {
3329 x: vm.x + Math.cos(halfAngle) * halfRadius,
3330 y: vm.y + Math.sin(halfAngle) * halfRadius
3331 };
3332 },
3333
3334 getArea: function() {
3335 var vm = this._view;
3336 return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
3337 },
3338
3339 tooltipPosition: function() {
3340 var vm = this._view;
3341 var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
3342 var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
3343
3344 return {
3345 x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
3346 y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
3347 };
3348 },
3349
3350 draw: function() {
3351 var ctx = this._chart.ctx;
3352 var vm = this._view;
3353 var sA = vm.startAngle;
3354 var eA = vm.endAngle;
3355 var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;
3356 var angleMargin;
3357
3358 ctx.save();
3359
3360 ctx.beginPath();
3361 ctx.arc(vm.x, vm.y, Math.max(vm.outerRadius - pixelMargin, 0), sA, eA);
3362 ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
3363 ctx.closePath();
3364
3365 ctx.fillStyle = vm.backgroundColor;
3366 ctx.fill();
3367
3368 if (vm.borderWidth) {
3369 if (vm.borderAlign === 'inner') {
3370 // Draw an inner border by cliping the arc and drawing a double-width border
3371 // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
3372 ctx.beginPath();
3373 angleMargin = pixelMargin / vm.outerRadius;
3374 ctx.arc(vm.x, vm.y, vm.outerRadius, sA - angleMargin, eA + angleMargin);
3375 if (vm.innerRadius > pixelMargin) {
3376 angleMargin = pixelMargin / vm.innerRadius;
3377 ctx.arc(vm.x, vm.y, vm.innerRadius - pixelMargin, eA + angleMargin, sA - angleMargin, true);
3378 } else {
3379 ctx.arc(vm.x, vm.y, pixelMargin, eA + Math.PI / 2, sA - Math.PI / 2);
3380 }
3381 ctx.closePath();
3382 ctx.clip();
3383
3384 ctx.beginPath();
3385 ctx.arc(vm.x, vm.y, vm.outerRadius, sA, eA);
3386 ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
3387 ctx.closePath();
3388
3389 ctx.lineWidth = vm.borderWidth * 2;
3390 ctx.lineJoin = 'round';
3391 } else {
3392 ctx.lineWidth = vm.borderWidth;
3393 ctx.lineJoin = 'bevel';
3394 }
3395
3396 ctx.strokeStyle = vm.borderColor;
3397 ctx.stroke();
3398 }
3399
3400 ctx.restore();
3401 }
3402});
3403
3404var valueOrDefault$1 = helpers$1.valueOrDefault;
3405
3406var defaultColor = core_defaults.global.defaultColor;
3407
3408core_defaults._set('global', {
3409 elements: {
3410 line: {
3411 tension: 0.4,
3412 backgroundColor: defaultColor,
3413 borderWidth: 3,
3414 borderColor: defaultColor,
3415 borderCapStyle: 'butt',
3416 borderDash: [],
3417 borderDashOffset: 0.0,
3418 borderJoinStyle: 'miter',
3419 capBezierPoints: true,
3420 fill: true, // do we fill in the area between the line and its base axis
3421 }
3422 }
3423});
3424
3425var element_line = core_element.extend({
3426 draw: function() {
3427 var me = this;
3428 var vm = me._view;
3429 var ctx = me._chart.ctx;
3430 var spanGaps = vm.spanGaps;
3431 var points = me._children.slice(); // clone array
3432 var globalDefaults = core_defaults.global;
3433 var globalOptionLineElements = globalDefaults.elements.line;
3434 var lastDrawnIndex = -1;
3435 var index, current, previous, currentVM;
3436
3437 // If we are looping, adding the first point again
3438 if (me._loop && points.length) {
3439 points.push(points[0]);
3440 }
3441
3442 ctx.save();
3443
3444 // Stroke Line Options
3445 ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
3446
3447 // IE 9 and 10 do not support line dash
3448 if (ctx.setLineDash) {
3449 ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
3450 }
3451
3452 ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
3453 ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
3454 ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth);
3455 ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
3456
3457 // Stroke Line
3458 ctx.beginPath();
3459 lastDrawnIndex = -1;
3460
3461 for (index = 0; index < points.length; ++index) {
3462 current = points[index];
3463 previous = helpers$1.previousItem(points, index);
3464 currentVM = current._view;
3465
3466 // First point moves to it's starting position no matter what
3467 if (index === 0) {
3468 if (!currentVM.skip) {
3469 ctx.moveTo(currentVM.x, currentVM.y);
3470 lastDrawnIndex = index;
3471 }
3472 } else {
3473 previous = lastDrawnIndex === -1 ? previous : points[lastDrawnIndex];
3474
3475 if (!currentVM.skip) {
3476 if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
3477 // There was a gap and this is the first point after the gap
3478 ctx.moveTo(currentVM.x, currentVM.y);
3479 } else {
3480 // Line to next point
3481 helpers$1.canvas.lineTo(ctx, previous._view, current._view);
3482 }
3483 lastDrawnIndex = index;
3484 }
3485 }
3486 }
3487
3488 ctx.stroke();
3489 ctx.restore();
3490 }
3491});
3492
3493var valueOrDefault$2 = helpers$1.valueOrDefault;
3494
3495var defaultColor$1 = core_defaults.global.defaultColor;
3496
3497core_defaults._set('global', {
3498 elements: {
3499 point: {
3500 radius: 3,
3501 pointStyle: 'circle',
3502 backgroundColor: defaultColor$1,
3503 borderColor: defaultColor$1,
3504 borderWidth: 1,
3505 // Hover
3506 hitRadius: 1,
3507 hoverRadius: 4,
3508 hoverBorderWidth: 1
3509 }
3510 }
3511});
3512
3513function xRange(mouseX) {
3514 var vm = this._view;
3515 return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
3516}
3517
3518function yRange(mouseY) {
3519 var vm = this._view;
3520 return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
3521}
3522
3523var element_point = core_element.extend({
3524 inRange: function(mouseX, mouseY) {
3525 var vm = this._view;
3526 return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
3527 },
3528
3529 inLabelRange: xRange,
3530 inXRange: xRange,
3531 inYRange: yRange,
3532
3533 getCenterPoint: function() {
3534 var vm = this._view;
3535 return {
3536 x: vm.x,
3537 y: vm.y
3538 };
3539 },
3540
3541 getArea: function() {
3542 return Math.PI * Math.pow(this._view.radius, 2);
3543 },
3544
3545 tooltipPosition: function() {
3546 var vm = this._view;
3547 return {
3548 x: vm.x,
3549 y: vm.y,
3550 padding: vm.radius + vm.borderWidth
3551 };
3552 },
3553
3554 draw: function(chartArea) {
3555 var vm = this._view;
3556 var ctx = this._chart.ctx;
3557 var pointStyle = vm.pointStyle;
3558 var rotation = vm.rotation;
3559 var radius = vm.radius;
3560 var x = vm.x;
3561 var y = vm.y;
3562 var globalDefaults = core_defaults.global;
3563 var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow
3564
3565 if (vm.skip) {
3566 return;
3567 }
3568
3569 // Clipping for Points.
3570 if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) {
3571 ctx.strokeStyle = vm.borderColor || defaultColor;
3572 ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth);
3573 ctx.fillStyle = vm.backgroundColor || defaultColor;
3574 helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
3575 }
3576 }
3577});
3578
3579var defaultColor$2 = core_defaults.global.defaultColor;
3580
3581core_defaults._set('global', {
3582 elements: {
3583 rectangle: {
3584 backgroundColor: defaultColor$2,
3585 borderColor: defaultColor$2,
3586 borderSkipped: 'bottom',
3587 borderWidth: 0
3588 }
3589 }
3590});
3591
3592function isVertical(bar) {
3593 return bar._view.width !== undefined;
3594}
3595
3596/**
3597 * Helper function to get the bounds of the bar regardless of the orientation
3598 * @param bar {Chart.Element.Rectangle} the bar
3599 * @return {Bounds} bounds of the bar
3600 * @private
3601 */
3602function getBarBounds(bar) {
3603 var vm = bar._view;
3604 var x1, x2, y1, y2;
3605
3606 if (isVertical(bar)) {
3607 // vertical
3608 var halfWidth = vm.width / 2;
3609 x1 = vm.x - halfWidth;
3610 x2 = vm.x + halfWidth;
3611 y1 = Math.min(vm.y, vm.base);
3612 y2 = Math.max(vm.y, vm.base);
3613 } else {
3614 // horizontal bar
3615 var halfHeight = vm.height / 2;
3616 x1 = Math.min(vm.x, vm.base);
3617 x2 = Math.max(vm.x, vm.base);
3618 y1 = vm.y - halfHeight;
3619 y2 = vm.y + halfHeight;
3620 }
3621
3622 return {
3623 left: x1,
3624 top: y1,
3625 right: x2,
3626 bottom: y2
3627 };
3628}
3629
3630var element_rectangle = core_element.extend({
3631 draw: function() {
3632 var ctx = this._chart.ctx;
3633 var vm = this._view;
3634 var left, right, top, bottom, signX, signY, borderSkipped;
3635 var borderWidth = vm.borderWidth;
3636
3637 if (!vm.horizontal) {
3638 // bar
3639 left = vm.x - vm.width / 2;
3640 right = vm.x + vm.width / 2;
3641 top = vm.y;
3642 bottom = vm.base;
3643 signX = 1;
3644 signY = bottom > top ? 1 : -1;
3645 borderSkipped = vm.borderSkipped || 'bottom';
3646 } else {
3647 // horizontal bar
3648 left = vm.base;
3649 right = vm.x;
3650 top = vm.y - vm.height / 2;
3651 bottom = vm.y + vm.height / 2;
3652 signX = right > left ? 1 : -1;
3653 signY = 1;
3654 borderSkipped = vm.borderSkipped || 'left';
3655 }
3656
3657 // Canvas doesn't allow us to stroke inside the width so we can
3658 // adjust the sizes to fit if we're setting a stroke on the line
3659 if (borderWidth) {
3660 // borderWidth shold be less than bar width and bar height.
3661 var barSize = Math.min(Math.abs(left - right), Math.abs(top - bottom));
3662 borderWidth = borderWidth > barSize ? barSize : borderWidth;
3663 var halfStroke = borderWidth / 2;
3664 // Adjust borderWidth when bar top position is near vm.base(zero).
3665 var borderLeft = left + (borderSkipped !== 'left' ? halfStroke * signX : 0);
3666 var borderRight = right + (borderSkipped !== 'right' ? -halfStroke * signX : 0);
3667 var borderTop = top + (borderSkipped !== 'top' ? halfStroke * signY : 0);
3668 var borderBottom = bottom + (borderSkipped !== 'bottom' ? -halfStroke * signY : 0);
3669 // not become a vertical line?
3670 if (borderLeft !== borderRight) {
3671 top = borderTop;
3672 bottom = borderBottom;
3673 }
3674 // not become a horizontal line?
3675 if (borderTop !== borderBottom) {
3676 left = borderLeft;
3677 right = borderRight;
3678 }
3679 }
3680
3681 ctx.beginPath();
3682 ctx.fillStyle = vm.backgroundColor;
3683 ctx.strokeStyle = vm.borderColor;
3684 ctx.lineWidth = borderWidth;
3685
3686 // Corner points, from bottom-left to bottom-right clockwise
3687 // | 1 2 |
3688 // | 0 3 |
3689 var corners = [
3690 [left, bottom],
3691 [left, top],
3692 [right, top],
3693 [right, bottom]
3694 ];
3695
3696 // Find first (starting) corner with fallback to 'bottom'
3697 var borders = ['bottom', 'left', 'top', 'right'];
3698 var startCorner = borders.indexOf(borderSkipped, 0);
3699 if (startCorner === -1) {
3700 startCorner = 0;
3701 }
3702
3703 function cornerAt(index) {
3704 return corners[(startCorner + index) % 4];
3705 }
3706
3707 // Draw rectangle from 'startCorner'
3708 var corner = cornerAt(0);
3709 ctx.moveTo(corner[0], corner[1]);
3710
3711 for (var i = 1; i < 4; i++) {
3712 corner = cornerAt(i);
3713 ctx.lineTo(corner[0], corner[1]);
3714 }
3715
3716 ctx.fill();
3717 if (borderWidth) {
3718 ctx.stroke();
3719 }
3720 },
3721
3722 height: function() {
3723 var vm = this._view;
3724 return vm.base - vm.y;
3725 },
3726
3727 inRange: function(mouseX, mouseY) {
3728 var inRange = false;
3729
3730 if (this._view) {
3731 var bounds = getBarBounds(this);
3732 inRange = mouseX >= bounds.left && mouseX <= bounds.right && mouseY >= bounds.top && mouseY <= bounds.bottom;
3733 }
3734
3735 return inRange;
3736 },
3737
3738 inLabelRange: function(mouseX, mouseY) {
3739 var me = this;
3740 if (!me._view) {
3741 return false;
3742 }
3743
3744 var inRange = false;
3745 var bounds = getBarBounds(me);
3746
3747 if (isVertical(me)) {
3748 inRange = mouseX >= bounds.left && mouseX <= bounds.right;
3749 } else {
3750 inRange = mouseY >= bounds.top && mouseY <= bounds.bottom;
3751 }
3752
3753 return inRange;
3754 },
3755
3756 inXRange: function(mouseX) {
3757 var bounds = getBarBounds(this);
3758 return mouseX >= bounds.left && mouseX <= bounds.right;
3759 },
3760
3761 inYRange: function(mouseY) {
3762 var bounds = getBarBounds(this);
3763 return mouseY >= bounds.top && mouseY <= bounds.bottom;
3764 },
3765
3766 getCenterPoint: function() {
3767 var vm = this._view;
3768 var x, y;
3769 if (isVertical(this)) {
3770 x = vm.x;
3771 y = (vm.y + vm.base) / 2;
3772 } else {
3773 x = (vm.x + vm.base) / 2;
3774 y = vm.y;
3775 }
3776
3777 return {x: x, y: y};
3778 },
3779
3780 getArea: function() {
3781 var vm = this._view;
3782 return vm.width * Math.abs(vm.y - vm.base);
3783 },
3784
3785 tooltipPosition: function() {
3786 var vm = this._view;
3787 return {
3788 x: vm.x,
3789 y: vm.y
3790 };
3791 }
3792});
3793
3794var elements = {};
3795var Arc = element_arc;
3796var Line = element_line;
3797var Point = element_point;
3798var Rectangle = element_rectangle;
3799elements.Arc = Arc;
3800elements.Line = Line;
3801elements.Point = Point;
3802elements.Rectangle = Rectangle;
3803
3804var resolve$1 = helpers$1.options.resolve;
3805
3806core_defaults._set('bar', {
3807 hover: {
3808 mode: 'label'
3809 },
3810
3811 scales: {
3812 xAxes: [{
3813 type: 'category',
3814 categoryPercentage: 0.8,
3815 barPercentage: 0.9,
3816 offset: true,
3817 gridLines: {
3818 offsetGridLines: true
3819 }
3820 }],
3821
3822 yAxes: [{
3823 type: 'linear'
3824 }]
3825 }
3826});
3827
3828/**
3829 * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
3830 * @private
3831 */
3832function computeMinSampleSize(scale, pixels) {
3833 var min = scale.isHorizontal() ? scale.width : scale.height;
3834 var ticks = scale.getTicks();
3835 var prev, curr, i, ilen;
3836
3837 for (i = 1, ilen = pixels.length; i < ilen; ++i) {
3838 min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
3839 }
3840
3841 for (i = 0, ilen = ticks.length; i < ilen; ++i) {
3842 curr = scale.getPixelForTick(i);
3843 min = i > 0 ? Math.min(min, curr - prev) : min;
3844 prev = curr;
3845 }
3846
3847 return min;
3848}
3849
3850/**
3851 * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
3852 * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
3853 * mode currently always generates bars equally sized (until we introduce scriptable options?).
3854 * @private
3855 */
3856function computeFitCategoryTraits(index, ruler, options) {
3857 var thickness = options.barThickness;
3858 var count = ruler.stackCount;
3859 var curr = ruler.pixels[index];
3860 var size, ratio;
3861
3862 if (helpers$1.isNullOrUndef(thickness)) {
3863 size = ruler.min * options.categoryPercentage;
3864 ratio = options.barPercentage;
3865 } else {
3866 // When bar thickness is enforced, category and bar percentages are ignored.
3867 // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
3868 // and deprecate barPercentage since this value is ignored when thickness is absolute.
3869 size = thickness * count;
3870 ratio = 1;
3871 }
3872
3873 return {
3874 chunk: size / count,
3875 ratio: ratio,
3876 start: curr - (size / 2)
3877 };
3878}
3879
3880/**
3881 * Computes an "optimal" category that globally arranges bars side by side (no gap when
3882 * percentage options are 1), based on the previous and following categories. This mode
3883 * generates bars with different widths when data are not evenly spaced.
3884 * @private
3885 */
3886function computeFlexCategoryTraits(index, ruler, options) {
3887 var pixels = ruler.pixels;
3888 var curr = pixels[index];
3889 var prev = index > 0 ? pixels[index - 1] : null;
3890 var next = index < pixels.length - 1 ? pixels[index + 1] : null;
3891 var percent = options.categoryPercentage;
3892 var start, size;
3893
3894 if (prev === null) {
3895 // first data: its size is double based on the next point or,
3896 // if it's also the last data, we use the scale size.
3897 prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
3898 }
3899
3900 if (next === null) {
3901 // last data: its size is also double based on the previous point.
3902 next = curr + curr - prev;
3903 }
3904
3905 start = curr - (curr - Math.min(prev, next)) / 2 * percent;
3906 size = Math.abs(next - prev) / 2 * percent;
3907
3908 return {
3909 chunk: size / ruler.stackCount,
3910 ratio: options.barPercentage,
3911 start: start
3912 };
3913}
3914
3915var controller_bar = core_datasetController.extend({
3916
3917 dataElementType: elements.Rectangle,
3918
3919 initialize: function() {
3920 var me = this;
3921 var meta;
3922
3923 core_datasetController.prototype.initialize.apply(me, arguments);
3924
3925 meta = me.getMeta();
3926 meta.stack = me.getDataset().stack;
3927 meta.bar = true;
3928 },
3929
3930 update: function(reset) {
3931 var me = this;
3932 var rects = me.getMeta().data;
3933 var i, ilen;
3934
3935 me._ruler = me.getRuler();
3936
3937 for (i = 0, ilen = rects.length; i < ilen; ++i) {
3938 me.updateElement(rects[i], i, reset);
3939 }
3940 },
3941
3942 updateElement: function(rectangle, index, reset) {
3943 var me = this;
3944 var meta = me.getMeta();
3945 var dataset = me.getDataset();
3946 var options = me._resolveElementOptions(rectangle, index);
3947
3948 rectangle._xScale = me.getScaleForId(meta.xAxisID);
3949 rectangle._yScale = me.getScaleForId(meta.yAxisID);
3950 rectangle._datasetIndex = me.index;
3951 rectangle._index = index;
3952 rectangle._model = {
3953 backgroundColor: options.backgroundColor,
3954 borderColor: options.borderColor,
3955 borderSkipped: options.borderSkipped,
3956 borderWidth: options.borderWidth,
3957 datasetLabel: dataset.label,
3958 label: me.chart.data.labels[index]
3959 };
3960
3961 me._updateElementGeometry(rectangle, index, reset);
3962
3963 rectangle.pivot();
3964 },
3965
3966 /**
3967 * @private
3968 */
3969 _updateElementGeometry: function(rectangle, index, reset) {
3970 var me = this;
3971 var model = rectangle._model;
3972 var vscale = me.getValueScale();
3973 var base = vscale.getBasePixel();
3974 var horizontal = vscale.isHorizontal();
3975 var ruler = me._ruler || me.getRuler();
3976 var vpixels = me.calculateBarValuePixels(me.index, index);
3977 var ipixels = me.calculateBarIndexPixels(me.index, index, ruler);
3978
3979 model.horizontal = horizontal;
3980 model.base = reset ? base : vpixels.base;
3981 model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
3982 model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
3983 model.height = horizontal ? ipixels.size : undefined;
3984 model.width = horizontal ? undefined : ipixels.size;
3985 },
3986
3987 /**
3988 * @private
3989 */
3990 getValueScaleId: function() {
3991 return this.getMeta().yAxisID;
3992 },
3993
3994 /**
3995 * @private
3996 */
3997 getIndexScaleId: function() {
3998 return this.getMeta().xAxisID;
3999 },
4000
4001 /**
4002 * @private
4003 */
4004 getValueScale: function() {
4005 return this.getScaleForId(this.getValueScaleId());
4006 },
4007
4008 /**
4009 * @private
4010 */
4011 getIndexScale: function() {
4012 return this.getScaleForId(this.getIndexScaleId());
4013 },
4014
4015 /**
4016 * Returns the stacks based on groups and bar visibility.
4017 * @param {Number} [last] - The dataset index
4018 * @returns {Array} The stack list
4019 * @private
4020 */
4021 _getStacks: function(last) {
4022 var me = this;
4023 var chart = me.chart;
4024 var scale = me.getIndexScale();
4025 var stacked = scale.options.stacked;
4026 var ilen = last === undefined ? chart.data.datasets.length : last + 1;
4027 var stacks = [];
4028 var i, meta;
4029
4030 for (i = 0; i < ilen; ++i) {
4031 meta = chart.getDatasetMeta(i);
4032 if (meta.bar && chart.isDatasetVisible(i) &&
4033 (stacked === false ||
4034 (stacked === true && stacks.indexOf(meta.stack) === -1) ||
4035 (stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) {
4036 stacks.push(meta.stack);
4037 }
4038 }
4039
4040 return stacks;
4041 },
4042
4043 /**
4044 * Returns the effective number of stacks based on groups and bar visibility.
4045 * @private
4046 */
4047 getStackCount: function() {
4048 return this._getStacks().length;
4049 },
4050
4051 /**
4052 * Returns the stack index for the given dataset based on groups and bar visibility.
4053 * @param {Number} [datasetIndex] - The dataset index
4054 * @param {String} [name] - The stack name to find
4055 * @returns {Number} The stack index
4056 * @private
4057 */
4058 getStackIndex: function(datasetIndex, name) {
4059 var stacks = this._getStacks(datasetIndex);
4060 var index = (name !== undefined)
4061 ? stacks.indexOf(name)
4062 : -1; // indexOf returns -1 if element is not present
4063
4064 return (index === -1)
4065 ? stacks.length - 1
4066 : index;
4067 },
4068
4069 /**
4070 * @private
4071 */
4072 getRuler: function() {
4073 var me = this;
4074 var scale = me.getIndexScale();
4075 var stackCount = me.getStackCount();
4076 var datasetIndex = me.index;
4077 var isHorizontal = scale.isHorizontal();
4078 var start = isHorizontal ? scale.left : scale.top;
4079 var end = start + (isHorizontal ? scale.width : scale.height);
4080 var pixels = [];
4081 var i, ilen, min;
4082
4083 for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
4084 pixels.push(scale.getPixelForValue(null, i, datasetIndex));
4085 }
4086
4087 min = helpers$1.isNullOrUndef(scale.options.barThickness)
4088 ? computeMinSampleSize(scale, pixels)
4089 : -1;
4090
4091 return {
4092 min: min,
4093 pixels: pixels,
4094 start: start,
4095 end: end,
4096 stackCount: stackCount,
4097 scale: scale
4098 };
4099 },
4100
4101 /**
4102 * Note: pixel values are not clamped to the scale area.
4103 * @private
4104 */
4105 calculateBarValuePixels: function(datasetIndex, index) {
4106 var me = this;
4107 var chart = me.chart;
4108 var meta = me.getMeta();
4109 var scale = me.getValueScale();
4110 var isHorizontal = scale.isHorizontal();
4111 var datasets = chart.data.datasets;
4112 var value = +scale.getRightValue(datasets[datasetIndex].data[index]);
4113 var minBarLength = scale.options.minBarLength;
4114 var stacked = scale.options.stacked;
4115 var stack = meta.stack;
4116 var start = 0;
4117 var i, imeta, ivalue, base, head, size;
4118
4119 if (stacked || (stacked === undefined && stack !== undefined)) {
4120 for (i = 0; i < datasetIndex; ++i) {
4121 imeta = chart.getDatasetMeta(i);
4122
4123 if (imeta.bar &&
4124 imeta.stack === stack &&
4125 imeta.controller.getValueScaleId() === scale.id &&
4126 chart.isDatasetVisible(i)) {
4127
4128 ivalue = +scale.getRightValue(datasets[i].data[index]);
4129 if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) {
4130 start += ivalue;
4131 }
4132 }
4133 }
4134 }
4135
4136 base = scale.getPixelForValue(start);
4137 head = scale.getPixelForValue(start + value);
4138 size = head - base;
4139
4140 if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
4141 size = minBarLength;
4142 if (value >= 0 && !isHorizontal || value < 0 && isHorizontal) {
4143 head = base - minBarLength;
4144 } else {
4145 head = base + minBarLength;
4146 }
4147 }
4148
4149 return {
4150 size: size,
4151 base: base,
4152 head: head,
4153 center: head + size / 2
4154 };
4155 },
4156
4157 /**
4158 * @private
4159 */
4160 calculateBarIndexPixels: function(datasetIndex, index, ruler) {
4161 var me = this;
4162 var options = ruler.scale.options;
4163 var range = options.barThickness === 'flex'
4164 ? computeFlexCategoryTraits(index, ruler, options)
4165 : computeFitCategoryTraits(index, ruler, options);
4166
4167 var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
4168 var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
4169 var size = Math.min(
4170 helpers$1.valueOrDefault(options.maxBarThickness, Infinity),
4171 range.chunk * range.ratio);
4172
4173 return {
4174 base: center - size / 2,
4175 head: center + size / 2,
4176 center: center,
4177 size: size
4178 };
4179 },
4180
4181 draw: function() {
4182 var me = this;
4183 var chart = me.chart;
4184 var scale = me.getValueScale();
4185 var rects = me.getMeta().data;
4186 var dataset = me.getDataset();
4187 var ilen = rects.length;
4188 var i = 0;
4189
4190 helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);
4191
4192 for (; i < ilen; ++i) {
4193 if (!isNaN(scale.getRightValue(dataset.data[i]))) {
4194 rects[i].draw();
4195 }
4196 }
4197
4198 helpers$1.canvas.unclipArea(chart.ctx);
4199 },
4200
4201 /**
4202 * @private
4203 */
4204 _resolveElementOptions: function(rectangle, index) {
4205 var me = this;
4206 var chart = me.chart;
4207 var datasets = chart.data.datasets;
4208 var dataset = datasets[me.index];
4209 var custom = rectangle.custom || {};
4210 var options = chart.options.elements.rectangle;
4211 var values = {};
4212 var i, ilen, key;
4213
4214 // Scriptable options
4215 var context = {
4216 chart: chart,
4217 dataIndex: index,
4218 dataset: dataset,
4219 datasetIndex: me.index
4220 };
4221
4222 var keys = [
4223 'backgroundColor',
4224 'borderColor',
4225 'borderSkipped',
4226 'borderWidth'
4227 ];
4228
4229 for (i = 0, ilen = keys.length; i < ilen; ++i) {
4230 key = keys[i];
4231 values[key] = resolve$1([
4232 custom[key],
4233 dataset[key],
4234 options[key]
4235 ], context, index);
4236 }
4237
4238 return values;
4239 }
4240});
4241
4242var valueOrDefault$3 = helpers$1.valueOrDefault;
4243var resolve$2 = helpers$1.options.resolve;
4244
4245core_defaults._set('bubble', {
4246 hover: {
4247 mode: 'single'
4248 },
4249
4250 scales: {
4251 xAxes: [{
4252 type: 'linear', // bubble should probably use a linear scale by default
4253 position: 'bottom',
4254 id: 'x-axis-0' // need an ID so datasets can reference the scale
4255 }],
4256 yAxes: [{
4257 type: 'linear',
4258 position: 'left',
4259 id: 'y-axis-0'
4260 }]
4261 },
4262
4263 tooltips: {
4264 callbacks: {
4265 title: function() {
4266 // Title doesn't make sense for scatter since we format the data as a point
4267 return '';
4268 },
4269 label: function(item, data) {
4270 var datasetLabel = data.datasets[item.datasetIndex].label || '';
4271 var dataPoint = data.datasets[item.datasetIndex].data[item.index];
4272 return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
4273 }
4274 }
4275 }
4276});
4277
4278var controller_bubble = core_datasetController.extend({
4279 /**
4280 * @protected
4281 */
4282 dataElementType: elements.Point,
4283
4284 /**
4285 * @protected
4286 */
4287 update: function(reset) {
4288 var me = this;
4289 var meta = me.getMeta();
4290 var points = meta.data;
4291
4292 // Update Points
4293 helpers$1.each(points, function(point, index) {
4294 me.updateElement(point, index, reset);
4295 });
4296 },
4297
4298 /**
4299 * @protected
4300 */
4301 updateElement: function(point, index, reset) {
4302 var me = this;
4303 var meta = me.getMeta();
4304 var custom = point.custom || {};
4305 var xScale = me.getScaleForId(meta.xAxisID);
4306 var yScale = me.getScaleForId(meta.yAxisID);
4307 var options = me._resolveElementOptions(point, index);
4308 var data = me.getDataset().data[index];
4309 var dsIndex = me.index;
4310
4311 var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
4312 var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
4313
4314 point._xScale = xScale;
4315 point._yScale = yScale;
4316 point._options = options;
4317 point._datasetIndex = dsIndex;
4318 point._index = index;
4319 point._model = {
4320 backgroundColor: options.backgroundColor,
4321 borderColor: options.borderColor,
4322 borderWidth: options.borderWidth,
4323 hitRadius: options.hitRadius,
4324 pointStyle: options.pointStyle,
4325 rotation: options.rotation,
4326 radius: reset ? 0 : options.radius,
4327 skip: custom.skip || isNaN(x) || isNaN(y),
4328 x: x,
4329 y: y,
4330 };
4331
4332 point.pivot();
4333 },
4334
4335 /**
4336 * @protected
4337 */
4338 setHoverStyle: function(point) {
4339 var model = point._model;
4340 var options = point._options;
4341 var getHoverColor = helpers$1.getHoverColor;
4342
4343 point.$previousStyle = {
4344 backgroundColor: model.backgroundColor,
4345 borderColor: model.borderColor,
4346 borderWidth: model.borderWidth,
4347 radius: model.radius
4348 };
4349
4350 model.backgroundColor = valueOrDefault$3(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
4351 model.borderColor = valueOrDefault$3(options.hoverBorderColor, getHoverColor(options.borderColor));
4352 model.borderWidth = valueOrDefault$3(options.hoverBorderWidth, options.borderWidth);
4353 model.radius = options.radius + options.hoverRadius;
4354 },
4355
4356 /**
4357 * @private
4358 */
4359 _resolveElementOptions: function(point, index) {
4360 var me = this;
4361 var chart = me.chart;
4362 var datasets = chart.data.datasets;
4363 var dataset = datasets[me.index];
4364 var custom = point.custom || {};
4365 var options = chart.options.elements.point;
4366 var data = dataset.data[index];
4367 var values = {};
4368 var i, ilen, key;
4369
4370 // Scriptable options
4371 var context = {
4372 chart: chart,
4373 dataIndex: index,
4374 dataset: dataset,
4375 datasetIndex: me.index
4376 };
4377
4378 var keys = [
4379 'backgroundColor',
4380 'borderColor',
4381 'borderWidth',
4382 'hoverBackgroundColor',
4383 'hoverBorderColor',
4384 'hoverBorderWidth',
4385 'hoverRadius',
4386 'hitRadius',
4387 'pointStyle',
4388 'rotation'
4389 ];
4390
4391 for (i = 0, ilen = keys.length; i < ilen; ++i) {
4392 key = keys[i];
4393 values[key] = resolve$2([
4394 custom[key],
4395 dataset[key],
4396 options[key]
4397 ], context, index);
4398 }
4399
4400 // Custom radius resolution
4401 values.radius = resolve$2([
4402 custom.radius,
4403 data ? data.r : undefined,
4404 dataset.radius,
4405 options.radius
4406 ], context, index);
4407
4408 return values;
4409 }
4410});
4411
4412var resolve$3 = helpers$1.options.resolve;
4413
4414core_defaults._set('doughnut', {
4415 animation: {
4416 // Boolean - Whether we animate the rotation of the Doughnut
4417 animateRotate: true,
4418 // Boolean - Whether we animate scaling the Doughnut from the centre
4419 animateScale: false
4420 },
4421 hover: {
4422 mode: 'single'
4423 },
4424 legendCallback: function(chart) {
4425 var text = [];
4426 text.push('<ul class="' + chart.id + '-legend">');
4427
4428 var data = chart.data;
4429 var datasets = data.datasets;
4430 var labels = data.labels;
4431
4432 if (datasets.length) {
4433 for (var i = 0; i < datasets[0].data.length; ++i) {
4434 text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
4435 if (labels[i]) {
4436 text.push(labels[i]);
4437 }
4438 text.push('</li>');
4439 }
4440 }
4441
4442 text.push('</ul>');
4443 return text.join('');
4444 },
4445 legend: {
4446 labels: {
4447 generateLabels: function(chart) {
4448 var data = chart.data;
4449 if (data.labels.length && data.datasets.length) {
4450 return data.labels.map(function(label, i) {
4451 var meta = chart.getDatasetMeta(0);
4452 var ds = data.datasets[0];
4453 var arc = meta.data[i];
4454 var custom = arc && arc.custom || {};
4455 var arcOpts = chart.options.elements.arc;
4456 var fill = resolve$3([custom.backgroundColor, ds.backgroundColor, arcOpts.backgroundColor], undefined, i);
4457 var stroke = resolve$3([custom.borderColor, ds.borderColor, arcOpts.borderColor], undefined, i);
4458 var bw = resolve$3([custom.borderWidth, ds.borderWidth, arcOpts.borderWidth], undefined, i);
4459
4460 return {
4461 text: label,
4462 fillStyle: fill,
4463 strokeStyle: stroke,
4464 lineWidth: bw,
4465 hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
4466
4467 // Extra data used for toggling the correct item
4468 index: i
4469 };
4470 });
4471 }
4472 return [];
4473 }
4474 },
4475
4476 onClick: function(e, legendItem) {
4477 var index = legendItem.index;
4478 var chart = this.chart;
4479 var i, ilen, meta;
4480
4481 for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
4482 meta = chart.getDatasetMeta(i);
4483 // toggle visibility of index if exists
4484 if (meta.data[index]) {
4485 meta.data[index].hidden = !meta.data[index].hidden;
4486 }
4487 }
4488
4489 chart.update();
4490 }
4491 },
4492
4493 // The percentage of the chart that we cut out of the middle.
4494 cutoutPercentage: 50,
4495
4496 // The rotation of the chart, where the first data arc begins.
4497 rotation: Math.PI * -0.5,
4498
4499 // The total circumference of the chart.
4500 circumference: Math.PI * 2.0,
4501
4502 // Need to override these to give a nice default
4503 tooltips: {
4504 callbacks: {
4505 title: function() {
4506 return '';
4507 },
4508 label: function(tooltipItem, data) {
4509 var dataLabel = data.labels[tooltipItem.index];
4510 var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
4511
4512 if (helpers$1.isArray(dataLabel)) {
4513 // show value on first line of multiline label
4514 // need to clone because we are changing the value
4515 dataLabel = dataLabel.slice();
4516 dataLabel[0] += value;
4517 } else {
4518 dataLabel += value;
4519 }
4520
4521 return dataLabel;
4522 }
4523 }
4524 }
4525});
4526
4527var controller_doughnut = core_datasetController.extend({
4528
4529 dataElementType: elements.Arc,
4530
4531 linkScales: helpers$1.noop,
4532
4533 // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
4534 getRingIndex: function(datasetIndex) {
4535 var ringIndex = 0;
4536
4537 for (var j = 0; j < datasetIndex; ++j) {
4538 if (this.chart.isDatasetVisible(j)) {
4539 ++ringIndex;
4540 }
4541 }
4542
4543 return ringIndex;
4544 },
4545
4546 update: function(reset) {
4547 var me = this;
4548 var chart = me.chart;
4549 var chartArea = chart.chartArea;
4550 var opts = chart.options;
4551 var availableWidth = chartArea.right - chartArea.left;
4552 var availableHeight = chartArea.bottom - chartArea.top;
4553 var minSize = Math.min(availableWidth, availableHeight);
4554 var offset = {x: 0, y: 0};
4555 var meta = me.getMeta();
4556 var arcs = meta.data;
4557 var cutoutPercentage = opts.cutoutPercentage;
4558 var circumference = opts.circumference;
4559 var i, ilen;
4560
4561 // If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc
4562 if (circumference < Math.PI * 2.0) {
4563 var startAngle = opts.rotation % (Math.PI * 2.0);
4564 startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0);
4565 var endAngle = startAngle + circumference;
4566 var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)};
4567 var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)};
4568 var contains0 = (startAngle <= 0 && endAngle >= 0) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle);
4569 var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle);
4570 var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle);
4571 var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle);
4572 var cutout = cutoutPercentage / 100.0;
4573 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))};
4574 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))};
4575 var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5};
4576 minSize = Math.min(availableWidth / size.width, availableHeight / size.height);
4577 offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5};
4578 }
4579
4580 for (i = 0, ilen = arcs.length; i < ilen; ++i) {
4581 arcs[i]._options = me._resolveElementOptions(arcs[i], i);
4582 }
4583
4584 chart.borderWidth = me.getMaxBorderWidth();
4585 chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0);
4586 chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0);
4587 chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
4588 chart.offsetX = offset.x * chart.outerRadius;
4589 chart.offsetY = offset.y * chart.outerRadius;
4590
4591 meta.total = me.calculateTotal();
4592
4593 me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index));
4594 me.innerRadius = Math.max(me.outerRadius - chart.radiusLength, 0);
4595
4596 for (i = 0, ilen = arcs.length; i < ilen; ++i) {
4597 me.updateElement(arcs[i], i, reset);
4598 }
4599 },
4600
4601 updateElement: function(arc, index, reset) {
4602 var me = this;
4603 var chart = me.chart;
4604 var chartArea = chart.chartArea;
4605 var opts = chart.options;
4606 var animationOpts = opts.animation;
4607 var centerX = (chartArea.left + chartArea.right) / 2;
4608 var centerY = (chartArea.top + chartArea.bottom) / 2;
4609 var startAngle = opts.rotation; // non reset case handled later
4610 var endAngle = opts.rotation; // non reset case handled later
4611 var dataset = me.getDataset();
4612 var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI));
4613 var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
4614 var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
4615 var options = arc._options || {};
4616
4617 helpers$1.extend(arc, {
4618 // Utility
4619 _datasetIndex: me.index,
4620 _index: index,
4621
4622 // Desired view properties
4623 _model: {
4624 backgroundColor: options.backgroundColor,
4625 borderColor: options.borderColor,
4626 borderWidth: options.borderWidth,
4627 borderAlign: options.borderAlign,
4628 x: centerX + chart.offsetX,
4629 y: centerY + chart.offsetY,
4630 startAngle: startAngle,
4631 endAngle: endAngle,
4632 circumference: circumference,
4633 outerRadius: outerRadius,
4634 innerRadius: innerRadius,
4635 label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
4636 }
4637 });
4638
4639 var model = arc._model;
4640
4641 // Set correct angles if not resetting
4642 if (!reset || !animationOpts.animateRotate) {
4643 if (index === 0) {
4644 model.startAngle = opts.rotation;
4645 } else {
4646 model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
4647 }
4648
4649 model.endAngle = model.startAngle + model.circumference;
4650 }
4651
4652 arc.pivot();
4653 },
4654
4655 calculateTotal: function() {
4656 var dataset = this.getDataset();
4657 var meta = this.getMeta();
4658 var total = 0;
4659 var value;
4660
4661 helpers$1.each(meta.data, function(element, index) {
4662 value = dataset.data[index];
4663 if (!isNaN(value) && !element.hidden) {
4664 total += Math.abs(value);
4665 }
4666 });
4667
4668 /* if (total === 0) {
4669 total = NaN;
4670 }*/
4671
4672 return total;
4673 },
4674
4675 calculateCircumference: function(value) {
4676 var total = this.getMeta().total;
4677 if (total > 0 && !isNaN(value)) {
4678 return (Math.PI * 2.0) * (Math.abs(value) / total);
4679 }
4680 return 0;
4681 },
4682
4683 // gets the max border or hover width to properly scale pie charts
4684 getMaxBorderWidth: function(arcs) {
4685 var me = this;
4686 var max = 0;
4687 var chart = me.chart;
4688 var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
4689
4690 if (!arcs) {
4691 // Find the outmost visible dataset
4692 for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
4693 if (chart.isDatasetVisible(i)) {
4694 meta = chart.getDatasetMeta(i);
4695 arcs = meta.data;
4696 if (i !== me.index) {
4697 controller = meta.controller;
4698 }
4699 break;
4700 }
4701 }
4702 }
4703
4704 if (!arcs) {
4705 return 0;
4706 }
4707
4708 for (i = 0, ilen = arcs.length; i < ilen; ++i) {
4709 arc = arcs[i];
4710 options = controller ? controller._resolveElementOptions(arc, i) : arc._options;
4711 if (options.borderAlign !== 'inner') {
4712 borderWidth = options.borderWidth;
4713 hoverWidth = options.hoverBorderWidth;
4714
4715 max = borderWidth > max ? borderWidth : max;
4716 max = hoverWidth > max ? hoverWidth : max;
4717 }
4718 }
4719 return max;
4720 },
4721
4722 /**
4723 * @protected
4724 */
4725 setHoverStyle: function(arc) {
4726 var model = arc._model;
4727 var options = arc._options;
4728 var getHoverColor = helpers$1.getHoverColor;
4729 var valueOrDefault = helpers$1.valueOrDefault;
4730
4731 arc.$previousStyle = {
4732 backgroundColor: model.backgroundColor,
4733 borderColor: model.borderColor,
4734 borderWidth: model.borderWidth,
4735 };
4736
4737 model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
4738 model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
4739 model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
4740 },
4741
4742 /**
4743 * @private
4744 */
4745 _resolveElementOptions: function(arc, index) {
4746 var me = this;
4747 var chart = me.chart;
4748 var dataset = me.getDataset();
4749 var custom = arc.custom || {};
4750 var options = chart.options.elements.arc;
4751 var values = {};
4752 var i, ilen, key;
4753
4754 // Scriptable options
4755 var context = {
4756 chart: chart,
4757 dataIndex: index,
4758 dataset: dataset,
4759 datasetIndex: me.index
4760 };
4761
4762 var keys = [
4763 'backgroundColor',
4764 'borderColor',
4765 'borderWidth',
4766 'borderAlign',
4767 'hoverBackgroundColor',
4768 'hoverBorderColor',
4769 'hoverBorderWidth',
4770 ];
4771
4772 for (i = 0, ilen = keys.length; i < ilen; ++i) {
4773 key = keys[i];
4774 values[key] = resolve$3([
4775 custom[key],
4776 dataset[key],
4777 options[key]
4778 ], context, index);
4779 }
4780
4781 return values;
4782 }
4783});
4784
4785core_defaults._set('horizontalBar', {
4786 hover: {
4787 mode: 'index',
4788 axis: 'y'
4789 },
4790
4791 scales: {
4792 xAxes: [{
4793 type: 'linear',
4794 position: 'bottom'
4795 }],
4796
4797 yAxes: [{
4798 type: 'category',
4799 position: 'left',
4800 categoryPercentage: 0.8,
4801 barPercentage: 0.9,
4802 offset: true,
4803 gridLines: {
4804 offsetGridLines: true
4805 }
4806 }]
4807 },
4808
4809 elements: {
4810 rectangle: {
4811 borderSkipped: 'left'
4812 }
4813 },
4814
4815 tooltips: {
4816 callbacks: {
4817 title: function(item, data) {
4818 // Pick first xLabel for now
4819 var title = '';
4820
4821 if (item.length > 0) {
4822 if (item[0].yLabel) {
4823 title = item[0].yLabel;
4824 } else if (data.labels.length > 0 && item[0].index < data.labels.length) {
4825 title = data.labels[item[0].index];
4826 }
4827 }
4828
4829 return title;
4830 },
4831
4832 label: function(item, data) {
4833 var datasetLabel = data.datasets[item.datasetIndex].label || '';
4834 return datasetLabel + ': ' + item.xLabel;
4835 }
4836 },
4837 mode: 'index',
4838 axis: 'y'
4839 }
4840});
4841
4842var controller_horizontalBar = controller_bar.extend({
4843 /**
4844 * @private
4845 */
4846 getValueScaleId: function() {
4847 return this.getMeta().xAxisID;
4848 },
4849
4850 /**
4851 * @private
4852 */
4853 getIndexScaleId: function() {
4854 return this.getMeta().yAxisID;
4855 }
4856});
4857
4858var valueOrDefault$4 = helpers$1.valueOrDefault;
4859var resolve$4 = helpers$1.options.resolve;
4860var isPointInArea = helpers$1.canvas._isPointInArea;
4861
4862core_defaults._set('line', {
4863 showLines: true,
4864 spanGaps: false,
4865
4866 hover: {
4867 mode: 'label'
4868 },
4869
4870 scales: {
4871 xAxes: [{
4872 type: 'category',
4873 id: 'x-axis-0'
4874 }],
4875 yAxes: [{
4876 type: 'linear',
4877 id: 'y-axis-0'
4878 }]
4879 }
4880});
4881
4882function lineEnabled(dataset, options) {
4883 return valueOrDefault$4(dataset.showLine, options.showLines);
4884}
4885
4886var controller_line = core_datasetController.extend({
4887
4888 datasetElementType: elements.Line,
4889
4890 dataElementType: elements.Point,
4891
4892 update: function(reset) {
4893 var me = this;
4894 var meta = me.getMeta();
4895 var line = meta.dataset;
4896 var points = meta.data || [];
4897 var options = me.chart.options;
4898 var lineElementOptions = options.elements.line;
4899 var scale = me.getScaleForId(meta.yAxisID);
4900 var i, ilen, custom;
4901 var dataset = me.getDataset();
4902 var showLine = lineEnabled(dataset, options);
4903
4904 // Update Line
4905 if (showLine) {
4906 custom = line.custom || {};
4907
4908 // Compatibility: If the properties are defined with only the old name, use those values
4909 if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
4910 dataset.lineTension = dataset.tension;
4911 }
4912
4913 // Utility
4914 line._scale = scale;
4915 line._datasetIndex = me.index;
4916 // Data
4917 line._children = points;
4918 // Model
4919 line._model = {
4920 // Appearance
4921 // The default behavior of lines is to break at null values, according
4922 // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
4923 // This option gives lines the ability to span gaps
4924 spanGaps: valueOrDefault$4(dataset.spanGaps, options.spanGaps),
4925 tension: resolve$4([custom.tension, dataset.lineTension, lineElementOptions.tension]),
4926 backgroundColor: resolve$4([custom.backgroundColor, dataset.backgroundColor, lineElementOptions.backgroundColor]),
4927 borderWidth: resolve$4([custom.borderWidth, dataset.borderWidth, lineElementOptions.borderWidth]),
4928 borderColor: resolve$4([custom.borderColor, dataset.borderColor, lineElementOptions.borderColor]),
4929 borderCapStyle: resolve$4([custom.borderCapStyle, dataset.borderCapStyle, lineElementOptions.borderCapStyle]),
4930 borderDash: resolve$4([custom.borderDash, dataset.borderDash, lineElementOptions.borderDash]),
4931 borderDashOffset: resolve$4([custom.borderDashOffset, dataset.borderDashOffset, lineElementOptions.borderDashOffset]),
4932 borderJoinStyle: resolve$4([custom.borderJoinStyle, dataset.borderJoinStyle, lineElementOptions.borderJoinStyle]),
4933 fill: resolve$4([custom.fill, dataset.fill, lineElementOptions.fill]),
4934 steppedLine: resolve$4([custom.steppedLine, dataset.steppedLine, lineElementOptions.stepped]),
4935 cubicInterpolationMode: resolve$4([custom.cubicInterpolationMode, dataset.cubicInterpolationMode, lineElementOptions.cubicInterpolationMode]),
4936 };
4937
4938 line.pivot();
4939 }
4940
4941 // Update Points
4942 for (i = 0, ilen = points.length; i < ilen; ++i) {
4943 me.updateElement(points[i], i, reset);
4944 }
4945
4946 if (showLine && line._model.tension !== 0) {
4947 me.updateBezierControlPoints();
4948 }
4949
4950 // Now pivot the point for animation
4951 for (i = 0, ilen = points.length; i < ilen; ++i) {
4952 points[i].pivot();
4953 }
4954 },
4955
4956 updateElement: function(point, index, reset) {
4957 var me = this;
4958 var meta = me.getMeta();
4959 var custom = point.custom || {};
4960 var dataset = me.getDataset();
4961 var datasetIndex = me.index;
4962 var value = dataset.data[index];
4963 var yScale = me.getScaleForId(meta.yAxisID);
4964 var xScale = me.getScaleForId(meta.xAxisID);
4965 var x, y;
4966
4967 var options = me._resolveElementOptions(point, index);
4968
4969 x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
4970 y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
4971
4972 // Utility
4973 point._xScale = xScale;
4974 point._yScale = yScale;
4975 point._options = options;
4976 point._datasetIndex = datasetIndex;
4977 point._index = index;
4978
4979 // Desired view properties
4980 point._model = {
4981 x: x,
4982 y: y,
4983 skip: custom.skip || isNaN(x) || isNaN(y),
4984 // Appearance
4985 radius: options.radius,
4986 pointStyle: options.pointStyle,
4987 rotation: options.rotation,
4988 backgroundColor: options.backgroundColor,
4989 borderColor: options.borderColor,
4990 borderWidth: options.borderWidth,
4991 tension: meta.dataset._model ? meta.dataset._model.tension : 0,
4992 steppedLine: meta.dataset._model ? meta.dataset._model.steppedLine : false,
4993 // Tooltip
4994 hitRadius: options.hitRadius,
4995 };
4996 },
4997
4998 /**
4999 * @private
5000 */
5001 _resolveElementOptions: function(point, index) {
5002 var me = this;
5003 var chart = me.chart;
5004 var datasets = chart.data.datasets;
5005 var dataset = datasets[me.index];
5006 var custom = point.custom || {};
5007 var options = chart.options.elements.point;
5008 var values = {};
5009 var i, ilen, key;
5010
5011 // Scriptable options
5012 var context = {
5013 chart: chart,
5014 dataIndex: index,
5015 dataset: dataset,
5016 datasetIndex: me.index
5017 };
5018
5019 var ELEMENT_OPTIONS = {
5020 backgroundColor: 'pointBackgroundColor',
5021 borderColor: 'pointBorderColor',
5022 borderWidth: 'pointBorderWidth',
5023 hitRadius: 'pointHitRadius',
5024 hoverBackgroundColor: 'pointHoverBackgroundColor',
5025 hoverBorderColor: 'pointHoverBorderColor',
5026 hoverBorderWidth: 'pointHoverBorderWidth',
5027 hoverRadius: 'pointHoverRadius',
5028 pointStyle: 'pointStyle',
5029 radius: 'pointRadius',
5030 rotation: 'pointRotation',
5031 };
5032 var keys = Object.keys(ELEMENT_OPTIONS);
5033
5034 for (i = 0, ilen = keys.length; i < ilen; ++i) {
5035 key = keys[i];
5036 values[key] = resolve$4([
5037 custom[key],
5038 dataset[ELEMENT_OPTIONS[key]],
5039 dataset[key],
5040 options[key]
5041 ], context, index);
5042 }
5043
5044 return values;
5045 },
5046
5047 calculatePointY: function(value, index, datasetIndex) {
5048 var me = this;
5049 var chart = me.chart;
5050 var meta = me.getMeta();
5051 var yScale = me.getScaleForId(meta.yAxisID);
5052 var sumPos = 0;
5053 var sumNeg = 0;
5054 var i, ds, dsMeta;
5055
5056 if (yScale.options.stacked) {
5057 for (i = 0; i < datasetIndex; i++) {
5058 ds = chart.data.datasets[i];
5059 dsMeta = chart.getDatasetMeta(i);
5060 if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) {
5061 var stackedRightValue = Number(yScale.getRightValue(ds.data[index]));
5062 if (stackedRightValue < 0) {
5063 sumNeg += stackedRightValue || 0;
5064 } else {
5065 sumPos += stackedRightValue || 0;
5066 }
5067 }
5068 }
5069
5070 var rightValue = Number(yScale.getRightValue(value));
5071 if (rightValue < 0) {
5072 return yScale.getPixelForValue(sumNeg + rightValue);
5073 }
5074 return yScale.getPixelForValue(sumPos + rightValue);
5075 }
5076
5077 return yScale.getPixelForValue(value);
5078 },
5079
5080 updateBezierControlPoints: function() {
5081 var me = this;
5082 var chart = me.chart;
5083 var meta = me.getMeta();
5084 var lineModel = meta.dataset._model;
5085 var area = chart.chartArea;
5086 var points = meta.data || [];
5087 var i, ilen, point, model, controlPoints;
5088
5089 // Only consider points that are drawn in case the spanGaps option is used
5090 if (lineModel.spanGaps) {
5091 points = points.filter(function(pt) {
5092 return !pt._model.skip;
5093 });
5094 }
5095
5096 function capControlPoint(pt, min, max) {
5097 return Math.max(Math.min(pt, max), min);
5098 }
5099
5100 if (lineModel.cubicInterpolationMode === 'monotone') {
5101 helpers$1.splineCurveMonotone(points);
5102 } else {
5103 for (i = 0, ilen = points.length; i < ilen; ++i) {
5104 point = points[i];
5105 model = point._model;
5106 controlPoints = helpers$1.splineCurve(
5107 helpers$1.previousItem(points, i)._model,
5108 model,
5109 helpers$1.nextItem(points, i)._model,
5110 lineModel.tension
5111 );
5112 model.controlPointPreviousX = controlPoints.previous.x;
5113 model.controlPointPreviousY = controlPoints.previous.y;
5114 model.controlPointNextX = controlPoints.next.x;
5115 model.controlPointNextY = controlPoints.next.y;
5116 }
5117 }
5118
5119 if (chart.options.elements.line.capBezierPoints) {
5120 for (i = 0, ilen = points.length; i < ilen; ++i) {
5121 model = points[i]._model;
5122 if (isPointInArea(model, area)) {
5123 if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
5124 model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
5125 model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
5126 }
5127 if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
5128 model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
5129 model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
5130 }
5131 }
5132 }
5133 }
5134 },
5135
5136 draw: function() {
5137 var me = this;
5138 var chart = me.chart;
5139 var meta = me.getMeta();
5140 var points = meta.data || [];
5141 var area = chart.chartArea;
5142 var ilen = points.length;
5143 var halfBorderWidth;
5144 var i = 0;
5145
5146 if (lineEnabled(me.getDataset(), chart.options)) {
5147 halfBorderWidth = (meta.dataset._model.borderWidth || 0) / 2;
5148
5149 helpers$1.canvas.clipArea(chart.ctx, {
5150 left: area.left,
5151 right: area.right,
5152 top: area.top - halfBorderWidth,
5153 bottom: area.bottom + halfBorderWidth
5154 });
5155
5156 meta.dataset.draw();
5157
5158 helpers$1.canvas.unclipArea(chart.ctx);
5159 }
5160
5161 // Draw the points
5162 for (; i < ilen; ++i) {
5163 points[i].draw(area);
5164 }
5165 },
5166
5167 /**
5168 * @protected
5169 */
5170 setHoverStyle: function(point) {
5171 var model = point._model;
5172 var options = point._options;
5173 var getHoverColor = helpers$1.getHoverColor;
5174
5175 point.$previousStyle = {
5176 backgroundColor: model.backgroundColor,
5177 borderColor: model.borderColor,
5178 borderWidth: model.borderWidth,
5179 radius: model.radius
5180 };
5181
5182 model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
5183 model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor));
5184 model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth);
5185 model.radius = valueOrDefault$4(options.hoverRadius, options.radius);
5186 },
5187});
5188
5189var resolve$5 = helpers$1.options.resolve;
5190
5191core_defaults._set('polarArea', {
5192 scale: {
5193 type: 'radialLinear',
5194 angleLines: {
5195 display: false
5196 },
5197 gridLines: {
5198 circular: true
5199 },
5200 pointLabels: {
5201 display: false
5202 },
5203 ticks: {
5204 beginAtZero: true
5205 }
5206 },
5207
5208 // Boolean - Whether to animate the rotation of the chart
5209 animation: {
5210 animateRotate: true,
5211 animateScale: true
5212 },
5213
5214 startAngle: -0.5 * Math.PI,
5215 legendCallback: function(chart) {
5216 var text = [];
5217 text.push('<ul class="' + chart.id + '-legend">');
5218
5219 var data = chart.data;
5220 var datasets = data.datasets;
5221 var labels = data.labels;
5222
5223 if (datasets.length) {
5224 for (var i = 0; i < datasets[0].data.length; ++i) {
5225 text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
5226 if (labels[i]) {
5227 text.push(labels[i]);
5228 }
5229 text.push('</li>');
5230 }
5231 }
5232
5233 text.push('</ul>');
5234 return text.join('');
5235 },
5236 legend: {
5237 labels: {
5238 generateLabels: function(chart) {
5239 var data = chart.data;
5240 if (data.labels.length && data.datasets.length) {
5241 return data.labels.map(function(label, i) {
5242 var meta = chart.getDatasetMeta(0);
5243 var ds = data.datasets[0];
5244 var arc = meta.data[i];
5245 var custom = arc.custom || {};
5246 var arcOpts = chart.options.elements.arc;
5247 var fill = resolve$5([custom.backgroundColor, ds.backgroundColor, arcOpts.backgroundColor], undefined, i);
5248 var stroke = resolve$5([custom.borderColor, ds.borderColor, arcOpts.borderColor], undefined, i);
5249 var bw = resolve$5([custom.borderWidth, ds.borderWidth, arcOpts.borderWidth], undefined, i);
5250
5251 return {
5252 text: label,
5253 fillStyle: fill,
5254 strokeStyle: stroke,
5255 lineWidth: bw,
5256 hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
5257
5258 // Extra data used for toggling the correct item
5259 index: i
5260 };
5261 });
5262 }
5263 return [];
5264 }
5265 },
5266
5267 onClick: function(e, legendItem) {
5268 var index = legendItem.index;
5269 var chart = this.chart;
5270 var i, ilen, meta;
5271
5272 for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
5273 meta = chart.getDatasetMeta(i);
5274 meta.data[index].hidden = !meta.data[index].hidden;
5275 }
5276
5277 chart.update();
5278 }
5279 },
5280
5281 // Need to override these to give a nice default
5282 tooltips: {
5283 callbacks: {
5284 title: function() {
5285 return '';
5286 },
5287 label: function(item, data) {
5288 return data.labels[item.index] + ': ' + item.yLabel;
5289 }
5290 }
5291 }
5292});
5293
5294var controller_polarArea = core_datasetController.extend({
5295
5296 dataElementType: elements.Arc,
5297
5298 linkScales: helpers$1.noop,
5299
5300 update: function(reset) {
5301 var me = this;
5302 var dataset = me.getDataset();
5303 var meta = me.getMeta();
5304 var start = me.chart.options.startAngle || 0;
5305 var starts = me._starts = [];
5306 var angles = me._angles = [];
5307 var arcs = meta.data;
5308 var i, ilen, angle;
5309
5310 me._updateRadius();
5311
5312 meta.count = me.countVisibleElements();
5313
5314 for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
5315 starts[i] = start;
5316 angle = me._computeAngle(i);
5317 angles[i] = angle;
5318 start += angle;
5319 }
5320
5321 for (i = 0, ilen = arcs.length; i < ilen; ++i) {
5322 arcs[i]._options = me._resolveElementOptions(arcs[i], i);
5323 me.updateElement(arcs[i], i, reset);
5324 }
5325 },
5326
5327 /**
5328 * @private
5329 */
5330 _updateRadius: function() {
5331 var me = this;
5332 var chart = me.chart;
5333 var chartArea = chart.chartArea;
5334 var opts = chart.options;
5335 var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
5336
5337 chart.outerRadius = Math.max(minSize / 2, 0);
5338 chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
5339 chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
5340
5341 me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
5342 me.innerRadius = me.outerRadius - chart.radiusLength;
5343 },
5344
5345 updateElement: function(arc, index, reset) {
5346 var me = this;
5347 var chart = me.chart;
5348 var dataset = me.getDataset();
5349 var opts = chart.options;
5350 var animationOpts = opts.animation;
5351 var scale = chart.scale;
5352 var labels = chart.data.labels;
5353
5354 var centerX = scale.xCenter;
5355 var centerY = scale.yCenter;
5356
5357 // var negHalfPI = -0.5 * Math.PI;
5358 var datasetStartAngle = opts.startAngle;
5359 var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
5360 var startAngle = me._starts[index];
5361 var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
5362
5363 var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
5364 var options = arc._options || {};
5365
5366 helpers$1.extend(arc, {
5367 // Utility
5368 _datasetIndex: me.index,
5369 _index: index,
5370 _scale: scale,
5371
5372 // Desired view properties
5373 _model: {
5374 backgroundColor: options.backgroundColor,
5375 borderColor: options.borderColor,
5376 borderWidth: options.borderWidth,
5377 borderAlign: options.borderAlign,
5378 x: centerX,
5379 y: centerY,
5380 innerRadius: 0,
5381 outerRadius: reset ? resetRadius : distance,
5382 startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
5383 endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
5384 label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index])
5385 }
5386 });
5387
5388 arc.pivot();
5389 },
5390
5391 countVisibleElements: function() {
5392 var dataset = this.getDataset();
5393 var meta = this.getMeta();
5394 var count = 0;
5395
5396 helpers$1.each(meta.data, function(element, index) {
5397 if (!isNaN(dataset.data[index]) && !element.hidden) {
5398 count++;
5399 }
5400 });
5401
5402 return count;
5403 },
5404
5405 /**
5406 * @protected
5407 */
5408 setHoverStyle: function(arc) {
5409 var model = arc._model;
5410 var options = arc._options;
5411 var getHoverColor = helpers$1.getHoverColor;
5412 var valueOrDefault = helpers$1.valueOrDefault;
5413
5414 arc.$previousStyle = {
5415 backgroundColor: model.backgroundColor,
5416 borderColor: model.borderColor,
5417 borderWidth: model.borderWidth,
5418 };
5419
5420 model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
5421 model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
5422 model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
5423 },
5424
5425 /**
5426 * @private
5427 */
5428 _resolveElementOptions: function(arc, index) {
5429 var me = this;
5430 var chart = me.chart;
5431 var dataset = me.getDataset();
5432 var custom = arc.custom || {};
5433 var options = chart.options.elements.arc;
5434 var values = {};
5435 var i, ilen, key;
5436
5437 // Scriptable options
5438 var context = {
5439 chart: chart,
5440 dataIndex: index,
5441 dataset: dataset,
5442 datasetIndex: me.index
5443 };
5444
5445 var keys = [
5446 'backgroundColor',
5447 'borderColor',
5448 'borderWidth',
5449 'borderAlign',
5450 'hoverBackgroundColor',
5451 'hoverBorderColor',
5452 'hoverBorderWidth',
5453 ];
5454
5455 for (i = 0, ilen = keys.length; i < ilen; ++i) {
5456 key = keys[i];
5457 values[key] = resolve$5([
5458 custom[key],
5459 dataset[key],
5460 options[key]
5461 ], context, index);
5462 }
5463
5464 return values;
5465 },
5466
5467 /**
5468 * @private
5469 */
5470 _computeAngle: function(index) {
5471 var me = this;
5472 var count = this.getMeta().count;
5473 var dataset = me.getDataset();
5474 var meta = me.getMeta();
5475
5476 if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
5477 return 0;
5478 }
5479
5480 // Scriptable options
5481 var context = {
5482 chart: me.chart,
5483 dataIndex: index,
5484 dataset: dataset,
5485 datasetIndex: me.index
5486 };
5487
5488 return resolve$5([
5489 me.chart.options.elements.arc.angle,
5490 (2 * Math.PI) / count
5491 ], context, index);
5492 }
5493});
5494
5495core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut));
5496core_defaults._set('pie', {
5497 cutoutPercentage: 0
5498});
5499
5500// Pie charts are Doughnut chart with different defaults
5501var controller_pie = controller_doughnut;
5502
5503var resolve$6 = helpers$1.options.resolve;
5504
5505core_defaults._set('radar', {
5506 scale: {
5507 type: 'radialLinear'
5508 },
5509 elements: {
5510 line: {
5511 tension: 0 // no bezier in radar
5512 }
5513 }
5514});
5515
5516var controller_radar = core_datasetController.extend({
5517
5518 datasetElementType: elements.Line,
5519
5520 dataElementType: elements.Point,
5521
5522 linkScales: helpers$1.noop,
5523
5524 update: function(reset) {
5525 var me = this;
5526 var meta = me.getMeta();
5527 var line = meta.dataset;
5528 var points = meta.data || [];
5529 var custom = line.custom || {};
5530 var dataset = me.getDataset();
5531 var lineElementOptions = me.chart.options.elements.line;
5532 var scale = me.chart.scale;
5533 var i, ilen;
5534
5535 // Compatibility: If the properties are defined with only the old name, use those values
5536 if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
5537 dataset.lineTension = dataset.tension;
5538 }
5539
5540 helpers$1.extend(meta.dataset, {
5541 // Utility
5542 _datasetIndex: me.index,
5543 _scale: scale,
5544 // Data
5545 _children: points,
5546 _loop: true,
5547 // Model
5548 _model: {
5549 // Appearance
5550 tension: resolve$6([custom.tension, dataset.lineTension, lineElementOptions.tension]),
5551 backgroundColor: resolve$6([custom.backgroundColor, dataset.backgroundColor, lineElementOptions.backgroundColor]),
5552 borderWidth: resolve$6([custom.borderWidth, dataset.borderWidth, lineElementOptions.borderWidth]),
5553 borderColor: resolve$6([custom.borderColor, dataset.borderColor, lineElementOptions.borderColor]),
5554 fill: resolve$6([custom.fill, dataset.fill, lineElementOptions.fill]),
5555 borderCapStyle: resolve$6([custom.borderCapStyle, dataset.borderCapStyle, lineElementOptions.borderCapStyle]),
5556 borderDash: resolve$6([custom.borderDash, dataset.borderDash, lineElementOptions.borderDash]),
5557 borderDashOffset: resolve$6([custom.borderDashOffset, dataset.borderDashOffset, lineElementOptions.borderDashOffset]),
5558 borderJoinStyle: resolve$6([custom.borderJoinStyle, dataset.borderJoinStyle, lineElementOptions.borderJoinStyle]),
5559 }
5560 });
5561
5562 meta.dataset.pivot();
5563
5564 // Update Points
5565 for (i = 0, ilen = points.length; i < ilen; i++) {
5566 me.updateElement(points[i], i, reset);
5567 }
5568
5569 // Update bezier control points
5570 me.updateBezierControlPoints();
5571
5572 // Now pivot the point for animation
5573 for (i = 0, ilen = points.length; i < ilen; i++) {
5574 points[i].pivot();
5575 }
5576 },
5577
5578 updateElement: function(point, index, reset) {
5579 var me = this;
5580 var custom = point.custom || {};
5581 var dataset = me.getDataset();
5582 var scale = me.chart.scale;
5583 var pointElementOptions = me.chart.options.elements.point;
5584 var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
5585
5586 // Compatibility: If the properties are defined with only the old name, use those values
5587 if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
5588 dataset.pointRadius = dataset.radius;
5589 }
5590 if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {
5591 dataset.pointHitRadius = dataset.hitRadius;
5592 }
5593
5594 helpers$1.extend(point, {
5595 // Utility
5596 _datasetIndex: me.index,
5597 _index: index,
5598 _scale: scale,
5599
5600 // Desired view properties
5601 _model: {
5602 x: reset ? scale.xCenter : pointPosition.x, // value not used in dataset scale, but we want a consistent API between scales
5603 y: reset ? scale.yCenter : pointPosition.y,
5604
5605 // Appearance
5606 tension: resolve$6([custom.tension, dataset.lineTension, me.chart.options.elements.line.tension]),
5607 radius: resolve$6([custom.radius, dataset.pointRadius, pointElementOptions.radius], undefined, index),
5608 backgroundColor: resolve$6([custom.backgroundColor, dataset.pointBackgroundColor, pointElementOptions.backgroundColor], undefined, index),
5609 borderColor: resolve$6([custom.borderColor, dataset.pointBorderColor, pointElementOptions.borderColor], undefined, index),
5610 borderWidth: resolve$6([custom.borderWidth, dataset.pointBorderWidth, pointElementOptions.borderWidth], undefined, index),
5611 pointStyle: resolve$6([custom.pointStyle, dataset.pointStyle, pointElementOptions.pointStyle], undefined, index),
5612 rotation: resolve$6([custom.rotation, dataset.pointRotation, pointElementOptions.rotation], undefined, index),
5613
5614 // Tooltip
5615 hitRadius: resolve$6([custom.hitRadius, dataset.pointHitRadius, pointElementOptions.hitRadius], undefined, index)
5616 }
5617 });
5618
5619 point._model.skip = custom.skip || isNaN(point._model.x) || isNaN(point._model.y);
5620 },
5621
5622 updateBezierControlPoints: function() {
5623 var me = this;
5624 var meta = me.getMeta();
5625 var area = me.chart.chartArea;
5626 var points = meta.data || [];
5627 var i, ilen, model, controlPoints;
5628
5629 function capControlPoint(pt, min, max) {
5630 return Math.max(Math.min(pt, max), min);
5631 }
5632
5633 for (i = 0, ilen = points.length; i < ilen; i++) {
5634 model = points[i]._model;
5635 controlPoints = helpers$1.splineCurve(
5636 helpers$1.previousItem(points, i, true)._model,
5637 model,
5638 helpers$1.nextItem(points, i, true)._model,
5639 model.tension
5640 );
5641
5642 // Prevent the bezier going outside of the bounds of the graph
5643 model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);
5644 model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);
5645 model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);
5646 model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);
5647 }
5648 },
5649
5650 setHoverStyle: function(point) {
5651 // Point
5652 var dataset = this.chart.data.datasets[point._datasetIndex];
5653 var custom = point.custom || {};
5654 var index = point._index;
5655 var model = point._model;
5656 var getHoverColor = helpers$1.getHoverColor;
5657
5658 point.$previousStyle = {
5659 backgroundColor: model.backgroundColor,
5660 borderColor: model.borderColor,
5661 borderWidth: model.borderWidth,
5662 radius: model.radius
5663 };
5664
5665 model.radius = resolve$6([custom.hoverRadius, dataset.pointHoverRadius, this.chart.options.elements.point.hoverRadius], undefined, index);
5666 model.backgroundColor = resolve$6([custom.hoverBackgroundColor, dataset.pointHoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
5667 model.borderColor = resolve$6([custom.hoverBorderColor, dataset.pointHoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
5668 model.borderWidth = resolve$6([custom.hoverBorderWidth, dataset.pointHoverBorderWidth, model.borderWidth], undefined, index);
5669 }
5670});
5671
5672core_defaults._set('scatter', {
5673 hover: {
5674 mode: 'single'
5675 },
5676
5677 scales: {
5678 xAxes: [{
5679 id: 'x-axis-1', // need an ID so datasets can reference the scale
5680 type: 'linear', // scatter should not use a category axis
5681 position: 'bottom'
5682 }],
5683 yAxes: [{
5684 id: 'y-axis-1',
5685 type: 'linear',
5686 position: 'left'
5687 }]
5688 },
5689
5690 showLines: false,
5691
5692 tooltips: {
5693 callbacks: {
5694 title: function() {
5695 return ''; // doesn't make sense for scatter since data are formatted as a point
5696 },
5697 label: function(item) {
5698 return '(' + item.xLabel + ', ' + item.yLabel + ')';
5699 }
5700 }
5701 }
5702});
5703
5704// Scatter charts use line controllers
5705var controller_scatter = controller_line;
5706
5707// NOTE export a map in which the key represents the controller type, not
5708// the class, and so must be CamelCase in order to be correctly retrieved
5709// by the controller in core.controller.js (`controllers[meta.type]`).
5710
5711var controllers = {
5712 bar: controller_bar,
5713 bubble: controller_bubble,
5714 doughnut: controller_doughnut,
5715 horizontalBar: controller_horizontalBar,
5716 line: controller_line,
5717 polarArea: controller_polarArea,
5718 pie: controller_pie,
5719 radar: controller_radar,
5720 scatter: controller_scatter
5721};
5722
5723/**
5724 * Helper function to get relative position for an event
5725 * @param {Event|IEvent} event - The event to get the position for
5726 * @param {Chart} chart - The chart
5727 * @returns {Point} the event position
5728 */
5729function getRelativePosition(e, chart) {
5730 if (e.native) {
5731 return {
5732 x: e.x,
5733 y: e.y
5734 };
5735 }
5736
5737 return helpers$1.getRelativePosition(e, chart);
5738}
5739
5740/**
5741 * Helper function to traverse all of the visible elements in the chart
5742 * @param chart {chart} the chart
5743 * @param handler {Function} the callback to execute for each visible item
5744 */
5745function parseVisibleItems(chart, handler) {
5746 var datasets = chart.data.datasets;
5747 var meta, i, j, ilen, jlen;
5748
5749 for (i = 0, ilen = datasets.length; i < ilen; ++i) {
5750 if (!chart.isDatasetVisible(i)) {
5751 continue;
5752 }
5753
5754 meta = chart.getDatasetMeta(i);
5755 for (j = 0, jlen = meta.data.length; j < jlen; ++j) {
5756 var element = meta.data[j];
5757 if (!element._view.skip) {
5758 handler(element);
5759 }
5760 }
5761 }
5762}
5763
5764/**
5765 * Helper function to get the items that intersect the event position
5766 * @param items {ChartElement[]} elements to filter
5767 * @param position {Point} the point to be nearest to
5768 * @return {ChartElement[]} the nearest items
5769 */
5770function getIntersectItems(chart, position) {
5771 var elements = [];
5772
5773 parseVisibleItems(chart, function(element) {
5774 if (element.inRange(position.x, position.y)) {
5775 elements.push(element);
5776 }
5777 });
5778
5779 return elements;
5780}
5781
5782/**
5783 * Helper function to get the items nearest to the event position considering all visible items in teh chart
5784 * @param chart {Chart} the chart to look at elements from
5785 * @param position {Point} the point to be nearest to
5786 * @param intersect {Boolean} if true, only consider items that intersect the position
5787 * @param distanceMetric {Function} function to provide the distance between points
5788 * @return {ChartElement[]} the nearest items
5789 */
5790function getNearestItems(chart, position, intersect, distanceMetric) {
5791 var minDistance = Number.POSITIVE_INFINITY;
5792 var nearestItems = [];
5793
5794 parseVisibleItems(chart, function(element) {
5795 if (intersect && !element.inRange(position.x, position.y)) {
5796 return;
5797 }
5798
5799 var center = element.getCenterPoint();
5800 var distance = distanceMetric(position, center);
5801
5802 if (distance < minDistance) {
5803 nearestItems = [element];
5804 minDistance = distance;
5805 } else if (distance === minDistance) {
5806 // Can have multiple items at the same distance in which case we sort by size
5807 nearestItems.push(element);
5808 }
5809 });
5810
5811 return nearestItems;
5812}
5813
5814/**
5815 * Get a distance metric function for two points based on the
5816 * axis mode setting
5817 * @param {String} axis the axis mode. x|y|xy
5818 */
5819function getDistanceMetricForAxis(axis) {
5820 var useX = axis.indexOf('x') !== -1;
5821 var useY = axis.indexOf('y') !== -1;
5822
5823 return function(pt1, pt2) {
5824 var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
5825 var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
5826 return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
5827 };
5828}
5829
5830function indexMode(chart, e, options) {
5831 var position = getRelativePosition(e, chart);
5832 // Default axis for index mode is 'x' to match old behaviour
5833 options.axis = options.axis || 'x';
5834 var distanceMetric = getDistanceMetricForAxis(options.axis);
5835 var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
5836 var elements = [];
5837
5838 if (!items.length) {
5839 return [];
5840 }
5841
5842 chart.data.datasets.forEach(function(dataset, datasetIndex) {
5843 if (chart.isDatasetVisible(datasetIndex)) {
5844 var meta = chart.getDatasetMeta(datasetIndex);
5845 var element = meta.data[items[0]._index];
5846
5847 // don't count items that are skipped (null data)
5848 if (element && !element._view.skip) {
5849 elements.push(element);
5850 }
5851 }
5852 });
5853
5854 return elements;
5855}
5856
5857/**
5858 * @interface IInteractionOptions
5859 */
5860/**
5861 * If true, only consider items that intersect the point
5862 * @name IInterfaceOptions#boolean
5863 * @type Boolean
5864 */
5865
5866/**
5867 * Contains interaction related functions
5868 * @namespace Chart.Interaction
5869 */
5870var core_interaction = {
5871 // Helper function for different modes
5872 modes: {
5873 single: function(chart, e) {
5874 var position = getRelativePosition(e, chart);
5875 var elements = [];
5876
5877 parseVisibleItems(chart, function(element) {
5878 if (element.inRange(position.x, position.y)) {
5879 elements.push(element);
5880 return elements;
5881 }
5882 });
5883
5884 return elements.slice(0, 1);
5885 },
5886
5887 /**
5888 * @function Chart.Interaction.modes.label
5889 * @deprecated since version 2.4.0
5890 * @todo remove at version 3
5891 * @private
5892 */
5893 label: indexMode,
5894
5895 /**
5896 * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
5897 * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
5898 * @function Chart.Interaction.modes.index
5899 * @since v2.4.0
5900 * @param chart {chart} the chart we are returning items from
5901 * @param e {Event} the event we are find things at
5902 * @param options {IInteractionOptions} options to use during interaction
5903 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
5904 */
5905 index: indexMode,
5906
5907 /**
5908 * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
5909 * If the options.intersect is false, we find the nearest item and return the items in that dataset
5910 * @function Chart.Interaction.modes.dataset
5911 * @param chart {chart} the chart we are returning items from
5912 * @param e {Event} the event we are find things at
5913 * @param options {IInteractionOptions} options to use during interaction
5914 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
5915 */
5916 dataset: function(chart, e, options) {
5917 var position = getRelativePosition(e, chart);
5918 options.axis = options.axis || 'xy';
5919 var distanceMetric = getDistanceMetricForAxis(options.axis);
5920 var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
5921
5922 if (items.length > 0) {
5923 items = chart.getDatasetMeta(items[0]._datasetIndex).data;
5924 }
5925
5926 return items;
5927 },
5928
5929 /**
5930 * @function Chart.Interaction.modes.x-axis
5931 * @deprecated since version 2.4.0. Use index mode and intersect == true
5932 * @todo remove at version 3
5933 * @private
5934 */
5935 'x-axis': function(chart, e) {
5936 return indexMode(chart, e, {intersect: false});
5937 },
5938
5939 /**
5940 * Point mode returns all elements that hit test based on the event position
5941 * of the event
5942 * @function Chart.Interaction.modes.intersect
5943 * @param chart {chart} the chart we are returning items from
5944 * @param e {Event} the event we are find things at
5945 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
5946 */
5947 point: function(chart, e) {
5948 var position = getRelativePosition(e, chart);
5949 return getIntersectItems(chart, position);
5950 },
5951
5952 /**
5953 * nearest mode returns the element closest to the point
5954 * @function Chart.Interaction.modes.intersect
5955 * @param chart {chart} the chart we are returning items from
5956 * @param e {Event} the event we are find things at
5957 * @param options {IInteractionOptions} options to use
5958 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
5959 */
5960 nearest: function(chart, e, options) {
5961 var position = getRelativePosition(e, chart);
5962 options.axis = options.axis || 'xy';
5963 var distanceMetric = getDistanceMetricForAxis(options.axis);
5964 return getNearestItems(chart, position, options.intersect, distanceMetric);
5965 },
5966
5967 /**
5968 * x mode returns the elements that hit-test at the current x coordinate
5969 * @function Chart.Interaction.modes.x
5970 * @param chart {chart} the chart we are returning items from
5971 * @param e {Event} the event we are find things at
5972 * @param options {IInteractionOptions} options to use
5973 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
5974 */
5975 x: function(chart, e, options) {
5976 var position = getRelativePosition(e, chart);
5977 var items = [];
5978 var intersectsItem = false;
5979
5980 parseVisibleItems(chart, function(element) {
5981 if (element.inXRange(position.x)) {
5982 items.push(element);
5983 }
5984
5985 if (element.inRange(position.x, position.y)) {
5986 intersectsItem = true;
5987 }
5988 });
5989
5990 // If we want to trigger on an intersect and we don't have any items
5991 // that intersect the position, return nothing
5992 if (options.intersect && !intersectsItem) {
5993 items = [];
5994 }
5995 return items;
5996 },
5997
5998 /**
5999 * y mode returns the elements that hit-test at the current y coordinate
6000 * @function Chart.Interaction.modes.y
6001 * @param chart {chart} the chart we are returning items from
6002 * @param e {Event} the event we are find things at
6003 * @param options {IInteractionOptions} options to use
6004 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
6005 */
6006 y: function(chart, e, options) {
6007 var position = getRelativePosition(e, chart);
6008 var items = [];
6009 var intersectsItem = false;
6010
6011 parseVisibleItems(chart, function(element) {
6012 if (element.inYRange(position.y)) {
6013 items.push(element);
6014 }
6015
6016 if (element.inRange(position.x, position.y)) {
6017 intersectsItem = true;
6018 }
6019 });
6020
6021 // If we want to trigger on an intersect and we don't have any items
6022 // that intersect the position, return nothing
6023 if (options.intersect && !intersectsItem) {
6024 items = [];
6025 }
6026 return items;
6027 }
6028 }
6029};
6030
6031function filterByPosition(array, position) {
6032 return helpers$1.where(array, function(v) {
6033 return v.position === position;
6034 });
6035}
6036
6037function sortByWeight(array, reverse) {
6038 array.forEach(function(v, i) {
6039 v._tmpIndex_ = i;
6040 return v;
6041 });
6042 array.sort(function(a, b) {
6043 var v0 = reverse ? b : a;
6044 var v1 = reverse ? a : b;
6045 return v0.weight === v1.weight ?
6046 v0._tmpIndex_ - v1._tmpIndex_ :
6047 v0.weight - v1.weight;
6048 });
6049 array.forEach(function(v) {
6050 delete v._tmpIndex_;
6051 });
6052}
6053
6054core_defaults._set('global', {
6055 layout: {
6056 padding: {
6057 top: 0,
6058 right: 0,
6059 bottom: 0,
6060 left: 0
6061 }
6062 }
6063});
6064
6065/**
6066 * @interface ILayoutItem
6067 * @prop {String} position - The position of the item in the chart layout. Possible values are
6068 * 'left', 'top', 'right', 'bottom', and 'chartArea'
6069 * @prop {Number} weight - The weight used to sort the item. Higher weights are further away from the chart area
6070 * @prop {Boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
6071 * @prop {Function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
6072 * @prop {Function} update - Takes two parameters: width and height. Returns size of item
6073 * @prop {Function} getPadding - Returns an object with padding on the edges
6074 * @prop {Number} width - Width of item. Must be valid after update()
6075 * @prop {Number} height - Height of item. Must be valid after update()
6076 * @prop {Number} left - Left edge of the item. Set by layout system and cannot be used in update
6077 * @prop {Number} top - Top edge of the item. Set by layout system and cannot be used in update
6078 * @prop {Number} right - Right edge of the item. Set by layout system and cannot be used in update
6079 * @prop {Number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
6080 */
6081
6082// The layout service is very self explanatory. It's responsible for the layout within a chart.
6083// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
6084// It is this service's responsibility of carrying out that layout.
6085var core_layouts = {
6086 defaults: {},
6087
6088 /**
6089 * Register a box to a chart.
6090 * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
6091 * @param {Chart} chart - the chart to use
6092 * @param {ILayoutItem} item - the item to add to be layed out
6093 */
6094 addBox: function(chart, item) {
6095 if (!chart.boxes) {
6096 chart.boxes = [];
6097 }
6098
6099 // initialize item with default values
6100 item.fullWidth = item.fullWidth || false;
6101 item.position = item.position || 'top';
6102 item.weight = item.weight || 0;
6103
6104 chart.boxes.push(item);
6105 },
6106
6107 /**
6108 * Remove a layoutItem from a chart
6109 * @param {Chart} chart - the chart to remove the box from
6110 * @param {Object} layoutItem - the item to remove from the layout
6111 */
6112 removeBox: function(chart, layoutItem) {
6113 var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
6114 if (index !== -1) {
6115 chart.boxes.splice(index, 1);
6116 }
6117 },
6118
6119 /**
6120 * Sets (or updates) options on the given `item`.
6121 * @param {Chart} chart - the chart in which the item lives (or will be added to)
6122 * @param {Object} item - the item to configure with the given options
6123 * @param {Object} options - the new item options.
6124 */
6125 configure: function(chart, item, options) {
6126 var props = ['fullWidth', 'position', 'weight'];
6127 var ilen = props.length;
6128 var i = 0;
6129 var prop;
6130
6131 for (; i < ilen; ++i) {
6132 prop = props[i];
6133 if (options.hasOwnProperty(prop)) {
6134 item[prop] = options[prop];
6135 }
6136 }
6137 },
6138
6139 /**
6140 * Fits boxes of the given chart into the given size by having each box measure itself
6141 * then running a fitting algorithm
6142 * @param {Chart} chart - the chart
6143 * @param {Number} width - the width to fit into
6144 * @param {Number} height - the height to fit into
6145 */
6146 update: function(chart, width, height) {
6147 if (!chart) {
6148 return;
6149 }
6150
6151 var layoutOptions = chart.options.layout || {};
6152 var padding = helpers$1.options.toPadding(layoutOptions.padding);
6153 var leftPadding = padding.left;
6154 var rightPadding = padding.right;
6155 var topPadding = padding.top;
6156 var bottomPadding = padding.bottom;
6157
6158 var leftBoxes = filterByPosition(chart.boxes, 'left');
6159 var rightBoxes = filterByPosition(chart.boxes, 'right');
6160 var topBoxes = filterByPosition(chart.boxes, 'top');
6161 var bottomBoxes = filterByPosition(chart.boxes, 'bottom');
6162 var chartAreaBoxes = filterByPosition(chart.boxes, 'chartArea');
6163
6164 // Sort boxes by weight. A higher weight is further away from the chart area
6165 sortByWeight(leftBoxes, true);
6166 sortByWeight(rightBoxes, false);
6167 sortByWeight(topBoxes, true);
6168 sortByWeight(bottomBoxes, false);
6169
6170 // Essentially we now have any number of boxes on each of the 4 sides.
6171 // Our canvas looks like the following.
6172 // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
6173 // B1 is the bottom axis
6174 // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
6175 // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
6176 // an error will be thrown.
6177 //
6178 // |----------------------------------------------------|
6179 // | T1 (Full Width) |
6180 // |----------------------------------------------------|
6181 // | | | T2 | |
6182 // | |----|-------------------------------------|----|
6183 // | | | C1 | | C2 | |
6184 // | | |----| |----| |
6185 // | | | | |
6186 // | L1 | L2 | ChartArea (C0) | R1 |
6187 // | | | | |
6188 // | | |----| |----| |
6189 // | | | C3 | | C4 | |
6190 // | |----|-------------------------------------|----|
6191 // | | | B1 | |
6192 // |----------------------------------------------------|
6193 // | B2 (Full Width) |
6194 // |----------------------------------------------------|
6195 //
6196 // What we do to find the best sizing, we do the following
6197 // 1. Determine the minimum size of the chart area.
6198 // 2. Split the remaining width equally between each vertical axis
6199 // 3. Split the remaining height equally between each horizontal axis
6200 // 4. Give each layout the maximum size it can be. The layout will return it's minimum size
6201 // 5. Adjust the sizes of each axis based on it's minimum reported size.
6202 // 6. Refit each axis
6203 // 7. Position each axis in the final location
6204 // 8. Tell the chart the final location of the chart area
6205 // 9. Tell any axes that overlay the chart area the positions of the chart area
6206
6207 // Step 1
6208 var chartWidth = width - leftPadding - rightPadding;
6209 var chartHeight = height - topPadding - bottomPadding;
6210 var chartAreaWidth = chartWidth / 2; // min 50%
6211 var chartAreaHeight = chartHeight / 2; // min 50%
6212
6213 // Step 2
6214 var verticalBoxWidth = (width - chartAreaWidth) / (leftBoxes.length + rightBoxes.length);
6215
6216 // Step 3
6217 var horizontalBoxHeight = (height - chartAreaHeight) / (topBoxes.length + bottomBoxes.length);
6218
6219 // Step 4
6220 var maxChartAreaWidth = chartWidth;
6221 var maxChartAreaHeight = chartHeight;
6222 var minBoxSizes = [];
6223
6224 function getMinimumBoxSize(box) {
6225 var minSize;
6226 var isHorizontal = box.isHorizontal();
6227
6228 if (isHorizontal) {
6229 minSize = box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, horizontalBoxHeight);
6230 maxChartAreaHeight -= minSize.height;
6231 } else {
6232 minSize = box.update(verticalBoxWidth, maxChartAreaHeight);
6233 maxChartAreaWidth -= minSize.width;
6234 }
6235
6236 minBoxSizes.push({
6237 horizontal: isHorizontal,
6238 minSize: minSize,
6239 box: box,
6240 });
6241 }
6242
6243 helpers$1.each(leftBoxes.concat(rightBoxes, topBoxes, bottomBoxes), getMinimumBoxSize);
6244
6245 // If a horizontal box has padding, we move the left boxes over to avoid ugly charts (see issue #2478)
6246 var maxHorizontalLeftPadding = 0;
6247 var maxHorizontalRightPadding = 0;
6248 var maxVerticalTopPadding = 0;
6249 var maxVerticalBottomPadding = 0;
6250
6251 helpers$1.each(topBoxes.concat(bottomBoxes), function(horizontalBox) {
6252 if (horizontalBox.getPadding) {
6253 var boxPadding = horizontalBox.getPadding();
6254 maxHorizontalLeftPadding = Math.max(maxHorizontalLeftPadding, boxPadding.left);
6255 maxHorizontalRightPadding = Math.max(maxHorizontalRightPadding, boxPadding.right);
6256 }
6257 });
6258
6259 helpers$1.each(leftBoxes.concat(rightBoxes), function(verticalBox) {
6260 if (verticalBox.getPadding) {
6261 var boxPadding = verticalBox.getPadding();
6262 maxVerticalTopPadding = Math.max(maxVerticalTopPadding, boxPadding.top);
6263 maxVerticalBottomPadding = Math.max(maxVerticalBottomPadding, boxPadding.bottom);
6264 }
6265 });
6266
6267 // At this point, maxChartAreaHeight and maxChartAreaWidth are the size the chart area could
6268 // be if the axes are drawn at their minimum sizes.
6269 // Steps 5 & 6
6270 var totalLeftBoxesWidth = leftPadding;
6271 var totalRightBoxesWidth = rightPadding;
6272 var totalTopBoxesHeight = topPadding;
6273 var totalBottomBoxesHeight = bottomPadding;
6274
6275 // Function to fit a box
6276 function fitBox(box) {
6277 var minBoxSize = helpers$1.findNextWhere(minBoxSizes, function(minBox) {
6278 return minBox.box === box;
6279 });
6280
6281 if (minBoxSize) {
6282 if (box.isHorizontal()) {
6283 var scaleMargin = {
6284 left: Math.max(totalLeftBoxesWidth, maxHorizontalLeftPadding),
6285 right: Math.max(totalRightBoxesWidth, maxHorizontalRightPadding),
6286 top: 0,
6287 bottom: 0
6288 };
6289
6290 // Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends
6291 // on the margin. Sometimes they need to increase in size slightly
6292 box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin);
6293 } else {
6294 box.update(minBoxSize.minSize.width, maxChartAreaHeight);
6295 }
6296 }
6297 }
6298
6299 // Update, and calculate the left and right margins for the horizontal boxes
6300 helpers$1.each(leftBoxes.concat(rightBoxes), fitBox);
6301
6302 helpers$1.each(leftBoxes, function(box) {
6303 totalLeftBoxesWidth += box.width;
6304 });
6305
6306 helpers$1.each(rightBoxes, function(box) {
6307 totalRightBoxesWidth += box.width;
6308 });
6309
6310 // Set the Left and Right margins for the horizontal boxes
6311 helpers$1.each(topBoxes.concat(bottomBoxes), fitBox);
6312
6313 // Figure out how much margin is on the top and bottom of the vertical boxes
6314 helpers$1.each(topBoxes, function(box) {
6315 totalTopBoxesHeight += box.height;
6316 });
6317
6318 helpers$1.each(bottomBoxes, function(box) {
6319 totalBottomBoxesHeight += box.height;
6320 });
6321
6322 function finalFitVerticalBox(box) {
6323 var minBoxSize = helpers$1.findNextWhere(minBoxSizes, function(minSize) {
6324 return minSize.box === box;
6325 });
6326
6327 var scaleMargin = {
6328 left: 0,
6329 right: 0,
6330 top: totalTopBoxesHeight,
6331 bottom: totalBottomBoxesHeight
6332 };
6333
6334 if (minBoxSize) {
6335 box.update(minBoxSize.minSize.width, maxChartAreaHeight, scaleMargin);
6336 }
6337 }
6338
6339 // Let the left layout know the final margin
6340 helpers$1.each(leftBoxes.concat(rightBoxes), finalFitVerticalBox);
6341
6342 // Recalculate because the size of each layout might have changed slightly due to the margins (label rotation for instance)
6343 totalLeftBoxesWidth = leftPadding;
6344 totalRightBoxesWidth = rightPadding;
6345 totalTopBoxesHeight = topPadding;
6346 totalBottomBoxesHeight = bottomPadding;
6347
6348 helpers$1.each(leftBoxes, function(box) {
6349 totalLeftBoxesWidth += box.width;
6350 });
6351
6352 helpers$1.each(rightBoxes, function(box) {
6353 totalRightBoxesWidth += box.width;
6354 });
6355
6356 helpers$1.each(topBoxes, function(box) {
6357 totalTopBoxesHeight += box.height;
6358 });
6359 helpers$1.each(bottomBoxes, function(box) {
6360 totalBottomBoxesHeight += box.height;
6361 });
6362
6363 // We may be adding some padding to account for rotated x axis labels
6364 var leftPaddingAddition = Math.max(maxHorizontalLeftPadding - totalLeftBoxesWidth, 0);
6365 totalLeftBoxesWidth += leftPaddingAddition;
6366 totalRightBoxesWidth += Math.max(maxHorizontalRightPadding - totalRightBoxesWidth, 0);
6367
6368 var topPaddingAddition = Math.max(maxVerticalTopPadding - totalTopBoxesHeight, 0);
6369 totalTopBoxesHeight += topPaddingAddition;
6370 totalBottomBoxesHeight += Math.max(maxVerticalBottomPadding - totalBottomBoxesHeight, 0);
6371
6372 // Figure out if our chart area changed. This would occur if the dataset layout label rotation
6373 // changed due to the application of the margins in step 6. Since we can only get bigger, this is safe to do
6374 // without calling `fit` again
6375 var newMaxChartAreaHeight = height - totalTopBoxesHeight - totalBottomBoxesHeight;
6376 var newMaxChartAreaWidth = width - totalLeftBoxesWidth - totalRightBoxesWidth;
6377
6378 if (newMaxChartAreaWidth !== maxChartAreaWidth || newMaxChartAreaHeight !== maxChartAreaHeight) {
6379 helpers$1.each(leftBoxes, function(box) {
6380 box.height = newMaxChartAreaHeight;
6381 });
6382
6383 helpers$1.each(rightBoxes, function(box) {
6384 box.height = newMaxChartAreaHeight;
6385 });
6386
6387 helpers$1.each(topBoxes, function(box) {
6388 if (!box.fullWidth) {
6389 box.width = newMaxChartAreaWidth;
6390 }
6391 });
6392
6393 helpers$1.each(bottomBoxes, function(box) {
6394 if (!box.fullWidth) {
6395 box.width = newMaxChartAreaWidth;
6396 }
6397 });
6398
6399 maxChartAreaHeight = newMaxChartAreaHeight;
6400 maxChartAreaWidth = newMaxChartAreaWidth;
6401 }
6402
6403 // Step 7 - Position the boxes
6404 var left = leftPadding + leftPaddingAddition;
6405 var top = topPadding + topPaddingAddition;
6406
6407 function placeBox(box) {
6408 if (box.isHorizontal()) {
6409 box.left = box.fullWidth ? leftPadding : totalLeftBoxesWidth;
6410 box.right = box.fullWidth ? width - rightPadding : totalLeftBoxesWidth + maxChartAreaWidth;
6411 box.top = top;
6412 box.bottom = top + box.height;
6413
6414 // Move to next point
6415 top = box.bottom;
6416
6417 } else {
6418
6419 box.left = left;
6420 box.right = left + box.width;
6421 box.top = totalTopBoxesHeight;
6422 box.bottom = totalTopBoxesHeight + maxChartAreaHeight;
6423
6424 // Move to next point
6425 left = box.right;
6426 }
6427 }
6428
6429 helpers$1.each(leftBoxes.concat(topBoxes), placeBox);
6430
6431 // Account for chart width and height
6432 left += maxChartAreaWidth;
6433 top += maxChartAreaHeight;
6434
6435 helpers$1.each(rightBoxes, placeBox);
6436 helpers$1.each(bottomBoxes, placeBox);
6437
6438 // Step 8
6439 chart.chartArea = {
6440 left: totalLeftBoxesWidth,
6441 top: totalTopBoxesHeight,
6442 right: totalLeftBoxesWidth + maxChartAreaWidth,
6443 bottom: totalTopBoxesHeight + maxChartAreaHeight
6444 };
6445
6446 // Step 9
6447 helpers$1.each(chartAreaBoxes, function(box) {
6448 box.left = chart.chartArea.left;
6449 box.top = chart.chartArea.top;
6450 box.right = chart.chartArea.right;
6451 box.bottom = chart.chartArea.bottom;
6452
6453 box.update(maxChartAreaWidth, maxChartAreaHeight);
6454 });
6455 }
6456};
6457
6458/**
6459 * Platform fallback implementation (minimal).
6460 * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
6461 */
6462
6463var platform_basic = {
6464 acquireContext: function(item) {
6465 if (item && item.canvas) {
6466 // Support for any object associated to a canvas (including a context2d)
6467 item = item.canvas;
6468 }
6469
6470 return item && item.getContext('2d') || null;
6471 }
6472};
6473
6474var EXPANDO_KEY = '$chartjs';
6475var CSS_PREFIX = 'chartjs-';
6476var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
6477var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
6478var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
6479
6480/**
6481 * DOM event types -> Chart.js event types.
6482 * Note: only events with different types are mapped.
6483 * @see https://developer.mozilla.org/en-US/docs/Web/Events
6484 */
6485var EVENT_TYPES = {
6486 touchstart: 'mousedown',
6487 touchmove: 'mousemove',
6488 touchend: 'mouseup',
6489 pointerenter: 'mouseenter',
6490 pointerdown: 'mousedown',
6491 pointermove: 'mousemove',
6492 pointerup: 'mouseup',
6493 pointerleave: 'mouseout',
6494 pointerout: 'mouseout'
6495};
6496
6497/**
6498 * The "used" size is the final value of a dimension property after all calculations have
6499 * been performed. This method uses the computed style of `element` but returns undefined
6500 * if the computed style is not expressed in pixels. That can happen in some cases where
6501 * `element` has a size relative to its parent and this last one is not yet displayed,
6502 * for example because of `display: none` on a parent node.
6503 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
6504 * @returns {Number} Size in pixels or undefined if unknown.
6505 */
6506function readUsedSize(element, property) {
6507 var value = helpers$1.getStyle(element, property);
6508 var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
6509 return matches ? Number(matches[1]) : undefined;
6510}
6511
6512/**
6513 * Initializes the canvas style and render size without modifying the canvas display size,
6514 * since responsiveness is handled by the controller.resize() method. The config is used
6515 * to determine the aspect ratio to apply in case no explicit height has been specified.
6516 */
6517function initCanvas(canvas, config) {
6518 var style = canvas.style;
6519
6520 // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
6521 // returns null or '' if no explicit value has been set to the canvas attribute.
6522 var renderHeight = canvas.getAttribute('height');
6523 var renderWidth = canvas.getAttribute('width');
6524
6525 // Chart.js modifies some canvas values that we want to restore on destroy
6526 canvas[EXPANDO_KEY] = {
6527 initial: {
6528 height: renderHeight,
6529 width: renderWidth,
6530 style: {
6531 display: style.display,
6532 height: style.height,
6533 width: style.width
6534 }
6535 }
6536 };
6537
6538 // Force canvas to display as block to avoid extra space caused by inline
6539 // elements, which would interfere with the responsive resize process.
6540 // https://github.com/chartjs/Chart.js/issues/2538
6541 style.display = style.display || 'block';
6542
6543 if (renderWidth === null || renderWidth === '') {
6544 var displayWidth = readUsedSize(canvas, 'width');
6545 if (displayWidth !== undefined) {
6546 canvas.width = displayWidth;
6547 }
6548 }
6549
6550 if (renderHeight === null || renderHeight === '') {
6551 if (canvas.style.height === '') {
6552 // If no explicit render height and style height, let's apply the aspect ratio,
6553 // which one can be specified by the user but also by charts as default option
6554 // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
6555 canvas.height = canvas.width / (config.options.aspectRatio || 2);
6556 } else {
6557 var displayHeight = readUsedSize(canvas, 'height');
6558 if (displayWidth !== undefined) {
6559 canvas.height = displayHeight;
6560 }
6561 }
6562 }
6563
6564 return canvas;
6565}
6566
6567/**
6568 * Detects support for options object argument in addEventListener.
6569 * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
6570 * @private
6571 */
6572var supportsEventListenerOptions = (function() {
6573 var supports = false;
6574 try {
6575 var options = Object.defineProperty({}, 'passive', {
6576 // eslint-disable-next-line getter-return
6577 get: function() {
6578 supports = true;
6579 }
6580 });
6581 window.addEventListener('e', null, options);
6582 } catch (e) {
6583 // continue regardless of error
6584 }
6585 return supports;
6586}());
6587
6588// Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
6589// https://github.com/chartjs/Chart.js/issues/4287
6590var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
6591
6592function addEventListener(node, type, listener) {
6593 node.addEventListener(type, listener, eventListenerOptions);
6594}
6595
6596function removeEventListener(node, type, listener) {
6597 node.removeEventListener(type, listener, eventListenerOptions);
6598}
6599
6600function createEvent(type, chart, x, y, nativeEvent) {
6601 return {
6602 type: type,
6603 chart: chart,
6604 native: nativeEvent || null,
6605 x: x !== undefined ? x : null,
6606 y: y !== undefined ? y : null,
6607 };
6608}
6609
6610function fromNativeEvent(event, chart) {
6611 var type = EVENT_TYPES[event.type] || event.type;
6612 var pos = helpers$1.getRelativePosition(event, chart);
6613 return createEvent(type, chart, pos.x, pos.y, event);
6614}
6615
6616function throttled(fn, thisArg) {
6617 var ticking = false;
6618 var args = [];
6619
6620 return function() {
6621 args = Array.prototype.slice.call(arguments);
6622 thisArg = thisArg || this;
6623
6624 if (!ticking) {
6625 ticking = true;
6626 helpers$1.requestAnimFrame.call(window, function() {
6627 ticking = false;
6628 fn.apply(thisArg, args);
6629 });
6630 }
6631 };
6632}
6633
6634function createDiv(cls, style) {
6635 var el = document.createElement('div');
6636 el.style.cssText = style || '';
6637 el.className = cls || '';
6638 return el;
6639}
6640
6641// Implementation based on https://github.com/marcj/css-element-queries
6642function createResizer(handler) {
6643 var cls = CSS_PREFIX + 'size-monitor';
6644 var maxSize = 1000000;
6645 var style =
6646 'position:absolute;' +
6647 'left:0;' +
6648 'top:0;' +
6649 'right:0;' +
6650 'bottom:0;' +
6651 'overflow:hidden;' +
6652 'pointer-events:none;' +
6653 'visibility:hidden;' +
6654 'z-index:-1;';
6655
6656 // NOTE(SB) Don't use innerHTML because it could be considered unsafe.
6657 // https://github.com/chartjs/Chart.js/issues/5902
6658 var resizer = createDiv(cls, style);
6659 var expand = createDiv(cls + '-expand', style);
6660 var shrink = createDiv(cls + '-shrink', style);
6661
6662 expand.appendChild(createDiv('',
6663 'position:absolute;' +
6664 'height:' + maxSize + 'px;' +
6665 'width:' + maxSize + 'px;' +
6666 'left:0;' +
6667 'top:0;'
6668 ));
6669 shrink.appendChild(createDiv('',
6670 'position:absolute;' +
6671 'height:200%;' +
6672 'width:200%;' +
6673 'left:0;' +
6674 'top:0;'
6675 ));
6676
6677 resizer.appendChild(expand);
6678 resizer.appendChild(shrink);
6679 resizer._reset = function() {
6680 expand.scrollLeft = maxSize;
6681 expand.scrollTop = maxSize;
6682 shrink.scrollLeft = maxSize;
6683 shrink.scrollTop = maxSize;
6684 };
6685
6686 var onScroll = function() {
6687 resizer._reset();
6688 handler();
6689 };
6690
6691 addEventListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
6692 addEventListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
6693
6694 return resizer;
6695}
6696
6697// https://davidwalsh.name/detect-node-insertion
6698function watchForRender(node, handler) {
6699 var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
6700 var proxy = expando.renderProxy = function(e) {
6701 if (e.animationName === CSS_RENDER_ANIMATION) {
6702 handler();
6703 }
6704 };
6705
6706 helpers$1.each(ANIMATION_START_EVENTS, function(type) {
6707 addEventListener(node, type, proxy);
6708 });
6709
6710 // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
6711 // is removed then added back immediately (same animation frame?). Accessing the
6712 // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
6713 // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
6714 // https://github.com/chartjs/Chart.js/issues/4737
6715 expando.reflow = !!node.offsetParent;
6716
6717 node.classList.add(CSS_RENDER_MONITOR);
6718}
6719
6720function unwatchForRender(node) {
6721 var expando = node[EXPANDO_KEY] || {};
6722 var proxy = expando.renderProxy;
6723
6724 if (proxy) {
6725 helpers$1.each(ANIMATION_START_EVENTS, function(type) {
6726 removeEventListener(node, type, proxy);
6727 });
6728
6729 delete expando.renderProxy;
6730 }
6731
6732 node.classList.remove(CSS_RENDER_MONITOR);
6733}
6734
6735function addResizeListener(node, listener, chart) {
6736 var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
6737
6738 // Let's keep track of this added resizer and thus avoid DOM query when removing it.
6739 var resizer = expando.resizer = createResizer(throttled(function() {
6740 if (expando.resizer) {
6741 return listener(createEvent('resize', chart));
6742 }
6743 }));
6744
6745 // The resizer needs to be attached to the node parent, so we first need to be
6746 // sure that `node` is attached to the DOM before injecting the resizer element.
6747 watchForRender(node, function() {
6748 if (expando.resizer) {
6749 var container = node.parentNode;
6750 if (container && container !== resizer.parentNode) {
6751 container.insertBefore(resizer, container.firstChild);
6752 }
6753
6754 // The container size might have changed, let's reset the resizer state.
6755 resizer._reset();
6756 }
6757 });
6758}
6759
6760function removeResizeListener(node) {
6761 var expando = node[EXPANDO_KEY] || {};
6762 var resizer = expando.resizer;
6763
6764 delete expando.resizer;
6765 unwatchForRender(node);
6766
6767 if (resizer && resizer.parentNode) {
6768 resizer.parentNode.removeChild(resizer);
6769 }
6770}
6771
6772function injectCSS(platform, css) {
6773 // https://stackoverflow.com/q/3922139
6774 var style = platform._style || document.createElement('style');
6775 if (!platform._style) {
6776 platform._style = style;
6777 css = '/* Chart.js */\n' + css;
6778 style.setAttribute('type', 'text/css');
6779 document.getElementsByTagName('head')[0].appendChild(style);
6780 }
6781
6782 style.appendChild(document.createTextNode(css));
6783}
6784
6785var platform_dom = {
6786 /**
6787 * This property holds whether this platform is enabled for the current environment.
6788 * Currently used by platform.js to select the proper implementation.
6789 * @private
6790 */
6791 _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
6792
6793 initialize: function() {
6794 var keyframes = 'from{opacity:0.99}to{opacity:1}';
6795
6796 injectCSS(this,
6797 // DOM rendering detection
6798 // https://davidwalsh.name/detect-node-insertion
6799 '@-webkit-keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' +
6800 '@keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' +
6801 '.' + CSS_RENDER_MONITOR + '{' +
6802 '-webkit-animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' +
6803 'animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' +
6804 '}'
6805 );
6806 },
6807
6808 acquireContext: function(item, config) {
6809 if (typeof item === 'string') {
6810 item = document.getElementById(item);
6811 } else if (item.length) {
6812 // Support for array based queries (such as jQuery)
6813 item = item[0];
6814 }
6815
6816 if (item && item.canvas) {
6817 // Support for any object associated to a canvas (including a context2d)
6818 item = item.canvas;
6819 }
6820
6821 // To prevent canvas fingerprinting, some add-ons undefine the getContext
6822 // method, for example: https://github.com/kkapsner/CanvasBlocker
6823 // https://github.com/chartjs/Chart.js/issues/2807
6824 var context = item && item.getContext && item.getContext('2d');
6825
6826 // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
6827 // inside an iframe or when running in a protected environment. We could guess the
6828 // types from their toString() value but let's keep things flexible and assume it's
6829 // a sufficient condition if the item has a context2D which has item as `canvas`.
6830 // https://github.com/chartjs/Chart.js/issues/3887
6831 // https://github.com/chartjs/Chart.js/issues/4102
6832 // https://github.com/chartjs/Chart.js/issues/4152
6833 if (context && context.canvas === item) {
6834 initCanvas(item, config);
6835 return context;
6836 }
6837
6838 return null;
6839 },
6840
6841 releaseContext: function(context) {
6842 var canvas = context.canvas;
6843 if (!canvas[EXPANDO_KEY]) {
6844 return;
6845 }
6846
6847 var initial = canvas[EXPANDO_KEY].initial;
6848 ['height', 'width'].forEach(function(prop) {
6849 var value = initial[prop];
6850 if (helpers$1.isNullOrUndef(value)) {
6851 canvas.removeAttribute(prop);
6852 } else {
6853 canvas.setAttribute(prop, value);
6854 }
6855 });
6856
6857 helpers$1.each(initial.style || {}, function(value, key) {
6858 canvas.style[key] = value;
6859 });
6860
6861 // The canvas render size might have been changed (and thus the state stack discarded),
6862 // we can't use save() and restore() to restore the initial state. So make sure that at
6863 // least the canvas context is reset to the default state by setting the canvas width.
6864 // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
6865 // eslint-disable-next-line no-self-assign
6866 canvas.width = canvas.width;
6867
6868 delete canvas[EXPANDO_KEY];
6869 },
6870
6871 addEventListener: function(chart, type, listener) {
6872 var canvas = chart.canvas;
6873 if (type === 'resize') {
6874 // Note: the resize event is not supported on all browsers.
6875 addResizeListener(canvas, listener, chart);
6876 return;
6877 }
6878
6879 var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
6880 var proxies = expando.proxies || (expando.proxies = {});
6881 var proxy = proxies[chart.id + '_' + type] = function(event) {
6882 listener(fromNativeEvent(event, chart));
6883 };
6884
6885 addEventListener(canvas, type, proxy);
6886 },
6887
6888 removeEventListener: function(chart, type, listener) {
6889 var canvas = chart.canvas;
6890 if (type === 'resize') {
6891 // Note: the resize event is not supported on all browsers.
6892 removeResizeListener(canvas);
6893 return;
6894 }
6895
6896 var expando = listener[EXPANDO_KEY] || {};
6897 var proxies = expando.proxies || {};
6898 var proxy = proxies[chart.id + '_' + type];
6899 if (!proxy) {
6900 return;
6901 }
6902
6903 removeEventListener(canvas, type, proxy);
6904 }
6905};
6906
6907// DEPRECATIONS
6908
6909/**
6910 * Provided for backward compatibility, use EventTarget.addEventListener instead.
6911 * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
6912 * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
6913 * @function Chart.helpers.addEvent
6914 * @deprecated since version 2.7.0
6915 * @todo remove at version 3
6916 * @private
6917 */
6918helpers$1.addEvent = addEventListener;
6919
6920/**
6921 * Provided for backward compatibility, use EventTarget.removeEventListener instead.
6922 * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
6923 * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
6924 * @function Chart.helpers.removeEvent
6925 * @deprecated since version 2.7.0
6926 * @todo remove at version 3
6927 * @private
6928 */
6929helpers$1.removeEvent = removeEventListener;
6930
6931// @TODO Make possible to select another platform at build time.
6932var implementation = platform_dom._enabled ? platform_dom : platform_basic;
6933
6934/**
6935 * @namespace Chart.platform
6936 * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
6937 * @since 2.4.0
6938 */
6939var platform = helpers$1.extend({
6940 /**
6941 * @since 2.7.0
6942 */
6943 initialize: function() {},
6944
6945 /**
6946 * Called at chart construction time, returns a context2d instance implementing
6947 * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
6948 * @param {*} item - The native item from which to acquire context (platform specific)
6949 * @param {Object} options - The chart options
6950 * @returns {CanvasRenderingContext2D} context2d instance
6951 */
6952 acquireContext: function() {},
6953
6954 /**
6955 * Called at chart destruction time, releases any resources associated to the context
6956 * previously returned by the acquireContext() method.
6957 * @param {CanvasRenderingContext2D} context - The context2d instance
6958 * @returns {Boolean} true if the method succeeded, else false
6959 */
6960 releaseContext: function() {},
6961
6962 /**
6963 * Registers the specified listener on the given chart.
6964 * @param {Chart} chart - Chart from which to listen for event
6965 * @param {String} type - The ({@link IEvent}) type to listen for
6966 * @param {Function} listener - Receives a notification (an object that implements
6967 * the {@link IEvent} interface) when an event of the specified type occurs.
6968 */
6969 addEventListener: function() {},
6970
6971 /**
6972 * Removes the specified listener previously registered with addEventListener.
6973 * @param {Chart} chart -Chart from which to remove the listener
6974 * @param {String} type - The ({@link IEvent}) type to remove
6975 * @param {Function} listener - The listener function to remove from the event target.
6976 */
6977 removeEventListener: function() {}
6978
6979}, implementation);
6980
6981core_defaults._set('global', {
6982 plugins: {}
6983});
6984
6985/**
6986 * The plugin service singleton
6987 * @namespace Chart.plugins
6988 * @since 2.1.0
6989 */
6990var core_plugins = {
6991 /**
6992 * Globally registered plugins.
6993 * @private
6994 */
6995 _plugins: [],
6996
6997 /**
6998 * This identifier is used to invalidate the descriptors cache attached to each chart
6999 * when a global plugin is registered or unregistered. In this case, the cache ID is
7000 * incremented and descriptors are regenerated during following API calls.
7001 * @private
7002 */
7003 _cacheId: 0,
7004
7005 /**
7006 * Registers the given plugin(s) if not already registered.
7007 * @param {Array|Object} plugins plugin instance(s).
7008 */
7009 register: function(plugins) {
7010 var p = this._plugins;
7011 ([]).concat(plugins).forEach(function(plugin) {
7012 if (p.indexOf(plugin) === -1) {
7013 p.push(plugin);
7014 }
7015 });
7016
7017 this._cacheId++;
7018 },
7019
7020 /**
7021 * Unregisters the given plugin(s) only if registered.
7022 * @param {Array|Object} plugins plugin instance(s).
7023 */
7024 unregister: function(plugins) {
7025 var p = this._plugins;
7026 ([]).concat(plugins).forEach(function(plugin) {
7027 var idx = p.indexOf(plugin);
7028 if (idx !== -1) {
7029 p.splice(idx, 1);
7030 }
7031 });
7032
7033 this._cacheId++;
7034 },
7035
7036 /**
7037 * Remove all registered plugins.
7038 * @since 2.1.5
7039 */
7040 clear: function() {
7041 this._plugins = [];
7042 this._cacheId++;
7043 },
7044
7045 /**
7046 * Returns the number of registered plugins?
7047 * @returns {Number}
7048 * @since 2.1.5
7049 */
7050 count: function() {
7051 return this._plugins.length;
7052 },
7053
7054 /**
7055 * Returns all registered plugin instances.
7056 * @returns {Array} array of plugin objects.
7057 * @since 2.1.5
7058 */
7059 getAll: function() {
7060 return this._plugins;
7061 },
7062
7063 /**
7064 * Calls enabled plugins for `chart` on the specified hook and with the given args.
7065 * This method immediately returns as soon as a plugin explicitly returns false. The
7066 * returned value can be used, for instance, to interrupt the current action.
7067 * @param {Object} chart - The chart instance for which plugins should be called.
7068 * @param {String} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
7069 * @param {Array} [args] - Extra arguments to apply to the hook call.
7070 * @returns {Boolean} false if any of the plugins return false, else returns true.
7071 */
7072 notify: function(chart, hook, args) {
7073 var descriptors = this.descriptors(chart);
7074 var ilen = descriptors.length;
7075 var i, descriptor, plugin, params, method;
7076
7077 for (i = 0; i < ilen; ++i) {
7078 descriptor = descriptors[i];
7079 plugin = descriptor.plugin;
7080 method = plugin[hook];
7081 if (typeof method === 'function') {
7082 params = [chart].concat(args || []);
7083 params.push(descriptor.options);
7084 if (method.apply(plugin, params) === false) {
7085 return false;
7086 }
7087 }
7088 }
7089
7090 return true;
7091 },
7092
7093 /**
7094 * Returns descriptors of enabled plugins for the given chart.
7095 * @returns {Array} [{ plugin, options }]
7096 * @private
7097 */
7098 descriptors: function(chart) {
7099 var cache = chart.$plugins || (chart.$plugins = {});
7100 if (cache.id === this._cacheId) {
7101 return cache.descriptors;
7102 }
7103
7104 var plugins = [];
7105 var descriptors = [];
7106 var config = (chart && chart.config) || {};
7107 var options = (config.options && config.options.plugins) || {};
7108
7109 this._plugins.concat(config.plugins || []).forEach(function(plugin) {
7110 var idx = plugins.indexOf(plugin);
7111 if (idx !== -1) {
7112 return;
7113 }
7114
7115 var id = plugin.id;
7116 var opts = options[id];
7117 if (opts === false) {
7118 return;
7119 }
7120
7121 if (opts === true) {
7122 opts = helpers$1.clone(core_defaults.global.plugins[id]);
7123 }
7124
7125 plugins.push(plugin);
7126 descriptors.push({
7127 plugin: plugin,
7128 options: opts || {}
7129 });
7130 });
7131
7132 cache.descriptors = descriptors;
7133 cache.id = this._cacheId;
7134 return descriptors;
7135 },
7136
7137 /**
7138 * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
7139 * but in some cases, this reference can be changed by the user when updating options.
7140 * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
7141 * @private
7142 */
7143 _invalidate: function(chart) {
7144 delete chart.$plugins;
7145 }
7146};
7147
7148var core_scaleService = {
7149 // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
7150 // use the new chart options to grab the correct scale
7151 constructors: {},
7152 // Use a registration function so that we can move to an ES6 map when we no longer need to support
7153 // old browsers
7154
7155 // Scale config defaults
7156 defaults: {},
7157 registerScaleType: function(type, scaleConstructor, scaleDefaults) {
7158 this.constructors[type] = scaleConstructor;
7159 this.defaults[type] = helpers$1.clone(scaleDefaults);
7160 },
7161 getScaleConstructor: function(type) {
7162 return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
7163 },
7164 getScaleDefaults: function(type) {
7165 // Return the scale defaults merged with the global settings so that we always use the latest ones
7166 return this.defaults.hasOwnProperty(type) ? helpers$1.merge({}, [core_defaults.scale, this.defaults[type]]) : {};
7167 },
7168 updateScaleDefaults: function(type, additions) {
7169 var me = this;
7170 if (me.defaults.hasOwnProperty(type)) {
7171 me.defaults[type] = helpers$1.extend(me.defaults[type], additions);
7172 }
7173 },
7174 addScalesToLayout: function(chart) {
7175 // Adds each scale to the chart.boxes array to be sized accordingly
7176 helpers$1.each(chart.scales, function(scale) {
7177 // Set ILayoutItem parameters for backwards compatibility
7178 scale.fullWidth = scale.options.fullWidth;
7179 scale.position = scale.options.position;
7180 scale.weight = scale.options.weight;
7181 core_layouts.addBox(chart, scale);
7182 });
7183 }
7184};
7185
7186var valueOrDefault$5 = helpers$1.valueOrDefault;
7187
7188core_defaults._set('global', {
7189 tooltips: {
7190 enabled: true,
7191 custom: null,
7192 mode: 'nearest',
7193 position: 'average',
7194 intersect: true,
7195 backgroundColor: 'rgba(0,0,0,0.8)',
7196 titleFontStyle: 'bold',
7197 titleSpacing: 2,
7198 titleMarginBottom: 6,
7199 titleFontColor: '#fff',
7200 titleAlign: 'left',
7201 bodySpacing: 2,
7202 bodyFontColor: '#fff',
7203 bodyAlign: 'left',
7204 footerFontStyle: 'bold',
7205 footerSpacing: 2,
7206 footerMarginTop: 6,
7207 footerFontColor: '#fff',
7208 footerAlign: 'left',
7209 yPadding: 6,
7210 xPadding: 6,
7211 caretPadding: 2,
7212 caretSize: 5,
7213 cornerRadius: 6,
7214 multiKeyBackground: '#fff',
7215 displayColors: true,
7216 borderColor: 'rgba(0,0,0,0)',
7217 borderWidth: 0,
7218 callbacks: {
7219 // Args are: (tooltipItems, data)
7220 beforeTitle: helpers$1.noop,
7221 title: function(tooltipItems, data) {
7222 // Pick first xLabel for now
7223 var title = '';
7224 var labels = data.labels;
7225 var labelCount = labels ? labels.length : 0;
7226
7227 if (tooltipItems.length > 0) {
7228 var item = tooltipItems[0];
7229
7230 if (item.xLabel) {
7231 title = item.xLabel;
7232 } else if (labelCount > 0 && item.index < labelCount) {
7233 title = labels[item.index];
7234 }
7235 }
7236
7237 return title;
7238 },
7239 afterTitle: helpers$1.noop,
7240
7241 // Args are: (tooltipItems, data)
7242 beforeBody: helpers$1.noop,
7243
7244 // Args are: (tooltipItem, data)
7245 beforeLabel: helpers$1.noop,
7246 label: function(tooltipItem, data) {
7247 var label = data.datasets[tooltipItem.datasetIndex].label || '';
7248
7249 if (label) {
7250 label += ': ';
7251 }
7252 label += tooltipItem.yLabel;
7253 return label;
7254 },
7255 labelColor: function(tooltipItem, chart) {
7256 var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
7257 var activeElement = meta.data[tooltipItem.index];
7258 var view = activeElement._view;
7259 return {
7260 borderColor: view.borderColor,
7261 backgroundColor: view.backgroundColor
7262 };
7263 },
7264 labelTextColor: function() {
7265 return this._options.bodyFontColor;
7266 },
7267 afterLabel: helpers$1.noop,
7268
7269 // Args are: (tooltipItems, data)
7270 afterBody: helpers$1.noop,
7271
7272 // Args are: (tooltipItems, data)
7273 beforeFooter: helpers$1.noop,
7274 footer: helpers$1.noop,
7275 afterFooter: helpers$1.noop
7276 }
7277 }
7278});
7279
7280var positioners = {
7281 /**
7282 * Average mode places the tooltip at the average position of the elements shown
7283 * @function Chart.Tooltip.positioners.average
7284 * @param elements {ChartElement[]} the elements being displayed in the tooltip
7285 * @returns {Point} tooltip position
7286 */
7287 average: function(elements) {
7288 if (!elements.length) {
7289 return false;
7290 }
7291
7292 var i, len;
7293 var x = 0;
7294 var y = 0;
7295 var count = 0;
7296
7297 for (i = 0, len = elements.length; i < len; ++i) {
7298 var el = elements[i];
7299 if (el && el.hasValue()) {
7300 var pos = el.tooltipPosition();
7301 x += pos.x;
7302 y += pos.y;
7303 ++count;
7304 }
7305 }
7306
7307 return {
7308 x: x / count,
7309 y: y / count
7310 };
7311 },
7312
7313 /**
7314 * Gets the tooltip position nearest of the item nearest to the event position
7315 * @function Chart.Tooltip.positioners.nearest
7316 * @param elements {Chart.Element[]} the tooltip elements
7317 * @param eventPosition {Point} the position of the event in canvas coordinates
7318 * @returns {Point} the tooltip position
7319 */
7320 nearest: function(elements, eventPosition) {
7321 var x = eventPosition.x;
7322 var y = eventPosition.y;
7323 var minDistance = Number.POSITIVE_INFINITY;
7324 var i, len, nearestElement;
7325
7326 for (i = 0, len = elements.length; i < len; ++i) {
7327 var el = elements[i];
7328 if (el && el.hasValue()) {
7329 var center = el.getCenterPoint();
7330 var d = helpers$1.distanceBetweenPoints(eventPosition, center);
7331
7332 if (d < minDistance) {
7333 minDistance = d;
7334 nearestElement = el;
7335 }
7336 }
7337 }
7338
7339 if (nearestElement) {
7340 var tp = nearestElement.tooltipPosition();
7341 x = tp.x;
7342 y = tp.y;
7343 }
7344
7345 return {
7346 x: x,
7347 y: y
7348 };
7349 }
7350};
7351
7352// Helper to push or concat based on if the 2nd parameter is an array or not
7353function pushOrConcat(base, toPush) {
7354 if (toPush) {
7355 if (helpers$1.isArray(toPush)) {
7356 // base = base.concat(toPush);
7357 Array.prototype.push.apply(base, toPush);
7358 } else {
7359 base.push(toPush);
7360 }
7361 }
7362
7363 return base;
7364}
7365
7366/**
7367 * Returns array of strings split by newline
7368 * @param {String} value - The value to split by newline.
7369 * @returns {Array} value if newline present - Returned from String split() method
7370 * @function
7371 */
7372function splitNewlines(str) {
7373 if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
7374 return str.split('\n');
7375 }
7376 return str;
7377}
7378
7379
7380// Private helper to create a tooltip item model
7381// @param element : the chart element (point, arc, bar) to create the tooltip item for
7382// @return : new tooltip item
7383function createTooltipItem(element) {
7384 var xScale = element._xScale;
7385 var yScale = element._yScale || element._scale; // handle radar || polarArea charts
7386 var index = element._index;
7387 var datasetIndex = element._datasetIndex;
7388
7389 return {
7390 xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
7391 yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
7392 index: index,
7393 datasetIndex: datasetIndex,
7394 x: element._model.x,
7395 y: element._model.y
7396 };
7397}
7398
7399/**
7400 * Helper to get the reset model for the tooltip
7401 * @param tooltipOpts {Object} the tooltip options
7402 */
7403function getBaseModel(tooltipOpts) {
7404 var globalDefaults = core_defaults.global;
7405
7406 return {
7407 // Positioning
7408 xPadding: tooltipOpts.xPadding,
7409 yPadding: tooltipOpts.yPadding,
7410 xAlign: tooltipOpts.xAlign,
7411 yAlign: tooltipOpts.yAlign,
7412
7413 // Body
7414 bodyFontColor: tooltipOpts.bodyFontColor,
7415 _bodyFontFamily: valueOrDefault$5(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
7416 _bodyFontStyle: valueOrDefault$5(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
7417 _bodyAlign: tooltipOpts.bodyAlign,
7418 bodyFontSize: valueOrDefault$5(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
7419 bodySpacing: tooltipOpts.bodySpacing,
7420
7421 // Title
7422 titleFontColor: tooltipOpts.titleFontColor,
7423 _titleFontFamily: valueOrDefault$5(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
7424 _titleFontStyle: valueOrDefault$5(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
7425 titleFontSize: valueOrDefault$5(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
7426 _titleAlign: tooltipOpts.titleAlign,
7427 titleSpacing: tooltipOpts.titleSpacing,
7428 titleMarginBottom: tooltipOpts.titleMarginBottom,
7429
7430 // Footer
7431 footerFontColor: tooltipOpts.footerFontColor,
7432 _footerFontFamily: valueOrDefault$5(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
7433 _footerFontStyle: valueOrDefault$5(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
7434 footerFontSize: valueOrDefault$5(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
7435 _footerAlign: tooltipOpts.footerAlign,
7436 footerSpacing: tooltipOpts.footerSpacing,
7437 footerMarginTop: tooltipOpts.footerMarginTop,
7438
7439 // Appearance
7440 caretSize: tooltipOpts.caretSize,
7441 cornerRadius: tooltipOpts.cornerRadius,
7442 backgroundColor: tooltipOpts.backgroundColor,
7443 opacity: 0,
7444 legendColorBackground: tooltipOpts.multiKeyBackground,
7445 displayColors: tooltipOpts.displayColors,
7446 borderColor: tooltipOpts.borderColor,
7447 borderWidth: tooltipOpts.borderWidth
7448 };
7449}
7450
7451/**
7452 * Get the size of the tooltip
7453 */
7454function getTooltipSize(tooltip, model) {
7455 var ctx = tooltip._chart.ctx;
7456
7457 var height = model.yPadding * 2; // Tooltip Padding
7458 var width = 0;
7459
7460 // Count of all lines in the body
7461 var body = model.body;
7462 var combinedBodyLength = body.reduce(function(count, bodyItem) {
7463 return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
7464 }, 0);
7465 combinedBodyLength += model.beforeBody.length + model.afterBody.length;
7466
7467 var titleLineCount = model.title.length;
7468 var footerLineCount = model.footer.length;
7469 var titleFontSize = model.titleFontSize;
7470 var bodyFontSize = model.bodyFontSize;
7471 var footerFontSize = model.footerFontSize;
7472
7473 height += titleLineCount * titleFontSize; // Title Lines
7474 height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
7475 height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
7476 height += combinedBodyLength * bodyFontSize; // Body Lines
7477 height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
7478 height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
7479 height += footerLineCount * (footerFontSize); // Footer Lines
7480 height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
7481
7482 // Title width
7483 var widthPadding = 0;
7484 var maxLineWidth = function(line) {
7485 width = Math.max(width, ctx.measureText(line).width + widthPadding);
7486 };
7487
7488 ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
7489 helpers$1.each(model.title, maxLineWidth);
7490
7491 // Body width
7492 ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
7493 helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
7494
7495 // Body lines may include some extra width due to the color box
7496 widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
7497 helpers$1.each(body, function(bodyItem) {
7498 helpers$1.each(bodyItem.before, maxLineWidth);
7499 helpers$1.each(bodyItem.lines, maxLineWidth);
7500 helpers$1.each(bodyItem.after, maxLineWidth);
7501 });
7502
7503 // Reset back to 0
7504 widthPadding = 0;
7505
7506 // Footer width
7507 ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
7508 helpers$1.each(model.footer, maxLineWidth);
7509
7510 // Add padding
7511 width += 2 * model.xPadding;
7512
7513 return {
7514 width: width,
7515 height: height
7516 };
7517}
7518
7519/**
7520 * Helper to get the alignment of a tooltip given the size
7521 */
7522function determineAlignment(tooltip, size) {
7523 var model = tooltip._model;
7524 var chart = tooltip._chart;
7525 var chartArea = tooltip._chart.chartArea;
7526 var xAlign = 'center';
7527 var yAlign = 'center';
7528
7529 if (model.y < size.height) {
7530 yAlign = 'top';
7531 } else if (model.y > (chart.height - size.height)) {
7532 yAlign = 'bottom';
7533 }
7534
7535 var lf, rf; // functions to determine left, right alignment
7536 var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
7537 var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
7538 var midX = (chartArea.left + chartArea.right) / 2;
7539 var midY = (chartArea.top + chartArea.bottom) / 2;
7540
7541 if (yAlign === 'center') {
7542 lf = function(x) {
7543 return x <= midX;
7544 };
7545 rf = function(x) {
7546 return x > midX;
7547 };
7548 } else {
7549 lf = function(x) {
7550 return x <= (size.width / 2);
7551 };
7552 rf = function(x) {
7553 return x >= (chart.width - (size.width / 2));
7554 };
7555 }
7556
7557 olf = function(x) {
7558 return x + size.width + model.caretSize + model.caretPadding > chart.width;
7559 };
7560 orf = function(x) {
7561 return x - size.width - model.caretSize - model.caretPadding < 0;
7562 };
7563 yf = function(y) {
7564 return y <= midY ? 'top' : 'bottom';
7565 };
7566
7567 if (lf(model.x)) {
7568 xAlign = 'left';
7569
7570 // Is tooltip too wide and goes over the right side of the chart.?
7571 if (olf(model.x)) {
7572 xAlign = 'center';
7573 yAlign = yf(model.y);
7574 }
7575 } else if (rf(model.x)) {
7576 xAlign = 'right';
7577
7578 // Is tooltip too wide and goes outside left edge of canvas?
7579 if (orf(model.x)) {
7580 xAlign = 'center';
7581 yAlign = yf(model.y);
7582 }
7583 }
7584
7585 var opts = tooltip._options;
7586 return {
7587 xAlign: opts.xAlign ? opts.xAlign : xAlign,
7588 yAlign: opts.yAlign ? opts.yAlign : yAlign
7589 };
7590}
7591
7592/**
7593 * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
7594 */
7595function getBackgroundPoint(vm, size, alignment, chart) {
7596 // Background Position
7597 var x = vm.x;
7598 var y = vm.y;
7599
7600 var caretSize = vm.caretSize;
7601 var caretPadding = vm.caretPadding;
7602 var cornerRadius = vm.cornerRadius;
7603 var xAlign = alignment.xAlign;
7604 var yAlign = alignment.yAlign;
7605 var paddingAndSize = caretSize + caretPadding;
7606 var radiusAndPadding = cornerRadius + caretPadding;
7607
7608 if (xAlign === 'right') {
7609 x -= size.width;
7610 } else if (xAlign === 'center') {
7611 x -= (size.width / 2);
7612 if (x + size.width > chart.width) {
7613 x = chart.width - size.width;
7614 }
7615 if (x < 0) {
7616 x = 0;
7617 }
7618 }
7619
7620 if (yAlign === 'top') {
7621 y += paddingAndSize;
7622 } else if (yAlign === 'bottom') {
7623 y -= size.height + paddingAndSize;
7624 } else {
7625 y -= (size.height / 2);
7626 }
7627
7628 if (yAlign === 'center') {
7629 if (xAlign === 'left') {
7630 x += paddingAndSize;
7631 } else if (xAlign === 'right') {
7632 x -= paddingAndSize;
7633 }
7634 } else if (xAlign === 'left') {
7635 x -= radiusAndPadding;
7636 } else if (xAlign === 'right') {
7637 x += radiusAndPadding;
7638 }
7639
7640 return {
7641 x: x,
7642 y: y
7643 };
7644}
7645
7646function getAlignedX(vm, align) {
7647 return align === 'center'
7648 ? vm.x + vm.width / 2
7649 : align === 'right'
7650 ? vm.x + vm.width - vm.xPadding
7651 : vm.x + vm.xPadding;
7652}
7653
7654/**
7655 * Helper to build before and after body lines
7656 */
7657function getBeforeAfterBodyLines(callback) {
7658 return pushOrConcat([], splitNewlines(callback));
7659}
7660
7661var exports$3 = core_element.extend({
7662 initialize: function() {
7663 this._model = getBaseModel(this._options);
7664 this._lastActive = [];
7665 },
7666
7667 // Get the title
7668 // Args are: (tooltipItem, data)
7669 getTitle: function() {
7670 var me = this;
7671 var opts = me._options;
7672 var callbacks = opts.callbacks;
7673
7674 var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
7675 var title = callbacks.title.apply(me, arguments);
7676 var afterTitle = callbacks.afterTitle.apply(me, arguments);
7677
7678 var lines = [];
7679 lines = pushOrConcat(lines, splitNewlines(beforeTitle));
7680 lines = pushOrConcat(lines, splitNewlines(title));
7681 lines = pushOrConcat(lines, splitNewlines(afterTitle));
7682
7683 return lines;
7684 },
7685
7686 // Args are: (tooltipItem, data)
7687 getBeforeBody: function() {
7688 return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));
7689 },
7690
7691 // Args are: (tooltipItem, data)
7692 getBody: function(tooltipItems, data) {
7693 var me = this;
7694 var callbacks = me._options.callbacks;
7695 var bodyItems = [];
7696
7697 helpers$1.each(tooltipItems, function(tooltipItem) {
7698 var bodyItem = {
7699 before: [],
7700 lines: [],
7701 after: []
7702 };
7703 pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));
7704 pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
7705 pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));
7706
7707 bodyItems.push(bodyItem);
7708 });
7709
7710 return bodyItems;
7711 },
7712
7713 // Args are: (tooltipItem, data)
7714 getAfterBody: function() {
7715 return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));
7716 },
7717
7718 // Get the footer and beforeFooter and afterFooter lines
7719 // Args are: (tooltipItem, data)
7720 getFooter: function() {
7721 var me = this;
7722 var callbacks = me._options.callbacks;
7723
7724 var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
7725 var footer = callbacks.footer.apply(me, arguments);
7726 var afterFooter = callbacks.afterFooter.apply(me, arguments);
7727
7728 var lines = [];
7729 lines = pushOrConcat(lines, splitNewlines(beforeFooter));
7730 lines = pushOrConcat(lines, splitNewlines(footer));
7731 lines = pushOrConcat(lines, splitNewlines(afterFooter));
7732
7733 return lines;
7734 },
7735
7736 update: function(changed) {
7737 var me = this;
7738 var opts = me._options;
7739
7740 // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
7741 // 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
7742 // which breaks any animations.
7743 var existingModel = me._model;
7744 var model = me._model = getBaseModel(opts);
7745 var active = me._active;
7746
7747 var data = me._data;
7748
7749 // In the case where active.length === 0 we need to keep these at existing values for good animations
7750 var alignment = {
7751 xAlign: existingModel.xAlign,
7752 yAlign: existingModel.yAlign
7753 };
7754 var backgroundPoint = {
7755 x: existingModel.x,
7756 y: existingModel.y
7757 };
7758 var tooltipSize = {
7759 width: existingModel.width,
7760 height: existingModel.height
7761 };
7762 var tooltipPosition = {
7763 x: existingModel.caretX,
7764 y: existingModel.caretY
7765 };
7766
7767 var i, len;
7768
7769 if (active.length) {
7770 model.opacity = 1;
7771
7772 var labelColors = [];
7773 var labelTextColors = [];
7774 tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
7775
7776 var tooltipItems = [];
7777 for (i = 0, len = active.length; i < len; ++i) {
7778 tooltipItems.push(createTooltipItem(active[i]));
7779 }
7780
7781 // If the user provided a filter function, use it to modify the tooltip items
7782 if (opts.filter) {
7783 tooltipItems = tooltipItems.filter(function(a) {
7784 return opts.filter(a, data);
7785 });
7786 }
7787
7788 // If the user provided a sorting function, use it to modify the tooltip items
7789 if (opts.itemSort) {
7790 tooltipItems = tooltipItems.sort(function(a, b) {
7791 return opts.itemSort(a, b, data);
7792 });
7793 }
7794
7795 // Determine colors for boxes
7796 helpers$1.each(tooltipItems, function(tooltipItem) {
7797 labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
7798 labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
7799 });
7800
7801
7802 // Build the Text Lines
7803 model.title = me.getTitle(tooltipItems, data);
7804 model.beforeBody = me.getBeforeBody(tooltipItems, data);
7805 model.body = me.getBody(tooltipItems, data);
7806 model.afterBody = me.getAfterBody(tooltipItems, data);
7807 model.footer = me.getFooter(tooltipItems, data);
7808
7809 // Initial positioning and colors
7810 model.x = tooltipPosition.x;
7811 model.y = tooltipPosition.y;
7812 model.caretPadding = opts.caretPadding;
7813 model.labelColors = labelColors;
7814 model.labelTextColors = labelTextColors;
7815
7816 // data points
7817 model.dataPoints = tooltipItems;
7818
7819 // We need to determine alignment of the tooltip
7820 tooltipSize = getTooltipSize(this, model);
7821 alignment = determineAlignment(this, tooltipSize);
7822 // Final Size and Position
7823 backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
7824 } else {
7825 model.opacity = 0;
7826 }
7827
7828 model.xAlign = alignment.xAlign;
7829 model.yAlign = alignment.yAlign;
7830 model.x = backgroundPoint.x;
7831 model.y = backgroundPoint.y;
7832 model.width = tooltipSize.width;
7833 model.height = tooltipSize.height;
7834
7835 // Point where the caret on the tooltip points to
7836 model.caretX = tooltipPosition.x;
7837 model.caretY = tooltipPosition.y;
7838
7839 me._model = model;
7840
7841 if (changed && opts.custom) {
7842 opts.custom.call(me, model);
7843 }
7844
7845 return me;
7846 },
7847
7848 drawCaret: function(tooltipPoint, size) {
7849 var ctx = this._chart.ctx;
7850 var vm = this._view;
7851 var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
7852
7853 ctx.lineTo(caretPosition.x1, caretPosition.y1);
7854 ctx.lineTo(caretPosition.x2, caretPosition.y2);
7855 ctx.lineTo(caretPosition.x3, caretPosition.y3);
7856 },
7857 getCaretPosition: function(tooltipPoint, size, vm) {
7858 var x1, x2, x3, y1, y2, y3;
7859 var caretSize = vm.caretSize;
7860 var cornerRadius = vm.cornerRadius;
7861 var xAlign = vm.xAlign;
7862 var yAlign = vm.yAlign;
7863 var ptX = tooltipPoint.x;
7864 var ptY = tooltipPoint.y;
7865 var width = size.width;
7866 var height = size.height;
7867
7868 if (yAlign === 'center') {
7869 y2 = ptY + (height / 2);
7870
7871 if (xAlign === 'left') {
7872 x1 = ptX;
7873 x2 = x1 - caretSize;
7874 x3 = x1;
7875
7876 y1 = y2 + caretSize;
7877 y3 = y2 - caretSize;
7878 } else {
7879 x1 = ptX + width;
7880 x2 = x1 + caretSize;
7881 x3 = x1;
7882
7883 y1 = y2 - caretSize;
7884 y3 = y2 + caretSize;
7885 }
7886 } else {
7887 if (xAlign === 'left') {
7888 x2 = ptX + cornerRadius + (caretSize);
7889 x1 = x2 - caretSize;
7890 x3 = x2 + caretSize;
7891 } else if (xAlign === 'right') {
7892 x2 = ptX + width - cornerRadius - caretSize;
7893 x1 = x2 - caretSize;
7894 x3 = x2 + caretSize;
7895 } else {
7896 x2 = vm.caretX;
7897 x1 = x2 - caretSize;
7898 x3 = x2 + caretSize;
7899 }
7900 if (yAlign === 'top') {
7901 y1 = ptY;
7902 y2 = y1 - caretSize;
7903 y3 = y1;
7904 } else {
7905 y1 = ptY + height;
7906 y2 = y1 + caretSize;
7907 y3 = y1;
7908 // invert drawing order
7909 var tmp = x3;
7910 x3 = x1;
7911 x1 = tmp;
7912 }
7913 }
7914 return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
7915 },
7916
7917 drawTitle: function(pt, vm, ctx) {
7918 var title = vm.title;
7919
7920 if (title.length) {
7921 pt.x = getAlignedX(vm, vm._titleAlign);
7922
7923 ctx.textAlign = vm._titleAlign;
7924 ctx.textBaseline = 'top';
7925
7926 var titleFontSize = vm.titleFontSize;
7927 var titleSpacing = vm.titleSpacing;
7928
7929 ctx.fillStyle = vm.titleFontColor;
7930 ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
7931
7932 var i, len;
7933 for (i = 0, len = title.length; i < len; ++i) {
7934 ctx.fillText(title[i], pt.x, pt.y);
7935 pt.y += titleFontSize + titleSpacing; // Line Height and spacing
7936
7937 if (i + 1 === title.length) {
7938 pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
7939 }
7940 }
7941 }
7942 },
7943
7944 drawBody: function(pt, vm, ctx) {
7945 var bodyFontSize = vm.bodyFontSize;
7946 var bodySpacing = vm.bodySpacing;
7947 var bodyAlign = vm._bodyAlign;
7948 var body = vm.body;
7949 var drawColorBoxes = vm.displayColors;
7950 var labelColors = vm.labelColors;
7951 var xLinePadding = 0;
7952 var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;
7953 var textColor;
7954
7955 ctx.textAlign = bodyAlign;
7956 ctx.textBaseline = 'top';
7957 ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
7958
7959 pt.x = getAlignedX(vm, bodyAlign);
7960
7961 // Before Body
7962 var fillLineOfText = function(line) {
7963 ctx.fillText(line, pt.x + xLinePadding, pt.y);
7964 pt.y += bodyFontSize + bodySpacing;
7965 };
7966
7967 // Before body lines
7968 ctx.fillStyle = vm.bodyFontColor;
7969 helpers$1.each(vm.beforeBody, fillLineOfText);
7970
7971 xLinePadding = drawColorBoxes && bodyAlign !== 'right'
7972 ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)
7973 : 0;
7974
7975 // Draw body lines now
7976 helpers$1.each(body, function(bodyItem, i) {
7977 textColor = vm.labelTextColors[i];
7978 ctx.fillStyle = textColor;
7979 helpers$1.each(bodyItem.before, fillLineOfText);
7980
7981 helpers$1.each(bodyItem.lines, function(line) {
7982 // Draw Legend-like boxes if needed
7983 if (drawColorBoxes) {
7984 // Fill a white rect so that colours merge nicely if the opacity is < 1
7985 ctx.fillStyle = vm.legendColorBackground;
7986 ctx.fillRect(colorX, pt.y, bodyFontSize, bodyFontSize);
7987
7988 // Border
7989 ctx.lineWidth = 1;
7990 ctx.strokeStyle = labelColors[i].borderColor;
7991 ctx.strokeRect(colorX, pt.y, bodyFontSize, bodyFontSize);
7992
7993 // Inner square
7994 ctx.fillStyle = labelColors[i].backgroundColor;
7995 ctx.fillRect(colorX + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
7996 ctx.fillStyle = textColor;
7997 }
7998
7999 fillLineOfText(line);
8000 });
8001
8002 helpers$1.each(bodyItem.after, fillLineOfText);
8003 });
8004
8005 // Reset back to 0 for after body
8006 xLinePadding = 0;
8007
8008 // After body lines
8009 helpers$1.each(vm.afterBody, fillLineOfText);
8010 pt.y -= bodySpacing; // Remove last body spacing
8011 },
8012
8013 drawFooter: function(pt, vm, ctx) {
8014 var footer = vm.footer;
8015
8016 if (footer.length) {
8017 pt.x = getAlignedX(vm, vm._footerAlign);
8018 pt.y += vm.footerMarginTop;
8019
8020 ctx.textAlign = vm._footerAlign;
8021 ctx.textBaseline = 'top';
8022
8023 ctx.fillStyle = vm.footerFontColor;
8024 ctx.font = helpers$1.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
8025
8026 helpers$1.each(footer, function(line) {
8027 ctx.fillText(line, pt.x, pt.y);
8028 pt.y += vm.footerFontSize + vm.footerSpacing;
8029 });
8030 }
8031 },
8032
8033 drawBackground: function(pt, vm, ctx, tooltipSize) {
8034 ctx.fillStyle = vm.backgroundColor;
8035 ctx.strokeStyle = vm.borderColor;
8036 ctx.lineWidth = vm.borderWidth;
8037 var xAlign = vm.xAlign;
8038 var yAlign = vm.yAlign;
8039 var x = pt.x;
8040 var y = pt.y;
8041 var width = tooltipSize.width;
8042 var height = tooltipSize.height;
8043 var radius = vm.cornerRadius;
8044
8045 ctx.beginPath();
8046 ctx.moveTo(x + radius, y);
8047 if (yAlign === 'top') {
8048 this.drawCaret(pt, tooltipSize);
8049 }
8050 ctx.lineTo(x + width - radius, y);
8051 ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
8052 if (yAlign === 'center' && xAlign === 'right') {
8053 this.drawCaret(pt, tooltipSize);
8054 }
8055 ctx.lineTo(x + width, y + height - radius);
8056 ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
8057 if (yAlign === 'bottom') {
8058 this.drawCaret(pt, tooltipSize);
8059 }
8060 ctx.lineTo(x + radius, y + height);
8061 ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
8062 if (yAlign === 'center' && xAlign === 'left') {
8063 this.drawCaret(pt, tooltipSize);
8064 }
8065 ctx.lineTo(x, y + radius);
8066 ctx.quadraticCurveTo(x, y, x + radius, y);
8067 ctx.closePath();
8068
8069 ctx.fill();
8070
8071 if (vm.borderWidth > 0) {
8072 ctx.stroke();
8073 }
8074 },
8075
8076 draw: function() {
8077 var ctx = this._chart.ctx;
8078 var vm = this._view;
8079
8080 if (vm.opacity === 0) {
8081 return;
8082 }
8083
8084 var tooltipSize = {
8085 width: vm.width,
8086 height: vm.height
8087 };
8088 var pt = {
8089 x: vm.x,
8090 y: vm.y
8091 };
8092
8093 // IE11/Edge does not like very small opacities, so snap to 0
8094 var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
8095
8096 // Truthy/falsey value for empty tooltip
8097 var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
8098
8099 if (this._options.enabled && hasTooltipContent) {
8100 ctx.save();
8101 ctx.globalAlpha = opacity;
8102
8103 // Draw Background
8104 this.drawBackground(pt, vm, ctx, tooltipSize);
8105
8106 // Draw Title, Body, and Footer
8107 pt.y += vm.yPadding;
8108
8109 // Titles
8110 this.drawTitle(pt, vm, ctx);
8111
8112 // Body
8113 this.drawBody(pt, vm, ctx);
8114
8115 // Footer
8116 this.drawFooter(pt, vm, ctx);
8117
8118 ctx.restore();
8119 }
8120 },
8121
8122 /**
8123 * Handle an event
8124 * @private
8125 * @param {IEvent} event - The event to handle
8126 * @returns {Boolean} true if the tooltip changed
8127 */
8128 handleEvent: function(e) {
8129 var me = this;
8130 var options = me._options;
8131 var changed = false;
8132
8133 me._lastActive = me._lastActive || [];
8134
8135 // Find Active Elements for tooltips
8136 if (e.type === 'mouseout') {
8137 me._active = [];
8138 } else {
8139 me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
8140 }
8141
8142 // Remember Last Actives
8143 changed = !helpers$1.arrayEquals(me._active, me._lastActive);
8144
8145 // Only handle target event on tooltip change
8146 if (changed) {
8147 me._lastActive = me._active;
8148
8149 if (options.enabled || options.custom) {
8150 me._eventPosition = {
8151 x: e.x,
8152 y: e.y
8153 };
8154
8155 me.update(true);
8156 me.pivot();
8157 }
8158 }
8159
8160 return changed;
8161 }
8162});
8163
8164/**
8165 * @namespace Chart.Tooltip.positioners
8166 */
8167var positioners_1 = positioners;
8168
8169var core_tooltip = exports$3;
8170core_tooltip.positioners = positioners_1;
8171
8172var valueOrDefault$6 = helpers$1.valueOrDefault;
8173
8174core_defaults._set('global', {
8175 elements: {},
8176 events: [
8177 'mousemove',
8178 'mouseout',
8179 'click',
8180 'touchstart',
8181 'touchmove'
8182 ],
8183 hover: {
8184 onHover: null,
8185 mode: 'nearest',
8186 intersect: true,
8187 animationDuration: 400
8188 },
8189 onClick: null,
8190 maintainAspectRatio: true,
8191 responsive: true,
8192 responsiveAnimationDuration: 0
8193});
8194
8195function initConfig(config) {
8196 config = config || {};
8197
8198 // Do NOT use configMerge() for the data object because this method merges arrays
8199 // and so would change references to labels and datasets, preventing data updates.
8200 var data = config.data = config.data || {};
8201 data.datasets = data.datasets || [];
8202 data.labels = data.labels || [];
8203
8204 config.options = helpers$1.configMerge(
8205 core_defaults.global,
8206 core_defaults[config.type],
8207 config.options || {});
8208
8209 return config;
8210}
8211
8212function updateConfig(chart) {
8213 var newOptions = chart.options;
8214
8215 helpers$1.each(chart.scales, function(scale) {
8216 core_layouts.removeBox(chart, scale);
8217 });
8218
8219 newOptions = helpers$1.configMerge(
8220 core_defaults.global,
8221 core_defaults[chart.config.type],
8222 newOptions);
8223
8224 chart.options = chart.config.options = newOptions;
8225 chart.ensureScalesHaveIDs();
8226 chart.buildOrUpdateScales();
8227
8228 // Tooltip
8229 chart.tooltip._options = newOptions.tooltips;
8230 chart.tooltip.initialize();
8231}
8232
8233function positionIsHorizontal(position) {
8234 return position === 'top' || position === 'bottom';
8235}
8236
8237var Chart = function(item, config) {
8238 this.construct(item, config);
8239 return this;
8240};
8241
8242helpers$1.extend(Chart.prototype, /** @lends Chart */ {
8243 /**
8244 * @private
8245 */
8246 construct: function(item, config) {
8247 var me = this;
8248
8249 config = initConfig(config);
8250
8251 var context = platform.acquireContext(item, config);
8252 var canvas = context && context.canvas;
8253 var height = canvas && canvas.height;
8254 var width = canvas && canvas.width;
8255
8256 me.id = helpers$1.uid();
8257 me.ctx = context;
8258 me.canvas = canvas;
8259 me.config = config;
8260 me.width = width;
8261 me.height = height;
8262 me.aspectRatio = height ? width / height : null;
8263 me.options = config.options;
8264 me._bufferedRender = false;
8265
8266 /**
8267 * Provided for backward compatibility, Chart and Chart.Controller have been merged,
8268 * the "instance" still need to be defined since it might be called from plugins.
8269 * @prop Chart#chart
8270 * @deprecated since version 2.6.0
8271 * @todo remove at version 3
8272 * @private
8273 */
8274 me.chart = me;
8275 me.controller = me; // chart.chart.controller #inception
8276
8277 // Add the chart instance to the global namespace
8278 Chart.instances[me.id] = me;
8279
8280 // Define alias to the config data: `chart.data === chart.config.data`
8281 Object.defineProperty(me, 'data', {
8282 get: function() {
8283 return me.config.data;
8284 },
8285 set: function(value) {
8286 me.config.data = value;
8287 }
8288 });
8289
8290 if (!context || !canvas) {
8291 // The given item is not a compatible context2d element, let's return before finalizing
8292 // the chart initialization but after setting basic chart / controller properties that
8293 // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
8294 // https://github.com/chartjs/Chart.js/issues/2807
8295 console.error("Failed to create chart: can't acquire context from the given item");
8296 return;
8297 }
8298
8299 me.initialize();
8300 me.update();
8301 },
8302
8303 /**
8304 * @private
8305 */
8306 initialize: function() {
8307 var me = this;
8308
8309 // Before init plugin notification
8310 core_plugins.notify(me, 'beforeInit');
8311
8312 helpers$1.retinaScale(me, me.options.devicePixelRatio);
8313
8314 me.bindEvents();
8315
8316 if (me.options.responsive) {
8317 // Initial resize before chart draws (must be silent to preserve initial animations).
8318 me.resize(true);
8319 }
8320
8321 // Make sure scales have IDs and are built before we build any controllers.
8322 me.ensureScalesHaveIDs();
8323 me.buildOrUpdateScales();
8324 me.initToolTip();
8325
8326 // After init plugin notification
8327 core_plugins.notify(me, 'afterInit');
8328
8329 return me;
8330 },
8331
8332 clear: function() {
8333 helpers$1.canvas.clear(this);
8334 return this;
8335 },
8336
8337 stop: function() {
8338 // Stops any current animation loop occurring
8339 core_animations.cancelAnimation(this);
8340 return this;
8341 },
8342
8343 resize: function(silent) {
8344 var me = this;
8345 var options = me.options;
8346 var canvas = me.canvas;
8347 var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
8348
8349 // the canvas render width and height will be casted to integers so make sure that
8350 // the canvas display style uses the same integer values to avoid blurring effect.
8351
8352 // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
8353 var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas)));
8354 var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas)));
8355
8356 if (me.width === newWidth && me.height === newHeight) {
8357 return;
8358 }
8359
8360 canvas.width = me.width = newWidth;
8361 canvas.height = me.height = newHeight;
8362 canvas.style.width = newWidth + 'px';
8363 canvas.style.height = newHeight + 'px';
8364
8365 helpers$1.retinaScale(me, options.devicePixelRatio);
8366
8367 if (!silent) {
8368 // Notify any plugins about the resize
8369 var newSize = {width: newWidth, height: newHeight};
8370 core_plugins.notify(me, 'resize', [newSize]);
8371
8372 // Notify of resize
8373 if (me.options.onResize) {
8374 me.options.onResize(me, newSize);
8375 }
8376
8377 me.stop();
8378 me.update({
8379 duration: me.options.responsiveAnimationDuration
8380 });
8381 }
8382 },
8383
8384 ensureScalesHaveIDs: function() {
8385 var options = this.options;
8386 var scalesOptions = options.scales || {};
8387 var scaleOptions = options.scale;
8388
8389 helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) {
8390 xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index);
8391 });
8392
8393 helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) {
8394 yAxisOptions.id = yAxisOptions.id || ('y-axis-' + index);
8395 });
8396
8397 if (scaleOptions) {
8398 scaleOptions.id = scaleOptions.id || 'scale';
8399 }
8400 },
8401
8402 /**
8403 * Builds a map of scale ID to scale object for future lookup.
8404 */
8405 buildOrUpdateScales: function() {
8406 var me = this;
8407 var options = me.options;
8408 var scales = me.scales || {};
8409 var items = [];
8410 var updated = Object.keys(scales).reduce(function(obj, id) {
8411 obj[id] = false;
8412 return obj;
8413 }, {});
8414
8415 if (options.scales) {
8416 items = items.concat(
8417 (options.scales.xAxes || []).map(function(xAxisOptions) {
8418 return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
8419 }),
8420 (options.scales.yAxes || []).map(function(yAxisOptions) {
8421 return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
8422 })
8423 );
8424 }
8425
8426 if (options.scale) {
8427 items.push({
8428 options: options.scale,
8429 dtype: 'radialLinear',
8430 isDefault: true,
8431 dposition: 'chartArea'
8432 });
8433 }
8434
8435 helpers$1.each(items, function(item) {
8436 var scaleOptions = item.options;
8437 var id = scaleOptions.id;
8438 var scaleType = valueOrDefault$6(scaleOptions.type, item.dtype);
8439
8440 if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
8441 scaleOptions.position = item.dposition;
8442 }
8443
8444 updated[id] = true;
8445 var scale = null;
8446 if (id in scales && scales[id].type === scaleType) {
8447 scale = scales[id];
8448 scale.options = scaleOptions;
8449 scale.ctx = me.ctx;
8450 scale.chart = me;
8451 } else {
8452 var scaleClass = core_scaleService.getScaleConstructor(scaleType);
8453 if (!scaleClass) {
8454 return;
8455 }
8456 scale = new scaleClass({
8457 id: id,
8458 type: scaleType,
8459 options: scaleOptions,
8460 ctx: me.ctx,
8461 chart: me
8462 });
8463 scales[scale.id] = scale;
8464 }
8465
8466 scale.mergeTicksOptions();
8467
8468 // TODO(SB): I think we should be able to remove this custom case (options.scale)
8469 // and consider it as a regular scale part of the "scales"" map only! This would
8470 // make the logic easier and remove some useless? custom code.
8471 if (item.isDefault) {
8472 me.scale = scale;
8473 }
8474 });
8475 // clear up discarded scales
8476 helpers$1.each(updated, function(hasUpdated, id) {
8477 if (!hasUpdated) {
8478 delete scales[id];
8479 }
8480 });
8481
8482 me.scales = scales;
8483
8484 core_scaleService.addScalesToLayout(this);
8485 },
8486
8487 buildOrUpdateControllers: function() {
8488 var me = this;
8489 var newControllers = [];
8490
8491 helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
8492 var meta = me.getDatasetMeta(datasetIndex);
8493 var type = dataset.type || me.config.type;
8494
8495 if (meta.type && meta.type !== type) {
8496 me.destroyDatasetMeta(datasetIndex);
8497 meta = me.getDatasetMeta(datasetIndex);
8498 }
8499 meta.type = type;
8500
8501 if (meta.controller) {
8502 meta.controller.updateIndex(datasetIndex);
8503 meta.controller.linkScales();
8504 } else {
8505 var ControllerClass = controllers[meta.type];
8506 if (ControllerClass === undefined) {
8507 throw new Error('"' + meta.type + '" is not a chart type.');
8508 }
8509
8510 meta.controller = new ControllerClass(me, datasetIndex);
8511 newControllers.push(meta.controller);
8512 }
8513 }, me);
8514
8515 return newControllers;
8516 },
8517
8518 /**
8519 * Reset the elements of all datasets
8520 * @private
8521 */
8522 resetElements: function() {
8523 var me = this;
8524 helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
8525 me.getDatasetMeta(datasetIndex).controller.reset();
8526 }, me);
8527 },
8528
8529 /**
8530 * Resets the chart back to it's state before the initial animation
8531 */
8532 reset: function() {
8533 this.resetElements();
8534 this.tooltip.initialize();
8535 },
8536
8537 update: function(config) {
8538 var me = this;
8539
8540 if (!config || typeof config !== 'object') {
8541 // backwards compatibility
8542 config = {
8543 duration: config,
8544 lazy: arguments[1]
8545 };
8546 }
8547
8548 updateConfig(me);
8549
8550 // plugins options references might have change, let's invalidate the cache
8551 // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
8552 core_plugins._invalidate(me);
8553
8554 if (core_plugins.notify(me, 'beforeUpdate') === false) {
8555 return;
8556 }
8557
8558 // In case the entire data object changed
8559 me.tooltip._data = me.data;
8560
8561 // Make sure dataset controllers are updated and new controllers are reset
8562 var newControllers = me.buildOrUpdateControllers();
8563
8564 // Make sure all dataset controllers have correct meta data counts
8565 helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
8566 me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements();
8567 }, me);
8568
8569 me.updateLayout();
8570
8571 // Can only reset the new controllers after the scales have been updated
8572 if (me.options.animation && me.options.animation.duration) {
8573 helpers$1.each(newControllers, function(controller) {
8574 controller.reset();
8575 });
8576 }
8577
8578 me.updateDatasets();
8579
8580 // Need to reset tooltip in case it is displayed with elements that are removed
8581 // after update.
8582 me.tooltip.initialize();
8583
8584 // Last active contains items that were previously in the tooltip.
8585 // When we reset the tooltip, we need to clear it
8586 me.lastActive = [];
8587
8588 // Do this before render so that any plugins that need final scale updates can use it
8589 core_plugins.notify(me, 'afterUpdate');
8590
8591 if (me._bufferedRender) {
8592 me._bufferedRequest = {
8593 duration: config.duration,
8594 easing: config.easing,
8595 lazy: config.lazy
8596 };
8597 } else {
8598 me.render(config);
8599 }
8600 },
8601
8602 /**
8603 * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
8604 * hook, in which case, plugins will not be called on `afterLayout`.
8605 * @private
8606 */
8607 updateLayout: function() {
8608 var me = this;
8609
8610 if (core_plugins.notify(me, 'beforeLayout') === false) {
8611 return;
8612 }
8613
8614 core_layouts.update(this, this.width, this.height);
8615
8616 /**
8617 * Provided for backward compatibility, use `afterLayout` instead.
8618 * @method IPlugin#afterScaleUpdate
8619 * @deprecated since version 2.5.0
8620 * @todo remove at version 3
8621 * @private
8622 */
8623 core_plugins.notify(me, 'afterScaleUpdate');
8624 core_plugins.notify(me, 'afterLayout');
8625 },
8626
8627 /**
8628 * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
8629 * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
8630 * @private
8631 */
8632 updateDatasets: function() {
8633 var me = this;
8634
8635 if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) {
8636 return;
8637 }
8638
8639 for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
8640 me.updateDataset(i);
8641 }
8642
8643 core_plugins.notify(me, 'afterDatasetsUpdate');
8644 },
8645
8646 /**
8647 * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
8648 * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
8649 * @private
8650 */
8651 updateDataset: function(index) {
8652 var me = this;
8653 var meta = me.getDatasetMeta(index);
8654 var args = {
8655 meta: meta,
8656 index: index
8657 };
8658
8659 if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
8660 return;
8661 }
8662
8663 meta.controller.update();
8664
8665 core_plugins.notify(me, 'afterDatasetUpdate', [args]);
8666 },
8667
8668 render: function(config) {
8669 var me = this;
8670
8671 if (!config || typeof config !== 'object') {
8672 // backwards compatibility
8673 config = {
8674 duration: config,
8675 lazy: arguments[1]
8676 };
8677 }
8678
8679 var animationOptions = me.options.animation;
8680 var duration = valueOrDefault$6(config.duration, animationOptions && animationOptions.duration);
8681 var lazy = config.lazy;
8682
8683 if (core_plugins.notify(me, 'beforeRender') === false) {
8684 return;
8685 }
8686
8687 var onComplete = function(animation) {
8688 core_plugins.notify(me, 'afterRender');
8689 helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me);
8690 };
8691
8692 if (animationOptions && duration) {
8693 var animation = new core_animation({
8694 numSteps: duration / 16.66, // 60 fps
8695 easing: config.easing || animationOptions.easing,
8696
8697 render: function(chart, animationObject) {
8698 var easingFunction = helpers$1.easing.effects[animationObject.easing];
8699 var currentStep = animationObject.currentStep;
8700 var stepDecimal = currentStep / animationObject.numSteps;
8701
8702 chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
8703 },
8704
8705 onAnimationProgress: animationOptions.onProgress,
8706 onAnimationComplete: onComplete
8707 });
8708
8709 core_animations.addAnimation(me, animation, duration, lazy);
8710 } else {
8711 me.draw();
8712
8713 // See https://github.com/chartjs/Chart.js/issues/3781
8714 onComplete(new core_animation({numSteps: 0, chart: me}));
8715 }
8716
8717 return me;
8718 },
8719
8720 draw: function(easingValue) {
8721 var me = this;
8722
8723 me.clear();
8724
8725 if (helpers$1.isNullOrUndef(easingValue)) {
8726 easingValue = 1;
8727 }
8728
8729 me.transition(easingValue);
8730
8731 if (me.width <= 0 || me.height <= 0) {
8732 return;
8733 }
8734
8735 if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
8736 return;
8737 }
8738
8739 // Draw all the scales
8740 helpers$1.each(me.boxes, function(box) {
8741 box.draw(me.chartArea);
8742 }, me);
8743
8744 if (me.scale) {
8745 me.scale.draw();
8746 }
8747
8748 me.drawDatasets(easingValue);
8749 me._drawTooltip(easingValue);
8750
8751 core_plugins.notify(me, 'afterDraw', [easingValue]);
8752 },
8753
8754 /**
8755 * @private
8756 */
8757 transition: function(easingValue) {
8758 var me = this;
8759
8760 for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
8761 if (me.isDatasetVisible(i)) {
8762 me.getDatasetMeta(i).controller.transition(easingValue);
8763 }
8764 }
8765
8766 me.tooltip.transition(easingValue);
8767 },
8768
8769 /**
8770 * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
8771 * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
8772 * @private
8773 */
8774 drawDatasets: function(easingValue) {
8775 var me = this;
8776
8777 if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
8778 return;
8779 }
8780
8781 // Draw datasets reversed to support proper line stacking
8782 for (var i = (me.data.datasets || []).length - 1; i >= 0; --i) {
8783 if (me.isDatasetVisible(i)) {
8784 me.drawDataset(i, easingValue);
8785 }
8786 }
8787
8788 core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
8789 },
8790
8791 /**
8792 * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
8793 * hook, in which case, plugins will not be called on `afterDatasetDraw`.
8794 * @private
8795 */
8796 drawDataset: function(index, easingValue) {
8797 var me = this;
8798 var meta = me.getDatasetMeta(index);
8799 var args = {
8800 meta: meta,
8801 index: index,
8802 easingValue: easingValue
8803 };
8804
8805 if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
8806 return;
8807 }
8808
8809 meta.controller.draw(easingValue);
8810
8811 core_plugins.notify(me, 'afterDatasetDraw', [args]);
8812 },
8813
8814 /**
8815 * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
8816 * hook, in which case, plugins will not be called on `afterTooltipDraw`.
8817 * @private
8818 */
8819 _drawTooltip: function(easingValue) {
8820 var me = this;
8821 var tooltip = me.tooltip;
8822 var args = {
8823 tooltip: tooltip,
8824 easingValue: easingValue
8825 };
8826
8827 if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
8828 return;
8829 }
8830
8831 tooltip.draw();
8832
8833 core_plugins.notify(me, 'afterTooltipDraw', [args]);
8834 },
8835
8836 // Get the single element that was clicked on
8837 // @return : An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
8838 getElementAtEvent: function(e) {
8839 return core_interaction.modes.single(this, e);
8840 },
8841
8842 getElementsAtEvent: function(e) {
8843 return core_interaction.modes.label(this, e, {intersect: true});
8844 },
8845
8846 getElementsAtXAxis: function(e) {
8847 return core_interaction.modes['x-axis'](this, e, {intersect: true});
8848 },
8849
8850 getElementsAtEventForMode: function(e, mode, options) {
8851 var method = core_interaction.modes[mode];
8852 if (typeof method === 'function') {
8853 return method(this, e, options);
8854 }
8855
8856 return [];
8857 },
8858
8859 getDatasetAtEvent: function(e) {
8860 return core_interaction.modes.dataset(this, e, {intersect: true});
8861 },
8862
8863 getDatasetMeta: function(datasetIndex) {
8864 var me = this;
8865 var dataset = me.data.datasets[datasetIndex];
8866 if (!dataset._meta) {
8867 dataset._meta = {};
8868 }
8869
8870 var meta = dataset._meta[me.id];
8871 if (!meta) {
8872 meta = dataset._meta[me.id] = {
8873 type: null,
8874 data: [],
8875 dataset: null,
8876 controller: null,
8877 hidden: null, // See isDatasetVisible() comment
8878 xAxisID: null,
8879 yAxisID: null
8880 };
8881 }
8882
8883 return meta;
8884 },
8885
8886 getVisibleDatasetCount: function() {
8887 var count = 0;
8888 for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
8889 if (this.isDatasetVisible(i)) {
8890 count++;
8891 }
8892 }
8893 return count;
8894 },
8895
8896 isDatasetVisible: function(datasetIndex) {
8897 var meta = this.getDatasetMeta(datasetIndex);
8898
8899 // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
8900 // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
8901 return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
8902 },
8903
8904 generateLegend: function() {
8905 return this.options.legendCallback(this);
8906 },
8907
8908 /**
8909 * @private
8910 */
8911 destroyDatasetMeta: function(datasetIndex) {
8912 var id = this.id;
8913 var dataset = this.data.datasets[datasetIndex];
8914 var meta = dataset._meta && dataset._meta[id];
8915
8916 if (meta) {
8917 meta.controller.destroy();
8918 delete dataset._meta[id];
8919 }
8920 },
8921
8922 destroy: function() {
8923 var me = this;
8924 var canvas = me.canvas;
8925 var i, ilen;
8926
8927 me.stop();
8928
8929 // dataset controllers need to cleanup associated data
8930 for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
8931 me.destroyDatasetMeta(i);
8932 }
8933
8934 if (canvas) {
8935 me.unbindEvents();
8936 helpers$1.canvas.clear(me);
8937 platform.releaseContext(me.ctx);
8938 me.canvas = null;
8939 me.ctx = null;
8940 }
8941
8942 core_plugins.notify(me, 'destroy');
8943
8944 delete Chart.instances[me.id];
8945 },
8946
8947 toBase64Image: function() {
8948 return this.canvas.toDataURL.apply(this.canvas, arguments);
8949 },
8950
8951 initToolTip: function() {
8952 var me = this;
8953 me.tooltip = new core_tooltip({
8954 _chart: me,
8955 _chartInstance: me, // deprecated, backward compatibility
8956 _data: me.data,
8957 _options: me.options.tooltips
8958 }, me);
8959 },
8960
8961 /**
8962 * @private
8963 */
8964 bindEvents: function() {
8965 var me = this;
8966 var listeners = me._listeners = {};
8967 var listener = function() {
8968 me.eventHandler.apply(me, arguments);
8969 };
8970
8971 helpers$1.each(me.options.events, function(type) {
8972 platform.addEventListener(me, type, listener);
8973 listeners[type] = listener;
8974 });
8975
8976 // Elements used to detect size change should not be injected for non responsive charts.
8977 // See https://github.com/chartjs/Chart.js/issues/2210
8978 if (me.options.responsive) {
8979 listener = function() {
8980 me.resize();
8981 };
8982
8983 platform.addEventListener(me, 'resize', listener);
8984 listeners.resize = listener;
8985 }
8986 },
8987
8988 /**
8989 * @private
8990 */
8991 unbindEvents: function() {
8992 var me = this;
8993 var listeners = me._listeners;
8994 if (!listeners) {
8995 return;
8996 }
8997
8998 delete me._listeners;
8999 helpers$1.each(listeners, function(listener, type) {
9000 platform.removeEventListener(me, type, listener);
9001 });
9002 },
9003
9004 updateHoverStyle: function(elements, mode, enabled) {
9005 var method = enabled ? 'setHoverStyle' : 'removeHoverStyle';
9006 var element, i, ilen;
9007
9008 for (i = 0, ilen = elements.length; i < ilen; ++i) {
9009 element = elements[i];
9010 if (element) {
9011 this.getDatasetMeta(element._datasetIndex).controller[method](element);
9012 }
9013 }
9014 },
9015
9016 /**
9017 * @private
9018 */
9019 eventHandler: function(e) {
9020 var me = this;
9021 var tooltip = me.tooltip;
9022
9023 if (core_plugins.notify(me, 'beforeEvent', [e]) === false) {
9024 return;
9025 }
9026
9027 // Buffer any update calls so that renders do not occur
9028 me._bufferedRender = true;
9029 me._bufferedRequest = null;
9030
9031 var changed = me.handleEvent(e);
9032 // for smooth tooltip animations issue #4989
9033 // the tooltip should be the source of change
9034 // Animation check workaround:
9035 // tooltip._start will be null when tooltip isn't animating
9036 if (tooltip) {
9037 changed = tooltip._start
9038 ? tooltip.handleEvent(e)
9039 : changed | tooltip.handleEvent(e);
9040 }
9041
9042 core_plugins.notify(me, 'afterEvent', [e]);
9043
9044 var bufferedRequest = me._bufferedRequest;
9045 if (bufferedRequest) {
9046 // If we have an update that was triggered, we need to do a normal render
9047 me.render(bufferedRequest);
9048 } else if (changed && !me.animating) {
9049 // If entering, leaving, or changing elements, animate the change via pivot
9050 me.stop();
9051
9052 // We only need to render at this point. Updating will cause scales to be
9053 // recomputed generating flicker & using more memory than necessary.
9054 me.render({
9055 duration: me.options.hover.animationDuration,
9056 lazy: true
9057 });
9058 }
9059
9060 me._bufferedRender = false;
9061 me._bufferedRequest = null;
9062
9063 return me;
9064 },
9065
9066 /**
9067 * Handle an event
9068 * @private
9069 * @param {IEvent} event the event to handle
9070 * @return {Boolean} true if the chart needs to re-render
9071 */
9072 handleEvent: function(e) {
9073 var me = this;
9074 var options = me.options || {};
9075 var hoverOptions = options.hover;
9076 var changed = false;
9077
9078 me.lastActive = me.lastActive || [];
9079
9080 // Find Active Elements for hover and tooltips
9081 if (e.type === 'mouseout') {
9082 me.active = [];
9083 } else {
9084 me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
9085 }
9086
9087 // Invoke onHover hook
9088 // Need to call with native event here to not break backwards compatibility
9089 helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
9090
9091 if (e.type === 'mouseup' || e.type === 'click') {
9092 if (options.onClick) {
9093 // Use e.native here for backwards compatibility
9094 options.onClick.call(me, e.native, me.active);
9095 }
9096 }
9097
9098 // Remove styling for last active (even if it may still be active)
9099 if (me.lastActive.length) {
9100 me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
9101 }
9102
9103 // Built in hover styling
9104 if (me.active.length && hoverOptions.mode) {
9105 me.updateHoverStyle(me.active, hoverOptions.mode, true);
9106 }
9107
9108 changed = !helpers$1.arrayEquals(me.active, me.lastActive);
9109
9110 // Remember Last Actives
9111 me.lastActive = me.active;
9112
9113 return changed;
9114 }
9115});
9116
9117/**
9118 * NOTE(SB) We actually don't use this container anymore but we need to keep it
9119 * for backward compatibility. Though, it can still be useful for plugins that
9120 * would need to work on multiple charts?!
9121 */
9122Chart.instances = {};
9123
9124var core_controller = Chart;
9125
9126// DEPRECATIONS
9127
9128/**
9129 * Provided for backward compatibility, use Chart instead.
9130 * @class Chart.Controller
9131 * @deprecated since version 2.6
9132 * @todo remove at version 3
9133 * @private
9134 */
9135Chart.Controller = Chart;
9136
9137/**
9138 * Provided for backward compatibility, not available anymore.
9139 * @namespace Chart
9140 * @deprecated since version 2.8
9141 * @todo remove at version 3
9142 * @private
9143 */
9144Chart.types = {};
9145
9146var core_helpers = function() {
9147
9148 // -- Basic js utility methods
9149
9150 helpers$1.configMerge = function(/* objects ... */) {
9151 return helpers$1.merge(helpers$1.clone(arguments[0]), [].slice.call(arguments, 1), {
9152 merger: function(key, target, source, options) {
9153 var tval = target[key] || {};
9154 var sval = source[key];
9155
9156 if (key === 'scales') {
9157 // scale config merging is complex. Add our own function here for that
9158 target[key] = helpers$1.scaleMerge(tval, sval);
9159 } else if (key === 'scale') {
9160 // used in polar area & radar charts since there is only one scale
9161 target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]);
9162 } else {
9163 helpers$1._merger(key, target, source, options);
9164 }
9165 }
9166 });
9167 };
9168
9169 helpers$1.scaleMerge = function(/* objects ... */) {
9170 return helpers$1.merge(helpers$1.clone(arguments[0]), [].slice.call(arguments, 1), {
9171 merger: function(key, target, source, options) {
9172 if (key === 'xAxes' || key === 'yAxes') {
9173 var slen = source[key].length;
9174 var i, type, scale;
9175
9176 if (!target[key]) {
9177 target[key] = [];
9178 }
9179
9180 for (i = 0; i < slen; ++i) {
9181 scale = source[key][i];
9182 type = helpers$1.valueOrDefault(scale.type, key === 'xAxes' ? 'category' : 'linear');
9183
9184 if (i >= target[key].length) {
9185 target[key].push({});
9186 }
9187
9188 if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
9189 // new/untyped scale or type changed: let's apply the new defaults
9190 // then merge source scale to correctly overwrite the defaults.
9191 helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);
9192 } else {
9193 // scales type are the same
9194 helpers$1.merge(target[key][i], scale);
9195 }
9196 }
9197 } else {
9198 helpers$1._merger(key, target, source, options);
9199 }
9200 }
9201 });
9202 };
9203
9204 helpers$1.where = function(collection, filterCallback) {
9205 if (helpers$1.isArray(collection) && Array.prototype.filter) {
9206 return collection.filter(filterCallback);
9207 }
9208 var filtered = [];
9209
9210 helpers$1.each(collection, function(item) {
9211 if (filterCallback(item)) {
9212 filtered.push(item);
9213 }
9214 });
9215
9216 return filtered;
9217 };
9218 helpers$1.findIndex = Array.prototype.findIndex ?
9219 function(array, callback, scope) {
9220 return array.findIndex(callback, scope);
9221 } :
9222 function(array, callback, scope) {
9223 scope = scope === undefined ? array : scope;
9224 for (var i = 0, ilen = array.length; i < ilen; ++i) {
9225 if (callback.call(scope, array[i], i, array)) {
9226 return i;
9227 }
9228 }
9229 return -1;
9230 };
9231 helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
9232 // Default to start of the array
9233 if (helpers$1.isNullOrUndef(startIndex)) {
9234 startIndex = -1;
9235 }
9236 for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
9237 var currentItem = arrayToSearch[i];
9238 if (filterCallback(currentItem)) {
9239 return currentItem;
9240 }
9241 }
9242 };
9243 helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
9244 // Default to end of the array
9245 if (helpers$1.isNullOrUndef(startIndex)) {
9246 startIndex = arrayToSearch.length;
9247 }
9248 for (var i = startIndex - 1; i >= 0; i--) {
9249 var currentItem = arrayToSearch[i];
9250 if (filterCallback(currentItem)) {
9251 return currentItem;
9252 }
9253 }
9254 };
9255
9256 // -- Math methods
9257 helpers$1.isNumber = function(n) {
9258 return !isNaN(parseFloat(n)) && isFinite(n);
9259 };
9260 helpers$1.almostEquals = function(x, y, epsilon) {
9261 return Math.abs(x - y) < epsilon;
9262 };
9263 helpers$1.almostWhole = function(x, epsilon) {
9264 var rounded = Math.round(x);
9265 return (((rounded - epsilon) < x) && ((rounded + epsilon) > x));
9266 };
9267 helpers$1.max = function(array) {
9268 return array.reduce(function(max, value) {
9269 if (!isNaN(value)) {
9270 return Math.max(max, value);
9271 }
9272 return max;
9273 }, Number.NEGATIVE_INFINITY);
9274 };
9275 helpers$1.min = function(array) {
9276 return array.reduce(function(min, value) {
9277 if (!isNaN(value)) {
9278 return Math.min(min, value);
9279 }
9280 return min;
9281 }, Number.POSITIVE_INFINITY);
9282 };
9283 helpers$1.sign = Math.sign ?
9284 function(x) {
9285 return Math.sign(x);
9286 } :
9287 function(x) {
9288 x = +x; // convert to a number
9289 if (x === 0 || isNaN(x)) {
9290 return x;
9291 }
9292 return x > 0 ? 1 : -1;
9293 };
9294 helpers$1.log10 = Math.log10 ?
9295 function(x) {
9296 return Math.log10(x);
9297 } :
9298 function(x) {
9299 var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
9300 // Check for whole powers of 10,
9301 // which due to floating point rounding error should be corrected.
9302 var powerOf10 = Math.round(exponent);
9303 var isPowerOf10 = x === Math.pow(10, powerOf10);
9304
9305 return isPowerOf10 ? powerOf10 : exponent;
9306 };
9307 helpers$1.toRadians = function(degrees) {
9308 return degrees * (Math.PI / 180);
9309 };
9310 helpers$1.toDegrees = function(radians) {
9311 return radians * (180 / Math.PI);
9312 };
9313
9314 /**
9315 * Returns the number of decimal places
9316 * i.e. the number of digits after the decimal point, of the value of this Number.
9317 * @param {Number} x - A number.
9318 * @returns {Number} The number of decimal places.
9319 */
9320 helpers$1.decimalPlaces = function(x) {
9321 if (!helpers$1.isFinite(x)) {
9322 return;
9323 }
9324 var e = 1;
9325 var p = 0;
9326 while (Math.round(x * e) / e !== x) {
9327 e *= 10;
9328 p++;
9329 }
9330 return p;
9331 };
9332
9333 // Gets the angle from vertical upright to the point about a centre.
9334 helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) {
9335 var distanceFromXCenter = anglePoint.x - centrePoint.x;
9336 var distanceFromYCenter = anglePoint.y - centrePoint.y;
9337 var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
9338
9339 var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
9340
9341 if (angle < (-0.5 * Math.PI)) {
9342 angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
9343 }
9344
9345 return {
9346 angle: angle,
9347 distance: radialDistanceFromCenter
9348 };
9349 };
9350 helpers$1.distanceBetweenPoints = function(pt1, pt2) {
9351 return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
9352 };
9353
9354 /**
9355 * Provided for backward compatibility, not available anymore
9356 * @function Chart.helpers.aliasPixel
9357 * @deprecated since version 2.8.0
9358 * @todo remove at version 3
9359 */
9360 helpers$1.aliasPixel = function(pixelWidth) {
9361 return (pixelWidth % 2 === 0) ? 0 : 0.5;
9362 };
9363
9364 /**
9365 * Returns the aligned pixel value to avoid anti-aliasing blur
9366 * @param {Chart} chart - The chart instance.
9367 * @param {Number} pixel - A pixel value.
9368 * @param {Number} width - The width of the element.
9369 * @returns {Number} The aligned pixel value.
9370 * @private
9371 */
9372 helpers$1._alignPixel = function(chart, pixel, width) {
9373 var devicePixelRatio = chart.currentDevicePixelRatio;
9374 var halfWidth = width / 2;
9375 return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
9376 };
9377
9378 helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
9379 // Props to Rob Spencer at scaled innovation for his post on splining between points
9380 // http://scaledinnovation.com/analytics/splines/aboutSplines.html
9381
9382 // This function must also respect "skipped" points
9383
9384 var previous = firstPoint.skip ? middlePoint : firstPoint;
9385 var current = middlePoint;
9386 var next = afterPoint.skip ? middlePoint : afterPoint;
9387
9388 var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
9389 var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
9390
9391 var s01 = d01 / (d01 + d12);
9392 var s12 = d12 / (d01 + d12);
9393
9394 // If all points are the same, s01 & s02 will be inf
9395 s01 = isNaN(s01) ? 0 : s01;
9396 s12 = isNaN(s12) ? 0 : s12;
9397
9398 var fa = t * s01; // scaling factor for triangle Ta
9399 var fb = t * s12;
9400
9401 return {
9402 previous: {
9403 x: current.x - fa * (next.x - previous.x),
9404 y: current.y - fa * (next.y - previous.y)
9405 },
9406 next: {
9407 x: current.x + fb * (next.x - previous.x),
9408 y: current.y + fb * (next.y - previous.y)
9409 }
9410 };
9411 };
9412 helpers$1.EPSILON = Number.EPSILON || 1e-14;
9413 helpers$1.splineCurveMonotone = function(points) {
9414 // This function calculates Bézier control points in a similar way than |splineCurve|,
9415 // but preserves monotonicity of the provided data and ensures no local extremums are added
9416 // between the dataset discrete points due to the interpolation.
9417 // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
9418
9419 var pointsWithTangents = (points || []).map(function(point) {
9420 return {
9421 model: point._model,
9422 deltaK: 0,
9423 mK: 0
9424 };
9425 });
9426
9427 // Calculate slopes (deltaK) and initialize tangents (mK)
9428 var pointsLen = pointsWithTangents.length;
9429 var i, pointBefore, pointCurrent, pointAfter;
9430 for (i = 0; i < pointsLen; ++i) {
9431 pointCurrent = pointsWithTangents[i];
9432 if (pointCurrent.model.skip) {
9433 continue;
9434 }
9435
9436 pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
9437 pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
9438 if (pointAfter && !pointAfter.model.skip) {
9439 var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
9440
9441 // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
9442 pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
9443 }
9444
9445 if (!pointBefore || pointBefore.model.skip) {
9446 pointCurrent.mK = pointCurrent.deltaK;
9447 } else if (!pointAfter || pointAfter.model.skip) {
9448 pointCurrent.mK = pointBefore.deltaK;
9449 } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
9450 pointCurrent.mK = 0;
9451 } else {
9452 pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
9453 }
9454 }
9455
9456 // Adjust tangents to ensure monotonic properties
9457 var alphaK, betaK, tauK, squaredMagnitude;
9458 for (i = 0; i < pointsLen - 1; ++i) {
9459 pointCurrent = pointsWithTangents[i];
9460 pointAfter = pointsWithTangents[i + 1];
9461 if (pointCurrent.model.skip || pointAfter.model.skip) {
9462 continue;
9463 }
9464
9465 if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
9466 pointCurrent.mK = pointAfter.mK = 0;
9467 continue;
9468 }
9469
9470 alphaK = pointCurrent.mK / pointCurrent.deltaK;
9471 betaK = pointAfter.mK / pointCurrent.deltaK;
9472 squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
9473 if (squaredMagnitude <= 9) {
9474 continue;
9475 }
9476
9477 tauK = 3 / Math.sqrt(squaredMagnitude);
9478 pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
9479 pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
9480 }
9481
9482 // Compute control points
9483 var deltaX;
9484 for (i = 0; i < pointsLen; ++i) {
9485 pointCurrent = pointsWithTangents[i];
9486 if (pointCurrent.model.skip) {
9487 continue;
9488 }
9489
9490 pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
9491 pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
9492 if (pointBefore && !pointBefore.model.skip) {
9493 deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
9494 pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
9495 pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
9496 }
9497 if (pointAfter && !pointAfter.model.skip) {
9498 deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
9499 pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
9500 pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
9501 }
9502 }
9503 };
9504 helpers$1.nextItem = function(collection, index, loop) {
9505 if (loop) {
9506 return index >= collection.length - 1 ? collection[0] : collection[index + 1];
9507 }
9508 return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
9509 };
9510 helpers$1.previousItem = function(collection, index, loop) {
9511 if (loop) {
9512 return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
9513 }
9514 return index <= 0 ? collection[0] : collection[index - 1];
9515 };
9516 // Implementation of the nice number algorithm used in determining where axis labels will go
9517 helpers$1.niceNum = function(range, round) {
9518 var exponent = Math.floor(helpers$1.log10(range));
9519 var fraction = range / Math.pow(10, exponent);
9520 var niceFraction;
9521
9522 if (round) {
9523 if (fraction < 1.5) {
9524 niceFraction = 1;
9525 } else if (fraction < 3) {
9526 niceFraction = 2;
9527 } else if (fraction < 7) {
9528 niceFraction = 5;
9529 } else {
9530 niceFraction = 10;
9531 }
9532 } else if (fraction <= 1.0) {
9533 niceFraction = 1;
9534 } else if (fraction <= 2) {
9535 niceFraction = 2;
9536 } else if (fraction <= 5) {
9537 niceFraction = 5;
9538 } else {
9539 niceFraction = 10;
9540 }
9541
9542 return niceFraction * Math.pow(10, exponent);
9543 };
9544 // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
9545 helpers$1.requestAnimFrame = (function() {
9546 if (typeof window === 'undefined') {
9547 return function(callback) {
9548 callback();
9549 };
9550 }
9551 return window.requestAnimationFrame ||
9552 window.webkitRequestAnimationFrame ||
9553 window.mozRequestAnimationFrame ||
9554 window.oRequestAnimationFrame ||
9555 window.msRequestAnimationFrame ||
9556 function(callback) {
9557 return window.setTimeout(callback, 1000 / 60);
9558 };
9559 }());
9560 // -- DOM methods
9561 helpers$1.getRelativePosition = function(evt, chart) {
9562 var mouseX, mouseY;
9563 var e = evt.originalEvent || evt;
9564 var canvas = evt.target || evt.srcElement;
9565 var boundingRect = canvas.getBoundingClientRect();
9566
9567 var touches = e.touches;
9568 if (touches && touches.length > 0) {
9569 mouseX = touches[0].clientX;
9570 mouseY = touches[0].clientY;
9571
9572 } else {
9573 mouseX = e.clientX;
9574 mouseY = e.clientY;
9575 }
9576
9577 // Scale mouse coordinates into canvas coordinates
9578 // by following the pattern laid out by 'jerryj' in the comments of
9579 // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
9580 var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left'));
9581 var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top'));
9582 var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right'));
9583 var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom'));
9584 var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
9585 var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
9586
9587 // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
9588 // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
9589 mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
9590 mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
9591
9592 return {
9593 x: mouseX,
9594 y: mouseY
9595 };
9596
9597 };
9598
9599 // Private helper function to convert max-width/max-height values that may be percentages into a number
9600 function parseMaxStyle(styleValue, node, parentProperty) {
9601 var valueInPixels;
9602 if (typeof styleValue === 'string') {
9603 valueInPixels = parseInt(styleValue, 10);
9604
9605 if (styleValue.indexOf('%') !== -1) {
9606 // percentage * size in dimension
9607 valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
9608 }
9609 } else {
9610 valueInPixels = styleValue;
9611 }
9612
9613 return valueInPixels;
9614 }
9615
9616 /**
9617 * Returns if the given value contains an effective constraint.
9618 * @private
9619 */
9620 function isConstrainedValue(value) {
9621 return value !== undefined && value !== null && value !== 'none';
9622 }
9623
9624 // Private helper to get a constraint dimension
9625 // @param domNode : the node to check the constraint on
9626 // @param maxStyle : the style that defines the maximum for the direction we are using (maxWidth / maxHeight)
9627 // @param percentageProperty : property of parent to use when calculating width as a percentage
9628 // @see https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser
9629 function getConstraintDimension(domNode, maxStyle, percentageProperty) {
9630 var view = document.defaultView;
9631 var parentNode = helpers$1._getParentNode(domNode);
9632 var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
9633 var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
9634 var hasCNode = isConstrainedValue(constrainedNode);
9635 var hasCContainer = isConstrainedValue(constrainedContainer);
9636 var infinity = Number.POSITIVE_INFINITY;
9637
9638 if (hasCNode || hasCContainer) {
9639 return Math.min(
9640 hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
9641 hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
9642 }
9643
9644 return 'none';
9645 }
9646 // returns Number or undefined if no constraint
9647 helpers$1.getConstraintWidth = function(domNode) {
9648 return getConstraintDimension(domNode, 'max-width', 'clientWidth');
9649 };
9650 // returns Number or undefined if no constraint
9651 helpers$1.getConstraintHeight = function(domNode) {
9652 return getConstraintDimension(domNode, 'max-height', 'clientHeight');
9653 };
9654 /**
9655 * @private
9656 */
9657 helpers$1._calculatePadding = function(container, padding, parentDimension) {
9658 padding = helpers$1.getStyle(container, padding);
9659
9660 return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
9661 };
9662 /**
9663 * @private
9664 */
9665 helpers$1._getParentNode = function(domNode) {
9666 var parent = domNode.parentNode;
9667 if (parent && parent.toString() === '[object ShadowRoot]') {
9668 parent = parent.host;
9669 }
9670 return parent;
9671 };
9672 helpers$1.getMaximumWidth = function(domNode) {
9673 var container = helpers$1._getParentNode(domNode);
9674 if (!container) {
9675 return domNode.clientWidth;
9676 }
9677
9678 var clientWidth = container.clientWidth;
9679 var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth);
9680 var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth);
9681
9682 var w = clientWidth - paddingLeft - paddingRight;
9683 var cw = helpers$1.getConstraintWidth(domNode);
9684 return isNaN(cw) ? w : Math.min(w, cw);
9685 };
9686 helpers$1.getMaximumHeight = function(domNode) {
9687 var container = helpers$1._getParentNode(domNode);
9688 if (!container) {
9689 return domNode.clientHeight;
9690 }
9691
9692 var clientHeight = container.clientHeight;
9693 var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight);
9694 var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight);
9695
9696 var h = clientHeight - paddingTop - paddingBottom;
9697 var ch = helpers$1.getConstraintHeight(domNode);
9698 return isNaN(ch) ? h : Math.min(h, ch);
9699 };
9700 helpers$1.getStyle = function(el, property) {
9701 return el.currentStyle ?
9702 el.currentStyle[property] :
9703 document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
9704 };
9705 helpers$1.retinaScale = function(chart, forceRatio) {
9706 var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
9707 if (pixelRatio === 1) {
9708 return;
9709 }
9710
9711 var canvas = chart.canvas;
9712 var height = chart.height;
9713 var width = chart.width;
9714
9715 canvas.height = height * pixelRatio;
9716 canvas.width = width * pixelRatio;
9717 chart.ctx.scale(pixelRatio, pixelRatio);
9718
9719 // If no style has been set on the canvas, the render size is used as display size,
9720 // making the chart visually bigger, so let's enforce it to the "correct" values.
9721 // See https://github.com/chartjs/Chart.js/issues/3575
9722 if (!canvas.style.height && !canvas.style.width) {
9723 canvas.style.height = height + 'px';
9724 canvas.style.width = width + 'px';
9725 }
9726 };
9727 // -- Canvas methods
9728 helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) {
9729 return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
9730 };
9731 helpers$1.longestText = function(ctx, font, arrayOfThings, cache) {
9732 cache = cache || {};
9733 var data = cache.data = cache.data || {};
9734 var gc = cache.garbageCollect = cache.garbageCollect || [];
9735
9736 if (cache.font !== font) {
9737 data = cache.data = {};
9738 gc = cache.garbageCollect = [];
9739 cache.font = font;
9740 }
9741
9742 ctx.font = font;
9743 var longest = 0;
9744 helpers$1.each(arrayOfThings, function(thing) {
9745 // Undefined strings and arrays should not be measured
9746 if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) {
9747 longest = helpers$1.measureText(ctx, data, gc, longest, thing);
9748 } else if (helpers$1.isArray(thing)) {
9749 // if it is an array lets measure each element
9750 // to do maybe simplify this function a bit so we can do this more recursively?
9751 helpers$1.each(thing, function(nestedThing) {
9752 // Undefined strings and arrays should not be measured
9753 if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) {
9754 longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing);
9755 }
9756 });
9757 }
9758 });
9759
9760 var gcLen = gc.length / 2;
9761 if (gcLen > arrayOfThings.length) {
9762 for (var i = 0; i < gcLen; i++) {
9763 delete data[gc[i]];
9764 }
9765 gc.splice(0, gcLen);
9766 }
9767 return longest;
9768 };
9769 helpers$1.measureText = function(ctx, data, gc, longest, string) {
9770 var textWidth = data[string];
9771 if (!textWidth) {
9772 textWidth = data[string] = ctx.measureText(string).width;
9773 gc.push(string);
9774 }
9775 if (textWidth > longest) {
9776 longest = textWidth;
9777 }
9778 return longest;
9779 };
9780 helpers$1.numberOfLabelLines = function(arrayOfThings) {
9781 var numberOfLines = 1;
9782 helpers$1.each(arrayOfThings, function(thing) {
9783 if (helpers$1.isArray(thing)) {
9784 if (thing.length > numberOfLines) {
9785 numberOfLines = thing.length;
9786 }
9787 }
9788 });
9789 return numberOfLines;
9790 };
9791
9792 helpers$1.color = !chartjsColor ?
9793 function(value) {
9794 console.error('Color.js not found!');
9795 return value;
9796 } :
9797 function(value) {
9798 /* global CanvasGradient */
9799 if (value instanceof CanvasGradient) {
9800 value = core_defaults.global.defaultColor;
9801 }
9802
9803 return chartjsColor(value);
9804 };
9805
9806 helpers$1.getHoverColor = function(colorValue) {
9807 /* global CanvasPattern */
9808 return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
9809 colorValue :
9810 helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString();
9811 };
9812};
9813
9814/**
9815 * @namespace Chart._adapters
9816 * @since 2.8.0
9817 * @private
9818 */
9819
9820function abstract() {
9821 throw new Error(
9822 'This method is not implemented: either no adapter can ' +
9823 'be found or an incomplete integration was provided.'
9824 );
9825}
9826
9827/**
9828 * Date adapter (current used by the time scale)
9829 * @namespace Chart._adapters._date
9830 * @memberof Chart._adapters
9831 * @private
9832 */
9833
9834/**
9835 * Currently supported unit string values.
9836 * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
9837 * @memberof Chart._adapters._date
9838 * @name Unit
9839 */
9840
9841/** @lends Chart._adapters._date */
9842var _date = {
9843 /**
9844 * Returns a map of time formats for the supported units.
9845 * @returns {{string: string}}
9846 */
9847 formats: abstract,
9848
9849 /**
9850 * Returns a map of date/time formats for the following presets:
9851 * 'full': date + time + millisecond
9852 * 'time': date + time
9853 * 'date': date
9854 * @returns {{string: string}}
9855 */
9856 presets: abstract,
9857
9858 /**
9859 * Parses the given `value` and return the associated timestamp.
9860 * @param {any} value - the value to parse (usually comes from the data)
9861 * @param {string} [format] - the expected data format
9862 * @returns {(number|null)}
9863 * @function
9864 */
9865 parse: abstract,
9866
9867 /**
9868 * Returns the formatted date in the specified `format` for a given `timestamp`.
9869 * @param {number} timestamp - the timestamp to format
9870 * @param {string} format - the date/time token
9871 * @return {string}
9872 * @function
9873 */
9874 format: abstract,
9875
9876 /**
9877 * Adds the specified `amount` of `unit` to the given `timestamp`.
9878 * @param {number} timestamp - the input timestamp
9879 * @param {number} amount - the amount to add
9880 * @param {Unit} unit - the unit as string
9881 * @return {number}
9882 * @function
9883 */
9884 add: abstract,
9885
9886 /**
9887 * Returns the number of `unit` between the given timestamps.
9888 * @param {number} max - the input timestamp (reference)
9889 * @param {number} min - the timestamp to substract
9890 * @param {Unit} unit - the unit as string
9891 * @return {number}
9892 * @function
9893 */
9894 diff: abstract,
9895
9896 /**
9897 * Returns start of `unit` for the given `timestamp`.
9898 * @param {number} timestamp - the input timestamp
9899 * @param {Unit} unit - the unit as string
9900 * @param {number} [weekday] - the ISO day of the week with 1 being Monday
9901 * and 7 being Sunday (only needed if param *unit* is `isoWeek`).
9902 * @function
9903 */
9904 startOf: abstract,
9905
9906 /**
9907 * Returns end of `unit` for the given `timestamp`.
9908 * @param {number} timestamp - the input timestamp
9909 * @param {Unit} unit - the unit as string
9910 * @function
9911 */
9912 endOf: abstract,
9913
9914 // DEPRECATIONS
9915
9916 /**
9917 * Provided for backward compatibility for scale.getValueForPixel(),
9918 * this method should be overridden only by the moment adapter.
9919 * @deprecated since version 2.8.0
9920 * @todo remove at version 3
9921 * @private
9922 */
9923 _create: function(value) {
9924 return value;
9925 }
9926};
9927
9928var core_adapters = {
9929 _date: _date
9930};
9931
9932/**
9933 * Namespace to hold static tick generation functions
9934 * @namespace Chart.Ticks
9935 */
9936var core_ticks = {
9937 /**
9938 * Namespace to hold formatters for different types of ticks
9939 * @namespace Chart.Ticks.formatters
9940 */
9941 formatters: {
9942 /**
9943 * Formatter for value labels
9944 * @method Chart.Ticks.formatters.values
9945 * @param value the value to display
9946 * @return {String|Array} the label to display
9947 */
9948 values: function(value) {
9949 return helpers$1.isArray(value) ? value : '' + value;
9950 },
9951
9952 /**
9953 * Formatter for linear numeric ticks
9954 * @method Chart.Ticks.formatters.linear
9955 * @param tickValue {Number} the value to be formatted
9956 * @param index {Number} the position of the tickValue parameter in the ticks array
9957 * @param ticks {Array<Number>} the list of ticks being converted
9958 * @return {String} string representation of the tickValue parameter
9959 */
9960 linear: function(tickValue, index, ticks) {
9961 // If we have lots of ticks, don't use the ones
9962 var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
9963
9964 // If we have a number like 2.5 as the delta, figure out how many decimal places we need
9965 if (Math.abs(delta) > 1) {
9966 if (tickValue !== Math.floor(tickValue)) {
9967 // not an integer
9968 delta = tickValue - Math.floor(tickValue);
9969 }
9970 }
9971
9972 var logDelta = helpers$1.log10(Math.abs(delta));
9973 var tickString = '';
9974
9975 if (tickValue !== 0) {
9976 var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
9977 if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
9978 var logTick = helpers$1.log10(Math.abs(tickValue));
9979 tickString = tickValue.toExponential(Math.floor(logTick) - Math.floor(logDelta));
9980 } else {
9981 var numDecimal = -1 * Math.floor(logDelta);
9982 numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
9983 tickString = tickValue.toFixed(numDecimal);
9984 }
9985 } else {
9986 tickString = '0'; // never show decimal places for 0
9987 }
9988
9989 return tickString;
9990 },
9991
9992 logarithmic: function(tickValue, index, ticks) {
9993 var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue))));
9994
9995 if (tickValue === 0) {
9996 return '0';
9997 } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
9998 return tickValue.toExponential();
9999 }
10000 return '';
10001 }
10002 }
10003};
10004
10005var valueOrDefault$7 = helpers$1.valueOrDefault;
10006var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault;
10007
10008core_defaults._set('scale', {
10009 display: true,
10010 position: 'left',
10011 offset: false,
10012
10013 // grid line settings
10014 gridLines: {
10015 display: true,
10016 color: 'rgba(0, 0, 0, 0.1)',
10017 lineWidth: 1,
10018 drawBorder: true,
10019 drawOnChartArea: true,
10020 drawTicks: true,
10021 tickMarkLength: 10,
10022 zeroLineWidth: 1,
10023 zeroLineColor: 'rgba(0,0,0,0.25)',
10024 zeroLineBorderDash: [],
10025 zeroLineBorderDashOffset: 0.0,
10026 offsetGridLines: false,
10027 borderDash: [],
10028 borderDashOffset: 0.0
10029 },
10030
10031 // scale label
10032 scaleLabel: {
10033 // display property
10034 display: false,
10035
10036 // actual label
10037 labelString: '',
10038
10039 // top/bottom padding
10040 padding: {
10041 top: 4,
10042 bottom: 4
10043 }
10044 },
10045
10046 // label settings
10047 ticks: {
10048 beginAtZero: false,
10049 minRotation: 0,
10050 maxRotation: 50,
10051 mirror: false,
10052 padding: 0,
10053 reverse: false,
10054 display: true,
10055 autoSkip: true,
10056 autoSkipPadding: 0,
10057 labelOffset: 0,
10058 // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
10059 callback: core_ticks.formatters.values,
10060 minor: {},
10061 major: {}
10062 }
10063});
10064
10065function labelsFromTicks(ticks) {
10066 var labels = [];
10067 var i, ilen;
10068
10069 for (i = 0, ilen = ticks.length; i < ilen; ++i) {
10070 labels.push(ticks[i].label);
10071 }
10072
10073 return labels;
10074}
10075
10076function getPixelForGridLine(scale, index, offsetGridLines) {
10077 var lineValue = scale.getPixelForTick(index);
10078
10079 if (offsetGridLines) {
10080 if (scale.getTicks().length === 1) {
10081 lineValue -= scale.isHorizontal() ?
10082 Math.max(lineValue - scale.left, scale.right - lineValue) :
10083 Math.max(lineValue - scale.top, scale.bottom - lineValue);
10084 } else if (index === 0) {
10085 lineValue -= (scale.getPixelForTick(1) - lineValue) / 2;
10086 } else {
10087 lineValue -= (lineValue - scale.getPixelForTick(index - 1)) / 2;
10088 }
10089 }
10090 return lineValue;
10091}
10092
10093function computeTextSize(context, tick, font) {
10094 return helpers$1.isArray(tick) ?
10095 helpers$1.longestText(context, font, tick) :
10096 context.measureText(tick).width;
10097}
10098
10099var core_scale = core_element.extend({
10100 /**
10101 * Get the padding needed for the scale
10102 * @method getPadding
10103 * @private
10104 * @returns {Padding} the necessary padding
10105 */
10106 getPadding: function() {
10107 var me = this;
10108 return {
10109 left: me.paddingLeft || 0,
10110 top: me.paddingTop || 0,
10111 right: me.paddingRight || 0,
10112 bottom: me.paddingBottom || 0
10113 };
10114 },
10115
10116 /**
10117 * Returns the scale tick objects ({label, major})
10118 * @since 2.7
10119 */
10120 getTicks: function() {
10121 return this._ticks;
10122 },
10123
10124 // These methods are ordered by lifecyle. Utilities then follow.
10125 // Any function defined here is inherited by all scale types.
10126 // Any function can be extended by the scale type
10127
10128 mergeTicksOptions: function() {
10129 var ticks = this.options.ticks;
10130 if (ticks.minor === false) {
10131 ticks.minor = {
10132 display: false
10133 };
10134 }
10135 if (ticks.major === false) {
10136 ticks.major = {
10137 display: false
10138 };
10139 }
10140 for (var key in ticks) {
10141 if (key !== 'major' && key !== 'minor') {
10142 if (typeof ticks.minor[key] === 'undefined') {
10143 ticks.minor[key] = ticks[key];
10144 }
10145 if (typeof ticks.major[key] === 'undefined') {
10146 ticks.major[key] = ticks[key];
10147 }
10148 }
10149 }
10150 },
10151 beforeUpdate: function() {
10152 helpers$1.callback(this.options.beforeUpdate, [this]);
10153 },
10154
10155 update: function(maxWidth, maxHeight, margins) {
10156 var me = this;
10157 var i, ilen, labels, label, ticks, tick;
10158
10159 // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
10160 me.beforeUpdate();
10161
10162 // Absorb the master measurements
10163 me.maxWidth = maxWidth;
10164 me.maxHeight = maxHeight;
10165 me.margins = helpers$1.extend({
10166 left: 0,
10167 right: 0,
10168 top: 0,
10169 bottom: 0
10170 }, margins);
10171 me.longestTextCache = me.longestTextCache || {};
10172
10173 // Dimensions
10174 me.beforeSetDimensions();
10175 me.setDimensions();
10176 me.afterSetDimensions();
10177
10178 // Data min/max
10179 me.beforeDataLimits();
10180 me.determineDataLimits();
10181 me.afterDataLimits();
10182
10183 // Ticks - `this.ticks` is now DEPRECATED!
10184 // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
10185 // and must not be accessed directly from outside this class. `this.ticks` being
10186 // around for long time and not marked as private, we can't change its structure
10187 // without unexpected breaking changes. If you need to access the scale ticks,
10188 // use scale.getTicks() instead.
10189
10190 me.beforeBuildTicks();
10191
10192 // New implementations should return an array of objects but for BACKWARD COMPAT,
10193 // we still support no return (`this.ticks` internally set by calling this method).
10194 ticks = me.buildTicks() || [];
10195
10196 // Allow modification of ticks in callback.
10197 ticks = me.afterBuildTicks(ticks) || ticks;
10198
10199 me.beforeTickToLabelConversion();
10200
10201 // New implementations should return the formatted tick labels but for BACKWARD
10202 // COMPAT, we still support no return (`this.ticks` internally changed by calling
10203 // this method and supposed to contain only string values).
10204 labels = me.convertTicksToLabels(ticks) || me.ticks;
10205
10206 me.afterTickToLabelConversion();
10207
10208 me.ticks = labels; // BACKWARD COMPATIBILITY
10209
10210 // IMPORTANT: from this point, we consider that `this.ticks` will NEVER change!
10211
10212 // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
10213 for (i = 0, ilen = labels.length; i < ilen; ++i) {
10214 label = labels[i];
10215 tick = ticks[i];
10216 if (!tick) {
10217 ticks.push(tick = {
10218 label: label,
10219 major: false
10220 });
10221 } else {
10222 tick.label = label;
10223 }
10224 }
10225
10226 me._ticks = ticks;
10227
10228 // Tick Rotation
10229 me.beforeCalculateTickRotation();
10230 me.calculateTickRotation();
10231 me.afterCalculateTickRotation();
10232 // Fit
10233 me.beforeFit();
10234 me.fit();
10235 me.afterFit();
10236 //
10237 me.afterUpdate();
10238
10239 return me.minSize;
10240
10241 },
10242 afterUpdate: function() {
10243 helpers$1.callback(this.options.afterUpdate, [this]);
10244 },
10245
10246 //
10247
10248 beforeSetDimensions: function() {
10249 helpers$1.callback(this.options.beforeSetDimensions, [this]);
10250 },
10251 setDimensions: function() {
10252 var me = this;
10253 // Set the unconstrained dimension before label rotation
10254 if (me.isHorizontal()) {
10255 // Reset position before calculating rotation
10256 me.width = me.maxWidth;
10257 me.left = 0;
10258 me.right = me.width;
10259 } else {
10260 me.height = me.maxHeight;
10261
10262 // Reset position before calculating rotation
10263 me.top = 0;
10264 me.bottom = me.height;
10265 }
10266
10267 // Reset padding
10268 me.paddingLeft = 0;
10269 me.paddingTop = 0;
10270 me.paddingRight = 0;
10271 me.paddingBottom = 0;
10272 },
10273 afterSetDimensions: function() {
10274 helpers$1.callback(this.options.afterSetDimensions, [this]);
10275 },
10276
10277 // Data limits
10278 beforeDataLimits: function() {
10279 helpers$1.callback(this.options.beforeDataLimits, [this]);
10280 },
10281 determineDataLimits: helpers$1.noop,
10282 afterDataLimits: function() {
10283 helpers$1.callback(this.options.afterDataLimits, [this]);
10284 },
10285
10286 //
10287 beforeBuildTicks: function() {
10288 helpers$1.callback(this.options.beforeBuildTicks, [this]);
10289 },
10290 buildTicks: helpers$1.noop,
10291 afterBuildTicks: function(ticks) {
10292 var me = this;
10293 // ticks is empty for old axis implementations here
10294 if (helpers$1.isArray(ticks) && ticks.length) {
10295 return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]);
10296 }
10297 // Support old implementations (that modified `this.ticks` directly in buildTicks)
10298 me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;
10299 return ticks;
10300 },
10301
10302 beforeTickToLabelConversion: function() {
10303 helpers$1.callback(this.options.beforeTickToLabelConversion, [this]);
10304 },
10305 convertTicksToLabels: function() {
10306 var me = this;
10307 // Convert ticks to strings
10308 var tickOpts = me.options.ticks;
10309 me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
10310 },
10311 afterTickToLabelConversion: function() {
10312 helpers$1.callback(this.options.afterTickToLabelConversion, [this]);
10313 },
10314
10315 //
10316
10317 beforeCalculateTickRotation: function() {
10318 helpers$1.callback(this.options.beforeCalculateTickRotation, [this]);
10319 },
10320 calculateTickRotation: function() {
10321 var me = this;
10322 var context = me.ctx;
10323 var tickOpts = me.options.ticks;
10324 var labels = labelsFromTicks(me._ticks);
10325
10326 // Get the width of each grid by calculating the difference
10327 // between x offsets between 0 and 1.
10328 var tickFont = helpers$1.options._parseFont(tickOpts);
10329 context.font = tickFont.string;
10330
10331 var labelRotation = tickOpts.minRotation || 0;
10332
10333 if (labels.length && me.options.display && me.isHorizontal()) {
10334 var originalLabelWidth = helpers$1.longestText(context, tickFont.string, labels, me.longestTextCache);
10335 var labelWidth = originalLabelWidth;
10336 var cosRotation, sinRotation;
10337
10338 // Allow 3 pixels x2 padding either side for label readability
10339 var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6;
10340
10341 // Max label rotation can be set or default to 90 - also act as a loop counter
10342 while (labelWidth > tickWidth && labelRotation < tickOpts.maxRotation) {
10343 var angleRadians = helpers$1.toRadians(labelRotation);
10344 cosRotation = Math.cos(angleRadians);
10345 sinRotation = Math.sin(angleRadians);
10346
10347 if (sinRotation * originalLabelWidth > me.maxHeight) {
10348 // go back one step
10349 labelRotation--;
10350 break;
10351 }
10352
10353 labelRotation++;
10354 labelWidth = cosRotation * originalLabelWidth;
10355 }
10356 }
10357
10358 me.labelRotation = labelRotation;
10359 },
10360 afterCalculateTickRotation: function() {
10361 helpers$1.callback(this.options.afterCalculateTickRotation, [this]);
10362 },
10363
10364 //
10365
10366 beforeFit: function() {
10367 helpers$1.callback(this.options.beforeFit, [this]);
10368 },
10369 fit: function() {
10370 var me = this;
10371 // Reset
10372 var minSize = me.minSize = {
10373 width: 0,
10374 height: 0
10375 };
10376
10377 var labels = labelsFromTicks(me._ticks);
10378
10379 var opts = me.options;
10380 var tickOpts = opts.ticks;
10381 var scaleLabelOpts = opts.scaleLabel;
10382 var gridLineOpts = opts.gridLines;
10383 var display = me._isVisible();
10384 var position = opts.position;
10385 var isHorizontal = me.isHorizontal();
10386
10387 var parseFont = helpers$1.options._parseFont;
10388 var tickFont = parseFont(tickOpts);
10389 var tickMarkLength = opts.gridLines.tickMarkLength;
10390
10391 // Width
10392 if (isHorizontal) {
10393 // subtract the margins to line up with the chartArea if we are a full width scale
10394 minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth;
10395 } else {
10396 minSize.width = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
10397 }
10398
10399 // height
10400 if (isHorizontal) {
10401 minSize.height = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
10402 } else {
10403 minSize.height = me.maxHeight; // fill all the height
10404 }
10405
10406 // Are we showing a title for the scale?
10407 if (scaleLabelOpts.display && display) {
10408 var scaleLabelFont = parseFont(scaleLabelOpts);
10409 var scaleLabelPadding = helpers$1.options.toPadding(scaleLabelOpts.padding);
10410 var deltaHeight = scaleLabelFont.lineHeight + scaleLabelPadding.height;
10411
10412 if (isHorizontal) {
10413 minSize.height += deltaHeight;
10414 } else {
10415 minSize.width += deltaHeight;
10416 }
10417 }
10418
10419 // Don't bother fitting the ticks if we are not showing them
10420 if (tickOpts.display && display) {
10421 var largestTextWidth = helpers$1.longestText(me.ctx, tickFont.string, labels, me.longestTextCache);
10422 var tallestLabelHeightInLines = helpers$1.numberOfLabelLines(labels);
10423 var lineSpace = tickFont.size * 0.5;
10424 var tickPadding = me.options.ticks.padding;
10425
10426 // Store max number of lines used in labels for _autoSkip
10427 me._maxLabelLines = tallestLabelHeightInLines;
10428
10429 if (isHorizontal) {
10430 // A horizontal axis is more constrained by the height.
10431 me.longestLabelWidth = largestTextWidth;
10432
10433 var angleRadians = helpers$1.toRadians(me.labelRotation);
10434 var cosRotation = Math.cos(angleRadians);
10435 var sinRotation = Math.sin(angleRadians);
10436
10437 // TODO - improve this calculation
10438 var labelHeight = (sinRotation * largestTextWidth)
10439 + (tickFont.lineHeight * tallestLabelHeightInLines)
10440 + lineSpace; // padding
10441
10442 minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
10443
10444 me.ctx.font = tickFont.string;
10445 var firstLabelWidth = computeTextSize(me.ctx, labels[0], tickFont.string);
10446 var lastLabelWidth = computeTextSize(me.ctx, labels[labels.length - 1], tickFont.string);
10447 var offsetLeft = me.getPixelForTick(0) - me.left;
10448 var offsetRight = me.right - me.getPixelForTick(labels.length - 1);
10449 var paddingLeft, paddingRight;
10450
10451 // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
10452 // which means that the right padding is dominated by the font height
10453 if (me.labelRotation !== 0) {
10454 paddingLeft = position === 'bottom' ? (cosRotation * firstLabelWidth) : (cosRotation * lineSpace);
10455 paddingRight = position === 'bottom' ? (cosRotation * lineSpace) : (cosRotation * lastLabelWidth);
10456 } else {
10457 paddingLeft = firstLabelWidth / 2;
10458 paddingRight = lastLabelWidth / 2;
10459 }
10460 me.paddingLeft = Math.max(paddingLeft - offsetLeft, 0) + 3; // add 3 px to move away from canvas edges
10461 me.paddingRight = Math.max(paddingRight - offsetRight, 0) + 3;
10462 } else {
10463 // A vertical axis is more constrained by the width. Labels are the
10464 // dominant factor here, so get that length first and account for padding
10465 if (tickOpts.mirror) {
10466 largestTextWidth = 0;
10467 } else {
10468 // use lineSpace for consistency with horizontal axis
10469 // tickPadding is not implemented for horizontal
10470 largestTextWidth += tickPadding + lineSpace;
10471 }
10472
10473 minSize.width = Math.min(me.maxWidth, minSize.width + largestTextWidth);
10474
10475 me.paddingTop = tickFont.size / 2;
10476 me.paddingBottom = tickFont.size / 2;
10477 }
10478 }
10479
10480 me.handleMargins();
10481
10482 me.width = minSize.width;
10483 me.height = minSize.height;
10484 },
10485
10486 /**
10487 * Handle margins and padding interactions
10488 * @private
10489 */
10490 handleMargins: function() {
10491 var me = this;
10492 if (me.margins) {
10493 me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0);
10494 me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0);
10495 me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0);
10496 me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0);
10497 }
10498 },
10499
10500 afterFit: function() {
10501 helpers$1.callback(this.options.afterFit, [this]);
10502 },
10503
10504 // Shared Methods
10505 isHorizontal: function() {
10506 return this.options.position === 'top' || this.options.position === 'bottom';
10507 },
10508 isFullWidth: function() {
10509 return (this.options.fullWidth);
10510 },
10511
10512 // 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
10513 getRightValue: function(rawValue) {
10514 // Null and undefined values first
10515 if (helpers$1.isNullOrUndef(rawValue)) {
10516 return NaN;
10517 }
10518 // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
10519 if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {
10520 return NaN;
10521 }
10522 // If it is in fact an object, dive in one more level
10523 if (rawValue) {
10524 if (this.isHorizontal()) {
10525 if (rawValue.x !== undefined) {
10526 return this.getRightValue(rawValue.x);
10527 }
10528 } else if (rawValue.y !== undefined) {
10529 return this.getRightValue(rawValue.y);
10530 }
10531 }
10532
10533 // Value is good, return it
10534 return rawValue;
10535 },
10536
10537 /**
10538 * Used to get the value to display in the tooltip for the data at the given index
10539 * @param index
10540 * @param datasetIndex
10541 */
10542 getLabelForIndex: helpers$1.noop,
10543
10544 /**
10545 * Returns the location of the given data point. Value can either be an index or a numerical value
10546 * The coordinate (0, 0) is at the upper-left corner of the canvas
10547 * @param value
10548 * @param index
10549 * @param datasetIndex
10550 */
10551 getPixelForValue: helpers$1.noop,
10552
10553 /**
10554 * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
10555 * The coordinate (0, 0) is at the upper-left corner of the canvas
10556 * @param pixel
10557 */
10558 getValueForPixel: helpers$1.noop,
10559
10560 /**
10561 * Returns the location of the tick at the given index
10562 * The coordinate (0, 0) is at the upper-left corner of the canvas
10563 */
10564 getPixelForTick: function(index) {
10565 var me = this;
10566 var offset = me.options.offset;
10567 if (me.isHorizontal()) {
10568 var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
10569 var tickWidth = innerWidth / Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
10570 var pixel = (tickWidth * index) + me.paddingLeft;
10571
10572 if (offset) {
10573 pixel += tickWidth / 2;
10574 }
10575
10576 var finalVal = me.left + pixel;
10577 finalVal += me.isFullWidth() ? me.margins.left : 0;
10578 return finalVal;
10579 }
10580 var innerHeight = me.height - (me.paddingTop + me.paddingBottom);
10581 return me.top + (index * (innerHeight / (me._ticks.length - 1)));
10582 },
10583
10584 /**
10585 * Utility for getting the pixel location of a percentage of scale
10586 * The coordinate (0, 0) is at the upper-left corner of the canvas
10587 */
10588 getPixelForDecimal: function(decimal) {
10589 var me = this;
10590 if (me.isHorizontal()) {
10591 var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
10592 var valueOffset = (innerWidth * decimal) + me.paddingLeft;
10593
10594 var finalVal = me.left + valueOffset;
10595 finalVal += me.isFullWidth() ? me.margins.left : 0;
10596 return finalVal;
10597 }
10598 return me.top + (decimal * me.height);
10599 },
10600
10601 /**
10602 * Returns the pixel for the minimum chart value
10603 * The coordinate (0, 0) is at the upper-left corner of the canvas
10604 */
10605 getBasePixel: function() {
10606 return this.getPixelForValue(this.getBaseValue());
10607 },
10608
10609 getBaseValue: function() {
10610 var me = this;
10611 var min = me.min;
10612 var max = me.max;
10613
10614 return me.beginAtZero ? 0 :
10615 min < 0 && max < 0 ? max :
10616 min > 0 && max > 0 ? min :
10617 0;
10618 },
10619
10620 /**
10621 * Returns a subset of ticks to be plotted to avoid overlapping labels.
10622 * @private
10623 */
10624 _autoSkip: function(ticks) {
10625 var skipRatio;
10626 var me = this;
10627 var isHorizontal = me.isHorizontal();
10628 var optionTicks = me.options.ticks.minor;
10629 var tickCount = ticks.length;
10630
10631 // Calculate space needed by label in axis direction.
10632 var rot = helpers$1.toRadians(me.labelRotation);
10633 var cos = Math.abs(Math.cos(rot));
10634 var sin = Math.abs(Math.sin(rot));
10635
10636 var padding = optionTicks.autoSkipPadding;
10637 var w = me.longestLabelWidth + padding || 0;
10638
10639 var tickFont = helpers$1.options._parseFont(optionTicks);
10640 var h = me._maxLabelLines * tickFont.lineHeight + padding;
10641
10642 // Calculate space needed for 1 tick in axis direction.
10643 var tickSize = isHorizontal
10644 ? h * cos > w * sin ? w / cos : h / sin
10645 : h * sin < w * cos ? h / cos : w / sin;
10646
10647 // Total space needed to display all ticks. First and last ticks are
10648 // drawn as their center at end of axis, so tickCount-1
10649 var ticksLength = tickSize * (tickCount - 1);
10650
10651 // Axis length
10652 var axisLength = isHorizontal
10653 ? me.width - (me.paddingLeft + me.paddingRight)
10654 : me.height - (me.paddingTop + me.PaddingBottom);
10655
10656 var result = [];
10657 var i, tick;
10658
10659 // figure out the maximum number of gridlines to show
10660 var maxTicks;
10661 if (optionTicks.maxTicksLimit) {
10662 maxTicks = optionTicks.maxTicksLimit;
10663 }
10664
10665 skipRatio = false;
10666
10667 if (ticksLength > axisLength) {
10668 skipRatio = 1 + Math.floor(ticksLength / axisLength);
10669 }
10670
10671 // if they defined a max number of optionTicks,
10672 // increase skipRatio until that number is met
10673 if (maxTicks && tickCount > maxTicks) {
10674 skipRatio = Math.max(skipRatio, 1 + Math.floor(tickCount / maxTicks));
10675 }
10676
10677 for (i = 0; i < tickCount; i++) {
10678 tick = ticks[i];
10679
10680 if (skipRatio > 1 && i % skipRatio > 0) {
10681 // leave tick in place but make sure it's not displayed (#4635)
10682 delete tick.label;
10683 }
10684 result.push(tick);
10685 }
10686 return result;
10687 },
10688
10689 /**
10690 * @private
10691 */
10692 _isVisible: function() {
10693 var me = this;
10694 var chart = me.chart;
10695 var display = me.options.display;
10696 var i, ilen, meta;
10697
10698 if (display !== 'auto') {
10699 return !!display;
10700 }
10701
10702 // When 'auto', the scale is visible if at least one associated dataset is visible.
10703 for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
10704 if (chart.isDatasetVisible(i)) {
10705 meta = chart.getDatasetMeta(i);
10706 if (meta.xAxisID === me.id || meta.yAxisID === me.id) {
10707 return true;
10708 }
10709 }
10710 }
10711
10712 return false;
10713 },
10714
10715 // Actually draw the scale on the canvas
10716 // @param {rectangle} chartArea : the area of the chart to draw full grid lines on
10717 draw: function(chartArea) {
10718 var me = this;
10719 var options = me.options;
10720
10721 if (!me._isVisible()) {
10722 return;
10723 }
10724
10725 var chart = me.chart;
10726 var context = me.ctx;
10727 var globalDefaults = core_defaults.global;
10728 var defaultFontColor = globalDefaults.defaultFontColor;
10729 var optionTicks = options.ticks.minor;
10730 var optionMajorTicks = options.ticks.major || optionTicks;
10731 var gridLines = options.gridLines;
10732 var scaleLabel = options.scaleLabel;
10733 var position = options.position;
10734
10735 var isRotated = me.labelRotation !== 0;
10736 var isMirrored = optionTicks.mirror;
10737 var isHorizontal = me.isHorizontal();
10738
10739 var parseFont = helpers$1.options._parseFont;
10740 var ticks = optionTicks.autoSkip ? me._autoSkip(me.getTicks()) : me.getTicks();
10741 var tickFontColor = valueOrDefault$7(optionTicks.fontColor, defaultFontColor);
10742 var tickFont = parseFont(optionTicks);
10743 var lineHeight = tickFont.lineHeight;
10744 var majorTickFontColor = valueOrDefault$7(optionMajorTicks.fontColor, defaultFontColor);
10745 var majorTickFont = parseFont(optionMajorTicks);
10746 var tickPadding = optionTicks.padding;
10747 var labelOffset = optionTicks.labelOffset;
10748
10749 var tl = gridLines.drawTicks ? gridLines.tickMarkLength : 0;
10750
10751 var scaleLabelFontColor = valueOrDefault$7(scaleLabel.fontColor, defaultFontColor);
10752 var scaleLabelFont = parseFont(scaleLabel);
10753 var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding);
10754 var labelRotationRadians = helpers$1.toRadians(me.labelRotation);
10755
10756 var itemsToDraw = [];
10757
10758 var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
10759 var alignPixel = helpers$1._alignPixel;
10760 var borderValue, tickStart, tickEnd;
10761
10762 if (position === 'top') {
10763 borderValue = alignPixel(chart, me.bottom, axisWidth);
10764 tickStart = me.bottom - tl;
10765 tickEnd = borderValue - axisWidth / 2;
10766 } else if (position === 'bottom') {
10767 borderValue = alignPixel(chart, me.top, axisWidth);
10768 tickStart = borderValue + axisWidth / 2;
10769 tickEnd = me.top + tl;
10770 } else if (position === 'left') {
10771 borderValue = alignPixel(chart, me.right, axisWidth);
10772 tickStart = me.right - tl;
10773 tickEnd = borderValue - axisWidth / 2;
10774 } else {
10775 borderValue = alignPixel(chart, me.left, axisWidth);
10776 tickStart = borderValue + axisWidth / 2;
10777 tickEnd = me.left + tl;
10778 }
10779
10780 var epsilon = 0.0000001; // 0.0000001 is margin in pixels for Accumulated error.
10781
10782 helpers$1.each(ticks, function(tick, index) {
10783 // autoskipper skipped this tick (#4635)
10784 if (helpers$1.isNullOrUndef(tick.label)) {
10785 return;
10786 }
10787
10788 var label = tick.label;
10789 var lineWidth, lineColor, borderDash, borderDashOffset;
10790 if (index === me.zeroLineIndex && options.offset === gridLines.offsetGridLines) {
10791 // Draw the first index specially
10792 lineWidth = gridLines.zeroLineWidth;
10793 lineColor = gridLines.zeroLineColor;
10794 borderDash = gridLines.zeroLineBorderDash || [];
10795 borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0;
10796 } else {
10797 lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, index);
10798 lineColor = valueAtIndexOrDefault(gridLines.color, index);
10799 borderDash = gridLines.borderDash || [];
10800 borderDashOffset = gridLines.borderDashOffset || 0.0;
10801 }
10802
10803 // Common properties
10804 var tx1, ty1, tx2, ty2, x1, y1, x2, y2, labelX, labelY, textOffset, textAlign;
10805 var labelCount = helpers$1.isArray(label) ? label.length : 1;
10806 var lineValue = getPixelForGridLine(me, index, gridLines.offsetGridLines);
10807
10808 if (isHorizontal) {
10809 var labelYOffset = tl + tickPadding;
10810
10811 if (lineValue < me.left - epsilon) {
10812 lineColor = 'rgba(0,0,0,0)';
10813 }
10814
10815 tx1 = tx2 = x1 = x2 = alignPixel(chart, lineValue, lineWidth);
10816 ty1 = tickStart;
10817 ty2 = tickEnd;
10818 labelX = me.getPixelForTick(index) + labelOffset; // x values for optionTicks (need to consider offsetLabel option)
10819
10820 if (position === 'top') {
10821 y1 = alignPixel(chart, chartArea.top, axisWidth) + axisWidth / 2;
10822 y2 = chartArea.bottom;
10823 textOffset = ((!isRotated ? 0.5 : 1) - labelCount) * lineHeight;
10824 textAlign = !isRotated ? 'center' : 'left';
10825 labelY = me.bottom - labelYOffset;
10826 } else {
10827 y1 = chartArea.top;
10828 y2 = alignPixel(chart, chartArea.bottom, axisWidth) - axisWidth / 2;
10829 textOffset = (!isRotated ? 0.5 : 0) * lineHeight;
10830 textAlign = !isRotated ? 'center' : 'right';
10831 labelY = me.top + labelYOffset;
10832 }
10833 } else {
10834 var labelXOffset = (isMirrored ? 0 : tl) + tickPadding;
10835
10836 if (lineValue < me.top - epsilon) {
10837 lineColor = 'rgba(0,0,0,0)';
10838 }
10839
10840 tx1 = tickStart;
10841 tx2 = tickEnd;
10842 ty1 = ty2 = y1 = y2 = alignPixel(chart, lineValue, lineWidth);
10843 labelY = me.getPixelForTick(index) + labelOffset;
10844 textOffset = (1 - labelCount) * lineHeight / 2;
10845
10846 if (position === 'left') {
10847 x1 = alignPixel(chart, chartArea.left, axisWidth) + axisWidth / 2;
10848 x2 = chartArea.right;
10849 textAlign = isMirrored ? 'left' : 'right';
10850 labelX = me.right - labelXOffset;
10851 } else {
10852 x1 = chartArea.left;
10853 x2 = alignPixel(chart, chartArea.right, axisWidth) - axisWidth / 2;
10854 textAlign = isMirrored ? 'right' : 'left';
10855 labelX = me.left + labelXOffset;
10856 }
10857 }
10858
10859 itemsToDraw.push({
10860 tx1: tx1,
10861 ty1: ty1,
10862 tx2: tx2,
10863 ty2: ty2,
10864 x1: x1,
10865 y1: y1,
10866 x2: x2,
10867 y2: y2,
10868 labelX: labelX,
10869 labelY: labelY,
10870 glWidth: lineWidth,
10871 glColor: lineColor,
10872 glBorderDash: borderDash,
10873 glBorderDashOffset: borderDashOffset,
10874 rotation: -1 * labelRotationRadians,
10875 label: label,
10876 major: tick.major,
10877 textOffset: textOffset,
10878 textAlign: textAlign
10879 });
10880 });
10881
10882 // Draw all of the tick labels, tick marks, and grid lines at the correct places
10883 helpers$1.each(itemsToDraw, function(itemToDraw) {
10884 var glWidth = itemToDraw.glWidth;
10885 var glColor = itemToDraw.glColor;
10886
10887 if (gridLines.display && glWidth && glColor) {
10888 context.save();
10889 context.lineWidth = glWidth;
10890 context.strokeStyle = glColor;
10891 if (context.setLineDash) {
10892 context.setLineDash(itemToDraw.glBorderDash);
10893 context.lineDashOffset = itemToDraw.glBorderDashOffset;
10894 }
10895
10896 context.beginPath();
10897
10898 if (gridLines.drawTicks) {
10899 context.moveTo(itemToDraw.tx1, itemToDraw.ty1);
10900 context.lineTo(itemToDraw.tx2, itemToDraw.ty2);
10901 }
10902
10903 if (gridLines.drawOnChartArea) {
10904 context.moveTo(itemToDraw.x1, itemToDraw.y1);
10905 context.lineTo(itemToDraw.x2, itemToDraw.y2);
10906 }
10907
10908 context.stroke();
10909 context.restore();
10910 }
10911
10912 if (optionTicks.display) {
10913 // Make sure we draw text in the correct color and font
10914 context.save();
10915 context.translate(itemToDraw.labelX, itemToDraw.labelY);
10916 context.rotate(itemToDraw.rotation);
10917 context.font = itemToDraw.major ? majorTickFont.string : tickFont.string;
10918 context.fillStyle = itemToDraw.major ? majorTickFontColor : tickFontColor;
10919 context.textBaseline = 'middle';
10920 context.textAlign = itemToDraw.textAlign;
10921
10922 var label = itemToDraw.label;
10923 var y = itemToDraw.textOffset;
10924 if (helpers$1.isArray(label)) {
10925 for (var i = 0; i < label.length; ++i) {
10926 // We just make sure the multiline element is a string here..
10927 context.fillText('' + label[i], 0, y);
10928 y += lineHeight;
10929 }
10930 } else {
10931 context.fillText(label, 0, y);
10932 }
10933 context.restore();
10934 }
10935 });
10936
10937 if (scaleLabel.display) {
10938 // Draw the scale label
10939 var scaleLabelX;
10940 var scaleLabelY;
10941 var rotation = 0;
10942 var halfLineHeight = scaleLabelFont.lineHeight / 2;
10943
10944 if (isHorizontal) {
10945 scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width
10946 scaleLabelY = position === 'bottom'
10947 ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
10948 : me.top + halfLineHeight + scaleLabelPadding.top;
10949 } else {
10950 var isLeft = position === 'left';
10951 scaleLabelX = isLeft
10952 ? me.left + halfLineHeight + scaleLabelPadding.top
10953 : me.right - halfLineHeight - scaleLabelPadding.top;
10954 scaleLabelY = me.top + ((me.bottom - me.top) / 2);
10955 rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
10956 }
10957
10958 context.save();
10959 context.translate(scaleLabelX, scaleLabelY);
10960 context.rotate(rotation);
10961 context.textAlign = 'center';
10962 context.textBaseline = 'middle';
10963 context.fillStyle = scaleLabelFontColor; // render in correct colour
10964 context.font = scaleLabelFont.string;
10965 context.fillText(scaleLabel.labelString, 0, 0);
10966 context.restore();
10967 }
10968
10969 if (axisWidth) {
10970 // Draw the line at the edge of the axis
10971 var firstLineWidth = axisWidth;
10972 var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, ticks.length - 1, 0);
10973 var x1, x2, y1, y2;
10974
10975 if (isHorizontal) {
10976 x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
10977 x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
10978 y1 = y2 = borderValue;
10979 } else {
10980 y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
10981 y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
10982 x1 = x2 = borderValue;
10983 }
10984
10985 context.lineWidth = axisWidth;
10986 context.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0);
10987 context.beginPath();
10988 context.moveTo(x1, y1);
10989 context.lineTo(x2, y2);
10990 context.stroke();
10991 }
10992 }
10993});
10994
10995var defaultConfig = {
10996 position: 'bottom'
10997};
10998
10999var scale_category = core_scale.extend({
11000 /**
11001 * Internal function to get the correct labels. If data.xLabels or data.yLabels are defined, use those
11002 * else fall back to data.labels
11003 * @private
11004 */
11005 getLabels: function() {
11006 var data = this.chart.data;
11007 return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels;
11008 },
11009
11010 determineDataLimits: function() {
11011 var me = this;
11012 var labels = me.getLabels();
11013 me.minIndex = 0;
11014 me.maxIndex = labels.length - 1;
11015 var findIndex;
11016
11017 if (me.options.ticks.min !== undefined) {
11018 // user specified min value
11019 findIndex = labels.indexOf(me.options.ticks.min);
11020 me.minIndex = findIndex !== -1 ? findIndex : me.minIndex;
11021 }
11022
11023 if (me.options.ticks.max !== undefined) {
11024 // user specified max value
11025 findIndex = labels.indexOf(me.options.ticks.max);
11026 me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex;
11027 }
11028
11029 me.min = labels[me.minIndex];
11030 me.max = labels[me.maxIndex];
11031 },
11032
11033 buildTicks: function() {
11034 var me = this;
11035 var labels = me.getLabels();
11036 // If we are viewing some subset of labels, slice the original array
11037 me.ticks = (me.minIndex === 0 && me.maxIndex === labels.length - 1) ? labels : labels.slice(me.minIndex, me.maxIndex + 1);
11038 },
11039
11040 getLabelForIndex: function(index, datasetIndex) {
11041 var me = this;
11042 var data = me.chart.data;
11043 var isHorizontal = me.isHorizontal();
11044
11045 if (data.yLabels && !isHorizontal) {
11046 return me.getRightValue(data.datasets[datasetIndex].data[index]);
11047 }
11048 return me.ticks[index - me.minIndex];
11049 },
11050
11051 // Used to get data value locations. Value can either be an index or a numerical value
11052 getPixelForValue: function(value, index) {
11053 var me = this;
11054 var offset = me.options.offset;
11055 // 1 is added because we need the length but we have the indexes
11056 var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - (offset ? 0 : 1)), 1);
11057
11058 // If value is a data object, then index is the index in the data array,
11059 // not the index of the scale. We need to change that.
11060 var valueCategory;
11061 if (value !== undefined && value !== null) {
11062 valueCategory = me.isHorizontal() ? value.x : value.y;
11063 }
11064 if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
11065 var labels = me.getLabels();
11066 value = valueCategory || value;
11067 var idx = labels.indexOf(value);
11068 index = idx !== -1 ? idx : index;
11069 }
11070
11071 if (me.isHorizontal()) {
11072 var valueWidth = me.width / offsetAmt;
11073 var widthOffset = (valueWidth * (index - me.minIndex));
11074
11075 if (offset) {
11076 widthOffset += (valueWidth / 2);
11077 }
11078
11079 return me.left + widthOffset;
11080 }
11081 var valueHeight = me.height / offsetAmt;
11082 var heightOffset = (valueHeight * (index - me.minIndex));
11083
11084 if (offset) {
11085 heightOffset += (valueHeight / 2);
11086 }
11087
11088 return me.top + heightOffset;
11089 },
11090
11091 getPixelForTick: function(index) {
11092 return this.getPixelForValue(this.ticks[index], index + this.minIndex, null);
11093 },
11094
11095 getValueForPixel: function(pixel) {
11096 var me = this;
11097 var offset = me.options.offset;
11098 var value;
11099 var offsetAmt = Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
11100 var horz = me.isHorizontal();
11101 var valueDimension = (horz ? me.width : me.height) / offsetAmt;
11102
11103 pixel -= horz ? me.left : me.top;
11104
11105 if (offset) {
11106 pixel -= (valueDimension / 2);
11107 }
11108
11109 if (pixel <= 0) {
11110 value = 0;
11111 } else {
11112 value = Math.round(pixel / valueDimension);
11113 }
11114
11115 return value + me.minIndex;
11116 },
11117
11118 getBasePixel: function() {
11119 return this.bottom;
11120 }
11121});
11122
11123// INTERNAL: static default options, registered in src/chart.js
11124var _defaults = defaultConfig;
11125scale_category._defaults = _defaults;
11126
11127var noop = helpers$1.noop;
11128var isNullOrUndef = helpers$1.isNullOrUndef;
11129
11130/**
11131 * Generate a set of linear ticks
11132 * @param generationOptions the options used to generate the ticks
11133 * @param dataRange the range of the data
11134 * @returns {Array<Number>} array of tick values
11135 */
11136function generateTicks(generationOptions, dataRange) {
11137 var ticks = [];
11138 // To get a "nice" value for the tick spacing, we will use the appropriately named
11139 // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
11140 // for details.
11141
11142 var MIN_SPACING = 1e-14;
11143 var stepSize = generationOptions.stepSize;
11144 var unit = stepSize || 1;
11145 var maxNumSpaces = generationOptions.maxTicks - 1;
11146 var min = generationOptions.min;
11147 var max = generationOptions.max;
11148 var precision = generationOptions.precision;
11149 var rmin = dataRange.min;
11150 var rmax = dataRange.max;
11151 var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit;
11152 var factor, niceMin, niceMax, numSpaces;
11153
11154 // Beyond MIN_SPACING floating point numbers being to lose precision
11155 // such that we can't do the math necessary to generate ticks
11156 if (spacing < MIN_SPACING && isNullOrUndef(min) && isNullOrUndef(max)) {
11157 return [rmin, rmax];
11158 }
11159
11160 numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
11161 if (numSpaces > maxNumSpaces) {
11162 // If the calculated num of spaces exceeds maxNumSpaces, recalculate it
11163 spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit;
11164 }
11165
11166 if (stepSize || isNullOrUndef(precision)) {
11167 // If a precision is not specified, calculate factor based on spacing
11168 factor = Math.pow(10, helpers$1.decimalPlaces(spacing));
11169 } else {
11170 // If the user specified a precision, round to that number of decimal places
11171 factor = Math.pow(10, precision);
11172 spacing = Math.ceil(spacing * factor) / factor;
11173 }
11174
11175 niceMin = Math.floor(rmin / spacing) * spacing;
11176 niceMax = Math.ceil(rmax / spacing) * spacing;
11177
11178 // If min, max and stepSize is set and they make an evenly spaced scale use it.
11179 if (stepSize) {
11180 // If very close to our whole number, use it.
11181 if (!isNullOrUndef(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) {
11182 niceMin = min;
11183 }
11184 if (!isNullOrUndef(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) {
11185 niceMax = max;
11186 }
11187 }
11188
11189 numSpaces = (niceMax - niceMin) / spacing;
11190 // If very close to our rounded value, use it.
11191 if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
11192 numSpaces = Math.round(numSpaces);
11193 } else {
11194 numSpaces = Math.ceil(numSpaces);
11195 }
11196
11197 niceMin = Math.round(niceMin * factor) / factor;
11198 niceMax = Math.round(niceMax * factor) / factor;
11199 ticks.push(isNullOrUndef(min) ? niceMin : min);
11200 for (var j = 1; j < numSpaces; ++j) {
11201 ticks.push(Math.round((niceMin + j * spacing) * factor) / factor);
11202 }
11203 ticks.push(isNullOrUndef(max) ? niceMax : max);
11204
11205 return ticks;
11206}
11207
11208var scale_linearbase = core_scale.extend({
11209 getRightValue: function(value) {
11210 if (typeof value === 'string') {
11211 return +value;
11212 }
11213 return core_scale.prototype.getRightValue.call(this, value);
11214 },
11215
11216 handleTickRangeOptions: function() {
11217 var me = this;
11218 var opts = me.options;
11219 var tickOpts = opts.ticks;
11220
11221 // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
11222 // do nothing since that would make the chart weird. If the user really wants a weird chart
11223 // axis, they can manually override it
11224 if (tickOpts.beginAtZero) {
11225 var minSign = helpers$1.sign(me.min);
11226 var maxSign = helpers$1.sign(me.max);
11227
11228 if (minSign < 0 && maxSign < 0) {
11229 // move the top up to 0
11230 me.max = 0;
11231 } else if (minSign > 0 && maxSign > 0) {
11232 // move the bottom down to 0
11233 me.min = 0;
11234 }
11235 }
11236
11237 var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
11238 var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
11239
11240 if (tickOpts.min !== undefined) {
11241 me.min = tickOpts.min;
11242 } else if (tickOpts.suggestedMin !== undefined) {
11243 if (me.min === null) {
11244 me.min = tickOpts.suggestedMin;
11245 } else {
11246 me.min = Math.min(me.min, tickOpts.suggestedMin);
11247 }
11248 }
11249
11250 if (tickOpts.max !== undefined) {
11251 me.max = tickOpts.max;
11252 } else if (tickOpts.suggestedMax !== undefined) {
11253 if (me.max === null) {
11254 me.max = tickOpts.suggestedMax;
11255 } else {
11256 me.max = Math.max(me.max, tickOpts.suggestedMax);
11257 }
11258 }
11259
11260 if (setMin !== setMax) {
11261 // We set the min or the max but not both.
11262 // So ensure that our range is good
11263 // Inverted or 0 length range can happen when
11264 // ticks.min is set, and no datasets are visible
11265 if (me.min >= me.max) {
11266 if (setMin) {
11267 me.max = me.min + 1;
11268 } else {
11269 me.min = me.max - 1;
11270 }
11271 }
11272 }
11273
11274 if (me.min === me.max) {
11275 me.max++;
11276
11277 if (!tickOpts.beginAtZero) {
11278 me.min--;
11279 }
11280 }
11281 },
11282
11283 getTickLimit: function() {
11284 var me = this;
11285 var tickOpts = me.options.ticks;
11286 var stepSize = tickOpts.stepSize;
11287 var maxTicksLimit = tickOpts.maxTicksLimit;
11288 var maxTicks;
11289
11290 if (stepSize) {
11291 maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
11292 } else {
11293 maxTicks = me._computeTickLimit();
11294 maxTicksLimit = maxTicksLimit || 11;
11295 }
11296
11297 if (maxTicksLimit) {
11298 maxTicks = Math.min(maxTicksLimit, maxTicks);
11299 }
11300
11301 return maxTicks;
11302 },
11303
11304 _computeTickLimit: function() {
11305 return Number.POSITIVE_INFINITY;
11306 },
11307
11308 handleDirectionalChanges: noop,
11309
11310 buildTicks: function() {
11311 var me = this;
11312 var opts = me.options;
11313 var tickOpts = opts.ticks;
11314
11315 // Figure out what the max number of ticks we can support it is based on the size of
11316 // the axis area. For now, we say that the minimum tick spacing in pixels must be 40
11317 // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
11318 // the graph. Make sure we always have at least 2 ticks
11319 var maxTicks = me.getTickLimit();
11320 maxTicks = Math.max(2, maxTicks);
11321
11322 var numericGeneratorOptions = {
11323 maxTicks: maxTicks,
11324 min: tickOpts.min,
11325 max: tickOpts.max,
11326 precision: tickOpts.precision,
11327 stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
11328 };
11329 var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
11330
11331 me.handleDirectionalChanges();
11332
11333 // At this point, we need to update our max and min given the tick values since we have expanded the
11334 // range of the scale
11335 me.max = helpers$1.max(ticks);
11336 me.min = helpers$1.min(ticks);
11337
11338 if (tickOpts.reverse) {
11339 ticks.reverse();
11340
11341 me.start = me.max;
11342 me.end = me.min;
11343 } else {
11344 me.start = me.min;
11345 me.end = me.max;
11346 }
11347 },
11348
11349 convertTicksToLabels: function() {
11350 var me = this;
11351 me.ticksAsNumbers = me.ticks.slice();
11352 me.zeroLineIndex = me.ticks.indexOf(0);
11353
11354 core_scale.prototype.convertTicksToLabels.call(me);
11355 }
11356});
11357
11358var defaultConfig$1 = {
11359 position: 'left',
11360 ticks: {
11361 callback: core_ticks.formatters.linear
11362 }
11363};
11364
11365var scale_linear = scale_linearbase.extend({
11366 determineDataLimits: function() {
11367 var me = this;
11368 var opts = me.options;
11369 var chart = me.chart;
11370 var data = chart.data;
11371 var datasets = data.datasets;
11372 var isHorizontal = me.isHorizontal();
11373 var DEFAULT_MIN = 0;
11374 var DEFAULT_MAX = 1;
11375
11376 function IDMatches(meta) {
11377 return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
11378 }
11379
11380 // First Calculate the range
11381 me.min = null;
11382 me.max = null;
11383
11384 var hasStacks = opts.stacked;
11385 if (hasStacks === undefined) {
11386 helpers$1.each(datasets, function(dataset, datasetIndex) {
11387 if (hasStacks) {
11388 return;
11389 }
11390
11391 var meta = chart.getDatasetMeta(datasetIndex);
11392 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
11393 meta.stack !== undefined) {
11394 hasStacks = true;
11395 }
11396 });
11397 }
11398
11399 if (opts.stacked || hasStacks) {
11400 var valuesPerStack = {};
11401
11402 helpers$1.each(datasets, function(dataset, datasetIndex) {
11403 var meta = chart.getDatasetMeta(datasetIndex);
11404 var key = [
11405 meta.type,
11406 // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
11407 ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
11408 meta.stack
11409 ].join('.');
11410
11411 if (valuesPerStack[key] === undefined) {
11412 valuesPerStack[key] = {
11413 positiveValues: [],
11414 negativeValues: []
11415 };
11416 }
11417
11418 // Store these per type
11419 var positiveValues = valuesPerStack[key].positiveValues;
11420 var negativeValues = valuesPerStack[key].negativeValues;
11421
11422 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
11423 helpers$1.each(dataset.data, function(rawValue, index) {
11424 var value = +me.getRightValue(rawValue);
11425 if (isNaN(value) || meta.data[index].hidden) {
11426 return;
11427 }
11428
11429 positiveValues[index] = positiveValues[index] || 0;
11430 negativeValues[index] = negativeValues[index] || 0;
11431
11432 if (opts.relativePoints) {
11433 positiveValues[index] = 100;
11434 } else if (value < 0) {
11435 negativeValues[index] += value;
11436 } else {
11437 positiveValues[index] += value;
11438 }
11439 });
11440 }
11441 });
11442
11443 helpers$1.each(valuesPerStack, function(valuesForType) {
11444 var values = valuesForType.positiveValues.concat(valuesForType.negativeValues);
11445 var minVal = helpers$1.min(values);
11446 var maxVal = helpers$1.max(values);
11447 me.min = me.min === null ? minVal : Math.min(me.min, minVal);
11448 me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
11449 });
11450
11451 } else {
11452 helpers$1.each(datasets, function(dataset, datasetIndex) {
11453 var meta = chart.getDatasetMeta(datasetIndex);
11454 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
11455 helpers$1.each(dataset.data, function(rawValue, index) {
11456 var value = +me.getRightValue(rawValue);
11457 if (isNaN(value) || meta.data[index].hidden) {
11458 return;
11459 }
11460
11461 if (me.min === null) {
11462 me.min = value;
11463 } else if (value < me.min) {
11464 me.min = value;
11465 }
11466
11467 if (me.max === null) {
11468 me.max = value;
11469 } else if (value > me.max) {
11470 me.max = value;
11471 }
11472 });
11473 }
11474 });
11475 }
11476
11477 me.min = isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
11478 me.max = isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
11479
11480 // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
11481 this.handleTickRangeOptions();
11482 },
11483
11484 // Returns the maximum number of ticks based on the scale dimension
11485 _computeTickLimit: function() {
11486 var me = this;
11487 var tickFont;
11488
11489 if (me.isHorizontal()) {
11490 return Math.ceil(me.width / 40);
11491 }
11492 tickFont = helpers$1.options._parseFont(me.options.ticks);
11493 return Math.ceil(me.height / tickFont.lineHeight);
11494 },
11495
11496 // Called after the ticks are built. We need
11497 handleDirectionalChanges: function() {
11498 if (!this.isHorizontal()) {
11499 // We are in a vertical orientation. The top value is the highest. So reverse the array
11500 this.ticks.reverse();
11501 }
11502 },
11503
11504 getLabelForIndex: function(index, datasetIndex) {
11505 return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
11506 },
11507
11508 // Utils
11509 getPixelForValue: function(value) {
11510 // This must be called after fit has been run so that
11511 // this.left, this.top, this.right, and this.bottom have been defined
11512 var me = this;
11513 var start = me.start;
11514
11515 var rightValue = +me.getRightValue(value);
11516 var pixel;
11517 var range = me.end - start;
11518
11519 if (me.isHorizontal()) {
11520 pixel = me.left + (me.width / range * (rightValue - start));
11521 } else {
11522 pixel = me.bottom - (me.height / range * (rightValue - start));
11523 }
11524 return pixel;
11525 },
11526
11527 getValueForPixel: function(pixel) {
11528 var me = this;
11529 var isHorizontal = me.isHorizontal();
11530 var innerDimension = isHorizontal ? me.width : me.height;
11531 var offset = (isHorizontal ? pixel - me.left : me.bottom - pixel) / innerDimension;
11532 return me.start + ((me.end - me.start) * offset);
11533 },
11534
11535 getPixelForTick: function(index) {
11536 return this.getPixelForValue(this.ticksAsNumbers[index]);
11537 }
11538});
11539
11540// INTERNAL: static default options, registered in src/chart.js
11541var _defaults$1 = defaultConfig$1;
11542scale_linear._defaults = _defaults$1;
11543
11544var valueOrDefault$8 = helpers$1.valueOrDefault;
11545
11546/**
11547 * Generate a set of logarithmic ticks
11548 * @param generationOptions the options used to generate the ticks
11549 * @param dataRange the range of the data
11550 * @returns {Array<Number>} array of tick values
11551 */
11552function generateTicks$1(generationOptions, dataRange) {
11553 var ticks = [];
11554
11555 var tickVal = valueOrDefault$8(generationOptions.min, Math.pow(10, Math.floor(helpers$1.log10(dataRange.min))));
11556
11557 var endExp = Math.floor(helpers$1.log10(dataRange.max));
11558 var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
11559 var exp, significand;
11560
11561 if (tickVal === 0) {
11562 exp = Math.floor(helpers$1.log10(dataRange.minNotZero));
11563 significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
11564
11565 ticks.push(tickVal);
11566 tickVal = significand * Math.pow(10, exp);
11567 } else {
11568 exp = Math.floor(helpers$1.log10(tickVal));
11569 significand = Math.floor(tickVal / Math.pow(10, exp));
11570 }
11571 var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
11572
11573 do {
11574 ticks.push(tickVal);
11575
11576 ++significand;
11577 if (significand === 10) {
11578 significand = 1;
11579 ++exp;
11580 precision = exp >= 0 ? 1 : precision;
11581 }
11582
11583 tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
11584 } while (exp < endExp || (exp === endExp && significand < endSignificand));
11585
11586 var lastTick = valueOrDefault$8(generationOptions.max, tickVal);
11587 ticks.push(lastTick);
11588
11589 return ticks;
11590}
11591
11592var defaultConfig$2 = {
11593 position: 'left',
11594
11595 // label settings
11596 ticks: {
11597 callback: core_ticks.formatters.logarithmic
11598 }
11599};
11600
11601var scale_logarithmic = core_scale.extend({
11602 determineDataLimits: function() {
11603 var me = this;
11604 var opts = me.options;
11605 var chart = me.chart;
11606 var data = chart.data;
11607 var datasets = data.datasets;
11608 var isHorizontal = me.isHorizontal();
11609 function IDMatches(meta) {
11610 return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
11611 }
11612
11613 // Calculate Range
11614 me.min = null;
11615 me.max = null;
11616 me.minNotZero = null;
11617
11618 var hasStacks = opts.stacked;
11619 if (hasStacks === undefined) {
11620 helpers$1.each(datasets, function(dataset, datasetIndex) {
11621 if (hasStacks) {
11622 return;
11623 }
11624
11625 var meta = chart.getDatasetMeta(datasetIndex);
11626 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
11627 meta.stack !== undefined) {
11628 hasStacks = true;
11629 }
11630 });
11631 }
11632
11633 if (opts.stacked || hasStacks) {
11634 var valuesPerStack = {};
11635
11636 helpers$1.each(datasets, function(dataset, datasetIndex) {
11637 var meta = chart.getDatasetMeta(datasetIndex);
11638 var key = [
11639 meta.type,
11640 // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
11641 ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
11642 meta.stack
11643 ].join('.');
11644
11645 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
11646 if (valuesPerStack[key] === undefined) {
11647 valuesPerStack[key] = [];
11648 }
11649
11650 helpers$1.each(dataset.data, function(rawValue, index) {
11651 var values = valuesPerStack[key];
11652 var value = +me.getRightValue(rawValue);
11653 // invalid, hidden and negative values are ignored
11654 if (isNaN(value) || meta.data[index].hidden || value < 0) {
11655 return;
11656 }
11657 values[index] = values[index] || 0;
11658 values[index] += value;
11659 });
11660 }
11661 });
11662
11663 helpers$1.each(valuesPerStack, function(valuesForType) {
11664 if (valuesForType.length > 0) {
11665 var minVal = helpers$1.min(valuesForType);
11666 var maxVal = helpers$1.max(valuesForType);
11667 me.min = me.min === null ? minVal : Math.min(me.min, minVal);
11668 me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
11669 }
11670 });
11671
11672 } else {
11673 helpers$1.each(datasets, function(dataset, datasetIndex) {
11674 var meta = chart.getDatasetMeta(datasetIndex);
11675 if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
11676 helpers$1.each(dataset.data, function(rawValue, index) {
11677 var value = +me.getRightValue(rawValue);
11678 // invalid, hidden and negative values are ignored
11679 if (isNaN(value) || meta.data[index].hidden || value < 0) {
11680 return;
11681 }
11682
11683 if (me.min === null) {
11684 me.min = value;
11685 } else if (value < me.min) {
11686 me.min = value;
11687 }
11688
11689 if (me.max === null) {
11690 me.max = value;
11691 } else if (value > me.max) {
11692 me.max = value;
11693 }
11694
11695 if (value !== 0 && (me.minNotZero === null || value < me.minNotZero)) {
11696 me.minNotZero = value;
11697 }
11698 });
11699 }
11700 });
11701 }
11702
11703 // Common base implementation to handle ticks.min, ticks.max
11704 this.handleTickRangeOptions();
11705 },
11706
11707 handleTickRangeOptions: function() {
11708 var me = this;
11709 var tickOpts = me.options.ticks;
11710 var DEFAULT_MIN = 1;
11711 var DEFAULT_MAX = 10;
11712
11713 me.min = valueOrDefault$8(tickOpts.min, me.min);
11714 me.max = valueOrDefault$8(tickOpts.max, me.max);
11715
11716 if (me.min === me.max) {
11717 if (me.min !== 0 && me.min !== null) {
11718 me.min = Math.pow(10, Math.floor(helpers$1.log10(me.min)) - 1);
11719 me.max = Math.pow(10, Math.floor(helpers$1.log10(me.max)) + 1);
11720 } else {
11721 me.min = DEFAULT_MIN;
11722 me.max = DEFAULT_MAX;
11723 }
11724 }
11725 if (me.min === null) {
11726 me.min = Math.pow(10, Math.floor(helpers$1.log10(me.max)) - 1);
11727 }
11728 if (me.max === null) {
11729 me.max = me.min !== 0
11730 ? Math.pow(10, Math.floor(helpers$1.log10(me.min)) + 1)
11731 : DEFAULT_MAX;
11732 }
11733 if (me.minNotZero === null) {
11734 if (me.min > 0) {
11735 me.minNotZero = me.min;
11736 } else if (me.max < 1) {
11737 me.minNotZero = Math.pow(10, Math.floor(helpers$1.log10(me.max)));
11738 } else {
11739 me.minNotZero = DEFAULT_MIN;
11740 }
11741 }
11742 },
11743
11744 buildTicks: function() {
11745 var me = this;
11746 var tickOpts = me.options.ticks;
11747 var reverse = !me.isHorizontal();
11748
11749 var generationOptions = {
11750 min: tickOpts.min,
11751 max: tickOpts.max
11752 };
11753 var ticks = me.ticks = generateTicks$1(generationOptions, me);
11754
11755 // At this point, we need to update our max and min given the tick values since we have expanded the
11756 // range of the scale
11757 me.max = helpers$1.max(ticks);
11758 me.min = helpers$1.min(ticks);
11759
11760 if (tickOpts.reverse) {
11761 reverse = !reverse;
11762 me.start = me.max;
11763 me.end = me.min;
11764 } else {
11765 me.start = me.min;
11766 me.end = me.max;
11767 }
11768 if (reverse) {
11769 ticks.reverse();
11770 }
11771 },
11772
11773 convertTicksToLabels: function() {
11774 this.tickValues = this.ticks.slice();
11775
11776 core_scale.prototype.convertTicksToLabels.call(this);
11777 },
11778
11779 // Get the correct tooltip label
11780 getLabelForIndex: function(index, datasetIndex) {
11781 return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
11782 },
11783
11784 getPixelForTick: function(index) {
11785 return this.getPixelForValue(this.tickValues[index]);
11786 },
11787
11788 /**
11789 * Returns the value of the first tick.
11790 * @param {Number} value - The minimum not zero value.
11791 * @return {Number} The first tick value.
11792 * @private
11793 */
11794 _getFirstTickValue: function(value) {
11795 var exp = Math.floor(helpers$1.log10(value));
11796 var significand = Math.floor(value / Math.pow(10, exp));
11797
11798 return significand * Math.pow(10, exp);
11799 },
11800
11801 getPixelForValue: function(value) {
11802 var me = this;
11803 var tickOpts = me.options.ticks;
11804 var reverse = tickOpts.reverse;
11805 var log10 = helpers$1.log10;
11806 var firstTickValue = me._getFirstTickValue(me.minNotZero);
11807 var offset = 0;
11808 var innerDimension, pixel, start, end, sign;
11809
11810 value = +me.getRightValue(value);
11811 if (reverse) {
11812 start = me.end;
11813 end = me.start;
11814 sign = -1;
11815 } else {
11816 start = me.start;
11817 end = me.end;
11818 sign = 1;
11819 }
11820 if (me.isHorizontal()) {
11821 innerDimension = me.width;
11822 pixel = reverse ? me.right : me.left;
11823 } else {
11824 innerDimension = me.height;
11825 sign *= -1; // invert, since the upper-left corner of the canvas is at pixel (0, 0)
11826 pixel = reverse ? me.top : me.bottom;
11827 }
11828 if (value !== start) {
11829 if (start === 0) { // include zero tick
11830 offset = valueOrDefault$8(tickOpts.fontSize, core_defaults.global.defaultFontSize);
11831 innerDimension -= offset;
11832 start = firstTickValue;
11833 }
11834 if (value !== 0) {
11835 offset += innerDimension / (log10(end) - log10(start)) * (log10(value) - log10(start));
11836 }
11837 pixel += sign * offset;
11838 }
11839 return pixel;
11840 },
11841
11842 getValueForPixel: function(pixel) {
11843 var me = this;
11844 var tickOpts = me.options.ticks;
11845 var reverse = tickOpts.reverse;
11846 var log10 = helpers$1.log10;
11847 var firstTickValue = me._getFirstTickValue(me.minNotZero);
11848 var innerDimension, start, end, value;
11849
11850 if (reverse) {
11851 start = me.end;
11852 end = me.start;
11853 } else {
11854 start = me.start;
11855 end = me.end;
11856 }
11857 if (me.isHorizontal()) {
11858 innerDimension = me.width;
11859 value = reverse ? me.right - pixel : pixel - me.left;
11860 } else {
11861 innerDimension = me.height;
11862 value = reverse ? pixel - me.top : me.bottom - pixel;
11863 }
11864 if (value !== start) {
11865 if (start === 0) { // include zero tick
11866 var offset = valueOrDefault$8(tickOpts.fontSize, core_defaults.global.defaultFontSize);
11867 value -= offset;
11868 innerDimension -= offset;
11869 start = firstTickValue;
11870 }
11871 value *= log10(end) - log10(start);
11872 value /= innerDimension;
11873 value = Math.pow(10, log10(start) + value);
11874 }
11875 return value;
11876 }
11877});
11878
11879// INTERNAL: static default options, registered in src/chart.js
11880var _defaults$2 = defaultConfig$2;
11881scale_logarithmic._defaults = _defaults$2;
11882
11883var valueOrDefault$9 = helpers$1.valueOrDefault;
11884var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault;
11885var resolve$7 = helpers$1.options.resolve;
11886
11887var defaultConfig$3 = {
11888 display: true,
11889
11890 // Boolean - Whether to animate scaling the chart from the centre
11891 animate: true,
11892 position: 'chartArea',
11893
11894 angleLines: {
11895 display: true,
11896 color: 'rgba(0, 0, 0, 0.1)',
11897 lineWidth: 1,
11898 borderDash: [],
11899 borderDashOffset: 0.0
11900 },
11901
11902 gridLines: {
11903 circular: false
11904 },
11905
11906 // label settings
11907 ticks: {
11908 // Boolean - Show a backdrop to the scale label
11909 showLabelBackdrop: true,
11910
11911 // String - The colour of the label backdrop
11912 backdropColor: 'rgba(255,255,255,0.75)',
11913
11914 // Number - The backdrop padding above & below the label in pixels
11915 backdropPaddingY: 2,
11916
11917 // Number - The backdrop padding to the side of the label in pixels
11918 backdropPaddingX: 2,
11919
11920 callback: core_ticks.formatters.linear
11921 },
11922
11923 pointLabels: {
11924 // Boolean - if true, show point labels
11925 display: true,
11926
11927 // Number - Point label font size in pixels
11928 fontSize: 10,
11929
11930 // Function - Used to convert point labels
11931 callback: function(label) {
11932 return label;
11933 }
11934 }
11935};
11936
11937function getValueCount(scale) {
11938 var opts = scale.options;
11939 return opts.angleLines.display || opts.pointLabels.display ? scale.chart.data.labels.length : 0;
11940}
11941
11942function getTickBackdropHeight(opts) {
11943 var tickOpts = opts.ticks;
11944
11945 if (tickOpts.display && opts.display) {
11946 return valueOrDefault$9(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;
11947 }
11948 return 0;
11949}
11950
11951function measureLabelSize(ctx, lineHeight, label) {
11952 if (helpers$1.isArray(label)) {
11953 return {
11954 w: helpers$1.longestText(ctx, ctx.font, label),
11955 h: label.length * lineHeight
11956 };
11957 }
11958
11959 return {
11960 w: ctx.measureText(label).width,
11961 h: lineHeight
11962 };
11963}
11964
11965function determineLimits(angle, pos, size, min, max) {
11966 if (angle === min || angle === max) {
11967 return {
11968 start: pos - (size / 2),
11969 end: pos + (size / 2)
11970 };
11971 } else if (angle < min || angle > max) {
11972 return {
11973 start: pos - size,
11974 end: pos
11975 };
11976 }
11977
11978 return {
11979 start: pos,
11980 end: pos + size
11981 };
11982}
11983
11984/**
11985 * Helper function to fit a radial linear scale with point labels
11986 */
11987function fitWithPointLabels(scale) {
11988
11989 // Right, this is really confusing and there is a lot of maths going on here
11990 // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
11991 //
11992 // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
11993 //
11994 // Solution:
11995 //
11996 // We assume the radius of the polygon is half the size of the canvas at first
11997 // at each index we check if the text overlaps.
11998 //
11999 // Where it does, we store that angle and that index.
12000 //
12001 // After finding the largest index and angle we calculate how much we need to remove
12002 // from the shape radius to move the point inwards by that x.
12003 //
12004 // We average the left and right distances to get the maximum shape radius that can fit in the box
12005 // along with labels.
12006 //
12007 // Once we have that, we can find the centre point for the chart, by taking the x text protrusion
12008 // on each side, removing that from the size, halving it and adding the left x protrusion width.
12009 //
12010 // This will mean we have a shape fitted to the canvas, as large as it can be with the labels
12011 // and position it in the most space efficient manner
12012 //
12013 // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
12014
12015 var plFont = helpers$1.options._parseFont(scale.options.pointLabels);
12016
12017 // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
12018 // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
12019 var furthestLimits = {
12020 l: 0,
12021 r: scale.width,
12022 t: 0,
12023 b: scale.height - scale.paddingTop
12024 };
12025 var furthestAngles = {};
12026 var i, textSize, pointPosition;
12027
12028 scale.ctx.font = plFont.string;
12029 scale._pointLabelSizes = [];
12030
12031 var valueCount = getValueCount(scale);
12032 for (i = 0; i < valueCount; i++) {
12033 pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
12034 textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i] || '');
12035 scale._pointLabelSizes[i] = textSize;
12036
12037 // Add quarter circle to make degree 0 mean top of circle
12038 var angleRadians = scale.getIndexAngle(i);
12039 var angle = helpers$1.toDegrees(angleRadians) % 360;
12040 var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
12041 var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
12042
12043 if (hLimits.start < furthestLimits.l) {
12044 furthestLimits.l = hLimits.start;
12045 furthestAngles.l = angleRadians;
12046 }
12047
12048 if (hLimits.end > furthestLimits.r) {
12049 furthestLimits.r = hLimits.end;
12050 furthestAngles.r = angleRadians;
12051 }
12052
12053 if (vLimits.start < furthestLimits.t) {
12054 furthestLimits.t = vLimits.start;
12055 furthestAngles.t = angleRadians;
12056 }
12057
12058 if (vLimits.end > furthestLimits.b) {
12059 furthestLimits.b = vLimits.end;
12060 furthestAngles.b = angleRadians;
12061 }
12062 }
12063
12064 scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);
12065}
12066
12067function getTextAlignForAngle(angle) {
12068 if (angle === 0 || angle === 180) {
12069 return 'center';
12070 } else if (angle < 180) {
12071 return 'left';
12072 }
12073
12074 return 'right';
12075}
12076
12077function fillText(ctx, text, position, lineHeight) {
12078 var y = position.y + lineHeight / 2;
12079 var i, ilen;
12080
12081 if (helpers$1.isArray(text)) {
12082 for (i = 0, ilen = text.length; i < ilen; ++i) {
12083 ctx.fillText(text[i], position.x, y);
12084 y += lineHeight;
12085 }
12086 } else {
12087 ctx.fillText(text, position.x, y);
12088 }
12089}
12090
12091function adjustPointPositionForLabelHeight(angle, textSize, position) {
12092 if (angle === 90 || angle === 270) {
12093 position.y -= (textSize.h / 2);
12094 } else if (angle > 270 || angle < 90) {
12095 position.y -= textSize.h;
12096 }
12097}
12098
12099function drawPointLabels(scale) {
12100 var ctx = scale.ctx;
12101 var opts = scale.options;
12102 var angleLineOpts = opts.angleLines;
12103 var gridLineOpts = opts.gridLines;
12104 var pointLabelOpts = opts.pointLabels;
12105 var lineWidth = valueOrDefault$9(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
12106 var lineColor = valueOrDefault$9(angleLineOpts.color, gridLineOpts.color);
12107 var tickBackdropHeight = getTickBackdropHeight(opts);
12108
12109 ctx.save();
12110 ctx.lineWidth = lineWidth;
12111 ctx.strokeStyle = lineColor;
12112 if (ctx.setLineDash) {
12113 ctx.setLineDash(resolve$7([angleLineOpts.borderDash, gridLineOpts.borderDash, []]));
12114 ctx.lineDashOffset = resolve$7([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]);
12115 }
12116
12117 var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
12118
12119 // Point Label Font
12120 var plFont = helpers$1.options._parseFont(pointLabelOpts);
12121
12122 ctx.font = plFont.string;
12123 ctx.textBaseline = 'middle';
12124
12125 for (var i = getValueCount(scale) - 1; i >= 0; i--) {
12126 if (angleLineOpts.display && lineWidth && lineColor) {
12127 var outerPosition = scale.getPointPosition(i, outerDistance);
12128 ctx.beginPath();
12129 ctx.moveTo(scale.xCenter, scale.yCenter);
12130 ctx.lineTo(outerPosition.x, outerPosition.y);
12131 ctx.stroke();
12132 }
12133
12134 if (pointLabelOpts.display) {
12135 // Extra pixels out for some label spacing
12136 var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
12137 var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
12138
12139 // Keep this in loop since we may support array properties here
12140 var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor);
12141 ctx.fillStyle = pointLabelFontColor;
12142
12143 var angleRadians = scale.getIndexAngle(i);
12144 var angle = helpers$1.toDegrees(angleRadians);
12145 ctx.textAlign = getTextAlignForAngle(angle);
12146 adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
12147 fillText(ctx, scale.pointLabels[i] || '', pointLabelPosition, plFont.lineHeight);
12148 }
12149 }
12150 ctx.restore();
12151}
12152
12153function drawRadiusLine(scale, gridLineOpts, radius, index) {
12154 var ctx = scale.ctx;
12155 var circular = gridLineOpts.circular;
12156 var valueCount = getValueCount(scale);
12157 var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1);
12158 var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1);
12159 var pointPosition;
12160
12161 if ((!circular && !valueCount) || !lineColor || !lineWidth) {
12162 return;
12163 }
12164
12165 ctx.save();
12166 ctx.strokeStyle = lineColor;
12167 ctx.lineWidth = lineWidth;
12168 if (ctx.setLineDash) {
12169 ctx.setLineDash(gridLineOpts.borderDash || []);
12170 ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0;
12171 }
12172
12173 ctx.beginPath();
12174 if (circular) {
12175 // Draw circular arcs between the points
12176 ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
12177 } else {
12178 // Draw straight lines connecting each index
12179 pointPosition = scale.getPointPosition(0, radius);
12180 ctx.moveTo(pointPosition.x, pointPosition.y);
12181
12182 for (var i = 1; i < valueCount; i++) {
12183 pointPosition = scale.getPointPosition(i, radius);
12184 ctx.lineTo(pointPosition.x, pointPosition.y);
12185 }
12186 }
12187 ctx.closePath();
12188 ctx.stroke();
12189 ctx.restore();
12190}
12191
12192function numberOrZero(param) {
12193 return helpers$1.isNumber(param) ? param : 0;
12194}
12195
12196var scale_radialLinear = scale_linearbase.extend({
12197 setDimensions: function() {
12198 var me = this;
12199
12200 // Set the unconstrained dimension before label rotation
12201 me.width = me.maxWidth;
12202 me.height = me.maxHeight;
12203 me.paddingTop = getTickBackdropHeight(me.options) / 2;
12204 me.xCenter = Math.floor(me.width / 2);
12205 me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
12206 me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
12207 },
12208
12209 determineDataLimits: function() {
12210 var me = this;
12211 var chart = me.chart;
12212 var min = Number.POSITIVE_INFINITY;
12213 var max = Number.NEGATIVE_INFINITY;
12214
12215 helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) {
12216 if (chart.isDatasetVisible(datasetIndex)) {
12217 var meta = chart.getDatasetMeta(datasetIndex);
12218
12219 helpers$1.each(dataset.data, function(rawValue, index) {
12220 var value = +me.getRightValue(rawValue);
12221 if (isNaN(value) || meta.data[index].hidden) {
12222 return;
12223 }
12224
12225 min = Math.min(value, min);
12226 max = Math.max(value, max);
12227 });
12228 }
12229 });
12230
12231 me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
12232 me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
12233
12234 // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
12235 me.handleTickRangeOptions();
12236 },
12237
12238 // Returns the maximum number of ticks based on the scale dimension
12239 _computeTickLimit: function() {
12240 return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
12241 },
12242
12243 convertTicksToLabels: function() {
12244 var me = this;
12245
12246 scale_linearbase.prototype.convertTicksToLabels.call(me);
12247
12248 // Point labels
12249 me.pointLabels = me.chart.data.labels.map(me.options.pointLabels.callback, me);
12250 },
12251
12252 getLabelForIndex: function(index, datasetIndex) {
12253 return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
12254 },
12255
12256 fit: function() {
12257 var me = this;
12258 var opts = me.options;
12259
12260 if (opts.display && opts.pointLabels.display) {
12261 fitWithPointLabels(me);
12262 } else {
12263 me.setCenterPoint(0, 0, 0, 0);
12264 }
12265 },
12266
12267 /**
12268 * Set radius reductions and determine new radius and center point
12269 * @private
12270 */
12271 setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
12272 var me = this;
12273 var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
12274 var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
12275 var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
12276 var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
12277
12278 radiusReductionLeft = numberOrZero(radiusReductionLeft);
12279 radiusReductionRight = numberOrZero(radiusReductionRight);
12280 radiusReductionTop = numberOrZero(radiusReductionTop);
12281 radiusReductionBottom = numberOrZero(radiusReductionBottom);
12282
12283 me.drawingArea = Math.min(
12284 Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
12285 Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
12286 me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
12287 },
12288
12289 setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
12290 var me = this;
12291 var maxRight = me.width - rightMovement - me.drawingArea;
12292 var maxLeft = leftMovement + me.drawingArea;
12293 var maxTop = topMovement + me.drawingArea;
12294 var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
12295
12296 me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
12297 me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
12298 },
12299
12300 getIndexAngle: function(index) {
12301 var angleMultiplier = (Math.PI * 2) / getValueCount(this);
12302 var startAngle = this.chart.options && this.chart.options.startAngle ?
12303 this.chart.options.startAngle :
12304 0;
12305
12306 var startAngleRadians = startAngle * Math.PI * 2 / 360;
12307
12308 // Start from the top instead of right, so remove a quarter of the circle
12309 return index * angleMultiplier + startAngleRadians;
12310 },
12311
12312 getDistanceFromCenterForValue: function(value) {
12313 var me = this;
12314
12315 if (value === null) {
12316 return 0; // null always in center
12317 }
12318
12319 // Take into account half font size + the yPadding of the top value
12320 var scalingFactor = me.drawingArea / (me.max - me.min);
12321 if (me.options.ticks.reverse) {
12322 return (me.max - value) * scalingFactor;
12323 }
12324 return (value - me.min) * scalingFactor;
12325 },
12326
12327 getPointPosition: function(index, distanceFromCenter) {
12328 var me = this;
12329 var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
12330 return {
12331 x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter,
12332 y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter
12333 };
12334 },
12335
12336 getPointPositionForValue: function(index, value) {
12337 return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
12338 },
12339
12340 getBasePosition: function() {
12341 var me = this;
12342 var min = me.min;
12343 var max = me.max;
12344
12345 return me.getPointPositionForValue(0,
12346 me.beginAtZero ? 0 :
12347 min < 0 && max < 0 ? max :
12348 min > 0 && max > 0 ? min :
12349 0);
12350 },
12351
12352 draw: function() {
12353 var me = this;
12354 var opts = me.options;
12355 var gridLineOpts = opts.gridLines;
12356 var tickOpts = opts.ticks;
12357
12358 if (opts.display) {
12359 var ctx = me.ctx;
12360 var startAngle = this.getIndexAngle(0);
12361 var tickFont = helpers$1.options._parseFont(tickOpts);
12362
12363 if (opts.angleLines.display || opts.pointLabels.display) {
12364 drawPointLabels(me);
12365 }
12366
12367 helpers$1.each(me.ticks, function(label, index) {
12368 // Don't draw a centre value (if it is minimum)
12369 if (index > 0 || tickOpts.reverse) {
12370 var yCenterOffset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
12371
12372 // Draw circular lines around the scale
12373 if (gridLineOpts.display && index !== 0) {
12374 drawRadiusLine(me, gridLineOpts, yCenterOffset, index);
12375 }
12376
12377 if (tickOpts.display) {
12378 var tickFontColor = valueOrDefault$9(tickOpts.fontColor, core_defaults.global.defaultFontColor);
12379 ctx.font = tickFont.string;
12380
12381 ctx.save();
12382 ctx.translate(me.xCenter, me.yCenter);
12383 ctx.rotate(startAngle);
12384
12385 if (tickOpts.showLabelBackdrop) {
12386 var labelWidth = ctx.measureText(label).width;
12387 ctx.fillStyle = tickOpts.backdropColor;
12388 ctx.fillRect(
12389 -labelWidth / 2 - tickOpts.backdropPaddingX,
12390 -yCenterOffset - tickFont.size / 2 - tickOpts.backdropPaddingY,
12391 labelWidth + tickOpts.backdropPaddingX * 2,
12392 tickFont.size + tickOpts.backdropPaddingY * 2
12393 );
12394 }
12395
12396 ctx.textAlign = 'center';
12397 ctx.textBaseline = 'middle';
12398 ctx.fillStyle = tickFontColor;
12399 ctx.fillText(label, 0, -yCenterOffset);
12400 ctx.restore();
12401 }
12402 }
12403 });
12404 }
12405 }
12406});
12407
12408// INTERNAL: static default options, registered in src/chart.js
12409var _defaults$3 = defaultConfig$3;
12410scale_radialLinear._defaults = _defaults$3;
12411
12412var adapter = core_adapters._date;
12413
12414
12415
12416
12417var valueOrDefault$a = helpers$1.valueOrDefault;
12418
12419// Integer constants are from the ES6 spec.
12420var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
12421var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
12422
12423var INTERVALS = {
12424 millisecond: {
12425 common: true,
12426 size: 1,
12427 steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]
12428 },
12429 second: {
12430 common: true,
12431 size: 1000,
12432 steps: [1, 2, 5, 10, 15, 30]
12433 },
12434 minute: {
12435 common: true,
12436 size: 60000,
12437 steps: [1, 2, 5, 10, 15, 30]
12438 },
12439 hour: {
12440 common: true,
12441 size: 3600000,
12442 steps: [1, 2, 3, 6, 12]
12443 },
12444 day: {
12445 common: true,
12446 size: 86400000,
12447 steps: [1, 2, 5]
12448 },
12449 week: {
12450 common: false,
12451 size: 604800000,
12452 steps: [1, 2, 3, 4]
12453 },
12454 month: {
12455 common: true,
12456 size: 2.628e9,
12457 steps: [1, 2, 3]
12458 },
12459 quarter: {
12460 common: false,
12461 size: 7.884e9,
12462 steps: [1, 2, 3, 4]
12463 },
12464 year: {
12465 common: true,
12466 size: 3.154e10
12467 }
12468};
12469
12470var UNITS = Object.keys(INTERVALS);
12471
12472function sorter(a, b) {
12473 return a - b;
12474}
12475
12476function arrayUnique(items) {
12477 var hash = {};
12478 var out = [];
12479 var i, ilen, item;
12480
12481 for (i = 0, ilen = items.length; i < ilen; ++i) {
12482 item = items[i];
12483 if (!hash[item]) {
12484 hash[item] = true;
12485 out.push(item);
12486 }
12487 }
12488
12489 return out;
12490}
12491
12492/**
12493 * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
12494 * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
12495 * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
12496 * extremity (left + width or top + height). Note that it would be more optimized to directly
12497 * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
12498 * to create the lookup table. The table ALWAYS contains at least two items: min and max.
12499 *
12500 * @param {Number[]} timestamps - timestamps sorted from lowest to highest.
12501 * @param {String} distribution - If 'linear', timestamps will be spread linearly along the min
12502 * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
12503 * If 'series', timestamps will be positioned at the same distance from each other. In this
12504 * case, only timestamps that break the time linearity are registered, meaning that in the
12505 * best case, all timestamps are linear, the table contains only min and max.
12506 */
12507function buildLookupTable(timestamps, min, max, distribution) {
12508 if (distribution === 'linear' || !timestamps.length) {
12509 return [
12510 {time: min, pos: 0},
12511 {time: max, pos: 1}
12512 ];
12513 }
12514
12515 var table = [];
12516 var items = [min];
12517 var i, ilen, prev, curr, next;
12518
12519 for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
12520 curr = timestamps[i];
12521 if (curr > min && curr < max) {
12522 items.push(curr);
12523 }
12524 }
12525
12526 items.push(max);
12527
12528 for (i = 0, ilen = items.length; i < ilen; ++i) {
12529 next = items[i + 1];
12530 prev = items[i - 1];
12531 curr = items[i];
12532
12533 // only add points that breaks the scale linearity
12534 if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
12535 table.push({time: curr, pos: i / (ilen - 1)});
12536 }
12537 }
12538
12539 return table;
12540}
12541
12542// @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
12543function lookup(table, key, value) {
12544 var lo = 0;
12545 var hi = table.length - 1;
12546 var mid, i0, i1;
12547
12548 while (lo >= 0 && lo <= hi) {
12549 mid = (lo + hi) >> 1;
12550 i0 = table[mid - 1] || null;
12551 i1 = table[mid];
12552
12553 if (!i0) {
12554 // given value is outside table (before first item)
12555 return {lo: null, hi: i1};
12556 } else if (i1[key] < value) {
12557 lo = mid + 1;
12558 } else if (i0[key] > value) {
12559 hi = mid - 1;
12560 } else {
12561 return {lo: i0, hi: i1};
12562 }
12563 }
12564
12565 // given value is outside table (after last item)
12566 return {lo: i1, hi: null};
12567}
12568
12569/**
12570 * Linearly interpolates the given source `value` using the table items `skey` values and
12571 * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
12572 * returns the position for a timestamp equal to 42. If value is out of bounds, values at
12573 * index [0, 1] or [n - 1, n] are used for the interpolation.
12574 */
12575function interpolate$1(table, skey, sval, tkey) {
12576 var range = lookup(table, skey, sval);
12577
12578 // Note: the lookup table ALWAYS contains at least 2 items (min and max)
12579 var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
12580 var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
12581
12582 var span = next[skey] - prev[skey];
12583 var ratio = span ? (sval - prev[skey]) / span : 0;
12584 var offset = (next[tkey] - prev[tkey]) * ratio;
12585
12586 return prev[tkey] + offset;
12587}
12588
12589function toTimestamp(input, options) {
12590 var parser = options.parser;
12591 var format = parser || options.format;
12592 var value = input;
12593
12594 if (typeof parser === 'function') {
12595 value = parser(value);
12596 }
12597
12598 // Only parse if its not a timestamp already
12599 if (!helpers$1.isFinite(value)) {
12600 value = typeof format === 'string'
12601 ? adapter.parse(value, format)
12602 : adapter.parse(value);
12603 }
12604
12605 if (value !== null) {
12606 return +value;
12607 }
12608
12609 // Labels are in an incompatible format and no `parser` has been provided.
12610 // The user might still use the deprecated `format` option for parsing.
12611 if (!parser && typeof format === 'function') {
12612 value = format(input);
12613
12614 // `format` could return something else than a timestamp, if so, parse it
12615 if (!helpers$1.isFinite(value)) {
12616 value = adapter.parse(value);
12617 }
12618 }
12619
12620 return value;
12621}
12622
12623function parse(input, scale) {
12624 if (helpers$1.isNullOrUndef(input)) {
12625 return null;
12626 }
12627
12628 var options = scale.options.time;
12629 var value = toTimestamp(scale.getRightValue(input), options);
12630 if (value === null) {
12631 return value;
12632 }
12633
12634 if (options.round) {
12635 value = +adapter.startOf(value, options.round);
12636 }
12637
12638 return value;
12639}
12640
12641/**
12642 * Returns the number of unit to skip to be able to display up to `capacity` number of ticks
12643 * in `unit` for the given `min` / `max` range and respecting the interval steps constraints.
12644 */
12645function determineStepSize(min, max, unit, capacity) {
12646 var range = max - min;
12647 var interval = INTERVALS[unit];
12648 var milliseconds = interval.size;
12649 var steps = interval.steps;
12650 var i, ilen, factor;
12651
12652 if (!steps) {
12653 return Math.ceil(range / (capacity * milliseconds));
12654 }
12655
12656 for (i = 0, ilen = steps.length; i < ilen; ++i) {
12657 factor = steps[i];
12658 if (Math.ceil(range / (milliseconds * factor)) <= capacity) {
12659 break;
12660 }
12661 }
12662
12663 return factor;
12664}
12665
12666/**
12667 * Figures out what unit results in an appropriate number of auto-generated ticks
12668 */
12669function determineUnitForAutoTicks(minUnit, min, max, capacity) {
12670 var ilen = UNITS.length;
12671 var i, interval, factor;
12672
12673 for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
12674 interval = INTERVALS[UNITS[i]];
12675 factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER;
12676
12677 if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
12678 return UNITS[i];
12679 }
12680 }
12681
12682 return UNITS[ilen - 1];
12683}
12684
12685/**
12686 * Figures out what unit to format a set of ticks with
12687 */
12688function determineUnitForFormatting(ticks, minUnit, min, max) {
12689 var ilen = UNITS.length;
12690 var i, unit;
12691
12692 for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) {
12693 unit = UNITS[i];
12694 if (INTERVALS[unit].common && adapter.diff(max, min, unit) >= ticks.length) {
12695 return unit;
12696 }
12697 }
12698
12699 return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
12700}
12701
12702function determineMajorUnit(unit) {
12703 for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
12704 if (INTERVALS[UNITS[i]].common) {
12705 return UNITS[i];
12706 }
12707 }
12708}
12709
12710/**
12711 * Generates a maximum of `capacity` timestamps between min and max, rounded to the
12712 * `minor` unit, aligned on the `major` unit and using the given scale time `options`.
12713 * Important: this method can return ticks outside the min and max range, it's the
12714 * responsibility of the calling code to clamp values if needed.
12715 */
12716function generate(min, max, capacity, options) {
12717 var timeOpts = options.time;
12718 var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
12719 var major = determineMajorUnit(minor);
12720 var stepSize = valueOrDefault$a(timeOpts.stepSize, timeOpts.unitStepSize);
12721 var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
12722 var majorTicksEnabled = options.ticks.major.enabled;
12723 var interval = INTERVALS[minor];
12724 var first = min;
12725 var last = max;
12726 var ticks = [];
12727 var time;
12728
12729 if (!stepSize) {
12730 stepSize = determineStepSize(min, max, minor, capacity);
12731 }
12732
12733 // For 'week' unit, handle the first day of week option
12734 if (weekday) {
12735 first = +adapter.startOf(first, 'isoWeek', weekday);
12736 last = +adapter.startOf(last, 'isoWeek', weekday);
12737 }
12738
12739 // Align first/last ticks on unit
12740 first = +adapter.startOf(first, weekday ? 'day' : minor);
12741 last = +adapter.startOf(last, weekday ? 'day' : minor);
12742
12743 // Make sure that the last tick include max
12744 if (last < max) {
12745 last = +adapter.add(last, 1, minor);
12746 }
12747
12748 time = first;
12749
12750 if (majorTicksEnabled && major && !weekday && !timeOpts.round) {
12751 // Align the first tick on the previous `minor` unit aligned on the `major` unit:
12752 // we first aligned time on the previous `major` unit then add the number of full
12753 // stepSize there is between first and the previous major time.
12754 time = +adapter.startOf(time, major);
12755 time = +adapter.add(time, ~~((first - time) / (interval.size * stepSize)) * stepSize, minor);
12756 }
12757
12758 for (; time < last; time = +adapter.add(time, stepSize, minor)) {
12759 ticks.push(+time);
12760 }
12761
12762 ticks.push(+time);
12763
12764 return ticks;
12765}
12766
12767/**
12768 * Returns the start and end offsets from edges in the form of {start, end}
12769 * where each value is a relative width to the scale and ranges between 0 and 1.
12770 * They add extra margins on the both sides by scaling down the original scale.
12771 * Offsets are added when the `offset` option is true.
12772 */
12773function computeOffsets(table, ticks, min, max, options) {
12774 var start = 0;
12775 var end = 0;
12776 var first, last;
12777
12778 if (options.offset && ticks.length) {
12779 if (!options.time.min) {
12780 first = interpolate$1(table, 'time', ticks[0], 'pos');
12781 if (ticks.length === 1) {
12782 start = 1 - first;
12783 } else {
12784 start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2;
12785 }
12786 }
12787 if (!options.time.max) {
12788 last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos');
12789 if (ticks.length === 1) {
12790 end = last;
12791 } else {
12792 end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2;
12793 }
12794 }
12795 }
12796
12797 return {start: start, end: end};
12798}
12799
12800function ticksFromTimestamps(values, majorUnit) {
12801 var ticks = [];
12802 var i, ilen, value, major;
12803
12804 for (i = 0, ilen = values.length; i < ilen; ++i) {
12805 value = values[i];
12806 major = majorUnit ? value === +adapter.startOf(value, majorUnit) : false;
12807
12808 ticks.push({
12809 value: value,
12810 major: major
12811 });
12812 }
12813
12814 return ticks;
12815}
12816
12817/**
12818 * Return the time format for the label with the most parts (milliseconds, second, etc.)
12819 */
12820function determineLabelFormat(timestamps) {
12821 var presets = adapter.presets();
12822 var ilen = timestamps.length;
12823 var i, ts, hasTime;
12824
12825 for (i = 0; i < ilen; i++) {
12826 ts = timestamps[i];
12827 if (ts % INTERVALS.second.size !== 0) {
12828 return presets.full;
12829 }
12830 if (!hasTime && adapter.startOf(ts, 'day') !== ts) {
12831 hasTime = true;
12832 }
12833 }
12834 if (hasTime) {
12835 return presets.time;
12836 }
12837 return presets.date;
12838}
12839
12840var defaultConfig$4 = {
12841 position: 'bottom',
12842
12843 /**
12844 * Data distribution along the scale:
12845 * - 'linear': data are spread according to their time (distances can vary),
12846 * - 'series': data are spread at the same distance from each other.
12847 * @see https://github.com/chartjs/Chart.js/pull/4507
12848 * @since 2.7.0
12849 */
12850 distribution: 'linear',
12851
12852 /**
12853 * Scale boundary strategy (bypassed by min/max time options)
12854 * - `data`: make sure data are fully visible, ticks outside are removed
12855 * - `ticks`: make sure ticks are fully visible, data outside are truncated
12856 * @see https://github.com/chartjs/Chart.js/pull/4556
12857 * @since 2.7.0
12858 */
12859 bounds: 'data',
12860
12861 time: {
12862 parser: false, // false == a pattern string from https://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment
12863 format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from https://momentjs.com/docs/#/parsing/string-format/
12864 unit: false, // false == automatic or override with week, month, year, etc.
12865 round: false, // none, or override with week, month, year, etc.
12866 displayFormat: false, // DEPRECATED
12867 isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/
12868 minUnit: 'millisecond',
12869 displayFormats: {}
12870 },
12871 ticks: {
12872 autoSkip: false,
12873
12874 /**
12875 * Ticks generation input values:
12876 * - 'auto': generates "optimal" ticks based on scale size and time options.
12877 * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
12878 * - 'labels': generates ticks from user given `data.labels` values ONLY.
12879 * @see https://github.com/chartjs/Chart.js/pull/4507
12880 * @since 2.7.0
12881 */
12882 source: 'auto',
12883
12884 major: {
12885 enabled: false
12886 }
12887 }
12888};
12889
12890var scale_time = core_scale.extend({
12891 initialize: function() {
12892 this.mergeTicksOptions();
12893 core_scale.prototype.initialize.call(this);
12894 },
12895
12896 update: function() {
12897 var me = this;
12898 var options = me.options;
12899 var time = options.time || (options.time = {});
12900
12901 // DEPRECATIONS: output a message only one time per update
12902 if (time.format) {
12903 console.warn('options.time.format is deprecated and replaced by options.time.parser.');
12904 }
12905
12906 // Backward compatibility: before introducing adapter, `displayFormats` was
12907 // supposed to contain *all* unit/string pairs but this can't be resolved
12908 // when loading the scale (adapters are loaded afterward), so let's populate
12909 // missing formats on update
12910 helpers$1.mergeIf(time.displayFormats, adapter.formats());
12911
12912 return core_scale.prototype.update.apply(me, arguments);
12913 },
12914
12915 /**
12916 * Allows data to be referenced via 't' attribute
12917 */
12918 getRightValue: function(rawValue) {
12919 if (rawValue && rawValue.t !== undefined) {
12920 rawValue = rawValue.t;
12921 }
12922 return core_scale.prototype.getRightValue.call(this, rawValue);
12923 },
12924
12925 determineDataLimits: function() {
12926 var me = this;
12927 var chart = me.chart;
12928 var timeOpts = me.options.time;
12929 var unit = timeOpts.unit || 'day';
12930 var min = MAX_INTEGER;
12931 var max = MIN_INTEGER;
12932 var timestamps = [];
12933 var datasets = [];
12934 var labels = [];
12935 var i, j, ilen, jlen, data, timestamp;
12936 var dataLabels = chart.data.labels || [];
12937
12938 // Convert labels to timestamps
12939 for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {
12940 labels.push(parse(dataLabels[i], me));
12941 }
12942
12943 // Convert data to timestamps
12944 for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
12945 if (chart.isDatasetVisible(i)) {
12946 data = chart.data.datasets[i].data;
12947
12948 // Let's consider that all data have the same format.
12949 if (helpers$1.isObject(data[0])) {
12950 datasets[i] = [];
12951
12952 for (j = 0, jlen = data.length; j < jlen; ++j) {
12953 timestamp = parse(data[j], me);
12954 timestamps.push(timestamp);
12955 datasets[i][j] = timestamp;
12956 }
12957 } else {
12958 for (j = 0, jlen = labels.length; j < jlen; ++j) {
12959 timestamps.push(labels[j]);
12960 }
12961 datasets[i] = labels.slice(0);
12962 }
12963 } else {
12964 datasets[i] = [];
12965 }
12966 }
12967
12968 if (labels.length) {
12969 // Sort labels **after** data have been converted
12970 labels = arrayUnique(labels).sort(sorter);
12971 min = Math.min(min, labels[0]);
12972 max = Math.max(max, labels[labels.length - 1]);
12973 }
12974
12975 if (timestamps.length) {
12976 timestamps = arrayUnique(timestamps).sort(sorter);
12977 min = Math.min(min, timestamps[0]);
12978 max = Math.max(max, timestamps[timestamps.length - 1]);
12979 }
12980
12981 min = parse(timeOpts.min, me) || min;
12982 max = parse(timeOpts.max, me) || max;
12983
12984 // In case there is no valid min/max, set limits based on unit time option
12985 min = min === MAX_INTEGER ? +adapter.startOf(+new Date(), unit) : min;
12986 max = max === MIN_INTEGER ? +adapter.endOf(+new Date(), unit) + 1 : max;
12987
12988 // Make sure that max is strictly higher than min (required by the lookup table)
12989 me.min = Math.min(min, max);
12990 me.max = Math.max(min + 1, max);
12991
12992 // PRIVATE
12993 me._horizontal = me.isHorizontal();
12994 me._table = [];
12995 me._timestamps = {
12996 data: timestamps,
12997 datasets: datasets,
12998 labels: labels
12999 };
13000 },
13001
13002 buildTicks: function() {
13003 var me = this;
13004 var min = me.min;
13005 var max = me.max;
13006 var options = me.options;
13007 var timeOpts = options.time;
13008 var timestamps = [];
13009 var ticks = [];
13010 var i, ilen, timestamp;
13011
13012 switch (options.ticks.source) {
13013 case 'data':
13014 timestamps = me._timestamps.data;
13015 break;
13016 case 'labels':
13017 timestamps = me._timestamps.labels;
13018 break;
13019 case 'auto':
13020 default:
13021 timestamps = generate(min, max, me.getLabelCapacity(min), options);
13022 }
13023
13024 if (options.bounds === 'ticks' && timestamps.length) {
13025 min = timestamps[0];
13026 max = timestamps[timestamps.length - 1];
13027 }
13028
13029 // Enforce limits with user min/max options
13030 min = parse(timeOpts.min, me) || min;
13031 max = parse(timeOpts.max, me) || max;
13032
13033 // Remove ticks outside the min/max range
13034 for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
13035 timestamp = timestamps[i];
13036 if (timestamp >= min && timestamp <= max) {
13037 ticks.push(timestamp);
13038 }
13039 }
13040
13041 me.min = min;
13042 me.max = max;
13043
13044 // PRIVATE
13045 me._unit = timeOpts.unit || determineUnitForFormatting(ticks, timeOpts.minUnit, me.min, me.max);
13046 me._majorUnit = determineMajorUnit(me._unit);
13047 me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);
13048 me._offsets = computeOffsets(me._table, ticks, min, max, options);
13049 me._labelFormat = determineLabelFormat(me._timestamps.data);
13050
13051 if (options.ticks.reverse) {
13052 ticks.reverse();
13053 }
13054
13055 return ticksFromTimestamps(ticks, me._majorUnit);
13056 },
13057
13058 getLabelForIndex: function(index, datasetIndex) {
13059 var me = this;
13060 var data = me.chart.data;
13061 var timeOpts = me.options.time;
13062 var label = data.labels && index < data.labels.length ? data.labels[index] : '';
13063 var value = data.datasets[datasetIndex].data[index];
13064
13065 if (helpers$1.isObject(value)) {
13066 label = me.getRightValue(value);
13067 }
13068 if (timeOpts.tooltipFormat) {
13069 return adapter.format(toTimestamp(label, timeOpts), timeOpts.tooltipFormat);
13070 }
13071 if (typeof label === 'string') {
13072 return label;
13073 }
13074
13075 return adapter.format(toTimestamp(label, timeOpts), me._labelFormat);
13076 },
13077
13078 /**
13079 * Function to format an individual tick mark
13080 * @private
13081 */
13082 tickFormatFunction: function(time, index, ticks, format) {
13083 var me = this;
13084 var options = me.options;
13085 var formats = options.time.displayFormats;
13086 var minorFormat = formats[me._unit];
13087 var majorUnit = me._majorUnit;
13088 var majorFormat = formats[majorUnit];
13089 var majorTime = +adapter.startOf(time, majorUnit);
13090 var majorTickOpts = options.ticks.major;
13091 var major = majorTickOpts.enabled && majorUnit && majorFormat && time === majorTime;
13092 var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat);
13093 var tickOpts = major ? majorTickOpts : options.ticks.minor;
13094 var formatter = valueOrDefault$a(tickOpts.callback, tickOpts.userCallback);
13095
13096 return formatter ? formatter(label, index, ticks) : label;
13097 },
13098
13099 convertTicksToLabels: function(ticks) {
13100 var labels = [];
13101 var i, ilen;
13102
13103 for (i = 0, ilen = ticks.length; i < ilen; ++i) {
13104 labels.push(this.tickFormatFunction(ticks[i].value, i, ticks));
13105 }
13106
13107 return labels;
13108 },
13109
13110 /**
13111 * @private
13112 */
13113 getPixelForOffset: function(time) {
13114 var me = this;
13115 var isReverse = me.options.ticks.reverse;
13116 var size = me._horizontal ? me.width : me.height;
13117 var start = me._horizontal ? isReverse ? me.right : me.left : isReverse ? me.bottom : me.top;
13118 var pos = interpolate$1(me._table, 'time', time, 'pos');
13119 var offset = size * (me._offsets.start + pos) / (me._offsets.start + 1 + me._offsets.end);
13120
13121 return isReverse ? start - offset : start + offset;
13122 },
13123
13124 getPixelForValue: function(value, index, datasetIndex) {
13125 var me = this;
13126 var time = null;
13127
13128 if (index !== undefined && datasetIndex !== undefined) {
13129 time = me._timestamps.datasets[datasetIndex][index];
13130 }
13131
13132 if (time === null) {
13133 time = parse(value, me);
13134 }
13135
13136 if (time !== null) {
13137 return me.getPixelForOffset(time);
13138 }
13139 },
13140
13141 getPixelForTick: function(index) {
13142 var ticks = this.getTicks();
13143 return index >= 0 && index < ticks.length ?
13144 this.getPixelForOffset(ticks[index].value) :
13145 null;
13146 },
13147
13148 getValueForPixel: function(pixel) {
13149 var me = this;
13150 var size = me._horizontal ? me.width : me.height;
13151 var start = me._horizontal ? me.left : me.top;
13152 var pos = (size ? (pixel - start) / size : 0) * (me._offsets.start + 1 + me._offsets.start) - me._offsets.end;
13153 var time = interpolate$1(me._table, 'pos', pos, 'time');
13154
13155 // DEPRECATION, we should return time directly
13156 return adapter._create(time);
13157 },
13158
13159 /**
13160 * Crude approximation of what the label width might be
13161 * @private
13162 */
13163 getLabelWidth: function(label) {
13164 var me = this;
13165 var ticksOpts = me.options.ticks;
13166 var tickLabelWidth = me.ctx.measureText(label).width;
13167 var angle = helpers$1.toRadians(ticksOpts.maxRotation);
13168 var cosRotation = Math.cos(angle);
13169 var sinRotation = Math.sin(angle);
13170 var tickFontSize = valueOrDefault$a(ticksOpts.fontSize, core_defaults.global.defaultFontSize);
13171
13172 return (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation);
13173 },
13174
13175 /**
13176 * @private
13177 */
13178 getLabelCapacity: function(exampleTime) {
13179 var me = this;
13180
13181 // pick the longest format (milliseconds) for guestimation
13182 var format = me.options.time.displayFormats.millisecond;
13183 var exampleLabel = me.tickFormatFunction(exampleTime, 0, [], format);
13184 var tickLabelWidth = me.getLabelWidth(exampleLabel);
13185 var innerWidth = me.isHorizontal() ? me.width : me.height;
13186 var capacity = Math.floor(innerWidth / tickLabelWidth);
13187
13188 return capacity > 0 ? capacity : 1;
13189 }
13190});
13191
13192// INTERNAL: static default options, registered in src/chart.js
13193var _defaults$4 = defaultConfig$4;
13194scale_time._defaults = _defaults$4;
13195
13196var scales = {
13197 category: scale_category,
13198 linear: scale_linear,
13199 logarithmic: scale_logarithmic,
13200 radialLinear: scale_radialLinear,
13201 time: scale_time
13202};
13203
13204var adapter$1 = core_adapters._date;
13205
13206
13207var FORMATS = {
13208 millisecond: 'h:mm:ss.SSS a',
13209 second: 'h:mm:ss a',
13210 minute: 'h:mm a',
13211 hour: 'hA',
13212 day: 'MMM D',
13213 week: 'll',
13214 month: 'MMM YYYY',
13215 quarter: '[Q]Q - YYYY',
13216 year: 'YYYY'
13217};
13218
13219var PRESETS = {
13220 full: 'MMM D, YYYY h:mm:ss.SSS a',
13221 time: 'MMM D, YYYY h:mm:ss a',
13222 date: 'MMM D, YYYY'
13223};
13224
13225helpers_core.merge(adapter$1, moment ? {
13226 _id: 'moment', // DEBUG ONLY
13227
13228 formats: function() {
13229 return FORMATS;
13230 },
13231
13232 presets: function() {
13233 return PRESETS;
13234 },
13235
13236 parse: function(value, format) {
13237 if (typeof value === 'string' && typeof format === 'string') {
13238 value = moment(value, format);
13239 } else if (!(value instanceof moment)) {
13240 value = moment(value);
13241 }
13242 return value.isValid() ? +value : null;
13243 },
13244
13245 format: function(time, format) {
13246 return moment(time).format(format);
13247 },
13248
13249 add: function(time, amount, unit) {
13250 return +moment(time).add(amount, unit);
13251 },
13252
13253 diff: function(max, min, unit) {
13254 return moment.duration(moment(max).diff(moment(min))).as(unit);
13255 },
13256
13257 startOf: function(time, unit, weekday) {
13258 time = moment(time);
13259 if (unit === 'isoWeek') {
13260 return +time.isoWeekday(weekday);
13261 }
13262 return +time.startOf(unit);
13263 },
13264
13265 endOf: function(time, unit) {
13266 return +moment(time).endOf(unit);
13267 },
13268
13269 // DEPRECATIONS
13270
13271 /**
13272 * Provided for backward compatibility with scale.getValueForPixel().
13273 * @deprecated since version 2.8.0
13274 * @todo remove at version 3
13275 * @private
13276 */
13277 _create: function(time) {
13278 return moment(time);
13279 },
13280} : {});
13281
13282core_defaults._set('global', {
13283 plugins: {
13284 filler: {
13285 propagate: true
13286 }
13287 }
13288});
13289
13290var mappers = {
13291 dataset: function(source) {
13292 var index = source.fill;
13293 var chart = source.chart;
13294 var meta = chart.getDatasetMeta(index);
13295 var visible = meta && chart.isDatasetVisible(index);
13296 var points = (visible && meta.dataset._children) || [];
13297 var length = points.length || 0;
13298
13299 return !length ? null : function(point, i) {
13300 return (i < length && points[i]._view) || null;
13301 };
13302 },
13303
13304 boundary: function(source) {
13305 var boundary = source.boundary;
13306 var x = boundary ? boundary.x : null;
13307 var y = boundary ? boundary.y : null;
13308
13309 return function(point) {
13310 return {
13311 x: x === null ? point.x : x,
13312 y: y === null ? point.y : y,
13313 };
13314 };
13315 }
13316};
13317
13318// @todo if (fill[0] === '#')
13319function decodeFill(el, index, count) {
13320 var model = el._model || {};
13321 var fill = model.fill;
13322 var target;
13323
13324 if (fill === undefined) {
13325 fill = !!model.backgroundColor;
13326 }
13327
13328 if (fill === false || fill === null) {
13329 return false;
13330 }
13331
13332 if (fill === true) {
13333 return 'origin';
13334 }
13335
13336 target = parseFloat(fill, 10);
13337 if (isFinite(target) && Math.floor(target) === target) {
13338 if (fill[0] === '-' || fill[0] === '+') {
13339 target = index + target;
13340 }
13341
13342 if (target === index || target < 0 || target >= count) {
13343 return false;
13344 }
13345
13346 return target;
13347 }
13348
13349 switch (fill) {
13350 // compatibility
13351 case 'bottom':
13352 return 'start';
13353 case 'top':
13354 return 'end';
13355 case 'zero':
13356 return 'origin';
13357 // supported boundaries
13358 case 'origin':
13359 case 'start':
13360 case 'end':
13361 return fill;
13362 // invalid fill values
13363 default:
13364 return false;
13365 }
13366}
13367
13368function computeBoundary(source) {
13369 var model = source.el._model || {};
13370 var scale = source.el._scale || {};
13371 var fill = source.fill;
13372 var target = null;
13373 var horizontal;
13374
13375 if (isFinite(fill)) {
13376 return null;
13377 }
13378
13379 // Backward compatibility: until v3, we still need to support boundary values set on
13380 // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
13381 // controllers might still use it (e.g. the Smith chart).
13382
13383 if (fill === 'start') {
13384 target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
13385 } else if (fill === 'end') {
13386 target = model.scaleTop === undefined ? scale.top : model.scaleTop;
13387 } else if (model.scaleZero !== undefined) {
13388 target = model.scaleZero;
13389 } else if (scale.getBasePosition) {
13390 target = scale.getBasePosition();
13391 } else if (scale.getBasePixel) {
13392 target = scale.getBasePixel();
13393 }
13394
13395 if (target !== undefined && target !== null) {
13396 if (target.x !== undefined && target.y !== undefined) {
13397 return target;
13398 }
13399
13400 if (helpers$1.isFinite(target)) {
13401 horizontal = scale.isHorizontal();
13402 return {
13403 x: horizontal ? target : null,
13404 y: horizontal ? null : target
13405 };
13406 }
13407 }
13408
13409 return null;
13410}
13411
13412function resolveTarget(sources, index, propagate) {
13413 var source = sources[index];
13414 var fill = source.fill;
13415 var visited = [index];
13416 var target;
13417
13418 if (!propagate) {
13419 return fill;
13420 }
13421
13422 while (fill !== false && visited.indexOf(fill) === -1) {
13423 if (!isFinite(fill)) {
13424 return fill;
13425 }
13426
13427 target = sources[fill];
13428 if (!target) {
13429 return false;
13430 }
13431
13432 if (target.visible) {
13433 return fill;
13434 }
13435
13436 visited.push(fill);
13437 fill = target.fill;
13438 }
13439
13440 return false;
13441}
13442
13443function createMapper(source) {
13444 var fill = source.fill;
13445 var type = 'dataset';
13446
13447 if (fill === false) {
13448 return null;
13449 }
13450
13451 if (!isFinite(fill)) {
13452 type = 'boundary';
13453 }
13454
13455 return mappers[type](source);
13456}
13457
13458function isDrawable(point) {
13459 return point && !point.skip;
13460}
13461
13462function drawArea(ctx, curve0, curve1, len0, len1) {
13463 var i;
13464
13465 if (!len0 || !len1) {
13466 return;
13467 }
13468
13469 // building first area curve (normal)
13470 ctx.moveTo(curve0[0].x, curve0[0].y);
13471 for (i = 1; i < len0; ++i) {
13472 helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
13473 }
13474
13475 // joining the two area curves
13476 ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
13477
13478 // building opposite area curve (reverse)
13479 for (i = len1 - 1; i > 0; --i) {
13480 helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
13481 }
13482}
13483
13484function doFill(ctx, points, mapper, view, color, loop) {
13485 var count = points.length;
13486 var span = view.spanGaps;
13487 var curve0 = [];
13488 var curve1 = [];
13489 var len0 = 0;
13490 var len1 = 0;
13491 var i, ilen, index, p0, p1, d0, d1;
13492
13493 ctx.beginPath();
13494
13495 for (i = 0, ilen = (count + !!loop); i < ilen; ++i) {
13496 index = i % count;
13497 p0 = points[index]._view;
13498 p1 = mapper(p0, index, view);
13499 d0 = isDrawable(p0);
13500 d1 = isDrawable(p1);
13501
13502 if (d0 && d1) {
13503 len0 = curve0.push(p0);
13504 len1 = curve1.push(p1);
13505 } else if (len0 && len1) {
13506 if (!span) {
13507 drawArea(ctx, curve0, curve1, len0, len1);
13508 len0 = len1 = 0;
13509 curve0 = [];
13510 curve1 = [];
13511 } else {
13512 if (d0) {
13513 curve0.push(p0);
13514 }
13515 if (d1) {
13516 curve1.push(p1);
13517 }
13518 }
13519 }
13520 }
13521
13522 drawArea(ctx, curve0, curve1, len0, len1);
13523
13524 ctx.closePath();
13525 ctx.fillStyle = color;
13526 ctx.fill();
13527}
13528
13529var plugin_filler = {
13530 id: 'filler',
13531
13532 afterDatasetsUpdate: function(chart, options) {
13533 var count = (chart.data.datasets || []).length;
13534 var propagate = options.propagate;
13535 var sources = [];
13536 var meta, i, el, source;
13537
13538 for (i = 0; i < count; ++i) {
13539 meta = chart.getDatasetMeta(i);
13540 el = meta.dataset;
13541 source = null;
13542
13543 if (el && el._model && el instanceof elements.Line) {
13544 source = {
13545 visible: chart.isDatasetVisible(i),
13546 fill: decodeFill(el, i, count),
13547 chart: chart,
13548 el: el
13549 };
13550 }
13551
13552 meta.$filler = source;
13553 sources.push(source);
13554 }
13555
13556 for (i = 0; i < count; ++i) {
13557 source = sources[i];
13558 if (!source) {
13559 continue;
13560 }
13561
13562 source.fill = resolveTarget(sources, i, propagate);
13563 source.boundary = computeBoundary(source);
13564 source.mapper = createMapper(source);
13565 }
13566 },
13567
13568 beforeDatasetDraw: function(chart, args) {
13569 var meta = args.meta.$filler;
13570 if (!meta) {
13571 return;
13572 }
13573
13574 var ctx = chart.ctx;
13575 var el = meta.el;
13576 var view = el._view;
13577 var points = el._children || [];
13578 var mapper = meta.mapper;
13579 var color = view.backgroundColor || core_defaults.global.defaultColor;
13580
13581 if (mapper && color && points.length) {
13582 helpers$1.canvas.clipArea(ctx, chart.chartArea);
13583 doFill(ctx, points, mapper, view, color, el._loop);
13584 helpers$1.canvas.unclipArea(ctx);
13585 }
13586 }
13587};
13588
13589var noop$1 = helpers$1.noop;
13590var valueOrDefault$b = helpers$1.valueOrDefault;
13591
13592core_defaults._set('global', {
13593 legend: {
13594 display: true,
13595 position: 'top',
13596 fullWidth: true,
13597 reverse: false,
13598 weight: 1000,
13599
13600 // a callback that will handle
13601 onClick: function(e, legendItem) {
13602 var index = legendItem.datasetIndex;
13603 var ci = this.chart;
13604 var meta = ci.getDatasetMeta(index);
13605
13606 // See controller.isDatasetVisible comment
13607 meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
13608
13609 // We hid a dataset ... rerender the chart
13610 ci.update();
13611 },
13612
13613 onHover: null,
13614
13615 labels: {
13616 boxWidth: 40,
13617 padding: 10,
13618 // Generates labels shown in the legend
13619 // Valid properties to return:
13620 // text : text to display
13621 // fillStyle : fill of coloured box
13622 // strokeStyle: stroke of coloured box
13623 // hidden : if this legend item refers to a hidden item
13624 // lineCap : cap style for line
13625 // lineDash
13626 // lineDashOffset :
13627 // lineJoin :
13628 // lineWidth :
13629 generateLabels: function(chart) {
13630 var data = chart.data;
13631 return helpers$1.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {
13632 return {
13633 text: dataset.label,
13634 fillStyle: (!helpers$1.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
13635 hidden: !chart.isDatasetVisible(i),
13636 lineCap: dataset.borderCapStyle,
13637 lineDash: dataset.borderDash,
13638 lineDashOffset: dataset.borderDashOffset,
13639 lineJoin: dataset.borderJoinStyle,
13640 lineWidth: dataset.borderWidth,
13641 strokeStyle: dataset.borderColor,
13642 pointStyle: dataset.pointStyle,
13643
13644 // Below is extra data used for toggling the datasets
13645 datasetIndex: i
13646 };
13647 }, this) : [];
13648 }
13649 }
13650 },
13651
13652 legendCallback: function(chart) {
13653 var text = [];
13654 text.push('<ul class="' + chart.id + '-legend">');
13655 for (var i = 0; i < chart.data.datasets.length; i++) {
13656 text.push('<li><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"></span>');
13657 if (chart.data.datasets[i].label) {
13658 text.push(chart.data.datasets[i].label);
13659 }
13660 text.push('</li>');
13661 }
13662 text.push('</ul>');
13663 return text.join('');
13664 }
13665});
13666
13667/**
13668 * Helper function to get the box width based on the usePointStyle option
13669 * @param labelopts {Object} the label options on the legend
13670 * @param fontSize {Number} the label font size
13671 * @return {Number} width of the color box area
13672 */
13673function getBoxWidth(labelOpts, fontSize) {
13674 return labelOpts.usePointStyle ?
13675 fontSize * Math.SQRT2 :
13676 labelOpts.boxWidth;
13677}
13678
13679/**
13680 * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
13681 */
13682var Legend = core_element.extend({
13683
13684 initialize: function(config) {
13685 helpers$1.extend(this, config);
13686
13687 // Contains hit boxes for each dataset (in dataset order)
13688 this.legendHitBoxes = [];
13689
13690 // Are we in doughnut mode which has a different data type
13691 this.doughnutMode = false;
13692 },
13693
13694 // These methods are ordered by lifecycle. Utilities then follow.
13695 // Any function defined here is inherited by all legend types.
13696 // Any function can be extended by the legend type
13697
13698 beforeUpdate: noop$1,
13699 update: function(maxWidth, maxHeight, margins) {
13700 var me = this;
13701
13702 // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
13703 me.beforeUpdate();
13704
13705 // Absorb the master measurements
13706 me.maxWidth = maxWidth;
13707 me.maxHeight = maxHeight;
13708 me.margins = margins;
13709
13710 // Dimensions
13711 me.beforeSetDimensions();
13712 me.setDimensions();
13713 me.afterSetDimensions();
13714 // Labels
13715 me.beforeBuildLabels();
13716 me.buildLabels();
13717 me.afterBuildLabels();
13718
13719 // Fit
13720 me.beforeFit();
13721 me.fit();
13722 me.afterFit();
13723 //
13724 me.afterUpdate();
13725
13726 return me.minSize;
13727 },
13728 afterUpdate: noop$1,
13729
13730 //
13731
13732 beforeSetDimensions: noop$1,
13733 setDimensions: function() {
13734 var me = this;
13735 // Set the unconstrained dimension before label rotation
13736 if (me.isHorizontal()) {
13737 // Reset position before calculating rotation
13738 me.width = me.maxWidth;
13739 me.left = 0;
13740 me.right = me.width;
13741 } else {
13742 me.height = me.maxHeight;
13743
13744 // Reset position before calculating rotation
13745 me.top = 0;
13746 me.bottom = me.height;
13747 }
13748
13749 // Reset padding
13750 me.paddingLeft = 0;
13751 me.paddingTop = 0;
13752 me.paddingRight = 0;
13753 me.paddingBottom = 0;
13754
13755 // Reset minSize
13756 me.minSize = {
13757 width: 0,
13758 height: 0
13759 };
13760 },
13761 afterSetDimensions: noop$1,
13762
13763 //
13764
13765 beforeBuildLabels: noop$1,
13766 buildLabels: function() {
13767 var me = this;
13768 var labelOpts = me.options.labels || {};
13769 var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];
13770
13771 if (labelOpts.filter) {
13772 legendItems = legendItems.filter(function(item) {
13773 return labelOpts.filter(item, me.chart.data);
13774 });
13775 }
13776
13777 if (me.options.reverse) {
13778 legendItems.reverse();
13779 }
13780
13781 me.legendItems = legendItems;
13782 },
13783 afterBuildLabels: noop$1,
13784
13785 //
13786
13787 beforeFit: noop$1,
13788 fit: function() {
13789 var me = this;
13790 var opts = me.options;
13791 var labelOpts = opts.labels;
13792 var display = opts.display;
13793
13794 var ctx = me.ctx;
13795
13796 var labelFont = helpers$1.options._parseFont(labelOpts);
13797 var fontSize = labelFont.size;
13798
13799 // Reset hit boxes
13800 var hitboxes = me.legendHitBoxes = [];
13801
13802 var minSize = me.minSize;
13803 var isHorizontal = me.isHorizontal();
13804
13805 if (isHorizontal) {
13806 minSize.width = me.maxWidth; // fill all the width
13807 minSize.height = display ? 10 : 0;
13808 } else {
13809 minSize.width = display ? 10 : 0;
13810 minSize.height = me.maxHeight; // fill all the height
13811 }
13812
13813 // Increase sizes here
13814 if (display) {
13815 ctx.font = labelFont.string;
13816
13817 if (isHorizontal) {
13818 // Labels
13819
13820 // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
13821 var lineWidths = me.lineWidths = [0];
13822 var totalHeight = 0;
13823
13824 ctx.textAlign = 'left';
13825 ctx.textBaseline = 'top';
13826
13827 helpers$1.each(me.legendItems, function(legendItem, i) {
13828 var boxWidth = getBoxWidth(labelOpts, fontSize);
13829 var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
13830
13831 if (i === 0 || lineWidths[lineWidths.length - 1] + width + labelOpts.padding > minSize.width) {
13832 totalHeight += fontSize + labelOpts.padding;
13833 lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = labelOpts.padding;
13834 }
13835
13836 // Store the hitbox width and height here. Final position will be updated in `draw`
13837 hitboxes[i] = {
13838 left: 0,
13839 top: 0,
13840 width: width,
13841 height: fontSize
13842 };
13843
13844 lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
13845 });
13846
13847 minSize.height += totalHeight;
13848
13849 } else {
13850 var vPadding = labelOpts.padding;
13851 var columnWidths = me.columnWidths = [];
13852 var totalWidth = labelOpts.padding;
13853 var currentColWidth = 0;
13854 var currentColHeight = 0;
13855 var itemHeight = fontSize + vPadding;
13856
13857 helpers$1.each(me.legendItems, function(legendItem, i) {
13858 var boxWidth = getBoxWidth(labelOpts, fontSize);
13859 var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
13860
13861 // If too tall, go to new column
13862 if (i > 0 && currentColHeight + itemHeight > minSize.height - vPadding) {
13863 totalWidth += currentColWidth + labelOpts.padding;
13864 columnWidths.push(currentColWidth); // previous column width
13865
13866 currentColWidth = 0;
13867 currentColHeight = 0;
13868 }
13869
13870 // Get max width
13871 currentColWidth = Math.max(currentColWidth, itemWidth);
13872 currentColHeight += itemHeight;
13873
13874 // Store the hitbox width and height here. Final position will be updated in `draw`
13875 hitboxes[i] = {
13876 left: 0,
13877 top: 0,
13878 width: itemWidth,
13879 height: fontSize
13880 };
13881 });
13882
13883 totalWidth += currentColWidth;
13884 columnWidths.push(currentColWidth);
13885 minSize.width += totalWidth;
13886 }
13887 }
13888
13889 me.width = minSize.width;
13890 me.height = minSize.height;
13891 },
13892 afterFit: noop$1,
13893
13894 // Shared Methods
13895 isHorizontal: function() {
13896 return this.options.position === 'top' || this.options.position === 'bottom';
13897 },
13898
13899 // Actually draw the legend on the canvas
13900 draw: function() {
13901 var me = this;
13902 var opts = me.options;
13903 var labelOpts = opts.labels;
13904 var globalDefaults = core_defaults.global;
13905 var defaultColor = globalDefaults.defaultColor;
13906 var lineDefault = globalDefaults.elements.line;
13907 var legendWidth = me.width;
13908 var lineWidths = me.lineWidths;
13909
13910 if (opts.display) {
13911 var ctx = me.ctx;
13912 var fontColor = valueOrDefault$b(labelOpts.fontColor, globalDefaults.defaultFontColor);
13913 var labelFont = helpers$1.options._parseFont(labelOpts);
13914 var fontSize = labelFont.size;
13915 var cursor;
13916
13917 // Canvas setup
13918 ctx.textAlign = 'left';
13919 ctx.textBaseline = 'middle';
13920 ctx.lineWidth = 0.5;
13921 ctx.strokeStyle = fontColor; // for strikethrough effect
13922 ctx.fillStyle = fontColor; // render in correct colour
13923 ctx.font = labelFont.string;
13924
13925 var boxWidth = getBoxWidth(labelOpts, fontSize);
13926 var hitboxes = me.legendHitBoxes;
13927
13928 // current position
13929 var drawLegendBox = function(x, y, legendItem) {
13930 if (isNaN(boxWidth) || boxWidth <= 0) {
13931 return;
13932 }
13933
13934 // Set the ctx for the box
13935 ctx.save();
13936
13937 var lineWidth = valueOrDefault$b(legendItem.lineWidth, lineDefault.borderWidth);
13938 ctx.fillStyle = valueOrDefault$b(legendItem.fillStyle, defaultColor);
13939 ctx.lineCap = valueOrDefault$b(legendItem.lineCap, lineDefault.borderCapStyle);
13940 ctx.lineDashOffset = valueOrDefault$b(legendItem.lineDashOffset, lineDefault.borderDashOffset);
13941 ctx.lineJoin = valueOrDefault$b(legendItem.lineJoin, lineDefault.borderJoinStyle);
13942 ctx.lineWidth = lineWidth;
13943 ctx.strokeStyle = valueOrDefault$b(legendItem.strokeStyle, defaultColor);
13944
13945 if (ctx.setLineDash) {
13946 // IE 9 and 10 do not support line dash
13947 ctx.setLineDash(valueOrDefault$b(legendItem.lineDash, lineDefault.borderDash));
13948 }
13949
13950 if (opts.labels && opts.labels.usePointStyle) {
13951 // Recalculate x and y for drawPoint() because its expecting
13952 // x and y to be center of figure (instead of top left)
13953 var radius = fontSize * Math.SQRT2 / 2;
13954 var offSet = radius / Math.SQRT2;
13955 var centerX = x + offSet;
13956 var centerY = y + offSet;
13957
13958 // Draw pointStyle as legend symbol
13959 helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY);
13960 } else {
13961 // Draw box as legend symbol
13962 if (lineWidth !== 0) {
13963 ctx.strokeRect(x, y, boxWidth, fontSize);
13964 }
13965 ctx.fillRect(x, y, boxWidth, fontSize);
13966 }
13967
13968 ctx.restore();
13969 };
13970 var fillText = function(x, y, legendItem, textWidth) {
13971 var halfFontSize = fontSize / 2;
13972 var xLeft = boxWidth + halfFontSize + x;
13973 var yMiddle = y + halfFontSize;
13974
13975 ctx.fillText(legendItem.text, xLeft, yMiddle);
13976
13977 if (legendItem.hidden) {
13978 // Strikethrough the text if hidden
13979 ctx.beginPath();
13980 ctx.lineWidth = 2;
13981 ctx.moveTo(xLeft, yMiddle);
13982 ctx.lineTo(xLeft + textWidth, yMiddle);
13983 ctx.stroke();
13984 }
13985 };
13986
13987 // Horizontal
13988 var isHorizontal = me.isHorizontal();
13989 if (isHorizontal) {
13990 cursor = {
13991 x: me.left + ((legendWidth - lineWidths[0]) / 2) + labelOpts.padding,
13992 y: me.top + labelOpts.padding,
13993 line: 0
13994 };
13995 } else {
13996 cursor = {
13997 x: me.left + labelOpts.padding,
13998 y: me.top + labelOpts.padding,
13999 line: 0
14000 };
14001 }
14002
14003 var itemHeight = fontSize + labelOpts.padding;
14004 helpers$1.each(me.legendItems, function(legendItem, i) {
14005 var textWidth = ctx.measureText(legendItem.text).width;
14006 var width = boxWidth + (fontSize / 2) + textWidth;
14007 var x = cursor.x;
14008 var y = cursor.y;
14009
14010 // Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
14011 // instead of me.right and me.bottom because me.width and me.height
14012 // may have been changed since me.minSize was calculated
14013 if (isHorizontal) {
14014 if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
14015 y = cursor.y += itemHeight;
14016 cursor.line++;
14017 x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2) + labelOpts.padding;
14018 }
14019 } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {
14020 x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
14021 y = cursor.y = me.top + labelOpts.padding;
14022 cursor.line++;
14023 }
14024
14025 drawLegendBox(x, y, legendItem);
14026
14027 hitboxes[i].left = x;
14028 hitboxes[i].top = y;
14029
14030 // Fill the actual label
14031 fillText(x, y, legendItem, textWidth);
14032
14033 if (isHorizontal) {
14034 cursor.x += width + labelOpts.padding;
14035 } else {
14036 cursor.y += itemHeight;
14037 }
14038
14039 });
14040 }
14041 },
14042
14043 /**
14044 * Handle an event
14045 * @private
14046 * @param {IEvent} event - The event to handle
14047 * @return {Boolean} true if a change occured
14048 */
14049 handleEvent: function(e) {
14050 var me = this;
14051 var opts = me.options;
14052 var type = e.type === 'mouseup' ? 'click' : e.type;
14053 var changed = false;
14054
14055 if (type === 'mousemove') {
14056 if (!opts.onHover) {
14057 return;
14058 }
14059 } else if (type === 'click') {
14060 if (!opts.onClick) {
14061 return;
14062 }
14063 } else {
14064 return;
14065 }
14066
14067 // Chart event already has relative position in it
14068 var x = e.x;
14069 var y = e.y;
14070
14071 if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
14072 // See if we are touching one of the dataset boxes
14073 var lh = me.legendHitBoxes;
14074 for (var i = 0; i < lh.length; ++i) {
14075 var hitBox = lh[i];
14076
14077 if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
14078 // Touching an element
14079 if (type === 'click') {
14080 // use e.native for backwards compatibility
14081 opts.onClick.call(me, e.native, me.legendItems[i]);
14082 changed = true;
14083 break;
14084 } else if (type === 'mousemove') {
14085 // use e.native for backwards compatibility
14086 opts.onHover.call(me, e.native, me.legendItems[i]);
14087 changed = true;
14088 break;
14089 }
14090 }
14091 }
14092 }
14093
14094 return changed;
14095 }
14096});
14097
14098function createNewLegendAndAttach(chart, legendOpts) {
14099 var legend = new Legend({
14100 ctx: chart.ctx,
14101 options: legendOpts,
14102 chart: chart
14103 });
14104
14105 core_layouts.configure(chart, legend, legendOpts);
14106 core_layouts.addBox(chart, legend);
14107 chart.legend = legend;
14108}
14109
14110var plugin_legend = {
14111 id: 'legend',
14112
14113 /**
14114 * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
14115 * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
14116 * the plugin, which one will be re-exposed in the chart.js file.
14117 * https://github.com/chartjs/Chart.js/pull/2640
14118 * @private
14119 */
14120 _element: Legend,
14121
14122 beforeInit: function(chart) {
14123 var legendOpts = chart.options.legend;
14124
14125 if (legendOpts) {
14126 createNewLegendAndAttach(chart, legendOpts);
14127 }
14128 },
14129
14130 beforeUpdate: function(chart) {
14131 var legendOpts = chart.options.legend;
14132 var legend = chart.legend;
14133
14134 if (legendOpts) {
14135 helpers$1.mergeIf(legendOpts, core_defaults.global.legend);
14136
14137 if (legend) {
14138 core_layouts.configure(chart, legend, legendOpts);
14139 legend.options = legendOpts;
14140 } else {
14141 createNewLegendAndAttach(chart, legendOpts);
14142 }
14143 } else if (legend) {
14144 core_layouts.removeBox(chart, legend);
14145 delete chart.legend;
14146 }
14147 },
14148
14149 afterEvent: function(chart, e) {
14150 var legend = chart.legend;
14151 if (legend) {
14152 legend.handleEvent(e);
14153 }
14154 }
14155};
14156
14157var noop$2 = helpers$1.noop;
14158
14159core_defaults._set('global', {
14160 title: {
14161 display: false,
14162 fontStyle: 'bold',
14163 fullWidth: true,
14164 padding: 10,
14165 position: 'top',
14166 text: '',
14167 weight: 2000 // by default greater than legend (1000) to be above
14168 }
14169});
14170
14171/**
14172 * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
14173 */
14174var Title = core_element.extend({
14175 initialize: function(config) {
14176 var me = this;
14177 helpers$1.extend(me, config);
14178
14179 // Contains hit boxes for each dataset (in dataset order)
14180 me.legendHitBoxes = [];
14181 },
14182
14183 // These methods are ordered by lifecycle. Utilities then follow.
14184
14185 beforeUpdate: noop$2,
14186 update: function(maxWidth, maxHeight, margins) {
14187 var me = this;
14188
14189 // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
14190 me.beforeUpdate();
14191
14192 // Absorb the master measurements
14193 me.maxWidth = maxWidth;
14194 me.maxHeight = maxHeight;
14195 me.margins = margins;
14196
14197 // Dimensions
14198 me.beforeSetDimensions();
14199 me.setDimensions();
14200 me.afterSetDimensions();
14201 // Labels
14202 me.beforeBuildLabels();
14203 me.buildLabels();
14204 me.afterBuildLabels();
14205
14206 // Fit
14207 me.beforeFit();
14208 me.fit();
14209 me.afterFit();
14210 //
14211 me.afterUpdate();
14212
14213 return me.minSize;
14214
14215 },
14216 afterUpdate: noop$2,
14217
14218 //
14219
14220 beforeSetDimensions: noop$2,
14221 setDimensions: function() {
14222 var me = this;
14223 // Set the unconstrained dimension before label rotation
14224 if (me.isHorizontal()) {
14225 // Reset position before calculating rotation
14226 me.width = me.maxWidth;
14227 me.left = 0;
14228 me.right = me.width;
14229 } else {
14230 me.height = me.maxHeight;
14231
14232 // Reset position before calculating rotation
14233 me.top = 0;
14234 me.bottom = me.height;
14235 }
14236
14237 // Reset padding
14238 me.paddingLeft = 0;
14239 me.paddingTop = 0;
14240 me.paddingRight = 0;
14241 me.paddingBottom = 0;
14242
14243 // Reset minSize
14244 me.minSize = {
14245 width: 0,
14246 height: 0
14247 };
14248 },
14249 afterSetDimensions: noop$2,
14250
14251 //
14252
14253 beforeBuildLabels: noop$2,
14254 buildLabels: noop$2,
14255 afterBuildLabels: noop$2,
14256
14257 //
14258
14259 beforeFit: noop$2,
14260 fit: function() {
14261 var me = this;
14262 var opts = me.options;
14263 var display = opts.display;
14264 var minSize = me.minSize;
14265 var lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;
14266 var fontOpts = helpers$1.options._parseFont(opts);
14267 var textSize = display ? (lineCount * fontOpts.lineHeight) + (opts.padding * 2) : 0;
14268
14269 if (me.isHorizontal()) {
14270 minSize.width = me.maxWidth; // fill all the width
14271 minSize.height = textSize;
14272 } else {
14273 minSize.width = textSize;
14274 minSize.height = me.maxHeight; // fill all the height
14275 }
14276
14277 me.width = minSize.width;
14278 me.height = minSize.height;
14279
14280 },
14281 afterFit: noop$2,
14282
14283 // Shared Methods
14284 isHorizontal: function() {
14285 var pos = this.options.position;
14286 return pos === 'top' || pos === 'bottom';
14287 },
14288
14289 // Actually draw the title block on the canvas
14290 draw: function() {
14291 var me = this;
14292 var ctx = me.ctx;
14293 var opts = me.options;
14294
14295 if (opts.display) {
14296 var fontOpts = helpers$1.options._parseFont(opts);
14297 var lineHeight = fontOpts.lineHeight;
14298 var offset = lineHeight / 2 + opts.padding;
14299 var rotation = 0;
14300 var top = me.top;
14301 var left = me.left;
14302 var bottom = me.bottom;
14303 var right = me.right;
14304 var maxWidth, titleX, titleY;
14305
14306 ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour
14307 ctx.font = fontOpts.string;
14308
14309 // Horizontal
14310 if (me.isHorizontal()) {
14311 titleX = left + ((right - left) / 2); // midpoint of the width
14312 titleY = top + offset;
14313 maxWidth = right - left;
14314 } else {
14315 titleX = opts.position === 'left' ? left + offset : right - offset;
14316 titleY = top + ((bottom - top) / 2);
14317 maxWidth = bottom - top;
14318 rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
14319 }
14320
14321 ctx.save();
14322 ctx.translate(titleX, titleY);
14323 ctx.rotate(rotation);
14324 ctx.textAlign = 'center';
14325 ctx.textBaseline = 'middle';
14326
14327 var text = opts.text;
14328 if (helpers$1.isArray(text)) {
14329 var y = 0;
14330 for (var i = 0; i < text.length; ++i) {
14331 ctx.fillText(text[i], 0, y, maxWidth);
14332 y += lineHeight;
14333 }
14334 } else {
14335 ctx.fillText(text, 0, 0, maxWidth);
14336 }
14337
14338 ctx.restore();
14339 }
14340 }
14341});
14342
14343function createNewTitleBlockAndAttach(chart, titleOpts) {
14344 var title = new Title({
14345 ctx: chart.ctx,
14346 options: titleOpts,
14347 chart: chart
14348 });
14349
14350 core_layouts.configure(chart, title, titleOpts);
14351 core_layouts.addBox(chart, title);
14352 chart.titleBlock = title;
14353}
14354
14355var plugin_title = {
14356 id: 'title',
14357
14358 /**
14359 * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
14360 * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
14361 * the plugin, which one will be re-exposed in the chart.js file.
14362 * https://github.com/chartjs/Chart.js/pull/2640
14363 * @private
14364 */
14365 _element: Title,
14366
14367 beforeInit: function(chart) {
14368 var titleOpts = chart.options.title;
14369
14370 if (titleOpts) {
14371 createNewTitleBlockAndAttach(chart, titleOpts);
14372 }
14373 },
14374
14375 beforeUpdate: function(chart) {
14376 var titleOpts = chart.options.title;
14377 var titleBlock = chart.titleBlock;
14378
14379 if (titleOpts) {
14380 helpers$1.mergeIf(titleOpts, core_defaults.global.title);
14381
14382 if (titleBlock) {
14383 core_layouts.configure(chart, titleBlock, titleOpts);
14384 titleBlock.options = titleOpts;
14385 } else {
14386 createNewTitleBlockAndAttach(chart, titleOpts);
14387 }
14388 } else if (titleBlock) {
14389 core_layouts.removeBox(chart, titleBlock);
14390 delete chart.titleBlock;
14391 }
14392 }
14393};
14394
14395var plugins = {};
14396var filler = plugin_filler;
14397var legend = plugin_legend;
14398var title = plugin_title;
14399plugins.filler = filler;
14400plugins.legend = legend;
14401plugins.title = title;
14402
14403/**
14404 * @namespace Chart
14405 */
14406
14407
14408core_controller.helpers = helpers$1;
14409
14410// @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
14411core_helpers(core_controller);
14412
14413core_controller._adapters = core_adapters;
14414core_controller.Animation = core_animation;
14415core_controller.animationService = core_animations;
14416core_controller.controllers = controllers;
14417core_controller.DatasetController = core_datasetController;
14418core_controller.defaults = core_defaults;
14419core_controller.Element = core_element;
14420core_controller.elements = elements;
14421core_controller.Interaction = core_interaction;
14422core_controller.layouts = core_layouts;
14423core_controller.platform = platform;
14424core_controller.plugins = core_plugins;
14425core_controller.Scale = core_scale;
14426core_controller.scaleService = core_scaleService;
14427core_controller.Ticks = core_ticks;
14428core_controller.Tooltip = core_tooltip;
14429
14430// Register built-in scales
14431
14432core_controller.helpers.each(scales, function(scale, type) {
14433 core_controller.scaleService.registerScaleType(type, scale, scale._defaults);
14434});
14435
14436// Load to register built-in adapters (as side effects)
14437
14438
14439// Loading built-in plugins
14440
14441for (var k in plugins) {
14442 if (plugins.hasOwnProperty(k)) {
14443 core_controller.plugins.register(plugins[k]);
14444 }
14445}
14446
14447core_controller.platform.initialize();
14448
14449var chart = core_controller;
14450if (typeof window !== 'undefined') {
14451 window.Chart = core_controller;
14452}
14453
14454// DEPRECATIONS
14455
14456/**
14457 * Provided for backward compatibility, not available anymore
14458 * @namespace Chart.Legend
14459 * @deprecated since version 2.1.5
14460 * @todo remove at version 3
14461 * @private
14462 */
14463core_controller.Legend = plugins.legend._element;
14464
14465/**
14466 * Provided for backward compatibility, not available anymore
14467 * @namespace Chart.Title
14468 * @deprecated since version 2.1.5
14469 * @todo remove at version 3
14470 * @private
14471 */
14472core_controller.Title = plugins.title._element;
14473
14474/**
14475 * Provided for backward compatibility, use Chart.plugins instead
14476 * @namespace Chart.pluginService
14477 * @deprecated since version 2.1.5
14478 * @todo remove at version 3
14479 * @private
14480 */
14481core_controller.pluginService = core_controller.plugins;
14482
14483/**
14484 * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
14485 * effect, instead simply create/register plugins via plain JavaScript objects.
14486 * @interface Chart.PluginBase
14487 * @deprecated since version 2.5.0
14488 * @todo remove at version 3
14489 * @private
14490 */
14491core_controller.PluginBase = core_controller.Element.extend({});
14492
14493/**
14494 * Provided for backward compatibility, use Chart.helpers.canvas instead.
14495 * @namespace Chart.canvasHelpers
14496 * @deprecated since version 2.6.0
14497 * @todo remove at version 3
14498 * @private
14499 */
14500core_controller.canvasHelpers = core_controller.helpers.canvas;
14501
14502/**
14503 * Provided for backward compatibility, use Chart.layouts instead.
14504 * @namespace Chart.layoutService
14505 * @deprecated since version 2.7.3
14506 * @todo remove at version 3
14507 * @private
14508 */
14509core_controller.layoutService = core_controller.layouts;
14510
14511/**
14512 * Provided for backward compatibility, not available anymore.
14513 * @namespace Chart.LinearScaleBase
14514 * @deprecated since version 2.8
14515 * @todo remove at version 3
14516 * @private
14517 */
14518core_controller.LinearScaleBase = scale_linearbase;
14519
14520/**
14521 * Provided for backward compatibility, instead we should create a new Chart
14522 * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`).
14523 * @deprecated since version 2.8.0
14524 * @todo remove at version 3
14525 */
14526core_controller.helpers.each(
14527 [
14528 'Bar',
14529 'Bubble',
14530 'Doughnut',
14531 'Line',
14532 'PolarArea',
14533 'Radar',
14534 'Scatter'
14535 ],
14536 function(klass) {
14537 core_controller[klass] = function(ctx, cfg) {
14538 return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, {
14539 type: klass.charAt(0).toLowerCase() + klass.slice(1)
14540 }));
14541 };
14542 }
14543);
14544
14545return chart;
14546
14547})));