Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

16173 řádky
419KB

  1. /*!
  2. * Chart.js v2.9.4
  3. * https://www.chartjs.org
  4. * (c) 2020 Chart.js Contributors
  5. * Released under the MIT License
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(function() { try { return require('moment'); } catch(e) { } }()) :
  9. typeof define === 'function' && define.amd ? define(['require'], function(require) { return factory(function() { try { return require('moment'); } catch(e) { } }()); }) :
  10. (global = global || self, global.Chart = factory(global.moment));
  11. }(this, (function (moment) { 'use strict';
  12. moment = moment && moment.hasOwnProperty('default') ? moment['default'] : moment;
  13. function createCommonjsModule(fn, module) {
  14. return module = { exports: {} }, fn(module, module.exports), module.exports;
  15. }
  16. function getCjsExportFromNamespace (n) {
  17. return n && n['default'] || n;
  18. }
  19. var colorName = {
  20. "aliceblue": [240, 248, 255],
  21. "antiquewhite": [250, 235, 215],
  22. "aqua": [0, 255, 255],
  23. "aquamarine": [127, 255, 212],
  24. "azure": [240, 255, 255],
  25. "beige": [245, 245, 220],
  26. "bisque": [255, 228, 196],
  27. "black": [0, 0, 0],
  28. "blanchedalmond": [255, 235, 205],
  29. "blue": [0, 0, 255],
  30. "blueviolet": [138, 43, 226],
  31. "brown": [165, 42, 42],
  32. "burlywood": [222, 184, 135],
  33. "cadetblue": [95, 158, 160],
  34. "chartreuse": [127, 255, 0],
  35. "chocolate": [210, 105, 30],
  36. "coral": [255, 127, 80],
  37. "cornflowerblue": [100, 149, 237],
  38. "cornsilk": [255, 248, 220],
  39. "crimson": [220, 20, 60],
  40. "cyan": [0, 255, 255],
  41. "darkblue": [0, 0, 139],
  42. "darkcyan": [0, 139, 139],
  43. "darkgoldenrod": [184, 134, 11],
  44. "darkgray": [169, 169, 169],
  45. "darkgreen": [0, 100, 0],
  46. "darkgrey": [169, 169, 169],
  47. "darkkhaki": [189, 183, 107],
  48. "darkmagenta": [139, 0, 139],
  49. "darkolivegreen": [85, 107, 47],
  50. "darkorange": [255, 140, 0],
  51. "darkorchid": [153, 50, 204],
  52. "darkred": [139, 0, 0],
  53. "darksalmon": [233, 150, 122],
  54. "darkseagreen": [143, 188, 143],
  55. "darkslateblue": [72, 61, 139],
  56. "darkslategray": [47, 79, 79],
  57. "darkslategrey": [47, 79, 79],
  58. "darkturquoise": [0, 206, 209],
  59. "darkviolet": [148, 0, 211],
  60. "deeppink": [255, 20, 147],
  61. "deepskyblue": [0, 191, 255],
  62. "dimgray": [105, 105, 105],
  63. "dimgrey": [105, 105, 105],
  64. "dodgerblue": [30, 144, 255],
  65. "firebrick": [178, 34, 34],
  66. "floralwhite": [255, 250, 240],
  67. "forestgreen": [34, 139, 34],
  68. "fuchsia": [255, 0, 255],
  69. "gainsboro": [220, 220, 220],
  70. "ghostwhite": [248, 248, 255],
  71. "gold": [255, 215, 0],
  72. "goldenrod": [218, 165, 32],
  73. "gray": [128, 128, 128],
  74. "green": [0, 128, 0],
  75. "greenyellow": [173, 255, 47],
  76. "grey": [128, 128, 128],
  77. "honeydew": [240, 255, 240],
  78. "hotpink": [255, 105, 180],
  79. "indianred": [205, 92, 92],
  80. "indigo": [75, 0, 130],
  81. "ivory": [255, 255, 240],
  82. "khaki": [240, 230, 140],
  83. "lavender": [230, 230, 250],
  84. "lavenderblush": [255, 240, 245],
  85. "lawngreen": [124, 252, 0],
  86. "lemonchiffon": [255, 250, 205],
  87. "lightblue": [173, 216, 230],
  88. "lightcoral": [240, 128, 128],
  89. "lightcyan": [224, 255, 255],
  90. "lightgoldenrodyellow": [250, 250, 210],
  91. "lightgray": [211, 211, 211],
  92. "lightgreen": [144, 238, 144],
  93. "lightgrey": [211, 211, 211],
  94. "lightpink": [255, 182, 193],
  95. "lightsalmon": [255, 160, 122],
  96. "lightseagreen": [32, 178, 170],
  97. "lightskyblue": [135, 206, 250],
  98. "lightslategray": [119, 136, 153],
  99. "lightslategrey": [119, 136, 153],
  100. "lightsteelblue": [176, 196, 222],
  101. "lightyellow": [255, 255, 224],
  102. "lime": [0, 255, 0],
  103. "limegreen": [50, 205, 50],
  104. "linen": [250, 240, 230],
  105. "magenta": [255, 0, 255],
  106. "maroon": [128, 0, 0],
  107. "mediumaquamarine": [102, 205, 170],
  108. "mediumblue": [0, 0, 205],
  109. "mediumorchid": [186, 85, 211],
  110. "mediumpurple": [147, 112, 219],
  111. "mediumseagreen": [60, 179, 113],
  112. "mediumslateblue": [123, 104, 238],
  113. "mediumspringgreen": [0, 250, 154],
  114. "mediumturquoise": [72, 209, 204],
  115. "mediumvioletred": [199, 21, 133],
  116. "midnightblue": [25, 25, 112],
  117. "mintcream": [245, 255, 250],
  118. "mistyrose": [255, 228, 225],
  119. "moccasin": [255, 228, 181],
  120. "navajowhite": [255, 222, 173],
  121. "navy": [0, 0, 128],
  122. "oldlace": [253, 245, 230],
  123. "olive": [128, 128, 0],
  124. "olivedrab": [107, 142, 35],
  125. "orange": [255, 165, 0],
  126. "orangered": [255, 69, 0],
  127. "orchid": [218, 112, 214],
  128. "palegoldenrod": [238, 232, 170],
  129. "palegreen": [152, 251, 152],
  130. "paleturquoise": [175, 238, 238],
  131. "palevioletred": [219, 112, 147],
  132. "papayawhip": [255, 239, 213],
  133. "peachpuff": [255, 218, 185],
  134. "peru": [205, 133, 63],
  135. "pink": [255, 192, 203],
  136. "plum": [221, 160, 221],
  137. "powderblue": [176, 224, 230],
  138. "purple": [128, 0, 128],
  139. "rebeccapurple": [102, 51, 153],
  140. "red": [255, 0, 0],
  141. "rosybrown": [188, 143, 143],
  142. "royalblue": [65, 105, 225],
  143. "saddlebrown": [139, 69, 19],
  144. "salmon": [250, 128, 114],
  145. "sandybrown": [244, 164, 96],
  146. "seagreen": [46, 139, 87],
  147. "seashell": [255, 245, 238],
  148. "sienna": [160, 82, 45],
  149. "silver": [192, 192, 192],
  150. "skyblue": [135, 206, 235],
  151. "slateblue": [106, 90, 205],
  152. "slategray": [112, 128, 144],
  153. "slategrey": [112, 128, 144],
  154. "snow": [255, 250, 250],
  155. "springgreen": [0, 255, 127],
  156. "steelblue": [70, 130, 180],
  157. "tan": [210, 180, 140],
  158. "teal": [0, 128, 128],
  159. "thistle": [216, 191, 216],
  160. "tomato": [255, 99, 71],
  161. "turquoise": [64, 224, 208],
  162. "violet": [238, 130, 238],
  163. "wheat": [245, 222, 179],
  164. "white": [255, 255, 255],
  165. "whitesmoke": [245, 245, 245],
  166. "yellow": [255, 255, 0],
  167. "yellowgreen": [154, 205, 50]
  168. };
  169. var conversions = createCommonjsModule(function (module) {
  170. /* MIT license */
  171. // NOTE: conversions should only return primitive values (i.e. arrays, or
  172. // values that give correct `typeof` results).
  173. // do not use box values types (i.e. Number(), String(), etc.)
  174. var reverseKeywords = {};
  175. for (var key in colorName) {
  176. if (colorName.hasOwnProperty(key)) {
  177. reverseKeywords[colorName[key]] = key;
  178. }
  179. }
  180. var convert = module.exports = {
  181. rgb: {channels: 3, labels: 'rgb'},
  182. hsl: {channels: 3, labels: 'hsl'},
  183. hsv: {channels: 3, labels: 'hsv'},
  184. hwb: {channels: 3, labels: 'hwb'},
  185. cmyk: {channels: 4, labels: 'cmyk'},
  186. xyz: {channels: 3, labels: 'xyz'},
  187. lab: {channels: 3, labels: 'lab'},
  188. lch: {channels: 3, labels: 'lch'},
  189. hex: {channels: 1, labels: ['hex']},
  190. keyword: {channels: 1, labels: ['keyword']},
  191. ansi16: {channels: 1, labels: ['ansi16']},
  192. ansi256: {channels: 1, labels: ['ansi256']},
  193. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  194. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  195. gray: {channels: 1, labels: ['gray']}
  196. };
  197. // hide .channels and .labels properties
  198. for (var model in convert) {
  199. if (convert.hasOwnProperty(model)) {
  200. if (!('channels' in convert[model])) {
  201. throw new Error('missing channels property: ' + model);
  202. }
  203. if (!('labels' in convert[model])) {
  204. throw new Error('missing channel labels property: ' + model);
  205. }
  206. if (convert[model].labels.length !== convert[model].channels) {
  207. throw new Error('channel and label counts mismatch: ' + model);
  208. }
  209. var channels = convert[model].channels;
  210. var labels = convert[model].labels;
  211. delete convert[model].channels;
  212. delete convert[model].labels;
  213. Object.defineProperty(convert[model], 'channels', {value: channels});
  214. Object.defineProperty(convert[model], 'labels', {value: labels});
  215. }
  216. }
  217. convert.rgb.hsl = function (rgb) {
  218. var r = rgb[0] / 255;
  219. var g = rgb[1] / 255;
  220. var b = rgb[2] / 255;
  221. var min = Math.min(r, g, b);
  222. var max = Math.max(r, g, b);
  223. var delta = max - min;
  224. var h;
  225. var s;
  226. var l;
  227. if (max === min) {
  228. h = 0;
  229. } else if (r === max) {
  230. h = (g - b) / delta;
  231. } else if (g === max) {
  232. h = 2 + (b - r) / delta;
  233. } else if (b === max) {
  234. h = 4 + (r - g) / delta;
  235. }
  236. h = Math.min(h * 60, 360);
  237. if (h < 0) {
  238. h += 360;
  239. }
  240. l = (min + max) / 2;
  241. if (max === min) {
  242. s = 0;
  243. } else if (l <= 0.5) {
  244. s = delta / (max + min);
  245. } else {
  246. s = delta / (2 - max - min);
  247. }
  248. return [h, s * 100, l * 100];
  249. };
  250. convert.rgb.hsv = function (rgb) {
  251. var rdif;
  252. var gdif;
  253. var bdif;
  254. var h;
  255. var s;
  256. var r = rgb[0] / 255;
  257. var g = rgb[1] / 255;
  258. var b = rgb[2] / 255;
  259. var v = Math.max(r, g, b);
  260. var diff = v - Math.min(r, g, b);
  261. var diffc = function (c) {
  262. return (v - c) / 6 / diff + 1 / 2;
  263. };
  264. if (diff === 0) {
  265. h = s = 0;
  266. } else {
  267. s = diff / v;
  268. rdif = diffc(r);
  269. gdif = diffc(g);
  270. bdif = diffc(b);
  271. if (r === v) {
  272. h = bdif - gdif;
  273. } else if (g === v) {
  274. h = (1 / 3) + rdif - bdif;
  275. } else if (b === v) {
  276. h = (2 / 3) + gdif - rdif;
  277. }
  278. if (h < 0) {
  279. h += 1;
  280. } else if (h > 1) {
  281. h -= 1;
  282. }
  283. }
  284. return [
  285. h * 360,
  286. s * 100,
  287. v * 100
  288. ];
  289. };
  290. convert.rgb.hwb = function (rgb) {
  291. var r = rgb[0];
  292. var g = rgb[1];
  293. var b = rgb[2];
  294. var h = convert.rgb.hsl(rgb)[0];
  295. var w = 1 / 255 * Math.min(r, Math.min(g, b));
  296. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  297. return [h, w * 100, b * 100];
  298. };
  299. convert.rgb.cmyk = function (rgb) {
  300. var r = rgb[0] / 255;
  301. var g = rgb[1] / 255;
  302. var b = rgb[2] / 255;
  303. var c;
  304. var m;
  305. var y;
  306. var k;
  307. k = Math.min(1 - r, 1 - g, 1 - b);
  308. c = (1 - r - k) / (1 - k) || 0;
  309. m = (1 - g - k) / (1 - k) || 0;
  310. y = (1 - b - k) / (1 - k) || 0;
  311. return [c * 100, m * 100, y * 100, k * 100];
  312. };
  313. /**
  314. * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  315. * */
  316. function comparativeDistance(x, y) {
  317. return (
  318. Math.pow(x[0] - y[0], 2) +
  319. Math.pow(x[1] - y[1], 2) +
  320. Math.pow(x[2] - y[2], 2)
  321. );
  322. }
  323. convert.rgb.keyword = function (rgb) {
  324. var reversed = reverseKeywords[rgb];
  325. if (reversed) {
  326. return reversed;
  327. }
  328. var currentClosestDistance = Infinity;
  329. var currentClosestKeyword;
  330. for (var keyword in colorName) {
  331. if (colorName.hasOwnProperty(keyword)) {
  332. var value = colorName[keyword];
  333. // Compute comparative distance
  334. var distance = comparativeDistance(rgb, value);
  335. // Check if its less, if so set as closest
  336. if (distance < currentClosestDistance) {
  337. currentClosestDistance = distance;
  338. currentClosestKeyword = keyword;
  339. }
  340. }
  341. }
  342. return currentClosestKeyword;
  343. };
  344. convert.keyword.rgb = function (keyword) {
  345. return colorName[keyword];
  346. };
  347. convert.rgb.xyz = function (rgb) {
  348. var r = rgb[0] / 255;
  349. var g = rgb[1] / 255;
  350. var b = rgb[2] / 255;
  351. // assume sRGB
  352. r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
  353. g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
  354. b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
  355. var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  356. var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  357. var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  358. return [x * 100, y * 100, z * 100];
  359. };
  360. convert.rgb.lab = function (rgb) {
  361. var xyz = convert.rgb.xyz(rgb);
  362. var x = xyz[0];
  363. var y = xyz[1];
  364. var z = xyz[2];
  365. var l;
  366. var a;
  367. var b;
  368. x /= 95.047;
  369. y /= 100;
  370. z /= 108.883;
  371. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  372. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  373. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  374. l = (116 * y) - 16;
  375. a = 500 * (x - y);
  376. b = 200 * (y - z);
  377. return [l, a, b];
  378. };
  379. convert.hsl.rgb = function (hsl) {
  380. var h = hsl[0] / 360;
  381. var s = hsl[1] / 100;
  382. var l = hsl[2] / 100;
  383. var t1;
  384. var t2;
  385. var t3;
  386. var rgb;
  387. var val;
  388. if (s === 0) {
  389. val = l * 255;
  390. return [val, val, val];
  391. }
  392. if (l < 0.5) {
  393. t2 = l * (1 + s);
  394. } else {
  395. t2 = l + s - l * s;
  396. }
  397. t1 = 2 * l - t2;
  398. rgb = [0, 0, 0];
  399. for (var i = 0; i < 3; i++) {
  400. t3 = h + 1 / 3 * -(i - 1);
  401. if (t3 < 0) {
  402. t3++;
  403. }
  404. if (t3 > 1) {
  405. t3--;
  406. }
  407. if (6 * t3 < 1) {
  408. val = t1 + (t2 - t1) * 6 * t3;
  409. } else if (2 * t3 < 1) {
  410. val = t2;
  411. } else if (3 * t3 < 2) {
  412. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  413. } else {
  414. val = t1;
  415. }
  416. rgb[i] = val * 255;
  417. }
  418. return rgb;
  419. };
  420. convert.hsl.hsv = function (hsl) {
  421. var h = hsl[0];
  422. var s = hsl[1] / 100;
  423. var l = hsl[2] / 100;
  424. var smin = s;
  425. var lmin = Math.max(l, 0.01);
  426. var sv;
  427. var v;
  428. l *= 2;
  429. s *= (l <= 1) ? l : 2 - l;
  430. smin *= lmin <= 1 ? lmin : 2 - lmin;
  431. v = (l + s) / 2;
  432. sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  433. return [h, sv * 100, v * 100];
  434. };
  435. convert.hsv.rgb = function (hsv) {
  436. var h = hsv[0] / 60;
  437. var s = hsv[1] / 100;
  438. var v = hsv[2] / 100;
  439. var hi = Math.floor(h) % 6;
  440. var f = h - Math.floor(h);
  441. var p = 255 * v * (1 - s);
  442. var q = 255 * v * (1 - (s * f));
  443. var t = 255 * v * (1 - (s * (1 - f)));
  444. v *= 255;
  445. switch (hi) {
  446. case 0:
  447. return [v, t, p];
  448. case 1:
  449. return [q, v, p];
  450. case 2:
  451. return [p, v, t];
  452. case 3:
  453. return [p, q, v];
  454. case 4:
  455. return [t, p, v];
  456. case 5:
  457. return [v, p, q];
  458. }
  459. };
  460. convert.hsv.hsl = function (hsv) {
  461. var h = hsv[0];
  462. var s = hsv[1] / 100;
  463. var v = hsv[2] / 100;
  464. var vmin = Math.max(v, 0.01);
  465. var lmin;
  466. var sl;
  467. var l;
  468. l = (2 - s) * v;
  469. lmin = (2 - s) * vmin;
  470. sl = s * vmin;
  471. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  472. sl = sl || 0;
  473. l /= 2;
  474. return [h, sl * 100, l * 100];
  475. };
  476. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  477. convert.hwb.rgb = function (hwb) {
  478. var h = hwb[0] / 360;
  479. var wh = hwb[1] / 100;
  480. var bl = hwb[2] / 100;
  481. var ratio = wh + bl;
  482. var i;
  483. var v;
  484. var f;
  485. var n;
  486. // wh + bl cant be > 1
  487. if (ratio > 1) {
  488. wh /= ratio;
  489. bl /= ratio;
  490. }
  491. i = Math.floor(6 * h);
  492. v = 1 - bl;
  493. f = 6 * h - i;
  494. if ((i & 0x01) !== 0) {
  495. f = 1 - f;
  496. }
  497. n = wh + f * (v - wh); // linear interpolation
  498. var r;
  499. var g;
  500. var b;
  501. switch (i) {
  502. default:
  503. case 6:
  504. case 0: r = v; g = n; b = wh; break;
  505. case 1: r = n; g = v; b = wh; break;
  506. case 2: r = wh; g = v; b = n; break;
  507. case 3: r = wh; g = n; b = v; break;
  508. case 4: r = n; g = wh; b = v; break;
  509. case 5: r = v; g = wh; b = n; break;
  510. }
  511. return [r * 255, g * 255, b * 255];
  512. };
  513. convert.cmyk.rgb = function (cmyk) {
  514. var c = cmyk[0] / 100;
  515. var m = cmyk[1] / 100;
  516. var y = cmyk[2] / 100;
  517. var k = cmyk[3] / 100;
  518. var r;
  519. var g;
  520. var b;
  521. r = 1 - Math.min(1, c * (1 - k) + k);
  522. g = 1 - Math.min(1, m * (1 - k) + k);
  523. b = 1 - Math.min(1, y * (1 - k) + k);
  524. return [r * 255, g * 255, b * 255];
  525. };
  526. convert.xyz.rgb = function (xyz) {
  527. var x = xyz[0] / 100;
  528. var y = xyz[1] / 100;
  529. var z = xyz[2] / 100;
  530. var r;
  531. var g;
  532. var b;
  533. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  534. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  535. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  536. // assume sRGB
  537. r = r > 0.0031308
  538. ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
  539. : r * 12.92;
  540. g = g > 0.0031308
  541. ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
  542. : g * 12.92;
  543. b = b > 0.0031308
  544. ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
  545. : b * 12.92;
  546. r = Math.min(Math.max(0, r), 1);
  547. g = Math.min(Math.max(0, g), 1);
  548. b = Math.min(Math.max(0, b), 1);
  549. return [r * 255, g * 255, b * 255];
  550. };
  551. convert.xyz.lab = function (xyz) {
  552. var x = xyz[0];
  553. var y = xyz[1];
  554. var z = xyz[2];
  555. var l;
  556. var a;
  557. var b;
  558. x /= 95.047;
  559. y /= 100;
  560. z /= 108.883;
  561. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  562. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  563. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  564. l = (116 * y) - 16;
  565. a = 500 * (x - y);
  566. b = 200 * (y - z);
  567. return [l, a, b];
  568. };
  569. convert.lab.xyz = function (lab) {
  570. var l = lab[0];
  571. var a = lab[1];
  572. var b = lab[2];
  573. var x;
  574. var y;
  575. var z;
  576. y = (l + 16) / 116;
  577. x = a / 500 + y;
  578. z = y - b / 200;
  579. var y2 = Math.pow(y, 3);
  580. var x2 = Math.pow(x, 3);
  581. var z2 = Math.pow(z, 3);
  582. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  583. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  584. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  585. x *= 95.047;
  586. y *= 100;
  587. z *= 108.883;
  588. return [x, y, z];
  589. };
  590. convert.lab.lch = function (lab) {
  591. var l = lab[0];
  592. var a = lab[1];
  593. var b = lab[2];
  594. var hr;
  595. var h;
  596. var c;
  597. hr = Math.atan2(b, a);
  598. h = hr * 360 / 2 / Math.PI;
  599. if (h < 0) {
  600. h += 360;
  601. }
  602. c = Math.sqrt(a * a + b * b);
  603. return [l, c, h];
  604. };
  605. convert.lch.lab = function (lch) {
  606. var l = lch[0];
  607. var c = lch[1];
  608. var h = lch[2];
  609. var a;
  610. var b;
  611. var hr;
  612. hr = h / 360 * 2 * Math.PI;
  613. a = c * Math.cos(hr);
  614. b = c * Math.sin(hr);
  615. return [l, a, b];
  616. };
  617. convert.rgb.ansi16 = function (args) {
  618. var r = args[0];
  619. var g = args[1];
  620. var b = args[2];
  621. var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
  622. value = Math.round(value / 50);
  623. if (value === 0) {
  624. return 30;
  625. }
  626. var ansi = 30
  627. + ((Math.round(b / 255) << 2)
  628. | (Math.round(g / 255) << 1)
  629. | Math.round(r / 255));
  630. if (value === 2) {
  631. ansi += 60;
  632. }
  633. return ansi;
  634. };
  635. convert.hsv.ansi16 = function (args) {
  636. // optimization here; we already know the value and don't need to get
  637. // it converted for us.
  638. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
  639. };
  640. convert.rgb.ansi256 = function (args) {
  641. var r = args[0];
  642. var g = args[1];
  643. var b = args[2];
  644. // we use the extended greyscale palette here, with the exception of
  645. // black and white. normal palette only has 4 greyscale shades.
  646. if (r === g && g === b) {
  647. if (r < 8) {
  648. return 16;
  649. }
  650. if (r > 248) {
  651. return 231;
  652. }
  653. return Math.round(((r - 8) / 247) * 24) + 232;
  654. }
  655. var ansi = 16
  656. + (36 * Math.round(r / 255 * 5))
  657. + (6 * Math.round(g / 255 * 5))
  658. + Math.round(b / 255 * 5);
  659. return ansi;
  660. };
  661. convert.ansi16.rgb = function (args) {
  662. var color = args % 10;
  663. // handle greyscale
  664. if (color === 0 || color === 7) {
  665. if (args > 50) {
  666. color += 3.5;
  667. }
  668. color = color / 10.5 * 255;
  669. return [color, color, color];
  670. }
  671. var mult = (~~(args > 50) + 1) * 0.5;
  672. var r = ((color & 1) * mult) * 255;
  673. var g = (((color >> 1) & 1) * mult) * 255;
  674. var b = (((color >> 2) & 1) * mult) * 255;
  675. return [r, g, b];
  676. };
  677. convert.ansi256.rgb = function (args) {
  678. // handle greyscale
  679. if (args >= 232) {
  680. var c = (args - 232) * 10 + 8;
  681. return [c, c, c];
  682. }
  683. args -= 16;
  684. var rem;
  685. var r = Math.floor(args / 36) / 5 * 255;
  686. var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  687. var b = (rem % 6) / 5 * 255;
  688. return [r, g, b];
  689. };
  690. convert.rgb.hex = function (args) {
  691. var integer = ((Math.round(args[0]) & 0xFF) << 16)
  692. + ((Math.round(args[1]) & 0xFF) << 8)
  693. + (Math.round(args[2]) & 0xFF);
  694. var string = integer.toString(16).toUpperCase();
  695. return '000000'.substring(string.length) + string;
  696. };
  697. convert.hex.rgb = function (args) {
  698. var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  699. if (!match) {
  700. return [0, 0, 0];
  701. }
  702. var colorString = match[0];
  703. if (match[0].length === 3) {
  704. colorString = colorString.split('').map(function (char) {
  705. return char + char;
  706. }).join('');
  707. }
  708. var integer = parseInt(colorString, 16);
  709. var r = (integer >> 16) & 0xFF;
  710. var g = (integer >> 8) & 0xFF;
  711. var b = integer & 0xFF;
  712. return [r, g, b];
  713. };
  714. convert.rgb.hcg = function (rgb) {
  715. var r = rgb[0] / 255;
  716. var g = rgb[1] / 255;
  717. var b = rgb[2] / 255;
  718. var max = Math.max(Math.max(r, g), b);
  719. var min = Math.min(Math.min(r, g), b);
  720. var chroma = (max - min);
  721. var grayscale;
  722. var hue;
  723. if (chroma < 1) {
  724. grayscale = min / (1 - chroma);
  725. } else {
  726. grayscale = 0;
  727. }
  728. if (chroma <= 0) {
  729. hue = 0;
  730. } else
  731. if (max === r) {
  732. hue = ((g - b) / chroma) % 6;
  733. } else
  734. if (max === g) {
  735. hue = 2 + (b - r) / chroma;
  736. } else {
  737. hue = 4 + (r - g) / chroma + 4;
  738. }
  739. hue /= 6;
  740. hue %= 1;
  741. return [hue * 360, chroma * 100, grayscale * 100];
  742. };
  743. convert.hsl.hcg = function (hsl) {
  744. var s = hsl[1] / 100;
  745. var l = hsl[2] / 100;
  746. var c = 1;
  747. var f = 0;
  748. if (l < 0.5) {
  749. c = 2.0 * s * l;
  750. } else {
  751. c = 2.0 * s * (1.0 - l);
  752. }
  753. if (c < 1.0) {
  754. f = (l - 0.5 * c) / (1.0 - c);
  755. }
  756. return [hsl[0], c * 100, f * 100];
  757. };
  758. convert.hsv.hcg = function (hsv) {
  759. var s = hsv[1] / 100;
  760. var v = hsv[2] / 100;
  761. var c = s * v;
  762. var f = 0;
  763. if (c < 1.0) {
  764. f = (v - c) / (1 - c);
  765. }
  766. return [hsv[0], c * 100, f * 100];
  767. };
  768. convert.hcg.rgb = function (hcg) {
  769. var h = hcg[0] / 360;
  770. var c = hcg[1] / 100;
  771. var g = hcg[2] / 100;
  772. if (c === 0.0) {
  773. return [g * 255, g * 255, g * 255];
  774. }
  775. var pure = [0, 0, 0];
  776. var hi = (h % 1) * 6;
  777. var v = hi % 1;
  778. var w = 1 - v;
  779. var mg = 0;
  780. switch (Math.floor(hi)) {
  781. case 0:
  782. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  783. case 1:
  784. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  785. case 2:
  786. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  787. case 3:
  788. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  789. case 4:
  790. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  791. default:
  792. pure[0] = 1; pure[1] = 0; pure[2] = w;
  793. }
  794. mg = (1.0 - c) * g;
  795. return [
  796. (c * pure[0] + mg) * 255,
  797. (c * pure[1] + mg) * 255,
  798. (c * pure[2] + mg) * 255
  799. ];
  800. };
  801. convert.hcg.hsv = function (hcg) {
  802. var c = hcg[1] / 100;
  803. var g = hcg[2] / 100;
  804. var v = c + g * (1.0 - c);
  805. var f = 0;
  806. if (v > 0.0) {
  807. f = c / v;
  808. }
  809. return [hcg[0], f * 100, v * 100];
  810. };
  811. convert.hcg.hsl = function (hcg) {
  812. var c = hcg[1] / 100;
  813. var g = hcg[2] / 100;
  814. var l = g * (1.0 - c) + 0.5 * c;
  815. var s = 0;
  816. if (l > 0.0 && l < 0.5) {
  817. s = c / (2 * l);
  818. } else
  819. if (l >= 0.5 && l < 1.0) {
  820. s = c / (2 * (1 - l));
  821. }
  822. return [hcg[0], s * 100, l * 100];
  823. };
  824. convert.hcg.hwb = function (hcg) {
  825. var c = hcg[1] / 100;
  826. var g = hcg[2] / 100;
  827. var v = c + g * (1.0 - c);
  828. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  829. };
  830. convert.hwb.hcg = function (hwb) {
  831. var w = hwb[1] / 100;
  832. var b = hwb[2] / 100;
  833. var v = 1 - b;
  834. var c = v - w;
  835. var g = 0;
  836. if (c < 1) {
  837. g = (v - c) / (1 - c);
  838. }
  839. return [hwb[0], c * 100, g * 100];
  840. };
  841. convert.apple.rgb = function (apple) {
  842. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  843. };
  844. convert.rgb.apple = function (rgb) {
  845. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  846. };
  847. convert.gray.rgb = function (args) {
  848. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  849. };
  850. convert.gray.hsl = convert.gray.hsv = function (args) {
  851. return [0, 0, args[0]];
  852. };
  853. convert.gray.hwb = function (gray) {
  854. return [0, 100, gray[0]];
  855. };
  856. convert.gray.cmyk = function (gray) {
  857. return [0, 0, 0, gray[0]];
  858. };
  859. convert.gray.lab = function (gray) {
  860. return [gray[0], 0, 0];
  861. };
  862. convert.gray.hex = function (gray) {
  863. var val = Math.round(gray[0] / 100 * 255) & 0xFF;
  864. var integer = (val << 16) + (val << 8) + val;
  865. var string = integer.toString(16).toUpperCase();
  866. return '000000'.substring(string.length) + string;
  867. };
  868. convert.rgb.gray = function (rgb) {
  869. var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  870. return [val / 255 * 100];
  871. };
  872. });
  873. var conversions_1 = conversions.rgb;
  874. var conversions_2 = conversions.hsl;
  875. var conversions_3 = conversions.hsv;
  876. var conversions_4 = conversions.hwb;
  877. var conversions_5 = conversions.cmyk;
  878. var conversions_6 = conversions.xyz;
  879. var conversions_7 = conversions.lab;
  880. var conversions_8 = conversions.lch;
  881. var conversions_9 = conversions.hex;
  882. var conversions_10 = conversions.keyword;
  883. var conversions_11 = conversions.ansi16;
  884. var conversions_12 = conversions.ansi256;
  885. var conversions_13 = conversions.hcg;
  886. var conversions_14 = conversions.apple;
  887. var conversions_15 = conversions.gray;
  888. /*
  889. this function routes a model to all other models.
  890. all functions that are routed have a property `.conversion` attached
  891. to the returned synthetic function. This property is an array
  892. of strings, each with the steps in between the 'from' and 'to'
  893. color models (inclusive).
  894. conversions that are not possible simply are not included.
  895. */
  896. function buildGraph() {
  897. var graph = {};
  898. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  899. var models = Object.keys(conversions);
  900. for (var len = models.length, i = 0; i < len; i++) {
  901. graph[models[i]] = {
  902. // http://jsperf.com/1-vs-infinity
  903. // micro-opt, but this is simple.
  904. distance: -1,
  905. parent: null
  906. };
  907. }
  908. return graph;
  909. }
  910. // https://en.wikipedia.org/wiki/Breadth-first_search
  911. function deriveBFS(fromModel) {
  912. var graph = buildGraph();
  913. var queue = [fromModel]; // unshift -> queue -> pop
  914. graph[fromModel].distance = 0;
  915. while (queue.length) {
  916. var current = queue.pop();
  917. var adjacents = Object.keys(conversions[current]);
  918. for (var len = adjacents.length, i = 0; i < len; i++) {
  919. var adjacent = adjacents[i];
  920. var node = graph[adjacent];
  921. if (node.distance === -1) {
  922. node.distance = graph[current].distance + 1;
  923. node.parent = current;
  924. queue.unshift(adjacent);
  925. }
  926. }
  927. }
  928. return graph;
  929. }
  930. function link(from, to) {
  931. return function (args) {
  932. return to(from(args));
  933. };
  934. }
  935. function wrapConversion(toModel, graph) {
  936. var path = [graph[toModel].parent, toModel];
  937. var fn = conversions[graph[toModel].parent][toModel];
  938. var cur = graph[toModel].parent;
  939. while (graph[cur].parent) {
  940. path.unshift(graph[cur].parent);
  941. fn = link(conversions[graph[cur].parent][cur], fn);
  942. cur = graph[cur].parent;
  943. }
  944. fn.conversion = path;
  945. return fn;
  946. }
  947. var route = function (fromModel) {
  948. var graph = deriveBFS(fromModel);
  949. var conversion = {};
  950. var models = Object.keys(graph);
  951. for (var len = models.length, i = 0; i < len; i++) {
  952. var toModel = models[i];
  953. var node = graph[toModel];
  954. if (node.parent === null) {
  955. // no possible conversion, or this node is the source model.
  956. continue;
  957. }
  958. conversion[toModel] = wrapConversion(toModel, graph);
  959. }
  960. return conversion;
  961. };
  962. var convert = {};
  963. var models = Object.keys(conversions);
  964. function wrapRaw(fn) {
  965. var wrappedFn = function (args) {
  966. if (args === undefined || args === null) {
  967. return args;
  968. }
  969. if (arguments.length > 1) {
  970. args = Array.prototype.slice.call(arguments);
  971. }
  972. return fn(args);
  973. };
  974. // preserve .conversion property if there is one
  975. if ('conversion' in fn) {
  976. wrappedFn.conversion = fn.conversion;
  977. }
  978. return wrappedFn;
  979. }
  980. function wrapRounded(fn) {
  981. var wrappedFn = function (args) {
  982. if (args === undefined || args === null) {
  983. return args;
  984. }
  985. if (arguments.length > 1) {
  986. args = Array.prototype.slice.call(arguments);
  987. }
  988. var result = fn(args);
  989. // we're assuming the result is an array here.
  990. // see notice in conversions.js; don't use box types
  991. // in conversion functions.
  992. if (typeof result === 'object') {
  993. for (var len = result.length, i = 0; i < len; i++) {
  994. result[i] = Math.round(result[i]);
  995. }
  996. }
  997. return result;
  998. };
  999. // preserve .conversion property if there is one
  1000. if ('conversion' in fn) {
  1001. wrappedFn.conversion = fn.conversion;
  1002. }
  1003. return wrappedFn;
  1004. }
  1005. models.forEach(function (fromModel) {
  1006. convert[fromModel] = {};
  1007. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  1008. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  1009. var routes = route(fromModel);
  1010. var routeModels = Object.keys(routes);
  1011. routeModels.forEach(function (toModel) {
  1012. var fn = routes[toModel];
  1013. convert[fromModel][toModel] = wrapRounded(fn);
  1014. convert[fromModel][toModel].raw = wrapRaw(fn);
  1015. });
  1016. });
  1017. var colorConvert = convert;
  1018. var colorName$1 = {
  1019. "aliceblue": [240, 248, 255],
  1020. "antiquewhite": [250, 235, 215],
  1021. "aqua": [0, 255, 255],
  1022. "aquamarine": [127, 255, 212],
  1023. "azure": [240, 255, 255],
  1024. "beige": [245, 245, 220],
  1025. "bisque": [255, 228, 196],
  1026. "black": [0, 0, 0],
  1027. "blanchedalmond": [255, 235, 205],
  1028. "blue": [0, 0, 255],
  1029. "blueviolet": [138, 43, 226],
  1030. "brown": [165, 42, 42],
  1031. "burlywood": [222, 184, 135],
  1032. "cadetblue": [95, 158, 160],
  1033. "chartreuse": [127, 255, 0],
  1034. "chocolate": [210, 105, 30],
  1035. "coral": [255, 127, 80],
  1036. "cornflowerblue": [100, 149, 237],
  1037. "cornsilk": [255, 248, 220],
  1038. "crimson": [220, 20, 60],
  1039. "cyan": [0, 255, 255],
  1040. "darkblue": [0, 0, 139],
  1041. "darkcyan": [0, 139, 139],
  1042. "darkgoldenrod": [184, 134, 11],
  1043. "darkgray": [169, 169, 169],
  1044. "darkgreen": [0, 100, 0],
  1045. "darkgrey": [169, 169, 169],
  1046. "darkkhaki": [189, 183, 107],
  1047. "darkmagenta": [139, 0, 139],
  1048. "darkolivegreen": [85, 107, 47],
  1049. "darkorange": [255, 140, 0],
  1050. "darkorchid": [153, 50, 204],
  1051. "darkred": [139, 0, 0],
  1052. "darksalmon": [233, 150, 122],
  1053. "darkseagreen": [143, 188, 143],
  1054. "darkslateblue": [72, 61, 139],
  1055. "darkslategray": [47, 79, 79],
  1056. "darkslategrey": [47, 79, 79],
  1057. "darkturquoise": [0, 206, 209],
  1058. "darkviolet": [148, 0, 211],
  1059. "deeppink": [255, 20, 147],
  1060. "deepskyblue": [0, 191, 255],
  1061. "dimgray": [105, 105, 105],
  1062. "dimgrey": [105, 105, 105],
  1063. "dodgerblue": [30, 144, 255],
  1064. "firebrick": [178, 34, 34],
  1065. "floralwhite": [255, 250, 240],
  1066. "forestgreen": [34, 139, 34],
  1067. "fuchsia": [255, 0, 255],
  1068. "gainsboro": [220, 220, 220],
  1069. "ghostwhite": [248, 248, 255],
  1070. "gold": [255, 215, 0],
  1071. "goldenrod": [218, 165, 32],
  1072. "gray": [128, 128, 128],
  1073. "green": [0, 128, 0],
  1074. "greenyellow": [173, 255, 47],
  1075. "grey": [128, 128, 128],
  1076. "honeydew": [240, 255, 240],
  1077. "hotpink": [255, 105, 180],
  1078. "indianred": [205, 92, 92],
  1079. "indigo": [75, 0, 130],
  1080. "ivory": [255, 255, 240],
  1081. "khaki": [240, 230, 140],
  1082. "lavender": [230, 230, 250],
  1083. "lavenderblush": [255, 240, 245],
  1084. "lawngreen": [124, 252, 0],
  1085. "lemonchiffon": [255, 250, 205],
  1086. "lightblue": [173, 216, 230],
  1087. "lightcoral": [240, 128, 128],
  1088. "lightcyan": [224, 255, 255],
  1089. "lightgoldenrodyellow": [250, 250, 210],
  1090. "lightgray": [211, 211, 211],
  1091. "lightgreen": [144, 238, 144],
  1092. "lightgrey": [211, 211, 211],
  1093. "lightpink": [255, 182, 193],
  1094. "lightsalmon": [255, 160, 122],
  1095. "lightseagreen": [32, 178, 170],
  1096. "lightskyblue": [135, 206, 250],
  1097. "lightslategray": [119, 136, 153],
  1098. "lightslategrey": [119, 136, 153],
  1099. "lightsteelblue": [176, 196, 222],
  1100. "lightyellow": [255, 255, 224],
  1101. "lime": [0, 255, 0],
  1102. "limegreen": [50, 205, 50],
  1103. "linen": [250, 240, 230],
  1104. "magenta": [255, 0, 255],
  1105. "maroon": [128, 0, 0],
  1106. "mediumaquamarine": [102, 205, 170],
  1107. "mediumblue": [0, 0, 205],
  1108. "mediumorchid": [186, 85, 211],
  1109. "mediumpurple": [147, 112, 219],
  1110. "mediumseagreen": [60, 179, 113],
  1111. "mediumslateblue": [123, 104, 238],
  1112. "mediumspringgreen": [0, 250, 154],
  1113. "mediumturquoise": [72, 209, 204],
  1114. "mediumvioletred": [199, 21, 133],
  1115. "midnightblue": [25, 25, 112],
  1116. "mintcream": [245, 255, 250],
  1117. "mistyrose": [255, 228, 225],
  1118. "moccasin": [255, 228, 181],
  1119. "navajowhite": [255, 222, 173],
  1120. "navy": [0, 0, 128],
  1121. "oldlace": [253, 245, 230],
  1122. "olive": [128, 128, 0],
  1123. "olivedrab": [107, 142, 35],
  1124. "orange": [255, 165, 0],
  1125. "orangered": [255, 69, 0],
  1126. "orchid": [218, 112, 214],
  1127. "palegoldenrod": [238, 232, 170],
  1128. "palegreen": [152, 251, 152],
  1129. "paleturquoise": [175, 238, 238],
  1130. "palevioletred": [219, 112, 147],
  1131. "papayawhip": [255, 239, 213],
  1132. "peachpuff": [255, 218, 185],
  1133. "peru": [205, 133, 63],
  1134. "pink": [255, 192, 203],
  1135. "plum": [221, 160, 221],
  1136. "powderblue": [176, 224, 230],
  1137. "purple": [128, 0, 128],
  1138. "rebeccapurple": [102, 51, 153],
  1139. "red": [255, 0, 0],
  1140. "rosybrown": [188, 143, 143],
  1141. "royalblue": [65, 105, 225],
  1142. "saddlebrown": [139, 69, 19],
  1143. "salmon": [250, 128, 114],
  1144. "sandybrown": [244, 164, 96],
  1145. "seagreen": [46, 139, 87],
  1146. "seashell": [255, 245, 238],
  1147. "sienna": [160, 82, 45],
  1148. "silver": [192, 192, 192],
  1149. "skyblue": [135, 206, 235],
  1150. "slateblue": [106, 90, 205],
  1151. "slategray": [112, 128, 144],
  1152. "slategrey": [112, 128, 144],
  1153. "snow": [255, 250, 250],
  1154. "springgreen": [0, 255, 127],
  1155. "steelblue": [70, 130, 180],
  1156. "tan": [210, 180, 140],
  1157. "teal": [0, 128, 128],
  1158. "thistle": [216, 191, 216],
  1159. "tomato": [255, 99, 71],
  1160. "turquoise": [64, 224, 208],
  1161. "violet": [238, 130, 238],
  1162. "wheat": [245, 222, 179],
  1163. "white": [255, 255, 255],
  1164. "whitesmoke": [245, 245, 245],
  1165. "yellow": [255, 255, 0],
  1166. "yellowgreen": [154, 205, 50]
  1167. };
  1168. /* MIT license */
  1169. var colorString = {
  1170. getRgba: getRgba,
  1171. getHsla: getHsla,
  1172. getRgb: getRgb,
  1173. getHsl: getHsl,
  1174. getHwb: getHwb,
  1175. getAlpha: getAlpha,
  1176. hexString: hexString,
  1177. rgbString: rgbString,
  1178. rgbaString: rgbaString,
  1179. percentString: percentString,
  1180. percentaString: percentaString,
  1181. hslString: hslString,
  1182. hslaString: hslaString,
  1183. hwbString: hwbString,
  1184. keyword: keyword
  1185. };
  1186. function getRgba(string) {
  1187. if (!string) {
  1188. return;
  1189. }
  1190. var abbr = /^#([a-fA-F0-9]{3,4})$/i,
  1191. hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i,
  1192. rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  1193. per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  1194. keyword = /(\w+)/;
  1195. var rgb = [0, 0, 0],
  1196. a = 1,
  1197. match = string.match(abbr),
  1198. hexAlpha = "";
  1199. if (match) {
  1200. match = match[1];
  1201. hexAlpha = match[3];
  1202. for (var i = 0; i < rgb.length; i++) {
  1203. rgb[i] = parseInt(match[i] + match[i], 16);
  1204. }
  1205. if (hexAlpha) {
  1206. a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100;
  1207. }
  1208. }
  1209. else if (match = string.match(hex)) {
  1210. hexAlpha = match[2];
  1211. match = match[1];
  1212. for (var i = 0; i < rgb.length; i++) {
  1213. rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
  1214. }
  1215. if (hexAlpha) {
  1216. a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100;
  1217. }
  1218. }
  1219. else if (match = string.match(rgba)) {
  1220. for (var i = 0; i < rgb.length; i++) {
  1221. rgb[i] = parseInt(match[i + 1]);
  1222. }
  1223. a = parseFloat(match[4]);
  1224. }
  1225. else if (match = string.match(per)) {
  1226. for (var i = 0; i < rgb.length; i++) {
  1227. rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
  1228. }
  1229. a = parseFloat(match[4]);
  1230. }
  1231. else if (match = string.match(keyword)) {
  1232. if (match[1] == "transparent") {
  1233. return [0, 0, 0, 0];
  1234. }
  1235. rgb = colorName$1[match[1]];
  1236. if (!rgb) {
  1237. return;
  1238. }
  1239. }
  1240. for (var i = 0; i < rgb.length; i++) {
  1241. rgb[i] = scale(rgb[i], 0, 255);
  1242. }
  1243. if (!a && a != 0) {
  1244. a = 1;
  1245. }
  1246. else {
  1247. a = scale(a, 0, 1);
  1248. }
  1249. rgb[3] = a;
  1250. return rgb;
  1251. }
  1252. function getHsla(string) {
  1253. if (!string) {
  1254. return;
  1255. }
  1256. var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  1257. var match = string.match(hsl);
  1258. if (match) {
  1259. var alpha = parseFloat(match[4]);
  1260. var h = scale(parseInt(match[1]), 0, 360),
  1261. s = scale(parseFloat(match[2]), 0, 100),
  1262. l = scale(parseFloat(match[3]), 0, 100),
  1263. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  1264. return [h, s, l, a];
  1265. }
  1266. }
  1267. function getHwb(string) {
  1268. if (!string) {
  1269. return;
  1270. }
  1271. var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  1272. var match = string.match(hwb);
  1273. if (match) {
  1274. var alpha = parseFloat(match[4]);
  1275. var h = scale(parseInt(match[1]), 0, 360),
  1276. w = scale(parseFloat(match[2]), 0, 100),
  1277. b = scale(parseFloat(match[3]), 0, 100),
  1278. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  1279. return [h, w, b, a];
  1280. }
  1281. }
  1282. function getRgb(string) {
  1283. var rgba = getRgba(string);
  1284. return rgba && rgba.slice(0, 3);
  1285. }
  1286. function getHsl(string) {
  1287. var hsla = getHsla(string);
  1288. return hsla && hsla.slice(0, 3);
  1289. }
  1290. function getAlpha(string) {
  1291. var vals = getRgba(string);
  1292. if (vals) {
  1293. return vals[3];
  1294. }
  1295. else if (vals = getHsla(string)) {
  1296. return vals[3];
  1297. }
  1298. else if (vals = getHwb(string)) {
  1299. return vals[3];
  1300. }
  1301. }
  1302. // generators
  1303. function hexString(rgba, a) {
  1304. var a = (a !== undefined && rgba.length === 3) ? a : rgba[3];
  1305. return "#" + hexDouble(rgba[0])
  1306. + hexDouble(rgba[1])
  1307. + hexDouble(rgba[2])
  1308. + (
  1309. (a >= 0 && a < 1)
  1310. ? hexDouble(Math.round(a * 255))
  1311. : ""
  1312. );
  1313. }
  1314. function rgbString(rgba, alpha) {
  1315. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  1316. return rgbaString(rgba, alpha);
  1317. }
  1318. return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
  1319. }
  1320. function rgbaString(rgba, alpha) {
  1321. if (alpha === undefined) {
  1322. alpha = (rgba[3] !== undefined ? rgba[3] : 1);
  1323. }
  1324. return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
  1325. + ", " + alpha + ")";
  1326. }
  1327. function percentString(rgba, alpha) {
  1328. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  1329. return percentaString(rgba, alpha);
  1330. }
  1331. var r = Math.round(rgba[0]/255 * 100),
  1332. g = Math.round(rgba[1]/255 * 100),
  1333. b = Math.round(rgba[2]/255 * 100);
  1334. return "rgb(" + r + "%, " + g + "%, " + b + "%)";
  1335. }
  1336. function percentaString(rgba, alpha) {
  1337. var r = Math.round(rgba[0]/255 * 100),
  1338. g = Math.round(rgba[1]/255 * 100),
  1339. b = Math.round(rgba[2]/255 * 100);
  1340. return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
  1341. }
  1342. function hslString(hsla, alpha) {
  1343. if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
  1344. return hslaString(hsla, alpha);
  1345. }
  1346. return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
  1347. }
  1348. function hslaString(hsla, alpha) {
  1349. if (alpha === undefined) {
  1350. alpha = (hsla[3] !== undefined ? hsla[3] : 1);
  1351. }
  1352. return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
  1353. + alpha + ")";
  1354. }
  1355. // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
  1356. // (hwb have alpha optional & 1 is default value)
  1357. function hwbString(hwb, alpha) {
  1358. if (alpha === undefined) {
  1359. alpha = (hwb[3] !== undefined ? hwb[3] : 1);
  1360. }
  1361. return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
  1362. + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
  1363. }
  1364. function keyword(rgb) {
  1365. return reverseNames[rgb.slice(0, 3)];
  1366. }
  1367. // helpers
  1368. function scale(num, min, max) {
  1369. return Math.min(Math.max(min, num), max);
  1370. }
  1371. function hexDouble(num) {
  1372. var str = num.toString(16).toUpperCase();
  1373. return (str.length < 2) ? "0" + str : str;
  1374. }
  1375. //create a list of reverse color names
  1376. var reverseNames = {};
  1377. for (var name in colorName$1) {
  1378. reverseNames[colorName$1[name]] = name;
  1379. }
  1380. /* MIT license */
  1381. var Color = function (obj) {
  1382. if (obj instanceof Color) {
  1383. return obj;
  1384. }
  1385. if (!(this instanceof Color)) {
  1386. return new Color(obj);
  1387. }
  1388. this.valid = false;
  1389. this.values = {
  1390. rgb: [0, 0, 0],
  1391. hsl: [0, 0, 0],
  1392. hsv: [0, 0, 0],
  1393. hwb: [0, 0, 0],
  1394. cmyk: [0, 0, 0, 0],
  1395. alpha: 1
  1396. };
  1397. // parse Color() argument
  1398. var vals;
  1399. if (typeof obj === 'string') {
  1400. vals = colorString.getRgba(obj);
  1401. if (vals) {
  1402. this.setValues('rgb', vals);
  1403. } else if (vals = colorString.getHsla(obj)) {
  1404. this.setValues('hsl', vals);
  1405. } else if (vals = colorString.getHwb(obj)) {
  1406. this.setValues('hwb', vals);
  1407. }
  1408. } else if (typeof obj === 'object') {
  1409. vals = obj;
  1410. if (vals.r !== undefined || vals.red !== undefined) {
  1411. this.setValues('rgb', vals);
  1412. } else if (vals.l !== undefined || vals.lightness !== undefined) {
  1413. this.setValues('hsl', vals);
  1414. } else if (vals.v !== undefined || vals.value !== undefined) {
  1415. this.setValues('hsv', vals);
  1416. } else if (vals.w !== undefined || vals.whiteness !== undefined) {
  1417. this.setValues('hwb', vals);
  1418. } else if (vals.c !== undefined || vals.cyan !== undefined) {
  1419. this.setValues('cmyk', vals);
  1420. }
  1421. }
  1422. };
  1423. Color.prototype = {
  1424. isValid: function () {
  1425. return this.valid;
  1426. },
  1427. rgb: function () {
  1428. return this.setSpace('rgb', arguments);
  1429. },
  1430. hsl: function () {
  1431. return this.setSpace('hsl', arguments);
  1432. },
  1433. hsv: function () {
  1434. return this.setSpace('hsv', arguments);
  1435. },
  1436. hwb: function () {
  1437. return this.setSpace('hwb', arguments);
  1438. },
  1439. cmyk: function () {
  1440. return this.setSpace('cmyk', arguments);
  1441. },
  1442. rgbArray: function () {
  1443. return this.values.rgb;
  1444. },
  1445. hslArray: function () {
  1446. return this.values.hsl;
  1447. },
  1448. hsvArray: function () {
  1449. return this.values.hsv;
  1450. },
  1451. hwbArray: function () {
  1452. var values = this.values;
  1453. if (values.alpha !== 1) {
  1454. return values.hwb.concat([values.alpha]);
  1455. }
  1456. return values.hwb;
  1457. },
  1458. cmykArray: function () {
  1459. return this.values.cmyk;
  1460. },
  1461. rgbaArray: function () {
  1462. var values = this.values;
  1463. return values.rgb.concat([values.alpha]);
  1464. },
  1465. hslaArray: function () {
  1466. var values = this.values;
  1467. return values.hsl.concat([values.alpha]);
  1468. },
  1469. alpha: function (val) {
  1470. if (val === undefined) {
  1471. return this.values.alpha;
  1472. }
  1473. this.setValues('alpha', val);
  1474. return this;
  1475. },
  1476. red: function (val) {
  1477. return this.setChannel('rgb', 0, val);
  1478. },
  1479. green: function (val) {
  1480. return this.setChannel('rgb', 1, val);
  1481. },
  1482. blue: function (val) {
  1483. return this.setChannel('rgb', 2, val);
  1484. },
  1485. hue: function (val) {
  1486. if (val) {
  1487. val %= 360;
  1488. val = val < 0 ? 360 + val : val;
  1489. }
  1490. return this.setChannel('hsl', 0, val);
  1491. },
  1492. saturation: function (val) {
  1493. return this.setChannel('hsl', 1, val);
  1494. },
  1495. lightness: function (val) {
  1496. return this.setChannel('hsl', 2, val);
  1497. },
  1498. saturationv: function (val) {
  1499. return this.setChannel('hsv', 1, val);
  1500. },
  1501. whiteness: function (val) {
  1502. return this.setChannel('hwb', 1, val);
  1503. },
  1504. blackness: function (val) {
  1505. return this.setChannel('hwb', 2, val);
  1506. },
  1507. value: function (val) {
  1508. return this.setChannel('hsv', 2, val);
  1509. },
  1510. cyan: function (val) {
  1511. return this.setChannel('cmyk', 0, val);
  1512. },
  1513. magenta: function (val) {
  1514. return this.setChannel('cmyk', 1, val);
  1515. },
  1516. yellow: function (val) {
  1517. return this.setChannel('cmyk', 2, val);
  1518. },
  1519. black: function (val) {
  1520. return this.setChannel('cmyk', 3, val);
  1521. },
  1522. hexString: function () {
  1523. return colorString.hexString(this.values.rgb);
  1524. },
  1525. rgbString: function () {
  1526. return colorString.rgbString(this.values.rgb, this.values.alpha);
  1527. },
  1528. rgbaString: function () {
  1529. return colorString.rgbaString(this.values.rgb, this.values.alpha);
  1530. },
  1531. percentString: function () {
  1532. return colorString.percentString(this.values.rgb, this.values.alpha);
  1533. },
  1534. hslString: function () {
  1535. return colorString.hslString(this.values.hsl, this.values.alpha);
  1536. },
  1537. hslaString: function () {
  1538. return colorString.hslaString(this.values.hsl, this.values.alpha);
  1539. },
  1540. hwbString: function () {
  1541. return colorString.hwbString(this.values.hwb, this.values.alpha);
  1542. },
  1543. keyword: function () {
  1544. return colorString.keyword(this.values.rgb, this.values.alpha);
  1545. },
  1546. rgbNumber: function () {
  1547. var rgb = this.values.rgb;
  1548. return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
  1549. },
  1550. luminosity: function () {
  1551. // http://www.w3.org/TR/WCAG20/#relativeluminancedef
  1552. var rgb = this.values.rgb;
  1553. var lum = [];
  1554. for (var i = 0; i < rgb.length; i++) {
  1555. var chan = rgb[i] / 255;
  1556. lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
  1557. }
  1558. return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  1559. },
  1560. contrast: function (color2) {
  1561. // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  1562. var lum1 = this.luminosity();
  1563. var lum2 = color2.luminosity();
  1564. if (lum1 > lum2) {
  1565. return (lum1 + 0.05) / (lum2 + 0.05);
  1566. }
  1567. return (lum2 + 0.05) / (lum1 + 0.05);
  1568. },
  1569. level: function (color2) {
  1570. var contrastRatio = this.contrast(color2);
  1571. if (contrastRatio >= 7.1) {
  1572. return 'AAA';
  1573. }
  1574. return (contrastRatio >= 4.5) ? 'AA' : '';
  1575. },
  1576. dark: function () {
  1577. // YIQ equation from http://24ways.org/2010/calculating-color-contrast
  1578. var rgb = this.values.rgb;
  1579. var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
  1580. return yiq < 128;
  1581. },
  1582. light: function () {
  1583. return !this.dark();
  1584. },
  1585. negate: function () {
  1586. var rgb = [];
  1587. for (var i = 0; i < 3; i++) {
  1588. rgb[i] = 255 - this.values.rgb[i];
  1589. }
  1590. this.setValues('rgb', rgb);
  1591. return this;
  1592. },
  1593. lighten: function (ratio) {
  1594. var hsl = this.values.hsl;
  1595. hsl[2] += hsl[2] * ratio;
  1596. this.setValues('hsl', hsl);
  1597. return this;
  1598. },
  1599. darken: function (ratio) {
  1600. var hsl = this.values.hsl;
  1601. hsl[2] -= hsl[2] * ratio;
  1602. this.setValues('hsl', hsl);
  1603. return this;
  1604. },
  1605. saturate: function (ratio) {
  1606. var hsl = this.values.hsl;
  1607. hsl[1] += hsl[1] * ratio;
  1608. this.setValues('hsl', hsl);
  1609. return this;
  1610. },
  1611. desaturate: function (ratio) {
  1612. var hsl = this.values.hsl;
  1613. hsl[1] -= hsl[1] * ratio;
  1614. this.setValues('hsl', hsl);
  1615. return this;
  1616. },
  1617. whiten: function (ratio) {
  1618. var hwb = this.values.hwb;
  1619. hwb[1] += hwb[1] * ratio;
  1620. this.setValues('hwb', hwb);
  1621. return this;
  1622. },
  1623. blacken: function (ratio) {
  1624. var hwb = this.values.hwb;
  1625. hwb[2] += hwb[2] * ratio;
  1626. this.setValues('hwb', hwb);
  1627. return this;
  1628. },
  1629. greyscale: function () {
  1630. var rgb = this.values.rgb;
  1631. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  1632. var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
  1633. this.setValues('rgb', [val, val, val]);
  1634. return this;
  1635. },
  1636. clearer: function (ratio) {
  1637. var alpha = this.values.alpha;
  1638. this.setValues('alpha', alpha - (alpha * ratio));
  1639. return this;
  1640. },
  1641. opaquer: function (ratio) {
  1642. var alpha = this.values.alpha;
  1643. this.setValues('alpha', alpha + (alpha * ratio));
  1644. return this;
  1645. },
  1646. rotate: function (degrees) {
  1647. var hsl = this.values.hsl;
  1648. var hue = (hsl[0] + degrees) % 360;
  1649. hsl[0] = hue < 0 ? 360 + hue : hue;
  1650. this.setValues('hsl', hsl);
  1651. return this;
  1652. },
  1653. /**
  1654. * Ported from sass implementation in C
  1655. * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
  1656. */
  1657. mix: function (mixinColor, weight) {
  1658. var color1 = this;
  1659. var color2 = mixinColor;
  1660. var p = weight === undefined ? 0.5 : weight;
  1661. var w = 2 * p - 1;
  1662. var a = color1.alpha() - color2.alpha();
  1663. var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  1664. var w2 = 1 - w1;
  1665. return this
  1666. .rgb(
  1667. w1 * color1.red() + w2 * color2.red(),
  1668. w1 * color1.green() + w2 * color2.green(),
  1669. w1 * color1.blue() + w2 * color2.blue()
  1670. )
  1671. .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
  1672. },
  1673. toJSON: function () {
  1674. return this.rgb();
  1675. },
  1676. clone: function () {
  1677. // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
  1678. // making the final build way to big to embed in Chart.js. So let's do it manually,
  1679. // assuming that values to clone are 1 dimension arrays containing only numbers,
  1680. // except 'alpha' which is a number.
  1681. var result = new Color();
  1682. var source = this.values;
  1683. var target = result.values;
  1684. var value, type;
  1685. for (var prop in source) {
  1686. if (source.hasOwnProperty(prop)) {
  1687. value = source[prop];
  1688. type = ({}).toString.call(value);
  1689. if (type === '[object Array]') {
  1690. target[prop] = value.slice(0);
  1691. } else if (type === '[object Number]') {
  1692. target[prop] = value;
  1693. } else {
  1694. console.error('unexpected color value:', value);
  1695. }
  1696. }
  1697. }
  1698. return result;
  1699. }
  1700. };
  1701. Color.prototype.spaces = {
  1702. rgb: ['red', 'green', 'blue'],
  1703. hsl: ['hue', 'saturation', 'lightness'],
  1704. hsv: ['hue', 'saturation', 'value'],
  1705. hwb: ['hue', 'whiteness', 'blackness'],
  1706. cmyk: ['cyan', 'magenta', 'yellow', 'black']
  1707. };
  1708. Color.prototype.maxes = {
  1709. rgb: [255, 255, 255],
  1710. hsl: [360, 100, 100],
  1711. hsv: [360, 100, 100],
  1712. hwb: [360, 100, 100],
  1713. cmyk: [100, 100, 100, 100]
  1714. };
  1715. Color.prototype.getValues = function (space) {
  1716. var values = this.values;
  1717. var vals = {};
  1718. for (var i = 0; i < space.length; i++) {
  1719. vals[space.charAt(i)] = values[space][i];
  1720. }
  1721. if (values.alpha !== 1) {
  1722. vals.a = values.alpha;
  1723. }
  1724. // {r: 255, g: 255, b: 255, a: 0.4}
  1725. return vals;
  1726. };
  1727. Color.prototype.setValues = function (space, vals) {
  1728. var values = this.values;
  1729. var spaces = this.spaces;
  1730. var maxes = this.maxes;
  1731. var alpha = 1;
  1732. var i;
  1733. this.valid = true;
  1734. if (space === 'alpha') {
  1735. alpha = vals;
  1736. } else if (vals.length) {
  1737. // [10, 10, 10]
  1738. values[space] = vals.slice(0, space.length);
  1739. alpha = vals[space.length];
  1740. } else if (vals[space.charAt(0)] !== undefined) {
  1741. // {r: 10, g: 10, b: 10}
  1742. for (i = 0; i < space.length; i++) {
  1743. values[space][i] = vals[space.charAt(i)];
  1744. }
  1745. alpha = vals.a;
  1746. } else if (vals[spaces[space][0]] !== undefined) {
  1747. // {red: 10, green: 10, blue: 10}
  1748. var chans = spaces[space];
  1749. for (i = 0; i < space.length; i++) {
  1750. values[space][i] = vals[chans[i]];
  1751. }
  1752. alpha = vals.alpha;
  1753. }
  1754. values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
  1755. if (space === 'alpha') {
  1756. return false;
  1757. }
  1758. var capped;
  1759. // cap values of the space prior converting all values
  1760. for (i = 0; i < space.length; i++) {
  1761. capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
  1762. values[space][i] = Math.round(capped);
  1763. }
  1764. // convert to all the other color spaces
  1765. for (var sname in spaces) {
  1766. if (sname !== space) {
  1767. values[sname] = colorConvert[space][sname](values[space]);
  1768. }
  1769. }
  1770. return true;
  1771. };
  1772. Color.prototype.setSpace = function (space, args) {
  1773. var vals = args[0];
  1774. if (vals === undefined) {
  1775. // color.rgb()
  1776. return this.getValues(space);
  1777. }
  1778. // color.rgb(10, 10, 10)
  1779. if (typeof vals === 'number') {
  1780. vals = Array.prototype.slice.call(args);
  1781. }
  1782. this.setValues(space, vals);
  1783. return this;
  1784. };
  1785. Color.prototype.setChannel = function (space, index, val) {
  1786. var svalues = this.values[space];
  1787. if (val === undefined) {
  1788. // color.red()
  1789. return svalues[index];
  1790. } else if (val === svalues[index]) {
  1791. // color.red(color.red())
  1792. return this;
  1793. }
  1794. // color.red(100)
  1795. svalues[index] = val;
  1796. this.setValues(space, svalues);
  1797. return this;
  1798. };
  1799. if (typeof window !== 'undefined') {
  1800. window.Color = Color;
  1801. }
  1802. var chartjsColor = Color;
  1803. function isValidKey(key) {
  1804. return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1;
  1805. }
  1806. /**
  1807. * @namespace Chart.helpers
  1808. */
  1809. var helpers = {
  1810. /**
  1811. * An empty function that can be used, for example, for optional callback.
  1812. */
  1813. noop: function() {},
  1814. /**
  1815. * Returns a unique id, sequentially generated from a global variable.
  1816. * @returns {number}
  1817. * @function
  1818. */
  1819. uid: (function() {
  1820. var id = 0;
  1821. return function() {
  1822. return id++;
  1823. };
  1824. }()),
  1825. /**
  1826. * Returns true if `value` is neither null nor undefined, else returns false.
  1827. * @param {*} value - The value to test.
  1828. * @returns {boolean}
  1829. * @since 2.7.0
  1830. */
  1831. isNullOrUndef: function(value) {
  1832. return value === null || typeof value === 'undefined';
  1833. },
  1834. /**
  1835. * Returns true if `value` is an array (including typed arrays), else returns false.
  1836. * @param {*} value - The value to test.
  1837. * @returns {boolean}
  1838. * @function
  1839. */
  1840. isArray: function(value) {
  1841. if (Array.isArray && Array.isArray(value)) {
  1842. return true;
  1843. }
  1844. var type = Object.prototype.toString.call(value);
  1845. if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
  1846. return true;
  1847. }
  1848. return false;
  1849. },
  1850. /**
  1851. * Returns true if `value` is an object (excluding null), else returns false.
  1852. * @param {*} value - The value to test.
  1853. * @returns {boolean}
  1854. * @since 2.7.0
  1855. */
  1856. isObject: function(value) {
  1857. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  1858. },
  1859. /**
  1860. * Returns true if `value` is a finite number, else returns false
  1861. * @param {*} value - The value to test.
  1862. * @returns {boolean}
  1863. */
  1864. isFinite: function(value) {
  1865. return (typeof value === 'number' || value instanceof Number) && isFinite(value);
  1866. },
  1867. /**
  1868. * Returns `value` if defined, else returns `defaultValue`.
  1869. * @param {*} value - The value to return if defined.
  1870. * @param {*} defaultValue - The value to return if `value` is undefined.
  1871. * @returns {*}
  1872. */
  1873. valueOrDefault: function(value, defaultValue) {
  1874. return typeof value === 'undefined' ? defaultValue : value;
  1875. },
  1876. /**
  1877. * Returns value at the given `index` in array if defined, else returns `defaultValue`.
  1878. * @param {Array} value - The array to lookup for value at `index`.
  1879. * @param {number} index - The index in `value` to lookup for value.
  1880. * @param {*} defaultValue - The value to return if `value[index]` is undefined.
  1881. * @returns {*}
  1882. */
  1883. valueAtIndexOrDefault: function(value, index, defaultValue) {
  1884. return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
  1885. },
  1886. /**
  1887. * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
  1888. * value returned by `fn`. If `fn` is not a function, this method returns undefined.
  1889. * @param {function} fn - The function to call.
  1890. * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
  1891. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1892. * @returns {*}
  1893. */
  1894. callback: function(fn, args, thisArg) {
  1895. if (fn && typeof fn.call === 'function') {
  1896. return fn.apply(thisArg, args);
  1897. }
  1898. },
  1899. /**
  1900. * Note(SB) for performance sake, this method should only be used when loopable type
  1901. * is unknown or in none intensive code (not called often and small loopable). Else
  1902. * it's preferable to use a regular for() loop and save extra function calls.
  1903. * @param {object|Array} loopable - The object or array to be iterated.
  1904. * @param {function} fn - The function to call for each item.
  1905. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1906. * @param {boolean} [reverse] - If true, iterates backward on the loopable.
  1907. */
  1908. each: function(loopable, fn, thisArg, reverse) {
  1909. var i, len, keys;
  1910. if (helpers.isArray(loopable)) {
  1911. len = loopable.length;
  1912. if (reverse) {
  1913. for (i = len - 1; i >= 0; i--) {
  1914. fn.call(thisArg, loopable[i], i);
  1915. }
  1916. } else {
  1917. for (i = 0; i < len; i++) {
  1918. fn.call(thisArg, loopable[i], i);
  1919. }
  1920. }
  1921. } else if (helpers.isObject(loopable)) {
  1922. keys = Object.keys(loopable);
  1923. len = keys.length;
  1924. for (i = 0; i < len; i++) {
  1925. fn.call(thisArg, loopable[keys[i]], keys[i]);
  1926. }
  1927. }
  1928. },
  1929. /**
  1930. * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
  1931. * @see https://stackoverflow.com/a/14853974
  1932. * @param {Array} a0 - The array to compare
  1933. * @param {Array} a1 - The array to compare
  1934. * @returns {boolean}
  1935. */
  1936. arrayEquals: function(a0, a1) {
  1937. var i, ilen, v0, v1;
  1938. if (!a0 || !a1 || a0.length !== a1.length) {
  1939. return false;
  1940. }
  1941. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  1942. v0 = a0[i];
  1943. v1 = a1[i];
  1944. if (v0 instanceof Array && v1 instanceof Array) {
  1945. if (!helpers.arrayEquals(v0, v1)) {
  1946. return false;
  1947. }
  1948. } else if (v0 !== v1) {
  1949. // NOTE: two different object instances will never be equal: {x:20} != {x:20}
  1950. return false;
  1951. }
  1952. }
  1953. return true;
  1954. },
  1955. /**
  1956. * Returns a deep copy of `source` without keeping references on objects and arrays.
  1957. * @param {*} source - The value to clone.
  1958. * @returns {*}
  1959. */
  1960. clone: function(source) {
  1961. if (helpers.isArray(source)) {
  1962. return source.map(helpers.clone);
  1963. }
  1964. if (helpers.isObject(source)) {
  1965. var target = Object.create(source);
  1966. var keys = Object.keys(source);
  1967. var klen = keys.length;
  1968. var k = 0;
  1969. for (; k < klen; ++k) {
  1970. target[keys[k]] = helpers.clone(source[keys[k]]);
  1971. }
  1972. return target;
  1973. }
  1974. return source;
  1975. },
  1976. /**
  1977. * The default merger when Chart.helpers.merge is called without merger option.
  1978. * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
  1979. * @private
  1980. */
  1981. _merger: function(key, target, source, options) {
  1982. if (!isValidKey(key)) {
  1983. // We want to ensure we do not copy prototypes over
  1984. // as this can pollute global namespaces
  1985. return;
  1986. }
  1987. var tval = target[key];
  1988. var sval = source[key];
  1989. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1990. helpers.merge(tval, sval, options);
  1991. } else {
  1992. target[key] = helpers.clone(sval);
  1993. }
  1994. },
  1995. /**
  1996. * Merges source[key] in target[key] only if target[key] is undefined.
  1997. * @private
  1998. */
  1999. _mergerIf: function(key, target, source) {
  2000. if (!isValidKey(key)) {
  2001. // We want to ensure we do not copy prototypes over
  2002. // as this can pollute global namespaces
  2003. return;
  2004. }
  2005. var tval = target[key];
  2006. var sval = source[key];
  2007. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  2008. helpers.mergeIf(tval, sval);
  2009. } else if (!target.hasOwnProperty(key)) {
  2010. target[key] = helpers.clone(sval);
  2011. }
  2012. },
  2013. /**
  2014. * Recursively deep copies `source` properties into `target` with the given `options`.
  2015. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  2016. * @param {object} target - The target object in which all sources are merged into.
  2017. * @param {object|object[]} source - Object(s) to merge into `target`.
  2018. * @param {object} [options] - Merging options:
  2019. * @param {function} [options.merger] - The merge method (key, target, source, options)
  2020. * @returns {object} The `target` object.
  2021. */
  2022. merge: function(target, source, options) {
  2023. var sources = helpers.isArray(source) ? source : [source];
  2024. var ilen = sources.length;
  2025. var merge, i, keys, klen, k;
  2026. if (!helpers.isObject(target)) {
  2027. return target;
  2028. }
  2029. options = options || {};
  2030. merge = options.merger || helpers._merger;
  2031. for (i = 0; i < ilen; ++i) {
  2032. source = sources[i];
  2033. if (!helpers.isObject(source)) {
  2034. continue;
  2035. }
  2036. keys = Object.keys(source);
  2037. for (k = 0, klen = keys.length; k < klen; ++k) {
  2038. merge(keys[k], target, source, options);
  2039. }
  2040. }
  2041. return target;
  2042. },
  2043. /**
  2044. * Recursively deep copies `source` properties into `target` *only* if not defined in target.
  2045. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  2046. * @param {object} target - The target object in which all sources are merged into.
  2047. * @param {object|object[]} source - Object(s) to merge into `target`.
  2048. * @returns {object} The `target` object.
  2049. */
  2050. mergeIf: function(target, source) {
  2051. return helpers.merge(target, source, {merger: helpers._mergerIf});
  2052. },
  2053. /**
  2054. * Applies the contents of two or more objects together into the first object.
  2055. * @param {object} target - The target object in which all objects are merged into.
  2056. * @param {object} arg1 - Object containing additional properties to merge in target.
  2057. * @param {object} argN - Additional objects containing properties to merge in target.
  2058. * @returns {object} The `target` object.
  2059. */
  2060. extend: Object.assign || function(target) {
  2061. return helpers.merge(target, [].slice.call(arguments, 1), {
  2062. merger: function(key, dst, src) {
  2063. dst[key] = src[key];
  2064. }
  2065. });
  2066. },
  2067. /**
  2068. * Basic javascript inheritance based on the model created in Backbone.js
  2069. */
  2070. inherits: function(extensions) {
  2071. var me = this;
  2072. var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
  2073. return me.apply(this, arguments);
  2074. };
  2075. var Surrogate = function() {
  2076. this.constructor = ChartElement;
  2077. };
  2078. Surrogate.prototype = me.prototype;
  2079. ChartElement.prototype = new Surrogate();
  2080. ChartElement.extend = helpers.inherits;
  2081. if (extensions) {
  2082. helpers.extend(ChartElement.prototype, extensions);
  2083. }
  2084. ChartElement.__super__ = me.prototype;
  2085. return ChartElement;
  2086. },
  2087. _deprecated: function(scope, value, previous, current) {
  2088. if (value !== undefined) {
  2089. console.warn(scope + ': "' + previous +
  2090. '" is deprecated. Please use "' + current + '" instead');
  2091. }
  2092. }
  2093. };
  2094. var helpers_core = helpers;
  2095. // DEPRECATIONS
  2096. /**
  2097. * Provided for backward compatibility, use Chart.helpers.callback instead.
  2098. * @function Chart.helpers.callCallback
  2099. * @deprecated since version 2.6.0
  2100. * @todo remove at version 3
  2101. * @private
  2102. */
  2103. helpers.callCallback = helpers.callback;
  2104. /**
  2105. * Provided for backward compatibility, use Array.prototype.indexOf instead.
  2106. * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
  2107. * @function Chart.helpers.indexOf
  2108. * @deprecated since version 2.7.0
  2109. * @todo remove at version 3
  2110. * @private
  2111. */
  2112. helpers.indexOf = function(array, item, fromIndex) {
  2113. return Array.prototype.indexOf.call(array, item, fromIndex);
  2114. };
  2115. /**
  2116. * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
  2117. * @function Chart.helpers.getValueOrDefault
  2118. * @deprecated since version 2.7.0
  2119. * @todo remove at version 3
  2120. * @private
  2121. */
  2122. helpers.getValueOrDefault = helpers.valueOrDefault;
  2123. /**
  2124. * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
  2125. * @function Chart.helpers.getValueAtIndexOrDefault
  2126. * @deprecated since version 2.7.0
  2127. * @todo remove at version 3
  2128. * @private
  2129. */
  2130. helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  2131. /**
  2132. * Easing functions adapted from Robert Penner's easing equations.
  2133. * @namespace Chart.helpers.easingEffects
  2134. * @see http://www.robertpenner.com/easing/
  2135. */
  2136. var effects = {
  2137. linear: function(t) {
  2138. return t;
  2139. },
  2140. easeInQuad: function(t) {
  2141. return t * t;
  2142. },
  2143. easeOutQuad: function(t) {
  2144. return -t * (t - 2);
  2145. },
  2146. easeInOutQuad: function(t) {
  2147. if ((t /= 0.5) < 1) {
  2148. return 0.5 * t * t;
  2149. }
  2150. return -0.5 * ((--t) * (t - 2) - 1);
  2151. },
  2152. easeInCubic: function(t) {
  2153. return t * t * t;
  2154. },
  2155. easeOutCubic: function(t) {
  2156. return (t = t - 1) * t * t + 1;
  2157. },
  2158. easeInOutCubic: function(t) {
  2159. if ((t /= 0.5) < 1) {
  2160. return 0.5 * t * t * t;
  2161. }
  2162. return 0.5 * ((t -= 2) * t * t + 2);
  2163. },
  2164. easeInQuart: function(t) {
  2165. return t * t * t * t;
  2166. },
  2167. easeOutQuart: function(t) {
  2168. return -((t = t - 1) * t * t * t - 1);
  2169. },
  2170. easeInOutQuart: function(t) {
  2171. if ((t /= 0.5) < 1) {
  2172. return 0.5 * t * t * t * t;
  2173. }
  2174. return -0.5 * ((t -= 2) * t * t * t - 2);
  2175. },
  2176. easeInQuint: function(t) {
  2177. return t * t * t * t * t;
  2178. },
  2179. easeOutQuint: function(t) {
  2180. return (t = t - 1) * t * t * t * t + 1;
  2181. },
  2182. easeInOutQuint: function(t) {
  2183. if ((t /= 0.5) < 1) {
  2184. return 0.5 * t * t * t * t * t;
  2185. }
  2186. return 0.5 * ((t -= 2) * t * t * t * t + 2);
  2187. },
  2188. easeInSine: function(t) {
  2189. return -Math.cos(t * (Math.PI / 2)) + 1;
  2190. },
  2191. easeOutSine: function(t) {
  2192. return Math.sin(t * (Math.PI / 2));
  2193. },
  2194. easeInOutSine: function(t) {
  2195. return -0.5 * (Math.cos(Math.PI * t) - 1);
  2196. },
  2197. easeInExpo: function(t) {
  2198. return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
  2199. },
  2200. easeOutExpo: function(t) {
  2201. return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
  2202. },
  2203. easeInOutExpo: function(t) {
  2204. if (t === 0) {
  2205. return 0;
  2206. }
  2207. if (t === 1) {
  2208. return 1;
  2209. }
  2210. if ((t /= 0.5) < 1) {
  2211. return 0.5 * Math.pow(2, 10 * (t - 1));
  2212. }
  2213. return 0.5 * (-Math.pow(2, -10 * --t) + 2);
  2214. },
  2215. easeInCirc: function(t) {
  2216. if (t >= 1) {
  2217. return t;
  2218. }
  2219. return -(Math.sqrt(1 - t * t) - 1);
  2220. },
  2221. easeOutCirc: function(t) {
  2222. return Math.sqrt(1 - (t = t - 1) * t);
  2223. },
  2224. easeInOutCirc: function(t) {
  2225. if ((t /= 0.5) < 1) {
  2226. return -0.5 * (Math.sqrt(1 - t * t) - 1);
  2227. }
  2228. return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  2229. },
  2230. easeInElastic: function(t) {
  2231. var s = 1.70158;
  2232. var p = 0;
  2233. var a = 1;
  2234. if (t === 0) {
  2235. return 0;
  2236. }
  2237. if (t === 1) {
  2238. return 1;
  2239. }
  2240. if (!p) {
  2241. p = 0.3;
  2242. }
  2243. if (a < 1) {
  2244. a = 1;
  2245. s = p / 4;
  2246. } else {
  2247. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2248. }
  2249. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  2250. },
  2251. easeOutElastic: function(t) {
  2252. var s = 1.70158;
  2253. var p = 0;
  2254. var a = 1;
  2255. if (t === 0) {
  2256. return 0;
  2257. }
  2258. if (t === 1) {
  2259. return 1;
  2260. }
  2261. if (!p) {
  2262. p = 0.3;
  2263. }
  2264. if (a < 1) {
  2265. a = 1;
  2266. s = p / 4;
  2267. } else {
  2268. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2269. }
  2270. return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
  2271. },
  2272. easeInOutElastic: function(t) {
  2273. var s = 1.70158;
  2274. var p = 0;
  2275. var a = 1;
  2276. if (t === 0) {
  2277. return 0;
  2278. }
  2279. if ((t /= 0.5) === 2) {
  2280. return 1;
  2281. }
  2282. if (!p) {
  2283. p = 0.45;
  2284. }
  2285. if (a < 1) {
  2286. a = 1;
  2287. s = p / 4;
  2288. } else {
  2289. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2290. }
  2291. if (t < 1) {
  2292. return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  2293. }
  2294. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2295. },
  2296. easeInBack: function(t) {
  2297. var s = 1.70158;
  2298. return t * t * ((s + 1) * t - s);
  2299. },
  2300. easeOutBack: function(t) {
  2301. var s = 1.70158;
  2302. return (t = t - 1) * t * ((s + 1) * t + s) + 1;
  2303. },
  2304. easeInOutBack: function(t) {
  2305. var s = 1.70158;
  2306. if ((t /= 0.5) < 1) {
  2307. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  2308. }
  2309. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  2310. },
  2311. easeInBounce: function(t) {
  2312. return 1 - effects.easeOutBounce(1 - t);
  2313. },
  2314. easeOutBounce: function(t) {
  2315. if (t < (1 / 2.75)) {
  2316. return 7.5625 * t * t;
  2317. }
  2318. if (t < (2 / 2.75)) {
  2319. return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
  2320. }
  2321. if (t < (2.5 / 2.75)) {
  2322. return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
  2323. }
  2324. return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
  2325. },
  2326. easeInOutBounce: function(t) {
  2327. if (t < 0.5) {
  2328. return effects.easeInBounce(t * 2) * 0.5;
  2329. }
  2330. return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
  2331. }
  2332. };
  2333. var helpers_easing = {
  2334. effects: effects
  2335. };
  2336. // DEPRECATIONS
  2337. /**
  2338. * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
  2339. * @function Chart.helpers.easingEffects
  2340. * @deprecated since version 2.7.0
  2341. * @todo remove at version 3
  2342. * @private
  2343. */
  2344. helpers_core.easingEffects = effects;
  2345. var PI = Math.PI;
  2346. var RAD_PER_DEG = PI / 180;
  2347. var DOUBLE_PI = PI * 2;
  2348. var HALF_PI = PI / 2;
  2349. var QUARTER_PI = PI / 4;
  2350. var TWO_THIRDS_PI = PI * 2 / 3;
  2351. /**
  2352. * @namespace Chart.helpers.canvas
  2353. */
  2354. var exports$1 = {
  2355. /**
  2356. * Clears the entire canvas associated to the given `chart`.
  2357. * @param {Chart} chart - The chart for which to clear the canvas.
  2358. */
  2359. clear: function(chart) {
  2360. chart.ctx.clearRect(0, 0, chart.width, chart.height);
  2361. },
  2362. /**
  2363. * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
  2364. * given size (width, height) and the same `radius` for all corners.
  2365. * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
  2366. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  2367. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  2368. * @param {number} width - The rectangle's width.
  2369. * @param {number} height - The rectangle's height.
  2370. * @param {number} radius - The rounded amount (in pixels) for the four corners.
  2371. * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
  2372. */
  2373. roundedRect: function(ctx, x, y, width, height, radius) {
  2374. if (radius) {
  2375. var r = Math.min(radius, height / 2, width / 2);
  2376. var left = x + r;
  2377. var top = y + r;
  2378. var right = x + width - r;
  2379. var bottom = y + height - r;
  2380. ctx.moveTo(x, top);
  2381. if (left < right && top < bottom) {
  2382. ctx.arc(left, top, r, -PI, -HALF_PI);
  2383. ctx.arc(right, top, r, -HALF_PI, 0);
  2384. ctx.arc(right, bottom, r, 0, HALF_PI);
  2385. ctx.arc(left, bottom, r, HALF_PI, PI);
  2386. } else if (left < right) {
  2387. ctx.moveTo(left, y);
  2388. ctx.arc(right, top, r, -HALF_PI, HALF_PI);
  2389. ctx.arc(left, top, r, HALF_PI, PI + HALF_PI);
  2390. } else if (top < bottom) {
  2391. ctx.arc(left, top, r, -PI, 0);
  2392. ctx.arc(left, bottom, r, 0, PI);
  2393. } else {
  2394. ctx.arc(left, top, r, -PI, PI);
  2395. }
  2396. ctx.closePath();
  2397. ctx.moveTo(x, y);
  2398. } else {
  2399. ctx.rect(x, y, width, height);
  2400. }
  2401. },
  2402. drawPoint: function(ctx, style, radius, x, y, rotation) {
  2403. var type, xOffset, yOffset, size, cornerRadius;
  2404. var rad = (rotation || 0) * RAD_PER_DEG;
  2405. if (style && typeof style === 'object') {
  2406. type = style.toString();
  2407. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  2408. ctx.save();
  2409. ctx.translate(x, y);
  2410. ctx.rotate(rad);
  2411. ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
  2412. ctx.restore();
  2413. return;
  2414. }
  2415. }
  2416. if (isNaN(radius) || radius <= 0) {
  2417. return;
  2418. }
  2419. ctx.beginPath();
  2420. switch (style) {
  2421. // Default includes circle
  2422. default:
  2423. ctx.arc(x, y, radius, 0, DOUBLE_PI);
  2424. ctx.closePath();
  2425. break;
  2426. case 'triangle':
  2427. ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2428. rad += TWO_THIRDS_PI;
  2429. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2430. rad += TWO_THIRDS_PI;
  2431. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2432. ctx.closePath();
  2433. break;
  2434. case 'rectRounded':
  2435. // NOTE: the rounded rect implementation changed to use `arc` instead of
  2436. // `quadraticCurveTo` since it generates better results when rect is
  2437. // almost a circle. 0.516 (instead of 0.5) produces results with visually
  2438. // closer proportion to the previous impl and it is inscribed in the
  2439. // circle with `radius`. For more details, see the following PRs:
  2440. // https://github.com/chartjs/Chart.js/issues/5597
  2441. // https://github.com/chartjs/Chart.js/issues/5858
  2442. cornerRadius = radius * 0.516;
  2443. size = radius - cornerRadius;
  2444. xOffset = Math.cos(rad + QUARTER_PI) * size;
  2445. yOffset = Math.sin(rad + QUARTER_PI) * size;
  2446. ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
  2447. ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
  2448. ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
  2449. ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
  2450. ctx.closePath();
  2451. break;
  2452. case 'rect':
  2453. if (!rotation) {
  2454. size = Math.SQRT1_2 * radius;
  2455. ctx.rect(x - size, y - size, 2 * size, 2 * size);
  2456. break;
  2457. }
  2458. rad += QUARTER_PI;
  2459. /* falls through */
  2460. case 'rectRot':
  2461. xOffset = Math.cos(rad) * radius;
  2462. yOffset = Math.sin(rad) * radius;
  2463. ctx.moveTo(x - xOffset, y - yOffset);
  2464. ctx.lineTo(x + yOffset, y - xOffset);
  2465. ctx.lineTo(x + xOffset, y + yOffset);
  2466. ctx.lineTo(x - yOffset, y + xOffset);
  2467. ctx.closePath();
  2468. break;
  2469. case 'crossRot':
  2470. rad += QUARTER_PI;
  2471. /* falls through */
  2472. case 'cross':
  2473. xOffset = Math.cos(rad) * radius;
  2474. yOffset = Math.sin(rad) * radius;
  2475. ctx.moveTo(x - xOffset, y - yOffset);
  2476. ctx.lineTo(x + xOffset, y + yOffset);
  2477. ctx.moveTo(x + yOffset, y - xOffset);
  2478. ctx.lineTo(x - yOffset, y + xOffset);
  2479. break;
  2480. case 'star':
  2481. xOffset = Math.cos(rad) * radius;
  2482. yOffset = Math.sin(rad) * radius;
  2483. ctx.moveTo(x - xOffset, y - yOffset);
  2484. ctx.lineTo(x + xOffset, y + yOffset);
  2485. ctx.moveTo(x + yOffset, y - xOffset);
  2486. ctx.lineTo(x - yOffset, y + xOffset);
  2487. rad += QUARTER_PI;
  2488. xOffset = Math.cos(rad) * radius;
  2489. yOffset = Math.sin(rad) * radius;
  2490. ctx.moveTo(x - xOffset, y - yOffset);
  2491. ctx.lineTo(x + xOffset, y + yOffset);
  2492. ctx.moveTo(x + yOffset, y - xOffset);
  2493. ctx.lineTo(x - yOffset, y + xOffset);
  2494. break;
  2495. case 'line':
  2496. xOffset = Math.cos(rad) * radius;
  2497. yOffset = Math.sin(rad) * radius;
  2498. ctx.moveTo(x - xOffset, y - yOffset);
  2499. ctx.lineTo(x + xOffset, y + yOffset);
  2500. break;
  2501. case 'dash':
  2502. ctx.moveTo(x, y);
  2503. ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
  2504. break;
  2505. }
  2506. ctx.fill();
  2507. ctx.stroke();
  2508. },
  2509. /**
  2510. * Returns true if the point is inside the rectangle
  2511. * @param {object} point - The point to test
  2512. * @param {object} area - The rectangle
  2513. * @returns {boolean}
  2514. * @private
  2515. */
  2516. _isPointInArea: function(point, area) {
  2517. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  2518. return point.x > area.left - epsilon && point.x < area.right + epsilon &&
  2519. point.y > area.top - epsilon && point.y < area.bottom + epsilon;
  2520. },
  2521. clipArea: function(ctx, area) {
  2522. ctx.save();
  2523. ctx.beginPath();
  2524. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  2525. ctx.clip();
  2526. },
  2527. unclipArea: function(ctx) {
  2528. ctx.restore();
  2529. },
  2530. lineTo: function(ctx, previous, target, flip) {
  2531. var stepped = target.steppedLine;
  2532. if (stepped) {
  2533. if (stepped === 'middle') {
  2534. var midpoint = (previous.x + target.x) / 2.0;
  2535. ctx.lineTo(midpoint, flip ? target.y : previous.y);
  2536. ctx.lineTo(midpoint, flip ? previous.y : target.y);
  2537. } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) {
  2538. ctx.lineTo(previous.x, target.y);
  2539. } else {
  2540. ctx.lineTo(target.x, previous.y);
  2541. }
  2542. ctx.lineTo(target.x, target.y);
  2543. return;
  2544. }
  2545. if (!target.tension) {
  2546. ctx.lineTo(target.x, target.y);
  2547. return;
  2548. }
  2549. ctx.bezierCurveTo(
  2550. flip ? previous.controlPointPreviousX : previous.controlPointNextX,
  2551. flip ? previous.controlPointPreviousY : previous.controlPointNextY,
  2552. flip ? target.controlPointNextX : target.controlPointPreviousX,
  2553. flip ? target.controlPointNextY : target.controlPointPreviousY,
  2554. target.x,
  2555. target.y);
  2556. }
  2557. };
  2558. var helpers_canvas = exports$1;
  2559. // DEPRECATIONS
  2560. /**
  2561. * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
  2562. * @namespace Chart.helpers.clear
  2563. * @deprecated since version 2.7.0
  2564. * @todo remove at version 3
  2565. * @private
  2566. */
  2567. helpers_core.clear = exports$1.clear;
  2568. /**
  2569. * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
  2570. * @namespace Chart.helpers.drawRoundedRectangle
  2571. * @deprecated since version 2.7.0
  2572. * @todo remove at version 3
  2573. * @private
  2574. */
  2575. helpers_core.drawRoundedRectangle = function(ctx) {
  2576. ctx.beginPath();
  2577. exports$1.roundedRect.apply(exports$1, arguments);
  2578. };
  2579. var defaults = {
  2580. /**
  2581. * @private
  2582. */
  2583. _set: function(scope, values) {
  2584. return helpers_core.merge(this[scope] || (this[scope] = {}), values);
  2585. }
  2586. };
  2587. // TODO(v3): remove 'global' from namespace. all default are global and
  2588. // there's inconsistency around which options are under 'global'
  2589. defaults._set('global', {
  2590. defaultColor: 'rgba(0,0,0,0.1)',
  2591. defaultFontColor: '#666',
  2592. defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  2593. defaultFontSize: 12,
  2594. defaultFontStyle: 'normal',
  2595. defaultLineHeight: 1.2,
  2596. showLines: true
  2597. });
  2598. var core_defaults = defaults;
  2599. var valueOrDefault = helpers_core.valueOrDefault;
  2600. /**
  2601. * Converts the given font object into a CSS font string.
  2602. * @param {object} font - A font object.
  2603. * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
  2604. * @private
  2605. */
  2606. function toFontString(font) {
  2607. if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) {
  2608. return null;
  2609. }
  2610. return (font.style ? font.style + ' ' : '')
  2611. + (font.weight ? font.weight + ' ' : '')
  2612. + font.size + 'px '
  2613. + font.family;
  2614. }
  2615. /**
  2616. * @alias Chart.helpers.options
  2617. * @namespace
  2618. */
  2619. var helpers_options = {
  2620. /**
  2621. * Converts the given line height `value` in pixels for a specific font `size`.
  2622. * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
  2623. * @param {number} size - The font size (in pixels) used to resolve relative `value`.
  2624. * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid).
  2625. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
  2626. * @since 2.7.0
  2627. */
  2628. toLineHeight: function(value, size) {
  2629. var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  2630. if (!matches || matches[1] === 'normal') {
  2631. return size * 1.2;
  2632. }
  2633. value = +matches[2];
  2634. switch (matches[3]) {
  2635. case 'px':
  2636. return value;
  2637. case '%':
  2638. value /= 100;
  2639. break;
  2640. }
  2641. return size * value;
  2642. },
  2643. /**
  2644. * Converts the given value into a padding object with pre-computed width/height.
  2645. * @param {number|object} value - If a number, set the value to all TRBL component,
  2646. * else, if and object, use defined properties and sets undefined ones to 0.
  2647. * @returns {object} The padding values (top, right, bottom, left, width, height)
  2648. * @since 2.7.0
  2649. */
  2650. toPadding: function(value) {
  2651. var t, r, b, l;
  2652. if (helpers_core.isObject(value)) {
  2653. t = +value.top || 0;
  2654. r = +value.right || 0;
  2655. b = +value.bottom || 0;
  2656. l = +value.left || 0;
  2657. } else {
  2658. t = r = b = l = +value || 0;
  2659. }
  2660. return {
  2661. top: t,
  2662. right: r,
  2663. bottom: b,
  2664. left: l,
  2665. height: t + b,
  2666. width: l + r
  2667. };
  2668. },
  2669. /**
  2670. * Parses font options and returns the font object.
  2671. * @param {object} options - A object that contains font options to be parsed.
  2672. * @return {object} The font object.
  2673. * @todo Support font.* options and renamed to toFont().
  2674. * @private
  2675. */
  2676. _parseFont: function(options) {
  2677. var globalDefaults = core_defaults.global;
  2678. var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
  2679. var font = {
  2680. family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
  2681. lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
  2682. size: size,
  2683. style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
  2684. weight: null,
  2685. string: ''
  2686. };
  2687. font.string = toFontString(font);
  2688. return font;
  2689. },
  2690. /**
  2691. * Evaluates the given `inputs` sequentially and returns the first defined value.
  2692. * @param {Array} inputs - An array of values, falling back to the last value.
  2693. * @param {object} [context] - If defined and the current value is a function, the value
  2694. * is called with `context` as first argument and the result becomes the new input.
  2695. * @param {number} [index] - If defined and the current value is an array, the value
  2696. * at `index` become the new input.
  2697. * @param {object} [info] - object to return information about resolution in
  2698. * @param {boolean} [info.cacheable] - Will be set to `false` if option is not cacheable.
  2699. * @since 2.7.0
  2700. */
  2701. resolve: function(inputs, context, index, info) {
  2702. var cacheable = true;
  2703. var i, ilen, value;
  2704. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  2705. value = inputs[i];
  2706. if (value === undefined) {
  2707. continue;
  2708. }
  2709. if (context !== undefined && typeof value === 'function') {
  2710. value = value(context);
  2711. cacheable = false;
  2712. }
  2713. if (index !== undefined && helpers_core.isArray(value)) {
  2714. value = value[index];
  2715. cacheable = false;
  2716. }
  2717. if (value !== undefined) {
  2718. if (info && !cacheable) {
  2719. info.cacheable = false;
  2720. }
  2721. return value;
  2722. }
  2723. }
  2724. }
  2725. };
  2726. /**
  2727. * @alias Chart.helpers.math
  2728. * @namespace
  2729. */
  2730. var exports$2 = {
  2731. /**
  2732. * Returns an array of factors sorted from 1 to sqrt(value)
  2733. * @private
  2734. */
  2735. _factorize: function(value) {
  2736. var result = [];
  2737. var sqrt = Math.sqrt(value);
  2738. var i;
  2739. for (i = 1; i < sqrt; i++) {
  2740. if (value % i === 0) {
  2741. result.push(i);
  2742. result.push(value / i);
  2743. }
  2744. }
  2745. if (sqrt === (sqrt | 0)) { // if value is a square number
  2746. result.push(sqrt);
  2747. }
  2748. result.sort(function(a, b) {
  2749. return a - b;
  2750. }).pop();
  2751. return result;
  2752. },
  2753. log10: Math.log10 || function(x) {
  2754. var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
  2755. // Check for whole powers of 10,
  2756. // which due to floating point rounding error should be corrected.
  2757. var powerOf10 = Math.round(exponent);
  2758. var isPowerOf10 = x === Math.pow(10, powerOf10);
  2759. return isPowerOf10 ? powerOf10 : exponent;
  2760. }
  2761. };
  2762. var helpers_math = exports$2;
  2763. // DEPRECATIONS
  2764. /**
  2765. * Provided for backward compatibility, use Chart.helpers.math.log10 instead.
  2766. * @namespace Chart.helpers.log10
  2767. * @deprecated since version 2.9.0
  2768. * @todo remove at version 3
  2769. * @private
  2770. */
  2771. helpers_core.log10 = exports$2.log10;
  2772. var getRtlAdapter = function(rectX, width) {
  2773. return {
  2774. x: function(x) {
  2775. return rectX + rectX + width - x;
  2776. },
  2777. setWidth: function(w) {
  2778. width = w;
  2779. },
  2780. textAlign: function(align) {
  2781. if (align === 'center') {
  2782. return align;
  2783. }
  2784. return align === 'right' ? 'left' : 'right';
  2785. },
  2786. xPlus: function(x, value) {
  2787. return x - value;
  2788. },
  2789. leftForLtr: function(x, itemWidth) {
  2790. return x - itemWidth;
  2791. },
  2792. };
  2793. };
  2794. var getLtrAdapter = function() {
  2795. return {
  2796. x: function(x) {
  2797. return x;
  2798. },
  2799. setWidth: function(w) { // eslint-disable-line no-unused-vars
  2800. },
  2801. textAlign: function(align) {
  2802. return align;
  2803. },
  2804. xPlus: function(x, value) {
  2805. return x + value;
  2806. },
  2807. leftForLtr: function(x, _itemWidth) { // eslint-disable-line no-unused-vars
  2808. return x;
  2809. },
  2810. };
  2811. };
  2812. var getAdapter = function(rtl, rectX, width) {
  2813. return rtl ? getRtlAdapter(rectX, width) : getLtrAdapter();
  2814. };
  2815. var overrideTextDirection = function(ctx, direction) {
  2816. var style, original;
  2817. if (direction === 'ltr' || direction === 'rtl') {
  2818. style = ctx.canvas.style;
  2819. original = [
  2820. style.getPropertyValue('direction'),
  2821. style.getPropertyPriority('direction'),
  2822. ];
  2823. style.setProperty('direction', direction, 'important');
  2824. ctx.prevTextDirection = original;
  2825. }
  2826. };
  2827. var restoreTextDirection = function(ctx) {
  2828. var original = ctx.prevTextDirection;
  2829. if (original !== undefined) {
  2830. delete ctx.prevTextDirection;
  2831. ctx.canvas.style.setProperty('direction', original[0], original[1]);
  2832. }
  2833. };
  2834. var helpers_rtl = {
  2835. getRtlAdapter: getAdapter,
  2836. overrideTextDirection: overrideTextDirection,
  2837. restoreTextDirection: restoreTextDirection,
  2838. };
  2839. var helpers$1 = helpers_core;
  2840. var easing = helpers_easing;
  2841. var canvas = helpers_canvas;
  2842. var options = helpers_options;
  2843. var math = helpers_math;
  2844. var rtl = helpers_rtl;
  2845. helpers$1.easing = easing;
  2846. helpers$1.canvas = canvas;
  2847. helpers$1.options = options;
  2848. helpers$1.math = math;
  2849. helpers$1.rtl = rtl;
  2850. function interpolate(start, view, model, ease) {
  2851. var keys = Object.keys(model);
  2852. var i, ilen, key, actual, origin, target, type, c0, c1;
  2853. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  2854. key = keys[i];
  2855. target = model[key];
  2856. // if a value is added to the model after pivot() has been called, the view
  2857. // doesn't contain it, so let's initialize the view to the target value.
  2858. if (!view.hasOwnProperty(key)) {
  2859. view[key] = target;
  2860. }
  2861. actual = view[key];
  2862. if (actual === target || key[0] === '_') {
  2863. continue;
  2864. }
  2865. if (!start.hasOwnProperty(key)) {
  2866. start[key] = actual;
  2867. }
  2868. origin = start[key];
  2869. type = typeof target;
  2870. if (type === typeof origin) {
  2871. if (type === 'string') {
  2872. c0 = chartjsColor(origin);
  2873. if (c0.valid) {
  2874. c1 = chartjsColor(target);
  2875. if (c1.valid) {
  2876. view[key] = c1.mix(c0, ease).rgbString();
  2877. continue;
  2878. }
  2879. }
  2880. } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) {
  2881. view[key] = origin + (target - origin) * ease;
  2882. continue;
  2883. }
  2884. }
  2885. view[key] = target;
  2886. }
  2887. }
  2888. var Element = function(configuration) {
  2889. helpers$1.extend(this, configuration);
  2890. this.initialize.apply(this, arguments);
  2891. };
  2892. helpers$1.extend(Element.prototype, {
  2893. _type: undefined,
  2894. initialize: function() {
  2895. this.hidden = false;
  2896. },
  2897. pivot: function() {
  2898. var me = this;
  2899. if (!me._view) {
  2900. me._view = helpers$1.extend({}, me._model);
  2901. }
  2902. me._start = {};
  2903. return me;
  2904. },
  2905. transition: function(ease) {
  2906. var me = this;
  2907. var model = me._model;
  2908. var start = me._start;
  2909. var view = me._view;
  2910. // No animation -> No Transition
  2911. if (!model || ease === 1) {
  2912. me._view = helpers$1.extend({}, model);
  2913. me._start = null;
  2914. return me;
  2915. }
  2916. if (!view) {
  2917. view = me._view = {};
  2918. }
  2919. if (!start) {
  2920. start = me._start = {};
  2921. }
  2922. interpolate(start, view, model, ease);
  2923. return me;
  2924. },
  2925. tooltipPosition: function() {
  2926. return {
  2927. x: this._model.x,
  2928. y: this._model.y
  2929. };
  2930. },
  2931. hasValue: function() {
  2932. return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);
  2933. }
  2934. });
  2935. Element.extend = helpers$1.inherits;
  2936. var core_element = Element;
  2937. var exports$3 = core_element.extend({
  2938. chart: null, // the animation associated chart instance
  2939. currentStep: 0, // the current animation step
  2940. numSteps: 60, // default number of steps
  2941. easing: '', // the easing to use for this animation
  2942. render: null, // render function used by the animation service
  2943. onAnimationProgress: null, // user specified callback to fire on each step of the animation
  2944. onAnimationComplete: null, // user specified callback to fire when the animation finishes
  2945. });
  2946. var core_animation = exports$3;
  2947. // DEPRECATIONS
  2948. /**
  2949. * Provided for backward compatibility, use Chart.Animation instead
  2950. * @prop Chart.Animation#animationObject
  2951. * @deprecated since version 2.6.0
  2952. * @todo remove at version 3
  2953. */
  2954. Object.defineProperty(exports$3.prototype, 'animationObject', {
  2955. get: function() {
  2956. return this;
  2957. }
  2958. });
  2959. /**
  2960. * Provided for backward compatibility, use Chart.Animation#chart instead
  2961. * @prop Chart.Animation#chartInstance
  2962. * @deprecated since version 2.6.0
  2963. * @todo remove at version 3
  2964. */
  2965. Object.defineProperty(exports$3.prototype, 'chartInstance', {
  2966. get: function() {
  2967. return this.chart;
  2968. },
  2969. set: function(value) {
  2970. this.chart = value;
  2971. }
  2972. });
  2973. core_defaults._set('global', {
  2974. animation: {
  2975. duration: 1000,
  2976. easing: 'easeOutQuart',
  2977. onProgress: helpers$1.noop,
  2978. onComplete: helpers$1.noop
  2979. }
  2980. });
  2981. var core_animations = {
  2982. animations: [],
  2983. request: null,
  2984. /**
  2985. * @param {Chart} chart - The chart to animate.
  2986. * @param {Chart.Animation} animation - The animation that we will animate.
  2987. * @param {number} duration - The animation duration in ms.
  2988. * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
  2989. */
  2990. addAnimation: function(chart, animation, duration, lazy) {
  2991. var animations = this.animations;
  2992. var i, ilen;
  2993. animation.chart = chart;
  2994. animation.startTime = Date.now();
  2995. animation.duration = duration;
  2996. if (!lazy) {
  2997. chart.animating = true;
  2998. }
  2999. for (i = 0, ilen = animations.length; i < ilen; ++i) {
  3000. if (animations[i].chart === chart) {
  3001. animations[i] = animation;
  3002. return;
  3003. }
  3004. }
  3005. animations.push(animation);
  3006. // If there are no animations queued, manually kickstart a digest, for lack of a better word
  3007. if (animations.length === 1) {
  3008. this.requestAnimationFrame();
  3009. }
  3010. },
  3011. cancelAnimation: function(chart) {
  3012. var index = helpers$1.findIndex(this.animations, function(animation) {
  3013. return animation.chart === chart;
  3014. });
  3015. if (index !== -1) {
  3016. this.animations.splice(index, 1);
  3017. chart.animating = false;
  3018. }
  3019. },
  3020. requestAnimationFrame: function() {
  3021. var me = this;
  3022. if (me.request === null) {
  3023. // Skip animation frame requests until the active one is executed.
  3024. // This can happen when processing mouse events, e.g. 'mousemove'
  3025. // and 'mouseout' events will trigger multiple renders.
  3026. me.request = helpers$1.requestAnimFrame.call(window, function() {
  3027. me.request = null;
  3028. me.startDigest();
  3029. });
  3030. }
  3031. },
  3032. /**
  3033. * @private
  3034. */
  3035. startDigest: function() {
  3036. var me = this;
  3037. me.advance();
  3038. // Do we have more stuff to animate?
  3039. if (me.animations.length > 0) {
  3040. me.requestAnimationFrame();
  3041. }
  3042. },
  3043. /**
  3044. * @private
  3045. */
  3046. advance: function() {
  3047. var animations = this.animations;
  3048. var animation, chart, numSteps, nextStep;
  3049. var i = 0;
  3050. // 1 animation per chart, so we are looping charts here
  3051. while (i < animations.length) {
  3052. animation = animations[i];
  3053. chart = animation.chart;
  3054. numSteps = animation.numSteps;
  3055. // Make sure that currentStep starts at 1
  3056. // https://github.com/chartjs/Chart.js/issues/6104
  3057. nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1;
  3058. animation.currentStep = Math.min(nextStep, numSteps);
  3059. helpers$1.callback(animation.render, [chart, animation], chart);
  3060. helpers$1.callback(animation.onAnimationProgress, [animation], chart);
  3061. if (animation.currentStep >= numSteps) {
  3062. helpers$1.callback(animation.onAnimationComplete, [animation], chart);
  3063. chart.animating = false;
  3064. animations.splice(i, 1);
  3065. } else {
  3066. ++i;
  3067. }
  3068. }
  3069. }
  3070. };
  3071. var resolve = helpers$1.options.resolve;
  3072. var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  3073. /**
  3074. * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
  3075. * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
  3076. * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
  3077. */
  3078. function listenArrayEvents(array, listener) {
  3079. if (array._chartjs) {
  3080. array._chartjs.listeners.push(listener);
  3081. return;
  3082. }
  3083. Object.defineProperty(array, '_chartjs', {
  3084. configurable: true,
  3085. enumerable: false,
  3086. value: {
  3087. listeners: [listener]
  3088. }
  3089. });
  3090. arrayEvents.forEach(function(key) {
  3091. var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
  3092. var base = array[key];
  3093. Object.defineProperty(array, key, {
  3094. configurable: true,
  3095. enumerable: false,
  3096. value: function() {
  3097. var args = Array.prototype.slice.call(arguments);
  3098. var res = base.apply(this, args);
  3099. helpers$1.each(array._chartjs.listeners, function(object) {
  3100. if (typeof object[method] === 'function') {
  3101. object[method].apply(object, args);
  3102. }
  3103. });
  3104. return res;
  3105. }
  3106. });
  3107. });
  3108. }
  3109. /**
  3110. * Removes the given array event listener and cleanup extra attached properties (such as
  3111. * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
  3112. */
  3113. function unlistenArrayEvents(array, listener) {
  3114. var stub = array._chartjs;
  3115. if (!stub) {
  3116. return;
  3117. }
  3118. var listeners = stub.listeners;
  3119. var index = listeners.indexOf(listener);
  3120. if (index !== -1) {
  3121. listeners.splice(index, 1);
  3122. }
  3123. if (listeners.length > 0) {
  3124. return;
  3125. }
  3126. arrayEvents.forEach(function(key) {
  3127. delete array[key];
  3128. });
  3129. delete array._chartjs;
  3130. }
  3131. // Base class for all dataset controllers (line, bar, etc)
  3132. var DatasetController = function(chart, datasetIndex) {
  3133. this.initialize(chart, datasetIndex);
  3134. };
  3135. helpers$1.extend(DatasetController.prototype, {
  3136. /**
  3137. * Element type used to generate a meta dataset (e.g. Chart.element.Line).
  3138. * @type {Chart.core.element}
  3139. */
  3140. datasetElementType: null,
  3141. /**
  3142. * Element type used to generate a meta data (e.g. Chart.element.Point).
  3143. * @type {Chart.core.element}
  3144. */
  3145. dataElementType: null,
  3146. /**
  3147. * Dataset element option keys to be resolved in _resolveDatasetElementOptions.
  3148. * A derived controller may override this to resolve controller-specific options.
  3149. * The keys defined here are for backward compatibility for legend styles.
  3150. * @private
  3151. */
  3152. _datasetElementOptions: [
  3153. 'backgroundColor',
  3154. 'borderCapStyle',
  3155. 'borderColor',
  3156. 'borderDash',
  3157. 'borderDashOffset',
  3158. 'borderJoinStyle',
  3159. 'borderWidth'
  3160. ],
  3161. /**
  3162. * Data element option keys to be resolved in _resolveDataElementOptions.
  3163. * A derived controller may override this to resolve controller-specific options.
  3164. * The keys defined here are for backward compatibility for legend styles.
  3165. * @private
  3166. */
  3167. _dataElementOptions: [
  3168. 'backgroundColor',
  3169. 'borderColor',
  3170. 'borderWidth',
  3171. 'pointStyle'
  3172. ],
  3173. initialize: function(chart, datasetIndex) {
  3174. var me = this;
  3175. me.chart = chart;
  3176. me.index = datasetIndex;
  3177. me.linkScales();
  3178. me.addElements();
  3179. me._type = me.getMeta().type;
  3180. },
  3181. updateIndex: function(datasetIndex) {
  3182. this.index = datasetIndex;
  3183. },
  3184. linkScales: function() {
  3185. var me = this;
  3186. var meta = me.getMeta();
  3187. var chart = me.chart;
  3188. var scales = chart.scales;
  3189. var dataset = me.getDataset();
  3190. var scalesOpts = chart.options.scales;
  3191. if (meta.xAxisID === null || !(meta.xAxisID in scales) || dataset.xAxisID) {
  3192. meta.xAxisID = dataset.xAxisID || scalesOpts.xAxes[0].id;
  3193. }
  3194. if (meta.yAxisID === null || !(meta.yAxisID in scales) || dataset.yAxisID) {
  3195. meta.yAxisID = dataset.yAxisID || scalesOpts.yAxes[0].id;
  3196. }
  3197. },
  3198. getDataset: function() {
  3199. return this.chart.data.datasets[this.index];
  3200. },
  3201. getMeta: function() {
  3202. return this.chart.getDatasetMeta(this.index);
  3203. },
  3204. getScaleForId: function(scaleID) {
  3205. return this.chart.scales[scaleID];
  3206. },
  3207. /**
  3208. * @private
  3209. */
  3210. _getValueScaleId: function() {
  3211. return this.getMeta().yAxisID;
  3212. },
  3213. /**
  3214. * @private
  3215. */
  3216. _getIndexScaleId: function() {
  3217. return this.getMeta().xAxisID;
  3218. },
  3219. /**
  3220. * @private
  3221. */
  3222. _getValueScale: function() {
  3223. return this.getScaleForId(this._getValueScaleId());
  3224. },
  3225. /**
  3226. * @private
  3227. */
  3228. _getIndexScale: function() {
  3229. return this.getScaleForId(this._getIndexScaleId());
  3230. },
  3231. reset: function() {
  3232. this._update(true);
  3233. },
  3234. /**
  3235. * @private
  3236. */
  3237. destroy: function() {
  3238. if (this._data) {
  3239. unlistenArrayEvents(this._data, this);
  3240. }
  3241. },
  3242. createMetaDataset: function() {
  3243. var me = this;
  3244. var type = me.datasetElementType;
  3245. return type && new type({
  3246. _chart: me.chart,
  3247. _datasetIndex: me.index
  3248. });
  3249. },
  3250. createMetaData: function(index) {
  3251. var me = this;
  3252. var type = me.dataElementType;
  3253. return type && new type({
  3254. _chart: me.chart,
  3255. _datasetIndex: me.index,
  3256. _index: index
  3257. });
  3258. },
  3259. addElements: function() {
  3260. var me = this;
  3261. var meta = me.getMeta();
  3262. var data = me.getDataset().data || [];
  3263. var metaData = meta.data;
  3264. var i, ilen;
  3265. for (i = 0, ilen = data.length; i < ilen; ++i) {
  3266. metaData[i] = metaData[i] || me.createMetaData(i);
  3267. }
  3268. meta.dataset = meta.dataset || me.createMetaDataset();
  3269. },
  3270. addElementAndReset: function(index) {
  3271. var element = this.createMetaData(index);
  3272. this.getMeta().data.splice(index, 0, element);
  3273. this.updateElement(element, index, true);
  3274. },
  3275. buildOrUpdateElements: function() {
  3276. var me = this;
  3277. var dataset = me.getDataset();
  3278. var data = dataset.data || (dataset.data = []);
  3279. // In order to correctly handle data addition/deletion animation (an thus simulate
  3280. // real-time charts), we need to monitor these data modifications and synchronize
  3281. // the internal meta data accordingly.
  3282. if (me._data !== data) {
  3283. if (me._data) {
  3284. // This case happens when the user replaced the data array instance.
  3285. unlistenArrayEvents(me._data, me);
  3286. }
  3287. if (data && Object.isExtensible(data)) {
  3288. listenArrayEvents(data, me);
  3289. }
  3290. me._data = data;
  3291. }
  3292. // Re-sync meta data in case the user replaced the data array or if we missed
  3293. // any updates and so make sure that we handle number of datapoints changing.
  3294. me.resyncElements();
  3295. },
  3296. /**
  3297. * Returns the merged user-supplied and default dataset-level options
  3298. * @private
  3299. */
  3300. _configure: function() {
  3301. var me = this;
  3302. me._config = helpers$1.merge(Object.create(null), [
  3303. me.chart.options.datasets[me._type],
  3304. me.getDataset(),
  3305. ], {
  3306. merger: function(key, target, source) {
  3307. if (key !== '_meta' && key !== 'data') {
  3308. helpers$1._merger(key, target, source);
  3309. }
  3310. }
  3311. });
  3312. },
  3313. _update: function(reset) {
  3314. var me = this;
  3315. me._configure();
  3316. me._cachedDataOpts = null;
  3317. me.update(reset);
  3318. },
  3319. update: helpers$1.noop,
  3320. transition: function(easingValue) {
  3321. var meta = this.getMeta();
  3322. var elements = meta.data || [];
  3323. var ilen = elements.length;
  3324. var i = 0;
  3325. for (; i < ilen; ++i) {
  3326. elements[i].transition(easingValue);
  3327. }
  3328. if (meta.dataset) {
  3329. meta.dataset.transition(easingValue);
  3330. }
  3331. },
  3332. draw: function() {
  3333. var meta = this.getMeta();
  3334. var elements = meta.data || [];
  3335. var ilen = elements.length;
  3336. var i = 0;
  3337. if (meta.dataset) {
  3338. meta.dataset.draw();
  3339. }
  3340. for (; i < ilen; ++i) {
  3341. elements[i].draw();
  3342. }
  3343. },
  3344. /**
  3345. * Returns a set of predefined style properties that should be used to represent the dataset
  3346. * or the data if the index is specified
  3347. * @param {number} index - data index
  3348. * @return {IStyleInterface} style object
  3349. */
  3350. getStyle: function(index) {
  3351. var me = this;
  3352. var meta = me.getMeta();
  3353. var dataset = meta.dataset;
  3354. var style;
  3355. me._configure();
  3356. if (dataset && index === undefined) {
  3357. style = me._resolveDatasetElementOptions(dataset || {});
  3358. } else {
  3359. index = index || 0;
  3360. style = me._resolveDataElementOptions(meta.data[index] || {}, index);
  3361. }
  3362. if (style.fill === false || style.fill === null) {
  3363. style.backgroundColor = style.borderColor;
  3364. }
  3365. return style;
  3366. },
  3367. /**
  3368. * @private
  3369. */
  3370. _resolveDatasetElementOptions: function(element, hover) {
  3371. var me = this;
  3372. var chart = me.chart;
  3373. var datasetOpts = me._config;
  3374. var custom = element.custom || {};
  3375. var options = chart.options.elements[me.datasetElementType.prototype._type] || {};
  3376. var elementOptions = me._datasetElementOptions;
  3377. var values = {};
  3378. var i, ilen, key, readKey;
  3379. // Scriptable options
  3380. var context = {
  3381. chart: chart,
  3382. dataset: me.getDataset(),
  3383. datasetIndex: me.index,
  3384. hover: hover
  3385. };
  3386. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  3387. key = elementOptions[i];
  3388. readKey = hover ? 'hover' + key.charAt(0).toUpperCase() + key.slice(1) : key;
  3389. values[key] = resolve([
  3390. custom[readKey],
  3391. datasetOpts[readKey],
  3392. options[readKey]
  3393. ], context);
  3394. }
  3395. return values;
  3396. },
  3397. /**
  3398. * @private
  3399. */
  3400. _resolveDataElementOptions: function(element, index) {
  3401. var me = this;
  3402. var custom = element && element.custom;
  3403. var cached = me._cachedDataOpts;
  3404. if (cached && !custom) {
  3405. return cached;
  3406. }
  3407. var chart = me.chart;
  3408. var datasetOpts = me._config;
  3409. var options = chart.options.elements[me.dataElementType.prototype._type] || {};
  3410. var elementOptions = me._dataElementOptions;
  3411. var values = {};
  3412. // Scriptable options
  3413. var context = {
  3414. chart: chart,
  3415. dataIndex: index,
  3416. dataset: me.getDataset(),
  3417. datasetIndex: me.index
  3418. };
  3419. // `resolve` sets cacheable to `false` if any option is indexed or scripted
  3420. var info = {cacheable: !custom};
  3421. var keys, i, ilen, key;
  3422. custom = custom || {};
  3423. if (helpers$1.isArray(elementOptions)) {
  3424. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  3425. key = elementOptions[i];
  3426. values[key] = resolve([
  3427. custom[key],
  3428. datasetOpts[key],
  3429. options[key]
  3430. ], context, index, info);
  3431. }
  3432. } else {
  3433. keys = Object.keys(elementOptions);
  3434. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3435. key = keys[i];
  3436. values[key] = resolve([
  3437. custom[key],
  3438. datasetOpts[elementOptions[key]],
  3439. datasetOpts[key],
  3440. options[key]
  3441. ], context, index, info);
  3442. }
  3443. }
  3444. if (info.cacheable) {
  3445. me._cachedDataOpts = Object.freeze(values);
  3446. }
  3447. return values;
  3448. },
  3449. removeHoverStyle: function(element) {
  3450. helpers$1.merge(element._model, element.$previousStyle || {});
  3451. delete element.$previousStyle;
  3452. },
  3453. setHoverStyle: function(element) {
  3454. var dataset = this.chart.data.datasets[element._datasetIndex];
  3455. var index = element._index;
  3456. var custom = element.custom || {};
  3457. var model = element._model;
  3458. var getHoverColor = helpers$1.getHoverColor;
  3459. element.$previousStyle = {
  3460. backgroundColor: model.backgroundColor,
  3461. borderColor: model.borderColor,
  3462. borderWidth: model.borderWidth
  3463. };
  3464. model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
  3465. model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
  3466. model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
  3467. },
  3468. /**
  3469. * @private
  3470. */
  3471. _removeDatasetHoverStyle: function() {
  3472. var element = this.getMeta().dataset;
  3473. if (element) {
  3474. this.removeHoverStyle(element);
  3475. }
  3476. },
  3477. /**
  3478. * @private
  3479. */
  3480. _setDatasetHoverStyle: function() {
  3481. var element = this.getMeta().dataset;
  3482. var prev = {};
  3483. var i, ilen, key, keys, hoverOptions, model;
  3484. if (!element) {
  3485. return;
  3486. }
  3487. model = element._model;
  3488. hoverOptions = this._resolveDatasetElementOptions(element, true);
  3489. keys = Object.keys(hoverOptions);
  3490. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3491. key = keys[i];
  3492. prev[key] = model[key];
  3493. model[key] = hoverOptions[key];
  3494. }
  3495. element.$previousStyle = prev;
  3496. },
  3497. /**
  3498. * @private
  3499. */
  3500. resyncElements: function() {
  3501. var me = this;
  3502. var meta = me.getMeta();
  3503. var data = me.getDataset().data;
  3504. var numMeta = meta.data.length;
  3505. var numData = data.length;
  3506. if (numData < numMeta) {
  3507. meta.data.splice(numData, numMeta - numData);
  3508. } else if (numData > numMeta) {
  3509. me.insertElements(numMeta, numData - numMeta);
  3510. }
  3511. },
  3512. /**
  3513. * @private
  3514. */
  3515. insertElements: function(start, count) {
  3516. for (var i = 0; i < count; ++i) {
  3517. this.addElementAndReset(start + i);
  3518. }
  3519. },
  3520. /**
  3521. * @private
  3522. */
  3523. onDataPush: function() {
  3524. var count = arguments.length;
  3525. this.insertElements(this.getDataset().data.length - count, count);
  3526. },
  3527. /**
  3528. * @private
  3529. */
  3530. onDataPop: function() {
  3531. this.getMeta().data.pop();
  3532. },
  3533. /**
  3534. * @private
  3535. */
  3536. onDataShift: function() {
  3537. this.getMeta().data.shift();
  3538. },
  3539. /**
  3540. * @private
  3541. */
  3542. onDataSplice: function(start, count) {
  3543. this.getMeta().data.splice(start, count);
  3544. this.insertElements(start, arguments.length - 2);
  3545. },
  3546. /**
  3547. * @private
  3548. */
  3549. onDataUnshift: function() {
  3550. this.insertElements(0, arguments.length);
  3551. }
  3552. });
  3553. DatasetController.extend = helpers$1.inherits;
  3554. var core_datasetController = DatasetController;
  3555. var TAU = Math.PI * 2;
  3556. core_defaults._set('global', {
  3557. elements: {
  3558. arc: {
  3559. backgroundColor: core_defaults.global.defaultColor,
  3560. borderColor: '#fff',
  3561. borderWidth: 2,
  3562. borderAlign: 'center'
  3563. }
  3564. }
  3565. });
  3566. function clipArc(ctx, arc) {
  3567. var startAngle = arc.startAngle;
  3568. var endAngle = arc.endAngle;
  3569. var pixelMargin = arc.pixelMargin;
  3570. var angleMargin = pixelMargin / arc.outerRadius;
  3571. var x = arc.x;
  3572. var y = arc.y;
  3573. // Draw an inner border by cliping the arc and drawing a double-width border
  3574. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  3575. ctx.beginPath();
  3576. ctx.arc(x, y, arc.outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  3577. if (arc.innerRadius > pixelMargin) {
  3578. angleMargin = pixelMargin / arc.innerRadius;
  3579. ctx.arc(x, y, arc.innerRadius - pixelMargin, endAngle + angleMargin, startAngle - angleMargin, true);
  3580. } else {
  3581. ctx.arc(x, y, pixelMargin, endAngle + Math.PI / 2, startAngle - Math.PI / 2);
  3582. }
  3583. ctx.closePath();
  3584. ctx.clip();
  3585. }
  3586. function drawFullCircleBorders(ctx, vm, arc, inner) {
  3587. var endAngle = arc.endAngle;
  3588. var i;
  3589. if (inner) {
  3590. arc.endAngle = arc.startAngle + TAU;
  3591. clipArc(ctx, arc);
  3592. arc.endAngle = endAngle;
  3593. if (arc.endAngle === arc.startAngle && arc.fullCircles) {
  3594. arc.endAngle += TAU;
  3595. arc.fullCircles--;
  3596. }
  3597. }
  3598. ctx.beginPath();
  3599. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.startAngle + TAU, arc.startAngle, true);
  3600. for (i = 0; i < arc.fullCircles; ++i) {
  3601. ctx.stroke();
  3602. }
  3603. ctx.beginPath();
  3604. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.startAngle + TAU);
  3605. for (i = 0; i < arc.fullCircles; ++i) {
  3606. ctx.stroke();
  3607. }
  3608. }
  3609. function drawBorder(ctx, vm, arc) {
  3610. var inner = vm.borderAlign === 'inner';
  3611. if (inner) {
  3612. ctx.lineWidth = vm.borderWidth * 2;
  3613. ctx.lineJoin = 'round';
  3614. } else {
  3615. ctx.lineWidth = vm.borderWidth;
  3616. ctx.lineJoin = 'bevel';
  3617. }
  3618. if (arc.fullCircles) {
  3619. drawFullCircleBorders(ctx, vm, arc, inner);
  3620. }
  3621. if (inner) {
  3622. clipArc(ctx, arc);
  3623. }
  3624. ctx.beginPath();
  3625. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.endAngle);
  3626. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3627. ctx.closePath();
  3628. ctx.stroke();
  3629. }
  3630. var element_arc = core_element.extend({
  3631. _type: 'arc',
  3632. inLabelRange: function(mouseX) {
  3633. var vm = this._view;
  3634. if (vm) {
  3635. return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
  3636. }
  3637. return false;
  3638. },
  3639. inRange: function(chartX, chartY) {
  3640. var vm = this._view;
  3641. if (vm) {
  3642. var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY});
  3643. var angle = pointRelativePosition.angle;
  3644. var distance = pointRelativePosition.distance;
  3645. // Sanitise angle range
  3646. var startAngle = vm.startAngle;
  3647. var endAngle = vm.endAngle;
  3648. while (endAngle < startAngle) {
  3649. endAngle += TAU;
  3650. }
  3651. while (angle > endAngle) {
  3652. angle -= TAU;
  3653. }
  3654. while (angle < startAngle) {
  3655. angle += TAU;
  3656. }
  3657. // Check if within the range of the open/close angle
  3658. var betweenAngles = (angle >= startAngle && angle <= endAngle);
  3659. var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
  3660. return (betweenAngles && withinRadius);
  3661. }
  3662. return false;
  3663. },
  3664. getCenterPoint: function() {
  3665. var vm = this._view;
  3666. var halfAngle = (vm.startAngle + vm.endAngle) / 2;
  3667. var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
  3668. return {
  3669. x: vm.x + Math.cos(halfAngle) * halfRadius,
  3670. y: vm.y + Math.sin(halfAngle) * halfRadius
  3671. };
  3672. },
  3673. getArea: function() {
  3674. var vm = this._view;
  3675. return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
  3676. },
  3677. tooltipPosition: function() {
  3678. var vm = this._view;
  3679. var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
  3680. var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
  3681. return {
  3682. x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
  3683. y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
  3684. };
  3685. },
  3686. draw: function() {
  3687. var ctx = this._chart.ctx;
  3688. var vm = this._view;
  3689. var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;
  3690. var arc = {
  3691. x: vm.x,
  3692. y: vm.y,
  3693. innerRadius: vm.innerRadius,
  3694. outerRadius: Math.max(vm.outerRadius - pixelMargin, 0),
  3695. pixelMargin: pixelMargin,
  3696. startAngle: vm.startAngle,
  3697. endAngle: vm.endAngle,
  3698. fullCircles: Math.floor(vm.circumference / TAU)
  3699. };
  3700. var i;
  3701. ctx.save();
  3702. ctx.fillStyle = vm.backgroundColor;
  3703. ctx.strokeStyle = vm.borderColor;
  3704. if (arc.fullCircles) {
  3705. arc.endAngle = arc.startAngle + TAU;
  3706. ctx.beginPath();
  3707. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  3708. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3709. ctx.closePath();
  3710. for (i = 0; i < arc.fullCircles; ++i) {
  3711. ctx.fill();
  3712. }
  3713. arc.endAngle = arc.startAngle + vm.circumference % TAU;
  3714. }
  3715. ctx.beginPath();
  3716. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  3717. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3718. ctx.closePath();
  3719. ctx.fill();
  3720. if (vm.borderWidth) {
  3721. drawBorder(ctx, vm, arc);
  3722. }
  3723. ctx.restore();
  3724. }
  3725. });
  3726. var valueOrDefault$1 = helpers$1.valueOrDefault;
  3727. var defaultColor = core_defaults.global.defaultColor;
  3728. core_defaults._set('global', {
  3729. elements: {
  3730. line: {
  3731. tension: 0.4,
  3732. backgroundColor: defaultColor,
  3733. borderWidth: 3,
  3734. borderColor: defaultColor,
  3735. borderCapStyle: 'butt',
  3736. borderDash: [],
  3737. borderDashOffset: 0.0,
  3738. borderJoinStyle: 'miter',
  3739. capBezierPoints: true,
  3740. fill: true, // do we fill in the area between the line and its base axis
  3741. }
  3742. }
  3743. });
  3744. var element_line = core_element.extend({
  3745. _type: 'line',
  3746. draw: function() {
  3747. var me = this;
  3748. var vm = me._view;
  3749. var ctx = me._chart.ctx;
  3750. var spanGaps = vm.spanGaps;
  3751. var points = me._children.slice(); // clone array
  3752. var globalDefaults = core_defaults.global;
  3753. var globalOptionLineElements = globalDefaults.elements.line;
  3754. var lastDrawnIndex = -1;
  3755. var closePath = me._loop;
  3756. var index, previous, currentVM;
  3757. if (!points.length) {
  3758. return;
  3759. }
  3760. if (me._loop) {
  3761. for (index = 0; index < points.length; ++index) {
  3762. previous = helpers$1.previousItem(points, index);
  3763. // If the line has an open path, shift the point array
  3764. if (!points[index]._view.skip && previous._view.skip) {
  3765. points = points.slice(index).concat(points.slice(0, index));
  3766. closePath = spanGaps;
  3767. break;
  3768. }
  3769. }
  3770. // If the line has a close path, add the first point again
  3771. if (closePath) {
  3772. points.push(points[0]);
  3773. }
  3774. }
  3775. ctx.save();
  3776. // Stroke Line Options
  3777. ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
  3778. // IE 9 and 10 do not support line dash
  3779. if (ctx.setLineDash) {
  3780. ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
  3781. }
  3782. ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
  3783. ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
  3784. ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth);
  3785. ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
  3786. // Stroke Line
  3787. ctx.beginPath();
  3788. // First point moves to it's starting position no matter what
  3789. currentVM = points[0]._view;
  3790. if (!currentVM.skip) {
  3791. ctx.moveTo(currentVM.x, currentVM.y);
  3792. lastDrawnIndex = 0;
  3793. }
  3794. for (index = 1; index < points.length; ++index) {
  3795. currentVM = points[index]._view;
  3796. previous = lastDrawnIndex === -1 ? helpers$1.previousItem(points, index) : points[lastDrawnIndex];
  3797. if (!currentVM.skip) {
  3798. if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
  3799. // There was a gap and this is the first point after the gap
  3800. ctx.moveTo(currentVM.x, currentVM.y);
  3801. } else {
  3802. // Line to next point
  3803. helpers$1.canvas.lineTo(ctx, previous._view, currentVM);
  3804. }
  3805. lastDrawnIndex = index;
  3806. }
  3807. }
  3808. if (closePath) {
  3809. ctx.closePath();
  3810. }
  3811. ctx.stroke();
  3812. ctx.restore();
  3813. }
  3814. });
  3815. var valueOrDefault$2 = helpers$1.valueOrDefault;
  3816. var defaultColor$1 = core_defaults.global.defaultColor;
  3817. core_defaults._set('global', {
  3818. elements: {
  3819. point: {
  3820. radius: 3,
  3821. pointStyle: 'circle',
  3822. backgroundColor: defaultColor$1,
  3823. borderColor: defaultColor$1,
  3824. borderWidth: 1,
  3825. // Hover
  3826. hitRadius: 1,
  3827. hoverRadius: 4,
  3828. hoverBorderWidth: 1
  3829. }
  3830. }
  3831. });
  3832. function xRange(mouseX) {
  3833. var vm = this._view;
  3834. return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
  3835. }
  3836. function yRange(mouseY) {
  3837. var vm = this._view;
  3838. return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
  3839. }
  3840. var element_point = core_element.extend({
  3841. _type: 'point',
  3842. inRange: function(mouseX, mouseY) {
  3843. var vm = this._view;
  3844. return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
  3845. },
  3846. inLabelRange: xRange,
  3847. inXRange: xRange,
  3848. inYRange: yRange,
  3849. getCenterPoint: function() {
  3850. var vm = this._view;
  3851. return {
  3852. x: vm.x,
  3853. y: vm.y
  3854. };
  3855. },
  3856. getArea: function() {
  3857. return Math.PI * Math.pow(this._view.radius, 2);
  3858. },
  3859. tooltipPosition: function() {
  3860. var vm = this._view;
  3861. return {
  3862. x: vm.x,
  3863. y: vm.y,
  3864. padding: vm.radius + vm.borderWidth
  3865. };
  3866. },
  3867. draw: function(chartArea) {
  3868. var vm = this._view;
  3869. var ctx = this._chart.ctx;
  3870. var pointStyle = vm.pointStyle;
  3871. var rotation = vm.rotation;
  3872. var radius = vm.radius;
  3873. var x = vm.x;
  3874. var y = vm.y;
  3875. var globalDefaults = core_defaults.global;
  3876. var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow
  3877. if (vm.skip) {
  3878. return;
  3879. }
  3880. // Clipping for Points.
  3881. if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) {
  3882. ctx.strokeStyle = vm.borderColor || defaultColor;
  3883. ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth);
  3884. ctx.fillStyle = vm.backgroundColor || defaultColor;
  3885. helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
  3886. }
  3887. }
  3888. });
  3889. var defaultColor$2 = core_defaults.global.defaultColor;
  3890. core_defaults._set('global', {
  3891. elements: {
  3892. rectangle: {
  3893. backgroundColor: defaultColor$2,
  3894. borderColor: defaultColor$2,
  3895. borderSkipped: 'bottom',
  3896. borderWidth: 0
  3897. }
  3898. }
  3899. });
  3900. function isVertical(vm) {
  3901. return vm && vm.width !== undefined;
  3902. }
  3903. /**
  3904. * Helper function to get the bounds of the bar regardless of the orientation
  3905. * @param bar {Chart.Element.Rectangle} the bar
  3906. * @return {Bounds} bounds of the bar
  3907. * @private
  3908. */
  3909. function getBarBounds(vm) {
  3910. var x1, x2, y1, y2, half;
  3911. if (isVertical(vm)) {
  3912. half = vm.width / 2;
  3913. x1 = vm.x - half;
  3914. x2 = vm.x + half;
  3915. y1 = Math.min(vm.y, vm.base);
  3916. y2 = Math.max(vm.y, vm.base);
  3917. } else {
  3918. half = vm.height / 2;
  3919. x1 = Math.min(vm.x, vm.base);
  3920. x2 = Math.max(vm.x, vm.base);
  3921. y1 = vm.y - half;
  3922. y2 = vm.y + half;
  3923. }
  3924. return {
  3925. left: x1,
  3926. top: y1,
  3927. right: x2,
  3928. bottom: y2
  3929. };
  3930. }
  3931. function swap(orig, v1, v2) {
  3932. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  3933. }
  3934. function parseBorderSkipped(vm) {
  3935. var edge = vm.borderSkipped;
  3936. var res = {};
  3937. if (!edge) {
  3938. return res;
  3939. }
  3940. if (vm.horizontal) {
  3941. if (vm.base > vm.x) {
  3942. edge = swap(edge, 'left', 'right');
  3943. }
  3944. } else if (vm.base < vm.y) {
  3945. edge = swap(edge, 'bottom', 'top');
  3946. }
  3947. res[edge] = true;
  3948. return res;
  3949. }
  3950. function parseBorderWidth(vm, maxW, maxH) {
  3951. var value = vm.borderWidth;
  3952. var skip = parseBorderSkipped(vm);
  3953. var t, r, b, l;
  3954. if (helpers$1.isObject(value)) {
  3955. t = +value.top || 0;
  3956. r = +value.right || 0;
  3957. b = +value.bottom || 0;
  3958. l = +value.left || 0;
  3959. } else {
  3960. t = r = b = l = +value || 0;
  3961. }
  3962. return {
  3963. t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t,
  3964. r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r,
  3965. b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b,
  3966. l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l
  3967. };
  3968. }
  3969. function boundingRects(vm) {
  3970. var bounds = getBarBounds(vm);
  3971. var width = bounds.right - bounds.left;
  3972. var height = bounds.bottom - bounds.top;
  3973. var border = parseBorderWidth(vm, width / 2, height / 2);
  3974. return {
  3975. outer: {
  3976. x: bounds.left,
  3977. y: bounds.top,
  3978. w: width,
  3979. h: height
  3980. },
  3981. inner: {
  3982. x: bounds.left + border.l,
  3983. y: bounds.top + border.t,
  3984. w: width - border.l - border.r,
  3985. h: height - border.t - border.b
  3986. }
  3987. };
  3988. }
  3989. function inRange(vm, x, y) {
  3990. var skipX = x === null;
  3991. var skipY = y === null;
  3992. var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm);
  3993. return bounds
  3994. && (skipX || x >= bounds.left && x <= bounds.right)
  3995. && (skipY || y >= bounds.top && y <= bounds.bottom);
  3996. }
  3997. var element_rectangle = core_element.extend({
  3998. _type: 'rectangle',
  3999. draw: function() {
  4000. var ctx = this._chart.ctx;
  4001. var vm = this._view;
  4002. var rects = boundingRects(vm);
  4003. var outer = rects.outer;
  4004. var inner = rects.inner;
  4005. ctx.fillStyle = vm.backgroundColor;
  4006. ctx.fillRect(outer.x, outer.y, outer.w, outer.h);
  4007. if (outer.w === inner.w && outer.h === inner.h) {
  4008. return;
  4009. }
  4010. ctx.save();
  4011. ctx.beginPath();
  4012. ctx.rect(outer.x, outer.y, outer.w, outer.h);
  4013. ctx.clip();
  4014. ctx.fillStyle = vm.borderColor;
  4015. ctx.rect(inner.x, inner.y, inner.w, inner.h);
  4016. ctx.fill('evenodd');
  4017. ctx.restore();
  4018. },
  4019. height: function() {
  4020. var vm = this._view;
  4021. return vm.base - vm.y;
  4022. },
  4023. inRange: function(mouseX, mouseY) {
  4024. return inRange(this._view, mouseX, mouseY);
  4025. },
  4026. inLabelRange: function(mouseX, mouseY) {
  4027. var vm = this._view;
  4028. return isVertical(vm)
  4029. ? inRange(vm, mouseX, null)
  4030. : inRange(vm, null, mouseY);
  4031. },
  4032. inXRange: function(mouseX) {
  4033. return inRange(this._view, mouseX, null);
  4034. },
  4035. inYRange: function(mouseY) {
  4036. return inRange(this._view, null, mouseY);
  4037. },
  4038. getCenterPoint: function() {
  4039. var vm = this._view;
  4040. var x, y;
  4041. if (isVertical(vm)) {
  4042. x = vm.x;
  4043. y = (vm.y + vm.base) / 2;
  4044. } else {
  4045. x = (vm.x + vm.base) / 2;
  4046. y = vm.y;
  4047. }
  4048. return {x: x, y: y};
  4049. },
  4050. getArea: function() {
  4051. var vm = this._view;
  4052. return isVertical(vm)
  4053. ? vm.width * Math.abs(vm.y - vm.base)
  4054. : vm.height * Math.abs(vm.x - vm.base);
  4055. },
  4056. tooltipPosition: function() {
  4057. var vm = this._view;
  4058. return {
  4059. x: vm.x,
  4060. y: vm.y
  4061. };
  4062. }
  4063. });
  4064. var elements = {};
  4065. var Arc = element_arc;
  4066. var Line = element_line;
  4067. var Point = element_point;
  4068. var Rectangle = element_rectangle;
  4069. elements.Arc = Arc;
  4070. elements.Line = Line;
  4071. elements.Point = Point;
  4072. elements.Rectangle = Rectangle;
  4073. var deprecated = helpers$1._deprecated;
  4074. var valueOrDefault$3 = helpers$1.valueOrDefault;
  4075. core_defaults._set('bar', {
  4076. hover: {
  4077. mode: 'label'
  4078. },
  4079. scales: {
  4080. xAxes: [{
  4081. type: 'category',
  4082. offset: true,
  4083. gridLines: {
  4084. offsetGridLines: true
  4085. }
  4086. }],
  4087. yAxes: [{
  4088. type: 'linear'
  4089. }]
  4090. }
  4091. });
  4092. core_defaults._set('global', {
  4093. datasets: {
  4094. bar: {
  4095. categoryPercentage: 0.8,
  4096. barPercentage: 0.9
  4097. }
  4098. }
  4099. });
  4100. /**
  4101. * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
  4102. * @private
  4103. */
  4104. function computeMinSampleSize(scale, pixels) {
  4105. var min = scale._length;
  4106. var prev, curr, i, ilen;
  4107. for (i = 1, ilen = pixels.length; i < ilen; ++i) {
  4108. min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
  4109. }
  4110. for (i = 0, ilen = scale.getTicks().length; i < ilen; ++i) {
  4111. curr = scale.getPixelForTick(i);
  4112. min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min;
  4113. prev = curr;
  4114. }
  4115. return min;
  4116. }
  4117. /**
  4118. * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
  4119. * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
  4120. * mode currently always generates bars equally sized (until we introduce scriptable options?).
  4121. * @private
  4122. */
  4123. function computeFitCategoryTraits(index, ruler, options) {
  4124. var thickness = options.barThickness;
  4125. var count = ruler.stackCount;
  4126. var curr = ruler.pixels[index];
  4127. var min = helpers$1.isNullOrUndef(thickness)
  4128. ? computeMinSampleSize(ruler.scale, ruler.pixels)
  4129. : -1;
  4130. var size, ratio;
  4131. if (helpers$1.isNullOrUndef(thickness)) {
  4132. size = min * options.categoryPercentage;
  4133. ratio = options.barPercentage;
  4134. } else {
  4135. // When bar thickness is enforced, category and bar percentages are ignored.
  4136. // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
  4137. // and deprecate barPercentage since this value is ignored when thickness is absolute.
  4138. size = thickness * count;
  4139. ratio = 1;
  4140. }
  4141. return {
  4142. chunk: size / count,
  4143. ratio: ratio,
  4144. start: curr - (size / 2)
  4145. };
  4146. }
  4147. /**
  4148. * Computes an "optimal" category that globally arranges bars side by side (no gap when
  4149. * percentage options are 1), based on the previous and following categories. This mode
  4150. * generates bars with different widths when data are not evenly spaced.
  4151. * @private
  4152. */
  4153. function computeFlexCategoryTraits(index, ruler, options) {
  4154. var pixels = ruler.pixels;
  4155. var curr = pixels[index];
  4156. var prev = index > 0 ? pixels[index - 1] : null;
  4157. var next = index < pixels.length - 1 ? pixels[index + 1] : null;
  4158. var percent = options.categoryPercentage;
  4159. var start, size;
  4160. if (prev === null) {
  4161. // first data: its size is double based on the next point or,
  4162. // if it's also the last data, we use the scale size.
  4163. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  4164. }
  4165. if (next === null) {
  4166. // last data: its size is also double based on the previous point.
  4167. next = curr + curr - prev;
  4168. }
  4169. start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  4170. size = Math.abs(next - prev) / 2 * percent;
  4171. return {
  4172. chunk: size / ruler.stackCount,
  4173. ratio: options.barPercentage,
  4174. start: start
  4175. };
  4176. }
  4177. var controller_bar = core_datasetController.extend({
  4178. dataElementType: elements.Rectangle,
  4179. /**
  4180. * @private
  4181. */
  4182. _dataElementOptions: [
  4183. 'backgroundColor',
  4184. 'borderColor',
  4185. 'borderSkipped',
  4186. 'borderWidth',
  4187. 'barPercentage',
  4188. 'barThickness',
  4189. 'categoryPercentage',
  4190. 'maxBarThickness',
  4191. 'minBarLength'
  4192. ],
  4193. initialize: function() {
  4194. var me = this;
  4195. var meta, scaleOpts;
  4196. core_datasetController.prototype.initialize.apply(me, arguments);
  4197. meta = me.getMeta();
  4198. meta.stack = me.getDataset().stack;
  4199. meta.bar = true;
  4200. scaleOpts = me._getIndexScale().options;
  4201. deprecated('bar chart', scaleOpts.barPercentage, 'scales.[x/y]Axes.barPercentage', 'dataset.barPercentage');
  4202. deprecated('bar chart', scaleOpts.barThickness, 'scales.[x/y]Axes.barThickness', 'dataset.barThickness');
  4203. deprecated('bar chart', scaleOpts.categoryPercentage, 'scales.[x/y]Axes.categoryPercentage', 'dataset.categoryPercentage');
  4204. deprecated('bar chart', me._getValueScale().options.minBarLength, 'scales.[x/y]Axes.minBarLength', 'dataset.minBarLength');
  4205. deprecated('bar chart', scaleOpts.maxBarThickness, 'scales.[x/y]Axes.maxBarThickness', 'dataset.maxBarThickness');
  4206. },
  4207. update: function(reset) {
  4208. var me = this;
  4209. var rects = me.getMeta().data;
  4210. var i, ilen;
  4211. me._ruler = me.getRuler();
  4212. for (i = 0, ilen = rects.length; i < ilen; ++i) {
  4213. me.updateElement(rects[i], i, reset);
  4214. }
  4215. },
  4216. updateElement: function(rectangle, index, reset) {
  4217. var me = this;
  4218. var meta = me.getMeta();
  4219. var dataset = me.getDataset();
  4220. var options = me._resolveDataElementOptions(rectangle, index);
  4221. rectangle._xScale = me.getScaleForId(meta.xAxisID);
  4222. rectangle._yScale = me.getScaleForId(meta.yAxisID);
  4223. rectangle._datasetIndex = me.index;
  4224. rectangle._index = index;
  4225. rectangle._model = {
  4226. backgroundColor: options.backgroundColor,
  4227. borderColor: options.borderColor,
  4228. borderSkipped: options.borderSkipped,
  4229. borderWidth: options.borderWidth,
  4230. datasetLabel: dataset.label,
  4231. label: me.chart.data.labels[index]
  4232. };
  4233. if (helpers$1.isArray(dataset.data[index])) {
  4234. rectangle._model.borderSkipped = null;
  4235. }
  4236. me._updateElementGeometry(rectangle, index, reset, options);
  4237. rectangle.pivot();
  4238. },
  4239. /**
  4240. * @private
  4241. */
  4242. _updateElementGeometry: function(rectangle, index, reset, options) {
  4243. var me = this;
  4244. var model = rectangle._model;
  4245. var vscale = me._getValueScale();
  4246. var base = vscale.getBasePixel();
  4247. var horizontal = vscale.isHorizontal();
  4248. var ruler = me._ruler || me.getRuler();
  4249. var vpixels = me.calculateBarValuePixels(me.index, index, options);
  4250. var ipixels = me.calculateBarIndexPixels(me.index, index, ruler, options);
  4251. model.horizontal = horizontal;
  4252. model.base = reset ? base : vpixels.base;
  4253. model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
  4254. model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
  4255. model.height = horizontal ? ipixels.size : undefined;
  4256. model.width = horizontal ? undefined : ipixels.size;
  4257. },
  4258. /**
  4259. * Returns the stacks based on groups and bar visibility.
  4260. * @param {number} [last] - The dataset index
  4261. * @returns {string[]} The list of stack IDs
  4262. * @private
  4263. */
  4264. _getStacks: function(last) {
  4265. var me = this;
  4266. var scale = me._getIndexScale();
  4267. var metasets = scale._getMatchingVisibleMetas(me._type);
  4268. var stacked = scale.options.stacked;
  4269. var ilen = metasets.length;
  4270. var stacks = [];
  4271. var i, meta;
  4272. for (i = 0; i < ilen; ++i) {
  4273. meta = metasets[i];
  4274. // stacked | meta.stack
  4275. // | found | not found | undefined
  4276. // false | x | x | x
  4277. // true | | x |
  4278. // undefined | | x | x
  4279. if (stacked === false || stacks.indexOf(meta.stack) === -1 ||
  4280. (stacked === undefined && meta.stack === undefined)) {
  4281. stacks.push(meta.stack);
  4282. }
  4283. if (meta.index === last) {
  4284. break;
  4285. }
  4286. }
  4287. return stacks;
  4288. },
  4289. /**
  4290. * Returns the effective number of stacks based on groups and bar visibility.
  4291. * @private
  4292. */
  4293. getStackCount: function() {
  4294. return this._getStacks().length;
  4295. },
  4296. /**
  4297. * Returns the stack index for the given dataset based on groups and bar visibility.
  4298. * @param {number} [datasetIndex] - The dataset index
  4299. * @param {string} [name] - The stack name to find
  4300. * @returns {number} The stack index
  4301. * @private
  4302. */
  4303. getStackIndex: function(datasetIndex, name) {
  4304. var stacks = this._getStacks(datasetIndex);
  4305. var index = (name !== undefined)
  4306. ? stacks.indexOf(name)
  4307. : -1; // indexOf returns -1 if element is not present
  4308. return (index === -1)
  4309. ? stacks.length - 1
  4310. : index;
  4311. },
  4312. /**
  4313. * @private
  4314. */
  4315. getRuler: function() {
  4316. var me = this;
  4317. var scale = me._getIndexScale();
  4318. var pixels = [];
  4319. var i, ilen;
  4320. for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
  4321. pixels.push(scale.getPixelForValue(null, i, me.index));
  4322. }
  4323. return {
  4324. pixels: pixels,
  4325. start: scale._startPixel,
  4326. end: scale._endPixel,
  4327. stackCount: me.getStackCount(),
  4328. scale: scale
  4329. };
  4330. },
  4331. /**
  4332. * Note: pixel values are not clamped to the scale area.
  4333. * @private
  4334. */
  4335. calculateBarValuePixels: function(datasetIndex, index, options) {
  4336. var me = this;
  4337. var chart = me.chart;
  4338. var scale = me._getValueScale();
  4339. var isHorizontal = scale.isHorizontal();
  4340. var datasets = chart.data.datasets;
  4341. var metasets = scale._getMatchingVisibleMetas(me._type);
  4342. var value = scale._parseValue(datasets[datasetIndex].data[index]);
  4343. var minBarLength = options.minBarLength;
  4344. var stacked = scale.options.stacked;
  4345. var stack = me.getMeta().stack;
  4346. var start = value.start === undefined ? 0 : value.max >= 0 && value.min >= 0 ? value.min : value.max;
  4347. var length = value.start === undefined ? value.end : value.max >= 0 && value.min >= 0 ? value.max - value.min : value.min - value.max;
  4348. var ilen = metasets.length;
  4349. var i, imeta, ivalue, base, head, size, stackLength;
  4350. if (stacked || (stacked === undefined && stack !== undefined)) {
  4351. for (i = 0; i < ilen; ++i) {
  4352. imeta = metasets[i];
  4353. if (imeta.index === datasetIndex) {
  4354. break;
  4355. }
  4356. if (imeta.stack === stack) {
  4357. stackLength = scale._parseValue(datasets[imeta.index].data[index]);
  4358. ivalue = stackLength.start === undefined ? stackLength.end : stackLength.min >= 0 && stackLength.max >= 0 ? stackLength.max : stackLength.min;
  4359. if ((value.min < 0 && ivalue < 0) || (value.max >= 0 && ivalue > 0)) {
  4360. start += ivalue;
  4361. }
  4362. }
  4363. }
  4364. }
  4365. base = scale.getPixelForValue(start);
  4366. head = scale.getPixelForValue(start + length);
  4367. size = head - base;
  4368. if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
  4369. size = minBarLength;
  4370. if (length >= 0 && !isHorizontal || length < 0 && isHorizontal) {
  4371. head = base - minBarLength;
  4372. } else {
  4373. head = base + minBarLength;
  4374. }
  4375. }
  4376. return {
  4377. size: size,
  4378. base: base,
  4379. head: head,
  4380. center: head + size / 2
  4381. };
  4382. },
  4383. /**
  4384. * @private
  4385. */
  4386. calculateBarIndexPixels: function(datasetIndex, index, ruler, options) {
  4387. var me = this;
  4388. var range = options.barThickness === 'flex'
  4389. ? computeFlexCategoryTraits(index, ruler, options)
  4390. : computeFitCategoryTraits(index, ruler, options);
  4391. var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
  4392. var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  4393. var size = Math.min(
  4394. valueOrDefault$3(options.maxBarThickness, Infinity),
  4395. range.chunk * range.ratio);
  4396. return {
  4397. base: center - size / 2,
  4398. head: center + size / 2,
  4399. center: center,
  4400. size: size
  4401. };
  4402. },
  4403. draw: function() {
  4404. var me = this;
  4405. var chart = me.chart;
  4406. var scale = me._getValueScale();
  4407. var rects = me.getMeta().data;
  4408. var dataset = me.getDataset();
  4409. var ilen = rects.length;
  4410. var i = 0;
  4411. helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);
  4412. for (; i < ilen; ++i) {
  4413. var val = scale._parseValue(dataset.data[i]);
  4414. if (!isNaN(val.min) && !isNaN(val.max)) {
  4415. rects[i].draw();
  4416. }
  4417. }
  4418. helpers$1.canvas.unclipArea(chart.ctx);
  4419. },
  4420. /**
  4421. * @private
  4422. */
  4423. _resolveDataElementOptions: function() {
  4424. var me = this;
  4425. var values = helpers$1.extend({}, core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments));
  4426. var indexOpts = me._getIndexScale().options;
  4427. var valueOpts = me._getValueScale().options;
  4428. values.barPercentage = valueOrDefault$3(indexOpts.barPercentage, values.barPercentage);
  4429. values.barThickness = valueOrDefault$3(indexOpts.barThickness, values.barThickness);
  4430. values.categoryPercentage = valueOrDefault$3(indexOpts.categoryPercentage, values.categoryPercentage);
  4431. values.maxBarThickness = valueOrDefault$3(indexOpts.maxBarThickness, values.maxBarThickness);
  4432. values.minBarLength = valueOrDefault$3(valueOpts.minBarLength, values.minBarLength);
  4433. return values;
  4434. }
  4435. });
  4436. var valueOrDefault$4 = helpers$1.valueOrDefault;
  4437. var resolve$1 = helpers$1.options.resolve;
  4438. core_defaults._set('bubble', {
  4439. hover: {
  4440. mode: 'single'
  4441. },
  4442. scales: {
  4443. xAxes: [{
  4444. type: 'linear', // bubble should probably use a linear scale by default
  4445. position: 'bottom',
  4446. id: 'x-axis-0' // need an ID so datasets can reference the scale
  4447. }],
  4448. yAxes: [{
  4449. type: 'linear',
  4450. position: 'left',
  4451. id: 'y-axis-0'
  4452. }]
  4453. },
  4454. tooltips: {
  4455. callbacks: {
  4456. title: function() {
  4457. // Title doesn't make sense for scatter since we format the data as a point
  4458. return '';
  4459. },
  4460. label: function(item, data) {
  4461. var datasetLabel = data.datasets[item.datasetIndex].label || '';
  4462. var dataPoint = data.datasets[item.datasetIndex].data[item.index];
  4463. return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
  4464. }
  4465. }
  4466. }
  4467. });
  4468. var controller_bubble = core_datasetController.extend({
  4469. /**
  4470. * @protected
  4471. */
  4472. dataElementType: elements.Point,
  4473. /**
  4474. * @private
  4475. */
  4476. _dataElementOptions: [
  4477. 'backgroundColor',
  4478. 'borderColor',
  4479. 'borderWidth',
  4480. 'hoverBackgroundColor',
  4481. 'hoverBorderColor',
  4482. 'hoverBorderWidth',
  4483. 'hoverRadius',
  4484. 'hitRadius',
  4485. 'pointStyle',
  4486. 'rotation'
  4487. ],
  4488. /**
  4489. * @protected
  4490. */
  4491. update: function(reset) {
  4492. var me = this;
  4493. var meta = me.getMeta();
  4494. var points = meta.data;
  4495. // Update Points
  4496. helpers$1.each(points, function(point, index) {
  4497. me.updateElement(point, index, reset);
  4498. });
  4499. },
  4500. /**
  4501. * @protected
  4502. */
  4503. updateElement: function(point, index, reset) {
  4504. var me = this;
  4505. var meta = me.getMeta();
  4506. var custom = point.custom || {};
  4507. var xScale = me.getScaleForId(meta.xAxisID);
  4508. var yScale = me.getScaleForId(meta.yAxisID);
  4509. var options = me._resolveDataElementOptions(point, index);
  4510. var data = me.getDataset().data[index];
  4511. var dsIndex = me.index;
  4512. var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
  4513. var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
  4514. point._xScale = xScale;
  4515. point._yScale = yScale;
  4516. point._options = options;
  4517. point._datasetIndex = dsIndex;
  4518. point._index = index;
  4519. point._model = {
  4520. backgroundColor: options.backgroundColor,
  4521. borderColor: options.borderColor,
  4522. borderWidth: options.borderWidth,
  4523. hitRadius: options.hitRadius,
  4524. pointStyle: options.pointStyle,
  4525. rotation: options.rotation,
  4526. radius: reset ? 0 : options.radius,
  4527. skip: custom.skip || isNaN(x) || isNaN(y),
  4528. x: x,
  4529. y: y,
  4530. };
  4531. point.pivot();
  4532. },
  4533. /**
  4534. * @protected
  4535. */
  4536. setHoverStyle: function(point) {
  4537. var model = point._model;
  4538. var options = point._options;
  4539. var getHoverColor = helpers$1.getHoverColor;
  4540. point.$previousStyle = {
  4541. backgroundColor: model.backgroundColor,
  4542. borderColor: model.borderColor,
  4543. borderWidth: model.borderWidth,
  4544. radius: model.radius
  4545. };
  4546. model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4547. model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor));
  4548. model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth);
  4549. model.radius = options.radius + options.hoverRadius;
  4550. },
  4551. /**
  4552. * @private
  4553. */
  4554. _resolveDataElementOptions: function(point, index) {
  4555. var me = this;
  4556. var chart = me.chart;
  4557. var dataset = me.getDataset();
  4558. var custom = point.custom || {};
  4559. var data = dataset.data[index] || {};
  4560. var values = core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments);
  4561. // Scriptable options
  4562. var context = {
  4563. chart: chart,
  4564. dataIndex: index,
  4565. dataset: dataset,
  4566. datasetIndex: me.index
  4567. };
  4568. // In case values were cached (and thus frozen), we need to clone the values
  4569. if (me._cachedDataOpts === values) {
  4570. values = helpers$1.extend({}, values);
  4571. }
  4572. // Custom radius resolution
  4573. values.radius = resolve$1([
  4574. custom.radius,
  4575. data.r,
  4576. me._config.radius,
  4577. chart.options.elements.point.radius
  4578. ], context, index);
  4579. return values;
  4580. }
  4581. });
  4582. var valueOrDefault$5 = helpers$1.valueOrDefault;
  4583. var PI$1 = Math.PI;
  4584. var DOUBLE_PI$1 = PI$1 * 2;
  4585. var HALF_PI$1 = PI$1 / 2;
  4586. core_defaults._set('doughnut', {
  4587. animation: {
  4588. // Boolean - Whether we animate the rotation of the Doughnut
  4589. animateRotate: true,
  4590. // Boolean - Whether we animate scaling the Doughnut from the centre
  4591. animateScale: false
  4592. },
  4593. hover: {
  4594. mode: 'single'
  4595. },
  4596. legendCallback: function(chart) {
  4597. var list = document.createElement('ul');
  4598. var data = chart.data;
  4599. var datasets = data.datasets;
  4600. var labels = data.labels;
  4601. var i, ilen, listItem, listItemSpan;
  4602. list.setAttribute('class', chart.id + '-legend');
  4603. if (datasets.length) {
  4604. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  4605. listItem = list.appendChild(document.createElement('li'));
  4606. listItemSpan = listItem.appendChild(document.createElement('span'));
  4607. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  4608. if (labels[i]) {
  4609. listItem.appendChild(document.createTextNode(labels[i]));
  4610. }
  4611. }
  4612. }
  4613. return list.outerHTML;
  4614. },
  4615. legend: {
  4616. labels: {
  4617. generateLabels: function(chart) {
  4618. var data = chart.data;
  4619. if (data.labels.length && data.datasets.length) {
  4620. return data.labels.map(function(label, i) {
  4621. var meta = chart.getDatasetMeta(0);
  4622. var style = meta.controller.getStyle(i);
  4623. return {
  4624. text: label,
  4625. fillStyle: style.backgroundColor,
  4626. strokeStyle: style.borderColor,
  4627. lineWidth: style.borderWidth,
  4628. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  4629. // Extra data used for toggling the correct item
  4630. index: i
  4631. };
  4632. });
  4633. }
  4634. return [];
  4635. }
  4636. },
  4637. onClick: function(e, legendItem) {
  4638. var index = legendItem.index;
  4639. var chart = this.chart;
  4640. var i, ilen, meta;
  4641. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  4642. meta = chart.getDatasetMeta(i);
  4643. // toggle visibility of index if exists
  4644. if (meta.data[index]) {
  4645. meta.data[index].hidden = !meta.data[index].hidden;
  4646. }
  4647. }
  4648. chart.update();
  4649. }
  4650. },
  4651. // The percentage of the chart that we cut out of the middle.
  4652. cutoutPercentage: 50,
  4653. // The rotation of the chart, where the first data arc begins.
  4654. rotation: -HALF_PI$1,
  4655. // The total circumference of the chart.
  4656. circumference: DOUBLE_PI$1,
  4657. // Need to override these to give a nice default
  4658. tooltips: {
  4659. callbacks: {
  4660. title: function() {
  4661. return '';
  4662. },
  4663. label: function(tooltipItem, data) {
  4664. var dataLabel = data.labels[tooltipItem.index];
  4665. var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
  4666. if (helpers$1.isArray(dataLabel)) {
  4667. // show value on first line of multiline label
  4668. // need to clone because we are changing the value
  4669. dataLabel = dataLabel.slice();
  4670. dataLabel[0] += value;
  4671. } else {
  4672. dataLabel += value;
  4673. }
  4674. return dataLabel;
  4675. }
  4676. }
  4677. }
  4678. });
  4679. var controller_doughnut = core_datasetController.extend({
  4680. dataElementType: elements.Arc,
  4681. linkScales: helpers$1.noop,
  4682. /**
  4683. * @private
  4684. */
  4685. _dataElementOptions: [
  4686. 'backgroundColor',
  4687. 'borderColor',
  4688. 'borderWidth',
  4689. 'borderAlign',
  4690. 'hoverBackgroundColor',
  4691. 'hoverBorderColor',
  4692. 'hoverBorderWidth',
  4693. ],
  4694. // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
  4695. getRingIndex: function(datasetIndex) {
  4696. var ringIndex = 0;
  4697. for (var j = 0; j < datasetIndex; ++j) {
  4698. if (this.chart.isDatasetVisible(j)) {
  4699. ++ringIndex;
  4700. }
  4701. }
  4702. return ringIndex;
  4703. },
  4704. update: function(reset) {
  4705. var me = this;
  4706. var chart = me.chart;
  4707. var chartArea = chart.chartArea;
  4708. var opts = chart.options;
  4709. var ratioX = 1;
  4710. var ratioY = 1;
  4711. var offsetX = 0;
  4712. var offsetY = 0;
  4713. var meta = me.getMeta();
  4714. var arcs = meta.data;
  4715. var cutout = opts.cutoutPercentage / 100 || 0;
  4716. var circumference = opts.circumference;
  4717. var chartWeight = me._getRingWeight(me.index);
  4718. var maxWidth, maxHeight, i, ilen;
  4719. // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc
  4720. if (circumference < DOUBLE_PI$1) {
  4721. var startAngle = opts.rotation % DOUBLE_PI$1;
  4722. startAngle += startAngle >= PI$1 ? -DOUBLE_PI$1 : startAngle < -PI$1 ? DOUBLE_PI$1 : 0;
  4723. var endAngle = startAngle + circumference;
  4724. var startX = Math.cos(startAngle);
  4725. var startY = Math.sin(startAngle);
  4726. var endX = Math.cos(endAngle);
  4727. var endY = Math.sin(endAngle);
  4728. var contains0 = (startAngle <= 0 && endAngle >= 0) || endAngle >= DOUBLE_PI$1;
  4729. var contains90 = (startAngle <= HALF_PI$1 && endAngle >= HALF_PI$1) || endAngle >= DOUBLE_PI$1 + HALF_PI$1;
  4730. var contains180 = startAngle === -PI$1 || endAngle >= PI$1;
  4731. var contains270 = (startAngle <= -HALF_PI$1 && endAngle >= -HALF_PI$1) || endAngle >= PI$1 + HALF_PI$1;
  4732. var minX = contains180 ? -1 : Math.min(startX, startX * cutout, endX, endX * cutout);
  4733. var minY = contains270 ? -1 : Math.min(startY, startY * cutout, endY, endY * cutout);
  4734. var maxX = contains0 ? 1 : Math.max(startX, startX * cutout, endX, endX * cutout);
  4735. var maxY = contains90 ? 1 : Math.max(startY, startY * cutout, endY, endY * cutout);
  4736. ratioX = (maxX - minX) / 2;
  4737. ratioY = (maxY - minY) / 2;
  4738. offsetX = -(maxX + minX) / 2;
  4739. offsetY = -(maxY + minY) / 2;
  4740. }
  4741. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4742. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  4743. }
  4744. chart.borderWidth = me.getMaxBorderWidth();
  4745. maxWidth = (chartArea.right - chartArea.left - chart.borderWidth) / ratioX;
  4746. maxHeight = (chartArea.bottom - chartArea.top - chart.borderWidth) / ratioY;
  4747. chart.outerRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  4748. chart.innerRadius = Math.max(chart.outerRadius * cutout, 0);
  4749. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
  4750. chart.offsetX = offsetX * chart.outerRadius;
  4751. chart.offsetY = offsetY * chart.outerRadius;
  4752. meta.total = me.calculateTotal();
  4753. me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
  4754. me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
  4755. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4756. me.updateElement(arcs[i], i, reset);
  4757. }
  4758. },
  4759. updateElement: function(arc, index, reset) {
  4760. var me = this;
  4761. var chart = me.chart;
  4762. var chartArea = chart.chartArea;
  4763. var opts = chart.options;
  4764. var animationOpts = opts.animation;
  4765. var centerX = (chartArea.left + chartArea.right) / 2;
  4766. var centerY = (chartArea.top + chartArea.bottom) / 2;
  4767. var startAngle = opts.rotation; // non reset case handled later
  4768. var endAngle = opts.rotation; // non reset case handled later
  4769. var dataset = me.getDataset();
  4770. var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / DOUBLE_PI$1);
  4771. var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
  4772. var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
  4773. var options = arc._options || {};
  4774. helpers$1.extend(arc, {
  4775. // Utility
  4776. _datasetIndex: me.index,
  4777. _index: index,
  4778. // Desired view properties
  4779. _model: {
  4780. backgroundColor: options.backgroundColor,
  4781. borderColor: options.borderColor,
  4782. borderWidth: options.borderWidth,
  4783. borderAlign: options.borderAlign,
  4784. x: centerX + chart.offsetX,
  4785. y: centerY + chart.offsetY,
  4786. startAngle: startAngle,
  4787. endAngle: endAngle,
  4788. circumference: circumference,
  4789. outerRadius: outerRadius,
  4790. innerRadius: innerRadius,
  4791. label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
  4792. }
  4793. });
  4794. var model = arc._model;
  4795. // Set correct angles if not resetting
  4796. if (!reset || !animationOpts.animateRotate) {
  4797. if (index === 0) {
  4798. model.startAngle = opts.rotation;
  4799. } else {
  4800. model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
  4801. }
  4802. model.endAngle = model.startAngle + model.circumference;
  4803. }
  4804. arc.pivot();
  4805. },
  4806. calculateTotal: function() {
  4807. var dataset = this.getDataset();
  4808. var meta = this.getMeta();
  4809. var total = 0;
  4810. var value;
  4811. helpers$1.each(meta.data, function(element, index) {
  4812. value = dataset.data[index];
  4813. if (!isNaN(value) && !element.hidden) {
  4814. total += Math.abs(value);
  4815. }
  4816. });
  4817. /* if (total === 0) {
  4818. total = NaN;
  4819. }*/
  4820. return total;
  4821. },
  4822. calculateCircumference: function(value) {
  4823. var total = this.getMeta().total;
  4824. if (total > 0 && !isNaN(value)) {
  4825. return DOUBLE_PI$1 * (Math.abs(value) / total);
  4826. }
  4827. return 0;
  4828. },
  4829. // gets the max border or hover width to properly scale pie charts
  4830. getMaxBorderWidth: function(arcs) {
  4831. var me = this;
  4832. var max = 0;
  4833. var chart = me.chart;
  4834. var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
  4835. if (!arcs) {
  4836. // Find the outmost visible dataset
  4837. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  4838. if (chart.isDatasetVisible(i)) {
  4839. meta = chart.getDatasetMeta(i);
  4840. arcs = meta.data;
  4841. if (i !== me.index) {
  4842. controller = meta.controller;
  4843. }
  4844. break;
  4845. }
  4846. }
  4847. }
  4848. if (!arcs) {
  4849. return 0;
  4850. }
  4851. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4852. arc = arcs[i];
  4853. if (controller) {
  4854. controller._configure();
  4855. options = controller._resolveDataElementOptions(arc, i);
  4856. } else {
  4857. options = arc._options;
  4858. }
  4859. if (options.borderAlign !== 'inner') {
  4860. borderWidth = options.borderWidth;
  4861. hoverWidth = options.hoverBorderWidth;
  4862. max = borderWidth > max ? borderWidth : max;
  4863. max = hoverWidth > max ? hoverWidth : max;
  4864. }
  4865. }
  4866. return max;
  4867. },
  4868. /**
  4869. * @protected
  4870. */
  4871. setHoverStyle: function(arc) {
  4872. var model = arc._model;
  4873. var options = arc._options;
  4874. var getHoverColor = helpers$1.getHoverColor;
  4875. arc.$previousStyle = {
  4876. backgroundColor: model.backgroundColor,
  4877. borderColor: model.borderColor,
  4878. borderWidth: model.borderWidth,
  4879. };
  4880. model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4881. model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor));
  4882. model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth);
  4883. },
  4884. /**
  4885. * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
  4886. * @private
  4887. */
  4888. _getRingWeightOffset: function(datasetIndex) {
  4889. var ringWeightOffset = 0;
  4890. for (var i = 0; i < datasetIndex; ++i) {
  4891. if (this.chart.isDatasetVisible(i)) {
  4892. ringWeightOffset += this._getRingWeight(i);
  4893. }
  4894. }
  4895. return ringWeightOffset;
  4896. },
  4897. /**
  4898. * @private
  4899. */
  4900. _getRingWeight: function(dataSetIndex) {
  4901. return Math.max(valueOrDefault$5(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
  4902. },
  4903. /**
  4904. * Returns the sum of all visibile data set weights. This value can be 0.
  4905. * @private
  4906. */
  4907. _getVisibleDatasetWeightTotal: function() {
  4908. return this._getRingWeightOffset(this.chart.data.datasets.length);
  4909. }
  4910. });
  4911. core_defaults._set('horizontalBar', {
  4912. hover: {
  4913. mode: 'index',
  4914. axis: 'y'
  4915. },
  4916. scales: {
  4917. xAxes: [{
  4918. type: 'linear',
  4919. position: 'bottom'
  4920. }],
  4921. yAxes: [{
  4922. type: 'category',
  4923. position: 'left',
  4924. offset: true,
  4925. gridLines: {
  4926. offsetGridLines: true
  4927. }
  4928. }]
  4929. },
  4930. elements: {
  4931. rectangle: {
  4932. borderSkipped: 'left'
  4933. }
  4934. },
  4935. tooltips: {
  4936. mode: 'index',
  4937. axis: 'y'
  4938. }
  4939. });
  4940. core_defaults._set('global', {
  4941. datasets: {
  4942. horizontalBar: {
  4943. categoryPercentage: 0.8,
  4944. barPercentage: 0.9
  4945. }
  4946. }
  4947. });
  4948. var controller_horizontalBar = controller_bar.extend({
  4949. /**
  4950. * @private
  4951. */
  4952. _getValueScaleId: function() {
  4953. return this.getMeta().xAxisID;
  4954. },
  4955. /**
  4956. * @private
  4957. */
  4958. _getIndexScaleId: function() {
  4959. return this.getMeta().yAxisID;
  4960. }
  4961. });
  4962. var valueOrDefault$6 = helpers$1.valueOrDefault;
  4963. var resolve$2 = helpers$1.options.resolve;
  4964. var isPointInArea = helpers$1.canvas._isPointInArea;
  4965. core_defaults._set('line', {
  4966. showLines: true,
  4967. spanGaps: false,
  4968. hover: {
  4969. mode: 'label'
  4970. },
  4971. scales: {
  4972. xAxes: [{
  4973. type: 'category',
  4974. id: 'x-axis-0'
  4975. }],
  4976. yAxes: [{
  4977. type: 'linear',
  4978. id: 'y-axis-0'
  4979. }]
  4980. }
  4981. });
  4982. function scaleClip(scale, halfBorderWidth) {
  4983. var tickOpts = scale && scale.options.ticks || {};
  4984. var reverse = tickOpts.reverse;
  4985. var min = tickOpts.min === undefined ? halfBorderWidth : 0;
  4986. var max = tickOpts.max === undefined ? halfBorderWidth : 0;
  4987. return {
  4988. start: reverse ? max : min,
  4989. end: reverse ? min : max
  4990. };
  4991. }
  4992. function defaultClip(xScale, yScale, borderWidth) {
  4993. var halfBorderWidth = borderWidth / 2;
  4994. var x = scaleClip(xScale, halfBorderWidth);
  4995. var y = scaleClip(yScale, halfBorderWidth);
  4996. return {
  4997. top: y.end,
  4998. right: x.end,
  4999. bottom: y.start,
  5000. left: x.start
  5001. };
  5002. }
  5003. function toClip(value) {
  5004. var t, r, b, l;
  5005. if (helpers$1.isObject(value)) {
  5006. t = value.top;
  5007. r = value.right;
  5008. b = value.bottom;
  5009. l = value.left;
  5010. } else {
  5011. t = r = b = l = value;
  5012. }
  5013. return {
  5014. top: t,
  5015. right: r,
  5016. bottom: b,
  5017. left: l
  5018. };
  5019. }
  5020. var controller_line = core_datasetController.extend({
  5021. datasetElementType: elements.Line,
  5022. dataElementType: elements.Point,
  5023. /**
  5024. * @private
  5025. */
  5026. _datasetElementOptions: [
  5027. 'backgroundColor',
  5028. 'borderCapStyle',
  5029. 'borderColor',
  5030. 'borderDash',
  5031. 'borderDashOffset',
  5032. 'borderJoinStyle',
  5033. 'borderWidth',
  5034. 'cubicInterpolationMode',
  5035. 'fill'
  5036. ],
  5037. /**
  5038. * @private
  5039. */
  5040. _dataElementOptions: {
  5041. backgroundColor: 'pointBackgroundColor',
  5042. borderColor: 'pointBorderColor',
  5043. borderWidth: 'pointBorderWidth',
  5044. hitRadius: 'pointHitRadius',
  5045. hoverBackgroundColor: 'pointHoverBackgroundColor',
  5046. hoverBorderColor: 'pointHoverBorderColor',
  5047. hoverBorderWidth: 'pointHoverBorderWidth',
  5048. hoverRadius: 'pointHoverRadius',
  5049. pointStyle: 'pointStyle',
  5050. radius: 'pointRadius',
  5051. rotation: 'pointRotation'
  5052. },
  5053. update: function(reset) {
  5054. var me = this;
  5055. var meta = me.getMeta();
  5056. var line = meta.dataset;
  5057. var points = meta.data || [];
  5058. var options = me.chart.options;
  5059. var config = me._config;
  5060. var showLine = me._showLine = valueOrDefault$6(config.showLine, options.showLines);
  5061. var i, ilen;
  5062. me._xScale = me.getScaleForId(meta.xAxisID);
  5063. me._yScale = me.getScaleForId(meta.yAxisID);
  5064. // Update Line
  5065. if (showLine) {
  5066. // Compatibility: If the properties are defined with only the old name, use those values
  5067. if (config.tension !== undefined && config.lineTension === undefined) {
  5068. config.lineTension = config.tension;
  5069. }
  5070. // Utility
  5071. line._scale = me._yScale;
  5072. line._datasetIndex = me.index;
  5073. // Data
  5074. line._children = points;
  5075. // Model
  5076. line._model = me._resolveDatasetElementOptions(line);
  5077. line.pivot();
  5078. }
  5079. // Update Points
  5080. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5081. me.updateElement(points[i], i, reset);
  5082. }
  5083. if (showLine && line._model.tension !== 0) {
  5084. me.updateBezierControlPoints();
  5085. }
  5086. // Now pivot the point for animation
  5087. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5088. points[i].pivot();
  5089. }
  5090. },
  5091. updateElement: function(point, index, reset) {
  5092. var me = this;
  5093. var meta = me.getMeta();
  5094. var custom = point.custom || {};
  5095. var dataset = me.getDataset();
  5096. var datasetIndex = me.index;
  5097. var value = dataset.data[index];
  5098. var xScale = me._xScale;
  5099. var yScale = me._yScale;
  5100. var lineModel = meta.dataset._model;
  5101. var x, y;
  5102. var options = me._resolveDataElementOptions(point, index);
  5103. x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
  5104. y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
  5105. // Utility
  5106. point._xScale = xScale;
  5107. point._yScale = yScale;
  5108. point._options = options;
  5109. point._datasetIndex = datasetIndex;
  5110. point._index = index;
  5111. // Desired view properties
  5112. point._model = {
  5113. x: x,
  5114. y: y,
  5115. skip: custom.skip || isNaN(x) || isNaN(y),
  5116. // Appearance
  5117. radius: options.radius,
  5118. pointStyle: options.pointStyle,
  5119. rotation: options.rotation,
  5120. backgroundColor: options.backgroundColor,
  5121. borderColor: options.borderColor,
  5122. borderWidth: options.borderWidth,
  5123. tension: valueOrDefault$6(custom.tension, lineModel ? lineModel.tension : 0),
  5124. steppedLine: lineModel ? lineModel.steppedLine : false,
  5125. // Tooltip
  5126. hitRadius: options.hitRadius
  5127. };
  5128. },
  5129. /**
  5130. * @private
  5131. */
  5132. _resolveDatasetElementOptions: function(element) {
  5133. var me = this;
  5134. var config = me._config;
  5135. var custom = element.custom || {};
  5136. var options = me.chart.options;
  5137. var lineOptions = options.elements.line;
  5138. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  5139. // The default behavior of lines is to break at null values, according
  5140. // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
  5141. // This option gives lines the ability to span gaps
  5142. values.spanGaps = valueOrDefault$6(config.spanGaps, options.spanGaps);
  5143. values.tension = valueOrDefault$6(config.lineTension, lineOptions.tension);
  5144. values.steppedLine = resolve$2([custom.steppedLine, config.steppedLine, lineOptions.stepped]);
  5145. values.clip = toClip(valueOrDefault$6(config.clip, defaultClip(me._xScale, me._yScale, values.borderWidth)));
  5146. return values;
  5147. },
  5148. calculatePointY: function(value, index, datasetIndex) {
  5149. var me = this;
  5150. var chart = me.chart;
  5151. var yScale = me._yScale;
  5152. var sumPos = 0;
  5153. var sumNeg = 0;
  5154. var i, ds, dsMeta, stackedRightValue, rightValue, metasets, ilen;
  5155. if (yScale.options.stacked) {
  5156. rightValue = +yScale.getRightValue(value);
  5157. metasets = chart._getSortedVisibleDatasetMetas();
  5158. ilen = metasets.length;
  5159. for (i = 0; i < ilen; ++i) {
  5160. dsMeta = metasets[i];
  5161. if (dsMeta.index === datasetIndex) {
  5162. break;
  5163. }
  5164. ds = chart.data.datasets[dsMeta.index];
  5165. if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id) {
  5166. stackedRightValue = +yScale.getRightValue(ds.data[index]);
  5167. if (stackedRightValue < 0) {
  5168. sumNeg += stackedRightValue || 0;
  5169. } else {
  5170. sumPos += stackedRightValue || 0;
  5171. }
  5172. }
  5173. }
  5174. if (rightValue < 0) {
  5175. return yScale.getPixelForValue(sumNeg + rightValue);
  5176. }
  5177. return yScale.getPixelForValue(sumPos + rightValue);
  5178. }
  5179. return yScale.getPixelForValue(value);
  5180. },
  5181. updateBezierControlPoints: function() {
  5182. var me = this;
  5183. var chart = me.chart;
  5184. var meta = me.getMeta();
  5185. var lineModel = meta.dataset._model;
  5186. var area = chart.chartArea;
  5187. var points = meta.data || [];
  5188. var i, ilen, model, controlPoints;
  5189. // Only consider points that are drawn in case the spanGaps option is used
  5190. if (lineModel.spanGaps) {
  5191. points = points.filter(function(pt) {
  5192. return !pt._model.skip;
  5193. });
  5194. }
  5195. function capControlPoint(pt, min, max) {
  5196. return Math.max(Math.min(pt, max), min);
  5197. }
  5198. if (lineModel.cubicInterpolationMode === 'monotone') {
  5199. helpers$1.splineCurveMonotone(points);
  5200. } else {
  5201. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5202. model = points[i]._model;
  5203. controlPoints = helpers$1.splineCurve(
  5204. helpers$1.previousItem(points, i)._model,
  5205. model,
  5206. helpers$1.nextItem(points, i)._model,
  5207. lineModel.tension
  5208. );
  5209. model.controlPointPreviousX = controlPoints.previous.x;
  5210. model.controlPointPreviousY = controlPoints.previous.y;
  5211. model.controlPointNextX = controlPoints.next.x;
  5212. model.controlPointNextY = controlPoints.next.y;
  5213. }
  5214. }
  5215. if (chart.options.elements.line.capBezierPoints) {
  5216. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5217. model = points[i]._model;
  5218. if (isPointInArea(model, area)) {
  5219. if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
  5220. model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
  5221. model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
  5222. }
  5223. if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
  5224. model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
  5225. model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
  5226. }
  5227. }
  5228. }
  5229. }
  5230. },
  5231. draw: function() {
  5232. var me = this;
  5233. var chart = me.chart;
  5234. var meta = me.getMeta();
  5235. var points = meta.data || [];
  5236. var area = chart.chartArea;
  5237. var canvas = chart.canvas;
  5238. var i = 0;
  5239. var ilen = points.length;
  5240. var clip;
  5241. if (me._showLine) {
  5242. clip = meta.dataset._model.clip;
  5243. helpers$1.canvas.clipArea(chart.ctx, {
  5244. left: clip.left === false ? 0 : area.left - clip.left,
  5245. right: clip.right === false ? canvas.width : area.right + clip.right,
  5246. top: clip.top === false ? 0 : area.top - clip.top,
  5247. bottom: clip.bottom === false ? canvas.height : area.bottom + clip.bottom
  5248. });
  5249. meta.dataset.draw();
  5250. helpers$1.canvas.unclipArea(chart.ctx);
  5251. }
  5252. // Draw the points
  5253. for (; i < ilen; ++i) {
  5254. points[i].draw(area);
  5255. }
  5256. },
  5257. /**
  5258. * @protected
  5259. */
  5260. setHoverStyle: function(point) {
  5261. var model = point._model;
  5262. var options = point._options;
  5263. var getHoverColor = helpers$1.getHoverColor;
  5264. point.$previousStyle = {
  5265. backgroundColor: model.backgroundColor,
  5266. borderColor: model.borderColor,
  5267. borderWidth: model.borderWidth,
  5268. radius: model.radius
  5269. };
  5270. model.backgroundColor = valueOrDefault$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5271. model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor));
  5272. model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth);
  5273. model.radius = valueOrDefault$6(options.hoverRadius, options.radius);
  5274. },
  5275. });
  5276. var resolve$3 = helpers$1.options.resolve;
  5277. core_defaults._set('polarArea', {
  5278. scale: {
  5279. type: 'radialLinear',
  5280. angleLines: {
  5281. display: false
  5282. },
  5283. gridLines: {
  5284. circular: true
  5285. },
  5286. pointLabels: {
  5287. display: false
  5288. },
  5289. ticks: {
  5290. beginAtZero: true
  5291. }
  5292. },
  5293. // Boolean - Whether to animate the rotation of the chart
  5294. animation: {
  5295. animateRotate: true,
  5296. animateScale: true
  5297. },
  5298. startAngle: -0.5 * Math.PI,
  5299. legendCallback: function(chart) {
  5300. var list = document.createElement('ul');
  5301. var data = chart.data;
  5302. var datasets = data.datasets;
  5303. var labels = data.labels;
  5304. var i, ilen, listItem, listItemSpan;
  5305. list.setAttribute('class', chart.id + '-legend');
  5306. if (datasets.length) {
  5307. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  5308. listItem = list.appendChild(document.createElement('li'));
  5309. listItemSpan = listItem.appendChild(document.createElement('span'));
  5310. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  5311. if (labels[i]) {
  5312. listItem.appendChild(document.createTextNode(labels[i]));
  5313. }
  5314. }
  5315. }
  5316. return list.outerHTML;
  5317. },
  5318. legend: {
  5319. labels: {
  5320. generateLabels: function(chart) {
  5321. var data = chart.data;
  5322. if (data.labels.length && data.datasets.length) {
  5323. return data.labels.map(function(label, i) {
  5324. var meta = chart.getDatasetMeta(0);
  5325. var style = meta.controller.getStyle(i);
  5326. return {
  5327. text: label,
  5328. fillStyle: style.backgroundColor,
  5329. strokeStyle: style.borderColor,
  5330. lineWidth: style.borderWidth,
  5331. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  5332. // Extra data used for toggling the correct item
  5333. index: i
  5334. };
  5335. });
  5336. }
  5337. return [];
  5338. }
  5339. },
  5340. onClick: function(e, legendItem) {
  5341. var index = legendItem.index;
  5342. var chart = this.chart;
  5343. var i, ilen, meta;
  5344. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  5345. meta = chart.getDatasetMeta(i);
  5346. meta.data[index].hidden = !meta.data[index].hidden;
  5347. }
  5348. chart.update();
  5349. }
  5350. },
  5351. // Need to override these to give a nice default
  5352. tooltips: {
  5353. callbacks: {
  5354. title: function() {
  5355. return '';
  5356. },
  5357. label: function(item, data) {
  5358. return data.labels[item.index] + ': ' + item.yLabel;
  5359. }
  5360. }
  5361. }
  5362. });
  5363. var controller_polarArea = core_datasetController.extend({
  5364. dataElementType: elements.Arc,
  5365. linkScales: helpers$1.noop,
  5366. /**
  5367. * @private
  5368. */
  5369. _dataElementOptions: [
  5370. 'backgroundColor',
  5371. 'borderColor',
  5372. 'borderWidth',
  5373. 'borderAlign',
  5374. 'hoverBackgroundColor',
  5375. 'hoverBorderColor',
  5376. 'hoverBorderWidth',
  5377. ],
  5378. /**
  5379. * @private
  5380. */
  5381. _getIndexScaleId: function() {
  5382. return this.chart.scale.id;
  5383. },
  5384. /**
  5385. * @private
  5386. */
  5387. _getValueScaleId: function() {
  5388. return this.chart.scale.id;
  5389. },
  5390. update: function(reset) {
  5391. var me = this;
  5392. var dataset = me.getDataset();
  5393. var meta = me.getMeta();
  5394. var start = me.chart.options.startAngle || 0;
  5395. var starts = me._starts = [];
  5396. var angles = me._angles = [];
  5397. var arcs = meta.data;
  5398. var i, ilen, angle;
  5399. me._updateRadius();
  5400. meta.count = me.countVisibleElements();
  5401. for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
  5402. starts[i] = start;
  5403. angle = me._computeAngle(i);
  5404. angles[i] = angle;
  5405. start += angle;
  5406. }
  5407. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  5408. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  5409. me.updateElement(arcs[i], i, reset);
  5410. }
  5411. },
  5412. /**
  5413. * @private
  5414. */
  5415. _updateRadius: function() {
  5416. var me = this;
  5417. var chart = me.chart;
  5418. var chartArea = chart.chartArea;
  5419. var opts = chart.options;
  5420. var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  5421. chart.outerRadius = Math.max(minSize / 2, 0);
  5422. chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  5423. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
  5424. me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
  5425. me.innerRadius = me.outerRadius - chart.radiusLength;
  5426. },
  5427. updateElement: function(arc, index, reset) {
  5428. var me = this;
  5429. var chart = me.chart;
  5430. var dataset = me.getDataset();
  5431. var opts = chart.options;
  5432. var animationOpts = opts.animation;
  5433. var scale = chart.scale;
  5434. var labels = chart.data.labels;
  5435. var centerX = scale.xCenter;
  5436. var centerY = scale.yCenter;
  5437. // var negHalfPI = -0.5 * Math.PI;
  5438. var datasetStartAngle = opts.startAngle;
  5439. var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  5440. var startAngle = me._starts[index];
  5441. var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
  5442. var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  5443. var options = arc._options || {};
  5444. helpers$1.extend(arc, {
  5445. // Utility
  5446. _datasetIndex: me.index,
  5447. _index: index,
  5448. _scale: scale,
  5449. // Desired view properties
  5450. _model: {
  5451. backgroundColor: options.backgroundColor,
  5452. borderColor: options.borderColor,
  5453. borderWidth: options.borderWidth,
  5454. borderAlign: options.borderAlign,
  5455. x: centerX,
  5456. y: centerY,
  5457. innerRadius: 0,
  5458. outerRadius: reset ? resetRadius : distance,
  5459. startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
  5460. endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
  5461. label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index])
  5462. }
  5463. });
  5464. arc.pivot();
  5465. },
  5466. countVisibleElements: function() {
  5467. var dataset = this.getDataset();
  5468. var meta = this.getMeta();
  5469. var count = 0;
  5470. helpers$1.each(meta.data, function(element, index) {
  5471. if (!isNaN(dataset.data[index]) && !element.hidden) {
  5472. count++;
  5473. }
  5474. });
  5475. return count;
  5476. },
  5477. /**
  5478. * @protected
  5479. */
  5480. setHoverStyle: function(arc) {
  5481. var model = arc._model;
  5482. var options = arc._options;
  5483. var getHoverColor = helpers$1.getHoverColor;
  5484. var valueOrDefault = helpers$1.valueOrDefault;
  5485. arc.$previousStyle = {
  5486. backgroundColor: model.backgroundColor,
  5487. borderColor: model.borderColor,
  5488. borderWidth: model.borderWidth,
  5489. };
  5490. model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5491. model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
  5492. model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
  5493. },
  5494. /**
  5495. * @private
  5496. */
  5497. _computeAngle: function(index) {
  5498. var me = this;
  5499. var count = this.getMeta().count;
  5500. var dataset = me.getDataset();
  5501. var meta = me.getMeta();
  5502. if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
  5503. return 0;
  5504. }
  5505. // Scriptable options
  5506. var context = {
  5507. chart: me.chart,
  5508. dataIndex: index,
  5509. dataset: dataset,
  5510. datasetIndex: me.index
  5511. };
  5512. return resolve$3([
  5513. me.chart.options.elements.arc.angle,
  5514. (2 * Math.PI) / count
  5515. ], context, index);
  5516. }
  5517. });
  5518. core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut));
  5519. core_defaults._set('pie', {
  5520. cutoutPercentage: 0
  5521. });
  5522. // Pie charts are Doughnut chart with different defaults
  5523. var controller_pie = controller_doughnut;
  5524. var valueOrDefault$7 = helpers$1.valueOrDefault;
  5525. core_defaults._set('radar', {
  5526. spanGaps: false,
  5527. scale: {
  5528. type: 'radialLinear'
  5529. },
  5530. elements: {
  5531. line: {
  5532. fill: 'start',
  5533. tension: 0 // no bezier in radar
  5534. }
  5535. }
  5536. });
  5537. var controller_radar = core_datasetController.extend({
  5538. datasetElementType: elements.Line,
  5539. dataElementType: elements.Point,
  5540. linkScales: helpers$1.noop,
  5541. /**
  5542. * @private
  5543. */
  5544. _datasetElementOptions: [
  5545. 'backgroundColor',
  5546. 'borderWidth',
  5547. 'borderColor',
  5548. 'borderCapStyle',
  5549. 'borderDash',
  5550. 'borderDashOffset',
  5551. 'borderJoinStyle',
  5552. 'fill'
  5553. ],
  5554. /**
  5555. * @private
  5556. */
  5557. _dataElementOptions: {
  5558. backgroundColor: 'pointBackgroundColor',
  5559. borderColor: 'pointBorderColor',
  5560. borderWidth: 'pointBorderWidth',
  5561. hitRadius: 'pointHitRadius',
  5562. hoverBackgroundColor: 'pointHoverBackgroundColor',
  5563. hoverBorderColor: 'pointHoverBorderColor',
  5564. hoverBorderWidth: 'pointHoverBorderWidth',
  5565. hoverRadius: 'pointHoverRadius',
  5566. pointStyle: 'pointStyle',
  5567. radius: 'pointRadius',
  5568. rotation: 'pointRotation'
  5569. },
  5570. /**
  5571. * @private
  5572. */
  5573. _getIndexScaleId: function() {
  5574. return this.chart.scale.id;
  5575. },
  5576. /**
  5577. * @private
  5578. */
  5579. _getValueScaleId: function() {
  5580. return this.chart.scale.id;
  5581. },
  5582. update: function(reset) {
  5583. var me = this;
  5584. var meta = me.getMeta();
  5585. var line = meta.dataset;
  5586. var points = meta.data || [];
  5587. var scale = me.chart.scale;
  5588. var config = me._config;
  5589. var i, ilen;
  5590. // Compatibility: If the properties are defined with only the old name, use those values
  5591. if (config.tension !== undefined && config.lineTension === undefined) {
  5592. config.lineTension = config.tension;
  5593. }
  5594. // Utility
  5595. line._scale = scale;
  5596. line._datasetIndex = me.index;
  5597. // Data
  5598. line._children = points;
  5599. line._loop = true;
  5600. // Model
  5601. line._model = me._resolveDatasetElementOptions(line);
  5602. line.pivot();
  5603. // Update Points
  5604. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5605. me.updateElement(points[i], i, reset);
  5606. }
  5607. // Update bezier control points
  5608. me.updateBezierControlPoints();
  5609. // Now pivot the point for animation
  5610. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5611. points[i].pivot();
  5612. }
  5613. },
  5614. updateElement: function(point, index, reset) {
  5615. var me = this;
  5616. var custom = point.custom || {};
  5617. var dataset = me.getDataset();
  5618. var scale = me.chart.scale;
  5619. var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
  5620. var options = me._resolveDataElementOptions(point, index);
  5621. var lineModel = me.getMeta().dataset._model;
  5622. var x = reset ? scale.xCenter : pointPosition.x;
  5623. var y = reset ? scale.yCenter : pointPosition.y;
  5624. // Utility
  5625. point._scale = scale;
  5626. point._options = options;
  5627. point._datasetIndex = me.index;
  5628. point._index = index;
  5629. // Desired view properties
  5630. point._model = {
  5631. x: x, // value not used in dataset scale, but we want a consistent API between scales
  5632. y: y,
  5633. skip: custom.skip || isNaN(x) || isNaN(y),
  5634. // Appearance
  5635. radius: options.radius,
  5636. pointStyle: options.pointStyle,
  5637. rotation: options.rotation,
  5638. backgroundColor: options.backgroundColor,
  5639. borderColor: options.borderColor,
  5640. borderWidth: options.borderWidth,
  5641. tension: valueOrDefault$7(custom.tension, lineModel ? lineModel.tension : 0),
  5642. // Tooltip
  5643. hitRadius: options.hitRadius
  5644. };
  5645. },
  5646. /**
  5647. * @private
  5648. */
  5649. _resolveDatasetElementOptions: function() {
  5650. var me = this;
  5651. var config = me._config;
  5652. var options = me.chart.options;
  5653. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  5654. values.spanGaps = valueOrDefault$7(config.spanGaps, options.spanGaps);
  5655. values.tension = valueOrDefault$7(config.lineTension, options.elements.line.tension);
  5656. return values;
  5657. },
  5658. updateBezierControlPoints: function() {
  5659. var me = this;
  5660. var meta = me.getMeta();
  5661. var area = me.chart.chartArea;
  5662. var points = meta.data || [];
  5663. var i, ilen, model, controlPoints;
  5664. // Only consider points that are drawn in case the spanGaps option is used
  5665. if (meta.dataset._model.spanGaps) {
  5666. points = points.filter(function(pt) {
  5667. return !pt._model.skip;
  5668. });
  5669. }
  5670. function capControlPoint(pt, min, max) {
  5671. return Math.max(Math.min(pt, max), min);
  5672. }
  5673. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5674. model = points[i]._model;
  5675. controlPoints = helpers$1.splineCurve(
  5676. helpers$1.previousItem(points, i, true)._model,
  5677. model,
  5678. helpers$1.nextItem(points, i, true)._model,
  5679. model.tension
  5680. );
  5681. // Prevent the bezier going outside of the bounds of the graph
  5682. model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);
  5683. model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);
  5684. model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);
  5685. model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);
  5686. }
  5687. },
  5688. setHoverStyle: function(point) {
  5689. var model = point._model;
  5690. var options = point._options;
  5691. var getHoverColor = helpers$1.getHoverColor;
  5692. point.$previousStyle = {
  5693. backgroundColor: model.backgroundColor,
  5694. borderColor: model.borderColor,
  5695. borderWidth: model.borderWidth,
  5696. radius: model.radius
  5697. };
  5698. model.backgroundColor = valueOrDefault$7(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5699. model.borderColor = valueOrDefault$7(options.hoverBorderColor, getHoverColor(options.borderColor));
  5700. model.borderWidth = valueOrDefault$7(options.hoverBorderWidth, options.borderWidth);
  5701. model.radius = valueOrDefault$7(options.hoverRadius, options.radius);
  5702. }
  5703. });
  5704. core_defaults._set('scatter', {
  5705. hover: {
  5706. mode: 'single'
  5707. },
  5708. scales: {
  5709. xAxes: [{
  5710. id: 'x-axis-1', // need an ID so datasets can reference the scale
  5711. type: 'linear', // scatter should not use a category axis
  5712. position: 'bottom'
  5713. }],
  5714. yAxes: [{
  5715. id: 'y-axis-1',
  5716. type: 'linear',
  5717. position: 'left'
  5718. }]
  5719. },
  5720. tooltips: {
  5721. callbacks: {
  5722. title: function() {
  5723. return ''; // doesn't make sense for scatter since data are formatted as a point
  5724. },
  5725. label: function(item) {
  5726. return '(' + item.xLabel + ', ' + item.yLabel + ')';
  5727. }
  5728. }
  5729. }
  5730. });
  5731. core_defaults._set('global', {
  5732. datasets: {
  5733. scatter: {
  5734. showLine: false
  5735. }
  5736. }
  5737. });
  5738. // Scatter charts use line controllers
  5739. var controller_scatter = controller_line;
  5740. // NOTE export a map in which the key represents the controller type, not
  5741. // the class, and so must be CamelCase in order to be correctly retrieved
  5742. // by the controller in core.controller.js (`controllers[meta.type]`).
  5743. var controllers = {
  5744. bar: controller_bar,
  5745. bubble: controller_bubble,
  5746. doughnut: controller_doughnut,
  5747. horizontalBar: controller_horizontalBar,
  5748. line: controller_line,
  5749. polarArea: controller_polarArea,
  5750. pie: controller_pie,
  5751. radar: controller_radar,
  5752. scatter: controller_scatter
  5753. };
  5754. /**
  5755. * Helper function to get relative position for an event
  5756. * @param {Event|IEvent} event - The event to get the position for
  5757. * @param {Chart} chart - The chart
  5758. * @returns {object} the event position
  5759. */
  5760. function getRelativePosition(e, chart) {
  5761. if (e.native) {
  5762. return {
  5763. x: e.x,
  5764. y: e.y
  5765. };
  5766. }
  5767. return helpers$1.getRelativePosition(e, chart);
  5768. }
  5769. /**
  5770. * Helper function to traverse all of the visible elements in the chart
  5771. * @param {Chart} chart - the chart
  5772. * @param {function} handler - the callback to execute for each visible item
  5773. */
  5774. function parseVisibleItems(chart, handler) {
  5775. var metasets = chart._getSortedVisibleDatasetMetas();
  5776. var metadata, i, j, ilen, jlen, element;
  5777. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  5778. metadata = metasets[i].data;
  5779. for (j = 0, jlen = metadata.length; j < jlen; ++j) {
  5780. element = metadata[j];
  5781. if (!element._view.skip) {
  5782. handler(element);
  5783. }
  5784. }
  5785. }
  5786. }
  5787. /**
  5788. * Helper function to get the items that intersect the event position
  5789. * @param {ChartElement[]} items - elements to filter
  5790. * @param {object} position - the point to be nearest to
  5791. * @return {ChartElement[]} the nearest items
  5792. */
  5793. function getIntersectItems(chart, position) {
  5794. var elements = [];
  5795. parseVisibleItems(chart, function(element) {
  5796. if (element.inRange(position.x, position.y)) {
  5797. elements.push(element);
  5798. }
  5799. });
  5800. return elements;
  5801. }
  5802. /**
  5803. * Helper function to get the items nearest to the event position considering all visible items in teh chart
  5804. * @param {Chart} chart - the chart to look at elements from
  5805. * @param {object} position - the point to be nearest to
  5806. * @param {boolean} intersect - if true, only consider items that intersect the position
  5807. * @param {function} distanceMetric - function to provide the distance between points
  5808. * @return {ChartElement[]} the nearest items
  5809. */
  5810. function getNearestItems(chart, position, intersect, distanceMetric) {
  5811. var minDistance = Number.POSITIVE_INFINITY;
  5812. var nearestItems = [];
  5813. parseVisibleItems(chart, function(element) {
  5814. if (intersect && !element.inRange(position.x, position.y)) {
  5815. return;
  5816. }
  5817. var center = element.getCenterPoint();
  5818. var distance = distanceMetric(position, center);
  5819. if (distance < minDistance) {
  5820. nearestItems = [element];
  5821. minDistance = distance;
  5822. } else if (distance === minDistance) {
  5823. // Can have multiple items at the same distance in which case we sort by size
  5824. nearestItems.push(element);
  5825. }
  5826. });
  5827. return nearestItems;
  5828. }
  5829. /**
  5830. * Get a distance metric function for two points based on the
  5831. * axis mode setting
  5832. * @param {string} axis - the axis mode. x|y|xy
  5833. */
  5834. function getDistanceMetricForAxis(axis) {
  5835. var useX = axis.indexOf('x') !== -1;
  5836. var useY = axis.indexOf('y') !== -1;
  5837. return function(pt1, pt2) {
  5838. var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  5839. var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  5840. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  5841. };
  5842. }
  5843. function indexMode(chart, e, options) {
  5844. var position = getRelativePosition(e, chart);
  5845. // Default axis for index mode is 'x' to match old behaviour
  5846. options.axis = options.axis || 'x';
  5847. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5848. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5849. var elements = [];
  5850. if (!items.length) {
  5851. return [];
  5852. }
  5853. chart._getSortedVisibleDatasetMetas().forEach(function(meta) {
  5854. var element = meta.data[items[0]._index];
  5855. // don't count items that are skipped (null data)
  5856. if (element && !element._view.skip) {
  5857. elements.push(element);
  5858. }
  5859. });
  5860. return elements;
  5861. }
  5862. /**
  5863. * @interface IInteractionOptions
  5864. */
  5865. /**
  5866. * If true, only consider items that intersect the point
  5867. * @name IInterfaceOptions#boolean
  5868. * @type Boolean
  5869. */
  5870. /**
  5871. * Contains interaction related functions
  5872. * @namespace Chart.Interaction
  5873. */
  5874. var core_interaction = {
  5875. // Helper function for different modes
  5876. modes: {
  5877. single: function(chart, e) {
  5878. var position = getRelativePosition(e, chart);
  5879. var elements = [];
  5880. parseVisibleItems(chart, function(element) {
  5881. if (element.inRange(position.x, position.y)) {
  5882. elements.push(element);
  5883. return elements;
  5884. }
  5885. });
  5886. return elements.slice(0, 1);
  5887. },
  5888. /**
  5889. * @function Chart.Interaction.modes.label
  5890. * @deprecated since version 2.4.0
  5891. * @todo remove at version 3
  5892. * @private
  5893. */
  5894. label: indexMode,
  5895. /**
  5896. * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
  5897. * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
  5898. * @function Chart.Interaction.modes.index
  5899. * @since v2.4.0
  5900. * @param {Chart} chart - the chart we are returning items from
  5901. * @param {Event} e - the event we are find things at
  5902. * @param {IInteractionOptions} options - options to use during interaction
  5903. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5904. */
  5905. index: indexMode,
  5906. /**
  5907. * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
  5908. * If the options.intersect is false, we find the nearest item and return the items in that dataset
  5909. * @function Chart.Interaction.modes.dataset
  5910. * @param {Chart} chart - the chart we are returning items from
  5911. * @param {Event} e - the event we are find things at
  5912. * @param {IInteractionOptions} options - options to use during interaction
  5913. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5914. */
  5915. dataset: function(chart, e, options) {
  5916. var position = getRelativePosition(e, chart);
  5917. options.axis = options.axis || 'xy';
  5918. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5919. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5920. if (items.length > 0) {
  5921. items = chart.getDatasetMeta(items[0]._datasetIndex).data;
  5922. }
  5923. return items;
  5924. },
  5925. /**
  5926. * @function Chart.Interaction.modes.x-axis
  5927. * @deprecated since version 2.4.0. Use index mode and intersect == true
  5928. * @todo remove at version 3
  5929. * @private
  5930. */
  5931. 'x-axis': function(chart, e) {
  5932. return indexMode(chart, e, {intersect: false});
  5933. },
  5934. /**
  5935. * Point mode returns all elements that hit test based on the event position
  5936. * of the event
  5937. * @function Chart.Interaction.modes.intersect
  5938. * @param {Chart} chart - the chart we are returning items from
  5939. * @param {Event} e - the event we are find things at
  5940. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5941. */
  5942. point: function(chart, e) {
  5943. var position = getRelativePosition(e, chart);
  5944. return getIntersectItems(chart, position);
  5945. },
  5946. /**
  5947. * nearest mode returns the element closest to the point
  5948. * @function Chart.Interaction.modes.intersect
  5949. * @param {Chart} chart - the chart we are returning items from
  5950. * @param {Event} e - the event we are find things at
  5951. * @param {IInteractionOptions} options - options to use
  5952. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5953. */
  5954. nearest: function(chart, e, options) {
  5955. var position = getRelativePosition(e, chart);
  5956. options.axis = options.axis || 'xy';
  5957. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5958. return getNearestItems(chart, position, options.intersect, distanceMetric);
  5959. },
  5960. /**
  5961. * x mode returns the elements that hit-test at the current x coordinate
  5962. * @function Chart.Interaction.modes.x
  5963. * @param {Chart} chart - the chart we are returning items from
  5964. * @param {Event} e - the event we are find things at
  5965. * @param {IInteractionOptions} options - options to use
  5966. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5967. */
  5968. x: function(chart, e, options) {
  5969. var position = getRelativePosition(e, chart);
  5970. var items = [];
  5971. var intersectsItem = false;
  5972. parseVisibleItems(chart, function(element) {
  5973. if (element.inXRange(position.x)) {
  5974. items.push(element);
  5975. }
  5976. if (element.inRange(position.x, position.y)) {
  5977. intersectsItem = true;
  5978. }
  5979. });
  5980. // If we want to trigger on an intersect and we don't have any items
  5981. // that intersect the position, return nothing
  5982. if (options.intersect && !intersectsItem) {
  5983. items = [];
  5984. }
  5985. return items;
  5986. },
  5987. /**
  5988. * y mode returns the elements that hit-test at the current y coordinate
  5989. * @function Chart.Interaction.modes.y
  5990. * @param {Chart} chart - the chart we are returning items from
  5991. * @param {Event} e - the event we are find things at
  5992. * @param {IInteractionOptions} options - options to use
  5993. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5994. */
  5995. y: function(chart, e, options) {
  5996. var position = getRelativePosition(e, chart);
  5997. var items = [];
  5998. var intersectsItem = false;
  5999. parseVisibleItems(chart, function(element) {
  6000. if (element.inYRange(position.y)) {
  6001. items.push(element);
  6002. }
  6003. if (element.inRange(position.x, position.y)) {
  6004. intersectsItem = true;
  6005. }
  6006. });
  6007. // If we want to trigger on an intersect and we don't have any items
  6008. // that intersect the position, return nothing
  6009. if (options.intersect && !intersectsItem) {
  6010. items = [];
  6011. }
  6012. return items;
  6013. }
  6014. }
  6015. };
  6016. var extend = helpers$1.extend;
  6017. function filterByPosition(array, position) {
  6018. return helpers$1.where(array, function(v) {
  6019. return v.pos === position;
  6020. });
  6021. }
  6022. function sortByWeight(array, reverse) {
  6023. return array.sort(function(a, b) {
  6024. var v0 = reverse ? b : a;
  6025. var v1 = reverse ? a : b;
  6026. return v0.weight === v1.weight ?
  6027. v0.index - v1.index :
  6028. v0.weight - v1.weight;
  6029. });
  6030. }
  6031. function wrapBoxes(boxes) {
  6032. var layoutBoxes = [];
  6033. var i, ilen, box;
  6034. for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
  6035. box = boxes[i];
  6036. layoutBoxes.push({
  6037. index: i,
  6038. box: box,
  6039. pos: box.position,
  6040. horizontal: box.isHorizontal(),
  6041. weight: box.weight
  6042. });
  6043. }
  6044. return layoutBoxes;
  6045. }
  6046. function setLayoutDims(layouts, params) {
  6047. var i, ilen, layout;
  6048. for (i = 0, ilen = layouts.length; i < ilen; ++i) {
  6049. layout = layouts[i];
  6050. // store width used instead of chartArea.w in fitBoxes
  6051. layout.width = layout.horizontal
  6052. ? layout.box.fullWidth && params.availableWidth
  6053. : params.vBoxMaxWidth;
  6054. // store height used instead of chartArea.h in fitBoxes
  6055. layout.height = layout.horizontal && params.hBoxMaxHeight;
  6056. }
  6057. }
  6058. function buildLayoutBoxes(boxes) {
  6059. var layoutBoxes = wrapBoxes(boxes);
  6060. var left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  6061. var right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  6062. var top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  6063. var bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  6064. return {
  6065. leftAndTop: left.concat(top),
  6066. rightAndBottom: right.concat(bottom),
  6067. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  6068. vertical: left.concat(right),
  6069. horizontal: top.concat(bottom)
  6070. };
  6071. }
  6072. function getCombinedMax(maxPadding, chartArea, a, b) {
  6073. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  6074. }
  6075. function updateDims(chartArea, params, layout) {
  6076. var box = layout.box;
  6077. var maxPadding = chartArea.maxPadding;
  6078. var newWidth, newHeight;
  6079. if (layout.size) {
  6080. // this layout was already counted for, lets first reduce old size
  6081. chartArea[layout.pos] -= layout.size;
  6082. }
  6083. layout.size = layout.horizontal ? box.height : box.width;
  6084. chartArea[layout.pos] += layout.size;
  6085. if (box.getPadding) {
  6086. var boxPadding = box.getPadding();
  6087. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  6088. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  6089. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  6090. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  6091. }
  6092. newWidth = params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right');
  6093. newHeight = params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom');
  6094. if (newWidth !== chartArea.w || newHeight !== chartArea.h) {
  6095. chartArea.w = newWidth;
  6096. chartArea.h = newHeight;
  6097. // return true if chart area changed in layout's direction
  6098. var sizes = layout.horizontal ? [newWidth, chartArea.w] : [newHeight, chartArea.h];
  6099. return sizes[0] !== sizes[1] && (!isNaN(sizes[0]) || !isNaN(sizes[1]));
  6100. }
  6101. }
  6102. function handleMaxPadding(chartArea) {
  6103. var maxPadding = chartArea.maxPadding;
  6104. function updatePos(pos) {
  6105. var change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  6106. chartArea[pos] += change;
  6107. return change;
  6108. }
  6109. chartArea.y += updatePos('top');
  6110. chartArea.x += updatePos('left');
  6111. updatePos('right');
  6112. updatePos('bottom');
  6113. }
  6114. function getMargins(horizontal, chartArea) {
  6115. var maxPadding = chartArea.maxPadding;
  6116. function marginForPositions(positions) {
  6117. var margin = {left: 0, top: 0, right: 0, bottom: 0};
  6118. positions.forEach(function(pos) {
  6119. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  6120. });
  6121. return margin;
  6122. }
  6123. return horizontal
  6124. ? marginForPositions(['left', 'right'])
  6125. : marginForPositions(['top', 'bottom']);
  6126. }
  6127. function fitBoxes(boxes, chartArea, params) {
  6128. var refitBoxes = [];
  6129. var i, ilen, layout, box, refit, changed;
  6130. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  6131. layout = boxes[i];
  6132. box = layout.box;
  6133. box.update(
  6134. layout.width || chartArea.w,
  6135. layout.height || chartArea.h,
  6136. getMargins(layout.horizontal, chartArea)
  6137. );
  6138. if (updateDims(chartArea, params, layout)) {
  6139. changed = true;
  6140. if (refitBoxes.length) {
  6141. // Dimensions changed and there were non full width boxes before this
  6142. // -> we have to refit those
  6143. refit = true;
  6144. }
  6145. }
  6146. if (!box.fullWidth) { // fullWidth boxes don't need to be re-fitted in any case
  6147. refitBoxes.push(layout);
  6148. }
  6149. }
  6150. return refit ? fitBoxes(refitBoxes, chartArea, params) || changed : changed;
  6151. }
  6152. function placeBoxes(boxes, chartArea, params) {
  6153. var userPadding = params.padding;
  6154. var x = chartArea.x;
  6155. var y = chartArea.y;
  6156. var i, ilen, layout, box;
  6157. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  6158. layout = boxes[i];
  6159. box = layout.box;
  6160. if (layout.horizontal) {
  6161. box.left = box.fullWidth ? userPadding.left : chartArea.left;
  6162. box.right = box.fullWidth ? params.outerWidth - userPadding.right : chartArea.left + chartArea.w;
  6163. box.top = y;
  6164. box.bottom = y + box.height;
  6165. box.width = box.right - box.left;
  6166. y = box.bottom;
  6167. } else {
  6168. box.left = x;
  6169. box.right = x + box.width;
  6170. box.top = chartArea.top;
  6171. box.bottom = chartArea.top + chartArea.h;
  6172. box.height = box.bottom - box.top;
  6173. x = box.right;
  6174. }
  6175. }
  6176. chartArea.x = x;
  6177. chartArea.y = y;
  6178. }
  6179. core_defaults._set('global', {
  6180. layout: {
  6181. padding: {
  6182. top: 0,
  6183. right: 0,
  6184. bottom: 0,
  6185. left: 0
  6186. }
  6187. }
  6188. });
  6189. /**
  6190. * @interface ILayoutItem
  6191. * @prop {string} position - The position of the item in the chart layout. Possible values are
  6192. * 'left', 'top', 'right', 'bottom', and 'chartArea'
  6193. * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area
  6194. * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
  6195. * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
  6196. * @prop {function} update - Takes two parameters: width and height. Returns size of item
  6197. * @prop {function} getPadding - Returns an object with padding on the edges
  6198. * @prop {number} width - Width of item. Must be valid after update()
  6199. * @prop {number} height - Height of item. Must be valid after update()
  6200. * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update
  6201. * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update
  6202. * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update
  6203. * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
  6204. */
  6205. // The layout service is very self explanatory. It's responsible for the layout within a chart.
  6206. // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
  6207. // It is this service's responsibility of carrying out that layout.
  6208. var core_layouts = {
  6209. defaults: {},
  6210. /**
  6211. * Register a box to a chart.
  6212. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
  6213. * @param {Chart} chart - the chart to use
  6214. * @param {ILayoutItem} item - the item to add to be layed out
  6215. */
  6216. addBox: function(chart, item) {
  6217. if (!chart.boxes) {
  6218. chart.boxes = [];
  6219. }
  6220. // initialize item with default values
  6221. item.fullWidth = item.fullWidth || false;
  6222. item.position = item.position || 'top';
  6223. item.weight = item.weight || 0;
  6224. item._layers = item._layers || function() {
  6225. return [{
  6226. z: 0,
  6227. draw: function() {
  6228. item.draw.apply(item, arguments);
  6229. }
  6230. }];
  6231. };
  6232. chart.boxes.push(item);
  6233. },
  6234. /**
  6235. * Remove a layoutItem from a chart
  6236. * @param {Chart} chart - the chart to remove the box from
  6237. * @param {ILayoutItem} layoutItem - the item to remove from the layout
  6238. */
  6239. removeBox: function(chart, layoutItem) {
  6240. var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  6241. if (index !== -1) {
  6242. chart.boxes.splice(index, 1);
  6243. }
  6244. },
  6245. /**
  6246. * Sets (or updates) options on the given `item`.
  6247. * @param {Chart} chart - the chart in which the item lives (or will be added to)
  6248. * @param {ILayoutItem} item - the item to configure with the given options
  6249. * @param {object} options - the new item options.
  6250. */
  6251. configure: function(chart, item, options) {
  6252. var props = ['fullWidth', 'position', 'weight'];
  6253. var ilen = props.length;
  6254. var i = 0;
  6255. var prop;
  6256. for (; i < ilen; ++i) {
  6257. prop = props[i];
  6258. if (options.hasOwnProperty(prop)) {
  6259. item[prop] = options[prop];
  6260. }
  6261. }
  6262. },
  6263. /**
  6264. * Fits boxes of the given chart into the given size by having each box measure itself
  6265. * then running a fitting algorithm
  6266. * @param {Chart} chart - the chart
  6267. * @param {number} width - the width to fit into
  6268. * @param {number} height - the height to fit into
  6269. */
  6270. update: function(chart, width, height) {
  6271. if (!chart) {
  6272. return;
  6273. }
  6274. var layoutOptions = chart.options.layout || {};
  6275. var padding = helpers$1.options.toPadding(layoutOptions.padding);
  6276. var availableWidth = width - padding.width;
  6277. var availableHeight = height - padding.height;
  6278. var boxes = buildLayoutBoxes(chart.boxes);
  6279. var verticalBoxes = boxes.vertical;
  6280. var horizontalBoxes = boxes.horizontal;
  6281. // Essentially we now have any number of boxes on each of the 4 sides.
  6282. // Our canvas looks like the following.
  6283. // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
  6284. // B1 is the bottom axis
  6285. // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
  6286. // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
  6287. // an error will be thrown.
  6288. //
  6289. // |----------------------------------------------------|
  6290. // | T1 (Full Width) |
  6291. // |----------------------------------------------------|
  6292. // | | | T2 | |
  6293. // | |----|-------------------------------------|----|
  6294. // | | | C1 | | C2 | |
  6295. // | | |----| |----| |
  6296. // | | | | |
  6297. // | L1 | L2 | ChartArea (C0) | R1 |
  6298. // | | | | |
  6299. // | | |----| |----| |
  6300. // | | | C3 | | C4 | |
  6301. // | |----|-------------------------------------|----|
  6302. // | | | B1 | |
  6303. // |----------------------------------------------------|
  6304. // | B2 (Full Width) |
  6305. // |----------------------------------------------------|
  6306. //
  6307. var params = Object.freeze({
  6308. outerWidth: width,
  6309. outerHeight: height,
  6310. padding: padding,
  6311. availableWidth: availableWidth,
  6312. vBoxMaxWidth: availableWidth / 2 / verticalBoxes.length,
  6313. hBoxMaxHeight: availableHeight / 2
  6314. });
  6315. var chartArea = extend({
  6316. maxPadding: extend({}, padding),
  6317. w: availableWidth,
  6318. h: availableHeight,
  6319. x: padding.left,
  6320. y: padding.top
  6321. }, padding);
  6322. setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  6323. // First fit vertical boxes
  6324. fitBoxes(verticalBoxes, chartArea, params);
  6325. // Then fit horizontal boxes
  6326. if (fitBoxes(horizontalBoxes, chartArea, params)) {
  6327. // if the area changed, re-fit vertical boxes
  6328. fitBoxes(verticalBoxes, chartArea, params);
  6329. }
  6330. handleMaxPadding(chartArea);
  6331. // Finally place the boxes to correct coordinates
  6332. placeBoxes(boxes.leftAndTop, chartArea, params);
  6333. // Move to opposite side of chart
  6334. chartArea.x += chartArea.w;
  6335. chartArea.y += chartArea.h;
  6336. placeBoxes(boxes.rightAndBottom, chartArea, params);
  6337. chart.chartArea = {
  6338. left: chartArea.left,
  6339. top: chartArea.top,
  6340. right: chartArea.left + chartArea.w,
  6341. bottom: chartArea.top + chartArea.h
  6342. };
  6343. // Finally update boxes in chartArea (radial scale for example)
  6344. helpers$1.each(boxes.chartArea, function(layout) {
  6345. var box = layout.box;
  6346. extend(box, chart.chartArea);
  6347. box.update(chartArea.w, chartArea.h);
  6348. });
  6349. }
  6350. };
  6351. /**
  6352. * Platform fallback implementation (minimal).
  6353. * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
  6354. */
  6355. var platform_basic = {
  6356. acquireContext: function(item) {
  6357. if (item && item.canvas) {
  6358. // Support for any object associated to a canvas (including a context2d)
  6359. item = item.canvas;
  6360. }
  6361. return item && item.getContext('2d') || null;
  6362. }
  6363. };
  6364. var platform_dom = "/*\r\n * DOM element rendering detection\r\n * https://davidwalsh.name/detect-node-insertion\r\n */\r\n@keyframes chartjs-render-animation {\r\n\tfrom { opacity: 0.99; }\r\n\tto { opacity: 1; }\r\n}\r\n\r\n.chartjs-render-monitor {\r\n\tanimation: chartjs-render-animation 0.001s;\r\n}\r\n\r\n/*\r\n * DOM element resizing detection\r\n * https://github.com/marcj/css-element-queries\r\n */\r\n.chartjs-size-monitor,\r\n.chartjs-size-monitor-expand,\r\n.chartjs-size-monitor-shrink {\r\n\tposition: absolute;\r\n\tdirection: ltr;\r\n\tleft: 0;\r\n\ttop: 0;\r\n\tright: 0;\r\n\tbottom: 0;\r\n\toverflow: hidden;\r\n\tpointer-events: none;\r\n\tvisibility: hidden;\r\n\tz-index: -1;\r\n}\r\n\r\n.chartjs-size-monitor-expand > div {\r\n\tposition: absolute;\r\n\twidth: 1000000px;\r\n\theight: 1000000px;\r\n\tleft: 0;\r\n\ttop: 0;\r\n}\r\n\r\n.chartjs-size-monitor-shrink > div {\r\n\tposition: absolute;\r\n\twidth: 200%;\r\n\theight: 200%;\r\n\tleft: 0;\r\n\ttop: 0;\r\n}\r\n";
  6365. var platform_dom$1 = /*#__PURE__*/Object.freeze({
  6366. __proto__: null,
  6367. 'default': platform_dom
  6368. });
  6369. var stylesheet = getCjsExportFromNamespace(platform_dom$1);
  6370. var EXPANDO_KEY = '$chartjs';
  6371. var CSS_PREFIX = 'chartjs-';
  6372. var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor';
  6373. var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
  6374. var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
  6375. var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
  6376. /**
  6377. * DOM event types -> Chart.js event types.
  6378. * Note: only events with different types are mapped.
  6379. * @see https://developer.mozilla.org/en-US/docs/Web/Events
  6380. */
  6381. var EVENT_TYPES = {
  6382. touchstart: 'mousedown',
  6383. touchmove: 'mousemove',
  6384. touchend: 'mouseup',
  6385. pointerenter: 'mouseenter',
  6386. pointerdown: 'mousedown',
  6387. pointermove: 'mousemove',
  6388. pointerup: 'mouseup',
  6389. pointerleave: 'mouseout',
  6390. pointerout: 'mouseout'
  6391. };
  6392. /**
  6393. * The "used" size is the final value of a dimension property after all calculations have
  6394. * been performed. This method uses the computed style of `element` but returns undefined
  6395. * if the computed style is not expressed in pixels. That can happen in some cases where
  6396. * `element` has a size relative to its parent and this last one is not yet displayed,
  6397. * for example because of `display: none` on a parent node.
  6398. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  6399. * @returns {number} Size in pixels or undefined if unknown.
  6400. */
  6401. function readUsedSize(element, property) {
  6402. var value = helpers$1.getStyle(element, property);
  6403. var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  6404. return matches ? Number(matches[1]) : undefined;
  6405. }
  6406. /**
  6407. * Initializes the canvas style and render size without modifying the canvas display size,
  6408. * since responsiveness is handled by the controller.resize() method. The config is used
  6409. * to determine the aspect ratio to apply in case no explicit height has been specified.
  6410. */
  6411. function initCanvas(canvas, config) {
  6412. var style = canvas.style;
  6413. // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
  6414. // returns null or '' if no explicit value has been set to the canvas attribute.
  6415. var renderHeight = canvas.getAttribute('height');
  6416. var renderWidth = canvas.getAttribute('width');
  6417. // Chart.js modifies some canvas values that we want to restore on destroy
  6418. canvas[EXPANDO_KEY] = {
  6419. initial: {
  6420. height: renderHeight,
  6421. width: renderWidth,
  6422. style: {
  6423. display: style.display,
  6424. height: style.height,
  6425. width: style.width
  6426. }
  6427. }
  6428. };
  6429. // Force canvas to display as block to avoid extra space caused by inline
  6430. // elements, which would interfere with the responsive resize process.
  6431. // https://github.com/chartjs/Chart.js/issues/2538
  6432. style.display = style.display || 'block';
  6433. if (renderWidth === null || renderWidth === '') {
  6434. var displayWidth = readUsedSize(canvas, 'width');
  6435. if (displayWidth !== undefined) {
  6436. canvas.width = displayWidth;
  6437. }
  6438. }
  6439. if (renderHeight === null || renderHeight === '') {
  6440. if (canvas.style.height === '') {
  6441. // If no explicit render height and style height, let's apply the aspect ratio,
  6442. // which one can be specified by the user but also by charts as default option
  6443. // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
  6444. canvas.height = canvas.width / (config.options.aspectRatio || 2);
  6445. } else {
  6446. var displayHeight = readUsedSize(canvas, 'height');
  6447. if (displayWidth !== undefined) {
  6448. canvas.height = displayHeight;
  6449. }
  6450. }
  6451. }
  6452. return canvas;
  6453. }
  6454. /**
  6455. * Detects support for options object argument in addEventListener.
  6456. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
  6457. * @private
  6458. */
  6459. var supportsEventListenerOptions = (function() {
  6460. var supports = false;
  6461. try {
  6462. var options = Object.defineProperty({}, 'passive', {
  6463. // eslint-disable-next-line getter-return
  6464. get: function() {
  6465. supports = true;
  6466. }
  6467. });
  6468. window.addEventListener('e', null, options);
  6469. } catch (e) {
  6470. // continue regardless of error
  6471. }
  6472. return supports;
  6473. }());
  6474. // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
  6475. // https://github.com/chartjs/Chart.js/issues/4287
  6476. var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  6477. function addListener(node, type, listener) {
  6478. node.addEventListener(type, listener, eventListenerOptions);
  6479. }
  6480. function removeListener(node, type, listener) {
  6481. node.removeEventListener(type, listener, eventListenerOptions);
  6482. }
  6483. function createEvent(type, chart, x, y, nativeEvent) {
  6484. return {
  6485. type: type,
  6486. chart: chart,
  6487. native: nativeEvent || null,
  6488. x: x !== undefined ? x : null,
  6489. y: y !== undefined ? y : null,
  6490. };
  6491. }
  6492. function fromNativeEvent(event, chart) {
  6493. var type = EVENT_TYPES[event.type] || event.type;
  6494. var pos = helpers$1.getRelativePosition(event, chart);
  6495. return createEvent(type, chart, pos.x, pos.y, event);
  6496. }
  6497. function throttled(fn, thisArg) {
  6498. var ticking = false;
  6499. var args = [];
  6500. return function() {
  6501. args = Array.prototype.slice.call(arguments);
  6502. thisArg = thisArg || this;
  6503. if (!ticking) {
  6504. ticking = true;
  6505. helpers$1.requestAnimFrame.call(window, function() {
  6506. ticking = false;
  6507. fn.apply(thisArg, args);
  6508. });
  6509. }
  6510. };
  6511. }
  6512. function createDiv(cls) {
  6513. var el = document.createElement('div');
  6514. el.className = cls || '';
  6515. return el;
  6516. }
  6517. // Implementation based on https://github.com/marcj/css-element-queries
  6518. function createResizer(handler) {
  6519. var maxSize = 1000000;
  6520. // NOTE(SB) Don't use innerHTML because it could be considered unsafe.
  6521. // https://github.com/chartjs/Chart.js/issues/5902
  6522. var resizer = createDiv(CSS_SIZE_MONITOR);
  6523. var expand = createDiv(CSS_SIZE_MONITOR + '-expand');
  6524. var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink');
  6525. expand.appendChild(createDiv());
  6526. shrink.appendChild(createDiv());
  6527. resizer.appendChild(expand);
  6528. resizer.appendChild(shrink);
  6529. resizer._reset = function() {
  6530. expand.scrollLeft = maxSize;
  6531. expand.scrollTop = maxSize;
  6532. shrink.scrollLeft = maxSize;
  6533. shrink.scrollTop = maxSize;
  6534. };
  6535. var onScroll = function() {
  6536. resizer._reset();
  6537. handler();
  6538. };
  6539. addListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
  6540. addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
  6541. return resizer;
  6542. }
  6543. // https://davidwalsh.name/detect-node-insertion
  6544. function watchForRender(node, handler) {
  6545. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  6546. var proxy = expando.renderProxy = function(e) {
  6547. if (e.animationName === CSS_RENDER_ANIMATION) {
  6548. handler();
  6549. }
  6550. };
  6551. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  6552. addListener(node, type, proxy);
  6553. });
  6554. // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
  6555. // is removed then added back immediately (same animation frame?). Accessing the
  6556. // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
  6557. // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
  6558. // https://github.com/chartjs/Chart.js/issues/4737
  6559. expando.reflow = !!node.offsetParent;
  6560. node.classList.add(CSS_RENDER_MONITOR);
  6561. }
  6562. function unwatchForRender(node) {
  6563. var expando = node[EXPANDO_KEY] || {};
  6564. var proxy = expando.renderProxy;
  6565. if (proxy) {
  6566. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  6567. removeListener(node, type, proxy);
  6568. });
  6569. delete expando.renderProxy;
  6570. }
  6571. node.classList.remove(CSS_RENDER_MONITOR);
  6572. }
  6573. function addResizeListener(node, listener, chart) {
  6574. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  6575. // Let's keep track of this added resizer and thus avoid DOM query when removing it.
  6576. var resizer = expando.resizer = createResizer(throttled(function() {
  6577. if (expando.resizer) {
  6578. var container = chart.options.maintainAspectRatio && node.parentNode;
  6579. var w = container ? container.clientWidth : 0;
  6580. listener(createEvent('resize', chart));
  6581. if (container && container.clientWidth < w && chart.canvas) {
  6582. // If the container size shrank during chart resize, let's assume
  6583. // scrollbar appeared. So we resize again with the scrollbar visible -
  6584. // effectively making chart smaller and the scrollbar hidden again.
  6585. // Because we are inside `throttled`, and currently `ticking`, scroll
  6586. // events are ignored during this whole 2 resize process.
  6587. // If we assumed wrong and something else happened, we are resizing
  6588. // twice in a frame (potential performance issue)
  6589. listener(createEvent('resize', chart));
  6590. }
  6591. }
  6592. }));
  6593. // The resizer needs to be attached to the node parent, so we first need to be
  6594. // sure that `node` is attached to the DOM before injecting the resizer element.
  6595. watchForRender(node, function() {
  6596. if (expando.resizer) {
  6597. var container = node.parentNode;
  6598. if (container && container !== resizer.parentNode) {
  6599. container.insertBefore(resizer, container.firstChild);
  6600. }
  6601. // The container size might have changed, let's reset the resizer state.
  6602. resizer._reset();
  6603. }
  6604. });
  6605. }
  6606. function removeResizeListener(node) {
  6607. var expando = node[EXPANDO_KEY] || {};
  6608. var resizer = expando.resizer;
  6609. delete expando.resizer;
  6610. unwatchForRender(node);
  6611. if (resizer && resizer.parentNode) {
  6612. resizer.parentNode.removeChild(resizer);
  6613. }
  6614. }
  6615. /**
  6616. * Injects CSS styles inline if the styles are not already present.
  6617. * @param {HTMLDocument|ShadowRoot} rootNode - the node to contain the <style>.
  6618. * @param {string} css - the CSS to be injected.
  6619. */
  6620. function injectCSS(rootNode, css) {
  6621. // https://stackoverflow.com/q/3922139
  6622. var expando = rootNode[EXPANDO_KEY] || (rootNode[EXPANDO_KEY] = {});
  6623. if (!expando.containsStyles) {
  6624. expando.containsStyles = true;
  6625. css = '/* Chart.js */\n' + css;
  6626. var style = document.createElement('style');
  6627. style.setAttribute('type', 'text/css');
  6628. style.appendChild(document.createTextNode(css));
  6629. rootNode.appendChild(style);
  6630. }
  6631. }
  6632. var platform_dom$2 = {
  6633. /**
  6634. * When `true`, prevents the automatic injection of the stylesheet required to
  6635. * correctly detect when the chart is added to the DOM and then resized. This
  6636. * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`)
  6637. * to be manually imported to make this library compatible with any CSP.
  6638. * See https://github.com/chartjs/Chart.js/issues/5208
  6639. */
  6640. disableCSSInjection: false,
  6641. /**
  6642. * This property holds whether this platform is enabled for the current environment.
  6643. * Currently used by platform.js to select the proper implementation.
  6644. * @private
  6645. */
  6646. _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
  6647. /**
  6648. * Initializes resources that depend on platform options.
  6649. * @param {HTMLCanvasElement} canvas - The Canvas element.
  6650. * @private
  6651. */
  6652. _ensureLoaded: function(canvas) {
  6653. if (!this.disableCSSInjection) {
  6654. // If the canvas is in a shadow DOM, then the styles must also be inserted
  6655. // into the same shadow DOM.
  6656. // https://github.com/chartjs/Chart.js/issues/5763
  6657. var root = canvas.getRootNode ? canvas.getRootNode() : document;
  6658. var targetNode = root.host ? root : document.head;
  6659. injectCSS(targetNode, stylesheet);
  6660. }
  6661. },
  6662. acquireContext: function(item, config) {
  6663. if (typeof item === 'string') {
  6664. item = document.getElementById(item);
  6665. } else if (item.length) {
  6666. // Support for array based queries (such as jQuery)
  6667. item = item[0];
  6668. }
  6669. if (item && item.canvas) {
  6670. // Support for any object associated to a canvas (including a context2d)
  6671. item = item.canvas;
  6672. }
  6673. // To prevent canvas fingerprinting, some add-ons undefine the getContext
  6674. // method, for example: https://github.com/kkapsner/CanvasBlocker
  6675. // https://github.com/chartjs/Chart.js/issues/2807
  6676. var context = item && item.getContext && item.getContext('2d');
  6677. // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
  6678. // inside an iframe or when running in a protected environment. We could guess the
  6679. // types from their toString() value but let's keep things flexible and assume it's
  6680. // a sufficient condition if the item has a context2D which has item as `canvas`.
  6681. // https://github.com/chartjs/Chart.js/issues/3887
  6682. // https://github.com/chartjs/Chart.js/issues/4102
  6683. // https://github.com/chartjs/Chart.js/issues/4152
  6684. if (context && context.canvas === item) {
  6685. // Load platform resources on first chart creation, to make it possible to
  6686. // import the library before setting platform options.
  6687. this._ensureLoaded(item);
  6688. initCanvas(item, config);
  6689. return context;
  6690. }
  6691. return null;
  6692. },
  6693. releaseContext: function(context) {
  6694. var canvas = context.canvas;
  6695. if (!canvas[EXPANDO_KEY]) {
  6696. return;
  6697. }
  6698. var initial = canvas[EXPANDO_KEY].initial;
  6699. ['height', 'width'].forEach(function(prop) {
  6700. var value = initial[prop];
  6701. if (helpers$1.isNullOrUndef(value)) {
  6702. canvas.removeAttribute(prop);
  6703. } else {
  6704. canvas.setAttribute(prop, value);
  6705. }
  6706. });
  6707. helpers$1.each(initial.style || {}, function(value, key) {
  6708. canvas.style[key] = value;
  6709. });
  6710. // The canvas render size might have been changed (and thus the state stack discarded),
  6711. // we can't use save() and restore() to restore the initial state. So make sure that at
  6712. // least the canvas context is reset to the default state by setting the canvas width.
  6713. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
  6714. // eslint-disable-next-line no-self-assign
  6715. canvas.width = canvas.width;
  6716. delete canvas[EXPANDO_KEY];
  6717. },
  6718. addEventListener: function(chart, type, listener) {
  6719. var canvas = chart.canvas;
  6720. if (type === 'resize') {
  6721. // Note: the resize event is not supported on all browsers.
  6722. addResizeListener(canvas, listener, chart);
  6723. return;
  6724. }
  6725. var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
  6726. var proxies = expando.proxies || (expando.proxies = {});
  6727. var proxy = proxies[chart.id + '_' + type] = function(event) {
  6728. listener(fromNativeEvent(event, chart));
  6729. };
  6730. addListener(canvas, type, proxy);
  6731. },
  6732. removeEventListener: function(chart, type, listener) {
  6733. var canvas = chart.canvas;
  6734. if (type === 'resize') {
  6735. // Note: the resize event is not supported on all browsers.
  6736. removeResizeListener(canvas);
  6737. return;
  6738. }
  6739. var expando = listener[EXPANDO_KEY] || {};
  6740. var proxies = expando.proxies || {};
  6741. var proxy = proxies[chart.id + '_' + type];
  6742. if (!proxy) {
  6743. return;
  6744. }
  6745. removeListener(canvas, type, proxy);
  6746. }
  6747. };
  6748. // DEPRECATIONS
  6749. /**
  6750. * Provided for backward compatibility, use EventTarget.addEventListener instead.
  6751. * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6752. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  6753. * @function Chart.helpers.addEvent
  6754. * @deprecated since version 2.7.0
  6755. * @todo remove at version 3
  6756. * @private
  6757. */
  6758. helpers$1.addEvent = addListener;
  6759. /**
  6760. * Provided for backward compatibility, use EventTarget.removeEventListener instead.
  6761. * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6762. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
  6763. * @function Chart.helpers.removeEvent
  6764. * @deprecated since version 2.7.0
  6765. * @todo remove at version 3
  6766. * @private
  6767. */
  6768. helpers$1.removeEvent = removeListener;
  6769. // @TODO Make possible to select another platform at build time.
  6770. var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic;
  6771. /**
  6772. * @namespace Chart.platform
  6773. * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
  6774. * @since 2.4.0
  6775. */
  6776. var platform = helpers$1.extend({
  6777. /**
  6778. * @since 2.7.0
  6779. */
  6780. initialize: function() {},
  6781. /**
  6782. * Called at chart construction time, returns a context2d instance implementing
  6783. * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
  6784. * @param {*} item - The native item from which to acquire context (platform specific)
  6785. * @param {object} options - The chart options
  6786. * @returns {CanvasRenderingContext2D} context2d instance
  6787. */
  6788. acquireContext: function() {},
  6789. /**
  6790. * Called at chart destruction time, releases any resources associated to the context
  6791. * previously returned by the acquireContext() method.
  6792. * @param {CanvasRenderingContext2D} context - The context2d instance
  6793. * @returns {boolean} true if the method succeeded, else false
  6794. */
  6795. releaseContext: function() {},
  6796. /**
  6797. * Registers the specified listener on the given chart.
  6798. * @param {Chart} chart - Chart from which to listen for event
  6799. * @param {string} type - The ({@link IEvent}) type to listen for
  6800. * @param {function} listener - Receives a notification (an object that implements
  6801. * the {@link IEvent} interface) when an event of the specified type occurs.
  6802. */
  6803. addEventListener: function() {},
  6804. /**
  6805. * Removes the specified listener previously registered with addEventListener.
  6806. * @param {Chart} chart - Chart from which to remove the listener
  6807. * @param {string} type - The ({@link IEvent}) type to remove
  6808. * @param {function} listener - The listener function to remove from the event target.
  6809. */
  6810. removeEventListener: function() {}
  6811. }, implementation);
  6812. core_defaults._set('global', {
  6813. plugins: {}
  6814. });
  6815. /**
  6816. * The plugin service singleton
  6817. * @namespace Chart.plugins
  6818. * @since 2.1.0
  6819. */
  6820. var core_plugins = {
  6821. /**
  6822. * Globally registered plugins.
  6823. * @private
  6824. */
  6825. _plugins: [],
  6826. /**
  6827. * This identifier is used to invalidate the descriptors cache attached to each chart
  6828. * when a global plugin is registered or unregistered. In this case, the cache ID is
  6829. * incremented and descriptors are regenerated during following API calls.
  6830. * @private
  6831. */
  6832. _cacheId: 0,
  6833. /**
  6834. * Registers the given plugin(s) if not already registered.
  6835. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6836. */
  6837. register: function(plugins) {
  6838. var p = this._plugins;
  6839. ([]).concat(plugins).forEach(function(plugin) {
  6840. if (p.indexOf(plugin) === -1) {
  6841. p.push(plugin);
  6842. }
  6843. });
  6844. this._cacheId++;
  6845. },
  6846. /**
  6847. * Unregisters the given plugin(s) only if registered.
  6848. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6849. */
  6850. unregister: function(plugins) {
  6851. var p = this._plugins;
  6852. ([]).concat(plugins).forEach(function(plugin) {
  6853. var idx = p.indexOf(plugin);
  6854. if (idx !== -1) {
  6855. p.splice(idx, 1);
  6856. }
  6857. });
  6858. this._cacheId++;
  6859. },
  6860. /**
  6861. * Remove all registered plugins.
  6862. * @since 2.1.5
  6863. */
  6864. clear: function() {
  6865. this._plugins = [];
  6866. this._cacheId++;
  6867. },
  6868. /**
  6869. * Returns the number of registered plugins?
  6870. * @returns {number}
  6871. * @since 2.1.5
  6872. */
  6873. count: function() {
  6874. return this._plugins.length;
  6875. },
  6876. /**
  6877. * Returns all registered plugin instances.
  6878. * @returns {IPlugin[]} array of plugin objects.
  6879. * @since 2.1.5
  6880. */
  6881. getAll: function() {
  6882. return this._plugins;
  6883. },
  6884. /**
  6885. * Calls enabled plugins for `chart` on the specified hook and with the given args.
  6886. * This method immediately returns as soon as a plugin explicitly returns false. The
  6887. * returned value can be used, for instance, to interrupt the current action.
  6888. * @param {Chart} chart - The chart instance for which plugins should be called.
  6889. * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
  6890. * @param {Array} [args] - Extra arguments to apply to the hook call.
  6891. * @returns {boolean} false if any of the plugins return false, else returns true.
  6892. */
  6893. notify: function(chart, hook, args) {
  6894. var descriptors = this.descriptors(chart);
  6895. var ilen = descriptors.length;
  6896. var i, descriptor, plugin, params, method;
  6897. for (i = 0; i < ilen; ++i) {
  6898. descriptor = descriptors[i];
  6899. plugin = descriptor.plugin;
  6900. method = plugin[hook];
  6901. if (typeof method === 'function') {
  6902. params = [chart].concat(args || []);
  6903. params.push(descriptor.options);
  6904. if (method.apply(plugin, params) === false) {
  6905. return false;
  6906. }
  6907. }
  6908. }
  6909. return true;
  6910. },
  6911. /**
  6912. * Returns descriptors of enabled plugins for the given chart.
  6913. * @returns {object[]} [{ plugin, options }]
  6914. * @private
  6915. */
  6916. descriptors: function(chart) {
  6917. var cache = chart.$plugins || (chart.$plugins = {});
  6918. if (cache.id === this._cacheId) {
  6919. return cache.descriptors;
  6920. }
  6921. var plugins = [];
  6922. var descriptors = [];
  6923. var config = (chart && chart.config) || {};
  6924. var options = (config.options && config.options.plugins) || {};
  6925. this._plugins.concat(config.plugins || []).forEach(function(plugin) {
  6926. var idx = plugins.indexOf(plugin);
  6927. if (idx !== -1) {
  6928. return;
  6929. }
  6930. var id = plugin.id;
  6931. var opts = options[id];
  6932. if (opts === false) {
  6933. return;
  6934. }
  6935. if (opts === true) {
  6936. opts = helpers$1.clone(core_defaults.global.plugins[id]);
  6937. }
  6938. plugins.push(plugin);
  6939. descriptors.push({
  6940. plugin: plugin,
  6941. options: opts || {}
  6942. });
  6943. });
  6944. cache.descriptors = descriptors;
  6945. cache.id = this._cacheId;
  6946. return descriptors;
  6947. },
  6948. /**
  6949. * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
  6950. * but in some cases, this reference can be changed by the user when updating options.
  6951. * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  6952. * @private
  6953. */
  6954. _invalidate: function(chart) {
  6955. delete chart.$plugins;
  6956. }
  6957. };
  6958. var core_scaleService = {
  6959. // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
  6960. // use the new chart options to grab the correct scale
  6961. constructors: {},
  6962. // Use a registration function so that we can move to an ES6 map when we no longer need to support
  6963. // old browsers
  6964. // Scale config defaults
  6965. defaults: {},
  6966. registerScaleType: function(type, scaleConstructor, scaleDefaults) {
  6967. this.constructors[type] = scaleConstructor;
  6968. this.defaults[type] = helpers$1.clone(scaleDefaults);
  6969. },
  6970. getScaleConstructor: function(type) {
  6971. return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
  6972. },
  6973. getScaleDefaults: function(type) {
  6974. // Return the scale defaults merged with the global settings so that we always use the latest ones
  6975. return this.defaults.hasOwnProperty(type) ? helpers$1.merge(Object.create(null), [core_defaults.scale, this.defaults[type]]) : {};
  6976. },
  6977. updateScaleDefaults: function(type, additions) {
  6978. var me = this;
  6979. if (me.defaults.hasOwnProperty(type)) {
  6980. me.defaults[type] = helpers$1.extend(me.defaults[type], additions);
  6981. }
  6982. },
  6983. addScalesToLayout: function(chart) {
  6984. // Adds each scale to the chart.boxes array to be sized accordingly
  6985. helpers$1.each(chart.scales, function(scale) {
  6986. // Set ILayoutItem parameters for backwards compatibility
  6987. scale.fullWidth = scale.options.fullWidth;
  6988. scale.position = scale.options.position;
  6989. scale.weight = scale.options.weight;
  6990. core_layouts.addBox(chart, scale);
  6991. });
  6992. }
  6993. };
  6994. var valueOrDefault$8 = helpers$1.valueOrDefault;
  6995. var getRtlHelper = helpers$1.rtl.getRtlAdapter;
  6996. core_defaults._set('global', {
  6997. tooltips: {
  6998. enabled: true,
  6999. custom: null,
  7000. mode: 'nearest',
  7001. position: 'average',
  7002. intersect: true,
  7003. backgroundColor: 'rgba(0,0,0,0.8)',
  7004. titleFontStyle: 'bold',
  7005. titleSpacing: 2,
  7006. titleMarginBottom: 6,
  7007. titleFontColor: '#fff',
  7008. titleAlign: 'left',
  7009. bodySpacing: 2,
  7010. bodyFontColor: '#fff',
  7011. bodyAlign: 'left',
  7012. footerFontStyle: 'bold',
  7013. footerSpacing: 2,
  7014. footerMarginTop: 6,
  7015. footerFontColor: '#fff',
  7016. footerAlign: 'left',
  7017. yPadding: 6,
  7018. xPadding: 6,
  7019. caretPadding: 2,
  7020. caretSize: 5,
  7021. cornerRadius: 6,
  7022. multiKeyBackground: '#fff',
  7023. displayColors: true,
  7024. borderColor: 'rgba(0,0,0,0)',
  7025. borderWidth: 0,
  7026. callbacks: {
  7027. // Args are: (tooltipItems, data)
  7028. beforeTitle: helpers$1.noop,
  7029. title: function(tooltipItems, data) {
  7030. var title = '';
  7031. var labels = data.labels;
  7032. var labelCount = labels ? labels.length : 0;
  7033. if (tooltipItems.length > 0) {
  7034. var item = tooltipItems[0];
  7035. if (item.label) {
  7036. title = item.label;
  7037. } else if (item.xLabel) {
  7038. title = item.xLabel;
  7039. } else if (labelCount > 0 && item.index < labelCount) {
  7040. title = labels[item.index];
  7041. }
  7042. }
  7043. return title;
  7044. },
  7045. afterTitle: helpers$1.noop,
  7046. // Args are: (tooltipItems, data)
  7047. beforeBody: helpers$1.noop,
  7048. // Args are: (tooltipItem, data)
  7049. beforeLabel: helpers$1.noop,
  7050. label: function(tooltipItem, data) {
  7051. var label = data.datasets[tooltipItem.datasetIndex].label || '';
  7052. if (label) {
  7053. label += ': ';
  7054. }
  7055. if (!helpers$1.isNullOrUndef(tooltipItem.value)) {
  7056. label += tooltipItem.value;
  7057. } else {
  7058. label += tooltipItem.yLabel;
  7059. }
  7060. return label;
  7061. },
  7062. labelColor: function(tooltipItem, chart) {
  7063. var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
  7064. var activeElement = meta.data[tooltipItem.index];
  7065. var view = activeElement._view;
  7066. return {
  7067. borderColor: view.borderColor,
  7068. backgroundColor: view.backgroundColor
  7069. };
  7070. },
  7071. labelTextColor: function() {
  7072. return this._options.bodyFontColor;
  7073. },
  7074. afterLabel: helpers$1.noop,
  7075. // Args are: (tooltipItems, data)
  7076. afterBody: helpers$1.noop,
  7077. // Args are: (tooltipItems, data)
  7078. beforeFooter: helpers$1.noop,
  7079. footer: helpers$1.noop,
  7080. afterFooter: helpers$1.noop
  7081. }
  7082. }
  7083. });
  7084. var positioners = {
  7085. /**
  7086. * Average mode places the tooltip at the average position of the elements shown
  7087. * @function Chart.Tooltip.positioners.average
  7088. * @param elements {ChartElement[]} the elements being displayed in the tooltip
  7089. * @returns {object} tooltip position
  7090. */
  7091. average: function(elements) {
  7092. if (!elements.length) {
  7093. return false;
  7094. }
  7095. var i, len;
  7096. var x = 0;
  7097. var y = 0;
  7098. var count = 0;
  7099. for (i = 0, len = elements.length; i < len; ++i) {
  7100. var el = elements[i];
  7101. if (el && el.hasValue()) {
  7102. var pos = el.tooltipPosition();
  7103. x += pos.x;
  7104. y += pos.y;
  7105. ++count;
  7106. }
  7107. }
  7108. return {
  7109. x: x / count,
  7110. y: y / count
  7111. };
  7112. },
  7113. /**
  7114. * Gets the tooltip position nearest of the item nearest to the event position
  7115. * @function Chart.Tooltip.positioners.nearest
  7116. * @param elements {Chart.Element[]} the tooltip elements
  7117. * @param eventPosition {object} the position of the event in canvas coordinates
  7118. * @returns {object} the tooltip position
  7119. */
  7120. nearest: function(elements, eventPosition) {
  7121. var x = eventPosition.x;
  7122. var y = eventPosition.y;
  7123. var minDistance = Number.POSITIVE_INFINITY;
  7124. var i, len, nearestElement;
  7125. for (i = 0, len = elements.length; i < len; ++i) {
  7126. var el = elements[i];
  7127. if (el && el.hasValue()) {
  7128. var center = el.getCenterPoint();
  7129. var d = helpers$1.distanceBetweenPoints(eventPosition, center);
  7130. if (d < minDistance) {
  7131. minDistance = d;
  7132. nearestElement = el;
  7133. }
  7134. }
  7135. }
  7136. if (nearestElement) {
  7137. var tp = nearestElement.tooltipPosition();
  7138. x = tp.x;
  7139. y = tp.y;
  7140. }
  7141. return {
  7142. x: x,
  7143. y: y
  7144. };
  7145. }
  7146. };
  7147. // Helper to push or concat based on if the 2nd parameter is an array or not
  7148. function pushOrConcat(base, toPush) {
  7149. if (toPush) {
  7150. if (helpers$1.isArray(toPush)) {
  7151. // base = base.concat(toPush);
  7152. Array.prototype.push.apply(base, toPush);
  7153. } else {
  7154. base.push(toPush);
  7155. }
  7156. }
  7157. return base;
  7158. }
  7159. /**
  7160. * Returns array of strings split by newline
  7161. * @param {string} value - The value to split by newline.
  7162. * @returns {string[]} value if newline present - Returned from String split() method
  7163. * @function
  7164. */
  7165. function splitNewlines(str) {
  7166. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  7167. return str.split('\n');
  7168. }
  7169. return str;
  7170. }
  7171. /**
  7172. * Private helper to create a tooltip item model
  7173. * @param element - the chart element (point, arc, bar) to create the tooltip item for
  7174. * @return new tooltip item
  7175. */
  7176. function createTooltipItem(element) {
  7177. var xScale = element._xScale;
  7178. var yScale = element._yScale || element._scale; // handle radar || polarArea charts
  7179. var index = element._index;
  7180. var datasetIndex = element._datasetIndex;
  7181. var controller = element._chart.getDatasetMeta(datasetIndex).controller;
  7182. var indexScale = controller._getIndexScale();
  7183. var valueScale = controller._getValueScale();
  7184. return {
  7185. xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
  7186. yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
  7187. label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '',
  7188. value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '',
  7189. index: index,
  7190. datasetIndex: datasetIndex,
  7191. x: element._model.x,
  7192. y: element._model.y
  7193. };
  7194. }
  7195. /**
  7196. * Helper to get the reset model for the tooltip
  7197. * @param tooltipOpts {object} the tooltip options
  7198. */
  7199. function getBaseModel(tooltipOpts) {
  7200. var globalDefaults = core_defaults.global;
  7201. return {
  7202. // Positioning
  7203. xPadding: tooltipOpts.xPadding,
  7204. yPadding: tooltipOpts.yPadding,
  7205. xAlign: tooltipOpts.xAlign,
  7206. yAlign: tooltipOpts.yAlign,
  7207. // Drawing direction and text direction
  7208. rtl: tooltipOpts.rtl,
  7209. textDirection: tooltipOpts.textDirection,
  7210. // Body
  7211. bodyFontColor: tooltipOpts.bodyFontColor,
  7212. _bodyFontFamily: valueOrDefault$8(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
  7213. _bodyFontStyle: valueOrDefault$8(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
  7214. _bodyAlign: tooltipOpts.bodyAlign,
  7215. bodyFontSize: valueOrDefault$8(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
  7216. bodySpacing: tooltipOpts.bodySpacing,
  7217. // Title
  7218. titleFontColor: tooltipOpts.titleFontColor,
  7219. _titleFontFamily: valueOrDefault$8(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
  7220. _titleFontStyle: valueOrDefault$8(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
  7221. titleFontSize: valueOrDefault$8(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
  7222. _titleAlign: tooltipOpts.titleAlign,
  7223. titleSpacing: tooltipOpts.titleSpacing,
  7224. titleMarginBottom: tooltipOpts.titleMarginBottom,
  7225. // Footer
  7226. footerFontColor: tooltipOpts.footerFontColor,
  7227. _footerFontFamily: valueOrDefault$8(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
  7228. _footerFontStyle: valueOrDefault$8(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
  7229. footerFontSize: valueOrDefault$8(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
  7230. _footerAlign: tooltipOpts.footerAlign,
  7231. footerSpacing: tooltipOpts.footerSpacing,
  7232. footerMarginTop: tooltipOpts.footerMarginTop,
  7233. // Appearance
  7234. caretSize: tooltipOpts.caretSize,
  7235. cornerRadius: tooltipOpts.cornerRadius,
  7236. backgroundColor: tooltipOpts.backgroundColor,
  7237. opacity: 0,
  7238. legendColorBackground: tooltipOpts.multiKeyBackground,
  7239. displayColors: tooltipOpts.displayColors,
  7240. borderColor: tooltipOpts.borderColor,
  7241. borderWidth: tooltipOpts.borderWidth
  7242. };
  7243. }
  7244. /**
  7245. * Get the size of the tooltip
  7246. */
  7247. function getTooltipSize(tooltip, model) {
  7248. var ctx = tooltip._chart.ctx;
  7249. var height = model.yPadding * 2; // Tooltip Padding
  7250. var width = 0;
  7251. // Count of all lines in the body
  7252. var body = model.body;
  7253. var combinedBodyLength = body.reduce(function(count, bodyItem) {
  7254. return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
  7255. }, 0);
  7256. combinedBodyLength += model.beforeBody.length + model.afterBody.length;
  7257. var titleLineCount = model.title.length;
  7258. var footerLineCount = model.footer.length;
  7259. var titleFontSize = model.titleFontSize;
  7260. var bodyFontSize = model.bodyFontSize;
  7261. var footerFontSize = model.footerFontSize;
  7262. height += titleLineCount * titleFontSize; // Title Lines
  7263. height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
  7264. height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
  7265. height += combinedBodyLength * bodyFontSize; // Body Lines
  7266. height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
  7267. height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
  7268. height += footerLineCount * (footerFontSize); // Footer Lines
  7269. height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
  7270. // Title width
  7271. var widthPadding = 0;
  7272. var maxLineWidth = function(line) {
  7273. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  7274. };
  7275. ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
  7276. helpers$1.each(model.title, maxLineWidth);
  7277. // Body width
  7278. ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
  7279. helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
  7280. // Body lines may include some extra width due to the color box
  7281. widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
  7282. helpers$1.each(body, function(bodyItem) {
  7283. helpers$1.each(bodyItem.before, maxLineWidth);
  7284. helpers$1.each(bodyItem.lines, maxLineWidth);
  7285. helpers$1.each(bodyItem.after, maxLineWidth);
  7286. });
  7287. // Reset back to 0
  7288. widthPadding = 0;
  7289. // Footer width
  7290. ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
  7291. helpers$1.each(model.footer, maxLineWidth);
  7292. // Add padding
  7293. width += 2 * model.xPadding;
  7294. return {
  7295. width: width,
  7296. height: height
  7297. };
  7298. }
  7299. /**
  7300. * Helper to get the alignment of a tooltip given the size
  7301. */
  7302. function determineAlignment(tooltip, size) {
  7303. var model = tooltip._model;
  7304. var chart = tooltip._chart;
  7305. var chartArea = tooltip._chart.chartArea;
  7306. var xAlign = 'center';
  7307. var yAlign = 'center';
  7308. if (model.y < size.height) {
  7309. yAlign = 'top';
  7310. } else if (model.y > (chart.height - size.height)) {
  7311. yAlign = 'bottom';
  7312. }
  7313. var lf, rf; // functions to determine left, right alignment
  7314. var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
  7315. var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
  7316. var midX = (chartArea.left + chartArea.right) / 2;
  7317. var midY = (chartArea.top + chartArea.bottom) / 2;
  7318. if (yAlign === 'center') {
  7319. lf = function(x) {
  7320. return x <= midX;
  7321. };
  7322. rf = function(x) {
  7323. return x > midX;
  7324. };
  7325. } else {
  7326. lf = function(x) {
  7327. return x <= (size.width / 2);
  7328. };
  7329. rf = function(x) {
  7330. return x >= (chart.width - (size.width / 2));
  7331. };
  7332. }
  7333. olf = function(x) {
  7334. return x + size.width + model.caretSize + model.caretPadding > chart.width;
  7335. };
  7336. orf = function(x) {
  7337. return x - size.width - model.caretSize - model.caretPadding < 0;
  7338. };
  7339. yf = function(y) {
  7340. return y <= midY ? 'top' : 'bottom';
  7341. };
  7342. if (lf(model.x)) {
  7343. xAlign = 'left';
  7344. // Is tooltip too wide and goes over the right side of the chart.?
  7345. if (olf(model.x)) {
  7346. xAlign = 'center';
  7347. yAlign = yf(model.y);
  7348. }
  7349. } else if (rf(model.x)) {
  7350. xAlign = 'right';
  7351. // Is tooltip too wide and goes outside left edge of canvas?
  7352. if (orf(model.x)) {
  7353. xAlign = 'center';
  7354. yAlign = yf(model.y);
  7355. }
  7356. }
  7357. var opts = tooltip._options;
  7358. return {
  7359. xAlign: opts.xAlign ? opts.xAlign : xAlign,
  7360. yAlign: opts.yAlign ? opts.yAlign : yAlign
  7361. };
  7362. }
  7363. /**
  7364. * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
  7365. */
  7366. function getBackgroundPoint(vm, size, alignment, chart) {
  7367. // Background Position
  7368. var x = vm.x;
  7369. var y = vm.y;
  7370. var caretSize = vm.caretSize;
  7371. var caretPadding = vm.caretPadding;
  7372. var cornerRadius = vm.cornerRadius;
  7373. var xAlign = alignment.xAlign;
  7374. var yAlign = alignment.yAlign;
  7375. var paddingAndSize = caretSize + caretPadding;
  7376. var radiusAndPadding = cornerRadius + caretPadding;
  7377. if (xAlign === 'right') {
  7378. x -= size.width;
  7379. } else if (xAlign === 'center') {
  7380. x -= (size.width / 2);
  7381. if (x + size.width > chart.width) {
  7382. x = chart.width - size.width;
  7383. }
  7384. if (x < 0) {
  7385. x = 0;
  7386. }
  7387. }
  7388. if (yAlign === 'top') {
  7389. y += paddingAndSize;
  7390. } else if (yAlign === 'bottom') {
  7391. y -= size.height + paddingAndSize;
  7392. } else {
  7393. y -= (size.height / 2);
  7394. }
  7395. if (yAlign === 'center') {
  7396. if (xAlign === 'left') {
  7397. x += paddingAndSize;
  7398. } else if (xAlign === 'right') {
  7399. x -= paddingAndSize;
  7400. }
  7401. } else if (xAlign === 'left') {
  7402. x -= radiusAndPadding;
  7403. } else if (xAlign === 'right') {
  7404. x += radiusAndPadding;
  7405. }
  7406. return {
  7407. x: x,
  7408. y: y
  7409. };
  7410. }
  7411. function getAlignedX(vm, align) {
  7412. return align === 'center'
  7413. ? vm.x + vm.width / 2
  7414. : align === 'right'
  7415. ? vm.x + vm.width - vm.xPadding
  7416. : vm.x + vm.xPadding;
  7417. }
  7418. /**
  7419. * Helper to build before and after body lines
  7420. */
  7421. function getBeforeAfterBodyLines(callback) {
  7422. return pushOrConcat([], splitNewlines(callback));
  7423. }
  7424. var exports$4 = core_element.extend({
  7425. initialize: function() {
  7426. this._model = getBaseModel(this._options);
  7427. this._lastActive = [];
  7428. },
  7429. // Get the title
  7430. // Args are: (tooltipItem, data)
  7431. getTitle: function() {
  7432. var me = this;
  7433. var opts = me._options;
  7434. var callbacks = opts.callbacks;
  7435. var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
  7436. var title = callbacks.title.apply(me, arguments);
  7437. var afterTitle = callbacks.afterTitle.apply(me, arguments);
  7438. var lines = [];
  7439. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  7440. lines = pushOrConcat(lines, splitNewlines(title));
  7441. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  7442. return lines;
  7443. },
  7444. // Args are: (tooltipItem, data)
  7445. getBeforeBody: function() {
  7446. return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));
  7447. },
  7448. // Args are: (tooltipItem, data)
  7449. getBody: function(tooltipItems, data) {
  7450. var me = this;
  7451. var callbacks = me._options.callbacks;
  7452. var bodyItems = [];
  7453. helpers$1.each(tooltipItems, function(tooltipItem) {
  7454. var bodyItem = {
  7455. before: [],
  7456. lines: [],
  7457. after: []
  7458. };
  7459. pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));
  7460. pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
  7461. pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));
  7462. bodyItems.push(bodyItem);
  7463. });
  7464. return bodyItems;
  7465. },
  7466. // Args are: (tooltipItem, data)
  7467. getAfterBody: function() {
  7468. return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));
  7469. },
  7470. // Get the footer and beforeFooter and afterFooter lines
  7471. // Args are: (tooltipItem, data)
  7472. getFooter: function() {
  7473. var me = this;
  7474. var callbacks = me._options.callbacks;
  7475. var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
  7476. var footer = callbacks.footer.apply(me, arguments);
  7477. var afterFooter = callbacks.afterFooter.apply(me, arguments);
  7478. var lines = [];
  7479. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  7480. lines = pushOrConcat(lines, splitNewlines(footer));
  7481. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  7482. return lines;
  7483. },
  7484. update: function(changed) {
  7485. var me = this;
  7486. var opts = me._options;
  7487. // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
  7488. // 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
  7489. // which breaks any animations.
  7490. var existingModel = me._model;
  7491. var model = me._model = getBaseModel(opts);
  7492. var active = me._active;
  7493. var data = me._data;
  7494. // In the case where active.length === 0 we need to keep these at existing values for good animations
  7495. var alignment = {
  7496. xAlign: existingModel.xAlign,
  7497. yAlign: existingModel.yAlign
  7498. };
  7499. var backgroundPoint = {
  7500. x: existingModel.x,
  7501. y: existingModel.y
  7502. };
  7503. var tooltipSize = {
  7504. width: existingModel.width,
  7505. height: existingModel.height
  7506. };
  7507. var tooltipPosition = {
  7508. x: existingModel.caretX,
  7509. y: existingModel.caretY
  7510. };
  7511. var i, len;
  7512. if (active.length) {
  7513. model.opacity = 1;
  7514. var labelColors = [];
  7515. var labelTextColors = [];
  7516. tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
  7517. var tooltipItems = [];
  7518. for (i = 0, len = active.length; i < len; ++i) {
  7519. tooltipItems.push(createTooltipItem(active[i]));
  7520. }
  7521. // If the user provided a filter function, use it to modify the tooltip items
  7522. if (opts.filter) {
  7523. tooltipItems = tooltipItems.filter(function(a) {
  7524. return opts.filter(a, data);
  7525. });
  7526. }
  7527. // If the user provided a sorting function, use it to modify the tooltip items
  7528. if (opts.itemSort) {
  7529. tooltipItems = tooltipItems.sort(function(a, b) {
  7530. return opts.itemSort(a, b, data);
  7531. });
  7532. }
  7533. // Determine colors for boxes
  7534. helpers$1.each(tooltipItems, function(tooltipItem) {
  7535. labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
  7536. labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
  7537. });
  7538. // Build the Text Lines
  7539. model.title = me.getTitle(tooltipItems, data);
  7540. model.beforeBody = me.getBeforeBody(tooltipItems, data);
  7541. model.body = me.getBody(tooltipItems, data);
  7542. model.afterBody = me.getAfterBody(tooltipItems, data);
  7543. model.footer = me.getFooter(tooltipItems, data);
  7544. // Initial positioning and colors
  7545. model.x = tooltipPosition.x;
  7546. model.y = tooltipPosition.y;
  7547. model.caretPadding = opts.caretPadding;
  7548. model.labelColors = labelColors;
  7549. model.labelTextColors = labelTextColors;
  7550. // data points
  7551. model.dataPoints = tooltipItems;
  7552. // We need to determine alignment of the tooltip
  7553. tooltipSize = getTooltipSize(this, model);
  7554. alignment = determineAlignment(this, tooltipSize);
  7555. // Final Size and Position
  7556. backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
  7557. } else {
  7558. model.opacity = 0;
  7559. }
  7560. model.xAlign = alignment.xAlign;
  7561. model.yAlign = alignment.yAlign;
  7562. model.x = backgroundPoint.x;
  7563. model.y = backgroundPoint.y;
  7564. model.width = tooltipSize.width;
  7565. model.height = tooltipSize.height;
  7566. // Point where the caret on the tooltip points to
  7567. model.caretX = tooltipPosition.x;
  7568. model.caretY = tooltipPosition.y;
  7569. me._model = model;
  7570. if (changed && opts.custom) {
  7571. opts.custom.call(me, model);
  7572. }
  7573. return me;
  7574. },
  7575. drawCaret: function(tooltipPoint, size) {
  7576. var ctx = this._chart.ctx;
  7577. var vm = this._view;
  7578. var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
  7579. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  7580. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  7581. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  7582. },
  7583. getCaretPosition: function(tooltipPoint, size, vm) {
  7584. var x1, x2, x3, y1, y2, y3;
  7585. var caretSize = vm.caretSize;
  7586. var cornerRadius = vm.cornerRadius;
  7587. var xAlign = vm.xAlign;
  7588. var yAlign = vm.yAlign;
  7589. var ptX = tooltipPoint.x;
  7590. var ptY = tooltipPoint.y;
  7591. var width = size.width;
  7592. var height = size.height;
  7593. if (yAlign === 'center') {
  7594. y2 = ptY + (height / 2);
  7595. if (xAlign === 'left') {
  7596. x1 = ptX;
  7597. x2 = x1 - caretSize;
  7598. x3 = x1;
  7599. y1 = y2 + caretSize;
  7600. y3 = y2 - caretSize;
  7601. } else {
  7602. x1 = ptX + width;
  7603. x2 = x1 + caretSize;
  7604. x3 = x1;
  7605. y1 = y2 - caretSize;
  7606. y3 = y2 + caretSize;
  7607. }
  7608. } else {
  7609. if (xAlign === 'left') {
  7610. x2 = ptX + cornerRadius + (caretSize);
  7611. x1 = x2 - caretSize;
  7612. x3 = x2 + caretSize;
  7613. } else if (xAlign === 'right') {
  7614. x2 = ptX + width - cornerRadius - caretSize;
  7615. x1 = x2 - caretSize;
  7616. x3 = x2 + caretSize;
  7617. } else {
  7618. x2 = vm.caretX;
  7619. x1 = x2 - caretSize;
  7620. x3 = x2 + caretSize;
  7621. }
  7622. if (yAlign === 'top') {
  7623. y1 = ptY;
  7624. y2 = y1 - caretSize;
  7625. y3 = y1;
  7626. } else {
  7627. y1 = ptY + height;
  7628. y2 = y1 + caretSize;
  7629. y3 = y1;
  7630. // invert drawing order
  7631. var tmp = x3;
  7632. x3 = x1;
  7633. x1 = tmp;
  7634. }
  7635. }
  7636. return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
  7637. },
  7638. drawTitle: function(pt, vm, ctx) {
  7639. var title = vm.title;
  7640. var length = title.length;
  7641. var titleFontSize, titleSpacing, i;
  7642. if (length) {
  7643. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7644. pt.x = getAlignedX(vm, vm._titleAlign);
  7645. ctx.textAlign = rtlHelper.textAlign(vm._titleAlign);
  7646. ctx.textBaseline = 'middle';
  7647. titleFontSize = vm.titleFontSize;
  7648. titleSpacing = vm.titleSpacing;
  7649. ctx.fillStyle = vm.titleFontColor;
  7650. ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
  7651. for (i = 0; i < length; ++i) {
  7652. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFontSize / 2);
  7653. pt.y += titleFontSize + titleSpacing; // Line Height and spacing
  7654. if (i + 1 === length) {
  7655. pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
  7656. }
  7657. }
  7658. }
  7659. },
  7660. drawBody: function(pt, vm, ctx) {
  7661. var bodyFontSize = vm.bodyFontSize;
  7662. var bodySpacing = vm.bodySpacing;
  7663. var bodyAlign = vm._bodyAlign;
  7664. var body = vm.body;
  7665. var drawColorBoxes = vm.displayColors;
  7666. var xLinePadding = 0;
  7667. var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;
  7668. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7669. var fillLineOfText = function(line) {
  7670. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyFontSize / 2);
  7671. pt.y += bodyFontSize + bodySpacing;
  7672. };
  7673. var bodyItem, textColor, labelColors, lines, i, j, ilen, jlen;
  7674. var bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  7675. ctx.textAlign = bodyAlign;
  7676. ctx.textBaseline = 'middle';
  7677. ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
  7678. pt.x = getAlignedX(vm, bodyAlignForCalculation);
  7679. // Before body lines
  7680. ctx.fillStyle = vm.bodyFontColor;
  7681. helpers$1.each(vm.beforeBody, fillLineOfText);
  7682. xLinePadding = drawColorBoxes && bodyAlignForCalculation !== 'right'
  7683. ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)
  7684. : 0;
  7685. // Draw body lines now
  7686. for (i = 0, ilen = body.length; i < ilen; ++i) {
  7687. bodyItem = body[i];
  7688. textColor = vm.labelTextColors[i];
  7689. labelColors = vm.labelColors[i];
  7690. ctx.fillStyle = textColor;
  7691. helpers$1.each(bodyItem.before, fillLineOfText);
  7692. lines = bodyItem.lines;
  7693. for (j = 0, jlen = lines.length; j < jlen; ++j) {
  7694. // Draw Legend-like boxes if needed
  7695. if (drawColorBoxes) {
  7696. var rtlColorX = rtlHelper.x(colorX);
  7697. // Fill a white rect so that colours merge nicely if the opacity is < 1
  7698. ctx.fillStyle = vm.legendColorBackground;
  7699. ctx.fillRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  7700. // Border
  7701. ctx.lineWidth = 1;
  7702. ctx.strokeStyle = labelColors.borderColor;
  7703. ctx.strokeRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  7704. // Inner square
  7705. ctx.fillStyle = labelColors.backgroundColor;
  7706. ctx.fillRect(rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), bodyFontSize - 2), pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
  7707. ctx.fillStyle = textColor;
  7708. }
  7709. fillLineOfText(lines[j]);
  7710. }
  7711. helpers$1.each(bodyItem.after, fillLineOfText);
  7712. }
  7713. // Reset back to 0 for after body
  7714. xLinePadding = 0;
  7715. // After body lines
  7716. helpers$1.each(vm.afterBody, fillLineOfText);
  7717. pt.y -= bodySpacing; // Remove last body spacing
  7718. },
  7719. drawFooter: function(pt, vm, ctx) {
  7720. var footer = vm.footer;
  7721. var length = footer.length;
  7722. var footerFontSize, i;
  7723. if (length) {
  7724. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7725. pt.x = getAlignedX(vm, vm._footerAlign);
  7726. pt.y += vm.footerMarginTop;
  7727. ctx.textAlign = rtlHelper.textAlign(vm._footerAlign);
  7728. ctx.textBaseline = 'middle';
  7729. footerFontSize = vm.footerFontSize;
  7730. ctx.fillStyle = vm.footerFontColor;
  7731. ctx.font = helpers$1.fontString(footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
  7732. for (i = 0; i < length; ++i) {
  7733. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFontSize / 2);
  7734. pt.y += footerFontSize + vm.footerSpacing;
  7735. }
  7736. }
  7737. },
  7738. drawBackground: function(pt, vm, ctx, tooltipSize) {
  7739. ctx.fillStyle = vm.backgroundColor;
  7740. ctx.strokeStyle = vm.borderColor;
  7741. ctx.lineWidth = vm.borderWidth;
  7742. var xAlign = vm.xAlign;
  7743. var yAlign = vm.yAlign;
  7744. var x = pt.x;
  7745. var y = pt.y;
  7746. var width = tooltipSize.width;
  7747. var height = tooltipSize.height;
  7748. var radius = vm.cornerRadius;
  7749. ctx.beginPath();
  7750. ctx.moveTo(x + radius, y);
  7751. if (yAlign === 'top') {
  7752. this.drawCaret(pt, tooltipSize);
  7753. }
  7754. ctx.lineTo(x + width - radius, y);
  7755. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  7756. if (yAlign === 'center' && xAlign === 'right') {
  7757. this.drawCaret(pt, tooltipSize);
  7758. }
  7759. ctx.lineTo(x + width, y + height - radius);
  7760. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  7761. if (yAlign === 'bottom') {
  7762. this.drawCaret(pt, tooltipSize);
  7763. }
  7764. ctx.lineTo(x + radius, y + height);
  7765. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  7766. if (yAlign === 'center' && xAlign === 'left') {
  7767. this.drawCaret(pt, tooltipSize);
  7768. }
  7769. ctx.lineTo(x, y + radius);
  7770. ctx.quadraticCurveTo(x, y, x + radius, y);
  7771. ctx.closePath();
  7772. ctx.fill();
  7773. if (vm.borderWidth > 0) {
  7774. ctx.stroke();
  7775. }
  7776. },
  7777. draw: function() {
  7778. var ctx = this._chart.ctx;
  7779. var vm = this._view;
  7780. if (vm.opacity === 0) {
  7781. return;
  7782. }
  7783. var tooltipSize = {
  7784. width: vm.width,
  7785. height: vm.height
  7786. };
  7787. var pt = {
  7788. x: vm.x,
  7789. y: vm.y
  7790. };
  7791. // IE11/Edge does not like very small opacities, so snap to 0
  7792. var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
  7793. // Truthy/falsey value for empty tooltip
  7794. var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
  7795. if (this._options.enabled && hasTooltipContent) {
  7796. ctx.save();
  7797. ctx.globalAlpha = opacity;
  7798. // Draw Background
  7799. this.drawBackground(pt, vm, ctx, tooltipSize);
  7800. // Draw Title, Body, and Footer
  7801. pt.y += vm.yPadding;
  7802. helpers$1.rtl.overrideTextDirection(ctx, vm.textDirection);
  7803. // Titles
  7804. this.drawTitle(pt, vm, ctx);
  7805. // Body
  7806. this.drawBody(pt, vm, ctx);
  7807. // Footer
  7808. this.drawFooter(pt, vm, ctx);
  7809. helpers$1.rtl.restoreTextDirection(ctx, vm.textDirection);
  7810. ctx.restore();
  7811. }
  7812. },
  7813. /**
  7814. * Handle an event
  7815. * @private
  7816. * @param {IEvent} event - The event to handle
  7817. * @returns {boolean} true if the tooltip changed
  7818. */
  7819. handleEvent: function(e) {
  7820. var me = this;
  7821. var options = me._options;
  7822. var changed = false;
  7823. me._lastActive = me._lastActive || [];
  7824. // Find Active Elements for tooltips
  7825. if (e.type === 'mouseout') {
  7826. me._active = [];
  7827. } else {
  7828. me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
  7829. if (options.reverse) {
  7830. me._active.reverse();
  7831. }
  7832. }
  7833. // Remember Last Actives
  7834. changed = !helpers$1.arrayEquals(me._active, me._lastActive);
  7835. // Only handle target event on tooltip change
  7836. if (changed) {
  7837. me._lastActive = me._active;
  7838. if (options.enabled || options.custom) {
  7839. me._eventPosition = {
  7840. x: e.x,
  7841. y: e.y
  7842. };
  7843. me.update(true);
  7844. me.pivot();
  7845. }
  7846. }
  7847. return changed;
  7848. }
  7849. });
  7850. /**
  7851. * @namespace Chart.Tooltip.positioners
  7852. */
  7853. var positioners_1 = positioners;
  7854. var core_tooltip = exports$4;
  7855. core_tooltip.positioners = positioners_1;
  7856. var valueOrDefault$9 = helpers$1.valueOrDefault;
  7857. core_defaults._set('global', {
  7858. elements: {},
  7859. events: [
  7860. 'mousemove',
  7861. 'mouseout',
  7862. 'click',
  7863. 'touchstart',
  7864. 'touchmove'
  7865. ],
  7866. hover: {
  7867. onHover: null,
  7868. mode: 'nearest',
  7869. intersect: true,
  7870. animationDuration: 400
  7871. },
  7872. onClick: null,
  7873. maintainAspectRatio: true,
  7874. responsive: true,
  7875. responsiveAnimationDuration: 0
  7876. });
  7877. /**
  7878. * Recursively merge the given config objects representing the `scales` option
  7879. * by incorporating scale defaults in `xAxes` and `yAxes` array items, then
  7880. * returns a deep copy of the result, thus doesn't alter inputs.
  7881. */
  7882. function mergeScaleConfig(/* config objects ... */) {
  7883. return helpers$1.merge(Object.create(null), [].slice.call(arguments), {
  7884. merger: function(key, target, source, options) {
  7885. if (key === 'xAxes' || key === 'yAxes') {
  7886. var slen = source[key].length;
  7887. var i, type, scale;
  7888. if (!target[key]) {
  7889. target[key] = [];
  7890. }
  7891. for (i = 0; i < slen; ++i) {
  7892. scale = source[key][i];
  7893. type = valueOrDefault$9(scale.type, key === 'xAxes' ? 'category' : 'linear');
  7894. if (i >= target[key].length) {
  7895. target[key].push({});
  7896. }
  7897. if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
  7898. // new/untyped scale or type changed: let's apply the new defaults
  7899. // then merge source scale to correctly overwrite the defaults.
  7900. helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);
  7901. } else {
  7902. // scales type are the same
  7903. helpers$1.merge(target[key][i], scale);
  7904. }
  7905. }
  7906. } else {
  7907. helpers$1._merger(key, target, source, options);
  7908. }
  7909. }
  7910. });
  7911. }
  7912. /**
  7913. * Recursively merge the given config objects as the root options by handling
  7914. * default scale options for the `scales` and `scale` properties, then returns
  7915. * a deep copy of the result, thus doesn't alter inputs.
  7916. */
  7917. function mergeConfig(/* config objects ... */) {
  7918. return helpers$1.merge(Object.create(null), [].slice.call(arguments), {
  7919. merger: function(key, target, source, options) {
  7920. var tval = target[key] || Object.create(null);
  7921. var sval = source[key];
  7922. if (key === 'scales') {
  7923. // scale config merging is complex. Add our own function here for that
  7924. target[key] = mergeScaleConfig(tval, sval);
  7925. } else if (key === 'scale') {
  7926. // used in polar area & radar charts since there is only one scale
  7927. target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]);
  7928. } else {
  7929. helpers$1._merger(key, target, source, options);
  7930. }
  7931. }
  7932. });
  7933. }
  7934. function initConfig(config) {
  7935. config = config || Object.create(null);
  7936. // Do NOT use mergeConfig for the data object because this method merges arrays
  7937. // and so would change references to labels and datasets, preventing data updates.
  7938. var data = config.data = config.data || {};
  7939. data.datasets = data.datasets || [];
  7940. data.labels = data.labels || [];
  7941. config.options = mergeConfig(
  7942. core_defaults.global,
  7943. core_defaults[config.type],
  7944. config.options || {});
  7945. return config;
  7946. }
  7947. function updateConfig(chart) {
  7948. var newOptions = chart.options;
  7949. helpers$1.each(chart.scales, function(scale) {
  7950. core_layouts.removeBox(chart, scale);
  7951. });
  7952. newOptions = mergeConfig(
  7953. core_defaults.global,
  7954. core_defaults[chart.config.type],
  7955. newOptions);
  7956. chart.options = chart.config.options = newOptions;
  7957. chart.ensureScalesHaveIDs();
  7958. chart.buildOrUpdateScales();
  7959. // Tooltip
  7960. chart.tooltip._options = newOptions.tooltips;
  7961. chart.tooltip.initialize();
  7962. }
  7963. function nextAvailableScaleId(axesOpts, prefix, index) {
  7964. var id;
  7965. var hasId = function(obj) {
  7966. return obj.id === id;
  7967. };
  7968. do {
  7969. id = prefix + index++;
  7970. } while (helpers$1.findIndex(axesOpts, hasId) >= 0);
  7971. return id;
  7972. }
  7973. function positionIsHorizontal(position) {
  7974. return position === 'top' || position === 'bottom';
  7975. }
  7976. function compare2Level(l1, l2) {
  7977. return function(a, b) {
  7978. return a[l1] === b[l1]
  7979. ? a[l2] - b[l2]
  7980. : a[l1] - b[l1];
  7981. };
  7982. }
  7983. var Chart = function(item, config) {
  7984. this.construct(item, config);
  7985. return this;
  7986. };
  7987. helpers$1.extend(Chart.prototype, /** @lends Chart */ {
  7988. /**
  7989. * @private
  7990. */
  7991. construct: function(item, config) {
  7992. var me = this;
  7993. config = initConfig(config);
  7994. var context = platform.acquireContext(item, config);
  7995. var canvas = context && context.canvas;
  7996. var height = canvas && canvas.height;
  7997. var width = canvas && canvas.width;
  7998. me.id = helpers$1.uid();
  7999. me.ctx = context;
  8000. me.canvas = canvas;
  8001. me.config = config;
  8002. me.width = width;
  8003. me.height = height;
  8004. me.aspectRatio = height ? width / height : null;
  8005. me.options = config.options;
  8006. me._bufferedRender = false;
  8007. me._layers = [];
  8008. /**
  8009. * Provided for backward compatibility, Chart and Chart.Controller have been merged,
  8010. * the "instance" still need to be defined since it might be called from plugins.
  8011. * @prop Chart#chart
  8012. * @deprecated since version 2.6.0
  8013. * @todo remove at version 3
  8014. * @private
  8015. */
  8016. me.chart = me;
  8017. me.controller = me; // chart.chart.controller #inception
  8018. // Add the chart instance to the global namespace
  8019. Chart.instances[me.id] = me;
  8020. // Define alias to the config data: `chart.data === chart.config.data`
  8021. Object.defineProperty(me, 'data', {
  8022. get: function() {
  8023. return me.config.data;
  8024. },
  8025. set: function(value) {
  8026. me.config.data = value;
  8027. }
  8028. });
  8029. if (!context || !canvas) {
  8030. // The given item is not a compatible context2d element, let's return before finalizing
  8031. // the chart initialization but after setting basic chart / controller properties that
  8032. // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
  8033. // https://github.com/chartjs/Chart.js/issues/2807
  8034. console.error("Failed to create chart: can't acquire context from the given item");
  8035. return;
  8036. }
  8037. me.initialize();
  8038. me.update();
  8039. },
  8040. /**
  8041. * @private
  8042. */
  8043. initialize: function() {
  8044. var me = this;
  8045. // Before init plugin notification
  8046. core_plugins.notify(me, 'beforeInit');
  8047. helpers$1.retinaScale(me, me.options.devicePixelRatio);
  8048. me.bindEvents();
  8049. if (me.options.responsive) {
  8050. // Initial resize before chart draws (must be silent to preserve initial animations).
  8051. me.resize(true);
  8052. }
  8053. me.initToolTip();
  8054. // After init plugin notification
  8055. core_plugins.notify(me, 'afterInit');
  8056. return me;
  8057. },
  8058. clear: function() {
  8059. helpers$1.canvas.clear(this);
  8060. return this;
  8061. },
  8062. stop: function() {
  8063. // Stops any current animation loop occurring
  8064. core_animations.cancelAnimation(this);
  8065. return this;
  8066. },
  8067. resize: function(silent) {
  8068. var me = this;
  8069. var options = me.options;
  8070. var canvas = me.canvas;
  8071. var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
  8072. // the canvas render width and height will be casted to integers so make sure that
  8073. // the canvas display style uses the same integer values to avoid blurring effect.
  8074. // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
  8075. var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas)));
  8076. var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas)));
  8077. if (me.width === newWidth && me.height === newHeight) {
  8078. return;
  8079. }
  8080. canvas.width = me.width = newWidth;
  8081. canvas.height = me.height = newHeight;
  8082. canvas.style.width = newWidth + 'px';
  8083. canvas.style.height = newHeight + 'px';
  8084. helpers$1.retinaScale(me, options.devicePixelRatio);
  8085. if (!silent) {
  8086. // Notify any plugins about the resize
  8087. var newSize = {width: newWidth, height: newHeight};
  8088. core_plugins.notify(me, 'resize', [newSize]);
  8089. // Notify of resize
  8090. if (options.onResize) {
  8091. options.onResize(me, newSize);
  8092. }
  8093. me.stop();
  8094. me.update({
  8095. duration: options.responsiveAnimationDuration
  8096. });
  8097. }
  8098. },
  8099. ensureScalesHaveIDs: function() {
  8100. var options = this.options;
  8101. var scalesOptions = options.scales || {};
  8102. var scaleOptions = options.scale;
  8103. helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) {
  8104. if (!xAxisOptions.id) {
  8105. xAxisOptions.id = nextAvailableScaleId(scalesOptions.xAxes, 'x-axis-', index);
  8106. }
  8107. });
  8108. helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) {
  8109. if (!yAxisOptions.id) {
  8110. yAxisOptions.id = nextAvailableScaleId(scalesOptions.yAxes, 'y-axis-', index);
  8111. }
  8112. });
  8113. if (scaleOptions) {
  8114. scaleOptions.id = scaleOptions.id || 'scale';
  8115. }
  8116. },
  8117. /**
  8118. * Builds a map of scale ID to scale object for future lookup.
  8119. */
  8120. buildOrUpdateScales: function() {
  8121. var me = this;
  8122. var options = me.options;
  8123. var scales = me.scales || {};
  8124. var items = [];
  8125. var updated = Object.keys(scales).reduce(function(obj, id) {
  8126. obj[id] = false;
  8127. return obj;
  8128. }, {});
  8129. if (options.scales) {
  8130. items = items.concat(
  8131. (options.scales.xAxes || []).map(function(xAxisOptions) {
  8132. return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
  8133. }),
  8134. (options.scales.yAxes || []).map(function(yAxisOptions) {
  8135. return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
  8136. })
  8137. );
  8138. }
  8139. if (options.scale) {
  8140. items.push({
  8141. options: options.scale,
  8142. dtype: 'radialLinear',
  8143. isDefault: true,
  8144. dposition: 'chartArea'
  8145. });
  8146. }
  8147. helpers$1.each(items, function(item) {
  8148. var scaleOptions = item.options;
  8149. var id = scaleOptions.id;
  8150. var scaleType = valueOrDefault$9(scaleOptions.type, item.dtype);
  8151. if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
  8152. scaleOptions.position = item.dposition;
  8153. }
  8154. updated[id] = true;
  8155. var scale = null;
  8156. if (id in scales && scales[id].type === scaleType) {
  8157. scale = scales[id];
  8158. scale.options = scaleOptions;
  8159. scale.ctx = me.ctx;
  8160. scale.chart = me;
  8161. } else {
  8162. var scaleClass = core_scaleService.getScaleConstructor(scaleType);
  8163. if (!scaleClass) {
  8164. return;
  8165. }
  8166. scale = new scaleClass({
  8167. id: id,
  8168. type: scaleType,
  8169. options: scaleOptions,
  8170. ctx: me.ctx,
  8171. chart: me
  8172. });
  8173. scales[scale.id] = scale;
  8174. }
  8175. scale.mergeTicksOptions();
  8176. // TODO(SB): I think we should be able to remove this custom case (options.scale)
  8177. // and consider it as a regular scale part of the "scales"" map only! This would
  8178. // make the logic easier and remove some useless? custom code.
  8179. if (item.isDefault) {
  8180. me.scale = scale;
  8181. }
  8182. });
  8183. // clear up discarded scales
  8184. helpers$1.each(updated, function(hasUpdated, id) {
  8185. if (!hasUpdated) {
  8186. delete scales[id];
  8187. }
  8188. });
  8189. me.scales = scales;
  8190. core_scaleService.addScalesToLayout(this);
  8191. },
  8192. buildOrUpdateControllers: function() {
  8193. var me = this;
  8194. var newControllers = [];
  8195. var datasets = me.data.datasets;
  8196. var i, ilen;
  8197. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  8198. var dataset = datasets[i];
  8199. var meta = me.getDatasetMeta(i);
  8200. var type = dataset.type || me.config.type;
  8201. if (meta.type && meta.type !== type) {
  8202. me.destroyDatasetMeta(i);
  8203. meta = me.getDatasetMeta(i);
  8204. }
  8205. meta.type = type;
  8206. meta.order = dataset.order || 0;
  8207. meta.index = i;
  8208. if (meta.controller) {
  8209. meta.controller.updateIndex(i);
  8210. meta.controller.linkScales();
  8211. } else {
  8212. var ControllerClass = controllers[meta.type];
  8213. if (ControllerClass === undefined) {
  8214. throw new Error('"' + meta.type + '" is not a chart type.');
  8215. }
  8216. meta.controller = new ControllerClass(me, i);
  8217. newControllers.push(meta.controller);
  8218. }
  8219. }
  8220. return newControllers;
  8221. },
  8222. /**
  8223. * Reset the elements of all datasets
  8224. * @private
  8225. */
  8226. resetElements: function() {
  8227. var me = this;
  8228. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  8229. me.getDatasetMeta(datasetIndex).controller.reset();
  8230. }, me);
  8231. },
  8232. /**
  8233. * Resets the chart back to it's state before the initial animation
  8234. */
  8235. reset: function() {
  8236. this.resetElements();
  8237. this.tooltip.initialize();
  8238. },
  8239. update: function(config) {
  8240. var me = this;
  8241. var i, ilen;
  8242. if (!config || typeof config !== 'object') {
  8243. // backwards compatibility
  8244. config = {
  8245. duration: config,
  8246. lazy: arguments[1]
  8247. };
  8248. }
  8249. updateConfig(me);
  8250. // plugins options references might have change, let's invalidate the cache
  8251. // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  8252. core_plugins._invalidate(me);
  8253. if (core_plugins.notify(me, 'beforeUpdate') === false) {
  8254. return;
  8255. }
  8256. // In case the entire data object changed
  8257. me.tooltip._data = me.data;
  8258. // Make sure dataset controllers are updated and new controllers are reset
  8259. var newControllers = me.buildOrUpdateControllers();
  8260. // Make sure all dataset controllers have correct meta data counts
  8261. for (i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
  8262. me.getDatasetMeta(i).controller.buildOrUpdateElements();
  8263. }
  8264. me.updateLayout();
  8265. // Can only reset the new controllers after the scales have been updated
  8266. if (me.options.animation && me.options.animation.duration) {
  8267. helpers$1.each(newControllers, function(controller) {
  8268. controller.reset();
  8269. });
  8270. }
  8271. me.updateDatasets();
  8272. // Need to reset tooltip in case it is displayed with elements that are removed
  8273. // after update.
  8274. me.tooltip.initialize();
  8275. // Last active contains items that were previously in the tooltip.
  8276. // When we reset the tooltip, we need to clear it
  8277. me.lastActive = [];
  8278. // Do this before render so that any plugins that need final scale updates can use it
  8279. core_plugins.notify(me, 'afterUpdate');
  8280. me._layers.sort(compare2Level('z', '_idx'));
  8281. if (me._bufferedRender) {
  8282. me._bufferedRequest = {
  8283. duration: config.duration,
  8284. easing: config.easing,
  8285. lazy: config.lazy
  8286. };
  8287. } else {
  8288. me.render(config);
  8289. }
  8290. },
  8291. /**
  8292. * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
  8293. * hook, in which case, plugins will not be called on `afterLayout`.
  8294. * @private
  8295. */
  8296. updateLayout: function() {
  8297. var me = this;
  8298. if (core_plugins.notify(me, 'beforeLayout') === false) {
  8299. return;
  8300. }
  8301. core_layouts.update(this, this.width, this.height);
  8302. me._layers = [];
  8303. helpers$1.each(me.boxes, function(box) {
  8304. // _configure is called twice, once in core.scale.update and once here.
  8305. // Here the boxes are fully updated and at their final positions.
  8306. if (box._configure) {
  8307. box._configure();
  8308. }
  8309. me._layers.push.apply(me._layers, box._layers());
  8310. }, me);
  8311. me._layers.forEach(function(item, index) {
  8312. item._idx = index;
  8313. });
  8314. /**
  8315. * Provided for backward compatibility, use `afterLayout` instead.
  8316. * @method IPlugin#afterScaleUpdate
  8317. * @deprecated since version 2.5.0
  8318. * @todo remove at version 3
  8319. * @private
  8320. */
  8321. core_plugins.notify(me, 'afterScaleUpdate');
  8322. core_plugins.notify(me, 'afterLayout');
  8323. },
  8324. /**
  8325. * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
  8326. * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
  8327. * @private
  8328. */
  8329. updateDatasets: function() {
  8330. var me = this;
  8331. if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) {
  8332. return;
  8333. }
  8334. for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  8335. me.updateDataset(i);
  8336. }
  8337. core_plugins.notify(me, 'afterDatasetsUpdate');
  8338. },
  8339. /**
  8340. * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
  8341. * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
  8342. * @private
  8343. */
  8344. updateDataset: function(index) {
  8345. var me = this;
  8346. var meta = me.getDatasetMeta(index);
  8347. var args = {
  8348. meta: meta,
  8349. index: index
  8350. };
  8351. if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
  8352. return;
  8353. }
  8354. meta.controller._update();
  8355. core_plugins.notify(me, 'afterDatasetUpdate', [args]);
  8356. },
  8357. render: function(config) {
  8358. var me = this;
  8359. if (!config || typeof config !== 'object') {
  8360. // backwards compatibility
  8361. config = {
  8362. duration: config,
  8363. lazy: arguments[1]
  8364. };
  8365. }
  8366. var animationOptions = me.options.animation;
  8367. var duration = valueOrDefault$9(config.duration, animationOptions && animationOptions.duration);
  8368. var lazy = config.lazy;
  8369. if (core_plugins.notify(me, 'beforeRender') === false) {
  8370. return;
  8371. }
  8372. var onComplete = function(animation) {
  8373. core_plugins.notify(me, 'afterRender');
  8374. helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me);
  8375. };
  8376. if (animationOptions && duration) {
  8377. var animation = new core_animation({
  8378. numSteps: duration / 16.66, // 60 fps
  8379. easing: config.easing || animationOptions.easing,
  8380. render: function(chart, animationObject) {
  8381. var easingFunction = helpers$1.easing.effects[animationObject.easing];
  8382. var currentStep = animationObject.currentStep;
  8383. var stepDecimal = currentStep / animationObject.numSteps;
  8384. chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
  8385. },
  8386. onAnimationProgress: animationOptions.onProgress,
  8387. onAnimationComplete: onComplete
  8388. });
  8389. core_animations.addAnimation(me, animation, duration, lazy);
  8390. } else {
  8391. me.draw();
  8392. // See https://github.com/chartjs/Chart.js/issues/3781
  8393. onComplete(new core_animation({numSteps: 0, chart: me}));
  8394. }
  8395. return me;
  8396. },
  8397. draw: function(easingValue) {
  8398. var me = this;
  8399. var i, layers;
  8400. me.clear();
  8401. if (helpers$1.isNullOrUndef(easingValue)) {
  8402. easingValue = 1;
  8403. }
  8404. me.transition(easingValue);
  8405. if (me.width <= 0 || me.height <= 0) {
  8406. return;
  8407. }
  8408. if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
  8409. return;
  8410. }
  8411. // Because of plugin hooks (before/afterDatasetsDraw), datasets can't
  8412. // currently be part of layers. Instead, we draw
  8413. // layers <= 0 before(default, backward compat), and the rest after
  8414. layers = me._layers;
  8415. for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
  8416. layers[i].draw(me.chartArea);
  8417. }
  8418. me.drawDatasets(easingValue);
  8419. // Rest of layers
  8420. for (; i < layers.length; ++i) {
  8421. layers[i].draw(me.chartArea);
  8422. }
  8423. me._drawTooltip(easingValue);
  8424. core_plugins.notify(me, 'afterDraw', [easingValue]);
  8425. },
  8426. /**
  8427. * @private
  8428. */
  8429. transition: function(easingValue) {
  8430. var me = this;
  8431. for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
  8432. if (me.isDatasetVisible(i)) {
  8433. me.getDatasetMeta(i).controller.transition(easingValue);
  8434. }
  8435. }
  8436. me.tooltip.transition(easingValue);
  8437. },
  8438. /**
  8439. * @private
  8440. */
  8441. _getSortedDatasetMetas: function(filterVisible) {
  8442. var me = this;
  8443. var datasets = me.data.datasets || [];
  8444. var result = [];
  8445. var i, ilen;
  8446. for (i = 0, ilen = datasets.length; i < ilen; ++i) {
  8447. if (!filterVisible || me.isDatasetVisible(i)) {
  8448. result.push(me.getDatasetMeta(i));
  8449. }
  8450. }
  8451. result.sort(compare2Level('order', 'index'));
  8452. return result;
  8453. },
  8454. /**
  8455. * @private
  8456. */
  8457. _getSortedVisibleDatasetMetas: function() {
  8458. return this._getSortedDatasetMetas(true);
  8459. },
  8460. /**
  8461. * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
  8462. * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
  8463. * @private
  8464. */
  8465. drawDatasets: function(easingValue) {
  8466. var me = this;
  8467. var metasets, i;
  8468. if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
  8469. return;
  8470. }
  8471. metasets = me._getSortedVisibleDatasetMetas();
  8472. for (i = metasets.length - 1; i >= 0; --i) {
  8473. me.drawDataset(metasets[i], easingValue);
  8474. }
  8475. core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
  8476. },
  8477. /**
  8478. * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
  8479. * hook, in which case, plugins will not be called on `afterDatasetDraw`.
  8480. * @private
  8481. */
  8482. drawDataset: function(meta, easingValue) {
  8483. var me = this;
  8484. var args = {
  8485. meta: meta,
  8486. index: meta.index,
  8487. easingValue: easingValue
  8488. };
  8489. if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
  8490. return;
  8491. }
  8492. meta.controller.draw(easingValue);
  8493. core_plugins.notify(me, 'afterDatasetDraw', [args]);
  8494. },
  8495. /**
  8496. * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
  8497. * hook, in which case, plugins will not be called on `afterTooltipDraw`.
  8498. * @private
  8499. */
  8500. _drawTooltip: function(easingValue) {
  8501. var me = this;
  8502. var tooltip = me.tooltip;
  8503. var args = {
  8504. tooltip: tooltip,
  8505. easingValue: easingValue
  8506. };
  8507. if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
  8508. return;
  8509. }
  8510. tooltip.draw();
  8511. core_plugins.notify(me, 'afterTooltipDraw', [args]);
  8512. },
  8513. /**
  8514. * Get the single element that was clicked on
  8515. * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
  8516. */
  8517. getElementAtEvent: function(e) {
  8518. return core_interaction.modes.single(this, e);
  8519. },
  8520. getElementsAtEvent: function(e) {
  8521. return core_interaction.modes.label(this, e, {intersect: true});
  8522. },
  8523. getElementsAtXAxis: function(e) {
  8524. return core_interaction.modes['x-axis'](this, e, {intersect: true});
  8525. },
  8526. getElementsAtEventForMode: function(e, mode, options) {
  8527. var method = core_interaction.modes[mode];
  8528. if (typeof method === 'function') {
  8529. return method(this, e, options);
  8530. }
  8531. return [];
  8532. },
  8533. getDatasetAtEvent: function(e) {
  8534. return core_interaction.modes.dataset(this, e, {intersect: true});
  8535. },
  8536. getDatasetMeta: function(datasetIndex) {
  8537. var me = this;
  8538. var dataset = me.data.datasets[datasetIndex];
  8539. if (!dataset._meta) {
  8540. dataset._meta = {};
  8541. }
  8542. var meta = dataset._meta[me.id];
  8543. if (!meta) {
  8544. meta = dataset._meta[me.id] = {
  8545. type: null,
  8546. data: [],
  8547. dataset: null,
  8548. controller: null,
  8549. hidden: null, // See isDatasetVisible() comment
  8550. xAxisID: null,
  8551. yAxisID: null,
  8552. order: dataset.order || 0,
  8553. index: datasetIndex
  8554. };
  8555. }
  8556. return meta;
  8557. },
  8558. getVisibleDatasetCount: function() {
  8559. var count = 0;
  8560. for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  8561. if (this.isDatasetVisible(i)) {
  8562. count++;
  8563. }
  8564. }
  8565. return count;
  8566. },
  8567. isDatasetVisible: function(datasetIndex) {
  8568. var meta = this.getDatasetMeta(datasetIndex);
  8569. // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
  8570. // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
  8571. return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
  8572. },
  8573. generateLegend: function() {
  8574. return this.options.legendCallback(this);
  8575. },
  8576. /**
  8577. * @private
  8578. */
  8579. destroyDatasetMeta: function(datasetIndex) {
  8580. var id = this.id;
  8581. var dataset = this.data.datasets[datasetIndex];
  8582. var meta = dataset._meta && dataset._meta[id];
  8583. if (meta) {
  8584. meta.controller.destroy();
  8585. delete dataset._meta[id];
  8586. }
  8587. },
  8588. destroy: function() {
  8589. var me = this;
  8590. var canvas = me.canvas;
  8591. var i, ilen;
  8592. me.stop();
  8593. // dataset controllers need to cleanup associated data
  8594. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  8595. me.destroyDatasetMeta(i);
  8596. }
  8597. if (canvas) {
  8598. me.unbindEvents();
  8599. helpers$1.canvas.clear(me);
  8600. platform.releaseContext(me.ctx);
  8601. me.canvas = null;
  8602. me.ctx = null;
  8603. }
  8604. core_plugins.notify(me, 'destroy');
  8605. delete Chart.instances[me.id];
  8606. },
  8607. toBase64Image: function() {
  8608. return this.canvas.toDataURL.apply(this.canvas, arguments);
  8609. },
  8610. initToolTip: function() {
  8611. var me = this;
  8612. me.tooltip = new core_tooltip({
  8613. _chart: me,
  8614. _chartInstance: me, // deprecated, backward compatibility
  8615. _data: me.data,
  8616. _options: me.options.tooltips
  8617. }, me);
  8618. },
  8619. /**
  8620. * @private
  8621. */
  8622. bindEvents: function() {
  8623. var me = this;
  8624. var listeners = me._listeners = {};
  8625. var listener = function() {
  8626. me.eventHandler.apply(me, arguments);
  8627. };
  8628. helpers$1.each(me.options.events, function(type) {
  8629. platform.addEventListener(me, type, listener);
  8630. listeners[type] = listener;
  8631. });
  8632. // Elements used to detect size change should not be injected for non responsive charts.
  8633. // See https://github.com/chartjs/Chart.js/issues/2210
  8634. if (me.options.responsive) {
  8635. listener = function() {
  8636. me.resize();
  8637. };
  8638. platform.addEventListener(me, 'resize', listener);
  8639. listeners.resize = listener;
  8640. }
  8641. },
  8642. /**
  8643. * @private
  8644. */
  8645. unbindEvents: function() {
  8646. var me = this;
  8647. var listeners = me._listeners;
  8648. if (!listeners) {
  8649. return;
  8650. }
  8651. delete me._listeners;
  8652. helpers$1.each(listeners, function(listener, type) {
  8653. platform.removeEventListener(me, type, listener);
  8654. });
  8655. },
  8656. updateHoverStyle: function(elements, mode, enabled) {
  8657. var prefix = enabled ? 'set' : 'remove';
  8658. var element, i, ilen;
  8659. for (i = 0, ilen = elements.length; i < ilen; ++i) {
  8660. element = elements[i];
  8661. if (element) {
  8662. this.getDatasetMeta(element._datasetIndex).controller[prefix + 'HoverStyle'](element);
  8663. }
  8664. }
  8665. if (mode === 'dataset') {
  8666. this.getDatasetMeta(elements[0]._datasetIndex).controller['_' + prefix + 'DatasetHoverStyle']();
  8667. }
  8668. },
  8669. /**
  8670. * @private
  8671. */
  8672. eventHandler: function(e) {
  8673. var me = this;
  8674. var tooltip = me.tooltip;
  8675. if (core_plugins.notify(me, 'beforeEvent', [e]) === false) {
  8676. return;
  8677. }
  8678. // Buffer any update calls so that renders do not occur
  8679. me._bufferedRender = true;
  8680. me._bufferedRequest = null;
  8681. var changed = me.handleEvent(e);
  8682. // for smooth tooltip animations issue #4989
  8683. // the tooltip should be the source of change
  8684. // Animation check workaround:
  8685. // tooltip._start will be null when tooltip isn't animating
  8686. if (tooltip) {
  8687. changed = tooltip._start
  8688. ? tooltip.handleEvent(e)
  8689. : changed | tooltip.handleEvent(e);
  8690. }
  8691. core_plugins.notify(me, 'afterEvent', [e]);
  8692. var bufferedRequest = me._bufferedRequest;
  8693. if (bufferedRequest) {
  8694. // If we have an update that was triggered, we need to do a normal render
  8695. me.render(bufferedRequest);
  8696. } else if (changed && !me.animating) {
  8697. // If entering, leaving, or changing elements, animate the change via pivot
  8698. me.stop();
  8699. // We only need to render at this point. Updating will cause scales to be
  8700. // recomputed generating flicker & using more memory than necessary.
  8701. me.render({
  8702. duration: me.options.hover.animationDuration,
  8703. lazy: true
  8704. });
  8705. }
  8706. me._bufferedRender = false;
  8707. me._bufferedRequest = null;
  8708. return me;
  8709. },
  8710. /**
  8711. * Handle an event
  8712. * @private
  8713. * @param {IEvent} event the event to handle
  8714. * @return {boolean} true if the chart needs to re-render
  8715. */
  8716. handleEvent: function(e) {
  8717. var me = this;
  8718. var options = me.options || {};
  8719. var hoverOptions = options.hover;
  8720. var changed = false;
  8721. me.lastActive = me.lastActive || [];
  8722. // Find Active Elements for hover and tooltips
  8723. if (e.type === 'mouseout') {
  8724. me.active = [];
  8725. } else {
  8726. me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
  8727. }
  8728. // Invoke onHover hook
  8729. // Need to call with native event here to not break backwards compatibility
  8730. helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
  8731. if (e.type === 'mouseup' || e.type === 'click') {
  8732. if (options.onClick) {
  8733. // Use e.native here for backwards compatibility
  8734. options.onClick.call(me, e.native, me.active);
  8735. }
  8736. }
  8737. // Remove styling for last active (even if it may still be active)
  8738. if (me.lastActive.length) {
  8739. me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
  8740. }
  8741. // Built in hover styling
  8742. if (me.active.length && hoverOptions.mode) {
  8743. me.updateHoverStyle(me.active, hoverOptions.mode, true);
  8744. }
  8745. changed = !helpers$1.arrayEquals(me.active, me.lastActive);
  8746. // Remember Last Actives
  8747. me.lastActive = me.active;
  8748. return changed;
  8749. }
  8750. });
  8751. /**
  8752. * NOTE(SB) We actually don't use this container anymore but we need to keep it
  8753. * for backward compatibility. Though, it can still be useful for plugins that
  8754. * would need to work on multiple charts?!
  8755. */
  8756. Chart.instances = {};
  8757. var core_controller = Chart;
  8758. // DEPRECATIONS
  8759. /**
  8760. * Provided for backward compatibility, use Chart instead.
  8761. * @class Chart.Controller
  8762. * @deprecated since version 2.6
  8763. * @todo remove at version 3
  8764. * @private
  8765. */
  8766. Chart.Controller = Chart;
  8767. /**
  8768. * Provided for backward compatibility, not available anymore.
  8769. * @namespace Chart
  8770. * @deprecated since version 2.8
  8771. * @todo remove at version 3
  8772. * @private
  8773. */
  8774. Chart.types = {};
  8775. /**
  8776. * Provided for backward compatibility, not available anymore.
  8777. * @namespace Chart.helpers.configMerge
  8778. * @deprecated since version 2.8.0
  8779. * @todo remove at version 3
  8780. * @private
  8781. */
  8782. helpers$1.configMerge = mergeConfig;
  8783. /**
  8784. * Provided for backward compatibility, not available anymore.
  8785. * @namespace Chart.helpers.scaleMerge
  8786. * @deprecated since version 2.8.0
  8787. * @todo remove at version 3
  8788. * @private
  8789. */
  8790. helpers$1.scaleMerge = mergeScaleConfig;
  8791. var core_helpers = function() {
  8792. // -- Basic js utility methods
  8793. helpers$1.where = function(collection, filterCallback) {
  8794. if (helpers$1.isArray(collection) && Array.prototype.filter) {
  8795. return collection.filter(filterCallback);
  8796. }
  8797. var filtered = [];
  8798. helpers$1.each(collection, function(item) {
  8799. if (filterCallback(item)) {
  8800. filtered.push(item);
  8801. }
  8802. });
  8803. return filtered;
  8804. };
  8805. helpers$1.findIndex = Array.prototype.findIndex ?
  8806. function(array, callback, scope) {
  8807. return array.findIndex(callback, scope);
  8808. } :
  8809. function(array, callback, scope) {
  8810. scope = scope === undefined ? array : scope;
  8811. for (var i = 0, ilen = array.length; i < ilen; ++i) {
  8812. if (callback.call(scope, array[i], i, array)) {
  8813. return i;
  8814. }
  8815. }
  8816. return -1;
  8817. };
  8818. helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
  8819. // Default to start of the array
  8820. if (helpers$1.isNullOrUndef(startIndex)) {
  8821. startIndex = -1;
  8822. }
  8823. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  8824. var currentItem = arrayToSearch[i];
  8825. if (filterCallback(currentItem)) {
  8826. return currentItem;
  8827. }
  8828. }
  8829. };
  8830. helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
  8831. // Default to end of the array
  8832. if (helpers$1.isNullOrUndef(startIndex)) {
  8833. startIndex = arrayToSearch.length;
  8834. }
  8835. for (var i = startIndex - 1; i >= 0; i--) {
  8836. var currentItem = arrayToSearch[i];
  8837. if (filterCallback(currentItem)) {
  8838. return currentItem;
  8839. }
  8840. }
  8841. };
  8842. // -- Math methods
  8843. helpers$1.isNumber = function(n) {
  8844. return !isNaN(parseFloat(n)) && isFinite(n);
  8845. };
  8846. helpers$1.almostEquals = function(x, y, epsilon) {
  8847. return Math.abs(x - y) < epsilon;
  8848. };
  8849. helpers$1.almostWhole = function(x, epsilon) {
  8850. var rounded = Math.round(x);
  8851. return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
  8852. };
  8853. helpers$1.max = function(array) {
  8854. return array.reduce(function(max, value) {
  8855. if (!isNaN(value)) {
  8856. return Math.max(max, value);
  8857. }
  8858. return max;
  8859. }, Number.NEGATIVE_INFINITY);
  8860. };
  8861. helpers$1.min = function(array) {
  8862. return array.reduce(function(min, value) {
  8863. if (!isNaN(value)) {
  8864. return Math.min(min, value);
  8865. }
  8866. return min;
  8867. }, Number.POSITIVE_INFINITY);
  8868. };
  8869. helpers$1.sign = Math.sign ?
  8870. function(x) {
  8871. return Math.sign(x);
  8872. } :
  8873. function(x) {
  8874. x = +x; // convert to a number
  8875. if (x === 0 || isNaN(x)) {
  8876. return x;
  8877. }
  8878. return x > 0 ? 1 : -1;
  8879. };
  8880. helpers$1.toRadians = function(degrees) {
  8881. return degrees * (Math.PI / 180);
  8882. };
  8883. helpers$1.toDegrees = function(radians) {
  8884. return radians * (180 / Math.PI);
  8885. };
  8886. /**
  8887. * Returns the number of decimal places
  8888. * i.e. the number of digits after the decimal point, of the value of this Number.
  8889. * @param {number} x - A number.
  8890. * @returns {number} The number of decimal places.
  8891. * @private
  8892. */
  8893. helpers$1._decimalPlaces = function(x) {
  8894. if (!helpers$1.isFinite(x)) {
  8895. return;
  8896. }
  8897. var e = 1;
  8898. var p = 0;
  8899. while (Math.round(x * e) / e !== x) {
  8900. e *= 10;
  8901. p++;
  8902. }
  8903. return p;
  8904. };
  8905. // Gets the angle from vertical upright to the point about a centre.
  8906. helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) {
  8907. var distanceFromXCenter = anglePoint.x - centrePoint.x;
  8908. var distanceFromYCenter = anglePoint.y - centrePoint.y;
  8909. var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  8910. var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  8911. if (angle < (-0.5 * Math.PI)) {
  8912. angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
  8913. }
  8914. return {
  8915. angle: angle,
  8916. distance: radialDistanceFromCenter
  8917. };
  8918. };
  8919. helpers$1.distanceBetweenPoints = function(pt1, pt2) {
  8920. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  8921. };
  8922. /**
  8923. * Provided for backward compatibility, not available anymore
  8924. * @function Chart.helpers.aliasPixel
  8925. * @deprecated since version 2.8.0
  8926. * @todo remove at version 3
  8927. */
  8928. helpers$1.aliasPixel = function(pixelWidth) {
  8929. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  8930. };
  8931. /**
  8932. * Returns the aligned pixel value to avoid anti-aliasing blur
  8933. * @param {Chart} chart - The chart instance.
  8934. * @param {number} pixel - A pixel value.
  8935. * @param {number} width - The width of the element.
  8936. * @returns {number} The aligned pixel value.
  8937. * @private
  8938. */
  8939. helpers$1._alignPixel = function(chart, pixel, width) {
  8940. var devicePixelRatio = chart.currentDevicePixelRatio;
  8941. var halfWidth = width / 2;
  8942. return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  8943. };
  8944. helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
  8945. // Props to Rob Spencer at scaled innovation for his post on splining between points
  8946. // http://scaledinnovation.com/analytics/splines/aboutSplines.html
  8947. // This function must also respect "skipped" points
  8948. var previous = firstPoint.skip ? middlePoint : firstPoint;
  8949. var current = middlePoint;
  8950. var next = afterPoint.skip ? middlePoint : afterPoint;
  8951. var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
  8952. var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
  8953. var s01 = d01 / (d01 + d12);
  8954. var s12 = d12 / (d01 + d12);
  8955. // If all points are the same, s01 & s02 will be inf
  8956. s01 = isNaN(s01) ? 0 : s01;
  8957. s12 = isNaN(s12) ? 0 : s12;
  8958. var fa = t * s01; // scaling factor for triangle Ta
  8959. var fb = t * s12;
  8960. return {
  8961. previous: {
  8962. x: current.x - fa * (next.x - previous.x),
  8963. y: current.y - fa * (next.y - previous.y)
  8964. },
  8965. next: {
  8966. x: current.x + fb * (next.x - previous.x),
  8967. y: current.y + fb * (next.y - previous.y)
  8968. }
  8969. };
  8970. };
  8971. helpers$1.EPSILON = Number.EPSILON || 1e-14;
  8972. helpers$1.splineCurveMonotone = function(points) {
  8973. // This function calculates Bézier control points in a similar way than |splineCurve|,
  8974. // but preserves monotonicity of the provided data and ensures no local extremums are added
  8975. // between the dataset discrete points due to the interpolation.
  8976. // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
  8977. var pointsWithTangents = (points || []).map(function(point) {
  8978. return {
  8979. model: point._model,
  8980. deltaK: 0,
  8981. mK: 0
  8982. };
  8983. });
  8984. // Calculate slopes (deltaK) and initialize tangents (mK)
  8985. var pointsLen = pointsWithTangents.length;
  8986. var i, pointBefore, pointCurrent, pointAfter;
  8987. for (i = 0; i < pointsLen; ++i) {
  8988. pointCurrent = pointsWithTangents[i];
  8989. if (pointCurrent.model.skip) {
  8990. continue;
  8991. }
  8992. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  8993. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  8994. if (pointAfter && !pointAfter.model.skip) {
  8995. var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
  8996. // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
  8997. pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
  8998. }
  8999. if (!pointBefore || pointBefore.model.skip) {
  9000. pointCurrent.mK = pointCurrent.deltaK;
  9001. } else if (!pointAfter || pointAfter.model.skip) {
  9002. pointCurrent.mK = pointBefore.deltaK;
  9003. } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
  9004. pointCurrent.mK = 0;
  9005. } else {
  9006. pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
  9007. }
  9008. }
  9009. // Adjust tangents to ensure monotonic properties
  9010. var alphaK, betaK, tauK, squaredMagnitude;
  9011. for (i = 0; i < pointsLen - 1; ++i) {
  9012. pointCurrent = pointsWithTangents[i];
  9013. pointAfter = pointsWithTangents[i + 1];
  9014. if (pointCurrent.model.skip || pointAfter.model.skip) {
  9015. continue;
  9016. }
  9017. if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
  9018. pointCurrent.mK = pointAfter.mK = 0;
  9019. continue;
  9020. }
  9021. alphaK = pointCurrent.mK / pointCurrent.deltaK;
  9022. betaK = pointAfter.mK / pointCurrent.deltaK;
  9023. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  9024. if (squaredMagnitude <= 9) {
  9025. continue;
  9026. }
  9027. tauK = 3 / Math.sqrt(squaredMagnitude);
  9028. pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
  9029. pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
  9030. }
  9031. // Compute control points
  9032. var deltaX;
  9033. for (i = 0; i < pointsLen; ++i) {
  9034. pointCurrent = pointsWithTangents[i];
  9035. if (pointCurrent.model.skip) {
  9036. continue;
  9037. }
  9038. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  9039. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  9040. if (pointBefore && !pointBefore.model.skip) {
  9041. deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
  9042. pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
  9043. pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
  9044. }
  9045. if (pointAfter && !pointAfter.model.skip) {
  9046. deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
  9047. pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
  9048. pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
  9049. }
  9050. }
  9051. };
  9052. helpers$1.nextItem = function(collection, index, loop) {
  9053. if (loop) {
  9054. return index >= collection.length - 1 ? collection[0] : collection[index + 1];
  9055. }
  9056. return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
  9057. };
  9058. helpers$1.previousItem = function(collection, index, loop) {
  9059. if (loop) {
  9060. return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
  9061. }
  9062. return index <= 0 ? collection[0] : collection[index - 1];
  9063. };
  9064. // Implementation of the nice number algorithm used in determining where axis labels will go
  9065. helpers$1.niceNum = function(range, round) {
  9066. var exponent = Math.floor(helpers$1.log10(range));
  9067. var fraction = range / Math.pow(10, exponent);
  9068. var niceFraction;
  9069. if (round) {
  9070. if (fraction < 1.5) {
  9071. niceFraction = 1;
  9072. } else if (fraction < 3) {
  9073. niceFraction = 2;
  9074. } else if (fraction < 7) {
  9075. niceFraction = 5;
  9076. } else {
  9077. niceFraction = 10;
  9078. }
  9079. } else if (fraction <= 1.0) {
  9080. niceFraction = 1;
  9081. } else if (fraction <= 2) {
  9082. niceFraction = 2;
  9083. } else if (fraction <= 5) {
  9084. niceFraction = 5;
  9085. } else {
  9086. niceFraction = 10;
  9087. }
  9088. return niceFraction * Math.pow(10, exponent);
  9089. };
  9090. // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  9091. helpers$1.requestAnimFrame = (function() {
  9092. if (typeof window === 'undefined') {
  9093. return function(callback) {
  9094. callback();
  9095. };
  9096. }
  9097. return window.requestAnimationFrame ||
  9098. window.webkitRequestAnimationFrame ||
  9099. window.mozRequestAnimationFrame ||
  9100. window.oRequestAnimationFrame ||
  9101. window.msRequestAnimationFrame ||
  9102. function(callback) {
  9103. return window.setTimeout(callback, 1000 / 60);
  9104. };
  9105. }());
  9106. // -- DOM methods
  9107. helpers$1.getRelativePosition = function(evt, chart) {
  9108. var mouseX, mouseY;
  9109. var e = evt.originalEvent || evt;
  9110. var canvas = evt.target || evt.srcElement;
  9111. var boundingRect = canvas.getBoundingClientRect();
  9112. var touches = e.touches;
  9113. if (touches && touches.length > 0) {
  9114. mouseX = touches[0].clientX;
  9115. mouseY = touches[0].clientY;
  9116. } else {
  9117. mouseX = e.clientX;
  9118. mouseY = e.clientY;
  9119. }
  9120. // Scale mouse coordinates into canvas coordinates
  9121. // by following the pattern laid out by 'jerryj' in the comments of
  9122. // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
  9123. var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left'));
  9124. var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top'));
  9125. var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right'));
  9126. var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom'));
  9127. var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
  9128. var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
  9129. // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
  9130. // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
  9131. mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
  9132. mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
  9133. return {
  9134. x: mouseX,
  9135. y: mouseY
  9136. };
  9137. };
  9138. // Private helper function to convert max-width/max-height values that may be percentages into a number
  9139. function parseMaxStyle(styleValue, node, parentProperty) {
  9140. var valueInPixels;
  9141. if (typeof styleValue === 'string') {
  9142. valueInPixels = parseInt(styleValue, 10);
  9143. if (styleValue.indexOf('%') !== -1) {
  9144. // percentage * size in dimension
  9145. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  9146. }
  9147. } else {
  9148. valueInPixels = styleValue;
  9149. }
  9150. return valueInPixels;
  9151. }
  9152. /**
  9153. * Returns if the given value contains an effective constraint.
  9154. * @private
  9155. */
  9156. function isConstrainedValue(value) {
  9157. return value !== undefined && value !== null && value !== 'none';
  9158. }
  9159. /**
  9160. * Returns the max width or height of the given DOM node in a cross-browser compatible fashion
  9161. * @param {HTMLElement} domNode - the node to check the constraint on
  9162. * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
  9163. * @param {string} percentageProperty - property of parent to use when calculating width as a percentage
  9164. * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
  9165. */
  9166. function getConstraintDimension(domNode, maxStyle, percentageProperty) {
  9167. var view = document.defaultView;
  9168. var parentNode = helpers$1._getParentNode(domNode);
  9169. var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
  9170. var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
  9171. var hasCNode = isConstrainedValue(constrainedNode);
  9172. var hasCContainer = isConstrainedValue(constrainedContainer);
  9173. var infinity = Number.POSITIVE_INFINITY;
  9174. if (hasCNode || hasCContainer) {
  9175. return Math.min(
  9176. hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
  9177. hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
  9178. }
  9179. return 'none';
  9180. }
  9181. // returns Number or undefined if no constraint
  9182. helpers$1.getConstraintWidth = function(domNode) {
  9183. return getConstraintDimension(domNode, 'max-width', 'clientWidth');
  9184. };
  9185. // returns Number or undefined if no constraint
  9186. helpers$1.getConstraintHeight = function(domNode) {
  9187. return getConstraintDimension(domNode, 'max-height', 'clientHeight');
  9188. };
  9189. /**
  9190. * @private
  9191. */
  9192. helpers$1._calculatePadding = function(container, padding, parentDimension) {
  9193. padding = helpers$1.getStyle(container, padding);
  9194. return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
  9195. };
  9196. /**
  9197. * @private
  9198. */
  9199. helpers$1._getParentNode = function(domNode) {
  9200. var parent = domNode.parentNode;
  9201. if (parent && parent.toString() === '[object ShadowRoot]') {
  9202. parent = parent.host;
  9203. }
  9204. return parent;
  9205. };
  9206. helpers$1.getMaximumWidth = function(domNode) {
  9207. var container = helpers$1._getParentNode(domNode);
  9208. if (!container) {
  9209. return domNode.clientWidth;
  9210. }
  9211. var clientWidth = container.clientWidth;
  9212. var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth);
  9213. var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth);
  9214. var w = clientWidth - paddingLeft - paddingRight;
  9215. var cw = helpers$1.getConstraintWidth(domNode);
  9216. return isNaN(cw) ? w : Math.min(w, cw);
  9217. };
  9218. helpers$1.getMaximumHeight = function(domNode) {
  9219. var container = helpers$1._getParentNode(domNode);
  9220. if (!container) {
  9221. return domNode.clientHeight;
  9222. }
  9223. var clientHeight = container.clientHeight;
  9224. var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight);
  9225. var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight);
  9226. var h = clientHeight - paddingTop - paddingBottom;
  9227. var ch = helpers$1.getConstraintHeight(domNode);
  9228. return isNaN(ch) ? h : Math.min(h, ch);
  9229. };
  9230. helpers$1.getStyle = function(el, property) {
  9231. return el.currentStyle ?
  9232. el.currentStyle[property] :
  9233. document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
  9234. };
  9235. helpers$1.retinaScale = function(chart, forceRatio) {
  9236. var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
  9237. if (pixelRatio === 1) {
  9238. return;
  9239. }
  9240. var canvas = chart.canvas;
  9241. var height = chart.height;
  9242. var width = chart.width;
  9243. canvas.height = height * pixelRatio;
  9244. canvas.width = width * pixelRatio;
  9245. chart.ctx.scale(pixelRatio, pixelRatio);
  9246. // If no style has been set on the canvas, the render size is used as display size,
  9247. // making the chart visually bigger, so let's enforce it to the "correct" values.
  9248. // See https://github.com/chartjs/Chart.js/issues/3575
  9249. if (!canvas.style.height && !canvas.style.width) {
  9250. canvas.style.height = height + 'px';
  9251. canvas.style.width = width + 'px';
  9252. }
  9253. };
  9254. // -- Canvas methods
  9255. helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) {
  9256. return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
  9257. };
  9258. helpers$1.longestText = function(ctx, font, arrayOfThings, cache) {
  9259. cache = cache || {};
  9260. var data = cache.data = cache.data || {};
  9261. var gc = cache.garbageCollect = cache.garbageCollect || [];
  9262. if (cache.font !== font) {
  9263. data = cache.data = {};
  9264. gc = cache.garbageCollect = [];
  9265. cache.font = font;
  9266. }
  9267. ctx.font = font;
  9268. var longest = 0;
  9269. var ilen = arrayOfThings.length;
  9270. var i, j, jlen, thing, nestedThing;
  9271. for (i = 0; i < ilen; i++) {
  9272. thing = arrayOfThings[i];
  9273. // Undefined strings and arrays should not be measured
  9274. if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) {
  9275. longest = helpers$1.measureText(ctx, data, gc, longest, thing);
  9276. } else if (helpers$1.isArray(thing)) {
  9277. // if it is an array lets measure each element
  9278. // to do maybe simplify this function a bit so we can do this more recursively?
  9279. for (j = 0, jlen = thing.length; j < jlen; j++) {
  9280. nestedThing = thing[j];
  9281. // Undefined strings and arrays should not be measured
  9282. if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) {
  9283. longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing);
  9284. }
  9285. }
  9286. }
  9287. }
  9288. var gcLen = gc.length / 2;
  9289. if (gcLen > arrayOfThings.length) {
  9290. for (i = 0; i < gcLen; i++) {
  9291. delete data[gc[i]];
  9292. }
  9293. gc.splice(0, gcLen);
  9294. }
  9295. return longest;
  9296. };
  9297. helpers$1.measureText = function(ctx, data, gc, longest, string) {
  9298. var textWidth = data[string];
  9299. if (!textWidth) {
  9300. textWidth = data[string] = ctx.measureText(string).width;
  9301. gc.push(string);
  9302. }
  9303. if (textWidth > longest) {
  9304. longest = textWidth;
  9305. }
  9306. return longest;
  9307. };
  9308. /**
  9309. * @deprecated
  9310. */
  9311. helpers$1.numberOfLabelLines = function(arrayOfThings) {
  9312. var numberOfLines = 1;
  9313. helpers$1.each(arrayOfThings, function(thing) {
  9314. if (helpers$1.isArray(thing)) {
  9315. if (thing.length > numberOfLines) {
  9316. numberOfLines = thing.length;
  9317. }
  9318. }
  9319. });
  9320. return numberOfLines;
  9321. };
  9322. helpers$1.color = !chartjsColor ?
  9323. function(value) {
  9324. console.error('Color.js not found!');
  9325. return value;
  9326. } :
  9327. function(value) {
  9328. /* global CanvasGradient */
  9329. if (value instanceof CanvasGradient) {
  9330. value = core_defaults.global.defaultColor;
  9331. }
  9332. return chartjsColor(value);
  9333. };
  9334. helpers$1.getHoverColor = function(colorValue) {
  9335. /* global CanvasPattern */
  9336. return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
  9337. colorValue :
  9338. helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString();
  9339. };
  9340. };
  9341. function abstract() {
  9342. throw new Error(
  9343. 'This method is not implemented: either no adapter can ' +
  9344. 'be found or an incomplete integration was provided.'
  9345. );
  9346. }
  9347. /**
  9348. * Date adapter (current used by the time scale)
  9349. * @namespace Chart._adapters._date
  9350. * @memberof Chart._adapters
  9351. * @private
  9352. */
  9353. /**
  9354. * Currently supported unit string values.
  9355. * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
  9356. * @memberof Chart._adapters._date
  9357. * @name Unit
  9358. */
  9359. /**
  9360. * @class
  9361. */
  9362. function DateAdapter(options) {
  9363. this.options = options || {};
  9364. }
  9365. helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
  9366. /**
  9367. * Returns a map of time formats for the supported formatting units defined
  9368. * in Unit as well as 'datetime' representing a detailed date/time string.
  9369. * @returns {{string: string}}
  9370. */
  9371. formats: abstract,
  9372. /**
  9373. * Parses the given `value` and return the associated timestamp.
  9374. * @param {any} value - the value to parse (usually comes from the data)
  9375. * @param {string} [format] - the expected data format
  9376. * @returns {(number|null)}
  9377. * @function
  9378. */
  9379. parse: abstract,
  9380. /**
  9381. * Returns the formatted date in the specified `format` for a given `timestamp`.
  9382. * @param {number} timestamp - the timestamp to format
  9383. * @param {string} format - the date/time token
  9384. * @return {string}
  9385. * @function
  9386. */
  9387. format: abstract,
  9388. /**
  9389. * Adds the specified `amount` of `unit` to the given `timestamp`.
  9390. * @param {number} timestamp - the input timestamp
  9391. * @param {number} amount - the amount to add
  9392. * @param {Unit} unit - the unit as string
  9393. * @return {number}
  9394. * @function
  9395. */
  9396. add: abstract,
  9397. /**
  9398. * Returns the number of `unit` between the given timestamps.
  9399. * @param {number} max - the input timestamp (reference)
  9400. * @param {number} min - the timestamp to substract
  9401. * @param {Unit} unit - the unit as string
  9402. * @return {number}
  9403. * @function
  9404. */
  9405. diff: abstract,
  9406. /**
  9407. * Returns start of `unit` for the given `timestamp`.
  9408. * @param {number} timestamp - the input timestamp
  9409. * @param {Unit} unit - the unit as string
  9410. * @param {number} [weekday] - the ISO day of the week with 1 being Monday
  9411. * and 7 being Sunday (only needed if param *unit* is `isoWeek`).
  9412. * @function
  9413. */
  9414. startOf: abstract,
  9415. /**
  9416. * Returns end of `unit` for the given `timestamp`.
  9417. * @param {number} timestamp - the input timestamp
  9418. * @param {Unit} unit - the unit as string
  9419. * @function
  9420. */
  9421. endOf: abstract,
  9422. // DEPRECATIONS
  9423. /**
  9424. * Provided for backward compatibility for scale.getValueForPixel(),
  9425. * this method should be overridden only by the moment adapter.
  9426. * @deprecated since version 2.8.0
  9427. * @todo remove at version 3
  9428. * @private
  9429. */
  9430. _create: function(value) {
  9431. return value;
  9432. }
  9433. });
  9434. DateAdapter.override = function(members) {
  9435. helpers$1.extend(DateAdapter.prototype, members);
  9436. };
  9437. var _date = DateAdapter;
  9438. var core_adapters = {
  9439. _date: _date
  9440. };
  9441. /**
  9442. * Namespace to hold static tick generation functions
  9443. * @namespace Chart.Ticks
  9444. */
  9445. var core_ticks = {
  9446. /**
  9447. * Namespace to hold formatters for different types of ticks
  9448. * @namespace Chart.Ticks.formatters
  9449. */
  9450. formatters: {
  9451. /**
  9452. * Formatter for value labels
  9453. * @method Chart.Ticks.formatters.values
  9454. * @param value the value to display
  9455. * @return {string|string[]} the label to display
  9456. */
  9457. values: function(value) {
  9458. return helpers$1.isArray(value) ? value : '' + value;
  9459. },
  9460. /**
  9461. * Formatter for linear numeric ticks
  9462. * @method Chart.Ticks.formatters.linear
  9463. * @param tickValue {number} the value to be formatted
  9464. * @param index {number} the position of the tickValue parameter in the ticks array
  9465. * @param ticks {number[]} the list of ticks being converted
  9466. * @return {string} string representation of the tickValue parameter
  9467. */
  9468. linear: function(tickValue, index, ticks) {
  9469. // If we have lots of ticks, don't use the ones
  9470. var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
  9471. // If we have a number like 2.5 as the delta, figure out how many decimal places we need
  9472. if (Math.abs(delta) > 1) {
  9473. if (tickValue !== Math.floor(tickValue)) {
  9474. // not an integer
  9475. delta = tickValue - Math.floor(tickValue);
  9476. }
  9477. }
  9478. var logDelta = helpers$1.log10(Math.abs(delta));
  9479. var tickString = '';
  9480. if (tickValue !== 0) {
  9481. var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
  9482. if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
  9483. var logTick = helpers$1.log10(Math.abs(tickValue));
  9484. var numExponential = Math.floor(logTick) - Math.floor(logDelta);
  9485. numExponential = Math.max(Math.min(numExponential, 20), 0);
  9486. tickString = tickValue.toExponential(numExponential);
  9487. } else {
  9488. var numDecimal = -1 * Math.floor(logDelta);
  9489. numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
  9490. tickString = tickValue.toFixed(numDecimal);
  9491. }
  9492. } else {
  9493. tickString = '0'; // never show decimal places for 0
  9494. }
  9495. return tickString;
  9496. },
  9497. logarithmic: function(tickValue, index, ticks) {
  9498. var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue))));
  9499. if (tickValue === 0) {
  9500. return '0';
  9501. } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
  9502. return tickValue.toExponential();
  9503. }
  9504. return '';
  9505. }
  9506. }
  9507. };
  9508. var isArray = helpers$1.isArray;
  9509. var isNullOrUndef = helpers$1.isNullOrUndef;
  9510. var valueOrDefault$a = helpers$1.valueOrDefault;
  9511. var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault;
  9512. core_defaults._set('scale', {
  9513. display: true,
  9514. position: 'left',
  9515. offset: false,
  9516. // grid line settings
  9517. gridLines: {
  9518. display: true,
  9519. color: 'rgba(0,0,0,0.1)',
  9520. lineWidth: 1,
  9521. drawBorder: true,
  9522. drawOnChartArea: true,
  9523. drawTicks: true,
  9524. tickMarkLength: 10,
  9525. zeroLineWidth: 1,
  9526. zeroLineColor: 'rgba(0,0,0,0.25)',
  9527. zeroLineBorderDash: [],
  9528. zeroLineBorderDashOffset: 0.0,
  9529. offsetGridLines: false,
  9530. borderDash: [],
  9531. borderDashOffset: 0.0
  9532. },
  9533. // scale label
  9534. scaleLabel: {
  9535. // display property
  9536. display: false,
  9537. // actual label
  9538. labelString: '',
  9539. // top/bottom padding
  9540. padding: {
  9541. top: 4,
  9542. bottom: 4
  9543. }
  9544. },
  9545. // label settings
  9546. ticks: {
  9547. beginAtZero: false,
  9548. minRotation: 0,
  9549. maxRotation: 50,
  9550. mirror: false,
  9551. padding: 0,
  9552. reverse: false,
  9553. display: true,
  9554. autoSkip: true,
  9555. autoSkipPadding: 0,
  9556. labelOffset: 0,
  9557. // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
  9558. callback: core_ticks.formatters.values,
  9559. minor: {},
  9560. major: {}
  9561. }
  9562. });
  9563. /** Returns a new array containing numItems from arr */
  9564. function sample(arr, numItems) {
  9565. var result = [];
  9566. var increment = arr.length / numItems;
  9567. var i = 0;
  9568. var len = arr.length;
  9569. for (; i < len; i += increment) {
  9570. result.push(arr[Math.floor(i)]);
  9571. }
  9572. return result;
  9573. }
  9574. function getPixelForGridLine(scale, index, offsetGridLines) {
  9575. var length = scale.getTicks().length;
  9576. var validIndex = Math.min(index, length - 1);
  9577. var lineValue = scale.getPixelForTick(validIndex);
  9578. var start = scale._startPixel;
  9579. var end = scale._endPixel;
  9580. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  9581. var offset;
  9582. if (offsetGridLines) {
  9583. if (length === 1) {
  9584. offset = Math.max(lineValue - start, end - lineValue);
  9585. } else if (index === 0) {
  9586. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  9587. } else {
  9588. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  9589. }
  9590. lineValue += validIndex < index ? offset : -offset;
  9591. // Return undefined if the pixel is out of the range
  9592. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  9593. return;
  9594. }
  9595. }
  9596. return lineValue;
  9597. }
  9598. function garbageCollect(caches, length) {
  9599. helpers$1.each(caches, function(cache) {
  9600. var gc = cache.gc;
  9601. var gcLen = gc.length / 2;
  9602. var i;
  9603. if (gcLen > length) {
  9604. for (i = 0; i < gcLen; ++i) {
  9605. delete cache.data[gc[i]];
  9606. }
  9607. gc.splice(0, gcLen);
  9608. }
  9609. });
  9610. }
  9611. /**
  9612. * Returns {width, height, offset} objects for the first, last, widest, highest tick
  9613. * labels where offset indicates the anchor point offset from the top in pixels.
  9614. */
  9615. function computeLabelSizes(ctx, tickFonts, ticks, caches) {
  9616. var length = ticks.length;
  9617. var widths = [];
  9618. var heights = [];
  9619. var offsets = [];
  9620. var widestLabelSize = 0;
  9621. var highestLabelSize = 0;
  9622. var i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel, widest, highest;
  9623. for (i = 0; i < length; ++i) {
  9624. label = ticks[i].label;
  9625. tickFont = ticks[i].major ? tickFonts.major : tickFonts.minor;
  9626. ctx.font = fontString = tickFont.string;
  9627. cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};
  9628. lineHeight = tickFont.lineHeight;
  9629. width = height = 0;
  9630. // Undefined labels and arrays should not be measured
  9631. if (!isNullOrUndef(label) && !isArray(label)) {
  9632. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, label);
  9633. height = lineHeight;
  9634. } else if (isArray(label)) {
  9635. // if it is an array let's measure each element
  9636. for (j = 0, jlen = label.length; j < jlen; ++j) {
  9637. nestedLabel = label[j];
  9638. // Undefined labels and arrays should not be measured
  9639. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  9640. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  9641. height += lineHeight;
  9642. }
  9643. }
  9644. }
  9645. widths.push(width);
  9646. heights.push(height);
  9647. offsets.push(lineHeight / 2);
  9648. widestLabelSize = Math.max(width, widestLabelSize);
  9649. highestLabelSize = Math.max(height, highestLabelSize);
  9650. }
  9651. garbageCollect(caches, length);
  9652. widest = widths.indexOf(widestLabelSize);
  9653. highest = heights.indexOf(highestLabelSize);
  9654. function valueAt(idx) {
  9655. return {
  9656. width: widths[idx] || 0,
  9657. height: heights[idx] || 0,
  9658. offset: offsets[idx] || 0
  9659. };
  9660. }
  9661. return {
  9662. first: valueAt(0),
  9663. last: valueAt(length - 1),
  9664. widest: valueAt(widest),
  9665. highest: valueAt(highest)
  9666. };
  9667. }
  9668. function getTickMarkLength(options) {
  9669. return options.drawTicks ? options.tickMarkLength : 0;
  9670. }
  9671. function getScaleLabelHeight(options) {
  9672. var font, padding;
  9673. if (!options.display) {
  9674. return 0;
  9675. }
  9676. font = helpers$1.options._parseFont(options);
  9677. padding = helpers$1.options.toPadding(options.padding);
  9678. return font.lineHeight + padding.height;
  9679. }
  9680. function parseFontOptions(options, nestedOpts) {
  9681. return helpers$1.extend(helpers$1.options._parseFont({
  9682. fontFamily: valueOrDefault$a(nestedOpts.fontFamily, options.fontFamily),
  9683. fontSize: valueOrDefault$a(nestedOpts.fontSize, options.fontSize),
  9684. fontStyle: valueOrDefault$a(nestedOpts.fontStyle, options.fontStyle),
  9685. lineHeight: valueOrDefault$a(nestedOpts.lineHeight, options.lineHeight)
  9686. }), {
  9687. color: helpers$1.options.resolve([nestedOpts.fontColor, options.fontColor, core_defaults.global.defaultFontColor])
  9688. });
  9689. }
  9690. function parseTickFontOptions(options) {
  9691. var minor = parseFontOptions(options, options.minor);
  9692. var major = options.major.enabled ? parseFontOptions(options, options.major) : minor;
  9693. return {minor: minor, major: major};
  9694. }
  9695. function nonSkipped(ticksToFilter) {
  9696. var filtered = [];
  9697. var item, index, len;
  9698. for (index = 0, len = ticksToFilter.length; index < len; ++index) {
  9699. item = ticksToFilter[index];
  9700. if (typeof item._index !== 'undefined') {
  9701. filtered.push(item);
  9702. }
  9703. }
  9704. return filtered;
  9705. }
  9706. function getEvenSpacing(arr) {
  9707. var len = arr.length;
  9708. var i, diff;
  9709. if (len < 2) {
  9710. return false;
  9711. }
  9712. for (diff = arr[0], i = 1; i < len; ++i) {
  9713. if (arr[i] - arr[i - 1] !== diff) {
  9714. return false;
  9715. }
  9716. }
  9717. return diff;
  9718. }
  9719. function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
  9720. var evenMajorSpacing = getEvenSpacing(majorIndices);
  9721. var spacing = (ticks.length - 1) / ticksLimit;
  9722. var factors, factor, i, ilen;
  9723. // If the major ticks are evenly spaced apart, place the minor ticks
  9724. // so that they divide the major ticks into even chunks
  9725. if (!evenMajorSpacing) {
  9726. return Math.max(spacing, 1);
  9727. }
  9728. factors = helpers$1.math._factorize(evenMajorSpacing);
  9729. for (i = 0, ilen = factors.length - 1; i < ilen; i++) {
  9730. factor = factors[i];
  9731. if (factor > spacing) {
  9732. return factor;
  9733. }
  9734. }
  9735. return Math.max(spacing, 1);
  9736. }
  9737. function getMajorIndices(ticks) {
  9738. var result = [];
  9739. var i, ilen;
  9740. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  9741. if (ticks[i].major) {
  9742. result.push(i);
  9743. }
  9744. }
  9745. return result;
  9746. }
  9747. function skipMajors(ticks, majorIndices, spacing) {
  9748. var count = 0;
  9749. var next = majorIndices[0];
  9750. var i, tick;
  9751. spacing = Math.ceil(spacing);
  9752. for (i = 0; i < ticks.length; i++) {
  9753. tick = ticks[i];
  9754. if (i === next) {
  9755. tick._index = i;
  9756. count++;
  9757. next = majorIndices[count * spacing];
  9758. } else {
  9759. delete tick.label;
  9760. }
  9761. }
  9762. }
  9763. function skip(ticks, spacing, majorStart, majorEnd) {
  9764. var start = valueOrDefault$a(majorStart, 0);
  9765. var end = Math.min(valueOrDefault$a(majorEnd, ticks.length), ticks.length);
  9766. var count = 0;
  9767. var length, i, tick, next;
  9768. spacing = Math.ceil(spacing);
  9769. if (majorEnd) {
  9770. length = majorEnd - majorStart;
  9771. spacing = length / Math.floor(length / spacing);
  9772. }
  9773. next = start;
  9774. while (next < 0) {
  9775. count++;
  9776. next = Math.round(start + count * spacing);
  9777. }
  9778. for (i = Math.max(start, 0); i < end; i++) {
  9779. tick = ticks[i];
  9780. if (i === next) {
  9781. tick._index = i;
  9782. count++;
  9783. next = Math.round(start + count * spacing);
  9784. } else {
  9785. delete tick.label;
  9786. }
  9787. }
  9788. }
  9789. var Scale = core_element.extend({
  9790. zeroLineIndex: 0,
  9791. /**
  9792. * Get the padding needed for the scale
  9793. * @method getPadding
  9794. * @private
  9795. * @returns {Padding} the necessary padding
  9796. */
  9797. getPadding: function() {
  9798. var me = this;
  9799. return {
  9800. left: me.paddingLeft || 0,
  9801. top: me.paddingTop || 0,
  9802. right: me.paddingRight || 0,
  9803. bottom: me.paddingBottom || 0
  9804. };
  9805. },
  9806. /**
  9807. * Returns the scale tick objects ({label, major})
  9808. * @since 2.7
  9809. */
  9810. getTicks: function() {
  9811. return this._ticks;
  9812. },
  9813. /**
  9814. * @private
  9815. */
  9816. _getLabels: function() {
  9817. var data = this.chart.data;
  9818. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  9819. },
  9820. // These methods are ordered by lifecyle. Utilities then follow.
  9821. // Any function defined here is inherited by all scale types.
  9822. // Any function can be extended by the scale type
  9823. /**
  9824. * Provided for backward compatibility, not available anymore
  9825. * @function Chart.Scale.mergeTicksOptions
  9826. * @deprecated since version 2.8.0
  9827. * @todo remove at version 3
  9828. */
  9829. mergeTicksOptions: function() {
  9830. // noop
  9831. },
  9832. beforeUpdate: function() {
  9833. helpers$1.callback(this.options.beforeUpdate, [this]);
  9834. },
  9835. /**
  9836. * @param {number} maxWidth - the max width in pixels
  9837. * @param {number} maxHeight - the max height in pixels
  9838. * @param {object} margins - the space between the edge of the other scales and edge of the chart
  9839. * This space comes from two sources:
  9840. * - padding - space that's required to show the labels at the edges of the scale
  9841. * - thickness of scales or legends in another orientation
  9842. */
  9843. update: function(maxWidth, maxHeight, margins) {
  9844. var me = this;
  9845. var tickOpts = me.options.ticks;
  9846. var sampleSize = tickOpts.sampleSize;
  9847. var i, ilen, labels, ticks, samplingEnabled;
  9848. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  9849. me.beforeUpdate();
  9850. // Absorb the master measurements
  9851. me.maxWidth = maxWidth;
  9852. me.maxHeight = maxHeight;
  9853. me.margins = helpers$1.extend({
  9854. left: 0,
  9855. right: 0,
  9856. top: 0,
  9857. bottom: 0
  9858. }, margins);
  9859. me._ticks = null;
  9860. me.ticks = null;
  9861. me._labelSizes = null;
  9862. me._maxLabelLines = 0;
  9863. me.longestLabelWidth = 0;
  9864. me.longestTextCache = me.longestTextCache || {};
  9865. me._gridLineItems = null;
  9866. me._labelItems = null;
  9867. // Dimensions
  9868. me.beforeSetDimensions();
  9869. me.setDimensions();
  9870. me.afterSetDimensions();
  9871. // Data min/max
  9872. me.beforeDataLimits();
  9873. me.determineDataLimits();
  9874. me.afterDataLimits();
  9875. // Ticks - `this.ticks` is now DEPRECATED!
  9876. // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
  9877. // and must not be accessed directly from outside this class. `this.ticks` being
  9878. // around for long time and not marked as private, we can't change its structure
  9879. // without unexpected breaking changes. If you need to access the scale ticks,
  9880. // use scale.getTicks() instead.
  9881. me.beforeBuildTicks();
  9882. // New implementations should return an array of objects but for BACKWARD COMPAT,
  9883. // we still support no return (`this.ticks` internally set by calling this method).
  9884. ticks = me.buildTicks() || [];
  9885. // Allow modification of ticks in callback.
  9886. ticks = me.afterBuildTicks(ticks) || ticks;
  9887. // Ensure ticks contains ticks in new tick format
  9888. if ((!ticks || !ticks.length) && me.ticks) {
  9889. ticks = [];
  9890. for (i = 0, ilen = me.ticks.length; i < ilen; ++i) {
  9891. ticks.push({
  9892. value: me.ticks[i],
  9893. major: false
  9894. });
  9895. }
  9896. }
  9897. me._ticks = ticks;
  9898. // Compute tick rotation and fit using a sampled subset of labels
  9899. // We generally don't need to compute the size of every single label for determining scale size
  9900. samplingEnabled = sampleSize < ticks.length;
  9901. labels = me._convertTicksToLabels(samplingEnabled ? sample(ticks, sampleSize) : ticks);
  9902. // _configure is called twice, once here, once from core.controller.updateLayout.
  9903. // Here we haven't been positioned yet, but dimensions are correct.
  9904. // Variables set in _configure are needed for calculateTickRotation, and
  9905. // it's ok that coordinates are not correct there, only dimensions matter.
  9906. me._configure();
  9907. // Tick Rotation
  9908. me.beforeCalculateTickRotation();
  9909. me.calculateTickRotation();
  9910. me.afterCalculateTickRotation();
  9911. me.beforeFit();
  9912. me.fit();
  9913. me.afterFit();
  9914. // Auto-skip
  9915. me._ticksToDraw = tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto') ? me._autoSkip(ticks) : ticks;
  9916. if (samplingEnabled) {
  9917. // Generate labels using all non-skipped ticks
  9918. labels = me._convertTicksToLabels(me._ticksToDraw);
  9919. }
  9920. me.ticks = labels; // BACKWARD COMPATIBILITY
  9921. // IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!
  9922. me.afterUpdate();
  9923. // TODO(v3): remove minSize as a public property and return value from all layout boxes. It is unused
  9924. // make maxWidth and maxHeight private
  9925. return me.minSize;
  9926. },
  9927. /**
  9928. * @private
  9929. */
  9930. _configure: function() {
  9931. var me = this;
  9932. var reversePixels = me.options.ticks.reverse;
  9933. var startPixel, endPixel;
  9934. if (me.isHorizontal()) {
  9935. startPixel = me.left;
  9936. endPixel = me.right;
  9937. } else {
  9938. startPixel = me.top;
  9939. endPixel = me.bottom;
  9940. // by default vertical scales are from bottom to top, so pixels are reversed
  9941. reversePixels = !reversePixels;
  9942. }
  9943. me._startPixel = startPixel;
  9944. me._endPixel = endPixel;
  9945. me._reversePixels = reversePixels;
  9946. me._length = endPixel - startPixel;
  9947. },
  9948. afterUpdate: function() {
  9949. helpers$1.callback(this.options.afterUpdate, [this]);
  9950. },
  9951. //
  9952. beforeSetDimensions: function() {
  9953. helpers$1.callback(this.options.beforeSetDimensions, [this]);
  9954. },
  9955. setDimensions: function() {
  9956. var me = this;
  9957. // Set the unconstrained dimension before label rotation
  9958. if (me.isHorizontal()) {
  9959. // Reset position before calculating rotation
  9960. me.width = me.maxWidth;
  9961. me.left = 0;
  9962. me.right = me.width;
  9963. } else {
  9964. me.height = me.maxHeight;
  9965. // Reset position before calculating rotation
  9966. me.top = 0;
  9967. me.bottom = me.height;
  9968. }
  9969. // Reset padding
  9970. me.paddingLeft = 0;
  9971. me.paddingTop = 0;
  9972. me.paddingRight = 0;
  9973. me.paddingBottom = 0;
  9974. },
  9975. afterSetDimensions: function() {
  9976. helpers$1.callback(this.options.afterSetDimensions, [this]);
  9977. },
  9978. // Data limits
  9979. beforeDataLimits: function() {
  9980. helpers$1.callback(this.options.beforeDataLimits, [this]);
  9981. },
  9982. determineDataLimits: helpers$1.noop,
  9983. afterDataLimits: function() {
  9984. helpers$1.callback(this.options.afterDataLimits, [this]);
  9985. },
  9986. //
  9987. beforeBuildTicks: function() {
  9988. helpers$1.callback(this.options.beforeBuildTicks, [this]);
  9989. },
  9990. buildTicks: helpers$1.noop,
  9991. afterBuildTicks: function(ticks) {
  9992. var me = this;
  9993. // ticks is empty for old axis implementations here
  9994. if (isArray(ticks) && ticks.length) {
  9995. return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]);
  9996. }
  9997. // Support old implementations (that modified `this.ticks` directly in buildTicks)
  9998. me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;
  9999. return ticks;
  10000. },
  10001. beforeTickToLabelConversion: function() {
  10002. helpers$1.callback(this.options.beforeTickToLabelConversion, [this]);
  10003. },
  10004. convertTicksToLabels: function() {
  10005. var me = this;
  10006. // Convert ticks to strings
  10007. var tickOpts = me.options.ticks;
  10008. me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
  10009. },
  10010. afterTickToLabelConversion: function() {
  10011. helpers$1.callback(this.options.afterTickToLabelConversion, [this]);
  10012. },
  10013. //
  10014. beforeCalculateTickRotation: function() {
  10015. helpers$1.callback(this.options.beforeCalculateTickRotation, [this]);
  10016. },
  10017. calculateTickRotation: function() {
  10018. var me = this;
  10019. var options = me.options;
  10020. var tickOpts = options.ticks;
  10021. var numTicks = me.getTicks().length;
  10022. var minRotation = tickOpts.minRotation || 0;
  10023. var maxRotation = tickOpts.maxRotation;
  10024. var labelRotation = minRotation;
  10025. var labelSizes, maxLabelWidth, maxLabelHeight, maxWidth, tickWidth, maxHeight, maxLabelDiagonal;
  10026. if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
  10027. me.labelRotation = minRotation;
  10028. return;
  10029. }
  10030. labelSizes = me._getLabelSizes();
  10031. maxLabelWidth = labelSizes.widest.width;
  10032. maxLabelHeight = labelSizes.highest.height - labelSizes.highest.offset;
  10033. // Estimate the width of each grid based on the canvas width, the maximum
  10034. // label width and the number of tick intervals
  10035. maxWidth = Math.min(me.maxWidth, me.chart.width - maxLabelWidth);
  10036. tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);
  10037. // Allow 3 pixels x2 padding either side for label readability
  10038. if (maxLabelWidth + 6 > tickWidth) {
  10039. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  10040. maxHeight = me.maxHeight - getTickMarkLength(options.gridLines)
  10041. - tickOpts.padding - getScaleLabelHeight(options.scaleLabel);
  10042. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  10043. labelRotation = helpers$1.toDegrees(Math.min(
  10044. Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
  10045. Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
  10046. ));
  10047. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  10048. }
  10049. me.labelRotation = labelRotation;
  10050. },
  10051. afterCalculateTickRotation: function() {
  10052. helpers$1.callback(this.options.afterCalculateTickRotation, [this]);
  10053. },
  10054. //
  10055. beforeFit: function() {
  10056. helpers$1.callback(this.options.beforeFit, [this]);
  10057. },
  10058. fit: function() {
  10059. var me = this;
  10060. // Reset
  10061. var minSize = me.minSize = {
  10062. width: 0,
  10063. height: 0
  10064. };
  10065. var chart = me.chart;
  10066. var opts = me.options;
  10067. var tickOpts = opts.ticks;
  10068. var scaleLabelOpts = opts.scaleLabel;
  10069. var gridLineOpts = opts.gridLines;
  10070. var display = me._isVisible();
  10071. var isBottom = opts.position === 'bottom';
  10072. var isHorizontal = me.isHorizontal();
  10073. // Width
  10074. if (isHorizontal) {
  10075. minSize.width = me.maxWidth;
  10076. } else if (display) {
  10077. minSize.width = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  10078. }
  10079. // height
  10080. if (!isHorizontal) {
  10081. minSize.height = me.maxHeight; // fill all the height
  10082. } else if (display) {
  10083. minSize.height = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  10084. }
  10085. // Don't bother fitting the ticks if we are not showing the labels
  10086. if (tickOpts.display && display) {
  10087. var tickFonts = parseTickFontOptions(tickOpts);
  10088. var labelSizes = me._getLabelSizes();
  10089. var firstLabelSize = labelSizes.first;
  10090. var lastLabelSize = labelSizes.last;
  10091. var widestLabelSize = labelSizes.widest;
  10092. var highestLabelSize = labelSizes.highest;
  10093. var lineSpace = tickFonts.minor.lineHeight * 0.4;
  10094. var tickPadding = tickOpts.padding;
  10095. if (isHorizontal) {
  10096. // A horizontal axis is more constrained by the height.
  10097. var isRotated = me.labelRotation !== 0;
  10098. var angleRadians = helpers$1.toRadians(me.labelRotation);
  10099. var cosRotation = Math.cos(angleRadians);
  10100. var sinRotation = Math.sin(angleRadians);
  10101. var labelHeight = sinRotation * widestLabelSize.width
  10102. + cosRotation * (highestLabelSize.height - (isRotated ? highestLabelSize.offset : 0))
  10103. + (isRotated ? 0 : lineSpace); // padding
  10104. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  10105. var offsetLeft = me.getPixelForTick(0) - me.left;
  10106. var offsetRight = me.right - me.getPixelForTick(me.getTicks().length - 1);
  10107. var paddingLeft, paddingRight;
  10108. // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
  10109. // which means that the right padding is dominated by the font height
  10110. if (isRotated) {
  10111. paddingLeft = isBottom ?
  10112. cosRotation * firstLabelSize.width + sinRotation * firstLabelSize.offset :
  10113. sinRotation * (firstLabelSize.height - firstLabelSize.offset);
  10114. paddingRight = isBottom ?
  10115. sinRotation * (lastLabelSize.height - lastLabelSize.offset) :
  10116. cosRotation * lastLabelSize.width + sinRotation * lastLabelSize.offset;
  10117. } else {
  10118. paddingLeft = firstLabelSize.width / 2;
  10119. paddingRight = lastLabelSize.width / 2;
  10120. }
  10121. // Adjust padding taking into account changes in offsets
  10122. // and add 3 px to move away from canvas edges
  10123. me.paddingLeft = Math.max((paddingLeft - offsetLeft) * me.width / (me.width - offsetLeft), 0) + 3;
  10124. me.paddingRight = Math.max((paddingRight - offsetRight) * me.width / (me.width - offsetRight), 0) + 3;
  10125. } else {
  10126. // A vertical axis is more constrained by the width. Labels are the
  10127. // dominant factor here, so get that length first and account for padding
  10128. var labelWidth = tickOpts.mirror ? 0 :
  10129. // use lineSpace for consistency with horizontal axis
  10130. // tickPadding is not implemented for horizontal
  10131. widestLabelSize.width + tickPadding + lineSpace;
  10132. minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth);
  10133. me.paddingTop = firstLabelSize.height / 2;
  10134. me.paddingBottom = lastLabelSize.height / 2;
  10135. }
  10136. }
  10137. me.handleMargins();
  10138. if (isHorizontal) {
  10139. me.width = me._length = chart.width - me.margins.left - me.margins.right;
  10140. me.height = minSize.height;
  10141. } else {
  10142. me.width = minSize.width;
  10143. me.height = me._length = chart.height - me.margins.top - me.margins.bottom;
  10144. }
  10145. },
  10146. /**
  10147. * Handle margins and padding interactions
  10148. * @private
  10149. */
  10150. handleMargins: function() {
  10151. var me = this;
  10152. if (me.margins) {
  10153. me.margins.left = Math.max(me.paddingLeft, me.margins.left);
  10154. me.margins.top = Math.max(me.paddingTop, me.margins.top);
  10155. me.margins.right = Math.max(me.paddingRight, me.margins.right);
  10156. me.margins.bottom = Math.max(me.paddingBottom, me.margins.bottom);
  10157. }
  10158. },
  10159. afterFit: function() {
  10160. helpers$1.callback(this.options.afterFit, [this]);
  10161. },
  10162. // Shared Methods
  10163. isHorizontal: function() {
  10164. var pos = this.options.position;
  10165. return pos === 'top' || pos === 'bottom';
  10166. },
  10167. isFullWidth: function() {
  10168. return this.options.fullWidth;
  10169. },
  10170. // 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
  10171. getRightValue: function(rawValue) {
  10172. // Null and undefined values first
  10173. if (isNullOrUndef(rawValue)) {
  10174. return NaN;
  10175. }
  10176. // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
  10177. if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {
  10178. return NaN;
  10179. }
  10180. // If it is in fact an object, dive in one more level
  10181. if (rawValue) {
  10182. if (this.isHorizontal()) {
  10183. if (rawValue.x !== undefined) {
  10184. return this.getRightValue(rawValue.x);
  10185. }
  10186. } else if (rawValue.y !== undefined) {
  10187. return this.getRightValue(rawValue.y);
  10188. }
  10189. }
  10190. // Value is good, return it
  10191. return rawValue;
  10192. },
  10193. _convertTicksToLabels: function(ticks) {
  10194. var me = this;
  10195. var labels, i, ilen;
  10196. me.ticks = ticks.map(function(tick) {
  10197. return tick.value;
  10198. });
  10199. me.beforeTickToLabelConversion();
  10200. // New implementations should return the formatted tick labels but for BACKWARD
  10201. // COMPAT, we still support no return (`this.ticks` internally changed by calling
  10202. // this method and supposed to contain only string values).
  10203. labels = me.convertTicksToLabels(ticks) || me.ticks;
  10204. me.afterTickToLabelConversion();
  10205. // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
  10206. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10207. ticks[i].label = labels[i];
  10208. }
  10209. return labels;
  10210. },
  10211. /**
  10212. * @private
  10213. */
  10214. _getLabelSizes: function() {
  10215. var me = this;
  10216. var labelSizes = me._labelSizes;
  10217. if (!labelSizes) {
  10218. me._labelSizes = labelSizes = computeLabelSizes(me.ctx, parseTickFontOptions(me.options.ticks), me.getTicks(), me.longestTextCache);
  10219. me.longestLabelWidth = labelSizes.widest.width;
  10220. }
  10221. return labelSizes;
  10222. },
  10223. /**
  10224. * @private
  10225. */
  10226. _parseValue: function(value) {
  10227. var start, end, min, max;
  10228. if (isArray(value)) {
  10229. start = +this.getRightValue(value[0]);
  10230. end = +this.getRightValue(value[1]);
  10231. min = Math.min(start, end);
  10232. max = Math.max(start, end);
  10233. } else {
  10234. value = +this.getRightValue(value);
  10235. start = undefined;
  10236. end = value;
  10237. min = value;
  10238. max = value;
  10239. }
  10240. return {
  10241. min: min,
  10242. max: max,
  10243. start: start,
  10244. end: end
  10245. };
  10246. },
  10247. /**
  10248. * @private
  10249. */
  10250. _getScaleLabel: function(rawValue) {
  10251. var v = this._parseValue(rawValue);
  10252. if (v.start !== undefined) {
  10253. return '[' + v.start + ', ' + v.end + ']';
  10254. }
  10255. return +this.getRightValue(rawValue);
  10256. },
  10257. /**
  10258. * Used to get the value to display in the tooltip for the data at the given index
  10259. * @param index
  10260. * @param datasetIndex
  10261. */
  10262. getLabelForIndex: helpers$1.noop,
  10263. /**
  10264. * Returns the location of the given data point. Value can either be an index or a numerical value
  10265. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10266. * @param value
  10267. * @param index
  10268. * @param datasetIndex
  10269. */
  10270. getPixelForValue: helpers$1.noop,
  10271. /**
  10272. * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
  10273. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10274. * @param pixel
  10275. */
  10276. getValueForPixel: helpers$1.noop,
  10277. /**
  10278. * Returns the location of the tick at the given index
  10279. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10280. */
  10281. getPixelForTick: function(index) {
  10282. var me = this;
  10283. var offset = me.options.offset;
  10284. var numTicks = me._ticks.length;
  10285. var tickWidth = 1 / Math.max(numTicks - (offset ? 0 : 1), 1);
  10286. return index < 0 || index > numTicks - 1
  10287. ? null
  10288. : me.getPixelForDecimal(index * tickWidth + (offset ? tickWidth / 2 : 0));
  10289. },
  10290. /**
  10291. * Utility for getting the pixel location of a percentage of scale
  10292. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10293. */
  10294. getPixelForDecimal: function(decimal) {
  10295. var me = this;
  10296. if (me._reversePixels) {
  10297. decimal = 1 - decimal;
  10298. }
  10299. return me._startPixel + decimal * me._length;
  10300. },
  10301. getDecimalForPixel: function(pixel) {
  10302. var decimal = (pixel - this._startPixel) / this._length;
  10303. return this._reversePixels ? 1 - decimal : decimal;
  10304. },
  10305. /**
  10306. * Returns the pixel for the minimum chart value
  10307. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10308. */
  10309. getBasePixel: function() {
  10310. return this.getPixelForValue(this.getBaseValue());
  10311. },
  10312. getBaseValue: function() {
  10313. var me = this;
  10314. var min = me.min;
  10315. var max = me.max;
  10316. return me.beginAtZero ? 0 :
  10317. min < 0 && max < 0 ? max :
  10318. min > 0 && max > 0 ? min :
  10319. 0;
  10320. },
  10321. /**
  10322. * Returns a subset of ticks to be plotted to avoid overlapping labels.
  10323. * @private
  10324. */
  10325. _autoSkip: function(ticks) {
  10326. var me = this;
  10327. var tickOpts = me.options.ticks;
  10328. var axisLength = me._length;
  10329. var ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize() + 1;
  10330. var majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  10331. var numMajorIndices = majorIndices.length;
  10332. var first = majorIndices[0];
  10333. var last = majorIndices[numMajorIndices - 1];
  10334. var i, ilen, spacing, avgMajorSpacing;
  10335. // If there are too many major ticks to display them all
  10336. if (numMajorIndices > ticksLimit) {
  10337. skipMajors(ticks, majorIndices, numMajorIndices / ticksLimit);
  10338. return nonSkipped(ticks);
  10339. }
  10340. spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit);
  10341. if (numMajorIndices > 0) {
  10342. for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
  10343. skip(ticks, spacing, majorIndices[i], majorIndices[i + 1]);
  10344. }
  10345. avgMajorSpacing = numMajorIndices > 1 ? (last - first) / (numMajorIndices - 1) : null;
  10346. skip(ticks, spacing, helpers$1.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  10347. skip(ticks, spacing, last, helpers$1.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  10348. return nonSkipped(ticks);
  10349. }
  10350. skip(ticks, spacing);
  10351. return nonSkipped(ticks);
  10352. },
  10353. /**
  10354. * @private
  10355. */
  10356. _tickSize: function() {
  10357. var me = this;
  10358. var optionTicks = me.options.ticks;
  10359. // Calculate space needed by label in axis direction.
  10360. var rot = helpers$1.toRadians(me.labelRotation);
  10361. var cos = Math.abs(Math.cos(rot));
  10362. var sin = Math.abs(Math.sin(rot));
  10363. var labelSizes = me._getLabelSizes();
  10364. var padding = optionTicks.autoSkipPadding || 0;
  10365. var w = labelSizes ? labelSizes.widest.width + padding : 0;
  10366. var h = labelSizes ? labelSizes.highest.height + padding : 0;
  10367. // Calculate space needed for 1 tick in axis direction.
  10368. return me.isHorizontal()
  10369. ? h * cos > w * sin ? w / cos : h / sin
  10370. : h * sin < w * cos ? h / cos : w / sin;
  10371. },
  10372. /**
  10373. * @private
  10374. */
  10375. _isVisible: function() {
  10376. var me = this;
  10377. var chart = me.chart;
  10378. var display = me.options.display;
  10379. var i, ilen, meta;
  10380. if (display !== 'auto') {
  10381. return !!display;
  10382. }
  10383. // When 'auto', the scale is visible if at least one associated dataset is visible.
  10384. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  10385. if (chart.isDatasetVisible(i)) {
  10386. meta = chart.getDatasetMeta(i);
  10387. if (meta.xAxisID === me.id || meta.yAxisID === me.id) {
  10388. return true;
  10389. }
  10390. }
  10391. }
  10392. return false;
  10393. },
  10394. /**
  10395. * @private
  10396. */
  10397. _computeGridLineItems: function(chartArea) {
  10398. var me = this;
  10399. var chart = me.chart;
  10400. var options = me.options;
  10401. var gridLines = options.gridLines;
  10402. var position = options.position;
  10403. var offsetGridLines = gridLines.offsetGridLines;
  10404. var isHorizontal = me.isHorizontal();
  10405. var ticks = me._ticksToDraw;
  10406. var ticksLength = ticks.length + (offsetGridLines ? 1 : 0);
  10407. var tl = getTickMarkLength(gridLines);
  10408. var items = [];
  10409. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  10410. var axisHalfWidth = axisWidth / 2;
  10411. var alignPixel = helpers$1._alignPixel;
  10412. var alignBorderValue = function(pixel) {
  10413. return alignPixel(chart, pixel, axisWidth);
  10414. };
  10415. var borderValue, i, tick, lineValue, alignedLineValue;
  10416. var tx1, ty1, tx2, ty2, x1, y1, x2, y2, lineWidth, lineColor, borderDash, borderDashOffset;
  10417. if (position === 'top') {
  10418. borderValue = alignBorderValue(me.bottom);
  10419. ty1 = me.bottom - tl;
  10420. ty2 = borderValue - axisHalfWidth;
  10421. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  10422. y2 = chartArea.bottom;
  10423. } else if (position === 'bottom') {
  10424. borderValue = alignBorderValue(me.top);
  10425. y1 = chartArea.top;
  10426. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  10427. ty1 = borderValue + axisHalfWidth;
  10428. ty2 = me.top + tl;
  10429. } else if (position === 'left') {
  10430. borderValue = alignBorderValue(me.right);
  10431. tx1 = me.right - tl;
  10432. tx2 = borderValue - axisHalfWidth;
  10433. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  10434. x2 = chartArea.right;
  10435. } else {
  10436. borderValue = alignBorderValue(me.left);
  10437. x1 = chartArea.left;
  10438. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  10439. tx1 = borderValue + axisHalfWidth;
  10440. tx2 = me.left + tl;
  10441. }
  10442. for (i = 0; i < ticksLength; ++i) {
  10443. tick = ticks[i] || {};
  10444. // autoskipper skipped this tick (#4635)
  10445. if (isNullOrUndef(tick.label) && i < ticks.length) {
  10446. continue;
  10447. }
  10448. if (i === me.zeroLineIndex && options.offset === offsetGridLines) {
  10449. // Draw the first index specially
  10450. lineWidth = gridLines.zeroLineWidth;
  10451. lineColor = gridLines.zeroLineColor;
  10452. borderDash = gridLines.zeroLineBorderDash || [];
  10453. borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0;
  10454. } else {
  10455. lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, i, 1);
  10456. lineColor = valueAtIndexOrDefault(gridLines.color, i, 'rgba(0,0,0,0.1)');
  10457. borderDash = gridLines.borderDash || [];
  10458. borderDashOffset = gridLines.borderDashOffset || 0.0;
  10459. }
  10460. lineValue = getPixelForGridLine(me, tick._index || i, offsetGridLines);
  10461. // Skip if the pixel is out of the range
  10462. if (lineValue === undefined) {
  10463. continue;
  10464. }
  10465. alignedLineValue = alignPixel(chart, lineValue, lineWidth);
  10466. if (isHorizontal) {
  10467. tx1 = tx2 = x1 = x2 = alignedLineValue;
  10468. } else {
  10469. ty1 = ty2 = y1 = y2 = alignedLineValue;
  10470. }
  10471. items.push({
  10472. tx1: tx1,
  10473. ty1: ty1,
  10474. tx2: tx2,
  10475. ty2: ty2,
  10476. x1: x1,
  10477. y1: y1,
  10478. x2: x2,
  10479. y2: y2,
  10480. width: lineWidth,
  10481. color: lineColor,
  10482. borderDash: borderDash,
  10483. borderDashOffset: borderDashOffset,
  10484. });
  10485. }
  10486. items.ticksLength = ticksLength;
  10487. items.borderValue = borderValue;
  10488. return items;
  10489. },
  10490. /**
  10491. * @private
  10492. */
  10493. _computeLabelItems: function() {
  10494. var me = this;
  10495. var options = me.options;
  10496. var optionTicks = options.ticks;
  10497. var position = options.position;
  10498. var isMirrored = optionTicks.mirror;
  10499. var isHorizontal = me.isHorizontal();
  10500. var ticks = me._ticksToDraw;
  10501. var fonts = parseTickFontOptions(optionTicks);
  10502. var tickPadding = optionTicks.padding;
  10503. var tl = getTickMarkLength(options.gridLines);
  10504. var rotation = -helpers$1.toRadians(me.labelRotation);
  10505. var items = [];
  10506. var i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  10507. if (position === 'top') {
  10508. y = me.bottom - tl - tickPadding;
  10509. textAlign = !rotation ? 'center' : 'left';
  10510. } else if (position === 'bottom') {
  10511. y = me.top + tl + tickPadding;
  10512. textAlign = !rotation ? 'center' : 'right';
  10513. } else if (position === 'left') {
  10514. x = me.right - (isMirrored ? 0 : tl) - tickPadding;
  10515. textAlign = isMirrored ? 'left' : 'right';
  10516. } else {
  10517. x = me.left + (isMirrored ? 0 : tl) + tickPadding;
  10518. textAlign = isMirrored ? 'right' : 'left';
  10519. }
  10520. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10521. tick = ticks[i];
  10522. label = tick.label;
  10523. // autoskipper skipped this tick (#4635)
  10524. if (isNullOrUndef(label)) {
  10525. continue;
  10526. }
  10527. pixel = me.getPixelForTick(tick._index || i) + optionTicks.labelOffset;
  10528. font = tick.major ? fonts.major : fonts.minor;
  10529. lineHeight = font.lineHeight;
  10530. lineCount = isArray(label) ? label.length : 1;
  10531. if (isHorizontal) {
  10532. x = pixel;
  10533. textOffset = position === 'top'
  10534. ? ((!rotation ? 0.5 : 1) - lineCount) * lineHeight
  10535. : (!rotation ? 0.5 : 0) * lineHeight;
  10536. } else {
  10537. y = pixel;
  10538. textOffset = (1 - lineCount) * lineHeight / 2;
  10539. }
  10540. items.push({
  10541. x: x,
  10542. y: y,
  10543. rotation: rotation,
  10544. label: label,
  10545. font: font,
  10546. textOffset: textOffset,
  10547. textAlign: textAlign
  10548. });
  10549. }
  10550. return items;
  10551. },
  10552. /**
  10553. * @private
  10554. */
  10555. _drawGrid: function(chartArea) {
  10556. var me = this;
  10557. var gridLines = me.options.gridLines;
  10558. if (!gridLines.display) {
  10559. return;
  10560. }
  10561. var ctx = me.ctx;
  10562. var chart = me.chart;
  10563. var alignPixel = helpers$1._alignPixel;
  10564. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  10565. var items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
  10566. var width, color, i, ilen, item;
  10567. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10568. item = items[i];
  10569. width = item.width;
  10570. color = item.color;
  10571. if (width && color) {
  10572. ctx.save();
  10573. ctx.lineWidth = width;
  10574. ctx.strokeStyle = color;
  10575. if (ctx.setLineDash) {
  10576. ctx.setLineDash(item.borderDash);
  10577. ctx.lineDashOffset = item.borderDashOffset;
  10578. }
  10579. ctx.beginPath();
  10580. if (gridLines.drawTicks) {
  10581. ctx.moveTo(item.tx1, item.ty1);
  10582. ctx.lineTo(item.tx2, item.ty2);
  10583. }
  10584. if (gridLines.drawOnChartArea) {
  10585. ctx.moveTo(item.x1, item.y1);
  10586. ctx.lineTo(item.x2, item.y2);
  10587. }
  10588. ctx.stroke();
  10589. ctx.restore();
  10590. }
  10591. }
  10592. if (axisWidth) {
  10593. // Draw the line at the edge of the axis
  10594. var firstLineWidth = axisWidth;
  10595. var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, items.ticksLength - 1, 1);
  10596. var borderValue = items.borderValue;
  10597. var x1, x2, y1, y2;
  10598. if (me.isHorizontal()) {
  10599. x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
  10600. x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  10601. y1 = y2 = borderValue;
  10602. } else {
  10603. y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
  10604. y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  10605. x1 = x2 = borderValue;
  10606. }
  10607. ctx.lineWidth = axisWidth;
  10608. ctx.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0);
  10609. ctx.beginPath();
  10610. ctx.moveTo(x1, y1);
  10611. ctx.lineTo(x2, y2);
  10612. ctx.stroke();
  10613. }
  10614. },
  10615. /**
  10616. * @private
  10617. */
  10618. _drawLabels: function() {
  10619. var me = this;
  10620. var optionTicks = me.options.ticks;
  10621. if (!optionTicks.display) {
  10622. return;
  10623. }
  10624. var ctx = me.ctx;
  10625. var items = me._labelItems || (me._labelItems = me._computeLabelItems());
  10626. var i, j, ilen, jlen, item, tickFont, label, y;
  10627. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10628. item = items[i];
  10629. tickFont = item.font;
  10630. // Make sure we draw text in the correct color and font
  10631. ctx.save();
  10632. ctx.translate(item.x, item.y);
  10633. ctx.rotate(item.rotation);
  10634. ctx.font = tickFont.string;
  10635. ctx.fillStyle = tickFont.color;
  10636. ctx.textBaseline = 'middle';
  10637. ctx.textAlign = item.textAlign;
  10638. label = item.label;
  10639. y = item.textOffset;
  10640. if (isArray(label)) {
  10641. for (j = 0, jlen = label.length; j < jlen; ++j) {
  10642. // We just make sure the multiline element is a string here..
  10643. ctx.fillText('' + label[j], 0, y);
  10644. y += tickFont.lineHeight;
  10645. }
  10646. } else {
  10647. ctx.fillText(label, 0, y);
  10648. }
  10649. ctx.restore();
  10650. }
  10651. },
  10652. /**
  10653. * @private
  10654. */
  10655. _drawTitle: function() {
  10656. var me = this;
  10657. var ctx = me.ctx;
  10658. var options = me.options;
  10659. var scaleLabel = options.scaleLabel;
  10660. if (!scaleLabel.display) {
  10661. return;
  10662. }
  10663. var scaleLabelFontColor = valueOrDefault$a(scaleLabel.fontColor, core_defaults.global.defaultFontColor);
  10664. var scaleLabelFont = helpers$1.options._parseFont(scaleLabel);
  10665. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding);
  10666. var halfLineHeight = scaleLabelFont.lineHeight / 2;
  10667. var position = options.position;
  10668. var rotation = 0;
  10669. var scaleLabelX, scaleLabelY;
  10670. if (me.isHorizontal()) {
  10671. scaleLabelX = me.left + me.width / 2; // midpoint of the width
  10672. scaleLabelY = position === 'bottom'
  10673. ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
  10674. : me.top + halfLineHeight + scaleLabelPadding.top;
  10675. } else {
  10676. var isLeft = position === 'left';
  10677. scaleLabelX = isLeft
  10678. ? me.left + halfLineHeight + scaleLabelPadding.top
  10679. : me.right - halfLineHeight - scaleLabelPadding.top;
  10680. scaleLabelY = me.top + me.height / 2;
  10681. rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
  10682. }
  10683. ctx.save();
  10684. ctx.translate(scaleLabelX, scaleLabelY);
  10685. ctx.rotate(rotation);
  10686. ctx.textAlign = 'center';
  10687. ctx.textBaseline = 'middle';
  10688. ctx.fillStyle = scaleLabelFontColor; // render in correct colour
  10689. ctx.font = scaleLabelFont.string;
  10690. ctx.fillText(scaleLabel.labelString, 0, 0);
  10691. ctx.restore();
  10692. },
  10693. draw: function(chartArea) {
  10694. var me = this;
  10695. if (!me._isVisible()) {
  10696. return;
  10697. }
  10698. me._drawGrid(chartArea);
  10699. me._drawTitle();
  10700. me._drawLabels();
  10701. },
  10702. /**
  10703. * @private
  10704. */
  10705. _layers: function() {
  10706. var me = this;
  10707. var opts = me.options;
  10708. var tz = opts.ticks && opts.ticks.z || 0;
  10709. var gz = opts.gridLines && opts.gridLines.z || 0;
  10710. if (!me._isVisible() || tz === gz || me.draw !== me._draw) {
  10711. // backward compatibility: draw has been overridden by custom scale
  10712. return [{
  10713. z: tz,
  10714. draw: function() {
  10715. me.draw.apply(me, arguments);
  10716. }
  10717. }];
  10718. }
  10719. return [{
  10720. z: gz,
  10721. draw: function() {
  10722. me._drawGrid.apply(me, arguments);
  10723. me._drawTitle.apply(me, arguments);
  10724. }
  10725. }, {
  10726. z: tz,
  10727. draw: function() {
  10728. me._drawLabels.apply(me, arguments);
  10729. }
  10730. }];
  10731. },
  10732. /**
  10733. * @private
  10734. */
  10735. _getMatchingVisibleMetas: function(type) {
  10736. var me = this;
  10737. var isHorizontal = me.isHorizontal();
  10738. return me.chart._getSortedVisibleDatasetMetas()
  10739. .filter(function(meta) {
  10740. return (!type || meta.type === type)
  10741. && (isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id);
  10742. });
  10743. }
  10744. });
  10745. Scale.prototype._draw = Scale.prototype.draw;
  10746. var core_scale = Scale;
  10747. var isNullOrUndef$1 = helpers$1.isNullOrUndef;
  10748. var defaultConfig = {
  10749. position: 'bottom'
  10750. };
  10751. var scale_category = core_scale.extend({
  10752. determineDataLimits: function() {
  10753. var me = this;
  10754. var labels = me._getLabels();
  10755. var ticksOpts = me.options.ticks;
  10756. var min = ticksOpts.min;
  10757. var max = ticksOpts.max;
  10758. var minIndex = 0;
  10759. var maxIndex = labels.length - 1;
  10760. var findIndex;
  10761. if (min !== undefined) {
  10762. // user specified min value
  10763. findIndex = labels.indexOf(min);
  10764. if (findIndex >= 0) {
  10765. minIndex = findIndex;
  10766. }
  10767. }
  10768. if (max !== undefined) {
  10769. // user specified max value
  10770. findIndex = labels.indexOf(max);
  10771. if (findIndex >= 0) {
  10772. maxIndex = findIndex;
  10773. }
  10774. }
  10775. me.minIndex = minIndex;
  10776. me.maxIndex = maxIndex;
  10777. me.min = labels[minIndex];
  10778. me.max = labels[maxIndex];
  10779. },
  10780. buildTicks: function() {
  10781. var me = this;
  10782. var labels = me._getLabels();
  10783. var minIndex = me.minIndex;
  10784. var maxIndex = me.maxIndex;
  10785. // If we are viewing some subset of labels, slice the original array
  10786. me.ticks = (minIndex === 0 && maxIndex === labels.length - 1) ? labels : labels.slice(minIndex, maxIndex + 1);
  10787. },
  10788. getLabelForIndex: function(index, datasetIndex) {
  10789. var me = this;
  10790. var chart = me.chart;
  10791. if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) {
  10792. return me.getRightValue(chart.data.datasets[datasetIndex].data[index]);
  10793. }
  10794. return me._getLabels()[index];
  10795. },
  10796. _configure: function() {
  10797. var me = this;
  10798. var offset = me.options.offset;
  10799. var ticks = me.ticks;
  10800. core_scale.prototype._configure.call(me);
  10801. if (!me.isHorizontal()) {
  10802. // For backward compatibility, vertical category scale reverse is inverted.
  10803. me._reversePixels = !me._reversePixels;
  10804. }
  10805. if (!ticks) {
  10806. return;
  10807. }
  10808. me._startValue = me.minIndex - (offset ? 0.5 : 0);
  10809. me._valueRange = Math.max(ticks.length - (offset ? 0 : 1), 1);
  10810. },
  10811. // Used to get data value locations. Value can either be an index or a numerical value
  10812. getPixelForValue: function(value, index, datasetIndex) {
  10813. var me = this;
  10814. var valueCategory, labels, idx;
  10815. if (!isNullOrUndef$1(index) && !isNullOrUndef$1(datasetIndex)) {
  10816. value = me.chart.data.datasets[datasetIndex].data[index];
  10817. }
  10818. // If value is a data object, then index is the index in the data array,
  10819. // not the index of the scale. We need to change that.
  10820. if (!isNullOrUndef$1(value)) {
  10821. valueCategory = me.isHorizontal() ? value.x : value.y;
  10822. }
  10823. if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
  10824. labels = me._getLabels();
  10825. value = helpers$1.valueOrDefault(valueCategory, value);
  10826. idx = labels.indexOf(value);
  10827. index = idx !== -1 ? idx : index;
  10828. if (isNaN(index)) {
  10829. index = value;
  10830. }
  10831. }
  10832. return me.getPixelForDecimal((index - me._startValue) / me._valueRange);
  10833. },
  10834. getPixelForTick: function(index) {
  10835. var ticks = this.ticks;
  10836. return index < 0 || index > ticks.length - 1
  10837. ? null
  10838. : this.getPixelForValue(ticks[index], index + this.minIndex);
  10839. },
  10840. getValueForPixel: function(pixel) {
  10841. var me = this;
  10842. var value = Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange);
  10843. return Math.min(Math.max(value, 0), me.ticks.length - 1);
  10844. },
  10845. getBasePixel: function() {
  10846. return this.bottom;
  10847. }
  10848. });
  10849. // INTERNAL: static default options, registered in src/index.js
  10850. var _defaults = defaultConfig;
  10851. scale_category._defaults = _defaults;
  10852. var noop = helpers$1.noop;
  10853. var isNullOrUndef$2 = helpers$1.isNullOrUndef;
  10854. /**
  10855. * Generate a set of linear ticks
  10856. * @param generationOptions the options used to generate the ticks
  10857. * @param dataRange the range of the data
  10858. * @returns {number[]} array of tick values
  10859. */
  10860. function generateTicks(generationOptions, dataRange) {
  10861. var ticks = [];
  10862. // To get a "nice" value for the tick spacing, we will use the appropriately named
  10863. // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
  10864. // for details.
  10865. var MIN_SPACING = 1e-14;
  10866. var stepSize = generationOptions.stepSize;
  10867. var unit = stepSize || 1;
  10868. var maxNumSpaces = generationOptions.maxTicks - 1;
  10869. var min = generationOptions.min;
  10870. var max = generationOptions.max;
  10871. var precision = generationOptions.precision;
  10872. var rmin = dataRange.min;
  10873. var rmax = dataRange.max;
  10874. var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit;
  10875. var factor, niceMin, niceMax, numSpaces;
  10876. // Beyond MIN_SPACING floating point numbers being to lose precision
  10877. // such that we can't do the math necessary to generate ticks
  10878. if (spacing < MIN_SPACING && isNullOrUndef$2(min) && isNullOrUndef$2(max)) {
  10879. return [rmin, rmax];
  10880. }
  10881. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  10882. if (numSpaces > maxNumSpaces) {
  10883. // If the calculated num of spaces exceeds maxNumSpaces, recalculate it
  10884. spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit;
  10885. }
  10886. if (stepSize || isNullOrUndef$2(precision)) {
  10887. // If a precision is not specified, calculate factor based on spacing
  10888. factor = Math.pow(10, helpers$1._decimalPlaces(spacing));
  10889. } else {
  10890. // If the user specified a precision, round to that number of decimal places
  10891. factor = Math.pow(10, precision);
  10892. spacing = Math.ceil(spacing * factor) / factor;
  10893. }
  10894. niceMin = Math.floor(rmin / spacing) * spacing;
  10895. niceMax = Math.ceil(rmax / spacing) * spacing;
  10896. // If min, max and stepSize is set and they make an evenly spaced scale use it.
  10897. if (stepSize) {
  10898. // If very close to our whole number, use it.
  10899. if (!isNullOrUndef$2(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) {
  10900. niceMin = min;
  10901. }
  10902. if (!isNullOrUndef$2(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) {
  10903. niceMax = max;
  10904. }
  10905. }
  10906. numSpaces = (niceMax - niceMin) / spacing;
  10907. // If very close to our rounded value, use it.
  10908. if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  10909. numSpaces = Math.round(numSpaces);
  10910. } else {
  10911. numSpaces = Math.ceil(numSpaces);
  10912. }
  10913. niceMin = Math.round(niceMin * factor) / factor;
  10914. niceMax = Math.round(niceMax * factor) / factor;
  10915. ticks.push(isNullOrUndef$2(min) ? niceMin : min);
  10916. for (var j = 1; j < numSpaces; ++j) {
  10917. ticks.push(Math.round((niceMin + j * spacing) * factor) / factor);
  10918. }
  10919. ticks.push(isNullOrUndef$2(max) ? niceMax : max);
  10920. return ticks;
  10921. }
  10922. var scale_linearbase = core_scale.extend({
  10923. getRightValue: function(value) {
  10924. if (typeof value === 'string') {
  10925. return +value;
  10926. }
  10927. return core_scale.prototype.getRightValue.call(this, value);
  10928. },
  10929. handleTickRangeOptions: function() {
  10930. var me = this;
  10931. var opts = me.options;
  10932. var tickOpts = opts.ticks;
  10933. // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
  10934. // do nothing since that would make the chart weird. If the user really wants a weird chart
  10935. // axis, they can manually override it
  10936. if (tickOpts.beginAtZero) {
  10937. var minSign = helpers$1.sign(me.min);
  10938. var maxSign = helpers$1.sign(me.max);
  10939. if (minSign < 0 && maxSign < 0) {
  10940. // move the top up to 0
  10941. me.max = 0;
  10942. } else if (minSign > 0 && maxSign > 0) {
  10943. // move the bottom down to 0
  10944. me.min = 0;
  10945. }
  10946. }
  10947. var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
  10948. var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
  10949. if (tickOpts.min !== undefined) {
  10950. me.min = tickOpts.min;
  10951. } else if (tickOpts.suggestedMin !== undefined) {
  10952. if (me.min === null) {
  10953. me.min = tickOpts.suggestedMin;
  10954. } else {
  10955. me.min = Math.min(me.min, tickOpts.suggestedMin);
  10956. }
  10957. }
  10958. if (tickOpts.max !== undefined) {
  10959. me.max = tickOpts.max;
  10960. } else if (tickOpts.suggestedMax !== undefined) {
  10961. if (me.max === null) {
  10962. me.max = tickOpts.suggestedMax;
  10963. } else {
  10964. me.max = Math.max(me.max, tickOpts.suggestedMax);
  10965. }
  10966. }
  10967. if (setMin !== setMax) {
  10968. // We set the min or the max but not both.
  10969. // So ensure that our range is good
  10970. // Inverted or 0 length range can happen when
  10971. // ticks.min is set, and no datasets are visible
  10972. if (me.min >= me.max) {
  10973. if (setMin) {
  10974. me.max = me.min + 1;
  10975. } else {
  10976. me.min = me.max - 1;
  10977. }
  10978. }
  10979. }
  10980. if (me.min === me.max) {
  10981. me.max++;
  10982. if (!tickOpts.beginAtZero) {
  10983. me.min--;
  10984. }
  10985. }
  10986. },
  10987. getTickLimit: function() {
  10988. var me = this;
  10989. var tickOpts = me.options.ticks;
  10990. var stepSize = tickOpts.stepSize;
  10991. var maxTicksLimit = tickOpts.maxTicksLimit;
  10992. var maxTicks;
  10993. if (stepSize) {
  10994. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  10995. } else {
  10996. maxTicks = me._computeTickLimit();
  10997. maxTicksLimit = maxTicksLimit || 11;
  10998. }
  10999. if (maxTicksLimit) {
  11000. maxTicks = Math.min(maxTicksLimit, maxTicks);
  11001. }
  11002. return maxTicks;
  11003. },
  11004. _computeTickLimit: function() {
  11005. return Number.POSITIVE_INFINITY;
  11006. },
  11007. handleDirectionalChanges: noop,
  11008. buildTicks: function() {
  11009. var me = this;
  11010. var opts = me.options;
  11011. var tickOpts = opts.ticks;
  11012. // Figure out what the max number of ticks we can support it is based on the size of
  11013. // the axis area. For now, we say that the minimum tick spacing in pixels must be 40
  11014. // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
  11015. // the graph. Make sure we always have at least 2 ticks
  11016. var maxTicks = me.getTickLimit();
  11017. maxTicks = Math.max(2, maxTicks);
  11018. var numericGeneratorOptions = {
  11019. maxTicks: maxTicks,
  11020. min: tickOpts.min,
  11021. max: tickOpts.max,
  11022. precision: tickOpts.precision,
  11023. stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
  11024. };
  11025. var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
  11026. me.handleDirectionalChanges();
  11027. // At this point, we need to update our max and min given the tick values since we have expanded the
  11028. // range of the scale
  11029. me.max = helpers$1.max(ticks);
  11030. me.min = helpers$1.min(ticks);
  11031. if (tickOpts.reverse) {
  11032. ticks.reverse();
  11033. me.start = me.max;
  11034. me.end = me.min;
  11035. } else {
  11036. me.start = me.min;
  11037. me.end = me.max;
  11038. }
  11039. },
  11040. convertTicksToLabels: function() {
  11041. var me = this;
  11042. me.ticksAsNumbers = me.ticks.slice();
  11043. me.zeroLineIndex = me.ticks.indexOf(0);
  11044. core_scale.prototype.convertTicksToLabels.call(me);
  11045. },
  11046. _configure: function() {
  11047. var me = this;
  11048. var ticks = me.getTicks();
  11049. var start = me.min;
  11050. var end = me.max;
  11051. var offset;
  11052. core_scale.prototype._configure.call(me);
  11053. if (me.options.offset && ticks.length) {
  11054. offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  11055. start -= offset;
  11056. end += offset;
  11057. }
  11058. me._startValue = start;
  11059. me._endValue = end;
  11060. me._valueRange = end - start;
  11061. }
  11062. });
  11063. var defaultConfig$1 = {
  11064. position: 'left',
  11065. ticks: {
  11066. callback: core_ticks.formatters.linear
  11067. }
  11068. };
  11069. var DEFAULT_MIN = 0;
  11070. var DEFAULT_MAX = 1;
  11071. function getOrCreateStack(stacks, stacked, meta) {
  11072. var key = [
  11073. meta.type,
  11074. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  11075. stacked === undefined && meta.stack === undefined ? meta.index : '',
  11076. meta.stack
  11077. ].join('.');
  11078. if (stacks[key] === undefined) {
  11079. stacks[key] = {
  11080. pos: [],
  11081. neg: []
  11082. };
  11083. }
  11084. return stacks[key];
  11085. }
  11086. function stackData(scale, stacks, meta, data) {
  11087. var opts = scale.options;
  11088. var stacked = opts.stacked;
  11089. var stack = getOrCreateStack(stacks, stacked, meta);
  11090. var pos = stack.pos;
  11091. var neg = stack.neg;
  11092. var ilen = data.length;
  11093. var i, value;
  11094. for (i = 0; i < ilen; ++i) {
  11095. value = scale._parseValue(data[i]);
  11096. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  11097. continue;
  11098. }
  11099. pos[i] = pos[i] || 0;
  11100. neg[i] = neg[i] || 0;
  11101. if (opts.relativePoints) {
  11102. pos[i] = 100;
  11103. } else if (value.min < 0 || value.max < 0) {
  11104. neg[i] += value.min;
  11105. } else {
  11106. pos[i] += value.max;
  11107. }
  11108. }
  11109. }
  11110. function updateMinMax(scale, meta, data) {
  11111. var ilen = data.length;
  11112. var i, value;
  11113. for (i = 0; i < ilen; ++i) {
  11114. value = scale._parseValue(data[i]);
  11115. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  11116. continue;
  11117. }
  11118. scale.min = Math.min(scale.min, value.min);
  11119. scale.max = Math.max(scale.max, value.max);
  11120. }
  11121. }
  11122. var scale_linear = scale_linearbase.extend({
  11123. determineDataLimits: function() {
  11124. var me = this;
  11125. var opts = me.options;
  11126. var chart = me.chart;
  11127. var datasets = chart.data.datasets;
  11128. var metasets = me._getMatchingVisibleMetas();
  11129. var hasStacks = opts.stacked;
  11130. var stacks = {};
  11131. var ilen = metasets.length;
  11132. var i, meta, data, values;
  11133. me.min = Number.POSITIVE_INFINITY;
  11134. me.max = Number.NEGATIVE_INFINITY;
  11135. if (hasStacks === undefined) {
  11136. for (i = 0; !hasStacks && i < ilen; ++i) {
  11137. meta = metasets[i];
  11138. hasStacks = meta.stack !== undefined;
  11139. }
  11140. }
  11141. for (i = 0; i < ilen; ++i) {
  11142. meta = metasets[i];
  11143. data = datasets[meta.index].data;
  11144. if (hasStacks) {
  11145. stackData(me, stacks, meta, data);
  11146. } else {
  11147. updateMinMax(me, meta, data);
  11148. }
  11149. }
  11150. helpers$1.each(stacks, function(stackValues) {
  11151. values = stackValues.pos.concat(stackValues.neg);
  11152. me.min = Math.min(me.min, helpers$1.min(values));
  11153. me.max = Math.max(me.max, helpers$1.max(values));
  11154. });
  11155. me.min = helpers$1.isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
  11156. me.max = helpers$1.isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
  11157. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  11158. me.handleTickRangeOptions();
  11159. },
  11160. // Returns the maximum number of ticks based on the scale dimension
  11161. _computeTickLimit: function() {
  11162. var me = this;
  11163. var tickFont;
  11164. if (me.isHorizontal()) {
  11165. return Math.ceil(me.width / 40);
  11166. }
  11167. tickFont = helpers$1.options._parseFont(me.options.ticks);
  11168. return Math.ceil(me.height / tickFont.lineHeight);
  11169. },
  11170. // Called after the ticks are built. We need
  11171. handleDirectionalChanges: function() {
  11172. if (!this.isHorizontal()) {
  11173. // We are in a vertical orientation. The top value is the highest. So reverse the array
  11174. this.ticks.reverse();
  11175. }
  11176. },
  11177. getLabelForIndex: function(index, datasetIndex) {
  11178. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  11179. },
  11180. // Utils
  11181. getPixelForValue: function(value) {
  11182. var me = this;
  11183. return me.getPixelForDecimal((+me.getRightValue(value) - me._startValue) / me._valueRange);
  11184. },
  11185. getValueForPixel: function(pixel) {
  11186. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  11187. },
  11188. getPixelForTick: function(index) {
  11189. var ticks = this.ticksAsNumbers;
  11190. if (index < 0 || index > ticks.length - 1) {
  11191. return null;
  11192. }
  11193. return this.getPixelForValue(ticks[index]);
  11194. }
  11195. });
  11196. // INTERNAL: static default options, registered in src/index.js
  11197. var _defaults$1 = defaultConfig$1;
  11198. scale_linear._defaults = _defaults$1;
  11199. var valueOrDefault$b = helpers$1.valueOrDefault;
  11200. var log10 = helpers$1.math.log10;
  11201. /**
  11202. * Generate a set of logarithmic ticks
  11203. * @param generationOptions the options used to generate the ticks
  11204. * @param dataRange the range of the data
  11205. * @returns {number[]} array of tick values
  11206. */
  11207. function generateTicks$1(generationOptions, dataRange) {
  11208. var ticks = [];
  11209. var tickVal = valueOrDefault$b(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
  11210. var endExp = Math.floor(log10(dataRange.max));
  11211. var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  11212. var exp, significand;
  11213. if (tickVal === 0) {
  11214. exp = Math.floor(log10(dataRange.minNotZero));
  11215. significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
  11216. ticks.push(tickVal);
  11217. tickVal = significand * Math.pow(10, exp);
  11218. } else {
  11219. exp = Math.floor(log10(tickVal));
  11220. significand = Math.floor(tickVal / Math.pow(10, exp));
  11221. }
  11222. var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  11223. do {
  11224. ticks.push(tickVal);
  11225. ++significand;
  11226. if (significand === 10) {
  11227. significand = 1;
  11228. ++exp;
  11229. precision = exp >= 0 ? 1 : precision;
  11230. }
  11231. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  11232. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  11233. var lastTick = valueOrDefault$b(generationOptions.max, tickVal);
  11234. ticks.push(lastTick);
  11235. return ticks;
  11236. }
  11237. var defaultConfig$2 = {
  11238. position: 'left',
  11239. // label settings
  11240. ticks: {
  11241. callback: core_ticks.formatters.logarithmic
  11242. }
  11243. };
  11244. // TODO(v3): change this to positiveOrDefault
  11245. function nonNegativeOrDefault(value, defaultValue) {
  11246. return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue;
  11247. }
  11248. var scale_logarithmic = core_scale.extend({
  11249. determineDataLimits: function() {
  11250. var me = this;
  11251. var opts = me.options;
  11252. var chart = me.chart;
  11253. var datasets = chart.data.datasets;
  11254. var isHorizontal = me.isHorizontal();
  11255. function IDMatches(meta) {
  11256. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  11257. }
  11258. var datasetIndex, meta, value, data, i, ilen;
  11259. // Calculate Range
  11260. me.min = Number.POSITIVE_INFINITY;
  11261. me.max = Number.NEGATIVE_INFINITY;
  11262. me.minNotZero = Number.POSITIVE_INFINITY;
  11263. var hasStacks = opts.stacked;
  11264. if (hasStacks === undefined) {
  11265. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11266. meta = chart.getDatasetMeta(datasetIndex);
  11267. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  11268. meta.stack !== undefined) {
  11269. hasStacks = true;
  11270. break;
  11271. }
  11272. }
  11273. }
  11274. if (opts.stacked || hasStacks) {
  11275. var valuesPerStack = {};
  11276. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11277. meta = chart.getDatasetMeta(datasetIndex);
  11278. var key = [
  11279. meta.type,
  11280. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  11281. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  11282. meta.stack
  11283. ].join('.');
  11284. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  11285. if (valuesPerStack[key] === undefined) {
  11286. valuesPerStack[key] = [];
  11287. }
  11288. data = datasets[datasetIndex].data;
  11289. for (i = 0, ilen = data.length; i < ilen; i++) {
  11290. var values = valuesPerStack[key];
  11291. value = me._parseValue(data[i]);
  11292. // invalid, hidden and negative values are ignored
  11293. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  11294. continue;
  11295. }
  11296. values[i] = values[i] || 0;
  11297. values[i] += value.max;
  11298. }
  11299. }
  11300. }
  11301. helpers$1.each(valuesPerStack, function(valuesForType) {
  11302. if (valuesForType.length > 0) {
  11303. var minVal = helpers$1.min(valuesForType);
  11304. var maxVal = helpers$1.max(valuesForType);
  11305. me.min = Math.min(me.min, minVal);
  11306. me.max = Math.max(me.max, maxVal);
  11307. }
  11308. });
  11309. } else {
  11310. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11311. meta = chart.getDatasetMeta(datasetIndex);
  11312. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  11313. data = datasets[datasetIndex].data;
  11314. for (i = 0, ilen = data.length; i < ilen; i++) {
  11315. value = me._parseValue(data[i]);
  11316. // invalid, hidden and negative values are ignored
  11317. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  11318. continue;
  11319. }
  11320. me.min = Math.min(value.min, me.min);
  11321. me.max = Math.max(value.max, me.max);
  11322. if (value.min !== 0) {
  11323. me.minNotZero = Math.min(value.min, me.minNotZero);
  11324. }
  11325. }
  11326. }
  11327. }
  11328. }
  11329. me.min = helpers$1.isFinite(me.min) ? me.min : null;
  11330. me.max = helpers$1.isFinite(me.max) ? me.max : null;
  11331. me.minNotZero = helpers$1.isFinite(me.minNotZero) ? me.minNotZero : null;
  11332. // Common base implementation to handle ticks.min, ticks.max
  11333. this.handleTickRangeOptions();
  11334. },
  11335. handleTickRangeOptions: function() {
  11336. var me = this;
  11337. var tickOpts = me.options.ticks;
  11338. var DEFAULT_MIN = 1;
  11339. var DEFAULT_MAX = 10;
  11340. me.min = nonNegativeOrDefault(tickOpts.min, me.min);
  11341. me.max = nonNegativeOrDefault(tickOpts.max, me.max);
  11342. if (me.min === me.max) {
  11343. if (me.min !== 0 && me.min !== null) {
  11344. me.min = Math.pow(10, Math.floor(log10(me.min)) - 1);
  11345. me.max = Math.pow(10, Math.floor(log10(me.max)) + 1);
  11346. } else {
  11347. me.min = DEFAULT_MIN;
  11348. me.max = DEFAULT_MAX;
  11349. }
  11350. }
  11351. if (me.min === null) {
  11352. me.min = Math.pow(10, Math.floor(log10(me.max)) - 1);
  11353. }
  11354. if (me.max === null) {
  11355. me.max = me.min !== 0
  11356. ? Math.pow(10, Math.floor(log10(me.min)) + 1)
  11357. : DEFAULT_MAX;
  11358. }
  11359. if (me.minNotZero === null) {
  11360. if (me.min > 0) {
  11361. me.minNotZero = me.min;
  11362. } else if (me.max < 1) {
  11363. me.minNotZero = Math.pow(10, Math.floor(log10(me.max)));
  11364. } else {
  11365. me.minNotZero = DEFAULT_MIN;
  11366. }
  11367. }
  11368. },
  11369. buildTicks: function() {
  11370. var me = this;
  11371. var tickOpts = me.options.ticks;
  11372. var reverse = !me.isHorizontal();
  11373. var generationOptions = {
  11374. min: nonNegativeOrDefault(tickOpts.min),
  11375. max: nonNegativeOrDefault(tickOpts.max)
  11376. };
  11377. var ticks = me.ticks = generateTicks$1(generationOptions, me);
  11378. // At this point, we need to update our max and min given the tick values since we have expanded the
  11379. // range of the scale
  11380. me.max = helpers$1.max(ticks);
  11381. me.min = helpers$1.min(ticks);
  11382. if (tickOpts.reverse) {
  11383. reverse = !reverse;
  11384. me.start = me.max;
  11385. me.end = me.min;
  11386. } else {
  11387. me.start = me.min;
  11388. me.end = me.max;
  11389. }
  11390. if (reverse) {
  11391. ticks.reverse();
  11392. }
  11393. },
  11394. convertTicksToLabels: function() {
  11395. this.tickValues = this.ticks.slice();
  11396. core_scale.prototype.convertTicksToLabels.call(this);
  11397. },
  11398. // Get the correct tooltip label
  11399. getLabelForIndex: function(index, datasetIndex) {
  11400. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  11401. },
  11402. getPixelForTick: function(index) {
  11403. var ticks = this.tickValues;
  11404. if (index < 0 || index > ticks.length - 1) {
  11405. return null;
  11406. }
  11407. return this.getPixelForValue(ticks[index]);
  11408. },
  11409. /**
  11410. * Returns the value of the first tick.
  11411. * @param {number} value - The minimum not zero value.
  11412. * @return {number} The first tick value.
  11413. * @private
  11414. */
  11415. _getFirstTickValue: function(value) {
  11416. var exp = Math.floor(log10(value));
  11417. var significand = Math.floor(value / Math.pow(10, exp));
  11418. return significand * Math.pow(10, exp);
  11419. },
  11420. _configure: function() {
  11421. var me = this;
  11422. var start = me.min;
  11423. var offset = 0;
  11424. core_scale.prototype._configure.call(me);
  11425. if (start === 0) {
  11426. start = me._getFirstTickValue(me.minNotZero);
  11427. offset = valueOrDefault$b(me.options.ticks.fontSize, core_defaults.global.defaultFontSize) / me._length;
  11428. }
  11429. me._startValue = log10(start);
  11430. me._valueOffset = offset;
  11431. me._valueRange = (log10(me.max) - log10(start)) / (1 - offset);
  11432. },
  11433. getPixelForValue: function(value) {
  11434. var me = this;
  11435. var decimal = 0;
  11436. value = +me.getRightValue(value);
  11437. if (value > me.min && value > 0) {
  11438. decimal = (log10(value) - me._startValue) / me._valueRange + me._valueOffset;
  11439. }
  11440. return me.getPixelForDecimal(decimal);
  11441. },
  11442. getValueForPixel: function(pixel) {
  11443. var me = this;
  11444. var decimal = me.getDecimalForPixel(pixel);
  11445. return decimal === 0 && me.min === 0
  11446. ? 0
  11447. : Math.pow(10, me._startValue + (decimal - me._valueOffset) * me._valueRange);
  11448. }
  11449. });
  11450. // INTERNAL: static default options, registered in src/index.js
  11451. var _defaults$2 = defaultConfig$2;
  11452. scale_logarithmic._defaults = _defaults$2;
  11453. var valueOrDefault$c = helpers$1.valueOrDefault;
  11454. var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault;
  11455. var resolve$4 = helpers$1.options.resolve;
  11456. var defaultConfig$3 = {
  11457. display: true,
  11458. // Boolean - Whether to animate scaling the chart from the centre
  11459. animate: true,
  11460. position: 'chartArea',
  11461. angleLines: {
  11462. display: true,
  11463. color: 'rgba(0,0,0,0.1)',
  11464. lineWidth: 1,
  11465. borderDash: [],
  11466. borderDashOffset: 0.0
  11467. },
  11468. gridLines: {
  11469. circular: false
  11470. },
  11471. // label settings
  11472. ticks: {
  11473. // Boolean - Show a backdrop to the scale label
  11474. showLabelBackdrop: true,
  11475. // String - The colour of the label backdrop
  11476. backdropColor: 'rgba(255,255,255,0.75)',
  11477. // Number - The backdrop padding above & below the label in pixels
  11478. backdropPaddingY: 2,
  11479. // Number - The backdrop padding to the side of the label in pixels
  11480. backdropPaddingX: 2,
  11481. callback: core_ticks.formatters.linear
  11482. },
  11483. pointLabels: {
  11484. // Boolean - if true, show point labels
  11485. display: true,
  11486. // Number - Point label font size in pixels
  11487. fontSize: 10,
  11488. // Function - Used to convert point labels
  11489. callback: function(label) {
  11490. return label;
  11491. }
  11492. }
  11493. };
  11494. function getTickBackdropHeight(opts) {
  11495. var tickOpts = opts.ticks;
  11496. if (tickOpts.display && opts.display) {
  11497. return valueOrDefault$c(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;
  11498. }
  11499. return 0;
  11500. }
  11501. function measureLabelSize(ctx, lineHeight, label) {
  11502. if (helpers$1.isArray(label)) {
  11503. return {
  11504. w: helpers$1.longestText(ctx, ctx.font, label),
  11505. h: label.length * lineHeight
  11506. };
  11507. }
  11508. return {
  11509. w: ctx.measureText(label).width,
  11510. h: lineHeight
  11511. };
  11512. }
  11513. function determineLimits(angle, pos, size, min, max) {
  11514. if (angle === min || angle === max) {
  11515. return {
  11516. start: pos - (size / 2),
  11517. end: pos + (size / 2)
  11518. };
  11519. } else if (angle < min || angle > max) {
  11520. return {
  11521. start: pos - size,
  11522. end: pos
  11523. };
  11524. }
  11525. return {
  11526. start: pos,
  11527. end: pos + size
  11528. };
  11529. }
  11530. /**
  11531. * Helper function to fit a radial linear scale with point labels
  11532. */
  11533. function fitWithPointLabels(scale) {
  11534. // Right, this is really confusing and there is a lot of maths going on here
  11535. // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  11536. //
  11537. // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  11538. //
  11539. // Solution:
  11540. //
  11541. // We assume the radius of the polygon is half the size of the canvas at first
  11542. // at each index we check if the text overlaps.
  11543. //
  11544. // Where it does, we store that angle and that index.
  11545. //
  11546. // After finding the largest index and angle we calculate how much we need to remove
  11547. // from the shape radius to move the point inwards by that x.
  11548. //
  11549. // We average the left and right distances to get the maximum shape radius that can fit in the box
  11550. // along with labels.
  11551. //
  11552. // Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  11553. // on each side, removing that from the size, halving it and adding the left x protrusion width.
  11554. //
  11555. // This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  11556. // and position it in the most space efficient manner
  11557. //
  11558. // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  11559. var plFont = helpers$1.options._parseFont(scale.options.pointLabels);
  11560. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  11561. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  11562. var furthestLimits = {
  11563. l: 0,
  11564. r: scale.width,
  11565. t: 0,
  11566. b: scale.height - scale.paddingTop
  11567. };
  11568. var furthestAngles = {};
  11569. var i, textSize, pointPosition;
  11570. scale.ctx.font = plFont.string;
  11571. scale._pointLabelSizes = [];
  11572. var valueCount = scale.chart.data.labels.length;
  11573. for (i = 0; i < valueCount; i++) {
  11574. pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
  11575. textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i]);
  11576. scale._pointLabelSizes[i] = textSize;
  11577. // Add quarter circle to make degree 0 mean top of circle
  11578. var angleRadians = scale.getIndexAngle(i);
  11579. var angle = helpers$1.toDegrees(angleRadians) % 360;
  11580. var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  11581. var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  11582. if (hLimits.start < furthestLimits.l) {
  11583. furthestLimits.l = hLimits.start;
  11584. furthestAngles.l = angleRadians;
  11585. }
  11586. if (hLimits.end > furthestLimits.r) {
  11587. furthestLimits.r = hLimits.end;
  11588. furthestAngles.r = angleRadians;
  11589. }
  11590. if (vLimits.start < furthestLimits.t) {
  11591. furthestLimits.t = vLimits.start;
  11592. furthestAngles.t = angleRadians;
  11593. }
  11594. if (vLimits.end > furthestLimits.b) {
  11595. furthestLimits.b = vLimits.end;
  11596. furthestAngles.b = angleRadians;
  11597. }
  11598. }
  11599. scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  11600. }
  11601. function getTextAlignForAngle(angle) {
  11602. if (angle === 0 || angle === 180) {
  11603. return 'center';
  11604. } else if (angle < 180) {
  11605. return 'left';
  11606. }
  11607. return 'right';
  11608. }
  11609. function fillText(ctx, text, position, lineHeight) {
  11610. var y = position.y + lineHeight / 2;
  11611. var i, ilen;
  11612. if (helpers$1.isArray(text)) {
  11613. for (i = 0, ilen = text.length; i < ilen; ++i) {
  11614. ctx.fillText(text[i], position.x, y);
  11615. y += lineHeight;
  11616. }
  11617. } else {
  11618. ctx.fillText(text, position.x, y);
  11619. }
  11620. }
  11621. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  11622. if (angle === 90 || angle === 270) {
  11623. position.y -= (textSize.h / 2);
  11624. } else if (angle > 270 || angle < 90) {
  11625. position.y -= textSize.h;
  11626. }
  11627. }
  11628. function drawPointLabels(scale) {
  11629. var ctx = scale.ctx;
  11630. var opts = scale.options;
  11631. var pointLabelOpts = opts.pointLabels;
  11632. var tickBackdropHeight = getTickBackdropHeight(opts);
  11633. var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  11634. var plFont = helpers$1.options._parseFont(pointLabelOpts);
  11635. ctx.save();
  11636. ctx.font = plFont.string;
  11637. ctx.textBaseline = 'middle';
  11638. for (var i = scale.chart.data.labels.length - 1; i >= 0; i--) {
  11639. // Extra pixels out for some label spacing
  11640. var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  11641. var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
  11642. // Keep this in loop since we may support array properties here
  11643. var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor);
  11644. ctx.fillStyle = pointLabelFontColor;
  11645. var angleRadians = scale.getIndexAngle(i);
  11646. var angle = helpers$1.toDegrees(angleRadians);
  11647. ctx.textAlign = getTextAlignForAngle(angle);
  11648. adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
  11649. fillText(ctx, scale.pointLabels[i], pointLabelPosition, plFont.lineHeight);
  11650. }
  11651. ctx.restore();
  11652. }
  11653. function drawRadiusLine(scale, gridLineOpts, radius, index) {
  11654. var ctx = scale.ctx;
  11655. var circular = gridLineOpts.circular;
  11656. var valueCount = scale.chart.data.labels.length;
  11657. var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1);
  11658. var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1);
  11659. var pointPosition;
  11660. if ((!circular && !valueCount) || !lineColor || !lineWidth) {
  11661. return;
  11662. }
  11663. ctx.save();
  11664. ctx.strokeStyle = lineColor;
  11665. ctx.lineWidth = lineWidth;
  11666. if (ctx.setLineDash) {
  11667. ctx.setLineDash(gridLineOpts.borderDash || []);
  11668. ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0;
  11669. }
  11670. ctx.beginPath();
  11671. if (circular) {
  11672. // Draw circular arcs between the points
  11673. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
  11674. } else {
  11675. // Draw straight lines connecting each index
  11676. pointPosition = scale.getPointPosition(0, radius);
  11677. ctx.moveTo(pointPosition.x, pointPosition.y);
  11678. for (var i = 1; i < valueCount; i++) {
  11679. pointPosition = scale.getPointPosition(i, radius);
  11680. ctx.lineTo(pointPosition.x, pointPosition.y);
  11681. }
  11682. }
  11683. ctx.closePath();
  11684. ctx.stroke();
  11685. ctx.restore();
  11686. }
  11687. function numberOrZero(param) {
  11688. return helpers$1.isNumber(param) ? param : 0;
  11689. }
  11690. var scale_radialLinear = scale_linearbase.extend({
  11691. setDimensions: function() {
  11692. var me = this;
  11693. // Set the unconstrained dimension before label rotation
  11694. me.width = me.maxWidth;
  11695. me.height = me.maxHeight;
  11696. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  11697. me.xCenter = Math.floor(me.width / 2);
  11698. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  11699. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  11700. },
  11701. determineDataLimits: function() {
  11702. var me = this;
  11703. var chart = me.chart;
  11704. var min = Number.POSITIVE_INFINITY;
  11705. var max = Number.NEGATIVE_INFINITY;
  11706. helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) {
  11707. if (chart.isDatasetVisible(datasetIndex)) {
  11708. var meta = chart.getDatasetMeta(datasetIndex);
  11709. helpers$1.each(dataset.data, function(rawValue, index) {
  11710. var value = +me.getRightValue(rawValue);
  11711. if (isNaN(value) || meta.data[index].hidden) {
  11712. return;
  11713. }
  11714. min = Math.min(value, min);
  11715. max = Math.max(value, max);
  11716. });
  11717. }
  11718. });
  11719. me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
  11720. me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
  11721. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  11722. me.handleTickRangeOptions();
  11723. },
  11724. // Returns the maximum number of ticks based on the scale dimension
  11725. _computeTickLimit: function() {
  11726. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  11727. },
  11728. convertTicksToLabels: function() {
  11729. var me = this;
  11730. scale_linearbase.prototype.convertTicksToLabels.call(me);
  11731. // Point labels
  11732. me.pointLabels = me.chart.data.labels.map(function() {
  11733. var label = helpers$1.callback(me.options.pointLabels.callback, arguments, me);
  11734. return label || label === 0 ? label : '';
  11735. });
  11736. },
  11737. getLabelForIndex: function(index, datasetIndex) {
  11738. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  11739. },
  11740. fit: function() {
  11741. var me = this;
  11742. var opts = me.options;
  11743. if (opts.display && opts.pointLabels.display) {
  11744. fitWithPointLabels(me);
  11745. } else {
  11746. me.setCenterPoint(0, 0, 0, 0);
  11747. }
  11748. },
  11749. /**
  11750. * Set radius reductions and determine new radius and center point
  11751. * @private
  11752. */
  11753. setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
  11754. var me = this;
  11755. var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  11756. var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  11757. var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  11758. var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  11759. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  11760. radiusReductionRight = numberOrZero(radiusReductionRight);
  11761. radiusReductionTop = numberOrZero(radiusReductionTop);
  11762. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  11763. me.drawingArea = Math.min(
  11764. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  11765. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
  11766. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  11767. },
  11768. setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
  11769. var me = this;
  11770. var maxRight = me.width - rightMovement - me.drawingArea;
  11771. var maxLeft = leftMovement + me.drawingArea;
  11772. var maxTop = topMovement + me.drawingArea;
  11773. var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  11774. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  11775. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  11776. },
  11777. getIndexAngle: function(index) {
  11778. var chart = this.chart;
  11779. var angleMultiplier = 360 / chart.data.labels.length;
  11780. var options = chart.options || {};
  11781. var startAngle = options.startAngle || 0;
  11782. // Start from the top instead of right, so remove a quarter of the circle
  11783. var angle = (index * angleMultiplier + startAngle) % 360;
  11784. return (angle < 0 ? angle + 360 : angle) * Math.PI * 2 / 360;
  11785. },
  11786. getDistanceFromCenterForValue: function(value) {
  11787. var me = this;
  11788. if (helpers$1.isNullOrUndef(value)) {
  11789. return NaN;
  11790. }
  11791. // Take into account half font size + the yPadding of the top value
  11792. var scalingFactor = me.drawingArea / (me.max - me.min);
  11793. if (me.options.ticks.reverse) {
  11794. return (me.max - value) * scalingFactor;
  11795. }
  11796. return (value - me.min) * scalingFactor;
  11797. },
  11798. getPointPosition: function(index, distanceFromCenter) {
  11799. var me = this;
  11800. var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
  11801. return {
  11802. x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter,
  11803. y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter
  11804. };
  11805. },
  11806. getPointPositionForValue: function(index, value) {
  11807. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  11808. },
  11809. getBasePosition: function(index) {
  11810. var me = this;
  11811. var min = me.min;
  11812. var max = me.max;
  11813. return me.getPointPositionForValue(index || 0,
  11814. me.beginAtZero ? 0 :
  11815. min < 0 && max < 0 ? max :
  11816. min > 0 && max > 0 ? min :
  11817. 0);
  11818. },
  11819. /**
  11820. * @private
  11821. */
  11822. _drawGrid: function() {
  11823. var me = this;
  11824. var ctx = me.ctx;
  11825. var opts = me.options;
  11826. var gridLineOpts = opts.gridLines;
  11827. var angleLineOpts = opts.angleLines;
  11828. var lineWidth = valueOrDefault$c(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
  11829. var lineColor = valueOrDefault$c(angleLineOpts.color, gridLineOpts.color);
  11830. var i, offset, position;
  11831. if (opts.pointLabels.display) {
  11832. drawPointLabels(me);
  11833. }
  11834. if (gridLineOpts.display) {
  11835. helpers$1.each(me.ticks, function(label, index) {
  11836. if (index !== 0) {
  11837. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  11838. drawRadiusLine(me, gridLineOpts, offset, index);
  11839. }
  11840. });
  11841. }
  11842. if (angleLineOpts.display && lineWidth && lineColor) {
  11843. ctx.save();
  11844. ctx.lineWidth = lineWidth;
  11845. ctx.strokeStyle = lineColor;
  11846. if (ctx.setLineDash) {
  11847. ctx.setLineDash(resolve$4([angleLineOpts.borderDash, gridLineOpts.borderDash, []]));
  11848. ctx.lineDashOffset = resolve$4([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]);
  11849. }
  11850. for (i = me.chart.data.labels.length - 1; i >= 0; i--) {
  11851. offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max);
  11852. position = me.getPointPosition(i, offset);
  11853. ctx.beginPath();
  11854. ctx.moveTo(me.xCenter, me.yCenter);
  11855. ctx.lineTo(position.x, position.y);
  11856. ctx.stroke();
  11857. }
  11858. ctx.restore();
  11859. }
  11860. },
  11861. /**
  11862. * @private
  11863. */
  11864. _drawLabels: function() {
  11865. var me = this;
  11866. var ctx = me.ctx;
  11867. var opts = me.options;
  11868. var tickOpts = opts.ticks;
  11869. if (!tickOpts.display) {
  11870. return;
  11871. }
  11872. var startAngle = me.getIndexAngle(0);
  11873. var tickFont = helpers$1.options._parseFont(tickOpts);
  11874. var tickFontColor = valueOrDefault$c(tickOpts.fontColor, core_defaults.global.defaultFontColor);
  11875. var offset, width;
  11876. ctx.save();
  11877. ctx.font = tickFont.string;
  11878. ctx.translate(me.xCenter, me.yCenter);
  11879. ctx.rotate(startAngle);
  11880. ctx.textAlign = 'center';
  11881. ctx.textBaseline = 'middle';
  11882. helpers$1.each(me.ticks, function(label, index) {
  11883. if (index === 0 && !tickOpts.reverse) {
  11884. return;
  11885. }
  11886. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  11887. if (tickOpts.showLabelBackdrop) {
  11888. width = ctx.measureText(label).width;
  11889. ctx.fillStyle = tickOpts.backdropColor;
  11890. ctx.fillRect(
  11891. -width / 2 - tickOpts.backdropPaddingX,
  11892. -offset - tickFont.size / 2 - tickOpts.backdropPaddingY,
  11893. width + tickOpts.backdropPaddingX * 2,
  11894. tickFont.size + tickOpts.backdropPaddingY * 2
  11895. );
  11896. }
  11897. ctx.fillStyle = tickFontColor;
  11898. ctx.fillText(label, 0, -offset);
  11899. });
  11900. ctx.restore();
  11901. },
  11902. /**
  11903. * @private
  11904. */
  11905. _drawTitle: helpers$1.noop
  11906. });
  11907. // INTERNAL: static default options, registered in src/index.js
  11908. var _defaults$3 = defaultConfig$3;
  11909. scale_radialLinear._defaults = _defaults$3;
  11910. var deprecated$1 = helpers$1._deprecated;
  11911. var resolve$5 = helpers$1.options.resolve;
  11912. var valueOrDefault$d = helpers$1.valueOrDefault;
  11913. // Integer constants are from the ES6 spec.
  11914. var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
  11915. var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  11916. var INTERVALS = {
  11917. millisecond: {
  11918. common: true,
  11919. size: 1,
  11920. steps: 1000
  11921. },
  11922. second: {
  11923. common: true,
  11924. size: 1000,
  11925. steps: 60
  11926. },
  11927. minute: {
  11928. common: true,
  11929. size: 60000,
  11930. steps: 60
  11931. },
  11932. hour: {
  11933. common: true,
  11934. size: 3600000,
  11935. steps: 24
  11936. },
  11937. day: {
  11938. common: true,
  11939. size: 86400000,
  11940. steps: 30
  11941. },
  11942. week: {
  11943. common: false,
  11944. size: 604800000,
  11945. steps: 4
  11946. },
  11947. month: {
  11948. common: true,
  11949. size: 2.628e9,
  11950. steps: 12
  11951. },
  11952. quarter: {
  11953. common: false,
  11954. size: 7.884e9,
  11955. steps: 4
  11956. },
  11957. year: {
  11958. common: true,
  11959. size: 3.154e10
  11960. }
  11961. };
  11962. var UNITS = Object.keys(INTERVALS);
  11963. function sorter(a, b) {
  11964. return a - b;
  11965. }
  11966. function arrayUnique(items) {
  11967. var hash = {};
  11968. var out = [];
  11969. var i, ilen, item;
  11970. for (i = 0, ilen = items.length; i < ilen; ++i) {
  11971. item = items[i];
  11972. if (!hash[item]) {
  11973. hash[item] = true;
  11974. out.push(item);
  11975. }
  11976. }
  11977. return out;
  11978. }
  11979. function getMin(options) {
  11980. return helpers$1.valueOrDefault(options.time.min, options.ticks.min);
  11981. }
  11982. function getMax(options) {
  11983. return helpers$1.valueOrDefault(options.time.max, options.ticks.max);
  11984. }
  11985. /**
  11986. * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
  11987. * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
  11988. * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
  11989. * extremity (left + width or top + height). Note that it would be more optimized to directly
  11990. * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
  11991. * to create the lookup table. The table ALWAYS contains at least two items: min and max.
  11992. *
  11993. * @param {number[]} timestamps - timestamps sorted from lowest to highest.
  11994. * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min
  11995. * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
  11996. * If 'series', timestamps will be positioned at the same distance from each other. In this
  11997. * case, only timestamps that break the time linearity are registered, meaning that in the
  11998. * best case, all timestamps are linear, the table contains only min and max.
  11999. */
  12000. function buildLookupTable(timestamps, min, max, distribution) {
  12001. if (distribution === 'linear' || !timestamps.length) {
  12002. return [
  12003. {time: min, pos: 0},
  12004. {time: max, pos: 1}
  12005. ];
  12006. }
  12007. var table = [];
  12008. var items = [min];
  12009. var i, ilen, prev, curr, next;
  12010. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  12011. curr = timestamps[i];
  12012. if (curr > min && curr < max) {
  12013. items.push(curr);
  12014. }
  12015. }
  12016. items.push(max);
  12017. for (i = 0, ilen = items.length; i < ilen; ++i) {
  12018. next = items[i + 1];
  12019. prev = items[i - 1];
  12020. curr = items[i];
  12021. // only add points that breaks the scale linearity
  12022. if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
  12023. table.push({time: curr, pos: i / (ilen - 1)});
  12024. }
  12025. }
  12026. return table;
  12027. }
  12028. // @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
  12029. function lookup(table, key, value) {
  12030. var lo = 0;
  12031. var hi = table.length - 1;
  12032. var mid, i0, i1;
  12033. while (lo >= 0 && lo <= hi) {
  12034. mid = (lo + hi) >> 1;
  12035. i0 = table[mid - 1] || null;
  12036. i1 = table[mid];
  12037. if (!i0) {
  12038. // given value is outside table (before first item)
  12039. return {lo: null, hi: i1};
  12040. } else if (i1[key] < value) {
  12041. lo = mid + 1;
  12042. } else if (i0[key] > value) {
  12043. hi = mid - 1;
  12044. } else {
  12045. return {lo: i0, hi: i1};
  12046. }
  12047. }
  12048. // given value is outside table (after last item)
  12049. return {lo: i1, hi: null};
  12050. }
  12051. /**
  12052. * Linearly interpolates the given source `value` using the table items `skey` values and
  12053. * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
  12054. * returns the position for a timestamp equal to 42. If value is out of bounds, values at
  12055. * index [0, 1] or [n - 1, n] are used for the interpolation.
  12056. */
  12057. function interpolate$1(table, skey, sval, tkey) {
  12058. var range = lookup(table, skey, sval);
  12059. // Note: the lookup table ALWAYS contains at least 2 items (min and max)
  12060. var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
  12061. var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
  12062. var span = next[skey] - prev[skey];
  12063. var ratio = span ? (sval - prev[skey]) / span : 0;
  12064. var offset = (next[tkey] - prev[tkey]) * ratio;
  12065. return prev[tkey] + offset;
  12066. }
  12067. function toTimestamp(scale, input) {
  12068. var adapter = scale._adapter;
  12069. var options = scale.options.time;
  12070. var parser = options.parser;
  12071. var format = parser || options.format;
  12072. var value = input;
  12073. if (typeof parser === 'function') {
  12074. value = parser(value);
  12075. }
  12076. // Only parse if its not a timestamp already
  12077. if (!helpers$1.isFinite(value)) {
  12078. value = typeof format === 'string'
  12079. ? adapter.parse(value, format)
  12080. : adapter.parse(value);
  12081. }
  12082. if (value !== null) {
  12083. return +value;
  12084. }
  12085. // Labels are in an incompatible format and no `parser` has been provided.
  12086. // The user might still use the deprecated `format` option for parsing.
  12087. if (!parser && typeof format === 'function') {
  12088. value = format(input);
  12089. // `format` could return something else than a timestamp, if so, parse it
  12090. if (!helpers$1.isFinite(value)) {
  12091. value = adapter.parse(value);
  12092. }
  12093. }
  12094. return value;
  12095. }
  12096. function parse(scale, input) {
  12097. if (helpers$1.isNullOrUndef(input)) {
  12098. return null;
  12099. }
  12100. var options = scale.options.time;
  12101. var value = toTimestamp(scale, scale.getRightValue(input));
  12102. if (value === null) {
  12103. return value;
  12104. }
  12105. if (options.round) {
  12106. value = +scale._adapter.startOf(value, options.round);
  12107. }
  12108. return value;
  12109. }
  12110. /**
  12111. * Figures out what unit results in an appropriate number of auto-generated ticks
  12112. */
  12113. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  12114. var ilen = UNITS.length;
  12115. var i, interval, factor;
  12116. for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  12117. interval = INTERVALS[UNITS[i]];
  12118. factor = interval.steps ? interval.steps : MAX_INTEGER;
  12119. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  12120. return UNITS[i];
  12121. }
  12122. }
  12123. return UNITS[ilen - 1];
  12124. }
  12125. /**
  12126. * Figures out what unit to format a set of ticks with
  12127. */
  12128. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  12129. var i, unit;
  12130. for (i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
  12131. unit = UNITS[i];
  12132. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  12133. return unit;
  12134. }
  12135. }
  12136. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  12137. }
  12138. function determineMajorUnit(unit) {
  12139. for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  12140. if (INTERVALS[UNITS[i]].common) {
  12141. return UNITS[i];
  12142. }
  12143. }
  12144. }
  12145. /**
  12146. * Generates a maximum of `capacity` timestamps between min and max, rounded to the
  12147. * `minor` unit using the given scale time `options`.
  12148. * Important: this method can return ticks outside the min and max range, it's the
  12149. * responsibility of the calling code to clamp values if needed.
  12150. */
  12151. function generate(scale, min, max, capacity) {
  12152. var adapter = scale._adapter;
  12153. var options = scale.options;
  12154. var timeOpts = options.time;
  12155. var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
  12156. var stepSize = resolve$5([timeOpts.stepSize, timeOpts.unitStepSize, 1]);
  12157. var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  12158. var first = min;
  12159. var ticks = [];
  12160. var time;
  12161. // For 'week' unit, handle the first day of week option
  12162. if (weekday) {
  12163. first = +adapter.startOf(first, 'isoWeek', weekday);
  12164. }
  12165. // Align first ticks on unit
  12166. first = +adapter.startOf(first, weekday ? 'day' : minor);
  12167. // Prevent browser from freezing in case user options request millions of milliseconds
  12168. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  12169. throw min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor;
  12170. }
  12171. for (time = first; time < max; time = +adapter.add(time, stepSize, minor)) {
  12172. ticks.push(time);
  12173. }
  12174. if (time === max || options.bounds === 'ticks') {
  12175. ticks.push(time);
  12176. }
  12177. return ticks;
  12178. }
  12179. /**
  12180. * Returns the start and end offsets from edges in the form of {start, end}
  12181. * where each value is a relative width to the scale and ranges between 0 and 1.
  12182. * They add extra margins on the both sides by scaling down the original scale.
  12183. * Offsets are added when the `offset` option is true.
  12184. */
  12185. function computeOffsets(table, ticks, min, max, options) {
  12186. var start = 0;
  12187. var end = 0;
  12188. var first, last;
  12189. if (options.offset && ticks.length) {
  12190. first = interpolate$1(table, 'time', ticks[0], 'pos');
  12191. if (ticks.length === 1) {
  12192. start = 1 - first;
  12193. } else {
  12194. start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2;
  12195. }
  12196. last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos');
  12197. if (ticks.length === 1) {
  12198. end = last;
  12199. } else {
  12200. end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2;
  12201. }
  12202. }
  12203. return {start: start, end: end, factor: 1 / (start + 1 + end)};
  12204. }
  12205. function setMajorTicks(scale, ticks, map, majorUnit) {
  12206. var adapter = scale._adapter;
  12207. var first = +adapter.startOf(ticks[0].value, majorUnit);
  12208. var last = ticks[ticks.length - 1].value;
  12209. var major, index;
  12210. for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
  12211. index = map[major];
  12212. if (index >= 0) {
  12213. ticks[index].major = true;
  12214. }
  12215. }
  12216. return ticks;
  12217. }
  12218. function ticksFromTimestamps(scale, values, majorUnit) {
  12219. var ticks = [];
  12220. var map = {};
  12221. var ilen = values.length;
  12222. var i, value;
  12223. for (i = 0; i < ilen; ++i) {
  12224. value = values[i];
  12225. map[value] = i;
  12226. ticks.push({
  12227. value: value,
  12228. major: false
  12229. });
  12230. }
  12231. // We set the major ticks separately from the above loop because calling startOf for every tick
  12232. // is expensive when there is a large number of ticks
  12233. return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  12234. }
  12235. var defaultConfig$4 = {
  12236. position: 'bottom',
  12237. /**
  12238. * Data distribution along the scale:
  12239. * - 'linear': data are spread according to their time (distances can vary),
  12240. * - 'series': data are spread at the same distance from each other.
  12241. * @see https://github.com/chartjs/Chart.js/pull/4507
  12242. * @since 2.7.0
  12243. */
  12244. distribution: 'linear',
  12245. /**
  12246. * Scale boundary strategy (bypassed by min/max time options)
  12247. * - `data`: make sure data are fully visible, ticks outside are removed
  12248. * - `ticks`: make sure ticks are fully visible, data outside are truncated
  12249. * @see https://github.com/chartjs/Chart.js/pull/4556
  12250. * @since 2.7.0
  12251. */
  12252. bounds: 'data',
  12253. adapters: {},
  12254. time: {
  12255. 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
  12256. unit: false, // false == automatic or override with week, month, year, etc.
  12257. round: false, // none, or override with week, month, year, etc.
  12258. displayFormat: false, // DEPRECATED
  12259. isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/
  12260. minUnit: 'millisecond',
  12261. displayFormats: {}
  12262. },
  12263. ticks: {
  12264. autoSkip: false,
  12265. /**
  12266. * Ticks generation input values:
  12267. * - 'auto': generates "optimal" ticks based on scale size and time options.
  12268. * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
  12269. * - 'labels': generates ticks from user given `data.labels` values ONLY.
  12270. * @see https://github.com/chartjs/Chart.js/pull/4507
  12271. * @since 2.7.0
  12272. */
  12273. source: 'auto',
  12274. major: {
  12275. enabled: false
  12276. }
  12277. }
  12278. };
  12279. var scale_time = core_scale.extend({
  12280. initialize: function() {
  12281. this.mergeTicksOptions();
  12282. core_scale.prototype.initialize.call(this);
  12283. },
  12284. update: function() {
  12285. var me = this;
  12286. var options = me.options;
  12287. var time = options.time || (options.time = {});
  12288. var adapter = me._adapter = new core_adapters._date(options.adapters.date);
  12289. // DEPRECATIONS: output a message only one time per update
  12290. deprecated$1('time scale', time.format, 'time.format', 'time.parser');
  12291. deprecated$1('time scale', time.min, 'time.min', 'ticks.min');
  12292. deprecated$1('time scale', time.max, 'time.max', 'ticks.max');
  12293. // Backward compatibility: before introducing adapter, `displayFormats` was
  12294. // supposed to contain *all* unit/string pairs but this can't be resolved
  12295. // when loading the scale (adapters are loaded afterward), so let's populate
  12296. // missing formats on update
  12297. helpers$1.mergeIf(time.displayFormats, adapter.formats());
  12298. return core_scale.prototype.update.apply(me, arguments);
  12299. },
  12300. /**
  12301. * Allows data to be referenced via 't' attribute
  12302. */
  12303. getRightValue: function(rawValue) {
  12304. if (rawValue && rawValue.t !== undefined) {
  12305. rawValue = rawValue.t;
  12306. }
  12307. return core_scale.prototype.getRightValue.call(this, rawValue);
  12308. },
  12309. determineDataLimits: function() {
  12310. var me = this;
  12311. var chart = me.chart;
  12312. var adapter = me._adapter;
  12313. var options = me.options;
  12314. var unit = options.time.unit || 'day';
  12315. var min = MAX_INTEGER;
  12316. var max = MIN_INTEGER;
  12317. var timestamps = [];
  12318. var datasets = [];
  12319. var labels = [];
  12320. var i, j, ilen, jlen, data, timestamp, labelsAdded;
  12321. var dataLabels = me._getLabels();
  12322. for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {
  12323. labels.push(parse(me, dataLabels[i]));
  12324. }
  12325. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  12326. if (chart.isDatasetVisible(i)) {
  12327. data = chart.data.datasets[i].data;
  12328. // Let's consider that all data have the same format.
  12329. if (helpers$1.isObject(data[0])) {
  12330. datasets[i] = [];
  12331. for (j = 0, jlen = data.length; j < jlen; ++j) {
  12332. timestamp = parse(me, data[j]);
  12333. timestamps.push(timestamp);
  12334. datasets[i][j] = timestamp;
  12335. }
  12336. } else {
  12337. datasets[i] = labels.slice(0);
  12338. if (!labelsAdded) {
  12339. timestamps = timestamps.concat(labels);
  12340. labelsAdded = true;
  12341. }
  12342. }
  12343. } else {
  12344. datasets[i] = [];
  12345. }
  12346. }
  12347. if (labels.length) {
  12348. min = Math.min(min, labels[0]);
  12349. max = Math.max(max, labels[labels.length - 1]);
  12350. }
  12351. if (timestamps.length) {
  12352. timestamps = ilen > 1 ? arrayUnique(timestamps).sort(sorter) : timestamps.sort(sorter);
  12353. min = Math.min(min, timestamps[0]);
  12354. max = Math.max(max, timestamps[timestamps.length - 1]);
  12355. }
  12356. min = parse(me, getMin(options)) || min;
  12357. max = parse(me, getMax(options)) || max;
  12358. // In case there is no valid min/max, set limits based on unit time option
  12359. min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min;
  12360. max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max;
  12361. // Make sure that max is strictly higher than min (required by the lookup table)
  12362. me.min = Math.min(min, max);
  12363. me.max = Math.max(min + 1, max);
  12364. // PRIVATE
  12365. me._table = [];
  12366. me._timestamps = {
  12367. data: timestamps,
  12368. datasets: datasets,
  12369. labels: labels
  12370. };
  12371. },
  12372. buildTicks: function() {
  12373. var me = this;
  12374. var min = me.min;
  12375. var max = me.max;
  12376. var options = me.options;
  12377. var tickOpts = options.ticks;
  12378. var timeOpts = options.time;
  12379. var timestamps = me._timestamps;
  12380. var ticks = [];
  12381. var capacity = me.getLabelCapacity(min);
  12382. var source = tickOpts.source;
  12383. var distribution = options.distribution;
  12384. var i, ilen, timestamp;
  12385. if (source === 'data' || (source === 'auto' && distribution === 'series')) {
  12386. timestamps = timestamps.data;
  12387. } else if (source === 'labels') {
  12388. timestamps = timestamps.labels;
  12389. } else {
  12390. timestamps = generate(me, min, max, capacity);
  12391. }
  12392. if (options.bounds === 'ticks' && timestamps.length) {
  12393. min = timestamps[0];
  12394. max = timestamps[timestamps.length - 1];
  12395. }
  12396. // Enforce limits with user min/max options
  12397. min = parse(me, getMin(options)) || min;
  12398. max = parse(me, getMax(options)) || max;
  12399. // Remove ticks outside the min/max range
  12400. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  12401. timestamp = timestamps[i];
  12402. if (timestamp >= min && timestamp <= max) {
  12403. ticks.push(timestamp);
  12404. }
  12405. }
  12406. me.min = min;
  12407. me.max = max;
  12408. // PRIVATE
  12409. // determineUnitForFormatting relies on the number of ticks so we don't use it when
  12410. // autoSkip is enabled because we don't yet know what the final number of ticks will be
  12411. me._unit = timeOpts.unit || (tickOpts.autoSkip
  12412. ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, capacity)
  12413. : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
  12414. me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
  12415. : determineMajorUnit(me._unit);
  12416. me._table = buildLookupTable(me._timestamps.data, min, max, distribution);
  12417. me._offsets = computeOffsets(me._table, ticks, min, max, options);
  12418. if (tickOpts.reverse) {
  12419. ticks.reverse();
  12420. }
  12421. return ticksFromTimestamps(me, ticks, me._majorUnit);
  12422. },
  12423. getLabelForIndex: function(index, datasetIndex) {
  12424. var me = this;
  12425. var adapter = me._adapter;
  12426. var data = me.chart.data;
  12427. var timeOpts = me.options.time;
  12428. var label = data.labels && index < data.labels.length ? data.labels[index] : '';
  12429. var value = data.datasets[datasetIndex].data[index];
  12430. if (helpers$1.isObject(value)) {
  12431. label = me.getRightValue(value);
  12432. }
  12433. if (timeOpts.tooltipFormat) {
  12434. return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat);
  12435. }
  12436. if (typeof label === 'string') {
  12437. return label;
  12438. }
  12439. return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime);
  12440. },
  12441. /**
  12442. * Function to format an individual tick mark
  12443. * @private
  12444. */
  12445. tickFormatFunction: function(time, index, ticks, format) {
  12446. var me = this;
  12447. var adapter = me._adapter;
  12448. var options = me.options;
  12449. var formats = options.time.displayFormats;
  12450. var minorFormat = formats[me._unit];
  12451. var majorUnit = me._majorUnit;
  12452. var majorFormat = formats[majorUnit];
  12453. var tick = ticks[index];
  12454. var tickOpts = options.ticks;
  12455. var major = majorUnit && majorFormat && tick && tick.major;
  12456. var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat);
  12457. var nestedTickOpts = major ? tickOpts.major : tickOpts.minor;
  12458. var formatter = resolve$5([
  12459. nestedTickOpts.callback,
  12460. nestedTickOpts.userCallback,
  12461. tickOpts.callback,
  12462. tickOpts.userCallback
  12463. ]);
  12464. return formatter ? formatter(label, index, ticks) : label;
  12465. },
  12466. convertTicksToLabels: function(ticks) {
  12467. var labels = [];
  12468. var i, ilen;
  12469. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  12470. labels.push(this.tickFormatFunction(ticks[i].value, i, ticks));
  12471. }
  12472. return labels;
  12473. },
  12474. /**
  12475. * @private
  12476. */
  12477. getPixelForOffset: function(time) {
  12478. var me = this;
  12479. var offsets = me._offsets;
  12480. var pos = interpolate$1(me._table, 'time', time, 'pos');
  12481. return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  12482. },
  12483. getPixelForValue: function(value, index, datasetIndex) {
  12484. var me = this;
  12485. var time = null;
  12486. if (index !== undefined && datasetIndex !== undefined) {
  12487. time = me._timestamps.datasets[datasetIndex][index];
  12488. }
  12489. if (time === null) {
  12490. time = parse(me, value);
  12491. }
  12492. if (time !== null) {
  12493. return me.getPixelForOffset(time);
  12494. }
  12495. },
  12496. getPixelForTick: function(index) {
  12497. var ticks = this.getTicks();
  12498. return index >= 0 && index < ticks.length ?
  12499. this.getPixelForOffset(ticks[index].value) :
  12500. null;
  12501. },
  12502. getValueForPixel: function(pixel) {
  12503. var me = this;
  12504. var offsets = me._offsets;
  12505. var pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  12506. var time = interpolate$1(me._table, 'pos', pos, 'time');
  12507. // DEPRECATION, we should return time directly
  12508. return me._adapter._create(time);
  12509. },
  12510. /**
  12511. * @private
  12512. */
  12513. _getLabelSize: function(label) {
  12514. var me = this;
  12515. var ticksOpts = me.options.ticks;
  12516. var tickLabelWidth = me.ctx.measureText(label).width;
  12517. var angle = helpers$1.toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  12518. var cosRotation = Math.cos(angle);
  12519. var sinRotation = Math.sin(angle);
  12520. var tickFontSize = valueOrDefault$d(ticksOpts.fontSize, core_defaults.global.defaultFontSize);
  12521. return {
  12522. w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),
  12523. h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)
  12524. };
  12525. },
  12526. /**
  12527. * Crude approximation of what the label width might be
  12528. * @private
  12529. */
  12530. getLabelWidth: function(label) {
  12531. return this._getLabelSize(label).w;
  12532. },
  12533. /**
  12534. * @private
  12535. */
  12536. getLabelCapacity: function(exampleTime) {
  12537. var me = this;
  12538. var timeOpts = me.options.time;
  12539. var displayFormats = timeOpts.displayFormats;
  12540. // pick the longest format (milliseconds) for guestimation
  12541. var format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  12542. var exampleLabel = me.tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format);
  12543. var size = me._getLabelSize(exampleLabel);
  12544. var capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h);
  12545. if (me.options.offset) {
  12546. capacity--;
  12547. }
  12548. return capacity > 0 ? capacity : 1;
  12549. }
  12550. });
  12551. // INTERNAL: static default options, registered in src/index.js
  12552. var _defaults$4 = defaultConfig$4;
  12553. scale_time._defaults = _defaults$4;
  12554. var scales = {
  12555. category: scale_category,
  12556. linear: scale_linear,
  12557. logarithmic: scale_logarithmic,
  12558. radialLinear: scale_radialLinear,
  12559. time: scale_time
  12560. };
  12561. var FORMATS = {
  12562. datetime: 'MMM D, YYYY, h:mm:ss a',
  12563. millisecond: 'h:mm:ss.SSS a',
  12564. second: 'h:mm:ss a',
  12565. minute: 'h:mm a',
  12566. hour: 'hA',
  12567. day: 'MMM D',
  12568. week: 'll',
  12569. month: 'MMM YYYY',
  12570. quarter: '[Q]Q - YYYY',
  12571. year: 'YYYY'
  12572. };
  12573. core_adapters._date.override(typeof moment === 'function' ? {
  12574. _id: 'moment', // DEBUG ONLY
  12575. formats: function() {
  12576. return FORMATS;
  12577. },
  12578. parse: function(value, format) {
  12579. if (typeof value === 'string' && typeof format === 'string') {
  12580. value = moment(value, format);
  12581. } else if (!(value instanceof moment)) {
  12582. value = moment(value);
  12583. }
  12584. return value.isValid() ? value.valueOf() : null;
  12585. },
  12586. format: function(time, format) {
  12587. return moment(time).format(format);
  12588. },
  12589. add: function(time, amount, unit) {
  12590. return moment(time).add(amount, unit).valueOf();
  12591. },
  12592. diff: function(max, min, unit) {
  12593. return moment(max).diff(moment(min), unit);
  12594. },
  12595. startOf: function(time, unit, weekday) {
  12596. time = moment(time);
  12597. if (unit === 'isoWeek') {
  12598. return time.isoWeekday(weekday).valueOf();
  12599. }
  12600. return time.startOf(unit).valueOf();
  12601. },
  12602. endOf: function(time, unit) {
  12603. return moment(time).endOf(unit).valueOf();
  12604. },
  12605. // DEPRECATIONS
  12606. /**
  12607. * Provided for backward compatibility with scale.getValueForPixel().
  12608. * @deprecated since version 2.8.0
  12609. * @todo remove at version 3
  12610. * @private
  12611. */
  12612. _create: function(time) {
  12613. return moment(time);
  12614. },
  12615. } : {});
  12616. core_defaults._set('global', {
  12617. plugins: {
  12618. filler: {
  12619. propagate: true
  12620. }
  12621. }
  12622. });
  12623. var mappers = {
  12624. dataset: function(source) {
  12625. var index = source.fill;
  12626. var chart = source.chart;
  12627. var meta = chart.getDatasetMeta(index);
  12628. var visible = meta && chart.isDatasetVisible(index);
  12629. var points = (visible && meta.dataset._children) || [];
  12630. var length = points.length || 0;
  12631. return !length ? null : function(point, i) {
  12632. return (i < length && points[i]._view) || null;
  12633. };
  12634. },
  12635. boundary: function(source) {
  12636. var boundary = source.boundary;
  12637. var x = boundary ? boundary.x : null;
  12638. var y = boundary ? boundary.y : null;
  12639. if (helpers$1.isArray(boundary)) {
  12640. return function(point, i) {
  12641. return boundary[i];
  12642. };
  12643. }
  12644. return function(point) {
  12645. return {
  12646. x: x === null ? point.x : x,
  12647. y: y === null ? point.y : y,
  12648. };
  12649. };
  12650. }
  12651. };
  12652. // @todo if (fill[0] === '#')
  12653. function decodeFill(el, index, count) {
  12654. var model = el._model || {};
  12655. var fill = model.fill;
  12656. var target;
  12657. if (fill === undefined) {
  12658. fill = !!model.backgroundColor;
  12659. }
  12660. if (fill === false || fill === null) {
  12661. return false;
  12662. }
  12663. if (fill === true) {
  12664. return 'origin';
  12665. }
  12666. target = parseFloat(fill, 10);
  12667. if (isFinite(target) && Math.floor(target) === target) {
  12668. if (fill[0] === '-' || fill[0] === '+') {
  12669. target = index + target;
  12670. }
  12671. if (target === index || target < 0 || target >= count) {
  12672. return false;
  12673. }
  12674. return target;
  12675. }
  12676. switch (fill) {
  12677. // compatibility
  12678. case 'bottom':
  12679. return 'start';
  12680. case 'top':
  12681. return 'end';
  12682. case 'zero':
  12683. return 'origin';
  12684. // supported boundaries
  12685. case 'origin':
  12686. case 'start':
  12687. case 'end':
  12688. return fill;
  12689. // invalid fill values
  12690. default:
  12691. return false;
  12692. }
  12693. }
  12694. function computeLinearBoundary(source) {
  12695. var model = source.el._model || {};
  12696. var scale = source.el._scale || {};
  12697. var fill = source.fill;
  12698. var target = null;
  12699. var horizontal;
  12700. if (isFinite(fill)) {
  12701. return null;
  12702. }
  12703. // Backward compatibility: until v3, we still need to support boundary values set on
  12704. // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
  12705. // controllers might still use it (e.g. the Smith chart).
  12706. if (fill === 'start') {
  12707. target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
  12708. } else if (fill === 'end') {
  12709. target = model.scaleTop === undefined ? scale.top : model.scaleTop;
  12710. } else if (model.scaleZero !== undefined) {
  12711. target = model.scaleZero;
  12712. } else if (scale.getBasePixel) {
  12713. target = scale.getBasePixel();
  12714. }
  12715. if (target !== undefined && target !== null) {
  12716. if (target.x !== undefined && target.y !== undefined) {
  12717. return target;
  12718. }
  12719. if (helpers$1.isFinite(target)) {
  12720. horizontal = scale.isHorizontal();
  12721. return {
  12722. x: horizontal ? target : null,
  12723. y: horizontal ? null : target
  12724. };
  12725. }
  12726. }
  12727. return null;
  12728. }
  12729. function computeCircularBoundary(source) {
  12730. var scale = source.el._scale;
  12731. var options = scale.options;
  12732. var length = scale.chart.data.labels.length;
  12733. var fill = source.fill;
  12734. var target = [];
  12735. var start, end, center, i, point;
  12736. if (!length) {
  12737. return null;
  12738. }
  12739. start = options.ticks.reverse ? scale.max : scale.min;
  12740. end = options.ticks.reverse ? scale.min : scale.max;
  12741. center = scale.getPointPositionForValue(0, start);
  12742. for (i = 0; i < length; ++i) {
  12743. point = fill === 'start' || fill === 'end'
  12744. ? scale.getPointPositionForValue(i, fill === 'start' ? start : end)
  12745. : scale.getBasePosition(i);
  12746. if (options.gridLines.circular) {
  12747. point.cx = center.x;
  12748. point.cy = center.y;
  12749. point.angle = scale.getIndexAngle(i) - Math.PI / 2;
  12750. }
  12751. target.push(point);
  12752. }
  12753. return target;
  12754. }
  12755. function computeBoundary(source) {
  12756. var scale = source.el._scale || {};
  12757. if (scale.getPointPositionForValue) {
  12758. return computeCircularBoundary(source);
  12759. }
  12760. return computeLinearBoundary(source);
  12761. }
  12762. function resolveTarget(sources, index, propagate) {
  12763. var source = sources[index];
  12764. var fill = source.fill;
  12765. var visited = [index];
  12766. var target;
  12767. if (!propagate) {
  12768. return fill;
  12769. }
  12770. while (fill !== false && visited.indexOf(fill) === -1) {
  12771. if (!isFinite(fill)) {
  12772. return fill;
  12773. }
  12774. target = sources[fill];
  12775. if (!target) {
  12776. return false;
  12777. }
  12778. if (target.visible) {
  12779. return fill;
  12780. }
  12781. visited.push(fill);
  12782. fill = target.fill;
  12783. }
  12784. return false;
  12785. }
  12786. function createMapper(source) {
  12787. var fill = source.fill;
  12788. var type = 'dataset';
  12789. if (fill === false) {
  12790. return null;
  12791. }
  12792. if (!isFinite(fill)) {
  12793. type = 'boundary';
  12794. }
  12795. return mappers[type](source);
  12796. }
  12797. function isDrawable(point) {
  12798. return point && !point.skip;
  12799. }
  12800. function drawArea(ctx, curve0, curve1, len0, len1) {
  12801. var i, cx, cy, r;
  12802. if (!len0 || !len1) {
  12803. return;
  12804. }
  12805. // building first area curve (normal)
  12806. ctx.moveTo(curve0[0].x, curve0[0].y);
  12807. for (i = 1; i < len0; ++i) {
  12808. helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
  12809. }
  12810. if (curve1[0].angle !== undefined) {
  12811. cx = curve1[0].cx;
  12812. cy = curve1[0].cy;
  12813. r = Math.sqrt(Math.pow(curve1[0].x - cx, 2) + Math.pow(curve1[0].y - cy, 2));
  12814. for (i = len1 - 1; i > 0; --i) {
  12815. ctx.arc(cx, cy, r, curve1[i].angle, curve1[i - 1].angle, true);
  12816. }
  12817. return;
  12818. }
  12819. // joining the two area curves
  12820. ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
  12821. // building opposite area curve (reverse)
  12822. for (i = len1 - 1; i > 0; --i) {
  12823. helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
  12824. }
  12825. }
  12826. function doFill(ctx, points, mapper, view, color, loop) {
  12827. var count = points.length;
  12828. var span = view.spanGaps;
  12829. var curve0 = [];
  12830. var curve1 = [];
  12831. var len0 = 0;
  12832. var len1 = 0;
  12833. var i, ilen, index, p0, p1, d0, d1, loopOffset;
  12834. ctx.beginPath();
  12835. for (i = 0, ilen = count; i < ilen; ++i) {
  12836. index = i % count;
  12837. p0 = points[index]._view;
  12838. p1 = mapper(p0, index, view);
  12839. d0 = isDrawable(p0);
  12840. d1 = isDrawable(p1);
  12841. if (loop && loopOffset === undefined && d0) {
  12842. loopOffset = i + 1;
  12843. ilen = count + loopOffset;
  12844. }
  12845. if (d0 && d1) {
  12846. len0 = curve0.push(p0);
  12847. len1 = curve1.push(p1);
  12848. } else if (len0 && len1) {
  12849. if (!span) {
  12850. drawArea(ctx, curve0, curve1, len0, len1);
  12851. len0 = len1 = 0;
  12852. curve0 = [];
  12853. curve1 = [];
  12854. } else {
  12855. if (d0) {
  12856. curve0.push(p0);
  12857. }
  12858. if (d1) {
  12859. curve1.push(p1);
  12860. }
  12861. }
  12862. }
  12863. }
  12864. drawArea(ctx, curve0, curve1, len0, len1);
  12865. ctx.closePath();
  12866. ctx.fillStyle = color;
  12867. ctx.fill();
  12868. }
  12869. var plugin_filler = {
  12870. id: 'filler',
  12871. afterDatasetsUpdate: function(chart, options) {
  12872. var count = (chart.data.datasets || []).length;
  12873. var propagate = options.propagate;
  12874. var sources = [];
  12875. var meta, i, el, source;
  12876. for (i = 0; i < count; ++i) {
  12877. meta = chart.getDatasetMeta(i);
  12878. el = meta.dataset;
  12879. source = null;
  12880. if (el && el._model && el instanceof elements.Line) {
  12881. source = {
  12882. visible: chart.isDatasetVisible(i),
  12883. fill: decodeFill(el, i, count),
  12884. chart: chart,
  12885. el: el
  12886. };
  12887. }
  12888. meta.$filler = source;
  12889. sources.push(source);
  12890. }
  12891. for (i = 0; i < count; ++i) {
  12892. source = sources[i];
  12893. if (!source) {
  12894. continue;
  12895. }
  12896. source.fill = resolveTarget(sources, i, propagate);
  12897. source.boundary = computeBoundary(source);
  12898. source.mapper = createMapper(source);
  12899. }
  12900. },
  12901. beforeDatasetsDraw: function(chart) {
  12902. var metasets = chart._getSortedVisibleDatasetMetas();
  12903. var ctx = chart.ctx;
  12904. var meta, i, el, view, points, mapper, color;
  12905. for (i = metasets.length - 1; i >= 0; --i) {
  12906. meta = metasets[i].$filler;
  12907. if (!meta || !meta.visible) {
  12908. continue;
  12909. }
  12910. el = meta.el;
  12911. view = el._view;
  12912. points = el._children || [];
  12913. mapper = meta.mapper;
  12914. color = view.backgroundColor || core_defaults.global.defaultColor;
  12915. if (mapper && color && points.length) {
  12916. helpers$1.canvas.clipArea(ctx, chart.chartArea);
  12917. doFill(ctx, points, mapper, view, color, el._loop);
  12918. helpers$1.canvas.unclipArea(ctx);
  12919. }
  12920. }
  12921. }
  12922. };
  12923. var getRtlHelper$1 = helpers$1.rtl.getRtlAdapter;
  12924. var noop$1 = helpers$1.noop;
  12925. var valueOrDefault$e = helpers$1.valueOrDefault;
  12926. core_defaults._set('global', {
  12927. legend: {
  12928. display: true,
  12929. position: 'top',
  12930. align: 'center',
  12931. fullWidth: true,
  12932. reverse: false,
  12933. weight: 1000,
  12934. // a callback that will handle
  12935. onClick: function(e, legendItem) {
  12936. var index = legendItem.datasetIndex;
  12937. var ci = this.chart;
  12938. var meta = ci.getDatasetMeta(index);
  12939. // See controller.isDatasetVisible comment
  12940. meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
  12941. // We hid a dataset ... rerender the chart
  12942. ci.update();
  12943. },
  12944. onHover: null,
  12945. onLeave: null,
  12946. labels: {
  12947. boxWidth: 40,
  12948. padding: 10,
  12949. // Generates labels shown in the legend
  12950. // Valid properties to return:
  12951. // text : text to display
  12952. // fillStyle : fill of coloured box
  12953. // strokeStyle: stroke of coloured box
  12954. // hidden : if this legend item refers to a hidden item
  12955. // lineCap : cap style for line
  12956. // lineDash
  12957. // lineDashOffset :
  12958. // lineJoin :
  12959. // lineWidth :
  12960. generateLabels: function(chart) {
  12961. var datasets = chart.data.datasets;
  12962. var options = chart.options.legend || {};
  12963. var usePointStyle = options.labels && options.labels.usePointStyle;
  12964. return chart._getSortedDatasetMetas().map(function(meta) {
  12965. var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  12966. return {
  12967. text: datasets[meta.index].label,
  12968. fillStyle: style.backgroundColor,
  12969. hidden: !chart.isDatasetVisible(meta.index),
  12970. lineCap: style.borderCapStyle,
  12971. lineDash: style.borderDash,
  12972. lineDashOffset: style.borderDashOffset,
  12973. lineJoin: style.borderJoinStyle,
  12974. lineWidth: style.borderWidth,
  12975. strokeStyle: style.borderColor,
  12976. pointStyle: style.pointStyle,
  12977. rotation: style.rotation,
  12978. // Below is extra data used for toggling the datasets
  12979. datasetIndex: meta.index
  12980. };
  12981. }, this);
  12982. }
  12983. }
  12984. },
  12985. legendCallback: function(chart) {
  12986. var list = document.createElement('ul');
  12987. var datasets = chart.data.datasets;
  12988. var i, ilen, listItem, listItemSpan;
  12989. list.setAttribute('class', chart.id + '-legend');
  12990. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  12991. listItem = list.appendChild(document.createElement('li'));
  12992. listItemSpan = listItem.appendChild(document.createElement('span'));
  12993. listItemSpan.style.backgroundColor = datasets[i].backgroundColor;
  12994. if (datasets[i].label) {
  12995. listItem.appendChild(document.createTextNode(datasets[i].label));
  12996. }
  12997. }
  12998. return list.outerHTML;
  12999. }
  13000. });
  13001. /**
  13002. * Helper function to get the box width based on the usePointStyle option
  13003. * @param {object} labelopts - the label options on the legend
  13004. * @param {number} fontSize - the label font size
  13005. * @return {number} width of the color box area
  13006. */
  13007. function getBoxWidth(labelOpts, fontSize) {
  13008. return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ?
  13009. fontSize :
  13010. labelOpts.boxWidth;
  13011. }
  13012. /**
  13013. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  13014. */
  13015. var Legend = core_element.extend({
  13016. initialize: function(config) {
  13017. var me = this;
  13018. helpers$1.extend(me, config);
  13019. // Contains hit boxes for each dataset (in dataset order)
  13020. me.legendHitBoxes = [];
  13021. /**
  13022. * @private
  13023. */
  13024. me._hoveredItem = null;
  13025. // Are we in doughnut mode which has a different data type
  13026. me.doughnutMode = false;
  13027. },
  13028. // These methods are ordered by lifecycle. Utilities then follow.
  13029. // Any function defined here is inherited by all legend types.
  13030. // Any function can be extended by the legend type
  13031. beforeUpdate: noop$1,
  13032. update: function(maxWidth, maxHeight, margins) {
  13033. var me = this;
  13034. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  13035. me.beforeUpdate();
  13036. // Absorb the master measurements
  13037. me.maxWidth = maxWidth;
  13038. me.maxHeight = maxHeight;
  13039. me.margins = margins;
  13040. // Dimensions
  13041. me.beforeSetDimensions();
  13042. me.setDimensions();
  13043. me.afterSetDimensions();
  13044. // Labels
  13045. me.beforeBuildLabels();
  13046. me.buildLabels();
  13047. me.afterBuildLabels();
  13048. // Fit
  13049. me.beforeFit();
  13050. me.fit();
  13051. me.afterFit();
  13052. //
  13053. me.afterUpdate();
  13054. return me.minSize;
  13055. },
  13056. afterUpdate: noop$1,
  13057. //
  13058. beforeSetDimensions: noop$1,
  13059. setDimensions: function() {
  13060. var me = this;
  13061. // Set the unconstrained dimension before label rotation
  13062. if (me.isHorizontal()) {
  13063. // Reset position before calculating rotation
  13064. me.width = me.maxWidth;
  13065. me.left = 0;
  13066. me.right = me.width;
  13067. } else {
  13068. me.height = me.maxHeight;
  13069. // Reset position before calculating rotation
  13070. me.top = 0;
  13071. me.bottom = me.height;
  13072. }
  13073. // Reset padding
  13074. me.paddingLeft = 0;
  13075. me.paddingTop = 0;
  13076. me.paddingRight = 0;
  13077. me.paddingBottom = 0;
  13078. // Reset minSize
  13079. me.minSize = {
  13080. width: 0,
  13081. height: 0
  13082. };
  13083. },
  13084. afterSetDimensions: noop$1,
  13085. //
  13086. beforeBuildLabels: noop$1,
  13087. buildLabels: function() {
  13088. var me = this;
  13089. var labelOpts = me.options.labels || {};
  13090. var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];
  13091. if (labelOpts.filter) {
  13092. legendItems = legendItems.filter(function(item) {
  13093. return labelOpts.filter(item, me.chart.data);
  13094. });
  13095. }
  13096. if (me.options.reverse) {
  13097. legendItems.reverse();
  13098. }
  13099. me.legendItems = legendItems;
  13100. },
  13101. afterBuildLabels: noop$1,
  13102. //
  13103. beforeFit: noop$1,
  13104. fit: function() {
  13105. var me = this;
  13106. var opts = me.options;
  13107. var labelOpts = opts.labels;
  13108. var display = opts.display;
  13109. var ctx = me.ctx;
  13110. var labelFont = helpers$1.options._parseFont(labelOpts);
  13111. var fontSize = labelFont.size;
  13112. // Reset hit boxes
  13113. var hitboxes = me.legendHitBoxes = [];
  13114. var minSize = me.minSize;
  13115. var isHorizontal = me.isHorizontal();
  13116. if (isHorizontal) {
  13117. minSize.width = me.maxWidth; // fill all the width
  13118. minSize.height = display ? 10 : 0;
  13119. } else {
  13120. minSize.width = display ? 10 : 0;
  13121. minSize.height = me.maxHeight; // fill all the height
  13122. }
  13123. // Increase sizes here
  13124. if (!display) {
  13125. me.width = minSize.width = me.height = minSize.height = 0;
  13126. return;
  13127. }
  13128. ctx.font = labelFont.string;
  13129. if (isHorizontal) {
  13130. // Labels
  13131. // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
  13132. var lineWidths = me.lineWidths = [0];
  13133. var totalHeight = 0;
  13134. ctx.textAlign = 'left';
  13135. ctx.textBaseline = 'middle';
  13136. helpers$1.each(me.legendItems, function(legendItem, i) {
  13137. var boxWidth = getBoxWidth(labelOpts, fontSize);
  13138. var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  13139. if (i === 0 || lineWidths[lineWidths.length - 1] + width + 2 * labelOpts.padding > minSize.width) {
  13140. totalHeight += fontSize + labelOpts.padding;
  13141. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  13142. }
  13143. // Store the hitbox width and height here. Final position will be updated in `draw`
  13144. hitboxes[i] = {
  13145. left: 0,
  13146. top: 0,
  13147. width: width,
  13148. height: fontSize
  13149. };
  13150. lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
  13151. });
  13152. minSize.height += totalHeight;
  13153. } else {
  13154. var vPadding = labelOpts.padding;
  13155. var columnWidths = me.columnWidths = [];
  13156. var columnHeights = me.columnHeights = [];
  13157. var totalWidth = labelOpts.padding;
  13158. var currentColWidth = 0;
  13159. var currentColHeight = 0;
  13160. helpers$1.each(me.legendItems, function(legendItem, i) {
  13161. var boxWidth = getBoxWidth(labelOpts, fontSize);
  13162. var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  13163. // If too tall, go to new column
  13164. if (i > 0 && currentColHeight + fontSize + 2 * vPadding > minSize.height) {
  13165. totalWidth += currentColWidth + labelOpts.padding;
  13166. columnWidths.push(currentColWidth); // previous column width
  13167. columnHeights.push(currentColHeight);
  13168. currentColWidth = 0;
  13169. currentColHeight = 0;
  13170. }
  13171. // Get max width
  13172. currentColWidth = Math.max(currentColWidth, itemWidth);
  13173. currentColHeight += fontSize + vPadding;
  13174. // Store the hitbox width and height here. Final position will be updated in `draw`
  13175. hitboxes[i] = {
  13176. left: 0,
  13177. top: 0,
  13178. width: itemWidth,
  13179. height: fontSize
  13180. };
  13181. });
  13182. totalWidth += currentColWidth;
  13183. columnWidths.push(currentColWidth);
  13184. columnHeights.push(currentColHeight);
  13185. minSize.width += totalWidth;
  13186. }
  13187. me.width = minSize.width;
  13188. me.height = minSize.height;
  13189. },
  13190. afterFit: noop$1,
  13191. // Shared Methods
  13192. isHorizontal: function() {
  13193. return this.options.position === 'top' || this.options.position === 'bottom';
  13194. },
  13195. // Actually draw the legend on the canvas
  13196. draw: function() {
  13197. var me = this;
  13198. var opts = me.options;
  13199. var labelOpts = opts.labels;
  13200. var globalDefaults = core_defaults.global;
  13201. var defaultColor = globalDefaults.defaultColor;
  13202. var lineDefault = globalDefaults.elements.line;
  13203. var legendHeight = me.height;
  13204. var columnHeights = me.columnHeights;
  13205. var legendWidth = me.width;
  13206. var lineWidths = me.lineWidths;
  13207. if (!opts.display) {
  13208. return;
  13209. }
  13210. var rtlHelper = getRtlHelper$1(opts.rtl, me.left, me.minSize.width);
  13211. var ctx = me.ctx;
  13212. var fontColor = valueOrDefault$e(labelOpts.fontColor, globalDefaults.defaultFontColor);
  13213. var labelFont = helpers$1.options._parseFont(labelOpts);
  13214. var fontSize = labelFont.size;
  13215. var cursor;
  13216. // Canvas setup
  13217. ctx.textAlign = rtlHelper.textAlign('left');
  13218. ctx.textBaseline = 'middle';
  13219. ctx.lineWidth = 0.5;
  13220. ctx.strokeStyle = fontColor; // for strikethrough effect
  13221. ctx.fillStyle = fontColor; // render in correct colour
  13222. ctx.font = labelFont.string;
  13223. var boxWidth = getBoxWidth(labelOpts, fontSize);
  13224. var hitboxes = me.legendHitBoxes;
  13225. // current position
  13226. var drawLegendBox = function(x, y, legendItem) {
  13227. if (isNaN(boxWidth) || boxWidth <= 0) {
  13228. return;
  13229. }
  13230. // Set the ctx for the box
  13231. ctx.save();
  13232. var lineWidth = valueOrDefault$e(legendItem.lineWidth, lineDefault.borderWidth);
  13233. ctx.fillStyle = valueOrDefault$e(legendItem.fillStyle, defaultColor);
  13234. ctx.lineCap = valueOrDefault$e(legendItem.lineCap, lineDefault.borderCapStyle);
  13235. ctx.lineDashOffset = valueOrDefault$e(legendItem.lineDashOffset, lineDefault.borderDashOffset);
  13236. ctx.lineJoin = valueOrDefault$e(legendItem.lineJoin, lineDefault.borderJoinStyle);
  13237. ctx.lineWidth = lineWidth;
  13238. ctx.strokeStyle = valueOrDefault$e(legendItem.strokeStyle, defaultColor);
  13239. if (ctx.setLineDash) {
  13240. // IE 9 and 10 do not support line dash
  13241. ctx.setLineDash(valueOrDefault$e(legendItem.lineDash, lineDefault.borderDash));
  13242. }
  13243. if (labelOpts && labelOpts.usePointStyle) {
  13244. // Recalculate x and y for drawPoint() because its expecting
  13245. // x and y to be center of figure (instead of top left)
  13246. var radius = boxWidth * Math.SQRT2 / 2;
  13247. var centerX = rtlHelper.xPlus(x, boxWidth / 2);
  13248. var centerY = y + fontSize / 2;
  13249. // Draw pointStyle as legend symbol
  13250. helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY, legendItem.rotation);
  13251. } else {
  13252. // Draw box as legend symbol
  13253. ctx.fillRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  13254. if (lineWidth !== 0) {
  13255. ctx.strokeRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  13256. }
  13257. }
  13258. ctx.restore();
  13259. };
  13260. var fillText = function(x, y, legendItem, textWidth) {
  13261. var halfFontSize = fontSize / 2;
  13262. var xLeft = rtlHelper.xPlus(x, boxWidth + halfFontSize);
  13263. var yMiddle = y + halfFontSize;
  13264. ctx.fillText(legendItem.text, xLeft, yMiddle);
  13265. if (legendItem.hidden) {
  13266. // Strikethrough the text if hidden
  13267. ctx.beginPath();
  13268. ctx.lineWidth = 2;
  13269. ctx.moveTo(xLeft, yMiddle);
  13270. ctx.lineTo(rtlHelper.xPlus(xLeft, textWidth), yMiddle);
  13271. ctx.stroke();
  13272. }
  13273. };
  13274. var alignmentOffset = function(dimension, blockSize) {
  13275. switch (opts.align) {
  13276. case 'start':
  13277. return labelOpts.padding;
  13278. case 'end':
  13279. return dimension - blockSize;
  13280. default: // center
  13281. return (dimension - blockSize + labelOpts.padding) / 2;
  13282. }
  13283. };
  13284. // Horizontal
  13285. var isHorizontal = me.isHorizontal();
  13286. if (isHorizontal) {
  13287. cursor = {
  13288. x: me.left + alignmentOffset(legendWidth, lineWidths[0]),
  13289. y: me.top + labelOpts.padding,
  13290. line: 0
  13291. };
  13292. } else {
  13293. cursor = {
  13294. x: me.left + labelOpts.padding,
  13295. y: me.top + alignmentOffset(legendHeight, columnHeights[0]),
  13296. line: 0
  13297. };
  13298. }
  13299. helpers$1.rtl.overrideTextDirection(me.ctx, opts.textDirection);
  13300. var itemHeight = fontSize + labelOpts.padding;
  13301. helpers$1.each(me.legendItems, function(legendItem, i) {
  13302. var textWidth = ctx.measureText(legendItem.text).width;
  13303. var width = boxWidth + (fontSize / 2) + textWidth;
  13304. var x = cursor.x;
  13305. var y = cursor.y;
  13306. rtlHelper.setWidth(me.minSize.width);
  13307. // Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
  13308. // instead of me.right and me.bottom because me.width and me.height
  13309. // may have been changed since me.minSize was calculated
  13310. if (isHorizontal) {
  13311. if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
  13312. y = cursor.y += itemHeight;
  13313. cursor.line++;
  13314. x = cursor.x = me.left + alignmentOffset(legendWidth, lineWidths[cursor.line]);
  13315. }
  13316. } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {
  13317. x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
  13318. cursor.line++;
  13319. y = cursor.y = me.top + alignmentOffset(legendHeight, columnHeights[cursor.line]);
  13320. }
  13321. var realX = rtlHelper.x(x);
  13322. drawLegendBox(realX, y, legendItem);
  13323. hitboxes[i].left = rtlHelper.leftForLtr(realX, hitboxes[i].width);
  13324. hitboxes[i].top = y;
  13325. // Fill the actual label
  13326. fillText(realX, y, legendItem, textWidth);
  13327. if (isHorizontal) {
  13328. cursor.x += width + labelOpts.padding;
  13329. } else {
  13330. cursor.y += itemHeight;
  13331. }
  13332. });
  13333. helpers$1.rtl.restoreTextDirection(me.ctx, opts.textDirection);
  13334. },
  13335. /**
  13336. * @private
  13337. */
  13338. _getLegendItemAt: function(x, y) {
  13339. var me = this;
  13340. var i, hitBox, lh;
  13341. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  13342. // See if we are touching one of the dataset boxes
  13343. lh = me.legendHitBoxes;
  13344. for (i = 0; i < lh.length; ++i) {
  13345. hitBox = lh[i];
  13346. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  13347. // Touching an element
  13348. return me.legendItems[i];
  13349. }
  13350. }
  13351. }
  13352. return null;
  13353. },
  13354. /**
  13355. * Handle an event
  13356. * @private
  13357. * @param {IEvent} event - The event to handle
  13358. */
  13359. handleEvent: function(e) {
  13360. var me = this;
  13361. var opts = me.options;
  13362. var type = e.type === 'mouseup' ? 'click' : e.type;
  13363. var hoveredItem;
  13364. if (type === 'mousemove') {
  13365. if (!opts.onHover && !opts.onLeave) {
  13366. return;
  13367. }
  13368. } else if (type === 'click') {
  13369. if (!opts.onClick) {
  13370. return;
  13371. }
  13372. } else {
  13373. return;
  13374. }
  13375. // Chart event already has relative position in it
  13376. hoveredItem = me._getLegendItemAt(e.x, e.y);
  13377. if (type === 'click') {
  13378. if (hoveredItem && opts.onClick) {
  13379. // use e.native for backwards compatibility
  13380. opts.onClick.call(me, e.native, hoveredItem);
  13381. }
  13382. } else {
  13383. if (opts.onLeave && hoveredItem !== me._hoveredItem) {
  13384. if (me._hoveredItem) {
  13385. opts.onLeave.call(me, e.native, me._hoveredItem);
  13386. }
  13387. me._hoveredItem = hoveredItem;
  13388. }
  13389. if (opts.onHover && hoveredItem) {
  13390. // use e.native for backwards compatibility
  13391. opts.onHover.call(me, e.native, hoveredItem);
  13392. }
  13393. }
  13394. }
  13395. });
  13396. function createNewLegendAndAttach(chart, legendOpts) {
  13397. var legend = new Legend({
  13398. ctx: chart.ctx,
  13399. options: legendOpts,
  13400. chart: chart
  13401. });
  13402. core_layouts.configure(chart, legend, legendOpts);
  13403. core_layouts.addBox(chart, legend);
  13404. chart.legend = legend;
  13405. }
  13406. var plugin_legend = {
  13407. id: 'legend',
  13408. /**
  13409. * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
  13410. * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
  13411. * the plugin, which one will be re-exposed in the chart.js file.
  13412. * https://github.com/chartjs/Chart.js/pull/2640
  13413. * @private
  13414. */
  13415. _element: Legend,
  13416. beforeInit: function(chart) {
  13417. var legendOpts = chart.options.legend;
  13418. if (legendOpts) {
  13419. createNewLegendAndAttach(chart, legendOpts);
  13420. }
  13421. },
  13422. beforeUpdate: function(chart) {
  13423. var legendOpts = chart.options.legend;
  13424. var legend = chart.legend;
  13425. if (legendOpts) {
  13426. helpers$1.mergeIf(legendOpts, core_defaults.global.legend);
  13427. if (legend) {
  13428. core_layouts.configure(chart, legend, legendOpts);
  13429. legend.options = legendOpts;
  13430. } else {
  13431. createNewLegendAndAttach(chart, legendOpts);
  13432. }
  13433. } else if (legend) {
  13434. core_layouts.removeBox(chart, legend);
  13435. delete chart.legend;
  13436. }
  13437. },
  13438. afterEvent: function(chart, e) {
  13439. var legend = chart.legend;
  13440. if (legend) {
  13441. legend.handleEvent(e);
  13442. }
  13443. }
  13444. };
  13445. var noop$2 = helpers$1.noop;
  13446. core_defaults._set('global', {
  13447. title: {
  13448. display: false,
  13449. fontStyle: 'bold',
  13450. fullWidth: true,
  13451. padding: 10,
  13452. position: 'top',
  13453. text: '',
  13454. weight: 2000 // by default greater than legend (1000) to be above
  13455. }
  13456. });
  13457. /**
  13458. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  13459. */
  13460. var Title = core_element.extend({
  13461. initialize: function(config) {
  13462. var me = this;
  13463. helpers$1.extend(me, config);
  13464. // Contains hit boxes for each dataset (in dataset order)
  13465. me.legendHitBoxes = [];
  13466. },
  13467. // These methods are ordered by lifecycle. Utilities then follow.
  13468. beforeUpdate: noop$2,
  13469. update: function(maxWidth, maxHeight, margins) {
  13470. var me = this;
  13471. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  13472. me.beforeUpdate();
  13473. // Absorb the master measurements
  13474. me.maxWidth = maxWidth;
  13475. me.maxHeight = maxHeight;
  13476. me.margins = margins;
  13477. // Dimensions
  13478. me.beforeSetDimensions();
  13479. me.setDimensions();
  13480. me.afterSetDimensions();
  13481. // Labels
  13482. me.beforeBuildLabels();
  13483. me.buildLabels();
  13484. me.afterBuildLabels();
  13485. // Fit
  13486. me.beforeFit();
  13487. me.fit();
  13488. me.afterFit();
  13489. //
  13490. me.afterUpdate();
  13491. return me.minSize;
  13492. },
  13493. afterUpdate: noop$2,
  13494. //
  13495. beforeSetDimensions: noop$2,
  13496. setDimensions: function() {
  13497. var me = this;
  13498. // Set the unconstrained dimension before label rotation
  13499. if (me.isHorizontal()) {
  13500. // Reset position before calculating rotation
  13501. me.width = me.maxWidth;
  13502. me.left = 0;
  13503. me.right = me.width;
  13504. } else {
  13505. me.height = me.maxHeight;
  13506. // Reset position before calculating rotation
  13507. me.top = 0;
  13508. me.bottom = me.height;
  13509. }
  13510. // Reset padding
  13511. me.paddingLeft = 0;
  13512. me.paddingTop = 0;
  13513. me.paddingRight = 0;
  13514. me.paddingBottom = 0;
  13515. // Reset minSize
  13516. me.minSize = {
  13517. width: 0,
  13518. height: 0
  13519. };
  13520. },
  13521. afterSetDimensions: noop$2,
  13522. //
  13523. beforeBuildLabels: noop$2,
  13524. buildLabels: noop$2,
  13525. afterBuildLabels: noop$2,
  13526. //
  13527. beforeFit: noop$2,
  13528. fit: function() {
  13529. var me = this;
  13530. var opts = me.options;
  13531. var minSize = me.minSize = {};
  13532. var isHorizontal = me.isHorizontal();
  13533. var lineCount, textSize;
  13534. if (!opts.display) {
  13535. me.width = minSize.width = me.height = minSize.height = 0;
  13536. return;
  13537. }
  13538. lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;
  13539. textSize = lineCount * helpers$1.options._parseFont(opts).lineHeight + opts.padding * 2;
  13540. me.width = minSize.width = isHorizontal ? me.maxWidth : textSize;
  13541. me.height = minSize.height = isHorizontal ? textSize : me.maxHeight;
  13542. },
  13543. afterFit: noop$2,
  13544. // Shared Methods
  13545. isHorizontal: function() {
  13546. var pos = this.options.position;
  13547. return pos === 'top' || pos === 'bottom';
  13548. },
  13549. // Actually draw the title block on the canvas
  13550. draw: function() {
  13551. var me = this;
  13552. var ctx = me.ctx;
  13553. var opts = me.options;
  13554. if (!opts.display) {
  13555. return;
  13556. }
  13557. var fontOpts = helpers$1.options._parseFont(opts);
  13558. var lineHeight = fontOpts.lineHeight;
  13559. var offset = lineHeight / 2 + opts.padding;
  13560. var rotation = 0;
  13561. var top = me.top;
  13562. var left = me.left;
  13563. var bottom = me.bottom;
  13564. var right = me.right;
  13565. var maxWidth, titleX, titleY;
  13566. ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour
  13567. ctx.font = fontOpts.string;
  13568. // Horizontal
  13569. if (me.isHorizontal()) {
  13570. titleX = left + ((right - left) / 2); // midpoint of the width
  13571. titleY = top + offset;
  13572. maxWidth = right - left;
  13573. } else {
  13574. titleX = opts.position === 'left' ? left + offset : right - offset;
  13575. titleY = top + ((bottom - top) / 2);
  13576. maxWidth = bottom - top;
  13577. rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
  13578. }
  13579. ctx.save();
  13580. ctx.translate(titleX, titleY);
  13581. ctx.rotate(rotation);
  13582. ctx.textAlign = 'center';
  13583. ctx.textBaseline = 'middle';
  13584. var text = opts.text;
  13585. if (helpers$1.isArray(text)) {
  13586. var y = 0;
  13587. for (var i = 0; i < text.length; ++i) {
  13588. ctx.fillText(text[i], 0, y, maxWidth);
  13589. y += lineHeight;
  13590. }
  13591. } else {
  13592. ctx.fillText(text, 0, 0, maxWidth);
  13593. }
  13594. ctx.restore();
  13595. }
  13596. });
  13597. function createNewTitleBlockAndAttach(chart, titleOpts) {
  13598. var title = new Title({
  13599. ctx: chart.ctx,
  13600. options: titleOpts,
  13601. chart: chart
  13602. });
  13603. core_layouts.configure(chart, title, titleOpts);
  13604. core_layouts.addBox(chart, title);
  13605. chart.titleBlock = title;
  13606. }
  13607. var plugin_title = {
  13608. id: 'title',
  13609. /**
  13610. * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
  13611. * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
  13612. * the plugin, which one will be re-exposed in the chart.js file.
  13613. * https://github.com/chartjs/Chart.js/pull/2640
  13614. * @private
  13615. */
  13616. _element: Title,
  13617. beforeInit: function(chart) {
  13618. var titleOpts = chart.options.title;
  13619. if (titleOpts) {
  13620. createNewTitleBlockAndAttach(chart, titleOpts);
  13621. }
  13622. },
  13623. beforeUpdate: function(chart) {
  13624. var titleOpts = chart.options.title;
  13625. var titleBlock = chart.titleBlock;
  13626. if (titleOpts) {
  13627. helpers$1.mergeIf(titleOpts, core_defaults.global.title);
  13628. if (titleBlock) {
  13629. core_layouts.configure(chart, titleBlock, titleOpts);
  13630. titleBlock.options = titleOpts;
  13631. } else {
  13632. createNewTitleBlockAndAttach(chart, titleOpts);
  13633. }
  13634. } else if (titleBlock) {
  13635. core_layouts.removeBox(chart, titleBlock);
  13636. delete chart.titleBlock;
  13637. }
  13638. }
  13639. };
  13640. var plugins = {};
  13641. var filler = plugin_filler;
  13642. var legend = plugin_legend;
  13643. var title = plugin_title;
  13644. plugins.filler = filler;
  13645. plugins.legend = legend;
  13646. plugins.title = title;
  13647. /**
  13648. * @namespace Chart
  13649. */
  13650. core_controller.helpers = helpers$1;
  13651. // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
  13652. core_helpers();
  13653. core_controller._adapters = core_adapters;
  13654. core_controller.Animation = core_animation;
  13655. core_controller.animationService = core_animations;
  13656. core_controller.controllers = controllers;
  13657. core_controller.DatasetController = core_datasetController;
  13658. core_controller.defaults = core_defaults;
  13659. core_controller.Element = core_element;
  13660. core_controller.elements = elements;
  13661. core_controller.Interaction = core_interaction;
  13662. core_controller.layouts = core_layouts;
  13663. core_controller.platform = platform;
  13664. core_controller.plugins = core_plugins;
  13665. core_controller.Scale = core_scale;
  13666. core_controller.scaleService = core_scaleService;
  13667. core_controller.Ticks = core_ticks;
  13668. core_controller.Tooltip = core_tooltip;
  13669. // Register built-in scales
  13670. core_controller.helpers.each(scales, function(scale, type) {
  13671. core_controller.scaleService.registerScaleType(type, scale, scale._defaults);
  13672. });
  13673. // Load to register built-in adapters (as side effects)
  13674. // Loading built-in plugins
  13675. for (var k in plugins) {
  13676. if (plugins.hasOwnProperty(k)) {
  13677. core_controller.plugins.register(plugins[k]);
  13678. }
  13679. }
  13680. core_controller.platform.initialize();
  13681. var src = core_controller;
  13682. if (typeof window !== 'undefined') {
  13683. window.Chart = core_controller;
  13684. }
  13685. // DEPRECATIONS
  13686. /**
  13687. * Provided for backward compatibility, not available anymore
  13688. * @namespace Chart.Chart
  13689. * @deprecated since version 2.8.0
  13690. * @todo remove at version 3
  13691. * @private
  13692. */
  13693. core_controller.Chart = core_controller;
  13694. /**
  13695. * Provided for backward compatibility, not available anymore
  13696. * @namespace Chart.Legend
  13697. * @deprecated since version 2.1.5
  13698. * @todo remove at version 3
  13699. * @private
  13700. */
  13701. core_controller.Legend = plugins.legend._element;
  13702. /**
  13703. * Provided for backward compatibility, not available anymore
  13704. * @namespace Chart.Title
  13705. * @deprecated since version 2.1.5
  13706. * @todo remove at version 3
  13707. * @private
  13708. */
  13709. core_controller.Title = plugins.title._element;
  13710. /**
  13711. * Provided for backward compatibility, use Chart.plugins instead
  13712. * @namespace Chart.pluginService
  13713. * @deprecated since version 2.1.5
  13714. * @todo remove at version 3
  13715. * @private
  13716. */
  13717. core_controller.pluginService = core_controller.plugins;
  13718. /**
  13719. * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
  13720. * effect, instead simply create/register plugins via plain JavaScript objects.
  13721. * @interface Chart.PluginBase
  13722. * @deprecated since version 2.5.0
  13723. * @todo remove at version 3
  13724. * @private
  13725. */
  13726. core_controller.PluginBase = core_controller.Element.extend({});
  13727. /**
  13728. * Provided for backward compatibility, use Chart.helpers.canvas instead.
  13729. * @namespace Chart.canvasHelpers
  13730. * @deprecated since version 2.6.0
  13731. * @todo remove at version 3
  13732. * @private
  13733. */
  13734. core_controller.canvasHelpers = core_controller.helpers.canvas;
  13735. /**
  13736. * Provided for backward compatibility, use Chart.layouts instead.
  13737. * @namespace Chart.layoutService
  13738. * @deprecated since version 2.7.3
  13739. * @todo remove at version 3
  13740. * @private
  13741. */
  13742. core_controller.layoutService = core_controller.layouts;
  13743. /**
  13744. * Provided for backward compatibility, not available anymore.
  13745. * @namespace Chart.LinearScaleBase
  13746. * @deprecated since version 2.8
  13747. * @todo remove at version 3
  13748. * @private
  13749. */
  13750. core_controller.LinearScaleBase = scale_linearbase;
  13751. /**
  13752. * Provided for backward compatibility, instead we should create a new Chart
  13753. * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`).
  13754. * @deprecated since version 2.8.0
  13755. * @todo remove at version 3
  13756. */
  13757. core_controller.helpers.each(
  13758. [
  13759. 'Bar',
  13760. 'Bubble',
  13761. 'Doughnut',
  13762. 'Line',
  13763. 'PolarArea',
  13764. 'Radar',
  13765. 'Scatter'
  13766. ],
  13767. function(klass) {
  13768. core_controller[klass] = function(ctx, cfg) {
  13769. return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, {
  13770. type: klass.charAt(0).toLowerCase() + klass.slice(1)
  13771. }));
  13772. };
  13773. }
  13774. );
  13775. return src;
  13776. })));