/*!
* Chart.js v2.8.0
* https://www.chartjs.org
* (c) 2019 Chart.js Contributors
* Released under the MIT License
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Chart = factory());
}(this, (function () { 'use strict';
/* MIT license */
var conversions = {
rgb2hsl: rgb2hsl,
rgb2hsv: rgb2hsv,
rgb2hwb: rgb2hwb,
rgb2cmyk: rgb2cmyk,
rgb2keyword: rgb2keyword,
rgb2xyz: rgb2xyz,
rgb2lab: rgb2lab,
rgb2lch: rgb2lch,
hsl2rgb: hsl2rgb,
hsl2hsv: hsl2hsv,
hsl2hwb: hsl2hwb,
hsl2cmyk: hsl2cmyk,
hsl2keyword: hsl2keyword,
hsv2rgb: hsv2rgb,
hsv2hsl: hsv2hsl,
hsv2hwb: hsv2hwb,
hsv2cmyk: hsv2cmyk,
hsv2keyword: hsv2keyword,
hwb2rgb: hwb2rgb,
hwb2hsl: hwb2hsl,
hwb2hsv: hwb2hsv,
hwb2cmyk: hwb2cmyk,
hwb2keyword: hwb2keyword,
cmyk2rgb: cmyk2rgb,
cmyk2hsl: cmyk2hsl,
cmyk2hsv: cmyk2hsv,
cmyk2hwb: cmyk2hwb,
cmyk2keyword: cmyk2keyword,
keyword2rgb: keyword2rgb,
keyword2hsl: keyword2hsl,
keyword2hsv: keyword2hsv,
keyword2hwb: keyword2hwb,
keyword2cmyk: keyword2cmyk,
keyword2lab: keyword2lab,
keyword2xyz: keyword2xyz,
xyz2rgb: xyz2rgb,
xyz2lab: xyz2lab,
xyz2lch: xyz2lch,
lab2xyz: lab2xyz,
lab2rgb: lab2rgb,
lab2lch: lab2lch,
lch2lab: lch2lab,
lch2xyz: lch2xyz,
lch2rgb: lch2rgb
};
function rgb2hsl(rgb) {
var r = rgb[0]/255,
g = rgb[1]/255,
b = rgb[2]/255,
min = Math.min(r, g, b),
max = Math.max(r, g, b),
delta = max - min,
h, s, l;
if (max == min)
h = 0;
else if (r == max)
h = (g - b) / delta;
else if (g == max)
h = 2 + (b - r) / delta;
else if (b == max)
h = 4 + (r - g)/ delta;
h = Math.min(h * 60, 360);
if (h < 0)
h += 360;
l = (min + max) / 2;
if (max == min)
s = 0;
else if (l <= 0.5)
s = delta / (max + min);
else
s = delta / (2 - max - min);
return [h, s * 100, l * 100];
}
function rgb2hsv(rgb) {
var r = rgb[0],
g = rgb[1],
b = rgb[2],
min = Math.min(r, g, b),
max = Math.max(r, g, b),
delta = max - min,
h, s, v;
if (max == 0)
s = 0;
else
s = (delta/max * 1000)/10;
if (max == min)
h = 0;
else if (r == max)
h = (g - b) / delta;
else if (g == max)
h = 2 + (b - r) / delta;
else if (b == max)
h = 4 + (r - g) / delta;
h = Math.min(h * 60, 360);
if (h < 0)
h += 360;
v = ((max / 255) * 1000) / 10;
return [h, s, v];
}
function rgb2hwb(rgb) {
var r = rgb[0],
g = rgb[1],
b = rgb[2],
h = rgb2hsl(rgb)[0],
w = 1/255 * Math.min(r, Math.min(g, b)),
b = 1 - 1/255 * Math.max(r, Math.max(g, b));
return [h, w * 100, b * 100];
}
function rgb2cmyk(rgb) {
var r = rgb[0] / 255,
g = rgb[1] / 255,
b = rgb[2] / 255,
c, m, y, k;
k = Math.min(1 - r, 1 - g, 1 - b);
c = (1 - r - k) / (1 - k) || 0;
m = (1 - g - k) / (1 - k) || 0;
y = (1 - b - k) / (1 - k) || 0;
return [c * 100, m * 100, y * 100, k * 100];
}
function rgb2keyword(rgb) {
return reverseKeywords[JSON.stringify(rgb)];
}
function rgb2xyz(rgb) {
var r = rgb[0] / 255,
g = rgb[1] / 255,
b = rgb[2] / 255;
// assume sRGB
r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
return [x * 100, y *100, z * 100];
}
function rgb2lab(rgb) {
var xyz = rgb2xyz(rgb),
x = xyz[0],
y = xyz[1],
z = xyz[2],
l, a, b;
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
l = (116 * y) - 16;
a = 500 * (x - y);
b = 200 * (y - z);
return [l, a, b];
}
function rgb2lch(args) {
return lab2lch(rgb2lab(args));
}
function hsl2rgb(hsl) {
var h = hsl[0] / 360,
s = hsl[1] / 100,
l = hsl[2] / 100,
t1, t2, t3, rgb, val;
if (s == 0) {
val = l * 255;
return [val, val, val];
}
if (l < 0.5)
t2 = l * (1 + s);
else
t2 = l + s - l * s;
t1 = 2 * l - t2;
rgb = [0, 0, 0];
for (var i = 0; i < 3; i++) {
t3 = h + 1 / 3 * - (i - 1);
t3 < 0 && t3++;
t3 > 1 && t3--;
if (6 * t3 < 1)
val = t1 + (t2 - t1) * 6 * t3;
else if (2 * t3 < 1)
val = t2;
else if (3 * t3 < 2)
val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
else
val = t1;
rgb[i] = val * 255;
}
return rgb;
}
function hsl2hsv(hsl) {
var h = hsl[0],
s = hsl[1] / 100,
l = hsl[2] / 100,
sv, v;
if(l === 0) {
// no need to do calc on black
// also avoids divide by 0 error
return [0, 0, 0];
}
l *= 2;
s *= (l <= 1) ? l : 2 - l;
v = (l + s) / 2;
sv = (2 * s) / (l + s);
return [h, sv * 100, v * 100];
}
function hsl2hwb(args) {
return rgb2hwb(hsl2rgb(args));
}
function hsl2cmyk(args) {
return rgb2cmyk(hsl2rgb(args));
}
function hsl2keyword(args) {
return rgb2keyword(hsl2rgb(args));
}
function hsv2rgb(hsv) {
var h = hsv[0] / 60,
s = hsv[1] / 100,
v = hsv[2] / 100,
hi = Math.floor(h) % 6;
var f = h - Math.floor(h),
p = 255 * v * (1 - s),
q = 255 * v * (1 - (s * f)),
t = 255 * v * (1 - (s * (1 - f))),
v = 255 * v;
switch(hi) {
case 0:
return [v, t, p];
case 1:
return [q, v, p];
case 2:
return [p, v, t];
case 3:
return [p, q, v];
case 4:
return [t, p, v];
case 5:
return [v, p, q];
}
}
function hsv2hsl(hsv) {
var h = hsv[0],
s = hsv[1] / 100,
v = hsv[2] / 100,
sl, l;
l = (2 - s) * v;
sl = s * v;
sl /= (l <= 1) ? l : 2 - l;
sl = sl || 0;
l /= 2;
return [h, sl * 100, l * 100];
}
function hsv2hwb(args) {
return rgb2hwb(hsv2rgb(args))
}
function hsv2cmyk(args) {
return rgb2cmyk(hsv2rgb(args));
}
function hsv2keyword(args) {
return rgb2keyword(hsv2rgb(args));
}
// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
function hwb2rgb(hwb) {
var h = hwb[0] / 360,
wh = hwb[1] / 100,
bl = hwb[2] / 100,
ratio = wh + bl,
i, v, f, n;
// wh + bl cant be > 1
if (ratio > 1) {
wh /= ratio;
bl /= ratio;
}
i = Math.floor(6 * h);
v = 1 - bl;
f = 6 * h - i;
if ((i & 0x01) != 0) {
f = 1 - f;
}
n = wh + f * (v - wh); // linear interpolation
switch (i) {
default:
case 6:
case 0: r = v; g = n; b = wh; break;
case 1: r = n; g = v; b = wh; break;
case 2: r = wh; g = v; b = n; break;
case 3: r = wh; g = n; b = v; break;
case 4: r = n; g = wh; b = v; break;
case 5: r = v; g = wh; b = n; break;
}
return [r * 255, g * 255, b * 255];
}
function hwb2hsl(args) {
return rgb2hsl(hwb2rgb(args));
}
function hwb2hsv(args) {
return rgb2hsv(hwb2rgb(args));
}
function hwb2cmyk(args) {
return rgb2cmyk(hwb2rgb(args));
}
function hwb2keyword(args) {
return rgb2keyword(hwb2rgb(args));
}
function cmyk2rgb(cmyk) {
var c = cmyk[0] / 100,
m = cmyk[1] / 100,
y = cmyk[2] / 100,
k = cmyk[3] / 100,
r, g, b;
r = 1 - Math.min(1, c * (1 - k) + k);
g = 1 - Math.min(1, m * (1 - k) + k);
b = 1 - Math.min(1, y * (1 - k) + k);
return [r * 255, g * 255, b * 255];
}
function cmyk2hsl(args) {
return rgb2hsl(cmyk2rgb(args));
}
function cmyk2hsv(args) {
return rgb2hsv(cmyk2rgb(args));
}
function cmyk2hwb(args) {
return rgb2hwb(cmyk2rgb(args));
}
function cmyk2keyword(args) {
return rgb2keyword(cmyk2rgb(args));
}
function xyz2rgb(xyz) {
var x = xyz[0] / 100,
y = xyz[1] / 100,
z = xyz[2] / 100,
r, g, b;
r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
// assume sRGB
r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
: r = (r * 12.92);
g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
: g = (g * 12.92);
b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
: b = (b * 12.92);
r = Math.min(Math.max(0, r), 1);
g = Math.min(Math.max(0, g), 1);
b = Math.min(Math.max(0, b), 1);
return [r * 255, g * 255, b * 255];
}
function xyz2lab(xyz) {
var x = xyz[0],
y = xyz[1],
z = xyz[2],
l, a, b;
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
l = (116 * y) - 16;
a = 500 * (x - y);
b = 200 * (y - z);
return [l, a, b];
}
function xyz2lch(args) {
return lab2lch(xyz2lab(args));
}
function lab2xyz(lab) {
var l = lab[0],
a = lab[1],
b = lab[2],
x, y, z, y2;
if (l <= 8) {
y = (l * 100) / 903.3;
y2 = (7.787 * (y / 100)) + (16 / 116);
} else {
y = 100 * Math.pow((l + 16) / 116, 3);
y2 = Math.pow(y / 100, 1/3);
}
x = x / 95.047 <= 0.008856 ? x = (95.047 * ((a / 500) + y2 - (16 / 116))) / 7.787 : 95.047 * Math.pow((a / 500) + y2, 3);
z = z / 108.883 <= 0.008859 ? z = (108.883 * (y2 - (b / 200) - (16 / 116))) / 7.787 : 108.883 * Math.pow(y2 - (b / 200), 3);
return [x, y, z];
}
function lab2lch(lab) {
var l = lab[0],
a = lab[1],
b = lab[2],
hr, h, c;
hr = Math.atan2(b, a);
h = hr * 360 / 2 / Math.PI;
if (h < 0) {
h += 360;
}
c = Math.sqrt(a * a + b * b);
return [l, c, h];
}
function lab2rgb(args) {
return xyz2rgb(lab2xyz(args));
}
function lch2lab(lch) {
var l = lch[0],
c = lch[1],
h = lch[2],
a, b, hr;
hr = h / 360 * 2 * Math.PI;
a = c * Math.cos(hr);
b = c * Math.sin(hr);
return [l, a, b];
}
function lch2xyz(args) {
return lab2xyz(lch2lab(args));
}
function lch2rgb(args) {
return lab2rgb(lch2lab(args));
}
function keyword2rgb(keyword) {
return cssKeywords[keyword];
}
function keyword2hsl(args) {
return rgb2hsl(keyword2rgb(args));
}
function keyword2hsv(args) {
return rgb2hsv(keyword2rgb(args));
}
function keyword2hwb(args) {
return rgb2hwb(keyword2rgb(args));
}
function keyword2cmyk(args) {
return rgb2cmyk(keyword2rgb(args));
}
function keyword2lab(args) {
return rgb2lab(keyword2rgb(args));
}
function keyword2xyz(args) {
return rgb2xyz(keyword2rgb(args));
}
var cssKeywords = {
aliceblue: [240,248,255],
antiquewhite: [250,235,215],
aqua: [0,255,255],
aquamarine: [127,255,212],
azure: [240,255,255],
beige: [245,245,220],
bisque: [255,228,196],
black: [0,0,0],
blanchedalmond: [255,235,205],
blue: [0,0,255],
blueviolet: [138,43,226],
brown: [165,42,42],
burlywood: [222,184,135],
cadetblue: [95,158,160],
chartreuse: [127,255,0],
chocolate: [210,105,30],
coral: [255,127,80],
cornflowerblue: [100,149,237],
cornsilk: [255,248,220],
crimson: [220,20,60],
cyan: [0,255,255],
darkblue: [0,0,139],
darkcyan: [0,139,139],
darkgoldenrod: [184,134,11],
darkgray: [169,169,169],
darkgreen: [0,100,0],
darkgrey: [169,169,169],
darkkhaki: [189,183,107],
darkmagenta: [139,0,139],
darkolivegreen: [85,107,47],
darkorange: [255,140,0],
darkorchid: [153,50,204],
darkred: [139,0,0],
darksalmon: [233,150,122],
darkseagreen: [143,188,143],
darkslateblue: [72,61,139],
darkslategray: [47,79,79],
darkslategrey: [47,79,79],
darkturquoise: [0,206,209],
darkviolet: [148,0,211],
deeppink: [255,20,147],
deepskyblue: [0,191,255],
dimgray: [105,105,105],
dimgrey: [105,105,105],
dodgerblue: [30,144,255],
firebrick: [178,34,34],
floralwhite: [255,250,240],
forestgreen: [34,139,34],
fuchsia: [255,0,255],
gainsboro: [220,220,220],
ghostwhite: [248,248,255],
gold: [255,215,0],
goldenrod: [218,165,32],
gray: [128,128,128],
green: [0,128,0],
greenyellow: [173,255,47],
grey: [128,128,128],
honeydew: [240,255,240],
hotpink: [255,105,180],
indianred: [205,92,92],
indigo: [75,0,130],
ivory: [255,255,240],
khaki: [240,230,140],
lavender: [230,230,250],
lavenderblush: [255,240,245],
lawngreen: [124,252,0],
lemonchiffon: [255,250,205],
lightblue: [173,216,230],
lightcoral: [240,128,128],
lightcyan: [224,255,255],
lightgoldenrodyellow: [250,250,210],
lightgray: [211,211,211],
lightgreen: [144,238,144],
lightgrey: [211,211,211],
lightpink: [255,182,193],
lightsalmon: [255,160,122],
lightseagreen: [32,178,170],
lightskyblue: [135,206,250],
lightslategray: [119,136,153],
lightslategrey: [119,136,153],
lightsteelblue: [176,196,222],
lightyellow: [255,255,224],
lime: [0,255,0],
limegreen: [50,205,50],
linen: [250,240,230],
magenta: [255,0,255],
maroon: [128,0,0],
mediumaquamarine: [102,205,170],
mediumblue: [0,0,205],
mediumorchid: [186,85,211],
mediumpurple: [147,112,219],
mediumseagreen: [60,179,113],
mediumslateblue: [123,104,238],
mediumspringgreen: [0,250,154],
mediumturquoise: [72,209,204],
mediumvioletred: [199,21,133],
midnightblue: [25,25,112],
mintcream: [245,255,250],
mistyrose: [255,228,225],
moccasin: [255,228,181],
navajowhite: [255,222,173],
navy: [0,0,128],
oldlace: [253,245,230],
olive: [128,128,0],
olivedrab: [107,142,35],
orange: [255,165,0],
orangered: [255,69,0],
orchid: [218,112,214],
palegoldenrod: [238,232,170],
palegreen: [152,251,152],
paleturquoise: [175,238,238],
palevioletred: [219,112,147],
papayawhip: [255,239,213],
peachpuff: [255,218,185],
peru: [205,133,63],
pink: [255,192,203],
plum: [221,160,221],
powderblue: [176,224,230],
purple: [128,0,128],
rebeccapurple: [102, 51, 153],
red: [255,0,0],
rosybrown: [188,143,143],
royalblue: [65,105,225],
saddlebrown: [139,69,19],
salmon: [250,128,114],
sandybrown: [244,164,96],
seagreen: [46,139,87],
seashell: [255,245,238],
sienna: [160,82,45],
silver: [192,192,192],
skyblue: [135,206,235],
slateblue: [106,90,205],
slategray: [112,128,144],
slategrey: [112,128,144],
snow: [255,250,250],
springgreen: [0,255,127],
steelblue: [70,130,180],
tan: [210,180,140],
teal: [0,128,128],
thistle: [216,191,216],
tomato: [255,99,71],
turquoise: [64,224,208],
violet: [238,130,238],
wheat: [245,222,179],
white: [255,255,255],
whitesmoke: [245,245,245],
yellow: [255,255,0],
yellowgreen: [154,205,50]
};
var reverseKeywords = {};
for (var key in cssKeywords) {
reverseKeywords[JSON.stringify(cssKeywords[key])] = key;
}
var convert = function() {
return new Converter();
};
for (var func in conversions) {
// export Raw versions
convert[func + "Raw"] = (function(func) {
// accept array or plain args
return function(arg) {
if (typeof arg == "number")
arg = Array.prototype.slice.call(arguments);
return conversions[func](arg);
}
})(func);
var pair = /(\w+)2(\w+)/.exec(func),
from = pair[1],
to = pair[2];
// export rgb2hsl and ["rgb"]["hsl"]
convert[from] = convert[from] || {};
convert[from][to] = convert[func] = (function(func) {
return function(arg) {
if (typeof arg == "number")
arg = Array.prototype.slice.call(arguments);
var val = conversions[func](arg);
if (typeof val == "string" || val === undefined)
return val; // keyword
for (var i = 0; i < val.length; i++)
val[i] = Math.round(val[i]);
return val;
}
})(func);
}
/* Converter does lazy conversion and caching */
var Converter = function() {
this.convs = {};
};
/* Either get the values for a space or
set the values for a space, depending on args */
Converter.prototype.routeSpace = function(space, args) {
var values = args[0];
if (values === undefined) {
// color.rgb()
return this.getValues(space);
}
// color.rgb(10, 10, 10)
if (typeof values == "number") {
values = Array.prototype.slice.call(args);
}
return this.setValues(space, values);
};
/* Set the values for a space, invalidating cache */
Converter.prototype.setValues = function(space, values) {
this.space = space;
this.convs = {};
this.convs[space] = values;
return this;
};
/* Get the values for a space. If there's already
a conversion for the space, fetch it, otherwise
compute it */
Converter.prototype.getValues = function(space) {
var vals = this.convs[space];
if (!vals) {
var fspace = this.space,
from = this.convs[fspace];
vals = convert[fspace][space](from);
this.convs[space] = vals;
}
return vals;
};
["rgb", "hsl", "hsv", "cmyk", "keyword"].forEach(function(space) {
Converter.prototype[space] = function(vals) {
return this.routeSpace(space, arguments);
};
});
var colorConvert = convert;
var colorName = {
"aliceblue": [240, 248, 255],
"antiquewhite": [250, 235, 215],
"aqua": [0, 255, 255],
"aquamarine": [127, 255, 212],
"azure": [240, 255, 255],
"beige": [245, 245, 220],
"bisque": [255, 228, 196],
"black": [0, 0, 0],
"blanchedalmond": [255, 235, 205],
"blue": [0, 0, 255],
"blueviolet": [138, 43, 226],
"brown": [165, 42, 42],
"burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
"coral": [255, 127, 80],
"cornflowerblue": [100, 149, 237],
"cornsilk": [255, 248, 220],
"crimson": [220, 20, 60],
"cyan": [0, 255, 255],
"darkblue": [0, 0, 139],
"darkcyan": [0, 139, 139],
"darkgoldenrod": [184, 134, 11],
"darkgray": [169, 169, 169],
"darkgreen": [0, 100, 0],
"darkgrey": [169, 169, 169],
"darkkhaki": [189, 183, 107],
"darkmagenta": [139, 0, 139],
"darkolivegreen": [85, 107, 47],
"darkorange": [255, 140, 0],
"darkorchid": [153, 50, 204],
"darkred": [139, 0, 0],
"darksalmon": [233, 150, 122],
"darkseagreen": [143, 188, 143],
"darkslateblue": [72, 61, 139],
"darkslategray": [47, 79, 79],
"darkslategrey": [47, 79, 79],
"darkturquoise": [0, 206, 209],
"darkviolet": [148, 0, 211],
"deeppink": [255, 20, 147],
"deepskyblue": [0, 191, 255],
"dimgray": [105, 105, 105],
"dimgrey": [105, 105, 105],
"dodgerblue": [30, 144, 255],
"firebrick": [178, 34, 34],
"floralwhite": [255, 250, 240],
"forestgreen": [34, 139, 34],
"fuchsia": [255, 0, 255],
"gainsboro": [220, 220, 220],
"ghostwhite": [248, 248, 255],
"gold": [255, 215, 0],
"goldenrod": [218, 165, 32],
"gray": [128, 128, 128],
"green": [0, 128, 0],
"greenyellow": [173, 255, 47],
"grey": [128, 128, 128],
"honeydew": [240, 255, 240],
"hotpink": [255, 105, 180],
"indianred": [205, 92, 92],
"indigo": [75, 0, 130],
"ivory": [255, 255, 240],
"khaki": [240, 230, 140],
"lavender": [230, 230, 250],
"lavenderblush": [255, 240, 245],
"lawngreen": [124, 252, 0],
"lemonchiffon": [255, 250, 205],
"lightblue": [173, 216, 230],
"lightcoral": [240, 128, 128],
"lightcyan": [224, 255, 255],
"lightgoldenrodyellow": [250, 250, 210],
"lightgray": [211, 211, 211],
"lightgreen": [144, 238, 144],
"lightgrey": [211, 211, 211],
"lightpink": [255, 182, 193],
"lightsalmon": [255, 160, 122],
"lightseagreen": [32, 178, 170],
"lightskyblue": [135, 206, 250],
"lightslategray": [119, 136, 153],
"lightslategrey": [119, 136, 153],
"lightsteelblue": [176, 196, 222],
"lightyellow": [255, 255, 224],
"lime": [0, 255, 0],
"limegreen": [50, 205, 50],
"linen": [250, 240, 230],
"magenta": [255, 0, 255],
"maroon": [128, 0, 0],
"mediumaquamarine": [102, 205, 170],
"mediumblue": [0, 0, 205],
"mediumorchid": [186, 85, 211],
"mediumpurple": [147, 112, 219],
"mediumseagreen": [60, 179, 113],
"mediumslateblue": [123, 104, 238],
"mediumspringgreen": [0, 250, 154],
"mediumturquoise": [72, 209, 204],
"mediumvioletred": [199, 21, 133],
"midnightblue": [25, 25, 112],
"mintcream": [245, 255, 250],
"mistyrose": [255, 228, 225],
"moccasin": [255, 228, 181],
"navajowhite": [255, 222, 173],
"navy": [0, 0, 128],
"oldlace": [253, 245, 230],
"olive": [128, 128, 0],
"olivedrab": [107, 142, 35],
"orange": [255, 165, 0],
"orangered": [255, 69, 0],
"orchid": [218, 112, 214],
"palegoldenrod": [238, 232, 170],
"palegreen": [152, 251, 152],
"paleturquoise": [175, 238, 238],
"palevioletred": [219, 112, 147],
"papayawhip": [255, 239, 213],
"peachpuff": [255, 218, 185],
"peru": [205, 133, 63],
"pink": [255, 192, 203],
"plum": [221, 160, 221],
"powderblue": [176, 224, 230],
"purple": [128, 0, 128],
"rebeccapurple": [102, 51, 153],
"red": [255, 0, 0],
"rosybrown": [188, 143, 143],
"royalblue": [65, 105, 225],
"saddlebrown": [139, 69, 19],
"salmon": [250, 128, 114],
"sandybrown": [244, 164, 96],
"seagreen": [46, 139, 87],
"seashell": [255, 245, 238],
"sienna": [160, 82, 45],
"silver": [192, 192, 192],
"skyblue": [135, 206, 235],
"slateblue": [106, 90, 205],
"slategray": [112, 128, 144],
"slategrey": [112, 128, 144],
"snow": [255, 250, 250],
"springgreen": [0, 255, 127],
"steelblue": [70, 130, 180],
"tan": [210, 180, 140],
"teal": [0, 128, 128],
"thistle": [216, 191, 216],
"tomato": [255, 99, 71],
"turquoise": [64, 224, 208],
"violet": [238, 130, 238],
"wheat": [245, 222, 179],
"white": [255, 255, 255],
"whitesmoke": [245, 245, 245],
"yellow": [255, 255, 0],
"yellowgreen": [154, 205, 50]
};
/* MIT license */
var colorString = {
getRgba: getRgba,
getHsla: getHsla,
getRgb: getRgb,
getHsl: getHsl,
getHwb: getHwb,
getAlpha: getAlpha,
hexString: hexString,
rgbString: rgbString,
rgbaString: rgbaString,
percentString: percentString,
percentaString: percentaString,
hslString: hslString,
hslaString: hslaString,
hwbString: hwbString,
keyword: keyword
};
function getRgba(string) {
if (!string) {
return;
}
var abbr = /^#([a-fA-F0-9]{3,4})$/i,
hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i,
rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
keyword = /(\w+)/;
var rgb = [0, 0, 0],
a = 1,
match = string.match(abbr),
hexAlpha = "";
if (match) {
match = match[1];
hexAlpha = match[3];
for (var i = 0; i < rgb.length; i++) {
rgb[i] = parseInt(match[i] + match[i], 16);
}
if (hexAlpha) {
a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100;
}
}
else if (match = string.match(hex)) {
hexAlpha = match[2];
match = match[1];
for (var i = 0; i < rgb.length; i++) {
rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
}
if (hexAlpha) {
a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100;
}
}
else if (match = string.match(rgba)) {
for (var i = 0; i < rgb.length; i++) {
rgb[i] = parseInt(match[i + 1]);
}
a = parseFloat(match[4]);
}
else if (match = string.match(per)) {
for (var i = 0; i < rgb.length; i++) {
rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
}
a = parseFloat(match[4]);
}
else if (match = string.match(keyword)) {
if (match[1] == "transparent") {
return [0, 0, 0, 0];
}
rgb = colorName[match[1]];
if (!rgb) {
return;
}
}
for (var i = 0; i < rgb.length; i++) {
rgb[i] = scale(rgb[i], 0, 255);
}
if (!a && a != 0) {
a = 1;
}
else {
a = scale(a, 0, 1);
}
rgb[3] = a;
return rgb;
}
function getHsla(string) {
if (!string) {
return;
}
var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
var match = string.match(hsl);
if (match) {
var alpha = parseFloat(match[4]);
var h = scale(parseInt(match[1]), 0, 360),
s = scale(parseFloat(match[2]), 0, 100),
l = scale(parseFloat(match[3]), 0, 100),
a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
return [h, s, l, a];
}
}
function getHwb(string) {
if (!string) {
return;
}
var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
var match = string.match(hwb);
if (match) {
var alpha = parseFloat(match[4]);
var h = scale(parseInt(match[1]), 0, 360),
w = scale(parseFloat(match[2]), 0, 100),
b = scale(parseFloat(match[3]), 0, 100),
a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
return [h, w, b, a];
}
}
function getRgb(string) {
var rgba = getRgba(string);
return rgba && rgba.slice(0, 3);
}
function getHsl(string) {
var hsla = getHsla(string);
return hsla && hsla.slice(0, 3);
}
function getAlpha(string) {
var vals = getRgba(string);
if (vals) {
return vals[3];
}
else if (vals = getHsla(string)) {
return vals[3];
}
else if (vals = getHwb(string)) {
return vals[3];
}
}
// generators
function hexString(rgba, a) {
var a = (a !== undefined && rgba.length === 3) ? a : rgba[3];
return "#" + hexDouble(rgba[0])
+ hexDouble(rgba[1])
+ hexDouble(rgba[2])
+ (
(a >= 0 && a < 1)
? hexDouble(Math.round(a * 255))
: ""
);
}
function rgbString(rgba, alpha) {
if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
return rgbaString(rgba, alpha);
}
return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
}
function rgbaString(rgba, alpha) {
if (alpha === undefined) {
alpha = (rgba[3] !== undefined ? rgba[3] : 1);
}
return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
+ ", " + alpha + ")";
}
function percentString(rgba, alpha) {
if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
return percentaString(rgba, alpha);
}
var r = Math.round(rgba[0]/255 * 100),
g = Math.round(rgba[1]/255 * 100),
b = Math.round(rgba[2]/255 * 100);
return "rgb(" + r + "%, " + g + "%, " + b + "%)";
}
function percentaString(rgba, alpha) {
var r = Math.round(rgba[0]/255 * 100),
g = Math.round(rgba[1]/255 * 100),
b = Math.round(rgba[2]/255 * 100);
return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
}
function hslString(hsla, alpha) {
if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
return hslaString(hsla, alpha);
}
return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
}
function hslaString(hsla, alpha) {
if (alpha === undefined) {
alpha = (hsla[3] !== undefined ? hsla[3] : 1);
}
return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
+ alpha + ")";
}
// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
// (hwb have alpha optional & 1 is default value)
function hwbString(hwb, alpha) {
if (alpha === undefined) {
alpha = (hwb[3] !== undefined ? hwb[3] : 1);
}
return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
+ (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
}
function keyword(rgb) {
return reverseNames[rgb.slice(0, 3)];
}
// helpers
function scale(num, min, max) {
return Math.min(Math.max(min, num), max);
}
function hexDouble(num) {
var str = num.toString(16).toUpperCase();
return (str.length < 2) ? "0" + str : str;
}
//create a list of reverse color names
var reverseNames = {};
for (var name in colorName) {
reverseNames[colorName[name]] = name;
}
/* MIT license */
var Color = function (obj) {
if (obj instanceof Color) {
return obj;
}
if (!(this instanceof Color)) {
return new Color(obj);
}
this.valid = false;
this.values = {
rgb: [0, 0, 0],
hsl: [0, 0, 0],
hsv: [0, 0, 0],
hwb: [0, 0, 0],
cmyk: [0, 0, 0, 0],
alpha: 1
};
// parse Color() argument
var vals;
if (typeof obj === 'string') {
vals = colorString.getRgba(obj);
if (vals) {
this.setValues('rgb', vals);
} else if (vals = colorString.getHsla(obj)) {
this.setValues('hsl', vals);
} else if (vals = colorString.getHwb(obj)) {
this.setValues('hwb', vals);
}
} else if (typeof obj === 'object') {
vals = obj;
if (vals.r !== undefined || vals.red !== undefined) {
this.setValues('rgb', vals);
} else if (vals.l !== undefined || vals.lightness !== undefined) {
this.setValues('hsl', vals);
} else if (vals.v !== undefined || vals.value !== undefined) {
this.setValues('hsv', vals);
} else if (vals.w !== undefined || vals.whiteness !== undefined) {
this.setValues('hwb', vals);
} else if (vals.c !== undefined || vals.cyan !== undefined) {
this.setValues('cmyk', vals);
}
}
};
Color.prototype = {
isValid: function () {
return this.valid;
},
rgb: function () {
return this.setSpace('rgb', arguments);
},
hsl: function () {
return this.setSpace('hsl', arguments);
},
hsv: function () {
return this.setSpace('hsv', arguments);
},
hwb: function () {
return this.setSpace('hwb', arguments);
},
cmyk: function () {
return this.setSpace('cmyk', arguments);
},
rgbArray: function () {
return this.values.rgb;
},
hslArray: function () {
return this.values.hsl;
},
hsvArray: function () {
return this.values.hsv;
},
hwbArray: function () {
var values = this.values;
if (values.alpha !== 1) {
return values.hwb.concat([values.alpha]);
}
return values.hwb;
},
cmykArray: function () {
return this.values.cmyk;
},
rgbaArray: function () {
var values = this.values;
return values.rgb.concat([values.alpha]);
},
hslaArray: function () {
var values = this.values;
return values.hsl.concat([values.alpha]);
},
alpha: function (val) {
if (val === undefined) {
return this.values.alpha;
}
this.setValues('alpha', val);
return this;
},
red: function (val) {
return this.setChannel('rgb', 0, val);
},
green: function (val) {
return this.setChannel('rgb', 1, val);
},
blue: function (val) {
return this.setChannel('rgb', 2, val);
},
hue: function (val) {
if (val) {
val %= 360;
val = val < 0 ? 360 + val : val;
}
return this.setChannel('hsl', 0, val);
},
saturation: function (val) {
return this.setChannel('hsl', 1, val);
},
lightness: function (val) {
return this.setChannel('hsl', 2, val);
},
saturationv: function (val) {
return this.setChannel('hsv', 1, val);
},
whiteness: function (val) {
return this.setChannel('hwb', 1, val);
},
blackness: function (val) {
return this.setChannel('hwb', 2, val);
},
value: function (val) {
return this.setChannel('hsv', 2, val);
},
cyan: function (val) {
return this.setChannel('cmyk', 0, val);
},
magenta: function (val) {
return this.setChannel('cmyk', 1, val);
},
yellow: function (val) {
return this.setChannel('cmyk', 2, val);
},
black: function (val) {
return this.setChannel('cmyk', 3, val);
},
hexString: function () {
return colorString.hexString(this.values.rgb);
},
rgbString: function () {
return colorString.rgbString(this.values.rgb, this.values.alpha);
},
rgbaString: function () {
return colorString.rgbaString(this.values.rgb, this.values.alpha);
},
percentString: function () {
return colorString.percentString(this.values.rgb, this.values.alpha);
},
hslString: function () {
return colorString.hslString(this.values.hsl, this.values.alpha);
},
hslaString: function () {
return colorString.hslaString(this.values.hsl, this.values.alpha);
},
hwbString: function () {
return colorString.hwbString(this.values.hwb, this.values.alpha);
},
keyword: function () {
return colorString.keyword(this.values.rgb, this.values.alpha);
},
rgbNumber: function () {
var rgb = this.values.rgb;
return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
},
luminosity: function () {
// http://www.w3.org/TR/WCAG20/#relativeluminancedef
var rgb = this.values.rgb;
var lum = [];
for (var i = 0; i < rgb.length; i++) {
var chan = rgb[i] / 255;
lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
}
return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
},
contrast: function (color2) {
// http://www.w3.org/TR/WCAG20/#contrast-ratiodef
var lum1 = this.luminosity();
var lum2 = color2.luminosity();
if (lum1 > lum2) {
return (lum1 + 0.05) / (lum2 + 0.05);
}
return (lum2 + 0.05) / (lum1 + 0.05);
},
level: function (color2) {
var contrastRatio = this.contrast(color2);
if (contrastRatio >= 7.1) {
return 'AAA';
}
return (contrastRatio >= 4.5) ? 'AA' : '';
},
dark: function () {
// YIQ equation from http://24ways.org/2010/calculating-color-contrast
var rgb = this.values.rgb;
var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
return yiq < 128;
},
light: function () {
return !this.dark();
},
negate: function () {
var rgb = [];
for (var i = 0; i < 3; i++) {
rgb[i] = 255 - this.values.rgb[i];
}
this.setValues('rgb', rgb);
return this;
},
lighten: function (ratio) {
var hsl = this.values.hsl;
hsl[2] += hsl[2] * ratio;
this.setValues('hsl', hsl);
return this;
},
darken: function (ratio) {
var hsl = this.values.hsl;
hsl[2] -= hsl[2] * ratio;
this.setValues('hsl', hsl);
return this;
},
saturate: function (ratio) {
var hsl = this.values.hsl;
hsl[1] += hsl[1] * ratio;
this.setValues('hsl', hsl);
return this;
},
desaturate: function (ratio) {
var hsl = this.values.hsl;
hsl[1] -= hsl[1] * ratio;
this.setValues('hsl', hsl);
return this;
},
whiten: function (ratio) {
var hwb = this.values.hwb;
hwb[1] += hwb[1] * ratio;
this.setValues('hwb', hwb);
return this;
},
blacken: function (ratio) {
var hwb = this.values.hwb;
hwb[2] += hwb[2] * ratio;
this.setValues('hwb', hwb);
return this;
},
greyscale: function () {
var rgb = this.values.rgb;
// http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
this.setValues('rgb', [val, val, val]);
return this;
},
clearer: function (ratio) {
var alpha = this.values.alpha;
this.setValues('alpha', alpha - (alpha * ratio));
return this;
},
opaquer: function (ratio) {
var alpha = this.values.alpha;
this.setValues('alpha', alpha + (alpha * ratio));
return this;
},
rotate: function (degrees) {
var hsl = this.values.hsl;
var hue = (hsl[0] + degrees) % 360;
hsl[0] = hue < 0 ? 360 + hue : hue;
this.setValues('hsl', hsl);
return this;
},
/**
* Ported from sass implementation in C
* https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
*/
mix: function (mixinColor, weight) {
var color1 = this;
var color2 = mixinColor;
var p = weight === undefined ? 0.5 : weight;
var w = 2 * p - 1;
var a = color1.alpha() - color2.alpha();
var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
var w2 = 1 - w1;
return this
.rgb(
w1 * color1.red() + w2 * color2.red(),
w1 * color1.green() + w2 * color2.green(),
w1 * color1.blue() + w2 * color2.blue()
)
.alpha(color1.alpha() * p + color2.alpha() * (1 - p));
},
toJSON: function () {
return this.rgb();
},
clone: function () {
// NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
// making the final build way to big to embed in Chart.js. So let's do it manually,
// assuming that values to clone are 1 dimension arrays containing only numbers,
// except 'alpha' which is a number.
var result = new Color();
var source = this.values;
var target = result.values;
var value, type;
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
value = source[prop];
type = ({}).toString.call(value);
if (type === '[object Array]') {
target[prop] = value.slice(0);
} else if (type === '[object Number]') {
target[prop] = value;
} else {
console.error('unexpected color value:', value);
}
}
}
return result;
}
};
Color.prototype.spaces = {
rgb: ['red', 'green', 'blue'],
hsl: ['hue', 'saturation', 'lightness'],
hsv: ['hue', 'saturation', 'value'],
hwb: ['hue', 'whiteness', 'blackness'],
cmyk: ['cyan', 'magenta', 'yellow', 'black']
};
Color.prototype.maxes = {
rgb: [255, 255, 255],
hsl: [360, 100, 100],
hsv: [360, 100, 100],
hwb: [360, 100, 100],
cmyk: [100, 100, 100, 100]
};
Color.prototype.getValues = function (space) {
var values = this.values;
var vals = {};
for (var i = 0; i < space.length; i++) {
vals[space.charAt(i)] = values[space][i];
}
if (values.alpha !== 1) {
vals.a = values.alpha;
}
// {r: 255, g: 255, b: 255, a: 0.4}
return vals;
};
Color.prototype.setValues = function (space, vals) {
var values = this.values;
var spaces = this.spaces;
var maxes = this.maxes;
var alpha = 1;
var i;
this.valid = true;
if (space === 'alpha') {
alpha = vals;
} else if (vals.length) {
// [10, 10, 10]
values[space] = vals.slice(0, space.length);
alpha = vals[space.length];
} else if (vals[space.charAt(0)] !== undefined) {
// {r: 10, g: 10, b: 10}
for (i = 0; i < space.length; i++) {
values[space][i] = vals[space.charAt(i)];
}
alpha = vals.a;
} else if (vals[spaces[space][0]] !== undefined) {
// {red: 10, green: 10, blue: 10}
var chans = spaces[space];
for (i = 0; i < space.length; i++) {
values[space][i] = vals[chans[i]];
}
alpha = vals.alpha;
}
values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
if (space === 'alpha') {
return false;
}
var capped;
// cap values of the space prior converting all values
for (i = 0; i < space.length; i++) {
capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
values[space][i] = Math.round(capped);
}
// convert to all the other color spaces
for (var sname in spaces) {
if (sname !== space) {
values[sname] = colorConvert[space][sname](values[space]);
}
}
return true;
};
Color.prototype.setSpace = function (space, args) {
var vals = args[0];
if (vals === undefined) {
// color.rgb()
return this.getValues(space);
}
// color.rgb(10, 10, 10)
if (typeof vals === 'number') {
vals = Array.prototype.slice.call(args);
}
this.setValues(space, vals);
return this;
};
Color.prototype.setChannel = function (space, index, val) {
var svalues = this.values[space];
if (val === undefined) {
// color.red()
return svalues[index];
} else if (val === svalues[index]) {
// color.red(color.red())
return this;
}
// color.red(100)
svalues[index] = val;
this.setValues(space, svalues);
return this;
};
if (typeof window !== 'undefined') {
window.Color = Color;
}
var chartjsColor = Color;
/**
* @namespace Chart.helpers
*/
var helpers = {
/**
* An empty function that can be used, for example, for optional callback.
*/
noop: function() {},
/**
* Returns a unique id, sequentially generated from a global variable.
* @returns {number}
* @function
*/
uid: (function() {
var id = 0;
return function() {
return id++;
};
}()),
/**
* Returns true if `value` is neither null nor undefined, else returns false.
* @param {*} value - The value to test.
* @returns {boolean}
* @since 2.7.0
*/
isNullOrUndef: function(value) {
return value === null || typeof value === 'undefined';
},
/**
* Returns true if `value` is an array (including typed arrays), else returns false.
* @param {*} value - The value to test.
* @returns {boolean}
* @function
*/
isArray: function(value) {
if (Array.isArray && Array.isArray(value)) {
return true;
}
var type = Object.prototype.toString.call(value);
if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
return true;
}
return false;
},
/**
* Returns true if `value` is an object (excluding null), else returns false.
* @param {*} value - The value to test.
* @returns {boolean}
* @since 2.7.0
*/
isObject: function(value) {
return value !== null && Object.prototype.toString.call(value) === '[object Object]';
},
/**
* Returns true if `value` is a finite number, else returns false
* @param {*} value - The value to test.
* @returns {boolean}
*/
isFinite: function(value) {
return (typeof value === 'number' || value instanceof Number) && isFinite(value);
},
/**
* Returns `value` if defined, else returns `defaultValue`.
* @param {*} value - The value to return if defined.
* @param {*} defaultValue - The value to return if `value` is undefined.
* @returns {*}
*/
valueOrDefault: function(value, defaultValue) {
return typeof value === 'undefined' ? defaultValue : value;
},
/**
* Returns value at the given `index` in array if defined, else returns `defaultValue`.
* @param {Array} value - The array to lookup for value at `index`.
* @param {number} index - The index in `value` to lookup for value.
* @param {*} defaultValue - The value to return if `value[index]` is undefined.
* @returns {*}
*/
valueAtIndexOrDefault: function(value, index, defaultValue) {
return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
},
/**
* Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
* value returned by `fn`. If `fn` is not a function, this method returns undefined.
* @param {function} fn - The function to call.
* @param {Array|undefined|null} args - The arguments with which `fn` should be called.
* @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
* @returns {*}
*/
callback: function(fn, args, thisArg) {
if (fn && typeof fn.call === 'function') {
return fn.apply(thisArg, args);
}
},
/**
* Note(SB) for performance sake, this method should only be used when loopable type
* is unknown or in none intensive code (not called often and small loopable). Else
* it's preferable to use a regular for() loop and save extra function calls.
* @param {object|Array} loopable - The object or array to be iterated.
* @param {function} fn - The function to call for each item.
* @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
* @param {boolean} [reverse] - If true, iterates backward on the loopable.
*/
each: function(loopable, fn, thisArg, reverse) {
var i, len, keys;
if (helpers.isArray(loopable)) {
len = loopable.length;
if (reverse) {
for (i = len - 1; i >= 0; i--) {
fn.call(thisArg, loopable[i], i);
}
} else {
for (i = 0; i < len; i++) {
fn.call(thisArg, loopable[i], i);
}
}
} else if (helpers.isObject(loopable)) {
keys = Object.keys(loopable);
len = keys.length;
for (i = 0; i < len; i++) {
fn.call(thisArg, loopable[keys[i]], keys[i]);
}
}
},
/**
* Returns true if the `a0` and `a1` arrays have the same content, else returns false.
* @see https://stackoverflow.com/a/14853974
* @param {Array} a0 - The array to compare
* @param {Array} a1 - The array to compare
* @returns {boolean}
*/
arrayEquals: function(a0, a1) {
var i, ilen, v0, v1;
if (!a0 || !a1 || a0.length !== a1.length) {
return false;
}
for (i = 0, ilen = a0.length; i < ilen; ++i) {
v0 = a0[i];
v1 = a1[i];
if (v0 instanceof Array && v1 instanceof Array) {
if (!helpers.arrayEquals(v0, v1)) {
return false;
}
} else if (v0 !== v1) {
// NOTE: two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
},
/**
* Returns a deep copy of `source` without keeping references on objects and arrays.
* @param {*} source - The value to clone.
* @returns {*}
*/
clone: function(source) {
if (helpers.isArray(source)) {
return source.map(helpers.clone);
}
if (helpers.isObject(source)) {
var target = {};
var keys = Object.keys(source);
var klen = keys.length;
var k = 0;
for (; k < klen; ++k) {
target[keys[k]] = helpers.clone(source[keys[k]]);
}
return target;
}
return source;
},
/**
* The default merger when Chart.helpers.merge is called without merger option.
* Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
* @private
*/
_merger: function(key, target, source, options) {
var tval = target[key];
var sval = source[key];
if (helpers.isObject(tval) && helpers.isObject(sval)) {
helpers.merge(tval, sval, options);
} else {
target[key] = helpers.clone(sval);
}
},
/**
* Merges source[key] in target[key] only if target[key] is undefined.
* @private
*/
_mergerIf: function(key, target, source) {
var tval = target[key];
var sval = source[key];
if (helpers.isObject(tval) && helpers.isObject(sval)) {
helpers.mergeIf(tval, sval);
} else if (!target.hasOwnProperty(key)) {
target[key] = helpers.clone(sval);
}
},
/**
* Recursively deep copies `source` properties into `target` with the given `options`.
* IMPORTANT: `target` is not cloned and will be updated with `source` properties.
* @param {object} target - The target object in which all sources are merged into.
* @param {object|object[]} source - Object(s) to merge into `target`.
* @param {object} [options] - Merging options:
* @param {function} [options.merger] - The merge method (key, target, source, options)
* @returns {object} The `target` object.
*/
merge: function(target, source, options) {
var sources = helpers.isArray(source) ? source : [source];
var ilen = sources.length;
var merge, i, keys, klen, k;
if (!helpers.isObject(target)) {
return target;
}
options = options || {};
merge = options.merger || helpers._merger;
for (i = 0; i < ilen; ++i) {
source = sources[i];
if (!helpers.isObject(source)) {
continue;
}
keys = Object.keys(source);
for (k = 0, klen = keys.length; k < klen; ++k) {
merge(keys[k], target, source, options);
}
}
return target;
},
/**
* Recursively deep copies `source` properties into `target` *only* if not defined in target.
* IMPORTANT: `target` is not cloned and will be updated with `source` properties.
* @param {object} target - The target object in which all sources are merged into.
* @param {object|object[]} source - Object(s) to merge into `target`.
* @returns {object} The `target` object.
*/
mergeIf: function(target, source) {
return helpers.merge(target, source, {merger: helpers._mergerIf});
},
/**
* Applies the contents of two or more objects together into the first object.
* @param {object} target - The target object in which all objects are merged into.
* @param {object} arg1 - Object containing additional properties to merge in target.
* @param {object} argN - Additional objects containing properties to merge in target.
* @returns {object} The `target` object.
*/
extend: function(target) {
var setFn = function(value, key) {
target[key] = value;
};
for (var i = 1, ilen = arguments.length; i < ilen; ++i) {
helpers.each(arguments[i], setFn);
}
return target;
},
/**
* Basic javascript inheritance based on the model created in Backbone.js
*/
inherits: function(extensions) {
var me = this;
var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
return me.apply(this, arguments);
};
var Surrogate = function() {
this.constructor = ChartElement;
};
Surrogate.prototype = me.prototype;
ChartElement.prototype = new Surrogate();
ChartElement.extend = helpers.inherits;
if (extensions) {
helpers.extend(ChartElement.prototype, extensions);
}
ChartElement.__super__ = me.prototype;
return ChartElement;
}
};
var helpers_core = helpers;
// DEPRECATIONS
/**
* Provided for backward compatibility, use Chart.helpers.callback instead.
* @function Chart.helpers.callCallback
* @deprecated since version 2.6.0
* @todo remove at version 3
* @private
*/
helpers.callCallback = helpers.callback;
/**
* Provided for backward compatibility, use Array.prototype.indexOf instead.
* Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
* @function Chart.helpers.indexOf
* @deprecated since version 2.7.0
* @todo remove at version 3
* @private
*/
helpers.indexOf = function(array, item, fromIndex) {
return Array.prototype.indexOf.call(array, item, fromIndex);
};
/**
* Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
* @function Chart.helpers.getValueOrDefault
* @deprecated since version 2.7.0
* @todo remove at version 3
* @private
*/
helpers.getValueOrDefault = helpers.valueOrDefault;
/**
* Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
* @function Chart.helpers.getValueAtIndexOrDefault
* @deprecated since version 2.7.0
* @todo remove at version 3
* @private
*/
helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
/**
* Easing functions adapted from Robert Penner's easing equations.
* @namespace Chart.helpers.easingEffects
* @see http://www.robertpenner.com/easing/
*/
var effects = {
linear: function(t) {
return t;
},
easeInQuad: function(t) {
return t * t;
},
easeOutQuad: function(t) {
return -t * (t - 2);
},
easeInOutQuad: function(t) {
if ((t /= 0.5) < 1) {
return 0.5 * t * t;
}
return -0.5 * ((--t) * (t - 2) - 1);
},
easeInCubic: function(t) {
return t * t * t;
},
easeOutCubic: function(t) {
return (t = t - 1) * t * t + 1;
},
easeInOutCubic: function(t) {
if ((t /= 0.5) < 1) {
return 0.5 * t * t * t;
}
return 0.5 * ((t -= 2) * t * t + 2);
},
easeInQuart: function(t) {
return t * t * t * t;
},
easeOutQuart: function(t) {
return -((t = t - 1) * t * t * t - 1);
},
easeInOutQuart: function(t) {
if ((t /= 0.5) < 1) {
return 0.5 * t * t * t * t;
}
return -0.5 * ((t -= 2) * t * t * t - 2);
},
easeInQuint: function(t) {
return t * t * t * t * t;
},
easeOutQuint: function(t) {
return (t = t - 1) * t * t * t * t + 1;
},
easeInOutQuint: function(t) {
if ((t /= 0.5) < 1) {
return 0.5 * t * t * t * t * t;
}
return 0.5 * ((t -= 2) * t * t * t * t + 2);
},
easeInSine: function(t) {
return -Math.cos(t * (Math.PI / 2)) + 1;
},
easeOutSine: function(t) {
return Math.sin(t * (Math.PI / 2));
},
easeInOutSine: function(t) {
return -0.5 * (Math.cos(Math.PI * t) - 1);
},
easeInExpo: function(t) {
return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
},
easeOutExpo: function(t) {
return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
},
easeInOutExpo: function(t) {
if (t === 0) {
return 0;
}
if (t === 1) {
return 1;
}
if ((t /= 0.5) < 1) {
return 0.5 * Math.pow(2, 10 * (t - 1));
}
return 0.5 * (-Math.pow(2, -10 * --t) + 2);
},
easeInCirc: function(t) {
if (t >= 1) {
return t;
}
return -(Math.sqrt(1 - t * t) - 1);
},
easeOutCirc: function(t) {
return Math.sqrt(1 - (t = t - 1) * t);
},
easeInOutCirc: function(t) {
if ((t /= 0.5) < 1) {
return -0.5 * (Math.sqrt(1 - t * t) - 1);
}
return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
},
easeInElastic: function(t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0) {
return 0;
}
if (t === 1) {
return 1;
}
if (!p) {
p = 0.3;
}
if (a < 1) {
a = 1;
s = p / 4;
} else {
s = p / (2 * Math.PI) * Math.asin(1 / a);
}
return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
},
easeOutElastic: function(t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0) {
return 0;
}
if (t === 1) {
return 1;
}
if (!p) {
p = 0.3;
}
if (a < 1) {
a = 1;
s = p / 4;
} else {
s = p / (2 * Math.PI) * Math.asin(1 / a);
}
return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
},
easeInOutElastic: function(t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0) {
return 0;
}
if ((t /= 0.5) === 2) {
return 1;
}
if (!p) {
p = 0.45;
}
if (a < 1) {
a = 1;
s = p / 4;
} else {
s = p / (2 * Math.PI) * Math.asin(1 / a);
}
if (t < 1) {
return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
}
return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
},
easeInBack: function(t) {
var s = 1.70158;
return t * t * ((s + 1) * t - s);
},
easeOutBack: function(t) {
var s = 1.70158;
return (t = t - 1) * t * ((s + 1) * t + s) + 1;
},
easeInOutBack: function(t) {
var s = 1.70158;
if ((t /= 0.5) < 1) {
return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
}
return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
},
easeInBounce: function(t) {
return 1 - effects.easeOutBounce(1 - t);
},
easeOutBounce: function(t) {
if (t < (1 / 2.75)) {
return 7.5625 * t * t;
}
if (t < (2 / 2.75)) {
return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
}
if (t < (2.5 / 2.75)) {
return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
}
return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
},
easeInOutBounce: function(t) {
if (t < 0.5) {
return effects.easeInBounce(t * 2) * 0.5;
}
return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
}
};
var helpers_easing = {
effects: effects
};
// DEPRECATIONS
/**
* Provided for backward compatibility, use Chart.helpers.easing.effects instead.
* @function Chart.helpers.easingEffects
* @deprecated since version 2.7.0
* @todo remove at version 3
* @private
*/
helpers_core.easingEffects = effects;
var PI = Math.PI;
var RAD_PER_DEG = PI / 180;
var DOUBLE_PI = PI * 2;
var HALF_PI = PI / 2;
var QUARTER_PI = PI / 4;
var TWO_THIRDS_PI = PI * 2 / 3;
/**
* @namespace Chart.helpers.canvas
*/
var exports$1 = {
/**
* Clears the entire canvas associated to the given `chart`.
* @param {Chart} chart - The chart for which to clear the canvas.
*/
clear: function(chart) {
chart.ctx.clearRect(0, 0, chart.width, chart.height);
},
/**
* Creates a "path" for a rectangle with rounded corners at position (x, y) with a
* given size (width, height) and the same `radius` for all corners.
* @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
* @param {number} x - The x axis of the coordinate for the rectangle starting point.
* @param {number} y - The y axis of the coordinate for the rectangle starting point.
* @param {number} width - The rectangle's width.
* @param {number} height - The rectangle's height.
* @param {number} radius - The rounded amount (in pixels) for the four corners.
* @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
*/
roundedRect: function(ctx, x, y, width, height, radius) {
if (radius) {
var r = Math.min(radius, height / 2, width / 2);
var left = x + r;
var top = y + r;
var right = x + width - r;
var bottom = y + height - r;
ctx.moveTo(x, top);
if (left < right && top < bottom) {
ctx.arc(left, top, r, -PI, -HALF_PI);
ctx.arc(right, top, r, -HALF_PI, 0);
ctx.arc(right, bottom, r, 0, HALF_PI);
ctx.arc(left, bottom, r, HALF_PI, PI);
} else if (left < right) {
ctx.moveTo(left, y);
ctx.arc(right, top, r, -HALF_PI, HALF_PI);
ctx.arc(left, top, r, HALF_PI, PI + HALF_PI);
} else if (top < bottom) {
ctx.arc(left, top, r, -PI, 0);
ctx.arc(left, bottom, r, 0, PI);
} else {
ctx.arc(left, top, r, -PI, PI);
}
ctx.closePath();
ctx.moveTo(x, y);
} else {
ctx.rect(x, y, width, height);
}
},
drawPoint: function(ctx, style, radius, x, y, rotation) {
var type, xOffset, yOffset, size, cornerRadius;
var rad = (rotation || 0) * RAD_PER_DEG;
if (style && typeof style === 'object') {
type = style.toString();
if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
ctx.drawImage(style, x - style.width / 2, y - style.height / 2, style.width, style.height);
return;
}
}
if (isNaN(radius) || radius <= 0) {
return;
}
ctx.beginPath();
switch (style) {
// Default includes circle
default:
ctx.arc(x, y, radius, 0, DOUBLE_PI);
ctx.closePath();
break;
case 'triangle':
ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
rad += TWO_THIRDS_PI;
ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
rad += TWO_THIRDS_PI;
ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
ctx.closePath();
break;
case 'rectRounded':
// NOTE: the rounded rect implementation changed to use `arc` instead of
// `quadraticCurveTo` since it generates better results when rect is
// almost a circle. 0.516 (instead of 0.5) produces results with visually
// closer proportion to the previous impl and it is inscribed in the
// circle with `radius`. For more details, see the following PRs:
// https://github.com/chartjs/Chart.js/issues/5597
// https://github.com/chartjs/Chart.js/issues/5858
cornerRadius = radius * 0.516;
size = radius - cornerRadius;
xOffset = Math.cos(rad + QUARTER_PI) * size;
yOffset = Math.sin(rad + QUARTER_PI) * size;
ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
ctx.closePath();
break;
case 'rect':
if (!rotation) {
size = Math.SQRT1_2 * radius;
ctx.rect(x - size, y - size, 2 * size, 2 * size);
break;
}
rad += QUARTER_PI;
/* falls through */
case 'rectRot':
xOffset = Math.cos(rad) * radius;
yOffset = Math.sin(rad) * radius;
ctx.moveTo(x - xOffset, y - yOffset);
ctx.lineTo(x + yOffset, y - xOffset);
ctx.lineTo(x + xOffset, y + yOffset);
ctx.lineTo(x - yOffset, y + xOffset);
ctx.closePath();
break;
case 'crossRot':
rad += QUARTER_PI;
/* falls through */
case 'cross':
xOffset = Math.cos(rad) * radius;
yOffset = Math.sin(rad) * radius;
ctx.moveTo(x - xOffset, y - yOffset);
ctx.lineTo(x + xOffset, y + yOffset);
ctx.moveTo(x + yOffset, y - xOffset);
ctx.lineTo(x - yOffset, y + xOffset);
break;
case 'star':
xOffset = Math.cos(rad) * radius;
yOffset = Math.sin(rad) * radius;
ctx.moveTo(x - xOffset, y - yOffset);
ctx.lineTo(x + xOffset, y + yOffset);
ctx.moveTo(x + yOffset, y - xOffset);
ctx.lineTo(x - yOffset, y + xOffset);
rad += QUARTER_PI;
xOffset = Math.cos(rad) * radius;
yOffset = Math.sin(rad) * radius;
ctx.moveTo(x - xOffset, y - yOffset);
ctx.lineTo(x + xOffset, y + yOffset);
ctx.moveTo(x + yOffset, y - xOffset);
ctx.lineTo(x - yOffset, y + xOffset);
break;
case 'line':
xOffset = Math.cos(rad) * radius;
yOffset = Math.sin(rad) * radius;
ctx.moveTo(x - xOffset, y - yOffset);
ctx.lineTo(x + xOffset, y + yOffset);
break;
case 'dash':
ctx.moveTo(x, y);
ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
break;
}
ctx.fill();
ctx.stroke();
},
/**
* Returns true if the point is inside the rectangle
* @param {object} point - The point to test
* @param {object} area - The rectangle
* @returns {boolean}
* @private
*/
_isPointInArea: function(point, area) {
var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
return point.x > area.left - epsilon && point.x < area.right + epsilon &&
point.y > area.top - epsilon && point.y < area.bottom + epsilon;
},
clipArea: function(ctx, area) {
ctx.save();
ctx.beginPath();
ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
ctx.clip();
},
unclipArea: function(ctx) {
ctx.restore();
},
lineTo: function(ctx, previous, target, flip) {
var stepped = target.steppedLine;
if (stepped) {
if (stepped === 'middle') {
var midpoint = (previous.x + target.x) / 2.0;
ctx.lineTo(midpoint, flip ? target.y : previous.y);
ctx.lineTo(midpoint, flip ? previous.y : target.y);
} else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) {
ctx.lineTo(previous.x, target.y);
} else {
ctx.lineTo(target.x, previous.y);
}
ctx.lineTo(target.x, target.y);
return;
}
if (!target.tension) {
ctx.lineTo(target.x, target.y);
return;
}
ctx.bezierCurveTo(
flip ? previous.controlPointPreviousX : previous.controlPointNextX,
flip ? previous.controlPointPreviousY : previous.controlPointNextY,
flip ? target.controlPointNextX : target.controlPointPreviousX,
flip ? target.controlPointNextY : target.controlPointPreviousY,
target.x,
target.y);
}
};
var helpers_canvas = exports$1;
// DEPRECATIONS
/**
* Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
* @namespace Chart.helpers.clear
* @deprecated since version 2.7.0
* @todo remove at version 3
* @private
*/
helpers_core.clear = exports$1.clear;
/**
* Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
* @namespace Chart.helpers.drawRoundedRectangle
* @deprecated since version 2.7.0
* @todo remove at version 3
* @private
*/
helpers_core.drawRoundedRectangle = function(ctx) {
ctx.beginPath();
exports$1.roundedRect.apply(exports$1, arguments);
};
var defaults = {
/**
* @private
*/
_set: function(scope, values) {
return helpers_core.merge(this[scope] || (this[scope] = {}), values);
}
};
defaults._set('global', {
defaultColor: 'rgba(0,0,0,0.1)',
defaultFontColor: '#666',
defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
defaultFontSize: 12,
defaultFontStyle: 'normal',
defaultLineHeight: 1.2,
showLines: true
});
var core_defaults = defaults;
var valueOrDefault = helpers_core.valueOrDefault;
/**
* Converts the given font object into a CSS font string.
* @param {object} font - A font object.
* @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
* @private
*/
function toFontString(font) {
if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) {
return null;
}
return (font.style ? font.style + ' ' : '')
+ (font.weight ? font.weight + ' ' : '')
+ font.size + 'px '
+ font.family;
}
/**
* @alias Chart.helpers.options
* @namespace
*/
var helpers_options = {
/**
* Converts the given line height `value` in pixels for a specific font `size`.
* @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
* @param {number} size - The font size (in pixels) used to resolve relative `value`.
* @returns {number} The effective line height in pixels (size * 1.2 if value is invalid).
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
* @since 2.7.0
*/
toLineHeight: function(value, size) {
var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
if (!matches || matches[1] === 'normal') {
return size * 1.2;
}
value = +matches[2];
switch (matches[3]) {
case 'px':
return value;
case '%':
value /= 100;
break;
default:
break;
}
return size * value;
},
/**
* Converts the given value into a padding object with pre-computed width/height.
* @param {number|object} value - If a number, set the value to all TRBL component,
* else, if and object, use defined properties and sets undefined ones to 0.
* @returns {object} The padding values (top, right, bottom, left, width, height)
* @since 2.7.0
*/
toPadding: function(value) {
var t, r, b, l;
if (helpers_core.isObject(value)) {
t = +value.top || 0;
r = +value.right || 0;
b = +value.bottom || 0;
l = +value.left || 0;
} else {
t = r = b = l = +value || 0;
}
return {
top: t,
right: r,
bottom: b,
left: l,
height: t + b,
width: l + r
};
},
/**
* Parses font options and returns the font object.
* @param {object} options - A object that contains font options to be parsed.
* @return {object} The font object.
* @todo Support font.* options and renamed to toFont().
* @private
*/
_parseFont: function(options) {
var globalDefaults = core_defaults.global;
var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
var font = {
family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
size: size,
style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
weight: null,
string: ''
};
font.string = toFontString(font);
return font;
},
/**
* Evaluates the given `inputs` sequentially and returns the first defined value.
* @param {Array} inputs - An array of values, falling back to the last value.
* @param {object} [context] - If defined and the current value is a function, the value
* is called with `context` as first argument and the result becomes the new input.
* @param {number} [index] - If defined and the current value is an array, the value
* at `index` become the new input.
* @since 2.7.0
*/
resolve: function(inputs, context, index) {
var i, ilen, value;
for (i = 0, ilen = inputs.length; i < ilen; ++i) {
value = inputs[i];
if (value === undefined) {
continue;
}
if (context !== undefined && typeof value === 'function') {
value = value(context);
}
if (index !== undefined && helpers_core.isArray(value)) {
value = value[index];
}
if (value !== undefined) {
return value;
}
}
}
};
var helpers$1 = helpers_core;
var easing = helpers_easing;
var canvas = helpers_canvas;
var options = helpers_options;
helpers$1.easing = easing;
helpers$1.canvas = canvas;
helpers$1.options = options;
function interpolate(start, view, model, ease) {
var keys = Object.keys(model);
var i, ilen, key, actual, origin, target, type, c0, c1;
for (i = 0, ilen = keys.length; i < ilen; ++i) {
key = keys[i];
target = model[key];
// if a value is added to the model after pivot() has been called, the view
// doesn't contain it, so let's initialize the view to the target value.
if (!view.hasOwnProperty(key)) {
view[key] = target;
}
actual = view[key];
if (actual === target || key[0] === '_') {
continue;
}
if (!start.hasOwnProperty(key)) {
start[key] = actual;
}
origin = start[key];
type = typeof target;
if (type === typeof origin) {
if (type === 'string') {
c0 = chartjsColor(origin);
if (c0.valid) {
c1 = chartjsColor(target);
if (c1.valid) {
view[key] = c1.mix(c0, ease).rgbString();
continue;
}
}
} else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) {
view[key] = origin + (target - origin) * ease;
continue;
}
}
view[key] = target;
}
}
var Element = function(configuration) {
helpers$1.extend(this, configuration);
this.initialize.apply(this, arguments);
};
helpers$1.extend(Element.prototype, {
initialize: function() {
this.hidden = false;
},
pivot: function() {
var me = this;
if (!me._view) {
me._view = helpers$1.clone(me._model);
}
me._start = {};
return me;
},
transition: function(ease) {
var me = this;
var model = me._model;
var start = me._start;
var view = me._view;
// No animation -> No Transition
if (!model || ease === 1) {
me._view = model;
me._start = null;
return me;
}
if (!view) {
view = me._view = {};
}
if (!start) {
start = me._start = {};
}
interpolate(start, view, model, ease);
return me;
},
tooltipPosition: function() {
return {
x: this._model.x,
y: this._model.y
};
},
hasValue: function() {
return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);
}
});
Element.extend = helpers$1.inherits;
var core_element = Element;
var exports$2 = core_element.extend({
chart: null, // the animation associated chart instance
currentStep: 0, // the current animation step
numSteps: 60, // default number of steps
easing: '', // the easing to use for this animation
render: null, // render function used by the animation service
onAnimationProgress: null, // user specified callback to fire on each step of the animation
onAnimationComplete: null, // user specified callback to fire when the animation finishes
});
var core_animation = exports$2;
// DEPRECATIONS
/**
* Provided for backward compatibility, use Chart.Animation instead
* @prop Chart.Animation#animationObject
* @deprecated since version 2.6.0
* @todo remove at version 3
*/
Object.defineProperty(exports$2.prototype, 'animationObject', {
get: function() {
return this;
}
});
/**
* Provided for backward compatibility, use Chart.Animation#chart instead
* @prop Chart.Animation#chartInstance
* @deprecated since version 2.6.0
* @todo remove at version 3
*/
Object.defineProperty(exports$2.prototype, 'chartInstance', {
get: function() {
return this.chart;
},
set: function(value) {
this.chart = value;
}
});
core_defaults._set('global', {
animation: {
duration: 1000,
easing: 'easeOutQuart',
onProgress: helpers$1.noop,
onComplete: helpers$1.noop
}
});
var core_animations = {
animations: [],
request: null,
/**
* @param {Chart} chart - The chart to animate.
* @param {Chart.Animation} animation - The animation that we will animate.
* @param {number} duration - The animation duration in ms.
* @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
*/
addAnimation: function(chart, animation, duration, lazy) {
var animations = this.animations;
var i, ilen;
animation.chart = chart;
animation.startTime = Date.now();
animation.duration = duration;
if (!lazy) {
chart.animating = true;
}
for (i = 0, ilen = animations.length; i < ilen; ++i) {
if (animations[i].chart === chart) {
animations[i] = animation;
return;
}
}
animations.push(animation);
// If there are no animations queued, manually kickstart a digest, for lack of a better word
if (animations.length === 1) {
this.requestAnimationFrame();
}
},
cancelAnimation: function(chart) {
var index = helpers$1.findIndex(this.animations, function(animation) {
return animation.chart === chart;
});
if (index !== -1) {
this.animations.splice(index, 1);
chart.animating = false;
}
},
requestAnimationFrame: function() {
var me = this;
if (me.request === null) {
// Skip animation frame requests until the active one is executed.
// This can happen when processing mouse events, e.g. 'mousemove'
// and 'mouseout' events will trigger multiple renders.
me.request = helpers$1.requestAnimFrame.call(window, function() {
me.request = null;
me.startDigest();
});
}
},
/**
* @private
*/
startDigest: function() {
var me = this;
me.advance();
// Do we have more stuff to animate?
if (me.animations.length > 0) {
me.requestAnimationFrame();
}
},
/**
* @private
*/
advance: function() {
var animations = this.animations;
var animation, chart, numSteps, nextStep;
var i = 0;
// 1 animation per chart, so we are looping charts here
while (i < animations.length) {
animation = animations[i];
chart = animation.chart;
numSteps = animation.numSteps;
// Make sure that currentStep starts at 1
// https://github.com/chartjs/Chart.js/issues/6104
nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1;
animation.currentStep = Math.min(nextStep, numSteps);
helpers$1.callback(animation.render, [chart, animation], chart);
helpers$1.callback(animation.onAnimationProgress, [animation], chart);
if (animation.currentStep >= numSteps) {
helpers$1.callback(animation.onAnimationComplete, [animation], chart);
chart.animating = false;
animations.splice(i, 1);
} else {
++i;
}
}
}
};
var resolve = helpers$1.options.resolve;
var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
/**
* Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
* 'unshift') and notify the listener AFTER the array has been altered. Listeners are
* called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
*/
function listenArrayEvents(array, listener) {
if (array._chartjs) {
array._chartjs.listeners.push(listener);
return;
}
Object.defineProperty(array, '_chartjs', {
configurable: true,
enumerable: false,
value: {
listeners: [listener]
}
});
arrayEvents.forEach(function(key) {
var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
var base = array[key];
Object.defineProperty(array, key, {
configurable: true,
enumerable: false,
value: function() {
var args = Array.prototype.slice.call(arguments);
var res = base.apply(this, args);
helpers$1.each(array._chartjs.listeners, function(object) {
if (typeof object[method] === 'function') {
object[method].apply(object, args);
}
});
return res;
}
});
});
}
/**
* Removes the given array event listener and cleanup extra attached properties (such as
* the _chartjs stub and overridden methods) if array doesn't have any more listeners.
*/
function unlistenArrayEvents(array, listener) {
var stub = array._chartjs;
if (!stub) {
return;
}
var listeners = stub.listeners;
var index = listeners.indexOf(listener);
if (index !== -1) {
listeners.splice(index, 1);
}
if (listeners.length > 0) {
return;
}
arrayEvents.forEach(function(key) {
delete array[key];
});
delete array._chartjs;
}
// Base class for all dataset controllers (line, bar, etc)
var DatasetController = function(chart, datasetIndex) {
this.initialize(chart, datasetIndex);
};
helpers$1.extend(DatasetController.prototype, {
/**
* Element type used to generate a meta dataset (e.g. Chart.element.Line).
* @type {Chart.core.element}
*/
datasetElementType: null,
/**
* Element type used to generate a meta data (e.g. Chart.element.Point).
* @type {Chart.core.element}
*/
dataElementType: null,
initialize: function(chart, datasetIndex) {
var me = this;
me.chart = chart;
me.index = datasetIndex;
me.linkScales();
me.addElements();
},
updateIndex: function(datasetIndex) {
this.index = datasetIndex;
},
linkScales: function() {
var me = this;
var meta = me.getMeta();
var dataset = me.getDataset();
if (meta.xAxisID === null || !(meta.xAxisID in me.chart.scales)) {
meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id;
}
if (meta.yAxisID === null || !(meta.yAxisID in me.chart.scales)) {
meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id;
}
},
getDataset: function() {
return this.chart.data.datasets[this.index];
},
getMeta: function() {
return this.chart.getDatasetMeta(this.index);
},
getScaleForId: function(scaleID) {
return this.chart.scales[scaleID];
},
/**
* @private
*/
_getValueScaleId: function() {
return this.getMeta().yAxisID;
},
/**
* @private
*/
_getIndexScaleId: function() {
return this.getMeta().xAxisID;
},
/**
* @private
*/
_getValueScale: function() {
return this.getScaleForId(this._getValueScaleId());
},
/**
* @private
*/
_getIndexScale: function() {
return this.getScaleForId(this._getIndexScaleId());
},
reset: function() {
this.update(true);
},
/**
* @private
*/
destroy: function() {
if (this._data) {
unlistenArrayEvents(this._data, this);
}
},
createMetaDataset: function() {
var me = this;
var type = me.datasetElementType;
return type && new type({
_chart: me.chart,
_datasetIndex: me.index
});
},
createMetaData: function(index) {
var me = this;
var type = me.dataElementType;
return type && new type({
_chart: me.chart,
_datasetIndex: me.index,
_index: index
});
},
addElements: function() {
var me = this;
var meta = me.getMeta();
var data = me.getDataset().data || [];
var metaData = meta.data;
var i, ilen;
for (i = 0, ilen = data.length; i < ilen; ++i) {
metaData[i] = metaData[i] || me.createMetaData(i);
}
meta.dataset = meta.dataset || me.createMetaDataset();
},
addElementAndReset: function(index) {
var element = this.createMetaData(index);
this.getMeta().data.splice(index, 0, element);
this.updateElement(element, index, true);
},
buildOrUpdateElements: function() {
var me = this;
var dataset = me.getDataset();
var data = dataset.data || (dataset.data = []);
// In order to correctly handle data addition/deletion animation (an thus simulate
// real-time charts), we need to monitor these data modifications and synchronize
// the internal meta data accordingly.
if (me._data !== data) {
if (me._data) {
// This case happens when the user replaced the data array instance.
unlistenArrayEvents(me._data, me);
}
if (data && Object.isExtensible(data)) {
listenArrayEvents(data, me);
}
me._data = data;
}
// Re-sync meta data in case the user replaced the data array or if we missed
// any updates and so make sure that we handle number of datapoints changing.
me.resyncElements();
},
update: helpers$1.noop,
transition: function(easingValue) {
var meta = this.getMeta();
var elements = meta.data || [];
var ilen = elements.length;
var i = 0;
for (; i < ilen; ++i) {
elements[i].transition(easingValue);
}
if (meta.dataset) {
meta.dataset.transition(easingValue);
}
},
draw: function() {
var meta = this.getMeta();
var elements = meta.data || [];
var ilen = elements.length;
var i = 0;
if (meta.dataset) {
meta.dataset.draw();
}
for (; i < ilen; ++i) {
elements[i].draw();
}
},
removeHoverStyle: function(element) {
helpers$1.merge(element._model, element.$previousStyle || {});
delete element.$previousStyle;
},
setHoverStyle: function(element) {
var dataset = this.chart.data.datasets[element._datasetIndex];
var index = element._index;
var custom = element.custom || {};
var model = element._model;
var getHoverColor = helpers$1.getHoverColor;
element.$previousStyle = {
backgroundColor: model.backgroundColor,
borderColor: model.borderColor,
borderWidth: model.borderWidth
};
model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
},
/**
* @private
*/
resyncElements: function() {
var me = this;
var meta = me.getMeta();
var data = me.getDataset().data;
var numMeta = meta.data.length;
var numData = data.length;
if (numData < numMeta) {
meta.data.splice(numData, numMeta - numData);
} else if (numData > numMeta) {
me.insertElements(numMeta, numData - numMeta);
}
},
/**
* @private
*/
insertElements: function(start, count) {
for (var i = 0; i < count; ++i) {
this.addElementAndReset(start + i);
}
},
/**
* @private
*/
onDataPush: function() {
var count = arguments.length;
this.insertElements(this.getDataset().data.length - count, count);
},
/**
* @private
*/
onDataPop: function() {
this.getMeta().data.pop();
},
/**
* @private
*/
onDataShift: function() {
this.getMeta().data.shift();
},
/**
* @private
*/
onDataSplice: function(start, count) {
this.getMeta().data.splice(start, count);
this.insertElements(start, arguments.length - 2);
},
/**
* @private
*/
onDataUnshift: function() {
this.insertElements(0, arguments.length);
}
});
DatasetController.extend = helpers$1.inherits;
var core_datasetController = DatasetController;
core_defaults._set('global', {
elements: {
arc: {
backgroundColor: core_defaults.global.defaultColor,
borderColor: '#fff',
borderWidth: 2,
borderAlign: 'center'
}
}
});
var element_arc = core_element.extend({
inLabelRange: function(mouseX) {
var vm = this._view;
if (vm) {
return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
}
return false;
},
inRange: function(chartX, chartY) {
var vm = this._view;
if (vm) {
var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY});
var angle = pointRelativePosition.angle;
var distance = pointRelativePosition.distance;
// Sanitise angle range
var startAngle = vm.startAngle;
var endAngle = vm.endAngle;
while (endAngle < startAngle) {
endAngle += 2.0 * Math.PI;
}
while (angle > endAngle) {
angle -= 2.0 * Math.PI;
}
while (angle < startAngle) {
angle += 2.0 * Math.PI;
}
// Check if within the range of the open/close angle
var betweenAngles = (angle >= startAngle && angle <= endAngle);
var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
return (betweenAngles && withinRadius);
}
return false;
},
getCenterPoint: function() {
var vm = this._view;
var halfAngle = (vm.startAngle + vm.endAngle) / 2;
var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
return {
x: vm.x + Math.cos(halfAngle) * halfRadius,
y: vm.y + Math.sin(halfAngle) * halfRadius
};
},
getArea: function() {
var vm = this._view;
return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
},
tooltipPosition: function() {
var vm = this._view;
var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
return {
x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
};
},
draw: function() {
var ctx = this._chart.ctx;
var vm = this._view;
var sA = vm.startAngle;
var eA = vm.endAngle;
var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;
var angleMargin;
ctx.save();
ctx.beginPath();
ctx.arc(vm.x, vm.y, Math.max(vm.outerRadius - pixelMargin, 0), sA, eA);
ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
ctx.closePath();
ctx.fillStyle = vm.backgroundColor;
ctx.fill();
if (vm.borderWidth) {
if (vm.borderAlign === 'inner') {
// Draw an inner border by cliping the arc and drawing a double-width border
// Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
ctx.beginPath();
angleMargin = pixelMargin / vm.outerRadius;
ctx.arc(vm.x, vm.y, vm.outerRadius, sA - angleMargin, eA + angleMargin);
if (vm.innerRadius > pixelMargin) {
angleMargin = pixelMargin / vm.innerRadius;
ctx.arc(vm.x, vm.y, vm.innerRadius - pixelMargin, eA + angleMargin, sA - angleMargin, true);
} else {
ctx.arc(vm.x, vm.y, pixelMargin, eA + Math.PI / 2, sA - Math.PI / 2);
}
ctx.closePath();
ctx.clip();
ctx.beginPath();
ctx.arc(vm.x, vm.y, vm.outerRadius, sA, eA);
ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
ctx.closePath();
ctx.lineWidth = vm.borderWidth * 2;
ctx.lineJoin = 'round';
} else {
ctx.lineWidth = vm.borderWidth;
ctx.lineJoin = 'bevel';
}
ctx.strokeStyle = vm.borderColor;
ctx.stroke();
}
ctx.restore();
}
});
var valueOrDefault$1 = helpers$1.valueOrDefault;
var defaultColor = core_defaults.global.defaultColor;
core_defaults._set('global', {
elements: {
line: {
tension: 0.4,
backgroundColor: defaultColor,
borderWidth: 3,
borderColor: defaultColor,
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
capBezierPoints: true,
fill: true, // do we fill in the area between the line and its base axis
}
}
});
var element_line = core_element.extend({
draw: function() {
var me = this;
var vm = me._view;
var ctx = me._chart.ctx;
var spanGaps = vm.spanGaps;
var points = me._children.slice(); // clone array
var globalDefaults = core_defaults.global;
var globalOptionLineElements = globalDefaults.elements.line;
var lastDrawnIndex = -1;
var index, current, previous, currentVM;
// If we are looping, adding the first point again
if (me._loop && points.length) {
points.push(points[0]);
}
ctx.save();
// Stroke Line Options
ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
// IE 9 and 10 do not support line dash
if (ctx.setLineDash) {
ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
}
ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth);
ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
// Stroke Line
ctx.beginPath();
lastDrawnIndex = -1;
for (index = 0; index < points.length; ++index) {
current = points[index];
previous = helpers$1.previousItem(points, index);
currentVM = current._view;
// First point moves to it's starting position no matter what
if (index === 0) {
if (!currentVM.skip) {
ctx.moveTo(currentVM.x, currentVM.y);
lastDrawnIndex = index;
}
} else {
previous = lastDrawnIndex === -1 ? previous : points[lastDrawnIndex];
if (!currentVM.skip) {
if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
// There was a gap and this is the first point after the gap
ctx.moveTo(currentVM.x, currentVM.y);
} else {
// Line to next point
helpers$1.canvas.lineTo(ctx, previous._view, current._view);
}
lastDrawnIndex = index;
}
}
}
ctx.stroke();
ctx.restore();
}
});
var valueOrDefault$2 = helpers$1.valueOrDefault;
var defaultColor$1 = core_defaults.global.defaultColor;
core_defaults._set('global', {
elements: {
point: {
radius: 3,
pointStyle: 'circle',
backgroundColor: defaultColor$1,
borderColor: defaultColor$1,
borderWidth: 1,
// Hover
hitRadius: 1,
hoverRadius: 4,
hoverBorderWidth: 1
}
}
});
function xRange(mouseX) {
var vm = this._view;
return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
}
function yRange(mouseY) {
var vm = this._view;
return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
}
var element_point = core_element.extend({
inRange: function(mouseX, mouseY) {
var vm = this._view;
return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
},
inLabelRange: xRange,
inXRange: xRange,
inYRange: yRange,
getCenterPoint: function() {
var vm = this._view;
return {
x: vm.x,
y: vm.y
};
},
getArea: function() {
return Math.PI * Math.pow(this._view.radius, 2);
},
tooltipPosition: function() {
var vm = this._view;
return {
x: vm.x,
y: vm.y,
padding: vm.radius + vm.borderWidth
};
},
draw: function(chartArea) {
var vm = this._view;
var ctx = this._chart.ctx;
var pointStyle = vm.pointStyle;
var rotation = vm.rotation;
var radius = vm.radius;
var x = vm.x;
var y = vm.y;
var globalDefaults = core_defaults.global;
var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow
if (vm.skip) {
return;
}
// Clipping for Points.
if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) {
ctx.strokeStyle = vm.borderColor || defaultColor;
ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth);
ctx.fillStyle = vm.backgroundColor || defaultColor;
helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
}
}
});
var defaultColor$2 = core_defaults.global.defaultColor;
core_defaults._set('global', {
elements: {
rectangle: {
backgroundColor: defaultColor$2,
borderColor: defaultColor$2,
borderSkipped: 'bottom',
borderWidth: 0
}
}
});
function isVertical(vm) {
return vm && vm.width !== undefined;
}
/**
* Helper function to get the bounds of the bar regardless of the orientation
* @param bar {Chart.Element.Rectangle} the bar
* @return {Bounds} bounds of the bar
* @private
*/
function getBarBounds(vm) {
var x1, x2, y1, y2, half;
if (isVertical(vm)) {
half = vm.width / 2;
x1 = vm.x - half;
x2 = vm.x + half;
y1 = Math.min(vm.y, vm.base);
y2 = Math.max(vm.y, vm.base);
} else {
half = vm.height / 2;
x1 = Math.min(vm.x, vm.base);
x2 = Math.max(vm.x, vm.base);
y1 = vm.y - half;
y2 = vm.y + half;
}
return {
left: x1,
top: y1,
right: x2,
bottom: y2
};
}
function swap(orig, v1, v2) {
return orig === v1 ? v2 : orig === v2 ? v1 : orig;
}
function parseBorderSkipped(vm) {
var edge = vm.borderSkipped;
var res = {};
if (!edge) {
return res;
}
if (vm.horizontal) {
if (vm.base > vm.x) {
edge = swap(edge, 'left', 'right');
}
} else if (vm.base < vm.y) {
edge = swap(edge, 'bottom', 'top');
}
res[edge] = true;
return res;
}
function parseBorderWidth(vm, maxW, maxH) {
var value = vm.borderWidth;
var skip = parseBorderSkipped(vm);
var t, r, b, l;
if (helpers$1.isObject(value)) {
t = +value.top || 0;
r = +value.right || 0;
b = +value.bottom || 0;
l = +value.left || 0;
} else {
t = r = b = l = +value || 0;
}
return {
t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t,
r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r,
b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b,
l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l
};
}
function boundingRects(vm) {
var bounds = getBarBounds(vm);
var width = bounds.right - bounds.left;
var height = bounds.bottom - bounds.top;
var border = parseBorderWidth(vm, width / 2, height / 2);
return {
outer: {
x: bounds.left,
y: bounds.top,
w: width,
h: height
},
inner: {
x: bounds.left + border.l,
y: bounds.top + border.t,
w: width - border.l - border.r,
h: height - border.t - border.b
}
};
}
function inRange(vm, x, y) {
var skipX = x === null;
var skipY = y === null;
var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm);
return bounds
&& (skipX || x >= bounds.left && x <= bounds.right)
&& (skipY || y >= bounds.top && y <= bounds.bottom);
}
var element_rectangle = core_element.extend({
draw: function() {
var ctx = this._chart.ctx;
var vm = this._view;
var rects = boundingRects(vm);
var outer = rects.outer;
var inner = rects.inner;
ctx.fillStyle = vm.backgroundColor;
ctx.fillRect(outer.x, outer.y, outer.w, outer.h);
if (outer.w === inner.w && outer.h === inner.h) {
return;
}
ctx.save();
ctx.beginPath();
ctx.rect(outer.x, outer.y, outer.w, outer.h);
ctx.clip();
ctx.fillStyle = vm.borderColor;
ctx.rect(inner.x, inner.y, inner.w, inner.h);
ctx.fill('evenodd');
ctx.restore();
},
height: function() {
var vm = this._view;
return vm.base - vm.y;
},
inRange: function(mouseX, mouseY) {
return inRange(this._view, mouseX, mouseY);
},
inLabelRange: function(mouseX, mouseY) {
var vm = this._view;
return isVertical(vm)
? inRange(vm, mouseX, null)
: inRange(vm, null, mouseY);
},
inXRange: function(mouseX) {
return inRange(this._view, mouseX, null);
},
inYRange: function(mouseY) {
return inRange(this._view, null, mouseY);
},
getCenterPoint: function() {
var vm = this._view;
var x, y;
if (isVertical(vm)) {
x = vm.x;
y = (vm.y + vm.base) / 2;
} else {
x = (vm.x + vm.base) / 2;
y = vm.y;
}
return {x: x, y: y};
},
getArea: function() {
var vm = this._view;
return isVertical(vm)
? vm.width * Math.abs(vm.y - vm.base)
: vm.height * Math.abs(vm.x - vm.base);
},
tooltipPosition: function() {
var vm = this._view;
return {
x: vm.x,
y: vm.y
};
}
});
var elements = {};
var Arc = element_arc;
var Line = element_line;
var Point = element_point;
var Rectangle = element_rectangle;
elements.Arc = Arc;
elements.Line = Line;
elements.Point = Point;
elements.Rectangle = Rectangle;
var resolve$1 = helpers$1.options.resolve;
core_defaults._set('bar', {
hover: {
mode: 'label'
},
scales: {
xAxes: [{
type: 'category',
categoryPercentage: 0.8,
barPercentage: 0.9,
offset: true,
gridLines: {
offsetGridLines: true
}
}],
yAxes: [{
type: 'linear'
}]
}
});
/**
* Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
* @private
*/
function computeMinSampleSize(scale, pixels) {
var min = scale.isHorizontal() ? scale.width : scale.height;
var ticks = scale.getTicks();
var prev, curr, i, ilen;
for (i = 1, ilen = pixels.length; i < ilen; ++i) {
min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
}
for (i = 0, ilen = ticks.length; i < ilen; ++i) {
curr = scale.getPixelForTick(i);
min = i > 0 ? Math.min(min, curr - prev) : min;
prev = curr;
}
return min;
}
/**
* Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
* uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
* mode currently always generates bars equally sized (until we introduce scriptable options?).
* @private
*/
function computeFitCategoryTraits(index, ruler, options) {
var thickness = options.barThickness;
var count = ruler.stackCount;
var curr = ruler.pixels[index];
var size, ratio;
if (helpers$1.isNullOrUndef(thickness)) {
size = ruler.min * options.categoryPercentage;
ratio = options.barPercentage;
} else {
// When bar thickness is enforced, category and bar percentages are ignored.
// Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
// and deprecate barPercentage since this value is ignored when thickness is absolute.
size = thickness * count;
ratio = 1;
}
return {
chunk: size / count,
ratio: ratio,
start: curr - (size / 2)
};
}
/**
* Computes an "optimal" category that globally arranges bars side by side (no gap when
* percentage options are 1), based on the previous and following categories. This mode
* generates bars with different widths when data are not evenly spaced.
* @private
*/
function computeFlexCategoryTraits(index, ruler, options) {
var pixels = ruler.pixels;
var curr = pixels[index];
var prev = index > 0 ? pixels[index - 1] : null;
var next = index < pixels.length - 1 ? pixels[index + 1] : null;
var percent = options.categoryPercentage;
var start, size;
if (prev === null) {
// first data: its size is double based on the next point or,
// if it's also the last data, we use the scale size.
prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
}
if (next === null) {
// last data: its size is also double based on the previous point.
next = curr + curr - prev;
}
start = curr - (curr - Math.min(prev, next)) / 2 * percent;
size = Math.abs(next - prev) / 2 * percent;
return {
chunk: size / ruler.stackCount,
ratio: options.barPercentage,
start: start
};
}
var controller_bar = core_datasetController.extend({
dataElementType: elements.Rectangle,
initialize: function() {
var me = this;
var meta;
core_datasetController.prototype.initialize.apply(me, arguments);
meta = me.getMeta();
meta.stack = me.getDataset().stack;
meta.bar = true;
},
update: function(reset) {
var me = this;
var rects = me.getMeta().data;
var i, ilen;
me._ruler = me.getRuler();
for (i = 0, ilen = rects.length; i < ilen; ++i) {
me.updateElement(rects[i], i, reset);
}
},
updateElement: function(rectangle, index, reset) {
var me = this;
var meta = me.getMeta();
var dataset = me.getDataset();
var options = me._resolveElementOptions(rectangle, index);
rectangle._xScale = me.getScaleForId(meta.xAxisID);
rectangle._yScale = me.getScaleForId(meta.yAxisID);
rectangle._datasetIndex = me.index;
rectangle._index = index;
rectangle._model = {
backgroundColor: options.backgroundColor,
borderColor: options.borderColor,
borderSkipped: options.borderSkipped,
borderWidth: options.borderWidth,
datasetLabel: dataset.label,
label: me.chart.data.labels[index]
};
me._updateElementGeometry(rectangle, index, reset);
rectangle.pivot();
},
/**
* @private
*/
_updateElementGeometry: function(rectangle, index, reset) {
var me = this;
var model = rectangle._model;
var vscale = me._getValueScale();
var base = vscale.getBasePixel();
var horizontal = vscale.isHorizontal();
var ruler = me._ruler || me.getRuler();
var vpixels = me.calculateBarValuePixels(me.index, index);
var ipixels = me.calculateBarIndexPixels(me.index, index, ruler);
model.horizontal = horizontal;
model.base = reset ? base : vpixels.base;
model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
model.height = horizontal ? ipixels.size : undefined;
model.width = horizontal ? undefined : ipixels.size;
},
/**
* Returns the stacks based on groups and bar visibility.
* @param {number} [last] - The dataset index
* @returns {string[]} The list of stack IDs
* @private
*/
_getStacks: function(last) {
var me = this;
var chart = me.chart;
var scale = me._getIndexScale();
var stacked = scale.options.stacked;
var ilen = last === undefined ? chart.data.datasets.length : last + 1;
var stacks = [];
var i, meta;
for (i = 0; i < ilen; ++i) {
meta = chart.getDatasetMeta(i);
if (meta.bar && chart.isDatasetVisible(i) &&
(stacked === false ||
(stacked === true && stacks.indexOf(meta.stack) === -1) ||
(stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) {
stacks.push(meta.stack);
}
}
return stacks;
},
/**
* Returns the effective number of stacks based on groups and bar visibility.
* @private
*/
getStackCount: function() {
return this._getStacks().length;
},
/**
* Returns the stack index for the given dataset based on groups and bar visibility.
* @param {number} [datasetIndex] - The dataset index
* @param {string} [name] - The stack name to find
* @returns {number} The stack index
* @private
*/
getStackIndex: function(datasetIndex, name) {
var stacks = this._getStacks(datasetIndex);
var index = (name !== undefined)
? stacks.indexOf(name)
: -1; // indexOf returns -1 if element is not present
return (index === -1)
? stacks.length - 1
: index;
},
/**
* @private
*/
getRuler: function() {
var me = this;
var scale = me._getIndexScale();
var stackCount = me.getStackCount();
var datasetIndex = me.index;
var isHorizontal = scale.isHorizontal();
var start = isHorizontal ? scale.left : scale.top;
var end = start + (isHorizontal ? scale.width : scale.height);
var pixels = [];
var i, ilen, min;
for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
pixels.push(scale.getPixelForValue(null, i, datasetIndex));
}
min = helpers$1.isNullOrUndef(scale.options.barThickness)
? computeMinSampleSize(scale, pixels)
: -1;
return {
min: min,
pixels: pixels,
start: start,
end: end,
stackCount: stackCount,
scale: scale
};
},
/**
* Note: pixel values are not clamped to the scale area.
* @private
*/
calculateBarValuePixels: function(datasetIndex, index) {
var me = this;
var chart = me.chart;
var meta = me.getMeta();
var scale = me._getValueScale();
var isHorizontal = scale.isHorizontal();
var datasets = chart.data.datasets;
var value = +scale.getRightValue(datasets[datasetIndex].data[index]);
var minBarLength = scale.options.minBarLength;
var stacked = scale.options.stacked;
var stack = meta.stack;
var start = 0;
var i, imeta, ivalue, base, head, size;
if (stacked || (stacked === undefined && stack !== undefined)) {
for (i = 0; i < datasetIndex; ++i) {
imeta = chart.getDatasetMeta(i);
if (imeta.bar &&
imeta.stack === stack &&
imeta.controller._getValueScaleId() === scale.id &&
chart.isDatasetVisible(i)) {
ivalue = +scale.getRightValue(datasets[i].data[index]);
if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) {
start += ivalue;
}
}
}
}
base = scale.getPixelForValue(start);
head = scale.getPixelForValue(start + value);
size = head - base;
if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
size = minBarLength;
if (value >= 0 && !isHorizontal || value < 0 && isHorizontal) {
head = base - minBarLength;
} else {
head = base + minBarLength;
}
}
return {
size: size,
base: base,
head: head,
center: head + size / 2
};
},
/**
* @private
*/
calculateBarIndexPixels: function(datasetIndex, index, ruler) {
var me = this;
var options = ruler.scale.options;
var range = options.barThickness === 'flex'
? computeFlexCategoryTraits(index, ruler, options)
: computeFitCategoryTraits(index, ruler, options);
var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
var size = Math.min(
helpers$1.valueOrDefault(options.maxBarThickness, Infinity),
range.chunk * range.ratio);
return {
base: center - size / 2,
head: center + size / 2,
center: center,
size: size
};
},
draw: function() {
var me = this;
var chart = me.chart;
var scale = me._getValueScale();
var rects = me.getMeta().data;
var dataset = me.getDataset();
var ilen = rects.length;
var i = 0;
helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);
for (; i < ilen; ++i) {
if (!isNaN(scale.getRightValue(dataset.data[i]))) {
rects[i].draw();
}
}
helpers$1.canvas.unclipArea(chart.ctx);
},
/**
* @private
*/
_resolveElementOptions: function(rectangle, index) {
var me = this;
var chart = me.chart;
var datasets = chart.data.datasets;
var dataset = datasets[me.index];
var custom = rectangle.custom || {};
var options = chart.options.elements.rectangle;
var values = {};
var i, ilen, key;
// Scriptable options
var context = {
chart: chart,
dataIndex: index,
dataset: dataset,
datasetIndex: me.index
};
var keys = [
'backgroundColor',
'borderColor',
'borderSkipped',
'borderWidth'
];
for (i = 0, ilen = keys.length; i < ilen; ++i) {
key = keys[i];
values[key] = resolve$1([
custom[key],
dataset[key],
options[key]
], context, index);
}
return values;
}
});
var valueOrDefault$3 = helpers$1.valueOrDefault;
var resolve$2 = helpers$1.options.resolve;
core_defaults._set('bubble', {
hover: {
mode: 'single'
},
scales: {
xAxes: [{
type: 'linear', // bubble should probably use a linear scale by default
position: 'bottom',
id: 'x-axis-0' // need an ID so datasets can reference the scale
}],
yAxes: [{
type: 'linear',
position: 'left',
id: 'y-axis-0'
}]
},
tooltips: {
callbacks: {
title: function() {
// Title doesn't make sense for scatter since we format the data as a point
return '';
},
label: function(item, data) {
var datasetLabel = data.datasets[item.datasetIndex].label || '';
var dataPoint = data.datasets[item.datasetIndex].data[item.index];
return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
}
}
}
});
var controller_bubble = core_datasetController.extend({
/**
* @protected
*/
dataElementType: elements.Point,
/**
* @protected
*/
update: function(reset) {
var me = this;
var meta = me.getMeta();
var points = meta.data;
// Update Points
helpers$1.each(points, function(point, index) {
me.updateElement(point, index, reset);
});
},
/**
* @protected
*/
updateElement: function(point, index, reset) {
var me = this;
var meta = me.getMeta();
var custom = point.custom || {};
var xScale = me.getScaleForId(meta.xAxisID);
var yScale = me.getScaleForId(meta.yAxisID);
var options = me._resolveElementOptions(point, index);
var data = me.getDataset().data[index];
var dsIndex = me.index;
var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
point._xScale = xScale;
point._yScale = yScale;
point._options = options;
point._datasetIndex = dsIndex;
point._index = index;
point._model = {
backgroundColor: options.backgroundColor,
borderColor: options.borderColor,
borderWidth: options.borderWidth,
hitRadius: options.hitRadius,
pointStyle: options.pointStyle,
rotation: options.rotation,
radius: reset ? 0 : options.radius,
skip: custom.skip || isNaN(x) || isNaN(y),
x: x,
y: y,
};
point.pivot();
},
/**
* @protected
*/
setHoverStyle: function(point) {
var model = point._model;
var options = point._options;
var getHoverColor = helpers$1.getHoverColor;
point.$previousStyle = {
backgroundColor: model.backgroundColor,
borderColor: model.borderColor,
borderWidth: model.borderWidth,
radius: model.radius
};
model.backgroundColor = valueOrDefault$3(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
model.borderColor = valueOrDefault$3(options.hoverBorderColor, getHoverColor(options.borderColor));
model.borderWidth = valueOrDefault$3(options.hoverBorderWidth, options.borderWidth);
model.radius = options.radius + options.hoverRadius;
},
/**
* @private
*/
_resolveElementOptions: function(point, index) {
var me = this;
var chart = me.chart;
var datasets = chart.data.datasets;
var dataset = datasets[me.index];
var custom = point.custom || {};
var options = chart.options.elements.point;
var data = dataset.data[index];
var values = {};
var i, ilen, key;
// Scriptable options
var context = {
chart: chart,
dataIndex: index,
dataset: dataset,
datasetIndex: me.index
};
var keys = [
'backgroundColor',
'borderColor',
'borderWidth',
'hoverBackgroundColor',
'hoverBorderColor',
'hoverBorderWidth',
'hoverRadius',
'hitRadius',
'pointStyle',
'rotation'
];
for (i = 0, ilen = keys.length; i < ilen; ++i) {
key = keys[i];
values[key] = resolve$2([
custom[key],
dataset[key],
options[key]
], context, index);
}
// Custom radius resolution
values.radius = resolve$2([
custom.radius,
data ? data.r : undefined,
dataset.radius,
options.radius
], context, index);
return values;
}
});
var resolve$3 = helpers$1.options.resolve;
var valueOrDefault$4 = helpers$1.valueOrDefault;
core_defaults._set('doughnut', {
animation: {
// Boolean - Whether we animate the rotation of the Doughnut
animateRotate: true,
// Boolean - Whether we animate scaling the Doughnut from the centre
animateScale: false
},
hover: {
mode: 'single'
},
legendCallback: function(chart) {
var text = [];
text.push('
');
var data = chart.data;
var datasets = data.datasets;
var labels = data.labels;
if (datasets.length) {
for (var i = 0; i < datasets[0].data.length; ++i) {
text.push('
');
if (labels[i]) {
text.push(labels[i]);
}
text.push('
');
}
}
text.push('
');
return text.join('');
},
legend: {
labels: {
generateLabels: function(chart) {
var data = chart.data;
if (data.labels.length && data.datasets.length) {
return data.labels.map(function(label, i) {
var meta = chart.getDatasetMeta(0);
var ds = data.datasets[0];
var arc = meta.data[i];
var custom = arc && arc.custom || {};
var arcOpts = chart.options.elements.arc;
var fill = resolve$3([custom.backgroundColor, ds.backgroundColor, arcOpts.backgroundColor], undefined, i);
var stroke = resolve$3([custom.borderColor, ds.borderColor, arcOpts.borderColor], undefined, i);
var bw = resolve$3([custom.borderWidth, ds.borderWidth, arcOpts.borderWidth], undefined, i);
return {
text: label,
fillStyle: fill,
strokeStyle: stroke,
lineWidth: bw,
hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
// Extra data used for toggling the correct item
index: i
};
});
}
return [];
}
},
onClick: function(e, legendItem) {
var index = legendItem.index;
var chart = this.chart;
var i, ilen, meta;
for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
meta = chart.getDatasetMeta(i);
// toggle visibility of index if exists
if (meta.data[index]) {
meta.data[index].hidden = !meta.data[index].hidden;
}
}
chart.update();
}
},
// The percentage of the chart that we cut out of the middle.
cutoutPercentage: 50,
// The rotation of the chart, where the first data arc begins.
rotation: Math.PI * -0.5,
// The total circumference of the chart.
circumference: Math.PI * 2.0,
// Need to override these to give a nice default
tooltips: {
callbacks: {
title: function() {
return '';
},
label: function(tooltipItem, data) {
var dataLabel = data.labels[tooltipItem.index];
var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
if (helpers$1.isArray(dataLabel)) {
// show value on first line of multiline label
// need to clone because we are changing the value
dataLabel = dataLabel.slice();
dataLabel[0] += value;
} else {
dataLabel += value;
}
return dataLabel;
}
}
}
});
var controller_doughnut = core_datasetController.extend({
dataElementType: elements.Arc,
linkScales: helpers$1.noop,
// Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
getRingIndex: function(datasetIndex) {
var ringIndex = 0;
for (var j = 0; j < datasetIndex; ++j) {
if (this.chart.isDatasetVisible(j)) {
++ringIndex;
}
}
return ringIndex;
},
update: function(reset) {
var me = this;
var chart = me.chart;
var chartArea = chart.chartArea;
var opts = chart.options;
var availableWidth = chartArea.right - chartArea.left;
var availableHeight = chartArea.bottom - chartArea.top;
var minSize = Math.min(availableWidth, availableHeight);
var offset = {x: 0, y: 0};
var meta = me.getMeta();
var arcs = meta.data;
var cutoutPercentage = opts.cutoutPercentage;
var circumference = opts.circumference;
var chartWeight = me._getRingWeight(me.index);
var i, ilen;
// If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc
if (circumference < Math.PI * 2.0) {
var startAngle = opts.rotation % (Math.PI * 2.0);
startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0);
var endAngle = startAngle + circumference;
var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)};
var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)};
var contains0 = (startAngle <= 0 && endAngle >= 0) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle);
var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle);
var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle);
var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle);
var cutout = cutoutPercentage / 100.0;
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))};
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))};
var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5};
minSize = Math.min(availableWidth / size.width, availableHeight / size.height);
offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5};
}
for (i = 0, ilen = arcs.length; i < ilen; ++i) {
arcs[i]._options = me._resolveElementOptions(arcs[i], i);
}
chart.borderWidth = me.getMaxBorderWidth();
chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0);
chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0);
chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
chart.offsetX = offset.x * chart.outerRadius;
chart.offsetY = offset.y * chart.outerRadius;
meta.total = me.calculateTotal();
me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
for (i = 0, ilen = arcs.length; i < ilen; ++i) {
me.updateElement(arcs[i], i, reset);
}
},
updateElement: function(arc, index, reset) {
var me = this;
var chart = me.chart;
var chartArea = chart.chartArea;
var opts = chart.options;
var animationOpts = opts.animation;
var centerX = (chartArea.left + chartArea.right) / 2;
var centerY = (chartArea.top + chartArea.bottom) / 2;
var startAngle = opts.rotation; // non reset case handled later
var endAngle = opts.rotation; // non reset case handled later
var dataset = me.getDataset();
var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI));
var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
var options = arc._options || {};
helpers$1.extend(arc, {
// Utility
_datasetIndex: me.index,
_index: index,
// Desired view properties
_model: {
backgroundColor: options.backgroundColor,
borderColor: options.borderColor,
borderWidth: options.borderWidth,
borderAlign: options.borderAlign,
x: centerX + chart.offsetX,
y: centerY + chart.offsetY,
startAngle: startAngle,
endAngle: endAngle,
circumference: circumference,
outerRadius: outerRadius,
innerRadius: innerRadius,
label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
}
});
var model = arc._model;
// Set correct angles if not resetting
if (!reset || !animationOpts.animateRotate) {
if (index === 0) {
model.startAngle = opts.rotation;
} else {
model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
}
model.endAngle = model.startAngle + model.circumference;
}
arc.pivot();
},
calculateTotal: function() {
var dataset = this.getDataset();
var meta = this.getMeta();
var total = 0;
var value;
helpers$1.each(meta.data, function(element, index) {
value = dataset.data[index];
if (!isNaN(value) && !element.hidden) {
total += Math.abs(value);
}
});
/* if (total === 0) {
total = NaN;
}*/
return total;
},
calculateCircumference: function(value) {
var total = this.getMeta().total;
if (total > 0 && !isNaN(value)) {
return (Math.PI * 2.0) * (Math.abs(value) / total);
}
return 0;
},
// gets the max border or hover width to properly scale pie charts
getMaxBorderWidth: function(arcs) {
var me = this;
var max = 0;
var chart = me.chart;
var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
if (!arcs) {
// Find the outmost visible dataset
for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
if (chart.isDatasetVisible(i)) {
meta = chart.getDatasetMeta(i);
arcs = meta.data;
if (i !== me.index) {
controller = meta.controller;
}
break;
}
}
}
if (!arcs) {
return 0;
}
for (i = 0, ilen = arcs.length; i < ilen; ++i) {
arc = arcs[i];
options = controller ? controller._resolveElementOptions(arc, i) : arc._options;
if (options.borderAlign !== 'inner') {
borderWidth = options.borderWidth;
hoverWidth = options.hoverBorderWidth;
max = borderWidth > max ? borderWidth : max;
max = hoverWidth > max ? hoverWidth : max;
}
}
return max;
},
/**
* @protected
*/
setHoverStyle: function(arc) {
var model = arc._model;
var options = arc._options;
var getHoverColor = helpers$1.getHoverColor;
arc.$previousStyle = {
backgroundColor: model.backgroundColor,
borderColor: model.borderColor,
borderWidth: model.borderWidth,
};
model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor));
model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth);
},
/**
* @private
*/
_resolveElementOptions: function(arc, index) {
var me = this;
var chart = me.chart;
var dataset = me.getDataset();
var custom = arc.custom || {};
var options = chart.options.elements.arc;
var values = {};
var i, ilen, key;
// Scriptable options
var context = {
chart: chart,
dataIndex: index,
dataset: dataset,
datasetIndex: me.index
};
var keys = [
'backgroundColor',
'borderColor',
'borderWidth',
'borderAlign',
'hoverBackgroundColor',
'hoverBorderColor',
'hoverBorderWidth',
];
for (i = 0, ilen = keys.length; i < ilen; ++i) {
key = keys[i];
values[key] = resolve$3([
custom[key],
dataset[key],
options[key]
], context, index);
}
return values;
},
/**
* Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
* @private
*/
_getRingWeightOffset: function(datasetIndex) {
var ringWeightOffset = 0;
for (var i = 0; i < datasetIndex; ++i) {
if (this.chart.isDatasetVisible(i)) {
ringWeightOffset += this._getRingWeight(i);
}
}
return ringWeightOffset;
},
/**
* @private
*/
_getRingWeight: function(dataSetIndex) {
return Math.max(valueOrDefault$4(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
},
/**
* Returns the sum of all visibile data set weights. This value can be 0.
* @private
*/
_getVisibleDatasetWeightTotal: function() {
return this._getRingWeightOffset(this.chart.data.datasets.length);
}
});
core_defaults._set('horizontalBar', {
hover: {
mode: 'index',
axis: 'y'
},
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}],
yAxes: [{
type: 'category',
position: 'left',
categoryPercentage: 0.8,
barPercentage: 0.9,
offset: true,
gridLines: {
offsetGridLines: true
}
}]
},
elements: {
rectangle: {
borderSkipped: 'left'
}
},
tooltips: {
mode: 'index',
axis: 'y'
}
});
var controller_horizontalBar = controller_bar.extend({
/**
* @private
*/
_getValueScaleId: function() {
return this.getMeta().xAxisID;
},
/**
* @private
*/
_getIndexScaleId: function() {
return this.getMeta().yAxisID;
}
});
var valueOrDefault$5 = helpers$1.valueOrDefault;
var resolve$4 = helpers$1.options.resolve;
var isPointInArea = helpers$1.canvas._isPointInArea;
core_defaults._set('line', {
showLines: true,
spanGaps: false,
hover: {
mode: 'label'
},
scales: {
xAxes: [{
type: 'category',
id: 'x-axis-0'
}],
yAxes: [{
type: 'linear',
id: 'y-axis-0'
}]
}
});
function lineEnabled(dataset, options) {
return valueOrDefault$5(dataset.showLine, options.showLines);
}
var controller_line = core_datasetController.extend({
datasetElementType: elements.Line,
dataElementType: elements.Point,
update: function(reset) {
var me = this;
var meta = me.getMeta();
var line = meta.dataset;
var points = meta.data || [];
var scale = me.getScaleForId(meta.yAxisID);
var dataset = me.getDataset();
var showLine = lineEnabled(dataset, me.chart.options);
var i, ilen;
// Update Line
if (showLine) {
// Compatibility: If the properties are defined with only the old name, use those values
if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
dataset.lineTension = dataset.tension;
}
// Utility
line._scale = scale;
line._datasetIndex = me.index;
// Data
line._children = points;
// Model
line._model = me._resolveLineOptions(line);
line.pivot();
}
// Update Points
for (i = 0, ilen = points.length; i < ilen; ++i) {
me.updateElement(points[i], i, reset);
}
if (showLine && line._model.tension !== 0) {
me.updateBezierControlPoints();
}
// Now pivot the point for animation
for (i = 0, ilen = points.length; i < ilen; ++i) {
points[i].pivot();
}
},
updateElement: function(point, index, reset) {
var me = this;
var meta = me.getMeta();
var custom = point.custom || {};
var dataset = me.getDataset();
var datasetIndex = me.index;
var value = dataset.data[index];
var yScale = me.getScaleForId(meta.yAxisID);
var xScale = me.getScaleForId(meta.xAxisID);
var lineModel = meta.dataset._model;
var x, y;
var options = me._resolvePointOptions(point, index);
x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
// Utility
point._xScale = xScale;
point._yScale = yScale;
point._options = options;
point._datasetIndex = datasetIndex;
point._index = index;
// Desired view properties
point._model = {
x: x,
y: y,
skip: custom.skip || isNaN(x) || isNaN(y),
// Appearance
radius: options.radius,
pointStyle: options.pointStyle,
rotation: options.rotation,
backgroundColor: options.backgroundColor,
borderColor: options.borderColor,
borderWidth: options.borderWidth,
tension: valueOrDefault$5(custom.tension, lineModel ? lineModel.tension : 0),
steppedLine: lineModel ? lineModel.steppedLine : false,
// Tooltip
hitRadius: options.hitRadius
};
},
/**
* @private
*/
_resolvePointOptions: function(element, index) {
var me = this;
var chart = me.chart;
var dataset = chart.data.datasets[me.index];
var custom = element.custom || {};
var options = chart.options.elements.point;
var values = {};
var i, ilen, key;
// Scriptable options
var context = {
chart: chart,
dataIndex: index,
dataset: dataset,
datasetIndex: me.index
};
var ELEMENT_OPTIONS = {
backgroundColor: 'pointBackgroundColor',
borderColor: 'pointBorderColor',
borderWidth: 'pointBorderWidth',
hitRadius: 'pointHitRadius',
hoverBackgroundColor: 'pointHoverBackgroundColor',
hoverBorderColor: 'pointHoverBorderColor',
hoverBorderWidth: 'pointHoverBorderWidth',
hoverRadius: 'pointHoverRadius',
pointStyle: 'pointStyle',
radius: 'pointRadius',
rotation: 'pointRotation'
};
var keys = Object.keys(ELEMENT_OPTIONS);
for (i = 0, ilen = keys.length; i < ilen; ++i) {
key = keys[i];
values[key] = resolve$4([
custom[key],
dataset[ELEMENT_OPTIONS[key]],
dataset[key],
options[key]
], context, index);
}
return values;
},
/**
* @private
*/
_resolveLineOptions: function(element) {
var me = this;
var chart = me.chart;
var dataset = chart.data.datasets[me.index];
var custom = element.custom || {};
var options = chart.options;
var elementOptions = options.elements.line;
var values = {};
var i, ilen, key;
var keys = [
'backgroundColor',
'borderWidth',
'borderColor',
'borderCapStyle',
'borderDash',
'borderDashOffset',
'borderJoinStyle',
'fill',
'cubicInterpolationMode'
];
for (i = 0, ilen = keys.length; i < ilen; ++i) {
key = keys[i];
values[key] = resolve$4([
custom[key],
dataset[key],
elementOptions[key]
]);
}
// The default behavior of lines is to break at null values, according
// to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
// This option gives lines the ability to span gaps
values.spanGaps = valueOrDefault$5(dataset.spanGaps, options.spanGaps);
values.tension = valueOrDefault$5(dataset.lineTension, elementOptions.tension);
values.steppedLine = resolve$4([custom.steppedLine, dataset.steppedLine, elementOptions.stepped]);
return values;
},
calculatePointY: function(value, index, datasetIndex) {
var me = this;
var chart = me.chart;
var meta = me.getMeta();
var yScale = me.getScaleForId(meta.yAxisID);
var sumPos = 0;
var sumNeg = 0;
var i, ds, dsMeta;
if (yScale.options.stacked) {
for (i = 0; i < datasetIndex; i++) {
ds = chart.data.datasets[i];
dsMeta = chart.getDatasetMeta(i);
if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) {
var stackedRightValue = Number(yScale.getRightValue(ds.data[index]));
if (stackedRightValue < 0) {
sumNeg += stackedRightValue || 0;
} else {
sumPos += stackedRightValue || 0;
}
}
}
var rightValue = Number(yScale.getRightValue(value));
if (rightValue < 0) {
return yScale.getPixelForValue(sumNeg + rightValue);
}
return yScale.getPixelForValue(sumPos + rightValue);
}
return yScale.getPixelForValue(value);
},
updateBezierControlPoints: function() {
var me = this;
var chart = me.chart;
var meta = me.getMeta();
var lineModel = meta.dataset._model;
var area = chart.chartArea;
var points = meta.data || [];
var i, ilen, model, controlPoints;
// Only consider points that are drawn in case the spanGaps option is used
if (lineModel.spanGaps) {
points = points.filter(function(pt) {
return !pt._model.skip;
});
}
function capControlPoint(pt, min, max) {
return Math.max(Math.min(pt, max), min);
}
if (lineModel.cubicInterpolationMode === 'monotone') {
helpers$1.splineCurveMonotone(points);
} else {
for (i = 0, ilen = points.length; i < ilen; ++i) {
model = points[i]._model;
controlPoints = helpers$1.splineCurve(
helpers$1.previousItem(points, i)._model,
model,
helpers$1.nextItem(points, i)._model,
lineModel.tension
);
model.controlPointPreviousX = controlPoints.previous.x;
model.controlPointPreviousY = controlPoints.previous.y;
model.controlPointNextX = controlPoints.next.x;
model.controlPointNextY = controlPoints.next.y;
}
}
if (chart.options.elements.line.capBezierPoints) {
for (i = 0, ilen = points.length; i < ilen; ++i) {
model = points[i]._model;
if (isPointInArea(model, area)) {
if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
}
if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
}
}
}
}
},
draw: function() {
var me = this;
var chart = me.chart;
var meta = me.getMeta();
var points = meta.data || [];
var area = chart.chartArea;
var ilen = points.length;
var halfBorderWidth;
var i = 0;
if (lineEnabled(me.getDataset(), chart.options)) {
halfBorderWidth = (meta.dataset._model.borderWidth || 0) / 2;
helpers$1.canvas.clipArea(chart.ctx, {
left: area.left,
right: area.right,
top: area.top - halfBorderWidth,
bottom: area.bottom + halfBorderWidth
});
meta.dataset.draw();
helpers$1.canvas.unclipArea(chart.ctx);
}
// Draw the points
for (; i < ilen; ++i) {
points[i].draw(area);
}
},
/**
* @protected
*/
setHoverStyle: function(point) {
var model = point._model;
var options = point._options;
var getHoverColor = helpers$1.getHoverColor;
point.$previousStyle = {
backgroundColor: model.backgroundColor,
borderColor: model.borderColor,
borderWidth: model.borderWidth,
radius: model.radius
};
model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor));
model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth);
model.radius = valueOrDefault$5(options.hoverRadius, options.radius);
},
});
var resolve$5 = helpers$1.options.resolve;
core_defaults._set('polarArea', {
scale: {
type: 'radialLinear',
angleLines: {
display: false
},
gridLines: {
circular: true
},
pointLabels: {
display: false
},
ticks: {
beginAtZero: true
}
},
// Boolean - Whether to animate the rotation of the chart
animation: {
animateRotate: true,
animateScale: true
},
startAngle: -0.5 * Math.PI,
legendCallback: function(chart) {
var text = [];
text.push('
');
var data = chart.data;
var datasets = data.datasets;
var labels = data.labels;
if (datasets.length) {
for (var i = 0; i < datasets[0].data.length; ++i) {
text.push('
');
if (labels[i]) {
text.push(labels[i]);
}
text.push('
');
for (var i = 0; i < chart.data.datasets.length; i++) {
text.push('
');
if (chart.data.datasets[i].label) {
text.push(chart.data.datasets[i].label);
}
text.push('
');
}
text.push('
');
return text.join('');
}
});
/**
* Helper function to get the box width based on the usePointStyle option
* @param {object} labelopts - the label options on the legend
* @param {number} fontSize - the label font size
* @return {number} width of the color box area
*/
function getBoxWidth(labelOpts, fontSize) {
return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ?
fontSize :
labelOpts.boxWidth;
}
/**
* IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
*/
var Legend = core_element.extend({
initialize: function(config) {
helpers$1.extend(this, config);
// Contains hit boxes for each dataset (in dataset order)
this.legendHitBoxes = [];
/**
* @private
*/
this._hoveredItem = null;
// Are we in doughnut mode which has a different data type
this.doughnutMode = false;
},
// These methods are ordered by lifecycle. Utilities then follow.
// Any function defined here is inherited by all legend types.
// Any function can be extended by the legend type
beforeUpdate: noop$1,
update: function(maxWidth, maxHeight, margins) {
var me = this;
// Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
me.beforeUpdate();
// Absorb the master measurements
me.maxWidth = maxWidth;
me.maxHeight = maxHeight;
me.margins = margins;
// Dimensions
me.beforeSetDimensions();
me.setDimensions();
me.afterSetDimensions();
// Labels
me.beforeBuildLabels();
me.buildLabels();
me.afterBuildLabels();
// Fit
me.beforeFit();
me.fit();
me.afterFit();
//
me.afterUpdate();
return me.minSize;
},
afterUpdate: noop$1,
//
beforeSetDimensions: noop$1,
setDimensions: function() {
var me = this;
// Set the unconstrained dimension before label rotation
if (me.isHorizontal()) {
// Reset position before calculating rotation
me.width = me.maxWidth;
me.left = 0;
me.right = me.width;
} else {
me.height = me.maxHeight;
// Reset position before calculating rotation
me.top = 0;
me.bottom = me.height;
}
// Reset padding
me.paddingLeft = 0;
me.paddingTop = 0;
me.paddingRight = 0;
me.paddingBottom = 0;
// Reset minSize
me.minSize = {
width: 0,
height: 0
};
},
afterSetDimensions: noop$1,
//
beforeBuildLabels: noop$1,
buildLabels: function() {
var me = this;
var labelOpts = me.options.labels || {};
var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];
if (labelOpts.filter) {
legendItems = legendItems.filter(function(item) {
return labelOpts.filter(item, me.chart.data);
});
}
if (me.options.reverse) {
legendItems.reverse();
}
me.legendItems = legendItems;
},
afterBuildLabels: noop$1,
//
beforeFit: noop$1,
fit: function() {
var me = this;
var opts = me.options;
var labelOpts = opts.labels;
var display = opts.display;
var ctx = me.ctx;
var labelFont = helpers$1.options._parseFont(labelOpts);
var fontSize = labelFont.size;
// Reset hit boxes
var hitboxes = me.legendHitBoxes = [];
var minSize = me.minSize;
var isHorizontal = me.isHorizontal();
if (isHorizontal) {
minSize.width = me.maxWidth; // fill all the width
minSize.height = display ? 10 : 0;
} else {
minSize.width = display ? 10 : 0;
minSize.height = me.maxHeight; // fill all the height
}
// Increase sizes here
if (display) {
ctx.font = labelFont.string;
if (isHorizontal) {
// Labels
// Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
var lineWidths = me.lineWidths = [0];
var totalHeight = 0;
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
helpers$1.each(me.legendItems, function(legendItem, i) {
var boxWidth = getBoxWidth(labelOpts, fontSize);
var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
if (i === 0 || lineWidths[lineWidths.length - 1] + width + labelOpts.padding > minSize.width) {
totalHeight += fontSize + labelOpts.padding;
lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = labelOpts.padding;
}
// Store the hitbox width and height here. Final position will be updated in `draw`
hitboxes[i] = {
left: 0,
top: 0,
width: width,
height: fontSize
};
lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
});
minSize.height += totalHeight;
} else {
var vPadding = labelOpts.padding;
var columnWidths = me.columnWidths = [];
var totalWidth = labelOpts.padding;
var currentColWidth = 0;
var currentColHeight = 0;
var itemHeight = fontSize + vPadding;
helpers$1.each(me.legendItems, function(legendItem, i) {
var boxWidth = getBoxWidth(labelOpts, fontSize);
var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
// If too tall, go to new column
if (i > 0 && currentColHeight + itemHeight > minSize.height - vPadding) {
totalWidth += currentColWidth + labelOpts.padding;
columnWidths.push(currentColWidth); // previous column width
currentColWidth = 0;
currentColHeight = 0;
}
// Get max width
currentColWidth = Math.max(currentColWidth, itemWidth);
currentColHeight += itemHeight;
// Store the hitbox width and height here. Final position will be updated in `draw`
hitboxes[i] = {
left: 0,
top: 0,
width: itemWidth,
height: fontSize
};
});
totalWidth += currentColWidth;
columnWidths.push(currentColWidth);
minSize.width += totalWidth;
}
}
me.width = minSize.width;
me.height = minSize.height;
},
afterFit: noop$1,
// Shared Methods
isHorizontal: function() {
return this.options.position === 'top' || this.options.position === 'bottom';
},
// Actually draw the legend on the canvas
draw: function() {
var me = this;
var opts = me.options;
var labelOpts = opts.labels;
var globalDefaults = core_defaults.global;
var defaultColor = globalDefaults.defaultColor;
var lineDefault = globalDefaults.elements.line;
var legendWidth = me.width;
var lineWidths = me.lineWidths;
if (opts.display) {
var ctx = me.ctx;
var fontColor = valueOrDefault$d(labelOpts.fontColor, globalDefaults.defaultFontColor);
var labelFont = helpers$1.options._parseFont(labelOpts);
var fontSize = labelFont.size;
var cursor;
// Canvas setup
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
ctx.lineWidth = 0.5;
ctx.strokeStyle = fontColor; // for strikethrough effect
ctx.fillStyle = fontColor; // render in correct colour
ctx.font = labelFont.string;
var boxWidth = getBoxWidth(labelOpts, fontSize);
var hitboxes = me.legendHitBoxes;
// current position
var drawLegendBox = function(x, y, legendItem) {
if (isNaN(boxWidth) || boxWidth <= 0) {
return;
}
// Set the ctx for the box
ctx.save();
var lineWidth = valueOrDefault$d(legendItem.lineWidth, lineDefault.borderWidth);
ctx.fillStyle = valueOrDefault$d(legendItem.fillStyle, defaultColor);
ctx.lineCap = valueOrDefault$d(legendItem.lineCap, lineDefault.borderCapStyle);
ctx.lineDashOffset = valueOrDefault$d(legendItem.lineDashOffset, lineDefault.borderDashOffset);
ctx.lineJoin = valueOrDefault$d(legendItem.lineJoin, lineDefault.borderJoinStyle);
ctx.lineWidth = lineWidth;
ctx.strokeStyle = valueOrDefault$d(legendItem.strokeStyle, defaultColor);
if (ctx.setLineDash) {
// IE 9 and 10 do not support line dash
ctx.setLineDash(valueOrDefault$d(legendItem.lineDash, lineDefault.borderDash));
}
if (opts.labels && opts.labels.usePointStyle) {
// Recalculate x and y for drawPoint() because its expecting
// x and y to be center of figure (instead of top left)
var radius = boxWidth * Math.SQRT2 / 2;
var centerX = x + boxWidth / 2;
var centerY = y + fontSize / 2;
// Draw pointStyle as legend symbol
helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY);
} else {
// Draw box as legend symbol
if (lineWidth !== 0) {
ctx.strokeRect(x, y, boxWidth, fontSize);
}
ctx.fillRect(x, y, boxWidth, fontSize);
}
ctx.restore();
};
var fillText = function(x, y, legendItem, textWidth) {
var halfFontSize = fontSize / 2;
var xLeft = boxWidth + halfFontSize + x;
var yMiddle = y + halfFontSize;
ctx.fillText(legendItem.text, xLeft, yMiddle);
if (legendItem.hidden) {
// Strikethrough the text if hidden
ctx.beginPath();
ctx.lineWidth = 2;
ctx.moveTo(xLeft, yMiddle);
ctx.lineTo(xLeft + textWidth, yMiddle);
ctx.stroke();
}
};
// Horizontal
var isHorizontal = me.isHorizontal();
if (isHorizontal) {
cursor = {
x: me.left + ((legendWidth - lineWidths[0]) / 2) + labelOpts.padding,
y: me.top + labelOpts.padding,
line: 0
};
} else {
cursor = {
x: me.left + labelOpts.padding,
y: me.top + labelOpts.padding,
line: 0
};
}
var itemHeight = fontSize + labelOpts.padding;
helpers$1.each(me.legendItems, function(legendItem, i) {
var textWidth = ctx.measureText(legendItem.text).width;
var width = boxWidth + (fontSize / 2) + textWidth;
var x = cursor.x;
var y = cursor.y;
// Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
// instead of me.right and me.bottom because me.width and me.height
// may have been changed since me.minSize was calculated
if (isHorizontal) {
if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
y = cursor.y += itemHeight;
cursor.line++;
x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2) + labelOpts.padding;
}
} else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {
x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
y = cursor.y = me.top + labelOpts.padding;
cursor.line++;
}
drawLegendBox(x, y, legendItem);
hitboxes[i].left = x;
hitboxes[i].top = y;
// Fill the actual label
fillText(x, y, legendItem, textWidth);
if (isHorizontal) {
cursor.x += width + labelOpts.padding;
} else {
cursor.y += itemHeight;
}
});
}
},
/**
* @private
*/
_getLegendItemAt: function(x, y) {
var me = this;
var i, hitBox, lh;
if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
// See if we are touching one of the dataset boxes
lh = me.legendHitBoxes;
for (i = 0; i < lh.length; ++i) {
hitBox = lh[i];
if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
// Touching an element
return me.legendItems[i];
}
}
}
return null;
},
/**
* Handle an event
* @private
* @param {IEvent} event - The event to handle
*/
handleEvent: function(e) {
var me = this;
var opts = me.options;
var type = e.type === 'mouseup' ? 'click' : e.type;
var hoveredItem;
if (type === 'mousemove') {
if (!opts.onHover && !opts.onLeave) {
return;
}
} else if (type === 'click') {
if (!opts.onClick) {
return;
}
} else {
return;
}
// Chart event already has relative position in it
hoveredItem = me._getLegendItemAt(e.x, e.y);
if (type === 'click') {
if (hoveredItem && opts.onClick) {
// use e.native for backwards compatibility
opts.onClick.call(me, e.native, hoveredItem);
}
} else {
if (opts.onLeave && hoveredItem !== me._hoveredItem) {
if (me._hoveredItem) {
opts.onLeave.call(me, e.native, me._hoveredItem);
}
me._hoveredItem = hoveredItem;
}
if (opts.onHover && hoveredItem) {
// use e.native for backwards compatibility
opts.onHover.call(me, e.native, hoveredItem);
}
}
}
});
function createNewLegendAndAttach(chart, legendOpts) {
var legend = new Legend({
ctx: chart.ctx,
options: legendOpts,
chart: chart
});
core_layouts.configure(chart, legend, legendOpts);
core_layouts.addBox(chart, legend);
chart.legend = legend;
}
var plugin_legend = {
id: 'legend',
/**
* Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
* Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
* the plugin, which one will be re-exposed in the chart.js file.
* https://github.com/chartjs/Chart.js/pull/2640
* @private
*/
_element: Legend,
beforeInit: function(chart) {
var legendOpts = chart.options.legend;
if (legendOpts) {
createNewLegendAndAttach(chart, legendOpts);
}
},
beforeUpdate: function(chart) {
var legendOpts = chart.options.legend;
var legend = chart.legend;
if (legendOpts) {
helpers$1.mergeIf(legendOpts, core_defaults.global.legend);
if (legend) {
core_layouts.configure(chart, legend, legendOpts);
legend.options = legendOpts;
} else {
createNewLegendAndAttach(chart, legendOpts);
}
} else if (legend) {
core_layouts.removeBox(chart, legend);
delete chart.legend;
}
},
afterEvent: function(chart, e) {
var legend = chart.legend;
if (legend) {
legend.handleEvent(e);
}
}
};
var noop$2 = helpers$1.noop;
core_defaults._set('global', {
title: {
display: false,
fontStyle: 'bold',
fullWidth: true,
padding: 10,
position: 'top',
text: '',
weight: 2000 // by default greater than legend (1000) to be above
}
});
/**
* IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
*/
var Title = core_element.extend({
initialize: function(config) {
var me = this;
helpers$1.extend(me, config);
// Contains hit boxes for each dataset (in dataset order)
me.legendHitBoxes = [];
},
// These methods are ordered by lifecycle. Utilities then follow.
beforeUpdate: noop$2,
update: function(maxWidth, maxHeight, margins) {
var me = this;
// Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
me.beforeUpdate();
// Absorb the master measurements
me.maxWidth = maxWidth;
me.maxHeight = maxHeight;
me.margins = margins;
// Dimensions
me.beforeSetDimensions();
me.setDimensions();
me.afterSetDimensions();
// Labels
me.beforeBuildLabels();
me.buildLabels();
me.afterBuildLabels();
// Fit
me.beforeFit();
me.fit();
me.afterFit();
//
me.afterUpdate();
return me.minSize;
},
afterUpdate: noop$2,
//
beforeSetDimensions: noop$2,
setDimensions: function() {
var me = this;
// Set the unconstrained dimension before label rotation
if (me.isHorizontal()) {
// Reset position before calculating rotation
me.width = me.maxWidth;
me.left = 0;
me.right = me.width;
} else {
me.height = me.maxHeight;
// Reset position before calculating rotation
me.top = 0;
me.bottom = me.height;
}
// Reset padding
me.paddingLeft = 0;
me.paddingTop = 0;
me.paddingRight = 0;
me.paddingBottom = 0;
// Reset minSize
me.minSize = {
width: 0,
height: 0
};
},
afterSetDimensions: noop$2,
//
beforeBuildLabels: noop$2,
buildLabels: noop$2,
afterBuildLabels: noop$2,
//
beforeFit: noop$2,
fit: function() {
var me = this;
var opts = me.options;
var display = opts.display;
var minSize = me.minSize;
var lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;
var fontOpts = helpers$1.options._parseFont(opts);
var textSize = display ? (lineCount * fontOpts.lineHeight) + (opts.padding * 2) : 0;
if (me.isHorizontal()) {
minSize.width = me.maxWidth; // fill all the width
minSize.height = textSize;
} else {
minSize.width = textSize;
minSize.height = me.maxHeight; // fill all the height
}
me.width = minSize.width;
me.height = minSize.height;
},
afterFit: noop$2,
// Shared Methods
isHorizontal: function() {
var pos = this.options.position;
return pos === 'top' || pos === 'bottom';
},
// Actually draw the title block on the canvas
draw: function() {
var me = this;
var ctx = me.ctx;
var opts = me.options;
if (opts.display) {
var fontOpts = helpers$1.options._parseFont(opts);
var lineHeight = fontOpts.lineHeight;
var offset = lineHeight / 2 + opts.padding;
var rotation = 0;
var top = me.top;
var left = me.left;
var bottom = me.bottom;
var right = me.right;
var maxWidth, titleX, titleY;
ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour
ctx.font = fontOpts.string;
// Horizontal
if (me.isHorizontal()) {
titleX = left + ((right - left) / 2); // midpoint of the width
titleY = top + offset;
maxWidth = right - left;
} else {
titleX = opts.position === 'left' ? left + offset : right - offset;
titleY = top + ((bottom - top) / 2);
maxWidth = bottom - top;
rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
}
ctx.save();
ctx.translate(titleX, titleY);
ctx.rotate(rotation);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var text = opts.text;
if (helpers$1.isArray(text)) {
var y = 0;
for (var i = 0; i < text.length; ++i) {
ctx.fillText(text[i], 0, y, maxWidth);
y += lineHeight;
}
} else {
ctx.fillText(text, 0, 0, maxWidth);
}
ctx.restore();
}
}
});
function createNewTitleBlockAndAttach(chart, titleOpts) {
var title = new Title({
ctx: chart.ctx,
options: titleOpts,
chart: chart
});
core_layouts.configure(chart, title, titleOpts);
core_layouts.addBox(chart, title);
chart.titleBlock = title;
}
var plugin_title = {
id: 'title',
/**
* Backward compatibility: since 2.1.5, the title is registered as a plugin, making
* Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
* the plugin, which one will be re-exposed in the chart.js file.
* https://github.com/chartjs/Chart.js/pull/2640
* @private
*/
_element: Title,
beforeInit: function(chart) {
var titleOpts = chart.options.title;
if (titleOpts) {
createNewTitleBlockAndAttach(chart, titleOpts);
}
},
beforeUpdate: function(chart) {
var titleOpts = chart.options.title;
var titleBlock = chart.titleBlock;
if (titleOpts) {
helpers$1.mergeIf(titleOpts, core_defaults.global.title);
if (titleBlock) {
core_layouts.configure(chart, titleBlock, titleOpts);
titleBlock.options = titleOpts;
} else {
createNewTitleBlockAndAttach(chart, titleOpts);
}
} else if (titleBlock) {
core_layouts.removeBox(chart, titleBlock);
delete chart.titleBlock;
}
}
};
var plugins = {};
var filler = plugin_filler;
var legend = plugin_legend;
var title = plugin_title;
plugins.filler = filler;
plugins.legend = legend;
plugins.title = title;
/**
* @namespace Chart
*/
core_controller.helpers = helpers$1;
// @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
core_helpers(core_controller);
core_controller._adapters = core_adapters;
core_controller.Animation = core_animation;
core_controller.animationService = core_animations;
core_controller.controllers = controllers;
core_controller.DatasetController = core_datasetController;
core_controller.defaults = core_defaults;
core_controller.Element = core_element;
core_controller.elements = elements;
core_controller.Interaction = core_interaction;
core_controller.layouts = core_layouts;
core_controller.platform = platform;
core_controller.plugins = core_plugins;
core_controller.Scale = core_scale;
core_controller.scaleService = core_scaleService;
core_controller.Ticks = core_ticks;
core_controller.Tooltip = core_tooltip;
// Register built-in scales
core_controller.helpers.each(scales, function(scale, type) {
core_controller.scaleService.registerScaleType(type, scale, scale._defaults);
});
// Load to register built-in adapters (as side effects)
// Loading built-in plugins
for (var k in plugins) {
if (plugins.hasOwnProperty(k)) {
core_controller.plugins.register(plugins[k]);
}
}
core_controller.platform.initialize();
var src = core_controller;
if (typeof window !== 'undefined') {
window.Chart = core_controller;
}
// DEPRECATIONS
/**
* Provided for backward compatibility, not available anymore
* @namespace Chart.Chart
* @deprecated since version 2.8.0
* @todo remove at version 3
* @private
*/
core_controller.Chart = core_controller;
/**
* Provided for backward compatibility, not available anymore
* @namespace Chart.Legend
* @deprecated since version 2.1.5
* @todo remove at version 3
* @private
*/
core_controller.Legend = plugins.legend._element;
/**
* Provided for backward compatibility, not available anymore
* @namespace Chart.Title
* @deprecated since version 2.1.5
* @todo remove at version 3
* @private
*/
core_controller.Title = plugins.title._element;
/**
* Provided for backward compatibility, use Chart.plugins instead
* @namespace Chart.pluginService
* @deprecated since version 2.1.5
* @todo remove at version 3
* @private
*/
core_controller.pluginService = core_controller.plugins;
/**
* Provided for backward compatibility, inheriting from Chart.PlugingBase has no
* effect, instead simply create/register plugins via plain JavaScript objects.
* @interface Chart.PluginBase
* @deprecated since version 2.5.0
* @todo remove at version 3
* @private
*/
core_controller.PluginBase = core_controller.Element.extend({});
/**
* Provided for backward compatibility, use Chart.helpers.canvas instead.
* @namespace Chart.canvasHelpers
* @deprecated since version 2.6.0
* @todo remove at version 3
* @private
*/
core_controller.canvasHelpers = core_controller.helpers.canvas;
/**
* Provided for backward compatibility, use Chart.layouts instead.
* @namespace Chart.layoutService
* @deprecated since version 2.7.3
* @todo remove at version 3
* @private
*/
core_controller.layoutService = core_controller.layouts;
/**
* Provided for backward compatibility, not available anymore.
* @namespace Chart.LinearScaleBase
* @deprecated since version 2.8
* @todo remove at version 3
* @private
*/
core_controller.LinearScaleBase = scale_linearbase;
/**
* Provided for backward compatibility, instead we should create a new Chart
* by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`).
* @deprecated since version 2.8.0
* @todo remove at version 3
*/
core_controller.helpers.each(
[
'Bar',
'Bubble',
'Doughnut',
'Line',
'PolarArea',
'Radar',
'Scatter'
],
function(klass) {
core_controller[klass] = function(ctx, cfg) {
return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, {
type: klass.charAt(0).toLowerCase() + klass.slice(1)
}));
};
}
);
return src;
})));