Business intelligence made simple
Updated jquery and chart.js [skip ci]
Andrew Kanee5a83ed8f1dc
diff --git a/app/assets/javascripts/blazer/Chart.js b/app/assets/javascripts/blazer/Chart.jsindex 362e9418..e8d937cf 100644--- a/app/assets/javascripts/blazer/Chart.js+++ b/app/assets/javascripts/blazer/Chart.js@@ -1,3241 +1,5358 @@/*!- * Chart.js- * http://chartjs.org/- * Version: 2.7.3- *- * Copyright 2018 Chart.js Contributors- * Released under the MIT license- * https://github.com/chartjs/Chart.js/blob/master/LICENSE.md+ * Chart.js v2.9.3+ * https://www.chartjs.org+ * (c) 2019 Chart.js Contributors+ * Released under the MIT License*/-(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Chart = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){+(function (global, factory) {+typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(function() { try { return require('moment'); } catch(e) { } }()) :+typeof define === 'function' && define.amd ? define(['require'], function(require) { return factory(function() { try { return require('moment'); } catch(e) { } }()); }) :+(global = global || self, global.Chart = factory(global.moment));+}(this, (function (moment) { 'use strict';++moment = moment && moment.hasOwnProperty('default') ? moment['default'] : moment;++function createCommonjsModule(fn, module) {+ return module = { exports: {} }, fn(module, module.exports), module.exports;+}++function getCjsExportFromNamespace (n) {+ return n && n['default'] || n;+}++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]+};-},{}],2:[function(require,module,exports){+var conversions = createCommonjsModule(function (module) {/* MIT license */-var colorNames = require(6);-module.exports = {- 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-}+// NOTE: conversions should only return primitive values (i.e. arrays, or+// values that give correct `typeof` results).+// do not use box values types (i.e. Number(), String(), etc.)++var reverseKeywords = {};+for (var key in colorName) {+ if (colorName.hasOwnProperty(key)) {+ reverseKeywords[colorName[key]] = key;+ }+}++var convert = module.exports = {+ rgb: {channels: 3, labels: 'rgb'},+ hsl: {channels: 3, labels: 'hsl'},+ hsv: {channels: 3, labels: 'hsv'},+ hwb: {channels: 3, labels: 'hwb'},+ cmyk: {channels: 4, labels: 'cmyk'},+ xyz: {channels: 3, labels: 'xyz'},+ lab: {channels: 3, labels: 'lab'},+ lch: {channels: 3, labels: 'lch'},+ hex: {channels: 1, labels: ['hex']},+ keyword: {channels: 1, labels: ['keyword']},+ ansi16: {channels: 1, labels: ['ansi16']},+ ansi256: {channels: 1, labels: ['ansi256']},+ hcg: {channels: 3, labels: ['h', 'c', 'g']},+ apple: {channels: 3, labels: ['r16', 'g16', 'b16']},+ gray: {channels: 1, labels: ['gray']}+};++// hide .channels and .labels properties+for (var model in convert) {+ if (convert.hasOwnProperty(model)) {+ if (!('channels' in convert[model])) {+ throw new Error('missing channels property: ' + model);+ }++ if (!('labels' in convert[model])) {+ throw new Error('missing channel labels property: ' + model);+ }++ if (convert[model].labels.length !== convert[model].channels) {+ throw new Error('channel and label counts mismatch: ' + model);+ }++ var channels = convert[model].channels;+ var labels = convert[model].labels;+ delete convert[model].channels;+ delete convert[model].labels;+ Object.defineProperty(convert[model], 'channels', {value: channels});+ Object.defineProperty(convert[model], 'labels', {value: labels});+ }+}++convert.rgb.hsl = function (rgb) {+ var r = rgb[0] / 255;+ var g = rgb[1] / 255;+ var b = rgb[2] / 255;+ var min = Math.min(r, g, b);+ var max = Math.max(r, g, b);+ var delta = max - min;+ var h;+ var s;+ var 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];+};++convert.rgb.hsv = function (rgb) {+ var rdif;+ var gdif;+ var bdif;+ var h;+ var s;++ var r = rgb[0] / 255;+ var g = rgb[1] / 255;+ var b = rgb[2] / 255;+ var v = Math.max(r, g, b);+ var diff = v - Math.min(r, g, b);+ var diffc = function (c) {+ return (v - c) / 6 / diff + 1 / 2;+ };++ if (diff === 0) {+ h = s = 0;+ } else {+ s = diff / v;+ rdif = diffc(r);+ gdif = diffc(g);+ bdif = diffc(b);++ if (r === v) {+ h = bdif - gdif;+ } else if (g === v) {+ h = (1 / 3) + rdif - bdif;+ } else if (b === v) {+ h = (2 / 3) + gdif - rdif;+ }+ if (h < 0) {+ h += 1;+ } else if (h > 1) {+ h -= 1;+ }+ }++ return [+ h * 360,+ s * 100,+ v * 100+ ];+};++convert.rgb.hwb = function (rgb) {+ var r = rgb[0];+ var g = rgb[1];+ var b = rgb[2];+ var h = convert.rgb.hsl(rgb)[0];+ var 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];+};++convert.rgb.cmyk = function (rgb) {+ var r = rgb[0] / 255;+ var g = rgb[1] / 255;+ var b = rgb[2] / 255;+ var c;+ var m;+ var y;+ var 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];+};++/**+ * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance+ * */+function comparativeDistance(x, y) {+ return (+ Math.pow(x[0] - y[0], 2) ++ Math.pow(x[1] - y[1], 2) ++ Math.pow(x[2] - y[2], 2)+ );+}++convert.rgb.keyword = function (rgb) {+ var reversed = reverseKeywords[rgb];+ if (reversed) {+ return reversed;+ }++ var currentClosestDistance = Infinity;+ var currentClosestKeyword;++ for (var keyword in colorName) {+ if (colorName.hasOwnProperty(keyword)) {+ var value = colorName[keyword];++ // Compute comparative distance+ var distance = comparativeDistance(rgb, value);++ // Check if its less, if so set as closest+ if (distance < currentClosestDistance) {+ currentClosestDistance = distance;+ currentClosestKeyword = keyword;+ }+ }+ }++ return currentClosestKeyword;+};++convert.keyword.rgb = function (keyword) {+ return colorName[keyword];+};++convert.rgb.xyz = function (rgb) {+ var r = rgb[0] / 255;+ var g = rgb[1] / 255;+ var 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];+};++convert.rgb.lab = function (rgb) {+ var xyz = convert.rgb.xyz(rgb);+ var x = xyz[0];+ var y = xyz[1];+ var z = xyz[2];+ var l;+ var a;+ var 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];+};++convert.hsl.rgb = function (hsl) {+ var h = hsl[0] / 360;+ var s = hsl[1] / 100;+ var l = hsl[2] / 100;+ var t1;+ var t2;+ var t3;+ var rgb;+ var 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);+ if (t3 < 0) {+ t3++;+ }+ if (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;+};++convert.hsl.hsv = function (hsl) {+ var h = hsl[0];+ var s = hsl[1] / 100;+ var l = hsl[2] / 100;+ var smin = s;+ var lmin = Math.max(l, 0.01);+ var sv;+ var v;++ l *= 2;+ s *= (l <= 1) ? l : 2 - l;+ smin *= lmin <= 1 ? lmin : 2 - lmin;+ v = (l + s) / 2;+ sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);++ return [h, sv * 100, v * 100];+};++convert.hsv.rgb = function (hsv) {+ var h = hsv[0] / 60;+ var s = hsv[1] / 100;+ var v = hsv[2] / 100;+ var hi = Math.floor(h) % 6;++ var f = h - Math.floor(h);+ var p = 255 * v * (1 - s);+ var q = 255 * v * (1 - (s * f));+ var t = 255 * v * (1 - (s * (1 - f)));+ v *= 255;++ 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];+ }+};++convert.hsv.hsl = function (hsv) {+ var h = hsv[0];+ var s = hsv[1] / 100;+ var v = hsv[2] / 100;+ var vmin = Math.max(v, 0.01);+ var lmin;+ var sl;+ var l;++ l = (2 - s) * v;+ lmin = (2 - s) * vmin;+ sl = s * vmin;+ sl /= (lmin <= 1) ? lmin : 2 - lmin;+ sl = sl || 0;+ l /= 2;++ return [h, sl * 100, l * 100];+};++// http://dev.w3.org/csswg/css-color/#hwb-to-rgb+convert.hwb.rgb = function (hwb) {+ var h = hwb[0] / 360;+ var wh = hwb[1] / 100;+ var bl = hwb[2] / 100;+ var ratio = wh + bl;+ var i;+ var v;+ var f;+ var 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++ var r;+ var g;+ var b;+ 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];+};++convert.cmyk.rgb = function (cmyk) {+ var c = cmyk[0] / 100;+ var m = cmyk[1] / 100;+ var y = cmyk[2] / 100;+ var k = cmyk[3] / 100;+ var r;+ var g;+ var 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];+};++convert.xyz.rgb = function (xyz) {+ var x = xyz[0] / 100;+ var y = xyz[1] / 100;+ var z = xyz[2] / 100;+ var r;+ var g;+ var 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 * 12.92;++ g = g > 0.0031308+ ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)+ : g * 12.92;++ b = b > 0.0031308+ ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)+ : 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];+};++convert.xyz.lab = function (xyz) {+ var x = xyz[0];+ var y = xyz[1];+ var z = xyz[2];+ var l;+ var a;+ var 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];+};++convert.lab.xyz = function (lab) {+ var l = lab[0];+ var a = lab[1];+ var b = lab[2];+ var x;+ var y;+ var z;++ y = (l + 16) / 116;+ x = a / 500 + y;+ z = y - b / 200;++ var y2 = Math.pow(y, 3);+ var x2 = Math.pow(x, 3);+ var z2 = Math.pow(z, 3);+ y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;+ x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;+ z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;++ x *= 95.047;+ y *= 100;+ z *= 108.883;++ return [x, y, z];+};++convert.lab.lch = function (lab) {+ var l = lab[0];+ var a = lab[1];+ var b = lab[2];+ var hr;+ var h;+ var 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];+};++convert.lch.lab = function (lch) {+ var l = lch[0];+ var c = lch[1];+ var h = lch[2];+ var a;+ var b;+ var hr;++ hr = h / 360 * 2 * Math.PI;+ a = c * Math.cos(hr);+ b = c * Math.sin(hr);++ return [l, a, b];+};++convert.rgb.ansi16 = function (args) {+ var r = args[0];+ var g = args[1];+ var b = args[2];+ var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization++ value = Math.round(value / 50);++ if (value === 0) {+ return 30;+ }++ var ansi = 30+ + ((Math.round(b / 255) << 2)+ | (Math.round(g / 255) << 1)+ | Math.round(r / 255));++ if (value === 2) {+ ansi += 60;+ }++ return ansi;+};++convert.hsv.ansi16 = function (args) {+ // optimization here; we already know the value and don't need to get+ // it converted for us.+ return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);+};++convert.rgb.ansi256 = function (args) {+ var r = args[0];+ var g = args[1];+ var b = args[2];++ // we use the extended greyscale palette here, with the exception of+ // black and white. normal palette only has 4 greyscale shades.+ if (r === g && g === b) {+ if (r < 8) {+ return 16;+ }++ if (r > 248) {+ return 231;+ }++ return Math.round(((r - 8) / 247) * 24) + 232;+ }++ var ansi = 16+ + (36 * Math.round(r / 255 * 5))+ + (6 * Math.round(g / 255 * 5))+ + Math.round(b / 255 * 5);++ return ansi;+};++convert.ansi16.rgb = function (args) {+ var color = args % 10;++ // handle greyscale+ if (color === 0 || color === 7) {+ if (args > 50) {+ color += 3.5;+ }++ color = color / 10.5 * 255;++ return [color, color, color];+ }++ var mult = (~~(args > 50) + 1) * 0.5;+ var r = ((color & 1) * mult) * 255;+ var g = (((color >> 1) & 1) * mult) * 255;+ var b = (((color >> 2) & 1) * mult) * 255;++ return [r, g, b];+};++convert.ansi256.rgb = function (args) {+ // handle greyscale+ if (args >= 232) {+ var c = (args - 232) * 10 + 8;+ return [c, c, c];+ }++ args -= 16;++ var rem;+ var r = Math.floor(args / 36) / 5 * 255;+ var g = Math.floor((rem = args % 36) / 6) / 5 * 255;+ var b = (rem % 6) / 5 * 255;++ return [r, g, b];+};++convert.rgb.hex = function (args) {+ var integer = ((Math.round(args[0]) & 0xFF) << 16)+ + ((Math.round(args[1]) & 0xFF) << 8)+ + (Math.round(args[2]) & 0xFF);++ var string = integer.toString(16).toUpperCase();+ return '000000'.substring(string.length) + string;+};++convert.hex.rgb = function (args) {+ var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);+ if (!match) {+ return [0, 0, 0];+ }++ var colorString = match[0];++ if (match[0].length === 3) {+ colorString = colorString.split('').map(function (char) {+ return char + char;+ }).join('');+ }++ var integer = parseInt(colorString, 16);+ var r = (integer >> 16) & 0xFF;+ var g = (integer >> 8) & 0xFF;+ var b = integer & 0xFF;++ return [r, g, b];+};++convert.rgb.hcg = function (rgb) {+ var r = rgb[0] / 255;+ var g = rgb[1] / 255;+ var b = rgb[2] / 255;+ var max = Math.max(Math.max(r, g), b);+ var min = Math.min(Math.min(r, g), b);+ var chroma = (max - min);+ var grayscale;+ var hue;++ if (chroma < 1) {+ grayscale = min / (1 - chroma);+ } else {+ grayscale = 0;+ }++ if (chroma <= 0) {+ hue = 0;+ } else+ if (max === r) {+ hue = ((g - b) / chroma) % 6;+ } else+ if (max === g) {+ hue = 2 + (b - r) / chroma;+ } else {+ hue = 4 + (r - g) / chroma + 4;+ }++ hue /= 6;+ hue %= 1;++ return [hue * 360, chroma * 100, grayscale * 100];+};++convert.hsl.hcg = function (hsl) {+ var s = hsl[1] / 100;+ var l = hsl[2] / 100;+ var c = 1;+ var f = 0;++ if (l < 0.5) {+ c = 2.0 * s * l;+ } else {+ c = 2.0 * s * (1.0 - l);+ }++ if (c < 1.0) {+ f = (l - 0.5 * c) / (1.0 - c);+ }++ return [hsl[0], c * 100, f * 100];+};++convert.hsv.hcg = function (hsv) {+ var s = hsv[1] / 100;+ var v = hsv[2] / 100;++ var c = s * v;+ var f = 0;++ if (c < 1.0) {+ f = (v - c) / (1 - c);+ }++ return [hsv[0], c * 100, f * 100];+};++convert.hcg.rgb = function (hcg) {+ var h = hcg[0] / 360;+ var c = hcg[1] / 100;+ var g = hcg[2] / 100;++ if (c === 0.0) {+ return [g * 255, g * 255, g * 255];+ }++ var pure = [0, 0, 0];+ var hi = (h % 1) * 6;+ var v = hi % 1;+ var w = 1 - v;+ var mg = 0;++ switch (Math.floor(hi)) {+ case 0:+ pure[0] = 1; pure[1] = v; pure[2] = 0; break;+ case 1:+ pure[0] = w; pure[1] = 1; pure[2] = 0; break;+ case 2:+ pure[0] = 0; pure[1] = 1; pure[2] = v; break;+ case 3:+ pure[0] = 0; pure[1] = w; pure[2] = 1; break;+ case 4:+ pure[0] = v; pure[1] = 0; pure[2] = 1; break;+ default:+ pure[0] = 1; pure[1] = 0; pure[2] = w;+ }++ mg = (1.0 - c) * g;++ return [+ (c * pure[0] + mg) * 255,+ (c * pure[1] + mg) * 255,+ (c * pure[2] + mg) * 255+ ];+};++convert.hcg.hsv = function (hcg) {+ var c = hcg[1] / 100;+ var g = hcg[2] / 100;++ var v = c + g * (1.0 - c);+ var f = 0;++ if (v > 0.0) {+ f = c / v;+ }++ return [hcg[0], f * 100, v * 100];+};++convert.hcg.hsl = function (hcg) {+ var c = hcg[1] / 100;+ var g = hcg[2] / 100;++ var l = g * (1.0 - c) + 0.5 * c;+ var s = 0;++ if (l > 0.0 && l < 0.5) {+ s = c / (2 * l);+ } else+ if (l >= 0.5 && l < 1.0) {+ s = c / (2 * (1 - l));+ }++ return [hcg[0], s * 100, l * 100];+};++convert.hcg.hwb = function (hcg) {+ var c = hcg[1] / 100;+ var g = hcg[2] / 100;+ var v = c + g * (1.0 - c);+ return [hcg[0], (v - c) * 100, (1 - v) * 100];+};++convert.hwb.hcg = function (hwb) {+ var w = hwb[1] / 100;+ var b = hwb[2] / 100;+ var v = 1 - b;+ var c = v - w;+ var g = 0;++ if (c < 1) {+ g = (v - c) / (1 - c);+ }++ return [hwb[0], c * 100, g * 100];+};++convert.apple.rgb = function (apple) {+ return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];+};++convert.rgb.apple = function (rgb) {+ return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];+};++convert.gray.rgb = function (args) {+ return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];+};++convert.gray.hsl = convert.gray.hsv = function (args) {+ return [0, 0, args[0]];+};++convert.gray.hwb = function (gray) {+ return [0, 100, gray[0]];+};++convert.gray.cmyk = function (gray) {+ return [0, 0, 0, gray[0]];+};++convert.gray.lab = function (gray) {+ return [gray[0], 0, 0];+};++convert.gray.hex = function (gray) {+ var val = Math.round(gray[0] / 100 * 255) & 0xFF;+ var integer = (val << 16) + (val << 8) + val;++ var string = integer.toString(16).toUpperCase();+ return '000000'.substring(string.length) + string;+};++convert.rgb.gray = function (rgb) {+ var val = (rgb[0] + rgb[1] + rgb[2]) / 3;+ return [val / 255 * 100];+};+});+var conversions_1 = conversions.rgb;+var conversions_2 = conversions.hsl;+var conversions_3 = conversions.hsv;+var conversions_4 = conversions.hwb;+var conversions_5 = conversions.cmyk;+var conversions_6 = conversions.xyz;+var conversions_7 = conversions.lab;+var conversions_8 = conversions.lch;+var conversions_9 = conversions.hex;+var conversions_10 = conversions.keyword;+var conversions_11 = conversions.ansi16;+var conversions_12 = conversions.ansi256;+var conversions_13 = conversions.hcg;+var conversions_14 = conversions.apple;+var conversions_15 = conversions.gray;++/*+ this function routes a model to all other models.++ all functions that are routed have a property `.conversion` attached+ to the returned synthetic function. This property is an array+ of strings, each with the steps in between the 'from' and 'to'+ color models (inclusive).++ conversions that are not possible simply are not included.+*/++function buildGraph() {+ var graph = {};+ // https://jsperf.com/object-keys-vs-for-in-with-closure/3+ var models = Object.keys(conversions);++ for (var len = models.length, i = 0; i < len; i++) {+ graph[models[i]] = {+ // http://jsperf.com/1-vs-infinity+ // micro-opt, but this is simple.+ distance: -1,+ parent: null+ };+ }++ return graph;+}++// https://en.wikipedia.org/wiki/Breadth-first_search+function deriveBFS(fromModel) {+ var graph = buildGraph();+ var queue = [fromModel]; // unshift -> queue -> pop++ graph[fromModel].distance = 0;++ while (queue.length) {+ var current = queue.pop();+ var adjacents = Object.keys(conversions[current]);++ for (var len = adjacents.length, i = 0; i < len; i++) {+ var adjacent = adjacents[i];+ var node = graph[adjacent];++ if (node.distance === -1) {+ node.distance = graph[current].distance + 1;+ node.parent = current;+ queue.unshift(adjacent);+ }+ }+ }++ return graph;+}++function link(from, to) {+ return function (args) {+ return to(from(args));+ };+}++function wrapConversion(toModel, graph) {+ var path = [graph[toModel].parent, toModel];+ var fn = conversions[graph[toModel].parent][toModel];++ var cur = graph[toModel].parent;+ while (graph[cur].parent) {+ path.unshift(graph[cur].parent);+ fn = link(conversions[graph[cur].parent][cur], fn);+ cur = graph[cur].parent;+ }++ fn.conversion = path;+ return fn;+}++var route = function (fromModel) {+ var graph = deriveBFS(fromModel);+ var conversion = {};++ var models = Object.keys(graph);+ for (var len = models.length, i = 0; i < len; i++) {+ var toModel = models[i];+ var node = graph[toModel];++ if (node.parent === null) {+ // no possible conversion, or this node is the source model.+ continue;+ }++ conversion[toModel] = wrapConversion(toModel, graph);+ }++ return conversion;+};++var convert = {};++var models = Object.keys(conversions);++function wrapRaw(fn) {+ var wrappedFn = function (args) {+ if (args === undefined || args === null) {+ return args;+ }++ if (arguments.length > 1) {+ args = Array.prototype.slice.call(arguments);+ }++ return fn(args);+ };++ // preserve .conversion property if there is one+ if ('conversion' in fn) {+ wrappedFn.conversion = fn.conversion;+ }++ return wrappedFn;+}++function wrapRounded(fn) {+ var wrappedFn = function (args) {+ if (args === undefined || args === null) {+ return args;+ }++ if (arguments.length > 1) {+ args = Array.prototype.slice.call(arguments);+ }++ var result = fn(args);++ // we're assuming the result is an array here.+ // see notice in conversions.js; don't use box types+ // in conversion functions.+ if (typeof result === 'object') {+ for (var len = result.length, i = 0; i < len; i++) {+ result[i] = Math.round(result[i]);+ }+ }++ return result;+ };++ // preserve .conversion property if there is one+ if ('conversion' in fn) {+ wrappedFn.conversion = fn.conversion;+ }++ return wrappedFn;+}++models.forEach(function (fromModel) {+ convert[fromModel] = {};++ Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});+ Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});++ var routes = route(fromModel);+ var routeModels = Object.keys(routes);++ routeModels.forEach(function (toModel) {+ var fn = routes[toModel];++ convert[fromModel][toModel] = wrapRounded(fn);+ convert[fromModel][toModel].raw = wrapRaw(fn);+ });+});++var colorConvert = convert;++var colorName$1 = {+ "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$1[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$1) {+ reverseNames[colorName$1[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);+ }-function getRgba(string) {- if (!string) {- return;- }- var abbr = /^#([a-fA-F0-9]{3})$/i,- hex = /^#([a-fA-F0-9]{6})$/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+)/;+ if (helpers.isObject(source)) {+ var target = {};+ var keys = Object.keys(source);+ var klen = keys.length;+ var k = 0;- var rgb = [0, 0, 0],- a = 1,- match = string.match(abbr);- if (match) {- match = match[1];- for (var i = 0; i < rgb.length; i++) {- rgb[i] = parseInt(match[i] + match[i], 16);- }- }- else if (match = string.match(hex)) {- match = match[1];- for (var i = 0; i < rgb.length; i++) {- rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);- }- }- 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 = colorNames[match[1]];- if (!rgb) {- return;- }- }+ for (; k < klen; ++k) {+ target[keys[k]] = helpers.clone(source[keys[k]]);+ }- 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;-}+ return target;+ }-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];- }-}+ return source;+ },-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];- }-}+ /**+ * 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];-function getRgb(string) {- var rgba = getRgba(string);- return rgba && rgba.slice(0, 3);-}+ if (helpers.isObject(tval) && helpers.isObject(sval)) {+ helpers.merge(tval, sval, options);+ } else {+ target[key] = helpers.clone(sval);+ }+ },-function getHsl(string) {- var hsla = getHsla(string);- return hsla && hsla.slice(0, 3);-}+ /**+ * 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];-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];- }-}+ if (helpers.isObject(tval) && helpers.isObject(sval)) {+ helpers.mergeIf(tval, sval);+ } else if (!target.hasOwnProperty(key)) {+ target[key] = helpers.clone(sval);+ }+ },-// generators-function hexString(rgb) {- return "#" + hexDouble(rgb[0]) + hexDouble(rgb[1])- + hexDouble(rgb[2]);-}+ /**+ * 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;-function rgbString(rgba, alpha) {- if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {- return rgbaString(rgba, alpha);- }- return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";-}+ if (!helpers.isObject(target)) {+ return target;+ }-function rgbaString(rgba, alpha) {- if (alpha === undefined) {- alpha = (rgba[3] !== undefined ? rgba[3] : 1);- }- return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]- + ", " + alpha + ")";-}+ options = options || {};+ merge = options.merger || helpers._merger;-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);+ for (i = 0; i < ilen; ++i) {+ source = sources[i];+ if (!helpers.isObject(source)) {+ continue;+ }- return "rgb(" + r + "%, " + g + "%, " + b + "%)";-}+ keys = Object.keys(source);+ for (k = 0, klen = keys.length; k < klen; ++k) {+ merge(keys[k], target, source, options);+ }+ }-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) + ")";-}+ return target;+ },-function hslString(hsla, alpha) {- if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {- return hslaString(hsla, alpha);- }- return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";-}+ /**+ * 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});+ },-function hslaString(hsla, alpha) {- if (alpha === undefined) {- alpha = (hsla[3] !== undefined ? hsla[3] : 1);- }- return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "- + alpha + ")";-}+ /**+ * 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: Object.assign || function(target) {+ return helpers.merge(target, [].slice.call(arguments, 1), {+ merger: function(key, dst, src) {+ dst[key] = src[key];+ }+ });+ },-// 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 : "") + ")";-}+ /**+ * 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);+ };-function keyword(rgb) {- return reverseNames[rgb.slice(0, 3)];-}+ var Surrogate = function() {+ this.constructor = ChartElement;+ };-// helpers-function scale(num, min, max) {- return Math.min(Math.max(min, num), max);-}+ Surrogate.prototype = me.prototype;+ ChartElement.prototype = new Surrogate();+ ChartElement.extend = helpers.inherits;-function hexDouble(num) {- var str = num.toString(16).toUpperCase();- return (str.length < 2) ? "0" + str : str;-}+ if (extensions) {+ helpers.extend(ChartElement.prototype, extensions);+ }+ ChartElement.__super__ = me.prototype;+ return ChartElement;+ },-//create a list of reverse color names-var reverseNames = {};-for (var name in colorNames) {- reverseNames[colorNames[name]] = name;-}+ _deprecated: function(scope, value, previous, current) {+ if (value !== undefined) {+ console.warn(scope + ': "' + previous ++ '" is deprecated. Please use "' + current + '" instead');+ }+ }+};-},{"6":6}],3:[function(require,module,exports){-/* MIT license */-var convert = require(5);-var string = require(2);+var helpers_core = helpers;-var Color = function (obj) {- if (obj instanceof Color) {- return obj;- }- if (!(this instanceof Color)) {- return new Color(obj);- }+// DEPRECATIONS- 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- };+/**+ * 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;- // parse Color() argument- var vals;- if (typeof obj === 'string') {- vals = string.getRgba(obj);- if (vals) {- this.setValues('rgb', vals);- } else if (vals = string.getHsla(obj)) {- this.setValues('hsl', vals);- } else if (vals = string.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);- }- }+/**+ * 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);};-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);- },+/**+ * 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;- 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;- },+/**+ * 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;- red: function (val) {- return this.setChannel('rgb', 0, val);+/**+ * 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;},- green: function (val) {- return this.setChannel('rgb', 1, val);++ easeInQuad: function(t) {+ return t * t;},- blue: function (val) {- return this.setChannel('rgb', 2, val);++ easeOutQuad: function(t) {+ return -t * (t - 2);},- hue: function (val) {- if (val) {- val %= 360;- val = val < 0 ? 360 + val : val;++ easeInOutQuad: function(t) {+ if ((t /= 0.5) < 1) {+ return 0.5 * t * t;}- 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);+ return -0.5 * ((--t) * (t - 2) - 1);},- hexString: function () {- return string.hexString(this.values.rgb);- },- rgbString: function () {- return string.rgbString(this.values.rgb, this.values.alpha);- },- rgbaString: function () {- return string.rgbaString(this.values.rgb, this.values.alpha);- },- percentString: function () {- return string.percentString(this.values.rgb, this.values.alpha);- },- hslString: function () {- return string.hslString(this.values.hsl, this.values.alpha);- },- hslaString: function () {- return string.hslaString(this.values.hsl, this.values.alpha);- },- hwbString: function () {- return string.hwbString(this.values.hwb, this.values.alpha);- },- keyword: function () {- return string.keyword(this.values.rgb, this.values.alpha);+ easeInCubic: function(t) {+ return t * t * t;},- rgbNumber: function () {- var rgb = this.values.rgb;- return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];+ easeOutCubic: function(t) {+ return (t = t - 1) * t * t + 1;},- 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);+ easeInOutCubic: function(t) {+ if ((t /= 0.5) < 1) {+ return 0.5 * t * t * t;}- return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];+ return 0.5 * ((t -= 2) * t * t + 2);+ },++ easeInQuart: function(t) {+ return t * t * t * t;},- 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);+ easeOutQuart: function(t) {+ return -((t = t - 1) * t * t * t - 1);},- level: function (color2) {- var contrastRatio = this.contrast(color2);- if (contrastRatio >= 7.1) {- return 'AAA';+ easeInOutQuart: function(t) {+ if ((t /= 0.5) < 1) {+ return 0.5 * t * t * t * t;}-- return (contrastRatio >= 4.5) ? 'AA' : '';+ return -0.5 * ((t -= 2) * t * t * t - 2);},- 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;+ easeInQuint: function(t) {+ return t * t * t * t * t;},- light: function () {- return !this.dark();+ easeOutQuint: function(t) {+ return (t = t - 1) * t * t * t * t + 1;},- negate: function () {- var rgb = [];- for (var i = 0; i < 3; i++) {- rgb[i] = 255 - this.values.rgb[i];+ easeInOutQuint: function(t) {+ if ((t /= 0.5) < 1) {+ return 0.5 * t * t * t * t * t;}- this.setValues('rgb', rgb);- return this;+ return 0.5 * ((t -= 2) * t * t * t * t + 2);},- lighten: function (ratio) {- var hsl = this.values.hsl;- hsl[2] += hsl[2] * ratio;- this.setValues('hsl', hsl);- return this;+ easeInSine: function(t) {+ return -Math.cos(t * (Math.PI / 2)) + 1;},- darken: function (ratio) {- var hsl = this.values.hsl;- hsl[2] -= hsl[2] * ratio;- this.setValues('hsl', hsl);- return this;+ easeOutSine: function(t) {+ return Math.sin(t * (Math.PI / 2));},- saturate: function (ratio) {- var hsl = this.values.hsl;- hsl[1] += hsl[1] * ratio;- this.setValues('hsl', hsl);- return this;+ easeInOutSine: function(t) {+ return -0.5 * (Math.cos(Math.PI * t) - 1);},- desaturate: function (ratio) {- var hsl = this.values.hsl;- hsl[1] -= hsl[1] * ratio;- this.setValues('hsl', hsl);- return this;+ easeInExpo: function(t) {+ return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));},- whiten: function (ratio) {- var hwb = this.values.hwb;- hwb[1] += hwb[1] * ratio;- this.setValues('hwb', hwb);- return this;+ easeOutExpo: function(t) {+ return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;},- blacken: function (ratio) {- var hwb = this.values.hwb;- hwb[2] += hwb[2] * ratio;- this.setValues('hwb', hwb);- return this;+ 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);},- 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;+ easeInCirc: function(t) {+ if (t >= 1) {+ return t;+ }+ return -(Math.sqrt(1 - t * t) - 1);},- clearer: function (ratio) {- var alpha = this.values.alpha;- this.setValues('alpha', alpha - (alpha * ratio));- return this;+ easeOutCirc: function(t) {+ return Math.sqrt(1 - (t = t - 1) * t);},- opaquer: function (ratio) {- var alpha = this.values.alpha;- this.setValues('alpha', alpha + (alpha * ratio));- return this;+ 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);},- 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;+ 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));},- /**- * 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();+ 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;+ },- var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;- var w2 = 1 - w1;+ 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);+ },- 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));+ easeOutBack: function(t) {+ var s = 1.70158;+ return (t = t - 1) * t * ((s + 1) * t + s) + 1;},- toJSON: function () {- return this.rgb();+ 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);},- 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;+ easeInBounce: function(t) {+ return 1 - effects.easeOutBounce(1 - t);+ },- 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);- }- }+ 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;+ },- return result;+ easeInOutBounce: function(t) {+ if (t < 0.5) {+ return effects.easeInBounce(t * 2) * 0.5;+ }+ return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;}};-Color.prototype.spaces = {- rgb: ['red', 'green', 'blue'],- hsl: ['hue', 'saturation', 'lightness'],- hsv: ['hue', 'saturation', 'value'],- hwb: ['hue', 'whiteness', 'blackness'],- cmyk: ['cyan', 'magenta', 'yellow', 'black']+var helpers_easing = {+ effects: effects};-Color.prototype.maxes = {- rgb: [255, 255, 255],- hsl: [360, 100, 100],- hsv: [360, 100, 100],- hwb: [360, 100, 100],- cmyk: [100, 100, 100, 100]-};+// DEPRECATIONS-Color.prototype.getValues = function (space) {- var values = this.values;- var vals = {};+/**+ * 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;- for (var i = 0; i < space.length; i++) {- vals[space.charAt(i)] = values[space][i];- }+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;- if (values.alpha !== 1) {- vals.a = values.alpha;- }+/**+ * @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);+ },- // {r: 255, g: 255, b: 255, a: 0.4}- return vals;-};+ /**+ * 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);+ }+ },-Color.prototype.setValues = function (space, vals) {- var values = this.values;- var spaces = this.spaces;- var maxes = this.maxes;- var alpha = 1;- var i;+ drawPoint: function(ctx, style, radius, x, y, rotation) {+ var type, xOffset, yOffset, size, cornerRadius;+ var rad = (rotation || 0) * RAD_PER_DEG;- this.valid = true;+ if (style && typeof style === 'object') {+ type = style.toString();+ if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {+ ctx.save();+ ctx.translate(x, y);+ ctx.rotate(rad);+ ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);+ ctx.restore();+ return;+ }+ }- 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)];+ if (isNaN(radius) || radius <= 0) {+ return;}- alpha = vals.a;- } else if (vals[spaces[space][0]] !== undefined) {- // {red: 10, green: 10, blue: 10}- var chans = spaces[space];+ ctx.beginPath();- for (i = 0; i < space.length; i++) {- values[space][i] = vals[chans[i]];+ 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;}- alpha = vals.alpha;- }+ ctx.fill();+ ctx.stroke();+ },- values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));+ /**+ * 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.- if (space === 'alpha') {- return false;- }+ return point.x > area.left - epsilon && point.x < area.right + epsilon &&+ point.y > area.top - epsilon && point.y < area.bottom + epsilon;+ },- var capped;+ clipArea: function(ctx, area) {+ ctx.save();+ ctx.beginPath();+ ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);+ ctx.clip();+ },- // 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);- }+ unclipArea: function(ctx) {+ ctx.restore();+ },- // convert to all the other color spaces- for (var sname in spaces) {- if (sname !== space) {- values[sname] = convert[space][sname](values[space]);+ 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;}- }- return true;+ 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);+ }};-Color.prototype.setSpace = function (space, args) {- var vals = args[0];+var helpers_canvas = exports$1;- if (vals === undefined) {- // color.rgb()- return this.getValues(space);- }+// DEPRECATIONS- // color.rgb(10, 10, 10)- if (typeof vals === 'number') {- vals = Array.prototype.slice.call(args);- }+/**+ * 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;- this.setValues(space, vals);- return this;+/**+ * 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);};-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;+var defaults = {+ /**+ * @private+ */+ _set: function(scope, values) {+ return helpers_core.merge(this[scope] || (this[scope] = {}), values);}+};- // color.red(100)- svalues[index] = val;- this.setValues(space, svalues);+// TODO(v3): remove 'global' from namespace. all default are global and+// there's inconsistency around which options are under 'global'+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+});- return this;-};+var core_defaults = defaults;-if (typeof window !== 'undefined') {- window.Color = Color;+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;}-module.exports = Color;+/**+ * @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;+ }-},{"2":2,"5":5}],4:[function(require,module,exports){-/* MIT license */+ value = +matches[2];-module.exports = {- 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;+ switch (matches[3]) {+ case 'px':+ return value;+ case '%':+ value /= 100;+ break;+ }- h = Math.min(h * 60, 360);+ return size * value;+ },- if (h < 0)- h += 360;+ /**+ * 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;- v = ((max / 255) * 1000) / 10;+ 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 [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 {+ top: t,+ right: r,+ bottom: b,+ left: l,+ height: t + b,+ width: l + r+ };+ },- return [h, w * 100, b * 100];-}+ /**+ * 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: ''+ };-function rgb2cmyk(rgb) {- var r = rgb[0] / 255,- g = rgb[1] / 255,- b = rgb[2] / 255,- c, m, y, k;+ font.string = toFontString(font);+ return font;+ },- 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];-}+ /**+ * 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.+ * @param {object} [info] - object to return information about resolution in+ * @param {boolean} [info.cacheable] - Will be set to `false` if option is not cacheable.+ * @since 2.7.0+ */+ resolve: function(inputs, context, index, info) {+ var cacheable = true;+ var i, ilen, value;-function rgb2keyword(rgb) {- return reverseKeywords[JSON.stringify(rgb)];-}+ 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);+ cacheable = false;+ }+ if (index !== undefined && helpers_core.isArray(value)) {+ value = value[index];+ cacheable = false;+ }+ if (value !== undefined) {+ if (info && !cacheable) {+ info.cacheable = false;+ }+ return value;+ }+ }+ }+};-function rgb2xyz(rgb) {- var r = rgb[0] / 255,- g = rgb[1] / 255,- b = rgb[2] / 255;+/**+ * @alias Chart.helpers.math+ * @namespace+ */+var exports$2 = {+ /**+ * Returns an array of factors sorted from 1 to sqrt(value)+ * @private+ */+ _factorize: function(value) {+ var result = [];+ var sqrt = Math.sqrt(value);+ var i;- // 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);+ for (i = 1; i < sqrt; i++) {+ if (value % i === 0) {+ result.push(i);+ result.push(value / i);+ }+ }+ if (sqrt === (sqrt | 0)) { // if value is a square number+ result.push(sqrt);+ }- 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);+ result.sort(function(a, b) {+ return a - b;+ }).pop();+ return result;+ },- return [x * 100, y *100, z * 100];-}+ log10: Math.log10 || function(x) {+ var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.+ // Check for whole powers of 10,+ // which due to floating point rounding error should be corrected.+ var powerOf10 = Math.round(exponent);+ var isPowerOf10 = x === Math.pow(10, powerOf10);-function rgb2lab(rgb) {- var xyz = rgb2xyz(rgb),- x = xyz[0],- y = xyz[1],- z = xyz[2],- l, a, b;+ return isPowerOf10 ? powerOf10 : exponent;+ }+};- x /= 95.047;- y /= 100;- z /= 108.883;+var helpers_math = exports$2;- 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);+// DEPRECATIONS- l = (116 * y) - 16;- a = 500 * (x - y);- b = 200 * (y - z);+/**+ * Provided for backward compatibility, use Chart.helpers.math.log10 instead.+ * @namespace Chart.helpers.log10+ * @deprecated since version 2.9.0+ * @todo remove at version 3+ * @private+ */+helpers_core.log10 = exports$2.log10;- return [l, a, b];-}+var getRtlAdapter = function(rectX, width) {+ return {+ x: function(x) {+ return rectX + rectX + width - x;+ },+ setWidth: function(w) {+ width = w;+ },+ textAlign: function(align) {+ if (align === 'center') {+ return align;+ }+ return align === 'right' ? 'left' : 'right';+ },+ xPlus: function(x, value) {+ return x - value;+ },+ leftForLtr: function(x, itemWidth) {+ return x - itemWidth;+ },+ };+};-function rgb2lch(args) {- return lab2lch(rgb2lab(args));-}+var getLtrAdapter = function() {+ return {+ x: function(x) {+ return x;+ },+ setWidth: function(w) { // eslint-disable-line no-unused-vars+ },+ textAlign: function(align) {+ return align;+ },+ xPlus: function(x, value) {+ return x + value;+ },+ leftForLtr: function(x, _itemWidth) { // eslint-disable-line no-unused-vars+ return x;+ },+ };+};-function hsl2rgb(hsl) {- var h = hsl[0] / 360,- s = hsl[1] / 100,- l = hsl[2] / 100,- t1, t2, t3, rgb, val;+var getAdapter = function(rtl, rectX, width) {+ return rtl ? getRtlAdapter(rectX, width) : getLtrAdapter();+};- if (s == 0) {- val = l * 255;- return [val, val, val];- }+var overrideTextDirection = function(ctx, direction) {+ var style, original;+ if (direction === 'ltr' || direction === 'rtl') {+ style = ctx.canvas.style;+ original = [+ style.getPropertyValue('direction'),+ style.getPropertyPriority('direction'),+ ];- if (l < 0.5)- t2 = l * (1 + s);- else- t2 = l + s - l * s;- t1 = 2 * l - t2;+ style.setProperty('direction', direction, 'important');+ ctx.prevTextDirection = original;+ }+};- rgb = [0, 0, 0];- for (var i = 0; i < 3; i++) {- t3 = h + 1 / 3 * - (i - 1);- t3 < 0 && t3++;- t3 > 1 && t3--;+var restoreTextDirection = function(ctx) {+ var original = ctx.prevTextDirection;+ if (original !== undefined) {+ delete ctx.prevTextDirection;+ ctx.canvas.style.setProperty('direction', original[0], original[1]);+ }+};- 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;+var helpers_rtl = {+ getRtlAdapter: getAdapter,+ overrideTextDirection: overrideTextDirection,+ restoreTextDirection: restoreTextDirection,+};- rgb[i] = val * 255;- }+var helpers$1 = helpers_core;+var easing = helpers_easing;+var canvas = helpers_canvas;+var options = helpers_options;+var math = helpers_math;+var rtl = helpers_rtl;+helpers$1.easing = easing;+helpers$1.canvas = canvas;+helpers$1.options = options;+helpers$1.math = math;+helpers$1.rtl = rtl;- return rgb;-}+function interpolate(start, view, model, ease) {+ var keys = Object.keys(model);+ var i, ilen, key, actual, origin, target, type, c0, c1;-function hsl2hsv(hsl) {- var h = hsl[0],- s = hsl[1] / 100,- l = hsl[2] / 100,- sv, v;+ for (i = 0, ilen = keys.length; i < ilen; ++i) {+ key = keys[i];- if(l === 0) {- // no need to do calc on black- // also avoids divide by 0 error- return [0, 0, 0];- }+ target = model[key];- l *= 2;- s *= (l <= 1) ? l : 2 - l;- v = (l + s) / 2;- sv = (2 * s) / (l + s);- return [h, sv * 100, v * 100];-}+ // 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;+ }-function hsl2hwb(args) {- return rgb2hwb(hsl2rgb(args));-}+ actual = view[key];-function hsl2cmyk(args) {- return rgb2cmyk(hsl2rgb(args));-}+ if (actual === target || key[0] === '_') {+ continue;+ }-function hsl2keyword(args) {- return rgb2keyword(hsl2rgb(args));-}+ if (!start.hasOwnProperty(key)) {+ start[key] = actual;+ }+ origin = start[key];-function hsv2rgb(hsv) {- var h = hsv[0] / 60,- s = hsv[1] / 100,- v = hsv[2] / 100,- hi = Math.floor(h) % 6;+ type = typeof target;- 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;+ 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;+ }+ }- 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];- }+ view[key] = target;+ }}-function hsv2hsl(hsv) {- var h = hsv[0],- s = hsv[1] / 100,- v = hsv[2] / 100,- sl, l;+var Element = function(configuration) {+ helpers$1.extend(this, configuration);+ this.initialize.apply(this, arguments);+};- l = (2 - s) * v;- sl = s * v;- sl /= (l <= 1) ? l : 2 - l;- sl = sl || 0;- l /= 2;- return [h, sl * 100, l * 100];-}+helpers$1.extend(Element.prototype, {+ _type: undefined,-function hsv2hwb(args) {- return rgb2hwb(hsv2rgb(args))-}+ initialize: function() {+ this.hidden = false;+ },-function hsv2cmyk(args) {- return rgb2cmyk(hsv2rgb(args));-}+ pivot: function() {+ var me = this;+ if (!me._view) {+ me._view = helpers$1.extend({}, me._model);+ }+ me._start = {};+ return me;+ },-function hsv2keyword(args) {- return rgb2keyword(hsv2rgb(args));-}+ transition: function(ease) {+ var me = this;+ var model = me._model;+ var start = me._start;+ var view = me._view;-// 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;+ // No animation -> No Transition+ if (!model || ease === 1) {+ me._view = helpers$1.extend({}, model);+ me._start = null;+ return me;+ }- // wh + bl cant be > 1- if (ratio > 1) {- wh /= ratio;- bl /= ratio;- }+ if (!view) {+ view = me._view = {};+ }- 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+ if (!start) {+ start = me._start = {};+ }- 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;- }+ interpolate(start, view, model, ease);- return [r * 255, g * 255, b * 255];-}+ return me;+ },-function hwb2hsl(args) {- return rgb2hsl(hwb2rgb(args));-}+ tooltipPosition: function() {+ return {+ x: this._model.x,+ y: this._model.y+ };+ },-function hwb2hsv(args) {- return rgb2hsv(hwb2rgb(args));-}+ hasValue: function() {+ return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);+ }+});-function hwb2cmyk(args) {- return rgb2cmyk(hwb2rgb(args));-}+Element.extend = helpers$1.inherits;-function hwb2keyword(args) {- return rgb2keyword(hwb2rgb(args));-}+var core_element = Element;-function cmyk2rgb(cmyk) {- var c = cmyk[0] / 100,- m = cmyk[1] / 100,- y = cmyk[2] / 100,- k = cmyk[3] / 100,- r, g, b;+var exports$3 = 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- 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];-}+ onAnimationProgress: null, // user specified callback to fire on each step of the animation+ onAnimationComplete: null, // user specified callback to fire when the animation finishes+});-function cmyk2hsl(args) {- return rgb2hsl(cmyk2rgb(args));-}+var core_animation = exports$3;-function cmyk2hsv(args) {- return rgb2hsv(cmyk2rgb(args));-}+// DEPRECATIONS-function cmyk2hwb(args) {- return rgb2hwb(cmyk2rgb(args));-}+/**+ * 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$3.prototype, 'animationObject', {+ get: function() {+ return this;+ }+});-function cmyk2keyword(args) {- return rgb2keyword(cmyk2rgb(args));-}+/**+ * 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$3.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+ }+});-function xyz2rgb(xyz) {- var x = xyz[0] / 100,- y = xyz[1] / 100,- z = xyz[2] / 100,- r, g, b;+var core_animations = {+ animations: [],+ request: null,- 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);+ /**+ * @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;- // assume sRGB- r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)- : r = (r * 12.92);+ animation.chart = chart;+ animation.startTime = Date.now();+ animation.duration = duration;- g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)- : g = (g * 12.92);+ if (!lazy) {+ chart.animating = true;+ }- b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)- : b = (b * 12.92);+ for (i = 0, ilen = animations.length; i < ilen; ++i) {+ if (animations[i].chart === chart) {+ animations[i] = animation;+ return;+ }+ }- r = Math.min(Math.max(0, r), 1);- g = Math.min(Math.max(0, g), 1);- b = Math.min(Math.max(0, b), 1);+ animations.push(animation);- return [r * 255, g * 255, b * 255];-}+ // If there are no animations queued, manually kickstart a digest, for lack of a better word+ if (animations.length === 1) {+ this.requestAnimationFrame();+ }+ },-function xyz2lab(xyz) {- var x = xyz[0],- y = xyz[1],- z = xyz[2],- l, a, b;+ cancelAnimation: function(chart) {+ var index = helpers$1.findIndex(this.animations, function(animation) {+ return animation.chart === chart;+ });- x /= 95.047;- y /= 100;- z /= 108.883;+ if (index !== -1) {+ this.animations.splice(index, 1);+ chart.animating = false;+ }+ },- 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);+ 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();+ });+ }+ },- l = (116 * y) - 16;- a = 500 * (x - y);- b = 200 * (y - z);+ /**+ * @private+ */+ startDigest: function() {+ var me = this;- return [l, a, b];-}+ me.advance();-function xyz2lch(args) {- return lab2lch(xyz2lab(args));-}+ // Do we have more stuff to animate?+ if (me.animations.length > 0) {+ me.requestAnimationFrame();+ }+ },-function lab2xyz(lab) {- var l = lab[0],- a = lab[1],- b = lab[2],- x, y, z, y2;+ /**+ * @private+ */+ advance: function() {+ var animations = this.animations;+ var animation, chart, numSteps, nextStep;+ var i = 0;- 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);- }+ // 1 animation per chart, so we are looping charts here+ while (i < animations.length) {+ animation = animations[i];+ chart = animation.chart;+ numSteps = animation.numSteps;- x = x / 95.047 <= 0.008856 ? x = (95.047 * ((a / 500) + y2 - (16 / 116))) / 7.787 : 95.047 * Math.pow((a / 500) + y2, 3);+ // 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);- z = z / 108.883 <= 0.008859 ? z = (108.883 * (y2 - (b / 200) - (16 / 116))) / 7.787 : 108.883 * Math.pow(y2 - (b / 200), 3);+ helpers$1.callback(animation.render, [chart, animation], chart);+ helpers$1.callback(animation.onAnimationProgress, [animation], chart);- return [x, y, z];-}+ if (animation.currentStep >= numSteps) {+ helpers$1.callback(animation.onAnimationComplete, [animation], chart);+ chart.animating = false;+ animations.splice(i, 1);+ } else {+ ++i;+ }+ }+ }+};-function lab2lch(lab) {- var l = lab[0],- a = lab[1],- b = lab[2],- hr, h, c;+var resolve = helpers$1.options.resolve;- 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];-}+var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];-function lab2rgb(args) {- return xyz2rgb(lab2xyz(args));-}+/**+ * 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;+ }-function lch2lab(lch) {- var l = lch[0],- c = lch[1],- h = lch[2],- a, b, hr;+ Object.defineProperty(array, '_chartjs', {+ configurable: true,+ enumerable: false,+ value: {+ listeners: [listener]+ }+ });- 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]-};+ arrayEvents.forEach(function(key) {+ var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);+ var base = array[key];-var reverseKeywords = {};-for (var key in cssKeywords) {- reverseKeywords[JSON.stringify(cssKeywords[key])] = key;-}+ Object.defineProperty(array, key, {+ configurable: true,+ enumerable: false,+ value: function() {+ var args = Array.prototype.slice.call(arguments);+ var res = base.apply(this, args);-},{}],5:[function(require,module,exports){-var conversions = require(4);+ helpers$1.each(array._chartjs.listeners, function(object) {+ if (typeof object[method] === 'function') {+ object[method].apply(object, args);+ }+ });-var convert = function() {- return new Converter();+ return res;+ }+ });+ });}-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);+/**+ * 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 pair = /(\w+)2(\w+)/.exec(func),- from = pair[1],- to = pair[2];+ var listeners = stub.listeners;+ var index = listeners.indexOf(listener);+ if (index !== -1) {+ listeners.splice(index, 1);+ }- // export rgb2hsl and ["rgb"]["hsl"]- convert[from] = convert[from] || {};+ if (listeners.length > 0) {+ return;+ }- 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+ arrayEvents.forEach(function(key) {+ delete array[key];+ });- for (var i = 0; i < val.length; i++)- val[i] = Math.round(val[i]);- return val;- }- })(func);+ delete array._chartjs;}--/* Converter does lazy conversion and caching */-var Converter = function() {- this.convs = {};+// Base class for all dataset controllers (line, bar, etc)+var DatasetController = function(chart, datasetIndex) {+ this.initialize(chart, datasetIndex);};-/* 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);- }+helpers$1.extend(DatasetController.prototype, {- 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;-};+ /**+ * Element type used to generate a meta dataset (e.g. Chart.element.Line).+ * @type {Chart.core.element}+ */+ datasetElementType: null,-/* 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;-};+ /**+ * Element type used to generate a meta data (e.g. Chart.element.Point).+ * @type {Chart.core.element}+ */+ dataElementType: null,-["rgb", "hsl", "hsv", "cmyk", "keyword"].forEach(function(space) {- Converter.prototype[space] = function(vals) {- return this.routeSpace(space, arguments);- }-});+ /**+ * Dataset element option keys to be resolved in _resolveDatasetElementOptions.+ * A derived controller may override this to resolve controller-specific options.+ * The keys defined here are for backward compatibility for legend styles.+ * @private+ */+ _datasetElementOptions: [+ 'backgroundColor',+ 'borderCapStyle',+ 'borderColor',+ 'borderDash',+ 'borderDashOffset',+ 'borderJoinStyle',+ 'borderWidth'+ ],-module.exports = convert;-},{"4":4}],6:[function(require,module,exports){-'use strict'--module.exports = {- "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]-};+ /**+ * Data element option keys to be resolved in _resolveDataElementOptions.+ * A derived controller may override this to resolve controller-specific options.+ * The keys defined here are for backward compatibility for legend styles.+ * @private+ */+ _dataElementOptions: [+ 'backgroundColor',+ 'borderColor',+ 'borderWidth',+ 'pointStyle'+ ],++ initialize: function(chart, datasetIndex) {+ var me = this;+ me.chart = chart;+ me.index = datasetIndex;+ me.linkScales();+ me.addElements();+ me._type = me.getMeta().type;+ },-},{}],7:[function(require,module,exports){-/**- * @namespace Chart- */-var Chart = require(30)();+ updateIndex: function(datasetIndex) {+ this.index = datasetIndex;+ },-Chart.helpers = require(46);+ linkScales: function() {+ var me = this;+ var meta = me.getMeta();+ var chart = me.chart;+ var scales = chart.scales;+ var dataset = me.getDataset();+ var scalesOpts = chart.options.scales;-// @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!-require(28)(Chart);--Chart.Animation = require(22);-Chart.animationService = require(23);-Chart.defaults = require(26);-Chart.Element = require(27);-Chart.elements = require(41);-Chart.Interaction = require(29);-Chart.layouts = require(31);-Chart.platform = require(49);-Chart.plugins = require(32);-Chart.Scale = require(33);-Chart.scaleService = require(34);-Chart.Ticks = require(35);-Chart.Tooltip = require(36);--require(24)(Chart);-require(25)(Chart);--require(56)(Chart);-require(54)(Chart);-require(55)(Chart);-require(57)(Chart);-require(58)(Chart);-require(59)(Chart);--// Controllers must be loaded after elements-// See Chart.core.datasetController.dataElementType-require(15)(Chart);-require(16)(Chart);-require(17)(Chart);-require(18)(Chart);-require(19)(Chart);-require(20)(Chart);-require(21)(Chart);--require(8)(Chart);-require(9)(Chart);-require(10)(Chart);-require(11)(Chart);-require(12)(Chart);-require(13)(Chart);-require(14)(Chart);+ if (meta.xAxisID === null || !(meta.xAxisID in scales) || dataset.xAxisID) {+ meta.xAxisID = dataset.xAxisID || scalesOpts.xAxes[0].id;+ }+ if (meta.yAxisID === null || !(meta.yAxisID in scales) || dataset.yAxisID) {+ meta.yAxisID = dataset.yAxisID || scalesOpts.yAxes[0].id;+ }+ },-// Loading built-in plugins-var plugins = require(50);-for (var k in plugins) {- if (plugins.hasOwnProperty(k)) {- Chart.plugins.register(plugins[k]);- }-}+ getDataset: function() {+ return this.chart.data.datasets[this.index];+ },-Chart.platform.initialize();+ getMeta: function() {+ return this.chart.getDatasetMeta(this.index);+ },-module.exports = Chart;-if (typeof window !== 'undefined') {- window.Chart = Chart;-}+ getScaleForId: function(scaleID) {+ return this.chart.scales[scaleID];+ },-// DEPRECATIONS+ /**+ * @private+ */+ _getValueScaleId: function() {+ return this.getMeta().yAxisID;+ },-/**- * Provided for backward compatibility, not available anymore- * @namespace Chart.Legend- * @deprecated since version 2.1.5- * @todo remove at version 3- * @private- */-Chart.Legend = plugins.legend._element;+ /**+ * @private+ */+ _getIndexScaleId: function() {+ return this.getMeta().xAxisID;+ },-/**- * Provided for backward compatibility, not available anymore- * @namespace Chart.Title- * @deprecated since version 2.1.5- * @todo remove at version 3- * @private- */-Chart.Title = plugins.title._element;+ /**+ * @private+ */+ _getValueScale: function() {+ return this.getScaleForId(this._getValueScaleId());+ },-/**- * Provided for backward compatibility, use Chart.plugins instead- * @namespace Chart.pluginService- * @deprecated since version 2.1.5- * @todo remove at version 3- * @private- */-Chart.pluginService = Chart.plugins;+ /**+ * @private+ */+ _getIndexScale: function() {+ return this.getScaleForId(this._getIndexScaleId());+ },-/**- * 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- */-Chart.PluginBase = Chart.Element.extend({});+ reset: function() {+ this._update(true);+ },-/**- * Provided for backward compatibility, use Chart.helpers.canvas instead.- * @namespace Chart.canvasHelpers- * @deprecated since version 2.6.0- * @todo remove at version 3- * @private- */-Chart.canvasHelpers = Chart.helpers.canvas;+ /**+ * @private+ */+ destroy: function() {+ if (this._data) {+ unlistenArrayEvents(this._data, this);+ }+ },-/**- * Provided for backward compatibility, use Chart.layouts instead.- * @namespace Chart.layoutService- * @deprecated since version 2.8.0- * @todo remove at version 3- * @private- */-Chart.layoutService = Chart.layouts;+ 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+ });+ },-},{"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":17,"18":18,"19":19,"20":20,"21":21,"22":22,"23":23,"24":24,"25":25,"26":26,"27":27,"28":28,"29":29,"30":30,"31":31,"32":32,"33":33,"34":34,"35":35,"36":36,"41":41,"46":46,"49":49,"50":50,"54":54,"55":55,"56":56,"57":57,"58":58,"59":59,"8":8,"9":9}],8:[function(require,module,exports){-'use strict';+ addElements: function() {+ var me = this;+ var meta = me.getMeta();+ var data = me.getDataset().data || [];+ var metaData = meta.data;+ var i, ilen;-module.exports = function(Chart) {+ for (i = 0, ilen = data.length; i < ilen; ++i) {+ metaData[i] = metaData[i] || me.createMetaData(i);+ }- Chart.Bar = function(context, config) {- config.type = 'bar';+ meta.dataset = meta.dataset || me.createMetaDataset();+ },- return new Chart(context, config);- };+ 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 = []);-},{}],9:[function(require,module,exports){-'use strict';+ // 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);+ }-module.exports = function(Chart) {+ if (data && Object.isExtensible(data)) {+ listenArrayEvents(data, me);+ }+ me._data = data;+ }- Chart.Bubble = function(context, config) {- config.type = 'bubble';- return new Chart(context, config);- };+ // 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();+ },-};+ /**+ * Returns the merged user-supplied and default dataset-level options+ * @private+ */+ _configure: function() {+ var me = this;+ me._config = helpers$1.merge({}, [+ me.chart.options.datasets[me._type],+ me.getDataset(),+ ], {+ merger: function(key, target, source) {+ if (key !== '_meta' && key !== 'data') {+ helpers$1._merger(key, target, source);+ }+ }+ });+ },-},{}],10:[function(require,module,exports){-'use strict';+ _update: function(reset) {+ var me = this;+ me._configure();+ me._cachedDataOpts = null;+ me.update(reset);+ },-module.exports = function(Chart) {+ update: helpers$1.noop,- Chart.Doughnut = function(context, config) {- config.type = 'doughnut';+ transition: function(easingValue) {+ var meta = this.getMeta();+ var elements = meta.data || [];+ var ilen = elements.length;+ var i = 0;- return new Chart(context, config);- };+ for (; i < ilen; ++i) {+ elements[i].transition(easingValue);+ }-};+ if (meta.dataset) {+ meta.dataset.transition(easingValue);+ }+ },-},{}],11:[function(require,module,exports){-'use strict';+ draw: function() {+ var meta = this.getMeta();+ var elements = meta.data || [];+ var ilen = elements.length;+ var i = 0;-module.exports = function(Chart) {+ if (meta.dataset) {+ meta.dataset.draw();+ }- Chart.Line = function(context, config) {- config.type = 'line';+ for (; i < ilen; ++i) {+ elements[i].draw();+ }+ },- return new Chart(context, config);- };+ /**+ * Returns a set of predefined style properties that should be used to represent the dataset+ * or the data if the index is specified+ * @param {number} index - data index+ * @return {IStyleInterface} style object+ */+ getStyle: function(index) {+ var me = this;+ var meta = me.getMeta();+ var dataset = meta.dataset;+ var style;-};+ me._configure();+ if (dataset && index === undefined) {+ style = me._resolveDatasetElementOptions(dataset || {});+ } else {+ index = index || 0;+ style = me._resolveDataElementOptions(meta.data[index] || {}, index);+ }-},{}],12:[function(require,module,exports){-'use strict';+ if (style.fill === false || style.fill === null) {+ style.backgroundColor = style.borderColor;+ }-module.exports = function(Chart) {+ return style;+ },- Chart.PolarArea = function(context, config) {- config.type = 'polarArea';+ /**+ * @private+ */+ _resolveDatasetElementOptions: function(element, hover) {+ var me = this;+ var chart = me.chart;+ var datasetOpts = me._config;+ var custom = element.custom || {};+ var options = chart.options.elements[me.datasetElementType.prototype._type] || {};+ var elementOptions = me._datasetElementOptions;+ var values = {};+ var i, ilen, key, readKey;++ // Scriptable options+ var context = {+ chart: chart,+ dataset: me.getDataset(),+ datasetIndex: me.index,+ hover: hover+ };- return new Chart(context, config);- };+ for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {+ key = elementOptions[i];+ readKey = hover ? 'hover' + key.charAt(0).toUpperCase() + key.slice(1) : key;+ values[key] = resolve([+ custom[readKey],+ datasetOpts[readKey],+ options[readKey]+ ], context);+ }-};+ return values;+ },-},{}],13:[function(require,module,exports){-'use strict';+ /**+ * @private+ */+ _resolveDataElementOptions: function(element, index) {+ var me = this;+ var custom = element && element.custom;+ var cached = me._cachedDataOpts;+ if (cached && !custom) {+ return cached;+ }+ var chart = me.chart;+ var datasetOpts = me._config;+ var options = chart.options.elements[me.dataElementType.prototype._type] || {};+ var elementOptions = me._dataElementOptions;+ var values = {};++ // Scriptable options+ var context = {+ chart: chart,+ dataIndex: index,+ dataset: me.getDataset(),+ datasetIndex: me.index+ };-module.exports = function(Chart) {+ // `resolve` sets cacheable to `false` if any option is indexed or scripted+ var info = {cacheable: !custom};- Chart.Radar = function(context, config) {- config.type = 'radar';+ var keys, i, ilen, key;- return new Chart(context, config);- };+ custom = custom || {};-};+ if (helpers$1.isArray(elementOptions)) {+ for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {+ key = elementOptions[i];+ values[key] = resolve([+ custom[key],+ datasetOpts[key],+ options[key]+ ], context, index, info);+ }+ } else {+ keys = Object.keys(elementOptions);+ for (i = 0, ilen = keys.length; i < ilen; ++i) {+ key = keys[i];+ values[key] = resolve([+ custom[key],+ datasetOpts[elementOptions[key]],+ datasetOpts[key],+ options[key]+ ], context, index, info);+ }+ }-},{}],14:[function(require,module,exports){-'use strict';+ if (info.cacheable) {+ me._cachedDataOpts = Object.freeze(values);+ }-module.exports = function(Chart) {- Chart.Scatter = function(context, config) {- config.type = 'scatter';- return new Chart(context, config);- };-};+ return values;+ },-},{}],15:[function(require,module,exports){-'use strict';+ removeHoverStyle: function(element) {+ helpers$1.merge(element._model, element.$previousStyle || {});+ delete element.$previousStyle;+ },-var defaults = require(26);-var elements = require(41);-var helpers = require(46);+ 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;-defaults._set('bar', {- hover: {- mode: 'label'+ 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);},- scales: {- xAxes: [{- type: 'category',+ /**+ * @private+ */+ _removeDatasetHoverStyle: function() {+ var element = this.getMeta().dataset;- // Specific to Bar Controller- categoryPercentage: 0.8,- barPercentage: 0.9,+ if (element) {+ this.removeHoverStyle(element);+ }+ },- // offset settings- offset: true,+ /**+ * @private+ */+ _setDatasetHoverStyle: function() {+ var element = this.getMeta().dataset;+ var prev = {};+ var i, ilen, key, keys, hoverOptions, model;- // grid line settings- gridLines: {- offsetGridLines: true- }- }],+ if (!element) {+ return;+ }- yAxes: [{- type: 'linear'- }]- }-});+ model = element._model;+ hoverOptions = this._resolveDatasetElementOptions(element, true);-defaults._set('horizontalBar', {- hover: {- mode: 'index',- axis: 'y'+ keys = Object.keys(hoverOptions);+ for (i = 0, ilen = keys.length; i < ilen; ++i) {+ key = keys[i];+ prev[key] = model[key];+ model[key] = hoverOptions[key];+ }++ element.$previousStyle = prev;},- scales: {- xAxes: [{- type: 'linear',- position: 'bottom'- }],+ /**+ * @private+ */+ resyncElements: function() {+ var me = this;+ var meta = me.getMeta();+ var data = me.getDataset().data;+ var numMeta = meta.data.length;+ var numData = data.length;- yAxes: [{- position: 'left',- type: 'category',+ 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);+ }+});- // Specific to Horizontal Bar Controller- categoryPercentage: 0.8,- barPercentage: 0.9,+DatasetController.extend = helpers$1.inherits;- // offset settings- offset: true,+var core_datasetController = DatasetController;- // grid line settings- gridLines: {- offsetGridLines: true- }- }]- },+var TAU = Math.PI * 2;+core_defaults._set('global', {elements: {- rectangle: {- borderSkipped: 'left'+ arc: {+ backgroundColor: core_defaults.global.defaultColor,+ borderColor: '#fff',+ borderWidth: 2,+ borderAlign: 'center'}- },-- tooltips: {- callbacks: {- title: function(item, data) {- // Pick first xLabel for now- var title = '';-- if (item.length > 0) {- if (item[0].yLabel) {- title = item[0].yLabel;- } else if (data.labels.length > 0 && item[0].index < data.labels.length) {- title = data.labels[item[0].index];- }- }+ }+});- return title;- },+function clipArc(ctx, arc) {+ var startAngle = arc.startAngle;+ var endAngle = arc.endAngle;+ var pixelMargin = arc.pixelMargin;+ var angleMargin = pixelMargin / arc.outerRadius;+ var x = arc.x;+ var y = arc.y;- label: function(item, data) {- var datasetLabel = data.datasets[item.datasetIndex].label || '';- return datasetLabel + ': ' + item.xLabel;- }- },- mode: 'index',- axis: 'y'+ // 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();+ ctx.arc(x, y, arc.outerRadius, startAngle - angleMargin, endAngle + angleMargin);+ if (arc.innerRadius > pixelMargin) {+ angleMargin = pixelMargin / arc.innerRadius;+ ctx.arc(x, y, arc.innerRadius - pixelMargin, endAngle + angleMargin, startAngle - angleMargin, true);+ } else {+ ctx.arc(x, y, pixelMargin, endAngle + Math.PI / 2, startAngle - Math.PI / 2);}-});+ ctx.closePath();+ ctx.clip();+}-/**- * 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;+function drawFullCircleBorders(ctx, vm, arc, inner) {+ var endAngle = arc.endAngle;+ var i;- for (i = 1, ilen = pixels.length; i < ilen; ++i) {- min = Math.min(min, pixels[i] - pixels[i - 1]);+ if (inner) {+ arc.endAngle = arc.startAngle + TAU;+ clipArc(ctx, arc);+ arc.endAngle = endAngle;+ if (arc.endAngle === arc.startAngle && arc.fullCircles) {+ arc.endAngle += TAU;+ arc.fullCircles--;+ }}- for (i = 0, ilen = ticks.length; i < ilen; ++i) {- curr = scale.getPixelForTick(i);- min = i > 0 ? Math.min(min, curr - prev) : min;- prev = curr;+ ctx.beginPath();+ ctx.arc(arc.x, arc.y, arc.innerRadius, arc.startAngle + TAU, arc.startAngle, true);+ for (i = 0; i < arc.fullCircles; ++i) {+ ctx.stroke();}- return min;+ ctx.beginPath();+ ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.startAngle + TAU);+ for (i = 0; i < arc.fullCircles; ++i) {+ ctx.stroke();+ }}-/**- * 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;+function drawBorder(ctx, vm, arc) {+ var inner = vm.borderAlign === 'inner';- if (helpers.isNullOrUndef(thickness)) {- size = ruler.min * options.categoryPercentage;- ratio = options.barPercentage;+ if (inner) {+ ctx.lineWidth = vm.borderWidth * 2;+ ctx.lineJoin = 'round';} 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;+ ctx.lineWidth = vm.borderWidth;+ ctx.lineJoin = 'bevel';}- return {- chunk: size / count,- ratio: ratio,- start: curr - (size / 2)- };+ if (arc.fullCircles) {+ drawFullCircleBorders(ctx, vm, arc, inner);+ }++ if (inner) {+ clipArc(ctx, arc);+ }++ ctx.beginPath();+ ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.endAngle);+ ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);+ ctx.closePath();+ ctx.stroke();}-/**- * 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;+var element_arc = core_element.extend({+ _type: 'arc',- 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 end extremity.- prev = curr - (next === null ? ruler.end - curr : next - curr);- }+ inLabelRange: function(mouseX) {+ var vm = this._view;- if (next === null) {- // last data: its size is also double based on the previous point.- next = curr + curr - prev;- }+ if (vm) {+ return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));+ }+ return false;+ },- start = curr - ((curr - prev) / 2) * percent;- size = ((next - prev) / 2) * percent;+ inRange: function(chartX, chartY) {+ var vm = this._view;- return {- chunk: size / ruler.stackCount,- ratio: options.barPercentage,- start: start- };-}+ 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 += TAU;+ }+ while (angle > endAngle) {+ angle -= TAU;+ }+ while (angle < startAngle) {+ angle += TAU;+ }-module.exports = function(Chart) {+ // 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;+ },- Chart.controllers.bar = Chart.DatasetController.extend({+ 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+ };+ },- dataElementType: elements.Rectangle,+ 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));+ },- initialize: function() {- var me = this;- var meta;+ tooltipPosition: function() {+ var vm = this._view;+ var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);+ var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;- Chart.DatasetController.prototype.initialize.apply(me, arguments);+ return {+ x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),+ y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)+ };+ },- meta = me.getMeta();- meta.stack = me.getDataset().stack;- meta.bar = true;- },+ draw: function() {+ var ctx = this._chart.ctx;+ var vm = this._view;+ var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;+ var arc = {+ x: vm.x,+ y: vm.y,+ innerRadius: vm.innerRadius,+ outerRadius: Math.max(vm.outerRadius - pixelMargin, 0),+ pixelMargin: pixelMargin,+ startAngle: vm.startAngle,+ endAngle: vm.endAngle,+ fullCircles: Math.floor(vm.circumference / TAU)+ };+ var i;- update: function(reset) {- var me = this;- var rects = me.getMeta().data;- var i, ilen;+ ctx.save();- me._ruler = me.getRuler();+ ctx.fillStyle = vm.backgroundColor;+ ctx.strokeStyle = vm.borderColor;- for (i = 0, ilen = rects.length; i < ilen; ++i) {- me.updateElement(rects[i], i, reset);+ if (arc.fullCircles) {+ arc.endAngle = arc.startAngle + TAU;+ ctx.beginPath();+ ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);+ ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);+ ctx.closePath();+ for (i = 0; i < arc.fullCircles; ++i) {+ ctx.fill();}- },+ arc.endAngle = arc.startAngle + vm.circumference % TAU;+ }- updateElement: function(rectangle, index, reset) {- var me = this;- var chart = me.chart;- var meta = me.getMeta();- var dataset = me.getDataset();- var custom = rectangle.custom || {};- var rectangleOptions = chart.options.elements.rectangle;-- rectangle._xScale = me.getScaleForId(meta.xAxisID);- rectangle._yScale = me.getScaleForId(meta.yAxisID);- rectangle._datasetIndex = me.index;- rectangle._index = index;-- rectangle._model = {- datasetLabel: dataset.label,- label: chart.data.labels[index],- borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleOptions.borderSkipped,- backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.backgroundColor, index, rectangleOptions.backgroundColor),- borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.borderColor, index, rectangleOptions.borderColor),- borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.borderWidth, index, rectangleOptions.borderWidth)- };+ ctx.beginPath();+ ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);+ ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);+ ctx.closePath();+ ctx.fill();- me.updateElementGeometry(rectangle, index, reset);+ if (vm.borderWidth) {+ drawBorder(ctx, vm, arc);+ }- rectangle.pivot();- },+ ctx.restore();+ }+});- /**- * @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;- },+var valueOrDefault$1 = helpers$1.valueOrDefault;- /**- * @private- */- getValueScaleId: function() {- return this.getMeta().yAxisID;- },+var defaultColor = core_defaults.global.defaultColor;- /**- * @private- */- getIndexScaleId: function() {- return this.getMeta().xAxisID;- },+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+ }+ }+});- /**- * @private- */- getValueScale: function() {- return this.getScaleForId(this.getValueScaleId());- },+var element_line = core_element.extend({+ _type: 'line',- /**- * @private- */- getIndexScale: function() {- return this.getScaleForId(this.getIndexScaleId());- },+ 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 closePath = me._loop;+ var index, previous, currentVM;- /**- * Returns the stacks based on groups and bar visibility.- * @param {Number} [last] - The dataset index- * @returns {Array} The stack list- * @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;+ if (!points.length) {+ return;+ }- 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);+ if (me._loop) {+ for (index = 0; index < points.length; ++index) {+ previous = helpers$1.previousItem(points, index);+ // If the line has an open path, shift the point array+ if (!points[index]._view.skip && previous._view.skip) {+ points = points.slice(index).concat(points.slice(0, index));+ closePath = spanGaps;+ break;}}+ // If the line has a close path, add the first point again+ if (closePath) {+ points.push(points[0]);+ }+ }- return stacks;- },+ ctx.save();- /**- * Returns the effective number of stacks based on groups and bar visibility.- * @private- */- getStackCount: function() {- return this._getStacks().length;- },+ // Stroke Line Options+ ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;- /**- * 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;- },+ // IE 9 and 10 do not support line dash+ if (ctx.setLineDash) {+ ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);+ }- /**- * @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;+ 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;- for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {- pixels.push(scale.getPixelForValue(null, i, datasetIndex));- }+ // Stroke Line+ ctx.beginPath();- min = helpers.isNullOrUndef(scale.options.barThickness)- ? computeMinSampleSize(scale, pixels)- : -1;+ // First point moves to it's starting position no matter what+ currentVM = points[0]._view;+ if (!currentVM.skip) {+ ctx.moveTo(currentVM.x, currentVM.y);+ lastDrawnIndex = 0;+ }- return {- min: min,- pixels: pixels,- start: start,- end: end,- stackCount: stackCount,- scale: scale- };- },+ for (index = 1; index < points.length; ++index) {+ currentVM = points[index]._view;+ previous = lastDrawnIndex === -1 ? helpers$1.previousItem(points, index) : points[lastDrawnIndex];- /**- * 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 datasets = chart.data.datasets;- var value = scale.getRightValue(datasets[datasetIndex].data[index]);- 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;- }- }+ 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, currentVM);}+ lastDrawnIndex = index;}+ }- base = scale.getPixelForValue(start);- head = scale.getPixelForValue(start + value);- size = (head - base) / 2;-- return {- size: size,- base: base,- head: head,- center: head + size / 2- };- },+ if (closePath) {+ ctx.closePath();+ }- /**- * @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.valueOrDefault(options.maxBarThickness, Infinity),- range.chunk * range.ratio);+ ctx.stroke();+ ctx.restore();+ }+});- return {- base: center - size / 2,- head: center + size / 2,- center: center,- size: size- };- },+var valueOrDefault$2 = helpers$1.valueOrDefault;- 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;+var defaultColor$1 = core_defaults.global.defaultColor;- helpers.canvas.clipArea(chart.ctx, chart.chartArea);+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+ }+ }+});- for (; i < ilen; ++i) {- if (!isNaN(scale.getRightValue(dataset.data[i]))) {- rects[i].draw();- }- }+function xRange(mouseX) {+ var vm = this._view;+ return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;+}- helpers.canvas.unclipArea(chart.ctx);- },- });+function yRange(mouseY) {+ var vm = this._view;+ return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;+}- Chart.controllers.horizontalBar = Chart.controllers.bar.extend({- /**- * @private- */- getValueScaleId: function() {- return this.getMeta().xAxisID;- },+var element_point = core_element.extend({+ _type: 'point',- /**- * @private- */- getIndexScaleId: function() {- return this.getMeta().yAxisID;- }- });-};+ 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;+ },-},{"26":26,"41":41,"46":46}],16:[function(require,module,exports){-'use strict';+ inLabelRange: xRange,+ inXRange: xRange,+ inYRange: yRange,-var defaults = require(26);-var elements = require(41);-var helpers = require(46);+ getCenterPoint: function() {+ var vm = this._view;+ return {+ x: vm.x,+ y: vm.y+ };+ },-defaults._set('bubble', {- hover: {- mode: 'single'+ getArea: function() {+ return Math.PI * Math.pow(this._view.radius, 2);},- 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'- }]+ tooltipPosition: function() {+ var vm = this._view;+ return {+ x: vm.x,+ y: vm.y,+ padding: vm.radius + vm.borderWidth+ };},- 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 + ')';- }+ 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;-module.exports = function(Chart) {+core_defaults._set('global', {+ elements: {+ rectangle: {+ backgroundColor: defaultColor$2,+ borderColor: defaultColor$2,+ borderSkipped: 'bottom',+ borderWidth: 0+ }+ }+});- Chart.controllers.bubble = Chart.DatasetController.extend({- /**- * @protected- */- dataElementType: elements.Point,+function isVertical(vm) {+ return vm && vm.width !== undefined;+}- /**- * @protected- */- update: function(reset) {- var me = this;- var meta = me.getMeta();- var points = meta.data;-- // Update Points- helpers.each(points, function(point, index) {- me.updateElement(point, index, reset);- });- },+/**+ * 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;- /**- * @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,- };+ 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;+ }- point.pivot();- },+ return {+ left: x1,+ top: y1,+ right: x2,+ bottom: y2+ };+}- /**- * @protected- */- setHoverStyle: function(point) {- var model = point._model;- var options = point._options;- point.$previousStyle = {- backgroundColor: model.backgroundColor,- borderColor: model.borderColor,- borderWidth: model.borderWidth,- radius: model.radius- };- model.backgroundColor = helpers.valueOrDefault(options.hoverBackgroundColor, helpers.getHoverColor(options.backgroundColor));- model.borderColor = helpers.valueOrDefault(options.hoverBorderColor, helpers.getHoverColor(options.borderColor));- model.borderWidth = helpers.valueOrDefault(options.hoverBorderWidth, options.borderWidth);- model.radius = options.radius + options.hoverRadius;- },+function swap(orig, v1, v2) {+ return orig === v1 ? v2 : orig === v2 ? v1 : orig;+}- /**- * @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 resolve = helpers.options.resolve;- var data = dataset.data[index];- var values = {};- var i, ilen, key;-- // Scriptable options- var context = {- chart: chart,- dataIndex: index,- dataset: dataset,- datasetIndex: me.index- };+function parseBorderSkipped(vm) {+ var edge = vm.borderSkipped;+ var res = {};- var keys = [- 'backgroundColor',- 'borderColor',- 'borderWidth',- 'hoverBackgroundColor',- 'hoverBorderColor',- 'hoverBorderWidth',- 'hoverRadius',- 'hitRadius',- 'pointStyle',- 'rotation'- ];+ if (!edge) {+ return res;+ }- for (i = 0, ilen = keys.length; i < ilen; ++i) {- key = keys[i];- values[key] = resolve([- custom[key],- dataset[key],- options[key]- ], context, index);- }+ 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+ };+}- // Custom radius resolution- values.radius = resolve([- custom.radius,- data ? data.r : undefined,- dataset.radius,- options.radius- ], context, index);- return values;+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}- });-};+ };+}-},{"26":26,"41":41,"46":46}],17:[function(require,module,exports){-'use strict';+function inRange(vm, x, y) {+ var skipX = x === null;+ var skipY = y === null;+ var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm);-var defaults = require(26);-var elements = require(41);-var helpers = require(46);+ return bounds+ && (skipX || x >= bounds.left && x <= bounds.right)+ && (skipY || y >= bounds.top && y <= bounds.bottom);+}-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('<ul class="' + chart.id + '-legend">');+var element_rectangle = core_element.extend({+ _type: 'rectangle',- var data = chart.data;- var datasets = data.datasets;- var labels = data.labels;+ draw: function() {+ var ctx = this._chart.ctx;+ var vm = this._view;+ var rects = boundingRects(vm);+ var outer = rects.outer;+ var inner = rects.inner;- if (datasets.length) {- for (var i = 0; i < datasets[0].data.length; ++i) {- text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');- if (labels[i]) {- text.push(labels[i]);- }- text.push('</li>');- }+ ctx.fillStyle = vm.backgroundColor;+ ctx.fillRect(outer.x, outer.y, outer.w, outer.h);++ if (outer.w === inner.w && outer.h === inner.h) {+ return;}- text.push('</ul>');- return text.join('');+ 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();},- 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 valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;- var arcOpts = chart.options.elements.arc;- var fill = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);- var stroke = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);- var bw = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);- return {- text: label,- fillStyle: fill,- strokeStyle: stroke,- lineWidth: bw,- hidden: isNaN(ds.data[i]) || meta.data[i].hidden,+ height: function() {+ var vm = this._view;+ return vm.base - vm.y;+ },- // Extra data used for toggling the correct item- index: i- };- });- }- return [];- }- },+ 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);+ },- onClick: function(e, legendItem) {- var index = legendItem.index;- var chart = this.chart;- var i, ilen, meta;+ inXRange: function(mouseX) {+ return inRange(this._view, mouseX, null);+ },- 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;- }- }+ inYRange: function(mouseY) {+ return inRange(this._view, null, mouseY);+ },- chart.update();+ 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};},- // The percentage of the chart that we cut out of the middle.- cutoutPercentage: 50,+ getArea: function() {+ var vm = this._view;- // The rotation of the chart, where the first data arc begins.- rotation: Math.PI * -0.5,+ return isVertical(vm)+ ? vm.width * Math.abs(vm.y - vm.base)+ : vm.height * Math.abs(vm.x - vm.base);+ },- // The total circumference of the chart.- circumference: Math.PI * 2.0,+ tooltipPosition: function() {+ var vm = this._view;+ return {+ x: vm.x,+ y: vm.y+ };+ }+});- // 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];+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;- if (helpers.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;- }+var deprecated = helpers$1._deprecated;+var valueOrDefault$3 = helpers$1.valueOrDefault;- return dataLabel;+core_defaults._set('bar', {+ hover: {+ mode: 'label'+ },++ scales: {+ xAxes: [{+ type: 'category',+ offset: true,+ gridLines: {+ offsetGridLines: true}- }+ }],++ yAxes: [{+ type: 'linear'+ }]}});-defaults._set('pie', helpers.clone(defaults.doughnut));-defaults._set('pie', {- cutoutPercentage: 0+core_defaults._set('global', {+ datasets: {+ bar: {+ categoryPercentage: 0.8,+ barPercentage: 0.9+ }+ }});-module.exports = function(Chart) {+/**+ * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.+ * @private+ */+function computeMinSampleSize(scale, pixels) {+ var min = scale._length;+ var prev, curr, i, ilen;- Chart.controllers.doughnut = Chart.controllers.pie = Chart.DatasetController.extend({+ for (i = 1, ilen = pixels.length; i < ilen; ++i) {+ min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));+ }- dataElementType: elements.Arc,+ for (i = 0, ilen = scale.getTicks().length; i < ilen; ++i) {+ curr = scale.getPixelForTick(i);+ min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min;+ prev = curr;+ }- linkScales: helpers.noop,+ return min;+}- // 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;+/**+ * 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 min = helpers$1.isNullOrUndef(thickness)+ ? computeMinSampleSize(ruler.scale, ruler.pixels)+ : -1;+ var size, ratio;- for (var j = 0; j < datasetIndex; ++j) {- if (this.chart.isDatasetVisible(j)) {- ++ringIndex;- }- }+ if (helpers$1.isNullOrUndef(thickness)) {+ size = 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 ringIndex;- },+ return {+ chunk: size / count,+ ratio: ratio,+ start: curr - (size / 2)+ };+}- update: function(reset) {- var me = this;- var chart = me.chart;- var chartArea = chart.chartArea;- var opts = chart.options;- var arcOpts = opts.elements.arc;- var availableWidth = chartArea.right - chartArea.left - arcOpts.borderWidth;- var availableHeight = chartArea.bottom - chartArea.top - arcOpts.borderWidth;- var minSize = Math.min(availableWidth, availableHeight);- var offset = {x: 0, y: 0};- var meta = me.getMeta();- var cutoutPercentage = opts.cutoutPercentage;- var circumference = opts.circumference;-- // 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};- }-- chart.borderWidth = me.getMaxBorderWidth(meta.data);- 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) / chart.getVisibleDatasetCount();- chart.offsetX = offset.x * chart.outerRadius;- chart.offsetY = offset.y * chart.outerRadius;-- meta.total = me.calculateTotal();-- me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index));- me.innerRadius = Math.max(me.outerRadius - chart.radiusLength, 0);-- helpers.each(meta.data, function(arc, index) {- me.updateElement(arc, index, reset);- });- },+/**+ * 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;- 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 valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;-- helpers.extend(arc, {- // Utility- _datasetIndex: me.index,- _index: index,-- // Desired view properties- _model: {- x: centerX + chart.offsetX,- y: centerY + chart.offsetY,- startAngle: startAngle,- endAngle: endAngle,- circumference: circumference,- outerRadius: outerRadius,- innerRadius: innerRadius,- label: valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])- }- });+ 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);+ }- var model = arc._model;+ if (next === null) {+ // last data: its size is also double based on the previous point.+ next = curr + curr - prev;+ }- // Resets the visual styles- var custom = arc.custom || {};- var valueOrDefault = helpers.valueAtIndexOrDefault;- var elementOpts = this.chart.options.elements.arc;- model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueOrDefault(dataset.backgroundColor, index, elementOpts.backgroundColor);- model.borderColor = custom.borderColor ? custom.borderColor : valueOrDefault(dataset.borderColor, index, elementOpts.borderColor);- model.borderWidth = custom.borderWidth ? custom.borderWidth : valueOrDefault(dataset.borderWidth, index, elementOpts.borderWidth);+ start = curr - (curr - Math.min(prev, next)) / 2 * percent;+ size = Math.abs(next - prev) / 2 * percent;- // 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;- }+ return {+ chunk: size / ruler.stackCount,+ ratio: options.barPercentage,+ start: start+ };+}- model.endAngle = model.startAngle + model.circumference;- }+var controller_bar = core_datasetController.extend({- arc.pivot();- },+ dataElementType: elements.Rectangle,- calculateTotal: function() {- var dataset = this.getDataset();- var meta = this.getMeta();- var total = 0;- var value;+ /**+ * @private+ */+ _dataElementOptions: [+ 'backgroundColor',+ 'borderColor',+ 'borderSkipped',+ 'borderWidth',+ 'barPercentage',+ 'barThickness',+ 'categoryPercentage',+ 'maxBarThickness',+ 'minBarLength'+ ],- helpers.each(meta.data, function(element, index) {- value = dataset.data[index];- if (!isNaN(value) && !element.hidden) {- total += Math.abs(value);- }- });+ initialize: function() {+ var me = this;+ var meta, scaleOpts;- /* if (total === 0) {- total = NaN;- }*/+ core_datasetController.prototype.initialize.apply(me, arguments);- return total;- },+ meta = me.getMeta();+ meta.stack = me.getDataset().stack;+ meta.bar = true;- calculateCircumference: function(value) {- var total = this.getMeta().total;- if (total > 0 && !isNaN(value)) {- return (Math.PI * 2.0) * (Math.abs(value) / total);- }- return 0;- },+ scaleOpts = me._getIndexScale().options;+ deprecated('bar chart', scaleOpts.barPercentage, 'scales.[x/y]Axes.barPercentage', 'dataset.barPercentage');+ deprecated('bar chart', scaleOpts.barThickness, 'scales.[x/y]Axes.barThickness', 'dataset.barThickness');+ deprecated('bar chart', scaleOpts.categoryPercentage, 'scales.[x/y]Axes.categoryPercentage', 'dataset.categoryPercentage');+ deprecated('bar chart', me._getValueScale().options.minBarLength, 'scales.[x/y]Axes.minBarLength', 'dataset.minBarLength');+ deprecated('bar chart', scaleOpts.maxBarThickness, 'scales.[x/y]Axes.maxBarThickness', 'dataset.maxBarThickness');+ },- // gets the max border or hover width to properly scale pie charts- getMaxBorderWidth: function(arcs) {- var max = 0;- var index = this.index;- var length = arcs.length;- var borderWidth;- var hoverWidth;+ update: function(reset) {+ var me = this;+ var rects = me.getMeta().data;+ var i, ilen;- for (var i = 0; i < length; i++) {- borderWidth = arcs[i]._model ? arcs[i]._model.borderWidth : 0;- hoverWidth = arcs[i]._chart ? arcs[i]._chart.config.data.datasets[index].hoverBorderWidth : 0;+ me._ruler = me.getRuler();- max = borderWidth > max ? borderWidth : max;- max = hoverWidth > max ? hoverWidth : max;- }- return max;+ for (i = 0, ilen = rects.length; i < ilen; ++i) {+ me.updateElement(rects[i], i, reset);}- });-};+ },-},{"26":26,"41":41,"46":46}],18:[function(require,module,exports){-'use strict';+ updateElement: function(rectangle, index, reset) {+ var me = this;+ var meta = me.getMeta();+ var dataset = me.getDataset();+ var options = me._resolveDataElementOptions(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]+ };-var defaults = require(26);-var elements = require(41);-var helpers = require(46);+ if (helpers$1.isArray(dataset.data[index])) {+ rectangle._model.borderSkipped = null;+ }-defaults._set('line', {- showLines: true,- spanGaps: false,+ me._updateElementGeometry(rectangle, index, reset, options);- hover: {- mode: 'label'+ rectangle.pivot();},- scales: {- xAxes: [{- type: 'category',- id: 'x-axis-0'- }],- yAxes: [{- type: 'linear',- id: 'y-axis-0'- }]- }-});+ /**+ * @private+ */+ _updateElementGeometry: function(rectangle, index, reset, options) {+ 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, options);+ var ipixels = me.calculateBarIndexPixels(me.index, index, ruler, options);++ 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;+ },-module.exports = function(Chart) {+ /**+ * 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 scale = me._getIndexScale();+ var metasets = scale._getMatchingVisibleMetas(me._type);+ var stacked = scale.options.stacked;+ var ilen = metasets.length;+ var stacks = [];+ var i, meta;- function lineEnabled(dataset, options) {- return helpers.valueOrDefault(dataset.showLine, options.showLines);- }+ for (i = 0; i < ilen; ++i) {+ meta = metasets[i];+ // stacked | meta.stack+ // | found | not found | undefined+ // false | x | x | x+ // true | | x |+ // undefined | | x | x+ if (stacked === false || stacks.indexOf(meta.stack) === -1 ||+ (stacked === undefined && meta.stack === undefined)) {+ stacks.push(meta.stack);+ }+ if (meta.index === last) {+ break;+ }+ }- Chart.controllers.line = Chart.DatasetController.extend({+ return stacks;+ },- datasetElementType: elements.Line,+ /**+ * Returns the effective number of stacks based on groups and bar visibility.+ * @private+ */+ getStackCount: function() {+ return this._getStacks().length;+ },- dataElementType: elements.Point,+ /**+ * 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- update: function(reset) {- var me = this;- var meta = me.getMeta();- var line = meta.dataset;- var points = meta.data || [];- var options = me.chart.options;- var lineElementOptions = options.elements.line;- var scale = me.getScaleForId(meta.yAxisID);- var i, ilen, custom;- var dataset = me.getDataset();- var showLine = lineEnabled(dataset, options);+ return (index === -1)+ ? stacks.length - 1+ : index;+ },- // Update Line- if (showLine) {- custom = line.custom || {};+ /**+ * @private+ */+ getRuler: function() {+ var me = this;+ var scale = me._getIndexScale();+ var pixels = [];+ var i, ilen;- // 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;- }+ for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {+ pixels.push(scale.getPixelForValue(null, i, me.index));+ }- // Utility- line._scale = scale;- line._datasetIndex = me.index;- // Data- line._children = points;- // Model- line._model = {- // Appearance- // 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- spanGaps: dataset.spanGaps ? dataset.spanGaps : options.spanGaps,- tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension),- backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),- borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),- borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),- borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),- borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),- borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),- borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),- fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),- steppedLine: custom.steppedLine ? custom.steppedLine : helpers.valueOrDefault(dataset.steppedLine, lineElementOptions.stepped),- cubicInterpolationMode: custom.cubicInterpolationMode ? custom.cubicInterpolationMode : helpers.valueOrDefault(dataset.cubicInterpolationMode, lineElementOptions.cubicInterpolationMode),- };+ return {+ pixels: pixels,+ start: scale._startPixel,+ end: scale._endPixel,+ stackCount: me.getStackCount(),+ scale: scale+ };+ },- line.pivot();- }+ /**+ * Note: pixel values are not clamped to the scale area.+ * @private+ */+ calculateBarValuePixels: function(datasetIndex, index, options) {+ var me = this;+ var chart = me.chart;+ var scale = me._getValueScale();+ var isHorizontal = scale.isHorizontal();+ var datasets = chart.data.datasets;+ var metasets = scale._getMatchingVisibleMetas(me._type);+ var value = scale._parseValue(datasets[datasetIndex].data[index]);+ var minBarLength = options.minBarLength;+ var stacked = scale.options.stacked;+ var stack = me.getMeta().stack;+ var start = value.start === undefined ? 0 : value.max >= 0 && value.min >= 0 ? value.min : value.max;+ var length = value.start === undefined ? value.end : value.max >= 0 && value.min >= 0 ? value.max - value.min : value.min - value.max;+ var ilen = metasets.length;+ var i, imeta, ivalue, base, head, size, stackLength;++ if (stacked || (stacked === undefined && stack !== undefined)) {+ for (i = 0; i < ilen; ++i) {+ imeta = metasets[i];- // Update Points- for (i = 0, ilen = points.length; i < ilen; ++i) {- me.updateElement(points[i], i, reset);- }+ if (imeta.index === datasetIndex) {+ break;+ }- if (showLine && line._model.tension !== 0) {- me.updateBezierControlPoints();- }+ if (imeta.stack === stack) {+ stackLength = scale._parseValue(datasets[imeta.index].data[index]);+ ivalue = stackLength.start === undefined ? stackLength.end : stackLength.min >= 0 && stackLength.max >= 0 ? stackLength.max : stackLength.min;- // Now pivot the point for animation- for (i = 0, ilen = points.length; i < ilen; ++i) {- points[i].pivot();+ if ((value.min < 0 && ivalue < 0) || (value.max >= 0 && ivalue > 0)) {+ start += ivalue;+ }+ }}- },+ }- getPointBackgroundColor: function(point, index) {- var backgroundColor = this.chart.options.elements.point.backgroundColor;- var dataset = this.getDataset();- var custom = point.custom || {};+ base = scale.getPixelForValue(start);+ head = scale.getPixelForValue(start + length);+ size = head - base;- if (custom.backgroundColor) {- backgroundColor = custom.backgroundColor;- } else if (dataset.pointBackgroundColor) {- backgroundColor = helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, backgroundColor);- } else if (dataset.backgroundColor) {- backgroundColor = dataset.backgroundColor;+ if (minBarLength !== undefined && Math.abs(size) < minBarLength) {+ size = minBarLength;+ if (length >= 0 && !isHorizontal || length < 0 && isHorizontal) {+ head = base - minBarLength;+ } else {+ head = base + minBarLength;}+ }- return backgroundColor;- },+ return {+ size: size,+ base: base,+ head: head,+ center: head + size / 2+ };+ },++ /**+ * @private+ */+ calculateBarIndexPixels: function(datasetIndex, index, ruler, options) {+ var me = this;+ var range = options.barThickness === 'flex'+ ? computeFlexCategoryTraits(index, ruler, options)+ : computeFitCategoryTraits(index, ruler, options);- getPointBorderColor: function(point, index) {- var borderColor = this.chart.options.elements.point.borderColor;- var dataset = this.getDataset();- var custom = point.custom || {};+ var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);+ var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);+ var size = Math.min(+ valueOrDefault$3(options.maxBarThickness, Infinity),+ range.chunk * range.ratio);- if (custom.borderColor) {- borderColor = custom.borderColor;- } else if (dataset.pointBorderColor) {- borderColor = helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, borderColor);- } else if (dataset.borderColor) {- borderColor = dataset.borderColor;- }+ return {+ base: center - size / 2,+ head: center + size / 2,+ center: center,+ size: size+ };+ },- return borderColor;- },+ 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;- getPointBorderWidth: function(point, index) {- var borderWidth = this.chart.options.elements.point.borderWidth;- var dataset = this.getDataset();- var custom = point.custom || {};+ helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);- if (!isNaN(custom.borderWidth)) {- borderWidth = custom.borderWidth;- } else if (!isNaN(dataset.pointBorderWidth) || helpers.isArray(dataset.pointBorderWidth)) {- borderWidth = helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, borderWidth);- } else if (!isNaN(dataset.borderWidth)) {- borderWidth = dataset.borderWidth;+ for (; i < ilen; ++i) {+ var val = scale._parseValue(dataset.data[i]);+ if (!isNaN(val.min) && !isNaN(val.max)) {+ rects[i].draw();}+ }- return borderWidth;- },-- getPointRotation: function(point, index) {- var pointRotation = this.chart.options.elements.point.rotation;- var dataset = this.getDataset();- var custom = point.custom || {};+ helpers$1.canvas.unclipArea(chart.ctx);+ },- if (!isNaN(custom.rotation)) {- pointRotation = custom.rotation;- } else if (!isNaN(dataset.pointRotation) || helpers.isArray(dataset.pointRotation)) {- pointRotation = helpers.valueAtIndexOrDefault(dataset.pointRotation, index, pointRotation);- }- return pointRotation;- },+ /**+ * @private+ */+ _resolveDataElementOptions: function() {+ var me = this;+ var values = helpers$1.extend({}, core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments));+ var indexOpts = me._getIndexScale().options;+ var valueOpts = me._getValueScale().options;- 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 pointOptions = me.chart.options.elements.point;- var x, y;+ values.barPercentage = valueOrDefault$3(indexOpts.barPercentage, values.barPercentage);+ values.barThickness = valueOrDefault$3(indexOpts.barThickness, values.barThickness);+ values.categoryPercentage = valueOrDefault$3(indexOpts.categoryPercentage, values.categoryPercentage);+ values.maxBarThickness = valueOrDefault$3(indexOpts.maxBarThickness, values.maxBarThickness);+ values.minBarLength = valueOrDefault$3(valueOpts.minBarLength, values.minBarLength);- // Compatibility: If the properties are defined with only the old name, use those values- if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {- dataset.pointRadius = dataset.radius;- }- if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {- dataset.pointHitRadius = dataset.hitRadius;- }+ return values;+ }- 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._datasetIndex = datasetIndex;- point._index = index;+var valueOrDefault$4 = helpers$1.valueOrDefault;+var resolve$1 = helpers$1.options.resolve;- // Desired view properties- point._model = {- x: x,- y: y,- skip: custom.skip || isNaN(x) || isNaN(y),- // Appearance- radius: custom.radius || helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointOptions.radius),- pointStyle: custom.pointStyle || helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointOptions.pointStyle),- rotation: me.getPointRotation(point, index),- backgroundColor: me.getPointBackgroundColor(point, index),- borderColor: me.getPointBorderColor(point, index),- borderWidth: me.getPointBorderWidth(point, index),- tension: meta.dataset._model ? meta.dataset._model.tension : 0,- steppedLine: meta.dataset._model ? meta.dataset._model.steppedLine : false,- // Tooltip- hitRadius: custom.hitRadius || helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointOptions.hitRadius)- };- },+core_defaults._set('bubble', {+ hover: {+ mode: 'single'+ },- 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;- }- }- }+ 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'+ }]+ },- var rightValue = Number(yScale.getRightValue(value));- if (rightValue < 0) {- return yScale.getPixelForValue(sumNeg + rightValue);- }- return yScale.getPixelForValue(sumPos + rightValue);+ 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 + ')';}+ }+ }+});- return yScale.getPixelForValue(value);- },+var controller_bubble = core_datasetController.extend({+ /**+ * @protected+ */+ dataElementType: elements.Point,- updateBezierControlPoints: function() {- var me = this;- var meta = me.getMeta();- var area = me.chart.chartArea;- var points = (meta.data || []);- var i, ilen, point, model, controlPoints;-- // Only consider points that are drawn in case the spanGaps option is used- if (meta.dataset._model.spanGaps) {- points = points.filter(function(pt) {- return !pt._model.skip;- });- }+ /**+ * @private+ */+ _dataElementOptions: [+ 'backgroundColor',+ 'borderColor',+ 'borderWidth',+ 'hoverBackgroundColor',+ 'hoverBorderColor',+ 'hoverBorderWidth',+ 'hoverRadius',+ 'hitRadius',+ 'pointStyle',+ 'rotation'+ ],- function capControlPoint(pt, min, max) {- return Math.max(Math.min(pt, max), min);- }+ /**+ * @protected+ */+ update: function(reset) {+ var me = this;+ var meta = me.getMeta();+ var points = meta.data;- if (meta.dataset._model.cubicInterpolationMode === 'monotone') {- helpers.splineCurveMonotone(points);- } else {- for (i = 0, ilen = points.length; i < ilen; ++i) {- point = points[i];- model = point._model;- controlPoints = helpers.splineCurve(- helpers.previousItem(points, i)._model,- model,- helpers.nextItem(points, i)._model,- meta.dataset._model.tension- );- model.controlPointPreviousX = controlPoints.previous.x;- model.controlPointPreviousY = controlPoints.previous.y;- model.controlPointNextX = controlPoints.next.x;- model.controlPointNextY = controlPoints.next.y;- }- }+ // Update Points+ helpers$1.each(points, function(point, index) {+ me.updateElement(point, index, reset);+ });+ },- if (me.chart.options.elements.line.capBezierPoints) {- for (i = 0, ilen = points.length; i < ilen; ++i) {- model = points[i]._model;- model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);- model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);- model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);- model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);- }- }- },+ /**+ * @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._resolveDataElementOptions(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,+ };- 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.canvas.clipArea(chart.ctx, {- left: area.left,- right: area.right,- top: area.top - halfBorderWidth,- bottom: area.bottom + halfBorderWidth- });+ point.pivot();+ },- meta.dataset.draw();+ /**+ * @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+ };- helpers.canvas.unclipArea(chart.ctx);- }+ 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);+ model.radius = options.radius + options.hoverRadius;+ },- // Draw the points- for (; i < ilen; ++i) {- points[i].draw(area);- }- },+ /**+ * @private+ */+ _resolveDataElementOptions: function(point, index) {+ var me = this;+ var chart = me.chart;+ var dataset = me.getDataset();+ var custom = point.custom || {};+ var data = dataset.data[index] || {};+ var values = core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments);++ // Scriptable options+ var context = {+ chart: chart,+ dataIndex: index,+ dataset: dataset,+ datasetIndex: me.index+ };- setHoverStyle: function(element) {- // Point- var dataset = this.chart.data.datasets[element._datasetIndex];- var index = element._index;- var custom = element.custom || {};- var model = element._model;-- element.$previousStyle = {- backgroundColor: model.backgroundColor,- borderColor: model.borderColor,- borderWidth: model.borderWidth,- radius: model.radius- };+ // In case values were cached (and thus frozen), we need to clone the values+ if (me._cachedDataOpts === values) {+ values = helpers$1.extend({}, values);+ }- model.backgroundColor = custom.hoverBackgroundColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));- model.borderColor = custom.hoverBorderColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));- model.borderWidth = custom.hoverBorderWidth || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);- model.radius = custom.hoverRadius || helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);- },- });-};+ // Custom radius resolution+ values.radius = resolve$1([+ custom.radius,+ data.r,+ me._config.radius,+ chart.options.elements.point.radius+ ], context, index);-},{"26":26,"41":41,"46":46}],19:[function(require,module,exports){-'use strict';+ return values;+ }+});-var defaults = require(26);-var elements = require(41);-var helpers = require(46);+var valueOrDefault$5 = helpers$1.valueOrDefault;-defaults._set('polarArea', {- scale: {- type: 'radialLinear',- angleLines: {- display: false- },- gridLines: {- circular: true- },- pointLabels: {- display: false- },- ticks: {- beginAtZero: true- }- },+var PI$1 = Math.PI;+var DOUBLE_PI$1 = PI$1 * 2;+var HALF_PI$1 = PI$1 / 2;- // Boolean - Whether to animate the rotation of the chart+core_defaults._set('doughnut', {animation: {+ // Boolean - Whether we animate the rotation of the DoughnutanimateRotate: true,- animateScale: true+ // Boolean - Whether we animate scaling the Doughnut from the centre+ animateScale: false+ },+ hover: {+ mode: 'single'},-- startAngle: -0.5 * Math.PI,legendCallback: function(chart) {- var text = [];- text.push('<ul class="' + chart.id + '-legend">');-+ var list = document.createElement('ul');var data = chart.data;var datasets = data.datasets;var labels = data.labels;+ var i, ilen, listItem, listItemSpan;+ list.setAttribute('class', chart.id + '-legend');if (datasets.length) {- for (var i = 0; i < datasets[0].data.length; ++i) {- text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');+ for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {+ listItem = list.appendChild(document.createElement('li'));+ listItemSpan = listItem.appendChild(document.createElement('span'));+ listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];if (labels[i]) {- text.push(labels[i]);+ listItem.appendChild(document.createTextNode(labels[i]));}- text.push('</li>');}}- text.push('</ul>');- return text.join('');+ return list.outerHTML;},legend: {labels: {@@ -3244,21 +5361,14 @@ defaults._set('polarArea', {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.custom || {};- var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;- var arcOpts = chart.options.elements.arc;- var fill = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);- var stroke = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);- var bw = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);+ var style = meta.controller.getStyle(i);return {text: label,- fillStyle: fill,- strokeStyle: stroke,- lineWidth: bw,- hidden: isNaN(ds.data[i]) || meta.data[i].hidden,+ fillStyle: style.backgroundColor,+ strokeStyle: style.borderColor,+ lineWidth: style.borderWidth,+ hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,// Extra data used for toggling the correct itemindex: i@@ -3276,11181 +5386,10766 @@ defaults._set('polarArea', {for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {meta = chart.getDatasetMeta(i);- meta.data[index].hidden = !meta.data[index].hidden;+ // toggle visibility of index if exists+ if (meta.data[index]) {+ meta.data[index].hidden = !meta.data[index].hidden;+ }}chart.update();}},- // Need to override these to give a nice default- tooltips: {- callbacks: {- title: function() {- return '';- },- label: function(item, data) {- return data.labels[item.index] + ': ' + item.yLabel;- }- }- }-});--module.exports = function(Chart) {-- Chart.controllers.polarArea = Chart.DatasetController.extend({-- dataElementType: elements.Arc,-- linkScales: helpers.noop,-- update: function(reset) {- var me = this;- var dataset = me.getDataset();- var meta = me.getMeta();- var start = me.chart.options.startAngle || 0;- var starts = me._starts = [];- var angles = me._angles = [];- var i, ilen, angle;-- me._updateRadius();-- meta.count = me.countVisibleElements();-- for (i = 0, ilen = dataset.data.length; i < ilen; i++) {- starts[i] = start;- angle = me._computeAngle(i);- angles[i] = angle;- start += angle;- }-- helpers.each(meta.data, function(arc, index) {- me.updateElement(arc, index, reset);- });- },-- /**- * @private- */- _updateRadius: function() {- var me = this;- var chart = me.chart;- var chartArea = chart.chartArea;- var opts = chart.options;- var arcOpts = opts.elements.arc;- var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);-- chart.outerRadius = Math.max((minSize - arcOpts.borderWidth / 2) / 2, 0);- chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);- chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();-- me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);- me.innerRadius = me.outerRadius - chart.radiusLength;- },-- updateElement: function(arc, index, reset) {- var me = this;- var chart = me.chart;- var dataset = me.getDataset();- var opts = chart.options;- var animationOpts = opts.animation;- var scale = chart.scale;- var labels = chart.data.labels;-- var centerX = scale.xCenter;- var centerY = scale.yCenter;-- // var negHalfPI = -0.5 * Math.PI;- var datasetStartAngle = opts.startAngle;- var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);- var startAngle = me._starts[index];- var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);-- var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);-- helpers.extend(arc, {- // Utility- _datasetIndex: me.index,- _index: index,- _scale: scale,-- // Desired view properties- _model: {- x: centerX,- y: centerY,- innerRadius: 0,- outerRadius: reset ? resetRadius : distance,- startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,- endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,- label: helpers.valueAtIndexOrDefault(labels, index, labels[index])- }- });-- // Apply border and fill style- var elementOpts = this.chart.options.elements.arc;- var custom = arc.custom || {};- var valueOrDefault = helpers.valueAtIndexOrDefault;- var model = arc._model;-- model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueOrDefault(dataset.backgroundColor, index, elementOpts.backgroundColor);- model.borderColor = custom.borderColor ? custom.borderColor : valueOrDefault(dataset.borderColor, index, elementOpts.borderColor);- model.borderWidth = custom.borderWidth ? custom.borderWidth : valueOrDefault(dataset.borderWidth, index, elementOpts.borderWidth);-- arc.pivot();- },-- countVisibleElements: function() {- var dataset = this.getDataset();- var meta = this.getMeta();- var count = 0;-- helpers.each(meta.data, function(element, index) {- if (!isNaN(dataset.data[index]) && !element.hidden) {- count++;- }- });-- return count;- },-- /**- * @private- */- _computeAngle: function(index) {- var me = this;- var count = this.getMeta().count;- var dataset = me.getDataset();- var meta = me.getMeta();-- if (isNaN(dataset.data[index]) || meta.data[index].hidden) {- return 0;- }-- // Scriptable options- var context = {- chart: me.chart,- dataIndex: index,- dataset: dataset,- datasetIndex: me.index- };-- return helpers.options.resolve([- me.chart.options.elements.arc.angle,- (2 * Math.PI) / count- ], context, index);- }- });-};--},{"26":26,"41":41,"46":46}],20:[function(require,module,exports){-'use strict';--var defaults = require(26);-var elements = require(41);-var helpers = require(46);--defaults._set('radar', {- scale: {- type: 'radialLinear'- },- elements: {- line: {- tension: 0 // no bezier in radar- }- }-});--module.exports = function(Chart) {-- Chart.controllers.radar = Chart.DatasetController.extend({-- datasetElementType: elements.Line,-- dataElementType: elements.Point,-- linkScales: helpers.noop,-- update: function(reset) {- var me = this;- var meta = me.getMeta();- var line = meta.dataset;- var points = meta.data;- var custom = line.custom || {};- var dataset = me.getDataset();- var lineElementOptions = me.chart.options.elements.line;- var scale = me.chart.scale;-- // 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;- }-- helpers.extend(meta.dataset, {- // Utility- _datasetIndex: me.index,- _scale: scale,- // Data- _children: points,- _loop: true,- // Model- _model: {- // Appearance- tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension),- backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),- borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),- borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),- fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),- borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),- borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),- borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),- borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),- }- });-- meta.dataset.pivot();-- // Update Points- helpers.each(points, function(point, index) {- me.updateElement(point, index, reset);- }, me);-- // Update bezier control points- me.updateBezierControlPoints();- },- updateElement: function(point, index, reset) {- var me = this;- var custom = point.custom || {};- var dataset = me.getDataset();- var scale = me.chart.scale;- var pointElementOptions = me.chart.options.elements.point;- var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);-- // Compatibility: If the properties are defined with only the old name, use those values- if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {- dataset.pointRadius = dataset.radius;- }- if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {- dataset.pointHitRadius = dataset.hitRadius;- }-- helpers.extend(point, {- // Utility- _datasetIndex: me.index,- _index: index,- _scale: scale,-- // Desired view properties- _model: {- x: reset ? scale.xCenter : pointPosition.x, // value not used in dataset scale, but we want a consistent API between scales- y: reset ? scale.yCenter : pointPosition.y,-- // Appearance- tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, me.chart.options.elements.line.tension),- radius: custom.radius ? custom.radius : helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius),- backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor),- borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor),- borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth),- pointStyle: custom.pointStyle ? custom.pointStyle : helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointElementOptions.pointStyle),- rotation: custom.rotation ? custom.rotation : helpers.valueAtIndexOrDefault(dataset.pointRotation, index, pointElementOptions.rotation),-- // Tooltip- hitRadius: custom.hitRadius ? custom.hitRadius : helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointElementOptions.hitRadius)- }- });-- point._model.skip = custom.skip ? custom.skip : (isNaN(point._model.x) || isNaN(point._model.y));- },- updateBezierControlPoints: function() {- var chartArea = this.chart.chartArea;- var meta = this.getMeta();-- helpers.each(meta.data, function(point, index) {- var model = point._model;- var controlPoints = helpers.splineCurve(- helpers.previousItem(meta.data, index, true)._model,- model,- helpers.nextItem(meta.data, index, true)._model,- model.tension- );-- // Prevent the bezier going outside of the bounds of the graph- model.controlPointPreviousX = Math.max(Math.min(controlPoints.previous.x, chartArea.right), chartArea.left);- model.controlPointPreviousY = Math.max(Math.min(controlPoints.previous.y, chartArea.bottom), chartArea.top);-- model.controlPointNextX = Math.max(Math.min(controlPoints.next.x, chartArea.right), chartArea.left);- model.controlPointNextY = Math.max(Math.min(controlPoints.next.y, chartArea.bottom), chartArea.top);-- // Now pivot the point for animation- point.pivot();- });- },-- setHoverStyle: function(point) {- // Point- var dataset = this.chart.data.datasets[point._datasetIndex];- var custom = point.custom || {};- var index = point._index;- var model = point._model;-- point.$previousStyle = {- backgroundColor: model.backgroundColor,- borderColor: model.borderColor,- borderWidth: model.borderWidth,- radius: model.radius- };-- model.radius = custom.hoverRadius ? custom.hoverRadius : helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);- model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));- model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));- model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);- },- });-};--},{"26":26,"41":41,"46":46}],21:[function(require,module,exports){-'use strict';--var defaults = require(26);--defaults._set('scatter', {- hover: {- mode: 'single'- },+ // The percentage of the chart that we cut out of the middle.+ cutoutPercentage: 50,- scales: {- xAxes: [{- id: 'x-axis-1', // need an ID so datasets can reference the scale- type: 'linear', // scatter should not use a category axis- position: 'bottom'- }],- yAxes: [{- id: 'y-axis-1',- type: 'linear',- position: 'left'- }]- },+ // The rotation of the chart, where the first data arc begins.+ rotation: -HALF_PI$1,- showLines: false,+ // The total circumference of the chart.+ circumference: DOUBLE_PI$1,+ // Need to override these to give a nice defaulttooltips: {callbacks: {title: function() {- return ''; // doesn't make sense for scatter since data are formatted as a point+ return '';},- label: function(item) {- return '(' + item.xLabel + ', ' + item.yLabel + ')';+ 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;}}}});-module.exports = function(Chart) {+var controller_doughnut = core_datasetController.extend({- // Scatter charts use line controllers- Chart.controllers.scatter = Chart.controllers.line;+ dataElementType: elements.Arc,-};+ linkScales: helpers$1.noop,-},{"26":26}],22:[function(require,module,exports){-'use strict';+ /**+ * @private+ */+ _dataElementOptions: [+ 'backgroundColor',+ 'borderColor',+ 'borderWidth',+ 'borderAlign',+ 'hoverBackgroundColor',+ 'hoverBorderColor',+ 'hoverBorderWidth',+ ],-var Element = require(27);+ // 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;-var exports = module.exports = 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+ for (var j = 0; j < datasetIndex; ++j) {+ if (this.chart.isDatasetVisible(j)) {+ ++ringIndex;+ }+ }- onAnimationProgress: null, // user specified callback to fire on each step of the animation- onAnimationComplete: null, // user specified callback to fire when the animation finishes-});+ return ringIndex;+ },-// DEPRECATIONS+ update: function(reset) {+ var me = this;+ var chart = me.chart;+ var chartArea = chart.chartArea;+ var opts = chart.options;+ var ratioX = 1;+ var ratioY = 1;+ var offsetX = 0;+ var offsetY = 0;+ var meta = me.getMeta();+ var arcs = meta.data;+ var cutout = opts.cutoutPercentage / 100 || 0;+ var circumference = opts.circumference;+ var chartWeight = me._getRingWeight(me.index);+ var maxWidth, maxHeight, i, ilen;++ // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc+ if (circumference < DOUBLE_PI$1) {+ var startAngle = opts.rotation % DOUBLE_PI$1;+ startAngle += startAngle >= PI$1 ? -DOUBLE_PI$1 : startAngle < -PI$1 ? DOUBLE_PI$1 : 0;+ var endAngle = startAngle + circumference;+ var startX = Math.cos(startAngle);+ var startY = Math.sin(startAngle);+ var endX = Math.cos(endAngle);+ var endY = Math.sin(endAngle);+ var contains0 = (startAngle <= 0 && endAngle >= 0) || endAngle >= DOUBLE_PI$1;+ var contains90 = (startAngle <= HALF_PI$1 && endAngle >= HALF_PI$1) || endAngle >= DOUBLE_PI$1 + HALF_PI$1;+ var contains180 = startAngle === -PI$1 || endAngle >= PI$1;+ var contains270 = (startAngle <= -HALF_PI$1 && endAngle >= -HALF_PI$1) || endAngle >= PI$1 + HALF_PI$1;+ var minX = contains180 ? -1 : Math.min(startX, startX * cutout, endX, endX * cutout);+ var minY = contains270 ? -1 : Math.min(startY, startY * cutout, endY, endY * cutout);+ var maxX = contains0 ? 1 : Math.max(startX, startX * cutout, endX, endX * cutout);+ var maxY = contains90 ? 1 : Math.max(startY, startY * cutout, endY, endY * cutout);+ ratioX = (maxX - minX) / 2;+ ratioY = (maxY - minY) / 2;+ offsetX = -(maxX + minX) / 2;+ offsetY = -(maxY + minY) / 2;+ }++ for (i = 0, ilen = arcs.length; i < ilen; ++i) {+ arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);+ }++ chart.borderWidth = me.getMaxBorderWidth();+ maxWidth = (chartArea.right - chartArea.left - chart.borderWidth) / ratioX;+ maxHeight = (chartArea.bottom - chartArea.top - chart.borderWidth) / ratioY;+ chart.outerRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);+ chart.innerRadius = Math.max(chart.outerRadius * cutout, 0);+ chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);+ chart.offsetX = offsetX * chart.outerRadius;+ chart.offsetY = offsetY * 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 / DOUBLE_PI$1);+ 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,-/**- * 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.prototype, 'animationObject', {- get: function() {- return this;- }-});+ // 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])+ }+ });-/**- * 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.prototype, 'chartInstance', {- get: function() {- return this.chart;- },- set: function(value) {- this.chart = value;- }-});+ var model = arc._model;-},{"27":27}],23:[function(require,module,exports){-/* global window: false */-'use strict';+ // 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;+ }-var defaults = require(26);-var helpers = require(46);+ model.endAngle = model.startAngle + model.circumference;+ }-defaults._set('global', {- animation: {- duration: 1000,- easing: 'easeOutQuart',- onProgress: helpers.noop,- onComplete: helpers.noop- }-});+ arc.pivot();+ },-module.exports = {- frameDuration: 17,- animations: [],- dropFrames: 0,- request: null,+ calculateTotal: function() {+ var dataset = this.getDataset();+ var meta = this.getMeta();+ var total = 0;+ var value;- /**- * @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;+ helpers$1.each(meta.data, function(element, index) {+ value = dataset.data[index];+ if (!isNaN(value) && !element.hidden) {+ total += Math.abs(value);+ }+ });- animation.chart = chart;+ /* if (total === 0) {+ total = NaN;+ }*/- if (!lazy) {- chart.animating = true;+ return total;+ },++ calculateCircumference: function(value) {+ var total = this.getMeta().total;+ if (total > 0 && !isNaN(value)) {+ return DOUBLE_PI$1 * (Math.abs(value) / total);}+ return 0;+ },- for (i = 0, ilen = animations.length; i < ilen; ++i) {- if (animations[i].chart === chart) {- animations[i] = animation;- return;+ // 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;+ }}}- 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();+ if (!arcs) {+ return 0;}- },- cancelAnimation: function(chart) {- var index = helpers.findIndex(this.animations, function(animation) {- return animation.chart === chart;- });+ for (i = 0, ilen = arcs.length; i < ilen; ++i) {+ arc = arcs[i];+ if (controller) {+ controller._configure();+ options = controller._resolveDataElementOptions(arc, i);+ } else {+ options = arc._options;+ }+ if (options.borderAlign !== 'inner') {+ borderWidth = options.borderWidth;+ hoverWidth = options.hoverBorderWidth;- if (index !== -1) {- this.animations.splice(index, 1);- chart.animating = false;+ max = borderWidth > max ? borderWidth : max;+ max = hoverWidth > max ? hoverWidth : max;+ }}+ return max;},- 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.requestAnimFrame.call(window, function() {- me.request = null;- me.startDigest();- });- }+ /**+ * @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$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));+ model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor));+ model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth);},/**+ * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly* @private*/- startDigest: function() {- var me = this;- var startTime = Date.now();- var framesToDrop = 0;+ _getRingWeightOffset: function(datasetIndex) {+ var ringWeightOffset = 0;- if (me.dropFrames > 1) {- framesToDrop = Math.floor(me.dropFrames);- me.dropFrames = me.dropFrames % 1;+ for (var i = 0; i < datasetIndex; ++i) {+ if (this.chart.isDatasetVisible(i)) {+ ringWeightOffset += this._getRingWeight(i);+ }}- me.advance(1 + framesToDrop);-- var endTime = Date.now();-- me.dropFrames += (endTime - startTime) / me.frameDuration;-- // Do we have more stuff to animate?- if (me.animations.length > 0) {- me.requestAnimationFrame();- }+ return ringWeightOffset;},/*** @private*/- advance: function(count) {- var animations = this.animations;- var animation, chart;- var i = 0;+ _getRingWeight: function(dataSetIndex) {+ return Math.max(valueOrDefault$5(this.chart.data.datasets[dataSetIndex].weight, 1), 0);+ },- while (i < animations.length) {- animation = animations[i];- chart = animation.chart;+ /**+ * 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);+ }+});- animation.currentStep = (animation.currentStep || 0) + count;- animation.currentStep = Math.min(animation.currentStep, animation.numSteps);+core_defaults._set('horizontalBar', {+ hover: {+ mode: 'index',+ axis: 'y'+ },- helpers.callback(animation.render, [chart, animation], chart);- helpers.callback(animation.onAnimationProgress, [animation], chart);+ scales: {+ xAxes: [{+ type: 'linear',+ position: 'bottom'+ }],- if (animation.currentStep >= animation.numSteps) {- helpers.callback(animation.onAnimationComplete, [animation], chart);- chart.animating = false;- animations.splice(i, 1);- } else {- ++i;+ yAxes: [{+ type: 'category',+ position: 'left',+ offset: true,+ gridLines: {+ offsetGridLines: true}- }- }-};--},{"26":26,"46":46}],24:[function(require,module,exports){-'use strict';--var Animation = require(22);-var animations = require(23);-var defaults = require(26);-var helpers = require(46);-var Interaction = require(29);-var layouts = require(31);-var platform = require(49);-var plugins = require(32);-var scaleService = require(34);-var Tooltip = require(36);+ }]+ },-module.exports = function(Chart) {+ elements: {+ rectangle: {+ borderSkipped: 'left'+ }+ },- // Create a dictionary of chart types, to allow for extension of existing types- Chart.types = {};+ tooltips: {+ mode: 'index',+ axis: 'y'+ }+});- // Store a reference to each instance - allowing us to globally resize chart instances on window resize.- // Destroy method on the chart will remove the instance of the chart from this reference.- Chart.instances = {};+core_defaults._set('global', {+ datasets: {+ horizontalBar: {+ categoryPercentage: 0.8,+ barPercentage: 0.9+ }+ }+});- // Controllers available for dataset visualization eg. bar, line, slice, etc.- Chart.controllers = {};+var controller_horizontalBar = controller_bar.extend({+ /**+ * @private+ */+ _getValueScaleId: function() {+ return this.getMeta().xAxisID;+ },/**- * Initializes the given config with global and chart default values.+ * @private*/- function initConfig(config) {- config = config || {};+ _getIndexScaleId: function() {+ return this.getMeta().yAxisID;+ }+});- // Do NOT use configMerge() for the data object because this method merges arrays- // and so would change references to labels and datasets, preventing data updates.- var data = config.data = config.data || {};- data.datasets = data.datasets || [];- data.labels = data.labels || [];+var valueOrDefault$6 = helpers$1.valueOrDefault;+var resolve$2 = helpers$1.options.resolve;+var isPointInArea = helpers$1.canvas._isPointInArea;++core_defaults._set('line', {+ showLines: true,+ spanGaps: false,- config.options = helpers.configMerge(- defaults.global,- defaults[config.type],- config.options || {});+ hover: {+ mode: 'label'+ },- return config;+ scales: {+ xAxes: [{+ type: 'category',+ id: 'x-axis-0'+ }],+ yAxes: [{+ type: 'linear',+ id: 'y-axis-0'+ }]}+});- /**- * Updates the config of the chart- * @param chart {Chart} chart to update the options for- */- function updateConfig(chart) {- var newOptions = chart.options;+function scaleClip(scale, halfBorderWidth) {+ var tickOpts = scale && scale.options.ticks || {};+ var reverse = tickOpts.reverse;+ var min = tickOpts.min === undefined ? halfBorderWidth : 0;+ var max = tickOpts.max === undefined ? halfBorderWidth : 0;+ return {+ start: reverse ? max : min,+ end: reverse ? min : max+ };+}- helpers.each(chart.scales, function(scale) {- layouts.removeBox(chart, scale);- });+function defaultClip(xScale, yScale, borderWidth) {+ var halfBorderWidth = borderWidth / 2;+ var x = scaleClip(xScale, halfBorderWidth);+ var y = scaleClip(yScale, halfBorderWidth);- newOptions = helpers.configMerge(- Chart.defaults.global,- Chart.defaults[chart.config.type],- newOptions);+ return {+ top: y.end,+ right: x.end,+ bottom: y.start,+ left: x.start+ };+}- chart.options = chart.config.options = newOptions;- chart.ensureScalesHaveIDs();- chart.buildOrUpdateScales();- // Tooltip- chart.tooltip._options = newOptions.tooltips;- chart.tooltip.initialize();- }+function toClip(value) {+ var t, r, b, l;- function positionIsHorizontal(position) {- return position === 'top' || position === 'bottom';+ if (helpers$1.isObject(value)) {+ t = value.top;+ r = value.right;+ b = value.bottom;+ l = value.left;+ } else {+ t = r = b = l = value;}- helpers.extend(Chart.prototype, /** @lends Chart */ {- /**- * @private- */- construct: function(item, config) {- var me = this;-- config = initConfig(config);-- var context = platform.acquireContext(item, config);- var canvas = context && context.canvas;- var height = canvas && canvas.height;- var width = canvas && canvas.width;-- me.id = helpers.uid();- me.ctx = context;- me.canvas = canvas;- me.config = config;- me.width = width;- me.height = height;- me.aspectRatio = height ? width / height : null;- me.options = config.options;- me._bufferedRender = false;-- /**- * Provided for backward compatibility, Chart and Chart.Controller have been merged,- * the "instance" still need to be defined since it might be called from plugins.- * @prop Chart#chart- * @deprecated since version 2.6.0- * @todo remove at version 3- * @private- */- me.chart = me;- me.controller = me; // chart.chart.controller #inception-- // Add the chart instance to the global namespace- Chart.instances[me.id] = me;-- // Define alias to the config data: `chart.data === chart.config.data`- Object.defineProperty(me, 'data', {- get: function() {- return me.config.data;- },- set: function(value) {- me.config.data = value;- }- });+ return {+ top: t,+ right: r,+ bottom: b,+ left: l+ };+}- if (!context || !canvas) {- // The given item is not a compatible context2d element, let's return before finalizing- // the chart initialization but after setting basic chart / controller properties that- // can help to figure out that the chart is not valid (e.g chart.canvas !== null);- // https://github.com/chartjs/Chart.js/issues/2807- console.error("Failed to create chart: can't acquire context from the given item");- return;- }- me.initialize();- me.update();- },+var controller_line = core_datasetController.extend({++ datasetElementType: elements.Line,++ dataElementType: elements.Point,++ /**+ * @private+ */+ _datasetElementOptions: [+ 'backgroundColor',+ 'borderCapStyle',+ 'borderColor',+ 'borderDash',+ 'borderDashOffset',+ 'borderJoinStyle',+ 'borderWidth',+ 'cubicInterpolationMode',+ 'fill'+ ],++ /**+ * @private+ */+ _dataElementOptions: {+ backgroundColor: 'pointBackgroundColor',+ borderColor: 'pointBorderColor',+ borderWidth: 'pointBorderWidth',+ hitRadius: 'pointHitRadius',+ hoverBackgroundColor: 'pointHoverBackgroundColor',+ hoverBorderColor: 'pointHoverBorderColor',+ hoverBorderWidth: 'pointHoverBorderWidth',+ hoverRadius: 'pointHoverRadius',+ pointStyle: 'pointStyle',+ radius: 'pointRadius',+ rotation: 'pointRotation'+ },++ update: function(reset) {+ var me = this;+ var meta = me.getMeta();+ var line = meta.dataset;+ var points = meta.data || [];+ var options = me.chart.options;+ var config = me._config;+ var showLine = me._showLine = valueOrDefault$6(config.showLine, options.showLines);+ var i, ilen;- /**- * @private- */- initialize: function() {- var me = this;+ me._xScale = me.getScaleForId(meta.xAxisID);+ me._yScale = me.getScaleForId(meta.yAxisID);- // Before init plugin notification- plugins.notify(me, 'beforeInit');+ // Update Line+ if (showLine) {+ // Compatibility: If the properties are defined with only the old name, use those values+ if (config.tension !== undefined && config.lineTension === undefined) {+ config.lineTension = config.tension;+ }- helpers.retinaScale(me, me.options.devicePixelRatio);+ // Utility+ line._scale = me._yScale;+ line._datasetIndex = me.index;+ // Data+ line._children = points;+ // Model+ line._model = me._resolveDatasetElementOptions(line);- me.bindEvents();+ line.pivot();+ }- if (me.options.responsive) {- // Initial resize before chart draws (must be silent to preserve initial animations).- me.resize(true);- }+ // Update Points+ for (i = 0, ilen = points.length; i < ilen; ++i) {+ me.updateElement(points[i], i, reset);+ }- // Make sure scales have IDs and are built before we build any controllers.- me.ensureScalesHaveIDs();- me.buildOrUpdateScales();- me.initToolTip();+ if (showLine && line._model.tension !== 0) {+ me.updateBezierControlPoints();+ }- // After init plugin notification- plugins.notify(me, 'afterInit');+ // Now pivot the point for animation+ for (i = 0, ilen = points.length; i < ilen; ++i) {+ points[i].pivot();+ }+ },- return me;- },+ 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 xScale = me._xScale;+ var yScale = me._yScale;+ var lineModel = meta.dataset._model;+ var x, y;- clear: function() {- helpers.canvas.clear(this);- return this;- },+ var options = me._resolveDataElementOptions(point, index);- stop: function() {- // Stops any current animation loop occurring- animations.cancelAnimation(this);- return this;- },+ x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);+ y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);- resize: function(silent) {- var me = this;- var options = me.options;- var canvas = me.canvas;- var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;+ // Utility+ point._xScale = xScale;+ point._yScale = yScale;+ point._options = options;+ point._datasetIndex = datasetIndex;+ point._index = index;- // the canvas render width and height will be casted to integers so make sure that- // the canvas display style uses the same integer values to avoid blurring effect.+ // 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$6(custom.tension, lineModel ? lineModel.tension : 0),+ steppedLine: lineModel ? lineModel.steppedLine : false,+ // Tooltip+ hitRadius: options.hitRadius+ };+ },- // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed- var newWidth = Math.max(0, Math.floor(helpers.getMaximumWidth(canvas)));- var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers.getMaximumHeight(canvas)));+ /**+ * @private+ */+ _resolveDatasetElementOptions: function(element) {+ var me = this;+ var config = me._config;+ var custom = element.custom || {};+ var options = me.chart.options;+ var lineOptions = options.elements.line;+ var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);- if (me.width === newWidth && me.height === newHeight) {- return;- }+ // 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$6(config.spanGaps, options.spanGaps);+ values.tension = valueOrDefault$6(config.lineTension, lineOptions.tension);+ values.steppedLine = resolve$2([custom.steppedLine, config.steppedLine, lineOptions.stepped]);+ values.clip = toClip(valueOrDefault$6(config.clip, defaultClip(me._xScale, me._yScale, values.borderWidth)));- canvas.width = me.width = newWidth;- canvas.height = me.height = newHeight;- canvas.style.width = newWidth + 'px';- canvas.style.height = newHeight + 'px';+ return values;+ },- helpers.retinaScale(me, options.devicePixelRatio);+ calculatePointY: function(value, index, datasetIndex) {+ var me = this;+ var chart = me.chart;+ var yScale = me._yScale;+ var sumPos = 0;+ var sumNeg = 0;+ var i, ds, dsMeta, stackedRightValue, rightValue, metasets, ilen;- if (!silent) {- // Notify any plugins about the resize- var newSize = {width: newWidth, height: newHeight};- plugins.notify(me, 'resize', [newSize]);+ if (yScale.options.stacked) {+ rightValue = +yScale.getRightValue(value);+ metasets = chart._getSortedVisibleDatasetMetas();+ ilen = metasets.length;- // Notify of resize- if (me.options.onResize) {- me.options.onResize(me, newSize);+ for (i = 0; i < ilen; ++i) {+ dsMeta = metasets[i];+ if (dsMeta.index === datasetIndex) {+ break;}- me.stop();- me.update({- duration: me.options.responsiveAnimationDuration- });+ ds = chart.data.datasets[dsMeta.index];+ if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id) {+ stackedRightValue = +yScale.getRightValue(ds.data[index]);+ if (stackedRightValue < 0) {+ sumNeg += stackedRightValue || 0;+ } else {+ sumPos += stackedRightValue || 0;+ }+ }}- },- ensureScalesHaveIDs: function() {- var options = this.options;- var scalesOptions = options.scales || {};- var scaleOptions = options.scale;-- helpers.each(scalesOptions.xAxes, function(xAxisOptions, index) {- xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index);- });+ if (rightValue < 0) {+ return yScale.getPixelForValue(sumNeg + rightValue);+ }+ return yScale.getPixelForValue(sumPos + rightValue);+ }+ return yScale.getPixelForValue(value);+ },- helpers.each(scalesOptions.yAxes, function(yAxisOptions, index) {- yAxisOptions.id = yAxisOptions.id || ('y-axis-' + index);+ 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;});+ }- if (scaleOptions) {- scaleOptions.id = scaleOptions.id || 'scale';- }- },+ function capControlPoint(pt, min, max) {+ return Math.max(Math.min(pt, max), min);+ }- /**- * Builds a map of scale ID to scale object for future lookup.- */- buildOrUpdateScales: function() {- var me = this;- var options = me.options;- var scales = me.scales || {};- var items = [];- var updated = Object.keys(scales).reduce(function(obj, id) {- obj[id] = false;- return obj;- }, {});-- if (options.scales) {- items = items.concat(- (options.scales.xAxes || []).map(function(xAxisOptions) {- return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};- }),- (options.scales.yAxes || []).map(function(yAxisOptions) {- return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};- })+ 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 (options.scale) {- items.push({- options: options.scale,- dtype: 'radialLinear',- isDefault: true,- dposition: 'chartArea'- });+ 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 canvas = chart.canvas;+ var i = 0;+ var ilen = points.length;+ var clip;- helpers.each(items, function(item) {- var scaleOptions = item.options;- var id = scaleOptions.id;- var scaleType = helpers.valueOrDefault(scaleOptions.type, item.dtype);+ if (me._showLine) {+ clip = meta.dataset._model.clip;- if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {- scaleOptions.position = item.dposition;- }+ helpers$1.canvas.clipArea(chart.ctx, {+ left: clip.left === false ? 0 : area.left - clip.left,+ right: clip.right === false ? canvas.width : area.right + clip.right,+ top: clip.top === false ? 0 : area.top - clip.top,+ bottom: clip.bottom === false ? canvas.height : area.bottom + clip.bottom+ });- updated[id] = true;- var scale = null;- if (id in scales && scales[id].type === scaleType) {- scale = scales[id];- scale.options = scaleOptions;- scale.ctx = me.ctx;- scale.chart = me;- } else {- var scaleClass = scaleService.getScaleConstructor(scaleType);- if (!scaleClass) {- return;- }- scale = new scaleClass({- id: id,- type: scaleType,- options: scaleOptions,- ctx: me.ctx,- chart: me- });- scales[scale.id] = scale;- }+ meta.dataset.draw();- scale.mergeTicksOptions();+ helpers$1.canvas.unclipArea(chart.ctx);+ }- // TODO(SB): I think we should be able to remove this custom case (options.scale)- // and consider it as a regular scale part of the "scales"" map only! This would- // make the logic easier and remove some useless? custom code.- if (item.isDefault) {- me.scale = scale;- }- });- // clear up discarded scales- helpers.each(updated, function(hasUpdated, id) {- if (!hasUpdated) {- delete scales[id];- }- });+ // 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$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));+ model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor));+ model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth);+ model.radius = valueOrDefault$6(options.hoverRadius, options.radius);+ },+});- me.scales = scales;+var resolve$3 = helpers$1.options.resolve;- scaleService.addScalesToLayout(this);+core_defaults._set('polarArea', {+ scale: {+ type: 'radialLinear',+ angleLines: {+ display: false+ },+ gridLines: {+ circular: true},+ pointLabels: {+ display: false+ },+ ticks: {+ beginAtZero: true+ }+ },- buildOrUpdateControllers: function() {- var me = this;- var types = [];- var newControllers = [];+ // Boolean - Whether to animate the rotation of the chart+ animation: {+ animateRotate: true,+ animateScale: true+ },- helpers.each(me.data.datasets, function(dataset, datasetIndex) {- var meta = me.getDatasetMeta(datasetIndex);- var type = dataset.type || me.config.type;+ startAngle: -0.5 * Math.PI,+ legendCallback: function(chart) {+ var list = document.createElement('ul');+ var data = chart.data;+ var datasets = data.datasets;+ var labels = data.labels;+ var i, ilen, listItem, listItemSpan;- if (meta.type && meta.type !== type) {- me.destroyDatasetMeta(datasetIndex);- meta = me.getDatasetMeta(datasetIndex);+ list.setAttribute('class', chart.id + '-legend');+ if (datasets.length) {+ for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {+ listItem = list.appendChild(document.createElement('li'));+ listItemSpan = listItem.appendChild(document.createElement('span'));+ listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];+ if (labels[i]) {+ listItem.appendChild(document.createTextNode(labels[i]));}- meta.type = type;+ }+ }- types.push(meta.type);+ return list.outerHTML;+ },+ 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 style = meta.controller.getStyle(i);- if (meta.controller) {- meta.controller.updateIndex(datasetIndex);- meta.controller.linkScales();- } else {- var ControllerClass = Chart.controllers[meta.type];- if (ControllerClass === undefined) {- throw new Error('"' + meta.type + '" is not a chart type.');- }+ return {+ text: label,+ fillStyle: style.backgroundColor,+ strokeStyle: style.borderColor,+ lineWidth: style.borderWidth,+ hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,- meta.controller = new ControllerClass(me, datasetIndex);- newControllers.push(meta.controller);+ // Extra data used for toggling the correct item+ index: i+ };+ });}- }, me);-- return newControllers;+ return [];+ }},- /**- * Reset the elements of all datasets- * @private- */- resetElements: function() {- var me = this;- helpers.each(me.data.datasets, function(dataset, datasetIndex) {- me.getDatasetMeta(datasetIndex).controller.reset();- }, me);- },+ onClick: function(e, legendItem) {+ var index = legendItem.index;+ var chart = this.chart;+ var i, ilen, meta;- /**- * Resets the chart back to it's state before the initial animation- */- reset: function() {- this.resetElements();- this.tooltip.initialize();- },+ for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {+ meta = chart.getDatasetMeta(i);+ meta.data[index].hidden = !meta.data[index].hidden;+ }- update: function(config) {- var me = this;+ chart.update();+ }+ },- if (!config || typeof config !== 'object') {- // backwards compatibility- config = {- duration: config,- lazy: arguments[1]- };+ // Need to override these to give a nice default+ tooltips: {+ callbacks: {+ title: function() {+ return '';+ },+ label: function(item, data) {+ return data.labels[item.index] + ': ' + item.yLabel;}+ }+ }+});- updateConfig(me);+var controller_polarArea = core_datasetController.extend({- // plugins options references might have change, let's invalidate the cache- // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167- plugins._invalidate(me);+ dataElementType: elements.Arc,- if (plugins.notify(me, 'beforeUpdate') === false) {- return;- }+ linkScales: helpers$1.noop,++ /**+ * @private+ */+ _dataElementOptions: [+ 'backgroundColor',+ 'borderColor',+ 'borderWidth',+ 'borderAlign',+ 'hoverBackgroundColor',+ 'hoverBorderColor',+ 'hoverBorderWidth',+ ],- // In case the entire data object changed- me.tooltip._data = me.data;+ /**+ * @private+ */+ _getIndexScaleId: function() {+ return this.chart.scale.id;+ },- // Make sure dataset controllers are updated and new controllers are reset- var newControllers = me.buildOrUpdateControllers();+ /**+ * @private+ */+ _getValueScaleId: function() {+ return this.chart.scale.id;+ },- // Make sure all dataset controllers have correct meta data counts- helpers.each(me.data.datasets, function(dataset, datasetIndex) {- me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements();- }, me);+ update: function(reset) {+ var me = this;+ var dataset = me.getDataset();+ var meta = me.getMeta();+ var start = me.chart.options.startAngle || 0;+ var starts = me._starts = [];+ var angles = me._angles = [];+ var arcs = meta.data;+ var i, ilen, angle;- me.updateLayout();+ me._updateRadius();- // Can only reset the new controllers after the scales have been updated- if (me.options.animation && me.options.animation.duration) {- helpers.each(newControllers, function(controller) {- controller.reset();- });- }+ meta.count = me.countVisibleElements();- me.updateDatasets();+ for (i = 0, ilen = dataset.data.length; i < ilen; i++) {+ starts[i] = start;+ angle = me._computeAngle(i);+ angles[i] = angle;+ start += angle;+ }- // Need to reset tooltip in case it is displayed with elements that are removed- // after update.- me.tooltip.initialize();+ for (i = 0, ilen = arcs.length; i < ilen; ++i) {+ arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);+ me.updateElement(arcs[i], i, reset);+ }+ },- // Last active contains items that were previously in the tooltip.- // When we reset the tooltip, we need to clear it- me.lastActive = [];+ /**+ * @private+ */+ _updateRadius: function() {+ var me = this;+ var chart = me.chart;+ var chartArea = chart.chartArea;+ var opts = chart.options;+ var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);- // Do this before render so that any plugins that need final scale updates can use it- plugins.notify(me, 'afterUpdate');+ chart.outerRadius = Math.max(minSize / 2, 0);+ chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);+ chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();- if (me._bufferedRender) {- me._bufferedRequest = {- duration: config.duration,- easing: config.easing,- lazy: config.lazy- };- } else {- me.render(config);+ me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);+ me.innerRadius = me.outerRadius - chart.radiusLength;+ },++ updateElement: function(arc, index, reset) {+ var me = this;+ var chart = me.chart;+ var dataset = me.getDataset();+ var opts = chart.options;+ var animationOpts = opts.animation;+ var scale = chart.scale;+ var labels = chart.data.labels;++ var centerX = scale.xCenter;+ var centerY = scale.yCenter;++ // var negHalfPI = -0.5 * Math.PI;+ var datasetStartAngle = opts.startAngle;+ var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);+ var startAngle = me._starts[index];+ var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);++ var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);+ var options = arc._options || {};++ helpers$1.extend(arc, {+ // Utility+ _datasetIndex: me.index,+ _index: index,+ _scale: scale,++ // Desired view properties+ _model: {+ backgroundColor: options.backgroundColor,+ borderColor: options.borderColor,+ borderWidth: options.borderWidth,+ borderAlign: options.borderAlign,+ x: centerX,+ y: centerY,+ innerRadius: 0,+ outerRadius: reset ? resetRadius : distance,+ startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,+ endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,+ label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index])}- },+ });- /**- * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`- * hook, in which case, plugins will not be called on `afterLayout`.- * @private- */- updateLayout: function() {- var me = this;+ arc.pivot();+ },- if (plugins.notify(me, 'beforeLayout') === false) {- return;+ countVisibleElements: function() {+ var dataset = this.getDataset();+ var meta = this.getMeta();+ var count = 0;++ helpers$1.each(meta.data, function(element, index) {+ if (!isNaN(dataset.data[index]) && !element.hidden) {+ count++;}+ });- layouts.update(this, this.width, this.height);+ return count;+ },- /**- * Provided for backward compatibility, use `afterLayout` instead.- * @method IPlugin#afterScaleUpdate- * @deprecated since version 2.5.0- * @todo remove at version 3- * @private- */- plugins.notify(me, 'afterScaleUpdate');- plugins.notify(me, 'afterLayout');- },+ /**+ * @protected+ */+ setHoverStyle: function(arc) {+ var model = arc._model;+ var options = arc._options;+ var getHoverColor = helpers$1.getHoverColor;+ var valueOrDefault = helpers$1.valueOrDefault;++ arc.$previousStyle = {+ backgroundColor: model.backgroundColor,+ borderColor: model.borderColor,+ borderWidth: model.borderWidth,+ };- /**- * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`- * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.- * @private- */- updateDatasets: function() {- var me = this;+ model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));+ model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));+ model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);+ },- if (plugins.notify(me, 'beforeDatasetsUpdate') === false) {- return;- }+ /**+ * @private+ */+ _computeAngle: function(index) {+ var me = this;+ var count = this.getMeta().count;+ var dataset = me.getDataset();+ var meta = me.getMeta();- for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {- me.updateDataset(i);- }+ if (isNaN(dataset.data[index]) || meta.data[index].hidden) {+ return 0;+ }- plugins.notify(me, 'afterDatasetsUpdate');- },+ // Scriptable options+ var context = {+ chart: me.chart,+ dataIndex: index,+ dataset: dataset,+ datasetIndex: me.index+ };- /**- * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`- * hook, in which case, plugins will not be called on `afterDatasetUpdate`.- * @private- */- updateDataset: function(index) {- var me = this;- var meta = me.getDatasetMeta(index);- var args = {- meta: meta,- index: index- };+ return resolve$3([+ me.chart.options.elements.arc.angle,+ (2 * Math.PI) / count+ ], context, index);+ }+});- if (plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {- return;- }+core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut));+core_defaults._set('pie', {+ cutoutPercentage: 0+});- meta.controller.update();+// Pie charts are Doughnut chart with different defaults+var controller_pie = controller_doughnut;- plugins.notify(me, 'afterDatasetUpdate', [args]);- },+var valueOrDefault$7 = helpers$1.valueOrDefault;++core_defaults._set('radar', {+ spanGaps: false,+ scale: {+ type: 'radialLinear'+ },+ elements: {+ line: {+ fill: 'start',+ tension: 0 // no bezier in radar+ }+ }+});++var controller_radar = core_datasetController.extend({+ datasetElementType: elements.Line,++ dataElementType: elements.Point,++ linkScales: helpers$1.noop,++ /**+ * @private+ */+ _datasetElementOptions: [+ 'backgroundColor',+ 'borderWidth',+ 'borderColor',+ 'borderCapStyle',+ 'borderDash',+ 'borderDashOffset',+ 'borderJoinStyle',+ 'fill'+ ],- render: function(config) {- var me = this;+ /**+ * @private+ */+ _dataElementOptions: {+ backgroundColor: 'pointBackgroundColor',+ borderColor: 'pointBorderColor',+ borderWidth: 'pointBorderWidth',+ hitRadius: 'pointHitRadius',+ hoverBackgroundColor: 'pointHoverBackgroundColor',+ hoverBorderColor: 'pointHoverBorderColor',+ hoverBorderWidth: 'pointHoverBorderWidth',+ hoverRadius: 'pointHoverRadius',+ pointStyle: 'pointStyle',+ radius: 'pointRadius',+ rotation: 'pointRotation'+ },- if (!config || typeof config !== 'object') {- // backwards compatibility- config = {- duration: config,- lazy: arguments[1]- };- }+ /**+ * @private+ */+ _getIndexScaleId: function() {+ return this.chart.scale.id;+ },- var duration = config.duration;- var lazy = config.lazy;+ /**+ * @private+ */+ _getValueScaleId: function() {+ return this.chart.scale.id;+ },- if (plugins.notify(me, 'beforeRender') === false) {- return;- }+ update: function(reset) {+ var me = this;+ var meta = me.getMeta();+ var line = meta.dataset;+ var points = meta.data || [];+ var scale = me.chart.scale;+ var config = me._config;+ var i, ilen;- var animationOptions = me.options.animation;- var onComplete = function(animation) {- plugins.notify(me, 'afterRender');- helpers.callback(animationOptions && animationOptions.onComplete, [animation], me);- };+ // Compatibility: If the properties are defined with only the old name, use those values+ if (config.tension !== undefined && config.lineTension === undefined) {+ config.lineTension = config.tension;+ }- if (animationOptions && ((typeof duration !== 'undefined' && duration !== 0) || (typeof duration === 'undefined' && animationOptions.duration !== 0))) {- var animation = new Animation({- numSteps: (duration || animationOptions.duration) / 16.66, // 60 fps- easing: config.easing || animationOptions.easing,+ // Utility+ line._scale = scale;+ line._datasetIndex = me.index;+ // Data+ line._children = points;+ line._loop = true;+ // Model+ line._model = me._resolveDatasetElementOptions(line);- render: function(chart, animationObject) {- var easingFunction = helpers.easing.effects[animationObject.easing];- var currentStep = animationObject.currentStep;- var stepDecimal = currentStep / animationObject.numSteps;+ line.pivot();- chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);- },+ // Update Points+ for (i = 0, ilen = points.length; i < ilen; ++i) {+ me.updateElement(points[i], i, reset);+ }- onAnimationProgress: animationOptions.onProgress,- onAnimationComplete: onComplete- });+ // Update bezier control points+ me.updateBezierControlPoints();- animations.addAnimation(me, animation, duration, lazy);- } else {- me.draw();+ // Now pivot the point for animation+ for (i = 0, ilen = points.length; i < ilen; ++i) {+ points[i].pivot();+ }+ },- // See https://github.com/chartjs/Chart.js/issues/3781- onComplete(new Animation({numSteps: 0, chart: me}));- }+ updateElement: function(point, index, reset) {+ var me = this;+ var custom = point.custom || {};+ var dataset = me.getDataset();+ var scale = me.chart.scale;+ var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);+ var options = me._resolveDataElementOptions(point, index);+ var lineModel = me.getMeta().dataset._model;+ var x = reset ? scale.xCenter : pointPosition.x;+ var y = reset ? scale.yCenter : pointPosition.y;++ // Utility+ point._scale = scale;+ point._options = options;+ point._datasetIndex = me.index;+ point._index = index;++ // Desired view properties+ point._model = {+ x: x, // value not used in dataset scale, but we want a consistent API between scales+ 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$7(custom.tension, lineModel ? lineModel.tension : 0),++ // Tooltip+ hitRadius: options.hitRadius+ };+ },- return me;- },+ /**+ * @private+ */+ _resolveDatasetElementOptions: function() {+ var me = this;+ var config = me._config;+ var options = me.chart.options;+ var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);- draw: function(easingValue) {- var me = this;+ values.spanGaps = valueOrDefault$7(config.spanGaps, options.spanGaps);+ values.tension = valueOrDefault$7(config.lineTension, options.elements.line.tension);- me.clear();+ return values;+ },- if (helpers.isNullOrUndef(easingValue)) {- easingValue = 1;- }+ updateBezierControlPoints: function() {+ var me = this;+ var meta = me.getMeta();+ var area = me.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 (meta.dataset._model.spanGaps) {+ points = points.filter(function(pt) {+ return !pt._model.skip;+ });+ }- me.transition(easingValue);+ function capControlPoint(pt, min, max) {+ return Math.max(Math.min(pt, max), min);+ }- if (me.width <= 0 || me.height <= 0) {- return;- }+ for (i = 0, ilen = points.length; i < ilen; ++i) {+ model = points[i]._model;+ controlPoints = helpers$1.splineCurve(+ helpers$1.previousItem(points, i, true)._model,+ model,+ helpers$1.nextItem(points, i, true)._model,+ model.tension+ );- if (plugins.notify(me, 'beforeDraw', [easingValue]) === false) {- return;- }+ // Prevent the bezier going outside of the bounds of the graph+ model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);+ model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);+ model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);+ model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);+ }+ },- // Draw all the scales- helpers.each(me.boxes, function(box) {- box.draw(me.chartArea);- }, me);+ setHoverStyle: function(point) {+ var model = point._model;+ var options = point._options;+ var getHoverColor = helpers$1.getHoverColor;- if (me.scale) {- me.scale.draw();- }+ point.$previousStyle = {+ backgroundColor: model.backgroundColor,+ borderColor: model.borderColor,+ borderWidth: model.borderWidth,+ radius: model.radius+ };- me.drawDatasets(easingValue);- me._drawTooltip(easingValue);+ model.backgroundColor = valueOrDefault$7(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));+ model.borderColor = valueOrDefault$7(options.hoverBorderColor, getHoverColor(options.borderColor));+ model.borderWidth = valueOrDefault$7(options.hoverBorderWidth, options.borderWidth);+ model.radius = valueOrDefault$7(options.hoverRadius, options.radius);+ }+});- plugins.notify(me, 'afterDraw', [easingValue]);- },+core_defaults._set('scatter', {+ hover: {+ mode: 'single'+ },- /**- * @private- */- transition: function(easingValue) {- var me = this;+ scales: {+ xAxes: [{+ id: 'x-axis-1', // need an ID so datasets can reference the scale+ type: 'linear', // scatter should not use a category axis+ position: 'bottom'+ }],+ yAxes: [{+ id: 'y-axis-1',+ type: 'linear',+ position: 'left'+ }]+ },- for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {- if (me.isDatasetVisible(i)) {- me.getDatasetMeta(i).controller.transition(easingValue);- }+ tooltips: {+ callbacks: {+ title: function() {+ return ''; // doesn't make sense for scatter since data are formatted as a point+ },+ label: function(item) {+ return '(' + item.xLabel + ', ' + item.yLabel + ')';}+ }+ }+});- me.tooltip.transition(easingValue);- },-- /**- * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`- * hook, in which case, plugins will not be called on `afterDatasetsDraw`.- * @private- */- drawDatasets: function(easingValue) {- var me = this;+core_defaults._set('global', {+ datasets: {+ scatter: {+ showLine: false+ }+ }+});- if (plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {- return;- }+// Scatter charts use line controllers+var controller_scatter = controller_line;++// NOTE export a map in which the key represents the controller type, not+// the class, and so must be CamelCase in order to be correctly retrieved+// by the controller in core.controller.js (`controllers[meta.type]`).++var controllers = {+ bar: controller_bar,+ bubble: controller_bubble,+ doughnut: controller_doughnut,+ horizontalBar: controller_horizontalBar,+ line: controller_line,+ polarArea: controller_polarArea,+ pie: controller_pie,+ radar: controller_radar,+ scatter: controller_scatter+};- // Draw datasets reversed to support proper line stacking- for (var i = (me.data.datasets || []).length - 1; i >= 0; --i) {- if (me.isDatasetVisible(i)) {- me.drawDataset(i, easingValue);- }- }+/**+ * Helper function to get relative position for an event+ * @param {Event|IEvent} event - The event to get the position for+ * @param {Chart} chart - The chart+ * @returns {object} the event position+ */+function getRelativePosition(e, chart) {+ if (e.native) {+ return {+ x: e.x,+ y: e.y+ };+ }- plugins.notify(me, 'afterDatasetsDraw', [easingValue]);- },+ return helpers$1.getRelativePosition(e, chart);+}- /**- * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`- * hook, in which case, plugins will not be called on `afterDatasetDraw`.- * @private- */- drawDataset: function(index, easingValue) {- var me = this;- var meta = me.getDatasetMeta(index);- var args = {- meta: meta,- index: index,- easingValue: easingValue- };+/**+ * Helper function to traverse all of the visible elements in the chart+ * @param {Chart} chart - the chart+ * @param {function} handler - the callback to execute for each visible item+ */+function parseVisibleItems(chart, handler) {+ var metasets = chart._getSortedVisibleDatasetMetas();+ var metadata, i, j, ilen, jlen, element;- if (plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {- return;+ for (i = 0, ilen = metasets.length; i < ilen; ++i) {+ metadata = metasets[i].data;+ for (j = 0, jlen = metadata.length; j < jlen; ++j) {+ element = metadata[j];+ if (!element._view.skip) {+ handler(element);}+ }+ }+}- meta.controller.draw(easingValue);+/**+ * Helper function to get the items that intersect the event position+ * @param {ChartElement[]} items - elements to filter+ * @param {object} position - the point to be nearest to+ * @return {ChartElement[]} the nearest items+ */+function getIntersectItems(chart, position) {+ var elements = [];- plugins.notify(me, 'afterDatasetDraw', [args]);- },+ parseVisibleItems(chart, function(element) {+ if (element.inRange(position.x, position.y)) {+ elements.push(element);+ }+ });- /**- * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`- * hook, in which case, plugins will not be called on `afterTooltipDraw`.- * @private- */- _drawTooltip: function(easingValue) {- var me = this;- var tooltip = me.tooltip;- var args = {- tooltip: tooltip,- easingValue: easingValue- };+ return elements;+}- if (plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {- return;- }+/**+ * Helper function to get the items nearest to the event position considering all visible items in teh chart+ * @param {Chart} chart - the chart to look at elements from+ * @param {object} position - the point to be nearest to+ * @param {boolean} intersect - if true, only consider items that intersect the position+ * @param {function} distanceMetric - function to provide the distance between points+ * @return {ChartElement[]} the nearest items+ */+function getNearestItems(chart, position, intersect, distanceMetric) {+ var minDistance = Number.POSITIVE_INFINITY;+ var nearestItems = [];- tooltip.draw();+ parseVisibleItems(chart, function(element) {+ if (intersect && !element.inRange(position.x, position.y)) {+ return;+ }- plugins.notify(me, 'afterTooltipDraw', [args]);- },+ var center = element.getCenterPoint();+ var distance = distanceMetric(position, center);+ if (distance < minDistance) {+ nearestItems = [element];+ minDistance = distance;+ } else if (distance === minDistance) {+ // Can have multiple items at the same distance in which case we sort by size+ nearestItems.push(element);+ }+ });- // Get the single element that was clicked on- // @return : An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw- getElementAtEvent: function(e) {- return Interaction.modes.single(this, e);- },+ return nearestItems;+}- getElementsAtEvent: function(e) {- return Interaction.modes.label(this, e, {intersect: true});- },+/**+ * Get a distance metric function for two points based on the+ * axis mode setting+ * @param {string} axis - the axis mode. x|y|xy+ */+function getDistanceMetricForAxis(axis) {+ var useX = axis.indexOf('x') !== -1;+ var useY = axis.indexOf('y') !== -1;- getElementsAtXAxis: function(e) {- return Interaction.modes['x-axis'](this, e, {intersect: true});- },+ return function(pt1, pt2) {+ var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;+ var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;+ return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));+ };+}- getElementsAtEventForMode: function(e, mode, options) {- var method = Interaction.modes[mode];- if (typeof method === 'function') {- return method(this, e, options);- }+function indexMode(chart, e, options) {+ var position = getRelativePosition(e, chart);+ // Default axis for index mode is 'x' to match old behaviour+ options.axis = options.axis || 'x';+ var distanceMetric = getDistanceMetricForAxis(options.axis);+ var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);+ var elements = [];- return [];- },+ if (!items.length) {+ return [];+ }- getDatasetAtEvent: function(e) {- return Interaction.modes.dataset(this, e, {intersect: true});- },+ chart._getSortedVisibleDatasetMetas().forEach(function(meta) {+ var element = meta.data[items[0]._index];- getDatasetMeta: function(datasetIndex) {- var me = this;- var dataset = me.data.datasets[datasetIndex];- if (!dataset._meta) {- dataset._meta = {};- }-- var meta = dataset._meta[me.id];- if (!meta) {- meta = dataset._meta[me.id] = {- type: null,- data: [],- dataset: null,- controller: null,- hidden: null, // See isDatasetVisible() comment- xAxisID: null,- yAxisID: null- };- }+ // don't count items that are skipped (null data)+ if (element && !element._view.skip) {+ elements.push(element);+ }+ });- return meta;- },+ return elements;+}- getVisibleDatasetCount: function() {- var count = 0;- for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {- if (this.isDatasetVisible(i)) {- count++;- }- }- return count;- },+/**+ * @interface IInteractionOptions+ */+/**+ * If true, only consider items that intersect the point+ * @name IInterfaceOptions#boolean+ * @type Boolean+ */- isDatasetVisible: function(datasetIndex) {- var meta = this.getDatasetMeta(datasetIndex);+/**+ * Contains interaction related functions+ * @namespace Chart.Interaction+ */+var core_interaction = {+ // Helper function for different modes+ modes: {+ single: function(chart, e) {+ var position = getRelativePosition(e, chart);+ var elements = [];- // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,- // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.- return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;- },+ parseVisibleItems(chart, function(element) {+ if (element.inRange(position.x, position.y)) {+ elements.push(element);+ return elements;+ }+ });- generateLegend: function() {- return this.options.legendCallback(this);+ return elements.slice(0, 1);},/**+ * @function Chart.Interaction.modes.label+ * @deprecated since version 2.4.0+ * @todo remove at version 3* @private*/- destroyDatasetMeta: function(datasetIndex) {- var id = this.id;- var dataset = this.data.datasets[datasetIndex];- var meta = dataset._meta && dataset._meta[id];-- if (meta) {- meta.controller.destroy();- delete dataset._meta[id];- }- },-- destroy: function() {- var me = this;- var canvas = me.canvas;- var i, ilen;-- me.stop();-- // dataset controllers need to cleanup associated data- for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {- me.destroyDatasetMeta(i);- }-- if (canvas) {- me.unbindEvents();- helpers.canvas.clear(me);- platform.releaseContext(me.ctx);- me.canvas = null;- me.ctx = null;- }+ label: indexMode,- plugins.notify(me, 'destroy');+ /**+ * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something+ * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item+ * @function Chart.Interaction.modes.index+ * @since v2.4.0+ * @param {Chart} chart - the chart we are returning items from+ * @param {Event} e - the event we are find things at+ * @param {IInteractionOptions} options - options to use during interaction+ * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned+ */+ index: indexMode,- delete Chart.instances[me.id];- },+ /**+ * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something+ * If the options.intersect is false, we find the nearest item and return the items in that dataset+ * @function Chart.Interaction.modes.dataset+ * @param {Chart} chart - the chart we are returning items from+ * @param {Event} e - the event we are find things at+ * @param {IInteractionOptions} options - options to use during interaction+ * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned+ */+ dataset: function(chart, e, options) {+ var position = getRelativePosition(e, chart);+ options.axis = options.axis || 'xy';+ var distanceMetric = getDistanceMetricForAxis(options.axis);+ var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);- toBase64Image: function() {- return this.canvas.toDataURL.apply(this.canvas, arguments);- },+ if (items.length > 0) {+ items = chart.getDatasetMeta(items[0]._datasetIndex).data;+ }- initToolTip: function() {- var me = this;- me.tooltip = new Tooltip({- _chart: me,- _chartInstance: me, // deprecated, backward compatibility- _data: me.data,- _options: me.options.tooltips- }, me);+ return items;},/**+ * @function Chart.Interaction.modes.x-axis+ * @deprecated since version 2.4.0. Use index mode and intersect == true+ * @todo remove at version 3* @private*/- bindEvents: function() {- var me = this;- var listeners = me._listeners = {};- var listener = function() {- me.eventHandler.apply(me, arguments);- };-- helpers.each(me.options.events, function(type) {- platform.addEventListener(me, type, listener);- listeners[type] = listener;- });-- // Elements used to detect size change should not be injected for non responsive charts.- // See https://github.com/chartjs/Chart.js/issues/2210- if (me.options.responsive) {- listener = function() {- me.resize();- };-- platform.addEventListener(me, 'resize', listener);- listeners.resize = listener;- }+ 'x-axis': function(chart, e) {+ return indexMode(chart, e, {intersect: false});},/**- * @private+ * Point mode returns all elements that hit test based on the event position+ * of the event+ * @function Chart.Interaction.modes.intersect+ * @param {Chart} chart - the chart we are returning items from+ * @param {Event} e - the event we are find things at+ * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned*/- unbindEvents: function() {- var me = this;- var listeners = me._listeners;- if (!listeners) {- return;- }-- delete me._listeners;- helpers.each(listeners, function(listener, type) {- platform.removeEventListener(me, type, listener);- });+ point: function(chart, e) {+ var position = getRelativePosition(e, chart);+ return getIntersectItems(chart, position);},- updateHoverStyle: function(elements, mode, enabled) {- var method = enabled ? 'setHoverStyle' : 'removeHoverStyle';- var element, i, ilen;-- for (i = 0, ilen = elements.length; i < ilen; ++i) {- element = elements[i];- if (element) {- this.getDatasetMeta(element._datasetIndex).controller[method](element);- }- }+ /**+ * nearest mode returns the element closest to the point+ * @function Chart.Interaction.modes.intersect+ * @param {Chart} chart - the chart we are returning items from+ * @param {Event} e - the event we are find things at+ * @param {IInteractionOptions} options - options to use+ * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned+ */+ nearest: function(chart, e, options) {+ var position = getRelativePosition(e, chart);+ options.axis = options.axis || 'xy';+ var distanceMetric = getDistanceMetricForAxis(options.axis);+ return getNearestItems(chart, position, options.intersect, distanceMetric);},/**- * @private+ * x mode returns the elements that hit-test at the current x coordinate+ * @function Chart.Interaction.modes.x+ * @param {Chart} chart - the chart we are returning items from+ * @param {Event} e - the event we are find things at+ * @param {IInteractionOptions} options - options to use+ * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned*/- eventHandler: function(e) {- var me = this;- var tooltip = me.tooltip;-- if (plugins.notify(me, 'beforeEvent', [e]) === false) {- return;- }+ x: function(chart, e, options) {+ var position = getRelativePosition(e, chart);+ var items = [];+ var intersectsItem = false;- // Buffer any update calls so that renders do not occur- me._bufferedRender = true;- me._bufferedRequest = null;-- var changed = me.handleEvent(e);- // for smooth tooltip animations issue #4989- // the tooltip should be the source of change- // Animation check workaround:- // tooltip._start will be null when tooltip isn't animating- if (tooltip) {- changed = tooltip._start- ? tooltip.handleEvent(e)- : changed | tooltip.handleEvent(e);- }-- plugins.notify(me, 'afterEvent', [e]);-- var bufferedRequest = me._bufferedRequest;- if (bufferedRequest) {- // If we have an update that was triggered, we need to do a normal render- me.render(bufferedRequest);- } else if (changed && !me.animating) {- // If entering, leaving, or changing elements, animate the change via pivot- me.stop();-- // We only need to render at this point. Updating will cause scales to be- // recomputed generating flicker & using more memory than necessary.- me.render({- duration: me.options.hover.animationDuration,- lazy: true- });- }+ parseVisibleItems(chart, function(element) {+ if (element.inXRange(position.x)) {+ items.push(element);+ }- me._bufferedRender = false;- me._bufferedRequest = null;+ if (element.inRange(position.x, position.y)) {+ intersectsItem = true;+ }+ });- return me;+ // If we want to trigger on an intersect and we don't have any items+ // that intersect the position, return nothing+ if (options.intersect && !intersectsItem) {+ items = [];+ }+ return items;},/**- * Handle an event- * @private- * @param {IEvent} event the event to handle- * @return {Boolean} true if the chart needs to re-render+ * y mode returns the elements that hit-test at the current y coordinate+ * @function Chart.Interaction.modes.y+ * @param {Chart} chart - the chart we are returning items from+ * @param {Event} e - the event we are find things at+ * @param {IInteractionOptions} options - options to use+ * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned*/- handleEvent: function(e) {- var me = this;- var options = me.options || {};- var hoverOptions = options.hover;- var changed = false;-- me.lastActive = me.lastActive || [];-- // Find Active Elements for hover and tooltips- if (e.type === 'mouseout') {- me.active = [];- } else {- me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);- }-- // Invoke onHover hook- // Need to call with native event here to not break backwards compatibility- helpers.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);+ y: function(chart, e, options) {+ var position = getRelativePosition(e, chart);+ var items = [];+ var intersectsItem = false;- if (e.type === 'mouseup' || e.type === 'click') {- if (options.onClick) {- // Use e.native here for backwards compatibility- options.onClick.call(me, e.native, me.active);+ parseVisibleItems(chart, function(element) {+ if (element.inYRange(position.y)) {+ items.push(element);}- }- // Remove styling for last active (even if it may still be active)- if (me.lastActive.length) {- me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);- }+ if (element.inRange(position.x, position.y)) {+ intersectsItem = true;+ }+ });- // Built in hover styling- if (me.active.length && hoverOptions.mode) {- me.updateHoverStyle(me.active, hoverOptions.mode, true);+ // If we want to trigger on an intersect and we don't have any items+ // that intersect the position, return nothing+ if (options.intersect && !intersectsItem) {+ items = [];}+ return items;+ }+ }+};- changed = !helpers.arrayEquals(me.active, me.lastActive);-- // Remember Last Actives- me.lastActive = me.active;+var extend = helpers$1.extend;- return changed;- }+function filterByPosition(array, position) {+ return helpers$1.where(array, function(v) {+ return v.pos === position;});+}- /**- * Provided for backward compatibility, use Chart instead.- * @class Chart.Controller- * @deprecated since version 2.6.0- * @todo remove at version 3- * @private- */- Chart.Controller = Chart;-};--},{"22":22,"23":23,"26":26,"29":29,"31":31,"32":32,"34":34,"36":36,"46":46,"49":49}],25:[function(require,module,exports){-'use strict';+function sortByWeight(array, reverse) {+ return array.sort(function(a, b) {+ var v0 = reverse ? b : a;+ var v1 = reverse ? a : b;+ return v0.weight === v1.weight ?+ v0.index - v1.index :+ v0.weight - v1.weight;+ });+}-var helpers = require(46);+function wrapBoxes(boxes) {+ var layoutBoxes = [];+ var i, ilen, box;-module.exports = function(Chart) {+ for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {+ box = boxes[i];+ layoutBoxes.push({+ index: i,+ box: box,+ pos: box.position,+ horizontal: box.isHorizontal(),+ weight: box.weight+ });+ }+ return layoutBoxes;+}- var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];+function setLayoutDims(layouts, params) {+ var i, ilen, layout;+ for (i = 0, ilen = layouts.length; i < ilen; ++i) {+ layout = layouts[i];+ // store width used instead of chartArea.w in fitBoxes+ layout.width = layout.horizontal+ ? layout.box.fullWidth && params.availableWidth+ : params.vBoxMaxWidth;+ // store height used instead of chartArea.h in fitBoxes+ layout.height = layout.horizontal && params.hBoxMaxHeight;+ }+}- /**- * 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;- }+function buildLayoutBoxes(boxes) {+ var layoutBoxes = wrapBoxes(boxes);+ var left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);+ var right = sortByWeight(filterByPosition(layoutBoxes, 'right'));+ var top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);+ var bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));- Object.defineProperty(array, '_chartjs', {- configurable: true,- enumerable: false,- value: {- listeners: [listener]- }- });+ return {+ leftAndTop: left.concat(top),+ rightAndBottom: right.concat(bottom),+ chartArea: filterByPosition(layoutBoxes, 'chartArea'),+ vertical: left.concat(right),+ horizontal: top.concat(bottom)+ };+}- arrayEvents.forEach(function(key) {- var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);- var base = array[key];+function getCombinedMax(maxPadding, chartArea, a, b) {+ return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);+}- Object.defineProperty(array, key, {- configurable: true,- enumerable: false,- value: function() {- var args = Array.prototype.slice.call(arguments);- var res = base.apply(this, args);+function updateDims(chartArea, params, layout) {+ var box = layout.box;+ var maxPadding = chartArea.maxPadding;+ var newWidth, newHeight;- helpers.each(array._chartjs.listeners, function(object) {- if (typeof object[method] === 'function') {- object[method].apply(object, args);- }- });+ if (layout.size) {+ // this layout was already counted for, lets first reduce old size+ chartArea[layout.pos] -= layout.size;+ }+ layout.size = layout.horizontal ? box.height : box.width;+ chartArea[layout.pos] += layout.size;- return res;- }- });- });+ if (box.getPadding) {+ var boxPadding = box.getPadding();+ maxPadding.top = Math.max(maxPadding.top, boxPadding.top);+ maxPadding.left = Math.max(maxPadding.left, boxPadding.left);+ maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);+ maxPadding.right = Math.max(maxPadding.right, boxPadding.right);}- /**- * 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;- }+ newWidth = params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right');+ newHeight = params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom');- var listeners = stub.listeners;- var index = listeners.indexOf(listener);- if (index !== -1) {- listeners.splice(index, 1);- }+ if (newWidth !== chartArea.w || newHeight !== chartArea.h) {+ chartArea.w = newWidth;+ chartArea.h = newHeight;- if (listeners.length > 0) {- return;- }+ // return true if chart area changed in layout's direction+ return layout.horizontal ? newWidth !== chartArea.w : newHeight !== chartArea.h;+ }+}- arrayEvents.forEach(function(key) {- delete array[key];- });+function handleMaxPadding(chartArea) {+ var maxPadding = chartArea.maxPadding;- delete array._chartjs;+ function updatePos(pos) {+ var change = Math.max(maxPadding[pos] - chartArea[pos], 0);+ chartArea[pos] += change;+ return change;}+ chartArea.y += updatePos('top');+ chartArea.x += updatePos('left');+ updatePos('right');+ updatePos('bottom');+}- // Base class for all dataset controllers (line, bar, etc)- Chart.DatasetController = function(chart, datasetIndex) {- this.initialize(chart, datasetIndex);- };-- helpers.extend(Chart.DatasetController.prototype, {+function getMargins(horizontal, chartArea) {+ var maxPadding = chartArea.maxPadding;- /**- * Element type used to generate a meta dataset (e.g. Chart.element.Line).- * @type {Chart.core.element}- */- datasetElementType: null,+ function marginForPositions(positions) {+ var margin = {left: 0, top: 0, right: 0, bottom: 0};+ positions.forEach(function(pos) {+ margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);+ });+ return margin;+ }- /**- * 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();- },+ return horizontal+ ? marginForPositions(['left', 'right'])+ : marginForPositions(['top', 'bottom']);+}- updateIndex: function(datasetIndex) {- this.index = datasetIndex;- },+function fitBoxes(boxes, chartArea, params) {+ var refitBoxes = [];+ var i, ilen, layout, box, refit, changed;- linkScales: function() {- var me = this;- var meta = me.getMeta();- var dataset = me.getDataset();+ for (i = 0, ilen = boxes.length; i < ilen; ++i) {+ layout = boxes[i];+ box = layout.box;- 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;+ box.update(+ layout.width || chartArea.w,+ layout.height || chartArea.h,+ getMargins(layout.horizontal, chartArea)+ );+ if (updateDims(chartArea, params, layout)) {+ changed = true;+ if (refitBoxes.length) {+ // Dimensions changed and there were non full width boxes before this+ // -> we have to refit those+ refit = true;}- },+ }+ if (!box.fullWidth) { // fullWidth boxes don't need to be re-fitted in any case+ refitBoxes.push(layout);+ }+ }- getDataset: function() {- return this.chart.data.datasets[this.index];- },+ return refit ? fitBoxes(refitBoxes, chartArea, params) || changed : changed;+}- getMeta: function() {- return this.chart.getDatasetMeta(this.index);- },+function placeBoxes(boxes, chartArea, params) {+ var userPadding = params.padding;+ var x = chartArea.x;+ var y = chartArea.y;+ var i, ilen, layout, box;- getScaleForId: function(scaleID) {- return this.chart.scales[scaleID];- },+ for (i = 0, ilen = boxes.length; i < ilen; ++i) {+ layout = boxes[i];+ box = layout.box;+ if (layout.horizontal) {+ box.left = box.fullWidth ? userPadding.left : chartArea.left;+ box.right = box.fullWidth ? params.outerWidth - userPadding.right : chartArea.left + chartArea.w;+ box.top = y;+ box.bottom = y + box.height;+ box.width = box.right - box.left;+ y = box.bottom;+ } else {+ box.left = x;+ box.right = x + box.width;+ box.top = chartArea.top;+ box.bottom = chartArea.top + chartArea.h;+ box.height = box.bottom - box.top;+ x = box.right;+ }+ }- reset: function() {- this.update(true);- },+ chartArea.x = x;+ chartArea.y = y;+}- /**- * @private- */- destroy: function() {- if (this._data) {- unlistenArrayEvents(this._data, this);- }- },+core_defaults._set('global', {+ layout: {+ padding: {+ top: 0,+ right: 0,+ bottom: 0,+ left: 0+ }+ }+});- createMetaDataset: function() {- var me = this;- var type = me.datasetElementType;- return type && new type({- _chart: me.chart,- _datasetIndex: me.index- });- },+/**+ * @interface ILayoutItem+ * @prop {string} position - The position of the item in the chart layout. Possible values are+ * 'left', 'top', 'right', 'bottom', and 'chartArea'+ * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area+ * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down+ * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)+ * @prop {function} update - Takes two parameters: width and height. Returns size of item+ * @prop {function} getPadding - Returns an object with padding on the edges+ * @prop {number} width - Width of item. Must be valid after update()+ * @prop {number} height - Height of item. Must be valid after update()+ * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update+ * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update+ * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update+ * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update+ */- createMetaData: function(index) {- var me = this;- var type = me.dataElementType;- return type && new type({- _chart: me.chart,- _datasetIndex: me.index,- _index: index- });- },+// The layout service is very self explanatory. It's responsible for the layout within a chart.+// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need+// It is this service's responsibility of carrying out that layout.+var core_layouts = {+ defaults: {},- addElements: function() {- var me = this;- var meta = me.getMeta();- var data = me.getDataset().data || [];- var metaData = meta.data;- var i, ilen;+ /**+ * Register a box to a chart.+ * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.+ * @param {Chart} chart - the chart to use+ * @param {ILayoutItem} item - the item to add to be layed out+ */+ addBox: function(chart, item) {+ if (!chart.boxes) {+ chart.boxes = [];+ }- for (i = 0, ilen = data.length; i < ilen; ++i) {- metaData[i] = metaData[i] || me.createMetaData(i);- }+ // initialize item with default values+ item.fullWidth = item.fullWidth || false;+ item.position = item.position || 'top';+ item.weight = item.weight || 0;+ item._layers = item._layers || function() {+ return [{+ z: 0,+ draw: function() {+ item.draw.apply(item, arguments);+ }+ }];+ };- meta.dataset = meta.dataset || me.createMetaDataset();- },+ chart.boxes.push(item);+ },- addElementAndReset: function(index) {- var element = this.createMetaData(index);- this.getMeta().data.splice(index, 0, element);- this.updateElement(element, index, true);- },+ /**+ * Remove a layoutItem from a chart+ * @param {Chart} chart - the chart to remove the box from+ * @param {ILayoutItem} layoutItem - the item to remove from the layout+ */+ removeBox: function(chart, layoutItem) {+ var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;+ if (index !== -1) {+ chart.boxes.splice(index, 1);+ }+ },- 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);- }+ /**+ * Sets (or updates) options on the given `item`.+ * @param {Chart} chart - the chart in which the item lives (or will be added to)+ * @param {ILayoutItem} item - the item to configure with the given options+ * @param {object} options - the new item options.+ */+ configure: function(chart, item, options) {+ var props = ['fullWidth', 'position', 'weight'];+ var ilen = props.length;+ var i = 0;+ var prop;- listenArrayEvents(data, me);- me._data = data;+ for (; i < ilen; ++i) {+ prop = props[i];+ if (options.hasOwnProperty(prop)) {+ item[prop] = options[prop];}+ }+ },- // 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.noop,-- transition: function(easingValue) {- var meta = this.getMeta();- var elements = meta.data || [];- var ilen = elements.length;- var i = 0;+ /**+ * Fits boxes of the given chart into the given size by having each box measure itself+ * then running a fitting algorithm+ * @param {Chart} chart - the chart+ * @param {number} width - the width to fit into+ * @param {number} height - the height to fit into+ */+ update: function(chart, width, height) {+ if (!chart) {+ return;+ }- for (; i < ilen; ++i) {- elements[i].transition(easingValue);- }+ var layoutOptions = chart.options.layout || {};+ var padding = helpers$1.options.toPadding(layoutOptions.padding);- if (meta.dataset) {- meta.dataset.transition(easingValue);- }- },+ var availableWidth = width - padding.width;+ var availableHeight = height - padding.height;+ var boxes = buildLayoutBoxes(chart.boxes);+ var verticalBoxes = boxes.vertical;+ var horizontalBoxes = boxes.horizontal;- draw: function() {- var meta = this.getMeta();- var elements = meta.data || [];- var ilen = elements.length;- var i = 0;+ // Essentially we now have any number of boxes on each of the 4 sides.+ // Our canvas looks like the following.+ // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and+ // B1 is the bottom axis+ // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays+ // These locations are single-box locations only, when trying to register a chartArea location that is already taken,+ // an error will be thrown.+ //+ // |----------------------------------------------------|+ // | T1 (Full Width) |+ // |----------------------------------------------------|+ // | | | T2 | |+ // | |----|-------------------------------------|----|+ // | | | C1 | | C2 | |+ // | | |----| |----| |+ // | | | | |+ // | L1 | L2 | ChartArea (C0) | R1 |+ // | | | | |+ // | | |----| |----| |+ // | | | C3 | | C4 | |+ // | |----|-------------------------------------|----|+ // | | | B1 | |+ // |----------------------------------------------------|+ // | B2 (Full Width) |+ // |----------------------------------------------------|+ //- if (meta.dataset) {- meta.dataset.draw();- }+ var params = Object.freeze({+ outerWidth: width,+ outerHeight: height,+ padding: padding,+ availableWidth: availableWidth,+ vBoxMaxWidth: availableWidth / 2 / verticalBoxes.length,+ hBoxMaxHeight: availableHeight / 2+ });+ var chartArea = extend({+ maxPadding: extend({}, padding),+ w: availableWidth,+ h: availableHeight,+ x: padding.left,+ y: padding.top+ }, padding);- for (; i < ilen; ++i) {- elements[i].draw();- }- },+ setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);- removeHoverStyle: function(element) {- helpers.merge(element._model, element.$previousStyle || {});- delete element.$previousStyle;- },+ // First fit vertical boxes+ fitBoxes(verticalBoxes, chartArea, params);- setHoverStyle: function(element) {- var dataset = this.chart.data.datasets[element._datasetIndex];- var index = element._index;- var custom = element.custom || {};- var valueOrDefault = helpers.valueAtIndexOrDefault;- var getHoverColor = helpers.getHoverColor;- var model = element._model;-- element.$previousStyle = {- backgroundColor: model.backgroundColor,- borderColor: model.borderColor,- borderWidth: model.borderWidth- };+ // Then fit horizontal boxes+ if (fitBoxes(horizontalBoxes, chartArea, params)) {+ // if the area changed, re-fit vertical boxes+ fitBoxes(verticalBoxes, chartArea, params);+ }- model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : valueOrDefault(dataset.hoverBackgroundColor, index, getHoverColor(model.backgroundColor));- model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : valueOrDefault(dataset.hoverBorderColor, index, getHoverColor(model.borderColor));- model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : valueOrDefault(dataset.hoverBorderWidth, index, model.borderWidth);- },+ handleMaxPadding(chartArea);- /**- * @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);- }- },+ // Finally place the boxes to correct coordinates+ placeBoxes(boxes.leftAndTop, chartArea, params);- /**- * @private- */- insertElements: function(start, count) {- for (var i = 0; i < count; ++i) {- this.addElementAndReset(start + i);- }- },+ // Move to opposite side of chart+ chartArea.x += chartArea.w;+ chartArea.y += chartArea.h;- /**- * @private- */- onDataPush: function() {- this.insertElements(this.getDataset().data.length - 1, arguments.length);- },+ placeBoxes(boxes.rightAndBottom, chartArea, params);- /**- * @private- */- onDataPop: function() {- this.getMeta().data.pop();- },+ chart.chartArea = {+ left: chartArea.left,+ top: chartArea.top,+ right: chartArea.left + chartArea.w,+ bottom: chartArea.top + chartArea.h+ };- /**- * @private- */- onDataShift: function() {- this.getMeta().data.shift();- },+ // Finally update boxes in chartArea (radial scale for example)+ helpers$1.each(boxes.chartArea, function(layout) {+ var box = layout.box;+ extend(box, chart.chartArea);+ box.update(chartArea.w, chartArea.h);+ });+ }+};- /**- * @private- */- onDataSplice: function(start, count) {- this.getMeta().data.splice(start, count);- this.insertElements(start, arguments.length - 2);- },+/**+ * Platform fallback implementation (minimal).+ * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939+ */- /**- * @private- */- onDataUnshift: function() {- this.insertElements(0, arguments.length);+var platform_basic = {+ acquireContext: function(item) {+ if (item && item.canvas) {+ // Support for any object associated to a canvas (including a context2d)+ item = item.canvas;}- });- Chart.DatasetController.extend = helpers.inherits;+ return item && item.getContext('2d') || null;+ }};-},{"46":46}],26:[function(require,module,exports){-'use strict';+var platform_dom = "/*\n * DOM element rendering detection\n * https://davidwalsh.name/detect-node-insertion\n */\n@keyframes chartjs-render-animation {\n\tfrom { opacity: 0.99; }\n\tto { opacity: 1; }\n}\n\n.chartjs-render-monitor {\n\tanimation: chartjs-render-animation 0.001s;\n}\n\n/*\n * DOM element resizing detection\n * https://github.com/marcj/css-element-queries\n */\n.chartjs-size-monitor,\n.chartjs-size-monitor-expand,\n.chartjs-size-monitor-shrink {\n\tposition: absolute;\n\tdirection: ltr;\n\tleft: 0;\n\ttop: 0;\n\tright: 0;\n\tbottom: 0;\n\toverflow: hidden;\n\tpointer-events: none;\n\tvisibility: hidden;\n\tz-index: -1;\n}\n\n.chartjs-size-monitor-expand > div {\n\tposition: absolute;\n\twidth: 1000000px;\n\theight: 1000000px;\n\tleft: 0;\n\ttop: 0;\n}\n\n.chartjs-size-monitor-shrink > div {\n\tposition: absolute;\n\twidth: 200%;\n\theight: 200%;\n\tleft: 0;\n\ttop: 0;\n}\n";-var helpers = require(46);+var platform_dom$1 = /*#__PURE__*/Object.freeze({+__proto__: null,+'default': platform_dom+});-module.exports = {- /**- * @private- */- _set: function(scope, values) {- return helpers.merge(this[scope] || (this[scope] = {}), values);- }-};+var stylesheet = getCjsExportFromNamespace(platform_dom$1);-},{"46":46}],27:[function(require,module,exports){-'use strict';+var EXPANDO_KEY = '$chartjs';+var CSS_PREFIX = 'chartjs-';+var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor';+var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';+var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';+var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];-var color = require(3);-var helpers = require(46);+/**+ * DOM event types -> Chart.js event types.+ * Note: only events with different types are mapped.+ * @see https://developer.mozilla.org/en-US/docs/Web/Events+ */+var EVENT_TYPES = {+ touchstart: 'mousedown',+ touchmove: 'mousemove',+ touchend: 'mouseup',+ pointerenter: 'mouseenter',+ pointerdown: 'mousedown',+ pointermove: 'mousemove',+ pointerup: 'mouseup',+ pointerleave: 'mouseout',+ pointerout: 'mouseout'+};-function interpolate(start, view, model, ease) {- var keys = Object.keys(model);- var i, ilen, key, actual, origin, target, type, c0, c1;+/**+ * The "used" size is the final value of a dimension property after all calculations have+ * been performed. This method uses the computed style of `element` but returns undefined+ * if the computed style is not expressed in pixels. That can happen in some cases where+ * `element` has a size relative to its parent and this last one is not yet displayed,+ * for example because of `display: none` on a parent node.+ * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value+ * @returns {number} Size in pixels or undefined if unknown.+ */+function readUsedSize(element, property) {+ var value = helpers$1.getStyle(element, property);+ var matches = value && value.match(/^(\d+)(\.\d+)?px$/);+ return matches ? Number(matches[1]) : undefined;+}- for (i = 0, ilen = keys.length; i < ilen; ++i) {- key = keys[i];+/**+ * Initializes the canvas style and render size without modifying the canvas display size,+ * since responsiveness is handled by the controller.resize() method. The config is used+ * to determine the aspect ratio to apply in case no explicit height has been specified.+ */+function initCanvas(canvas, config) {+ var style = canvas.style;- target = model[key];+ // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it+ // returns null or '' if no explicit value has been set to the canvas attribute.+ var renderHeight = canvas.getAttribute('height');+ var renderWidth = canvas.getAttribute('width');- // 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;+ // Chart.js modifies some canvas values that we want to restore on destroy+ canvas[EXPANDO_KEY] = {+ initial: {+ height: renderHeight,+ width: renderWidth,+ style: {+ display: style.display,+ height: style.height,+ width: style.width+ }}+ };- actual = view[key];+ // Force canvas to display as block to avoid extra space caused by inline+ // elements, which would interfere with the responsive resize process.+ // https://github.com/chartjs/Chart.js/issues/2538+ style.display = style.display || 'block';- if (actual === target || key[0] === '_') {- continue;+ if (renderWidth === null || renderWidth === '') {+ var displayWidth = readUsedSize(canvas, 'width');+ if (displayWidth !== undefined) {+ canvas.width = displayWidth;}+ }- if (!start.hasOwnProperty(key)) {- start[key] = actual;+ if (renderHeight === null || renderHeight === '') {+ if (canvas.style.height === '') {+ // If no explicit render height and style height, let's apply the aspect ratio,+ // which one can be specified by the user but also by charts as default option+ // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.+ canvas.height = canvas.width / (config.options.aspectRatio || 2);+ } else {+ var displayHeight = readUsedSize(canvas, 'height');+ if (displayWidth !== undefined) {+ canvas.height = displayHeight;+ }}+ }- origin = start[key];-- type = typeof target;+ return canvas;+}- if (type === typeof origin) {- if (type === 'string') {- c0 = color(origin);- if (c0.valid) {- c1 = color(target);- if (c1.valid) {- view[key] = c1.mix(c0, ease).rgbString();- continue;- }- }- } else if (type === 'number' && isFinite(origin) && isFinite(target)) {- view[key] = origin + (target - origin) * ease;- continue;+/**+ * Detects support for options object argument in addEventListener.+ * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support+ * @private+ */+var supportsEventListenerOptions = (function() {+ var supports = false;+ try {+ var options = Object.defineProperty({}, 'passive', {+ // eslint-disable-next-line getter-return+ get: function() {+ supports = true;}- }-- view[key] = target;+ });+ window.addEventListener('e', null, options);+ } catch (e) {+ // continue regardless of error}+ return supports;+}());++// Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.+// https://github.com/chartjs/Chart.js/issues/4287+var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;++function addListener(node, type, listener) {+ node.addEventListener(type, listener, eventListenerOptions);+}++function removeListener(node, type, listener) {+ node.removeEventListener(type, listener, eventListenerOptions);+}++function createEvent(type, chart, x, y, nativeEvent) {+ return {+ type: type,+ chart: chart,+ native: nativeEvent || null,+ x: x !== undefined ? x : null,+ y: y !== undefined ? y : null,+ };}-var Element = function(configuration) {- helpers.extend(this, configuration);- this.initialize.apply(this, arguments);-};+function fromNativeEvent(event, chart) {+ var type = EVENT_TYPES[event.type] || event.type;+ var pos = helpers$1.getRelativePosition(event, chart);+ return createEvent(type, chart, pos.x, pos.y, event);+}-helpers.extend(Element.prototype, {+function throttled(fn, thisArg) {+ var ticking = false;+ var args = [];- initialize: function() {- this.hidden = false;- },+ return function() {+ args = Array.prototype.slice.call(arguments);+ thisArg = thisArg || this;- pivot: function() {- var me = this;- if (!me._view) {- me._view = helpers.clone(me._model);+ if (!ticking) {+ ticking = true;+ helpers$1.requestAnimFrame.call(window, function() {+ ticking = false;+ fn.apply(thisArg, args);+ });}- 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;- }+function createDiv(cls) {+ var el = document.createElement('div');+ el.className = cls || '';+ return el;+}- if (!view) {- view = me._view = {};- }+// Implementation based on https://github.com/marcj/css-element-queries+function createResizer(handler) {+ var maxSize = 1000000;- if (!start) {- start = me._start = {};- }+ // NOTE(SB) Don't use innerHTML because it could be considered unsafe.+ // https://github.com/chartjs/Chart.js/issues/5902+ var resizer = createDiv(CSS_SIZE_MONITOR);+ var expand = createDiv(CSS_SIZE_MONITOR + '-expand');+ var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink');- interpolate(start, view, model, ease);+ expand.appendChild(createDiv());+ shrink.appendChild(createDiv());- return me;- },+ resizer.appendChild(expand);+ resizer.appendChild(shrink);+ resizer._reset = function() {+ expand.scrollLeft = maxSize;+ expand.scrollTop = maxSize;+ shrink.scrollLeft = maxSize;+ shrink.scrollTop = maxSize;+ };- tooltipPosition: function() {- return {- x: this._model.x,- y: this._model.y- };- },+ var onScroll = function() {+ resizer._reset();+ handler();+ };- hasValue: function() {- return helpers.isNumber(this._model.x) && helpers.isNumber(this._model.y);- }-});+ addListener(expand, 'scroll', onScroll.bind(expand, 'expand'));+ addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));-Element.extend = helpers.inherits;+ return resizer;+}-module.exports = Element;+// https://davidwalsh.name/detect-node-insertion+function watchForRender(node, handler) {+ var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});+ var proxy = expando.renderProxy = function(e) {+ if (e.animationName === CSS_RENDER_ANIMATION) {+ handler();+ }+ };-},{"3":3,"46":46}],28:[function(require,module,exports){-/* global window: false */-/* global document: false */-'use strict';+ helpers$1.each(ANIMATION_START_EVENTS, function(type) {+ addListener(node, type, proxy);+ });-var color = require(3);-var defaults = require(26);-var helpers = require(46);-var scaleService = require(34);+ // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class+ // is removed then added back immediately (same animation frame?). Accessing the+ // `offsetParent` property will force a reflow and re-evaluate the CSS animation.+ // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics+ // https://github.com/chartjs/Chart.js/issues/4737+ expando.reflow = !!node.offsetParent;-module.exports = function() {+ node.classList.add(CSS_RENDER_MONITOR);+}- // -- Basic js utility methods+function unwatchForRender(node) {+ var expando = node[EXPANDO_KEY] || {};+ var proxy = expando.renderProxy;- helpers.configMerge = function(/* objects ... */) {- return helpers.merge(helpers.clone(arguments[0]), [].slice.call(arguments, 1), {- merger: function(key, target, source, options) {- var tval = target[key] || {};- var sval = source[key];-- if (key === 'scales') {- // scale config merging is complex. Add our own function here for that- target[key] = helpers.scaleMerge(tval, sval);- } else if (key === 'scale') {- // used in polar area & radar charts since there is only one scale- target[key] = helpers.merge(tval, [scaleService.getScaleDefaults(sval.type), sval]);- } else {- helpers._merger(key, target, source, options);- }- }+ if (proxy) {+ helpers$1.each(ANIMATION_START_EVENTS, function(type) {+ removeListener(node, type, proxy);});- };- helpers.scaleMerge = function(/* objects ... */) {- return helpers.merge(helpers.clone(arguments[0]), [].slice.call(arguments, 1), {- merger: function(key, target, source, options) {- if (key === 'xAxes' || key === 'yAxes') {- var slen = source[key].length;- var i, type, scale;-- if (!target[key]) {- target[key] = [];- }+ delete expando.renderProxy;+ }- for (i = 0; i < slen; ++i) {- scale = source[key][i];- type = helpers.valueOrDefault(scale.type, key === 'xAxes' ? 'category' : 'linear');+ node.classList.remove(CSS_RENDER_MONITOR);+}- if (i >= target[key].length) {- target[key].push({});- }+function addResizeListener(node, listener, chart) {+ var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});- if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {- // new/untyped scale or type changed: let's apply the new defaults- // then merge source scale to correctly overwrite the defaults.- helpers.merge(target[key][i], [scaleService.getScaleDefaults(type), scale]);- } else {- // scales type are the same- helpers.merge(target[key][i], scale);- }- }- } else {- helpers._merger(key, target, source, options);- }+ // Let's keep track of this added resizer and thus avoid DOM query when removing it.+ var resizer = expando.resizer = createResizer(throttled(function() {+ if (expando.resizer) {+ var container = chart.options.maintainAspectRatio && node.parentNode;+ var w = container ? container.clientWidth : 0;+ listener(createEvent('resize', chart));+ if (container && container.clientWidth < w && chart.canvas) {+ // If the container size shrank during chart resize, let's assume+ // scrollbar appeared. So we resize again with the scrollbar visible -+ // effectively making chart smaller and the scrollbar hidden again.+ // Because we are inside `throttled`, and currently `ticking`, scroll+ // events are ignored during this whole 2 resize process.+ // If we assumed wrong and something else happened, we are resizing+ // twice in a frame (potential performance issue)+ listener(createEvent('resize', chart));}- });- };-- helpers.where = function(collection, filterCallback) {- if (helpers.isArray(collection) && Array.prototype.filter) {- return collection.filter(filterCallback);}- var filtered = [];+ }));- helpers.each(collection, function(item) {- if (filterCallback(item)) {- filtered.push(item);+ // The resizer needs to be attached to the node parent, so we first need to be+ // sure that `node` is attached to the DOM before injecting the resizer element.+ watchForRender(node, function() {+ if (expando.resizer) {+ var container = node.parentNode;+ if (container && container !== resizer.parentNode) {+ container.insertBefore(resizer, container.firstChild);}- });- return filtered;- };- helpers.findIndex = Array.prototype.findIndex ?- function(array, callback, scope) {- return array.findIndex(callback, scope);- } :- function(array, callback, scope) {- scope = scope === undefined ? array : scope;- for (var i = 0, ilen = array.length; i < ilen; ++i) {- if (callback.call(scope, array[i], i, array)) {- return i;- }- }- return -1;- };- helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {- // Default to start of the array- if (helpers.isNullOrUndef(startIndex)) {- startIndex = -1;- }- for (var i = startIndex + 1; i < arrayToSearch.length; i++) {- var currentItem = arrayToSearch[i];- if (filterCallback(currentItem)) {- return currentItem;- }- }- };- helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {- // Default to end of the array- if (helpers.isNullOrUndef(startIndex)) {- startIndex = arrayToSearch.length;- }- for (var i = startIndex - 1; i >= 0; i--) {- var currentItem = arrayToSearch[i];- if (filterCallback(currentItem)) {- return currentItem;- }+ // The container size might have changed, let's reset the resizer state.+ resizer._reset();}- };-- // -- Math methods- helpers.isNumber = function(n) {- return !isNaN(parseFloat(n)) && isFinite(n);- };- helpers.almostEquals = function(x, y, epsilon) {- return Math.abs(x - y) < epsilon;- };- helpers.almostWhole = function(x, epsilon) {- var rounded = Math.round(x);- return (((rounded - epsilon) < x) && ((rounded + epsilon) > x));- };- helpers.max = function(array) {- return array.reduce(function(max, value) {- if (!isNaN(value)) {- return Math.max(max, value);- }- return max;- }, Number.NEGATIVE_INFINITY);- };- helpers.min = function(array) {- return array.reduce(function(min, value) {- if (!isNaN(value)) {- return Math.min(min, value);- }- return min;- }, Number.POSITIVE_INFINITY);- };- helpers.sign = Math.sign ?- function(x) {- return Math.sign(x);- } :- function(x) {- x = +x; // convert to a number- if (x === 0 || isNaN(x)) {- return x;- }- return x > 0 ? 1 : -1;- };- helpers.log10 = Math.log10 ?- function(x) {- return Math.log10(x);- } :- function(x) {- var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.- // Check for whole powers of 10,- // which due to floating point rounding error should be corrected.- var powerOf10 = Math.round(exponent);- var isPowerOf10 = x === Math.pow(10, powerOf10);-- return isPowerOf10 ? powerOf10 : exponent;- };- helpers.toRadians = function(degrees) {- return degrees * (Math.PI / 180);- };- helpers.toDegrees = function(radians) {- return radians * (180 / Math.PI);- };- // Gets the angle from vertical upright to the point about a centre.- helpers.getAngleFromPoint = function(centrePoint, anglePoint) {- var distanceFromXCenter = anglePoint.x - centrePoint.x;- var distanceFromYCenter = anglePoint.y - centrePoint.y;- var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);-- var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);+ });+}- if (angle < (-0.5 * Math.PI)) {- angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]- }+function removeResizeListener(node) {+ var expando = node[EXPANDO_KEY] || {};+ var resizer = expando.resizer;- return {- angle: angle,- distance: radialDistanceFromCenter- };- };- helpers.distanceBetweenPoints = function(pt1, pt2) {- return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));- };- helpers.aliasPixel = function(pixelWidth) {- return (pixelWidth % 2 === 0) ? 0 : 0.5;- };- helpers.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {- // Props to Rob Spencer at scaled innovation for his post on splining between points- // http://scaledinnovation.com/analytics/splines/aboutSplines.html+ delete expando.resizer;+ unwatchForRender(node);- // This function must also respect "skipped" points+ if (resizer && resizer.parentNode) {+ resizer.parentNode.removeChild(resizer);+ }+}- var previous = firstPoint.skip ? middlePoint : firstPoint;- var current = middlePoint;- var next = afterPoint.skip ? middlePoint : afterPoint;+/**+ * Injects CSS styles inline if the styles are not already present.+ * @param {HTMLDocument|ShadowRoot} rootNode - the node to contain the <style>.+ * @param {string} css - the CSS to be injected.+ */+function injectCSS(rootNode, css) {+ // https://stackoverflow.com/q/3922139+ var expando = rootNode[EXPANDO_KEY] || (rootNode[EXPANDO_KEY] = {});+ if (!expando.containsStyles) {+ expando.containsStyles = true;+ css = '/* Chart.js */\n' + css;+ var style = document.createElement('style');+ style.setAttribute('type', 'text/css');+ style.appendChild(document.createTextNode(css));+ rootNode.appendChild(style);+ }+}- var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));- var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));+var platform_dom$2 = {+ /**+ * When `true`, prevents the automatic injection of the stylesheet required to+ * correctly detect when the chart is added to the DOM and then resized. This+ * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`)+ * to be manually imported to make this library compatible with any CSP.+ * See https://github.com/chartjs/Chart.js/issues/5208+ */+ disableCSSInjection: false,- var s01 = d01 / (d01 + d12);- var s12 = d12 / (d01 + d12);+ /**+ * This property holds whether this platform is enabled for the current environment.+ * Currently used by platform.js to select the proper implementation.+ * @private+ */+ _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',- // If all points are the same, s01 & s02 will be inf- s01 = isNaN(s01) ? 0 : s01;- s12 = isNaN(s12) ? 0 : s12;+ /**+ * Initializes resources that depend on platform options.+ * @param {HTMLCanvasElement} canvas - The Canvas element.+ * @private+ */+ _ensureLoaded: function(canvas) {+ if (!this.disableCSSInjection) {+ // If the canvas is in a shadow DOM, then the styles must also be inserted+ // into the same shadow DOM.+ // https://github.com/chartjs/Chart.js/issues/5763+ var root = canvas.getRootNode ? canvas.getRootNode() : document;+ var targetNode = root.host ? root : document.head;+ injectCSS(targetNode, stylesheet);+ }+ },- var fa = t * s01; // scaling factor for triangle Ta- var fb = t * s12;+ acquireContext: function(item, config) {+ if (typeof item === 'string') {+ item = document.getElementById(item);+ } else if (item.length) {+ // Support for array based queries (such as jQuery)+ item = item[0];+ }- return {- previous: {- x: current.x - fa * (next.x - previous.x),- y: current.y - fa * (next.y - previous.y)- },- next: {- x: current.x + fb * (next.x - previous.x),- y: current.y + fb * (next.y - previous.y)- }- };- };- helpers.EPSILON = Number.EPSILON || 1e-14;- helpers.splineCurveMonotone = function(points) {- // This function calculates Bézier control points in a similar way than |splineCurve|,- // but preserves monotonicity of the provided data and ensures no local extremums are added- // between the dataset discrete points due to the interpolation.- // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation+ if (item && item.canvas) {+ // Support for any object associated to a canvas (including a context2d)+ item = item.canvas;+ }- var pointsWithTangents = (points || []).map(function(point) {- return {- model: point._model,- deltaK: 0,- mK: 0- };- });+ // To prevent canvas fingerprinting, some add-ons undefine the getContext+ // method, for example: https://github.com/kkapsner/CanvasBlocker+ // https://github.com/chartjs/Chart.js/issues/2807+ var context = item && item.getContext && item.getContext('2d');- // Calculate slopes (deltaK) and initialize tangents (mK)- var pointsLen = pointsWithTangents.length;- var i, pointBefore, pointCurrent, pointAfter;- for (i = 0; i < pointsLen; ++i) {- pointCurrent = pointsWithTangents[i];- if (pointCurrent.model.skip) {- continue;- }+ // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is+ // inside an iframe or when running in a protected environment. We could guess the+ // types from their toString() value but let's keep things flexible and assume it's+ // a sufficient condition if the item has a context2D which has item as `canvas`.+ // https://github.com/chartjs/Chart.js/issues/3887+ // https://github.com/chartjs/Chart.js/issues/4102+ // https://github.com/chartjs/Chart.js/issues/4152+ if (context && context.canvas === item) {+ // Load platform resources on first chart creation, to make it possible to+ // import the library before setting platform options.+ this._ensureLoaded(item);+ initCanvas(item, config);+ return context;+ }- pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;- pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;- if (pointAfter && !pointAfter.model.skip) {- var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);+ return null;+ },- // In the case of two points that appear at the same x pixel, slopeDeltaX is 0- pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;- }+ releaseContext: function(context) {+ var canvas = context.canvas;+ if (!canvas[EXPANDO_KEY]) {+ return;+ }- if (!pointBefore || pointBefore.model.skip) {- pointCurrent.mK = pointCurrent.deltaK;- } else if (!pointAfter || pointAfter.model.skip) {- pointCurrent.mK = pointBefore.deltaK;- } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {- pointCurrent.mK = 0;+ var initial = canvas[EXPANDO_KEY].initial;+ ['height', 'width'].forEach(function(prop) {+ var value = initial[prop];+ if (helpers$1.isNullOrUndef(value)) {+ canvas.removeAttribute(prop);} else {- pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;+ canvas.setAttribute(prop, value);}- }+ });- // Adjust tangents to ensure monotonic properties- var alphaK, betaK, tauK, squaredMagnitude;- for (i = 0; i < pointsLen - 1; ++i) {- pointCurrent = pointsWithTangents[i];- pointAfter = pointsWithTangents[i + 1];- if (pointCurrent.model.skip || pointAfter.model.skip) {- continue;- }+ helpers$1.each(initial.style || {}, function(value, key) {+ canvas.style[key] = value;+ });- if (helpers.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {- pointCurrent.mK = pointAfter.mK = 0;- continue;- }+ // The canvas render size might have been changed (and thus the state stack discarded),+ // we can't use save() and restore() to restore the initial state. So make sure that at+ // least the canvas context is reset to the default state by setting the canvas width.+ // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html+ // eslint-disable-next-line no-self-assign+ canvas.width = canvas.width;- alphaK = pointCurrent.mK / pointCurrent.deltaK;- betaK = pointAfter.mK / pointCurrent.deltaK;- squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);- if (squaredMagnitude <= 9) {- continue;- }+ delete canvas[EXPANDO_KEY];+ },- tauK = 3 / Math.sqrt(squaredMagnitude);- pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;- pointAfter.mK = betaK * tauK * pointCurrent.deltaK;+ addEventListener: function(chart, type, listener) {+ var canvas = chart.canvas;+ if (type === 'resize') {+ // Note: the resize event is not supported on all browsers.+ addResizeListener(canvas, listener, chart);+ return;}- // Compute control points- var deltaX;- for (i = 0; i < pointsLen; ++i) {- pointCurrent = pointsWithTangents[i];- if (pointCurrent.model.skip) {- continue;- }+ var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});+ var proxies = expando.proxies || (expando.proxies = {});+ var proxy = proxies[chart.id + '_' + type] = function(event) {+ listener(fromNativeEvent(event, chart));+ };- pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;- pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;- if (pointBefore && !pointBefore.model.skip) {- deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;- pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;- pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;- }- if (pointAfter && !pointAfter.model.skip) {- deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;- pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;- pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;- }- }- };- helpers.nextItem = function(collection, index, loop) {- if (loop) {- return index >= collection.length - 1 ? collection[0] : collection[index + 1];- }- return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];- };- helpers.previousItem = function(collection, index, loop) {- if (loop) {- return index <= 0 ? collection[collection.length - 1] : collection[index - 1];- }- return index <= 0 ? collection[0] : collection[index - 1];- };- // Implementation of the nice number algorithm used in determining where axis labels will go- helpers.niceNum = function(range, round) {- var exponent = Math.floor(helpers.log10(range));- var fraction = range / Math.pow(10, exponent);- var niceFraction;+ addListener(canvas, type, proxy);+ },- if (round) {- if (fraction < 1.5) {- niceFraction = 1;- } else if (fraction < 3) {- niceFraction = 2;- } else if (fraction < 7) {- niceFraction = 5;- } else {- niceFraction = 10;- }- } else if (fraction <= 1.0) {- niceFraction = 1;- } else if (fraction <= 2) {- niceFraction = 2;- } else if (fraction <= 5) {- niceFraction = 5;- } else {- niceFraction = 10;+ removeEventListener: function(chart, type, listener) {+ var canvas = chart.canvas;+ if (type === 'resize') {+ // Note: the resize event is not supported on all browsers.+ removeResizeListener(canvas);+ return;}- return niceFraction * Math.pow(10, exponent);- };- // Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/- helpers.requestAnimFrame = (function() {- if (typeof window === 'undefined') {- return function(callback) {- callback();- };+ var expando = listener[EXPANDO_KEY] || {};+ var proxies = expando.proxies || {};+ var proxy = proxies[chart.id + '_' + type];+ if (!proxy) {+ return;}- return window.requestAnimationFrame ||- window.webkitRequestAnimationFrame ||- window.mozRequestAnimationFrame ||- window.oRequestAnimationFrame ||- window.msRequestAnimationFrame ||- function(callback) {- return window.setTimeout(callback, 1000 / 60);- };- }());- // -- DOM methods- helpers.getRelativePosition = function(evt, chart) {- var mouseX, mouseY;- var e = evt.originalEvent || evt;- var canvas = evt.target || evt.srcElement;- var boundingRect = canvas.getBoundingClientRect();- var touches = e.touches;- if (touches && touches.length > 0) {- mouseX = touches[0].clientX;- mouseY = touches[0].clientY;+ removeListener(canvas, type, proxy);+ }+};- } else {- mouseX = e.clientX;- mouseY = e.clientY;- }+// DEPRECATIONS- // Scale mouse coordinates into canvas coordinates- // by following the pattern laid out by 'jerryj' in the comments of- // http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/- var paddingLeft = parseFloat(helpers.getStyle(canvas, 'padding-left'));- var paddingTop = parseFloat(helpers.getStyle(canvas, 'padding-top'));- var paddingRight = parseFloat(helpers.getStyle(canvas, 'padding-right'));- var paddingBottom = parseFloat(helpers.getStyle(canvas, 'padding-bottom'));- var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;- var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;+/**+ * Provided for backward compatibility, use EventTarget.addEventListener instead.+ * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9++ * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener+ * @function Chart.helpers.addEvent+ * @deprecated since version 2.7.0+ * @todo remove at version 3+ * @private+ */+helpers$1.addEvent = addListener;- // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However- // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here- mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);- mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);+/**+ * Provided for backward compatibility, use EventTarget.removeEventListener instead.+ * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9++ * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener+ * @function Chart.helpers.removeEvent+ * @deprecated since version 2.7.0+ * @todo remove at version 3+ * @private+ */+helpers$1.removeEvent = removeListener;- return {- x: mouseX,- y: mouseY- };+// @TODO Make possible to select another platform at build time.+var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic;- };+/**+ * @namespace Chart.platform+ * @see https://chartjs.gitbooks.io/proposals/content/Platform.html+ * @since 2.4.0+ */+var platform = helpers$1.extend({+ /**+ * @since 2.7.0+ */+ initialize: function() {},- // Private helper function to convert max-width/max-height values that may be percentages into a number- function parseMaxStyle(styleValue, node, parentProperty) {- var valueInPixels;- if (typeof styleValue === 'string') {- valueInPixels = parseInt(styleValue, 10);+ /**+ * Called at chart construction time, returns a context2d instance implementing+ * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.+ * @param {*} item - The native item from which to acquire context (platform specific)+ * @param {object} options - The chart options+ * @returns {CanvasRenderingContext2D} context2d instance+ */+ acquireContext: function() {},- if (styleValue.indexOf('%') !== -1) {- // percentage * size in dimension- valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];- }- } else {- valueInPixels = styleValue;- }+ /**+ * Called at chart destruction time, releases any resources associated to the context+ * previously returned by the acquireContext() method.+ * @param {CanvasRenderingContext2D} context - The context2d instance+ * @returns {boolean} true if the method succeeded, else false+ */+ releaseContext: function() {},- return valueInPixels;- }+ /**+ * Registers the specified listener on the given chart.+ * @param {Chart} chart - Chart from which to listen for event+ * @param {string} type - The ({@link IEvent}) type to listen for+ * @param {function} listener - Receives a notification (an object that implements+ * the {@link IEvent} interface) when an event of the specified type occurs.+ */+ addEventListener: function() {},/**- * Returns if the given value contains an effective constraint.- * @private+ * Removes the specified listener previously registered with addEventListener.+ * @param {Chart} chart - Chart from which to remove the listener+ * @param {string} type - The ({@link IEvent}) type to remove+ * @param {function} listener - The listener function to remove from the event target.*/- function isConstrainedValue(value) {- return value !== undefined && value !== null && value !== 'none';- }+ removeEventListener: function() {}- // Private helper to get a constraint dimension- // @param domNode : the node to check the constraint on- // @param maxStyle : the style that defines the maximum for the direction we are using (maxWidth / maxHeight)- // @param percentageProperty : property of parent to use when calculating width as a percentage- // @see http://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser- function getConstraintDimension(domNode, maxStyle, percentageProperty) {- var view = document.defaultView;- var parentNode = helpers._getParentNode(domNode);- var constrainedNode = view.getComputedStyle(domNode)[maxStyle];- var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];- var hasCNode = isConstrainedValue(constrainedNode);- var hasCContainer = isConstrainedValue(constrainedContainer);- var infinity = Number.POSITIVE_INFINITY;+}, implementation);- if (hasCNode || hasCContainer) {- return Math.min(- hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,- hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);- }+core_defaults._set('global', {+ plugins: {}+});- return 'none';- }- // returns Number or undefined if no constraint- helpers.getConstraintWidth = function(domNode) {- return getConstraintDimension(domNode, 'max-width', 'clientWidth');- };- // returns Number or undefined if no constraint- helpers.getConstraintHeight = function(domNode) {- return getConstraintDimension(domNode, 'max-height', 'clientHeight');- };+/**+ * The plugin service singleton+ * @namespace Chart.plugins+ * @since 2.1.0+ */+var core_plugins = {/**+ * Globally registered plugins.* @private- */- helpers._calculatePadding = function(container, padding, parentDimension) {- padding = helpers.getStyle(container, padding);+ */+ _plugins: [],- return padding.indexOf('%') > -1 ? parentDimension / parseInt(padding, 10) : parseInt(padding, 10);- };/**+ * This identifier is used to invalidate the descriptors cache attached to each chart+ * when a global plugin is registered or unregistered. In this case, the cache ID is+ * incremented and descriptors are regenerated during following API calls.* @private*/- helpers._getParentNode = function(domNode) {- var parent = domNode.parentNode;- if (parent && parent.host) {- parent = parent.host;- }- return parent;- };- helpers.getMaximumWidth = function(domNode) {- var container = helpers._getParentNode(domNode);- if (!container) {- return domNode.clientWidth;- }-- var clientWidth = container.clientWidth;- var paddingLeft = helpers._calculatePadding(container, 'padding-left', clientWidth);- var paddingRight = helpers._calculatePadding(container, 'padding-right', clientWidth);+ _cacheId: 0,- var w = clientWidth - paddingLeft - paddingRight;- var cw = helpers.getConstraintWidth(domNode);- return isNaN(cw) ? w : Math.min(w, cw);- };- helpers.getMaximumHeight = function(domNode) {- var container = helpers._getParentNode(domNode);- if (!container) {- return domNode.clientHeight;- }+ /**+ * Registers the given plugin(s) if not already registered.+ * @param {IPlugin[]|IPlugin} plugins plugin instance(s).+ */+ register: function(plugins) {+ var p = this._plugins;+ ([]).concat(plugins).forEach(function(plugin) {+ if (p.indexOf(plugin) === -1) {+ p.push(plugin);+ }+ });- var clientHeight = container.clientHeight;- var paddingTop = helpers._calculatePadding(container, 'padding-top', clientHeight);- var paddingBottom = helpers._calculatePadding(container, 'padding-bottom', clientHeight);+ this._cacheId++;+ },- var h = clientHeight - paddingTop - paddingBottom;- var ch = helpers.getConstraintHeight(domNode);- return isNaN(ch) ? h : Math.min(h, ch);- };- helpers.getStyle = function(el, property) {- return el.currentStyle ?- el.currentStyle[property] :- document.defaultView.getComputedStyle(el, null).getPropertyValue(property);- };- helpers.retinaScale = function(chart, forceRatio) {- var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;- if (pixelRatio === 1) {- return;- }+ /**+ * Unregisters the given plugin(s) only if registered.+ * @param {IPlugin[]|IPlugin} plugins plugin instance(s).+ */+ unregister: function(plugins) {+ var p = this._plugins;+ ([]).concat(plugins).forEach(function(plugin) {+ var idx = p.indexOf(plugin);+ if (idx !== -1) {+ p.splice(idx, 1);+ }+ });- var canvas = chart.canvas;- var height = chart.height;- var width = chart.width;+ this._cacheId++;+ },- canvas.height = height * pixelRatio;- canvas.width = width * pixelRatio;- chart.ctx.scale(pixelRatio, pixelRatio);+ /**+ * Remove all registered plugins.+ * @since 2.1.5+ */+ clear: function() {+ this._plugins = [];+ this._cacheId++;+ },- // If no style has been set on the canvas, the render size is used as display size,- // making the chart visually bigger, so let's enforce it to the "correct" values.- // See https://github.com/chartjs/Chart.js/issues/3575- if (!canvas.style.height && !canvas.style.width) {- canvas.style.height = height + 'px';- canvas.style.width = width + 'px';- }- };- // -- Canvas methods- helpers.fontString = function(pixelSize, fontStyle, fontFamily) {- return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;- };- helpers.longestText = function(ctx, font, arrayOfThings, cache) {- cache = cache || {};- var data = cache.data = cache.data || {};- var gc = cache.garbageCollect = cache.garbageCollect || [];+ /**+ * Returns the number of registered plugins?+ * @returns {number}+ * @since 2.1.5+ */+ count: function() {+ return this._plugins.length;+ },- if (cache.font !== font) {- data = cache.data = {};- gc = cache.garbageCollect = [];- cache.font = font;- }+ /**+ * Returns all registered plugin instances.+ * @returns {IPlugin[]} array of plugin objects.+ * @since 2.1.5+ */+ getAll: function() {+ return this._plugins;+ },- ctx.font = font;- var longest = 0;- helpers.each(arrayOfThings, function(thing) {- // Undefined strings and arrays should not be measured- if (thing !== undefined && thing !== null && helpers.isArray(thing) !== true) {- longest = helpers.measureText(ctx, data, gc, longest, thing);- } else if (helpers.isArray(thing)) {- // if it is an array lets measure each element- // to do maybe simplify this function a bit so we can do this more recursively?- helpers.each(thing, function(nestedThing) {- // Undefined strings and arrays should not be measured- if (nestedThing !== undefined && nestedThing !== null && !helpers.isArray(nestedThing)) {- longest = helpers.measureText(ctx, data, gc, longest, nestedThing);- }- });- }- });+ /**+ * Calls enabled plugins for `chart` on the specified hook and with the given args.+ * This method immediately returns as soon as a plugin explicitly returns false. The+ * returned value can be used, for instance, to interrupt the current action.+ * @param {Chart} chart - The chart instance for which plugins should be called.+ * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').+ * @param {Array} [args] - Extra arguments to apply to the hook call.+ * @returns {boolean} false if any of the plugins return false, else returns true.+ */+ notify: function(chart, hook, args) {+ var descriptors = this.descriptors(chart);+ var ilen = descriptors.length;+ var i, descriptor, plugin, params, method;- var gcLen = gc.length / 2;- if (gcLen > arrayOfThings.length) {- for (var i = 0; i < gcLen; i++) {- delete data[gc[i]];+ for (i = 0; i < ilen; ++i) {+ descriptor = descriptors[i];+ plugin = descriptor.plugin;+ method = plugin[hook];+ if (typeof method === 'function') {+ params = [chart].concat(args || []);+ params.push(descriptor.options);+ if (method.apply(plugin, params) === false) {+ return false;+ }}- gc.splice(0, gcLen);- }- return longest;- };- helpers.measureText = function(ctx, data, gc, longest, string) {- var textWidth = data[string];- if (!textWidth) {- textWidth = data[string] = ctx.measureText(string).width;- gc.push(string);}- if (textWidth > longest) {- longest = textWidth;- }- return longest;- };- helpers.numberOfLabelLines = function(arrayOfThings) {- var numberOfLines = 1;- helpers.each(arrayOfThings, function(thing) {- if (helpers.isArray(thing)) {- if (thing.length > numberOfLines) {- numberOfLines = thing.length;- }++ return true;+ },++ /**+ * Returns descriptors of enabled plugins for the given chart.+ * @returns {object[]} [{ plugin, options }]+ * @private+ */+ descriptors: function(chart) {+ var cache = chart.$plugins || (chart.$plugins = {});+ if (cache.id === this._cacheId) {+ return cache.descriptors;+ }++ var plugins = [];+ var descriptors = [];+ var config = (chart && chart.config) || {};+ var options = (config.options && config.options.plugins) || {};++ this._plugins.concat(config.plugins || []).forEach(function(plugin) {+ var idx = plugins.indexOf(plugin);+ if (idx !== -1) {+ return;}- });- return numberOfLines;- };- helpers.color = !color ?- function(value) {- console.error('Color.js not found!');- return value;- } :- function(value) {- /* global CanvasGradient */- if (value instanceof CanvasGradient) {- value = defaults.global.defaultColor;+ var id = plugin.id;+ var opts = options[id];+ if (opts === false) {+ return;}- return color(value);- };+ if (opts === true) {+ opts = helpers$1.clone(core_defaults.global.plugins[id]);+ }- helpers.getHoverColor = function(colorValue) {- /* global CanvasPattern */- return (colorValue instanceof CanvasPattern) ?- colorValue :- helpers.color(colorValue).saturate(0.5).darken(0.1).rgbString();- };-};+ plugins.push(plugin);+ descriptors.push({+ plugin: plugin,+ options: opts || {}+ });+ });-},{"26":26,"3":3,"34":34,"46":46}],29:[function(require,module,exports){-'use strict';+ cache.descriptors = descriptors;+ cache.id = this._cacheId;+ return descriptors;+ },-var helpers = require(46);+ /**+ * Invalidates cache for the given chart: descriptors hold a reference on plugin option,+ * but in some cases, this reference can be changed by the user when updating options.+ * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167+ * @private+ */+ _invalidate: function(chart) {+ delete chart.$plugins;+ }+};-/**- * Helper function to get relative position for an event- * @param {Event|IEvent} event - The event to get the position for- * @param {Chart} chart - The chart- * @returns {Point} the event position- */-function getRelativePosition(e, chart) {- if (e.native) {- return {- x: e.x,- y: e.y- };+var core_scaleService = {+ // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then+ // use the new chart options to grab the correct scale+ constructors: {},+ // Use a registration function so that we can move to an ES6 map when we no longer need to support+ // old browsers++ // Scale config defaults+ defaults: {},+ registerScaleType: function(type, scaleConstructor, scaleDefaults) {+ this.constructors[type] = scaleConstructor;+ this.defaults[type] = helpers$1.clone(scaleDefaults);+ },+ getScaleConstructor: function(type) {+ return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;+ },+ getScaleDefaults: function(type) {+ // Return the scale defaults merged with the global settings so that we always use the latest ones+ return this.defaults.hasOwnProperty(type) ? helpers$1.merge({}, [core_defaults.scale, this.defaults[type]]) : {};+ },+ updateScaleDefaults: function(type, additions) {+ var me = this;+ if (me.defaults.hasOwnProperty(type)) {+ me.defaults[type] = helpers$1.extend(me.defaults[type], additions);+ }+ },+ addScalesToLayout: function(chart) {+ // Adds each scale to the chart.boxes array to be sized accordingly+ helpers$1.each(chart.scales, function(scale) {+ // Set ILayoutItem parameters for backwards compatibility+ scale.fullWidth = scale.options.fullWidth;+ scale.position = scale.options.position;+ scale.weight = scale.options.weight;+ core_layouts.addBox(chart, scale);+ });}+};- return helpers.getRelativePosition(e, chart);-}+var valueOrDefault$8 = helpers$1.valueOrDefault;+var getRtlHelper = helpers$1.rtl.getRtlAdapter;-/**- * Helper function to traverse all of the visible elements in the chart- * @param chart {chart} the chart- * @param handler {Function} the callback to execute for each visible item- */-function parseVisibleItems(chart, handler) {- var datasets = chart.data.datasets;- var meta, i, j, ilen, jlen;+core_defaults._set('global', {+ tooltips: {+ enabled: true,+ custom: null,+ mode: 'nearest',+ position: 'average',+ intersect: true,+ backgroundColor: 'rgba(0,0,0,0.8)',+ titleFontStyle: 'bold',+ titleSpacing: 2,+ titleMarginBottom: 6,+ titleFontColor: '#fff',+ titleAlign: 'left',+ bodySpacing: 2,+ bodyFontColor: '#fff',+ bodyAlign: 'left',+ footerFontStyle: 'bold',+ footerSpacing: 2,+ footerMarginTop: 6,+ footerFontColor: '#fff',+ footerAlign: 'left',+ yPadding: 6,+ xPadding: 6,+ caretPadding: 2,+ caretSize: 5,+ cornerRadius: 6,+ multiKeyBackground: '#fff',+ displayColors: true,+ borderColor: 'rgba(0,0,0,0)',+ borderWidth: 0,+ callbacks: {+ // Args are: (tooltipItems, data)+ beforeTitle: helpers$1.noop,+ title: function(tooltipItems, data) {+ var title = '';+ var labels = data.labels;+ var labelCount = labels ? labels.length : 0;- for (i = 0, ilen = datasets.length; i < ilen; ++i) {- if (!chart.isDatasetVisible(i)) {- continue;- }+ if (tooltipItems.length > 0) {+ var item = tooltipItems[0];+ if (item.label) {+ title = item.label;+ } else if (item.xLabel) {+ title = item.xLabel;+ } else if (labelCount > 0 && item.index < labelCount) {+ title = labels[item.index];+ }+ }- meta = chart.getDatasetMeta(i);- for (j = 0, jlen = meta.data.length; j < jlen; ++j) {- var element = meta.data[j];- if (!element._view.skip) {- handler(element);- }- }- }-}+ return title;+ },+ afterTitle: helpers$1.noop,-/**- * Helper function to get the items that intersect the event position- * @param items {ChartElement[]} elements to filter- * @param position {Point} the point to be nearest to- * @return {ChartElement[]} the nearest items- */-function getIntersectItems(chart, position) {- var elements = [];+ // Args are: (tooltipItems, data)+ beforeBody: helpers$1.noop,- parseVisibleItems(chart, function(element) {- if (element.inRange(position.x, position.y)) {- elements.push(element);- }- });+ // Args are: (tooltipItem, data)+ beforeLabel: helpers$1.noop,+ label: function(tooltipItem, data) {+ var label = data.datasets[tooltipItem.datasetIndex].label || '';- return elements;-}+ if (label) {+ label += ': ';+ }+ if (!helpers$1.isNullOrUndef(tooltipItem.value)) {+ label += tooltipItem.value;+ } else {+ label += tooltipItem.yLabel;+ }+ return label;+ },+ labelColor: function(tooltipItem, chart) {+ var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);+ var activeElement = meta.data[tooltipItem.index];+ var view = activeElement._view;+ return {+ borderColor: view.borderColor,+ backgroundColor: view.backgroundColor+ };+ },+ labelTextColor: function() {+ return this._options.bodyFontColor;+ },+ afterLabel: helpers$1.noop,-/**- * Helper function to get the items nearest to the event position considering all visible items in teh chart- * @param chart {Chart} the chart to look at elements from- * @param position {Point} the point to be nearest to- * @param intersect {Boolean} if true, only consider items that intersect the position- * @param distanceMetric {Function} function to provide the distance between points- * @return {ChartElement[]} the nearest items- */-function getNearestItems(chart, position, intersect, distanceMetric) {- var minDistance = Number.POSITIVE_INFINITY;- var nearestItems = [];+ // Args are: (tooltipItems, data)+ afterBody: helpers$1.noop,- parseVisibleItems(chart, function(element) {- if (intersect && !element.inRange(position.x, position.y)) {- return;+ // Args are: (tooltipItems, data)+ beforeFooter: helpers$1.noop,+ footer: helpers$1.noop,+ afterFooter: helpers$1.noop}+ }+});- var center = element.getCenterPoint();- var distance = distanceMetric(position, center);+var positioners = {+ /**+ * Average mode places the tooltip at the average position of the elements shown+ * @function Chart.Tooltip.positioners.average+ * @param elements {ChartElement[]} the elements being displayed in the tooltip+ * @returns {object} tooltip position+ */+ average: function(elements) {+ if (!elements.length) {+ return false;+ }- if (distance < minDistance) {- nearestItems = [element];- minDistance = distance;- } else if (distance === minDistance) {- // Can have multiple items at the same distance in which case we sort by size- nearestItems.push(element);+ var i, len;+ var x = 0;+ var y = 0;+ var count = 0;++ for (i = 0, len = elements.length; i < len; ++i) {+ var el = elements[i];+ if (el && el.hasValue()) {+ var pos = el.tooltipPosition();+ x += pos.x;+ y += pos.y;+ ++count;+ }}- });- return nearestItems;-}+ return {+ x: x / count,+ y: y / count+ };+ },-/**- * Get a distance metric function for two points based on the- * axis mode setting- * @param {String} axis the axis mode. x|y|xy- */-function getDistanceMetricForAxis(axis) {- var useX = axis.indexOf('x') !== -1;- var useY = axis.indexOf('y') !== -1;+ /**+ * Gets the tooltip position nearest of the item nearest to the event position+ * @function Chart.Tooltip.positioners.nearest+ * @param elements {Chart.Element[]} the tooltip elements+ * @param eventPosition {object} the position of the event in canvas coordinates+ * @returns {object} the tooltip position+ */+ nearest: function(elements, eventPosition) {+ var x = eventPosition.x;+ var y = eventPosition.y;+ var minDistance = Number.POSITIVE_INFINITY;+ var i, len, nearestElement;++ for (i = 0, len = elements.length; i < len; ++i) {+ var el = elements[i];+ if (el && el.hasValue()) {+ var center = el.getCenterPoint();+ var d = helpers$1.distanceBetweenPoints(eventPosition, center);- return function(pt1, pt2) {- var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;- var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;- return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));- };-}+ if (d < minDistance) {+ minDistance = d;+ nearestElement = el;+ }+ }+ }-function indexMode(chart, e, options) {- var position = getRelativePosition(e, chart);- // Default axis for index mode is 'x' to match old behaviour- options.axis = options.axis || 'x';- var distanceMetric = getDistanceMetricForAxis(options.axis);- var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);- var elements = [];+ if (nearestElement) {+ var tp = nearestElement.tooltipPosition();+ x = tp.x;+ y = tp.y;+ }- if (!items.length) {- return [];+ return {+ x: x,+ y: y+ };}+};- chart.data.datasets.forEach(function(dataset, datasetIndex) {- if (chart.isDatasetVisible(datasetIndex)) {- var meta = chart.getDatasetMeta(datasetIndex);- var element = meta.data[items[0]._index];-- // don't count items that are skipped (null data)- if (element && !element._view.skip) {- elements.push(element);- }+// Helper to push or concat based on if the 2nd parameter is an array or not+function pushOrConcat(base, toPush) {+ if (toPush) {+ if (helpers$1.isArray(toPush)) {+ // base = base.concat(toPush);+ Array.prototype.push.apply(base, toPush);+ } else {+ base.push(toPush);}- });+ }- return elements;+ return base;}/**- * @interface IInteractionOptions- */-/**- * If true, only consider items that intersect the point- * @name IInterfaceOptions#boolean- * @type Boolean+ * Returns array of strings split by newline+ * @param {string} value - The value to split by newline.+ * @returns {string[]} value if newline present - Returned from String split() method+ * @function*/+function splitNewlines(str) {+ if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {+ return str.split('\n');+ }+ return str;+}+/**- * Contains interaction related functions- * @namespace Chart.Interaction+ * Private helper to create a tooltip item model+ * @param element - the chart element (point, arc, bar) to create the tooltip item for+ * @return new tooltip item*/-module.exports = {- // Helper function for different modes- modes: {- single: function(chart, e) {- var position = getRelativePosition(e, chart);- var elements = [];+function createTooltipItem(element) {+ var xScale = element._xScale;+ var yScale = element._yScale || element._scale; // handle radar || polarArea charts+ var index = element._index;+ var datasetIndex = element._datasetIndex;+ var controller = element._chart.getDatasetMeta(datasetIndex).controller;+ var indexScale = controller._getIndexScale();+ var valueScale = controller._getValueScale();- parseVisibleItems(chart, function(element) {- if (element.inRange(position.x, position.y)) {- elements.push(element);- return elements;- }- });+ return {+ xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',+ yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',+ label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '',+ value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '',+ index: index,+ datasetIndex: datasetIndex,+ x: element._model.x,+ y: element._model.y+ };+}- return elements.slice(0, 1);- },+/**+ * Helper to get the reset model for the tooltip+ * @param tooltipOpts {object} the tooltip options+ */+function getBaseModel(tooltipOpts) {+ var globalDefaults = core_defaults.global;- /**- * @function Chart.Interaction.modes.label- * @deprecated since version 2.4.0- * @todo remove at version 3- * @private- */- label: indexMode,+ return {+ // Positioning+ xPadding: tooltipOpts.xPadding,+ yPadding: tooltipOpts.yPadding,+ xAlign: tooltipOpts.xAlign,+ yAlign: tooltipOpts.yAlign,- /**- * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something- * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item- * @function Chart.Interaction.modes.index- * @since v2.4.0- * @param chart {chart} the chart we are returning items from- * @param e {Event} the event we are find things at- * @param options {IInteractionOptions} options to use during interaction- * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned- */- index: indexMode,+ // Drawing direction and text direction+ rtl: tooltipOpts.rtl,+ textDirection: tooltipOpts.textDirection,- /**- * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something- * If the options.intersect is false, we find the nearest item and return the items in that dataset- * @function Chart.Interaction.modes.dataset- * @param chart {chart} the chart we are returning items from- * @param e {Event} the event we are find things at- * @param options {IInteractionOptions} options to use during interaction- * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned- */- dataset: function(chart, e, options) {- var position = getRelativePosition(e, chart);- options.axis = options.axis || 'xy';- var distanceMetric = getDistanceMetricForAxis(options.axis);- var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);+ // Body+ bodyFontColor: tooltipOpts.bodyFontColor,+ _bodyFontFamily: valueOrDefault$8(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),+ _bodyFontStyle: valueOrDefault$8(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),+ _bodyAlign: tooltipOpts.bodyAlign,+ bodyFontSize: valueOrDefault$8(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),+ bodySpacing: tooltipOpts.bodySpacing,- if (items.length > 0) {- items = chart.getDatasetMeta(items[0]._datasetIndex).data;- }+ // Title+ titleFontColor: tooltipOpts.titleFontColor,+ _titleFontFamily: valueOrDefault$8(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),+ _titleFontStyle: valueOrDefault$8(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),+ titleFontSize: valueOrDefault$8(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),+ _titleAlign: tooltipOpts.titleAlign,+ titleSpacing: tooltipOpts.titleSpacing,+ titleMarginBottom: tooltipOpts.titleMarginBottom,- return items;- },+ // Footer+ footerFontColor: tooltipOpts.footerFontColor,+ _footerFontFamily: valueOrDefault$8(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),+ _footerFontStyle: valueOrDefault$8(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),+ footerFontSize: valueOrDefault$8(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),+ _footerAlign: tooltipOpts.footerAlign,+ footerSpacing: tooltipOpts.footerSpacing,+ footerMarginTop: tooltipOpts.footerMarginTop,- /**- * @function Chart.Interaction.modes.x-axis- * @deprecated since version 2.4.0. Use index mode and intersect == true- * @todo remove at version 3- * @private- */- 'x-axis': function(chart, e) {- return indexMode(chart, e, {intersect: false});- },+ // Appearance+ caretSize: tooltipOpts.caretSize,+ cornerRadius: tooltipOpts.cornerRadius,+ backgroundColor: tooltipOpts.backgroundColor,+ opacity: 0,+ legendColorBackground: tooltipOpts.multiKeyBackground,+ displayColors: tooltipOpts.displayColors,+ borderColor: tooltipOpts.borderColor,+ borderWidth: tooltipOpts.borderWidth+ };+}- /**- * Point mode returns all elements that hit test based on the event position- * of the event- * @function Chart.Interaction.modes.intersect- * @param chart {chart} the chart we are returning items from- * @param e {Event} the event we are find things at- * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned- */- point: function(chart, e) {- var position = getRelativePosition(e, chart);- return getIntersectItems(chart, position);- },+/**+ * Get the size of the tooltip+ */+function getTooltipSize(tooltip, model) {+ var ctx = tooltip._chart.ctx;- /**- * nearest mode returns the element closest to the point- * @function Chart.Interaction.modes.intersect- * @param chart {chart} the chart we are returning items from- * @param e {Event} the event we are find things at- * @param options {IInteractionOptions} options to use- * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned- */- nearest: function(chart, e, options) {- var position = getRelativePosition(e, chart);- options.axis = options.axis || 'xy';- var distanceMetric = getDistanceMetricForAxis(options.axis);- var nearestItems = getNearestItems(chart, position, options.intersect, distanceMetric);-- // We have multiple items at the same distance from the event. Now sort by smallest- if (nearestItems.length > 1) {- nearestItems.sort(function(a, b) {- var sizeA = a.getArea();- var sizeB = b.getArea();- var ret = sizeA - sizeB;-- if (ret === 0) {- // if equal sort by dataset index- ret = a._datasetIndex - b._datasetIndex;- }+ var height = model.yPadding * 2; // Tooltip Padding+ var width = 0;- return ret;- });- }+ // Count of all lines in the body+ var body = model.body;+ var combinedBodyLength = body.reduce(function(count, bodyItem) {+ return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;+ }, 0);+ combinedBodyLength += model.beforeBody.length + model.afterBody.length;- // Return only 1 item- return nearestItems.slice(0, 1);- },+ var titleLineCount = model.title.length;+ var footerLineCount = model.footer.length;+ var titleFontSize = model.titleFontSize;+ var bodyFontSize = model.bodyFontSize;+ var footerFontSize = model.footerFontSize;- /**- * x mode returns the elements that hit-test at the current x coordinate- * @function Chart.Interaction.modes.x- * @param chart {chart} the chart we are returning items from- * @param e {Event} the event we are find things at- * @param options {IInteractionOptions} options to use- * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned- */- x: function(chart, e, options) {- var position = getRelativePosition(e, chart);- var items = [];- var intersectsItem = false;+ height += titleLineCount * titleFontSize; // Title Lines+ height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing+ height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin+ height += combinedBodyLength * bodyFontSize; // Body Lines+ height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing+ height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin+ height += footerLineCount * (footerFontSize); // Footer Lines+ height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing- parseVisibleItems(chart, function(element) {- if (element.inXRange(position.x)) {- items.push(element);- }+ // Title width+ var widthPadding = 0;+ var maxLineWidth = function(line) {+ width = Math.max(width, ctx.measureText(line).width + widthPadding);+ };- if (element.inRange(position.x, position.y)) {- intersectsItem = true;- }- });+ ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);+ helpers$1.each(model.title, maxLineWidth);- // If we want to trigger on an intersect and we don't have any items- // that intersect the position, return nothing- if (options.intersect && !intersectsItem) {- items = [];- }- return items;- },+ // Body width+ ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);+ helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth);- /**- * y mode returns the elements that hit-test at the current y coordinate- * @function Chart.Interaction.modes.y- * @param chart {chart} the chart we are returning items from- * @param e {Event} the event we are find things at- * @param options {IInteractionOptions} options to use- * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned- */- y: function(chart, e, options) {- var position = getRelativePosition(e, chart);- var items = [];- var intersectsItem = false;+ // Body lines may include some extra width due to the color box+ widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;+ helpers$1.each(body, function(bodyItem) {+ helpers$1.each(bodyItem.before, maxLineWidth);+ helpers$1.each(bodyItem.lines, maxLineWidth);+ helpers$1.each(bodyItem.after, maxLineWidth);+ });- parseVisibleItems(chart, function(element) {- if (element.inYRange(position.y)) {- items.push(element);- }+ // Reset back to 0+ widthPadding = 0;- if (element.inRange(position.x, position.y)) {- intersectsItem = true;- }- });+ // Footer width+ ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);+ helpers$1.each(model.footer, maxLineWidth);- // If we want to trigger on an intersect and we don't have any items- // that intersect the position, return nothing- if (options.intersect && !intersectsItem) {- items = [];- }- return items;- }+ // Add padding+ width += 2 * model.xPadding;++ return {+ width: width,+ height: height+ };+}++/**+ * Helper to get the alignment of a tooltip given the size+ */+function determineAlignment(tooltip, size) {+ var model = tooltip._model;+ var chart = tooltip._chart;+ var chartArea = tooltip._chart.chartArea;+ var xAlign = 'center';+ var yAlign = 'center';++ if (model.y < size.height) {+ yAlign = 'top';+ } else if (model.y > (chart.height - size.height)) {+ yAlign = 'bottom';}-};-},{"46":46}],30:[function(require,module,exports){-'use strict';+ var lf, rf; // functions to determine left, right alignment+ var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart+ var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges+ var midX = (chartArea.left + chartArea.right) / 2;+ var midY = (chartArea.top + chartArea.bottom) / 2;++ if (yAlign === 'center') {+ lf = function(x) {+ return x <= midX;+ };+ rf = function(x) {+ return x > midX;+ };+ } else {+ lf = function(x) {+ return x <= (size.width / 2);+ };+ rf = function(x) {+ return x >= (chart.width - (size.width / 2));+ };+ }-var defaults = require(26);+ olf = function(x) {+ return x + size.width + model.caretSize + model.caretPadding > chart.width;+ };+ orf = function(x) {+ return x - size.width - model.caretSize - model.caretPadding < 0;+ };+ yf = function(y) {+ return y <= midY ? 'top' : 'bottom';+ };-defaults._set('global', {- responsive: true,- responsiveAnimationDuration: 0,- maintainAspectRatio: true,- events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],- hover: {- onHover: null,- mode: 'nearest',- intersect: true,- animationDuration: 400- },- onClick: null,- defaultColor: 'rgba(0,0,0,0.1)',- defaultFontColor: '#666',- defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",- defaultFontSize: 12,- defaultFontStyle: 'normal',- showLines: true,+ if (lf(model.x)) {+ xAlign = 'left';- // Element defaults defined in element extensions- elements: {},+ // Is tooltip too wide and goes over the right side of the chart.?+ if (olf(model.x)) {+ xAlign = 'center';+ yAlign = yf(model.y);+ }+ } else if (rf(model.x)) {+ xAlign = 'right';- // Layout options such as padding- layout: {- padding: {- top: 0,- right: 0,- bottom: 0,- left: 0+ // Is tooltip too wide and goes outside left edge of canvas?+ if (orf(model.x)) {+ xAlign = 'center';+ yAlign = yf(model.y);}}-});--module.exports = function() {- // Occupy the global variable of Chart, and create a simple base class- var Chart = function(item, config) {- this.construct(item, config);- return this;+ var opts = tooltip._options;+ return {+ xAlign: opts.xAlign ? opts.xAlign : xAlign,+ yAlign: opts.yAlign ? opts.yAlign : yAlign};+}- Chart.Chart = Chart;+/**+ * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment+ */+function getBackgroundPoint(vm, size, alignment, chart) {+ // Background Position+ var x = vm.x;+ var y = vm.y;- return Chart;-};+ var caretSize = vm.caretSize;+ var caretPadding = vm.caretPadding;+ var cornerRadius = vm.cornerRadius;+ var xAlign = alignment.xAlign;+ var yAlign = alignment.yAlign;+ var paddingAndSize = caretSize + caretPadding;+ var radiusAndPadding = cornerRadius + caretPadding;-},{"26":26}],31:[function(require,module,exports){-'use strict';+ if (xAlign === 'right') {+ x -= size.width;+ } else if (xAlign === 'center') {+ x -= (size.width / 2);+ if (x + size.width > chart.width) {+ x = chart.width - size.width;+ }+ if (x < 0) {+ x = 0;+ }+ }-var helpers = require(46);+ if (yAlign === 'top') {+ y += paddingAndSize;+ } else if (yAlign === 'bottom') {+ y -= size.height + paddingAndSize;+ } else {+ y -= (size.height / 2);+ }-function filterByPosition(array, position) {- return helpers.where(array, function(v) {- return v.position === position;- });+ if (yAlign === 'center') {+ if (xAlign === 'left') {+ x += paddingAndSize;+ } else if (xAlign === 'right') {+ x -= paddingAndSize;+ }+ } else if (xAlign === 'left') {+ x -= radiusAndPadding;+ } else if (xAlign === 'right') {+ x += radiusAndPadding;+ }++ return {+ x: x,+ y: y+ };}-function sortByWeight(array, reverse) {- array.forEach(function(v, i) {- v._tmpIndex_ = i;- return v;- });- array.sort(function(a, b) {- var v0 = reverse ? b : a;- var v1 = reverse ? a : b;- return v0.weight === v1.weight ?- v0._tmpIndex_ - v1._tmpIndex_ :- v0.weight - v1.weight;- });- array.forEach(function(v) {- delete v._tmpIndex_;- });+function getAlignedX(vm, align) {+ return align === 'center'+ ? vm.x + vm.width / 2+ : align === 'right'+ ? vm.x + vm.width - vm.xPadding+ : vm.x + vm.xPadding;}/**- * @interface ILayoutItem- * @prop {String} position - The position of the item in the chart layout. Possible values are- * 'left', 'top', 'right', 'bottom', and 'chartArea'- * @prop {Number} weight - The weight used to sort the item. Higher weights are further away from the chart area- * @prop {Boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down- * @prop {Function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)- * @prop {Function} update - Takes two parameters: width and height. Returns size of item- * @prop {Function} getPadding - Returns an object with padding on the edges- * @prop {Number} width - Width of item. Must be valid after update()- * @prop {Number} height - Height of item. Must be valid after update()- * @prop {Number} left - Left edge of the item. Set by layout system and cannot be used in update- * @prop {Number} top - Top edge of the item. Set by layout system and cannot be used in update- * @prop {Number} right - Right edge of the item. Set by layout system and cannot be used in update- * @prop {Number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update+ * Helper to build before and after body lines*/+function getBeforeAfterBodyLines(callback) {+ return pushOrConcat([], splitNewlines(callback));+}-// The layout service is very self explanatory. It's responsible for the layout within a chart.-// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need-// It is this service's responsibility of carrying out that layout.-module.exports = {- defaults: {},+var exports$4 = core_element.extend({+ initialize: function() {+ this._model = getBaseModel(this._options);+ this._lastActive = [];+ },- /**- * Register a box to a chart.- * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.- * @param {Chart} chart - the chart to use- * @param {ILayoutItem} item - the item to add to be layed out- */- addBox: function(chart, item) {- if (!chart.boxes) {- chart.boxes = [];- }+ // Get the title+ // Args are: (tooltipItem, data)+ getTitle: function() {+ var me = this;+ var opts = me._options;+ var callbacks = opts.callbacks;- // initialize item with default values- item.fullWidth = item.fullWidth || false;- item.position = item.position || 'top';- item.weight = item.weight || 0;+ var beforeTitle = callbacks.beforeTitle.apply(me, arguments);+ var title = callbacks.title.apply(me, arguments);+ var afterTitle = callbacks.afterTitle.apply(me, arguments);- chart.boxes.push(item);+ var lines = [];+ lines = pushOrConcat(lines, splitNewlines(beforeTitle));+ lines = pushOrConcat(lines, splitNewlines(title));+ lines = pushOrConcat(lines, splitNewlines(afterTitle));++ return lines;},- /**- * Remove a layoutItem from a chart- * @param {Chart} chart - the chart to remove the box from- * @param {Object} layoutItem - the item to remove from the layout- */- removeBox: function(chart, layoutItem) {- var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;- if (index !== -1) {- chart.boxes.splice(index, 1);- }+ // Args are: (tooltipItem, data)+ getBeforeBody: function() {+ return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));},- /**- * Sets (or updates) options on the given `item`.- * @param {Chart} chart - the chart in which the item lives (or will be added to)- * @param {Object} item - the item to configure with the given options- * @param {Object} options - the new item options.- */- configure: function(chart, item, options) {- var props = ['fullWidth', 'position', 'weight'];- var ilen = props.length;- var i = 0;- var prop;+ // Args are: (tooltipItem, data)+ getBody: function(tooltipItems, data) {+ var me = this;+ var callbacks = me._options.callbacks;+ var bodyItems = [];++ helpers$1.each(tooltipItems, function(tooltipItem) {+ var bodyItem = {+ before: [],+ lines: [],+ after: []+ };+ pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));+ pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));+ pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));- for (; i < ilen; ++i) {- prop = props[i];- if (options.hasOwnProperty(prop)) {- item[prop] = options[prop];- }- }+ bodyItems.push(bodyItem);+ });++ return bodyItems;},- /**- * Fits boxes of the given chart into the given size by having each box measure itself- * then running a fitting algorithm- * @param {Chart} chart - the chart- * @param {Number} width - the width to fit into- * @param {Number} height - the height to fit into- */- update: function(chart, width, height) {- if (!chart) {- return;- }+ // Args are: (tooltipItem, data)+ getAfterBody: function() {+ return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));+ },- var layoutOptions = chart.options.layout || {};- var padding = helpers.options.toPadding(layoutOptions.padding);- var leftPadding = padding.left;- var rightPadding = padding.right;- var topPadding = padding.top;- var bottomPadding = padding.bottom;-- var leftBoxes = filterByPosition(chart.boxes, 'left');- var rightBoxes = filterByPosition(chart.boxes, 'right');- var topBoxes = filterByPosition(chart.boxes, 'top');- var bottomBoxes = filterByPosition(chart.boxes, 'bottom');- var chartAreaBoxes = filterByPosition(chart.boxes, 'chartArea');-- // Sort boxes by weight. A higher weight is further away from the chart area- sortByWeight(leftBoxes, true);- sortByWeight(rightBoxes, false);- sortByWeight(topBoxes, true);- sortByWeight(bottomBoxes, false);+ // Get the footer and beforeFooter and afterFooter lines+ // Args are: (tooltipItem, data)+ getFooter: function() {+ var me = this;+ var callbacks = me._options.callbacks;- // Essentially we now have any number of boxes on each of the 4 sides.- // Our canvas looks like the following.- // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and- // B1 is the bottom axis- // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays- // These locations are single-box locations only, when trying to register a chartArea location that is already taken,- // an error will be thrown.- //- // |----------------------------------------------------|- // | T1 (Full Width) |- // |----------------------------------------------------|- // | | | T2 | |- // | |----|-------------------------------------|----|- // | | | C1 | | C2 | |- // | | |----| |----| |- // | | | | |- // | L1 | L2 | ChartArea (C0) | R1 |- // | | | | |- // | | |----| |----| |- // | | | C3 | | C4 | |- // | |----|-------------------------------------|----|- // | | | B1 | |- // |----------------------------------------------------|- // | B2 (Full Width) |- // |----------------------------------------------------|- //- // What we do to find the best sizing, we do the following- // 1. Determine the minimum size of the chart area.- // 2. Split the remaining width equally between each vertical axis- // 3. Split the remaining height equally between each horizontal axis- // 4. Give each layout the maximum size it can be. The layout will return it's minimum size- // 5. Adjust the sizes of each axis based on it's minimum reported size.- // 6. Refit each axis- // 7. Position each axis in the final location- // 8. Tell the chart the final location of the chart area- // 9. Tell any axes that overlay the chart area the positions of the chart area-- // Step 1- var chartWidth = width - leftPadding - rightPadding;- var chartHeight = height - topPadding - bottomPadding;- var chartAreaWidth = chartWidth / 2; // min 50%- var chartAreaHeight = chartHeight / 2; // min 50%-- // Step 2- var verticalBoxWidth = (width - chartAreaWidth) / (leftBoxes.length + rightBoxes.length);-- // Step 3- var horizontalBoxHeight = (height - chartAreaHeight) / (topBoxes.length + bottomBoxes.length);-- // Step 4- var maxChartAreaWidth = chartWidth;- var maxChartAreaHeight = chartHeight;- var minBoxSizes = [];-- function getMinimumBoxSize(box) {- var minSize;- var isHorizontal = box.isHorizontal();+ var beforeFooter = callbacks.beforeFooter.apply(me, arguments);+ var footer = callbacks.footer.apply(me, arguments);+ var afterFooter = callbacks.afterFooter.apply(me, arguments);- if (isHorizontal) {- minSize = box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, horizontalBoxHeight);- maxChartAreaHeight -= minSize.height;- } else {- minSize = box.update(verticalBoxWidth, maxChartAreaHeight);- maxChartAreaWidth -= minSize.width;- }+ var lines = [];+ lines = pushOrConcat(lines, splitNewlines(beforeFooter));+ lines = pushOrConcat(lines, splitNewlines(footer));+ lines = pushOrConcat(lines, splitNewlines(afterFooter));- minBoxSizes.push({- horizontal: isHorizontal,- minSize: minSize,- box: box,- });- }+ return lines;+ },- helpers.each(leftBoxes.concat(rightBoxes, topBoxes, bottomBoxes), getMinimumBoxSize);+ update: function(changed) {+ var me = this;+ var opts = me._options;- // If a horizontal box has padding, we move the left boxes over to avoid ugly charts (see issue #2478)- var maxHorizontalLeftPadding = 0;- var maxHorizontalRightPadding = 0;- var maxVerticalTopPadding = 0;- var maxVerticalBottomPadding = 0;+ // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition+ // that does _view = _model if ease === 1. This causes the 2nd tooltip update to set properties in both the view and model at the same time+ // which breaks any animations.+ var existingModel = me._model;+ var model = me._model = getBaseModel(opts);+ var active = me._active;- helpers.each(topBoxes.concat(bottomBoxes), function(horizontalBox) {- if (horizontalBox.getPadding) {- var boxPadding = horizontalBox.getPadding();- maxHorizontalLeftPadding = Math.max(maxHorizontalLeftPadding, boxPadding.left);- maxHorizontalRightPadding = Math.max(maxHorizontalRightPadding, boxPadding.right);- }- });+ var data = me._data;- helpers.each(leftBoxes.concat(rightBoxes), function(verticalBox) {- if (verticalBox.getPadding) {- var boxPadding = verticalBox.getPadding();- maxVerticalTopPadding = Math.max(maxVerticalTopPadding, boxPadding.top);- maxVerticalBottomPadding = Math.max(maxVerticalBottomPadding, boxPadding.bottom);- }- });+ // In the case where active.length === 0 we need to keep these at existing values for good animations+ var alignment = {+ xAlign: existingModel.xAlign,+ yAlign: existingModel.yAlign+ };+ var backgroundPoint = {+ x: existingModel.x,+ y: existingModel.y+ };+ var tooltipSize = {+ width: existingModel.width,+ height: existingModel.height+ };+ var tooltipPosition = {+ x: existingModel.caretX,+ y: existingModel.caretY+ };- // At this point, maxChartAreaHeight and maxChartAreaWidth are the size the chart area could- // be if the axes are drawn at their minimum sizes.- // Steps 5 & 6- var totalLeftBoxesWidth = leftPadding;- var totalRightBoxesWidth = rightPadding;- var totalTopBoxesHeight = topPadding;- var totalBottomBoxesHeight = bottomPadding;-- // Function to fit a box- function fitBox(box) {- var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minBox) {- return minBox.box === box;- });+ var i, len;- if (minBoxSize) {- if (box.isHorizontal()) {- var scaleMargin = {- left: Math.max(totalLeftBoxesWidth, maxHorizontalLeftPadding),- right: Math.max(totalRightBoxesWidth, maxHorizontalRightPadding),- top: 0,- bottom: 0- };+ if (active.length) {+ model.opacity = 1;- // Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends- // on the margin. Sometimes they need to increase in size slightly- box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin);- } else {- box.update(minBoxSize.minSize.width, maxChartAreaHeight);- }- }- }+ var labelColors = [];+ var labelTextColors = [];+ tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);- // Update, and calculate the left and right margins for the horizontal boxes- helpers.each(leftBoxes.concat(rightBoxes), fitBox);+ var tooltipItems = [];+ for (i = 0, len = active.length; i < len; ++i) {+ tooltipItems.push(createTooltipItem(active[i]));+ }- helpers.each(leftBoxes, function(box) {- totalLeftBoxesWidth += box.width;- });+ // If the user provided a filter function, use it to modify the tooltip items+ if (opts.filter) {+ tooltipItems = tooltipItems.filter(function(a) {+ return opts.filter(a, data);+ });+ }- helpers.each(rightBoxes, function(box) {- totalRightBoxesWidth += box.width;- });+ // If the user provided a sorting function, use it to modify the tooltip items+ if (opts.itemSort) {+ tooltipItems = tooltipItems.sort(function(a, b) {+ return opts.itemSort(a, b, data);+ });+ }- // Set the Left and Right margins for the horizontal boxes- helpers.each(topBoxes.concat(bottomBoxes), fitBox);+ // Determine colors for boxes+ helpers$1.each(tooltipItems, function(tooltipItem) {+ labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));+ labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));+ });- // Figure out how much margin is on the top and bottom of the vertical boxes- helpers.each(topBoxes, function(box) {- totalTopBoxesHeight += box.height;- });- helpers.each(bottomBoxes, function(box) {- totalBottomBoxesHeight += box.height;- });+ // Build the Text Lines+ model.title = me.getTitle(tooltipItems, data);+ model.beforeBody = me.getBeforeBody(tooltipItems, data);+ model.body = me.getBody(tooltipItems, data);+ model.afterBody = me.getAfterBody(tooltipItems, data);+ model.footer = me.getFooter(tooltipItems, data);- function finalFitVerticalBox(box) {- var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minSize) {- return minSize.box === box;- });+ // Initial positioning and colors+ model.x = tooltipPosition.x;+ model.y = tooltipPosition.y;+ model.caretPadding = opts.caretPadding;+ model.labelColors = labelColors;+ model.labelTextColors = labelTextColors;- var scaleMargin = {- left: 0,- right: 0,- top: totalTopBoxesHeight,- bottom: totalBottomBoxesHeight- };+ // data points+ model.dataPoints = tooltipItems;- if (minBoxSize) {- box.update(minBoxSize.minSize.width, maxChartAreaHeight, scaleMargin);- }+ // We need to determine alignment of the tooltip+ tooltipSize = getTooltipSize(this, model);+ alignment = determineAlignment(this, tooltipSize);+ // Final Size and Position+ backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);+ } else {+ model.opacity = 0;}- // Let the left layout know the final margin- helpers.each(leftBoxes.concat(rightBoxes), finalFitVerticalBox);+ model.xAlign = alignment.xAlign;+ model.yAlign = alignment.yAlign;+ model.x = backgroundPoint.x;+ model.y = backgroundPoint.y;+ model.width = tooltipSize.width;+ model.height = tooltipSize.height;- // Recalculate because the size of each layout might have changed slightly due to the margins (label rotation for instance)- totalLeftBoxesWidth = leftPadding;- totalRightBoxesWidth = rightPadding;- totalTopBoxesHeight = topPadding;- totalBottomBoxesHeight = bottomPadding;+ // Point where the caret on the tooltip points to+ model.caretX = tooltipPosition.x;+ model.caretY = tooltipPosition.y;- helpers.each(leftBoxes, function(box) {- totalLeftBoxesWidth += box.width;- });+ me._model = model;- helpers.each(rightBoxes, function(box) {- totalRightBoxesWidth += box.width;- });+ if (changed && opts.custom) {+ opts.custom.call(me, model);+ }- helpers.each(topBoxes, function(box) {- totalTopBoxesHeight += box.height;- });- helpers.each(bottomBoxes, function(box) {- totalBottomBoxesHeight += box.height;- });+ return me;+ },- // We may be adding some padding to account for rotated x axis labels- var leftPaddingAddition = Math.max(maxHorizontalLeftPadding - totalLeftBoxesWidth, 0);- totalLeftBoxesWidth += leftPaddingAddition;- totalRightBoxesWidth += Math.max(maxHorizontalRightPadding - totalRightBoxesWidth, 0);+ drawCaret: function(tooltipPoint, size) {+ var ctx = this._chart.ctx;+ var vm = this._view;+ var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);- var topPaddingAddition = Math.max(maxVerticalTopPadding - totalTopBoxesHeight, 0);- totalTopBoxesHeight += topPaddingAddition;- totalBottomBoxesHeight += Math.max(maxVerticalBottomPadding - totalBottomBoxesHeight, 0);+ ctx.lineTo(caretPosition.x1, caretPosition.y1);+ ctx.lineTo(caretPosition.x2, caretPosition.y2);+ ctx.lineTo(caretPosition.x3, caretPosition.y3);+ },+ getCaretPosition: function(tooltipPoint, size, vm) {+ var x1, x2, x3, y1, y2, y3;+ var caretSize = vm.caretSize;+ var cornerRadius = vm.cornerRadius;+ var xAlign = vm.xAlign;+ var yAlign = vm.yAlign;+ var ptX = tooltipPoint.x;+ var ptY = tooltipPoint.y;+ var width = size.width;+ var height = size.height;- // Figure out if our chart area changed. This would occur if the dataset layout label rotation- // changed due to the application of the margins in step 6. Since we can only get bigger, this is safe to do- // without calling `fit` again- var newMaxChartAreaHeight = height - totalTopBoxesHeight - totalBottomBoxesHeight;- var newMaxChartAreaWidth = width - totalLeftBoxesWidth - totalRightBoxesWidth;+ if (yAlign === 'center') {+ y2 = ptY + (height / 2);- if (newMaxChartAreaWidth !== maxChartAreaWidth || newMaxChartAreaHeight !== maxChartAreaHeight) {- helpers.each(leftBoxes, function(box) {- box.height = newMaxChartAreaHeight;- });+ if (xAlign === 'left') {+ x1 = ptX;+ x2 = x1 - caretSize;+ x3 = x1;- helpers.each(rightBoxes, function(box) {- box.height = newMaxChartAreaHeight;- });+ y1 = y2 + caretSize;+ y3 = y2 - caretSize;+ } else {+ x1 = ptX + width;+ x2 = x1 + caretSize;+ x3 = x1;- helpers.each(topBoxes, function(box) {- if (!box.fullWidth) {- box.width = newMaxChartAreaWidth;- }- });+ y1 = y2 - caretSize;+ y3 = y2 + caretSize;+ }+ } else {+ if (xAlign === 'left') {+ x2 = ptX + cornerRadius + (caretSize);+ x1 = x2 - caretSize;+ x3 = x2 + caretSize;+ } else if (xAlign === 'right') {+ x2 = ptX + width - cornerRadius - caretSize;+ x1 = x2 - caretSize;+ x3 = x2 + caretSize;+ } else {+ x2 = vm.caretX;+ x1 = x2 - caretSize;+ x3 = x2 + caretSize;+ }+ if (yAlign === 'top') {+ y1 = ptY;+ y2 = y1 - caretSize;+ y3 = y1;+ } else {+ y1 = ptY + height;+ y2 = y1 + caretSize;+ y3 = y1;+ // invert drawing order+ var tmp = x3;+ x3 = x1;+ x1 = tmp;+ }+ }+ return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};+ },- helpers.each(bottomBoxes, function(box) {- if (!box.fullWidth) {- box.width = newMaxChartAreaWidth;- }- });+ drawTitle: function(pt, vm, ctx) {+ var title = vm.title;+ var length = title.length;+ var titleFontSize, titleSpacing, i;- maxChartAreaHeight = newMaxChartAreaHeight;- maxChartAreaWidth = newMaxChartAreaWidth;- }+ if (length) {+ var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);- // Step 7 - Position the boxes- var left = leftPadding + leftPaddingAddition;- var top = topPadding + topPaddingAddition;+ pt.x = getAlignedX(vm, vm._titleAlign);- function placeBox(box) {- if (box.isHorizontal()) {- box.left = box.fullWidth ? leftPadding : totalLeftBoxesWidth;- box.right = box.fullWidth ? width - rightPadding : totalLeftBoxesWidth + maxChartAreaWidth;- box.top = top;- box.bottom = top + box.height;+ ctx.textAlign = rtlHelper.textAlign(vm._titleAlign);+ ctx.textBaseline = 'middle';- // Move to next point- top = box.bottom;+ titleFontSize = vm.titleFontSize;+ titleSpacing = vm.titleSpacing;- } else {+ ctx.fillStyle = vm.titleFontColor;+ ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);- box.left = left;- box.right = left + box.width;- box.top = totalTopBoxesHeight;- box.bottom = totalTopBoxesHeight + maxChartAreaHeight;+ for (i = 0; i < length; ++i) {+ ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFontSize / 2);+ pt.y += titleFontSize + titleSpacing; // Line Height and spacing- // Move to next point- left = box.right;+ if (i + 1 === length) {+ pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing+ }}}+ },++ drawBody: function(pt, vm, ctx) {+ var bodyFontSize = vm.bodyFontSize;+ var bodySpacing = vm.bodySpacing;+ var bodyAlign = vm._bodyAlign;+ var body = vm.body;+ var drawColorBoxes = vm.displayColors;+ var xLinePadding = 0;+ var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;- helpers.each(leftBoxes.concat(topBoxes), placeBox);+ var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);- // Account for chart width and height- left += maxChartAreaWidth;- top += maxChartAreaHeight;+ var fillLineOfText = function(line) {+ ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyFontSize / 2);+ pt.y += bodyFontSize + bodySpacing;+ };- helpers.each(rightBoxes, placeBox);- helpers.each(bottomBoxes, placeBox);+ var bodyItem, textColor, labelColors, lines, i, j, ilen, jlen;+ var bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);- // Step 8- chart.chartArea = {- left: totalLeftBoxesWidth,- top: totalTopBoxesHeight,- right: totalLeftBoxesWidth + maxChartAreaWidth,- bottom: totalTopBoxesHeight + maxChartAreaHeight- };+ ctx.textAlign = bodyAlign;+ ctx.textBaseline = 'middle';+ ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);- // Step 9- helpers.each(chartAreaBoxes, function(box) {- box.left = chart.chartArea.left;- box.top = chart.chartArea.top;- box.right = chart.chartArea.right;- box.bottom = chart.chartArea.bottom;+ pt.x = getAlignedX(vm, bodyAlignForCalculation);- box.update(maxChartAreaWidth, maxChartAreaHeight);- });- }-};+ // Before body lines+ ctx.fillStyle = vm.bodyFontColor;+ helpers$1.each(vm.beforeBody, fillLineOfText);-},{"46":46}],32:[function(require,module,exports){-'use strict';+ xLinePadding = drawColorBoxes && bodyAlignForCalculation !== 'right'+ ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)+ : 0;-var defaults = require(26);-var helpers = require(46);+ // Draw body lines now+ for (i = 0, ilen = body.length; i < ilen; ++i) {+ bodyItem = body[i];+ textColor = vm.labelTextColors[i];+ labelColors = vm.labelColors[i];-defaults._set('global', {- plugins: {}-});+ ctx.fillStyle = textColor;+ helpers$1.each(bodyItem.before, fillLineOfText);-/**- * The plugin service singleton- * @namespace Chart.plugins- * @since 2.1.0- */-module.exports = {- /**- * Globally registered plugins.- * @private- */- _plugins: [],+ lines = bodyItem.lines;+ for (j = 0, jlen = lines.length; j < jlen; ++j) {+ // Draw Legend-like boxes if needed+ if (drawColorBoxes) {+ var rtlColorX = rtlHelper.x(colorX);- /**- * This identifier is used to invalidate the descriptors cache attached to each chart- * when a global plugin is registered or unregistered. In this case, the cache ID is- * incremented and descriptors are regenerated during following API calls.- * @private- */- _cacheId: 0,+ // Fill a white rect so that colours merge nicely if the opacity is < 1+ ctx.fillStyle = vm.legendColorBackground;+ ctx.fillRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);- /**- * Registers the given plugin(s) if not already registered.- * @param {Array|Object} plugins plugin instance(s).- */- register: function(plugins) {- var p = this._plugins;- ([]).concat(plugins).forEach(function(plugin) {- if (p.indexOf(plugin) === -1) {- p.push(plugin);- }- });+ // Border+ ctx.lineWidth = 1;+ ctx.strokeStyle = labelColors.borderColor;+ ctx.strokeRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);- this._cacheId++;- },+ // Inner square+ ctx.fillStyle = labelColors.backgroundColor;+ ctx.fillRect(rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), bodyFontSize - 2), pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);+ ctx.fillStyle = textColor;+ }- /**- * Unregisters the given plugin(s) only if registered.- * @param {Array|Object} plugins plugin instance(s).- */- unregister: function(plugins) {- var p = this._plugins;- ([]).concat(plugins).forEach(function(plugin) {- var idx = p.indexOf(plugin);- if (idx !== -1) {- p.splice(idx, 1);+ fillLineOfText(lines[j]);}- });- this._cacheId++;- },+ helpers$1.each(bodyItem.after, fillLineOfText);+ }- /**- * Remove all registered plugins.- * @since 2.1.5- */- clear: function() {- this._plugins = [];- this._cacheId++;- },+ // Reset back to 0 for after body+ xLinePadding = 0;- /**- * Returns the number of registered plugins?- * @returns {Number}- * @since 2.1.5- */- count: function() {- return this._plugins.length;+ // After body lines+ helpers$1.each(vm.afterBody, fillLineOfText);+ pt.y -= bodySpacing; // Remove last body spacing},- /**- * Returns all registered plugin instances.- * @returns {Array} array of plugin objects.- * @since 2.1.5- */- getAll: function() {- return this._plugins;- },+ drawFooter: function(pt, vm, ctx) {+ var footer = vm.footer;+ var length = footer.length;+ var footerFontSize, i;- /**- * Calls enabled plugins for `chart` on the specified hook and with the given args.- * This method immediately returns as soon as a plugin explicitly returns false. The- * returned value can be used, for instance, to interrupt the current action.- * @param {Object} chart - The chart instance for which plugins should be called.- * @param {String} hook - The name of the plugin method to call (e.g. 'beforeUpdate').- * @param {Array} [args] - Extra arguments to apply to the hook call.- * @returns {Boolean} false if any of the plugins return false, else returns true.- */- notify: function(chart, hook, args) {- var descriptors = this.descriptors(chart);- var ilen = descriptors.length;- var i, descriptor, plugin, params, method;+ if (length) {+ var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);- for (i = 0; i < ilen; ++i) {- descriptor = descriptors[i];- plugin = descriptor.plugin;- method = plugin[hook];- if (typeof method === 'function') {- params = [chart].concat(args || []);- params.push(descriptor.options);- if (method.apply(plugin, params) === false) {- return false;- }- }- }+ pt.x = getAlignedX(vm, vm._footerAlign);+ pt.y += vm.footerMarginTop;- return true;- },+ ctx.textAlign = rtlHelper.textAlign(vm._footerAlign);+ ctx.textBaseline = 'middle';- /**- * Returns descriptors of enabled plugins for the given chart.- * @returns {Array} [{ plugin, options }]- * @private- */- descriptors: function(chart) {- var cache = chart.$plugins || (chart.$plugins = {});- if (cache.id === this._cacheId) {- return cache.descriptors;- }+ footerFontSize = vm.footerFontSize;- var plugins = [];- var descriptors = [];- var config = (chart && chart.config) || {};- var options = (config.options && config.options.plugins) || {};+ ctx.fillStyle = vm.footerFontColor;+ ctx.font = helpers$1.fontString(footerFontSize, vm._footerFontStyle, vm._footerFontFamily);- this._plugins.concat(config.plugins || []).forEach(function(plugin) {- var idx = plugins.indexOf(plugin);- if (idx !== -1) {- return;+ for (i = 0; i < length; ++i) {+ ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFontSize / 2);+ pt.y += footerFontSize + vm.footerSpacing;}+ }+ },- var id = plugin.id;- var opts = options[id];- if (opts === false) {- return;- }+ drawBackground: function(pt, vm, ctx, tooltipSize) {+ ctx.fillStyle = vm.backgroundColor;+ ctx.strokeStyle = vm.borderColor;+ ctx.lineWidth = vm.borderWidth;+ var xAlign = vm.xAlign;+ var yAlign = vm.yAlign;+ var x = pt.x;+ var y = pt.y;+ var width = tooltipSize.width;+ var height = tooltipSize.height;+ var radius = vm.cornerRadius;- if (opts === true) {- opts = helpers.clone(defaults.global.plugins[id]);- }+ ctx.beginPath();+ ctx.moveTo(x + radius, y);+ if (yAlign === 'top') {+ this.drawCaret(pt, tooltipSize);+ }+ ctx.lineTo(x + width - radius, y);+ ctx.quadraticCurveTo(x + width, y, x + width, y + radius);+ if (yAlign === 'center' && xAlign === 'right') {+ this.drawCaret(pt, tooltipSize);+ }+ ctx.lineTo(x + width, y + height - radius);+ ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);+ if (yAlign === 'bottom') {+ this.drawCaret(pt, tooltipSize);+ }+ ctx.lineTo(x + radius, y + height);+ ctx.quadraticCurveTo(x, y + height, x, y + height - radius);+ if (yAlign === 'center' && xAlign === 'left') {+ this.drawCaret(pt, tooltipSize);+ }+ ctx.lineTo(x, y + radius);+ ctx.quadraticCurveTo(x, y, x + radius, y);+ ctx.closePath();- plugins.push(plugin);- descriptors.push({- plugin: plugin,- options: opts || {}- });- });+ ctx.fill();- cache.descriptors = descriptors;- cache.id = this._cacheId;- return descriptors;+ if (vm.borderWidth > 0) {+ ctx.stroke();+ }},- /**- * Invalidates cache for the given chart: descriptors hold a reference on plugin option,- * but in some cases, this reference can be changed by the user when updating options.- * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167- * @private- */- _invalidate: function(chart) {- delete chart.$plugins;- }-};--/**- * Plugin extension hooks.- * @interface IPlugin- * @since 2.1.0- */-/**- * @method IPlugin#beforeInit- * @desc Called before initializing `chart`.- * @param {Chart.Controller} chart - The chart instance.- * @param {Object} options - The plugin options.- */-/**- * @method IPlugin#afterInit- * @desc Called after `chart` has been initialized and before the first update.- * @param {Chart.Controller} chart - The chart instance.- * @param {Object} options - The plugin options.- */-/**- * @method IPlugin#beforeUpdate- * @desc Called before updating `chart`. If any plugin returns `false`, the update- * is cancelled (and thus subsequent render(s)) until another `update` is triggered.- * @param {Chart.Controller} chart - The chart instance.- * @param {Object} options - The plugin options.- * @returns {Boolean} `false` to cancel the chart update.- */-/**- * @method IPlugin#afterUpdate- * @desc Called after `chart` has been updated and before rendering. Note that this- * hook will not be called if the chart update has been previously cancelled.- * @param {Chart.Controller} chart - The chart instance.- * @param {Object} options - The plugin options.- */-/**- * @method IPlugin#beforeDatasetsUpdate- * @desc Called before updating the `chart` datasets. If any plugin returns `false`,- * the datasets update is cancelled until another `update` is triggered.- * @param {Chart.Controller} chart - The chart instance.- * @param {Object} options - The plugin options.- * @returns {Boolean} false to cancel the datasets update.- * @since version 2.1.5-*/-/**- * @method IPlugin#afterDatasetsUpdate- * @desc Called after the `chart` datasets have been updated. Note that this hook- * will not be called if the datasets update has been previously cancelled.- * @param {Chart.Controller} chart - The chart instance.- * @param {Object} options - The plugin options.- * @since version 2.1.5- */-/**- * @method IPlugin#beforeDatasetUpdate- * @desc Called before updating the `chart` dataset at the given `args.index`. If any plugin- * returns `false`, the datasets update is cancelled until another `update` is triggered.- * @param {Chart} chart - The chart instance.- * @param {Object} args - The call arguments.- * @param {Number} args.index - The dataset index.- * @param {Object} args.meta - The dataset metadata.- * @param {Object} options - The plugin options.- * @returns {Boolean} `false` to cancel the chart datasets drawing.- */-/**- * @method IPlugin#afterDatasetUpdate- * @desc Called after the `chart` datasets at the given `args.index` has been updated. Note- * that this hook will not be called if the datasets update has been previously cancelled.- * @param {Chart} chart - The chart instance.- * @param {Object} args - The call arguments.- * @param {Number} args.index - The dataset index.- * @param {Object} args.meta - The dataset metadata.- * @param {Object} options - The plugin options.- */-/**- * @method IPlugin#beforeLayout- * @desc Called before laying out `chart`. If any plugin returns `false`,- * the layout update is cancelled until another `update` is triggered.- * @param {Chart.Controller} chart - The chart instance.- * @param {Object} options - The plugin options.- * @returns {Boolean} `false` to cancel the chart layout.- */-/**- * @method IPlugin#afterLayout- * @desc Called after the `chart` has been layed out. Note that this hook will not- * be called if the layout update has been previously cancelled.- * @param {Chart.Controller} chart - The chart instance.- * @param {Object} options - The plugin options.- */-/**- * @method IPlugin#beforeRender- * @desc Called before rendering `chart`. If any plugin returns `false`,- * the rendering is cancelled until another `render` is triggered.- * @param {Chart.Controller} chart - The chart instance.- * @param {Object} options - The plugin options.- * @returns {Boolean} `false` to cancel the chart rendering.- */-/**- * @method IPlugin#afterRender- * @desc Called after the `chart` has been fully rendered (and animation completed). Note- * that this hook will not be called if the rendering has been previously cancelled.- * @param {Chart.Controller} chart - The chart instance.- * @param {Object} options - The plugin options.- */-/**- * @method IPlugin#beforeDraw- * @desc Called before drawing `chart` at every animation frame specified by the given- * easing value. If any plugin returns `false`, the frame drawing is cancelled until- * another `render` is triggered.- * @param {Chart.Controller} chart - The chart instance.- * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.- * @param {Object} options - The plugin options.- * @returns {Boolean} `false` to cancel the chart drawing.- */-/**- * @method IPlugin#afterDraw- * @desc Called after the `chart` has been drawn for the specific easing value. Note- * that this hook will not be called if the drawing has been previously cancelled.- * @param {Chart.Controller} chart - The chart instance.- * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.- * @param {Object} options - The plugin options.- */-/**- * @method IPlugin#beforeDatasetsDraw- * @desc Called before drawing the `chart` datasets. If any plugin returns `false`,- * the datasets drawing is cancelled until another `render` is triggered.- * @param {Chart.Controller} chart - The chart instance.- * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.- * @param {Object} options - The plugin options.- * @returns {Boolean} `false` to cancel the chart datasets drawing.- */-/**- * @method IPlugin#afterDatasetsDraw- * @desc Called after the `chart` datasets have been drawn. Note that this hook- * will not be called if the datasets drawing has been previously cancelled.- * @param {Chart.Controller} chart - The chart instance.- * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.- * @param {Object} options - The plugin options.- */-/**- * @method IPlugin#beforeDatasetDraw- * @desc Called before drawing the `chart` dataset at the given `args.index` (datasets- * are drawn in the reverse order). If any plugin returns `false`, the datasets drawing- * is cancelled until another `render` is triggered.- * @param {Chart} chart - The chart instance.- * @param {Object} args - The call arguments.- * @param {Number} args.index - The dataset index.- * @param {Object} args.meta - The dataset metadata.- * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.- * @param {Object} options - The plugin options.- * @returns {Boolean} `false` to cancel the chart datasets drawing.- */-/**- * @method IPlugin#afterDatasetDraw- * @desc Called after the `chart` datasets at the given `args.index` have been drawn- * (datasets are drawn in the reverse order). Note that this hook will not be called- * if the datasets drawing has been previously cancelled.- * @param {Chart} chart - The chart instance.- * @param {Object} args - The call arguments.- * @param {Number} args.index - The dataset index.- * @param {Object} args.meta - The dataset metadata.- * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.- * @param {Object} options - The plugin options.- */-/**- * @method IPlugin#beforeTooltipDraw- * @desc Called before drawing the `tooltip`. If any plugin returns `false`,- * the tooltip drawing is cancelled until another `render` is triggered.- * @param {Chart} chart - The chart instance.- * @param {Object} args - The call arguments.- * @param {Object} args.tooltip - The tooltip.- * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.- * @param {Object} options - The plugin options.- * @returns {Boolean} `false` to cancel the chart tooltip drawing.- */-/**- * @method IPlugin#afterTooltipDraw- * @desc Called after drawing the `tooltip`. Note that this hook will not- * be called if the tooltip drawing has been previously cancelled.- * @param {Chart} chart - The chart instance.- * @param {Object} args - The call arguments.- * @param {Object} args.tooltip - The tooltip.- * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.- * @param {Object} options - The plugin options.- */-/**- * @method IPlugin#beforeEvent- * @desc Called before processing the specified `event`. If any plugin returns `false`,- * the event will be discarded.- * @param {Chart.Controller} chart - The chart instance.- * @param {IEvent} event - The event object.- * @param {Object} options - The plugin options.- */-/**- * @method IPlugin#afterEvent- * @desc Called after the `event` has been consumed. Note that this hook- * will not be called if the `event` has been previously discarded.- * @param {Chart.Controller} chart - The chart instance.- * @param {IEvent} event - The event object.- * @param {Object} options - The plugin options.- */-/**- * @method IPlugin#resize- * @desc Called after the chart as been resized.- * @param {Chart.Controller} chart - The chart instance.- * @param {Number} size - The new canvas display size (eq. canvas.style width & height).- * @param {Object} options - The plugin options.- */-/**- * @method IPlugin#destroy- * @desc Called after the chart as been destroyed.- * @param {Chart.Controller} chart - The chart instance.- * @param {Object} options - The plugin options.- */+ draw: function() {+ var ctx = this._chart.ctx;+ var vm = this._view;-},{"26":26,"46":46}],33:[function(require,module,exports){-'use strict';+ if (vm.opacity === 0) {+ return;+ }-var defaults = require(26);-var Element = require(27);-var helpers = require(46);-var Ticks = require(35);+ var tooltipSize = {+ width: vm.width,+ height: vm.height+ };+ var pt = {+ x: vm.x,+ y: vm.y+ };-defaults._set('scale', {- display: true,- position: 'left',- offset: false,+ // IE11/Edge does not like very small opacities, so snap to 0+ var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;- // grid line settings- gridLines: {- display: true,- color: 'rgba(0, 0, 0, 0.1)',- lineWidth: 1,- drawBorder: true,- drawOnChartArea: true,- drawTicks: true,- tickMarkLength: 10,- zeroLineWidth: 1,- zeroLineColor: 'rgba(0,0,0,0.25)',- zeroLineBorderDash: [],- zeroLineBorderDashOffset: 0.0,- offsetGridLines: false,- borderDash: [],- borderDashOffset: 0.0- },+ // Truthy/falsey value for empty tooltip+ var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;- // scale label- scaleLabel: {- // display property- display: false,+ if (this._options.enabled && hasTooltipContent) {+ ctx.save();+ ctx.globalAlpha = opacity;- // actual label- labelString: '',+ // Draw Background+ this.drawBackground(pt, vm, ctx, tooltipSize);- // line height- lineHeight: 1.2,+ // Draw Title, Body, and Footer+ pt.y += vm.yPadding;- // top/bottom padding- padding: {- top: 4,- bottom: 4+ helpers$1.rtl.overrideTextDirection(ctx, vm.textDirection);++ // Titles+ this.drawTitle(pt, vm, ctx);++ // Body+ this.drawBody(pt, vm, ctx);++ // Footer+ this.drawFooter(pt, vm, ctx);++ helpers$1.rtl.restoreTextDirection(ctx, vm.textDirection);++ ctx.restore();}},- // label settings- ticks: {- beginAtZero: false,- minRotation: 0,- maxRotation: 50,- mirror: false,- padding: 0,- reverse: false,- display: true,- autoSkip: true,- autoSkipPadding: 0,- labelOffset: 0,- // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.- callback: Ticks.formatters.values,- minor: {},- major: {}- }-});+ /**+ * Handle an event+ * @private+ * @param {IEvent} event - The event to handle+ * @returns {boolean} true if the tooltip changed+ */+ handleEvent: function(e) {+ var me = this;+ var options = me._options;+ var changed = false;-function labelsFromTicks(ticks) {- var labels = [];- var i, ilen;+ me._lastActive = me._lastActive || [];- for (i = 0, ilen = ticks.length; i < ilen; ++i) {- labels.push(ticks[i].label);- }+ // Find Active Elements for tooltips+ if (e.type === 'mouseout') {+ me._active = [];+ } else {+ me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);+ if (options.reverse) {+ me._active.reverse();+ }+ }- return labels;-}+ // Remember Last Actives+ changed = !helpers$1.arrayEquals(me._active, me._lastActive);-function getLineValue(scale, index, offsetGridLines) {- var lineValue = scale.getPixelForTick(index);+ // Only handle target event on tooltip change+ if (changed) {+ me._lastActive = me._active;- if (offsetGridLines) {- if (index === 0) {- lineValue -= (scale.getPixelForTick(1) - lineValue) / 2;- } else {- lineValue -= (lineValue - scale.getPixelForTick(index - 1)) / 2;+ if (options.enabled || options.custom) {+ me._eventPosition = {+ x: e.x,+ y: e.y+ };++ me.update(true);+ me.pivot();+ }}- }- return lineValue;-}-function computeTextSize(context, tick, font) {- return helpers.isArray(tick) ?- helpers.longestText(context, font, tick) :- context.measureText(tick).width;-}+ return changed;+ }+});-function parseFontOptions(options) {- var valueOrDefault = helpers.valueOrDefault;- var globalDefaults = defaults.global;- var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);- var style = valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle);- var family = valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily);+/**+ * @namespace Chart.Tooltip.positioners+ */+var positioners_1 = positioners;- return {- size: size,- style: style,- family: family,- font: helpers.fontString(size, style, family)- };-}+var core_tooltip = exports$4;+core_tooltip.positioners = positioners_1;-function parseLineHeight(options) {- return helpers.options.toLineHeight(- helpers.valueOrDefault(options.lineHeight, 1.2),- helpers.valueOrDefault(options.fontSize, defaults.global.defaultFontSize));-}+var valueOrDefault$9 = helpers$1.valueOrDefault;-module.exports = Element.extend({- /**- * Get the padding needed for the scale- * @method getPadding- * @private- * @returns {Padding} the necessary padding- */- getPadding: function() {- var me = this;- return {- left: me.paddingLeft || 0,- top: me.paddingTop || 0,- right: me.paddingRight || 0,- bottom: me.paddingBottom || 0- };+core_defaults._set('global', {+ elements: {},+ events: [+ 'mousemove',+ 'mouseout',+ 'click',+ 'touchstart',+ 'touchmove'+ ],+ hover: {+ onHover: null,+ mode: 'nearest',+ intersect: true,+ animationDuration: 400},+ onClick: null,+ maintainAspectRatio: true,+ responsive: true,+ responsiveAnimationDuration: 0+});- /**- * Returns the scale tick objects ({label, major})- * @since 2.7- */- getTicks: function() {- return this._ticks;- },+/**+ * Recursively merge the given config objects representing the `scales` option+ * by incorporating scale defaults in `xAxes` and `yAxes` array items, then+ * returns a deep copy of the result, thus doesn't alter inputs.+ */+function mergeScaleConfig(/* config objects ... */) {+ return helpers$1.merge({}, [].slice.call(arguments), {+ merger: function(key, target, source, options) {+ if (key === 'xAxes' || key === 'yAxes') {+ var slen = source[key].length;+ var i, type, scale;++ if (!target[key]) {+ target[key] = [];+ }- // These methods are ordered by lifecyle. Utilities then follow.- // Any function defined here is inherited by all scale types.- // Any function can be extended by the scale type+ for (i = 0; i < slen; ++i) {+ scale = source[key][i];+ type = valueOrDefault$9(scale.type, key === 'xAxes' ? 'category' : 'linear');- mergeTicksOptions: function() {- var ticks = this.options.ticks;- if (ticks.minor === false) {- ticks.minor = {- display: false- };- }- if (ticks.major === false) {- ticks.major = {- display: false- };- }- for (var key in ticks) {- if (key !== 'major' && key !== 'minor') {- if (typeof ticks.minor[key] === 'undefined') {- ticks.minor[key] = ticks[key];- }- if (typeof ticks.major[key] === 'undefined') {- ticks.major[key] = ticks[key];+ if (i >= target[key].length) {+ target[key].push({});+ }++ if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {+ // new/untyped scale or type changed: let's apply the new defaults+ // then merge source scale to correctly overwrite the defaults.+ helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);+ } else {+ // scales type are the same+ helpers$1.merge(target[key][i], scale);+ }}+ } else {+ helpers$1._merger(key, target, source, options);}}- },- beforeUpdate: function() {- helpers.callback(this.options.beforeUpdate, [this]);- },+ });+}- update: function(maxWidth, maxHeight, margins) {- var me = this;- var i, ilen, labels, label, ticks, tick;+/**+ * Recursively merge the given config objects as the root options by handling+ * default scale options for the `scales` and `scale` properties, then returns+ * a deep copy of the result, thus doesn't alter inputs.+ */+function mergeConfig(/* config objects ... */) {+ return helpers$1.merge({}, [].slice.call(arguments), {+ merger: function(key, target, source, options) {+ var tval = target[key] || {};+ var sval = source[key];++ if (key === 'scales') {+ // scale config merging is complex. Add our own function here for that+ target[key] = mergeScaleConfig(tval, sval);+ } else if (key === 'scale') {+ // used in polar area & radar charts since there is only one scale+ target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]);+ } else {+ helpers$1._merger(key, target, source, options);+ }+ }+ });+}- // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)- me.beforeUpdate();+function initConfig(config) {+ config = config || {};- // Absorb the master measurements- me.maxWidth = maxWidth;- me.maxHeight = maxHeight;- me.margins = helpers.extend({- left: 0,- right: 0,- top: 0,- bottom: 0- }, margins);- me.longestTextCache = me.longestTextCache || {};+ // Do NOT use mergeConfig for the data object because this method merges arrays+ // and so would change references to labels and datasets, preventing data updates.+ var data = config.data = config.data || {};+ data.datasets = data.datasets || [];+ data.labels = data.labels || [];- // Dimensions- me.beforeSetDimensions();- me.setDimensions();- me.afterSetDimensions();+ config.options = mergeConfig(+ core_defaults.global,+ core_defaults[config.type],+ config.options || {});- // Data min/max- me.beforeDataLimits();- me.determineDataLimits();- me.afterDataLimits();+ return config;+}- // Ticks - `this.ticks` is now DEPRECATED!- // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member- // and must not be accessed directly from outside this class. `this.ticks` being- // around for long time and not marked as private, we can't change its structure- // without unexpected breaking changes. If you need to access the scale ticks,- // use scale.getTicks() instead.+function updateConfig(chart) {+ var newOptions = chart.options;- me.beforeBuildTicks();+ helpers$1.each(chart.scales, function(scale) {+ core_layouts.removeBox(chart, scale);+ });- // New implementations should return an array of objects but for BACKWARD COMPAT,- // we still support no return (`this.ticks` internally set by calling this method).- ticks = me.buildTicks() || [];+ newOptions = mergeConfig(+ core_defaults.global,+ core_defaults[chart.config.type],+ newOptions);- me.afterBuildTicks();+ chart.options = chart.config.options = newOptions;+ chart.ensureScalesHaveIDs();+ chart.buildOrUpdateScales();- me.beforeTickToLabelConversion();+ // Tooltip+ chart.tooltip._options = newOptions.tooltips;+ chart.tooltip.initialize();+}- // New implementations should return the formatted tick labels but for BACKWARD- // COMPAT, we still support no return (`this.ticks` internally changed by calling- // this method and supposed to contain only string values).- labels = me.convertTicksToLabels(ticks) || me.ticks;+function nextAvailableScaleId(axesOpts, prefix, index) {+ var id;+ var hasId = function(obj) {+ return obj.id === id;+ };- me.afterTickToLabelConversion();+ do {+ id = prefix + index++;+ } while (helpers$1.findIndex(axesOpts, hasId) >= 0);- me.ticks = labels; // BACKWARD COMPATIBILITY+ return id;+}- // IMPORTANT: from this point, we consider that `this.ticks` will NEVER change!+function positionIsHorizontal(position) {+ return position === 'top' || position === 'bottom';+}- // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)- for (i = 0, ilen = labels.length; i < ilen; ++i) {- label = labels[i];- tick = ticks[i];- if (!tick) {- ticks.push(tick = {- label: label,- major: false- });- } else {- tick.label = label;- }- }+function compare2Level(l1, l2) {+ return function(a, b) {+ return a[l1] === b[l1]+ ? a[l2] - b[l2]+ : a[l1] - b[l1];+ };+}- me._ticks = ticks;+var Chart = function(item, config) {+ this.construct(item, config);+ return this;+};- // Tick Rotation- me.beforeCalculateTickRotation();- me.calculateTickRotation();- me.afterCalculateTickRotation();- // Fit- me.beforeFit();- me.fit();- me.afterFit();- //- me.afterUpdate();+helpers$1.extend(Chart.prototype, /** @lends Chart */ {+ /**+ * @private+ */+ construct: function(item, config) {+ var me = this;- return me.minSize;+ config = initConfig(config);- },- afterUpdate: function() {- helpers.callback(this.options.afterUpdate, [this]);- },+ var context = platform.acquireContext(item, config);+ var canvas = context && context.canvas;+ var height = canvas && canvas.height;+ var width = canvas && canvas.width;- //+ me.id = helpers$1.uid();+ me.ctx = context;+ me.canvas = canvas;+ me.config = config;+ me.width = width;+ me.height = height;+ me.aspectRatio = height ? width / height : null;+ me.options = config.options;+ me._bufferedRender = false;+ me._layers = [];- beforeSetDimensions: function() {- helpers.callback(this.options.beforeSetDimensions, [this]);+ /**+ * Provided for backward compatibility, Chart and Chart.Controller have been merged,+ * the "instance" still need to be defined since it might be called from plugins.+ * @prop Chart#chart+ * @deprecated since version 2.6.0+ * @todo remove at version 3+ * @private+ */+ me.chart = me;+ me.controller = me; // chart.chart.controller #inception++ // Add the chart instance to the global namespace+ Chart.instances[me.id] = me;++ // Define alias to the config data: `chart.data === chart.config.data`+ Object.defineProperty(me, 'data', {+ get: function() {+ return me.config.data;+ },+ set: function(value) {+ me.config.data = value;+ }+ });++ if (!context || !canvas) {+ // The given item is not a compatible context2d element, let's return before finalizing+ // the chart initialization but after setting basic chart / controller properties that+ // can help to figure out that the chart is not valid (e.g chart.canvas !== null);+ // https://github.com/chartjs/Chart.js/issues/2807+ console.error("Failed to create chart: can't acquire context from the given item");+ return;+ }++ me.initialize();+ me.update();},- setDimensions: function() {++ /**+ * @private+ */+ initialize: 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;+ // Before init plugin notification+ core_plugins.notify(me, 'beforeInit');++ helpers$1.retinaScale(me, me.options.devicePixelRatio);++ me.bindEvents();++ if (me.options.responsive) {+ // Initial resize before chart draws (must be silent to preserve initial animations).+ me.resize(true);}- // Reset padding- me.paddingLeft = 0;- me.paddingTop = 0;- me.paddingRight = 0;- me.paddingBottom = 0;- },- afterSetDimensions: function() {- helpers.callback(this.options.afterSetDimensions, [this]);- },+ me.initToolTip();- // Data limits- beforeDataLimits: function() {- helpers.callback(this.options.beforeDataLimits, [this]);- },- determineDataLimits: helpers.noop,- afterDataLimits: function() {- helpers.callback(this.options.afterDataLimits, [this]);- },+ // After init plugin notification+ core_plugins.notify(me, 'afterInit');- //- beforeBuildTicks: function() {- helpers.callback(this.options.beforeBuildTicks, [this]);- },- buildTicks: helpers.noop,- afterBuildTicks: function() {- helpers.callback(this.options.afterBuildTicks, [this]);+ return me;},- beforeTickToLabelConversion: function() {- helpers.callback(this.options.beforeTickToLabelConversion, [this]);- },- convertTicksToLabels: function() {- var me = this;- // Convert ticks to strings- var tickOpts = me.options.ticks;- me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);- },- afterTickToLabelConversion: function() {- helpers.callback(this.options.afterTickToLabelConversion, [this]);+ clear: function() {+ helpers$1.canvas.clear(this);+ return this;},- //-- beforeCalculateTickRotation: function() {- helpers.callback(this.options.beforeCalculateTickRotation, [this]);+ stop: function() {+ // Stops any current animation loop occurring+ core_animations.cancelAnimation(this);+ return this;},- calculateTickRotation: function() {++ resize: function(silent) {var me = this;- var context = me.ctx;- var tickOpts = me.options.ticks;- var labels = labelsFromTicks(me._ticks);+ var options = me.options;+ var canvas = me.canvas;+ var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;- // Get the width of each grid by calculating the difference- // between x offsets between 0 and 1.- var tickFont = parseFontOptions(tickOpts);- context.font = tickFont.font;+ // the canvas render width and height will be casted to integers so make sure that+ // the canvas display style uses the same integer values to avoid blurring effect.- var labelRotation = tickOpts.minRotation || 0;+ // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed+ var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas)));+ var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas)));- if (labels.length && me.options.display && me.isHorizontal()) {- var originalLabelWidth = helpers.longestText(context, tickFont.font, labels, me.longestTextCache);- var labelWidth = originalLabelWidth;- var cosRotation, sinRotation;+ if (me.width === newWidth && me.height === newHeight) {+ return;+ }- // Allow 3 pixels x2 padding either side for label readability- var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6;+ canvas.width = me.width = newWidth;+ canvas.height = me.height = newHeight;+ canvas.style.width = newWidth + 'px';+ canvas.style.height = newHeight + 'px';- // Max label rotation can be set or default to 90 - also act as a loop counter- while (labelWidth > tickWidth && labelRotation < tickOpts.maxRotation) {- var angleRadians = helpers.toRadians(labelRotation);- cosRotation = Math.cos(angleRadians);- sinRotation = Math.sin(angleRadians);+ helpers$1.retinaScale(me, options.devicePixelRatio);- if (sinRotation * originalLabelWidth > me.maxHeight) {- // go back one step- labelRotation--;- break;- }+ if (!silent) {+ // Notify any plugins about the resize+ var newSize = {width: newWidth, height: newHeight};+ core_plugins.notify(me, 'resize', [newSize]);- labelRotation++;- labelWidth = cosRotation * originalLabelWidth;+ // Notify of resize+ if (options.onResize) {+ options.onResize(me, newSize);}- }-- me.labelRotation = labelRotation;- },- afterCalculateTickRotation: function() {- helpers.callback(this.options.afterCalculateTickRotation, [this]);- },-- //- beforeFit: function() {- helpers.callback(this.options.beforeFit, [this]);+ me.stop();+ me.update({+ duration: options.responsiveAnimationDuration+ });+ }},- fit: function() {- var me = this;- // Reset- var minSize = me.minSize = {- width: 0,- height: 0- };- var labels = labelsFromTicks(me._ticks);+ ensureScalesHaveIDs: function() {+ var options = this.options;+ var scalesOptions = options.scales || {};+ var scaleOptions = options.scale;- var opts = me.options;- var tickOpts = opts.ticks;- var scaleLabelOpts = opts.scaleLabel;- var gridLineOpts = opts.gridLines;- var display = opts.display;- var isHorizontal = me.isHorizontal();+ helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) {+ if (!xAxisOptions.id) {+ xAxisOptions.id = nextAvailableScaleId(scalesOptions.xAxes, 'x-axis-', index);+ }+ });- var tickFont = parseFontOptions(tickOpts);- var tickMarkLength = opts.gridLines.tickMarkLength;+ helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) {+ if (!yAxisOptions.id) {+ yAxisOptions.id = nextAvailableScaleId(scalesOptions.yAxes, 'y-axis-', index);+ }+ });- // Width- if (isHorizontal) {- // subtract the margins to line up with the chartArea if we are a full width scale- minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth;- } else {- minSize.width = display && gridLineOpts.drawTicks ? tickMarkLength : 0;+ if (scaleOptions) {+ scaleOptions.id = scaleOptions.id || 'scale';}+ },- // height- if (isHorizontal) {- minSize.height = display && gridLineOpts.drawTicks ? tickMarkLength : 0;- } else {- minSize.height = me.maxHeight; // fill all the height+ /**+ * Builds a map of scale ID to scale object for future lookup.+ */+ buildOrUpdateScales: function() {+ var me = this;+ var options = me.options;+ var scales = me.scales || {};+ var items = [];+ var updated = Object.keys(scales).reduce(function(obj, id) {+ obj[id] = false;+ return obj;+ }, {});++ if (options.scales) {+ items = items.concat(+ (options.scales.xAxes || []).map(function(xAxisOptions) {+ return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};+ }),+ (options.scales.yAxes || []).map(function(yAxisOptions) {+ return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};+ })+ );+ }++ if (options.scale) {+ items.push({+ options: options.scale,+ dtype: 'radialLinear',+ isDefault: true,+ dposition: 'chartArea'+ });}- // Are we showing a title for the scale?- if (scaleLabelOpts.display && display) {- var scaleLabelLineHeight = parseLineHeight(scaleLabelOpts);- var scaleLabelPadding = helpers.options.toPadding(scaleLabelOpts.padding);- var deltaHeight = scaleLabelLineHeight + scaleLabelPadding.height;+ helpers$1.each(items, function(item) {+ var scaleOptions = item.options;+ var id = scaleOptions.id;+ var scaleType = valueOrDefault$9(scaleOptions.type, item.dtype);- if (isHorizontal) {- minSize.height += deltaHeight;+ if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {+ scaleOptions.position = item.dposition;+ }++ updated[id] = true;+ var scale = null;+ if (id in scales && scales[id].type === scaleType) {+ scale = scales[id];+ scale.options = scaleOptions;+ scale.ctx = me.ctx;+ scale.chart = me;} else {- minSize.width += deltaHeight;+ var scaleClass = core_scaleService.getScaleConstructor(scaleType);+ if (!scaleClass) {+ return;+ }+ scale = new scaleClass({+ id: id,+ type: scaleType,+ options: scaleOptions,+ ctx: me.ctx,+ chart: me+ });+ scales[scale.id] = scale;}- }- // Don't bother fitting the ticks if we are not showing them- if (tickOpts.display && display) {- var largestTextWidth = helpers.longestText(me.ctx, tickFont.font, labels, me.longestTextCache);- var tallestLabelHeightInLines = helpers.numberOfLabelLines(labels);- var lineSpace = tickFont.size * 0.5;- var tickPadding = me.options.ticks.padding;+ scale.mergeTicksOptions();- if (isHorizontal) {- // A horizontal axis is more constrained by the height.- me.longestLabelWidth = largestTextWidth;+ // TODO(SB): I think we should be able to remove this custom case (options.scale)+ // and consider it as a regular scale part of the "scales"" map only! This would+ // make the logic easier and remove some useless? custom code.+ if (item.isDefault) {+ me.scale = scale;+ }+ });+ // clear up discarded scales+ helpers$1.each(updated, function(hasUpdated, id) {+ if (!hasUpdated) {+ delete scales[id];+ }+ });- var angleRadians = helpers.toRadians(me.labelRotation);- var cosRotation = Math.cos(angleRadians);- var sinRotation = Math.sin(angleRadians);+ me.scales = scales;- // TODO - improve this calculation- var labelHeight = (sinRotation * largestTextWidth)- + (tickFont.size * tallestLabelHeightInLines)- + (lineSpace * (tallestLabelHeightInLines - 1))- + lineSpace; // padding+ core_scaleService.addScalesToLayout(this);+ },- minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);+ buildOrUpdateControllers: function() {+ var me = this;+ var newControllers = [];+ var datasets = me.data.datasets;+ var i, ilen;- me.ctx.font = tickFont.font;- var firstLabelWidth = computeTextSize(me.ctx, labels[0], tickFont.font);- var lastLabelWidth = computeTextSize(me.ctx, labels[labels.length - 1], tickFont.font);+ for (i = 0, ilen = datasets.length; i < ilen; i++) {+ var dataset = datasets[i];+ var meta = me.getDatasetMeta(i);+ var type = dataset.type || me.config.type;- // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned- // which means that the right padding is dominated by the font height- if (me.labelRotation !== 0) {- me.paddingLeft = opts.position === 'bottom' ? (cosRotation * firstLabelWidth) + 3 : (cosRotation * lineSpace) + 3; // add 3 px to move away from canvas edges- me.paddingRight = opts.position === 'bottom' ? (cosRotation * lineSpace) + 3 : (cosRotation * lastLabelWidth) + 3;- } else {- me.paddingLeft = firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges- me.paddingRight = lastLabelWidth / 2 + 3;- }+ if (meta.type && meta.type !== type) {+ me.destroyDatasetMeta(i);+ meta = me.getDatasetMeta(i);+ }+ meta.type = type;+ meta.order = dataset.order || 0;+ meta.index = i;++ if (meta.controller) {+ meta.controller.updateIndex(i);+ meta.controller.linkScales();} else {- // A vertical axis is more constrained by the width. Labels are the- // dominant factor here, so get that length first and account for padding- if (tickOpts.mirror) {- largestTextWidth = 0;- } else {- // use lineSpace for consistency with horizontal axis- // tickPadding is not implemented for horizontal- largestTextWidth += tickPadding + lineSpace;+ var ControllerClass = controllers[meta.type];+ if (ControllerClass === undefined) {+ throw new Error('"' + meta.type + '" is not a chart type.');}- minSize.width = Math.min(me.maxWidth, minSize.width + largestTextWidth);-- me.paddingTop = tickFont.size / 2;- me.paddingBottom = tickFont.size / 2;+ meta.controller = new ControllerClass(me, i);+ newControllers.push(meta.controller);}}- me.handleMargins();-- me.width = minSize.width;- me.height = minSize.height;+ return newControllers;},/**- * Handle margins and padding interactions+ * Reset the elements of all datasets* @private*/- handleMargins: function() {+ resetElements: function() {var me = this;- if (me.margins) {- me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0);- me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0);- me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0);- me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0);- }+ helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {+ me.getDatasetMeta(datasetIndex).controller.reset();+ }, me);},- afterFit: function() {- helpers.callback(this.options.afterFit, [this]);+ /**+ * Resets the chart back to it's state before the initial animation+ */+ reset: function() {+ this.resetElements();+ this.tooltip.initialize();},- // Shared Methods- isHorizontal: function() {- return this.options.position === 'top' || this.options.position === 'bottom';- },- isFullWidth: function() {- return (this.options.fullWidth);- },+ update: function(config) {+ var me = this;+ var i, ilen;- // Get the correct value. NaN bad inputs, If the value type is object get the x or y based on whether we are horizontal or not- getRightValue: function(rawValue) {- // Null and undefined values first- if (helpers.isNullOrUndef(rawValue)) {- return NaN;+ if (!config || typeof config !== 'object') {+ // backwards compatibility+ config = {+ duration: config,+ lazy: arguments[1]+ };}- // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values- if (typeof rawValue === 'number' && !isFinite(rawValue)) {- return NaN;++ updateConfig(me);++ // plugins options references might have change, let's invalidate the cache+ // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167+ core_plugins._invalidate(me);++ if (core_plugins.notify(me, 'beforeUpdate') === false) {+ return;}- // If it is in fact an object, dive in one more level- if (rawValue) {- if (this.isHorizontal()) {- if (rawValue.x !== undefined) {- return this.getRightValue(rawValue.x);- }- } else if (rawValue.y !== undefined) {- return this.getRightValue(rawValue.y);- }++ // In case the entire data object changed+ me.tooltip._data = me.data;++ // Make sure dataset controllers are updated and new controllers are reset+ var newControllers = me.buildOrUpdateControllers();++ // Make sure all dataset controllers have correct meta data counts+ for (i = 0, ilen = me.data.datasets.length; i < ilen; i++) {+ me.getDatasetMeta(i).controller.buildOrUpdateElements();}- // Value is good, return it- return rawValue;- },+ me.updateLayout();- /**- * Used to get the value to display in the tooltip for the data at the given index- * @param index- * @param datasetIndex- */- getLabelForIndex: helpers.noop,+ // Can only reset the new controllers after the scales have been updated+ if (me.options.animation && me.options.animation.duration) {+ helpers$1.each(newControllers, function(controller) {+ controller.reset();+ });+ }- /**- * Returns the location of the given data point. Value can either be an index or a numerical value- * The coordinate (0, 0) is at the upper-left corner of the canvas- * @param value- * @param index- * @param datasetIndex- */- getPixelForValue: helpers.noop,+ me.updateDatasets();- /**- * Used to get the data value from a given pixel. This is the inverse of getPixelForValue- * The coordinate (0, 0) is at the upper-left corner of the canvas- * @param pixel- */- getValueForPixel: helpers.noop,+ // Need to reset tooltip in case it is displayed with elements that are removed+ // after update.+ me.tooltip.initialize();- /**- * Returns the location of the tick at the given index- * The coordinate (0, 0) is at the upper-left corner of the canvas- */- getPixelForTick: function(index) {- var me = this;- var offset = me.options.offset;- if (me.isHorizontal()) {- var innerWidth = me.width - (me.paddingLeft + me.paddingRight);- var tickWidth = innerWidth / Math.max((me._ticks.length - (offset ? 0 : 1)), 1);- var pixel = (tickWidth * index) + me.paddingLeft;+ // Last active contains items that were previously in the tooltip.+ // When we reset the tooltip, we need to clear it+ me.lastActive = [];- if (offset) {- pixel += tickWidth / 2;- }+ // Do this before render so that any plugins that need final scale updates can use it+ core_plugins.notify(me, 'afterUpdate');++ me._layers.sort(compare2Level('z', '_idx'));- var finalVal = me.left + Math.round(pixel);- finalVal += me.isFullWidth() ? me.margins.left : 0;- return finalVal;+ if (me._bufferedRender) {+ me._bufferedRequest = {+ duration: config.duration,+ easing: config.easing,+ lazy: config.lazy+ };+ } else {+ me.render(config);}- var innerHeight = me.height - (me.paddingTop + me.paddingBottom);- return me.top + (index * (innerHeight / (me._ticks.length - 1)));},/**- * Utility for getting the pixel location of a percentage of scale- * The coordinate (0, 0) is at the upper-left corner of the canvas+ * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`+ * hook, in which case, plugins will not be called on `afterLayout`.+ * @private*/- getPixelForDecimal: function(decimal) {+ updateLayout: function() {var me = this;- if (me.isHorizontal()) {- var innerWidth = me.width - (me.paddingLeft + me.paddingRight);- var valueOffset = (innerWidth * decimal) + me.paddingLeft;- var finalVal = me.left + Math.round(valueOffset);- finalVal += me.isFullWidth() ? me.margins.left : 0;- return finalVal;+ if (core_plugins.notify(me, 'beforeLayout') === false) {+ return;}- return me.top + (decimal * me.height);- },- /**- * Returns the pixel for the minimum chart value- * The coordinate (0, 0) is at the upper-left corner of the canvas- */- getBasePixel: function() {- return this.getPixelForValue(this.getBaseValue());- },+ core_layouts.update(this, this.width, this.height);- getBaseValue: function() {- var me = this;- var min = me.min;- var max = me.max;+ me._layers = [];+ helpers$1.each(me.boxes, function(box) {+ // _configure is called twice, once in core.scale.update and once here.+ // Here the boxes are fully updated and at their final positions.+ if (box._configure) {+ box._configure();+ }+ me._layers.push.apply(me._layers, box._layers());+ }, me);- return me.beginAtZero ? 0 :- min < 0 && max < 0 ? max :- min > 0 && max > 0 ? min :- 0;+ me._layers.forEach(function(item, index) {+ item._idx = index;+ });++ /**+ * Provided for backward compatibility, use `afterLayout` instead.+ * @method IPlugin#afterScaleUpdate+ * @deprecated since version 2.5.0+ * @todo remove at version 3+ * @private+ */+ core_plugins.notify(me, 'afterScaleUpdate');+ core_plugins.notify(me, 'afterLayout');},/**- * Returns a subset of ticks to be plotted to avoid overlapping labels.+ * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`+ * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.* @private*/- _autoSkip: function(ticks) {- var skipRatio;+ updateDatasets: function() {var me = this;- var isHorizontal = me.isHorizontal();- var optionTicks = me.options.ticks.minor;- var tickCount = ticks.length;- var labelRotationRadians = helpers.toRadians(me.labelRotation);- var cosRotation = Math.cos(labelRotationRadians);- var longestRotatedLabel = me.longestLabelWidth * cosRotation;- var result = [];- var i, tick, shouldSkip;- // figure out the maximum number of gridlines to show- var maxTicks;- if (optionTicks.maxTicksLimit) {- maxTicks = optionTicks.maxTicksLimit;+ if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) {+ return;}- if (isHorizontal) {- skipRatio = false;-- if ((longestRotatedLabel + optionTicks.autoSkipPadding) * tickCount > (me.width - (me.paddingLeft + me.paddingRight))) {- skipRatio = 1 + Math.floor(((longestRotatedLabel + optionTicks.autoSkipPadding) * tickCount) / (me.width - (me.paddingLeft + me.paddingRight)));- }-- // if they defined a max number of optionTicks,- // increase skipRatio until that number is met- if (maxTicks && tickCount > maxTicks) {- skipRatio = Math.max(skipRatio, Math.floor(tickCount / maxTicks));- }+ for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {+ me.updateDataset(i);}- for (i = 0; i < tickCount; i++) {- tick = ticks[i];-- // Since we always show the last tick,we need may need to hide the last shown one before- shouldSkip = (skipRatio > 1 && i % skipRatio > 0) || (i % skipRatio === 0 && i + skipRatio >= tickCount);- if (shouldSkip && i !== tickCount - 1) {- // leave tick in place but make sure it's not displayed (#4635)- delete tick.label;- }- result.push(tick);- }- return result;+ core_plugins.notify(me, 'afterDatasetsUpdate');},- // Actually draw the scale on the canvas- // @param {rectangle} chartArea : the area of the chart to draw full grid lines on- draw: function(chartArea) {+ /**+ * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`+ * hook, in which case, plugins will not be called on `afterDatasetUpdate`.+ * @private+ */+ updateDataset: function(index) {var me = this;- var options = me.options;- if (!options.display) {+ var meta = me.getDatasetMeta(index);+ var args = {+ meta: meta,+ index: index+ };++ if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {return;}- var context = me.ctx;- var globalDefaults = defaults.global;- var optionTicks = options.ticks.minor;- var optionMajorTicks = options.ticks.major || optionTicks;- var gridLines = options.gridLines;- var scaleLabel = options.scaleLabel;-- var isRotated = me.labelRotation !== 0;- var isHorizontal = me.isHorizontal();+ meta.controller._update();- var ticks = optionTicks.autoSkip ? me._autoSkip(me.getTicks()) : me.getTicks();- var tickFontColor = helpers.valueOrDefault(optionTicks.fontColor, globalDefaults.defaultFontColor);- var tickFont = parseFontOptions(optionTicks);- var majorTickFontColor = helpers.valueOrDefault(optionMajorTicks.fontColor, globalDefaults.defaultFontColor);- var majorTickFont = parseFontOptions(optionMajorTicks);+ core_plugins.notify(me, 'afterDatasetUpdate', [args]);+ },- var tl = gridLines.drawTicks ? gridLines.tickMarkLength : 0;+ render: function(config) {+ var me = this;- var scaleLabelFontColor = helpers.valueOrDefault(scaleLabel.fontColor, globalDefaults.defaultFontColor);- var scaleLabelFont = parseFontOptions(scaleLabel);- var scaleLabelPadding = helpers.options.toPadding(scaleLabel.padding);- var labelRotationRadians = helpers.toRadians(me.labelRotation);+ if (!config || typeof config !== 'object') {+ // backwards compatibility+ config = {+ duration: config,+ lazy: arguments[1]+ };+ }- var itemsToDraw = [];+ var animationOptions = me.options.animation;+ var duration = valueOrDefault$9(config.duration, animationOptions && animationOptions.duration);+ var lazy = config.lazy;- var axisWidth = me.options.gridLines.lineWidth;- var xTickStart = options.position === 'right' ? me.left : me.right - axisWidth - tl;- var xTickEnd = options.position === 'right' ? me.left + tl : me.right;- var yTickStart = options.position === 'bottom' ? me.top + axisWidth : me.bottom - tl - axisWidth;- var yTickEnd = options.position === 'bottom' ? me.top + axisWidth + tl : me.bottom + axisWidth;+ if (core_plugins.notify(me, 'beforeRender') === false) {+ return;+ }- helpers.each(ticks, function(tick, index) {- // autoskipper skipped this tick (#4635)- if (helpers.isNullOrUndef(tick.label)) {- return;- }+ var onComplete = function(animation) {+ core_plugins.notify(me, 'afterRender');+ helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me);+ };- var label = tick.label;- var lineWidth, lineColor, borderDash, borderDashOffset;- if (index === me.zeroLineIndex && options.offset === gridLines.offsetGridLines) {- // Draw the first index specially- lineWidth = gridLines.zeroLineWidth;- lineColor = gridLines.zeroLineColor;- borderDash = gridLines.zeroLineBorderDash;- borderDashOffset = gridLines.zeroLineBorderDashOffset;- } else {- lineWidth = helpers.valueAtIndexOrDefault(gridLines.lineWidth, index);- lineColor = helpers.valueAtIndexOrDefault(gridLines.color, index);- borderDash = helpers.valueOrDefault(gridLines.borderDash, globalDefaults.borderDash);- borderDashOffset = helpers.valueOrDefault(gridLines.borderDashOffset, globalDefaults.borderDashOffset);- }+ if (animationOptions && duration) {+ var animation = new core_animation({+ numSteps: duration / 16.66, // 60 fps+ easing: config.easing || animationOptions.easing,- // Common properties- var tx1, ty1, tx2, ty2, x1, y1, x2, y2, labelX, labelY;- var textAlign = 'middle';- var textBaseline = 'middle';- var tickPadding = optionTicks.padding;+ render: function(chart, animationObject) {+ var easingFunction = helpers$1.easing.effects[animationObject.easing];+ var currentStep = animationObject.currentStep;+ var stepDecimal = currentStep / animationObject.numSteps;- if (isHorizontal) {- var labelYOffset = tl + tickPadding;+ chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);+ },- if (options.position === 'bottom') {- // bottom- textBaseline = !isRotated ? 'top' : 'middle';- textAlign = !isRotated ? 'center' : 'right';- labelY = me.top + labelYOffset;- } else {- // top- textBaseline = !isRotated ? 'bottom' : 'middle';- textAlign = !isRotated ? 'center' : 'left';- labelY = me.bottom - labelYOffset;- }+ onAnimationProgress: animationOptions.onProgress,+ onAnimationComplete: onComplete+ });- var xLineValue = getLineValue(me, index, gridLines.offsetGridLines && ticks.length > 1);- if (xLineValue < me.left) {- lineColor = 'rgba(0,0,0,0)';- }- xLineValue += helpers.aliasPixel(lineWidth);+ core_animations.addAnimation(me, animation, duration, lazy);+ } else {+ me.draw();- labelX = me.getPixelForTick(index) + optionTicks.labelOffset; // x values for optionTicks (need to consider offsetLabel option)+ // See https://github.com/chartjs/Chart.js/issues/3781+ onComplete(new core_animation({numSteps: 0, chart: me}));+ }- tx1 = tx2 = x1 = x2 = xLineValue;- ty1 = yTickStart;- ty2 = yTickEnd;- y1 = chartArea.top;- y2 = chartArea.bottom + axisWidth;- } else {- var isLeft = options.position === 'left';- var labelXOffset;+ return me;+ },- if (optionTicks.mirror) {- textAlign = isLeft ? 'left' : 'right';- labelXOffset = tickPadding;- } else {- textAlign = isLeft ? 'right' : 'left';- labelXOffset = tl + tickPadding;- }+ draw: function(easingValue) {+ var me = this;+ var i, layers;- labelX = isLeft ? me.right - labelXOffset : me.left + labelXOffset;+ me.clear();- var yLineValue = getLineValue(me, index, gridLines.offsetGridLines && ticks.length > 1);- if (yLineValue < me.top) {- lineColor = 'rgba(0,0,0,0)';- }- yLineValue += helpers.aliasPixel(lineWidth);+ if (helpers$1.isNullOrUndef(easingValue)) {+ easingValue = 1;+ }- labelY = me.getPixelForTick(index) + optionTicks.labelOffset;+ me.transition(easingValue);- tx1 = xTickStart;- tx2 = xTickEnd;- x1 = chartArea.left;- x2 = chartArea.right + axisWidth;- ty1 = ty2 = y1 = y2 = yLineValue;- }+ if (me.width <= 0 || me.height <= 0) {+ return;+ }- itemsToDraw.push({- tx1: tx1,- ty1: ty1,- tx2: tx2,- ty2: ty2,- x1: x1,- y1: y1,- x2: x2,- y2: y2,- labelX: labelX,- labelY: labelY,- glWidth: lineWidth,- glColor: lineColor,- glBorderDash: borderDash,- glBorderDashOffset: borderDashOffset,- rotation: -1 * labelRotationRadians,- label: label,- major: tick.major,- textBaseline: textBaseline,- textAlign: textAlign- });- });+ if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) {+ return;+ }- // Draw all of the tick labels, tick marks, and grid lines at the correct places- helpers.each(itemsToDraw, function(itemToDraw) {- if (gridLines.display) {- context.save();- context.lineWidth = itemToDraw.glWidth;- context.strokeStyle = itemToDraw.glColor;- if (context.setLineDash) {- context.setLineDash(itemToDraw.glBorderDash);- context.lineDashOffset = itemToDraw.glBorderDashOffset;- }+ // Because of plugin hooks (before/afterDatasetsDraw), datasets can't+ // currently be part of layers. Instead, we draw+ // layers <= 0 before(default, backward compat), and the rest after+ layers = me._layers;+ for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {+ layers[i].draw(me.chartArea);+ }- context.beginPath();+ me.drawDatasets(easingValue);- if (gridLines.drawTicks) {- context.moveTo(itemToDraw.tx1, itemToDraw.ty1);- context.lineTo(itemToDraw.tx2, itemToDraw.ty2);- }+ // Rest of layers+ for (; i < layers.length; ++i) {+ layers[i].draw(me.chartArea);+ }- if (gridLines.drawOnChartArea) {- context.moveTo(itemToDraw.x1, itemToDraw.y1);- context.lineTo(itemToDraw.x2, itemToDraw.y2);- }+ me._drawTooltip(easingValue);- context.stroke();- context.restore();- }-- if (optionTicks.display) {- // Make sure we draw text in the correct color and font- context.save();- context.translate(itemToDraw.labelX, itemToDraw.labelY);- context.rotate(itemToDraw.rotation);- context.font = itemToDraw.major ? majorTickFont.font : tickFont.font;- context.fillStyle = itemToDraw.major ? majorTickFontColor : tickFontColor;- context.textBaseline = itemToDraw.textBaseline;- context.textAlign = itemToDraw.textAlign;-- var label = itemToDraw.label;- if (helpers.isArray(label)) {- var lineCount = label.length;- var lineHeight = tickFont.size * 1.5;- var y = me.isHorizontal() ? 0 : -lineHeight * (lineCount - 1) / 2;-- for (var i = 0; i < lineCount; ++i) {- // We just make sure the multiline element is a string here..- context.fillText('' + label[i], 0, y);- // apply same lineSpacing as calculated @ L#320- y += lineHeight;- }- } else {- context.fillText(label, 0, 0);- }- context.restore();- }- });+ core_plugins.notify(me, 'afterDraw', [easingValue]);+ },- if (scaleLabel.display) {- // Draw the scale label- var scaleLabelX;- var scaleLabelY;- var rotation = 0;- var halfLineHeight = parseLineHeight(scaleLabel) / 2;+ /**+ * @private+ */+ transition: function(easingValue) {+ var me = this;- if (isHorizontal) {- scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width- scaleLabelY = options.position === 'bottom'- ? me.bottom - halfLineHeight - scaleLabelPadding.bottom- : me.top + halfLineHeight + scaleLabelPadding.top;- } else {- var isLeft = options.position === 'left';- scaleLabelX = isLeft- ? me.left + halfLineHeight + scaleLabelPadding.top- : me.right - halfLineHeight - scaleLabelPadding.top;- scaleLabelY = me.top + ((me.bottom - me.top) / 2);- rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;- }-- context.save();- context.translate(scaleLabelX, scaleLabelY);- context.rotate(rotation);- context.textAlign = 'center';- context.textBaseline = 'middle';- context.fillStyle = scaleLabelFontColor; // render in correct colour- context.font = scaleLabelFont.font;- context.fillText(scaleLabel.labelString, 0, 0);- context.restore();- }-- if (gridLines.drawBorder) {- // Draw the line at the edge of the axis- context.lineWidth = helpers.valueAtIndexOrDefault(gridLines.lineWidth, 0);- context.strokeStyle = helpers.valueAtIndexOrDefault(gridLines.color, 0);- var x1 = me.left;- var x2 = me.right + axisWidth;- var y1 = me.top;- var y2 = me.bottom + axisWidth;-- var aliasPixel = helpers.aliasPixel(context.lineWidth);- if (isHorizontal) {- y1 = y2 = options.position === 'top' ? me.bottom : me.top;- y1 += aliasPixel;- y2 += aliasPixel;- } else {- x1 = x2 = options.position === 'left' ? me.right : me.left;- x1 += aliasPixel;- x2 += aliasPixel;+ for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {+ if (me.isDatasetVisible(i)) {+ me.getDatasetMeta(i).controller.transition(easingValue);}-- context.beginPath();- context.moveTo(x1, y1);- context.lineTo(x2, y2);- context.stroke();}- }-});--},{"26":26,"27":27,"35":35,"46":46}],34:[function(require,module,exports){-'use strict';-var defaults = require(26);-var helpers = require(46);-var layouts = require(31);--module.exports = {- // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then- // use the new chart options to grab the correct scale- constructors: {},- // Use a registration function so that we can move to an ES6 map when we no longer need to support- // old browsers-- // Scale config defaults- defaults: {},- registerScaleType: function(type, scaleConstructor, scaleDefaults) {- this.constructors[type] = scaleConstructor;- this.defaults[type] = helpers.clone(scaleDefaults);- },- getScaleConstructor: function(type) {- return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;- },- getScaleDefaults: function(type) {- // Return the scale defaults merged with the global settings so that we always use the latest ones- return this.defaults.hasOwnProperty(type) ? helpers.merge({}, [defaults.scale, this.defaults[type]]) : {};+ me.tooltip.transition(easingValue);},- updateScaleDefaults: function(type, additions) {++ /**+ * @private+ */+ _getSortedDatasetMetas: function(filterVisible) {var me = this;- if (me.defaults.hasOwnProperty(type)) {- me.defaults[type] = helpers.extend(me.defaults[type], additions);+ var datasets = me.data.datasets || [];+ var result = [];+ var i, ilen;++ for (i = 0, ilen = datasets.length; i < ilen; ++i) {+ if (!filterVisible || me.isDatasetVisible(i)) {+ result.push(me.getDatasetMeta(i));+ }}- },- addScalesToLayout: function(chart) {- // Adds each scale to the chart.boxes array to be sized accordingly- helpers.each(chart.scales, function(scale) {- // Set ILayoutItem parameters for backwards compatibility- scale.fullWidth = scale.options.fullWidth;- scale.position = scale.options.position;- scale.weight = scale.options.weight;- layouts.addBox(chart, scale);- });- }-};-},{"26":26,"31":31,"46":46}],35:[function(require,module,exports){-'use strict';+ result.sort(compare2Level('order', 'index'));-var helpers = require(46);+ return result;+ },-/**- * Namespace to hold static tick generation functions- * @namespace Chart.Ticks- */-module.exports = {/**- * Namespace to hold formatters for different types of ticks- * @namespace Chart.Ticks.formatters+ * @private*/- formatters: {- /**- * Formatter for value labels- * @method Chart.Ticks.formatters.values- * @param value the value to display- * @return {String|Array} the label to display- */- values: function(value) {- return helpers.isArray(value) ? value : '' + value;- },-- /**- * Formatter for linear numeric ticks- * @method Chart.Ticks.formatters.linear- * @param tickValue {Number} the value to be formatted- * @param index {Number} the position of the tickValue parameter in the ticks array- * @param ticks {Array<Number>} the list of ticks being converted- * @return {String} string representation of the tickValue parameter- */- linear: function(tickValue, index, ticks) {- // If we have lots of ticks, don't use the ones- var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];+ _getSortedVisibleDatasetMetas: function() {+ return this._getSortedDatasetMetas(true);+ },- // If we have a number like 2.5 as the delta, figure out how many decimal places we need- if (Math.abs(delta) > 1) {- if (tickValue !== Math.floor(tickValue)) {- // not an integer- delta = tickValue - Math.floor(tickValue);- }- }+ /**+ * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`+ * hook, in which case, plugins will not be called on `afterDatasetsDraw`.+ * @private+ */+ drawDatasets: function(easingValue) {+ var me = this;+ var metasets, i;- var logDelta = helpers.log10(Math.abs(delta));- var tickString = '';+ if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {+ return;+ }- if (tickValue !== 0) {- var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));- if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation- var logTick = helpers.log10(Math.abs(tickValue));- tickString = tickValue.toExponential(Math.floor(logTick) - Math.floor(logDelta));- } else {- var numDecimal = -1 * Math.floor(logDelta);- numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places- tickString = tickValue.toFixed(numDecimal);- }- } else {- tickString = '0'; // never show decimal places for 0- }+ metasets = me._getSortedVisibleDatasetMetas();+ for (i = metasets.length - 1; i >= 0; --i) {+ me.drawDataset(metasets[i], easingValue);+ }- return tickString;- },+ core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]);+ },- logarithmic: function(tickValue, index, ticks) {- var remain = tickValue / (Math.pow(10, Math.floor(helpers.log10(tickValue))));+ /**+ * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`+ * hook, in which case, plugins will not be called on `afterDatasetDraw`.+ * @private+ */+ drawDataset: function(meta, easingValue) {+ var me = this;+ var args = {+ meta: meta,+ index: meta.index,+ easingValue: easingValue+ };- if (tickValue === 0) {- return '0';- } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {- return tickValue.toExponential();- }- return '';+ if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {+ return;}- }-};-},{"46":46}],36:[function(require,module,exports){-'use strict';+ meta.controller.draw(easingValue);-var defaults = require(26);-var Element = require(27);-var helpers = require(46);+ core_plugins.notify(me, 'afterDatasetDraw', [args]);+ },-defaults._set('global', {- tooltips: {- enabled: true,- custom: null,- mode: 'nearest',- position: 'average',- intersect: true,- backgroundColor: 'rgba(0,0,0,0.8)',- titleFontStyle: 'bold',- titleSpacing: 2,- titleMarginBottom: 6,- titleFontColor: '#fff',- titleAlign: 'left',- bodySpacing: 2,- bodyFontColor: '#fff',- bodyAlign: 'left',- footerFontStyle: 'bold',- footerSpacing: 2,- footerMarginTop: 6,- footerFontColor: '#fff',- footerAlign: 'left',- yPadding: 6,- xPadding: 6,- caretPadding: 2,- caretSize: 5,- cornerRadius: 6,- multiKeyBackground: '#fff',- displayColors: true,- borderColor: 'rgba(0,0,0,0)',- borderWidth: 0,- callbacks: {- // Args are: (tooltipItems, data)- beforeTitle: helpers.noop,- title: function(tooltipItems, data) {- // Pick first xLabel for now- var title = '';- var labels = data.labels;- var labelCount = labels ? labels.length : 0;+ /**+ * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`+ * hook, in which case, plugins will not be called on `afterTooltipDraw`.+ * @private+ */+ _drawTooltip: function(easingValue) {+ var me = this;+ var tooltip = me.tooltip;+ var args = {+ tooltip: tooltip,+ easingValue: easingValue+ };++ if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {+ return;+ }- if (tooltipItems.length > 0) {- var item = tooltipItems[0];+ tooltip.draw();- if (item.xLabel) {- title = item.xLabel;- } else if (labelCount > 0 && item.index < labelCount) {- title = labels[item.index];- }- }+ core_plugins.notify(me, 'afterTooltipDraw', [args]);+ },- return title;- },- afterTitle: helpers.noop,+ /**+ * Get the single element that was clicked on+ * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw+ */+ getElementAtEvent: function(e) {+ return core_interaction.modes.single(this, e);+ },- // Args are: (tooltipItems, data)- beforeBody: helpers.noop,+ getElementsAtEvent: function(e) {+ return core_interaction.modes.label(this, e, {intersect: true});+ },- // Args are: (tooltipItem, data)- beforeLabel: helpers.noop,- label: function(tooltipItem, data) {- var label = data.datasets[tooltipItem.datasetIndex].label || '';+ getElementsAtXAxis: function(e) {+ return core_interaction.modes['x-axis'](this, e, {intersect: true});+ },- if (label) {- label += ': ';- }- label += tooltipItem.yLabel;- return label;- },- labelColor: function(tooltipItem, chart) {- var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);- var activeElement = meta.data[tooltipItem.index];- var view = activeElement._view;- return {- borderColor: view.borderColor,- backgroundColor: view.backgroundColor- };- },- labelTextColor: function() {- return this._options.bodyFontColor;- },- afterLabel: helpers.noop,+ getElementsAtEventForMode: function(e, mode, options) {+ var method = core_interaction.modes[mode];+ if (typeof method === 'function') {+ return method(this, e, options);+ }- // Args are: (tooltipItems, data)- afterBody: helpers.noop,+ return [];+ },- // Args are: (tooltipItems, data)- beforeFooter: helpers.noop,- footer: helpers.noop,- afterFooter: helpers.noop+ getDatasetAtEvent: function(e) {+ return core_interaction.modes.dataset(this, e, {intersect: true});+ },++ getDatasetMeta: function(datasetIndex) {+ var me = this;+ var dataset = me.data.datasets[datasetIndex];+ if (!dataset._meta) {+ dataset._meta = {};}- }-});-var positioners = {- /**- * Average mode places the tooltip at the average position of the elements shown- * @function Chart.Tooltip.positioners.average- * @param elements {ChartElement[]} the elements being displayed in the tooltip- * @returns {Point} tooltip position- */- average: function(elements) {- if (!elements.length) {- return false;+ var meta = dataset._meta[me.id];+ if (!meta) {+ meta = dataset._meta[me.id] = {+ type: null,+ data: [],+ dataset: null,+ controller: null,+ hidden: null, // See isDatasetVisible() comment+ xAxisID: null,+ yAxisID: null,+ order: dataset.order || 0,+ index: datasetIndex+ };}- var i, len;- var x = 0;- var y = 0;- var count = 0;+ return meta;+ },- for (i = 0, len = elements.length; i < len; ++i) {- var el = elements[i];- if (el && el.hasValue()) {- var pos = el.tooltipPosition();- x += pos.x;- y += pos.y;- ++count;+ getVisibleDatasetCount: function() {+ var count = 0;+ for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {+ if (this.isDatasetVisible(i)) {+ count++;}}+ return count;+ },- return {- x: Math.round(x / count),- y: Math.round(y / count)- };+ isDatasetVisible: function(datasetIndex) {+ var meta = this.getDatasetMeta(datasetIndex);++ // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,+ // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.+ return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;+ },++ generateLegend: function() {+ return this.options.legendCallback(this);},/**- * Gets the tooltip position nearest of the item nearest to the event position- * @function Chart.Tooltip.positioners.nearest- * @param elements {Chart.Element[]} the tooltip elements- * @param eventPosition {Point} the position of the event in canvas coordinates- * @returns {Point} the tooltip position+ * @private*/- nearest: function(elements, eventPosition) {- var x = eventPosition.x;- var y = eventPosition.y;- var minDistance = Number.POSITIVE_INFINITY;- var i, len, nearestElement;+ destroyDatasetMeta: function(datasetIndex) {+ var id = this.id;+ var dataset = this.data.datasets[datasetIndex];+ var meta = dataset._meta && dataset._meta[id];- for (i = 0, len = elements.length; i < len; ++i) {- var el = elements[i];- if (el && el.hasValue()) {- var center = el.getCenterPoint();- var d = helpers.distanceBetweenPoints(eventPosition, center);+ if (meta) {+ meta.controller.destroy();+ delete dataset._meta[id];+ }+ },- if (d < minDistance) {- minDistance = d;- nearestElement = el;- }- }+ destroy: function() {+ var me = this;+ var canvas = me.canvas;+ var i, ilen;++ me.stop();++ // dataset controllers need to cleanup associated data+ for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {+ me.destroyDatasetMeta(i);}- if (nearestElement) {- var tp = nearestElement.tooltipPosition();- x = tp.x;- y = tp.y;+ if (canvas) {+ me.unbindEvents();+ helpers$1.canvas.clear(me);+ platform.releaseContext(me.ctx);+ me.canvas = null;+ me.ctx = null;}- return {- x: x,- y: y+ core_plugins.notify(me, 'destroy');++ delete Chart.instances[me.id];+ },++ toBase64Image: function() {+ return this.canvas.toDataURL.apply(this.canvas, arguments);+ },++ initToolTip: function() {+ var me = this;+ me.tooltip = new core_tooltip({+ _chart: me,+ _chartInstance: me, // deprecated, backward compatibility+ _data: me.data,+ _options: me.options.tooltips+ }, me);+ },++ /**+ * @private+ */+ bindEvents: function() {+ var me = this;+ var listeners = me._listeners = {};+ var listener = function() {+ me.eventHandler.apply(me, arguments);};- }-};-/**- * Helper method to merge the opacity into a color- */-function mergeOpacity(colorString, opacity) {- var color = helpers.color(colorString);- return color.alpha(opacity * color.alpha()).rgbaString();-}+ helpers$1.each(me.options.events, function(type) {+ platform.addEventListener(me, type, listener);+ listeners[type] = listener;+ });-// Helper to push or concat based on if the 2nd parameter is an array or not-function pushOrConcat(base, toPush) {- if (toPush) {- if (helpers.isArray(toPush)) {- // base = base.concat(toPush);- Array.prototype.push.apply(base, toPush);- } else {- base.push(toPush);+ // Elements used to detect size change should not be injected for non responsive charts.+ // See https://github.com/chartjs/Chart.js/issues/2210+ if (me.options.responsive) {+ listener = function() {+ me.resize();+ };++ platform.addEventListener(me, 'resize', listener);+ listeners.resize = listener;}- }+ },- return base;-}+ /**+ * @private+ */+ unbindEvents: function() {+ var me = this;+ var listeners = me._listeners;+ if (!listeners) {+ return;+ }-/**- * Returns array of strings split by newline- * @param {String} value - The value to split by newline.- * @returns {Array} value if newline present - Returned from String split() method- * @function- */-function splitNewlines(str) {- if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {- return str.split('\n');- }- return str;-}+ delete me._listeners;+ helpers$1.each(listeners, function(listener, type) {+ platform.removeEventListener(me, type, listener);+ });+ },+ updateHoverStyle: function(elements, mode, enabled) {+ var prefix = enabled ? 'set' : 'remove';+ var element, i, ilen;-// Private helper to create a tooltip item model-// @param element : the chart element (point, arc, bar) to create the tooltip item for-// @return : new tooltip item-function createTooltipItem(element) {- var xScale = element._xScale;- var yScale = element._yScale || element._scale; // handle radar || polarArea charts- var index = element._index;- var datasetIndex = element._datasetIndex;+ for (i = 0, ilen = elements.length; i < ilen; ++i) {+ element = elements[i];+ if (element) {+ this.getDatasetMeta(element._datasetIndex).controller[prefix + 'HoverStyle'](element);+ }+ }- return {- xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',- yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',- index: index,- datasetIndex: datasetIndex,- x: element._model.x,- y: element._model.y- };-}+ if (mode === 'dataset') {+ this.getDatasetMeta(elements[0]._datasetIndex).controller['_' + prefix + 'DatasetHoverStyle']();+ }+ },-/**- * Helper to get the reset model for the tooltip- * @param tooltipOpts {Object} the tooltip options- */-function getBaseModel(tooltipOpts) {- var globalDefaults = defaults.global;- var valueOrDefault = helpers.valueOrDefault;+ /**+ * @private+ */+ eventHandler: function(e) {+ var me = this;+ var tooltip = me.tooltip;- return {- // Positioning- xPadding: tooltipOpts.xPadding,- yPadding: tooltipOpts.yPadding,- xAlign: tooltipOpts.xAlign,- yAlign: tooltipOpts.yAlign,+ if (core_plugins.notify(me, 'beforeEvent', [e]) === false) {+ return;+ }- // Body- bodyFontColor: tooltipOpts.bodyFontColor,- _bodyFontFamily: valueOrDefault(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),- _bodyFontStyle: valueOrDefault(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),- _bodyAlign: tooltipOpts.bodyAlign,- bodyFontSize: valueOrDefault(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),- bodySpacing: tooltipOpts.bodySpacing,+ // Buffer any update calls so that renders do not occur+ me._bufferedRender = true;+ me._bufferedRequest = null;- // Title- titleFontColor: tooltipOpts.titleFontColor,- _titleFontFamily: valueOrDefault(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),- _titleFontStyle: valueOrDefault(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),- titleFontSize: valueOrDefault(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),- _titleAlign: tooltipOpts.titleAlign,- titleSpacing: tooltipOpts.titleSpacing,- titleMarginBottom: tooltipOpts.titleMarginBottom,+ var changed = me.handleEvent(e);+ // for smooth tooltip animations issue #4989+ // the tooltip should be the source of change+ // Animation check workaround:+ // tooltip._start will be null when tooltip isn't animating+ if (tooltip) {+ changed = tooltip._start+ ? tooltip.handleEvent(e)+ : changed | tooltip.handleEvent(e);+ }- // Footer- footerFontColor: tooltipOpts.footerFontColor,- _footerFontFamily: valueOrDefault(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),- _footerFontStyle: valueOrDefault(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),- footerFontSize: valueOrDefault(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),- _footerAlign: tooltipOpts.footerAlign,- footerSpacing: tooltipOpts.footerSpacing,- footerMarginTop: tooltipOpts.footerMarginTop,+ core_plugins.notify(me, 'afterEvent', [e]);- // Appearance- caretSize: tooltipOpts.caretSize,- cornerRadius: tooltipOpts.cornerRadius,- backgroundColor: tooltipOpts.backgroundColor,- opacity: 0,- legendColorBackground: tooltipOpts.multiKeyBackground,- displayColors: tooltipOpts.displayColors,- borderColor: tooltipOpts.borderColor,- borderWidth: tooltipOpts.borderWidth- };-}+ var bufferedRequest = me._bufferedRequest;+ if (bufferedRequest) {+ // If we have an update that was triggered, we need to do a normal render+ me.render(bufferedRequest);+ } else if (changed && !me.animating) {+ // If entering, leaving, or changing elements, animate the change via pivot+ me.stop();-/**- * Get the size of the tooltip- */-function getTooltipSize(tooltip, model) {- var ctx = tooltip._chart.ctx;+ // We only need to render at this point. Updating will cause scales to be+ // recomputed generating flicker & using more memory than necessary.+ me.render({+ duration: me.options.hover.animationDuration,+ lazy: true+ });+ }- var height = model.yPadding * 2; // Tooltip Padding- var width = 0;+ me._bufferedRender = false;+ me._bufferedRequest = null;- // Count of all lines in the body- var body = model.body;- var combinedBodyLength = body.reduce(function(count, bodyItem) {- return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;- }, 0);- combinedBodyLength += model.beforeBody.length + model.afterBody.length;+ return me;+ },- var titleLineCount = model.title.length;- var footerLineCount = model.footer.length;- var titleFontSize = model.titleFontSize;- var bodyFontSize = model.bodyFontSize;- var footerFontSize = model.footerFontSize;+ /**+ * Handle an event+ * @private+ * @param {IEvent} event the event to handle+ * @return {boolean} true if the chart needs to re-render+ */+ handleEvent: function(e) {+ var me = this;+ var options = me.options || {};+ var hoverOptions = options.hover;+ var changed = false;++ me.lastActive = me.lastActive || [];++ // Find Active Elements for hover and tooltips+ if (e.type === 'mouseout') {+ me.active = [];+ } else {+ me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);+ }++ // Invoke onHover hook+ // Need to call with native event here to not break backwards compatibility+ helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);++ if (e.type === 'mouseup' || e.type === 'click') {+ if (options.onClick) {+ // Use e.native here for backwards compatibility+ options.onClick.call(me, e.native, me.active);+ }+ }++ // Remove styling for last active (even if it may still be active)+ if (me.lastActive.length) {+ me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);+ }- height += titleLineCount * titleFontSize; // Title Lines- height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing- height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin- height += combinedBodyLength * bodyFontSize; // Body Lines- height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing- height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin- height += footerLineCount * (footerFontSize); // Footer Lines- height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing+ // Built in hover styling+ if (me.active.length && hoverOptions.mode) {+ me.updateHoverStyle(me.active, hoverOptions.mode, true);+ }- // Title width- var widthPadding = 0;- var maxLineWidth = function(line) {- width = Math.max(width, ctx.measureText(line).width + widthPadding);- };+ changed = !helpers$1.arrayEquals(me.active, me.lastActive);- ctx.font = helpers.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);- helpers.each(model.title, maxLineWidth);+ // Remember Last Actives+ me.lastActive = me.active;- // Body width- ctx.font = helpers.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);- helpers.each(model.beforeBody.concat(model.afterBody), maxLineWidth);+ return changed;+ }+});- // Body lines may include some extra width due to the color box- widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;- helpers.each(body, function(bodyItem) {- helpers.each(bodyItem.before, maxLineWidth);- helpers.each(bodyItem.lines, maxLineWidth);- helpers.each(bodyItem.after, maxLineWidth);- });+/**+ * NOTE(SB) We actually don't use this container anymore but we need to keep it+ * for backward compatibility. Though, it can still be useful for plugins that+ * would need to work on multiple charts?!+ */+Chart.instances = {};- // Reset back to 0- widthPadding = 0;+var core_controller = Chart;- // Footer width- ctx.font = helpers.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);- helpers.each(model.footer, maxLineWidth);+// DEPRECATIONS- // Add padding- width += 2 * model.xPadding;+/**+ * Provided for backward compatibility, use Chart instead.+ * @class Chart.Controller+ * @deprecated since version 2.6+ * @todo remove at version 3+ * @private+ */+Chart.Controller = Chart;- return {- width: width,- height: height- };-}+/**+ * Provided for backward compatibility, not available anymore.+ * @namespace Chart+ * @deprecated since version 2.8+ * @todo remove at version 3+ * @private+ */+Chart.types = {};/**- * Helper to get the alignment of a tooltip given the size+ * Provided for backward compatibility, not available anymore.+ * @namespace Chart.helpers.configMerge+ * @deprecated since version 2.8.0+ * @todo remove at version 3+ * @private*/-function determineAlignment(tooltip, size) {- var model = tooltip._model;- var chart = tooltip._chart;- var chartArea = tooltip._chart.chartArea;- var xAlign = 'center';- var yAlign = 'center';+helpers$1.configMerge = mergeConfig;- if (model.y < size.height) {- yAlign = 'top';- } else if (model.y > (chart.height - size.height)) {- yAlign = 'bottom';- }+/**+ * Provided for backward compatibility, not available anymore.+ * @namespace Chart.helpers.scaleMerge+ * @deprecated since version 2.8.0+ * @todo remove at version 3+ * @private+ */+helpers$1.scaleMerge = mergeScaleConfig;- var lf, rf; // functions to determine left, right alignment- var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart- var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges- var midX = (chartArea.left + chartArea.right) / 2;- var midY = (chartArea.top + chartArea.bottom) / 2;+var core_helpers = function() {- if (yAlign === 'center') {- lf = function(x) {- return x <= midX;- };- rf = function(x) {- return x > midX;- };- } else {- lf = function(x) {- return x <= (size.width / 2);- };- rf = function(x) {- return x >= (chart.width - (size.width / 2));- };- }+ // -- Basic js utility methods- olf = function(x) {- return x + size.width + model.caretSize + model.caretPadding > chart.width;+ helpers$1.where = function(collection, filterCallback) {+ if (helpers$1.isArray(collection) && Array.prototype.filter) {+ return collection.filter(filterCallback);+ }+ var filtered = [];++ helpers$1.each(collection, function(item) {+ if (filterCallback(item)) {+ filtered.push(item);+ }+ });++ return filtered;};- orf = function(x) {- return x - size.width - model.caretSize - model.caretPadding < 0;+ helpers$1.findIndex = Array.prototype.findIndex ?+ function(array, callback, scope) {+ return array.findIndex(callback, scope);+ } :+ function(array, callback, scope) {+ scope = scope === undefined ? array : scope;+ for (var i = 0, ilen = array.length; i < ilen; ++i) {+ if (callback.call(scope, array[i], i, array)) {+ return i;+ }+ }+ return -1;+ };+ helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {+ // Default to start of the array+ if (helpers$1.isNullOrUndef(startIndex)) {+ startIndex = -1;+ }+ for (var i = startIndex + 1; i < arrayToSearch.length; i++) {+ var currentItem = arrayToSearch[i];+ if (filterCallback(currentItem)) {+ return currentItem;+ }+ }};- yf = function(y) {- return y <= midY ? 'top' : 'bottom';+ helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {+ // Default to end of the array+ if (helpers$1.isNullOrUndef(startIndex)) {+ startIndex = arrayToSearch.length;+ }+ for (var i = startIndex - 1; i >= 0; i--) {+ var currentItem = arrayToSearch[i];+ if (filterCallback(currentItem)) {+ return currentItem;+ }+ }};- if (lf(model.x)) {- xAlign = 'left';+ // -- Math methods+ helpers$1.isNumber = function(n) {+ return !isNaN(parseFloat(n)) && isFinite(n);+ };+ helpers$1.almostEquals = function(x, y, epsilon) {+ return Math.abs(x - y) < epsilon;+ };+ helpers$1.almostWhole = function(x, epsilon) {+ var rounded = Math.round(x);+ return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);+ };+ helpers$1.max = function(array) {+ return array.reduce(function(max, value) {+ if (!isNaN(value)) {+ return Math.max(max, value);+ }+ return max;+ }, Number.NEGATIVE_INFINITY);+ };+ helpers$1.min = function(array) {+ return array.reduce(function(min, value) {+ if (!isNaN(value)) {+ return Math.min(min, value);+ }+ return min;+ }, Number.POSITIVE_INFINITY);+ };+ helpers$1.sign = Math.sign ?+ function(x) {+ return Math.sign(x);+ } :+ function(x) {+ x = +x; // convert to a number+ if (x === 0 || isNaN(x)) {+ return x;+ }+ return x > 0 ? 1 : -1;+ };+ helpers$1.toRadians = function(degrees) {+ return degrees * (Math.PI / 180);+ };+ helpers$1.toDegrees = function(radians) {+ return radians * (180 / Math.PI);+ };- // Is tooltip too wide and goes over the right side of the chart.?- if (olf(model.x)) {- xAlign = 'center';- yAlign = yf(model.y);+ /**+ * Returns the number of decimal places+ * i.e. the number of digits after the decimal point, of the value of this Number.+ * @param {number} x - A number.+ * @returns {number} The number of decimal places.+ * @private+ */+ helpers$1._decimalPlaces = function(x) {+ if (!helpers$1.isFinite(x)) {+ return;}- } else if (rf(model.x)) {- xAlign = 'right';-- // Is tooltip too wide and goes outside left edge of canvas?- if (orf(model.x)) {- xAlign = 'center';- yAlign = yf(model.y);+ var e = 1;+ var p = 0;+ while (Math.round(x * e) / e !== x) {+ e *= 10;+ p++;}- }-- var opts = tooltip._options;- return {- xAlign: opts.xAlign ? opts.xAlign : xAlign,- yAlign: opts.yAlign ? opts.yAlign : yAlign+ return p;};-}-/**- * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment- */-function getBackgroundPoint(vm, size, alignment, chart) {- // Background Position- var x = vm.x;- var y = vm.y;+ // Gets the angle from vertical upright to the point about a centre.+ helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) {+ var distanceFromXCenter = anglePoint.x - centrePoint.x;+ var distanceFromYCenter = anglePoint.y - centrePoint.y;+ var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);- var caretSize = vm.caretSize;- var caretPadding = vm.caretPadding;- var cornerRadius = vm.cornerRadius;- var xAlign = alignment.xAlign;- var yAlign = alignment.yAlign;- var paddingAndSize = caretSize + caretPadding;- var radiusAndPadding = cornerRadius + caretPadding;+ var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);- if (xAlign === 'right') {- x -= size.width;- } else if (xAlign === 'center') {- x -= (size.width / 2);- if (x + size.width > chart.width) {- x = chart.width - size.width;- }- if (x < 0) {- x = 0;+ if (angle < (-0.5 * Math.PI)) {+ angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]}- }-- if (yAlign === 'top') {- y += paddingAndSize;- } else if (yAlign === 'bottom') {- y -= size.height + paddingAndSize;- } else {- y -= (size.height / 2);- }- if (yAlign === 'center') {- if (xAlign === 'left') {- x += paddingAndSize;- } else if (xAlign === 'right') {- x -= paddingAndSize;- }- } else if (xAlign === 'left') {- x -= radiusAndPadding;- } else if (xAlign === 'right') {- x += radiusAndPadding;- }+ return {+ angle: angle,+ distance: radialDistanceFromCenter+ };+ };+ helpers$1.distanceBetweenPoints = function(pt1, pt2) {+ return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));+ };- return {- x: x,- y: y+ /**+ * Provided for backward compatibility, not available anymore+ * @function Chart.helpers.aliasPixel+ * @deprecated since version 2.8.0+ * @todo remove at version 3+ */+ helpers$1.aliasPixel = function(pixelWidth) {+ return (pixelWidth % 2 === 0) ? 0 : 0.5;};-}-/**- * Helper to build before and after body lines- */-function getBeforeAfterBodyLines(callback) {- return pushOrConcat([], splitNewlines(callback));-}+ /**+ * Returns the aligned pixel value to avoid anti-aliasing blur+ * @param {Chart} chart - The chart instance.+ * @param {number} pixel - A pixel value.+ * @param {number} width - The width of the element.+ * @returns {number} The aligned pixel value.+ * @private+ */+ helpers$1._alignPixel = function(chart, pixel, width) {+ var devicePixelRatio = chart.currentDevicePixelRatio;+ var halfWidth = width / 2;+ return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;+ };-var exports = module.exports = Element.extend({- initialize: function() {- this._model = getBaseModel(this._options);- this._lastActive = [];- },+ helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {+ // Props to Rob Spencer at scaled innovation for his post on splining between points+ // http://scaledinnovation.com/analytics/splines/aboutSplines.html- // Get the title- // Args are: (tooltipItem, data)- getTitle: function() {- var me = this;- var opts = me._options;- var callbacks = opts.callbacks;+ // This function must also respect "skipped" points- var beforeTitle = callbacks.beforeTitle.apply(me, arguments);- var title = callbacks.title.apply(me, arguments);- var afterTitle = callbacks.afterTitle.apply(me, arguments);+ var previous = firstPoint.skip ? middlePoint : firstPoint;+ var current = middlePoint;+ var next = afterPoint.skip ? middlePoint : afterPoint;- var lines = [];- lines = pushOrConcat(lines, splitNewlines(beforeTitle));- lines = pushOrConcat(lines, splitNewlines(title));- lines = pushOrConcat(lines, splitNewlines(afterTitle));+ var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));+ var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));- return lines;- },+ var s01 = d01 / (d01 + d12);+ var s12 = d12 / (d01 + d12);- // Args are: (tooltipItem, data)- getBeforeBody: function() {- return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));- },+ // If all points are the same, s01 & s02 will be inf+ s01 = isNaN(s01) ? 0 : s01;+ s12 = isNaN(s12) ? 0 : s12;- // Args are: (tooltipItem, data)- getBody: function(tooltipItems, data) {- var me = this;- var callbacks = me._options.callbacks;- var bodyItems = [];+ var fa = t * s01; // scaling factor for triangle Ta+ var fb = t * s12;- helpers.each(tooltipItems, function(tooltipItem) {- var bodyItem = {- before: [],- lines: [],- after: []- };- pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));- pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));- pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));+ return {+ previous: {+ x: current.x - fa * (next.x - previous.x),+ y: current.y - fa * (next.y - previous.y)+ },+ next: {+ x: current.x + fb * (next.x - previous.x),+ y: current.y + fb * (next.y - previous.y)+ }+ };+ };+ helpers$1.EPSILON = Number.EPSILON || 1e-14;+ helpers$1.splineCurveMonotone = function(points) {+ // This function calculates Bézier control points in a similar way than |splineCurve|,+ // but preserves monotonicity of the provided data and ensures no local extremums are added+ // between the dataset discrete points due to the interpolation.+ // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation- bodyItems.push(bodyItem);+ var pointsWithTangents = (points || []).map(function(point) {+ return {+ model: point._model,+ deltaK: 0,+ mK: 0+ };});- return bodyItems;- },+ // Calculate slopes (deltaK) and initialize tangents (mK)+ var pointsLen = pointsWithTangents.length;+ var i, pointBefore, pointCurrent, pointAfter;+ for (i = 0; i < pointsLen; ++i) {+ pointCurrent = pointsWithTangents[i];+ if (pointCurrent.model.skip) {+ continue;+ }- // Args are: (tooltipItem, data)- getAfterBody: function() {- return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));- },+ pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;+ pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;+ if (pointAfter && !pointAfter.model.skip) {+ var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);- // Get the footer and beforeFooter and afterFooter lines- // Args are: (tooltipItem, data)- getFooter: function() {- var me = this;- var callbacks = me._options.callbacks;+ // In the case of two points that appear at the same x pixel, slopeDeltaX is 0+ pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;+ }- var beforeFooter = callbacks.beforeFooter.apply(me, arguments);- var footer = callbacks.footer.apply(me, arguments);- var afterFooter = callbacks.afterFooter.apply(me, arguments);+ if (!pointBefore || pointBefore.model.skip) {+ pointCurrent.mK = pointCurrent.deltaK;+ } else if (!pointAfter || pointAfter.model.skip) {+ pointCurrent.mK = pointBefore.deltaK;+ } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {+ pointCurrent.mK = 0;+ } else {+ pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;+ }+ }- var lines = [];- lines = pushOrConcat(lines, splitNewlines(beforeFooter));- lines = pushOrConcat(lines, splitNewlines(footer));- lines = pushOrConcat(lines, splitNewlines(afterFooter));+ // Adjust tangents to ensure monotonic properties+ var alphaK, betaK, tauK, squaredMagnitude;+ for (i = 0; i < pointsLen - 1; ++i) {+ pointCurrent = pointsWithTangents[i];+ pointAfter = pointsWithTangents[i + 1];+ if (pointCurrent.model.skip || pointAfter.model.skip) {+ continue;+ }- return lines;- },+ if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {+ pointCurrent.mK = pointAfter.mK = 0;+ continue;+ }- update: function(changed) {- var me = this;- var opts = me._options;+ alphaK = pointCurrent.mK / pointCurrent.deltaK;+ betaK = pointAfter.mK / pointCurrent.deltaK;+ squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);+ if (squaredMagnitude <= 9) {+ continue;+ }- // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition- // that does _view = _model if ease === 1. This causes the 2nd tooltip update to set properties in both the view and model at the same time- // which breaks any animations.- var existingModel = me._model;- var model = me._model = getBaseModel(opts);- var active = me._active;+ tauK = 3 / Math.sqrt(squaredMagnitude);+ pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;+ pointAfter.mK = betaK * tauK * pointCurrent.deltaK;+ }- var data = me._data;+ // Compute control points+ var deltaX;+ for (i = 0; i < pointsLen; ++i) {+ pointCurrent = pointsWithTangents[i];+ if (pointCurrent.model.skip) {+ continue;+ }- // In the case where active.length === 0 we need to keep these at existing values for good animations- var alignment = {- xAlign: existingModel.xAlign,- yAlign: existingModel.yAlign- };- var backgroundPoint = {- x: existingModel.x,- y: existingModel.y- };- var tooltipSize = {- width: existingModel.width,- height: existingModel.height- };- var tooltipPosition = {- x: existingModel.caretX,- y: existingModel.caretY- };+ pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;+ pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;+ if (pointBefore && !pointBefore.model.skip) {+ deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;+ pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;+ pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;+ }+ if (pointAfter && !pointAfter.model.skip) {+ deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;+ pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;+ pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;+ }+ }+ };+ helpers$1.nextItem = function(collection, index, loop) {+ if (loop) {+ return index >= collection.length - 1 ? collection[0] : collection[index + 1];+ }+ return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];+ };+ helpers$1.previousItem = function(collection, index, loop) {+ if (loop) {+ return index <= 0 ? collection[collection.length - 1] : collection[index - 1];+ }+ return index <= 0 ? collection[0] : collection[index - 1];+ };+ // Implementation of the nice number algorithm used in determining where axis labels will go+ helpers$1.niceNum = function(range, round) {+ var exponent = Math.floor(helpers$1.log10(range));+ var fraction = range / Math.pow(10, exponent);+ var niceFraction;++ if (round) {+ if (fraction < 1.5) {+ niceFraction = 1;+ } else if (fraction < 3) {+ niceFraction = 2;+ } else if (fraction < 7) {+ niceFraction = 5;+ } else {+ niceFraction = 10;+ }+ } else if (fraction <= 1.0) {+ niceFraction = 1;+ } else if (fraction <= 2) {+ niceFraction = 2;+ } else if (fraction <= 5) {+ niceFraction = 5;+ } else {+ niceFraction = 10;+ }++ return niceFraction * Math.pow(10, exponent);+ };+ // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/+ helpers$1.requestAnimFrame = (function() {+ if (typeof window === 'undefined') {+ return function(callback) {+ callback();+ };+ }+ return window.requestAnimationFrame ||+ window.webkitRequestAnimationFrame ||+ window.mozRequestAnimationFrame ||+ window.oRequestAnimationFrame ||+ window.msRequestAnimationFrame ||+ function(callback) {+ return window.setTimeout(callback, 1000 / 60);+ };+ }());+ // -- DOM methods+ helpers$1.getRelativePosition = function(evt, chart) {+ var mouseX, mouseY;+ var e = evt.originalEvent || evt;+ var canvas = evt.target || evt.srcElement;+ var boundingRect = canvas.getBoundingClientRect();++ var touches = e.touches;+ if (touches && touches.length > 0) {+ mouseX = touches[0].clientX;+ mouseY = touches[0].clientY;- var i, len;+ } else {+ mouseX = e.clientX;+ mouseY = e.clientY;+ }- if (active.length) {- model.opacity = 1;+ // Scale mouse coordinates into canvas coordinates+ // by following the pattern laid out by 'jerryj' in the comments of+ // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/+ var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left'));+ var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top'));+ var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right'));+ var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom'));+ var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;+ var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;- var labelColors = [];- var labelTextColors = [];- tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);+ // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However+ // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here+ mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);+ mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);- var tooltipItems = [];- for (i = 0, len = active.length; i < len; ++i) {- tooltipItems.push(createTooltipItem(active[i]));- }+ return {+ x: mouseX,+ y: mouseY+ };- // If the user provided a filter function, use it to modify the tooltip items- if (opts.filter) {- tooltipItems = tooltipItems.filter(function(a) {- return opts.filter(a, data);- });- }+ };- // If the user provided a sorting function, use it to modify the tooltip items- if (opts.itemSort) {- tooltipItems = tooltipItems.sort(function(a, b) {- return opts.itemSort(a, b, data);- });+ // Private helper function to convert max-width/max-height values that may be percentages into a number+ function parseMaxStyle(styleValue, node, parentProperty) {+ var valueInPixels;+ if (typeof styleValue === 'string') {+ valueInPixels = parseInt(styleValue, 10);++ if (styleValue.indexOf('%') !== -1) {+ // percentage * size in dimension+ valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];}+ } else {+ valueInPixels = styleValue;+ }- // Determine colors for boxes- helpers.each(tooltipItems, function(tooltipItem) {- labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));- labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));- });+ return valueInPixels;+ }+ /**+ * Returns if the given value contains an effective constraint.+ * @private+ */+ function isConstrainedValue(value) {+ return value !== undefined && value !== null && value !== 'none';+ }- // Build the Text Lines- model.title = me.getTitle(tooltipItems, data);- model.beforeBody = me.getBeforeBody(tooltipItems, data);- model.body = me.getBody(tooltipItems, data);- model.afterBody = me.getAfterBody(tooltipItems, data);- model.footer = me.getFooter(tooltipItems, data);+ /**+ * Returns the max width or height of the given DOM node in a cross-browser compatible fashion+ * @param {HTMLElement} domNode - the node to check the constraint on+ * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')+ * @param {string} percentageProperty - property of parent to use when calculating width as a percentage+ * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}+ */+ function getConstraintDimension(domNode, maxStyle, percentageProperty) {+ var view = document.defaultView;+ var parentNode = helpers$1._getParentNode(domNode);+ var constrainedNode = view.getComputedStyle(domNode)[maxStyle];+ var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];+ var hasCNode = isConstrainedValue(constrainedNode);+ var hasCContainer = isConstrainedValue(constrainedContainer);+ var infinity = Number.POSITIVE_INFINITY;- // Initial positioning and colors- model.x = Math.round(tooltipPosition.x);- model.y = Math.round(tooltipPosition.y);- model.caretPadding = opts.caretPadding;- model.labelColors = labelColors;- model.labelTextColors = labelTextColors;+ if (hasCNode || hasCContainer) {+ return Math.min(+ hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,+ hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);+ }- // data points- model.dataPoints = tooltipItems;+ return 'none';+ }+ // returns Number or undefined if no constraint+ helpers$1.getConstraintWidth = function(domNode) {+ return getConstraintDimension(domNode, 'max-width', 'clientWidth');+ };+ // returns Number or undefined if no constraint+ helpers$1.getConstraintHeight = function(domNode) {+ return getConstraintDimension(domNode, 'max-height', 'clientHeight');+ };+ /**+ * @private+ */+ helpers$1._calculatePadding = function(container, padding, parentDimension) {+ padding = helpers$1.getStyle(container, padding);- // We need to determine alignment of the tooltip- tooltipSize = getTooltipSize(this, model);- alignment = determineAlignment(this, tooltipSize);- // Final Size and Position- backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);- } else {- model.opacity = 0;+ return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);+ };+ /**+ * @private+ */+ helpers$1._getParentNode = function(domNode) {+ var parent = domNode.parentNode;+ if (parent && parent.toString() === '[object ShadowRoot]') {+ parent = parent.host;+ }+ return parent;+ };+ helpers$1.getMaximumWidth = function(domNode) {+ var container = helpers$1._getParentNode(domNode);+ if (!container) {+ return domNode.clientWidth;}- model.xAlign = alignment.xAlign;- model.yAlign = alignment.yAlign;- model.x = backgroundPoint.x;- model.y = backgroundPoint.y;- model.width = tooltipSize.width;- model.height = tooltipSize.height;+ var clientWidth = container.clientWidth;+ var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth);+ var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth);- // Point where the caret on the tooltip points to- model.caretX = tooltipPosition.x;- model.caretY = tooltipPosition.y;+ var w = clientWidth - paddingLeft - paddingRight;+ var cw = helpers$1.getConstraintWidth(domNode);+ return isNaN(cw) ? w : Math.min(w, cw);+ };+ helpers$1.getMaximumHeight = function(domNode) {+ var container = helpers$1._getParentNode(domNode);+ if (!container) {+ return domNode.clientHeight;+ }- me._model = model;+ var clientHeight = container.clientHeight;+ var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight);+ var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight);- if (changed && opts.custom) {- opts.custom.call(me, model);+ var h = clientHeight - paddingTop - paddingBottom;+ var ch = helpers$1.getConstraintHeight(domNode);+ return isNaN(ch) ? h : Math.min(h, ch);+ };+ helpers$1.getStyle = function(el, property) {+ return el.currentStyle ?+ el.currentStyle[property] :+ document.defaultView.getComputedStyle(el, null).getPropertyValue(property);+ };+ helpers$1.retinaScale = function(chart, forceRatio) {+ var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;+ if (pixelRatio === 1) {+ return;}- return me;- },-- drawCaret: function(tooltipPoint, size) {- var ctx = this._chart.ctx;- var vm = this._view;- var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);+ var canvas = chart.canvas;+ var height = chart.height;+ var width = chart.width;- ctx.lineTo(caretPosition.x1, caretPosition.y1);- ctx.lineTo(caretPosition.x2, caretPosition.y2);- ctx.lineTo(caretPosition.x3, caretPosition.y3);- },- getCaretPosition: function(tooltipPoint, size, vm) {- var x1, x2, x3, y1, y2, y3;- var caretSize = vm.caretSize;- var cornerRadius = vm.cornerRadius;- var xAlign = vm.xAlign;- var yAlign = vm.yAlign;- var ptX = tooltipPoint.x;- var ptY = tooltipPoint.y;- var width = size.width;- var height = size.height;+ canvas.height = height * pixelRatio;+ canvas.width = width * pixelRatio;+ chart.ctx.scale(pixelRatio, pixelRatio);- if (yAlign === 'center') {- y2 = ptY + (height / 2);+ // If no style has been set on the canvas, the render size is used as display size,+ // making the chart visually bigger, so let's enforce it to the "correct" values.+ // See https://github.com/chartjs/Chart.js/issues/3575+ if (!canvas.style.height && !canvas.style.width) {+ canvas.style.height = height + 'px';+ canvas.style.width = width + 'px';+ }+ };+ // -- Canvas methods+ helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) {+ return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;+ };+ helpers$1.longestText = function(ctx, font, arrayOfThings, cache) {+ cache = cache || {};+ var data = cache.data = cache.data || {};+ var gc = cache.garbageCollect = cache.garbageCollect || [];- if (xAlign === 'left') {- x1 = ptX;- x2 = x1 - caretSize;- x3 = x1;+ if (cache.font !== font) {+ data = cache.data = {};+ gc = cache.garbageCollect = [];+ cache.font = font;+ }- y1 = y2 + caretSize;- y3 = y2 - caretSize;- } else {- x1 = ptX + width;- x2 = x1 + caretSize;- x3 = x1;+ ctx.font = font;+ var longest = 0;+ var ilen = arrayOfThings.length;+ var i, j, jlen, thing, nestedThing;+ for (i = 0; i < ilen; i++) {+ thing = arrayOfThings[i];- y1 = y2 - caretSize;- y3 = y2 + caretSize;- }- } else {- if (xAlign === 'left') {- x2 = ptX + cornerRadius + (caretSize);- x1 = x2 - caretSize;- x3 = x2 + caretSize;- } else if (xAlign === 'right') {- x2 = ptX + width - cornerRadius - caretSize;- x1 = x2 - caretSize;- x3 = x2 + caretSize;- } else {- x2 = vm.caretX;- x1 = x2 - caretSize;- x3 = x2 + caretSize;+ // Undefined strings and arrays should not be measured+ if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) {+ longest = helpers$1.measureText(ctx, data, gc, longest, thing);+ } else if (helpers$1.isArray(thing)) {+ // if it is an array lets measure each element+ // to do maybe simplify this function a bit so we can do this more recursively?+ for (j = 0, jlen = thing.length; j < jlen; j++) {+ nestedThing = thing[j];+ // Undefined strings and arrays should not be measured+ if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) {+ longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing);+ }+ }}- if (yAlign === 'top') {- y1 = ptY;- y2 = y1 - caretSize;- y3 = y1;- } else {- y1 = ptY + height;- y2 = y1 + caretSize;- y3 = y1;- // invert drawing order- var tmp = x3;- x3 = x1;- x1 = tmp;+ }++ var gcLen = gc.length / 2;+ if (gcLen > arrayOfThings.length) {+ for (i = 0; i < gcLen; i++) {+ delete data[gc[i]];}+ gc.splice(0, gcLen);+ }+ return longest;+ };+ helpers$1.measureText = function(ctx, data, gc, longest, string) {+ var textWidth = data[string];+ if (!textWidth) {+ textWidth = data[string] = ctx.measureText(string).width;+ gc.push(string);}- return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};- },-- drawTitle: function(pt, vm, ctx, opacity) {- var title = vm.title;-- if (title.length) {- ctx.textAlign = vm._titleAlign;- ctx.textBaseline = 'top';-- var titleFontSize = vm.titleFontSize;- var titleSpacing = vm.titleSpacing;-- ctx.fillStyle = mergeOpacity(vm.titleFontColor, opacity);- ctx.font = helpers.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);-- var i, len;- for (i = 0, len = title.length; i < len; ++i) {- ctx.fillText(title[i], pt.x, pt.y);- pt.y += titleFontSize + titleSpacing; // Line Height and spacing+ if (textWidth > longest) {+ longest = textWidth;+ }+ return longest;+ };- if (i + 1 === title.length) {- pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing+ /**+ * @deprecated+ */+ helpers$1.numberOfLabelLines = function(arrayOfThings) {+ var numberOfLines = 1;+ helpers$1.each(arrayOfThings, function(thing) {+ if (helpers$1.isArray(thing)) {+ if (thing.length > numberOfLines) {+ numberOfLines = thing.length;}}- }- },-- drawBody: function(pt, vm, ctx, opacity) {- var bodyFontSize = vm.bodyFontSize;- var bodySpacing = vm.bodySpacing;- var body = vm.body;+ });+ return numberOfLines;+ };- ctx.textAlign = vm._bodyAlign;- ctx.textBaseline = 'top';- ctx.font = helpers.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);+ helpers$1.color = !chartjsColor ?+ function(value) {+ console.error('Color.js not found!');+ return value;+ } :+ function(value) {+ /* global CanvasGradient */+ if (value instanceof CanvasGradient) {+ value = core_defaults.global.defaultColor;+ }- // Before Body- var xLinePadding = 0;- var fillLineOfText = function(line) {- ctx.fillText(line, pt.x + xLinePadding, pt.y);- pt.y += bodyFontSize + bodySpacing;+ return chartjsColor(value);};- // Before body lines- ctx.fillStyle = mergeOpacity(vm.bodyFontColor, opacity);- helpers.each(vm.beforeBody, fillLineOfText);-- var drawColorBoxes = vm.displayColors;- xLinePadding = drawColorBoxes ? (bodyFontSize + 2) : 0;-- // Draw body lines now- helpers.each(body, function(bodyItem, i) {- var textColor = mergeOpacity(vm.labelTextColors[i], opacity);- ctx.fillStyle = textColor;- helpers.each(bodyItem.before, fillLineOfText);-- helpers.each(bodyItem.lines, function(line) {- // Draw Legend-like boxes if needed- if (drawColorBoxes) {- // Fill a white rect so that colours merge nicely if the opacity is < 1- ctx.fillStyle = mergeOpacity(vm.legendColorBackground, opacity);- ctx.fillRect(pt.x, pt.y, bodyFontSize, bodyFontSize);-- // Border- ctx.lineWidth = 1;- ctx.strokeStyle = mergeOpacity(vm.labelColors[i].borderColor, opacity);- ctx.strokeRect(pt.x, pt.y, bodyFontSize, bodyFontSize);+ helpers$1.getHoverColor = function(colorValue) {+ /* global CanvasPattern */+ return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?+ colorValue :+ helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString();+ };+};- // Inner square- ctx.fillStyle = mergeOpacity(vm.labelColors[i].backgroundColor, opacity);- ctx.fillRect(pt.x + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);- ctx.fillStyle = textColor;- }+function abstract() {+ throw new Error(+ 'This method is not implemented: either no adapter can ' ++ 'be found or an incomplete integration was provided.'+ );+}- fillLineOfText(line);- });+/**+ * Date adapter (current used by the time scale)+ * @namespace Chart._adapters._date+ * @memberof Chart._adapters+ * @private+ */- helpers.each(bodyItem.after, fillLineOfText);- });+/**+ * Currently supported unit string values.+ * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}+ * @memberof Chart._adapters._date+ * @name Unit+ */- // Reset back to 0 for after body- xLinePadding = 0;+/**+ * @class+ */+function DateAdapter(options) {+ this.options = options || {};+}- // After body lines- helpers.each(vm.afterBody, fillLineOfText);- pt.y -= bodySpacing; // Remove last body spacing- },+helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ {+ /**+ * Returns a map of time formats for the supported formatting units defined+ * in Unit as well as 'datetime' representing a detailed date/time string.+ * @returns {{string: string}}+ */+ formats: abstract,- drawFooter: function(pt, vm, ctx, opacity) {- var footer = vm.footer;+ /**+ * Parses the given `value` and return the associated timestamp.+ * @param {any} value - the value to parse (usually comes from the data)+ * @param {string} [format] - the expected data format+ * @returns {(number|null)}+ * @function+ */+ parse: abstract,- if (footer.length) {- pt.y += vm.footerMarginTop;+ /**+ * Returns the formatted date in the specified `format` for a given `timestamp`.+ * @param {number} timestamp - the timestamp to format+ * @param {string} format - the date/time token+ * @return {string}+ * @function+ */+ format: abstract,- ctx.textAlign = vm._footerAlign;- ctx.textBaseline = 'top';+ /**+ * Adds the specified `amount` of `unit` to the given `timestamp`.+ * @param {number} timestamp - the input timestamp+ * @param {number} amount - the amount to add+ * @param {Unit} unit - the unit as string+ * @return {number}+ * @function+ */+ add: abstract,- ctx.fillStyle = mergeOpacity(vm.footerFontColor, opacity);- ctx.font = helpers.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily);+ /**+ * Returns the number of `unit` between the given timestamps.+ * @param {number} max - the input timestamp (reference)+ * @param {number} min - the timestamp to substract+ * @param {Unit} unit - the unit as string+ * @return {number}+ * @function+ */+ diff: abstract,- helpers.each(footer, function(line) {- ctx.fillText(line, pt.x, pt.y);- pt.y += vm.footerFontSize + vm.footerSpacing;- });- }- },+ /**+ * Returns start of `unit` for the given `timestamp`.+ * @param {number} timestamp - the input timestamp+ * @param {Unit} unit - the unit as string+ * @param {number} [weekday] - the ISO day of the week with 1 being Monday+ * and 7 being Sunday (only needed if param *unit* is `isoWeek`).+ * @function+ */+ startOf: abstract,- drawBackground: function(pt, vm, ctx, tooltipSize, opacity) {- ctx.fillStyle = mergeOpacity(vm.backgroundColor, opacity);- ctx.strokeStyle = mergeOpacity(vm.borderColor, opacity);- ctx.lineWidth = vm.borderWidth;- var xAlign = vm.xAlign;- var yAlign = vm.yAlign;- var x = pt.x;- var y = pt.y;- var width = tooltipSize.width;- var height = tooltipSize.height;- var radius = vm.cornerRadius;+ /**+ * Returns end of `unit` for the given `timestamp`.+ * @param {number} timestamp - the input timestamp+ * @param {Unit} unit - the unit as string+ * @function+ */+ endOf: abstract,- ctx.beginPath();- ctx.moveTo(x + radius, y);- if (yAlign === 'top') {- this.drawCaret(pt, tooltipSize);- }- ctx.lineTo(x + width - radius, y);- ctx.quadraticCurveTo(x + width, y, x + width, y + radius);- if (yAlign === 'center' && xAlign === 'right') {- this.drawCaret(pt, tooltipSize);- }- ctx.lineTo(x + width, y + height - radius);- ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);- if (yAlign === 'bottom') {- this.drawCaret(pt, tooltipSize);- }- ctx.lineTo(x + radius, y + height);- ctx.quadraticCurveTo(x, y + height, x, y + height - radius);- if (yAlign === 'center' && xAlign === 'left') {- this.drawCaret(pt, tooltipSize);- }- ctx.lineTo(x, y + radius);- ctx.quadraticCurveTo(x, y, x + radius, y);- ctx.closePath();+ // DEPRECATIONS- ctx.fill();+ /**+ * Provided for backward compatibility for scale.getValueForPixel(),+ * this method should be overridden only by the moment adapter.+ * @deprecated since version 2.8.0+ * @todo remove at version 3+ * @private+ */+ _create: function(value) {+ return value;+ }+});- if (vm.borderWidth > 0) {- ctx.stroke();- }- },+DateAdapter.override = function(members) {+ helpers$1.extend(DateAdapter.prototype, members);+};- draw: function() {- var ctx = this._chart.ctx;- var vm = this._view;+var _date = DateAdapter;- if (vm.opacity === 0) {- return;- }+var core_adapters = {+ _date: _date+};- var tooltipSize = {- width: vm.width,- height: vm.height- };- var pt = {- x: vm.x,- y: vm.y- };+/**+ * Namespace to hold static tick generation functions+ * @namespace Chart.Ticks+ */+var core_ticks = {+ /**+ * Namespace to hold formatters for different types of ticks+ * @namespace Chart.Ticks.formatters+ */+ formatters: {+ /**+ * Formatter for value labels+ * @method Chart.Ticks.formatters.values+ * @param value the value to display+ * @return {string|string[]} the label to display+ */+ values: function(value) {+ return helpers$1.isArray(value) ? value : '' + value;+ },- // IE11/Edge does not like very small opacities, so snap to 0- var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;+ /**+ * Formatter for linear numeric ticks+ * @method Chart.Ticks.formatters.linear+ * @param tickValue {number} the value to be formatted+ * @param index {number} the position of the tickValue parameter in the ticks array+ * @param ticks {number[]} the list of ticks being converted+ * @return {string} string representation of the tickValue parameter+ */+ linear: function(tickValue, index, ticks) {+ // If we have lots of ticks, don't use the ones+ var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];- // Truthy/falsey value for empty tooltip- var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;+ // If we have a number like 2.5 as the delta, figure out how many decimal places we need+ if (Math.abs(delta) > 1) {+ if (tickValue !== Math.floor(tickValue)) {+ // not an integer+ delta = tickValue - Math.floor(tickValue);+ }+ }- if (this._options.enabled && hasTooltipContent) {- // Draw Background- this.drawBackground(pt, vm, ctx, tooltipSize, opacity);+ var logDelta = helpers$1.log10(Math.abs(delta));+ var tickString = '';- // Draw Title, Body, and Footer- pt.x += vm.xPadding;- pt.y += vm.yPadding;+ if (tickValue !== 0) {+ var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));+ if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation+ var logTick = helpers$1.log10(Math.abs(tickValue));+ var numExponential = Math.floor(logTick) - Math.floor(logDelta);+ numExponential = Math.max(Math.min(numExponential, 20), 0);+ tickString = tickValue.toExponential(numExponential);+ } else {+ var numDecimal = -1 * Math.floor(logDelta);+ numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places+ tickString = tickValue.toFixed(numDecimal);+ }+ } else {+ tickString = '0'; // never show decimal places for 0+ }- // Titles- this.drawTitle(pt, vm, ctx, opacity);+ return tickString;+ },- // Body- this.drawBody(pt, vm, ctx, opacity);+ logarithmic: function(tickValue, index, ticks) {+ var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue))));- // Footer- this.drawFooter(pt, vm, ctx, opacity);+ if (tickValue === 0) {+ return '0';+ } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {+ return tickValue.toExponential();+ }+ return '';}- },-- /**- * Handle an event- * @private- * @param {IEvent} event - The event to handle- * @returns {Boolean} true if the tooltip changed- */- handleEvent: function(e) {- var me = this;- var options = me._options;- var changed = false;+ }+};- me._lastActive = me._lastActive || [];+var isArray = helpers$1.isArray;+var isNullOrUndef = helpers$1.isNullOrUndef;+var valueOrDefault$a = helpers$1.valueOrDefault;+var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault;- // Find Active Elements for tooltips- if (e.type === 'mouseout') {- me._active = [];- } else {- me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);- }+core_defaults._set('scale', {+ display: true,+ position: 'left',+ offset: false,- // Remember Last Actives- changed = !helpers.arrayEquals(me._active, me._lastActive);+ // grid line settings+ gridLines: {+ display: true,+ color: 'rgba(0,0,0,0.1)',+ lineWidth: 1,+ drawBorder: true,+ drawOnChartArea: true,+ drawTicks: true,+ tickMarkLength: 10,+ zeroLineWidth: 1,+ zeroLineColor: 'rgba(0,0,0,0.25)',+ zeroLineBorderDash: [],+ zeroLineBorderDashOffset: 0.0,+ offsetGridLines: false,+ borderDash: [],+ borderDashOffset: 0.0+ },- // Only handle target event on tooltip change- if (changed) {- me._lastActive = me._active;+ // scale label+ scaleLabel: {+ // display property+ display: false,- if (options.enabled || options.custom) {- me._eventPosition = {- x: e.x,- y: e.y- };+ // actual label+ labelString: '',- me.update(true);- me.pivot();- }+ // top/bottom padding+ padding: {+ top: 4,+ bottom: 4}+ },- return changed;+ // label settings+ ticks: {+ beginAtZero: false,+ minRotation: 0,+ maxRotation: 50,+ mirror: false,+ padding: 0,+ reverse: false,+ display: true,+ autoSkip: true,+ autoSkipPadding: 0,+ labelOffset: 0,+ // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.+ callback: core_ticks.formatters.values,+ minor: {},+ major: {}}});-/**- * @namespace Chart.Tooltip.positioners- */-exports.positioners = positioners;+/** Returns a new array containing numItems from arr */+function sample(arr, numItems) {+ var result = [];+ var increment = arr.length / numItems;+ var i = 0;+ var len = arr.length;+ for (; i < len; i += increment) {+ result.push(arr[Math.floor(i)]);+ }+ return result;+}-},{"26":26,"27":27,"46":46}],37:[function(require,module,exports){-'use strict';+function getPixelForGridLine(scale, index, offsetGridLines) {+ var length = scale.getTicks().length;+ var validIndex = Math.min(index, length - 1);+ var lineValue = scale.getPixelForTick(validIndex);+ var start = scale._startPixel;+ var end = scale._endPixel;+ var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.+ var offset;-var defaults = require(26);-var Element = require(27);-var helpers = require(46);+ if (offsetGridLines) {+ if (length === 1) {+ offset = Math.max(lineValue - start, end - lineValue);+ } else if (index === 0) {+ offset = (scale.getPixelForTick(1) - lineValue) / 2;+ } else {+ offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;+ }+ lineValue += validIndex < index ? offset : -offset;-defaults._set('global', {- elements: {- arc: {- backgroundColor: defaults.global.defaultColor,- borderColor: '#fff',- borderWidth: 2+ // Return undefined if the pixel is out of the range+ if (lineValue < start - epsilon || lineValue > end + epsilon) {+ return;}}-});--module.exports = Element.extend({- inLabelRange: function(mouseX) {- var vm = this._view;+ return lineValue;+}- if (vm) {- return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));+function garbageCollect(caches, length) {+ helpers$1.each(caches, function(cache) {+ var gc = cache.gc;+ var gcLen = gc.length / 2;+ var i;+ if (gcLen > length) {+ for (i = 0; i < gcLen; ++i) {+ delete cache.data[gc[i]];+ }+ gc.splice(0, gcLen);}- return false;- },-- inRange: function(chartX, chartY) {- var vm = this._view;-- if (vm) {- var pointRelativePosition = helpers.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;+/**+ * Returns {width, height, offset} objects for the first, last, widest, highest tick+ * labels where offset indicates the anchor point offset from the top in pixels.+ */+function computeLabelSizes(ctx, tickFonts, ticks, caches) {+ var length = ticks.length;+ var widths = [];+ var heights = [];+ var offsets = [];+ var i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel, widest, highest;++ for (i = 0; i < length; ++i) {+ label = ticks[i].label;+ tickFont = ticks[i].major ? tickFonts.major : tickFonts.minor;+ ctx.font = fontString = tickFont.string;+ cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};+ lineHeight = tickFont.lineHeight;+ width = height = 0;+ // Undefined labels and arrays should not be measured+ if (!isNullOrUndef(label) && !isArray(label)) {+ width = helpers$1.measureText(ctx, cache.data, cache.gc, width, label);+ height = lineHeight;+ } else if (isArray(label)) {+ // if it is an array let's measure each element+ for (j = 0, jlen = label.length; j < jlen; ++j) {+ nestedLabel = label[j];+ // Undefined labels and arrays should not be measured+ if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {+ width = helpers$1.measureText(ctx, cache.data, cache.gc, width, nestedLabel);+ height += lineHeight;+ }}-- // 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;- },+ widths.push(width);+ heights.push(height);+ offsets.push(lineHeight / 2);+ }+ garbageCollect(caches, length);- getCenterPoint: function() {- var vm = this._view;- var halfAngle = (vm.startAngle + vm.endAngle) / 2;- var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;+ widest = widths.indexOf(Math.max.apply(null, widths));+ highest = heights.indexOf(Math.max.apply(null, heights));++ function valueAt(idx) {return {- x: vm.x + Math.cos(halfAngle) * halfRadius,- y: vm.y + Math.sin(halfAngle) * halfRadius+ width: widths[idx] || 0,+ height: heights[idx] || 0,+ offset: offsets[idx] || 0};- },+ }- 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));- },+ return {+ first: valueAt(0),+ last: valueAt(length - 1),+ widest: valueAt(widest),+ highest: valueAt(highest)+ };+}- tooltipPosition: function() {- var vm = this._view;- var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);- var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;+function getTickMarkLength(options) {+ return options.drawTicks ? options.tickMarkLength : 0;+}- return {- x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),- y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)- };- },+function getScaleLabelHeight(options) {+ var font, padding;- draw: function() {- var ctx = this._chart.ctx;- var vm = this._view;- var sA = vm.startAngle;- var eA = vm.endAngle;+ if (!options.display) {+ return 0;+ }- ctx.beginPath();+ font = helpers$1.options._parseFont(options);+ padding = helpers$1.options.toPadding(options.padding);- ctx.arc(vm.x, vm.y, vm.outerRadius, sA, eA);- ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);+ return font.lineHeight + padding.height;+}- ctx.closePath();- ctx.strokeStyle = vm.borderColor;- ctx.lineWidth = vm.borderWidth;+function parseFontOptions(options, nestedOpts) {+ return helpers$1.extend(helpers$1.options._parseFont({+ fontFamily: valueOrDefault$a(nestedOpts.fontFamily, options.fontFamily),+ fontSize: valueOrDefault$a(nestedOpts.fontSize, options.fontSize),+ fontStyle: valueOrDefault$a(nestedOpts.fontStyle, options.fontStyle),+ lineHeight: valueOrDefault$a(nestedOpts.lineHeight, options.lineHeight)+ }), {+ color: helpers$1.options.resolve([nestedOpts.fontColor, options.fontColor, core_defaults.global.defaultFontColor])+ });+}- ctx.fillStyle = vm.backgroundColor;+function parseTickFontOptions(options) {+ var minor = parseFontOptions(options, options.minor);+ var major = options.major.enabled ? parseFontOptions(options, options.major) : minor;- ctx.fill();- ctx.lineJoin = 'bevel';+ return {minor: minor, major: major};+}- if (vm.borderWidth) {- ctx.stroke();+function nonSkipped(ticksToFilter) {+ var filtered = [];+ var item, index, len;+ for (index = 0, len = ticksToFilter.length; index < len; ++index) {+ item = ticksToFilter[index];+ if (typeof item._index !== 'undefined') {+ filtered.push(item);}}-});--},{"26":26,"27":27,"46":46}],38:[function(require,module,exports){-'use strict';--var defaults = require(26);-var Element = require(27);-var helpers = require(46);+ return filtered;+}-var globalDefaults = defaults.global;+function getEvenSpacing(arr) {+ var len = arr.length;+ var i, diff;-defaults._set('global', {- elements: {- line: {- tension: 0.4,- backgroundColor: globalDefaults.defaultColor,- borderWidth: 3,- borderColor: globalDefaults.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- }+ if (len < 2) {+ return false;}-});-module.exports = 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 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]);+ for (diff = arr[0], i = 1; i < len; ++i) {+ if (arr[i] - arr[i - 1] !== diff) {+ return false;}+ }+ return diff;+}- ctx.save();+function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {+ var evenMajorSpacing = getEvenSpacing(majorIndices);+ var spacing = (ticks.length - 1) / ticksLimit;+ var factors, factor, i, ilen;- // Stroke Line Options- ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;+ // If the major ticks are evenly spaced apart, place the minor ticks+ // so that they divide the major ticks into even chunks+ if (!evenMajorSpacing) {+ return Math.max(spacing, 1);+ }- // IE 9 and 10 do not support line dash- if (ctx.setLineDash) {- ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);+ factors = helpers$1.math._factorize(evenMajorSpacing);+ for (i = 0, ilen = factors.length - 1; i < ilen; i++) {+ factor = factors[i];+ if (factor > spacing) {+ return factor;}+ }+ return Math.max(spacing, 1);+}- ctx.lineDashOffset = vm.borderDashOffset || globalOptionLineElements.borderDashOffset;- ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;- ctx.lineWidth = 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.previousItem(points, index);- currentVM = current._view;+function getMajorIndices(ticks) {+ var result = [];+ var i, ilen;+ for (i = 0, ilen = ticks.length; i < ilen; i++) {+ if (ticks[i].major) {+ result.push(i);+ }+ }+ return result;+}- // 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];+function skipMajors(ticks, majorIndices, spacing) {+ var count = 0;+ var next = majorIndices[0];+ var i, tick;- 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.canvas.lineTo(ctx, previous._view, current._view);- }- lastDrawnIndex = index;- }- }+ spacing = Math.ceil(spacing);+ for (i = 0; i < ticks.length; i++) {+ tick = ticks[i];+ if (i === next) {+ tick._index = i;+ count++;+ next = majorIndices[count * spacing];+ } else {+ delete tick.label;}-- ctx.stroke();- ctx.restore();}-});+}-},{"26":26,"27":27,"46":46}],39:[function(require,module,exports){-'use strict';+function skip(ticks, spacing, majorStart, majorEnd) {+ var start = valueOrDefault$a(majorStart, 0);+ var end = Math.min(valueOrDefault$a(majorEnd, ticks.length), ticks.length);+ var count = 0;+ var length, i, tick, next;-var defaults = require(26);-var Element = require(27);-var helpers = require(46);+ spacing = Math.ceil(spacing);+ if (majorEnd) {+ length = majorEnd - majorStart;+ spacing = length / Math.floor(length / spacing);+ }-var defaultColor = defaults.global.defaultColor;+ next = start;-defaults._set('global', {- elements: {- point: {- radius: 3,- pointStyle: 'circle',- backgroundColor: defaultColor,- borderColor: defaultColor,- borderWidth: 1,- // Hover- hitRadius: 1,- hoverRadius: 4,- hoverBorderWidth: 1- }+ while (next < 0) {+ count++;+ next = Math.round(start + count * spacing);}-});-function xRange(mouseX) {- var vm = this._view;- return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;+ for (i = Math.max(start, 0); i < end; i++) {+ tick = ticks[i];+ if (i === next) {+ tick._index = i;+ count++;+ next = Math.round(start + count * spacing);+ } else {+ delete tick.label;+ }+ }}-function yRange(mouseY) {- var vm = this._view;- return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;-}+var Scale = core_element.extend({-module.exports = 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;+ zeroLineIndex: 0,++ /**+ * Get the padding needed for the scale+ * @method getPadding+ * @private+ * @returns {Padding} the necessary padding+ */+ getPadding: function() {+ var me = this;+ return {+ left: me.paddingLeft || 0,+ top: me.paddingTop || 0,+ right: me.paddingRight || 0,+ bottom: me.paddingBottom || 0+ };+ },++ /**+ * Returns the scale tick objects ({label, major})+ * @since 2.7+ */+ getTicks: function() {+ return this._ticks;},- inLabelRange: xRange,- inXRange: xRange,- inYRange: yRange,-- getCenterPoint: function() {- var vm = this._view;- return {- x: vm.x,- y: vm.y- };+ /**+ * @private+ */+ _getLabels: function() {+ var data = this.chart.data;+ return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];},- getArea: function() {- return Math.PI * Math.pow(this._view.radius, 2);+ // These methods are ordered by lifecyle. Utilities then follow.+ // Any function defined here is inherited by all scale types.+ // Any function can be extended by the scale type++ /**+ * Provided for backward compatibility, not available anymore+ * @function Chart.Scale.mergeTicksOptions+ * @deprecated since version 2.8.0+ * @todo remove at version 3+ */+ mergeTicksOptions: function() {+ // noop},- tooltipPosition: function() {- var vm = this._view;- return {- x: vm.x,- y: vm.y,- padding: vm.radius + vm.borderWidth- };+ beforeUpdate: function() {+ helpers$1.callback(this.options.beforeUpdate, [this]);},- draw: function(chartArea) {- var vm = this._view;- var model = this._model;- 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 errMargin = 1.01; // 1.01 is margin for Accumulated error. (Especially Edge, IE.)+ /**+ * @param {number} maxWidth - the max width in pixels+ * @param {number} maxHeight - the max height in pixels+ * @param {object} margins - the space between the edge of the other scales and edge of the chart+ * This space comes from two sources:+ * - padding - space that's required to show the labels at the edges of the scale+ * - thickness of scales or legends in another orientation+ */+ update: function(maxWidth, maxHeight, margins) {+ var me = this;+ var tickOpts = me.options.ticks;+ var sampleSize = tickOpts.sampleSize;+ var i, ilen, labels, ticks, samplingEnabled;- if (vm.skip) {- return;- }+ // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)+ me.beforeUpdate();- // Clipping for Points.- if (chartArea === undefined || (model.x >= chartArea.left && chartArea.right * errMargin >= model.x && model.y >= chartArea.top && chartArea.bottom * errMargin >= model.y)) {- ctx.strokeStyle = vm.borderColor || defaultColor;- ctx.lineWidth = helpers.valueOrDefault(vm.borderWidth, defaults.global.elements.point.borderWidth);- ctx.fillStyle = vm.backgroundColor || defaultColor;- helpers.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);- }- }-});+ // Absorb the master measurements+ me.maxWidth = maxWidth;+ me.maxHeight = maxHeight;+ me.margins = helpers$1.extend({+ left: 0,+ right: 0,+ top: 0,+ bottom: 0+ }, margins);++ me._ticks = null;+ me.ticks = null;+ me._labelSizes = null;+ me._maxLabelLines = 0;+ me.longestLabelWidth = 0;+ me.longestTextCache = me.longestTextCache || {};+ me._gridLineItems = null;+ me._labelItems = null;-},{"26":26,"27":27,"46":46}],40:[function(require,module,exports){-'use strict';+ // Dimensions+ me.beforeSetDimensions();+ me.setDimensions();+ me.afterSetDimensions();-var defaults = require(26);-var Element = require(27);+ // Data min/max+ me.beforeDataLimits();+ me.determineDataLimits();+ me.afterDataLimits();-defaults._set('global', {- elements: {- rectangle: {- backgroundColor: defaults.global.defaultColor,- borderColor: defaults.global.defaultColor,- borderSkipped: 'bottom',- borderWidth: 0- }- }-});+ // Ticks - `this.ticks` is now DEPRECATED!+ // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member+ // and must not be accessed directly from outside this class. `this.ticks` being+ // around for long time and not marked as private, we can't change its structure+ // without unexpected breaking changes. If you need to access the scale ticks,+ // use scale.getTicks() instead.-function isVertical(bar) {- return bar._view.width !== undefined;-}+ me.beforeBuildTicks();-/**- * 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(bar) {- var vm = bar._view;- var x1, x2, y1, y2;-- if (isVertical(bar)) {- // vertical- var halfWidth = vm.width / 2;- x1 = vm.x - halfWidth;- x2 = vm.x + halfWidth;- y1 = Math.min(vm.y, vm.base);- y2 = Math.max(vm.y, vm.base);- } else {- // horizontal bar- var halfHeight = vm.height / 2;- x1 = Math.min(vm.x, vm.base);- x2 = Math.max(vm.x, vm.base);- y1 = vm.y - halfHeight;- y2 = vm.y + halfHeight;- }+ // New implementations should return an array of objects but for BACKWARD COMPAT,+ // we still support no return (`this.ticks` internally set by calling this method).+ ticks = me.buildTicks() || [];- return {- left: x1,- top: y1,- right: x2,- bottom: y2- };-}+ // Allow modification of ticks in callback.+ ticks = me.afterBuildTicks(ticks) || ticks;-module.exports = Element.extend({- draw: function() {- var ctx = this._chart.ctx;- var vm = this._view;- var left, right, top, bottom, signX, signY, borderSkipped;- var borderWidth = vm.borderWidth;-- if (!vm.horizontal) {- // bar- left = vm.x - vm.width / 2;- right = vm.x + vm.width / 2;- top = vm.y;- bottom = vm.base;- signX = 1;- signY = bottom > top ? 1 : -1;- borderSkipped = vm.borderSkipped || 'bottom';- } else {- // horizontal bar- left = vm.base;- right = vm.x;- top = vm.y - vm.height / 2;- bottom = vm.y + vm.height / 2;- signX = right > left ? 1 : -1;- signY = 1;- borderSkipped = vm.borderSkipped || 'left';- }-- // Canvas doesn't allow us to stroke inside the width so we can- // adjust the sizes to fit if we're setting a stroke on the line- if (borderWidth) {- // borderWidth shold be less than bar width and bar height.- var barSize = Math.min(Math.abs(left - right), Math.abs(top - bottom));- borderWidth = borderWidth > barSize ? barSize : borderWidth;- var halfStroke = borderWidth / 2;- // Adjust borderWidth when bar top position is near vm.base(zero).- var borderLeft = left + (borderSkipped !== 'left' ? halfStroke * signX : 0);- var borderRight = right + (borderSkipped !== 'right' ? -halfStroke * signX : 0);- var borderTop = top + (borderSkipped !== 'top' ? halfStroke * signY : 0);- var borderBottom = bottom + (borderSkipped !== 'bottom' ? -halfStroke * signY : 0);- // not become a vertical line?- if (borderLeft !== borderRight) {- top = borderTop;- bottom = borderBottom;- }- // not become a horizontal line?- if (borderTop !== borderBottom) {- left = borderLeft;- right = borderRight;+ // Ensure ticks contains ticks in new tick format+ if ((!ticks || !ticks.length) && me.ticks) {+ ticks = [];+ for (i = 0, ilen = me.ticks.length; i < ilen; ++i) {+ ticks.push({+ value: me.ticks[i],+ major: false+ });}}- ctx.beginPath();- ctx.fillStyle = vm.backgroundColor;- ctx.strokeStyle = vm.borderColor;- ctx.lineWidth = borderWidth;-- // Corner points, from bottom-left to bottom-right clockwise- // | 1 2 |- // | 0 3 |- var corners = [- [left, bottom],- [left, top],- [right, top],- [right, bottom]- ];+ me._ticks = ticks;- // Find first (starting) corner with fallback to 'bottom'- var borders = ['bottom', 'left', 'top', 'right'];- var startCorner = borders.indexOf(borderSkipped, 0);- if (startCorner === -1) {- startCorner = 0;- }+ // Compute tick rotation and fit using a sampled subset of labels+ // We generally don't need to compute the size of every single label for determining scale size+ samplingEnabled = sampleSize < ticks.length;+ labels = me._convertTicksToLabels(samplingEnabled ? sample(ticks, sampleSize) : ticks);- function cornerAt(index) {- return corners[(startCorner + index) % 4];- }+ // _configure is called twice, once here, once from core.controller.updateLayout.+ // Here we haven't been positioned yet, but dimensions are correct.+ // Variables set in _configure are needed for calculateTickRotation, and+ // it's ok that coordinates are not correct there, only dimensions matter.+ me._configure();- // Draw rectangle from 'startCorner'- var corner = cornerAt(0);- ctx.moveTo(corner[0], corner[1]);+ // Tick Rotation+ me.beforeCalculateTickRotation();+ me.calculateTickRotation();+ me.afterCalculateTickRotation();- for (var i = 1; i < 4; i++) {- corner = cornerAt(i);- ctx.lineTo(corner[0], corner[1]);- }+ me.beforeFit();+ me.fit();+ me.afterFit();- ctx.fill();- if (borderWidth) {- ctx.stroke();+ // Auto-skip+ me._ticksToDraw = tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto') ? me._autoSkip(ticks) : ticks;++ if (samplingEnabled) {+ // Generate labels using all non-skipped ticks+ labels = me._convertTicksToLabels(me._ticksToDraw);}- },- height: function() {- var vm = this._view;- return vm.base - vm.y;- },+ me.ticks = labels; // BACKWARD COMPATIBILITY- inRange: function(mouseX, mouseY) {- var inRange = false;+ // IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!- if (this._view) {- var bounds = getBarBounds(this);- inRange = mouseX >= bounds.left && mouseX <= bounds.right && mouseY >= bounds.top && mouseY <= bounds.bottom;- }+ me.afterUpdate();- return inRange;+ // TODO(v3): remove minSize as a public property and return value from all layout boxes. It is unused+ // make maxWidth and maxHeight private+ return me.minSize;},- inLabelRange: function(mouseX, mouseY) {+ /**+ * @private+ */+ _configure: function() {var me = this;- if (!me._view) {- return false;- }+ var reversePixels = me.options.ticks.reverse;+ var startPixel, endPixel;- var inRange = false;- var bounds = getBarBounds(me);-- if (isVertical(me)) {- inRange = mouseX >= bounds.left && mouseX <= bounds.right;+ if (me.isHorizontal()) {+ startPixel = me.left;+ endPixel = me.right;} else {- inRange = mouseY >= bounds.top && mouseY <= bounds.bottom;+ startPixel = me.top;+ endPixel = me.bottom;+ // by default vertical scales are from bottom to top, so pixels are reversed+ reversePixels = !reversePixels;}-- return inRange;+ me._startPixel = startPixel;+ me._endPixel = endPixel;+ me._reversePixels = reversePixels;+ me._length = endPixel - startPixel;},- inXRange: function(mouseX) {- var bounds = getBarBounds(this);- return mouseX >= bounds.left && mouseX <= bounds.right;+ afterUpdate: function() {+ helpers$1.callback(this.options.afterUpdate, [this]);},- inYRange: function(mouseY) {- var bounds = getBarBounds(this);- return mouseY >= bounds.top && mouseY <= bounds.bottom;- },+ //- getCenterPoint: function() {- var vm = this._view;- var x, y;- if (isVertical(this)) {- x = vm.x;- y = (vm.y + vm.base) / 2;+ beforeSetDimensions: function() {+ helpers$1.callback(this.options.beforeSetDimensions, [this]);+ },+ 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 {- x = (vm.x + vm.base) / 2;- y = vm.y;+ me.height = me.maxHeight;++ // Reset position before calculating rotation+ me.top = 0;+ me.bottom = me.height;}- return {x: x, y: y};+ // Reset padding+ me.paddingLeft = 0;+ me.paddingTop = 0;+ me.paddingRight = 0;+ me.paddingBottom = 0;},-- getArea: function() {- var vm = this._view;- return vm.width * Math.abs(vm.y - vm.base);+ afterSetDimensions: function() {+ helpers$1.callback(this.options.afterSetDimensions, [this]);},- tooltipPosition: function() {- var vm = this._view;- return {- x: vm.x,- y: vm.y- };- }-});--},{"26":26,"27":27}],41:[function(require,module,exports){-'use strict';--module.exports = {};-module.exports.Arc = require(37);-module.exports.Line = require(38);-module.exports.Point = require(39);-module.exports.Rectangle = require(40);--},{"37":37,"38":38,"39":39,"40":40}],42:[function(require,module,exports){-'use strict';--var helpers = require(43);--/**- * @namespace Chart.helpers.canvas- */-var exports = module.exports = {- /**- * 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);+ // Data limits+ beforeDataLimits: function() {+ helpers$1.callback(this.options.beforeDataLimits, [this]);+ },+ determineDataLimits: helpers$1.noop,+ afterDataLimits: function() {+ helpers$1.callback(this.options.afterDataLimits, [this]);},- /**- * 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) {- // NOTE(SB) `epsilon` helps to prevent minor artifacts appearing- // on Chrome when `r` is exactly half the height or the width.- var epsilon = 0.0000001;- var r = Math.min(radius, (height / 2) - epsilon, (width / 2) - epsilon);-- ctx.moveTo(x + r, y);- ctx.lineTo(x + width - r, y);- ctx.arcTo(x + width, y, x + width, y + r, r);- ctx.lineTo(x + width, y + height - r);- ctx.arcTo(x + width, y + height, x + width - r, y + height, r);- ctx.lineTo(x + r, y + height);- ctx.arcTo(x, y + height, x, y + height - r, r);- ctx.lineTo(x, y + r);- ctx.arcTo(x, y, x + r, y, r);- ctx.closePath();- ctx.moveTo(x, y);- } else {- ctx.rect(x, y, width, height);+ //+ beforeBuildTicks: function() {+ helpers$1.callback(this.options.beforeBuildTicks, [this]);+ },+ buildTicks: helpers$1.noop,+ afterBuildTicks: function(ticks) {+ var me = this;+ // ticks is empty for old axis implementations here+ if (isArray(ticks) && ticks.length) {+ return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]);}+ // Support old implementations (that modified `this.ticks` directly in buildTicks)+ me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;+ return ticks;},- drawPoint: function(ctx, style, radius, x, y, rotation) {- var type, edgeLength, xOffset, yOffset, height, size;- rotation = rotation || 0;+ beforeTickToLabelConversion: function() {+ helpers$1.callback(this.options.beforeTickToLabelConversion, [this]);+ },+ convertTicksToLabels: function() {+ var me = this;+ // Convert ticks to strings+ var tickOpts = me.options.ticks;+ me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);+ },+ afterTickToLabelConversion: function() {+ helpers$1.callback(this.options.afterTickToLabelConversion, [this]);+ },- 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) {+ beforeCalculateTickRotation: function() {+ helpers$1.callback(this.options.beforeCalculateTickRotation, [this]);+ },+ calculateTickRotation: function() {+ var me = this;+ var options = me.options;+ var tickOpts = options.ticks;+ var numTicks = me.getTicks().length;+ var minRotation = tickOpts.minRotation || 0;+ var maxRotation = tickOpts.maxRotation;+ var labelRotation = minRotation;+ var labelSizes, maxLabelWidth, maxLabelHeight, maxWidth, tickWidth, maxHeight, maxLabelDiagonal;++ if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {+ me.labelRotation = minRotation;return;}- ctx.save();- ctx.translate(x, y);- ctx.rotate(rotation * Math.PI / 180);- ctx.beginPath();+ labelSizes = me._getLabelSizes();+ maxLabelWidth = labelSizes.widest.width;+ maxLabelHeight = labelSizes.highest.height - labelSizes.highest.offset;- switch (style) {- // Default includes circle- default:- ctx.arc(0, 0, radius, 0, Math.PI * 2);- ctx.closePath();- break;- case 'triangle':- edgeLength = 3 * radius / Math.sqrt(3);- height = edgeLength * Math.sqrt(3) / 2;- ctx.moveTo(-edgeLength / 2, height / 3);- ctx.lineTo(edgeLength / 2, height / 3);- ctx.lineTo(0, -2 * height / 3);- ctx.closePath();- break;- case 'rect':- size = 1 / Math.SQRT2 * radius;- ctx.rect(-size, -size, 2 * size, 2 * size);- break;- case 'rectRounded':- var offset = radius / Math.SQRT2;- var leftX = -offset;- var topY = -offset;- var sideSize = Math.SQRT2 * radius;-- // NOTE(SB) the rounded rect implementation changed to use `arcTo`- // instead of `quadraticCurveTo` since it generates better results- // when rect is almost a circle. 0.425 (instead of 0.5) produces- // results visually closer to the previous impl.- this.roundedRect(ctx, leftX, topY, sideSize, sideSize, radius * 0.425);- break;- case 'rectRot':- size = 1 / Math.SQRT2 * radius;- ctx.moveTo(-size, 0);- ctx.lineTo(0, size);- ctx.lineTo(size, 0);- ctx.lineTo(0, -size);- ctx.closePath();- break;- case 'cross':- ctx.moveTo(0, radius);- ctx.lineTo(0, -radius);- ctx.moveTo(-radius, 0);- ctx.lineTo(radius, 0);- break;- case 'crossRot':- xOffset = Math.cos(Math.PI / 4) * radius;- yOffset = Math.sin(Math.PI / 4) * radius;- ctx.moveTo(-xOffset, -yOffset);- ctx.lineTo(xOffset, yOffset);- ctx.moveTo(-xOffset, yOffset);- ctx.lineTo(xOffset, -yOffset);- break;- case 'star':- ctx.moveTo(0, radius);- ctx.lineTo(0, -radius);- ctx.moveTo(-radius, 0);- ctx.lineTo(radius, 0);- xOffset = Math.cos(Math.PI / 4) * radius;- yOffset = Math.sin(Math.PI / 4) * radius;- ctx.moveTo(-xOffset, -yOffset);- ctx.lineTo(xOffset, yOffset);- ctx.moveTo(-xOffset, yOffset);- ctx.lineTo(xOffset, -yOffset);- break;- case 'line':- ctx.moveTo(-radius, 0);- ctx.lineTo(radius, 0);- break;- case 'dash':- ctx.moveTo(0, 0);- ctx.lineTo(radius, 0);- break;+ // Estimate the width of each grid based on the canvas width, the maximum+ // label width and the number of tick intervals+ maxWidth = Math.min(me.maxWidth, me.chart.width - maxLabelWidth);+ tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);++ // Allow 3 pixels x2 padding either side for label readability+ if (maxLabelWidth + 6 > tickWidth) {+ tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));+ maxHeight = me.maxHeight - getTickMarkLength(options.gridLines)+ - tickOpts.padding - getScaleLabelHeight(options.scaleLabel);+ maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);+ labelRotation = helpers$1.toDegrees(Math.min(+ Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),+ Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)+ ));+ labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));}- ctx.fill();- ctx.stroke();- ctx.restore();+ me.labelRotation = labelRotation;},-- clipArea: function(ctx, area) {- ctx.save();- ctx.beginPath();- ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);- ctx.clip();+ afterCalculateTickRotation: function() {+ helpers$1.callback(this.options.afterCalculateTickRotation, [this]);},- unclipArea: function(ctx) {- ctx.restore();+ //++ beforeFit: function() {+ helpers$1.callback(this.options.beforeFit, [this]);},+ fit: function() {+ var me = this;+ // Reset+ var minSize = me.minSize = {+ width: 0,+ height: 0+ };- lineTo: function(ctx, previous, target, flip) {- if (target.steppedLine) {- if ((target.steppedLine === 'after' && !flip) || (target.steppedLine !== 'after' && flip)) {- ctx.lineTo(previous.x, target.y);- } else {- ctx.lineTo(target.x, previous.y);- }- ctx.lineTo(target.x, target.y);- return;- }+ var chart = me.chart;+ var opts = me.options;+ var tickOpts = opts.ticks;+ var scaleLabelOpts = opts.scaleLabel;+ var gridLineOpts = opts.gridLines;+ var display = me._isVisible();+ var isBottom = opts.position === 'bottom';+ var isHorizontal = me.isHorizontal();- if (!target.tension) {- ctx.lineTo(target.x, target.y);- return;+ // Width+ if (isHorizontal) {+ minSize.width = me.maxWidth;+ } else if (display) {+ minSize.width = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);}- 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);- }-};+ // height+ if (!isHorizontal) {+ minSize.height = me.maxHeight; // fill all the height+ } else if (display) {+ minSize.height = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);+ }-// DEPRECATIONS+ // Don't bother fitting the ticks if we are not showing the labels+ if (tickOpts.display && display) {+ var tickFonts = parseTickFontOptions(tickOpts);+ var labelSizes = me._getLabelSizes();+ var firstLabelSize = labelSizes.first;+ var lastLabelSize = labelSizes.last;+ var widestLabelSize = labelSizes.widest;+ var highestLabelSize = labelSizes.highest;+ var lineSpace = tickFonts.minor.lineHeight * 0.4;+ var tickPadding = tickOpts.padding;-/**- * 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.clear = exports.clear;+ if (isHorizontal) {+ // A horizontal axis is more constrained by the height.+ var isRotated = me.labelRotation !== 0;+ var angleRadians = helpers$1.toRadians(me.labelRotation);+ var cosRotation = Math.cos(angleRadians);+ var sinRotation = Math.sin(angleRadians);-/**- * 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.drawRoundedRectangle = function(ctx) {- ctx.beginPath();- exports.roundedRect.apply(exports, arguments);-};+ var labelHeight = sinRotation * widestLabelSize.width+ + cosRotation * (highestLabelSize.height - (isRotated ? highestLabelSize.offset : 0))+ + (isRotated ? 0 : lineSpace); // padding-},{"43":43}],43:[function(require,module,exports){-'use strict';+ minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);-/**- * @namespace Chart.helpers- */-var helpers = {- /**- * An empty function that can be used, for example, for optional callback.- */- noop: function() {},+ var offsetLeft = me.getPixelForTick(0) - me.left;+ var offsetRight = me.right - me.getPixelForTick(me.getTicks().length - 1);+ var paddingLeft, paddingRight;- /**- * Returns a unique id, sequentially generated from a global variable.- * @returns {Number}- * @function- */- uid: (function() {- var id = 0;- return function() {- return id++;- };- }()),+ // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned+ // which means that the right padding is dominated by the font height+ if (isRotated) {+ paddingLeft = isBottom ?+ cosRotation * firstLabelSize.width + sinRotation * firstLabelSize.offset :+ sinRotation * (firstLabelSize.height - firstLabelSize.offset);+ paddingRight = isBottom ?+ sinRotation * (lastLabelSize.height - lastLabelSize.offset) :+ cosRotation * lastLabelSize.width + sinRotation * lastLabelSize.offset;+ } else {+ paddingLeft = firstLabelSize.width / 2;+ paddingRight = lastLabelSize.width / 2;+ }- /**- * 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';- },+ // Adjust padding taking into account changes in offsets+ // and add 3 px to move away from canvas edges+ me.paddingLeft = Math.max((paddingLeft - offsetLeft) * me.width / (me.width - offsetLeft), 0) + 3;+ me.paddingRight = Math.max((paddingRight - offsetRight) * me.width / (me.width - offsetRight), 0) + 3;+ } else {+ // A vertical axis is more constrained by the width. Labels are the+ // dominant factor here, so get that length first and account for padding+ var labelWidth = tickOpts.mirror ? 0 :+ // use lineSpace for consistency with horizontal axis+ // tickPadding is not implemented for horizontal+ widestLabelSize.width + tickPadding + lineSpace;- /**- * Returns true if `value` is an array, else returns false.- * @param {*} value - The value to test.- * @returns {Boolean}- * @function- */- isArray: Array.isArray ? Array.isArray : function(value) {- return Object.prototype.toString.call(value) === '[object Array]';- },+ minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth);- /**- * 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]';- },+ me.paddingTop = firstLabelSize.height / 2;+ me.paddingBottom = lastLabelSize.height / 2;+ }+ }- /**- * 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;- },+ me.handleMargins();- /**- * 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);+ if (isHorizontal) {+ me.width = me._length = chart.width - me.margins.left - me.margins.right;+ me.height = minSize.height;+ } else {+ me.width = minSize.width;+ me.height = me._length = chart.height - me.margins.top - me.margins.bottom;+ }},/**- * 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 {*}+ * Handle margins and padding interactions+ * @private*/- callback: function(fn, args, thisArg) {- if (fn && typeof fn.call === 'function') {- return fn.apply(thisArg, args);+ handleMargins: function() {+ var me = this;+ if (me.margins) {+ me.margins.left = Math.max(me.paddingLeft, me.margins.left);+ me.margins.top = Math.max(me.paddingTop, me.margins.top);+ me.margins.right = Math.max(me.paddingRight, me.margins.right);+ me.margins.bottom = Math.max(me.paddingBottom, me.margins.bottom);}},- /**- * 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]);- }- }+ afterFit: function() {+ helpers$1.callback(this.options.afterFit, [this]);},- /**- * Returns true if the `a0` and `a1` arrays have the same content, else returns false.- * @see http://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;+ // Shared Methods+ isHorizontal: function() {+ var pos = this.options.position;+ return pos === 'top' || pos === 'bottom';+ },+ isFullWidth: function() {+ return this.options.fullWidth;+ },- if (!a0 || !a1 || a0.length !== a1.length) {- return false;+ // Get the correct value. NaN bad inputs, If the value type is object get the x or y based on whether we are horizontal or not+ getRightValue: function(rawValue) {+ // Null and undefined values first+ if (isNullOrUndef(rawValue)) {+ return NaN;+ }+ // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values+ if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {+ return NaN;}- 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;+ // If it is in fact an object, dive in one more level+ if (rawValue) {+ if (this.isHorizontal()) {+ if (rawValue.x !== undefined) {+ return this.getRightValue(rawValue.x);}- } else if (v0 !== v1) {- // NOTE: two different object instances will never be equal: {x:20} != {x:20}- return false;+ } else if (rawValue.y !== undefined) {+ return this.getRightValue(rawValue.y);}}- return true;+ // Value is good, return it+ return rawValue;},- /**- * 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);- }+ _convertTicksToLabels: function(ticks) {+ var me = this;+ var labels, i, ilen;- if (helpers.isObject(source)) {- var target = {};- var keys = Object.keys(source);- var klen = keys.length;- var k = 0;+ me.ticks = ticks.map(function(tick) {+ return tick.value;+ });- for (; k < klen; ++k) {- target[keys[k]] = helpers.clone(source[keys[k]]);- }+ me.beforeTickToLabelConversion();- return target;+ // New implementations should return the formatted tick labels but for BACKWARD+ // COMPAT, we still support no return (`this.ticks` internally changed by calling+ // this method and supposed to contain only string values).+ labels = me.convertTicksToLabels(ticks) || me.ticks;++ me.afterTickToLabelConversion();++ // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)+ for (i = 0, ilen = ticks.length; i < ilen; ++i) {+ ticks[i].label = labels[i];}- return source;+ return labels;},/**- * The default merger when Chart.helpers.merge is called without merger option.- * Note(SB): this method is also used by configMerge and scaleMerge as fallback.* @private*/- _merger: function(key, target, source, options) {- var tval = target[key];- var sval = source[key];+ _getLabelSizes: function() {+ var me = this;+ var labelSizes = me._labelSizes;- if (helpers.isObject(tval) && helpers.isObject(sval)) {- helpers.merge(tval, sval, options);- } else {- target[key] = helpers.clone(sval);+ if (!labelSizes) {+ me._labelSizes = labelSizes = computeLabelSizes(me.ctx, parseTickFontOptions(me.options.ticks), me.getTicks(), me.longestTextCache);+ me.longestLabelWidth = labelSizes.widest.width;}++ return labelSizes;},/**- * 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);+ _parseValue: function(value) {+ var start, end, min, max;++ if (isArray(value)) {+ start = +this.getRightValue(value[0]);+ end = +this.getRightValue(value[1]);+ min = Math.min(start, end);+ max = Math.max(start, end);+ } else {+ value = +this.getRightValue(value);+ start = undefined;+ end = value;+ min = value;+ max = value;}++ return {+ min: min,+ max: max,+ start: start,+ end: end+ };},/**- * 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|Array(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;+ * @private+ */+ _getScaleLabel: function(rawValue) {+ var v = this._parseValue(rawValue);+ if (v.start !== undefined) {+ return '[' + v.start + ', ' + v.end + ']';}- options = options || {};- merge = options.merger || helpers._merger;-- for (i = 0; i < ilen; ++i) {- source = sources[i];- if (!helpers.isObject(source)) {- continue;- }+ return +this.getRightValue(rawValue);+ },- keys = Object.keys(source);- for (k = 0, klen = keys.length; k < klen; ++k) {- merge(keys[k], target, source, options);- }- }+ /**+ * Used to get the value to display in the tooltip for the data at the given index+ * @param index+ * @param datasetIndex+ */+ getLabelForIndex: helpers$1.noop,- return target;- },+ /**+ * Returns the location of the given data point. Value can either be an index or a numerical value+ * The coordinate (0, 0) is at the upper-left corner of the canvas+ * @param value+ * @param index+ * @param datasetIndex+ */+ getPixelForValue: helpers$1.noop,/**- * 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|Array(Object)} source - Object(s) to merge into `target`.- * @returns {Object} The `target` object.+ * Used to get the data value from a given pixel. This is the inverse of getPixelForValue+ * The coordinate (0, 0) is at the upper-left corner of the canvas+ * @param pixel*/- mergeIf: function(target, source) {- return helpers.merge(target, source, {merger: helpers._mergerIf});- },+ getValueForPixel: helpers$1.noop,/**- * 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;+ * Returns the location of the tick at the given index+ * The coordinate (0, 0) is at the upper-left corner of the canvas+ */+ getPixelForTick: function(index) {+ var me = this;+ var offset = me.options.offset;+ var numTicks = me._ticks.length;+ var tickWidth = 1 / Math.max(numTicks - (offset ? 0 : 1), 1);++ return index < 0 || index > numTicks - 1+ ? null+ : me.getPixelForDecimal(index * tickWidth + (offset ? tickWidth / 2 : 0));},/**- * Basic javascript inheritance based on the model created in Backbone.js+ * Utility for getting the pixel location of a percentage of scale+ * The coordinate (0, 0) is at the upper-left corner of the canvas*/- inherits: function(extensions) {+ getPixelForDecimal: function(decimal) {var me = this;- var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {- return me.apply(this, arguments);- };- var Surrogate = function() {- this.constructor = ChartElement;- };+ if (me._reversePixels) {+ decimal = 1 - decimal;+ }- Surrogate.prototype = me.prototype;- ChartElement.prototype = new Surrogate();- ChartElement.extend = helpers.inherits;+ return me._startPixel + decimal * me._length;+ },- if (extensions) {- helpers.extend(ChartElement.prototype, extensions);- }+ getDecimalForPixel: function(pixel) {+ var decimal = (pixel - this._startPixel) / this._length;+ return this._reversePixels ? 1 - decimal : decimal;+ },- ChartElement.__super__ = me.prototype;- return ChartElement;- }-};+ /**+ * Returns the pixel for the minimum chart value+ * The coordinate (0, 0) is at the upper-left corner of the canvas+ */+ getBasePixel: function() {+ return this.getPixelForValue(this.getBaseValue());+ },-module.exports = helpers;+ getBaseValue: function() {+ var me = this;+ var min = me.min;+ var max = me.max;-// DEPRECATIONS+ return me.beginAtZero ? 0 :+ min < 0 && max < 0 ? max :+ min > 0 && max > 0 ? min :+ 0;+ },-/**- * 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;+ /**+ * Returns a subset of ticks to be plotted to avoid overlapping labels.+ * @private+ */+ _autoSkip: function(ticks) {+ var me = this;+ var tickOpts = me.options.ticks;+ var axisLength = me._length;+ var ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize() + 1;+ var majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];+ var numMajorIndices = majorIndices.length;+ var first = majorIndices[0];+ var last = majorIndices[numMajorIndices - 1];+ var i, ilen, spacing, avgMajorSpacing;-/**- * 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);-};+ // If there are too many major ticks to display them all+ if (numMajorIndices > ticksLimit) {+ skipMajors(ticks, majorIndices, numMajorIndices / ticksLimit);+ return nonSkipped(ticks);+ }-/**- * 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;+ spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit);-/**- * 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;+ if (numMajorIndices > 0) {+ for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {+ skip(ticks, spacing, majorIndices[i], majorIndices[i + 1]);+ }+ avgMajorSpacing = numMajorIndices > 1 ? (last - first) / (numMajorIndices - 1) : null;+ skip(ticks, spacing, helpers$1.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);+ skip(ticks, spacing, last, helpers$1.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);+ return nonSkipped(ticks);+ }+ skip(ticks, spacing);+ return nonSkipped(ticks);+ },-},{}],44:[function(require,module,exports){-'use strict';+ /**+ * @private+ */+ _tickSize: function() {+ var me = this;+ var optionTicks = me.options.ticks;-var helpers = require(43);+ // Calculate space needed by label in axis direction.+ var rot = helpers$1.toRadians(me.labelRotation);+ var cos = Math.abs(Math.cos(rot));+ var sin = Math.abs(Math.sin(rot));-/**- * 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;- },+ var labelSizes = me._getLabelSizes();+ var padding = optionTicks.autoSkipPadding || 0;+ var w = labelSizes ? labelSizes.widest.width + padding : 0;+ var h = labelSizes ? labelSizes.highest.height + padding : 0;- easeInQuad: function(t) {- return t * t;+ // Calculate space needed for 1 tick in axis direction.+ return me.isHorizontal()+ ? h * cos > w * sin ? w / cos : h / sin+ : h * sin < w * cos ? h / cos : w / sin;},- easeOutQuad: function(t) {- return -t * (t - 2);- },+ /**+ * @private+ */+ _isVisible: function() {+ var me = this;+ var chart = me.chart;+ var display = me.options.display;+ var i, ilen, meta;- easeInOutQuad: function(t) {- if ((t /= 0.5) < 1) {- return 0.5 * t * t;+ if (display !== 'auto') {+ return !!display;}- return -0.5 * ((--t) * (t - 2) - 1);- },- easeInCubic: function(t) {- return t * t * t;- },+ // When 'auto', the scale is visible if at least one associated dataset is visible.+ for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {+ if (chart.isDatasetVisible(i)) {+ meta = chart.getDatasetMeta(i);+ if (meta.xAxisID === me.id || meta.yAxisID === me.id) {+ return true;+ }+ }+ }- easeOutCubic: function(t) {- return (t = t - 1) * t * t + 1;+ return false;},- easeInOutCubic: function(t) {- if ((t /= 0.5) < 1) {- return 0.5 * t * t * t;+ /**+ * @private+ */+ _computeGridLineItems: function(chartArea) {+ var me = this;+ var chart = me.chart;+ var options = me.options;+ var gridLines = options.gridLines;+ var position = options.position;+ var offsetGridLines = gridLines.offsetGridLines;+ var isHorizontal = me.isHorizontal();+ var ticks = me._ticksToDraw;+ var ticksLength = ticks.length + (offsetGridLines ? 1 : 0);++ var tl = getTickMarkLength(gridLines);+ var items = [];+ var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;+ var axisHalfWidth = axisWidth / 2;+ var alignPixel = helpers$1._alignPixel;+ var alignBorderValue = function(pixel) {+ return alignPixel(chart, pixel, axisWidth);+ };+ var borderValue, i, tick, lineValue, alignedLineValue;+ var tx1, ty1, tx2, ty2, x1, y1, x2, y2, lineWidth, lineColor, borderDash, borderDashOffset;++ if (position === 'top') {+ borderValue = alignBorderValue(me.bottom);+ ty1 = me.bottom - tl;+ ty2 = borderValue - axisHalfWidth;+ y1 = alignBorderValue(chartArea.top) + axisHalfWidth;+ y2 = chartArea.bottom;+ } else if (position === 'bottom') {+ borderValue = alignBorderValue(me.top);+ y1 = chartArea.top;+ y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;+ ty1 = borderValue + axisHalfWidth;+ ty2 = me.top + tl;+ } else if (position === 'left') {+ borderValue = alignBorderValue(me.right);+ tx1 = me.right - tl;+ tx2 = borderValue - axisHalfWidth;+ x1 = alignBorderValue(chartArea.left) + axisHalfWidth;+ x2 = chartArea.right;+ } else {+ borderValue = alignBorderValue(me.left);+ x1 = chartArea.left;+ x2 = alignBorderValue(chartArea.right) - axisHalfWidth;+ tx1 = borderValue + axisHalfWidth;+ tx2 = me.left + tl;}- return 0.5 * ((t -= 2) * t * t + 2);- },- easeInQuart: function(t) {- return t * t * t * t;- },+ for (i = 0; i < ticksLength; ++i) {+ tick = ticks[i] || {};++ // autoskipper skipped this tick (#4635)+ if (isNullOrUndef(tick.label) && i < ticks.length) {+ continue;+ }++ if (i === me.zeroLineIndex && options.offset === offsetGridLines) {+ // Draw the first index specially+ lineWidth = gridLines.zeroLineWidth;+ lineColor = gridLines.zeroLineColor;+ borderDash = gridLines.zeroLineBorderDash || [];+ borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0;+ } else {+ lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, i, 1);+ lineColor = valueAtIndexOrDefault(gridLines.color, i, 'rgba(0,0,0,0.1)');+ borderDash = gridLines.borderDash || [];+ borderDashOffset = gridLines.borderDashOffset || 0.0;+ }++ lineValue = getPixelForGridLine(me, tick._index || i, offsetGridLines);- easeOutQuart: function(t) {- return -((t = t - 1) * t * t * t - 1);- },+ // Skip if the pixel is out of the range+ if (lineValue === undefined) {+ continue;+ }- easeInOutQuart: function(t) {- if ((t /= 0.5) < 1) {- return 0.5 * t * t * t * t;+ alignedLineValue = alignPixel(chart, lineValue, lineWidth);++ if (isHorizontal) {+ tx1 = tx2 = x1 = x2 = alignedLineValue;+ } else {+ ty1 = ty2 = y1 = y2 = alignedLineValue;+ }++ items.push({+ tx1: tx1,+ ty1: ty1,+ tx2: tx2,+ ty2: ty2,+ x1: x1,+ y1: y1,+ x2: x2,+ y2: y2,+ width: lineWidth,+ color: lineColor,+ borderDash: borderDash,+ borderDashOffset: borderDashOffset,+ });}- return -0.5 * ((t -= 2) * t * t * t - 2);- },- easeInQuint: function(t) {- return t * t * t * t * t;- },+ items.ticksLength = ticksLength;+ items.borderValue = borderValue;- easeOutQuint: function(t) {- return (t = t - 1) * t * t * t * t + 1;+ return items;},- easeInOutQuint: function(t) {- if ((t /= 0.5) < 1) {- return 0.5 * t * t * t * t * t;+ /**+ * @private+ */+ _computeLabelItems: function() {+ var me = this;+ var options = me.options;+ var optionTicks = options.ticks;+ var position = options.position;+ var isMirrored = optionTicks.mirror;+ var isHorizontal = me.isHorizontal();+ var ticks = me._ticksToDraw;+ var fonts = parseTickFontOptions(optionTicks);+ var tickPadding = optionTicks.padding;+ var tl = getTickMarkLength(options.gridLines);+ var rotation = -helpers$1.toRadians(me.labelRotation);+ var items = [];+ var i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;++ if (position === 'top') {+ y = me.bottom - tl - tickPadding;+ textAlign = !rotation ? 'center' : 'left';+ } else if (position === 'bottom') {+ y = me.top + tl + tickPadding;+ textAlign = !rotation ? 'center' : 'right';+ } else if (position === 'left') {+ x = me.right - (isMirrored ? 0 : tl) - tickPadding;+ textAlign = isMirrored ? 'left' : 'right';+ } else {+ x = me.left + (isMirrored ? 0 : tl) + tickPadding;+ textAlign = isMirrored ? 'right' : 'left';}- 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));- },+ for (i = 0, ilen = ticks.length; i < ilen; ++i) {+ tick = ticks[i];+ label = tick.label;- easeInOutSine: function(t) {- return -0.5 * (Math.cos(Math.PI * t) - 1);- },+ // autoskipper skipped this tick (#4635)+ if (isNullOrUndef(label)) {+ continue;+ }- easeInExpo: function(t) {- return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));- },+ pixel = me.getPixelForTick(tick._index || i) + optionTicks.labelOffset;+ font = tick.major ? fonts.major : fonts.minor;+ lineHeight = font.lineHeight;+ lineCount = isArray(label) ? label.length : 1;- easeOutExpo: function(t) {- return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;- },+ if (isHorizontal) {+ x = pixel;+ textOffset = position === 'top'+ ? ((!rotation ? 0.5 : 1) - lineCount) * lineHeight+ : (!rotation ? 0.5 : 0) * lineHeight;+ } else {+ y = pixel;+ textOffset = (1 - lineCount) * lineHeight / 2;+ }- 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));+ items.push({+ x: x,+ y: y,+ rotation: rotation,+ label: label,+ font: font,+ textOffset: textOffset,+ textAlign: textAlign+ });}- return 0.5 * (-Math.pow(2, -10 * --t) + 2);- },- easeInCirc: function(t) {- if (t >= 1) {- return t;- }- return -(Math.sqrt(1 - t * t) - 1);+ return items;},- easeOutCirc: function(t) {- return Math.sqrt(1 - (t = t - 1) * t);- },+ /**+ * @private+ */+ _drawGrid: function(chartArea) {+ var me = this;+ var gridLines = me.options.gridLines;- easeInOutCirc: function(t) {- if ((t /= 0.5) < 1) {- return -0.5 * (Math.sqrt(1 - t * t) - 1);+ if (!gridLines.display) {+ return;}- 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));- },+ var ctx = me.ctx;+ var chart = me.chart;+ var alignPixel = helpers$1._alignPixel;+ var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;+ var items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));+ var width, color, i, ilen, item;++ for (i = 0, ilen = items.length; i < ilen; ++i) {+ item = items[i];+ width = item.width;+ color = item.color;++ if (width && color) {+ ctx.save();+ ctx.lineWidth = width;+ ctx.strokeStyle = color;+ if (ctx.setLineDash) {+ ctx.setLineDash(item.borderDash);+ ctx.lineDashOffset = item.borderDashOffset;+ }- 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;- },+ ctx.beginPath();- 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);- },+ if (gridLines.drawTicks) {+ ctx.moveTo(item.tx1, item.ty1);+ ctx.lineTo(item.tx2, item.ty2);+ }- easeOutBack: function(t) {- var s = 1.70158;- return (t = t - 1) * t * ((s + 1) * t + s) + 1;- },+ if (gridLines.drawOnChartArea) {+ ctx.moveTo(item.x1, item.y1);+ ctx.lineTo(item.x2, item.y2);+ }- easeInOutBack: function(t) {- var s = 1.70158;- if ((t /= 0.5) < 1) {- return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));+ ctx.stroke();+ ctx.restore();+ }}- return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);- },- easeInBounce: function(t) {- return 1 - effects.easeOutBounce(1 - t);- },+ if (axisWidth) {+ // Draw the line at the edge of the axis+ var firstLineWidth = axisWidth;+ var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, items.ticksLength - 1, 1);+ var borderValue = items.borderValue;+ var x1, x2, y1, y2;- 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;- },+ if (me.isHorizontal()) {+ x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;+ x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;+ y1 = y2 = borderValue;+ } else {+ y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;+ y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;+ x1 = x2 = borderValue;+ }- easeInOutBounce: function(t) {- if (t < 0.5) {- return effects.easeInBounce(t * 2) * 0.5;+ ctx.lineWidth = axisWidth;+ ctx.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0);+ ctx.beginPath();+ ctx.moveTo(x1, y1);+ ctx.lineTo(x2, y2);+ ctx.stroke();}- return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;- }-};+ },-module.exports = {- effects: effects-};+ /**+ * @private+ */+ _drawLabels: function() {+ var me = this;+ var optionTicks = me.options.ticks;-// DEPRECATIONS+ if (!optionTicks.display) {+ return;+ }-/**- * 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.easingEffects = effects;+ var ctx = me.ctx;+ var items = me._labelItems || (me._labelItems = me._computeLabelItems());+ var i, j, ilen, jlen, item, tickFont, label, y;-},{"43":43}],45:[function(require,module,exports){-'use strict';+ for (i = 0, ilen = items.length; i < ilen; ++i) {+ item = items[i];+ tickFont = item.font;-var helpers = require(43);+ // Make sure we draw text in the correct color and font+ ctx.save();+ ctx.translate(item.x, item.y);+ ctx.rotate(item.rotation);+ ctx.font = tickFont.string;+ ctx.fillStyle = tickFont.color;+ ctx.textBaseline = 'middle';+ ctx.textAlign = item.textAlign;++ label = item.label;+ y = item.textOffset;+ if (isArray(label)) {+ for (j = 0, jlen = label.length; j < jlen; ++j) {+ // We just make sure the multiline element is a string here..+ ctx.fillText('' + label[j], 0, y);+ y += tickFont.lineHeight;+ }+ } else {+ ctx.fillText(label, 0, y);+ }+ ctx.restore();+ }+ },-/**- * @alias Chart.helpers.options- * @namespace- */-module.exports = {/**- * 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+ * @private*/- toLineHeight: function(value, size) {- var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);- if (!matches || matches[1] === 'normal') {- return size * 1.2;+ _drawTitle: function() {+ var me = this;+ var ctx = me.ctx;+ var options = me.options;+ var scaleLabel = options.scaleLabel;++ if (!scaleLabel.display) {+ return;}- value = +matches[2];+ var scaleLabelFontColor = valueOrDefault$a(scaleLabel.fontColor, core_defaults.global.defaultFontColor);+ var scaleLabelFont = helpers$1.options._parseFont(scaleLabel);+ var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding);+ var halfLineHeight = scaleLabelFont.lineHeight / 2;+ var position = options.position;+ var rotation = 0;+ var scaleLabelX, scaleLabelY;- switch (matches[3]) {- case 'px':- return value;- case '%':- value /= 100;- break;- default:- break;+ if (me.isHorizontal()) {+ scaleLabelX = me.left + me.width / 2; // midpoint of the width+ scaleLabelY = position === 'bottom'+ ? me.bottom - halfLineHeight - scaleLabelPadding.bottom+ : me.top + halfLineHeight + scaleLabelPadding.top;+ } else {+ var isLeft = position === 'left';+ scaleLabelX = isLeft+ ? me.left + halfLineHeight + scaleLabelPadding.top+ : me.right - halfLineHeight - scaleLabelPadding.top;+ scaleLabelY = me.top + me.height / 2;+ rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;}- return size * value;+ ctx.save();+ ctx.translate(scaleLabelX, scaleLabelY);+ ctx.rotate(rotation);+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';+ ctx.fillStyle = scaleLabelFontColor; // render in correct colour+ ctx.font = scaleLabelFont.string;+ ctx.fillText(scaleLabel.labelString, 0, 0);+ ctx.restore();},- /**- * 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;+ draw: function(chartArea) {+ var me = this;- if (helpers.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;+ if (!me._isVisible()) {+ return;}- return {- top: t,- right: r,- bottom: b,- left: l,- height: t + b,- width: l + r- };+ me._drawGrid(chartArea);+ me._drawTitle();+ me._drawLabels();},/**- * 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+ * @private*/- resolve: function(inputs, context, index) {- var i, ilen, value;+ _layers: function() {+ var me = this;+ var opts = me.options;+ var tz = opts.ticks && opts.ticks.z || 0;+ var gz = opts.gridLines && opts.gridLines.z || 0;++ if (!me._isVisible() || tz === gz || me.draw !== me._draw) {+ // backward compatibility: draw has been overridden by custom scale+ return [{+ z: tz,+ draw: function() {+ me.draw.apply(me, arguments);+ }+ }];+ }- 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.isArray(value)) {- value = value[index];+ return [{+ z: gz,+ draw: function() {+ me._drawGrid.apply(me, arguments);+ me._drawTitle.apply(me, arguments);}- if (value !== undefined) {- return value;+ }, {+ z: tz,+ draw: function() {+ me._drawLabels.apply(me, arguments);}- }- }-};+ }];+ },-},{"43":43}],46:[function(require,module,exports){-'use strict';+ /**+ * @private+ */+ _getMatchingVisibleMetas: function(type) {+ var me = this;+ var isHorizontal = me.isHorizontal();+ return me.chart._getSortedVisibleDatasetMetas()+ .filter(function(meta) {+ return (!type || meta.type === type)+ && (isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id);+ });+ }+});-module.exports = require(43);-module.exports.easing = require(44);-module.exports.canvas = require(42);-module.exports.options = require(45);+Scale.prototype._draw = Scale.prototype.draw;-},{"42":42,"43":43,"44":44,"45":45}],47:[function(require,module,exports){-/**- * Platform fallback implementation (minimal).- * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939- */+var core_scale = Scale;-module.exports = {- acquireContext: function(item) {- if (item && item.canvas) {- // Support for any object associated to a canvas (including a context2d)- item = item.canvas;- }+var isNullOrUndef$1 = helpers$1.isNullOrUndef;- return item && item.getContext('2d') || null;- }+var defaultConfig = {+ position: 'bottom'};-},{}],48:[function(require,module,exports){-/**- * Chart.Platform implementation for targeting a web browser- */--'use strict';+var scale_category = core_scale.extend({+ determineDataLimits: function() {+ var me = this;+ var labels = me._getLabels();+ var ticksOpts = me.options.ticks;+ var min = ticksOpts.min;+ var max = ticksOpts.max;+ var minIndex = 0;+ var maxIndex = labels.length - 1;+ var findIndex;-var helpers = require(46);+ if (min !== undefined) {+ // user specified min value+ findIndex = labels.indexOf(min);+ if (findIndex >= 0) {+ minIndex = findIndex;+ }+ }-var EXPANDO_KEY = '$chartjs';-var CSS_PREFIX = 'chartjs-';-var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';-var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';-var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];+ if (max !== undefined) {+ // user specified max value+ findIndex = labels.indexOf(max);+ if (findIndex >= 0) {+ maxIndex = findIndex;+ }+ }-/**- * DOM event types -> Chart.js event types.- * Note: only events with different types are mapped.- * @see https://developer.mozilla.org/en-US/docs/Web/Events- */-var EVENT_TYPES = {- touchstart: 'mousedown',- touchmove: 'mousemove',- touchend: 'mouseup',- pointerenter: 'mouseenter',- pointerdown: 'mousedown',- pointermove: 'mousemove',- pointerup: 'mouseup',- pointerleave: 'mouseout',- pointerout: 'mouseout'-};+ me.minIndex = minIndex;+ me.maxIndex = maxIndex;+ me.min = labels[minIndex];+ me.max = labels[maxIndex];+ },-/**- * The "used" size is the final value of a dimension property after all calculations have- * been performed. This method uses the computed style of `element` but returns undefined- * if the computed style is not expressed in pixels. That can happen in some cases where- * `element` has a size relative to its parent and this last one is not yet displayed,- * for example because of `display: none` on a parent node.- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value- * @returns {Number} Size in pixels or undefined if unknown.- */-function readUsedSize(element, property) {- var value = helpers.getStyle(element, property);- var matches = value && value.match(/^(\d+)(\.\d+)?px$/);- return matches ? Number(matches[1]) : undefined;-}+ buildTicks: function() {+ var me = this;+ var labels = me._getLabels();+ var minIndex = me.minIndex;+ var maxIndex = me.maxIndex;-/**- * Initializes the canvas style and render size without modifying the canvas display size,- * since responsiveness is handled by the controller.resize() method. The config is used- * to determine the aspect ratio to apply in case no explicit height has been specified.- */-function initCanvas(canvas, config) {- var style = canvas.style;+ // If we are viewing some subset of labels, slice the original array+ me.ticks = (minIndex === 0 && maxIndex === labels.length - 1) ? labels : labels.slice(minIndex, maxIndex + 1);+ },- // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it- // returns null or '' if no explicit value has been set to the canvas attribute.- var renderHeight = canvas.getAttribute('height');- var renderWidth = canvas.getAttribute('width');+ getLabelForIndex: function(index, datasetIndex) {+ var me = this;+ var chart = me.chart;- // Chart.js modifies some canvas values that we want to restore on destroy- canvas[EXPANDO_KEY] = {- initial: {- height: renderHeight,- width: renderWidth,- style: {- display: style.display,- height: style.height,- width: style.width- }+ if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) {+ return me.getRightValue(chart.data.datasets[datasetIndex].data[index]);}- };- // Force canvas to display as block to avoid extra space caused by inline- // elements, which would interfere with the responsive resize process.- // https://github.com/chartjs/Chart.js/issues/2538- style.display = style.display || 'block';-- if (renderWidth === null || renderWidth === '') {- var displayWidth = readUsedSize(canvas, 'width');- if (displayWidth !== undefined) {- canvas.width = displayWidth;- }- }+ return me._getLabels()[index];+ },- if (renderHeight === null || renderHeight === '') {- if (canvas.style.height === '') {- // If no explicit render height and style height, let's apply the aspect ratio,- // which one can be specified by the user but also by charts as default option- // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.- canvas.height = canvas.width / (config.options.aspectRatio || 2);- } else {- var displayHeight = readUsedSize(canvas, 'height');- if (displayWidth !== undefined) {- canvas.height = displayHeight;- }- }- }+ _configure: function() {+ var me = this;+ var offset = me.options.offset;+ var ticks = me.ticks;- return canvas;-}+ core_scale.prototype._configure.call(me);-/**- * Detects support for options object argument in addEventListener.- * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support- * @private- */-var supportsEventListenerOptions = (function() {- var supports = false;- try {- var options = Object.defineProperty({}, 'passive', {- get: function() {- supports = true;- }- });- window.addEventListener('e', null, options);- } catch (e) {- // continue regardless of error- }- return supports;-}());+ if (!me.isHorizontal()) {+ // For backward compatibility, vertical category scale reverse is inverted.+ me._reversePixels = !me._reversePixels;+ }-// Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.-// https://github.com/chartjs/Chart.js/issues/4287-var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;+ if (!ticks) {+ return;+ }-function addEventListener(node, type, listener) {- node.addEventListener(type, listener, eventListenerOptions);-}+ me._startValue = me.minIndex - (offset ? 0.5 : 0);+ me._valueRange = Math.max(ticks.length - (offset ? 0 : 1), 1);+ },-function removeEventListener(node, type, listener) {- node.removeEventListener(type, listener, eventListenerOptions);-}+ // Used to get data value locations. Value can either be an index or a numerical value+ getPixelForValue: function(value, index, datasetIndex) {+ var me = this;+ var valueCategory, labels, idx;-function createEvent(type, chart, x, y, nativeEvent) {- return {- type: type,- chart: chart,- native: nativeEvent || null,- x: x !== undefined ? x : null,- y: y !== undefined ? y : null,- };-}+ if (!isNullOrUndef$1(index) && !isNullOrUndef$1(datasetIndex)) {+ value = me.chart.data.datasets[datasetIndex].data[index];+ }-function fromNativeEvent(event, chart) {- var type = EVENT_TYPES[event.type] || event.type;- var pos = helpers.getRelativePosition(event, chart);- return createEvent(type, chart, pos.x, pos.y, event);-}+ // If value is a data object, then index is the index in the data array,+ // not the index of the scale. We need to change that.+ if (!isNullOrUndef$1(value)) {+ valueCategory = me.isHorizontal() ? value.x : value.y;+ }+ if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {+ labels = me._getLabels();+ value = helpers$1.valueOrDefault(valueCategory, value);+ idx = labels.indexOf(value);+ index = idx !== -1 ? idx : index;+ if (isNaN(index)) {+ index = value;+ }+ }+ return me.getPixelForDecimal((index - me._startValue) / me._valueRange);+ },-function throttled(fn, thisArg) {- var ticking = false;- var args = [];+ getPixelForTick: function(index) {+ var ticks = this.ticks;+ return index < 0 || index > ticks.length - 1+ ? null+ : this.getPixelForValue(ticks[index], index + this.minIndex);+ },- return function() {- args = Array.prototype.slice.call(arguments);- thisArg = thisArg || this;+ getValueForPixel: function(pixel) {+ var me = this;+ var value = Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange);+ return Math.min(Math.max(value, 0), me.ticks.length - 1);+ },- if (!ticking) {- ticking = true;- helpers.requestAnimFrame.call(window, function() {- ticking = false;- fn.apply(thisArg, args);- });- }- };-}+ getBasePixel: function() {+ return this.bottom;+ }+});-// Implementation based on https://github.com/marcj/css-element-queries-function createResizer(handler) {- var resizer = document.createElement('div');- var cls = CSS_PREFIX + 'size-monitor';- var maxSize = 1000000;- var style =- 'position:absolute;' +- 'left:0;' +- 'top:0;' +- 'right:0;' +- 'bottom:0;' +- 'overflow:hidden;' +- 'pointer-events:none;' +- 'visibility:hidden;' +- 'z-index:-1;';-- resizer.style.cssText = style;- resizer.className = cls;- resizer.innerHTML =- '<div class="' + cls + '-expand" style="' + style + '">' +- '<div style="' +- 'position:absolute;' +- 'width:' + maxSize + 'px;' +- 'height:' + maxSize + 'px;' +- 'left:0;' +- 'top:0">' +- '</div>' +- '</div>' +- '<div class="' + cls + '-shrink" style="' + style + '">' +- '<div style="' +- 'position:absolute;' +- 'width:200%;' +- 'height:200%;' +- 'left:0; ' +- 'top:0">' +- '</div>' +- '</div>';-- var expand = resizer.childNodes[0];- var shrink = resizer.childNodes[1];+// INTERNAL: static default options, registered in src/index.js+var _defaults = defaultConfig;+scale_category._defaults = _defaults;- resizer._reset = function() {- expand.scrollLeft = maxSize;- expand.scrollTop = maxSize;- shrink.scrollLeft = maxSize;- shrink.scrollTop = maxSize;- };- var onScroll = function() {- resizer._reset();- handler();- };+var noop = helpers$1.noop;+var isNullOrUndef$2 = helpers$1.isNullOrUndef;- addEventListener(expand, 'scroll', onScroll.bind(expand, 'expand'));- addEventListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));+/**+ * Generate a set of linear ticks+ * @param generationOptions the options used to generate the ticks+ * @param dataRange the range of the data+ * @returns {number[]} array of tick values+ */+function generateTicks(generationOptions, dataRange) {+ var ticks = [];+ // To get a "nice" value for the tick spacing, we will use the appropriately named+ // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks+ // for details.- return resizer;-}+ var MIN_SPACING = 1e-14;+ var stepSize = generationOptions.stepSize;+ var unit = stepSize || 1;+ var maxNumSpaces = generationOptions.maxTicks - 1;+ var min = generationOptions.min;+ var max = generationOptions.max;+ var precision = generationOptions.precision;+ var rmin = dataRange.min;+ var rmax = dataRange.max;+ var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit;+ var factor, niceMin, niceMax, numSpaces;++ // Beyond MIN_SPACING floating point numbers being to lose precision+ // such that we can't do the math necessary to generate ticks+ if (spacing < MIN_SPACING && isNullOrUndef$2(min) && isNullOrUndef$2(max)) {+ return [rmin, rmax];+ }++ numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);+ if (numSpaces > maxNumSpaces) {+ // If the calculated num of spaces exceeds maxNumSpaces, recalculate it+ spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit;+ }++ if (stepSize || isNullOrUndef$2(precision)) {+ // If a precision is not specified, calculate factor based on spacing+ factor = Math.pow(10, helpers$1._decimalPlaces(spacing));+ } else {+ // If the user specified a precision, round to that number of decimal places+ factor = Math.pow(10, precision);+ spacing = Math.ceil(spacing * factor) / factor;+ }-// https://davidwalsh.name/detect-node-insertion-function watchForRender(node, handler) {- var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});- var proxy = expando.renderProxy = function(e) {- if (e.animationName === CSS_RENDER_ANIMATION) {- handler();+ niceMin = Math.floor(rmin / spacing) * spacing;+ niceMax = Math.ceil(rmax / spacing) * spacing;++ // If min, max and stepSize is set and they make an evenly spaced scale use it.+ if (stepSize) {+ // If very close to our whole number, use it.+ if (!isNullOrUndef$2(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) {+ niceMin = min;}- };+ if (!isNullOrUndef$2(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) {+ niceMax = max;+ }+ }- helpers.each(ANIMATION_START_EVENTS, function(type) {- addEventListener(node, type, proxy);- });+ numSpaces = (niceMax - niceMin) / spacing;+ // If very close to our rounded value, use it.+ if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {+ numSpaces = Math.round(numSpaces);+ } else {+ numSpaces = Math.ceil(numSpaces);+ }- // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class- // is removed then added back immediately (same animation frame?). Accessing the- // `offsetParent` property will force a reflow and re-evaluate the CSS animation.- // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics- // https://github.com/chartjs/Chart.js/issues/4737- expando.reflow = !!node.offsetParent;+ niceMin = Math.round(niceMin * factor) / factor;+ niceMax = Math.round(niceMax * factor) / factor;+ ticks.push(isNullOrUndef$2(min) ? niceMin : min);+ for (var j = 1; j < numSpaces; ++j) {+ ticks.push(Math.round((niceMin + j * spacing) * factor) / factor);+ }+ ticks.push(isNullOrUndef$2(max) ? niceMax : max);- node.classList.add(CSS_RENDER_MONITOR);+ return ticks;}-function unwatchForRender(node) {- var expando = node[EXPANDO_KEY] || {};- var proxy = expando.renderProxy;+var scale_linearbase = core_scale.extend({+ getRightValue: function(value) {+ if (typeof value === 'string') {+ return +value;+ }+ return core_scale.prototype.getRightValue.call(this, value);+ },- if (proxy) {- helpers.each(ANIMATION_START_EVENTS, function(type) {- removeEventListener(node, type, proxy);- });+ handleTickRangeOptions: function() {+ var me = this;+ var opts = me.options;+ var tickOpts = opts.ticks;- delete expando.renderProxy;- }+ // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,+ // do nothing since that would make the chart weird. If the user really wants a weird chart+ // axis, they can manually override it+ if (tickOpts.beginAtZero) {+ var minSign = helpers$1.sign(me.min);+ var maxSign = helpers$1.sign(me.max);- node.classList.remove(CSS_RENDER_MONITOR);-}+ if (minSign < 0 && maxSign < 0) {+ // move the top up to 0+ me.max = 0;+ } else if (minSign > 0 && maxSign > 0) {+ // move the bottom down to 0+ me.min = 0;+ }+ }-function addResizeListener(node, listener, chart) {- var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});+ var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;+ var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;- // Let's keep track of this added resizer and thus avoid DOM query when removing it.- var resizer = expando.resizer = createResizer(throttled(function() {- if (expando.resizer) {- return listener(createEvent('resize', chart));+ if (tickOpts.min !== undefined) {+ me.min = tickOpts.min;+ } else if (tickOpts.suggestedMin !== undefined) {+ if (me.min === null) {+ me.min = tickOpts.suggestedMin;+ } else {+ me.min = Math.min(me.min, tickOpts.suggestedMin);+ }}- }));- // The resizer needs to be attached to the node parent, so we first need to be- // sure that `node` is attached to the DOM before injecting the resizer element.- watchForRender(node, function() {- if (expando.resizer) {- var container = node.parentNode;- if (container && container !== resizer.parentNode) {- container.insertBefore(resizer, container.firstChild);+ if (tickOpts.max !== undefined) {+ me.max = tickOpts.max;+ } else if (tickOpts.suggestedMax !== undefined) {+ if (me.max === null) {+ me.max = tickOpts.suggestedMax;+ } else {+ me.max = Math.max(me.max, tickOpts.suggestedMax);}+ }- // The container size might have changed, let's reset the resizer state.- resizer._reset();+ if (setMin !== setMax) {+ // We set the min or the max but not both.+ // So ensure that our range is good+ // Inverted or 0 length range can happen when+ // ticks.min is set, and no datasets are visible+ if (me.min >= me.max) {+ if (setMin) {+ me.max = me.min + 1;+ } else {+ me.min = me.max - 1;+ }+ }}- });-}-function removeResizeListener(node) {- var expando = node[EXPANDO_KEY] || {};- var resizer = expando.resizer;+ if (me.min === me.max) {+ me.max++;- delete expando.resizer;- unwatchForRender(node);+ if (!tickOpts.beginAtZero) {+ me.min--;+ }+ }+ },- if (resizer && resizer.parentNode) {- resizer.parentNode.removeChild(resizer);- }-}+ getTickLimit: function() {+ var me = this;+ var tickOpts = me.options.ticks;+ var stepSize = tickOpts.stepSize;+ var maxTicksLimit = tickOpts.maxTicksLimit;+ var maxTicks;-function injectCSS(platform, css) {- // http://stackoverflow.com/q/3922139- var style = platform._style || document.createElement('style');- if (!platform._style) {- platform._style = style;- css = '/* Chart.js */\n' + css;- style.setAttribute('type', 'text/css');- document.getElementsByTagName('head')[0].appendChild(style);- }+ if (stepSize) {+ maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;+ } else {+ maxTicks = me._computeTickLimit();+ maxTicksLimit = maxTicksLimit || 11;+ }- style.appendChild(document.createTextNode(css));-}+ if (maxTicksLimit) {+ maxTicks = Math.min(maxTicksLimit, maxTicks);+ }-module.exports = {- /**- * This property holds whether this platform is enabled for the current environment.- * Currently used by platform.js to select the proper implementation.- * @private- */- _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',+ return maxTicks;+ },- initialize: function() {- var keyframes = 'from{opacity:0.99}to{opacity:1}';-- injectCSS(this,- // DOM rendering detection- // https://davidwalsh.name/detect-node-insertion- '@-webkit-keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' +- '@keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' +- '.' + CSS_RENDER_MONITOR + '{' +- '-webkit-animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' +- 'animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' +- '}'- );+ _computeTickLimit: function() {+ return Number.POSITIVE_INFINITY;},- acquireContext: function(item, config) {- if (typeof item === 'string') {- item = document.getElementById(item);- } else if (item.length) {- // Support for array based queries (such as jQuery)- item = item[0];- }+ handleDirectionalChanges: noop,- if (item && item.canvas) {- // Support for any object associated to a canvas (including a context2d)- item = item.canvas;- }+ buildTicks: function() {+ var me = this;+ var opts = me.options;+ var tickOpts = opts.ticks;- // To prevent canvas fingerprinting, some add-ons undefine the getContext- // method, for example: https://github.com/kkapsner/CanvasBlocker- // https://github.com/chartjs/Chart.js/issues/2807- var context = item && item.getContext && item.getContext('2d');+ // Figure out what the max number of ticks we can support it is based on the size of+ // the axis area. For now, we say that the minimum tick spacing in pixels must be 40+ // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on+ // the graph. Make sure we always have at least 2 ticks+ var maxTicks = me.getTickLimit();+ maxTicks = Math.max(2, maxTicks);++ var numericGeneratorOptions = {+ maxTicks: maxTicks,+ min: tickOpts.min,+ max: tickOpts.max,+ precision: tickOpts.precision,+ stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)+ };+ var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);- // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is- // inside an iframe or when running in a protected environment. We could guess the- // types from their toString() value but let's keep things flexible and assume it's- // a sufficient condition if the item has a context2D which has item as `canvas`.- // https://github.com/chartjs/Chart.js/issues/3887- // https://github.com/chartjs/Chart.js/issues/4102- // https://github.com/chartjs/Chart.js/issues/4152- if (context && context.canvas === item) {- initCanvas(item, config);- return context;- }+ me.handleDirectionalChanges();- return null;- },+ // At this point, we need to update our max and min given the tick values since we have expanded the+ // range of the scale+ me.max = helpers$1.max(ticks);+ me.min = helpers$1.min(ticks);- releaseContext: function(context) {- var canvas = context.canvas;- if (!canvas[EXPANDO_KEY]) {- return;+ if (tickOpts.reverse) {+ ticks.reverse();++ me.start = me.max;+ me.end = me.min;+ } else {+ me.start = me.min;+ me.end = me.max;}+ },- var initial = canvas[EXPANDO_KEY].initial;- ['height', 'width'].forEach(function(prop) {- var value = initial[prop];- if (helpers.isNullOrUndef(value)) {- canvas.removeAttribute(prop);- } else {- canvas.setAttribute(prop, value);- }- });+ convertTicksToLabels: function() {+ var me = this;+ me.ticksAsNumbers = me.ticks.slice();+ me.zeroLineIndex = me.ticks.indexOf(0);- helpers.each(initial.style || {}, function(value, key) {- canvas.style[key] = value;- });+ core_scale.prototype.convertTicksToLabels.call(me);+ },- // The canvas render size might have been changed (and thus the state stack discarded),- // we can't use save() and restore() to restore the initial state. So make sure that at- // least the canvas context is reset to the default state by setting the canvas width.- // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html- canvas.width = canvas.width;+ _configure: function() {+ var me = this;+ var ticks = me.getTicks();+ var start = me.min;+ var end = me.max;+ var offset;- delete canvas[EXPANDO_KEY];- },+ core_scale.prototype._configure.call(me);- addEventListener: function(chart, type, listener) {- var canvas = chart.canvas;- if (type === 'resize') {- // Note: the resize event is not supported on all browsers.- addResizeListener(canvas, listener, chart);- return;+ if (me.options.offset && ticks.length) {+ offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;+ start -= offset;+ end += offset;}+ me._startValue = start;+ me._endValue = end;+ me._valueRange = end - start;+ }+});- var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});- var proxies = expando.proxies || (expando.proxies = {});- var proxy = proxies[chart.id + '_' + type] = function(event) {- listener(fromNativeEvent(event, chart));+var defaultConfig$1 = {+ position: 'left',+ ticks: {+ callback: core_ticks.formatters.linear+ }+};++var DEFAULT_MIN = 0;+var DEFAULT_MAX = 1;++function getOrCreateStack(stacks, stacked, meta) {+ var key = [+ meta.type,+ // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined+ stacked === undefined && meta.stack === undefined ? meta.index : '',+ meta.stack+ ].join('.');++ if (stacks[key] === undefined) {+ stacks[key] = {+ pos: [],+ neg: []};+ }- addEventListener(canvas, type, proxy);- },+ return stacks[key];+}- removeEventListener: function(chart, type, listener) {- var canvas = chart.canvas;- if (type === 'resize') {- // Note: the resize event is not supported on all browsers.- removeResizeListener(canvas, listener);- return;+function stackData(scale, stacks, meta, data) {+ var opts = scale.options;+ var stacked = opts.stacked;+ var stack = getOrCreateStack(stacks, stacked, meta);+ var pos = stack.pos;+ var neg = stack.neg;+ var ilen = data.length;+ var i, value;++ for (i = 0; i < ilen; ++i) {+ value = scale._parseValue(data[i]);+ if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {+ continue;}- var expando = listener[EXPANDO_KEY] || {};- var proxies = expando.proxies || {};- var proxy = proxies[chart.id + '_' + type];- if (!proxy) {- return;+ pos[i] = pos[i] || 0;+ neg[i] = neg[i] || 0;++ if (opts.relativePoints) {+ pos[i] = 100;+ } else if (value.min < 0 || value.max < 0) {+ neg[i] += value.min;+ } else {+ pos[i] += value.max;+ }+ }+}++function updateMinMax(scale, meta, data) {+ var ilen = data.length;+ var i, value;++ for (i = 0; i < ilen; ++i) {+ value = scale._parseValue(data[i]);+ if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {+ continue;}- removeEventListener(canvas, type, proxy);+ scale.min = Math.min(scale.min, value.min);+ scale.max = Math.max(scale.max, value.max);}-};+}-// DEPRECATIONS+var scale_linear = scale_linearbase.extend({+ determineDataLimits: function() {+ var me = this;+ var opts = me.options;+ var chart = me.chart;+ var datasets = chart.data.datasets;+ var metasets = me._getMatchingVisibleMetas();+ var hasStacks = opts.stacked;+ var stacks = {};+ var ilen = metasets.length;+ var i, meta, data, values;-/**- * Provided for backward compatibility, use EventTarget.addEventListener instead.- * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+- * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener- * @function Chart.helpers.addEvent- * @deprecated since version 2.7.0- * @todo remove at version 3- * @private- */-helpers.addEvent = addEventListener;+ me.min = Number.POSITIVE_INFINITY;+ me.max = Number.NEGATIVE_INFINITY;++ if (hasStacks === undefined) {+ for (i = 0; !hasStacks && i < ilen; ++i) {+ meta = metasets[i];+ hasStacks = meta.stack !== undefined;+ }+ }++ for (i = 0; i < ilen; ++i) {+ meta = metasets[i];+ data = datasets[meta.index].data;+ if (hasStacks) {+ stackData(me, stacks, meta, data);+ } else {+ updateMinMax(me, meta, data);+ }+ }++ helpers$1.each(stacks, function(stackValues) {+ values = stackValues.pos.concat(stackValues.neg);+ me.min = Math.min(me.min, helpers$1.min(values));+ me.max = Math.max(me.max, helpers$1.max(values));+ });-/**- * Provided for backward compatibility, use EventTarget.removeEventListener instead.- * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+- * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener- * @function Chart.helpers.removeEvent- * @deprecated since version 2.7.0- * @todo remove at version 3- * @private- */-helpers.removeEvent = removeEventListener;+ me.min = helpers$1.isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;+ me.max = helpers$1.isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;-},{"46":46}],49:[function(require,module,exports){-'use strict';+ // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero+ me.handleTickRangeOptions();+ },-var helpers = require(46);-var basic = require(47);-var dom = require(48);+ // Returns the maximum number of ticks based on the scale dimension+ _computeTickLimit: function() {+ var me = this;+ var tickFont;-// @TODO Make possible to select another platform at build time.-var implementation = dom._enabled ? dom : basic;+ if (me.isHorizontal()) {+ return Math.ceil(me.width / 40);+ }+ tickFont = helpers$1.options._parseFont(me.options.ticks);+ return Math.ceil(me.height / tickFont.lineHeight);+ },-/**- * @namespace Chart.platform- * @see https://chartjs.gitbooks.io/proposals/content/Platform.html- * @since 2.4.0- */-module.exports = helpers.extend({- /**- * @since 2.7.0- */- initialize: function() {},+ // Called after the ticks are built. We need+ handleDirectionalChanges: function() {+ if (!this.isHorizontal()) {+ // We are in a vertical orientation. The top value is the highest. So reverse the array+ this.ticks.reverse();+ }+ },- /**- * Called at chart construction time, returns a context2d instance implementing- * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.- * @param {*} item - The native item from which to acquire context (platform specific)- * @param {Object} options - The chart options- * @returns {CanvasRenderingContext2D} context2d instance- */- acquireContext: function() {},+ getLabelForIndex: function(index, datasetIndex) {+ return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);+ },- /**- * Called at chart destruction time, releases any resources associated to the context- * previously returned by the acquireContext() method.- * @param {CanvasRenderingContext2D} context - The context2d instance- * @returns {Boolean} true if the method succeeded, else false- */- releaseContext: function() {},+ // Utils+ getPixelForValue: function(value) {+ var me = this;+ return me.getPixelForDecimal((+me.getRightValue(value) - me._startValue) / me._valueRange);+ },- /**- * Registers the specified listener on the given chart.- * @param {Chart} chart - Chart from which to listen for event- * @param {String} type - The ({@link IEvent}) type to listen for- * @param {Function} listener - Receives a notification (an object that implements- * the {@link IEvent} interface) when an event of the specified type occurs.- */- addEventListener: function() {},+ getValueForPixel: function(pixel) {+ return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;+ },- /**- * Removes the specified listener previously registered with addEventListener.- * @param {Chart} chart -Chart from which to remove the listener- * @param {String} type - The ({@link IEvent}) type to remove- * @param {Function} listener - The listener function to remove from the event target.- */- removeEventListener: function() {}+ getPixelForTick: function(index) {+ var ticks = this.ticksAsNumbers;+ if (index < 0 || index > ticks.length - 1) {+ return null;+ }+ return this.getPixelForValue(ticks[index]);+ }+});-}, implementation);+// INTERNAL: static default options, registered in src/index.js+var _defaults$1 = defaultConfig$1;+scale_linear._defaults = _defaults$1;-/**- * @interface IPlatform- * Allows abstracting platform dependencies away from the chart- * @borrows Chart.platform.acquireContext as acquireContext- * @borrows Chart.platform.releaseContext as releaseContext- * @borrows Chart.platform.addEventListener as addEventListener- * @borrows Chart.platform.removeEventListener as removeEventListener- */+var valueOrDefault$b = helpers$1.valueOrDefault;+var log10 = helpers$1.math.log10;/**- * @interface IEvent- * @prop {String} type - The event type name, possible values are:- * 'contextmenu', 'mouseenter', 'mousedown', 'mousemove', 'mouseup', 'mouseout',- * 'click', 'dblclick', 'keydown', 'keypress', 'keyup' and 'resize'- * @prop {*} native - The original native event (null for emulated events, e.g. 'resize')- * @prop {Number} x - The mouse x position, relative to the canvas (null for incompatible events)- * @prop {Number} y - The mouse y position, relative to the canvas (null for incompatible events)+ * Generate a set of logarithmic ticks+ * @param generationOptions the options used to generate the ticks+ * @param dataRange the range of the data+ * @returns {number[]} array of tick values*/+function generateTicks$1(generationOptions, dataRange) {+ var ticks = [];-},{"46":46,"47":47,"48":48}],50:[function(require,module,exports){-'use strict';+ var tickVal = valueOrDefault$b(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));-module.exports = {};-module.exports.filler = require(51);-module.exports.legend = require(52);-module.exports.title = require(53);+ var endExp = Math.floor(log10(dataRange.max));+ var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));+ var exp, significand;-},{"51":51,"52":52,"53":53}],51:[function(require,module,exports){-/**- * Plugin based on discussion from the following Chart.js issues:- * @see https://github.com/chartjs/Chart.js/issues/2380#issuecomment-279961569- * @see https://github.com/chartjs/Chart.js/issues/2440#issuecomment-256461897- */+ if (tickVal === 0) {+ exp = Math.floor(log10(dataRange.minNotZero));+ significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));-'use strict';+ ticks.push(tickVal);+ tickVal = significand * Math.pow(10, exp);+ } else {+ exp = Math.floor(log10(tickVal));+ significand = Math.floor(tickVal / Math.pow(10, exp));+ }+ var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;-var defaults = require(26);-var elements = require(41);-var helpers = require(46);+ do {+ ticks.push(tickVal);-defaults._set('global', {- plugins: {- filler: {- propagate: true+ ++significand;+ if (significand === 10) {+ significand = 1;+ ++exp;+ precision = exp >= 0 ? 1 : precision;}- }-});-var mappers = {- dataset: function(source) {- var index = source.fill;- var chart = source.chart;- var meta = chart.getDatasetMeta(index);- var visible = meta && chart.isDatasetVisible(index);- var points = (visible && meta.dataset._children) || [];- var length = points.length || 0;+ tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;+ } while (exp < endExp || (exp === endExp && significand < endSignificand));- return !length ? null : function(point, i) {- return (i < length && points[i]._view) || null;- };- },+ var lastTick = valueOrDefault$b(generationOptions.max, tickVal);+ ticks.push(lastTick);- boundary: function(source) {- var boundary = source.boundary;- var x = boundary ? boundary.x : null;- var y = boundary ? boundary.y : null;+ return ticks;+}- return function(point) {- return {- x: x === null ? point.x : x,- y: y === null ? point.y : y,- };- };+var defaultConfig$2 = {+ position: 'left',++ // label settings+ ticks: {+ callback: core_ticks.formatters.logarithmic}};-// @todo if (fill[0] === '#')-function decodeFill(el, index, count) {- var model = el._model || {};- var fill = model.fill;- var target;+// TODO(v3): change this to positiveOrDefault+function nonNegativeOrDefault(value, defaultValue) {+ return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue;+}- if (fill === undefined) {- fill = !!model.backgroundColor;- }+var scale_logarithmic = core_scale.extend({+ determineDataLimits: function() {+ var me = this;+ var opts = me.options;+ var chart = me.chart;+ var datasets = chart.data.datasets;+ var isHorizontal = me.isHorizontal();+ function IDMatches(meta) {+ return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;+ }+ var datasetIndex, meta, value, data, i, ilen;++ // Calculate Range+ me.min = Number.POSITIVE_INFINITY;+ me.max = Number.NEGATIVE_INFINITY;+ me.minNotZero = Number.POSITIVE_INFINITY;++ var hasStacks = opts.stacked;+ if (hasStacks === undefined) {+ for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {+ meta = chart.getDatasetMeta(datasetIndex);+ if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&+ meta.stack !== undefined) {+ hasStacks = true;+ break;+ }+ }+ }- if (fill === false || fill === null) {- return false;- }+ if (opts.stacked || hasStacks) {+ var valuesPerStack = {};- if (fill === true) {- return 'origin';- }+ for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {+ meta = chart.getDatasetMeta(datasetIndex);+ var key = [+ meta.type,+ // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined+ ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),+ meta.stack+ ].join('.');- target = parseFloat(fill, 10);- if (isFinite(target) && Math.floor(target) === target) {- if (fill[0] === '-' || fill[0] === '+') {- target = index + target;- }+ if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {+ if (valuesPerStack[key] === undefined) {+ valuesPerStack[key] = [];+ }- if (target === index || target < 0 || target >= count) {- return false;+ data = datasets[datasetIndex].data;+ for (i = 0, ilen = data.length; i < ilen; i++) {+ var values = valuesPerStack[key];+ value = me._parseValue(data[i]);+ // invalid, hidden and negative values are ignored+ if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {+ continue;+ }+ values[i] = values[i] || 0;+ values[i] += value.max;+ }+ }+ }++ helpers$1.each(valuesPerStack, function(valuesForType) {+ if (valuesForType.length > 0) {+ var minVal = helpers$1.min(valuesForType);+ var maxVal = helpers$1.max(valuesForType);+ me.min = Math.min(me.min, minVal);+ me.max = Math.max(me.max, maxVal);+ }+ });++ } else {+ for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {+ meta = chart.getDatasetMeta(datasetIndex);+ if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {+ data = datasets[datasetIndex].data;+ for (i = 0, ilen = data.length; i < ilen; i++) {+ value = me._parseValue(data[i]);+ // invalid, hidden and negative values are ignored+ if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {+ continue;+ }++ me.min = Math.min(value.min, me.min);+ me.max = Math.max(value.max, me.max);++ if (value.min !== 0) {+ me.minNotZero = Math.min(value.min, me.minNotZero);+ }+ }+ }+ }}- return target;- }+ me.min = helpers$1.isFinite(me.min) ? me.min : null;+ me.max = helpers$1.isFinite(me.max) ? me.max : null;+ me.minNotZero = helpers$1.isFinite(me.minNotZero) ? me.minNotZero : null;- switch (fill) {- // compatibility- case 'bottom':- return 'start';- case 'top':- return 'end';- case 'zero':- return 'origin';- // supported boundaries- case 'origin':- case 'start':- case 'end':- return fill;- // invalid fill values- default:- return false;- }-}+ // Common base implementation to handle ticks.min, ticks.max+ this.handleTickRangeOptions();+ },-function computeBoundary(source) {- var model = source.el._model || {};- var scale = source.el._scale || {};- var fill = source.fill;- var target = null;- var horizontal;+ handleTickRangeOptions: function() {+ var me = this;+ var tickOpts = me.options.ticks;+ var DEFAULT_MIN = 1;+ var DEFAULT_MAX = 10;- if (isFinite(fill)) {- return null;- }+ me.min = nonNegativeOrDefault(tickOpts.min, me.min);+ me.max = nonNegativeOrDefault(tickOpts.max, me.max);- // Backward compatibility: until v3, we still need to support boundary values set on- // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and- // controllers might still use it (e.g. the Smith chart).+ if (me.min === me.max) {+ if (me.min !== 0 && me.min !== null) {+ me.min = Math.pow(10, Math.floor(log10(me.min)) - 1);+ me.max = Math.pow(10, Math.floor(log10(me.max)) + 1);+ } else {+ me.min = DEFAULT_MIN;+ me.max = DEFAULT_MAX;+ }+ }+ if (me.min === null) {+ me.min = Math.pow(10, Math.floor(log10(me.max)) - 1);+ }+ if (me.max === null) {+ me.max = me.min !== 0+ ? Math.pow(10, Math.floor(log10(me.min)) + 1)+ : DEFAULT_MAX;+ }+ if (me.minNotZero === null) {+ if (me.min > 0) {+ me.minNotZero = me.min;+ } else if (me.max < 1) {+ me.minNotZero = Math.pow(10, Math.floor(log10(me.max)));+ } else {+ me.minNotZero = DEFAULT_MIN;+ }+ }+ },- if (fill === 'start') {- target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;- } else if (fill === 'end') {- target = model.scaleTop === undefined ? scale.top : model.scaleTop;- } else if (model.scaleZero !== undefined) {- target = model.scaleZero;- } else if (scale.getBasePosition) {- target = scale.getBasePosition();- } else if (scale.getBasePixel) {- target = scale.getBasePixel();- }+ buildTicks: function() {+ var me = this;+ var tickOpts = me.options.ticks;+ var reverse = !me.isHorizontal();- if (target !== undefined && target !== null) {- if (target.x !== undefined && target.y !== undefined) {- return target;+ var generationOptions = {+ min: nonNegativeOrDefault(tickOpts.min),+ max: nonNegativeOrDefault(tickOpts.max)+ };+ var ticks = me.ticks = generateTicks$1(generationOptions, me);++ // At this point, we need to update our max and min given the tick values since we have expanded the+ // range of the scale+ me.max = helpers$1.max(ticks);+ me.min = helpers$1.min(ticks);++ if (tickOpts.reverse) {+ reverse = !reverse;+ me.start = me.max;+ me.end = me.min;+ } else {+ me.start = me.min;+ me.end = me.max;+ }+ if (reverse) {+ ticks.reverse();}+ },- if (typeof target === 'number' && isFinite(target)) {- horizontal = scale.isHorizontal();- return {- x: horizontal ? target : null,- y: horizontal ? null : target- };+ convertTicksToLabels: function() {+ this.tickValues = this.ticks.slice();++ core_scale.prototype.convertTicksToLabels.call(this);+ },++ // Get the correct tooltip label+ getLabelForIndex: function(index, datasetIndex) {+ return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);+ },++ getPixelForTick: function(index) {+ var ticks = this.tickValues;+ if (index < 0 || index > ticks.length - 1) {+ return null;}- }+ return this.getPixelForValue(ticks[index]);+ },- return null;-}+ /**+ * Returns the value of the first tick.+ * @param {number} value - The minimum not zero value.+ * @return {number} The first tick value.+ * @private+ */+ _getFirstTickValue: function(value) {+ var exp = Math.floor(log10(value));+ var significand = Math.floor(value / Math.pow(10, exp));-function resolveTarget(sources, index, propagate) {- var source = sources[index];- var fill = source.fill;- var visited = [index];- var target;+ return significand * Math.pow(10, exp);+ },- if (!propagate) {- return fill;- }+ _configure: function() {+ var me = this;+ var start = me.min;+ var offset = 0;- while (fill !== false && visited.indexOf(fill) === -1) {- if (!isFinite(fill)) {- return fill;- }+ core_scale.prototype._configure.call(me);- target = sources[fill];- if (!target) {- return false;+ if (start === 0) {+ start = me._getFirstTickValue(me.minNotZero);+ offset = valueOrDefault$b(me.options.ticks.fontSize, core_defaults.global.defaultFontSize) / me._length;}- if (target.visible) {- return fill;+ me._startValue = log10(start);+ me._valueOffset = offset;+ me._valueRange = (log10(me.max) - log10(start)) / (1 - offset);+ },++ getPixelForValue: function(value) {+ var me = this;+ var decimal = 0;++ value = +me.getRightValue(value);++ if (value > me.min && value > 0) {+ decimal = (log10(value) - me._startValue) / me._valueRange + me._valueOffset;}+ return me.getPixelForDecimal(decimal);+ },- visited.push(fill);- fill = target.fill;+ getValueForPixel: function(pixel) {+ var me = this;+ var decimal = me.getDecimalForPixel(pixel);+ return decimal === 0 && me.min === 0+ ? 0+ : Math.pow(10, me._startValue + (decimal - me._valueOffset) * me._valueRange);}+});- return false;-}+// INTERNAL: static default options, registered in src/index.js+var _defaults$2 = defaultConfig$2;+scale_logarithmic._defaults = _defaults$2;-function createMapper(source) {- var fill = source.fill;- var type = 'dataset';+var valueOrDefault$c = helpers$1.valueOrDefault;+var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault;+var resolve$4 = helpers$1.options.resolve;- if (fill === false) {- return null;- }+var defaultConfig$3 = {+ display: true,- if (!isFinite(fill)) {- type = 'boundary';- }+ // Boolean - Whether to animate scaling the chart from the centre+ animate: true,+ position: 'chartArea',- return mappers[type](source);-}+ angleLines: {+ display: true,+ color: 'rgba(0,0,0,0.1)',+ lineWidth: 1,+ borderDash: [],+ borderDashOffset: 0.0+ },-function isDrawable(point) {- return point && !point.skip;-}+ gridLines: {+ circular: false+ },-function drawArea(ctx, curve0, curve1, len0, len1) {- var i;+ // label settings+ ticks: {+ // Boolean - Show a backdrop to the scale label+ showLabelBackdrop: true,- if (!len0 || !len1) {- return;- }+ // String - The colour of the label backdrop+ backdropColor: 'rgba(255,255,255,0.75)',- // building first area curve (normal)- ctx.moveTo(curve0[0].x, curve0[0].y);- for (i = 1; i < len0; ++i) {- helpers.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);+ // Number - The backdrop padding above & below the label in pixels+ backdropPaddingY: 2,++ // Number - The backdrop padding to the side of the label in pixels+ backdropPaddingX: 2,++ callback: core_ticks.formatters.linear+ },++ pointLabels: {+ // Boolean - if true, show point labels+ display: true,++ // Number - Point label font size in pixels+ fontSize: 10,++ // Function - Used to convert point labels+ callback: function(label) {+ return label;+ }}+};- // joining the two area curves- ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);+function getTickBackdropHeight(opts) {+ var tickOpts = opts.ticks;- // building opposite area curve (reverse)- for (i = len1 - 1; i > 0; --i) {- helpers.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);+ if (tickOpts.display && opts.display) {+ return valueOrDefault$c(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;}+ return 0;}-function doFill(ctx, points, mapper, view, color, loop) {- var count = points.length;- var span = view.spanGaps;- var curve0 = [];- var curve1 = [];- var len0 = 0;- var len1 = 0;- var i, ilen, index, p0, p1, d0, d1;-- ctx.beginPath();+function measureLabelSize(ctx, lineHeight, label) {+ if (helpers$1.isArray(label)) {+ return {+ w: helpers$1.longestText(ctx, ctx.font, label),+ h: label.length * lineHeight+ };+ }- for (i = 0, ilen = (count + !!loop); i < ilen; ++i) {- index = i % count;- p0 = points[index]._view;- p1 = mapper(p0, index, view);- d0 = isDrawable(p0);- d1 = isDrawable(p1);+ return {+ w: ctx.measureText(label).width,+ h: lineHeight+ };+}- if (d0 && d1) {- len0 = curve0.push(p0);- len1 = curve1.push(p1);- } else if (len0 && len1) {- if (!span) {- drawArea(ctx, curve0, curve1, len0, len1);- len0 = len1 = 0;- curve0 = [];- curve1 = [];- } else {- if (d0) {- curve0.push(p0);- }- if (d1) {- curve1.push(p1);- }- }- }+function determineLimits(angle, pos, size, min, max) {+ if (angle === min || angle === max) {+ return {+ start: pos - (size / 2),+ end: pos + (size / 2)+ };+ } else if (angle < min || angle > max) {+ return {+ start: pos - size,+ end: pos+ };}- drawArea(ctx, curve0, curve1, len0, len1);-- ctx.closePath();- ctx.fillStyle = color;- ctx.fill();+ return {+ start: pos,+ end: pos + size+ };}-module.exports = {- id: 'filler',+/**+ * Helper function to fit a radial linear scale with point labels+ */+function fitWithPointLabels(scale) {- afterDatasetsUpdate: function(chart, options) {- var count = (chart.data.datasets || []).length;- var propagate = options.propagate;- var sources = [];- var meta, i, el, source;+ // Right, this is really confusing and there is a lot of maths going on here+ // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9+ //+ // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif+ //+ // Solution:+ //+ // We assume the radius of the polygon is half the size of the canvas at first+ // at each index we check if the text overlaps.+ //+ // Where it does, we store that angle and that index.+ //+ // After finding the largest index and angle we calculate how much we need to remove+ // from the shape radius to move the point inwards by that x.+ //+ // We average the left and right distances to get the maximum shape radius that can fit in the box+ // along with labels.+ //+ // Once we have that, we can find the centre point for the chart, by taking the x text protrusion+ // on each side, removing that from the size, halving it and adding the left x protrusion width.+ //+ // This will mean we have a shape fitted to the canvas, as large as it can be with the labels+ // and position it in the most space efficient manner+ //+ // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif- for (i = 0; i < count; ++i) {- meta = chart.getDatasetMeta(i);- el = meta.dataset;- source = null;+ var plFont = helpers$1.options._parseFont(scale.options.pointLabels);- if (el && el._model && el instanceof elements.Line) {- source = {- visible: chart.isDatasetVisible(i),- fill: decodeFill(el, i, count),- chart: chart,- el: el- };- }+ // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.+ // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points+ var furthestLimits = {+ l: 0,+ r: scale.width,+ t: 0,+ b: scale.height - scale.paddingTop+ };+ var furthestAngles = {};+ var i, textSize, pointPosition;- meta.$filler = source;- sources.push(source);+ scale.ctx.font = plFont.string;+ scale._pointLabelSizes = [];++ var valueCount = scale.chart.data.labels.length;+ for (i = 0; i < valueCount; i++) {+ pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);+ textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i]);+ scale._pointLabelSizes[i] = textSize;++ // Add quarter circle to make degree 0 mean top of circle+ var angleRadians = scale.getIndexAngle(i);+ var angle = helpers$1.toDegrees(angleRadians) % 360;+ var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);+ var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);++ if (hLimits.start < furthestLimits.l) {+ furthestLimits.l = hLimits.start;+ furthestAngles.l = angleRadians;}- for (i = 0; i < count; ++i) {- source = sources[i];- if (!source) {- continue;- }+ if (hLimits.end > furthestLimits.r) {+ furthestLimits.r = hLimits.end;+ furthestAngles.r = angleRadians;+ }- source.fill = resolveTarget(sources, i, propagate);- source.boundary = computeBoundary(source);- source.mapper = createMapper(source);+ if (vLimits.start < furthestLimits.t) {+ furthestLimits.t = vLimits.start;+ furthestAngles.t = angleRadians;}- },- beforeDatasetDraw: function(chart, args) {- var meta = args.meta.$filler;- if (!meta) {- return;+ if (vLimits.end > furthestLimits.b) {+ furthestLimits.b = vLimits.end;+ furthestAngles.b = angleRadians;}+ }- var ctx = chart.ctx;- var el = meta.el;- var view = el._view;- var points = el._children || [];- var mapper = meta.mapper;- var color = view.backgroundColor || defaults.global.defaultColor;+ scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);+}++function getTextAlignForAngle(angle) {+ if (angle === 0 || angle === 180) {+ return 'center';+ } else if (angle < 180) {+ return 'left';+ }++ return 'right';+}++function fillText(ctx, text, position, lineHeight) {+ var y = position.y + lineHeight / 2;+ var i, ilen;- if (mapper && color && points.length) {- helpers.canvas.clipArea(ctx, chart.chartArea);- doFill(ctx, points, mapper, view, color, el._loop);- helpers.canvas.unclipArea(ctx);+ if (helpers$1.isArray(text)) {+ for (i = 0, ilen = text.length; i < ilen; ++i) {+ ctx.fillText(text[i], position.x, y);+ y += lineHeight;}+ } else {+ ctx.fillText(text, position.x, y);}-};+}-},{"26":26,"41":41,"46":46}],52:[function(require,module,exports){-'use strict';+function adjustPointPositionForLabelHeight(angle, textSize, position) {+ if (angle === 90 || angle === 270) {+ position.y -= (textSize.h / 2);+ } else if (angle > 270 || angle < 90) {+ position.y -= textSize.h;+ }+}-var defaults = require(26);-var Element = require(27);-var helpers = require(46);-var layouts = require(31);+function drawPointLabels(scale) {+ var ctx = scale.ctx;+ var opts = scale.options;+ var pointLabelOpts = opts.pointLabels;+ var tickBackdropHeight = getTickBackdropHeight(opts);+ var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);+ var plFont = helpers$1.options._parseFont(pointLabelOpts);-var noop = helpers.noop;+ ctx.save();-defaults._set('global', {- legend: {- display: true,- position: 'top',- fullWidth: true,- reverse: false,- weight: 1000,+ ctx.font = plFont.string;+ ctx.textBaseline = 'middle';- // a callback that will handle- onClick: function(e, legendItem) {- var index = legendItem.datasetIndex;- var ci = this.chart;- var meta = ci.getDatasetMeta(index);+ for (var i = scale.chart.data.labels.length - 1; i >= 0; i--) {+ // Extra pixels out for some label spacing+ var extra = (i === 0 ? tickBackdropHeight / 2 : 0);+ var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);- // See controller.isDatasetVisible comment- meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;+ // Keep this in loop since we may support array properties here+ var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor);+ ctx.fillStyle = pointLabelFontColor;- // We hid a dataset ... rerender the chart- ci.update();- },+ var angleRadians = scale.getIndexAngle(i);+ var angle = helpers$1.toDegrees(angleRadians);+ ctx.textAlign = getTextAlignForAngle(angle);+ adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);+ fillText(ctx, scale.pointLabels[i], pointLabelPosition, plFont.lineHeight);+ }+ ctx.restore();+}- onHover: null,+function drawRadiusLine(scale, gridLineOpts, radius, index) {+ var ctx = scale.ctx;+ var circular = gridLineOpts.circular;+ var valueCount = scale.chart.data.labels.length;+ var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1);+ var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1);+ var pointPosition;- labels: {- boxWidth: 40,- padding: 10,- // Generates labels shown in the legend- // Valid properties to return:- // text : text to display- // fillStyle : fill of coloured box- // strokeStyle: stroke of coloured box- // hidden : if this legend item refers to a hidden item- // lineCap : cap style for line- // lineDash- // lineDashOffset :- // lineJoin :- // lineWidth :- generateLabels: function(chart) {- var data = chart.data;- return helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {- return {- text: dataset.label,- fillStyle: (!helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),- hidden: !chart.isDatasetVisible(i),- lineCap: dataset.borderCapStyle,- lineDash: dataset.borderDash,- lineDashOffset: dataset.borderDashOffset,- lineJoin: dataset.borderJoinStyle,- lineWidth: dataset.borderWidth,- strokeStyle: dataset.borderColor,- pointStyle: dataset.pointStyle,+ if ((!circular && !valueCount) || !lineColor || !lineWidth) {+ return;+ }- // Below is extra data used for toggling the datasets- datasetIndex: i- };- }, this) : [];- }- }- },+ ctx.save();+ ctx.strokeStyle = lineColor;+ ctx.lineWidth = lineWidth;+ if (ctx.setLineDash) {+ ctx.setLineDash(gridLineOpts.borderDash || []);+ ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0;+ }- legendCallback: function(chart) {- var text = [];- text.push('<ul class="' + chart.id + '-legend">');- for (var i = 0; i < chart.data.datasets.length; i++) {- text.push('<li><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"></span>');- if (chart.data.datasets[i].label) {- text.push(chart.data.datasets[i].label);- }- text.push('</li>');+ ctx.beginPath();+ if (circular) {+ // Draw circular arcs between the points+ ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);+ } else {+ // Draw straight lines connecting each index+ pointPosition = scale.getPointPosition(0, radius);+ ctx.moveTo(pointPosition.x, pointPosition.y);++ for (var i = 1; i < valueCount; i++) {+ pointPosition = scale.getPointPosition(i, radius);+ ctx.lineTo(pointPosition.x, pointPosition.y);}- text.push('</ul>');- return text.join('');}-});+ ctx.closePath();+ ctx.stroke();+ ctx.restore();+}-/**- * Helper function to get the box width based on the usePointStyle option- * @param labelopts {Object} the label options on the legend- * @param fontSize {Number} the label font size- * @return {Number} width of the color box area- */-function getBoxWidth(labelOpts, fontSize) {- return labelOpts.usePointStyle ?- fontSize * Math.SQRT2 :- labelOpts.boxWidth;+function numberOrZero(param) {+ return helpers$1.isNumber(param) ? param : 0;}-/**- * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!- */-var Legend = Element.extend({+var scale_radialLinear = scale_linearbase.extend({+ setDimensions: function() {+ var me = this;- initialize: function(config) {- helpers.extend(this, config);+ // Set the unconstrained dimension before label rotation+ me.width = me.maxWidth;+ me.height = me.maxHeight;+ me.paddingTop = getTickBackdropHeight(me.options) / 2;+ me.xCenter = Math.floor(me.width / 2);+ me.yCenter = Math.floor((me.height - me.paddingTop) / 2);+ me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;+ },++ determineDataLimits: function() {+ var me = this;+ var chart = me.chart;+ var min = Number.POSITIVE_INFINITY;+ var max = Number.NEGATIVE_INFINITY;++ helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) {+ if (chart.isDatasetVisible(datasetIndex)) {+ var meta = chart.getDatasetMeta(datasetIndex);++ helpers$1.each(dataset.data, function(rawValue, index) {+ var value = +me.getRightValue(rawValue);+ if (isNaN(value) || meta.data[index].hidden) {+ return;+ }++ min = Math.min(value, min);+ max = Math.max(value, max);+ });+ }+ });- // Contains hit boxes for each dataset (in dataset order)- this.legendHitBoxes = [];+ me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);+ me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);- // Are we in doughnut mode which has a different data type- this.doughnutMode = false;+ // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero+ me.handleTickRangeOptions();},- // 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+ // Returns the maximum number of ticks based on the scale dimension+ _computeTickLimit: function() {+ return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));+ },- beforeUpdate: noop,- update: function(maxWidth, maxHeight, margins) {+ convertTicksToLabels: function() {var me = this;- // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)- me.beforeUpdate();+ scale_linearbase.prototype.convertTicksToLabels.call(me);- // Absorb the master measurements- me.maxWidth = maxWidth;- me.maxHeight = maxHeight;- me.margins = margins;+ // Point labels+ me.pointLabels = me.chart.data.labels.map(function() {+ var label = helpers$1.callback(me.options.pointLabels.callback, arguments, me);+ return label || label === 0 ? label : '';+ });+ },- // Dimensions- me.beforeSetDimensions();- me.setDimensions();- me.afterSetDimensions();- // Labels- me.beforeBuildLabels();- me.buildLabels();- me.afterBuildLabels();+ getLabelForIndex: function(index, datasetIndex) {+ return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);+ },- // Fit- me.beforeFit();- me.fit();- me.afterFit();- //- me.afterUpdate();+ fit: function() {+ var me = this;+ var opts = me.options;- return me.minSize;+ if (opts.display && opts.pointLabels.display) {+ fitWithPointLabels(me);+ } else {+ me.setCenterPoint(0, 0, 0, 0);+ }},- afterUpdate: noop,-- //- beforeSetDimensions: noop,- setDimensions: function() {+ /**+ * Set radius reductions and determine new radius and center point+ * @private+ */+ setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {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;+ var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);+ var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);+ var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);+ var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);- // Reset position before calculating rotation- me.top = 0;- me.bottom = me.height;- }+ radiusReductionLeft = numberOrZero(radiusReductionLeft);+ radiusReductionRight = numberOrZero(radiusReductionRight);+ radiusReductionTop = numberOrZero(radiusReductionTop);+ radiusReductionBottom = numberOrZero(radiusReductionBottom);- // Reset padding- me.paddingLeft = 0;- me.paddingTop = 0;- me.paddingRight = 0;- me.paddingBottom = 0;+ me.drawingArea = Math.min(+ Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),+ Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));+ me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);+ },- // Reset minSize- me.minSize = {- width: 0,- height: 0- };+ setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {+ var me = this;+ var maxRight = me.width - rightMovement - me.drawingArea;+ var maxLeft = leftMovement + me.drawingArea;+ var maxTop = topMovement + me.drawingArea;+ var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;++ me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);+ me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);},- afterSetDimensions: noop,- //+ getIndexAngle: function(index) {+ var chart = this.chart;+ var angleMultiplier = 360 / chart.data.labels.length;+ var options = chart.options || {};+ var startAngle = options.startAngle || 0;- beforeBuildLabels: noop,- buildLabels: function() {+ // Start from the top instead of right, so remove a quarter of the circle+ var angle = (index * angleMultiplier + startAngle) % 360;++ return (angle < 0 ? angle + 360 : angle) * Math.PI * 2 / 360;+ },++ getDistanceFromCenterForValue: function(value) {var me = this;- var labelOpts = me.options.labels || {};- var legendItems = helpers.callback(labelOpts.generateLabels, [me.chart], me) || [];- if (labelOpts.filter) {- legendItems = legendItems.filter(function(item) {- return labelOpts.filter(item, me.chart.data);- });+ if (helpers$1.isNullOrUndef(value)) {+ return NaN;}- if (me.options.reverse) {- legendItems.reverse();+ // Take into account half font size + the yPadding of the top value+ var scalingFactor = me.drawingArea / (me.max - me.min);+ if (me.options.ticks.reverse) {+ return (me.max - value) * scalingFactor;}+ return (value - me.min) * scalingFactor;+ },- me.legendItems = legendItems;+ getPointPosition: function(index, distanceFromCenter) {+ var me = this;+ var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);+ return {+ x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter,+ y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter+ };},- afterBuildLabels: noop,- //+ getPointPositionForValue: function(index, value) {+ return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));+ },- beforeFit: noop,- fit: function() {+ getBasePosition: function(index) {var me = this;- var opts = me.options;- var labelOpts = opts.labels;- var display = opts.display;+ var min = me.min;+ var max = me.max;++ return me.getPointPositionForValue(index || 0,+ me.beginAtZero ? 0 :+ min < 0 && max < 0 ? max :+ min > 0 && max > 0 ? min :+ 0);+ },+ /**+ * @private+ */+ _drawGrid: function() {+ var me = this;var ctx = me.ctx;+ var opts = me.options;+ var gridLineOpts = opts.gridLines;+ var angleLineOpts = opts.angleLines;+ var lineWidth = valueOrDefault$c(angleLineOpts.lineWidth, gridLineOpts.lineWidth);+ var lineColor = valueOrDefault$c(angleLineOpts.color, gridLineOpts.color);+ var i, offset, position;- var globalDefault = defaults.global;- var valueOrDefault = helpers.valueOrDefault;- var fontSize = valueOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize);- var fontStyle = valueOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle);- var fontFamily = valueOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily);- var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily);+ if (opts.pointLabels.display) {+ drawPointLabels(me);+ }- // Reset hit boxes- var hitboxes = me.legendHitBoxes = [];+ if (gridLineOpts.display) {+ helpers$1.each(me.ticks, function(label, index) {+ if (index !== 0) {+ offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);+ drawRadiusLine(me, gridLineOpts, offset, index);+ }+ });+ }- var minSize = me.minSize;- var isHorizontal = me.isHorizontal();+ if (angleLineOpts.display && lineWidth && lineColor) {+ ctx.save();+ ctx.lineWidth = lineWidth;+ ctx.strokeStyle = lineColor;+ if (ctx.setLineDash) {+ ctx.setLineDash(resolve$4([angleLineOpts.borderDash, gridLineOpts.borderDash, []]));+ ctx.lineDashOffset = resolve$4([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]);+ }- 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+ for (i = me.chart.data.labels.length - 1; i >= 0; i--) {+ offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max);+ position = me.getPointPosition(i, offset);+ ctx.beginPath();+ ctx.moveTo(me.xCenter, me.yCenter);+ ctx.lineTo(position.x, position.y);+ ctx.stroke();+ }++ ctx.restore();}+ },- // Increase sizes here- if (display) {- ctx.font = labelFont;+ /**+ * @private+ */+ _drawLabels: function() {+ var me = this;+ var ctx = me.ctx;+ var opts = me.options;+ var tickOpts = opts.ticks;- if (isHorizontal) {- // Labels+ if (!tickOpts.display) {+ return;+ }- // 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 = me.legendItems.length ? fontSize + (labelOpts.padding) : 0;+ var startAngle = me.getIndexAngle(0);+ var tickFont = helpers$1.options._parseFont(tickOpts);+ var tickFontColor = valueOrDefault$c(tickOpts.fontColor, core_defaults.global.defaultFontColor);+ var offset, width;- ctx.textAlign = 'left';- ctx.textBaseline = 'top';+ ctx.save();+ ctx.font = tickFont.string;+ ctx.translate(me.xCenter, me.yCenter);+ ctx.rotate(startAngle);+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';++ helpers$1.each(me.ticks, function(label, index) {+ if (index === 0 && !tickOpts.reverse) {+ return;+ }- helpers.each(me.legendItems, function(legendItem, i) {- var boxWidth = getBoxWidth(labelOpts, fontSize);- var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;+ offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);- if (lineWidths[lineWidths.length - 1] + width + labelOpts.padding >= me.width) {- totalHeight += fontSize + (labelOpts.padding);- lineWidths[lineWidths.length] = me.left;- }+ if (tickOpts.showLabelBackdrop) {+ width = ctx.measureText(label).width;+ ctx.fillStyle = tickOpts.backdropColor;- // Store the hitbox width and height here. Final position will be updated in `draw`- hitboxes[i] = {- left: 0,- top: 0,- width: width,- height: fontSize- };+ ctx.fillRect(+ -width / 2 - tickOpts.backdropPaddingX,+ -offset - tickFont.size / 2 - tickOpts.backdropPaddingY,+ width + tickOpts.backdropPaddingX * 2,+ tickFont.size + tickOpts.backdropPaddingY * 2+ );+ }- lineWidths[lineWidths.length - 1] += width + labelOpts.padding;- });+ ctx.fillStyle = tickFontColor;+ ctx.fillText(label, 0, -offset);+ });- minSize.height += totalHeight;+ ctx.restore();+ },- } else {- var vPadding = labelOpts.padding;- var columnWidths = me.columnWidths = [];- var totalWidth = labelOpts.padding;- var currentColWidth = 0;- var currentColHeight = 0;- var itemHeight = fontSize + vPadding;-- helpers.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 (currentColHeight + itemHeight > minSize.height) {- totalWidth += currentColWidth + labelOpts.padding;- columnWidths.push(currentColWidth); // previous column width-- currentColWidth = 0;- currentColHeight = 0;- }+ /**+ * @private+ */+ _drawTitle: helpers$1.noop+});- // Get max width- currentColWidth = Math.max(currentColWidth, itemWidth);- currentColHeight += itemHeight;+// INTERNAL: static default options, registered in src/index.js+var _defaults$3 = defaultConfig$3;+scale_radialLinear._defaults = _defaults$3;- // Store the hitbox width and height here. Final position will be updated in `draw`- hitboxes[i] = {- left: 0,- top: 0,- width: itemWidth,- height: fontSize- };- });+var deprecated$1 = helpers$1._deprecated;+var resolve$5 = helpers$1.options.resolve;+var valueOrDefault$d = helpers$1.valueOrDefault;- totalWidth += currentColWidth;- columnWidths.push(currentColWidth);- minSize.width += totalWidth;- }- }+// Integer constants are from the ES6 spec.+var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;+var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;- me.width = minSize.width;- me.height = minSize.height;+var INTERVALS = {+ millisecond: {+ common: true,+ size: 1,+ steps: 1000},- afterFit: noop,-- // Shared Methods- isHorizontal: function() {- return this.options.position === 'top' || this.options.position === 'bottom';+ second: {+ common: true,+ size: 1000,+ steps: 60},+ minute: {+ common: true,+ size: 60000,+ steps: 60+ },+ hour: {+ common: true,+ size: 3600000,+ steps: 24+ },+ day: {+ common: true,+ size: 86400000,+ steps: 30+ },+ week: {+ common: false,+ size: 604800000,+ steps: 4+ },+ month: {+ common: true,+ size: 2.628e9,+ steps: 12+ },+ quarter: {+ common: false,+ size: 7.884e9,+ steps: 4+ },+ year: {+ common: true,+ size: 3.154e10+ }+};- // Actually draw the legend on the canvas- draw: function() {- var me = this;- var opts = me.options;- var labelOpts = opts.labels;- var globalDefault = defaults.global;- var lineDefault = globalDefault.elements.line;- var legendWidth = me.width;- var lineWidths = me.lineWidths;-- if (opts.display) {- var ctx = me.ctx;- var valueOrDefault = helpers.valueOrDefault;- var fontColor = valueOrDefault(labelOpts.fontColor, globalDefault.defaultFontColor);- var fontSize = valueOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize);- var fontStyle = valueOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle);- var fontFamily = valueOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily);- var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily);- 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;-- var boxWidth = getBoxWidth(labelOpts, fontSize);- var hitboxes = me.legendHitBoxes;-- // current position- var drawLegendBox = function(x, y, legendItem) {- if (isNaN(boxWidth) || boxWidth <= 0) {- return;- }+var UNITS = Object.keys(INTERVALS);- // Set the ctx for the box- ctx.save();+function sorter(a, b) {+ return a - b;+}- ctx.fillStyle = valueOrDefault(legendItem.fillStyle, globalDefault.defaultColor);- ctx.lineCap = valueOrDefault(legendItem.lineCap, lineDefault.borderCapStyle);- ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, lineDefault.borderDashOffset);- ctx.lineJoin = valueOrDefault(legendItem.lineJoin, lineDefault.borderJoinStyle);- ctx.lineWidth = valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth);- ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, globalDefault.defaultColor);- var isLineWidthZero = (valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth) === 0);+function arrayUnique(items) {+ var hash = {};+ var out = [];+ var i, ilen, item;- if (ctx.setLineDash) {- // IE 9 and 10 do not support line dash- ctx.setLineDash(valueOrDefault(legendItem.lineDash, lineDefault.borderDash));- }+ for (i = 0, ilen = items.length; i < ilen; ++i) {+ item = items[i];+ if (!hash[item]) {+ hash[item] = true;+ out.push(item);+ }+ }- 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 = fontSize * Math.SQRT2 / 2;- var offSet = radius / Math.SQRT2;- var centerX = x + offSet;- var centerY = y + offSet;+ return out;+}- // Draw pointStyle as legend symbol- helpers.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY);- } else {- // Draw box as legend symbol- if (!isLineWidthZero) {- ctx.strokeRect(x, y, boxWidth, fontSize);- }- ctx.fillRect(x, y, boxWidth, fontSize);- }+function getMin(options) {+ return helpers$1.valueOrDefault(options.time.min, options.ticks.min);+}- 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();- }- };+function getMax(options) {+ return helpers$1.valueOrDefault(options.time.max, options.ticks.max);+}- // Horizontal- var isHorizontal = me.isHorizontal();- if (isHorizontal) {- cursor = {- x: me.left + ((legendWidth - lineWidths[0]) / 2),- y: me.top + labelOpts.padding,- line: 0- };- } else {- cursor = {- x: me.left + labelOpts.padding,- y: me.top + labelOpts.padding,- line: 0- };- }+/**+ * Returns an array of {time, pos} objects used to interpolate a specific `time` or position+ * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is+ * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other+ * extremity (left + width or top + height). Note that it would be more optimized to directly+ * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need+ * to create the lookup table. The table ALWAYS contains at least two items: min and max.+ *+ * @param {number[]} timestamps - timestamps sorted from lowest to highest.+ * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min+ * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.+ * If 'series', timestamps will be positioned at the same distance from each other. In this+ * case, only timestamps that break the time linearity are registered, meaning that in the+ * best case, all timestamps are linear, the table contains only min and max.+ */+function buildLookupTable(timestamps, min, max, distribution) {+ if (distribution === 'linear' || !timestamps.length) {+ return [+ {time: min, pos: 0},+ {time: max, pos: 1}+ ];+ }- var itemHeight = fontSize + labelOpts.padding;- helpers.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;+ var table = [];+ var items = [min];+ var i, ilen, prev, curr, next;- if (isHorizontal) {- if (x + width >= legendWidth) {- y = cursor.y += itemHeight;- cursor.line++;- x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2);- }- } else if (y + itemHeight > me.bottom) {- x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;- y = cursor.y = me.top + labelOpts.padding;- cursor.line++;- }+ for (i = 0, ilen = timestamps.length; i < ilen; ++i) {+ curr = timestamps[i];+ if (curr > min && curr < max) {+ items.push(curr);+ }+ }- drawLegendBox(x, y, legendItem);+ items.push(max);- hitboxes[i].left = x;- hitboxes[i].top = y;+ for (i = 0, ilen = items.length; i < ilen; ++i) {+ next = items[i + 1];+ prev = items[i - 1];+ curr = items[i];- // Fill the actual label- fillText(x, y, legendItem, textWidth);+ // only add points that breaks the scale linearity+ if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {+ table.push({time: curr, pos: i / (ilen - 1)});+ }+ }- if (isHorizontal) {- cursor.x += width + (labelOpts.padding);- } else {- cursor.y += itemHeight;- }+ return table;+}- });- }- },+// @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/+function lookup(table, key, value) {+ var lo = 0;+ var hi = table.length - 1;+ var mid, i0, i1;- /**- * Handle an event- * @private- * @param {IEvent} event - The event to handle- * @return {Boolean} true if a change occured- */- handleEvent: function(e) {- var me = this;- var opts = me.options;- var type = e.type === 'mouseup' ? 'click' : e.type;- var changed = false;+ while (lo >= 0 && lo <= hi) {+ mid = (lo + hi) >> 1;+ i0 = table[mid - 1] || null;+ i1 = table[mid];- if (type === 'mousemove') {- if (!opts.onHover) {- return;- }- } else if (type === 'click') {- if (!opts.onClick) {- return;- }+ if (!i0) {+ // given value is outside table (before first item)+ return {lo: null, hi: i1};+ } else if (i1[key] < value) {+ lo = mid + 1;+ } else if (i0[key] > value) {+ hi = mid - 1;} else {- return;+ return {lo: i0, hi: i1};}+ }- // Chart event already has relative position in it- var x = e.x;- var y = e.y;-- if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {- // See if we are touching one of the dataset boxes- var lh = me.legendHitBoxes;- for (var i = 0; i < lh.length; ++i) {- var hitBox = lh[i];+ // given value is outside table (after last item)+ return {lo: i1, hi: null};+}- if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {- // Touching an element- if (type === 'click') {- // use e.native for backwards compatibility- opts.onClick.call(me, e.native, me.legendItems[i]);- changed = true;- break;- } else if (type === 'mousemove') {- // use e.native for backwards compatibility- opts.onHover.call(me, e.native, me.legendItems[i]);- changed = true;- break;- }- }- }- }+/**+ * Linearly interpolates the given source `value` using the table items `skey` values and+ * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')+ * returns the position for a timestamp equal to 42. If value is out of bounds, values at+ * index [0, 1] or [n - 1, n] are used for the interpolation.+ */+function interpolate$1(table, skey, sval, tkey) {+ var range = lookup(table, skey, sval);- return changed;- }-});+ // Note: the lookup table ALWAYS contains at least 2 items (min and max)+ var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;+ var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;-function createNewLegendAndAttach(chart, legendOpts) {- var legend = new Legend({- ctx: chart.ctx,- options: legendOpts,- chart: chart- });+ var span = next[skey] - prev[skey];+ var ratio = span ? (sval - prev[skey]) / span : 0;+ var offset = (next[tkey] - prev[tkey]) * ratio;- layouts.configure(chart, legend, legendOpts);- layouts.addBox(chart, legend);- chart.legend = legend;+ return prev[tkey] + offset;}-module.exports = {- 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;+function toTimestamp(scale, input) {+ var adapter = scale._adapter;+ var options = scale.options.time;+ var parser = options.parser;+ var format = parser || options.format;+ var value = input;- if (legendOpts) {- createNewLegendAndAttach(chart, legendOpts);- }- },+ if (typeof parser === 'function') {+ value = parser(value);+ }- beforeUpdate: function(chart) {- var legendOpts = chart.options.legend;- var legend = chart.legend;+ // Only parse if its not a timestamp already+ if (!helpers$1.isFinite(value)) {+ value = typeof format === 'string'+ ? adapter.parse(value, format)+ : adapter.parse(value);+ }- if (legendOpts) {- helpers.mergeIf(legendOpts, defaults.global.legend);+ if (value !== null) {+ return +value;+ }- if (legend) {- layouts.configure(chart, legend, legendOpts);- legend.options = legendOpts;- } else {- createNewLegendAndAttach(chart, legendOpts);- }- } else if (legend) {- layouts.removeBox(chart, legend);- delete chart.legend;- }- },+ // Labels are in an incompatible format and no `parser` has been provided.+ // The user might still use the deprecated `format` option for parsing.+ if (!parser && typeof format === 'function') {+ value = format(input);- afterEvent: function(chart, e) {- var legend = chart.legend;- if (legend) {- legend.handleEvent(e);+ // `format` could return something else than a timestamp, if so, parse it+ if (!helpers$1.isFinite(value)) {+ value = adapter.parse(value);}}-};-},{"26":26,"27":27,"31":31,"46":46}],53:[function(require,module,exports){-'use strict';+ return value;+}-var defaults = require(26);-var Element = require(27);-var helpers = require(46);-var layouts = require(31);+function parse(scale, input) {+ if (helpers$1.isNullOrUndef(input)) {+ return null;+ }-var noop = helpers.noop;+ var options = scale.options.time;+ var value = toTimestamp(scale, scale.getRightValue(input));+ if (value === null) {+ return value;+ }-defaults._set('global', {- title: {- display: false,- fontStyle: 'bold',- fullWidth: true,- lineHeight: 1.2,- padding: 10,- position: 'top',- text: '',- weight: 2000 // by default greater than legend (1000) to be above+ if (options.round) {+ value = +scale._adapter.startOf(value, options.round);}-});++ return value;+}/**- * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!+ * Figures out what unit results in an appropriate number of auto-generated ticks*/-var Title = Element.extend({- initialize: function(config) {- var me = this;- helpers.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,- update: function(maxWidth, maxHeight, margins) {- var me = this;+function determineUnitForAutoTicks(minUnit, min, max, capacity) {+ var ilen = UNITS.length;+ var i, interval, factor;- // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)- me.beforeUpdate();+ for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {+ interval = INTERVALS[UNITS[i]];+ factor = interval.steps ? interval.steps : MAX_INTEGER;- // Absorb the master measurements- me.maxWidth = maxWidth;- me.maxHeight = maxHeight;- me.margins = margins;+ if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {+ return UNITS[i];+ }+ }- // Dimensions- me.beforeSetDimensions();- me.setDimensions();- me.afterSetDimensions();- // Labels- me.beforeBuildLabels();- me.buildLabels();- me.afterBuildLabels();+ return UNITS[ilen - 1];+}- // Fit- me.beforeFit();- me.fit();- me.afterFit();- //- me.afterUpdate();+/**+ * Figures out what unit to format a set of ticks with+ */+function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {+ var i, unit;- return me.minSize;+ for (i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {+ unit = UNITS[i];+ if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {+ return unit;+ }+ }- },- afterUpdate: noop,+ return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];+}- //+function determineMajorUnit(unit) {+ for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {+ if (INTERVALS[UNITS[i]].common) {+ return UNITS[i];+ }+ }+}- beforeSetDimensions: noop,- 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;+/**+ * Generates a maximum of `capacity` timestamps between min and max, rounded to the+ * `minor` unit using the given scale time `options`.+ * Important: this method can return ticks outside the min and max range, it's the+ * responsibility of the calling code to clamp values if needed.+ */+function generate(scale, min, max, capacity) {+ var adapter = scale._adapter;+ var options = scale.options;+ var timeOpts = options.time;+ var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);+ var stepSize = resolve$5([timeOpts.stepSize, timeOpts.unitStepSize, 1]);+ var weekday = minor === 'week' ? timeOpts.isoWeekday : false;+ var first = min;+ var ticks = [];+ var time;- // Reset position before calculating rotation- me.top = 0;- me.bottom = me.height;- }+ // For 'week' unit, handle the first day of week option+ if (weekday) {+ first = +adapter.startOf(first, 'isoWeek', weekday);+ }- // Reset padding- me.paddingLeft = 0;- me.paddingTop = 0;- me.paddingRight = 0;- me.paddingBottom = 0;+ // Align first ticks on unit+ first = +adapter.startOf(first, weekday ? 'day' : minor);- // Reset minSize- me.minSize = {- width: 0,- height: 0- };- },- afterSetDimensions: noop,+ // Prevent browser from freezing in case user options request millions of milliseconds+ if (adapter.diff(max, min, minor) > 100000 * stepSize) {+ throw min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor;+ }- //+ for (time = first; time < max; time = +adapter.add(time, stepSize, minor)) {+ ticks.push(time);+ }- beforeBuildLabels: noop,- buildLabels: noop,- afterBuildLabels: noop,+ if (time === max || options.bounds === 'ticks') {+ ticks.push(time);+ }- //+ return ticks;+}- beforeFit: noop,- fit: function() {- var me = this;- var valueOrDefault = helpers.valueOrDefault;- var opts = me.options;- var display = opts.display;- var fontSize = valueOrDefault(opts.fontSize, defaults.global.defaultFontSize);- var minSize = me.minSize;- var lineCount = helpers.isArray(opts.text) ? opts.text.length : 1;- var lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize);- var textSize = display ? (lineCount * lineHeight) + (opts.padding * 2) : 0;+/**+ * Returns the start and end offsets from edges in the form of {start, end}+ * where each value is a relative width to the scale and ranges between 0 and 1.+ * They add extra margins on the both sides by scaling down the original scale.+ * Offsets are added when the `offset` option is true.+ */+function computeOffsets(table, ticks, min, max, options) {+ var start = 0;+ var end = 0;+ var first, last;- if (me.isHorizontal()) {- minSize.width = me.maxWidth; // fill all the width- minSize.height = textSize;+ if (options.offset && ticks.length) {+ first = interpolate$1(table, 'time', ticks[0], 'pos');+ if (ticks.length === 1) {+ start = 1 - first;} else {- minSize.width = textSize;- minSize.height = me.maxHeight; // fill all the height+ start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2;}+ last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos');+ if (ticks.length === 1) {+ end = last;+ } else {+ end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2;+ }+ }- me.width = minSize.width;- me.height = minSize.height;-- },- afterFit: noop,+ return {start: start, end: end, factor: 1 / (start + 1 + end)};+}- // Shared Methods- isHorizontal: function() {- var pos = this.options.position;- return pos === 'top' || pos === 'bottom';- },+function setMajorTicks(scale, ticks, map, majorUnit) {+ var adapter = scale._adapter;+ var first = +adapter.startOf(ticks[0].value, majorUnit);+ var last = ticks[ticks.length - 1].value;+ var major, index;- // Actually draw the title block on the canvas- draw: function() {- var me = this;- var ctx = me.ctx;- var valueOrDefault = helpers.valueOrDefault;- var opts = me.options;- var globalDefaults = defaults.global;-- if (opts.display) {- var fontSize = valueOrDefault(opts.fontSize, globalDefaults.defaultFontSize);- var fontStyle = valueOrDefault(opts.fontStyle, globalDefaults.defaultFontStyle);- var fontFamily = valueOrDefault(opts.fontFamily, globalDefaults.defaultFontFamily);- var titleFont = helpers.fontString(fontSize, fontStyle, fontFamily);- var lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize);- 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 = valueOrDefault(opts.fontColor, globalDefaults.defaultFontColor); // render in correct colour- ctx.font = titleFont;-- // 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);- }+ for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {+ index = map[major];+ if (index >= 0) {+ ticks[index].major = true;+ }+ }+ return ticks;+}- ctx.save();- ctx.translate(titleX, titleY);- ctx.rotate(rotation);- ctx.textAlign = 'center';- ctx.textBaseline = 'middle';+function ticksFromTimestamps(scale, values, majorUnit) {+ var ticks = [];+ var map = {};+ var ilen = values.length;+ var i, value;- var text = opts.text;- if (helpers.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);- }+ for (i = 0; i < ilen; ++i) {+ value = values[i];+ map[value] = i;- ctx.restore();- }+ ticks.push({+ value: value,+ major: false+ });}-});--function createNewTitleBlockAndAttach(chart, titleOpts) {- var title = new Title({- ctx: chart.ctx,- options: titleOpts,- chart: chart- });- layouts.configure(chart, title, titleOpts);- layouts.addBox(chart, title);- chart.titleBlock = title;+ // We set the major ticks separately from the above loop because calling startOf for every tick+ // is expensive when there is a large number of ticks+ return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);}-module.exports = {- id: 'title',+var defaultConfig$4 = {+ position: 'bottom',/**- * 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+ * Data distribution along the scale:+ * - 'linear': data are spread according to their time (distances can vary),+ * - 'series': data are spread at the same distance from each other.+ * @see https://github.com/chartjs/Chart.js/pull/4507+ * @since 2.7.0*/- _element: Title,-- beforeInit: function(chart) {- var titleOpts = chart.options.title;+ distribution: 'linear',- if (titleOpts) {- createNewTitleBlockAndAttach(chart, titleOpts);- }+ /**+ * Scale boundary strategy (bypassed by min/max time options)+ * - `data`: make sure data are fully visible, ticks outside are removed+ * - `ticks`: make sure ticks are fully visible, data outside are truncated+ * @see https://github.com/chartjs/Chart.js/pull/4556+ * @since 2.7.0+ */+ bounds: 'data',++ adapters: {},+ time: {+ parser: false, // false == a pattern string from https://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment+ unit: false, // false == automatic or override with week, month, year, etc.+ round: false, // none, or override with week, month, year, etc.+ displayFormat: false, // DEPRECATED+ isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/+ minUnit: 'millisecond',+ displayFormats: {}},+ ticks: {+ autoSkip: false,- beforeUpdate: function(chart) {- var titleOpts = chart.options.title;- var titleBlock = chart.titleBlock;-- if (titleOpts) {- helpers.mergeIf(titleOpts, defaults.global.title);+ /**+ * Ticks generation input values:+ * - 'auto': generates "optimal" ticks based on scale size and time options.+ * - 'data': generates ticks from data (including labels from data {t|x|y} objects).+ * - 'labels': generates ticks from user given `data.labels` values ONLY.+ * @see https://github.com/chartjs/Chart.js/pull/4507+ * @since 2.7.0+ */+ source: 'auto',- if (titleBlock) {- layouts.configure(chart, titleBlock, titleOpts);- titleBlock.options = titleOpts;- } else {- createNewTitleBlockAndAttach(chart, titleOpts);- }- } else if (titleBlock) {- layouts.removeBox(chart, titleBlock);- delete chart.titleBlock;+ major: {+ enabled: false}}};-},{"26":26,"27":27,"31":31,"46":46}],54:[function(require,module,exports){-'use strict';--var Scale = require(33);-var scaleService = require(34);+var scale_time = core_scale.extend({+ initialize: function() {+ this.mergeTicksOptions();+ core_scale.prototype.initialize.call(this);+ },-module.exports = function() {+ update: function() {+ var me = this;+ var options = me.options;+ var time = options.time || (options.time = {});+ var adapter = me._adapter = new core_adapters._date(options.adapters.date);- // Default config for a category scale- var defaultConfig = {- position: 'bottom'- };+ // DEPRECATIONS: output a message only one time per update+ deprecated$1('time scale', time.format, 'time.format', 'time.parser');+ deprecated$1('time scale', time.min, 'time.min', 'ticks.min');+ deprecated$1('time scale', time.max, 'time.max', 'ticks.max');- var DatasetScale = Scale.extend({- /**- * Internal function to get the correct labels. If data.xLabels or data.yLabels are defined, use those- * else fall back to data.labels- * @private- */- getLabels: function() {- var data = this.chart.data;- return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels;- },+ // Backward compatibility: before introducing adapter, `displayFormats` was+ // supposed to contain *all* unit/string pairs but this can't be resolved+ // when loading the scale (adapters are loaded afterward), so let's populate+ // missing formats on update+ helpers$1.mergeIf(time.displayFormats, adapter.formats());- determineDataLimits: function() {- var me = this;- var labels = me.getLabels();- me.minIndex = 0;- me.maxIndex = labels.length - 1;- var findIndex;+ return core_scale.prototype.update.apply(me, arguments);+ },- if (me.options.ticks.min !== undefined) {- // user specified min value- findIndex = labels.indexOf(me.options.ticks.min);- me.minIndex = findIndex !== -1 ? findIndex : me.minIndex;- }+ /**+ * Allows data to be referenced via 't' attribute+ */+ getRightValue: function(rawValue) {+ if (rawValue && rawValue.t !== undefined) {+ rawValue = rawValue.t;+ }+ return core_scale.prototype.getRightValue.call(this, rawValue);+ },- if (me.options.ticks.max !== undefined) {- // user specified max value- findIndex = labels.indexOf(me.options.ticks.max);- me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex;- }+ determineDataLimits: function() {+ var me = this;+ var chart = me.chart;+ var adapter = me._adapter;+ var options = me.options;+ var unit = options.time.unit || 'day';+ var min = MAX_INTEGER;+ var max = MIN_INTEGER;+ var timestamps = [];+ var datasets = [];+ var labels = [];+ var i, j, ilen, jlen, data, timestamp, labelsAdded;+ var dataLabels = me._getLabels();- me.min = labels[me.minIndex];- me.max = labels[me.maxIndex];- },+ for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {+ labels.push(parse(me, dataLabels[i]));+ }- buildTicks: function() {- var me = this;- var labels = me.getLabels();- // If we are viewing some subset of labels, slice the original array- me.ticks = (me.minIndex === 0 && me.maxIndex === labels.length - 1) ? labels : labels.slice(me.minIndex, me.maxIndex + 1);- },+ for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {+ if (chart.isDatasetVisible(i)) {+ data = chart.data.datasets[i].data;- getLabelForIndex: function(index, datasetIndex) {- var me = this;- var data = me.chart.data;- var isHorizontal = me.isHorizontal();+ // Let's consider that all data have the same format.+ if (helpers$1.isObject(data[0])) {+ datasets[i] = [];- if (data.yLabels && !isHorizontal) {- return me.getRightValue(data.datasets[datasetIndex].data[index]);+ for (j = 0, jlen = data.length; j < jlen; ++j) {+ timestamp = parse(me, data[j]);+ timestamps.push(timestamp);+ datasets[i][j] = timestamp;+ }+ } else {+ datasets[i] = labels.slice(0);+ if (!labelsAdded) {+ timestamps = timestamps.concat(labels);+ labelsAdded = true;+ }+ }+ } else {+ datasets[i] = [];}- return me.ticks[index - me.minIndex];- },+ }- // Used to get data value locations. Value can either be an index or a numerical value- getPixelForValue: function(value, index) {- var me = this;- var offset = me.options.offset;- // 1 is added because we need the length but we have the indexes- var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - (offset ? 0 : 1)), 1);+ if (labels.length) {+ min = Math.min(min, labels[0]);+ max = Math.max(max, labels[labels.length - 1]);+ }- // If value is a data object, then index is the index in the data array,- // not the index of the scale. We need to change that.- var valueCategory;- if (value !== undefined && value !== null) {- valueCategory = me.isHorizontal() ? value.x : value.y;- }- if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {- var labels = me.getLabels();- value = valueCategory || value;- var idx = labels.indexOf(value);- index = idx !== -1 ? idx : index;- }+ if (timestamps.length) {+ timestamps = ilen > 1 ? arrayUnique(timestamps).sort(sorter) : timestamps.sort(sorter);+ min = Math.min(min, timestamps[0]);+ max = Math.max(max, timestamps[timestamps.length - 1]);+ }- if (me.isHorizontal()) {- var valueWidth = me.width / offsetAmt;- var widthOffset = (valueWidth * (index - me.minIndex));+ min = parse(me, getMin(options)) || min;+ max = parse(me, getMax(options)) || max;- if (offset) {- widthOffset += (valueWidth / 2);- }+ // In case there is no valid min/max, set limits based on unit time option+ min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min;+ max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max;- return me.left + Math.round(widthOffset);- }- var valueHeight = me.height / offsetAmt;- var heightOffset = (valueHeight * (index - me.minIndex));+ // Make sure that max is strictly higher than min (required by the lookup table)+ me.min = Math.min(min, max);+ me.max = Math.max(min + 1, max);- if (offset) {- heightOffset += (valueHeight / 2);- }+ // PRIVATE+ me._table = [];+ me._timestamps = {+ data: timestamps,+ datasets: datasets,+ labels: labels+ };+ },- return me.top + Math.round(heightOffset);- },- getPixelForTick: function(index) {- return this.getPixelForValue(this.ticks[index], index + this.minIndex, null);- },- getValueForPixel: function(pixel) {- var me = this;- var offset = me.options.offset;- var value;- var offsetAmt = Math.max((me._ticks.length - (offset ? 0 : 1)), 1);- var horz = me.isHorizontal();- var valueDimension = (horz ? me.width : me.height) / offsetAmt;+ buildTicks: function() {+ var me = this;+ var min = me.min;+ var max = me.max;+ var options = me.options;+ var tickOpts = options.ticks;+ var timeOpts = options.time;+ var timestamps = me._timestamps;+ var ticks = [];+ var capacity = me.getLabelCapacity(min);+ var source = tickOpts.source;+ var distribution = options.distribution;+ var i, ilen, timestamp;++ if (source === 'data' || (source === 'auto' && distribution === 'series')) {+ timestamps = timestamps.data;+ } else if (source === 'labels') {+ timestamps = timestamps.labels;+ } else {+ timestamps = generate(me, min, max, capacity);+ }- pixel -= horz ? me.left : me.top;+ if (options.bounds === 'ticks' && timestamps.length) {+ min = timestamps[0];+ max = timestamps[timestamps.length - 1];+ }- if (offset) {- pixel -= (valueDimension / 2);- }+ // Enforce limits with user min/max options+ min = parse(me, getMin(options)) || min;+ max = parse(me, getMax(options)) || max;- if (pixel <= 0) {- value = 0;- } else {- value = Math.round(pixel / valueDimension);+ // Remove ticks outside the min/max range+ for (i = 0, ilen = timestamps.length; i < ilen; ++i) {+ timestamp = timestamps[i];+ if (timestamp >= min && timestamp <= max) {+ ticks.push(timestamp);}+ }- return value + me.minIndex;- },- getBasePixel: function() {- return this.bottom;+ me.min = min;+ me.max = max;++ // PRIVATE+ // determineUnitForFormatting relies on the number of ticks so we don't use it when+ // autoSkip is enabled because we don't yet know what the final number of ticks will be+ me._unit = timeOpts.unit || (tickOpts.autoSkip+ ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, capacity)+ : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));+ me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined+ : determineMajorUnit(me._unit);+ me._table = buildLookupTable(me._timestamps.data, min, max, distribution);+ me._offsets = computeOffsets(me._table, ticks, min, max, options);++ if (tickOpts.reverse) {+ ticks.reverse();}- });- scaleService.registerScaleType('category', DatasetScale, defaultConfig);-};+ return ticksFromTimestamps(me, ticks, me._majorUnit);+ },-},{"33":33,"34":34}],55:[function(require,module,exports){-'use strict';+ getLabelForIndex: function(index, datasetIndex) {+ var me = this;+ var adapter = me._adapter;+ var data = me.chart.data;+ var timeOpts = me.options.time;+ var label = data.labels && index < data.labels.length ? data.labels[index] : '';+ var value = data.datasets[datasetIndex].data[index];-var defaults = require(26);-var helpers = require(46);-var scaleService = require(34);-var Ticks = require(35);+ if (helpers$1.isObject(value)) {+ label = me.getRightValue(value);+ }+ if (timeOpts.tooltipFormat) {+ return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat);+ }+ if (typeof label === 'string') {+ return label;+ }+ return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime);+ },-module.exports = function(Chart) {+ /**+ * Function to format an individual tick mark+ * @private+ */+ tickFormatFunction: function(time, index, ticks, format) {+ var me = this;+ var adapter = me._adapter;+ var options = me.options;+ var formats = options.time.displayFormats;+ var minorFormat = formats[me._unit];+ var majorUnit = me._majorUnit;+ var majorFormat = formats[majorUnit];+ var tick = ticks[index];+ var tickOpts = options.ticks;+ var major = majorUnit && majorFormat && tick && tick.major;+ var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat);+ var nestedTickOpts = major ? tickOpts.major : tickOpts.minor;+ var formatter = resolve$5([+ nestedTickOpts.callback,+ nestedTickOpts.userCallback,+ tickOpts.callback,+ tickOpts.userCallback+ ]);++ return formatter ? formatter(label, index, ticks) : label;+ },++ convertTicksToLabels: function(ticks) {+ var labels = [];+ var i, ilen;- var defaultConfig = {- position: 'left',- ticks: {- callback: Ticks.formatters.linear+ for (i = 0, ilen = ticks.length; i < ilen; ++i) {+ labels.push(this.tickFormatFunction(ticks[i].value, i, ticks));}- };- var LinearScale = Chart.LinearScaleBase.extend({+ return labels;+ },- determineDataLimits: function() {- var me = this;- var opts = me.options;- var chart = me.chart;- var data = chart.data;- var datasets = data.datasets;- var isHorizontal = me.isHorizontal();- var DEFAULT_MIN = 0;- var DEFAULT_MAX = 1;+ /**+ * @private+ */+ getPixelForOffset: function(time) {+ var me = this;+ var offsets = me._offsets;+ var pos = interpolate$1(me._table, 'time', time, 'pos');+ return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);+ },- function IDMatches(meta) {- return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;- }+ getPixelForValue: function(value, index, datasetIndex) {+ var me = this;+ var time = null;- // First Calculate the range- me.min = null;- me.max = null;+ if (index !== undefined && datasetIndex !== undefined) {+ time = me._timestamps.datasets[datasetIndex][index];+ }- var hasStacks = opts.stacked;- if (hasStacks === undefined) {- helpers.each(datasets, function(dataset, datasetIndex) {- if (hasStacks) {- return;- }+ if (time === null) {+ time = parse(me, value);+ }- var meta = chart.getDatasetMeta(datasetIndex);- if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&- meta.stack !== undefined) {- hasStacks = true;- }- });- }+ if (time !== null) {+ return me.getPixelForOffset(time);+ }+ },- if (opts.stacked || hasStacks) {- var valuesPerStack = {};+ getPixelForTick: function(index) {+ var ticks = this.getTicks();+ return index >= 0 && index < ticks.length ?+ this.getPixelForOffset(ticks[index].value) :+ null;+ },- helpers.each(datasets, function(dataset, datasetIndex) {- var meta = chart.getDatasetMeta(datasetIndex);- var key = [- meta.type,- // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined- ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),- meta.stack- ].join('.');+ getValueForPixel: function(pixel) {+ var me = this;+ var offsets = me._offsets;+ var pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;+ var time = interpolate$1(me._table, 'pos', pos, 'time');- if (valuesPerStack[key] === undefined) {- valuesPerStack[key] = {- positiveValues: [],- negativeValues: []- };- }+ // DEPRECATION, we should return time directly+ return me._adapter._create(time);+ },- // Store these per type- var positiveValues = valuesPerStack[key].positiveValues;- var negativeValues = valuesPerStack[key].negativeValues;-- if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {- helpers.each(dataset.data, function(rawValue, index) {- var value = +me.getRightValue(rawValue);- if (isNaN(value) || meta.data[index].hidden) {- return;- }-- positiveValues[index] = positiveValues[index] || 0;- negativeValues[index] = negativeValues[index] || 0;-- if (opts.relativePoints) {- positiveValues[index] = 100;- } else if (value < 0) {- negativeValues[index] += value;- } else {- positiveValues[index] += value;- }- });- }- });+ /**+ * @private+ */+ _getLabelSize: function(label) {+ var me = this;+ var ticksOpts = me.options.ticks;+ var tickLabelWidth = me.ctx.measureText(label).width;+ var angle = helpers$1.toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);+ var cosRotation = Math.cos(angle);+ var sinRotation = Math.sin(angle);+ var tickFontSize = valueOrDefault$d(ticksOpts.fontSize, core_defaults.global.defaultFontSize);- helpers.each(valuesPerStack, function(valuesForType) {- var values = valuesForType.positiveValues.concat(valuesForType.negativeValues);- var minVal = helpers.min(values);- var maxVal = helpers.max(values);- me.min = me.min === null ? minVal : Math.min(me.min, minVal);- me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);- });+ return {+ w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),+ h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)+ };+ },- } else {- helpers.each(datasets, function(dataset, datasetIndex) {- var meta = chart.getDatasetMeta(datasetIndex);- if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {- helpers.each(dataset.data, function(rawValue, index) {- var value = +me.getRightValue(rawValue);- if (isNaN(value) || meta.data[index].hidden) {- return;- }-- if (me.min === null) {- me.min = value;- } else if (value < me.min) {- me.min = value;- }-- if (me.max === null) {- me.max = value;- } else if (value > me.max) {- me.max = value;- }- });- }- });- }+ /**+ * Crude approximation of what the label width might be+ * @private+ */+ getLabelWidth: function(label) {+ return this._getLabelSize(label).w;+ },++ /**+ * @private+ */+ getLabelCapacity: function(exampleTime) {+ var me = this;+ var timeOpts = me.options.time;+ var displayFormats = timeOpts.displayFormats;- me.min = isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;- me.max = isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;+ // pick the longest format (milliseconds) for guestimation+ var format = displayFormats[timeOpts.unit] || displayFormats.millisecond;+ var exampleLabel = me.tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format);+ var size = me._getLabelSize(exampleLabel);+ var capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h);- // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero- this.handleTickRangeOptions();- },- getTickLimit: function() {- var maxTicks;- var me = this;- var tickOpts = me.options.ticks;+ if (me.options.offset) {+ capacity--;+ }- if (me.isHorizontal()) {- maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.width / 50));- } else {- // The factor of 2 used to scale the font size has been experimentally determined.- var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, defaults.global.defaultFontSize);- maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.height / (2 * tickFontSize)));- }+ return capacity > 0 ? capacity : 1;+ }+});- return maxTicks;- },- // Called after the ticks are built. We need- handleDirectionalChanges: function() {- if (!this.isHorizontal()) {- // We are in a vertical orientation. The top value is the highest. So reverse the array- this.ticks.reverse();- }- },- getLabelForIndex: function(index, datasetIndex) {- return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);- },- // Utils- getPixelForValue: function(value) {- // This must be called after fit has been run so that- // this.left, this.top, this.right, and this.bottom have been defined- var me = this;- var start = me.start;+// INTERNAL: static default options, registered in src/index.js+var _defaults$4 = defaultConfig$4;+scale_time._defaults = _defaults$4;++var scales = {+ category: scale_category,+ linear: scale_linear,+ logarithmic: scale_logarithmic,+ radialLinear: scale_radialLinear,+ time: scale_time+};++var FORMATS = {+ datetime: 'MMM D, YYYY, h:mm:ss a',+ millisecond: 'h:mm:ss.SSS a',+ second: 'h:mm:ss a',+ minute: 'h:mm a',+ hour: 'hA',+ day: 'MMM D',+ week: 'll',+ month: 'MMM YYYY',+ quarter: '[Q]Q - YYYY',+ year: 'YYYY'+};- var rightValue = +me.getRightValue(value);- var pixel;- var range = me.end - start;+core_adapters._date.override(typeof moment === 'function' ? {+ _id: 'moment', // DEBUG ONLY- if (me.isHorizontal()) {- pixel = me.left + (me.width / range * (rightValue - start));- } else {- pixel = me.bottom - (me.height / range * (rightValue - start));- }- return pixel;- },- getValueForPixel: function(pixel) {- var me = this;- var isHorizontal = me.isHorizontal();- var innerDimension = isHorizontal ? me.width : me.height;- var offset = (isHorizontal ? pixel - me.left : me.bottom - pixel) / innerDimension;- return me.start + ((me.end - me.start) * offset);- },- getPixelForTick: function(index) {- return this.getPixelForValue(this.ticksAsNumbers[index]);+ formats: function() {+ return FORMATS;+ },++ parse: function(value, format) {+ if (typeof value === 'string' && typeof format === 'string') {+ value = moment(value, format);+ } else if (!(value instanceof moment)) {+ value = moment(value);}- });+ return value.isValid() ? value.valueOf() : null;+ },- scaleService.registerScaleType('linear', LinearScale, defaultConfig);-};+ format: function(time, format) {+ return moment(time).format(format);+ },-},{"26":26,"34":34,"35":35,"46":46}],56:[function(require,module,exports){-'use strict';+ add: function(time, amount, unit) {+ return moment(time).add(amount, unit).valueOf();+ },-var helpers = require(46);-var Scale = require(33);+ diff: function(max, min, unit) {+ return moment(max).diff(moment(min), unit);+ },-/**- * Generate a set of linear ticks- * @param generationOptions the options used to generate the ticks- * @param dataRange the range of the data- * @returns {Array<Number>} array of tick values- */-function generateTicks(generationOptions, dataRange) {- var ticks = [];- // To get a "nice" value for the tick spacing, we will use the appropriately named- // "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks- // for details.+ startOf: function(time, unit, weekday) {+ time = moment(time);+ if (unit === 'isoWeek') {+ return time.isoWeekday(weekday).valueOf();+ }+ return time.startOf(unit).valueOf();+ },++ endOf: function(time, unit) {+ return moment(time).endOf(unit).valueOf();+ },- var factor;- var precision;- var spacing;+ // DEPRECATIONS- if (generationOptions.stepSize && generationOptions.stepSize > 0) {- spacing = generationOptions.stepSize;- } else {- var niceRange = helpers.niceNum(dataRange.max - dataRange.min, false);- spacing = helpers.niceNum(niceRange / (generationOptions.maxTicks - 1), true);+ /**+ * Provided for backward compatibility with scale.getValueForPixel().+ * @deprecated since version 2.8.0+ * @todo remove at version 3+ * @private+ */+ _create: function(time) {+ return moment(time);+ },+} : {});- precision = generationOptions.precision;- if (precision !== undefined) {- // If the user specified a precision, round to that number of decimal places- factor = Math.pow(10, precision);- spacing = Math.ceil(spacing * factor) / factor;+core_defaults._set('global', {+ plugins: {+ filler: {+ propagate: true}}- var niceMin = Math.floor(dataRange.min / spacing) * spacing;- var niceMax = Math.ceil(dataRange.max / spacing) * spacing;+});- // If min, max and stepSize is set and they make an evenly spaced scale use it.- if (!helpers.isNullOrUndef(generationOptions.min) && !helpers.isNullOrUndef(generationOptions.max) && generationOptions.stepSize) {- // If very close to our whole number, use it.- if (helpers.almostWhole((generationOptions.max - generationOptions.min) / generationOptions.stepSize, spacing / 1000)) {- niceMin = generationOptions.min;- niceMax = generationOptions.max;+var mappers = {+ dataset: function(source) {+ var index = source.fill;+ var chart = source.chart;+ var meta = chart.getDatasetMeta(index);+ var visible = meta && chart.isDatasetVisible(index);+ var points = (visible && meta.dataset._children) || [];+ var length = points.length || 0;++ return !length ? null : function(point, i) {+ return (i < length && points[i]._view) || null;+ };+ },++ boundary: function(source) {+ var boundary = source.boundary;+ var x = boundary ? boundary.x : null;+ var y = boundary ? boundary.y : null;++ if (helpers$1.isArray(boundary)) {+ return function(point, i) {+ return boundary[i];+ };}- }- var numSpaces = (niceMax - niceMin) / spacing;- // If very close to our rounded value, use it.- if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {- numSpaces = Math.round(numSpaces);- } else {- numSpaces = Math.ceil(numSpaces);+ return function(point) {+ return {+ x: x === null ? point.x : x,+ y: y === null ? point.y : y,+ };+ };}+};++// @todo if (fill[0] === '#')+function decodeFill(el, index, count) {+ var model = el._model || {};+ var fill = model.fill;+ var target;- precision = 1;- if (spacing < 1) {- precision = Math.pow(10, 1 - Math.floor(helpers.log10(spacing)));- niceMin = Math.round(niceMin * precision) / precision;- niceMax = Math.round(niceMax * precision) / precision;+ if (fill === undefined) {+ fill = !!model.backgroundColor;}- ticks.push(generationOptions.min !== undefined ? generationOptions.min : niceMin);- for (var j = 1; j < numSpaces; ++j) {- ticks.push(Math.round((niceMin + j * spacing) * precision) / precision);++ if (fill === false || fill === null) {+ return false;}- ticks.push(generationOptions.max !== undefined ? generationOptions.max : niceMax);- return ticks;-}+ if (fill === true) {+ return 'origin';+ }-module.exports = function(Chart) {+ target = parseFloat(fill, 10);+ if (isFinite(target) && Math.floor(target) === target) {+ if (fill[0] === '-' || fill[0] === '+') {+ target = index + target;+ }- var noop = helpers.noop;+ if (target === index || target < 0 || target >= count) {+ return false;+ }- Chart.LinearScaleBase = Scale.extend({- getRightValue: function(value) {- if (typeof value === 'string') {- return +value;- }- return Scale.prototype.getRightValue.call(this, value);- },+ return target;+ }- handleTickRangeOptions: function() {- var me = this;- var opts = me.options;- var tickOpts = opts.ticks;-- // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,- // do nothing since that would make the chart weird. If the user really wants a weird chart- // axis, they can manually override it- if (tickOpts.beginAtZero) {- var minSign = helpers.sign(me.min);- var maxSign = helpers.sign(me.max);-- if (minSign < 0 && maxSign < 0) {- // move the top up to 0- me.max = 0;- } else if (minSign > 0 && maxSign > 0) {- // move the bottom down to 0- me.min = 0;- }- }+ switch (fill) {+ // compatibility+ case 'bottom':+ return 'start';+ case 'top':+ return 'end';+ case 'zero':+ return 'origin';+ // supported boundaries+ case 'origin':+ case 'start':+ case 'end':+ return fill;+ // invalid fill values+ default:+ return false;+ }+}- var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;- var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;+function computeLinearBoundary(source) {+ var model = source.el._model || {};+ var scale = source.el._scale || {};+ var fill = source.fill;+ var target = null;+ var horizontal;- if (tickOpts.min !== undefined) {- me.min = tickOpts.min;- } else if (tickOpts.suggestedMin !== undefined) {- if (me.min === null) {- me.min = tickOpts.suggestedMin;- } else {- me.min = Math.min(me.min, tickOpts.suggestedMin);- }- }+ if (isFinite(fill)) {+ return null;+ }- if (tickOpts.max !== undefined) {- me.max = tickOpts.max;- } else if (tickOpts.suggestedMax !== undefined) {- if (me.max === null) {- me.max = tickOpts.suggestedMax;- } else {- me.max = Math.max(me.max, tickOpts.suggestedMax);- }- }+ // Backward compatibility: until v3, we still need to support boundary values set on+ // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and+ // controllers might still use it (e.g. the Smith chart).- if (setMin !== setMax) {- // We set the min or the max but not both.- // So ensure that our range is good- // Inverted or 0 length range can happen when- // ticks.min is set, and no datasets are visible- if (me.min >= me.max) {- if (setMin) {- me.max = me.min + 1;- } else {- me.min = me.max - 1;- }- }- }+ if (fill === 'start') {+ target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;+ } else if (fill === 'end') {+ target = model.scaleTop === undefined ? scale.top : model.scaleTop;+ } else if (model.scaleZero !== undefined) {+ target = model.scaleZero;+ } else if (scale.getBasePixel) {+ target = scale.getBasePixel();+ }- if (me.min === me.max) {- me.max++;+ if (target !== undefined && target !== null) {+ if (target.x !== undefined && target.y !== undefined) {+ return target;+ }- if (!tickOpts.beginAtZero) {- me.min--;- }- }- },- getTickLimit: noop,- handleDirectionalChanges: noop,-- buildTicks: function() {- var me = this;- var opts = me.options;- var tickOpts = opts.ticks;-- // Figure out what the max number of ticks we can support it is based on the size of- // the axis area. For now, we say that the minimum tick spacing in pixels must be 50- // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on- // the graph. Make sure we always have at least 2 ticks- var maxTicks = me.getTickLimit();- maxTicks = Math.max(2, maxTicks);-- var numericGeneratorOptions = {- maxTicks: maxTicks,- min: tickOpts.min,- max: tickOpts.max,- precision: tickOpts.precision,- stepSize: helpers.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)+ if (helpers$1.isFinite(target)) {+ horizontal = scale.isHorizontal();+ return {+ x: horizontal ? target : null,+ y: horizontal ? null : target};- var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);-- me.handleDirectionalChanges();+ }+ }- // At this point, we need to update our max and min given the tick values since we have expanded the- // range of the scale- me.max = helpers.max(ticks);- me.min = helpers.min(ticks);+ return null;+}- if (tickOpts.reverse) {- ticks.reverse();+function computeCircularBoundary(source) {+ var scale = source.el._scale;+ var options = scale.options;+ var length = scale.chart.data.labels.length;+ var fill = source.fill;+ var target = [];+ var start, end, center, i, point;- me.start = me.max;- me.end = me.min;- } else {- me.start = me.min;- me.end = me.max;- }- },- convertTicksToLabels: function() {- var me = this;- me.ticksAsNumbers = me.ticks.slice();- me.zeroLineIndex = me.ticks.indexOf(0);+ if (!length) {+ return null;+ }- Scale.prototype.convertTicksToLabels.call(me);+ start = options.ticks.reverse ? scale.max : scale.min;+ end = options.ticks.reverse ? scale.min : scale.max;+ center = scale.getPointPositionForValue(0, start);+ for (i = 0; i < length; ++i) {+ point = fill === 'start' || fill === 'end'+ ? scale.getPointPositionForValue(i, fill === 'start' ? start : end)+ : scale.getBasePosition(i);+ if (options.gridLines.circular) {+ point.cx = center.x;+ point.cy = center.y;+ point.angle = scale.getIndexAngle(i) - Math.PI / 2;}- });-};--},{"33":33,"46":46}],57:[function(require,module,exports){-'use strict';--var helpers = require(46);-var Scale = require(33);-var scaleService = require(34);-var Ticks = require(35);--/**- * Generate a set of logarithmic ticks- * @param generationOptions the options used to generate the ticks- * @param dataRange the range of the data- * @returns {Array<Number>} array of tick values- */-function generateTicks(generationOptions, dataRange) {- var ticks = [];- var valueOrDefault = helpers.valueOrDefault;+ target.push(point);+ }+ return target;+}- // Figure out what the max number of ticks we can support it is based on the size of- // the axis area. For now, we say that the minimum tick spacing in pixels must be 50- // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on- // the graph- var tickVal = valueOrDefault(generationOptions.min, Math.pow(10, Math.floor(helpers.log10(dataRange.min))));+function computeBoundary(source) {+ var scale = source.el._scale || {};- var endExp = Math.floor(helpers.log10(dataRange.max));- var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));- var exp, significand;+ if (scale.getPointPositionForValue) {+ return computeCircularBoundary(source);+ }+ return computeLinearBoundary(source);+}- if (tickVal === 0) {- exp = Math.floor(helpers.log10(dataRange.minNotZero));- significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));+function resolveTarget(sources, index, propagate) {+ var source = sources[index];+ var fill = source.fill;+ var visited = [index];+ var target;- ticks.push(tickVal);- tickVal = significand * Math.pow(10, exp);- } else {- exp = Math.floor(helpers.log10(tickVal));- significand = Math.floor(tickVal / Math.pow(10, exp));+ if (!propagate) {+ return fill;}- var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;- do {- ticks.push(tickVal);+ while (fill !== false && visited.indexOf(fill) === -1) {+ if (!isFinite(fill)) {+ return fill;+ }- ++significand;- if (significand === 10) {- significand = 1;- ++exp;- precision = exp >= 0 ? 1 : precision;+ target = sources[fill];+ if (!target) {+ return false;}- tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;- } while (exp < endExp || (exp === endExp && significand < endSignificand));+ if (target.visible) {+ return fill;+ }- var lastTick = valueOrDefault(generationOptions.max, tickVal);- ticks.push(lastTick);+ visited.push(fill);+ fill = target.fill;+ }- return ticks;+ return false;}+function createMapper(source) {+ var fill = source.fill;+ var type = 'dataset';-module.exports = function(Chart) {-- var defaultConfig = {- position: 'left',+ if (fill === false) {+ return null;+ }- // label settings- ticks: {- callback: Ticks.formatters.logarithmic- }- };+ if (!isFinite(fill)) {+ type = 'boundary';+ }- var LogarithmicScale = Scale.extend({- determineDataLimits: function() {- var me = this;- var opts = me.options;- var chart = me.chart;- var data = chart.data;- var datasets = data.datasets;- var isHorizontal = me.isHorizontal();- function IDMatches(meta) {- return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;- }-- // Calculate Range- me.min = null;- me.max = null;- me.minNotZero = null;-- var hasStacks = opts.stacked;- if (hasStacks === undefined) {- helpers.each(datasets, function(dataset, datasetIndex) {- if (hasStacks) {- return;- }+ return mappers[type](source);+}- var meta = chart.getDatasetMeta(datasetIndex);- if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&- meta.stack !== undefined) {- hasStacks = true;- }- });- }+function isDrawable(point) {+ return point && !point.skip;+}- if (opts.stacked || hasStacks) {- var valuesPerStack = {};+function drawArea(ctx, curve0, curve1, len0, len1) {+ var i, cx, cy, r;- helpers.each(datasets, function(dataset, datasetIndex) {- var meta = chart.getDatasetMeta(datasetIndex);- var key = [- meta.type,- // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined- ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),- meta.stack- ].join('.');+ if (!len0 || !len1) {+ return;+ }- if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {- if (valuesPerStack[key] === undefined) {- valuesPerStack[key] = [];- }+ // building first area curve (normal)+ ctx.moveTo(curve0[0].x, curve0[0].y);+ for (i = 1; i < len0; ++i) {+ helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);+ }- helpers.each(dataset.data, function(rawValue, index) {- var values = valuesPerStack[key];- var value = +me.getRightValue(rawValue);- // invalid, hidden and negative values are ignored- if (isNaN(value) || meta.data[index].hidden || value < 0) {- return;- }- values[index] = values[index] || 0;- values[index] += value;- });- }- });+ if (curve1[0].angle !== undefined) {+ cx = curve1[0].cx;+ cy = curve1[0].cy;+ r = Math.sqrt(Math.pow(curve1[0].x - cx, 2) + Math.pow(curve1[0].y - cy, 2));+ for (i = len1 - 1; i > 0; --i) {+ ctx.arc(cx, cy, r, curve1[i].angle, curve1[i - 1].angle, true);+ }+ return;+ }- helpers.each(valuesPerStack, function(valuesForType) {- if (valuesForType.length > 0) {- var minVal = helpers.min(valuesForType);- var maxVal = helpers.max(valuesForType);- me.min = me.min === null ? minVal : Math.min(me.min, minVal);- me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);- }- });+ // joining the two area curves+ ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);- } else {- helpers.each(datasets, function(dataset, datasetIndex) {- var meta = chart.getDatasetMeta(datasetIndex);- if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {- helpers.each(dataset.data, function(rawValue, index) {- var value = +me.getRightValue(rawValue);- // invalid, hidden and negative values are ignored- if (isNaN(value) || meta.data[index].hidden || value < 0) {- return;- }-- if (me.min === null) {- me.min = value;- } else if (value < me.min) {- me.min = value;- }-- if (me.max === null) {- me.max = value;- } else if (value > me.max) {- me.max = value;- }-- if (value !== 0 && (me.minNotZero === null || value < me.minNotZero)) {- me.minNotZero = value;- }- });- }- });- }+ // building opposite area curve (reverse)+ for (i = len1 - 1; i > 0; --i) {+ helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);+ }+}- // Common base implementation to handle ticks.min, ticks.max- this.handleTickRangeOptions();- },- handleTickRangeOptions: function() {- var me = this;- var opts = me.options;- var tickOpts = opts.ticks;- var valueOrDefault = helpers.valueOrDefault;- var DEFAULT_MIN = 1;- var DEFAULT_MAX = 10;-- me.min = valueOrDefault(tickOpts.min, me.min);- me.max = valueOrDefault(tickOpts.max, me.max);-- if (me.min === me.max) {- if (me.min !== 0 && me.min !== null) {- me.min = Math.pow(10, Math.floor(helpers.log10(me.min)) - 1);- me.max = Math.pow(10, Math.floor(helpers.log10(me.max)) + 1);- } else {- me.min = DEFAULT_MIN;- me.max = DEFAULT_MAX;- }- }- if (me.min === null) {- me.min = Math.pow(10, Math.floor(helpers.log10(me.max)) - 1);- }- if (me.max === null) {- me.max = me.min !== 0- ? Math.pow(10, Math.floor(helpers.log10(me.min)) + 1)- : DEFAULT_MAX;- }- if (me.minNotZero === null) {- if (me.min > 0) {- me.minNotZero = me.min;- } else if (me.max < 1) {- me.minNotZero = Math.pow(10, Math.floor(helpers.log10(me.max)));- } else {- me.minNotZero = DEFAULT_MIN;- }- }- },- buildTicks: function() {- var me = this;- var opts = me.options;- var tickOpts = opts.ticks;- var reverse = !me.isHorizontal();-- var generationOptions = {- min: tickOpts.min,- max: tickOpts.max- };- var ticks = me.ticks = generateTicks(generationOptions, me);+function doFill(ctx, points, mapper, view, color, loop) {+ var count = points.length;+ var span = view.spanGaps;+ var curve0 = [];+ var curve1 = [];+ var len0 = 0;+ var len1 = 0;+ var i, ilen, index, p0, p1, d0, d1, loopOffset;- // At this point, we need to update our max and min given the tick values since we have expanded the- // range of the scale- me.max = helpers.max(ticks);- me.min = helpers.min(ticks);+ ctx.beginPath();- if (tickOpts.reverse) {- reverse = !reverse;- me.start = me.max;- me.end = me.min;- } else {- me.start = me.min;- me.end = me.max;- }- if (reverse) {- ticks.reverse();- }- },- convertTicksToLabels: function() {- this.tickValues = this.ticks.slice();+ for (i = 0, ilen = count; i < ilen; ++i) {+ index = i % count;+ p0 = points[index]._view;+ p1 = mapper(p0, index, view);+ d0 = isDrawable(p0);+ d1 = isDrawable(p1);- Scale.prototype.convertTicksToLabels.call(this);- },- // Get the correct tooltip label- getLabelForIndex: function(index, datasetIndex) {- return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);- },- getPixelForTick: function(index) {- return this.getPixelForValue(this.tickValues[index]);- },- /**- * Returns the value of the first tick.- * @param {Number} value - The minimum not zero value.- * @return {Number} The first tick value.- * @private- */- _getFirstTickValue: function(value) {- var exp = Math.floor(helpers.log10(value));- var significand = Math.floor(value / Math.pow(10, exp));+ if (loop && loopOffset === undefined && d0) {+ loopOffset = i + 1;+ ilen = count + loopOffset;+ }- return significand * Math.pow(10, exp);- },- getPixelForValue: function(value) {- var me = this;- var reverse = me.options.ticks.reverse;- var log10 = helpers.log10;- var firstTickValue = me._getFirstTickValue(me.minNotZero);- var offset = 0;- var innerDimension, pixel, start, end, sign;-- value = +me.getRightValue(value);- if (reverse) {- start = me.end;- end = me.start;- sign = -1;- } else {- start = me.start;- end = me.end;- sign = 1;- }- if (me.isHorizontal()) {- innerDimension = me.width;- pixel = reverse ? me.right : me.left;+ if (d0 && d1) {+ len0 = curve0.push(p0);+ len1 = curve1.push(p1);+ } else if (len0 && len1) {+ if (!span) {+ drawArea(ctx, curve0, curve1, len0, len1);+ len0 = len1 = 0;+ curve0 = [];+ curve1 = [];} else {- innerDimension = me.height;- sign *= -1; // invert, since the upper-left corner of the canvas is at pixel (0, 0)- pixel = reverse ? me.top : me.bottom;- }- if (value !== start) {- if (start === 0) { // include zero tick- offset = helpers.getValueOrDefault(- me.options.ticks.fontSize,- Chart.defaults.global.defaultFontSize- );- innerDimension -= offset;- start = firstTickValue;- }- if (value !== 0) {- offset += innerDimension / (log10(end) - log10(start)) * (log10(value) - log10(start));+ if (d0) {+ curve0.push(p0);}- pixel += sign * offset;- }- return pixel;- },- getValueForPixel: function(pixel) {- var me = this;- var reverse = me.options.ticks.reverse;- var log10 = helpers.log10;- var firstTickValue = me._getFirstTickValue(me.minNotZero);- var innerDimension, start, end, value;-- if (reverse) {- start = me.end;- end = me.start;- } else {- start = me.start;- end = me.end;- }- if (me.isHorizontal()) {- innerDimension = me.width;- value = reverse ? me.right - pixel : pixel - me.left;- } else {- innerDimension = me.height;- value = reverse ? pixel - me.top : me.bottom - pixel;- }- if (value !== start) {- if (start === 0) { // include zero tick- var offset = helpers.getValueOrDefault(- me.options.ticks.fontSize,- Chart.defaults.global.defaultFontSize- );- value -= offset;- innerDimension -= offset;- start = firstTickValue;+ if (d1) {+ curve1.push(p1);}- value *= log10(end) - log10(start);- value /= innerDimension;- value = Math.pow(10, log10(start) + value);}- return value;}- });-- scaleService.registerScaleType('logarithmic', LogarithmicScale, defaultConfig);-};--},{"33":33,"34":34,"35":35,"46":46}],58:[function(require,module,exports){-'use strict';--var defaults = require(26);-var helpers = require(46);-var scaleService = require(34);-var Ticks = require(35);+ }-module.exports = function(Chart) {+ drawArea(ctx, curve0, curve1, len0, len1);- var globalDefaults = defaults.global;+ ctx.closePath();+ ctx.fillStyle = color;+ ctx.fill();+}- var defaultConfig = {- display: true,+var plugin_filler = {+ id: 'filler',- // Boolean - Whether to animate scaling the chart from the centre- animate: true,- position: 'chartArea',+ afterDatasetsUpdate: function(chart, options) {+ var count = (chart.data.datasets || []).length;+ var propagate = options.propagate;+ var sources = [];+ var meta, i, el, source;- angleLines: {- display: true,- color: 'rgba(0, 0, 0, 0.1)',- lineWidth: 1- },+ for (i = 0; i < count; ++i) {+ meta = chart.getDatasetMeta(i);+ el = meta.dataset;+ source = null;- gridLines: {- circular: false- },+ if (el && el._model && el instanceof elements.Line) {+ source = {+ visible: chart.isDatasetVisible(i),+ fill: decodeFill(el, i, count),+ chart: chart,+ el: el+ };+ }- // label settings- ticks: {- // Boolean - Show a backdrop to the scale label- showLabelBackdrop: true,+ meta.$filler = source;+ sources.push(source);+ }- // String - The colour of the label backdrop- backdropColor: 'rgba(255,255,255,0.75)',+ for (i = 0; i < count; ++i) {+ source = sources[i];+ if (!source) {+ continue;+ }- // Number - The backdrop padding above & below the label in pixels- backdropPaddingY: 2,+ source.fill = resolveTarget(sources, i, propagate);+ source.boundary = computeBoundary(source);+ source.mapper = createMapper(source);+ }+ },- // Number - The backdrop padding to the side of the label in pixels- backdropPaddingX: 2,+ beforeDatasetsDraw: function(chart) {+ var metasets = chart._getSortedVisibleDatasetMetas();+ var ctx = chart.ctx;+ var meta, i, el, view, points, mapper, color;- callback: Ticks.formatters.linear- },+ for (i = metasets.length - 1; i >= 0; --i) {+ meta = metasets[i].$filler;- pointLabels: {- // Boolean - if true, show point labels- display: true,+ if (!meta || !meta.visible) {+ continue;+ }- // Number - Point label font size in pixels- fontSize: 10,+ el = meta.el;+ view = el._view;+ points = el._children || [];+ mapper = meta.mapper;+ color = view.backgroundColor || core_defaults.global.defaultColor;- // Function - Used to convert point labels- callback: function(label) {- return label;+ if (mapper && color && points.length) {+ helpers$1.canvas.clipArea(ctx, chart.chartArea);+ doFill(ctx, points, mapper, view, color, el._loop);+ helpers$1.canvas.unclipArea(ctx);}}- };-- function getValueCount(scale) {- var opts = scale.options;- return opts.angleLines.display || opts.pointLabels.display ? scale.chart.data.labels.length : 0;- }-- function getPointLabelFontOptions(scale) {- var pointLabelOptions = scale.options.pointLabels;- var fontSize = helpers.valueOrDefault(pointLabelOptions.fontSize, globalDefaults.defaultFontSize);- var fontStyle = helpers.valueOrDefault(pointLabelOptions.fontStyle, globalDefaults.defaultFontStyle);- var fontFamily = helpers.valueOrDefault(pointLabelOptions.fontFamily, globalDefaults.defaultFontFamily);- var font = helpers.fontString(fontSize, fontStyle, fontFamily);-- return {- size: fontSize,- style: fontStyle,- family: fontFamily,- font: font- };}+};- function measureLabelSize(ctx, fontSize, label) {- if (helpers.isArray(label)) {- return {- w: helpers.longestText(ctx, ctx.font, label),- h: (label.length * fontSize) + ((label.length - 1) * 1.5 * fontSize)- };- }-- return {- w: ctx.measureText(label).width,- h: fontSize- };- }+var getRtlHelper$1 = helpers$1.rtl.getRtlAdapter;+var noop$1 = helpers$1.noop;+var valueOrDefault$e = helpers$1.valueOrDefault;- function determineLimits(angle, pos, size, min, max) {- if (angle === min || angle === max) {- return {- start: pos - (size / 2),- end: pos + (size / 2)- };- } else if (angle < min || angle > max) {- return {- start: pos - size - 5,- end: pos- };- }+core_defaults._set('global', {+ legend: {+ display: true,+ position: 'top',+ align: 'center',+ fullWidth: true,+ reverse: false,+ weight: 1000,- return {- start: pos,- end: pos + size + 5- };- }+ // a callback that will handle+ onClick: function(e, legendItem) {+ var index = legendItem.datasetIndex;+ var ci = this.chart;+ var meta = ci.getDatasetMeta(index);- /**- * Helper function to fit a radial linear scale with point labels- */- function fitWithPointLabels(scale) {- /*- * Right, this is really confusing and there is a lot of maths going on here- * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9- *- * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif- *- * Solution:- *- * We assume the radius of the polygon is half the size of the canvas at first- * at each index we check if the text overlaps.- *- * Where it does, we store that angle and that index.- *- * After finding the largest index and angle we calculate how much we need to remove- * from the shape radius to move the point inwards by that x.- *- * We average the left and right distances to get the maximum shape radius that can fit in the box- * along with labels.- *- * Once we have that, we can find the centre point for the chart, by taking the x text protrusion- * on each side, removing that from the size, halving it and adding the left x protrusion width.- *- * This will mean we have a shape fitted to the canvas, as large as it can be with the labels- * and position it in the most space efficient manner- *- * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif- */+ // See controller.isDatasetVisible comment+ meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;- var plFont = getPointLabelFontOptions(scale);+ // We hid a dataset ... rerender the chart+ ci.update();+ },- // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.- // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points- var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2);- var furthestLimits = {- r: scale.width,- l: 0,- t: scale.height,- b: 0- };- var furthestAngles = {};- var i, textSize, pointPosition;+ onHover: null,+ onLeave: null,- scale.ctx.font = plFont.font;- scale._pointLabelSizes = [];+ labels: {+ boxWidth: 40,+ padding: 10,+ // Generates labels shown in the legend+ // Valid properties to return:+ // text : text to display+ // fillStyle : fill of coloured box+ // strokeStyle: stroke of coloured box+ // hidden : if this legend item refers to a hidden item+ // lineCap : cap style for line+ // lineDash+ // lineDashOffset :+ // lineJoin :+ // lineWidth :+ generateLabels: function(chart) {+ var datasets = chart.data.datasets;+ var options = chart.options.legend || {};+ var usePointStyle = options.labels && options.labels.usePointStyle;- var valueCount = getValueCount(scale);- for (i = 0; i < valueCount; i++) {- pointPosition = scale.getPointPosition(i, largestPossibleRadius);- textSize = measureLabelSize(scale.ctx, plFont.size, scale.pointLabels[i] || '');- scale._pointLabelSizes[i] = textSize;+ return chart._getSortedDatasetMetas().map(function(meta) {+ var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);- // Add quarter circle to make degree 0 mean top of circle- var angleRadians = scale.getIndexAngle(i);- var angle = helpers.toDegrees(angleRadians) % 360;- var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);- var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);+ return {+ text: datasets[meta.index].label,+ fillStyle: style.backgroundColor,+ hidden: !chart.isDatasetVisible(meta.index),+ lineCap: style.borderCapStyle,+ lineDash: style.borderDash,+ lineDashOffset: style.borderDashOffset,+ lineJoin: style.borderJoinStyle,+ lineWidth: style.borderWidth,+ strokeStyle: style.borderColor,+ pointStyle: style.pointStyle,+ rotation: style.rotation,- if (hLimits.start < furthestLimits.l) {- furthestLimits.l = hLimits.start;- furthestAngles.l = angleRadians;+ // Below is extra data used for toggling the datasets+ datasetIndex: meta.index+ };+ }, this);}+ }+ },- if (hLimits.end > furthestLimits.r) {- furthestLimits.r = hLimits.end;- furthestAngles.r = angleRadians;- }+ legendCallback: function(chart) {+ var list = document.createElement('ul');+ var datasets = chart.data.datasets;+ var i, ilen, listItem, listItemSpan;- if (vLimits.start < furthestLimits.t) {- furthestLimits.t = vLimits.start;- furthestAngles.t = angleRadians;- }+ list.setAttribute('class', chart.id + '-legend');- if (vLimits.end > furthestLimits.b) {- furthestLimits.b = vLimits.end;- furthestAngles.b = angleRadians;+ for (i = 0, ilen = datasets.length; i < ilen; i++) {+ listItem = list.appendChild(document.createElement('li'));+ listItemSpan = listItem.appendChild(document.createElement('span'));+ listItemSpan.style.backgroundColor = datasets[i].backgroundColor;+ if (datasets[i].label) {+ listItem.appendChild(document.createTextNode(datasets[i].label));}}- scale.setReductions(largestPossibleRadius, furthestLimits, furthestAngles);+ return list.outerHTML;}+});- /**- * Helper function to fit a radial linear scale with no point labels- */- function fit(scale) {- var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2);- scale.drawingArea = Math.round(largestPossibleRadius);- scale.setCenterPoint(0, 0, 0, 0);- }+/**+ * 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;+}- function getTextAlignForAngle(angle) {- if (angle === 0 || angle === 180) {- return 'center';- } else if (angle < 180) {- return 'left';- }+/**+ * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!+ */+var Legend = core_element.extend({- return 'right';- }+ initialize: function(config) {+ var me = this;+ helpers$1.extend(me, config);- function fillText(ctx, text, position, fontSize) {- if (helpers.isArray(text)) {- var y = position.y;- var spacing = 1.5 * fontSize;+ // Contains hit boxes for each dataset (in dataset order)+ me.legendHitBoxes = [];- for (var i = 0; i < text.length; ++i) {- ctx.fillText(text[i], position.x, y);- y += spacing;- }- } else {- ctx.fillText(text, position.x, position.y);- }- }+ /**+ * @private+ */+ me._hoveredItem = null;- function adjustPointPositionForLabelHeight(angle, textSize, position) {- if (angle === 90 || angle === 270) {- position.y -= (textSize.h / 2);- } else if (angle > 270 || angle < 90) {- position.y -= textSize.h;- }- }+ // Are we in doughnut mode which has a different data type+ me.doughnutMode = false;+ },- function drawPointLabels(scale) {- var ctx = scale.ctx;- var opts = scale.options;- var angleLineOpts = opts.angleLines;- var pointLabelOpts = opts.pointLabels;+ // 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;- ctx.lineWidth = angleLineOpts.lineWidth;- ctx.strokeStyle = angleLineOpts.color;+ // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)+ me.beforeUpdate();- var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);+ // Absorb the master measurements+ me.maxWidth = maxWidth;+ me.maxHeight = maxHeight;+ me.margins = margins;- // Point Label Font- var plFont = getPointLabelFontOptions(scale);+ // Dimensions+ me.beforeSetDimensions();+ me.setDimensions();+ me.afterSetDimensions();+ // Labels+ me.beforeBuildLabels();+ me.buildLabels();+ me.afterBuildLabels();- ctx.textBaseline = 'top';+ // Fit+ me.beforeFit();+ me.fit();+ me.afterFit();+ //+ me.afterUpdate();- for (var i = getValueCount(scale) - 1; i >= 0; i--) {- if (angleLineOpts.display) {- var outerPosition = scale.getPointPosition(i, outerDistance);- ctx.beginPath();- ctx.moveTo(scale.xCenter, scale.yCenter);- ctx.lineTo(outerPosition.x, outerPosition.y);- ctx.stroke();- ctx.closePath();- }+ return me.minSize;+ },+ afterUpdate: noop$1,- if (pointLabelOpts.display) {- // Extra 3px out for some label spacing- var pointLabelPosition = scale.getPointPosition(i, outerDistance + 5);+ //- // Keep this in loop since we may support array properties here- var pointLabelFontColor = helpers.valueAtIndexOrDefault(pointLabelOpts.fontColor, i, globalDefaults.defaultFontColor);- ctx.font = plFont.font;- ctx.fillStyle = pointLabelFontColor;+ 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;- var angleRadians = scale.getIndexAngle(i);- var angle = helpers.toDegrees(angleRadians);- ctx.textAlign = getTextAlignForAngle(angle);- adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);- fillText(ctx, scale.pointLabels[i] || '', pointLabelPosition, plFont.size);- }+ // Reset position before calculating rotation+ me.top = 0;+ me.bottom = me.height;}- }- function drawRadiusLine(scale, gridLineOpts, radius, index) {- var ctx = scale.ctx;- ctx.strokeStyle = helpers.valueAtIndexOrDefault(gridLineOpts.color, index - 1);- ctx.lineWidth = helpers.valueAtIndexOrDefault(gridLineOpts.lineWidth, index - 1);+ // Reset padding+ me.paddingLeft = 0;+ me.paddingTop = 0;+ me.paddingRight = 0;+ me.paddingBottom = 0;- if (scale.options.gridLines.circular) {- // Draw circular arcs between the points- ctx.beginPath();- ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);- ctx.closePath();- ctx.stroke();- } else {- // Draw straight lines connecting each index- var valueCount = getValueCount(scale);+ // Reset minSize+ me.minSize = {+ width: 0,+ height: 0+ };+ },+ afterSetDimensions: noop$1,- if (valueCount === 0) {- return;- }+ //- ctx.beginPath();- var pointPosition = scale.getPointPosition(0, radius);- ctx.moveTo(pointPosition.x, pointPosition.y);+ beforeBuildLabels: noop$1,+ buildLabels: function() {+ var me = this;+ var labelOpts = me.options.labels || {};+ var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];- for (var i = 1; i < valueCount; i++) {- pointPosition = scale.getPointPosition(i, radius);- ctx.lineTo(pointPosition.x, pointPosition.y);- }+ if (labelOpts.filter) {+ legendItems = legendItems.filter(function(item) {+ return labelOpts.filter(item, me.chart.data);+ });+ }- ctx.closePath();- ctx.stroke();+ if (me.options.reverse) {+ legendItems.reverse();}- }- function numberOrZero(param) {- return helpers.isNumber(param) ? param : 0;- }+ me.legendItems = legendItems;+ },+ afterBuildLabels: noop$1,- var LinearRadialScale = Chart.LinearScaleBase.extend({- setDimensions: function() {- var me = this;- var opts = me.options;- var tickOpts = opts.ticks;- // Set the unconstrained dimension before label rotation- me.width = me.maxWidth;- me.height = me.maxHeight;- me.xCenter = Math.round(me.width / 2);- me.yCenter = Math.round(me.height / 2);+ //- var minSize = helpers.min([me.height, me.width]);- var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);- me.drawingArea = opts.display ? (minSize / 2) - (tickFontSize / 2 + tickOpts.backdropPaddingY) : (minSize / 2);- },- determineDataLimits: function() {- var me = this;- var chart = me.chart;- var min = Number.POSITIVE_INFINITY;- var max = Number.NEGATIVE_INFINITY;-- helpers.each(chart.data.datasets, function(dataset, datasetIndex) {- if (chart.isDatasetVisible(datasetIndex)) {- var meta = chart.getDatasetMeta(datasetIndex);-- helpers.each(dataset.data, function(rawValue, index) {- var value = +me.getRightValue(rawValue);- if (isNaN(value) || meta.data[index].hidden) {- return;- }+ beforeFit: noop$1,+ fit: function() {+ var me = this;+ var opts = me.options;+ var labelOpts = opts.labels;+ var display = opts.display;- min = Math.min(value, min);- max = Math.max(value, max);- });- }- });+ var ctx = me.ctx;- me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);- me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);+ var labelFont = helpers$1.options._parseFont(labelOpts);+ var fontSize = labelFont.size;- // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero- me.handleTickRangeOptions();- },- getTickLimit: function() {- var tickOpts = this.options.ticks;- var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);- return Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(this.drawingArea / (1.5 * tickFontSize)));- },- convertTicksToLabels: function() {- var me = this;+ // Reset hit boxes+ var hitboxes = me.legendHitBoxes = [];- Chart.LinearScaleBase.prototype.convertTicksToLabels.call(me);+ var minSize = me.minSize;+ var isHorizontal = me.isHorizontal();- // Point labels- me.pointLabels = me.chart.data.labels.map(me.options.pointLabels.callback, me);- },- getLabelForIndex: function(index, datasetIndex) {- return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);- },- fit: function() {- if (this.options.pointLabels.display) {- fitWithPointLabels(this);- } else {- fit(this);- }- },- /**- * Set radius reductions and determine new radius and center point- * @private- */- setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {- var me = this;- var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);- var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);- var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);- var radiusReductionBottom = -Math.max(furthestLimits.b - me.height, 0) / Math.cos(furthestAngles.b);-- radiusReductionLeft = numberOrZero(radiusReductionLeft);- radiusReductionRight = numberOrZero(radiusReductionRight);- radiusReductionTop = numberOrZero(radiusReductionTop);- radiusReductionBottom = numberOrZero(radiusReductionBottom);-- me.drawingArea = Math.min(- Math.round(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),- Math.round(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));- me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);- },- setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {- var me = this;- var maxRight = me.width - rightMovement - me.drawingArea;- var maxLeft = leftMovement + me.drawingArea;- var maxTop = topMovement + me.drawingArea;- var maxBottom = me.height - bottomMovement - me.drawingArea;-- me.xCenter = Math.round(((maxLeft + maxRight) / 2) + me.left);- me.yCenter = Math.round(((maxTop + maxBottom) / 2) + me.top);- },+ 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+ }- getIndexAngle: function(index) {- var angleMultiplier = (Math.PI * 2) / getValueCount(this);- var startAngle = this.chart.options && this.chart.options.startAngle ?- this.chart.options.startAngle :- 0;+ // Increase sizes here+ if (!display) {+ me.width = minSize.width = me.height = minSize.height = 0;+ return;+ }+ ctx.font = labelFont.string;- var startAngleRadians = startAngle * Math.PI * 2 / 360;+ if (isHorizontal) {+ // Labels- // Start from the top instead of right, so remove a quarter of the circle- return index * angleMultiplier + startAngleRadians;- },- getDistanceFromCenterForValue: function(value) {- var me = this;+ // 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;- if (value === null) {- return 0; // null always in center- }+ ctx.textAlign = 'left';+ ctx.textBaseline = 'middle';- // Take into account half font size + the yPadding of the top value- var scalingFactor = me.drawingArea / (me.max - me.min);- if (me.options.ticks.reverse) {- return (me.max - value) * scalingFactor;- }- return (value - me.min) * scalingFactor;- },- getPointPosition: function(index, distanceFromCenter) {- var me = this;- var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);- return {- x: Math.round(Math.cos(thisAngle) * distanceFromCenter) + me.xCenter,- y: Math.round(Math.sin(thisAngle) * distanceFromCenter) + me.yCenter- };- },- getPointPositionForValue: function(index, value) {- return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));- },+ helpers$1.each(me.legendItems, function(legendItem, i) {+ var boxWidth = getBoxWidth(labelOpts, fontSize);+ var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;- getBasePosition: function() {- var me = this;- var min = me.min;- var max = me.max;+ if (i === 0 || lineWidths[lineWidths.length - 1] + width + 2 * labelOpts.padding > minSize.width) {+ totalHeight += fontSize + labelOpts.padding;+ lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;+ }- return me.getPointPositionForValue(0,- me.beginAtZero ? 0 :- min < 0 && max < 0 ? max :- min > 0 && max > 0 ? min :- 0);- },+ // Store the hitbox width and height here. Final position will be updated in `draw`+ hitboxes[i] = {+ left: 0,+ top: 0,+ width: width,+ height: fontSize+ };- draw: function() {- var me = this;- var opts = me.options;- var gridLineOpts = opts.gridLines;- var tickOpts = opts.ticks;- var valueOrDefault = helpers.valueOrDefault;-- if (opts.display) {- var ctx = me.ctx;- var startAngle = this.getIndexAngle(0);-- // Tick Font- var tickFontSize = valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);- var tickFontStyle = valueOrDefault(tickOpts.fontStyle, globalDefaults.defaultFontStyle);- var tickFontFamily = valueOrDefault(tickOpts.fontFamily, globalDefaults.defaultFontFamily);- var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);-- helpers.each(me.ticks, function(label, index) {- // Don't draw a centre value (if it is minimum)- if (index > 0 || tickOpts.reverse) {- var yCenterOffset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);-- // Draw circular lines around the scale- if (gridLineOpts.display && index !== 0) {- drawRadiusLine(me, gridLineOpts, yCenterOffset, index);- }+ lineWidths[lineWidths.length - 1] += width + labelOpts.padding;+ });- if (tickOpts.display) {- var tickFontColor = valueOrDefault(tickOpts.fontColor, globalDefaults.defaultFontColor);- ctx.font = tickLabelFont;-- ctx.save();- ctx.translate(me.xCenter, me.yCenter);- ctx.rotate(startAngle);-- if (tickOpts.showLabelBackdrop) {- var labelWidth = ctx.measureText(label).width;- ctx.fillStyle = tickOpts.backdropColor;- ctx.fillRect(- -labelWidth / 2 - tickOpts.backdropPaddingX,- -yCenterOffset - tickFontSize / 2 - tickOpts.backdropPaddingY,- labelWidth + tickOpts.backdropPaddingX * 2,- tickFontSize + tickOpts.backdropPaddingY * 2- );- }-- ctx.textAlign = 'center';- ctx.textBaseline = 'middle';- ctx.fillStyle = tickFontColor;- ctx.fillText(label, 0, -yCenterOffset);- ctx.restore();- }- }- });+ minSize.height += totalHeight;- if (opts.angleLines.display || opts.pointLabels.display) {- drawPointLabels(me);+ } else {+ var vPadding = labelOpts.padding;+ var columnWidths = me.columnWidths = [];+ var columnHeights = me.columnHeights = [];+ var totalWidth = labelOpts.padding;+ var currentColWidth = 0;+ var currentColHeight = 0;++ 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 + fontSize + 2 * vPadding > minSize.height) {+ totalWidth += currentColWidth + labelOpts.padding;+ columnWidths.push(currentColWidth); // previous column width+ columnHeights.push(currentColHeight);+ currentColWidth = 0;+ currentColHeight = 0;}- }- }- });-- scaleService.registerScaleType('radialLinear', LinearRadialScale, defaultConfig);-};--},{"26":26,"34":34,"35":35,"46":46}],59:[function(require,module,exports){-/* global window: false */-'use strict';-var moment = require(1);-moment = typeof moment === 'function' ? moment : window.moment;+ // Get max width+ currentColWidth = Math.max(currentColWidth, itemWidth);+ currentColHeight += fontSize + vPadding;-var defaults = require(26);-var helpers = require(46);-var Scale = require(33);-var scaleService = require(34);+ // Store the hitbox width and height here. Final position will be updated in `draw`+ hitboxes[i] = {+ left: 0,+ top: 0,+ width: itemWidth,+ height: fontSize+ };+ });-// Integer constants are from the ES6 spec.-var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;-var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;+ totalWidth += currentColWidth;+ columnWidths.push(currentColWidth);+ columnHeights.push(currentColHeight);+ minSize.width += totalWidth;+ }-var INTERVALS = {- millisecond: {- common: true,- size: 1,- steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]- },- second: {- common: true,- size: 1000,- steps: [1, 2, 5, 10, 15, 30]- },- minute: {- common: true,- size: 60000,- steps: [1, 2, 5, 10, 15, 30]- },- hour: {- common: true,- size: 3600000,- steps: [1, 2, 3, 6, 12]- },- day: {- common: true,- size: 86400000,- steps: [1, 2, 5]- },- week: {- common: false,- size: 604800000,- steps: [1, 2, 3, 4]- },- month: {- common: true,- size: 2.628e9,- steps: [1, 2, 3]- },- quarter: {- common: false,- size: 7.884e9,- steps: [1, 2, 3, 4]+ me.width = minSize.width;+ me.height = minSize.height;},- year: {- common: true,- size: 3.154e10- }-};--var UNITS = Object.keys(INTERVALS);+ afterFit: noop$1,-function sorter(a, b) {- return a - b;-}+ // Shared Methods+ isHorizontal: function() {+ return this.options.position === 'top' || this.options.position === 'bottom';+ },-function arrayUnique(items) {- var hash = {};- var out = [];- var i, ilen, item;+ // 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 legendHeight = me.height;+ var columnHeights = me.columnHeights;+ var legendWidth = me.width;+ var lineWidths = me.lineWidths;- for (i = 0, ilen = items.length; i < ilen; ++i) {- item = items[i];- if (!hash[item]) {- hash[item] = true;- out.push(item);+ if (!opts.display) {+ return;}- }- return out;-}+ var rtlHelper = getRtlHelper$1(opts.rtl, me.left, me.minSize.width);+ var ctx = me.ctx;+ var fontColor = valueOrDefault$e(labelOpts.fontColor, globalDefaults.defaultFontColor);+ var labelFont = helpers$1.options._parseFont(labelOpts);+ var fontSize = labelFont.size;+ var cursor;++ // Canvas setup+ ctx.textAlign = rtlHelper.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;+ }-/**- * Returns an array of {time, pos} objects used to interpolate a specific `time` or position- * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is- * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other- * extremity (left + width or top + height). Note that it would be more optimized to directly- * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need- * to create the lookup table. The table ALWAYS contains at least two items: min and max.- *- * @param {Number[]} timestamps - timestamps sorted from lowest to highest.- * @param {String} distribution - If 'linear', timestamps will be spread linearly along the min- * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.- * If 'series', timestamps will be positioned at the same distance from each other. In this- * case, only timestamps that break the time linearity are registered, meaning that in the- * best case, all timestamps are linear, the table contains only min and max.- */-function buildLookupTable(timestamps, min, max, distribution) {- if (distribution === 'linear' || !timestamps.length) {- return [- {time: min, pos: 0},- {time: max, pos: 1}- ];- }+ // Set the ctx for the box+ ctx.save();- var table = [];- var items = [min];- var i, ilen, prev, curr, next;+ var lineWidth = valueOrDefault$e(legendItem.lineWidth, lineDefault.borderWidth);+ ctx.fillStyle = valueOrDefault$e(legendItem.fillStyle, defaultColor);+ ctx.lineCap = valueOrDefault$e(legendItem.lineCap, lineDefault.borderCapStyle);+ ctx.lineDashOffset = valueOrDefault$e(legendItem.lineDashOffset, lineDefault.borderDashOffset);+ ctx.lineJoin = valueOrDefault$e(legendItem.lineJoin, lineDefault.borderJoinStyle);+ ctx.lineWidth = lineWidth;+ ctx.strokeStyle = valueOrDefault$e(legendItem.strokeStyle, defaultColor);- for (i = 0, ilen = timestamps.length; i < ilen; ++i) {- curr = timestamps[i];- if (curr > min && curr < max) {- items.push(curr);- }- }+ if (ctx.setLineDash) {+ // IE 9 and 10 do not support line dash+ ctx.setLineDash(valueOrDefault$e(legendItem.lineDash, lineDefault.borderDash));+ }- items.push(max);+ if (labelOpts && labelOpts.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 = rtlHelper.xPlus(x, boxWidth / 2);+ var centerY = y + fontSize / 2;- for (i = 0, ilen = items.length; i < ilen; ++i) {- next = items[i + 1];- prev = items[i - 1];- curr = items[i];+ // Draw pointStyle as legend symbol+ helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY, legendItem.rotation);+ } else {+ // Draw box as legend symbol+ ctx.fillRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);+ if (lineWidth !== 0) {+ ctx.strokeRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);+ }+ }- // only add points that breaks the scale linearity- if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {- table.push({time: curr, pos: i / (ilen - 1)});- }- }+ ctx.restore();+ };++ var fillText = function(x, y, legendItem, textWidth) {+ var halfFontSize = fontSize / 2;+ var xLeft = rtlHelper.xPlus(x, boxWidth + halfFontSize);+ var yMiddle = y + halfFontSize;- return table;-}+ ctx.fillText(legendItem.text, xLeft, yMiddle);-// @see adapted from http://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/-function lookup(table, key, value) {- var lo = 0;- var hi = table.length - 1;- var mid, i0, i1;+ if (legendItem.hidden) {+ // Strikethrough the text if hidden+ ctx.beginPath();+ ctx.lineWidth = 2;+ ctx.moveTo(xLeft, yMiddle);+ ctx.lineTo(rtlHelper.xPlus(xLeft, textWidth), yMiddle);+ ctx.stroke();+ }+ };- while (lo >= 0 && lo <= hi) {- mid = (lo + hi) >> 1;- i0 = table[mid - 1] || null;- i1 = table[mid];+ var alignmentOffset = function(dimension, blockSize) {+ switch (opts.align) {+ case 'start':+ return labelOpts.padding;+ case 'end':+ return dimension - blockSize;+ default: // center+ return (dimension - blockSize + labelOpts.padding) / 2;+ }+ };- if (!i0) {- // given value is outside table (before first item)- return {lo: null, hi: i1};- } else if (i1[key] < value) {- lo = mid + 1;- } else if (i0[key] > value) {- hi = mid - 1;+ // Horizontal+ var isHorizontal = me.isHorizontal();+ if (isHorizontal) {+ cursor = {+ x: me.left + alignmentOffset(legendWidth, lineWidths[0]),+ y: me.top + labelOpts.padding,+ line: 0+ };} else {- return {lo: i0, hi: i1};+ cursor = {+ x: me.left + labelOpts.padding,+ y: me.top + alignmentOffset(legendHeight, columnHeights[0]),+ line: 0+ };}- }- // given value is outside table (after last item)- return {lo: i1, hi: null};-}+ helpers$1.rtl.overrideTextDirection(me.ctx, opts.textDirection);-/**- * Linearly interpolates the given source `value` using the table items `skey` values and- * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')- * returns the position for a timestamp equal to 42. If value is out of bounds, values at- * index [0, 1] or [n - 1, n] are used for the interpolation.- */-function interpolate(table, skey, sval, tkey) {- var range = lookup(table, skey, sval);+ 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;- // Note: the lookup table ALWAYS contains at least 2 items (min and max)- var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;- var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;+ rtlHelper.setWidth(me.minSize.width);- var span = next[skey] - prev[skey];- var ratio = span ? (sval - prev[skey]) / span : 0;- var offset = (next[tkey] - prev[tkey]) * ratio;+ // 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 + alignmentOffset(legendWidth, lineWidths[cursor.line]);+ }+ } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {+ x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;+ cursor.line++;+ y = cursor.y = me.top + alignmentOffset(legendHeight, columnHeights[cursor.line]);+ }- return prev[tkey] + offset;-}+ var realX = rtlHelper.x(x);-/**- * Convert the given value to a moment object using the given time options.- * @see http://momentjs.com/docs/#/parsing/- */-function momentify(value, options) {- var parser = options.parser;- var format = options.parser || options.format;+ drawLegendBox(realX, y, legendItem);- if (typeof parser === 'function') {- return parser(value);- }+ hitboxes[i].left = rtlHelper.leftForLtr(realX, hitboxes[i].width);+ hitboxes[i].top = y;- if (typeof value === 'string' && typeof format === 'string') {- return moment(value, format);- }+ // Fill the actual label+ fillText(realX, y, legendItem, textWidth);- if (!(value instanceof moment)) {- value = moment(value);- }+ if (isHorizontal) {+ cursor.x += width + labelOpts.padding;+ } else {+ cursor.y += itemHeight;+ }+ });- if (value.isValid()) {- return value;- }+ helpers$1.rtl.restoreTextDirection(me.ctx, opts.textDirection);+ },- // Labels are in an incompatible moment format and no `parser` has been provided.- // The user might still use the deprecated `format` option to convert his inputs.- if (typeof format === 'function') {- return format(value);- }+ /**+ * @private+ */+ _getLegendItemAt: function(x, y) {+ var me = this;+ var i, hitBox, lh;- return value;-}+ 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];-function parse(input, scale) {- if (helpers.isNullOrUndef(input)) {- return null;- }+ if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {+ // Touching an element+ return me.legendItems[i];+ }+ }+ }- var options = scale.options.time;- var value = momentify(scale.getRightValue(input), options);- if (!value.isValid()) {return null;- }+ },- if (options.round) {- value.startOf(options.round);- }+ /**+ * 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;- return value.valueOf();-}+ if (type === 'mousemove') {+ if (!opts.onHover && !opts.onLeave) {+ return;+ }+ } else if (type === 'click') {+ if (!opts.onClick) {+ return;+ }+ } else {+ return;+ }-/**- * Returns the number of unit to skip to be able to display up to `capacity` number of ticks- * in `unit` for the given `min` / `max` range and respecting the interval steps constraints.- */-function determineStepSize(min, max, unit, capacity) {- var range = max - min;- var interval = INTERVALS[unit];- var milliseconds = interval.size;- var steps = interval.steps;- var i, ilen, factor;+ // Chart event already has relative position in it+ hoveredItem = me._getLegendItemAt(e.x, e.y);- if (!steps) {- return Math.ceil(range / (capacity * milliseconds));- }+ 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;+ }- for (i = 0, ilen = steps.length; i < ilen; ++i) {- factor = steps[i];- if (Math.ceil(range / (milliseconds * factor)) <= capacity) {- break;+ 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+ });- return factor;+ core_layouts.configure(chart, legend, legendOpts);+ core_layouts.addBox(chart, legend);+ chart.legend = legend;}-/**- * Figures out what unit results in an appropriate number of auto-generated ticks- */-function determineUnitForAutoTicks(minUnit, min, max, capacity) {- var ilen = UNITS.length;- var i, interval, factor;+var plugin_legend = {+ id: 'legend',- for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {- interval = INTERVALS[UNITS[i]];- factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER;+ /**+ * 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,- if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {- return UNITS[i];+ beforeInit: function(chart) {+ var legendOpts = chart.options.legend;++ if (legendOpts) {+ createNewLegendAndAttach(chart, legendOpts);}- }+ },- return UNITS[ilen - 1];-}+ beforeUpdate: function(chart) {+ var legendOpts = chart.options.legend;+ var legend = chart.legend;-/**- * Figures out what unit to format a set of ticks with- */-function determineUnitForFormatting(ticks, minUnit, min, max) {- var duration = moment.duration(moment(max).diff(moment(min)));- var ilen = UNITS.length;- var i, unit;+ if (legendOpts) {+ helpers$1.mergeIf(legendOpts, core_defaults.global.legend);- for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) {- unit = UNITS[i];- if (INTERVALS[unit].common && duration.as(unit) >= ticks.length) {- return unit;+ 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;}- }-- return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];-}+ },-function determineMajorUnit(unit) {- for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {- if (INTERVALS[UNITS[i]].common) {- return UNITS[i];+ afterEvent: function(chart, e) {+ var legend = chart.legend;+ if (legend) {+ legend.handleEvent(e);}}-}--/**- * Generates a maximum of `capacity` timestamps between min and max, rounded to the- * `minor` unit, aligned on the `major` unit and using the given scale time `options`.- * Important: this method can return ticks outside the min and max range, it's the- * responsibility of the calling code to clamp values if needed.- */-function generate(min, max, capacity, options) {- var timeOpts = options.time;- var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);- var major = determineMajorUnit(minor);- var stepSize = helpers.valueOrDefault(timeOpts.stepSize, timeOpts.unitStepSize);- var weekday = minor === 'week' ? timeOpts.isoWeekday : false;- var majorTicksEnabled = options.ticks.major.enabled;- var interval = INTERVALS[minor];- var first = moment(min);- var last = moment(max);- var ticks = [];- var time;-- if (!stepSize) {- stepSize = determineStepSize(min, max, minor, capacity);- }-- // For 'week' unit, handle the first day of week option- if (weekday) {- first = first.isoWeekday(weekday);- last = last.isoWeekday(weekday);- }+};- // Align first/last ticks on unit- first = first.startOf(weekday ? 'day' : minor);- last = last.startOf(weekday ? 'day' : minor);+var noop$2 = helpers$1.noop;- // Make sure that the last tick include max- if (last < max) {- last.add(1, minor);+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}+});- time = moment(first);-- if (majorTicksEnabled && major && !weekday && !timeOpts.round) {- // Align the first tick on the previous `minor` unit aligned on the `major` unit:- // we first aligned time on the previous `major` unit then add the number of full- // stepSize there is between first and the previous major time.- time.startOf(major);- time.add(~~((first - time) / (interval.size * stepSize)) * stepSize, minor);- }+/**+ * 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);- for (; time < last; time.add(stepSize, minor)) {- ticks.push(+time);- }+ // Contains hit boxes for each dataset (in dataset order)+ me.legendHitBoxes = [];+ },- ticks.push(+time);+ // These methods are ordered by lifecycle. Utilities then follow.- return ticks;-}+ beforeUpdate: noop$2,+ update: function(maxWidth, maxHeight, margins) {+ var me = this;-/**- * Returns the right and left offsets from edges in the form of {left, right}.- * Offsets are added when the `offset` option is true.- */-function computeOffsets(table, ticks, min, max, options) {- var left = 0;- var right = 0;- var upper, lower;+ // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)+ me.beforeUpdate();- if (options.offset && ticks.length) {- if (!options.time.min) {- upper = ticks.length > 1 ? ticks[1] : max;- lower = ticks[0];- left = (- interpolate(table, 'time', upper, 'pos') -- interpolate(table, 'time', lower, 'pos')- ) / 2;- }- if (!options.time.max) {- upper = ticks[ticks.length - 1];- lower = ticks.length > 1 ? ticks[ticks.length - 2] : min;- right = (- interpolate(table, 'time', upper, 'pos') -- interpolate(table, 'time', lower, 'pos')- ) / 2;- }- }+ // Absorb the master measurements+ me.maxWidth = maxWidth;+ me.maxHeight = maxHeight;+ me.margins = margins;- return {left: left, right: right};-}+ // Dimensions+ me.beforeSetDimensions();+ me.setDimensions();+ me.afterSetDimensions();+ // Labels+ me.beforeBuildLabels();+ me.buildLabels();+ me.afterBuildLabels();-function ticksFromTimestamps(values, majorUnit) {- var ticks = [];- var i, ilen, value, major;+ // Fit+ me.beforeFit();+ me.fit();+ me.afterFit();+ //+ me.afterUpdate();- for (i = 0, ilen = values.length; i < ilen; ++i) {- value = values[i];- major = majorUnit ? value === +moment(value).startOf(majorUnit) : false;+ return me.minSize;- ticks.push({- value: value,- major: major- });- }+ },+ afterUpdate: noop$2,- return ticks;-}+ //-function determineLabelFormat(data, timeOpts) {- var i, momentDate, hasTime;- var ilen = data.length;+ 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;- // find the label with the most parts (milliseconds, minutes, etc.)- // format all labels with the same level of detail as the most specific label- for (i = 0; i < ilen; i++) {- momentDate = momentify(data[i], timeOpts);- if (momentDate.millisecond() !== 0) {- return 'MMM D, YYYY h:mm:ss.SSS a';- }- if (momentDate.second() !== 0 || momentDate.minute() !== 0 || momentDate.hour() !== 0) {- hasTime = true;+ // Reset position before calculating rotation+ me.top = 0;+ me.bottom = me.height;}- }- if (hasTime) {- return 'MMM D, YYYY h:mm:ss a';- }- return 'MMM D, YYYY';-}--module.exports = function() {-- var defaultConfig = {- position: 'bottom',- /**- * Data distribution along the scale:- * - 'linear': data are spread according to their time (distances can vary),- * - 'series': data are spread at the same distance from each other.- * @see https://github.com/chartjs/Chart.js/pull/4507- * @since 2.7.0- */- distribution: 'linear',+ // Reset padding+ me.paddingLeft = 0;+ me.paddingTop = 0;+ me.paddingRight = 0;+ me.paddingBottom = 0;- /**- * Scale boundary strategy (bypassed by min/max time options)- * - `data`: make sure data are fully visible, ticks outside are removed- * - `ticks`: make sure ticks are fully visible, data outside are truncated- * @see https://github.com/chartjs/Chart.js/pull/4556- * @since 2.7.0- */- bounds: 'data',-- time: {- parser: false, // false == a pattern string from http://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment- format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from http://momentjs.com/docs/#/parsing/string-format/- unit: false, // false == automatic or override with week, month, year, etc.- round: false, // none, or override with week, month, year, etc.- displayFormat: false, // DEPRECATED- isoWeekday: false, // override week start day - see http://momentjs.com/docs/#/get-set/iso-weekday/- minUnit: 'millisecond',-- // defaults to unit's corresponding unitFormat below or override using pattern string from http://momentjs.com/docs/#/displaying/format/- displayFormats: {- millisecond: 'h:mm:ss.SSS a', // 11:20:01.123 AM,- second: 'h:mm:ss a', // 11:20:01 AM- minute: 'h:mm a', // 11:20 AM- hour: 'hA', // 5PM- day: 'MMM D', // Sep 4- week: 'll', // Week 46, or maybe "[W]WW - YYYY" ?- month: 'MMM YYYY', // Sept 2015- quarter: '[Q]Q - YYYY', // Q3- year: 'YYYY' // 2015- },- },- ticks: {- autoSkip: false,+ // Reset minSize+ me.minSize = {+ width: 0,+ height: 0+ };+ },+ afterSetDimensions: noop$2,- /**- * Ticks generation input values:- * - 'auto': generates "optimal" ticks based on scale size and time options.- * - 'data': generates ticks from data (including labels from data {t|x|y} objects).- * - 'labels': generates ticks from user given `data.labels` values ONLY.- * @see https://github.com/chartjs/Chart.js/pull/4507- * @since 2.7.0- */- source: 'auto',+ //- major: {- enabled: false- }- }- };+ beforeBuildLabels: noop$2,+ buildLabels: noop$2,+ afterBuildLabels: noop$2,- var TimeScale = Scale.extend({- initialize: function() {- if (!moment) {- throw new Error('Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com');- }+ //- this.mergeTicksOptions();+ beforeFit: noop$2,+ fit: function() {+ var me = this;+ var opts = me.options;+ var minSize = me.minSize = {};+ var isHorizontal = me.isHorizontal();+ var lineCount, textSize;- Scale.prototype.initialize.call(this);- },+ if (!opts.display) {+ me.width = minSize.width = me.height = minSize.height = 0;+ return;+ }- update: function() {- var me = this;- var options = me.options;+ lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;+ textSize = lineCount * helpers$1.options._parseFont(opts).lineHeight + opts.padding * 2;- // DEPRECATIONS: output a message only one time per update- if (options.time && options.time.format) {- console.warn('options.time.format is deprecated and replaced by options.time.parser.');- }+ me.width = minSize.width = isHorizontal ? me.maxWidth : textSize;+ me.height = minSize.height = isHorizontal ? textSize : me.maxHeight;+ },+ afterFit: noop$2,- return Scale.prototype.update.apply(me, arguments);- },+ // Shared Methods+ isHorizontal: function() {+ var pos = this.options.position;+ return pos === 'top' || pos === 'bottom';+ },- /**- * Allows data to be referenced via 't' attribute- */- getRightValue: function(rawValue) {- if (rawValue && rawValue.t !== undefined) {- rawValue = rawValue.t;- }- return Scale.prototype.getRightValue.call(this, rawValue);- },+ // Actually draw the title block on the canvas+ draw: function() {+ var me = this;+ var ctx = me.ctx;+ var opts = me.options;- determineDataLimits: function() {- var me = this;- var chart = me.chart;- var timeOpts = me.options.time;- var unit = timeOpts.unit || 'day';- var min = MAX_INTEGER;- var max = MIN_INTEGER;- var timestamps = [];- var datasets = [];- var labels = [];- var i, j, ilen, jlen, data, timestamp;+ if (!opts.display) {+ return;+ }- // Convert labels to timestamps- for (i = 0, ilen = chart.data.labels.length; i < ilen; ++i) {- labels.push(parse(chart.data.labels[i], me));- }+ 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;- // Convert data to timestamps- for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {- if (chart.isDatasetVisible(i)) {- data = chart.data.datasets[i].data;+ ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour+ ctx.font = fontOpts.string;- // Let's consider that all data have the same format.- if (helpers.isObject(data[0])) {- datasets[i] = [];+ // 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);+ }- for (j = 0, jlen = data.length; j < jlen; ++j) {- timestamp = parse(data[j], me);- timestamps.push(timestamp);- datasets[i][j] = timestamp;- }- } else {- timestamps.push.apply(timestamps, labels);- datasets[i] = labels.slice(0);- }- } else {- datasets[i] = [];- }+ 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);+ }- if (labels.length) {- // Sort labels **after** data have been converted- labels = arrayUnique(labels).sort(sorter);- min = Math.min(min, labels[0]);- max = Math.max(max, labels[labels.length - 1]);- }+ ctx.restore();+ }+});- if (timestamps.length) {- timestamps = arrayUnique(timestamps).sort(sorter);- min = Math.min(min, timestamps[0]);- max = Math.max(max, timestamps[timestamps.length - 1]);- }+function createNewTitleBlockAndAttach(chart, titleOpts) {+ var title = new Title({+ ctx: chart.ctx,+ options: titleOpts,+ chart: chart+ });- min = parse(timeOpts.min, me) || min;- max = parse(timeOpts.max, me) || max;+ core_layouts.configure(chart, title, titleOpts);+ core_layouts.addBox(chart, title);+ chart.titleBlock = title;+}- // In case there is no valid min/max, set limits based on unit time option- min = min === MAX_INTEGER ? +moment().startOf(unit) : min;- max = max === MIN_INTEGER ? +moment().endOf(unit) + 1 : max;+var plugin_title = {+ id: 'title',- // Make sure that max is strictly higher than min (required by the lookup table)- me.min = Math.min(min, max);- me.max = Math.max(min + 1, max);+ /**+ * 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,- // PRIVATE- me._horizontal = me.isHorizontal();- me._table = [];- me._timestamps = {- data: timestamps,- datasets: datasets,- labels: labels- };- },+ beforeInit: function(chart) {+ var titleOpts = chart.options.title;- buildTicks: function() {- var me = this;- var min = me.min;- var max = me.max;- var options = me.options;- var timeOpts = options.time;- var timestamps = [];- var ticks = [];- var i, ilen, timestamp;-- switch (options.ticks.source) {- case 'data':- timestamps = me._timestamps.data;- break;- case 'labels':- timestamps = me._timestamps.labels;- break;- case 'auto':- default:- timestamps = generate(min, max, me.getLabelCapacity(min), options);- }+ if (titleOpts) {+ createNewTitleBlockAndAttach(chart, titleOpts);+ }+ },- if (options.bounds === 'ticks' && timestamps.length) {- min = timestamps[0];- max = timestamps[timestamps.length - 1];- }+ beforeUpdate: function(chart) {+ var titleOpts = chart.options.title;+ var titleBlock = chart.titleBlock;- // Enforce limits with user min/max options- min = parse(timeOpts.min, me) || min;- max = parse(timeOpts.max, me) || max;+ if (titleOpts) {+ helpers$1.mergeIf(titleOpts, core_defaults.global.title);- // Remove ticks outside the min/max range- for (i = 0, ilen = timestamps.length; i < ilen; ++i) {- timestamp = timestamps[i];- if (timestamp >= min && timestamp <= max) {- ticks.push(timestamp);- }+ 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;+ }+ }+};- me.min = min;- me.max = max;-- // PRIVATE- me._unit = timeOpts.unit || determineUnitForFormatting(ticks, timeOpts.minUnit, me.min, me.max);- me._majorUnit = determineMajorUnit(me._unit);- me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);- me._offsets = computeOffsets(me._table, ticks, min, max, options);- me._labelFormat = determineLabelFormat(me._timestamps.data, timeOpts);-- return ticksFromTimestamps(ticks, me._majorUnit);- },-- getLabelForIndex: function(index, datasetIndex) {- var me = this;- var data = me.chart.data;- var timeOpts = me.options.time;- var label = data.labels && index < data.labels.length ? data.labels[index] : '';- var value = data.datasets[datasetIndex].data[index];+var plugins = {};+var filler = plugin_filler;+var legend = plugin_legend;+var title = plugin_title;+plugins.filler = filler;+plugins.legend = legend;+plugins.title = title;- if (helpers.isObject(value)) {- label = me.getRightValue(value);- }- if (timeOpts.tooltipFormat) {- return momentify(label, timeOpts).format(timeOpts.tooltipFormat);- }- if (typeof label === 'string') {- return label;- }+/**+ * @namespace Chart+ */- return momentify(label, timeOpts).format(me._labelFormat);- },- /**- * Function to format an individual tick mark- * @private- */- tickFormatFunction: function(tick, index, ticks, formatOverride) {- var me = this;- var options = me.options;- var time = tick.valueOf();- var formats = options.time.displayFormats;- var minorFormat = formats[me._unit];- var majorUnit = me._majorUnit;- var majorFormat = formats[majorUnit];- var majorTime = tick.clone().startOf(majorUnit).valueOf();- var majorTickOpts = options.ticks.major;- var major = majorTickOpts.enabled && majorUnit && majorFormat && time === majorTime;- var label = tick.format(formatOverride ? formatOverride : major ? majorFormat : minorFormat);- var tickOpts = major ? majorTickOpts : options.ticks.minor;- var formatter = helpers.valueOrDefault(tickOpts.callback, tickOpts.userCallback);-- return formatter ? formatter(label, index, ticks) : label;- },+core_controller.helpers = helpers$1;- convertTicksToLabels: function(ticks) {- var labels = [];- var i, ilen;+// @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!+core_helpers();++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);+});- for (i = 0, ilen = ticks.length; i < ilen; ++i) {- labels.push(this.tickFormatFunction(moment(ticks[i].value), i, ticks));- }+// Load to register built-in adapters (as side effects)- return labels;- },- /**- * @private- */- getPixelForOffset: function(time) {- var me = this;- var size = me._horizontal ? me.width : me.height;- var start = me._horizontal ? me.left : me.top;- var pos = interpolate(me._table, 'time', time, 'pos');+// Loading built-in plugins- return start + size * (me._offsets.left + pos) / (me._offsets.left + 1 + me._offsets.right);- },+for (var k in plugins) {+ if (plugins.hasOwnProperty(k)) {+ core_controller.plugins.register(plugins[k]);+ }+}- getPixelForValue: function(value, index, datasetIndex) {- var me = this;- var time = null;+core_controller.platform.initialize();- if (index !== undefined && datasetIndex !== undefined) {- time = me._timestamps.datasets[datasetIndex][index];- }+var src = core_controller;+if (typeof window !== 'undefined') {+ window.Chart = core_controller;+}- if (time === null) {- time = parse(value, me);- }+// DEPRECATIONS- if (time !== null) {- return me.getPixelForOffset(time);- }- },+/**+ * 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;- getPixelForTick: function(index) {- var ticks = this.getTicks();- return index >= 0 && index < ticks.length ?- this.getPixelForOffset(ticks[index].value) :- null;- },+/**+ * 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;- getValueForPixel: function(pixel) {- var me = this;- var size = me._horizontal ? me.width : me.height;- var start = me._horizontal ? me.left : me.top;- var pos = (size ? (pixel - start) / size : 0) * (me._offsets.left + 1 + me._offsets.left) - me._offsets.right;- var time = interpolate(me._table, 'pos', pos, 'time');+/**+ * 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;- return moment(time);- },+/**+ * 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;- /**- * Crude approximation of what the label width might be- * @private- */- getLabelWidth: function(label) {- var me = this;- var ticksOpts = me.options.ticks;- var tickLabelWidth = me.ctx.measureText(label).width;- var angle = helpers.toRadians(ticksOpts.maxRotation);- var cosRotation = Math.cos(angle);- var sinRotation = Math.sin(angle);- var tickFontSize = helpers.valueOrDefault(ticksOpts.fontSize, defaults.global.defaultFontSize);-- return (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation);- },+/**+ * 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({});- /**- * @private- */- getLabelCapacity: function(exampleTime) {- var me = this;+/**+ * 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;- var formatOverride = me.options.time.displayFormats.millisecond; // Pick the longest format for guestimation+/**+ * 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;- var exampleLabel = me.tickFormatFunction(moment(exampleTime), 0, [], formatOverride);- var tickLabelWidth = me.getLabelWidth(exampleLabel);- var innerWidth = me.isHorizontal() ? me.width : me.height;+/**+ * 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;- var capacity = Math.floor(innerWidth / tickLabelWidth);- return capacity > 0 ? capacity : 1;- }- });+/**+ * 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)+ }));+ };+ }+);- scaleService.registerScaleType('time', TimeScale, defaultConfig);-};+return src;-},{"1":1,"26":26,"33":33,"34":34,"46":46}]},{},[7])(7)-});+})));diff --git a/app/assets/javascripts/blazer/jquery.js b/app/assets/javascripts/blazer/jquery.jsindex 9b5206bc..50937333 100644--- a/app/assets/javascripts/blazer/jquery.js+++ b/app/assets/javascripts/blazer/jquery.js@@ -1,5 +1,5 @@/*!- * jQuery JavaScript Library v3.3.1+ * jQuery JavaScript Library v3.5.1* https://jquery.com/** Includes Sizzle.js@@ -9,7 +9,7 @@* Released under the MIT license* https://jquery.org/license*- * Date: 2018-01-20T17:24Z+ * Date: 2020-05-04T22:49Z*/( function( global, factory ) {@@ -47,13 +47,16 @@var arr = [];-var document = window.document;-var getProto = Object.getPrototypeOf;var slice = arr.slice;-var concat = arr.concat;+var flat = arr.flat ? function( array ) {+ return arr.flat.call( array );+} : function( array ) {+ return arr.concat.apply( [], array );+};+var push = arr.push;@@ -86,25 +89,40 @@ var isWindow = function isWindow( obj ) {};+var document = window.document;+var preservedScriptAttributes = {type: true,src: true,+ nonce: true,noModule: true};- function DOMEval( code, doc, node ) {+ function DOMEval( code, node, doc ) {doc = doc || document;- var i,+ var i, val,script = doc.createElement( "script" );script.text = code;if ( node ) {for ( i in preservedScriptAttributes ) {- if ( node[ i ] ) {- script[ i ] = node[ i ];++ // Support: Firefox 64+, Edge 18++ // Some browsers don't support the "nonce" property on scripts.+ // On the other hand, just using `getAttribute` is not enough as+ // the `nonce` attribute is reset to an empty string whenever it+ // becomes browsing-context connected.+ // See https://github.com/whatwg/html/issues/2369+ // See https://html.spec.whatwg.org/#nonce-attributes+ // The `node.getAttribute` check was added for the sake of+ // `jQuery.globalEval` so that it can fake a nonce-containing node+ // via an object.+ val = node[ i ] || node.getAttribute && node.getAttribute( i );+ if ( val ) {+ script.setAttribute( i, val );}}}@@ -129,7 +147,7 @@ function toType( obj ) {var- version = "3.3.1",+ version = "3.5.1",// Define a local copy of jQueryjQuery = function( selector, context ) {@@ -137,11 +155,7 @@ var// The jQuery object is actually just the init constructor 'enhanced'// Need init if jQuery is called (just allow error to be thrown if not included)return new jQuery.fn.init( selector, context );- },-- // Support: Android <=4.0 only- // Make sure we trim BOM and NBSP- rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;+ };jQuery.fn = jQuery.prototype = {@@ -207,6 +221,18 @@ jQuery.fn = jQuery.prototype = {return this.eq( -1 );},+ even: function() {+ return this.pushStack( jQuery.grep( this, function( _elem, i ) {+ return ( i + 1 ) % 2;+ } ) );+ },++ odd: function() {+ return this.pushStack( jQuery.grep( this, function( _elem, i ) {+ return i % 2;+ } ) );+ },+eq: function( i ) {var len = this.length,j = +i + ( i < 0 ? len : 0 );@@ -258,25 +284,28 @@ jQuery.extend = jQuery.fn.extend = function() {// Extend the base objectfor ( name in options ) {- src = target[ name ];copy = options[ name ];+ // Prevent Object.prototype pollution// Prevent never-ending loop- if ( target === copy ) {+ if ( name === "__proto__" || target === copy ) {continue;}// Recurse if we're merging plain objects or arraysif ( deep && copy && ( jQuery.isPlainObject( copy ) ||( copyIsArray = Array.isArray( copy ) ) ) ) {+ src = target[ name ];- if ( copyIsArray ) {- copyIsArray = false;- clone = src && Array.isArray( src ) ? src : [];-+ // Ensure proper type for the source value+ if ( copyIsArray && !Array.isArray( src ) ) {+ clone = [];+ } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) {+ clone = {};} else {- clone = src && jQuery.isPlainObject( src ) ? src : {};+ clone = src;}+ copyIsArray = false;// Never move original objects, clone themtarget[ name ] = jQuery.extend( deep, clone, copy );@@ -329,9 +358,6 @@ jQuery.extend( {},isEmptyObject: function( obj ) {-- /* eslint-disable no-unused-vars */- // See https://github.com/eslint/eslint/issues/6125var name;for ( name in obj ) {@@ -340,9 +366,10 @@ jQuery.extend( {return true;},- // Evaluates a script in a global context- globalEval: function( code ) {- DOMEval( code );+ // Evaluates a script in a provided context; falls back to the global one+ // if not specified.+ globalEval: function( code, options, doc ) {+ DOMEval( code, { nonce: options && options.nonce }, doc );},each: function( obj, callback ) {@@ -366,13 +393,6 @@ jQuery.extend( {return obj;},- // Support: Android <=4.0 only- trim: function( text ) {- return text == null ?- "" :- ( text + "" ).replace( rtrim, "" );- },-// results is for internal usage onlymakeArray: function( arr, results ) {var ret = results || [];@@ -459,7 +479,7 @@ jQuery.extend( {}// Flatten any nested arrays- return concat.apply( [], ret );+ return flat( ret );},// A global GUID counter for objects@@ -476,7 +496,7 @@ if ( typeof Symbol === "function" ) {// Populate the class2type mapjQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),-function( i, name ) {+function( _i, name ) {class2type[ "[object " + name + "]" ] = name.toLowerCase();} );@@ -498,17 +518,16 @@ function isArrayLike( obj ) {}var Sizzle =/*!- * Sizzle CSS Selector Engine v2.3.3+ * Sizzle CSS Selector Engine v2.3.5* https://sizzlejs.com/*- * Copyright jQuery Foundation and other contributors+ * Copyright JS Foundation and other contributors* Released under the MIT license- * http://jquery.org/license+ * https://js.foundation/*- * Date: 2016-08-08+ * Date: 2020-03-14*/-(function( window ) {-+( function( window ) {var i,support,Expr,@@ -539,6 +558,7 @@ var i,classCache = createCache(),tokenCache = createCache(),compilerCache = createCache(),+ nonnativeSelectorCache = createCache(),sortOrder = function( a, b ) {if ( a === b ) {hasDuplicate = true;@@ -547,61 +567,71 @@ var i,},// Instance methods- hasOwn = ({}).hasOwnProperty,+ hasOwn = ( {} ).hasOwnProperty,arr = [],pop = arr.pop,- push_native = arr.push,+ pushNative = arr.push,push = arr.push,slice = arr.slice,+// Use a stripped-down indexOf as it's faster than native// https://jsperf.com/thor-indexof-vs-for/5indexOf = function( list, elem ) {var i = 0,len = list.length;for ( ; i < len; i++ ) {- if ( list[i] === elem ) {+ if ( list[ i ] === elem ) {return i;}}return -1;},- booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",+ booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" ++ "ismap|loop|multiple|open|readonly|required|scoped",// Regular expressions// http://www.w3.org/TR/css3-selectors/#whitespacewhitespace = "[\\x20\\t\\r\\n\\f]",- // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier- identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",+ // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram+ identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace ++ "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectorsattributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace ++// Operator (capture 2)"*([*^$|!~]?=)" + whitespace +- // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"- "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +- "*\\]",++ // "Attribute values must be CSS identifiers [capture 5]+ // or strings [capture 3 or capture 4]"+ "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" ++ whitespace + "*\\]",pseudos = ":(" + identifier + ")(?:\\((" ++// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:// 1. quoted (capture 3; capture 4 or capture 5)"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" ++// 2. simple (capture 6)"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" ++// 3. anything else (capture 2)".*" +")\\)|)",// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latterrwhitespace = new RegExp( whitespace + "+", "g" ),- rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),+ rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" ++ whitespace + "+$", "g" ),rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),- rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),-- rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),+ rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace ++ "*" ),+ rdescend = new RegExp( whitespace + "|>" ),rpseudo = new RegExp( pseudos ),ridentifier = new RegExp( "^" + identifier + "$" ),@@ -612,16 +642,19 @@ var i,"TAG": new RegExp( "^(" + identifier + "|[*])" ),"ATTR": new RegExp( "^" + attributes ),"PSEUDO": new RegExp( "^" + pseudos ),- "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +- "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +- "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),+ "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" ++ whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" ++ whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),+// For use in libraries implementing .is()// We use this for POS matching in `select`- "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +- whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )+ "needsContext": new RegExp( "^" + whitespace ++ "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace ++ "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )},+ rhtml = /HTML$/i,rinputs = /^(?:input|select|textarea|button)$/i,rheader = /^h\d$/i,@@ -634,18 +667,21 @@ var i,// CSS escapes// http://www.w3.org/TR/CSS21/syndata.html#escaped-characters- runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),- funescape = function( _, escaped, escapedWhitespace ) {- var high = "0x" + escaped - 0x10000;- // NaN means non-codepoint- // Support: Firefox<24- // Workaround erroneous numeric interpretation of +"0x"- return high !== high || escapedWhitespace ?- escaped :+ runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ),+ funescape = function( escape, nonHex ) {+ var high = "0x" + escape.slice( 1 ) - 0x10000;++ return nonHex ?++ // Strip the backslash prefix from a non-hex escape sequence+ nonHex :++ // Replace a hexadecimal escape sequence with the encoded Unicode code point+ // Support: IE <=11++ // For values outside the Basic Multilingual Plane (BMP), manually construct a+ // surrogate pairhigh < 0 ?- // BMP codepointString.fromCharCode( high + 0x10000 ) :- // Supplemental Plane codepoint (surrogate pair)String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );},@@ -661,7 +697,8 @@ var i,}// Control characters and (dependent upon position) numbers get escaped as code points- return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";+ return ch.slice( 0, -1 ) + "\\" ++ ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";}// Other potentially-special ASCII characters get backslash-escaped@@ -676,9 +713,9 @@ var i,setDocument();},- disabledAncestor = addCombinator(+ inDisabledFieldset = addCombinator(function( elem ) {- return elem.disabled === true && ("form" in elem || "label" in elem);+ return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset";},{ dir: "parentNode", next: "legend" });@@ -686,18 +723,20 @@ var i,// Optimize for push.apply( _, NodeList )try {push.apply(- (arr = slice.call( preferredDoc.childNodes )),+ ( arr = slice.call( preferredDoc.childNodes ) ),preferredDoc.childNodes);+// Support: Android<4.0// Detect silently failing push.apply+ // eslint-disable-next-line no-unused-expressionsarr[ preferredDoc.childNodes.length ].nodeType;} catch ( e ) {push = { apply: arr.length ?// Leverage slice if possiblefunction( target, els ) {- push_native.apply( target, slice.call(els) );+ pushNative.apply( target, slice.call( els ) );} :// Support: IE<9@@ -705,8 +744,9 @@ try {function( target, els ) {var j = target.length,i = 0;+// Can't trust NodeList.length- while ( (target[j++] = els[i++]) ) {}+ while ( ( target[ j++ ] = els[ i++ ] ) ) {}target.length = j - 1;}};@@ -730,24 +770,21 @@ function Sizzle( selector, context, results, seed ) {// Try to shortcut find operations (as opposed to filters) in HTML documentsif ( !seed ) {-- if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {- setDocument( context );- }+ setDocument( context );context = context || document;if ( documentIsHTML ) {// If the selector is sufficiently simple, try using a "get*By*" DOM method// (excepting DocumentFragment context, where the methods don't exist)- if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {+ if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) {// ID selector- if ( (m = match[1]) ) {+ if ( ( m = match[ 1 ] ) ) {// Document contextif ( nodeType === 9 ) {- if ( (elem = context.getElementById( m )) ) {+ if ( ( elem = context.getElementById( m ) ) ) {// Support: IE, Opera, Webkit// TODO: identify versions@@ -766,7 +803,7 @@ function Sizzle( selector, context, results, seed ) {// Support: IE, Opera, Webkit// TODO: identify versions// getElementById can match elements by name instead of ID- if ( newContext && (elem = newContext.getElementById( m )) &&+ if ( newContext && ( elem = newContext.getElementById( m ) ) &&contains( context, elem ) &&elem.id === m ) {@@ -776,12 +813,12 @@ function Sizzle( selector, context, results, seed ) {}// Type selector- } else if ( match[2] ) {+ } else if ( match[ 2 ] ) {push.apply( results, context.getElementsByTagName( selector ) );return results;// Class selector- } else if ( (m = match[3]) && support.getElementsByClassName &&+ } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName &&context.getElementsByClassName ) {push.apply( results, context.getElementsByClassName( m ) );@@ -791,50 +828,62 @@ function Sizzle( selector, context, results, seed ) {// Take advantage of querySelectorAllif ( support.qsa &&- !compilerCache[ selector + " " ] &&- (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {-- if ( nodeType !== 1 ) {- newContext = context;- newSelector = selector;+ !nonnativeSelectorCache[ selector + " " ] &&+ ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) &&- // qSA looks outside Element context, which is not what we want- // Thanks to Andrew Dupont for this workaround technique- // Support: IE <=8+ // Support: IE 8 only// Exclude object elements- } else if ( context.nodeName.toLowerCase() !== "object" ) {+ ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) {- // Capture the context ID, setting it first if necessary- if ( (nid = context.getAttribute( "id" )) ) {- nid = nid.replace( rcssescape, fcssescape );- } else {- context.setAttribute( "id", (nid = expando) );+ newSelector = selector;+ newContext = context;++ // qSA considers elements outside a scoping root when evaluating child or+ // descendant combinators, which is not what we want.+ // In such cases, we work around the behavior by prefixing every selector in the+ // list with an ID selector referencing the scope context.+ // The technique has to be used as well when a leading combinator is used+ // as such selectors are not recognized by querySelectorAll.+ // Thanks to Andrew Dupont for this technique.+ if ( nodeType === 1 &&+ ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) {++ // Expand context for sibling selectors+ newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||+ context;++ // We can use :scope instead of the ID hack if the browser+ // supports it & if we're not changing the context.+ if ( newContext !== context || !support.scope ) {++ // Capture the context ID, setting it first if necessary+ if ( ( nid = context.getAttribute( "id" ) ) ) {+ nid = nid.replace( rcssescape, fcssescape );+ } else {+ context.setAttribute( "id", ( nid = expando ) );+ }}// Prefix every selector in the listgroups = tokenize( selector );i = groups.length;while ( i-- ) {- groups[i] = "#" + nid + " " + toSelector( groups[i] );+ groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " ++ toSelector( groups[ i ] );}newSelector = groups.join( "," );-- // Expand context for sibling selectors- newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||- context;}- if ( newSelector ) {- try {- push.apply( results,- newContext.querySelectorAll( newSelector )- );- return results;- } catch ( qsaError ) {- } finally {- if ( nid === expando ) {- context.removeAttribute( "id" );- }+ try {+ push.apply( results,+ newContext.querySelectorAll( newSelector )+ );+ return results;+ } catch ( qsaError ) {+ nonnativeSelectorCache( selector, true );+ } finally {+ if ( nid === expando ) {+ context.removeAttribute( "id" );}}}@@ -855,12 +904,14 @@ function createCache() {var keys = [];function cache( key, value ) {+// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)if ( keys.push( key + " " ) > Expr.cacheLength ) {+// Only keep the most recent entriesdelete cache[ keys.shift() ];}- return (cache[ key + " " ] = value);+ return ( cache[ key + " " ] = value );}return cache;}@@ -879,17 +930,19 @@ function markFunction( fn ) {* @param {Function} fn Passed the created element and returns a boolean result*/function assert( fn ) {- var el = document.createElement("fieldset");+ var el = document.createElement( "fieldset" );try {return !!fn( el );- } catch (e) {+ } catch ( e ) {return false;} finally {+// Remove from its parent by defaultif ( el.parentNode ) {el.parentNode.removeChild( el );}+// release memory in IEel = null;}@@ -901,11 +954,11 @@ function assert( fn ) {* @param {Function} handler The method that will be applied*/function addHandle( attrs, handler ) {- var arr = attrs.split("|"),+ var arr = attrs.split( "|" ),i = arr.length;while ( i-- ) {- Expr.attrHandle[ arr[i] ] = handler;+ Expr.attrHandle[ arr[ i ] ] = handler;}}@@ -927,7 +980,7 @@ function siblingCheck( a, b ) {// Check if b follows aif ( cur ) {- while ( (cur = cur.nextSibling) ) {+ while ( ( cur = cur.nextSibling ) ) {if ( cur === b ) {return -1;}@@ -955,7 +1008,7 @@ function createInputPseudo( type ) {function createButtonPseudo( type ) {return function( elem ) {var name = elem.nodeName.toLowerCase();- return (name === "input" || name === "button") && elem.type === type;+ return ( name === "input" || name === "button" ) && elem.type === type;};}@@ -998,7 +1051,7 @@ function createDisabledPseudo( disabled ) {// Where there is no isDisabled, check manually/* jshint -W018 */elem.isDisabled !== !disabled &&- disabledAncestor( elem ) === disabled;+ inDisabledFieldset( elem ) === disabled;}return elem.disabled === disabled;@@ -1020,21 +1073,21 @@ function createDisabledPseudo( disabled ) {* @param {Function} fn*/function createPositionalPseudo( fn ) {- return markFunction(function( argument ) {+ return markFunction( function( argument ) {argument = +argument;- return markFunction(function( seed, matches ) {+ return markFunction( function( seed, matches ) {var j,matchIndexes = fn( [], seed.length, argument ),i = matchIndexes.length;// Match elements found at the specified indexeswhile ( i-- ) {- if ( seed[ (j = matchIndexes[i]) ] ) {- seed[j] = !(matches[j] = seed[j]);+ if ( seed[ ( j = matchIndexes[ i ] ) ] ) {+ seed[ j ] = !( matches[ j ] = seed[ j ] );}}- });- });+ } );+ } );}/**@@ -1055,10 +1108,13 @@ support = Sizzle.support = {};* @returns {Boolean} True iff elem is a non-HTML XML node*/isXML = Sizzle.isXML = function( elem ) {- // documentElement is verified for cases where it doesn't yet exist- // (such as loading iframes in IE - #4833)- var documentElement = elem && (elem.ownerDocument || elem).documentElement;- return documentElement ? documentElement.nodeName !== "HTML" : false;+ var namespace = elem.namespaceURI,+ docElem = ( elem.ownerDocument || elem ).documentElement;++ // Support: IE <=8+ // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes+ // https://bugs.jquery.com/ticket/4833+ return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" );};/**@@ -1071,7 +1127,11 @@ setDocument = Sizzle.setDocument = function( node ) {doc = node ? node.ownerDocument || node : preferredDoc;// Return early if doc is invalid or already selected- if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {+ // Support: IE 11+, Edge 17 - 18++ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing+ // two documents; shallow comparisons work.+ // eslint-disable-next-line eqeqeq+ if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) {return document;}@@ -1080,10 +1140,14 @@ setDocument = Sizzle.setDocument = function( node ) {docElem = document.documentElement;documentIsHTML = !isXML( document );- // Support: IE 9-11, Edge+ // Support: IE 9 - 11+, Edge 12 - 18+// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)- if ( preferredDoc !== document &&- (subWindow = document.defaultView) && subWindow.top !== subWindow ) {+ // Support: IE 11+, Edge 17 - 18++ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing+ // two documents; shallow comparisons work.+ // eslint-disable-next-line eqeqeq+ if ( preferredDoc != document &&+ ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) {// Support: IE 11, Edgeif ( subWindow.addEventListener ) {@@ -1095,25 +1159,36 @@ setDocument = Sizzle.setDocument = function( node ) {}}+ // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only,+ // Safari 4 - 5 only, Opera <=11.6 - 12.x only+ // IE/Edge & older browsers don't support the :scope pseudo-class.+ // Support: Safari 6.0 only+ // Safari 6.0 supports :scope but it's an alias of :root there.+ support.scope = assert( function( el ) {+ docElem.appendChild( el ).appendChild( document.createElement( "div" ) );+ return typeof el.querySelectorAll !== "undefined" &&+ !el.querySelectorAll( ":scope fieldset div" ).length;+ } );+/* Attributes---------------------------------------------------------------------- */// Support: IE<8// Verify that getAttribute really returns attributes and not properties// (excepting IE8 booleans)- support.attributes = assert(function( el ) {+ support.attributes = assert( function( el ) {el.className = "i";- return !el.getAttribute("className");- });+ return !el.getAttribute( "className" );+ } );/* getElement(s)By*---------------------------------------------------------------------- */// Check if getElementsByTagName("*") returns only elements- support.getElementsByTagName = assert(function( el ) {- el.appendChild( document.createComment("") );- return !el.getElementsByTagName("*").length;- });+ support.getElementsByTagName = assert( function( el ) {+ el.appendChild( document.createComment( "" ) );+ return !el.getElementsByTagName( "*" ).length;+ } );// Support: IE<9support.getElementsByClassName = rnative.test( document.getElementsByClassName );@@ -1122,38 +1197,38 @@ setDocument = Sizzle.setDocument = function( node ) {// Check if getElementById returns elements by name// The broken getElementById methods don't pick up programmatically-set names,// so use a roundabout getElementsByName test- support.getById = assert(function( el ) {+ support.getById = assert( function( el ) {docElem.appendChild( el ).id = expando;return !document.getElementsByName || !document.getElementsByName( expando ).length;- });+ } );// ID filter and findif ( support.getById ) {- Expr.filter["ID"] = function( id ) {+ Expr.filter[ "ID" ] = function( id ) {var attrId = id.replace( runescape, funescape );return function( elem ) {- return elem.getAttribute("id") === attrId;+ return elem.getAttribute( "id" ) === attrId;};};- Expr.find["ID"] = function( id, context ) {+ Expr.find[ "ID" ] = function( id, context ) {if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {var elem = context.getElementById( id );return elem ? [ elem ] : [];}};} else {- Expr.filter["ID"] = function( id ) {+ Expr.filter[ "ID" ] = function( id ) {var attrId = id.replace( runescape, funescape );return function( elem ) {var node = typeof elem.getAttributeNode !== "undefined" &&- elem.getAttributeNode("id");+ elem.getAttributeNode( "id" );return node && node.value === attrId;};};// Support: IE 6 - 7 only// getElementById is not reliable as a find shortcut- Expr.find["ID"] = function( id, context ) {+ Expr.find[ "ID" ] = function( id, context ) {if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {var node, i, elems,elem = context.getElementById( id );@@ -1161,7 +1236,7 @@ setDocument = Sizzle.setDocument = function( node ) {if ( elem ) {// Verify the id attribute- node = elem.getAttributeNode("id");+ node = elem.getAttributeNode( "id" );if ( node && node.value === id ) {return [ elem ];}@@ -1169,8 +1244,8 @@ setDocument = Sizzle.setDocument = function( node ) {// Fall back on getElementsByNameelems = context.getElementsByName( id );i = 0;- while ( (elem = elems[i++]) ) {- node = elem.getAttributeNode("id");+ while ( ( elem = elems[ i++ ] ) ) {+ node = elem.getAttributeNode( "id" );if ( node && node.value === id ) {return [ elem ];}@@ -1183,7 +1258,7 @@ setDocument = Sizzle.setDocument = function( node ) {}// Tag- Expr.find["TAG"] = support.getElementsByTagName ?+ Expr.find[ "TAG" ] = support.getElementsByTagName ?function( tag, context ) {if ( typeof context.getElementsByTagName !== "undefined" ) {return context.getElementsByTagName( tag );@@ -1198,12 +1273,13 @@ setDocument = Sizzle.setDocument = function( node ) {var elem,tmp = [],i = 0,+// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes tooresults = context.getElementsByTagName( tag );// Filter out possible commentsif ( tag === "*" ) {- while ( (elem = results[i++]) ) {+ while ( ( elem = results[ i++ ] ) ) {if ( elem.nodeType === 1 ) {tmp.push( elem );}@@ -1215,7 +1291,7 @@ setDocument = Sizzle.setDocument = function( node ) {};// Class- Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {+ Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) {if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {return context.getElementsByClassName( className );}@@ -1236,10 +1312,14 @@ setDocument = Sizzle.setDocument = function( node ) {// See https://bugs.jquery.com/ticket/13378rbuggyQSA = [];- if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {+ if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) {+// Build QSA regex// Regex strategy adopted from Diego Perini- assert(function( el ) {+ assert( function( el ) {++ var input;+// Select is set to empty string on purpose// This is to test IE's treatment of not explicitly// setting a boolean content attribute,@@ -1253,78 +1333,98 @@ setDocument = Sizzle.setDocument = function( node ) {// Nothing should be selected when empty strings follow ^= or $= or *=// The test attribute must be unknown in Opera but "safe" for WinRT// https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section- if ( el.querySelectorAll("[msallowcapture^='']").length ) {+ if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) {rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );}// Support: IE8// Boolean attributes and "value" are not treated correctly- if ( !el.querySelectorAll("[selected]").length ) {+ if ( !el.querySelectorAll( "[selected]" ).length ) {rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );}// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {- rbuggyQSA.push("~=");+ rbuggyQSA.push( "~=" );+ }++ // Support: IE 11+, Edge 15 - 18++ // IE 11/Edge don't find elements on a `[name='']` query in some cases.+ // Adding a temporary attribute to the document before the selection works+ // around the issue.+ // Interestingly, IE 10 & older don't seem to have the issue.+ input = document.createElement( "input" );+ input.setAttribute( "name", "" );+ el.appendChild( input );+ if ( !el.querySelectorAll( "[name='']" ).length ) {+ rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" ++ whitespace + "*(?:''|\"\")" );}// Webkit/Opera - :checked should return selected option elements// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked// IE8 throws error here and will not see later tests- if ( !el.querySelectorAll(":checked").length ) {- rbuggyQSA.push(":checked");+ if ( !el.querySelectorAll( ":checked" ).length ) {+ rbuggyQSA.push( ":checked" );}// Support: Safari 8+, iOS 8+// https://bugs.webkit.org/show_bug.cgi?id=136851// In-page `selector#id sibling-combinator selector` failsif ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {- rbuggyQSA.push(".#.+[+~]");+ rbuggyQSA.push( ".#.+[+~]" );}- });- assert(function( el ) {+ // Support: Firefox <=3.6 - 5 only+ // Old Firefox doesn't throw on a badly-escaped identifier.+ el.querySelectorAll( "\\\f" );+ rbuggyQSA.push( "[\\r\\n\\f]" );+ } );++ assert( function( el ) {el.innerHTML = "<a href='' disabled='disabled'></a>" +"<select disabled='disabled'><option/></select>";// Support: Windows 8 Native Apps// The type and name attributes are restricted during .innerHTML assignment- var input = document.createElement("input");+ var input = document.createElement( "input" );input.setAttribute( "type", "hidden" );el.appendChild( input ).setAttribute( "name", "D" );// Support: IE8// Enforce case-sensitivity of name attribute- if ( el.querySelectorAll("[name=d]").length ) {+ if ( el.querySelectorAll( "[name=d]" ).length ) {rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );}// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)// IE8 throws error here and will not see later tests- if ( el.querySelectorAll(":enabled").length !== 2 ) {+ if ( el.querySelectorAll( ":enabled" ).length !== 2 ) {rbuggyQSA.push( ":enabled", ":disabled" );}// Support: IE9-11+// IE's :disabled selector does not pick up the children of disabled fieldsetsdocElem.appendChild( el ).disabled = true;- if ( el.querySelectorAll(":disabled").length !== 2 ) {+ if ( el.querySelectorAll( ":disabled" ).length !== 2 ) {rbuggyQSA.push( ":enabled", ":disabled" );}+ // Support: Opera 10 - 11 only// Opera 10-11 does not throw on post-comma invalid pseudos- el.querySelectorAll("*,:x");- rbuggyQSA.push(",.*:");- });+ el.querySelectorAll( "*,:x" );+ rbuggyQSA.push( ",.*:" );+ } );}- if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||+ if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches ||docElem.webkitMatchesSelector ||docElem.mozMatchesSelector ||docElem.oMatchesSelector ||- docElem.msMatchesSelector) )) ) {+ docElem.msMatchesSelector ) ) ) ) {++ assert( function( el ) {- assert(function( el ) {// Check to see if it's possible to do matchesSelector// on a disconnected node (IE 9)support.disconnectedMatch = matches.call( el, "*" );@@ -1333,11 +1433,11 @@ setDocument = Sizzle.setDocument = function( node ) {// Gecko does not error, returns false insteadmatches.call( el, "[s!='']:x" );rbuggyMatches.push( "!=", pseudos );- });+ } );}- rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );- rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );+ rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) );+ rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) );/* Contains---------------------------------------------------------------------- */@@ -1354,11 +1454,11 @@ setDocument = Sizzle.setDocument = function( node ) {adown.contains ?adown.contains( bup ) :a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16- ));+ ) );} :function( a, b ) {if ( b ) {- while ( (b = b.parentNode) ) {+ while ( ( b = b.parentNode ) ) {if ( b === a ) {return true;}@@ -1387,7 +1487,11 @@ setDocument = Sizzle.setDocument = function( node ) {}// Calculate position if both inputs belong to the same document- compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?+ // Support: IE 11+, Edge 17 - 18++ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing+ // two documents; shallow comparisons work.+ // eslint-disable-next-line eqeqeq+ compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ?a.compareDocumentPosition( b ) :// Otherwise we know they are disconnected@@ -1395,13 +1499,24 @@ setDocument = Sizzle.setDocument = function( node ) {// Disconnected nodesif ( compare & 1 ||- (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {+ ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) {// Choose the first element that is related to our preferred document- if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {+ // Support: IE 11+, Edge 17 - 18++ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing+ // two documents; shallow comparisons work.+ // eslint-disable-next-line eqeqeq+ if ( a == document || a.ownerDocument == preferredDoc &&+ contains( preferredDoc, a ) ) {return -1;}- if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {++ // Support: IE 11+, Edge 17 - 18++ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing+ // two documents; shallow comparisons work.+ // eslint-disable-next-line eqeqeq+ if ( b == document || b.ownerDocument == preferredDoc &&+ contains( preferredDoc, b ) ) {return 1;}@@ -1414,6 +1529,7 @@ setDocument = Sizzle.setDocument = function( node ) {return compare & 4 ? -1 : 1;} :function( a, b ) {+// Exit early if the nodes are identicalif ( a === b ) {hasDuplicate = true;@@ -1429,8 +1545,14 @@ setDocument = Sizzle.setDocument = function( node ) {// Parentless nodes are either documents or disconnectedif ( !aup || !bup ) {- return a === document ? -1 :- b === document ? 1 :++ // Support: IE 11+, Edge 17 - 18++ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing+ // two documents; shallow comparisons work.+ /* eslint-disable eqeqeq */+ return a == document ? -1 :+ b == document ? 1 :+ /* eslint-enable eqeqeq */aup ? -1 :bup ? 1 :sortInput ?@@ -1444,26 +1566,32 @@ setDocument = Sizzle.setDocument = function( node ) {// Otherwise we need full lists of their ancestors for comparisoncur = a;- while ( (cur = cur.parentNode) ) {+ while ( ( cur = cur.parentNode ) ) {ap.unshift( cur );}cur = b;- while ( (cur = cur.parentNode) ) {+ while ( ( cur = cur.parentNode ) ) {bp.unshift( cur );}// Walk down the tree looking for a discrepancy- while ( ap[i] === bp[i] ) {+ while ( ap[ i ] === bp[ i ] ) {i++;}return i ?+// Do a sibling check if the nodes have a common ancestor- siblingCheck( ap[i], bp[i] ) :+ siblingCheck( ap[ i ], bp[ i ] ) :// Otherwise nodes in our document sort first- ap[i] === preferredDoc ? -1 :- bp[i] === preferredDoc ? 1 :+ // Support: IE 11+, Edge 17 - 18++ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing+ // two documents; shallow comparisons work.+ /* eslint-disable eqeqeq */+ ap[ i ] == preferredDoc ? -1 :+ bp[ i ] == preferredDoc ? 1 :+ /* eslint-enable eqeqeq */0;};@@ -1475,16 +1603,10 @@ Sizzle.matches = function( expr, elements ) {};Sizzle.matchesSelector = function( elem, expr ) {- // Set document vars if needed- if ( ( elem.ownerDocument || elem ) !== document ) {- setDocument( elem );- }-- // Make sure that attribute selectors are quoted- expr = expr.replace( rattributeQuotes, "='$1']" );+ setDocument( elem );if ( support.matchesSelector && documentIsHTML &&- !compilerCache[ expr + " " ] &&+ !nonnativeSelectorCache[ expr + " " ] &&( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {@@ -1493,32 +1615,46 @@ Sizzle.matchesSelector = function( elem, expr ) {// IE 9's matchesSelector returns false on disconnected nodesif ( ret || support.disconnectedMatch ||- // As well, disconnected nodes are said to be in a document- // fragment in IE 9- elem.document && elem.document.nodeType !== 11 ) {++ // As well, disconnected nodes are said to be in a document+ // fragment in IE 9+ elem.document && elem.document.nodeType !== 11 ) {return ret;}- } catch (e) {}+ } catch ( e ) {+ nonnativeSelectorCache( expr, true );+ }}return Sizzle( expr, document, null, [ elem ] ).length > 0;};Sizzle.contains = function( context, elem ) {+// Set document vars if needed- if ( ( context.ownerDocument || context ) !== document ) {+ // Support: IE 11+, Edge 17 - 18++ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing+ // two documents; shallow comparisons work.+ // eslint-disable-next-line eqeqeq+ if ( ( context.ownerDocument || context ) != document ) {setDocument( context );}return contains( context, elem );};Sizzle.attr = function( elem, name ) {+// Set document vars if needed- if ( ( elem.ownerDocument || elem ) !== document ) {+ // Support: IE 11+, Edge 17 - 18++ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing+ // two documents; shallow comparisons work.+ // eslint-disable-next-line eqeqeq+ if ( ( elem.ownerDocument || elem ) != document ) {setDocument( elem );}var fn = Expr.attrHandle[ name.toLowerCase() ],+// Don't get fooled by Object.prototype properties (jQuery #13807)val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?fn( elem, name, !documentIsHTML ) :@@ -1528,13 +1664,13 @@ Sizzle.attr = function( elem, name ) {val :support.attributes || !documentIsHTML ?elem.getAttribute( name ) :- (val = elem.getAttributeNode(name)) && val.specified ?+ ( val = elem.getAttributeNode( name ) ) && val.specified ?val.value :null;};Sizzle.escape = function( sel ) {- return (sel + "").replace( rcssescape, fcssescape );+ return ( sel + "" ).replace( rcssescape, fcssescape );};Sizzle.error = function( msg ) {@@ -1557,7 +1693,7 @@ Sizzle.uniqueSort = function( results ) {results.sort( sortOrder );if ( hasDuplicate ) {- while ( (elem = results[i++]) ) {+ while ( ( elem = results[ i++ ] ) ) {if ( elem === results[ i ] ) {j = duplicates.push( i );}@@ -1585,17 +1721,21 @@ getText = Sizzle.getText = function( elem ) {nodeType = elem.nodeType;if ( !nodeType ) {+// If no nodeType, this is expected to be an array- while ( (node = elem[i++]) ) {+ while ( ( node = elem[ i++ ] ) ) {+// Do not traverse comment nodesret += getText( node );}} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {+// Use textContent for elements// innerText usage removed for consistency of new lines (jQuery #11153)if ( typeof elem.textContent === "string" ) {return elem.textContent;} else {+// Traverse its childrenfor ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {ret += getText( elem );@@ -1604,6 +1744,7 @@ getText = Sizzle.getText = function( elem ) {} else if ( nodeType === 3 || nodeType === 4 ) {return elem.nodeValue;}+// Do not include comment or processing instruction nodesreturn ret;@@ -1631,19 +1772,21 @@ Expr = Sizzle.selectors = {preFilter: {"ATTR": function( match ) {- match[1] = match[1].replace( runescape, funescape );+ match[ 1 ] = match[ 1 ].replace( runescape, funescape );// Move the given value to match[3] whether quoted or unquoted- match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );+ match[ 3 ] = ( match[ 3 ] || match[ 4 ] ||+ match[ 5 ] || "" ).replace( runescape, funescape );- if ( match[2] === "~=" ) {- match[3] = " " + match[3] + " ";+ if ( match[ 2 ] === "~=" ) {+ match[ 3 ] = " " + match[ 3 ] + " ";}return match.slice( 0, 4 );},"CHILD": function( match ) {+/* matches from matchExpr["CHILD"]1 type (only|nth|...)2 what (child|of-type)@@ -1654,22 +1797,25 @@ Expr = Sizzle.selectors = {7 sign of y-component8 y of y-component*/- match[1] = match[1].toLowerCase();+ match[ 1 ] = match[ 1 ].toLowerCase();++ if ( match[ 1 ].slice( 0, 3 ) === "nth" ) {- if ( match[1].slice( 0, 3 ) === "nth" ) {// nth-* requires argument- if ( !match[3] ) {- Sizzle.error( match[0] );+ if ( !match[ 3 ] ) {+ Sizzle.error( match[ 0 ] );}// numeric x and y parameters for Expr.filter.CHILD// remember that false/true cast respectively to 0/1- match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );- match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );+ match[ 4 ] = +( match[ 4 ] ?+ match[ 5 ] + ( match[ 6 ] || 1 ) :+ 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) );+ match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" );- // other types prohibit arguments- } else if ( match[3] ) {- Sizzle.error( match[0] );+ // other types prohibit arguments+ } else if ( match[ 3 ] ) {+ Sizzle.error( match[ 0 ] );}return match;@@ -1677,26 +1823,28 @@ Expr = Sizzle.selectors = {"PSEUDO": function( match ) {var excess,- unquoted = !match[6] && match[2];+ unquoted = !match[ 6 ] && match[ 2 ];- if ( matchExpr["CHILD"].test( match[0] ) ) {+ if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) {return null;}// Accept quoted arguments as-is- if ( match[3] ) {- match[2] = match[4] || match[5] || "";+ if ( match[ 3 ] ) {+ match[ 2 ] = match[ 4 ] || match[ 5 ] || "";// Strip excess characters from unquoted arguments} else if ( unquoted && rpseudo.test( unquoted ) &&+// Get excess from tokenize (recursively)- (excess = tokenize( unquoted, true )) &&+ ( excess = tokenize( unquoted, true ) ) &&+// advance to the next closing parenthesis- (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {+ ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) {// excess is a negative index- match[0] = match[0].slice( 0, excess );- match[2] = unquoted.slice( 0, excess );+ match[ 0 ] = match[ 0 ].slice( 0, excess );+ match[ 2 ] = unquoted.slice( 0, excess );}// Return only captures needed by the pseudo filter method (type and argument)@@ -1709,7 +1857,9 @@ Expr = Sizzle.selectors = {"TAG": function( nodeNameSelector ) {var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();return nodeNameSelector === "*" ?- function() { return true; } :+ function() {+ return true;+ } :function( elem ) {return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;};@@ -1719,10 +1869,16 @@ Expr = Sizzle.selectors = {var pattern = classCache[ className + " " ];return pattern ||- (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&- classCache( className, function( elem ) {- return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );- });+ ( pattern = new RegExp( "(^|" + whitespace ++ ")" + className + "(" + whitespace + "|$)" ) ) && classCache(+ className, function( elem ) {+ return pattern.test(+ typeof elem.className === "string" && elem.className ||+ typeof elem.getAttribute !== "undefined" &&+ elem.getAttribute( "class" ) ||+ ""+ );+ } );},"ATTR": function( name, operator, check ) {@@ -1738,6 +1894,8 @@ Expr = Sizzle.selectors = {result += "";+ /* eslint-disable max-len */+return operator === "=" ? result === check :operator === "!=" ? result !== check :operator === "^=" ? check && result.indexOf( check ) === 0 :@@ -1746,10 +1904,12 @@ Expr = Sizzle.selectors = {operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :false;+ /* eslint-enable max-len */+};},- "CHILD": function( type, what, argument, first, last ) {+ "CHILD": function( type, what, _argument, first, last ) {var simple = type.slice( 0, 3 ) !== "nth",forward = type.slice( -4 ) !== "last",ofType = what === "of-type";@@ -1761,7 +1921,7 @@ Expr = Sizzle.selectors = {return !!elem.parentNode;} :- function( elem, context, xml ) {+ function( elem, _context, xml ) {var cache, uniqueCache, outerCache, node, nodeIndex, start,dir = simple !== forward ? "nextSibling" : "previousSibling",parent = elem.parentNode,@@ -1775,7 +1935,7 @@ Expr = Sizzle.selectors = {if ( simple ) {while ( dir ) {node = elem;- while ( (node = node[ dir ]) ) {+ while ( ( node = node[ dir ] ) ) {if ( ofType ?node.nodeName.toLowerCase() === name :node.nodeType === 1 ) {@@ -1783,6 +1943,7 @@ Expr = Sizzle.selectors = {return false;}}+// Reverse direction for :only-* (if we haven't yet done so)start = dir = type === "only" && !start && "nextSibling";}@@ -1798,22 +1959,22 @@ Expr = Sizzle.selectors = {// ...in a gzip-friendly waynode = parent;- outerCache = node[ expando ] || (node[ expando ] = {});+ outerCache = node[ expando ] || ( node[ expando ] = {} );// Support: IE <9 only// Defend against cloned attroperties (jQuery gh-1709)uniqueCache = outerCache[ node.uniqueID ] ||- (outerCache[ node.uniqueID ] = {});+ ( outerCache[ node.uniqueID ] = {} );cache = uniqueCache[ type ] || [];nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];diff = nodeIndex && cache[ 2 ];node = nodeIndex && parent.childNodes[ nodeIndex ];- while ( (node = ++nodeIndex && node && node[ dir ] ||+ while ( ( node = ++nodeIndex && node && node[ dir ] ||// Fallback to seeking `elem` from the start- (diff = nodeIndex = 0) || start.pop()) ) {+ ( diff = nodeIndex = 0 ) || start.pop() ) ) {// When found, cache indexes on `parent` and breakif ( node.nodeType === 1 && ++diff && node === elem ) {@@ -1823,16 +1984,18 @@ Expr = Sizzle.selectors = {}} else {+// Use previously-cached element index if availableif ( useCache ) {+// ...in a gzip-friendly waynode = elem;- outerCache = node[ expando ] || (node[ expando ] = {});+ outerCache = node[ expando ] || ( node[ expando ] = {} );// Support: IE <9 only// Defend against cloned attroperties (jQuery gh-1709)uniqueCache = outerCache[ node.uniqueID ] ||- (outerCache[ node.uniqueID ] = {});+ ( outerCache[ node.uniqueID ] = {} );cache = uniqueCache[ type ] || [];nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];@@ -1842,9 +2005,10 @@ Expr = Sizzle.selectors = {// xml :nth-child(...)// or :nth-last-child(...) or :nth(-last)?-of-type(...)if ( diff === false ) {+// Use the same loop as above to seek `elem` from the start- while ( (node = ++nodeIndex && node && node[ dir ] ||- (diff = nodeIndex = 0) || start.pop()) ) {+ while ( ( node = ++nodeIndex && node && node[ dir ] ||+ ( diff = nodeIndex = 0 ) || start.pop() ) ) {if ( ( ofType ?node.nodeName.toLowerCase() === name :@@ -1853,12 +2017,13 @@ Expr = Sizzle.selectors = {// Cache the index of each encountered elementif ( useCache ) {- outerCache = node[ expando ] || (node[ expando ] = {});+ outerCache = node[ expando ] ||+ ( node[ expando ] = {} );// Support: IE <9 only// Defend against cloned attroperties (jQuery gh-1709)uniqueCache = outerCache[ node.uniqueID ] ||- (outerCache[ node.uniqueID ] = {});+ ( outerCache[ node.uniqueID ] = {} );uniqueCache[ type ] = [ dirruns, diff ];}@@ -1879,6 +2044,7 @@ Expr = Sizzle.selectors = {},"PSEUDO": function( pseudo, argument ) {+// pseudo-class names are case-insensitive// http://www.w3.org/TR/selectors/#pseudo-classes// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters@@ -1898,15 +2064,15 @@ Expr = Sizzle.selectors = {if ( fn.length > 1 ) {args = [ pseudo, pseudo, "", argument ];return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?- markFunction(function( seed, matches ) {+ markFunction( function( seed, matches ) {var idx,matched = fn( seed, argument ),i = matched.length;while ( i-- ) {- idx = indexOf( seed, matched[i] );- seed[ idx ] = !( matches[ idx ] = matched[i] );+ idx = indexOf( seed, matched[ i ] );+ seed[ idx ] = !( matches[ idx ] = matched[ i ] );}- }) :+ } ) :function( elem ) {return fn( elem, 0, args );};@@ -1917,8 +2083,10 @@ Expr = Sizzle.selectors = {},pseudos: {+// Potentially complex pseudos- "not": markFunction(function( selector ) {+ "not": markFunction( function( selector ) {+// Trim the selector passed to compile// to avoid treating leading and trailing// spaces as combinators@@ -1927,39 +2095,40 @@ Expr = Sizzle.selectors = {matcher = compile( selector.replace( rtrim, "$1" ) );return matcher[ expando ] ?- markFunction(function( seed, matches, context, xml ) {+ markFunction( function( seed, matches, _context, xml ) {var elem,unmatched = matcher( seed, null, xml, [] ),i = seed.length;// Match elements unmatched by `matcher`while ( i-- ) {- if ( (elem = unmatched[i]) ) {- seed[i] = !(matches[i] = elem);+ if ( ( elem = unmatched[ i ] ) ) {+ seed[ i ] = !( matches[ i ] = elem );}}- }) :- function( elem, context, xml ) {- input[0] = elem;+ } ) :+ function( elem, _context, xml ) {+ input[ 0 ] = elem;matcher( input, null, xml, results );+// Don't keep the element (issue #299)- input[0] = null;+ input[ 0 ] = null;return !results.pop();};- }),+ } ),- "has": markFunction(function( selector ) {+ "has": markFunction( function( selector ) {return function( elem ) {return Sizzle( selector, elem ).length > 0;};- }),+ } ),- "contains": markFunction(function( text ) {+ "contains": markFunction( function( text ) {text = text.replace( runescape, funescape );return function( elem ) {- return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;+ return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1;};- }),+ } ),// "Whether an element is represented by a :lang() selector// is based solely on the element's language value@@ -1969,25 +2138,26 @@ Expr = Sizzle.selectors = {// The identifier C does not have to be a valid language name."// http://www.w3.org/TR/selectors/#lang-pseudo"lang": markFunction( function( lang ) {+// lang value must be a valid identifier- if ( !ridentifier.test(lang || "") ) {+ if ( !ridentifier.test( lang || "" ) ) {Sizzle.error( "unsupported lang: " + lang );}lang = lang.replace( runescape, funescape ).toLowerCase();return function( elem ) {var elemLang;do {- if ( (elemLang = documentIsHTML ?+ if ( ( elemLang = documentIsHTML ?elem.lang :- elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {+ elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) {elemLang = elemLang.toLowerCase();return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;}- } while ( (elem = elem.parentNode) && elem.nodeType === 1 );+ } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 );return false;};- }),+ } ),// Miscellaneous"target": function( elem ) {@@ -2000,7 +2170,9 @@ Expr = Sizzle.selectors = {},"focus": function( elem ) {- return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);+ return elem === document.activeElement &&+ ( !document.hasFocus || document.hasFocus() ) &&+ !!( elem.type || elem.href || ~elem.tabIndex );},// Boolean properties@@ -2008,16 +2180,20 @@ Expr = Sizzle.selectors = {"disabled": createDisabledPseudo( true ),"checked": function( elem ) {+// In CSS3, :checked should return both checked and selected elements// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checkedvar nodeName = elem.nodeName.toLowerCase();- return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);+ return ( nodeName === "input" && !!elem.checked ) ||+ ( nodeName === "option" && !!elem.selected );},"selected": function( elem ) {+// Accessing this property makes selected-by-default// options in Safari work properlyif ( elem.parentNode ) {+ // eslint-disable-next-line no-unused-expressionselem.parentNode.selectedIndex;}@@ -2026,6 +2202,7 @@ Expr = Sizzle.selectors = {// Contents"empty": function( elem ) {+// http://www.w3.org/TR/selectors/#empty-pseudo// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),// but not by others (comment: 8; processing instruction: 7; etc.)@@ -2039,7 +2216,7 @@ Expr = Sizzle.selectors = {},"parent": function( elem ) {- return !Expr.pseudos["empty"]( elem );+ return !Expr.pseudos[ "empty" ]( elem );},// Element/input types@@ -2063,57 +2240,62 @@ Expr = Sizzle.selectors = {// Support: IE<8// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"- ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );+ ( ( attr = elem.getAttribute( "type" ) ) == null ||+ attr.toLowerCase() === "text" );},// Position-in-collection- "first": createPositionalPseudo(function() {+ "first": createPositionalPseudo( function() {return [ 0 ];- }),+ } ),- "last": createPositionalPseudo(function( matchIndexes, length ) {+ "last": createPositionalPseudo( function( _matchIndexes, length ) {return [ length - 1 ];- }),+ } ),- "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {+ "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) {return [ argument < 0 ? argument + length : argument ];- }),+ } ),- "even": createPositionalPseudo(function( matchIndexes, length ) {+ "even": createPositionalPseudo( function( matchIndexes, length ) {var i = 0;for ( ; i < length; i += 2 ) {matchIndexes.push( i );}return matchIndexes;- }),+ } ),- "odd": createPositionalPseudo(function( matchIndexes, length ) {+ "odd": createPositionalPseudo( function( matchIndexes, length ) {var i = 1;for ( ; i < length; i += 2 ) {matchIndexes.push( i );}return matchIndexes;- }),+ } ),- "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {- var i = argument < 0 ? argument + length : argument;+ "lt": createPositionalPseudo( function( matchIndexes, length, argument ) {+ var i = argument < 0 ?+ argument + length :+ argument > length ?+ length :+ argument;for ( ; --i >= 0; ) {matchIndexes.push( i );}return matchIndexes;- }),+ } ),- "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {+ "gt": createPositionalPseudo( function( matchIndexes, length, argument ) {var i = argument < 0 ? argument + length : argument;for ( ; ++i < length; ) {matchIndexes.push( i );}return matchIndexes;- })+ } )}};-Expr.pseudos["nth"] = Expr.pseudos["eq"];+Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ];// Add button/input type pseudosfor ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {@@ -2144,37 +2326,39 @@ tokenize = Sizzle.tokenize = function( selector, parseOnly ) {while ( soFar ) {// Comma and first run- if ( !matched || (match = rcomma.exec( soFar )) ) {+ if ( !matched || ( match = rcomma.exec( soFar ) ) ) {if ( match ) {+// Don't consume trailing commas as valid- soFar = soFar.slice( match[0].length ) || soFar;+ soFar = soFar.slice( match[ 0 ].length ) || soFar;}- groups.push( (tokens = []) );+ groups.push( ( tokens = [] ) );}matched = false;// Combinators- if ( (match = rcombinators.exec( soFar )) ) {+ if ( ( match = rcombinators.exec( soFar ) ) ) {matched = match.shift();- tokens.push({+ tokens.push( {value: matched,+// Cast descendant combinators to space- type: match[0].replace( rtrim, " " )- });+ type: match[ 0 ].replace( rtrim, " " )+ } );soFar = soFar.slice( matched.length );}// Filtersfor ( type in Expr.filter ) {- if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||- (match = preFilters[ type ]( match ))) ) {+ if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] ||+ ( match = preFilters[ type ]( match ) ) ) ) {matched = match.shift();- tokens.push({+ tokens.push( {value: matched,type: type,matches: match- });+ } );soFar = soFar.slice( matched.length );}}@@ -2191,6 +2375,7 @@ tokenize = Sizzle.tokenize = function( selector, parseOnly ) {soFar.length :soFar ?Sizzle.error( selector ) :+// Cache the tokenstokenCache( selector, groups ).slice( 0 );};@@ -2200,7 +2385,7 @@ function toSelector( tokens ) {len = tokens.length,selector = "";for ( ; i < len; i++ ) {- selector += tokens[i].value;+ selector += tokens[ i ].value;}return selector;}@@ -2213,9 +2398,10 @@ function addCombinator( matcher, combinator, base ) {doneName = done++;return combinator.first ?+// Check against closest ancestor/preceding elementfunction( elem, context, xml ) {- while ( (elem = elem[ dir ]) ) {+ while ( ( elem = elem[ dir ] ) ) {if ( elem.nodeType === 1 || checkNonElements ) {return matcher( elem, context, xml );}@@ -2230,7 +2416,7 @@ function addCombinator( matcher, combinator, base ) {// We can't set arbitrary data on XML nodes, so they don't benefit from combinator cachingif ( xml ) {- while ( (elem = elem[ dir ]) ) {+ while ( ( elem = elem[ dir ] ) ) {if ( elem.nodeType === 1 || checkNonElements ) {if ( matcher( elem, context, xml ) ) {return true;@@ -2238,27 +2424,29 @@ function addCombinator( matcher, combinator, base ) {}}} else {- while ( (elem = elem[ dir ]) ) {+ while ( ( elem = elem[ dir ] ) ) {if ( elem.nodeType === 1 || checkNonElements ) {- outerCache = elem[ expando ] || (elem[ expando ] = {});+ outerCache = elem[ expando ] || ( elem[ expando ] = {} );// Support: IE <9 only// Defend against cloned attroperties (jQuery gh-1709)- uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});+ uniqueCache = outerCache[ elem.uniqueID ] ||+ ( outerCache[ elem.uniqueID ] = {} );if ( skip && skip === elem.nodeName.toLowerCase() ) {elem = elem[ dir ] || elem;- } else if ( (oldCache = uniqueCache[ key ]) &&+ } else if ( ( oldCache = uniqueCache[ key ] ) &&oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {// Assign to newCache so results back-propagate to previous elements- return (newCache[ 2 ] = oldCache[ 2 ]);+ return ( newCache[ 2 ] = oldCache[ 2 ] );} else {+// Reuse newcache so results back-propagate to previous elementsuniqueCache[ key ] = newCache;// A match means we're done; a fail means we have to keep checking- if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {+ if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) {return true;}}@@ -2274,20 +2462,20 @@ function elementMatcher( matchers ) {function( elem, context, xml ) {var i = matchers.length;while ( i-- ) {- if ( !matchers[i]( elem, context, xml ) ) {+ if ( !matchers[ i ]( elem, context, xml ) ) {return false;}}return true;} :- matchers[0];+ matchers[ 0 ];}function multipleContexts( selector, contexts, results ) {var i = 0,len = contexts.length;for ( ; i < len; i++ ) {- Sizzle( selector, contexts[i], results );+ Sizzle( selector, contexts[ i ], results );}return results;}@@ -2300,7 +2488,7 @@ function condense( unmatched, map, filter, context, xml ) {mapped = map != null;for ( ; i < len; i++ ) {- if ( (elem = unmatched[i]) ) {+ if ( ( elem = unmatched[ i ] ) ) {if ( !filter || filter( elem, context, xml ) ) {newUnmatched.push( elem );if ( mapped ) {@@ -2320,14 +2508,18 @@ function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSif ( postFinder && !postFinder[ expando ] ) {postFinder = setMatcher( postFinder, postSelector );}- return markFunction(function( seed, results, context, xml ) {+ return markFunction( function( seed, results, context, xml ) {var temp, i, elem,preMap = [],postMap = [],preexisting = results.length,// Get initial elements from seed or context- elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),+ elems = seed || multipleContexts(+ selector || "*",+ context.nodeType ? [ context ] : context,+ []+ ),// Prefilter to get matcher input, preserving a map for seed-results synchronizationmatcherIn = preFilter && ( seed || !selector ) ?@@ -2335,6 +2527,7 @@ function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelems,matcherOut = matcher ?+// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,postFinder || ( seed ? preFilter : preexisting || postFilter ) ?@@ -2358,8 +2551,8 @@ function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postS// Un-match failing elements by moving them back to matcherIni = temp.length;while ( i-- ) {- if ( (elem = temp[i]) ) {- matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);+ if ( ( elem = temp[ i ] ) ) {+ matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem );}}}@@ -2367,25 +2560,27 @@ function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSif ( seed ) {if ( postFinder || preFilter ) {if ( postFinder ) {+// Get the final matcherOut by condensing this intermediate into postFinder contextstemp = [];i = matcherOut.length;while ( i-- ) {- if ( (elem = matcherOut[i]) ) {+ if ( ( elem = matcherOut[ i ] ) ) {+// Restore matcherIn since elem is not yet a final match- temp.push( (matcherIn[i] = elem) );+ temp.push( ( matcherIn[ i ] = elem ) );}}- postFinder( null, (matcherOut = []), temp, xml );+ postFinder( null, ( matcherOut = [] ), temp, xml );}// Move matched elements from seed to results to keep them synchronizedi = matcherOut.length;while ( i-- ) {- if ( (elem = matcherOut[i]) &&- (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {+ if ( ( elem = matcherOut[ i ] ) &&+ ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) {- seed[temp] = !(results[temp] = elem);+ seed[ temp ] = !( results[ temp ] = elem );}}}@@ -2403,14 +2598,14 @@ function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSpush.apply( results, matcherOut );}}- });+ } );}function matcherFromTokens( tokens ) {var checkContext, matcher, j,len = tokens.length,- leadingRelative = Expr.relative[ tokens[0].type ],- implicitRelative = leadingRelative || Expr.relative[" "],+ leadingRelative = Expr.relative[ tokens[ 0 ].type ],+ implicitRelative = leadingRelative || Expr.relative[ " " ],i = leadingRelative ? 1 : 0,// The foundational matcher ensures that elements are reachable from top-level context(s)@@ -2422,38 +2617,43 @@ function matcherFromTokens( tokens ) {}, implicitRelative, true ),matchers = [ function( elem, context, xml ) {var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (- (checkContext = context).nodeType ?+ ( checkContext = context ).nodeType ?matchContext( elem, context, xml ) :matchAnyContext( elem, context, xml ) );+// Avoid hanging onto element (issue #299)checkContext = null;return ret;} ];for ( ; i < len; i++ ) {- if ( (matcher = Expr.relative[ tokens[i].type ]) ) {- matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];+ if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) {+ matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];} else {- matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );+ matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches );// Return special upon seeing a positional matcherif ( matcher[ expando ] ) {+// Find the next relative operator (if any) for proper handlingj = ++i;for ( ; j < len; j++ ) {- if ( Expr.relative[ tokens[j].type ] ) {+ if ( Expr.relative[ tokens[ j ].type ] ) {break;}}return setMatcher(i > 1 && elementMatcher( matchers ),i > 1 && toSelector(- // If the preceding token was a descendant combinator, insert an implicit any-element `*`- tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })++ // If the preceding token was a descendant combinator, insert an implicit any-element `*`+ tokens+ .slice( 0, i - 1 )+ .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } )).replace( rtrim, "$1" ),matcher,i < j && matcherFromTokens( tokens.slice( i, j ) ),- j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),+ j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ),j < len && toSelector( tokens ));}@@ -2474,28 +2674,40 @@ function matcherFromGroupMatchers( elementMatchers, setMatchers ) {unmatched = seed && [],setMatched = [],contextBackup = outermostContext,+// We must always have either seed elements or outermost context- elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),+ elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ),+// Use integer dirruns iff this is the outermost matcher- dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),+ dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ),len = elems.length;if ( outermost ) {- outermostContext = context === document || context || outermost;++ // Support: IE 11+, Edge 17 - 18++ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing+ // two documents; shallow comparisons work.+ // eslint-disable-next-line eqeqeq+ outermostContext = context == document || context || outermost;}// Add elements passing elementMatchers directly to results// Support: IE<9, Safari// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id- for ( ; i !== len && (elem = elems[i]) != null; i++ ) {+ for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) {if ( byElement && elem ) {j = 0;- if ( !context && elem.ownerDocument !== document ) {++ // Support: IE 11+, Edge 17 - 18++ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing+ // two documents; shallow comparisons work.+ // eslint-disable-next-line eqeqeq+ if ( !context && elem.ownerDocument != document ) {setDocument( elem );xml = !documentIsHTML;}- while ( (matcher = elementMatchers[j++]) ) {- if ( matcher( elem, context || document, xml) ) {+ while ( ( matcher = elementMatchers[ j++ ] ) ) {+ if ( matcher( elem, context || document, xml ) ) {results.push( elem );break;}@@ -2507,8 +2719,9 @@ function matcherFromGroupMatchers( elementMatchers, setMatchers ) {// Track unmatched elements for set filtersif ( bySet ) {+// They will have gone through all possible matchers- if ( (elem = !matcher && elem) ) {+ if ( ( elem = !matcher && elem ) ) {matchedCount--;}@@ -2532,16 +2745,17 @@ function matcherFromGroupMatchers( elementMatchers, setMatchers ) {// numerically zero.if ( bySet && i !== matchedCount ) {j = 0;- while ( (matcher = setMatchers[j++]) ) {+ while ( ( matcher = setMatchers[ j++ ] ) ) {matcher( unmatched, setMatched, context, xml );}if ( seed ) {+// Reintegrate element matches to eliminate the need for sortingif ( matchedCount > 0 ) {while ( i-- ) {- if ( !(unmatched[i] || setMatched[i]) ) {- setMatched[i] = pop.call( results );+ if ( !( unmatched[ i ] || setMatched[ i ] ) ) {+ setMatched[ i ] = pop.call( results );}}}@@ -2582,13 +2796,14 @@ compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {cached = compilerCache[ selector + " " ];if ( !cached ) {+// Generate a function of recursive functions that can be used to check each elementif ( !match ) {match = tokenize( selector );}i = match.length;while ( i-- ) {- cached = matcherFromTokens( match[i] );+ cached = matcherFromTokens( match[ i ] );if ( cached[ expando ] ) {setMatchers.push( cached );} else {@@ -2597,7 +2812,10 @@ compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {}// Cache the compiled function- cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );+ cached = compilerCache(+ selector,+ matcherFromGroupMatchers( elementMatchers, setMatchers )+ );// Save selector and tokenizationcached.selector = selector;@@ -2617,7 +2835,7 @@ compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {select = Sizzle.select = function( selector, context, results, seed ) {var i, tokens, token, type, find,compiled = typeof selector === "function" && selector,- match = !seed && tokenize( (selector = compiled.selector || selector) );+ match = !seed && tokenize( ( selector = compiled.selector || selector ) );results = results || [];@@ -2626,11 +2844,12 @@ select = Sizzle.select = function( selector, context, results, seed ) {if ( match.length === 1 ) {// Reduce context if the leading compound selector is an ID- tokens = match[0] = match[0].slice( 0 );- if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&- context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) {+ tokens = match[ 0 ] = match[ 0 ].slice( 0 );+ if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" &&+ context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) {- context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];+ context = ( Expr.find[ "ID" ]( token.matches[ 0 ]+ .replace( runescape, funescape ), context ) || [] )[ 0 ];if ( !context ) {return results;@@ -2643,20 +2862,22 @@ select = Sizzle.select = function( selector, context, results, seed ) {}// Fetch a seed set for right-to-left matching- i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;+ i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length;while ( i-- ) {- token = tokens[i];+ token = tokens[ i ];// Abort if we hit a combinator- if ( Expr.relative[ (type = token.type) ] ) {+ if ( Expr.relative[ ( type = token.type ) ] ) {break;}- if ( (find = Expr.find[ type ]) ) {+ if ( ( find = Expr.find[ type ] ) ) {+// Search, expanding context for leading sibling combinators- if ( (seed = find(- token.matches[0].replace( runescape, funescape ),- rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context- )) ) {+ if ( ( seed = find(+ token.matches[ 0 ].replace( runescape, funescape ),+ rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) ||+ context+ ) ) ) {// If seed is empty or no tokens remain, we can return earlytokens.splice( i, 1 );@@ -2687,7 +2908,7 @@ select = Sizzle.select = function( selector, context, results, seed ) {// One-time assignments// Sort stability-support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;+support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando;// Support: Chrome 14-35+// Always assume duplicates if they aren't passed to the comparison function@@ -2698,58 +2919,59 @@ setDocument();// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)// Detached nodes confoundingly follow *each other*-support.sortDetached = assert(function( el ) {+support.sortDetached = assert( function( el ) {+// Should return 1, but returns 4 (following)- return el.compareDocumentPosition( document.createElement("fieldset") ) & 1;-});+ return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1;+} );// Support: IE<8// Prevent attribute/property "interpolation"// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx-if ( !assert(function( el ) {+if ( !assert( function( el ) {el.innerHTML = "<a href='#'></a>";- return el.firstChild.getAttribute("href") === "#" ;-}) ) {+ return el.firstChild.getAttribute( "href" ) === "#";+} ) ) {addHandle( "type|href|height|width", function( elem, name, isXML ) {if ( !isXML ) {return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );}- });+ } );}// Support: IE<9// Use defaultValue in place of getAttribute("value")-if ( !support.attributes || !assert(function( el ) {+if ( !support.attributes || !assert( function( el ) {el.innerHTML = "<input/>";el.firstChild.setAttribute( "value", "" );return el.firstChild.getAttribute( "value" ) === "";-}) ) {- addHandle( "value", function( elem, name, isXML ) {+} ) ) {+ addHandle( "value", function( elem, _name, isXML ) {if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {return elem.defaultValue;}- });+ } );}// Support: IE<9// Use getAttributeNode to fetch booleans when getAttribute lies-if ( !assert(function( el ) {- return el.getAttribute("disabled") == null;-}) ) {+if ( !assert( function( el ) {+ return el.getAttribute( "disabled" ) == null;+} ) ) {addHandle( booleans, function( elem, name, isXML ) {var val;if ( !isXML ) {return elem[ name ] === true ? name.toLowerCase() :- (val = elem.getAttributeNode( name )) && val.specified ?+ ( val = elem.getAttributeNode( name ) ) && val.specified ?val.value :- null;+ null;}- });+ } );}return Sizzle;-})( window );+} )( window );@@ -3118,7 +3340,7 @@ jQuery.each( {parents: function( elem ) {return dir( elem, "parentNode" );},- parentsUntil: function( elem, i, until ) {+ parentsUntil: function( elem, _i, until ) {return dir( elem, "parentNode", until );},next: function( elem ) {@@ -3133,10 +3355,10 @@ jQuery.each( {prevAll: function( elem ) {return dir( elem, "previousSibling" );},- nextUntil: function( elem, i, until ) {+ nextUntil: function( elem, _i, until ) {return dir( elem, "nextSibling", until );},- prevUntil: function( elem, i, until ) {+ prevUntil: function( elem, _i, until ) {return dir( elem, "previousSibling", until );},siblings: function( elem ) {@@ -3146,18 +3368,24 @@ jQuery.each( {return siblings( elem.firstChild );},contents: function( elem ) {- if ( nodeName( elem, "iframe" ) ) {- return elem.contentDocument;- }+ if ( elem.contentDocument != null &&++ // Support: IE 11++ // <object> elements with no `data` attribute has an object+ // `contentDocument` with a `null` prototype.+ getProto( elem.contentDocument ) ) {- // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only- // Treat the template element as a regular one in browsers that- // don't support it.- if ( nodeName( elem, "template" ) ) {- elem = elem.content || elem;- }+ return elem.contentDocument;+ }- return jQuery.merge( [], elem.childNodes );+ // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only+ // Treat the template element as a regular one in browsers that+ // don't support it.+ if ( nodeName( elem, "template" ) ) {+ elem = elem.content || elem;+ }++ return jQuery.merge( [], elem.childNodes );}}, function( name, fn ) {jQuery.fn[ name ] = function( until, selector ) {@@ -3489,7 +3717,7 @@ jQuery.extend( {var fns = arguments;return jQuery.Deferred( function( newDefer ) {- jQuery.each( tuples, function( i, tuple ) {+ jQuery.each( tuples, function( _i, tuple ) {// Map tuples (progress, done, fail) to arguments (done, fail, progress)var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];@@ -3942,7 +4170,7 @@ var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {// ...except when executing function values} else {bulk = fn;- fn = function( elem, key, value ) {+ fn = function( elem, _key, value ) {return bulk.call( jQuery( elem ), value );};}@@ -3977,7 +4205,7 @@ var rmsPrefix = /^-ms-/,rdashAlpha = /-([a-z])/g;// Used by camelCase as callback to replace()-function fcamelCase( all, letter ) {+function fcamelCase( _all, letter ) {return letter.toUpperCase();}@@ -4466,6 +4694,26 @@ var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );var cssExpand = [ "Top", "Right", "Bottom", "Left" ];+var documentElement = document.documentElement;++++ var isAttached = function( elem ) {+ return jQuery.contains( elem.ownerDocument, elem );+ },+ composed = { composed: true };++ // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only+ // Check attachment across shadow DOM boundaries when possible (gh-3504)+ // Support: iOS 10.0-10.2 only+ // Early iOS 10 versions support `attachShadow` but not `getRootNode`,+ // leading to errors. We need to check for `getRootNode`.+ if ( documentElement.getRootNode ) {+ isAttached = function( elem ) {+ return jQuery.contains( elem.ownerDocument, elem ) ||+ elem.getRootNode( composed ) === elem.ownerDocument;+ };+ }var isHiddenWithinTree = function( elem, el ) {// isHiddenWithinTree might be called from jQuery#filter function;@@ -4480,32 +4728,11 @@ var isHiddenWithinTree = function( elem, el ) {// Support: Firefox <=43 - 45// Disconnected elements can have computed display: none, so first confirm that elem is// in the document.- jQuery.contains( elem.ownerDocument, elem ) &&+ isAttached( elem ) &&jQuery.css( elem, "display" ) === "none";};-var swap = function( elem, options, callback, args ) {- var ret, name,- old = {};-- // Remember the old values, and insert the new ones- for ( name in options ) {- old[ name ] = elem.style[ name ];- elem.style[ name ] = options[ name ];- }-- ret = callback.apply( elem, args || [] );-- // Revert the old values- for ( name in options ) {- elem.style[ name ] = old[ name ];- }-- return ret;-};--function adjustCSS( elem, prop, valueParts, tween ) {@@ -4522,7 +4749,8 @@ function adjustCSS( elem, prop, valueParts, tween ) {unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),// Starting value computation is required for potential unit mismatches- initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&+ initialInUnit = elem.nodeType &&+ ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&rcssNum.exec( jQuery.css( elem, prop ) );if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {@@ -4669,17 +4897,46 @@ jQuery.fn.extend( {} );var rcheckableType = ( /^(?:checkbox|radio)$/i );-var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i );+var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i );var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i );-// We have to close these tags to support XHTML (#13200)-var wrapMap = {+( function() {+ var fragment = document.createDocumentFragment(),+ div = fragment.appendChild( document.createElement( "div" ) ),+ input = document.createElement( "input" );++ // Support: Android 4.0 - 4.3 only+ // Check state lost if the name is set (#11217)+ // Support: Windows Web Apps (WWA)+ // `name` and `type` must use .setAttribute for WWA (#14901)+ input.setAttribute( "type", "radio" );+ input.setAttribute( "checked", "checked" );+ input.setAttribute( "name", "t" );++ div.appendChild( input );++ // Support: Android <=4.1 only+ // Older WebKit doesn't clone checked state correctly in fragments+ support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;++ // Support: IE <=11 only+ // Make sure textarea (and checkbox) defaultValue is properly cloned+ div.innerHTML = "<textarea>x</textarea>";+ support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;// Support: IE <=9 only- option: [ 1, "<select multiple='multiple'>", "</select>" ],+ // IE <=9 replaces <option> tags with their contents when inserted outside of+ // the select element.+ div.innerHTML = "<option></option>";+ support.option = !!div.lastChild;+} )();+++// We have to close these tags to support XHTML (#13200)+var wrapMap = {// XHTML parsers do not magically insert elements in the// same way that tag soup parsers do. So we cannot shorten@@ -4692,12 +4949,14 @@ var wrapMap = {_default: [ 0, "", "" ]};-// Support: IE <=9 only-wrapMap.optgroup = wrapMap.option;-wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;wrapMap.th = wrapMap.td;+// Support: IE <=9 only+if ( !support.option ) {+ wrapMap.optgroup = wrapMap.option = [ 1, "<select multiple='multiple'>", "</select>" ];+}+function getAll( context, tag ) {@@ -4741,7 +5000,7 @@ function setGlobalEval( elems, refElements ) {var rhtml = /<|&#?\w+;/;function buildFragment( elems, context, scripts, selection, ignored ) {- var elem, tmp, tag, wrap, contains, j,+ var elem, tmp, tag, wrap, attached, j,fragment = context.createDocumentFragment(),nodes = [],i = 0,@@ -4805,13 +5064,13 @@ function buildFragment( elems, context, scripts, selection, ignored ) {continue;}- contains = jQuery.contains( elem.ownerDocument, elem );+ attached = isAttached( elem );// Append to fragmenttmp = getAll( fragment.appendChild( elem ), "script" );// Preserve script evaluation history- if ( contains ) {+ if ( attached ) {setGlobalEval( tmp );}@@ -4830,34 +5089,6 @@ function buildFragment( elems, context, scripts, selection, ignored ) {}-( function() {- var fragment = document.createDocumentFragment(),- div = fragment.appendChild( document.createElement( "div" ) ),- input = document.createElement( "input" );-- // Support: Android 4.0 - 4.3 only- // Check state lost if the name is set (#11217)- // Support: Windows Web Apps (WWA)- // `name` and `type` must use .setAttribute for WWA (#14901)- input.setAttribute( "type", "radio" );- input.setAttribute( "checked", "checked" );- input.setAttribute( "name", "t" );-- div.appendChild( input );-- // Support: Android <=4.1 only- // Older WebKit doesn't clone checked state correctly in fragments- support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;-- // Support: IE <=11 only- // Make sure textarea (and checkbox) defaultValue is properly cloned- div.innerHTML = "<textarea>x</textarea>";- support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;-} )();-var documentElement = document.documentElement;---varrkeyEvent = /^key/,rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,@@ -4871,8 +5102,19 @@ function returnFalse() {return false;}+// Support: IE <=9 - 11++// focus() and blur() are asynchronous, except when they are no-op.+// So expect focus to be synchronous when the element is already active,+// and blur to be synchronous when the element is not already active.+// (focus and blur are always synchronous in other supported browsers,+// this just defines when we can count on it).+function expectSync( elem, type ) {+ return ( elem === safeActiveElement() ) === ( type === "focus" );+}+// Support: IE <=9 only-// See #13393 for more info+// Accessing document.activeElement can throw unexpectedly+// https://bugs.jquery.com/ticket/13393function safeActiveElement() {try {return document.activeElement;@@ -4955,8 +5197,8 @@ jQuery.event = {special, handlers, type, namespaces, origType,elemData = dataPriv.get( elem );- // Don't attach events to noData or text/comment nodes (but allow plain objects)- if ( !elemData ) {+ // Only attach events to objects that accept data+ if ( !acceptData( elem ) ) {return;}@@ -4980,7 +5222,7 @@ jQuery.event = {// Init the element's event structure and main handler, if this is the firstif ( !( events = elemData.events ) ) {- events = elemData.events = {};+ events = elemData.events = Object.create( null );}if ( !( eventHandle = elemData.handle ) ) {eventHandle = elemData.handle = function( e ) {@@ -5138,12 +5380,15 @@ jQuery.event = {dispatch: function( nativeEvent ) {- // Make a writable jQuery.Event from the native event object- var event = jQuery.event.fix( nativeEvent );-var i, j, ret, matched, handleObj, handlerQueue,args = new Array( arguments.length ),- handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [],++ // Make a writable jQuery.Event from the native event object+ event = jQuery.event.fix( nativeEvent ),++ handlers = (+ dataPriv.get( this, "events" ) || Object.create( null )+ )[ event.type ] || [],special = jQuery.event.special[ event.type ] || {};// Use the fix-ed jQuery.Event rather than the (read-only) native event@@ -5172,9 +5417,10 @@ jQuery.event = {while ( ( handleObj = matched.handlers[ j++ ] ) &&!event.isImmediatePropagationStopped() ) {- // Triggered event must either 1) have no namespace, or 2) have namespace(s)- // a subset or equal to those in the bound event (both can have no namespace).- if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) {+ // If the event is namespaced, then each handler is only invoked if it is+ // specially universal or its namespaces are a superset of the event's.+ if ( !event.rnamespace || handleObj.namespace === false ||+ event.rnamespace.test( handleObj.namespace ) ) {event.handleObj = handleObj;event.data = handleObj.data;@@ -5298,39 +5544,51 @@ jQuery.event = {// Prevent triggered image.load events from bubbling to window.loadnoBubble: true},- focus: {+ click: {- // Fire native event if possible so blur/focus sequence is correct- trigger: function() {- if ( this !== safeActiveElement() && this.focus ) {- this.focus();- return false;- }- },- delegateType: "focusin"- },- blur: {- trigger: function() {- if ( this === safeActiveElement() && this.blur ) {- this.blur();- return false;+ // Utilize native event to ensure correct state for checkable inputs+ setup: function( data ) {++ // For mutual compressibility with _default, replace `this` access with a local var.+ // `|| data` is dead code meant only to preserve the variable through minification.+ var el = this || data;++ // Claim the first handler+ if ( rcheckableType.test( el.type ) &&+ el.click && nodeName( el, "input" ) ) {++ // dataPriv.set( el, "click", ... )+ leverageNative( el, "click", returnTrue );}++ // Return false to allow normal processing in the caller+ return false;},- delegateType: "focusout"- },- click: {+ trigger: function( data ) {- // For checkbox, fire native event so checked state will be right- trigger: function() {- if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) {- this.click();- return false;+ // For mutual compressibility with _default, replace `this` access with a local var.+ // `|| data` is dead code meant only to preserve the variable through minification.+ var el = this || data;++ // Force setup before triggering a click+ if ( rcheckableType.test( el.type ) &&+ el.click && nodeName( el, "input" ) ) {++ leverageNative( el, "click" );}++ // Return non-false to allow normal event-path propagation+ return true;},- // For cross-browser consistency, don't fire native .click() on links+ // For cross-browser consistency, suppress native .click() on links+ // Also prevent it if we're currently inside a leveraged native-event stack_default: function( event ) {- return nodeName( event.target, "a" );+ var target = event.target;+ return rcheckableType.test( target.type ) &&+ target.click && nodeName( target, "input" ) &&+ dataPriv.get( target, "click" ) ||+ nodeName( target, "a" );}},@@ -5347,6 +5605,93 @@ jQuery.event = {}};+// Ensure the presence of an event listener that handles manually-triggered+// synthetic events by interrupting progress until reinvoked in response to+// *native* events that it fires directly, ensuring that state changes have+// already occurred before other listeners are invoked.+function leverageNative( el, type, expectSync ) {++ // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add+ if ( !expectSync ) {+ if ( dataPriv.get( el, type ) === undefined ) {+ jQuery.event.add( el, type, returnTrue );+ }+ return;+ }++ // Register the controller as a special universal handler for all event namespaces+ dataPriv.set( el, type, false );+ jQuery.event.add( el, type, {+ namespace: false,+ handler: function( event ) {+ var notAsync, result,+ saved = dataPriv.get( this, type );++ if ( ( event.isTrigger & 1 ) && this[ type ] ) {++ // Interrupt processing of the outer synthetic .trigger()ed event+ // Saved data should be false in such cases, but might be a leftover capture object+ // from an async native handler (gh-4350)+ if ( !saved.length ) {++ // Store arguments for use when handling the inner native event+ // There will always be at least one argument (an event object), so this array+ // will not be confused with a leftover capture object.+ saved = slice.call( arguments );+ dataPriv.set( this, type, saved );++ // Trigger the native event and capture its result+ // Support: IE <=9 - 11++ // focus() and blur() are asynchronous+ notAsync = expectSync( this, type );+ this[ type ]();+ result = dataPriv.get( this, type );+ if ( saved !== result || notAsync ) {+ dataPriv.set( this, type, false );+ } else {+ result = {};+ }+ if ( saved !== result ) {++ // Cancel the outer synthetic event+ event.stopImmediatePropagation();+ event.preventDefault();+ return result.value;+ }++ // If this is an inner synthetic event for an event with a bubbling surrogate+ // (focus or blur), assume that the surrogate already propagated from triggering the+ // native event and prevent that from happening again here.+ // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the+ // bubbling surrogate propagates *after* the non-bubbling base), but that seems+ // less bad than duplication.+ } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) {+ event.stopPropagation();+ }++ // If this is a native event triggered above, everything is now in order+ // Fire an inner synthetic event with the original arguments+ } else if ( saved.length ) {++ // ...and capture the result+ dataPriv.set( this, type, {+ value: jQuery.event.trigger(++ // Support: IE <=9 - 11++ // Extend with the prototype to reset the above stopImmediatePropagation()+ jQuery.extend( saved[ 0 ], jQuery.Event.prototype ),+ saved.slice( 1 ),+ this+ )+ } );++ // Abort handling of the native event+ event.stopImmediatePropagation();+ }+ }+ } );+}+jQuery.removeEvent = function( elem, type, handle ) {// This "if" is needed for plain objects@@ -5459,6 +5804,7 @@ jQuery.each( {shiftKey: true,view: true,"char": true,+ code: true,charCode: true,key: true,keyCode: true,@@ -5505,6 +5851,33 @@ jQuery.each( {}}, jQuery.event.addProp );+jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) {+ jQuery.event.special[ type ] = {++ // Utilize native event if possible so blur/focus sequence is correct+ setup: function() {++ // Claim the first handler+ // dataPriv.set( this, "focus", ... )+ // dataPriv.set( this, "blur", ... )+ leverageNative( this, type, expectSync );++ // Return false to allow normal processing in the caller+ return false;+ },+ trigger: function() {++ // Force setup before trigger+ leverageNative( this, type );++ // Return non-false to allow normal event-path propagation+ return true;+ },++ delegateType: delegateType+ };+} );+// Create mouseenter/leave events using mouseover/out and event-time checks// so that event delegation works in jQuery.// Do the same for pointerenter/pointerleave and pointerover/pointerout@@ -5590,13 +5963,6 @@ jQuery.fn.extend( {var- /* eslint-disable max-len */-- // See https://github.com/eslint/eslint/issues/3229- rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,-- /* eslint-enable */-// Support: IE <=10 - 11, Edge 12 - 13 only// In IE/Edge using regex groups here causes severe slowdowns.// See https://connect.microsoft.com/IE/feedback/details/1736512/@@ -5633,7 +5999,7 @@ function restoreScript( elem ) {}function cloneCopyEvent( src, dest ) {- var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;+ var i, l, type, pdataOld, udataOld, udataCur, events;if ( dest.nodeType !== 1 ) {return;@@ -5641,13 +6007,11 @@ function cloneCopyEvent( src, dest ) {// 1. Copy private data: events, handlers, etc.if ( dataPriv.hasData( src ) ) {- pdataOld = dataPriv.access( src );- pdataCur = dataPriv.set( dest, pdataOld );+ pdataOld = dataPriv.get( src );events = pdataOld.events;if ( events ) {- delete pdataCur.handle;- pdataCur.events = {};+ dataPriv.remove( dest, "handle events" );for ( type in events ) {for ( i = 0, l = events[ type ].length; i < l; i++ ) {@@ -5683,7 +6047,7 @@ function fixInput( src, dest ) {function domManip( collection, args, callback, ignored ) {// Flatten any nested arrays- args = concat.apply( [], args );+ args = flat( args );var fragment, first, scripts, hasScripts, node, doc,i = 0,@@ -5755,11 +6119,13 @@ function domManip( collection, args, callback, ignored ) {if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) {// Optional AJAX dependency, but won't run scripts if not present- if ( jQuery._evalUrl ) {- jQuery._evalUrl( node.src );+ if ( jQuery._evalUrl && !node.noModule ) {+ jQuery._evalUrl( node.src, {+ nonce: node.nonce || node.getAttribute( "nonce" )+ }, doc );}} else {- DOMEval( node.textContent.replace( rcleanScript, "" ), doc, node );+ DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc );}}}@@ -5781,7 +6147,7 @@ function remove( elem, selector, keepData ) {}if ( node.parentNode ) {- if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {+ if ( keepData && isAttached( node ) ) {setGlobalEval( getAll( node, "script" ) );}node.parentNode.removeChild( node );@@ -5793,13 +6159,13 @@ function remove( elem, selector, keepData ) {jQuery.extend( {htmlPrefilter: function( html ) {- return html.replace( rxhtmlTag, "<$1></$2>" );+ return html;},clone: function( elem, dataAndEvents, deepDataAndEvents ) {var i, l, srcElements, destElements,clone = elem.cloneNode( true ),- inPage = jQuery.contains( elem.ownerDocument, elem );+ inPage = isAttached( elem );// Fix IE cloning issuesif ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&@@ -6055,6 +6421,27 @@ var getStyles = function( elem ) {return view.getComputedStyle( elem );};+var swap = function( elem, options, callback ) {+ var ret, name,+ old = {};++ // Remember the old values, and insert the new ones+ for ( name in options ) {+ old[ name ] = elem.style[ name ];+ elem.style[ name ] = options[ name ];+ }++ ret = callback.call( elem );++ // Revert the old values+ for ( name in options ) {+ elem.style[ name ] = old[ name ];+ }++ return ret;+};++var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" );@@ -6095,8 +6482,10 @@ var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" );// Support: IE 9 only// Detect overflow:scroll screwiness (gh-3699)+ // Support: Chrome <=64+ // Don't get tricked when zoom affects offsetWidth (gh-4029)div.style.position = "absolute";- scrollboxSizeVal = div.offsetWidth === 36 || "absolute";+ scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12;documentElement.removeChild( container );@@ -6110,7 +6499,7 @@ var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" );}var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal,- reliableMarginLeftVal,+ reliableTrDimensionsVal, reliableMarginLeftVal,container = document.createElement( "div" ),div = document.createElement( "div" );@@ -6145,6 +6534,35 @@ var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" );scrollboxSize: function() {computeStyleTests();return scrollboxSizeVal;+ },++ // Support: IE 9 - 11+, Edge 15 - 18++ // IE/Edge misreport `getComputedStyle` of table rows with width/height+ // set in CSS while `offset*` properties report correct values.+ // Behavior in IE 9 is more subtle than in newer versions & it passes+ // some versions of this test; make sure not to make it pass there!+ reliableTrDimensions: function() {+ var table, tr, trChild, trStyle;+ if ( reliableTrDimensionsVal == null ) {+ table = document.createElement( "table" );+ tr = document.createElement( "tr" );+ trChild = document.createElement( "div" );++ table.style.cssText = "position:absolute;left:-11111px";+ tr.style.height = "1px";+ trChild.style.height = "9px";++ documentElement+ .appendChild( table )+ .appendChild( tr )+ .appendChild( trChild );++ trStyle = window.getComputedStyle( tr );+ reliableTrDimensionsVal = parseInt( trStyle.height ) > 3;++ documentElement.removeChild( table );+ }+ return reliableTrDimensionsVal;}} );} )();@@ -6167,7 +6585,7 @@ function curCSS( elem, name, computed ) {if ( computed ) {ret = computed.getPropertyValue( name ) || computed[ name ];- if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {+ if ( ret === "" && !isAttached( elem ) ) {ret = jQuery.style( elem, name );}@@ -6223,30 +6641,13 @@ function addGetHookIf( conditionFn, hookFn ) {}-var-- // Swappable if display is none or starts with table- // except "table", "table-cell", or "table-caption"- // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display- rdisplayswap = /^(none|table(?!-c[ea]).+)/,- rcustomProp = /^--/,- cssShow = { position: "absolute", visibility: "hidden", display: "block" },- cssNormalTransform = {- letterSpacing: "0",- fontWeight: "400"- },-- cssPrefixes = [ "Webkit", "Moz", "ms" ],- emptyStyle = document.createElement( "div" ).style;+var cssPrefixes = [ "Webkit", "Moz", "ms" ],+ emptyStyle = document.createElement( "div" ).style,+ vendorProps = {};-// Return a css property mapped to a potentially vendor prefixed property+// Return a vendor-prefixed property or undefinedfunction vendorPropName( name ) {- // Shortcut for names that are not vendor prefixed- if ( name in emptyStyle ) {- return name;- }-// Check for vendor prefixed namesvar capName = name[ 0 ].toUpperCase() + name.slice( 1 ),i = cssPrefixes.length;@@ -6259,17 +6660,34 @@ function vendorPropName( name ) {}}-// Return a property mapped along what jQuery.cssProps suggests or to-// a vendor prefixed property.+// Return a potentially-mapped jQuery.cssProps or vendor prefixed propertyfunction finalPropName( name ) {- var ret = jQuery.cssProps[ name ];- if ( !ret ) {- ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name;+ var final = jQuery.cssProps[ name ] || vendorProps[ name ];++ if ( final ) {+ return final;}- return ret;+ if ( name in emptyStyle ) {+ return name;+ }+ return vendorProps[ name ] = vendorPropName( name ) || name;}-function setPositiveNumber( elem, value, subtract ) {++var++ // Swappable if display is none or starts with table+ // except "table", "table-cell", or "table-caption"+ // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display+ rdisplayswap = /^(none|table(?!-c[ea]).+)/,+ rcustomProp = /^--/,+ cssShow = { position: "absolute", visibility: "hidden", display: "block" },+ cssNormalTransform = {+ letterSpacing: "0",+ fontWeight: "400"+ };++function setPositiveNumber( _elem, value, subtract ) {// Any relative (+/-) values have already been// normalized at this point@@ -6340,7 +6758,10 @@ function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computeddelta -extra -0.5- ) );++ // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter+ // Use an explicit zero to avoid NaN (gh-3964)+ ) ) || 0;}return delta;@@ -6350,9 +6771,16 @@ function getWidthOrHeight( elem, dimension, extra ) {// Start with computed stylevar styles = getStyles( elem ),++ // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322).+ // Fake content-box until we know it's needed to know the true value.+ boxSizingNeeded = !support.boxSizingReliable() || extra,+ isBorderBox = boxSizingNeeded &&+ jQuery.css( elem, "boxSizing", false, styles ) === "border-box",+ valueIsBorderBox = isBorderBox,+val = curCSS( elem, dimension, styles ),- isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box",- valueIsBorderBox = isBorderBox;+ offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 );// Support: Firefox <=54// Return a confounding non-pixel value or feign ignorance, as appropriate.@@ -6363,22 +6791,38 @@ function getWidthOrHeight( elem, dimension, extra ) {val = "auto";}- // Check for style in case a browser which returns unreliable values- // for getComputedStyle silently falls back to the reliable elem.style- valueIsBorderBox = valueIsBorderBox &&- ( support.boxSizingReliable() || val === elem.style[ dimension ] );- // Fall back to offsetWidth/offsetHeight when value is "auto"- // This happens for inline elements with no explicit setting (gh-3571)- // Support: Android <=4.1 - 4.3 only- // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602)- if ( val === "auto" ||- !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) {+ // Support: IE 9 - 11 only+ // Use offsetWidth/offsetHeight for when box sizing is unreliable.+ // In those cases, the computed value can be trusted to be border-box.+ if ( ( !support.boxSizingReliable() && isBorderBox ||++ // Support: IE 10 - 11+, Edge 15 - 18++ // IE/Edge misreport `getComputedStyle` of table rows with width/height+ // set in CSS while `offset*` properties report correct values.+ // Interestingly, in some cases IE 9 doesn't suffer from this issue.+ !support.reliableTrDimensions() && nodeName( elem, "tr" ) ||++ // Fall back to offsetWidth/offsetHeight when value is "auto"+ // This happens for inline elements with no explicit setting (gh-3571)+ val === "auto" ||++ // Support: Android <=4.1 - 4.3 only+ // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602)+ !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) &&- val = elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ];+ // Make sure the element is visible & connected+ elem.getClientRects().length ) {- // offsetWidth/offsetHeight provide border-box values- valueIsBorderBox = true;+ isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";++ // Where available, offsetWidth/offsetHeight approximate border box dimensions.+ // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the+ // retrieved value as a content box dimension.+ valueIsBorderBox = offsetProp in elem;+ if ( valueIsBorderBox ) {+ val = elem[ offsetProp ];+ }}// Normalize "" and auto@@ -6424,6 +6868,13 @@ jQuery.extend( {"flexGrow": true,"flexShrink": true,"fontWeight": true,+ "gridArea": true,+ "gridColumn": true,+ "gridColumnEnd": true,+ "gridColumnStart": true,+ "gridRow": true,+ "gridRowEnd": true,+ "gridRowStart": true,"lineHeight": true,"opacity": true,"order": true,@@ -6479,7 +6930,9 @@ jQuery.extend( {}// If a number was passed in, add the unit (except for certain CSS properties)- if ( type === "number" ) {+ // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append+ // "px" to a few hardcoded values.+ if ( type === "number" && !isCustomProp ) {value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );}@@ -6553,7 +7006,7 @@ jQuery.extend( {}} );-jQuery.each( [ "height", "width" ], function( i, dimension ) {+jQuery.each( [ "height", "width" ], function( _i, dimension ) {jQuery.cssHooks[ dimension ] = {get: function( elem, computed, extra ) {if ( computed ) {@@ -6579,18 +7032,29 @@ jQuery.each( [ "height", "width" ], function( i, dimension ) {set: function( elem, value, extra ) {var matches,styles = getStyles( elem ),- isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box",- subtract = extra && boxModelAdjustment(- elem,- dimension,- extra,- isBorderBox,- styles- );++ // Only read styles.position if the test has a chance to fail+ // to avoid forcing a reflow.+ scrollboxSizeBuggy = !support.scrollboxSize() &&+ styles.position === "absolute",++ // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991)+ boxSizingNeeded = scrollboxSizeBuggy || extra,+ isBorderBox = boxSizingNeeded &&+ jQuery.css( elem, "boxSizing", false, styles ) === "border-box",+ subtract = extra ?+ boxModelAdjustment(+ elem,+ dimension,+ extra,+ isBorderBox,+ styles+ ) :+ 0;// Account for unreliable border-box dimensions by comparing offset* to computed and// faking a content-box to get border and padding (gh-3699)- if ( isBorderBox && support.scrollboxSize() === styles.position ) {+ if ( isBorderBox && scrollboxSizeBuggy ) {subtract -= Math.ceil(elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -parseFloat( styles[ dimension ] ) -@@ -6758,9 +7222,9 @@ Tween.propHooks = {// Use .style if available and use plain properties where available.if ( jQuery.fx.step[ tween.prop ] ) {jQuery.fx.step[ tween.prop ]( tween );- } else if ( tween.elem.nodeType === 1 &&- ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null ||- jQuery.cssHooks[ tween.prop ] ) ) {+ } else if ( tween.elem.nodeType === 1 && (+ jQuery.cssHooks[ tween.prop ] ||+ tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) {jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );} else {tween.elem[ tween.prop ] = tween.now;@@ -7315,7 +7779,7 @@ jQuery.fn.extend( {clearQueue = type;type = undefined;}- if ( clearQueue && type !== false ) {+ if ( clearQueue ) {this.queue( type || "fx", [] );}@@ -7398,7 +7862,7 @@ jQuery.fn.extend( {}} );-jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) {+jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) {var cssFn = jQuery.fn[ name ];jQuery.fn[ name ] = function( speed, easing, callback ) {return speed == null || typeof speed === "boolean" ?@@ -7619,7 +8083,7 @@ boolHook = {}};-jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {+jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) {var getter = attrHandle[ name ] || jQuery.find.attr;attrHandle[ name ] = function( elem, name, isXML ) {@@ -8243,7 +8707,9 @@ jQuery.extend( jQuery.event, {special.bindType || type;// jQuery handler- handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] &&+ handle = (+ dataPriv.get( cur, "events" ) || Object.create( null )+ )[ event.type ] &&dataPriv.get( cur, "handle" );if ( handle ) {handle.apply( cur, data );@@ -8354,7 +8820,10 @@ if ( !support.focusin ) {jQuery.event.special[ fix ] = {setup: function() {- var doc = this.ownerDocument || this,++ // Handle: regular nodes (via `this.ownerDocument`), window+ // (via `this.document`) & document (via `this`).+ var doc = this.ownerDocument || this.document || this,attaches = dataPriv.access( doc, fix );if ( !attaches ) {@@ -8363,7 +8832,7 @@ if ( !support.focusin ) {dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );},teardown: function() {- var doc = this.ownerDocument || this,+ var doc = this.ownerDocument || this.document || this,attaches = dataPriv.access( doc, fix ) - 1;if ( !attaches ) {@@ -8379,7 +8848,7 @@ if ( !support.focusin ) {}var location = window.location;-var nonce = Date.now();+var nonce = { guid: Date.now() };var rquery = ( /\?/ );@@ -8467,6 +8936,10 @@ jQuery.param = function( a, traditional ) {encodeURIComponent( value == null ? "" : value );};+ if ( a == null ) {+ return "";+ }+// If an array was passed in, assume that it is an array of form elements.if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {@@ -8507,7 +8980,7 @@ jQuery.fn.extend( {rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&( this.checked || !rcheckableType.test( type ) );} )- .map( function( i, elem ) {+ .map( function( _i, elem ) {var val = jQuery( this ).val();if ( val == null ) {@@ -8969,12 +9442,14 @@ jQuery.extend( {if ( !responseHeaders ) {responseHeaders = {};while ( ( match = rheaders.exec( responseHeadersString ) ) ) {- responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];+ responseHeaders[ match[ 1 ].toLowerCase() + " " ] =+ ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] )+ .concat( match[ 2 ] );}}- match = responseHeaders[ key.toLowerCase() ];+ match = responseHeaders[ key.toLowerCase() + " " ];}- return match == null ? null : match;+ return match == null ? null : match.join( ", " );},// Raw string@@ -9118,7 +9593,8 @@ jQuery.extend( {// Add or update anti-cache param if neededif ( s.cache === false ) {cacheURL = cacheURL.replace( rantiCache, "$1" );- uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached;+ uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) ++ uncached;}// Put hash and anti-cache on the URL that will be requested (gh-1732)@@ -9251,6 +9727,11 @@ jQuery.extend( {response = ajaxHandleResponses( s, jqXHR, responses );}+ // Use a noop converter for missing script+ if ( !isSuccess && jQuery.inArray( "script", s.dataTypes ) > -1 ) {+ s.converters[ "text script" ] = function() {};+ }+// Convert no matter what (that way responseXXX fields are always set)response = ajaxConvert( s, response, jqXHR, isSuccess );@@ -9341,7 +9822,7 @@ jQuery.extend( {}} );-jQuery.each( [ "get", "post" ], function( i, method ) {+jQuery.each( [ "get", "post" ], function( _i, method ) {jQuery[ method ] = function( url, data, callback, type ) {// Shift arguments if data argument was omitted@@ -9362,8 +9843,17 @@ jQuery.each( [ "get", "post" ], function( i, method ) {};} );+jQuery.ajaxPrefilter( function( s ) {+ var i;+ for ( i in s.headers ) {+ if ( i.toLowerCase() === "content-type" ) {+ s.contentType = s.headers[ i ] || "";+ }+ }+} );+-jQuery._evalUrl = function( url ) {+jQuery._evalUrl = function( url, options, doc ) {return jQuery.ajax( {url: url,@@ -9373,7 +9863,16 @@ jQuery._evalUrl = function( url ) {cache: true,async: false,global: false,- "throws": true++ // Only evaluate the response if it is successful (gh-4126)+ // dataFilter is not invoked for failure responses, so using it instead+ // of the default converter is kludgy but it works.+ converters: {+ "text script": function() {}+ },+ dataFilter: function( response ) {+ jQuery.globalEval( response, options, doc );+ }} );};@@ -9656,24 +10155,21 @@ jQuery.ajaxPrefilter( "script", function( s ) {// Bind script tag hack transportjQuery.ajaxTransport( "script", function( s ) {- // This transport only deals with cross domain requests- if ( s.crossDomain ) {+ // This transport only deals with cross domain or forced-by-attrs requests+ if ( s.crossDomain || s.scriptAttrs ) {var script, callback;return {send: function( _, complete ) {- script = jQuery( "<script>" ).prop( {- charset: s.scriptCharset,- src: s.url- } ).on(- "load error",- callback = function( evt ) {+ script = jQuery( "<script>" )+ .attr( s.scriptAttrs || {} )+ .prop( { charset: s.scriptCharset, src: s.url } )+ .on( "load error", callback = function( evt ) {script.remove();callback = null;if ( evt ) {complete( evt.type === "error" ? 404 : 200, evt.type );}- }- );+ } );// Use native DOM manipulation to avoid our domManip AJAX trickerydocument.head.appendChild( script[ 0 ] );@@ -9697,7 +10193,7 @@ var oldCallbacks = [],jQuery.ajaxSetup( {jsonp: "callback",jsonpCallback: function() {- var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );+ var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce.guid++ ) );this[ callback ] = true;return callback;}@@ -9914,23 +10410,6 @@ jQuery.fn.load = function( url, params, callback ) {-// Attach a bunch of functions for handling common AJAX events-jQuery.each( [- "ajaxStart",- "ajaxStop",- "ajaxComplete",- "ajaxError",- "ajaxSuccess",- "ajaxSend"-], function( i, type ) {- jQuery.fn[ type ] = function( fn ) {- return this.on( type, fn );- };-} );----jQuery.expr.pseudos.animated = function( elem ) {return jQuery.grep( jQuery.timers, function( fn ) {return elem === fn.elem;@@ -9987,6 +10466,12 @@ jQuery.offset = {options.using.call( elem, props );} else {+ if ( typeof props.top === "number" ) {+ props.top += "px";+ }+ if ( typeof props.left === "number" ) {+ props.left += "px";+ }curElem.css( props );}}@@ -10137,7 +10622,7 @@ jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function(// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347// getComputedStyle returns percent when specified for top/left/bottom/right;// rather than make the css module depend on the offset module, just check for it here-jQuery.each( [ "top", "left" ], function( i, prop ) {+jQuery.each( [ "top", "left" ], function( _i, prop ) {jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,function( elem, computed ) {if ( computed ) {@@ -10200,25 +10685,19 @@ jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {} );-jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +- "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +- "change select submit keydown keypress keyup contextmenu" ).split( " " ),- function( i, name ) {-- // Handle event binding- jQuery.fn[ name ] = function( data, fn ) {- return arguments.length > 0 ?- this.on( name, null, data, fn ) :- this.trigger( name );+jQuery.each( [+ "ajaxStart",+ "ajaxStop",+ "ajaxComplete",+ "ajaxError",+ "ajaxSuccess",+ "ajaxSend"+], function( _i, type ) {+ jQuery.fn[ type ] = function( fn ) {+ return this.on( type, fn );};} );-jQuery.fn.extend( {- hover: function( fnOver, fnOut ) {- return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );- }-} );-@@ -10240,9 +10719,33 @@ jQuery.fn.extend( {return arguments.length === 1 ?this.off( selector, "**" ) :this.off( types, selector || "**", fn );+ },++ hover: function( fnOver, fnOut ) {+ return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );}} );+jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " ++ "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " ++ "change select submit keydown keypress keyup contextmenu" ).split( " " ),+ function( _i, name ) {++ // Handle event binding+ jQuery.fn[ name ] = function( data, fn ) {+ return arguments.length > 0 ?+ this.on( name, null, data, fn ) :+ this.trigger( name );+ };+ } );+++++// Support: Android <=4.0 only+// Make sure we trim BOM and NBSP+var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;+// Bind a function to a context, optionally partially applying any// arguments.// jQuery.proxy is deprecated to promote standards (specifically Function#bind)@@ -10305,6 +10808,11 @@ jQuery.isNumeric = function( obj ) {!isNaN( obj - parseFloat( obj ) );};+jQuery.trim = function( text ) {+ return text == null ?+ "" :+ ( text + "" ).replace( rtrim, "" );+};@@ -10353,7 +10861,7 @@ jQuery.noConflict = function( deep ) {// Expose jQuery and $ identifiers, even in AMD// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)// and CommonJS for browser emulators (#13566)-if ( !noGlobal ) {+if ( typeof noGlobal === "undefined" ) {window.jQuery = window.$ = jQuery;}